@sjcrh/proteinpaint-server 2.33.0 → 2.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dataset/clinvar.hg19.js +2 -2
- package/dataset/clinvar.hg38.js +2 -2
- package/package.json +2 -2
- package/server.js +1 -1
package/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var t={5037:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(9157),o=n(1017),i=n.n(o),s=n(334),a=n.n(s),l=n(3345);const c={endpoint:"burden",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{var o;const s=t[e.query.genome];if(!s)throw`invalid q.genome=${e.query.genome}`;const c=e.query,f=s.datasets[c.dslabel];if(!f)throw`invalid q.genome=${e.query.dslabel}`;if(null===(o=f.cohort.cumburden)||void 0===o||!o.files)throw"missing ds.cohort.cumburden.files";const d=await async function(t,e){const n=i().join(a().cachedir,Math.random().toString()+".json");for(const e in t.query)t.query[e]=Number(t.query[e]);const o=Object.assign({},u,t.query);await(0,l.Sf)(n,JSON.stringify(o));const{fit:s,surv:c,sample:f}=e.cohort.cumburden.files;if(!s||!c||!f)throw"missing one or more of ds.cohort.burden.files.{fit, surv, sample}";const d=[n,`${a().tpmasterdir}/${s}`,`${a().tpmasterdir}/${c}`,`${a().tpmasterdir}/${f}`],h=await(0,r.default)(i().join(a().binpath,"utils/burden.R"),[],d),p=JSON.parse(h[0]);return p}(e,f),{keys:h,rows:p}=function(t){const e=Object.keys(t[0]),n=[],r=[];for(const t of e)if("chc"==t)r.push(t),n.push(t);else{const e=Number(t.slice(1).split(",")[0]);e<=60&&e%2==0&&(r.push(t),n.push(`burden${e}`))}const o=[];for(const e of t)o.push(r.map((t=>e[t])));return{keys:n,rows:o}}(d);n.send({status:"ok",keys:h,rows:p})}catch(t){n.send({status:"error",error:t.message||t})}},request:{typeId:"BurdenRequest"},response:{typeId:"BurdenResponse"},examples:[{request:{body:{genome:"hg38",dslabel:"SJLife",diaggrp:5,sex:1,white:1,agedx:1,bleo:0,etop:0,cisp:0,carbo:0,steriod:0,vcr:0,hdmtx:0,itmt:0,ced:0,dox:0,heart:0,brain:0,abd:0,pelvis:0,chest:0}},response:{header:{status:200}}}]}}};const u=Object.freeze({diaggrp:5,sex:0,white:1,agedx:1,steriod:0,bleo:0,vcr:0,etop:0,itmt:0,ced:0,cisp:0,dox:0,carbo:0,hdmtx:0,brain:0,chest:0,heart:0,pelvis:0,abd:0})},2538:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>h});var r=n(1017),o=n.n(r),i=n(6452),s=n.n(i),a=n(334),l=n.n(a);const c=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",u=1e3,f="Aliquot Ensemble Somatic Variant Merging and Masking",d=l().features.gdcMafMaxFileSize||5e7,h={endpoint:"gdc/maf",methods:{get:{init:function({genomes:t}){return async(e,n)=>{try{const r=t.hg38;if(!r)throw"hg38 missing";if(!r.datasets.GDC)throw"hg38 GDC missing";const i=await async function(t){var e,n,r;const i={op:"and",content:[{op:"=",content:{field:"data_format",value:"MAF"}},{op:"=",content:{field:"experimental_strategy",value:t.experimentalStrategy}},{op:"=",content:{field:"analysis.workflow_type",value:f}},{op:"=",content:{field:"access",value:"open"}}]};t.filter0&&i.content.push(t.filter0);const a={"Content-Type":"application/json",Accept:"application/json"},l={filters:i,size:u,fields:["id","file_size","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},p=await s().post(o().join(c,"files"),{headers:a,body:JSON.stringify(l)});let m;try{m=JSON.parse(p.body)}catch(t){throw"invalid JSON from "+h.endpoint}if(!Number.isInteger(null===(e=m.data)||void 0===e||null===(n=e.pagination)||void 0===n?void 0:n.total))throw"re.data.pagination.total is not int";if(!Array.isArray(null===(r=m.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const g=[];for(const t of m.data.hits){var y;const e=null===(y=t.cases)||void 0===y?void 0:y[0];if(!e)throw"h.cases[0] missing";const n={id:t.id,project_id:e.project.project_id,file_size:t.file_size};n.case_submitter_id=e.submitter_id,e.samples&&(n.sample_types=e.samples.map((t=>t.sample_type)).sort()),g.push(n)}return{files:g,filesTotal:m.data.pagination.total,maxTotalSizeCompressed:d}}(e.query);n.send(i)}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafRequest"},response:{typeId:"GdcMafResponse"},examples:[{request:{body:{experimentalStrategy:"WXS",embedder:"localhost"}},response:{header:{status:200}}}]}}}},86:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>d});var r=n(6452),o=n.n(r),i=n(1017),s=n.n(i),a=n(1271),l=n(334),c=n.n(l);const u=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",f=c().features.gdcMafMaxFileSize||5e7,d={endpoint:"gdc/mafBuild",methods:{all:{init:function({genomes:t}){return async(t,e)=>{try{await async function(t,e){const n=Date.now(),r=await async function(t){var e;if(0==t.length)throw"fileIdLst[] not array or blank";const n={filters:{op:"in",content:{field:"file_id",value:t}},size:1e3,fields:"file_size"},r={"Content-Type":"application/json",Accept:"application/json"},i=await o().post(s().join(u,"files"),{headers:r,body:JSON.stringify(n)});let a;try{a=JSON.parse(i.body)}catch(t){throw"invalid json from getFileLstUnderSizeLimit"}if(!Array.isArray(null===(e=a.data)||void 0===e?void 0:e.hits))throw"re.data.hits[] not array";const l=[];let c=0;for(const t of a.data.hits){if(c>=f)break;if(!t.id)throw".id missing";if(!Number.isInteger(t.file_size))throw".file_size not integer";c+=t.file_size,l.push(t.id)}if(0==l.length)throw"no file available";return l}(t.fileIdLst);console.log("test gdc maf sizes",Date.now()-n);const i={fileIdLst:r,host:s().join(u,"data")},l=(0,a.run_rust_stream)("gdcmaf",JSON.stringify(i));e.setHeader("Content-Type","application/octet-stream"),e.setHeader("Content-Disposition","attachment; filename=cohort.maf.gz"),l.pipe(e),console.log("rust gdcmaf",Date.now()-n),l.on("end",(()=>{e.end()})),l.on("error",(t=>{console.error(t),e.statusCode=500,e.end("Internal Server Error")}))}(t.query,e)}catch(t){t.stack&&console.log(t.stack),e.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafBuildRequest"},response:{typeId:null}}}}},889:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>l});var r=n(1017),o=n.n(r),i=n(6452),s=n.n(i);const a=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",l={endpoint:"gdc/topMutatedGenes",methods:{get:{init:({genomes:t})=>async(t,e)=>{try{const n={genes:await async function(t){let e={op:"and",content:[]};if(t.filter0){if("object"!=typeof t.filter0)throw"filter0 not object";e=t.filter0}const n=await s().post(o().join(a,"/analysis/top_mutated_genes_by_project"),{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({size:t.maxGenes||50,fields:"symbol",filters:c(e,t.geneFilter)})}),r=JSON.parse(n.body),i=[];for(const t of r.data.hits)t.symbol&&i.push(t.symbol);return i}(t.query)};e.send(n)}catch(t){e.send({status:"error",error:t.message||t})}},request:{typeId:null},response:{typeId:"GdcTopMutatedGeneResponse"}}}};function c(t,e){let n;if("in"==t.op)n={op:"and",content:[t]};else{if("and"!=t.op)throw'f.op not "in" or "and"';n=t}return n.content.push({op:"NOT",content:{field:"ssms.consequence.transcript.annotation.vep_impact",value:"missing"}}),n.content.push({op:"in",content:{field:"ssms.consequence.transcript.consequence_type",value:["missense_variant","frameshift_variant","start_lost","stop_lost","stop_gained"]}}),"CGC"==e&&n.content.push({op:"in",content:{field:"genes.is_cancer_gene_census",value:["true"]}}),n}},449:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f});var r=n(1169),o=n(1017),i=n.n(o),s=n(6452),a=n.n(s),l=n(334),c=n.n(l);const u="https://uat-api.gdc.cancer.gov",f={endpoint:"gdc/topVariablyExpressedGenes",methods:{get:{init:function({genomes:t}){return async(e,n)=>{try{var o;const s=t.hg38;if(!s)throw"hg38 genome missing";const l=null===(o=s.datasets)||void 0===o?void 0:o.GDC;if(!l)throw"gdc dataset missing";const f=await async function(t,e,n){if(c().features.gdcGenes)return c().features.gdcGenes;if(!e.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";const o=await(0,r.Pj)(t,e);if(0==o.length)return[];const s=i().join(u,"/gene_expression/gene_selection");try{const e=await a().post(s,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({case_ids:o.slice(0,20),gene_ids:d(n),selection_size:Number(t.maxGenes)})}),r=JSON.parse(e.body),i=[];if(!Array.isArray(r.gene_selection))throw"re.gene_selection[] is not array";for(const t of r.gene_selection)if(t.gene_id&&"string"==typeof t.gene_id){const e=n.genedb.getNameByAlias.get(t.gene_id);e&&i.push(e.name)}else{if(!t.symbol||"string"!=typeof t.symbol)throw"one of re.gene_selection[] is missing both gene_id and symbol";i.push(t.symbol)}return i}catch(t){throw console.log(t.stack||t),t}}(e.query,l,s),h={genes:f};n.send(h)}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcTopVariablyExpressedGenesRequest"},response:{typeId:"GdcTopVariablyExpressedGenesResponse"}}}};function d(t){const e=[];for(const n of t.geneset[0].lst){const r=t.genedb.getAliasByName.all(n);if(r)for(const t of r)t.alias.startsWith("ENSG")&&e.push(t.alias)}return e}},3202:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(4065);function o({genomes:t}){return(e,n)=>{try{e.query;const o=t[e.query.genome];if(!o)throw"invalid genome name";const i=(0,r.S)(o,e.query);n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}const i={endpoint:"genelookup",methods:{get:{init:o,request:{typeId:"GeneLookupRequest"},response:{typeId:"GeneLookupResponse"},examples:[{request:{body:{input:"kr",genome:"hg38-test"}},response:{header:{status:200},body:{hits:["KRAS"]}}}]},post:{alternativeFor:"get",init:o}}}},1746:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(2062);const o={endpoint:"healthcheck",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{const e=await(0,r.W)(t);n.send(e)}catch(t){n.send({status:"error",error:t.message||t})}},request:{typeId:null},response:{typeId:"HealthCheckResponse"}}}}},3932:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(3345),o=n(2081),i=n(4521),s=n.n(i),a=n(334),l=n.n(a);const c={endpoint:"hicdata",methods:{get:{init:u,request:{typeId:"HicdataRequest"},response:{typeId:"HicdataResponse"}},post:{alternativeFor:"get",init:u}}};function u({genomes:t}){return async(t,e)=>{try{const i=await(n=t.query,new Promise(((t,e)=>{const[i,a,c]=(0,r.ZX)({query:n});i&&e({error:"illegal file name"});const u=[n.nmeth||"NONE",a,n.pos1,n.pos2,n.isfrag?"FRAG":"BP",n.resolution],f=(0,o.spawn)(l().hicstraw,u),d=s().createInterface({input:f.stdout}),h=[],p=[];let m=0,g=0;d.on("line",(t=>{const e=t.split("\t");if(3!=e.length)return void m++;const r=Number.parseInt(e[0]),o=Number.parseInt(e[1]),i=Number.parseFloat(e[2]);Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(i)?g++:null!=n.mincutoff&&i<=n.mincutoff||h.push([r,o,i])})),f.stderr.on("data",(t=>p.push(t))),f.on("close",(()=>{const n=p.join("");n&&e({error:n}),m&&e({error:m+" lines have other than 3 fields"}),g&&e({error:g+" lines have non-numerical values in any of the 3 fields"}),t({items:h})}))})));e.send(i)}catch(t){e.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}var n}}},6310:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>u});var r=n(3345),o=n(7147),i=n.n(o),s=n(6464),a=n.n(s),l=n(6452),c=n.n(l);const u={endpoint:"hicstat",methods:{get:{init:f,request:{typeId:"HicstatRequest"},response:{typeId:"HicstatResponse"},examples:[{request:{body:{genome:"hg19",file:"proteinpaint_demo/hg19/hic/hic_demo.hic",embedder:"localhost"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:f}}};function f(){return async(t,e)=>{try{const[n,o,s]=(0,r.ZX)(t);if(n)throw"illegal file name";s||await(0,r.Ic)(o);const l=await async function(t,e){const n={},r=e?await S(t,0,32e3):await N(t,0,32e3),o=new DataView(r);let s=0;if("HIC"!==A())throw Error("Unsupported hic file");const l=M();if(7!==l&&8!==l&&9!=l)throw Error("Unsupported hic version: "+l);n.version=l;const u=Number(T());let f=[];const d=1e5;if(8==l||7==l){let e=await k(t,u,d);const n=e.getInt32(0,!0);n>0&&(e=await k(t,u+n+4,d),f=await q(e,u+n+4))}const h=A();if(n["Genome ID"]=h,9==l){const e=Number(T()),n=Number(T());if(e>0&&n>0){const r=await k(t,e,n);f=await q(r,0)}}const p={},m=M();let g=0;for(;g!==m;)p[A()]=A(),g++;n.Chromosomes={},n.chrorder=[];const y=M();let v=0;for(;v!==y;){const t=A();n.chrorder.push(t),n.Chromosomes[t]=7==l||8==l?M():T(),v++}n["Base pair-delimited resolutions"]=[];const b=M();let w=0;for(;w!==b;){const t=M();n["Base pair-delimited resolutions"].push(t),w++}n["Fragment-delimited resolutions"]=[];const _=M();let x=0;for(;x!==_;){const t=M();n["Fragment-delimited resolutions"].push(t),x++}return BigInt.prototype.toJSON||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return()=>String(this)}}),n.normalization=f,n;async function k(t,n,r){const o=e?await S(t,n,r):await N(t,n,r);return new DataView(o)}async function q(e,n){const r=Date.now();let o=[];const i=e.getInt32(0,!0);let s=4;for(let t=1;t<=i;t++){let t=await f("string");o.push(t),8==l||7==l?(t=await f("string"),c(4),c(8*await f("int32")),c(12*await f("int32"))):9==l&&(s+=4,t=await f("string"),s+=20)}o=[...new Set(o)];const a=Date.now()-r;return console.log(`Read normalization on ${t} on ${a/1e3} seconds`),o;async function c(t){s+t>d&&u(),s+=t}async function u(){e=await k(t,n+s,d),n+=s,s=0}async function f(t){let n;if("string"==t){let t,r="";for(;0!=(t=e.getUint8(s++));)s>d&&await u(),r+=String.fromCharCode(t);n=r}else{if("int32"!=t)throw"No value assigned [server/src/hicstat.ts getViewValue()]";s+4>d&&await u(),n=e.getInt32(s,!0),s+=4}return n}}async function N(t,e,n){const r=a().promisify(i().open),o=a().promisify(i().read),s=Buffer.alloc(n),l=await r(t,"r"),c=await o(l,s,0,n,e);i().close(l,(function(t){return t}));const u=c.buffer;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}async function S(t,e,n){try{const r=e+"-"+(e+n-1);return(await c()(t,{headers:{Range:"bytes="+r}}).buffer()).buffer}catch(t){throw console.log(t.response),"error reading file, check file details"}}function A(){let t,e="";for(;0!=(t=o.getUint8(s++));)e+=String.fromCharCode(t);return e}function M(){const t=o.getInt32(s,!0);return s+=4,t}function T(){const t=o.getBigInt64(s,!0);return s+=8,t}}(o,s);e.send({out:l})}catch(t){e.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5852:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(938),o=n(2974);const i={endpoint:"termdb/categories",methods:{get:{init:s,request:{typeId:"getcategoriesRequest"},response:{typeId:"getcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getcategories:1,tid:"diaggrp",term1_q:{isAtomic:!0,hiddenValues:{},type:"values",groupsetting:{disabled:!0},mode:"discrete"},filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:s}}};function s({genomes:t}){return async(e,n)=>{const i=e.query;try{const s=t[e.query.genome];if(!s)throw"invalid genome name";const l=s.datasets[e.query.dslabel];if(!l)throw"invalid dataset name";const c=l.cohort.termdb;if(!c)throw"invalid termdb object";await async function(t,e,n,i,s){var l,c,u,f,d,h;if(!t.tid)throw".tid missing";const p="geneVariant"==t.type?{name:t.tid,type:"geneVariant",isleaf:!0}:n.q.termjsonByOneid(t.tid),m={filter:t.filter,terms:"geneVariant"==t.type?[{term:p,q:{isAtomic:!0}}]:[{id:t.tid,term:p,q:t.term1_q||a(p,t)}],currentGeneNames:t.currentGeneNames},g=await(0,o.Yu)(m,i,s);if(g.error)throw g.error;const y=[];if("geneVariant"==t.type){var v;const e=g.samples,n=new Map;if(null!==(v=i.assayAvailability)&&void 0!==v&&v.byDt)for(const[t,e]of Object.entries(i.assayAvailability.byDt))e.byOrigin&&n.set(parseInt(t),{byOrigin:{germline:{},somatic:{}}});const r=new Set;for(const[o,i]of Object.entries(e)){const e=i[t.tid].values;r.clear();for(const t of e){n.has(t.dt)||n.set(t.dt,{});const e=n.get(t.dt);e.byOrigin?(e.byOrigin[t.origin][t.class]||(e.byOrigin[t.origin][t.class]=1,r.add(`${t.dt} ${t.origin} ${t.class}`)),r.has(`${t.dt} ${t.origin} ${t.class}`)||(r.add(`${t.dt} ${t.origin} ${t.class}`),e.byOrigin[t.origin][t.class]+=1)):(e[t.class]||(r.add(`${t.dt} ${t.class}`),e[t.class]=1),r.has(`${t.dt} ${t.class}`)||(r.add(`${t.dt} ${t.class}`),e[t.class]+=1))}}for(const[t,e]of n)y.push({dt:t,classes:e})}else{const e=new Map;for(const n in g.samples){const r=g.samples[n][t.tid];r&&("key"in r&&e.set(r.key,1+(e.get(r.key)||0)))}for(const[n,r]of e){var b,w,_,x,k,q;y.push({samplecount:r,key:n,label:(null===(b=g.refs)||void 0===b||null===(w=b.byTermId)||void 0===w||null===(_=w[t.tid])||void 0===_||null===(x=_.events)||void 0===x?void 0:x.find((t=>t.event===n)).label)||(null==p||null===(k=p.values)||void 0===k||null===(q=k[n])||void 0===q?void 0:q.label)||n})}}const N=(0,r.Tt)(p,(null===(l=g.refs)||void 0===l||null===(c=l.byTermId)||void 0===c||null===(u=c[t.tid])||void 0===u?void 0:u.bins)||[],null===(f=g.refs)||void 0===f||null===(d=f.byTermId)||void 0===d||null===(h=d[t.tid])||void 0===h?void 0:h.events,t.term1_q);N.length&&y.sort(((t,e)=>N.indexOf(t.label)-N.indexOf(e.label)));e.send({lst:y,orderedLabels:N})}(i,n,c,l,s)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}function a(t,e){if("categorical"==t.type)return{};if("survival"==t.type)return{};if("integer"==t.type||"float"==t.type)return t.bins.default;if("condition"==t.type)return{mode:e.mode,breaks:e.breaks,bar_by_grade:e.bar_by_grade,bar_by_children:e.bar_by_children,value_by_max_grade:e.value_by_max_grade,value_by_most_recent:e.value_by_most_recent,value_by_computable_grade:e.value_by_computable_grade};if("geneVariant"==t.type)return{};throw"unknown term type"}},2630:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(8907),o=n(7027);const i={endpoint:"termdb/getpercentile",methods:{get:{init:s,request:{typeId:"getpercentileRequest"},response:{typeId:"getpercentileResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getpercentile:[50],tid:"agedx",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:s}}};function s({genomes:t}){return async(e,n)=>{const i=e.query;try{const s=t[e.query.genome];if(!s)throw"invalid genome name";const a=s.datasets[e.query.dslabel];if(!a)throw"invalid dataset name";await async function(t,e,n){const i=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!i)throw"invalid termid";if("float"!=i.type&&"integer"!=i.type)throw"not numerical term";const s=t.getpercentile,a=[],l=[],c=await r.J4({ds:n,key:t.tid,filter:t.filter?"string"==typeof t.filter?JSON.parse(t.filter):t.filter:null});for(const{value:t}of c)i.values&&i.values[t]&&i.values[t].uncomputable||i.skip0forPercentile&&0==t||l.push(Number(t));for(const t of s){const e=(0,o.Z)(l,t);a.push(e)}e.send({values:a})}(i,n,a)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5707:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>r});const r={endpoint:"termdb/singlecellData",methods:{get:{init:o,request:{typeId:"TermdbSinglecellDataRequest"},response:{typeId:"TermdbSinglecellDataResponse"}},post:{alternativeFor:"get",init:o}}};function o({genomes:t}){return async(e,n)=>{const r=e.query;try{var o;const e=t[r.genome];if(!e)throw"invalid genome name";const i=e.datasets[r.dslabel];if(!i)throw"invalid dataset name";if(null===(o=i.queries)||void 0===o||!o.singleCell)throw"no singlecell data on this dataset";const s=await i.queries.singleCell.data.get(r);n.send(s)}catch(t){t instanceof Error&&t.stack&&console.log(t),n.send({error:t.message||t})}}}},7934:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f,validate_query_singleCell:()=>h});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(334),c=n.n(l),u=n(1169);const f={endpoint:"termdb/singlecellSamples",methods:{get:{init:d,request:{typeId:"TermdbSinglecellsamplesRequest"},response:{typeId:"TermdbSinglecellsamplesResponse"}},post:{alternativeFor:"get",init:d}}};function d({genomes:t}){return async(e,n)=>{const r=e.query;try{var o;const e=t[r.genome];if(!e)throw"invalid genome name";const i=e.datasets[r.dslabel];if(!i)throw"invalid dataset name";if(null===(o=i.queries)||void 0===o||!o.singleCell)throw"no singlecell data on this dataset";const s=await i.queries.singleCell.samples.get(r);n.send({samples:s})}catch(t){t instanceof Error&&t.stack&&console.log(t),n.send({error:t.message||t})}}}async function h(t,e){const n=t.queries.singleCell;n&&("gdcapi"==n.samples.src?(0,u.z7)(t,e):function(t,e){const n=[],r=e.cohort.termdb.q.getAllValues4term(t.isSampleTerm);for(const t of r.keys())n.push({sample:e.cohort.termdb.q.id2sampleName(t)});if(0==n.length)throw"no sample with sc data";t.get=()=>n}(n.samples,t),"gdcapi"==n.data.src?(0,u.r8)(t,e):function(t,e){const n=new Set;for(const e of t.plots){if(n.has(e.name))throw"duplicate plot.name";n.add(e.name)}const r=[],i={};for(const n of t.termIds){const t=e.cohort.termdb.q.termjsonByOneid(n);if(!t)throw"invalid term id from queries.singleCell.data.termIds[]";r.push(t),i[n]=e.cohort.termdb.q.getAllValues4term(n)}t.get=async e=>{try{const n={};for(const e of t.termIds)n[e]={};const l=[];for(const r of t.plots){const u=s().join(c().tpmasterdir,r.folder,e,r.fileSuffix);try{await o().promises.stat(u)}catch(t){if("ENOENT"==t.code)continue;if("EACCES"==t.code)throw"cannot read file, permission denied";throw"failed to load sc data file"}const f=(await(0,a.b5)(u)).trim().split("\n"),d=[];for(let e=1;e<f.length;e++){const r=f[e].split("\t"),o=r[0],s=Number(r[4]),a=Number(r[5]);if(!o)throw"cell id missing";if(!Number.isFinite(s)||!Number.isFinite(a))throw"x/y not number";d.push({cellId:o,x:s,y:a});for(const e of t.termIds)i[e].has(o)&&(n[e][o]=i[e].get(o))}l.push({name:r.name,cells:d})}return 0==l.length?{nodata:!0}:{plots:l,terms:r,tid2cellvalue:n}}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}}(n.data,t))}},7071:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(2826);const o={endpoint:"termdb/termbyid",methods:{get:{init:i,request:{typeId:"gettermbyidRequest"},response:{typeId:"gettermbyidResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",gettermbyid:"subcohort"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:t}){return async(e,n)=>{const o=e.query;try{const i=t[e.query.genome];if(!i)throw"invalid genome name";const s=i.datasets[e.query.dslabel];if(!s)throw"invalid dataset name";const a=s.cohort.termdb;if(!a)throw"invalid termdb object";await async function(t,e,n){const o=n.q.termjsonByOneid(t.gettermbyid);e.send({term:o?(0,r.iK)(o):void 0})}(o,n,a)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},1485:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>_});var r=n(7147),o=n(3016),i=n(334),s=n.n(i),a=n(9157),l=n(1017),c=n.n(l),u=n(3345),f=n(2974),d=n(6718),h=n(7011),p=n(7027),m=n(5684);function g(t){let e=t;"string"==typeof t[0]&&(e=t.map(Number));const n=e.length;function r(t){return t.reduce(((t,e)=>t+e))/n}const o=(0,p.Z)(e,50),i=e.map((t=>(t-r(e))**2)).reduce(((t,e)=>t+e),0)/(n-1),s=Math.sqrt(i),a=(0,p.Z)(e,25),l=(0,p.Z)(e,75),c=l-a,u=Math.min(...e),f=Math.max(...e);return{values:[{id:"total",label:"Total",value:n},{id:"min",label:"Minimum",value:(0,m.Z)(u,2)},{id:"p25",label:"1st quartile",value:(0,m.Z)(a,2)},{id:"median",label:"Median",value:(0,m.Z)(o,2)},{id:"mean",label:"Mean",value:(0,m.Z)(r(e),2)},{id:"p75",label:"3rd quartile",value:(0,m.Z)(l,2)},{id:"max",label:"Maximum",value:(0,m.Z)(f,2)},{id:"SD",label:"Standard deviation",value:(0,m.Z)(s,2)},{id:"variance",label:"Variance",value:(0,m.Z)(i,2)},{id:"IQR",label:"Inter-quartile range",value:(0,m.Z)(c,2)}]}}var y=n(938);async function v(t,e,n,i){var l;const p=n.cohort.termdb.q.termjsonByOneid(t.termid);if(!p)throw".termid invalid";if("integer"!=p.type&&"float"!=p.type)throw"term type is not integer/float.";const m=[{id:t.termid,term:p,q:{mode:"continuous"}}];t.divideTw&&(null===t.divideTw||void 0===t.divideTw||"object"!=typeof t.divideTw||"id"in t.divideTw||(t.divideTw.id=t.divideTw.term.name,t.divideTw.term.id=t.divideTw.term.name),m.push(t.divideTw),t.term2_q=t.divideTw.q);const v=await(0,f.Yu)({terms:m,filter:t.filter,currentGeneNames:t.currentGeneNames},n,i);if(v.error)throw v.error;var _,x,k;t.divideTw&&v.refs.byTermId[null===(l=t.divideTw)||void 0===l?void 0:l.id]&&(v.refs.byTermId[null===(_=t.divideTw)||void 0===_?void 0:_.id].orderedLabels=(0,y.Tt)(t.divideTw,null===(x=v.refs.byTermId[null===(k=t.divideTw)||void 0===k?void 0:k.id])||void 0===x?void 0:x.bins,void 0,t.divideTw.q));t.scale&&function(t,e,n){if(!t.scale)return;const r=Number(t.scale);for(const[t,a]of Object.entries(e.samples)){var o,i,s;a[n.id]&&(null!==(o=n.values)&&void 0!==o&&null!==(i=o[null===(s=a[n.id])||void 0===s?void 0:s.value])&&void 0!==i&&i.uncomputable||(a[n.id].key=a[n.id].key/r,a[n.id].value=a[n.id].value/r))}}(t,v,p);const q=function(t,e,n,r){const o="log"==t.unit,i=new Map;let s=1/0,a=-1/0;const l={};let c=0;for(const[t,w]of Object.entries(e.samples)){var u,f,d;const t=null===(u=w[n.id])||void 0===u?void 0:u.value;if(Number.isFinite(t))if(null!==(f=n.values)&&void 0!==f&&null!==(d=f[t])&&void 0!==d&&d.uncomputable){const e=n.values[t].label;l[e]=(l[e]||0)+1}else if(o&&t<=0)c++;else if(s>t&&(s=t),a<t&&(a=t),"log"===o&&0===s&&(s=Math.max(s,t)),r){var h,p,m,g,y,v,b;if(!w[null==r?void 0:r.id])continue;if(null!==(h=r.term)&&void 0!==h&&null!==(p=h.values)&&void 0!==p&&null!==(m=p[null===(g=w[r.id])||void 0===g?void 0:g.key])&&void 0!==m&&m.uncomputable){var _,x;const t=null===(_=r.term.values[null===(x=w[r.id])||void 0===x?void 0:x.value])||void 0===_?void 0:_.label;l[t]=(l[t]||0)+1}i.has(null===(y=w[r.id])||void 0===y?void 0:y.key)||i.set(null===(v=w[r.id])||void 0===v?void 0:v.key,[]),i.get(null===(b=w[r.id])||void 0===b?void 0:b.key).push(t)}else i.has("All samples")||i.set("All samples",[]),i.get("All samples").push(t)}return{key2values:i,minMaxValues:{min:s,max:a},uncomputableValueObj:w(l),skipNonPositiveCount:c}}(t,v,p,t.divideTw),N=function(t,e,n){const r=n.divideTw,o={min:t.minMaxValues.min,max:t.minMaxValues.max,plots:[],pvalues:[],plotThickness:Number,uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null};for(const[n,f]of function(t,e,n){var r,o,i,s;const a=null===(r=t.refs.byTermId[null==n||null===(o=n.term)||void 0===o?void 0:o.id])||void 0===r?void 0:r.orderedLabels;return e=new Map([...e].sort(a?(t,e)=>a.indexOf(t[0])-a.indexOf(e[0]):"categorical"===(null==n||null===(i=n.term)||void 0===i?void 0:i.type)?(t,e)=>e[1].length-t[1].length:"condition"===(null==n||null===(s=n.term)||void 0===s?void 0:s.type)?(t,e)=>t[0]-e[0]:(t,e)=>t.toString().replace(/[^a-zA-Z0-9<]/g,"").localeCompare(e.toString().replace(/[^a-zA-Z0-9<]/g,""),void 0,{numeric:!0}))),e}(e,t.key2values,r)){var i,s,a,l,c,u;if(r)o.plots.push({label:(null==r||null===(i=r.term)||void 0===i||null===(s=i.values)||void 0===s||null===(a=s[n])||void 0===a?void 0:a.label)||n,values:f,seriesId:n,plotValueCount:null==f?void 0:f.length,color:(null==r||null===(l=r.term)||void 0===l||null===(c=l.values)||void 0===c||null===(u=c[n])||void 0===u?void 0:u.color)||null,divideTwBins:b(r,e).has(n)?b(r,e).get(n):null,uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null});else o.plots.push({label:"All samples",values:f,plotValueCount:f.length})}o.plots.length>=1&&(o.plotThickness=n.plotThickness?Number(n.plotThickness):function(t,e){const n=e.screenThickness/t.plots.length,r=Math.round(Math.min(n,e.maxThickness));return r}(o,n));return o}(q,v,t);if(await async function(t,e){if(!t)return;const n=e.plots.length;if(n<2)return;const o=[];for(let t=0;t<n;t++){const r=e.plots[t].label,i=e.plots[t].values;for(let s=t+1;s<n;s++){const t=e.plots[s].label,n=e.plots[s].values;o.push({group1_id:r,group1_values:i,group2_id:t,group2_values:n})}}const i=c().join(s().cachedir,Math.random().toString()+".json");await(0,u.Sf)(i,JSON.stringify(o));const l=await(0,a.default)(c().join(s().binpath,"utils/wilcoxon.R"),[],[i]);(0,r.unlink)(i,(()=>{}));const f=JSON.parse(l);for(const t of f)null==t.pvalue||"null"==t.pvalue?e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:"NA"}]):e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:t.pvalue.toPrecision(4)}])}(t.divideTw,N),function(t,e,n){t.radius||(t.radius=5);if(t.radius<=0)throw"q.radius is not a number";t.radius=+t.radius;t.strokeWidth||(t.strokeWidth=.2);const r=4*t.radius;let i;const s="log"==t.unit;i=s?(0,o.scaleLog)().base(n.cohort.termdb.logscaleBase2?2:10).domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]):(0,o.scaleLinear)().domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]);const[a,l]="horizontal"==t.orientation?[t.svgw*t.devicePixelRatio,r*t.devicePixelRatio]:[r*t.devicePixelRatio,t.svgw*t.devicePixelRatio],c=t.radius/t.devicePixelRatio,u=c*Math.PI;for(const n of e.plots){const e=(0,d.createCanvas)(a,l),r=e.getContext("2d");r.strokeStyle="rgba(0,0,0,0.8)",r.lineWidth=t.strokeWidth/t.devicePixelRatio,r.globalAlpha=.5,r.fillStyle="#ffe6e6",1!=t.devicePixelRatio&&r.scale(t.devicePixelRatio,t.devicePixelRatio),"rug"===t.datasymbol?n.values.forEach((e=>{r.beginPath(),"horizontal"==t.orientation?(r.moveTo(+i(e),0),r.lineTo(+i(e),2*c)):(r.moveTo(0,+i(e)),r.lineTo(2*c,+i(e))),r.stroke()})):"bean"===t.datasymbol&&n.values.forEach((e=>{r.beginPath(),"horizontal"===t.orientation?r.arc(+i(e),t.radius,c,0,u):r.arc(t.radius,+i(e),c,0,u),r.fill(),r.stroke()})),n.src=e.toDataURL();const o=(0,h.I)(i,n);n.bins=o.bins,n.biggestBin=Math.max(...o.bins0.map((t=>t.length))),n.summaryStats=g(n.values),delete n.values}}(t,N,n),!e)return N;e.send(N)}function b(t,e){var n,r;const o=new Map,i=null===(n=e.refs.byTermId[null==t||null===(r=t.term)||void 0===r?void 0:r.id])||void 0===n?void 0:n.bins;if(i)for(const t of i)o.set(t.label,t);return o}function w(t){return Object.fromEntries(Object.entries(t).sort((([,t],[,e])=>t-e)))}const _={endpoint:"termdb/violin",methods:{get:{init:x,request:{typeId:"getViolinRequest"},response:{typeId:"getViolinResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",devicePixelRatio:2.200000047683716,maxThickness:150,screenThickness:1218,filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{id:"subcohort",type:"categorical"},values:[{key:"ABC",label:"ABC"}]}}]},svgw:227.27272234672367,orientation:"horizontal",datasymbol:"bean",radius:5,strokeWidth:.2,axisHeight:60,rightMargin:50,unit:"abs",plotThickness:150,termid:"agedx"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:x}}};function x({genomes:t}){return async(e,n)=>{e.query;try{const r=t[e.query.genome],o=r.datasets[e.query.dslabel];if(!r)throw"invalid genome name";const i=await v(e.query,null,o,r);n.send(i)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},6733:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for CNV";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");return-1==o?"gene missing from header":(n[o]="gene",o=r("cnv"),-1==o?"CNV missing from header":(n[o]="cnv",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.cnv.header=n,e.cnv.loaded=!0,!1))}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.cnv.header.length;t++)s[n.cnv.header[t]]=i[t];if(!s.gene)return void n.cnv.badlines.push([t,"missing gene",i]);if(!s.cnv)return void n.cnv.badlines.push([t,"missing cnv value",i]);switch(s.cnv.toLowerCase()){case"amplification":case"gain":s.class=r.mclasscnvgain;break;case"deletion":case"loss":s.class=r.mclasscnvloss;break;case"loh":s.class=r.mclasscnvloh;break;default:n.cnv.badlines.push([t,"invalid cnv value: "+s.cnv,i]),s.class=null}if(!s.class)return;if(o.EJ(s,n,t,i,n.cnv.badlines))return;s.dt=r.dtcnv,n.good++;const a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}},5558:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for intragenic deletion";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";if(n[o]="isoform",o=r("rnaposition"),-1!=o){if(n[o]="rnaposition",o=r("rnadellength"),-1==o)return"rnadellength is required when rnaPosition is used";n[o]="rnadellength"}if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("chr_start"),-1==o)return"chr_start is required when chr is used";if(n[o]="chrpos1",o=r("chr_stop"),-1==o)return"chr_stop is required when chr is used";n[o]="chrpos2"}return o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.del.header=n,e.del.loaded=!0,!1}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.del.header.length&&null!=i[t];t++)s[n.del.header[t]]=i[t];if(s.gene){if(s.rnaposition){let e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaPosition value",i]);if(s.rnaposition=e,!s.rnadellength)return void n.del.badlines.push([t,"missing rnaDellength value",i]);if(e=Number.parseInt(s.rnadellength),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaDellength value",i]);s.rnadellength=e}if(s.chr){let e=Number.parseInt(s.chrpos1);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_start value",i]);if(s.chrpos1=e,e=Number.parseInt(s.chrpos2),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_stop value",i]);s.chrpos2=e}if(!o.EJ(s,n,t,i,n.del.badlines)){s.dt=r.dtdel,s.class=r.mclassdel,s.mname="DEL",n.good++;var a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}}else n.del.badlines.push([t,"missing gene",i])}},3602:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for ITD";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";if(n[o]="isoform",o=r("rnaposition"),-1!=o){if(n[o]="rnaposition",o=r("rnaduplength"),-1==o)return"rnaduplength is required when rnaposition is present";n[o]="rnaduplength"}if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("chr_start"),-1==o)return"chr_start is required when chr is present";if(n[o]="chrpos1",o=r("chr_stop"),-1==o)return"chr_stop is required when chr is present";n[o]="chrpos2"}return o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.itd.header=n,e.itd.loaded=!0,!1}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.itd.header.length&&null!=i[t];t++)s[n.itd.header[t]]=i[t];if(s.gene){if(s.rnaposition){let e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaPosition value",i]);if(s.rnaposition=e,!s.rnaduplength)return void n.itd.badlines.push([t,"missing rnaDuplength value",i]);if(e=Number.parseInt(s.rnaduplength),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaDuplength value",i]);s.rnaduplength=e}if(s.chr){let e=Number.parseInt(s.chrpos1);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_start value",i]);if(s.chrpos1=e,e=Number.parseInt(s.chrpos2),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_stop value",i]);s.chrpos2=e}if(!o.EJ(s,n,t,i,n.itd.badlines)){s.dt=r.dtitd,s.class=r.mclassitd,s.mname="ITD",n.good++;var a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}}else n.itd.badlines.push([t,"missing gene",i])}},8064:(t,e,n)=>{"use strict";n.d(e,{Dz:()=>o,EJ:()=>i});var r=n(2273);function o(t){if(!t)return null;const e={};for(const t in r.mclass)e[r.mclass[t].label.toUpperCase()]=t;return{genome:t,mclasslabel2key:e,data:{},sample2disease:{},patient2st:{},good:0,geneToUpper:!0,snv:{loaded:!1,header:null,badlines:[],missense:0,silent:0},svjson:{loaded:!1,header:null,badlines:[]},fusion:{loaded:!1,header:null,badlines:[],original:[]},sv:{loaded:!1,header:null,badlines:[],original:[]},cnv:{loaded:!1,header:null,badlines:[]},itd:{loaded:!1,header:null,badlines:[]},del:{loaded:!1,header:null,badlines:[]},truncation:{loaded:!1,header:null,badlines:[]}}}function i(t,e,n,o,i){let s=r.moriginsomatic;if(t.sampletype){switch(t.sampletype.toLowerCase()){case"relapse":s=r.moriginrelapse;break;case"germline":s=r.morigingermline}t.sample?t.patient||(t.patient=t.sample+" "+t.sampletype):t.patient&&(t.sample=t.patient+" "+t.sampletype)}else t.patient?t.sample?t.sampletype=t.sample:t.sample=t.sampletype=t.patient:t.sample&&(t.sampletype=t.sample);if(t.origin){switch(t.origin.toLowerCase()){case"r":case"relapse":s=r.moriginrelapse,t.isrim2=!0;break;case"g":case"germline":s=r.morigingermline,t.isrim1=!0;break;case"gp":case"germline pathogenic":s=r.morigingermlinepathogenic,t.isrim1=!0;break;case"gnp":case"germline nonpathogenic":case"germline non-pathogenic":s=r.morigingermlinenonpathogenic,t.isrim1=!0;break;case"s":case"somatic":case"diagnosis":s=r.moriginsomatic}}if(t.origin=s,!t.sample&&!t.patient)return;const a="no patient/individual name";if(t.patient?(e.patient2st[t.patient]||(e.patient2st[t.patient]={}),e.patient2st[t.patient][t.sampletype]=t.sample):(e.patient2st[a]||(e.patient2st[a]={}),e.patient2st[a][t.sampletype]=t.sample),t.sample&&t.disease)if(t.sample in e.sample2disease){if(t.disease!=e.sample2disease[t.sample])return e.snv.badlines.push([n,'conflict of disease types for sample "'+t.sample+'": '+t.disease+", "+e.sample2disease[t.sample],o]),!0}else e.sample2disease[t.sample]=t.disease;return!1}},5494:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for snv/indel";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("annovar_gene","annovar_sj_gene","gene","genename","gene_symbol","hugo_symbol");return-1==o?"gene missing from header":(n[o]="gene",o=r("annovar_aachange","amino_acid_change","annovar_sj_aachange","aachange","protein_change","variant"),-1==o?"amino_acid_change missing from header":(n[o]="mname",o=r("annovar_class","class","mclass","variant_class","variant_classification","annovar_sj_class"),-1==o?"variant_class missing from header":(n[o]="class",o=r("chromosome","chr"),-1==o?"chromosome missing from header":(n[o]="chr",o=r("wu_hg19_pos","start","start_position","chr_position","position"),-1==o?"start missing from header":(n[o]="pos",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o?"isoform missing from header":(n[o]="isoform",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("quantitative_measurements"),-1!=o&&(n[o]="qmset"),o=r("mutant_reads_in_case","mutant_in_tumor","tumor_readcount_alt"),-1!=o&&(n[o]="maf_tumor_v1"),o=r("total_reads_in_case","total_in_tumor","tumor_readcount_total"),-1!=o&&(n[o]="maf_tumor_v2"),o=r("mutant_reads_in_control","mutant_in_normal","normal_readcount_alt"),-1!=o&&(n[o]="maf_normal_v1"),o=r("total_reads_in_control","total_in_normal","normal_readcount_total"),-1!=o&&(n[o]="maf_normal_v2"),o=r("cdna_change"),-1!=o&&(n[o]="cdna_change"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("cancer","disease","diagnosis"),-1!=o&&(n[o]="disease"),e.snv.header=n,e.snv.loaded=!0,!1))))))}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.snv.header.length&&null!=i[t];t++)s[n.snv.header[t]]=i[t];if(!s.gene)return void n.snv.badlines.push([t,"missing gene",i]);if("UNKNOWN"==s.gene.toUpperCase())return void n.snv.badlines.push([t,"gene name is UNKNOWN",i]);if(!s.isoform)return void n.snv.badlines.push([t,"missing isoform",i]);if(s.mname)0==s.mname.indexOf("p.")&&(s.mname=s.mname.replace(/^p\./,""));else if(s.mname=s.cdna_change,!s.mname)return void n.snv.badlines.push([t,"missing amino acid change",i]);if(!s.class)return void n.snv.badlines.push([t,"missing mutation class",i]);let a=n.mclasslabel2key[s.class.toUpperCase()];if(a)s.class=a;else{if(a=r.mclasstester(s.class),!a)return void n.snv.badlines.push([t,"wrong mutation class: "+s.class,i]);s.class=a}if(o.EJ(s,n,t,i,n.snv.badlines))return;if(!s.chr)return void n.snv.badlines.push([t,"missing chromosome",i]);if(0!=s.chr.toLowerCase().indexOf("chr")&&(s.chr="chr"+s.chr),!s.pos)return void n.snv.badlines.push([t,"missing chromosome position",i]);const l=Number.parseInt(s.pos);if(Number.isNaN(l))return void n.snv.badlines.push([t,"invalid chromosome position",i]);if(s.pos=l-1,null!=s.maf_tumor_v2&&null!=s.maf_tumor_v1){if(""==s.maf_tumor_v2);else{let e=Number.parseInt(s.maf_tumor_v1),r=Number.parseInt(s.maf_tumor_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_tumor mutant and/or total read count",i]);s.maf_tumor={f:e/r,v1:e,v2:r}}delete s.maf_tumor_v1,delete s.maf_tumor_v2}if(null!=s.maf_normal_v1&&null!=s.maf_normal_v2){if(""==s.maf_normal_v2);else{let e=Number.parseInt(s.maf_normal_v1),r=Number.parseInt(s.maf_normal_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_normal mutant and/or total read count",i]);s.maf_normal={f:e/r,v1:e,v2:r}}delete s.maf_normal_v1,delete s.maf_normal_v2}n.good++,"M"==s.class?n.snv.missense++:"S"==s.class&&n.snv.silent++;const c=n.geneToUpper?s.gene.toUpperCase():s.gene;n.data[c]||(n.data[c]=[]),s.dt=r.dtsnvindel,n.data[c].push(s)}},6279:(t,e,n)=>{"use strict";n.r(e),n.d(e,{duplicate:()=>a,parseheader:()=>i,parseline:()=>s});var r=n(8064),o=n(2273);function i(t,e,n){const r=t.toLowerCase().split("\t");if(r.length<=1)return"invalid file header for fusions";const o=(...t)=>{for(const e of t){const t=r.indexOf(e);if(-1!=t)return t}return-1};let i=o("gene_a","gene1","genea");return-1==i?"gene_a missing from header":(r[i]="gene1",i=o("gene_b","gene2","geneb"),-1==i?"gene_b missing from header":(r[i]="gene2",i=o("chr_a","chr1","chra"),-1==i?"chr_a missing from header":(r[i]="chr1",i=o("chr_b","chr2","chrb"),-1==i?"chr_b missing from header":(r[i]="chr2",i=o("pos_a","position_a","position1","posa"),-1==i?"pos_a missing from header":(r[i]="position1",i=o("pos_b","position_b","position2","posb"),-1==i?"pos_b missing from header":(r[i]="position2",i=o("isoform_a","refseq_a","refseq1","isoform1","sv_refseqa"),-1==i?"isoform_a missing from header":(r[i]="isoform1",i=o("isoform_b","refseq_b","refseq2","isoform2","sv_refseqb"),-1==i?"isoform_b missing from header":(r[i]="isoform2",i=o("strand_a","orta"),-1==i?"strand_a missing from header":(r[i]="strand1",i=o("strand_b","ortb"),-1==i?"strand_b missing from header":(r[i]="strand2",i=o("sample","sample_name","tumor_sample_barcode"),-1!=i&&(r[i]="sample"),i=o("patient","donor","target_case_id"),-1!=i&&(r[i]="patient"),i=o("sampletype","sample type","sample_type"),-1!=i&&(r[i]="sampletype"),i=o("disease"),-1!=i&&(r[i]="disease"),i=o("origin"),-1!=i&&(r[i]="origin"),n?(e.sv.loaded=!0,e.sv.header=r):(e.fusion.loaded=!0,e.fusion.header=r),!1))))))))))}function s(t,e,n,i){if(""==e||"#"==e[0])return;const s=e.split("\t"),a={},l=i?n.sv.header:n.fusion.header,c=i?n.sv.badlines:n.fusion.badlines;for(let t=0;t<l.length;t++)a[l[t]]=s[t];if(!a.chr1)return void c.push([t,"missing chr1",s]);if(0!=a.chr1.toLowerCase().indexOf("chr")&&(a.chr1="chr"+a.chr1),!a.chr2)return void c.push([t,"missing chr2",s]);0!=a.chr2.toLowerCase().indexOf("chr")&&(a.chr2="chr"+a.chr2);let u=a.position1;if(!u)return void c.push([t,"missing position1",s]);let f=Number.parseInt(u);if(Number.isNaN(f)||f<=0)c.push([t,"invalid value for position1",s]);else if(a.position1=f,u=a.position2,u){if(f=Number.parseInt(u),Number.isNaN(f)||f<=0)c.push([t,"invalid value for position2",s]);else if(a.position2=f,!r.EJ(a,n,t,s,c)){if(a.isoform1&&-1!=a.isoform1.indexOf(",")){const t=a.isoform1.split(",");a.isoform1=void 0;for(const e of t)""!=e&&(a.isoform1=e)}if(a.isoform2&&-1!=a.isoform2.indexOf(",")){const t=a.isoform2.split(",");a.isoform2=void 0;for(const e of t)""!=e&&(a.isoform2=e)}if(a.gene1||(a.isoform1=void 0),a.gene2||(a.isoform2=void 0),a.gene1){n.good++;const t={dt:i?o.dtsv:o.dtfusionrna,class:i?o.mclasssv:o.mclassfusionrna,isoform:a.isoform1,mname:a.gene2||a.chr2,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},e=n.geneToUpper?a.gene1.toUpperCase():a.gene1;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}if(a.gene2&&a.gene2!=a.gene1){n.good++;const t={dt:i?o.dtsv:o.dtfusionrna,class:i?o.mclasssv:o.mclassfusionrna,isoform:a.isoform2,mname:a.gene1||a.chr1,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},e=n.geneToUpper?a.gene2.toUpperCase():a.gene2;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}}}else c.push([t,"missing position2",s])}function a(t){const e={};for(const n in t){if("pairlst"==n)continue;const r=t[n];"object"!=typeof r&&(e[n]=r)}if(t.pairlst){e.pairlst=[];for(const n of t.pairlst){const t={};for(const e in n)"a"!=e&&"b"!=e&&"interstitial"!=e&&(t[e]=n[e]);if(n.a){t.a={};for(const e in n.a){const r=n.a[e];"object"!=typeof r&&(t.a[e]=r)}}if(n.b){t.b={};for(const e in n.b){const r=n.b[e];"object"!=typeof r&&(t.b[e]=r)}}if(n.interstitial){t.interstitial={};for(const e in n.interstitial){const r=n.interstitial[e];"object"!=typeof r&&(t.interstitial[e]=r)}}e.pairlst.push(t)}}return e}},8423:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for svjson";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("sample");return-1!=o&&(n[o]="sample"),o=r("sampletype"),-1!=o&&(n[o]="sampletype"),o=r("patient"),-1!=o&&(n[o]="patient"),o=r("json","jsontext"),-1==o?["json missing from header"]:(n[o]="jsontext",[null,n])}function s(t,e,n,i){if(""==e||"#"==e[0])return;const s=e.split("\t"),l={},c=n.svjson.badlines;for(let t=0;t<i.length;t++)l[i[t]]=s[t];if(!l.jsontext)return void c.push([t,"missing jsontext",s]);if(o.EJ(l,n,t,s,c))return;let u;try{u=JSON.parse(l.jsontext)}catch(e){return void c.push([t,"invalid JSON text",s])}if(Array.isArray(u))for(const t of u){if(t.a&&t.a.name&&t.a.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.a.isoform,mname:t.b.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const o=t.a.name.toUpperCase();n.data[o]||(n.data[o]=[]),n.data[o].push(e)}if(t.b&&t.b.name&&t.b.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.b.isoform,mname:t.a.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const o=t.b.name.toUpperCase();n.data[o]||(n.data[o]=[]),n.data[o].push(e)}}else{switch(u.dt=u.typecode,delete u.typecode,u.dt){case r.dtitd:u.class=r.mclassitd,u.mname="ITD";break;case r.dtnloss:u.class=r.mclassnloss,u.mname="N-loss";break;case r.dtcloss:u.class=r.mclasscloss,u.mname="C-loss";break;case r.dtdel:u.class=r.mclassdel,u.mname="Del";break;case r.dtsv:u.class=r.mclasssv,u.mname="SV";break;default:return void c.push([t,"unknown datatype",s])}if(!u.gene)return void c.push([t,"json.gene missing",s]);n.good++;for(const t in l)"jsontext"!=t&&(u[t]=l[t]);const e=(n.geneToUpper,u.gene.toUpperCase());n.data[e]||(n.data[e]=[]),n.data[e].push(u)}}function a(t){const e=[];for(const n of t){const t={a:{},b:{}};for(const e in n)"a"!=e&&"b"!=e&&(t[e]=n[e]);for(const e in n.a)t.a[e]=n.a[e];for(const e in n.b)t.b[e]=n.b[e];e.push(t)}return e}},8235:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for truncation";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";n[o]="isoform";let i=!1;if(o=r("rnaposition"),-1!=o&&(n[o]="rnaposition",i=!0),o=r("losstype"),-1==o)return"lossType missing from header";n[o]="losstype";let s=!1;if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("start","start_position","wu_hg19_pos","chr_position","position"),-1==o)return"genomic position missing from header";n[o]="pos",s=!0}return i||s?(o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.truncation.header=n,e.truncation.loaded=!0,!1):"neither rnaposition nor genomic position is given"}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.truncation.header.length;t++)s[n.truncation.header[t]]=i[t];if(!s.gene)return void n.truncation.badlines.push([t,"missing gene",i]);if(s.rnaposition){const e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid rnaPosition value",i]);s.rnaposition=e}if(s.pos){const e=Number.parseInt(s.pos);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid genomic position",i]);s.pos=e}if(!s.losstype)return void n.truncation.badlines.push([t,"missing lossType value",i]);if("n"!=s.losstype&&"c"!=s.losstype)return void n.truncation.badlines.push([t,'lossType value not "n" or "c"',i]);if(o.EJ(s,n,t,i,n.truncation.badlines))return;"n"==s.losstype?(s.dt=r.dtnloss,s.class=r.mclassnloss,s.mname="N-loss"):(s.dt=r.dtcloss,s.class=r.mclasscloss,s.mname="C-loss"),n.good++;const a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}},2273:(t,e,n)=>{"use strict";n.r(e),n.d(e,{IN_frame:()=>c,OUT_frame:()=>u,alleleInGenotypeStr:()=>ht,applyOverrides:()=>Z,basecolor:()=>ot,basecompliment:()=>it,bplen:()=>rt,codon:()=>tt,codon_stop:()=>et,contigNameNoChr:()=>ut,contigNameNoChr2:()=>ft,custommdstktype:()=>Q,default_text_color:()=>a,defaultcolor:()=>s,dt2label:()=>_,dtcloss:()=>b,dtcnv:()=>p,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>h,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>v,dtsnvindel:()=>f,dtsv:()=>m,exoncolor:()=>l,fasta2gmframecheck:()=>lt,germlinelegend:()=>U,getColorScheme:()=>_t,getColors:()=>xt,getMax_byiqr:()=>dt,gmmode:()=>pt,kernelDensityEstimator:()=>yt,kernelEpanechnikov:()=>vt,mclass:()=>x,mclasscloss:()=>S,mclasscnvgain:()=>I,mclasscnvloh:()=>P,mclasscnvloss:()=>R,mclassdel:()=>q,mclassdeletion:()=>$,mclassfusionrna:()=>E,mclassinsertion:()=>L,mclassitd:()=>k,mclassmnv:()=>D,mclassnloss:()=>N,mclassnoncoding:()=>C,mclassnonstandard:()=>T,mclasssnv:()=>F,mclasssv:()=>O,mclasstester:()=>j,mclassutr3:()=>A,mclassutr5:()=>M,mdsvcftype:()=>X,morigin:()=>B,morigingermline:()=>J,morigingermlinenonpathogenic:()=>V,morigingermlinepathogenic:()=>H,moriginrelapse:()=>W,moriginsomatic:()=>G,not_annotated:()=>gt,nt2aa:()=>nt,proteinChangingMutations:()=>qt,reversecompliment:()=>st,schemeCategory2:()=>wt,schemeCategory20:()=>bt,spliceeventchangegmexon:()=>at,tkt:()=>Y,truncatingMutations:()=>kt,validate_vcfinfofilter:()=>ct,validtkt:()=>K,vcfcopymclass:()=>mt,vepinfo:()=>z});var r=n(1495);const o=n(4635),i=n(3016),s=(0,r.B8)("#8AB1D4").darker(),a=(0,r.B8)("#aaa").darker().darker(),l="#4F8053",c=!0,u=!1,f=1,d=2,h=3,p=4,m=5,g=6,y=7,v=8,b=9,w=10,_={[f]:"SNV/indel",[d]:"Fusion RNA",[p]:"CNV",[m]:"SV",[g]:"ITD",[y]:"Deletion",[v]:"N-loss",[b]:"C-loss",[w]:"LOH",[h]:"Gene Expression"},x={M:{label:"MISSENSE",color:"#3987CC",dt:f,desc:"A substitution variant in the coding region resulting in altered protein coding.",key:"M"},E:{label:"EXON",color:"#bcbd22",dt:f,desc:"A variant in the exon of a non-coding RNA.",key:"E"},F:{label:"FRAMESHIFT",color:"#db3d3d",dt:f,desc:"An insertion or deletion variant that alters the protein coding frame.",key:"F"},N:{label:"NONSENSE",color:"#ff7f0e",dt:f,desc:"A variant altering protein coding to produce a premature stopgain or stoploss.",key:"N"},S:{label:"SILENT",color:"#2ca02c",dt:f,desc:"A substitution variant in the coding region that does not alter protein coding.",key:"S"},D:{label:"PROTEINDEL",color:"#7f7f7f",dt:f,desc:"A deletion resulting in a loss of one or more codons from the product, but not altering the protein coding frame.",key:"D"},I:{label:"PROTEININS",color:"#8c564b",dt:f,desc:"An insertion introducing one or more codons into the product, but not altering the protein coding frame.",key:"I"},P:{label:"SPLICE_REGION",color:"#9467bd",dt:f,desc:"A variant in an intron within 10 nt of an exon boundary.",key:"P"},L:{label:"SPLICE",color:"#6633FF",dt:f,desc:"A variant near an exon edge that may affect splicing functionality.",key:"L"},Intron:{label:"INTRON",color:"#656565",dt:f,desc:"An intronic variant.",key:"Intron"},Blank:{label:"Not tested",color:"#fff",dt:f,desc:"This gene is not tested.",key:"Blank"},WT:{label:"Wildtype",color:"#D3D3D3",dt:f,desc:"Wildtype",key:"WT"}},k="ITD";x[k]={label:"ITD",color:"#ff70ff",dt:g,desc:"In-frame internal tandem duplication.",key:k};const q="DEL";x[q]={label:"DELETION, intragenic",color:"#858585",dt:y,desc:"Intragenic deletion.",key:q};const N="NLOSS";x[N]={label:"N-terminus loss",color:"#545454",dt:v,desc:"N-terminus loss due to translocation",key:N};const S="CLOSS";x[S]={label:"C-terminus loss",color:"#545454",dt:b,desc:"C-terminus loss due to translocation",key:S};const A="Utr3";x[A]={label:"UTR_3",color:"#998199",dt:f,desc:"A variant in the 3' untranslated region.",key:A};const M="Utr5";x[M]={label:"UTR_5",color:"#819981",dt:f,desc:"A variant in the 5' untranslated region.",key:M};const T="X";x[T]={label:"NONSTANDARD",color:"black",dt:f,desc:"A mutation class that either does not match our notation, or is unspecified.",key:T};const C="noncoding";function j(t){switch(t.toLowerCase()){case"missense_mutation":return"M";case"nonsense_mutation":case"nonstop_mutation":return"N";case"splice_site":return"L";case"rna":case"3'flank":case"5'flank":return C;case"frame_shift_del":case"frame_shift_ins":return"F";case"in_frame_del":return"D";case"in_frame_ins":return"I";case"translation_start_site":return T;case"3'utr":return A;case"5'utr":return M;case"blank":return"Blank";default:return null}}x[C]={label:"NONCODING",color:"black",dt:f,desc:"Noncoding mutation.",key:C};const E="Fuserna";x[E]={label:"Fusion transcript",color:"#545454",dt:d,desc:"Marks the break points leading to fusion transcripts.<br><span style=\"font-size:150%\">◐</span> - 3' end of the break point is fused to the 5' end of another break point in a different gene.<br><span style=\"font-size:150%\">◑</span> - 5' end of the break point is fused to the 3' end of another break point in a different gene.",key:E};const O="SV";x[O]={label:"Structural variation",color:"#858585",dt:m,desc:"Structural variation detected in genomic DNA.",key:O};const I="CNV_amp";x[I]={label:"Copy number gain",color:"#e9a3c9",dt:p,desc:"Copy number gain",key:I};const R="CNV_loss";x[R]={label:"Copy number loss",color:"#a1d76a",dt:p,desc:"Copy number loss",key:R};const P="CNV_loh";x[P]={label:"LOH",color:"#12EDFC",dt:p,desc:"Loss of heterozygosity",key:P};const F="snv";x[F]={label:"SNV",color:"#92a2d4",dt:f,desc:"Single nucleotide variation",key:F};const D="mnv";x[D]={label:"MNV",color:"#92a2d4",dt:f,desc:"Multiple nucleotide variation",key:D};const L="insertion";x[L]={label:"Sequence insertion",color:"#bd8e91",dt:f,desc:"Sequence insertion",key:L};const $="deletion";function Z(t={}){if(t.mclass)for(const e in t.mclass){x[e]||(x[e]={});for(const n in t.mclass[e])x[e][n]=t.mclass[e][n]}}x[$]={label:"Sequence deletion",color:"#b5a174",dt:f,desc:"Sequence deletion",key:$};const z=function(t){const e=t.toLowerCase().split(",");let n=1;return-1!=e.indexOf("transcript_ablation")?[y,q,n]:(n++,-1!=e.indexOf("splice_acceptor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("splice_donor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("stop_gained")?[f,"N",n]:(n++,-1!=e.indexOf("frameshift_variant")?[f,"F",n]:(n++,-1!=e.indexOf("stop_lost")?[f,"N",n]:(n++,-1!=e.indexOf("start_lost")?[f,"N",n]:(n++,-1!=e.indexOf("transcript_amplification")?[f,T,n]:(n++,-1!=e.indexOf("inframe_insertion")||-1!=e.indexOf("conservative_inframe_insertion")||-1!=e.indexOf("disruptive_inframe_insertion")?[f,"I",n]:(n++,-1!=e.indexOf("inframe_deletion")||-1!=e.indexOf("conservative_inframe_deletion")||-1!=e.indexOf("disruptive_inframe_deletion")?[f,"D",n]:(n++,-1!=e.indexOf("missense_variant")?[f,"M",n]:(n++,-1!=e.indexOf("protein_altering_variant")?[f,"N",n]:(n++,-1!=e.indexOf("splice_region_variant")?[f,"P",n]:(n++,-1!=e.indexOf("incomplete_terminal_codon_variant")?[f,"N",n]:(n++,-1!=e.indexOf("stop_retained_variant")?[f,"S",n]:(n++,-1!=e.indexOf("synonymous_variant")?[f,"S",n]:(n++,-1!=e.indexOf("coding_sequence_variant")?[f,T,n]:(n++,-1!=e.indexOf("mature_mirna_variant")?[f,"E",n]:(n++,-1!=e.indexOf("5_prime_utr_variant")?[f,M,n]:(n++,-1!=e.indexOf("3_prime_utr_variant")?[f,A,n]:(n++,-1!=e.indexOf("non_coding_transcript_exon_variant")?[f,"E",n]:(n++,-1!=e.indexOf("intron_variant")?[f,"Intron",n]:(n++,-1!=e.indexOf("nmd_transcript_variant")?[f,"S",n]:(n++,-1!=e.indexOf("non_coding_transcript_variant")?[f,"E",n]:(n++,-1!=e.indexOf("upstream_gene_variant")?[f,C,n]:(n++,-1!=e.indexOf("downstream_gene_variant")?[f,C,n]:(n++,-1!=e.indexOf("tfbs_ablation")?[f,C,n]:(n++,-1!=e.indexOf("tfbs_amplification")?[f,C,n]:(n++,-1!=e.indexOf("tf_binding_site_variant")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_ablation")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_amplification")?[f,C,n]:(n++,-1!=e.indexOf("feature_elongation")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_variant")?[f,C,n]:(n++,-1!=e.indexOf("feature_truncation")?[f,C,n]:(n++,-1!=e.indexOf("intergenic_variant")?[f,C,n]:(n++,[f,T,n])))))))))))))))))))))))))))))))))))},U='<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="#858585" stroke="none"></path>',B={},G="S";B[G]={label:"Somatic",desc:"A variant found only in a tumor sample. The proportion is indicated by lack of any arc.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle>'};const J="G";B[J]={label:"Germline",desc:"A constitutional variant found in a normal sample. The proportion is indicated by the span of the solid arc within the whole circle.",legend:U},B.germline=B[J],B.somatic=B[G];const W="R";B[W]={label:"Relapse",desc:"A somatic variant found only in a relapse sample. The proportion is indicated by the span of the hollow arc within the whole circle.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="none" stroke="#858585"></path>'};const H="GP";B[H]={label:"Germline pathogenic",desc:"A constitutional variant with pathogenic allele.",legend:U};const V="GNP";B[V]={label:"Germline non-pathogenic",desc:"A constitutional variant with non-pathogenic allele.",legend:U,hidden:!0};const Y={usegm:"usegm",ds:"dataset",bigwig:"bigwig",bigwigstranded:"bigwigstranded",junction:"junction",mdsjunction:"mdsjunction",mdscnv:"mdscnv",mdssvcnv:"mdssvcnv",mdsexpressionrank:"mdsexpressionrank",mdsvcf:"mdsvcf",bedj:"bedj",pgv:"profilegenevalue",bampile:"bampile",hicstraw:"hicstraw",expressionrank:"expressionrank",aicheck:"aicheck",ase:"ase",mds2:"mds2",mds3:"mds3",bedgraphdot:"bedgraphdot",bam:"bam",ld:"ld"};function K(t){for(const e in Y)if(t==Y[e])return!0;return!1}const X={vcf:"vcf"},Q={vcf:"vcf",svcnvitd:"svcnvitd",geneexpression:"geneexpression"},tt={GCT:"A",GCC:"A",GCA:"A",GCG:"A",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGA:"R",AGG:"R",AAT:"N",AAC:"N",GAT:"D",GAC:"D",TGT:"C",TGC:"C",CAA:"Q",CAG:"Q",GAA:"E",GAG:"E",GGT:"G",GGC:"G",GGA:"G",GGG:"G",CAT:"H",CAC:"H",ATT:"I",ATC:"I",ATA:"I",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",AAA:"K",AAG:"K",ATG:"M",TTT:"F",TTC:"F",CCT:"P",CCC:"P",CCA:"P",CCG:"P",TCT:"S",TCC:"S",TCA:"S",TCG:"S",AGT:"S",AGC:"S",ACT:"T",ACC:"T",ACA:"T",ACG:"T",TGG:"W",TAT:"Y",TAC:"Y",GTT:"V",GTC:"V",GTA:"V",GTG:"V"},et="*";function nt(t){if(!t.genomicseq)return;const e=[];if(t.coding)for(const[n,r]of t.coding.entries()){const n=t.genomicseq.substr(r[0]-t.start,r[1]-r[0]);"-"==t.strand?e.push(st(n)):e.push(n)}const n=e.join(""),r=[];for(let e=t.startCodonFrame?3-t.startCodonFrame:0;e<n.length;e+=3){const t=tt[n.substr(e,3)];r.push(t||et)}return t.cdseq=n,r.join("")}function rt(t,e){return t>=1e9?(t/1e9).toFixed(1)+" Gb":t>=1e7?Math.ceil(t/1e6)+" Mb":t>=1e6?(t/1e6).toFixed(1)+" Mb":t>=1e4?Math.ceil(t/1e3)+" Kb":t>=1e3?(t/1e3).toFixed(1)+" Kb":t+(e?"bytes":" bp")}const ot={A:"#ca0020",T:"#f4a582",C:"#92c5de",G:"#0571b0"};function it(t){switch(t){case"A":return"T";case"T":return"A";case"C":return"G";case"G":return"C";case"a":return"t";case"t":return"a";case"c":return"g";case"g":return"c";default:return t}}function st(t){const e=[];for(let n=t.length-1;n>=0;n--)e.push(it(t[n]));return e.join("")}function at(t,e){const n={chr:t.chr,start:t.start,stop:t.stop,strand:t.strand,coding:[]};if(e.isskipexon||e.isaltexon)for(let r=0;r<t.exon.length;r++){const o=Math.max(t.codingstart,t.exon[r][0]),i=Math.min(t.codingstop,t.exon[r][1]);o>i||-1==e.skippedexon.indexOf(r)&&n.coding.push([o,i])}else if(e.a5ss||e.a3ss){const r=t.exon.map((t=>[t[0],t[1]])),o="+"==t.strand;e.a5ss?o?r[e.exon5idx][1]=e.junctionB.start:r[e.exon5idx+1][0]=e.junctionB.stop:o?r[e.exon5idx+1][0]=e.junctionB.stop:r[e.exon5idx][1]=e.junctionB.start;for(const e of r){const r=Math.max(t.codingstart,e[0]),o=Math.min(t.codingstop,e[1]);r>o||n.coding.push([r,o])}}return n}function lt(t,e){const n=e.split("\n");n.shift(),t.genomicseq=n.join("").toUpperCase();const r=nt(t);let o=u;return r.indexOf(et)==r.length-1&&(o=c),o}function ct(t){if(!t.lst)return".lst missing";if(!Array.isArray(t.lst))return"input is not an array";for(const e of t.lst){if(!e.name)return"name missing from a set of .vcfinfofilter.lst";if(e.autocategory||e.categories){if(!e.autocategory)for(const t in e.categories){const n=e.categories[t];if(!e.autocolor&&!n.color)return".color missing for class "+t+" from .categories of set "+e.name;n.label||(n.label=t)}if(e.categoryhidden){for(const t in e.categoryhidden)if(!e.categories[t])return"unknown hidden-by-default category "+t+" from set "+e.name}else e.categoryhidden={}}else if(e.numericfilter){const t=[];for(const n of e.numericfilter)"number"==typeof n?t.push({side:"<",value:n}):t.push({side:n.side||"<",value:n.value});e.numericfilter=t}if(e.altalleleinfo){if(!e.altalleleinfo.key)return".key missing from .altalleleinfo from set "+e.name}else{if(!e.locusinfo)return"neither .altalleleinfo or .locusinfo is available from set "+e.name;if(!e.locusinfo.key)return".key missing from .locusinfo from set "+e.name}}}function ut(t,e){for(const n in t.majorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;if(t.minorchr)for(const n in t.minorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;return!1}function ft(t,e){let n=0,r=0;for(const o in t.majorchr)e.includes(o)?r++:e.includes(o.replace("chr",""))&&n++;if(t.minorchr)for(const o in t.minorchr)e.includes(o)?r++:e.includes(o.replace("chr",""))&&n++;return[n,r]}function dt(t,e){if(0==t.length)return e;t.sort(((t,e)=>t-e));const n=t[t.length-1];if(t.length<=5)return n;const r=t[Math.floor(t.length/4)],o=t[Math.floor(3*t.length/4)];return Math.min(o+1.5*(o-r),n)}function ht(t,e){return!!t&&(-1!=t.indexOf("/")?-1!=t.split("/").indexOf(e):-1!=t.split("|").indexOf(e))}const pt={genomic:"genomic",splicingrna:"splicing RNA",exononly:"exon only",protein:"protein",gmsum:"aggregated exons"};function mt(t,e){if(t.csq){let n;if(e.usegm&&(n=t.csq.find((t=>t._isoform==e.usegm.isoform))),!n&&(n=t.csq.find((t=>t.CANONICAL)),!n)){n=t.csq[0];for(const e of t.csq)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==C&&delete t.class)}else if(t.ann){let n=null;if(e.usegm){for(const r of t.ann)r._isoform==e.usegm.isoform&&(n?r._csqrank<n._csqrank&&(n=r):n=r);n||e.gmmode!=pt.genomic||(n=t.ann[0])}else{n=t.ann[0];for(const e of t.ann)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==C&&delete t.class)}null==t.class&&(x[t.type]?(t.class=t.type,t.dt=x[t.type].dt,t.mname=t.id&&"."!=t.id?t.id:t.ref+">"+t.alt,t.mname.length>15&&(t.mname=t.type)):(t.class=T,t.dt=f,t.mname=t.type)),delete t.type}const gt="Unannotated";function yt(t,e){return function(n){return e.map((e=>[e,n.map((n=>t(e-n))).reduce(((t,e)=>t+e),0)/n.length]))}}function vt(t){return function(e){return Math.abs(e/=t)<=1?.75*(1-e*e)/t:0}}const bt=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],wt=["#e75480","blue"];function _t(t){return t>12?bt:t>8?i.schemePaired:t>2?i.schemeDark2:wt}function xt(t){return o.scaleOrdinal(_t(t))}const kt=["F","N","D","I","L"],qt=["F","N","D","I","L","M","P"]},7027:(t,e,n)=>{"use strict";function r(t,e){t.sort(((t,e)=>t-e));const n=Math.abs(e/100*t.length-1);return Number.isInteger(n)?(t[n]+t[n+1])/2:t[Math.ceil(n)]}n.d(e,{Z:()=>r})},478:(t,e,n)=>{"use strict";function r(t){if(!t||0==t.length)return;let e=JSON.parse(JSON.stringify(t[0]));if(1==t.length)return e;if(e.lst.length<2){if(""!==e.join)throw'filter.join must be an empty string "" when filter.lst.length < 2';e.join="and"}else if("or"==e.join)e={type:"tvslst",join:"and",in:!0,lst:[e]};else if("and"!=e.join)throw'filter.join must be either "and" or "or" when .lst length > 1';for(let n=1;n<t.length;n++){const r=JSON.parse(JSON.stringify(t[n]));"or"==r.join?e.lst.push(r):e.lst.push(...r.lst)}return 1==e.lst.length&&"tvs"==e.lst[0].type&&(e.join=""),e}n.d(e,{xH:()=>r})},5684:(t,e,n)=>{"use strict";function r(t,e){const n=Number(t);return Number.isInteger(n)?n:Math.abs(n)<1?Number(n.toPrecision(e)):Number(n.toFixed(e))}n.d(e,{Z:()=>r})},4048:(t,e,n)=>{"use strict";n.d(e,{gp:()=>a});var r=n(2163),o=n(2273);function i(t){return!isNaN(parseFloat(t))&&isFinite(t)}function s(t,e,n,r,o){if(r>=1){const e=Math.floor(t*r);return o?`${e}${n.charAt(0)}`:`${e} ${e>1?n+"s":""}`}const i=Math.floor(t*r),s=Math.ceil(t%(1/r));return 0==s?o?`${i}${n.charAt(0)}`:`${i} ${i>1?n+"s":""}`:o?`${i}${n.charAt(0)}${s}${e.charAt(0)}`:`${i} ${i>1?n+"s":""} ${s} ${s>1?e+"s":""}`}function a(t,e,n){const r=t;if(function(t){const e=t;if(!e||"object"!=typeof e)throw"bin schema must be an object";if("type"in e||(e.type="regular-bin"),"custom-bin"==e.type){if(!Array.isArray(e.lst))throw"binconfig.lst must be an array";if(!e.lst.length)throw"binconfig.lst must have entries";const t=e.lst[0],n=e.lst[e.lst.length-1];for(const r of e.lst){if(!("startinclusive"in r)&&!("stopinclusive"in r))throw"custom bin.startinclusive and/or bin.stopinclusive must be defined";if(r==t){if("startunbounded"in r&&!r.startunbounded)throw"a custom first bin must not set bin.startunbounded to false";if(r.startunbounded=!0,"start"in r)throw"a custom first bin must not set a bin.start value";if("start_percentile"in r)throw"the first bin must not set a bin.start_percentile value";if(!("stop"in r))throw"a custom first bin must define a bin.stop value";if(!i(r.stop))throw"a custom first bin.stop value should be numeric"}else if(r==n){if(!("start"in r))throw"a custom last bin must define a bin.start value";if(!i(r.start))throw"a custom last bin.start must be numeric";if("stopunbounded"in r&&!r.stopunbounded)throw"a custom last bin must not set bin.stopunbounded to false";if(r.stopunbounded=!0,"stop"in r)throw"a custom last bin must not set a bin.stop value"}else{if(!i(r.start))throw"bin.start must be numeric for a non-first bin";if(!i(r.stop))throw"bin.stop must be numeric for a non-last bin"}}}else{if("regular-bin"!=e.type)throw`invalid binconfig.type="${e.type}"`;if(!Number.isFinite(e.bin_size))throw"non-numeric bin_size";if(e.bin_size<=0)throw"bin_size must be greater than 0";if(e.startinclusive||e.stopinclusive||(e.startinclusive=1,e.stopinclusive=0),!e.first_bin)throw"first_bin{} missing";if("object"!=typeof e.first_bin)throw"first_bin{} is not an object";if(!Object.keys(e.first_bin).length)throw"first_bin is an empty object";{const t=e.first_bin;if(t.startunbounded=!0,t.stop_percentile){if(!Number.isInteger(t.stop_percentile))throw"first_bin.stop_percentile should be integer";if(t.stop_percentile<=0||t.stop_percentile>=100)throw"first_bin.stop_percentile out of bound (0-100)"}else if(!Number.isFinite(t.stop))throw"first_bin.stop not a number when stop_percentile is not set"}if(e.last_bin){const t=e.last_bin;if(t.start_percentile){if(!Number.isInteger(t.start_percentile))throw"last_bin.start_percentile should be integer";if(t.start_percentile<=0||t.start_percentile>=100)throw"last_bin.start_percentile out of bound (0-100)"}else if(!Number.isFinite(t.start))throw"last_bin.start not a number when start_percentile is not set";if(t.stopunbounded=!0,"stop"in t)throw"a regular last bin must not set a bin.stop value"}}}(r),r.lst){const t=(0,o.getColors)(r.lst.length);for(const e of r.lst)e.color=t(e.label)}if("custom-bin"==r.type)return JSON.parse(JSON.stringify(r.lst));if("function"!=typeof e)throw"summaryfxn required for modules/termdb.bins.js compute_bins()";const s=function(t){const e=[],n=t.first_bin;n&&i(n.start_percentile)&&e.push(n.start_percentile);n&&i(n.stop_percentile)&&e.push(n.stop_percentile);const r=t.last_bin;r&&i(r.start_percentile)&&e.push(r.start_percentile);r&&i(r.stop_percentile)&&e.push(r.stop_percentile);return e}(r),a=e(s);if(!a||"object"!=typeof a)throw"invalid returned value by summaryfxn";r.results={summary:a},r.binLabelFormatter||(r.binLabelFormatter=l(r));const u=Math.floor(100*a.min)/100,f=Math.ceil(100*a.max)/100,d=r.first_bin.startunbounded?u:r.first_bin.start_percentile?a["p"+r.first_bin.start_percentile]:r.first_bin.start;let h,p,m=f;if(r.last_bin)m=r.last_bin.stopunbounded?f:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:i(r.last_bin.stop)&&r.last_bin.stop<=a.max?r.last_bin.stop:f,h=i(r.last_bin.start_percentile)?a["p"+r.last_bin.start_percentile]:i(r.last_bin.start)?r.last_bin.start:void 0,p=r.last_bin.stopunbounded?null:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:i(r.last_bin.stop)?r.last_bin.stop:null;else if(r.lst){const t=r.lst[r.lst.length-1];h=t.start,p="stop"in t&&!t.stopunbounded?t.stop:f,m=p}else h=f,p=f;const g=i(m),y=i(h),v=i(p);if(!g&&!y)return[];const b=[];let w={startunbounded:r.first_bin.startunbounded,start:r.first_bin.startunbounded?void 0:d,stop:i(r.first_bin.stop_percentile)?+a["p"+r.first_bin.stop_percentile]:i(r.first_bin.stop)?+r.first_bin.stop:d+r.bin_size,startinclusive:r.startinclusive,stopinclusive:r.stopinclusive};if(!i(w.stop))throw"the computed first_bin.stop is non-numeric"+w.stop;for(;(g&&w.stop<=m||w.startunbounded&&!b.length||w.stopunbounded)&&(b.push(w),w.stop>=m&&(w.stopunbounded=!0,b.length>1&&delete w.stop),w.label=c(w,r,n),!w.stopunbounded);){const t=w.stop+r.bin_size,e=w.stop;if(w={startinclusive:r.startinclusive,stopinclusive:r.stopinclusive,start:e,stop:v&&(e==h||t>p)?p:y&&t>h&&e!=h?h:t},w.stop>=m&&(w.stop=m,r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),r.last_bin&&r.last_bin.stopinclusive&&(w.stopinclusive=1)),y&&w.start==h&&r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),w.start>w.stop){if(!(y&&w.stop==h&&r.last_bin&&r.last_bin.stopunbounded))break;w.stopunbounded=!0}if(b.length+1>=100){r.error="max_num_bins_reached";break}}delete r.binLabelFormatter,b.length>1&&delete b[b.length-1].stop;const _=(0,o.getColors)(b.length);for(const t of b)t.color=_(t.label);return b}function l(t){return"rounding"in t?(0,r.WU)(t.rounding):t=>t}function c(t,e,n){const r=e;r.binLabelFormatter||(r.binLabelFormatter=l(r)),t.startunbounded||t.stopunbounded||"startinclusive"in t||"stopinclusive"in t||(r.startinclusive?t.startinclusive=!0:r.stopinclusive&&(t.stopinclusive=!0));const o="bins"==r.use_as||t.start,i="bins"==r.use_as||t.stop;let a=0;if("label_offset"in r?(r.label_offset_ignored="bin_size"in r&&r.bin_size<r.label_offset,r.label_offset_ignored||(a=r.label_offset)):1===r.bin_size&&"integer"==r.termtype&&(a=1),t.startunbounded){return(t.stopinclusive?"≤":"<")+(n?s(i,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(i))}if(t.stopunbounded||o===i){return(t.startinclusive?"≥":">")+(n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o))}if(a&&t.startinclusive&&!t.stopinclusive){if(Number.isInteger(r.bin_size)&&Math.abs(o-i)===a)return""+(n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o));{const t=n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o),e=n?s(i-a,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(i-a);return+t>=+e?t.toString():t+" to "+e}}{const e=t.startinclusive?"":">",a=t.stopinclusive?"":"<",l=n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(o)?o:r.binLabelFormatter(o),c=n?s(i,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(i)?i:r.binLabelFormatter(i);if(+l>=+c){return(t.startinclusive?"≥":">")+l}return e+l+" to "+a+c}}},1575:(t,e,n)=>{"use strict";n.d(e,{CG:()=>o});new Set(["snplst","prs","snplocus","geneVariant","samplelst"]);const r=new Set(["categorical","integer","float","condition","survival","snplst","snplocus","geneVariant","samplelst"]);function o(t,e,n){const o=e||{};if(n&&n.usecase&&use.target in n.usecase)return n.usecase[use.target](t,use);const a=new Set,l=t.child_types||[];switch(o.target){case"barchart":case"summary":case"matrix":return"term0"==o.detail&&"geneVariant"==t.type||("term2"==o.detail&&"geneVariant"==t.type&&"geneVariant"==o.term1type||(t.type&&"survival"!==t.type&&a.add("plot"),i(l)&&a.add("branch"))),a;case"table":return"term"==o.detail&&a.add("plot"),l.length>1&&a.add("branch"),a;case"scatterplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch"),a;case"sampleScatter":return"numeric"==o.detail?("float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch")):(r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch")),a;case"boxplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),"term2"===o.detail&&s(l)&&a.add("branch"),a;case"cuminc":if("term"==o.detail)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a;if("term2"===o.detail)return t.type&&"survival"!=t.type&&a.add("plot"),i(l)&&a.add("branch"),a;if("term0"==o.detail)return a.add("plot"),a;case"survival":return"term"==o.detail?("survival"==t.type&&a.add("plot"),l.includes("survival")&&a.add("branch"),a):"term2"===o.detail?("survival"!=t.type&&(t.type&&a.add("plot"),i(l)&&a.add("branch")),a):"term0"==o.detail?(t.type&&a.add("plot"),i(l)&&a.add("branch"),a):(t.isleaf?a.add("plot"):a.add("branch"),a);case"regression":if("outcome"==o.detail){if("linear"==o.regressionType)return"float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch"),a;if("logistic"==o.regressionType)return t.type&&"survival"!=t.type&&a.add("plot"),i(l)&&a.add("branch"),a;if("cox"==o.regressionType)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a}if("independent"==o.detail)return"float"!=t.type&&"integer"!=t.type&&"categorical"!=t.type||a.add("plot"),function(t,e){for(const n of e)if(t.includes(n))return!0}(l,["categorical","float","integer"])&&a.add("branch"),a;default:return r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch"),a}}function i(t){return!!t.length&&(t.length>1||"survival"!=t[0])}function s(t){return t.includes("float")||t.includes("integer")}},1881:(t,e,n)=>{"use strict";n.d(e,{N:()=>i});const r="root",o="...";function i(t,e){const n=Object.create(null),i=Object.create(null),a=Object.create(null);for(const r of t)for(const[t,o]of e.entries()){const l=s(r,t,e),c=s(r,t-1,e);if(!r[o.k]){t>0&&(a[c]+=1);break}if(n[l]=c,l in a||(a[l]=0),!(l in i)){const n={lst:[]};o.full&&(n.full=r[o.full]),n.id0=e[0].k,n.v0=r[e[0].k],1==t&&(n.id1=e[1].k,n.v1=r[e[1].k]),2==t&&(n.id2=e[2].k,n.v1=r[e[2].k]),i[l]=n}i[l].lst.push(r),t==e.length-1&&(a[l]+=1)}const l=[{id:r,name:r}];for(const t in n){const e=n[t],r=i[t],s=t.split(o);l.push({id:t,parentId:e,lst:r.lst,value:a[t],name:s[s.length-1],full:r.full,id0:r.id0,v0:r.v0,id1:r.id1,v1:r.v1,id2:r.id2,v2:r.v2})}return l}function s(t,e,n){const i=[r];for(let r=0;r<e;r++)i.push(t[n[r].k]);return e>=0&&i.push(t[n[e].k]),i.join(o)}},4298:(t,e,n)=>{"use strict";n.d(e,{A:()=>o});var r=n(2273);function o(t,e,n){if(!e)return null;for(const o of t.split(",")){const t=o.replace(/&/g,",").split("|"),i={};for(let n=0;n<e.length;n++)t[n]&&(i[e[n].name]=t[n]);if(!i.Allele)continue;let s=null;for(const t of n.mlst||n.alleles)if(t.allele_original==i.Allele){s=t;break}if(!s){if("-"==i.Allele)n.mlst?1==n.mlst.length&&(s=n.mlst[0]):n.alleles&&1==n.alleles.length&&(s=n.alleles[0]);else for(const t of n.mlst||n.alleles)if(t.allele_original.substr(1)==i.Allele){s=t;break}if(!s)continue}if(s.csq||(s.csq=[]),s.csq.push(i),i._gene=i.SYMBOL||i.Gene,i.Feature_type&&"Transcript"==i.Feature_type?i._isoform=i.Feature.split(".")[0]:i._isoform=i._gene,i.Consequence){const[t,e,n]=(0,r.vepinfo)(i.Consequence);i._dt=t,i._class=e,i._csqrank=n}else i._dt=dtsnvindel,i._class=mclassnonstandard;i.HGVSp?i._mname=decodeURIComponent(i.HGVSp.substr(i.HGVSp.indexOf(":")+1)):i.Protein_position&&i.Amino_acids?i._mname=decodeURIComponent(i.Protein_position+i.Amino_acids):i.HGVSc?i._mname=i.HGVSc.substr(i.HGVSc.indexOf(":")+1):i.Existing_variation&&(i._name=i.Existing_variation)}return!0}},9380:(t,e,n)=>{"use strict";function r(t){let e=!1,n=!0,r=0,o=0;const i={};let s;for(;r<t.length;){const a=t[r];n?"="==a?(e=!0,n=!1,s=t.substring(o,r),o=r+1):";"==a&&(i[t.substring(o,r)]=1,o=r+1):e&&";"==a&&(n=!0,e=!1,i[s]=t.substring(o,r),s=null,o=r+1),r++}const a=t.substr(o,r);return s?i[s]=a:i[a]=1,i}n.d(e,{w:()=>r})},6819:(t,e,n)=>{"use strict";n.d(e,{S:()=>d,e:()=>f});var r=n(2273),o=n(9380),s=n(4298);function a(t,e,n){if(!e)return null;for(const o of t.split(",")){const t=o.replace(/&/g,",").split("|"),i={};for(let n=0;n<e.length;n++)t[n]&&(i[e[n].name]=t[n]);if(!i.Allele)continue;let s=null;for(const t of n.alleles)if(t.allele==i.Allele){s=t;break}if(s){if(s.ann||(s.ann=[]),s.ann.push(i),i._gene=i.Gene_Name,i.Feature_Type&&"transcript"==i.Feature_Type&&i.Feature_ID&&(i._isoform=i.Feature_ID.split(".")[0]),i.Annotation){const[t,e,n]=(0,r.vepinfo)(i.Annotation);i._dt=t,i._class=e,i._csqrank=n}else i._dt=dtsnvindel,i._class=mclassnonstandard;i["HGVS.p"]?i._mname=i["HGVS.p"]:i["HGVS.c"]&&(i._mname=i["HGVS.c"])}}return!0}var l=n(736);const c=new RegExp(/<(.+)>/),u={};for(const t in r.mclass)u[r.mclass[t].label.toUpperCase()]=t;function f(t){let e=[],n=[],r={},o=!1,i={},s=!1;for(const a of t)if(a.startsWith("#"))if(a.startsWith("#C"))e=a.split("\t").slice(9);else if(a.startsWith("##INFO")){const t=p(a.substring(8,a.length-1),r);t?n.push("INFO error: "+t):o=!0}else if(a.startsWith("##FORMAT")){const t=p(a.substring(10,a.length-1),i);t?n.push("FORMAT error: "+t):s=!0}const a=[];for(const t of e){const e={name:t};a.push(e)}if(r.CSQ){const t=r.CSQ.Description.split(" Format: ");if(t[1]){const e=t[1].split("|");if(e.length>1){r.CSQ.csqheader=[];for(const t of e){const e={name:t};r.CSQ.csqheader.push(e)}}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}if(r.ANN){const t=r.ANN.Description.split("'");if(t[1]){const e=t[1].split(" | ");if(e.length){r.ANN.annheader=[];for(const t of e){const e={name:t};r.ANN.annheader.push(e)}}else n.push('no " | " joined annotation fields for ANN (snpEff annotation): '+r.ANN.Description)}else n.push("no single-quote enclosed annotation fields for ANN (snpEff annotation): "+r.ANN.Description)}return[o?r:null,s?i:null,a,n.length?n:null]}function d(t,e){const n=t.split("\t");if(n.length<8)return["line has less than 8 fields",null,null];const r=Number.parseInt(n[1]);if(!Number.isInteger(r))return["invalid value for genomic position",null,null];const i=n[3],u={vcf_ID:n[2],chr:(e.nochr?"chr":"")+n[0],pos:r-1,ref:i,altstr:n[4],alleles:[{allele:i,sampledata:[]}],info:{},name:"."==n[2]?null:n[2]},f=[];for(const t of n[4].split(",")){const e={ref:u.ref,allele:t,allele_original:t,sampledata:[],_m:u,info:{}};if(u.alleles.push(e),"<"==t[0]){const n=t.match(c);if(!n){f.push(t);continue}e.type=n[1],e.allele=n[1],e.issymbolicallele=!0}else{const[t,n,r]=h(u.pos,u.ref,e.allele);e.pos=t,e.ref=n,e.allele=r}}n[8]&&n[9]&&function(t,e,n){const r=t[8].split(":");for(let o=9;o<t.length;o++){const i=t[o].split(":");{let t=!0;for(const e of i)if("."!=e){t=!1;break}if(t)continue}const s=o-9;for(let t=1;t<e.alleles.length;t++){const r={};if(n.samples&&n.samples[s])for(const t in n.samples[s])r[t]=n.samples[s][t];else r.name="missing_samplename_from_vcf_header";e.alleles[t].sampledata.push({sampleobj:r})}for(let t=0;t<r.length;t++){const o=r[t],s=i[t];if("."==s)continue;if("GT"==o){const t=-1!=s.indexOf("/")?"/":"|";let n=0,r=!1;const o=[];for(const i of s.split(t)){if("."==i){r=!0;continue}const t=Number.parseInt(i);if(Number.isNaN(t)){r=!0;continue}n+=t;const s=e.alleles[t];s&&o.push(s.allele)}let i=!1;r||(i=0==n);const a=o.join(t);for(let t=1;t<e.alleles.length;t++){const n=e.alleles[t].sampledata[e.alleles[t].sampledata.length-1];n.GT=s,n.genotype=a,i&&(n.gtallref=!0),n.__gtalleles=o}continue}const a=n.format?n.format[o]:null;if(!a){for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][o]=s;continue}const l="Integer"==a.Type,c="Float"==a.Type;if(a.Number&&"R"==a.Number||"AD"==o){const t=s.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n]){const r=e.alleles[n],i=r.sampledata[r.sampledata.length-1];i[o]={},i[o][r.ref]=t[0],i[o][r.allele]=t[n]}}else if(a.Number&&"A"==a.Number){const t=s.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n-1]){const r=e.alleles[n],i=r.sampledata[r.sampledata.length-1];i[o]={},i[o][r.allele]=t[n-1]}}else for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][o]=s}}for(const t of e.alleles)for(const e of t.sampledata)if(e.AD){e.allele2readcount={};for(const t in e.AD)e.allele2readcount[t]=e.AD[t]}}(n,u,e),u.alleles.shift();const d="."==n[7]?[]:(0,o.w)(n[7]);let p=[];e.info?p=function(t,e,n){const r=[];for(const o in t){if(null==n.info[o]){r.push(o);continue}const i=t[o];if("CSQ"==o){(0,s.A)(i,n.info.CSQ.csqheader,e)||(e.info[o]=i);continue}if("ANN"==o){a(i,n.info.ANN.annheader,e)||(e.info[o]=i);continue}if("Flag"==n.info[o].Type){e.info[o]=o;continue}const l=n.info[o].Number,c="Integer"==n.info[o].Type,u="Float"==n.info[o].Type;if("0"==l){e.info[o]=o;continue}if("A"==l){const t=i.split(",");for(let n=0;n<t.length;n++)e.alleles[n]&&(e.alleles[n].info[o]=c?Number.parseInt(t[n]):u?Number.parseFloat(t[n]):t[n]);continue}if("1"==l){e.info[o]=c?Number.parseInt(i):u?Number.parseFloat(i):i;continue}if(!i.split)continue;const f=i.split(",");e.info[o]=c?f.map(Number.parseInt):u?f.map(Number.parseFloat):f}return r}(d,u,e):u.info=d;const m=[];for(const t of u.alleles){const e={};for(const t in u)"alleles"!=t&&(e[t]=u[t]);for(const n in t)"allele"==n?e.alt=t[n]:"info"==n?e.altinfo=t[n]:e[n]=t[n];e.issymbolicallele||"NON_REF"==e.alt||(e.type=(0,l.P)(e.ref,e.alt)),m.push(e)}return[p.length?"unknown info keys: "+p.join(","):null,m,f.length>0?f:null]}function h(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substr(0,e.length-1),n=n.substr(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substr(1),n=n.substr(1),t++;return[t,e,n]}function p(t,e){const n={},r=[];let o=0,s=!1,a=null;for(let e=0;e<t.length;e++)if('"'!=t[e])"="!=t[e]?","!=t[e]||(s?s=!1:a?(n[a]=t.substring(o,e),a=null):r.push("k undefined"),o=e+1):(a=t.substring(o,e),o=e+1);else{e++;const o=e;for(;'"'!=t[e];)e++;a?(n[a]=t.substring(o,e),a=null):r.push("k undefined before double quotes"),s=!0}return a&&(n[a]=t.substring(o,i)),n.ID?(e[n.ID]=n,r.length?r.join("\n"):void 0):"no ID"}},736:(t,e,n)=>{"use strict";n.d(e,{P:()=>o});var r=n(2273);function o(t,e){return 1==t.length&&1==e.length?"."==e?r.mclassdeletion:r.mclasssnv:t.length==e.length?r.mclassmnv:t.length<e.length?r.mclassinsertion:t.length>e.length?r.mclassdeletion:r.mclassnonstandard}},7011:(t,e,n)=>{"use strict";n.d(e,{I:()=>o});const{bin:r}=n(9060);function o(t,e){const n=function(t,e){const n=r().domain(t.domain()).thresholds(t.ticks(15)).value((t=>t));return n(e)}(t,e.values),o=[];for(const t of n){const e={x0:t.x0,x1:t.x1,binValueCount:t.length};delete t.x0,delete t.x1,o.push(e)}const i=o[o.length-1].x1,s={x0:i,x1:i,binValueCount:0};return o.push(s),{bins0:n,bins:o}}},141:(t,e,n)=>{"use strict";n.d(e,{l2:()=>yo,LJ:()=>vo,g_:()=>fo,U_:()=>lo,lE:()=>ni,SC:()=>No,OG:()=>_o});var r=n(334),o=n.n(r);const i=require("express");var s=n.n(i),a=n(6464);const l=require("url");var c=n.n(l);const u=require("http");var f=n.n(u);const d=require("https");var h=n.n(d),p=n(7147),m=n.n(p),g=n(1017),y=n.n(g),v=n(6452),b=n.n(v);const w=require("lazy");var _=n.n(w);const x=require("compression");var k=n.n(x),q=n(2081),N=n.n(q),S=n(6718),A=n(1881);const M=require("body-parser");var T=n.n(M),C=n(7219),j=n.n(C),E=n(4521),O=n.n(E),I=n(9344),R=n.n(I),P=n(3345),F=n(2273),D=n(6819),L=n(8064),$=n(5494),Z=n(6733),z=n(5558),U=n(3602),B=n(6279),G=n(8423),J=n(8235),W=n(5026);function H(t){delete t.mclasslabel2key,delete t.sample2disease,delete t.patient2ori2sample}var V=n(4766);const Y=require("express-basic-auth");var K=n.n(Y),X=n(2826),Q=n(1271),tt=n(1495);async function et(t,e,n,r,o,i,s,a){const l=nt().height(t.query.barheight).min(r).max(o),c=e.width/(e.stop-e.start);await P.UE({args:[i,e.chr+":"+e.start+"-"+e.stop],dir:s,callback:i=>{const s=i.split("\t"),u=Number.parseInt(s[1]);if(Number.isNaN(u))return;const f=Number.parseInt(s[2]);if(Number.isNaN(f))return;const d=Number.parseFloat(s[3]);if(Number.isNaN(d))return;a.fillStyle=d>0?t.query.pcolor:t.query.ncolor;const h=l(d),p=n+(Math.max(u,e.start)-e.start)*c,m=n+(Math.min(f,e.stop)-e.start)*c,g=Math.max(1,m-p);a.fillRect(p,h.y,g,h.h),d>o?(a.fillStyle=t.query.pcolor2,a.fillRect(p,0,g,2)):d<r&&(a.fillStyle=t.query.ncolor2,a.fillRect(p,t.query.barheight-2,g,2))}})}function nt(){var t=50,e=0,n=100;function r(r){var o,i=!1,s=0;return 0==e&&0==n||e<=0&&n>=0&&(i=!0,s=t*n/(n-e)),i?r>=n?{y:0,h:s}:r>=0?{y:s-(o=s*r/n),h:o}:r<=e?{y:s,h:t-s}:{y:s,h:o=(t-s)*r/e}:r<=e?{y:t,h:0}:{y:t-(o=t*(r-e)/(n-e)),h:o}}return r.height=function(e){return t=e,r},r.min=function(t){return e=t,r},r.max=function(t){return n=t,r},r}function rt(t,e,n){return new Promise(((r,i)=>{const s=(0,q.spawn)(o().bigwigsummary,["-udcDir="+o().cachedir,n,e.chr,e.start,e.stop,Math.ceil(e.width*(t.query.dotplotfactor||1))]),a=[],l=[];s.stdout.on("data",(t=>a.push(t))),s.stderr.on("data",(t=>l.push(t))),s.on("close",(t=>{const e=l.join("");e.length?e.startsWith("no data")?r():i("Cannot read bigWig file"):r(a.join(""))}))}))}function ot(t,e,n,r,o){const[i,s]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const o=new Map,i=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let s=r;for(const t of i)o.set(t,s+n/2),s+=n;return[n,o]}(t,n),a=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?a.set(r,(t.stop-r)/e):a.set(r,(r-t.start)/e)}let l=0;for(const t of e)l=Math.max(l,(s.get(t.stop)-s.get(t.start))/2);const c=r+l+i/2,u=(0,S.createCanvas)(t.width*o,c*o),f=u.getContext("2d");o>1&&f.scale(o,o),f.strokeStyle="black";for(const t of n)f.beginPath(),f.moveTo(a.get(t),0),f.lineTo(s.get(t),r),f.closePath(),f.stroke();for(const t of e){const e=s.get(t.start),n=s.get(t.stop),o=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(o,a-i/2),f.lineTo(o-i/2,a),f.lineTo(o,a+i/2),f.lineTo(o+i/2,a),f.lineTo(o,a-i/2),f.closePath(),f.fill()}return{height:c,src:u.toDataURL()}}var it=n(938);async function st(t,e,n){const r={rglst:[]};let o=0,i=0;if(t.autoscale){for(const r of t.rglst){const s=(n?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;await P.UE({args:[t.file,s],dir:e,callback:t=>{const[e,n,r,s]=t.split("\t");for(const t of s.split(",")){const e=Number(t);o=Math.min(o,e),i=Math.max(i,e)}}})}r.minv=o,r.maxv=i}else o=t.minv,i=t.maxv;const s=app.makeyscale().height(t.barheight).min(o).max(i);for(const a of t.rglst){const l={chr:a.chr,start:a.start,stop:a.stop,width:a.width,reverse:a.reverse,xoff:a.xoff},c=(0,S.createCanvas)(a.width,t.barheight),u=c.getContext("2d"),f=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await P.UE({args:[t.file,f],dir:e,callback:e=>{const[n,r,l,c]=e.split("\t"),f=Math.max(Number.parseInt(r),a.start),d=Math.min(Number.parseInt(l),a.stop),h=(a.reverse?a.stop-d:f-a.start)*a.width/(a.stop-a.start),p=(a.reverse?a.stop-f:d-a.start)*a.width/(a.stop-a.start);for(const e of c.split(",")){const n=Number(e);u.fillStyle=n>0?t.pcolor:t.ncolor;const r=s(n),a=Math.max(1,p-h);u.fillRect(h,r.y,a,2),n>i?(u.fillStyle=req.query.pcolor2,u.fillRect(h,0,a,2)):n<o&&(u.fillStyle=req.query.ncolor2,u.fillRect(h,t.barheight-2,a,2))}}}),l.img=c.toDataURL(),r.rglst.push(l)}return r}var at=n(2781);const lt="all",ct="support_ref",ut="support_alt",ft="support_no",dt="support_amb",ht="support_sv";function pt(t){const e={};if(t.variant)if(t.grouptype)e[t.grouptype]={partstack:t.partstack};else{e[ct]={},e[ft]={},e[dt]={};for(let n=0;n<t.variant.length;n++)e[ut+n.toString()]={}}else{if(!t.sv)throw"q.variant or q.sv missing";t.grouptype?e[t.grouptype]={partstack:t.partstack}:(e[ht]={},e[ct]={})}for(const n in e){const r=e[n];r.type=n,r.templates=[],r.regions=mt(t.regions),r.messages=[]}return e}function mt(t){return t.map((t=>({x:t.x,scale:t.scale,ntwidth:t.ntwidth})))}const gt=require("crypto");var yt=n.n(gt),vt=n(490);require("jstat"),o().features,o().clustalo;function bt(t){return t>1e9?(t/1e9).toFixed(2)+" GB":t>1e6?(t/1e6).toFixed(2)+" MB":t>1e3?(t/1e3).toFixed(2)+" KB":t+" Bytes"}const wt=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",_t={end_point:y().join(wt,"files/"),fields:["id","file_size","experimental_strategy","cases.submitter_id","associated_entities.entity_submitter_id","associated_entities.case_id","cases.samples.sample_type","analysis.workflow_type"],size:100},xt={end_point:y().join(wt,"cases/"),fields:["case_id"]},kt="STAR 2-Pass Transcriptome";async function qt(t,e,n){if(await Nt(t,"cases.case_id",n))return e.is_case_uuid=!0,await St(t,"cases.case_id",n);if(await Nt(t,"cases.submitter_id",n))return e.is_case_id=!0,await St(t,"cases.submitter_id",n);const r=await At(t,"file_id",n);if(r.data.hits.length)return e.is_file_uuid=!0,r;const o=await At(t,"file_name",n);return o.data.hits.length&&(e.is_file_id=!0),o}async function Nt(t,e,n){const r={op:"and",content:[{op:"in",content:{field:e,value:t}}]};n&&r.content.push(n);return(await Mt(r,xt)).data.hits.length>0}async function St(t,e,n,r){const o={op:"and",content:[{op:"=",content:{field:"data_category",value:"Sequencing Reads"}},{op:"=",content:{field:"index_files.data_format",value:"bai"}},{op:"=",content:{field:"data_type",value:"Aligned Reads"}},{op:"=",content:{field:"data_format",value:"bam"}}]};return t&&e&&o.content.push({op:"in",content:{field:e,value:t}}),n&&o.content.push(n),await Mt(o,_t,r)}async function At(t,e,n){const r={op:"and",content:[{op:"in",content:{field:e,value:t}}]};return n&&r.content.push(n),await Mt(r,_t)}async function Mt(t,e,n){const r={filters:t,size:n||10,fields:e.fields.join(",")},o=await b()(e.end_point,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});let i;try{i=JSON.parse(o.body)}catch(t){throw"invalid JSON from "+e.end_point}if(!i.data||!i.data.hits)throw"data structure not data.hits[]";return i}async function Tt(t,e,n){const r={Range:"bytes=0-0"};n?r.Cookie=`sessionid=${n}`:r["X-Auth-Token"]=e;const o=wt+"/data/"+t;try{const t=await b()(o,{headers:r,decompress:!1});if(!(t.statusCode>=200&&t.statusCode<400))throw console.log(`gdcCheckPermission() error for got(${o})`,t),"Invalid status code: "+t.statusCode}catch(t){throw console.log("gdcCheckPermission error: ",(null==t?void 0:t.code)||t),"Permission denied"}}const Ct=1e3;const jt=o().clustalo,Et=(0,a.promisify)(at.pipeline),Ot="rgb(120,120,120)",It="rgb(230,230,230)",Rt=(0,vt.ZP)(It,Ot),Pt="#d48b37",Ft=(0,vt.ZP)("#dbc6ad",Pt),Dt="#3B7A57",Lt=(0,vt.ZP)("#E5FFCC",Dt),$t="#d13232",Zt="#ffdbdd",zt=(0,vt.ZP)(Zt,$t),Ut="#4888bf",Bt="#c9e6ff",Gt=(0,vt.ZP)(Bt,Ut),Jt="#6B4423",Wt=(0,vt.ZP)("#987654",Jt),Ht="#fc6df3",Vt=(0,vt.ZP)("#dea4da",Ht),Yt="#47FFFC",Kt="#B2D7D7",Xt=(0,vt.ZP)(Kt,Yt),Qt=12,te=7,ee="black",ne="#ededed",re="blue",oe="#e0e0e0",ie="#FF0000",se="#6cc24a",ae="#ffff00",le="#DEB887",ce="#CD853F",ue="#9a92ec",fe="#47C8FF",de=1,he=1,pe=.4,me=.9,ge=7,ye=7,ve=10,be=7,we=40,_e=.5,xe=2,ke=5,qe=7e3,Ne=1500,Se=2e3,Ae=7,Me=200,Te=20,Ce=(new Set(["A","T","C","G"]),process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov"),je=Math.random.toString();async function Ee(t,e,n,r,o){const i=t.diff_score_plotwidth/(r-o),s=r*i-o*i,a=(0,S.createCanvas)(s*t.devicePixelRatio,e.canvasheight*t.devicePixelRatio),l=a.getContext("2d");t.devicePixelRatio>1&&l.scale(t.devicePixelRatio,t.devicePixelRatio);const c=n.map((t=>t.__tempscore)),u=e.canvasheight/c.length;let f=0;const d=e.stackspace/e.canvasheight;for(const t of c){let e=0;for(const n of t)"alt0"==n?l.fillStyle=ie:"ref"==n?l.fillStyle=fe:"alt1"==n?l.fillStyle=se:"alt2"==n?l.fillStyle=ae:"alt3"==n?l.fillStyle=le:"alt4"==n?l.fillStyle=ce:"alt5"==n&&(l.fillStyle=ue),l.fillRect(i*e,f*u,i,u-d*u),e+=1;f+=1}return{height:e.canvasheight,width:s,src:a.toDataURL(),read_height:u}}function Oe(t,e,n,r){for(const o of n)for(const n of o.segments)if(!(n.ridx!=t||Math.max(n.segstart,e.start)>Math.min(n.segstop,e.stop)))for(const t of n.boxes)if(e.ntwidth>=1){if(("S"==t.opr||"X"==t.opr)&&t.s)for(let e=0;e<t.s.length;e++){const n=t.start+e,o=r.find((t=>t.position==n));if(!o)continue;const i=t.s[e];o[i]=1+(o[i]||0),"S"==t.opr&&o.total++}}else if("S"==t.opr){const n=Math.floor((t.start-e.start)*e.ntwidth),o=Math.floor((t.start+t.len-e.start)*e.ntwidth);for(let t=n;t<=o;t++){const e=r[t];e&&(e.softclip=1+(e.softclip||0),e.total++)}}}async function Ie(t,e){if(!await P.yE(e))return;if(!t.query.gdcFilePosition)throw".gdcFilePosition missing";const n=t.query.regions,r=t.query.gdcFilePosition.split(".");t.query.regions=[{chr:r[0],start:Number(r[1]),stop:Number(r[2])}],await en(t),t.query.regions=n}async function Re(t,e,n,r,o){const i=t.map((t=>t.segments[0].seq)),s=t.map((t=>t.segments[0].qual));let a="",l="";o&&(a+=">seq\n"+o.replace("\n","")+"\n");let c=0;for(const t of i){if(!(c<Me))break;a+=">seq\n"+t.replace("\n","")+"\n",l+=Je(s[c].replace("\n",""))+"\n",c+=1}return await function(t,e,n,r,o,i,s,a){return new Promise(((n,l)=>{const c=(0,q.spawn)(jt,["-i","-","-t","DNA","--outfmt=clu","--wrap=5000","--maxnumseq="+(e+1),"--maxseqlen=1000"]),u=[],f=[];at.Readable.from(t).pipe(c.stdin),c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("error",(t=>{console.log("stderr (clustalo):",f),l(t)})),c.on("close",(t=>{let e=0;const c=[],f={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const t of u.toString().split("\n"))if(t.includes("seq ")){let n=0,l="",u=0,h="";0!=e&&a?h=r.split("\n")[e-1].split(","):a||(h=r.split("\n")[e].split(","));let p="",m="",g="";for(const r of t.replace("seq ",""))if(","!=r){if("-"!=r){if(n+=1,l+=r,0==e&&a)c.push(r);else if(r==c[u]&&a||!a){const t=Rt(h[n-1]/we).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}else if(r!=c[u]&&a){const t=zt(h[n-1]/we).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}}else n>0&&n<t.replace(/-/g,"").replace(/,/g,"").replace("seq ","").length?(l+=r,0==e&&(c.push(r),u<o&&(d+=1))):(l+=" ",0==e&&c.push(r)),p+="255,",m+="255,",g+="255,";u+=1}e+=1,f.gaps_before_variant=d,f.read_count=a?e-1:e,f.qual_r.push(p),f.qual_g.push(m),f.qual_b.push(g),f.final_read_align.push(l),0!=i&&0!=s&&(f.partstack_start=i,f.partstack_stop=s)}else(t.includes("FATAL:")||t.includes("ERROR:"))&&(console.log(t),l(t));n(f)}))}))}(a,Me,i.length,l,e,n,r,o)}async function Pe(t,e){let n=0;for(const r of e){const e=["view","-c",t.file];t.gdc_case_id||e.push((t.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop),await P.UE({isbam:!0,args:e,dir:t.dir,callback:t=>{const e=Number(t);if(!Number.isInteger(e))throw"total number of reads from a region not integer";n+=e}})}if(n<1.1*qe)return;const r=(n-qe)/(.1*qe);t.downsample={keep:10,skip:Math.floor(r),pointer:0},t.read_limit_reached=n}async function Fe(t,e){t.lines=[];const n=["view",e.file];e.gdc_case_id||n.push((e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop),await P.UE({isbam:!0,args:n,dir:e.dir,callback:(n,r)=>{if(!(1024&n.split("\t")[1]&&e.drop_pcrduplicates)){if(e.downsample){const t=e.downsample;if(t.pointer++,t.pointer>=t.keep&&t.pointer<t.keep+t.skip)return;t.pointer>=t.keep+t.skip&&(t.pointer=0)}t.lines.push(n)}}})}async function De(t,e){const n=[],r=["depth","-r",(t.nochr?e.chr.replace("chr",""):e.chr)+":"+(e.start+1)+"-"+e.stop,"-g","DUP",t.file||t.url];if(t.drop_pcrduplicates&&(r.push("-G"),r.push("0x400")),await P.UE({isbam:!0,args:r,dir:t.dir,callback:t=>{const r=t.split("\t"),o=Number.parseInt(r[1])-1,i=Number.parseInt(r[2]);if(e.ntwidth>=1)return void n.push({position:o,total:i});const s=Math.floor((o-e.start)*e.ntwidth);n[s]||(n[s]={position:o,sum:0,count:0}),n[s].sum+=i,n[s].count++}}),e.ntwidth<1)for(const t of n)t&&(t.total=t.sum/t.count,delete t.sum,delete t.count);return n}async function Le(t,e){for(const t of e.regions)t.lines.length>0&&t.ntwidth>=me&&(t.to_checkmismatch=!0,t.referenceseq=await Be(e.genome,t.chr+":"+(t.start+1)+"-"+t.stop));for(const n of t)for(const t of n.segments){const n=e.regions[t.ridx];if(!n.to_checkmismatch)continue;const r=[];for(const e of t.boxes)null!=e.cidx&&"M"==e.opr&&(e.s=t.seq.substr(e.cidx,e.len),He(r,n,e,e.s));r.length&&t.boxes.push(...r)}for(const t of e.regions)delete t.to_checkmismatch,delete t.referenceseq}function $e(t,e){if(!t.asPaired){const n=[];for(let r=0;r<t.regions.length;r++){const o=t.regions[r];for(const i of e.templates){i.ridx=r;const e=Ze(i,o,t);e&&n.push({x1:e.x1,x2:e.x2,__tempscore:e.tempscore,segments:[e]})}}return n}const n=new Map;for(let r=0;r<t.regions.length;r++){const o=t.regions[r];for(const i of e.templates){i.ridx=r;const e=Ze(i,o,t);if(!e||!e.qname)continue;const s=n.get(e.qname);s?(s.segments.push(e),s.x2=Math.max(s.x2,e.x2)):n.set(e.qname,{x1:Math.max(e.x1,o.x),x2:Math.min(e.x2,o.x+o.width),__tempscore:e.tempscore,segments:[e]})}}return[...n.values()]}function Ze(t,e,n){const{sam_info:r,tempscore:o,ridx:i,keepallboxes:s,keepmatepos:a,keepunmappedread:l}=t,c=r.trim().split("\t");if(c.length<11)return;const u=c[0],f=c[1],d=Number.parseInt(c[3]),h=c[5],p=c[6],m=c[7],g=Number.parseInt(c[8]),y=c[9],v=c[10];if(Number.isNaN(d)||d<=0)return;const b=d-1,w={qname:u,segstart:b,segstart_original:b,segstop:b,boxes:[],forward:!(16&f),ridx:i,seq:y,qual:v,cigarstr:h,tlen:g,flag:f,tempscore:o};if(function(t,e,n,r,o,i){const s=t.flag;if(!(1&s))return;64&s?t.isfirst=!0:128&s&&(t.islast=!0);if("="!=e&&"*"!=e&&e!=r.chr)return t.rnext=e,void(t.pnext=n);if(8&s)return void(t.discord_unmapped2=!0);32&s&&!(16&s)&&64&s||16&s&&!(32&s)&&128&s||16&s&&!(32&s)&&64&s||32&s&&!(16&s)&&128&s||(t.discord_orientation=!0,o&&(16&s?32&s?t.discord_orientation_direction="R1R2":n>i&&(t.discord_orientation_direction="R1F2"):32&s?n<i&&(t.discord_orientation_direction="R1F2"):t.discord_orientation_direction="F1F2")),2&s||(t.discord_wrong_insertsize=!0,o&&(t.pnext=n))}(w,p,m,e,a,d),4&f)return l?(w.boxes.push({opr:h,start:b,len:y.length,cidx:0,qual:v}),w.discord_unmapped1=!0,w):void 0;if("*"!=h){let t=b,r=0,o=0;for(let n=0;n<h.length;n++){const i=h[n];if(i.match(/[0-9]/))continue;const a=Number.parseInt(h.substring(r,n));if("H"!=i)if("N"==i||"P"==i||"D"==i||(o+=a),r=n+1,"="!=i&&"M"!=i)if("I"!=i)if("N"!=i&&"D"!=i)if("X"!=i)if("S"!=i){if("P"!=i)console.log("unknown cigar: "+i);else if(s||t>e.start&&t<e.stop){const e={opr:"P",start:t,len:a,cidx:o-a};w.boxes.push(e)}}else{const n={opr:i,start:t,len:a,cidx:o-a};0==w.boxes.length?(n.start-=a,(s||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push(n)):w.boxes.push(n)}else{if(s||Math.max(t,e.start)<Math.min(t+a-1,e.stop)){const e={opr:i,start:t,len:a,cidx:o-a};w.boxes.push(e)}t+=a}else(t>=e.start&&t<=e.stop||t+a-1>=e.start&&t+a-1<=e.stop||s)&&w.boxes.push({opr:i,start:t,len:a}),t+=a;else(s||t>e.start&&t<e.stop)&&a*e.ntwidth>=de&&w.boxes.push({opr:"I",start:t,len:a,cidx:o-a});else(s||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push({opr:i,start:t,len:a,cidx:o-a}),t+=a;else w.boxes.push({opr:i,start:t,len:a,cidx:o-a}),r=n+1}if(0==w.boxes.length)return void(n&&n.readcount_skipped++);w.segstop=t,w.x1=e.x+e.scale(w.boxes[0].start),w.x2=e.x+e.scale((_=w.boxes,Math.max(..._.map((t=>t.start+t.len)))))}var _;return w}async function ze(t,e,n){const[r,o]=function(t,e){let n=(e.groups.length>1?Ne/2:Ne)/t;return n>10?[Math.min(15,Math.floor(n)),1]:n>7?[Math.floor(n),1]:n>3?[Math.ceil(n),0]:n>1?[Math.floor(n),0]:[n,0]}(t.stacks.length,e);t.stackheight=r,t.stackspace=o;for(const e of t.regions)e.to_printnt=t.stackheight>7&&e.ntwidth>=7,e.to_qual=e.ntwidth>=he;if(t.stacks.length&&(t.stackheight>=Ae&&n.length<Se?t.returntemplatebox=[]:t.partstack||(t.allowpartstack=!0)),t.stackheight>=ge){let e=0;for(const t of n)for(const n of t.segments)e=Math.max(e,n.x2-n.x1);e>.7*t.stackheight&&(t.canClipArrowhead=!0)}}function Ue(t,e,n){if(e.asPaired){t.stacks=[];const r=[],o=[];for(const t of n){let n=t.segments[0].ridx;1==t.segments.length||2==t.segments.length&&t.segments[0].ridx==t.segments[1].ridx?(t.x1=Math.max(e.regions[n].x,t.x1),t.x2=Math.min(e.regions[n].x+e.regions[n].width,t.x2),r.push(t)):2==t.segments.length&&t.segments[0].ridx!=t.segments[1].ridx&&(t.x1=t.x1,t.x2=t.x2,o.push(t))}if(r.sort(((t,e)=>t.x1-e.x1)),o.sort(((t,e)=>t.x1-e.x1)),o.length>0){const t=[],e=[],i=o[0];for(const n of r)n.x1<i.x1&&n.x2<i.x1?t.push(n):e.push(n);n=[...t,...o,...e]}for(const r of n){let n=r.segments[0].ridx,o=null;if(!e.variant)for(let i=0;i<t.stacks.length;i++){if(r.x2==e.regions[n].x+e.regions[n].width&&t.stacks[i]<r.x1){o=i,t.stacks[i]=r.x2;break}if(t.stacks[i]+e.stacksegspacing<r.x1){o=i,t.stacks[i]=r.x2;break}}null==o&&(o=t.stacks.length,t.stacks[o]=r.x2),r.y=o}}else{n.sort(((t,e)=>t.x1-e.x1)),t.stacks=[];for(let r=0;r<e.regions.length;r++)for(const o of n)if(o.segments[0].ridx==r){let n=null;if(!e.variant&&!e.sv)for(let i=0;i<t.stacks.length;i++)if(t.stacks[i]+e.stacksegspacing<o.x1&&t.stacks[i]+e.stacksegspacing<e.regions[r].x+e.regions[r].width){n=i,t.stacks[i]=o.x2;break}null==n&&(n=t.stacks.length,t.stacks[n]=o.x2),o.y=n}}return n=function(t,e,n){if(!t.partstack)return e;const r=e.filter((e=>e.y>=t.partstack.start&&e.y<=t.partstack.stop));r.forEach((e=>e.y-=t.partstack.start)),e=r,t.stacks=[];for(let e=t.partstack.start;e<=t.partstack.stop;e++)t.stacks.push(0);return t.returntemplatebox=[],e}(t,n),n}async function Be(t,e){const n=(await P.Kf(t,e)).split("\n");return n.shift(),n.join("").toUpperCase()}function Ge(t,e,n){const r=function(t,e,n){const r=[];for(let e=0;e<t.stacks.length;e++)r.push(t.stackheight);if(function(t,e){if(!e.asPaired)return;for(const e of t.regions)if(e.ntwidth<=pe)return;t.overlapRP_multirows=!0,t.overlapRP_hlline=t.stackspace>0}(t,n),t.overlapRP_multirows)for(const n of e)n.segments.length<=1||n.segments[0].ridx!=n.segments[1].ridx||(n.height=We(n,t.stackheight),r[n.y]=Math.max(r[n.y],n.height));const o=[];let i=t.stackspace;for(const e of r)o.push(i),i+=e+t.stackspace;return t.canvasheight=i,o}(t,e,n);for(const n of e){n.y=r[n.y];for(const e of n.segments){const n=t.regions[e.ridx].to_qual?Je(e.qual):null;for(const t of e.boxes)null!=t.cidx&&"H"!=t.opr&&(n&&(t.qual=n.slice(t.cidx,t.cidx+t.len)),"I"==t.opr?t.s=e.seq.substr(t.cidx,t.len):"X"!=t.opr&&"S"!=t.opr||(t.s=e.seq.substr(t.cidx,t.len)),delete t.cidx);delete e.seq,delete e.qual}}}function Je(t){if("*"==t)return null;const e=[];for(let n=0;n<t.length;n++){const r=t[n].charCodeAt(0)-33;e.push(r)}return e}function We(t,e){if(2==t.segments.length){const[n,r]=t.segments;return n.x2>r.x1?(r.shiftdownrow=1,2*e):e}console.log("more than 2 segments",t.segments.length);const n=[];for(const e of t.segments){let t=null;for(let r=0;r<n.length;r++)if(n[r]<e.x1){t=r,n[r]=e.x2;break}null==t&&(t=n.length,n[t]=e.x2),e.shiftdownrow=t}return e*n.length}function He(t,e,n,r){for(let o=0;o<r.length;o++){if(n.start+o<e.start||n.start+o>e.stop)continue;const i=r[o];if(e.referenceseq[n.start+o-e.start]!=i.toUpperCase()){const e={opr:"X",start:n.start+o,len:1,s:i,cidx:n.cidx+o};t.push(e)}}}function Ve(t,e,n,r){if(n.returntemplatebox){const t=n.regions[e.segments[0].ridx];let o;if(t.width=n.widths[e.segments[0].ridx],r.asPaired)if(2==e.segments.length)o=e.segments[0].ridx!=e.segments[1].ridx?{qname:e.segments[0].qname,x1:e.x1,x2:e.x2,y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop))),multi_region:!0}:{qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))};else{const t=e.segments[0],r=n.regions[t.ridx];r.width=n.widths[t.ridx],o={qname:e.segments[0].qname,x1:Math.max(r.x,e.x1),x2:Math.min(e.x2,r.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))}}else o={qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.x+t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))},e.segments[0].isfirst&&(o.isfirst=!0),e.segments[0].islast&&(o.islast=!0);n.returntemplatebox.push(o)}for(let o=0;o<e.segments.length;o++){const i=e.segments[o],s=n.regions[i.ridx];if(s.width=n.widths[i.ridx],0==o){Ye(t,i,e.y,n,r);continue}const a=e.segments[o-1],l=n.regions[a.ridx];if(l.width=n.widths[a.ridx],a.x2<=i.x1||e.segments[0].ridx!=e.segments[1].ridx){Ye(t,i,e.y,n,r);const o=Math.floor(e.y+n.stackheight/2)+.5;if(t.strokeStyle=n.stackheight<=2?ne:Ot,t.setLineDash([5,3]),t.beginPath(),l.x==s.x?(t.moveTo(a.x2,o),t.lineTo(i.x1,o)):l.x<a.x2&&i.x1<s.width&&(t.moveTo(Math.min(a.x2,l.width),o),t.lineTo(Math.max(i.x1,s.x),o)),t.stroke(),n.overlapRP_hlline){const r=a.boxes.reduce(((t,e)=>t.start+t.len>e.start+e.len?t:e));if(r.start+r.len==i.boxes[0].start){t.strokeStyle=re,t.setLineDash([]),t.beginPath();const r=Math.floor(i.x1)+.5;t.moveTo(r,e.y),t.lineTo(r,e.y+n.stackheight),t.stroke()}}}else if(n.overlapRP_multirows){if(Ye(t,i,e.y+n.stackheight,n,r),n.overlapRP_hlline){const r=Math.floor(e.y+n.stackheight)+.5;t.strokeStyle=re,t.setLineDash([]),t.beginPath(),l.x<=a.x2&&i.x1<=s.width&&(t.moveTo(Math.max(i.x1,s.x),r),t.lineTo(Math.min(a.x2,l.width),r)),t.stroke()}}else Ye(t,i,e.y,n,r)}null!=e.__tempscore&&o().features.indel_read_alignment_scores&&(t.fillStyle="blue",t.font=n.stackheight+"pt Arial",t.fillText(e.__tempscore,r.regions[0].width-100,e.y+n.stackheight/2))}function Ye(t,e,n,r,o){const i=r.regions[e.ridx];i.width=r.widths[e.ridx];for(const o of e.boxes){const s=i.x+i.scale(o.start);if("P"!=o.opr&&"H"!=o.opr&&"I"!=o.opr)if("D"!=o.opr&&"N"!=o.opr)if("*"!=o.opr){if("X"!=o.opr&&"S"!=o.opr){if("M"!=o.opr&&"="!=o.opr)throw"unknown opr at rendering: "+o.opr;if(i.to_qual&&o.qual){let a=s;o.qual.forEach((o=>{e.rnext?t.fillStyle=Ft(o/we):e.discord_orientation?t.fillStyle=Vt(o/we):e.discord_wrong_insertsize?t.fillStyle=Lt(o/we):e.discord_unmapped2?t.fillStyle=Wt(o/we):t.fillStyle=Rt(o/we),a+i.ntwidth+_e<i.width&&i.x<=a?t.fillRect(a,n,i.ntwidth+_e,r.stackheight):a<i.width&&a+i.ntwidth+_e>=i.width&&i.x<=a?t.fillRect(a,n,i.width-a,r.stackheight):a<=i.x&&a+i.ntwidth+_e>i.x&&t.fillRect(i.x,n,i.ntwidth+_e+a-i.x,r.stackheight),a+=i.ntwidth}))}else o.qual?e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Ht:e.discord_wrong_insertsize?t.fillStyle=Dt:e.discord_unmapped2?t.fillStyle=Jt:t.fillStyle=Ot:i.to_printnt?t.fillStyle="white":e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Ht:e.discord_wrong_insertsize?t.fillStyle=Dt:e.discord_unmapped2?t.fillStyle=Jt:t.fillStyle=Ot,s+o.len*i.ntwidth+_e<i.width&&s<i.width&&i.x<s+_e?t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight):s+o.len*i.ntwidth+_e<i.width&&i.x>=s?t.fillRect(i.x,n,o.len*i.ntwidth+_e+s-i.x,r.stackheight):s+o.len*i.ntwidth+_e>=i.width&&i.x<s?t.fillRect(s,n,i.width-s,r.stackheight):s+o.len*i.ntwidth+_e>=i.width&&i.x>=s&&t.fillRect(i.x,n,i.width-s,r.stackheight);if(i.to_printnt){t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial",o.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<o.s.length;e++)s+i.ntwidth*(e+.5)<i.width&&s<i.width&&i.x<=s+i.ntwidth*(e+.5)&&t.fillText(o.s[e],s+i.ntwidth*(e+.5),n+r.stackheight/2)}}else if(i.to_qual&&o.qual){i.to_printnt&&(t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial");let e=s;for(let s=0;s<o.qual.length;s++){const a=o.qual[s]/we;t.fillStyle="S"==o.opr?Gt(a):zt(a),e+i.ntwidth+_e<i.x+i.width&&i.x<=e?t.fillRect(e,n,i.ntwidth+_e,r.stackheight):e<i.x+i.width&&e+i.ntwidth+_e>=i.x+i.width&&i.x<=e?t.fillRect(e,n,i.width+i.x-e,r.stackheight):e<=i.x&&e+i.ntwidth+_e>i.x&&t.fillRect(i.x,n,i.ntwidth+_e+e-i.x,r.stackheight),i.to_printnt&&(o.qual?t.fillStyle="white":t.fillStyle="black",e+i.ntwidth/2<i.width&&e<i.width&&i.x<=e+i.ntwidth/2&&t.fillText(o.s[s],e+i.ntwidth/2,n+r.stackheight/2)),e+=i.ntwidth}}else if(t.fillStyle="S"==o.opr?Ut:$t,s+o.len*i.ntwidth+_e<i.width&&i.x<s?t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight):s+o.len*i.ntwidth+_e<i.width&&i.x>=s?t.fillRect(i.x,n,o.len*i.ntwidth+_e+s-i.x,r.stackheight):s+o.len*i.ntwidth+_e<=i.width&&i.x<s&&t.fillRect(s,n,i.width-s,r.stackheight),i.to_printnt&&!o.qual){t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial",o.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<o.s.length;e++)s+i.ntwidth*(e+.5)<i.width&&s<i.width&&i.x<=s+i.ntwidth*(e+.5)&&t.fillText(o.s[e],s+i.ntwidth*(e+.5),n+r.stackheight/2)}}else{if(i.to_qual&&o.qual){let a=s;o.qual.forEach((o=>{e.discord_unmapped2&&(t.fillStyle=Wt(o/we)),t.fillRect(a,n,i.ntwidth+_e,r.stackheight),a+=i.ntwidth}))}else e.discord_unmapped2&&(t.fillStyle=Jt),t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight);i.to_printnt&&(t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial")}else{"D"==o.opr?t.strokeStyle=ee:t.strokeStyle=r.stackheight<=2?ne:Ot,t.setLineDash([]);const e=Math.floor(n+r.stackheight/2)+.5;if(t.beginPath(),t.moveTo(Math.max(s,i.x),e),t.lineTo(Math.min(s+o.len*i.ntwidth,i.x+i.width),e),t.stroke(),r.stackheight>ye){const e=Math.max(i.x,s),a=Math.min(i.x+i.width,s+o.len*i.ntwidth);if(a-e>=50){const s=Math.min(ve,Math.max(be,r.stackheight-2));t.font=s+"pt Arial";const l=t.measureText(o.len+" bp").width;l<a-e-20&&(t.fillStyle="white",(a+e)/2+l/2<i.width&&i.x<(a+e)/2-l/2?(t.fillRect((a+e)/2-l/2,n,l,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2<i.width&&i.x>=(a+e)/2-l/2?(t.fillRect(i.x,n,l+(a+e)/2-l/2-i.x,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2>=i.width&&i.x<(a+e)/2-l/2&&(t.fillRect((a+e)/2-l/2,n,i.width-(a+e)/2+l/2,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)))}}}}!function(t,e,n,r,o){if(!n.canClipArrowhead)return;if(e.x2-e.x1<5)return;if(e.forward){const i=Math.ceil(e.x2+_e);i<=r.width+n.stackheight/2&&(t.fillStyle="white",t.beginPath(),t.moveTo(i-n.stackheight/2,o),t.lineTo(i,o),t.lineTo(i,o+n.stackheight/2),t.lineTo(i-n.stackheight/2,o),t.closePath(),t.fill(),t.beginPath(),t.moveTo(i-n.stackheight/2,o+n.stackheight),t.lineTo(i,o+n.stackheight),t.lineTo(i,o+n.stackheight/2),t.lineTo(i-n.stackheight/2,o+n.stackheight),t.closePath(),t.fill())}else{const i=e.x1;i>=r.x&&(t.fillStyle="white",t.beginPath(),t.moveTo(i+n.stackheight/2,o),t.lineTo(i,o),t.lineTo(i,o+n.stackheight/2),t.lineTo(i+n.stackheight/2,o),t.closePath(),t.fill(),t.beginPath(),t.moveTo(i+n.stackheight/2,o+n.stackheight),t.lineTo(i,o+n.stackheight),t.lineTo(i,o+n.stackheight/2),t.lineTo(i+n.stackheight/2,o+n.stackheight),t.closePath(),t.fill())}}(t,e,r,i,n),e.rnext&&(i.to_qual||e.x2-e.x1>=20&&r.stackheight>=7&&(t.font=Math.min(Qt,Math.max(te,r.stackheight-4))+"pt Arial",t.fillStyle="white",t.fillText((o.nochr?"chr":"")+e.rnext,(e.x1+e.x2)/2,n+r.stackheight/2,e.x2-e.x1)))}function Ke(t,e,n,r){for(const[t,n]of e.regions.entries()){if(!n.to_printnt)continue;const e=new Set;for(const o of r)for(const r of o.segments){if(r.ridx!=t)continue;const o=r.boxes.filter((t=>"I"==t.opr));if(o.length)for(const t of o)e.add(n.x+n.scale(t.start))}}for(const n of r)for(const r of n.segments){const o=e.regions[r.ridx],i=r.boxes.filter((t=>"I"==t.opr));if(i.length){t.font=Math.max(Qt,e.stackheight-2)+"pt Arial";for(const s of i){const i=o.x+o.scale(s.start);s.qual?t.fillStyle=Xt(s.qual.reduce(((t,e)=>t+e),0)/s.qual.length/we):t.fillStyle=Yt;const a=1==s.s.length?s.s:s.s.length;t.fillText(a,i,n.y+e.stackheight*(r.on2ndrow||0)+e.stackheight/2)}}}}async function Xe(t,e,n){const r=Je(t.qual),o=['<td style="color:black;text-align:left">Read</td>'];for(const e of t.boxes)for(let n=0;n<e.len;n++){t.seq[e.cidx+n];o.push('<td style="background:'+Rt(r[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>")}const i=[];i.push('<li><span style="background:'+Jt+';color:white">This segment in template is unmapped</span></li>'),1&t.flag&&i.push("<li>Template has multiple segments</li>"),2&t.flag&&i.push("<li>Each segment properly aligned</li>"),16&t.flag&&i.push("<li>Reverse complemented</li>"),32&t.flag&&i.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&i.push("<li>This is the first segment in the template</li>"),128&t.flag&&i.push("<li>This is the last segment in the template</li>"),256&t.flag&&i.push("<li>Secondary alignment</li>"),512&t.flag&&i.push("<li>Not passing filters</li>"),1024&t.flag&&i.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&i.push("<li>Supplementary alignment</li>");let s={seq:t.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center">\n\t\t\t <tr style="color:white">${o.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE</span>: ${Math.abs(t.seq.length)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${i.join("")}</ul>`};return t.discord_unmapped2&&(s.unmapped_mate=!0),s}async function Qe(t,e,n){const r=t.boxes[0].start,o=t.boxes[t.boxes.length-1],i=o.start+o.len,s=await Be(e,n.chr+":"+(r+1)+"-"+i),a=Je(t.qual),l=["<td>Reference</td>"],c=['<td style="color:black;text-align:left">Read</td>'];for(const e of t.boxes)if("H"!=e.opr)if("I"!=e.opr)if("D"!=e.opr&&"N"!=e.opr)if("S"!=e.opr)if("M"!=e.opr&&"="!=e.opr&&"X"!=e.opr&&"*"!=e.opr);else for(let n=0;n<e.len;n++){const o=s[e.start-r+n],i=t.seq[e.cidx+n];l.push("<td>"+o+"</td>"),"*"==t.qual?c.push('<td style="color:black;background:'+(o.toUpperCase()==i.toUpperCase()?Rt:zt)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+(o.toUpperCase()==i.toUpperCase()?Rt:zt)(a[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>")}else for(let n=0;n<e.len;n++)l.push("<td>"+s[e.start-r+n]+"</td>"),"*"==t.qual?c.push('<td style="background:'+Gt(1)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+Gt(a[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>");else if(e.len>=Te)l.push('<td style="font-size:.8em;opacity:.5;white-space:nowrap">'+e.len+" bp</td>"),c.push('<td style="color:black;white-space:nowrap">-----------</td>');else for(let t=0;t<e.len;t++)l.push("<td>"+s[e.start-r+t]+"</td>"),c.push('<td style="color:black">-</td>');else for(let n=e.cidx;n<e.cidx+e.len;n++)l.push("<td>-</td>"),"*"==t.qual?c.push('<td style="color:'+Yt+';background:white">'+t.seq[n]+"</td>"):c.push('<td style="color:'+Yt+";background:"+Rt(a[n]/we)+'">'+t.seq[n]+"</td>");let u=0,f=0,d=[],h=[],p=0;for(const e of t.boxes)u=f,f+=e.len,"S"==e.opr&&(p=1,d.push(u),h.push(f));const m=[];t.rnext&&m.push('<li>Next segment on <span style="background:'+Pt+'">'+(n.nochr?"chr":"")+t.rnext+", "+t.pnext+"</span></li>"),t.discord_wrong_insertsize&&t.discord_orientation?m.push('<li><span style="background:'+Dt+';color:white">Wrong insert size</span> mate position: '+t.pnext+'</li><li><span style="background:'+Ht+';color:white">Segments also having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_wrong_insertsize?m.push('<li><span style="background:'+Dt+';color:white">Wrong insert size</span> mate position: '+t.pnext+"</li>"):t.discord_orientation?m.push('<li><span style="background:'+Ht+';color:white">Segments having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_unmapped2&&m.push('<li><span style="background:'+Jt+';color:white">Other segment in template is unmapped</span></li>'),1&t.flag&&m.push("<li>Template has multiple segments</li>"),2&t.flag&&m.push("<li>Each segment properly aligned</li>"),16&t.flag&&m.push("<li>Reverse complemented</li>"),32&t.flag&&m.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&m.push("<li>This is the first segment in the template</li>"),128&t.flag&&m.push("<li>This is the last segment in the template</li>"),256&t.flag&&m.push("<li>Secondary alignment</li>"),512&t.flag&&m.push("<li>Not passing filters</li>"),1024&t.flag&&m.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&m.push("<li>Supplementary alignment</li>");let g={seq:t.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center;font-family:courier">\n\t\t\t <tr style="opacity:.6">${l.join("")}</tr>\n\t\t\t <tr style="color:white">${c.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">CHR</span>: ${n.chr.replace("chr","")},\n\t\t\t<span style="opacity:.5;font-size:.7em">START</span>: ${t.segstart_original+1},\n\t\t\t<span style="opacity:.5;font-size:.7em">STOP</span>: ${i},\n\t\t\t<span style="opacity:.5;font-size:.7em">READ LENGTH</span>: ${t.seq.length} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE LENGTH</span>: ${Math.abs(t.tlen)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${m.join("")}</ul>`,start_readpos:r+1,boxes:t.boxes,readpanel_DN_maxlength:Te};return 1==p&&(g.soft_starts=d,g.soft_stops=h),t.discord_unmapped2&&(g.unmapped_mate=!0),g}function tn(t){const e=yt().createHmac("md5",je),n=[t.get("X-Auth-Token")||t.cookies.sessionid,t.query.gdcFileUUID,t.query.gdcFilePosition];return e.update(n.join("")).digest("hex")+".bam"}async function en(t){const e=t.query.regions;if(!Array.isArray(e)||0==e.length)throw"req.query.regions[] not non-empty array";const n=[];for(const r of e){const e=await nn(r.chr,r.start,r.stop,t.get("X-Auth-Token"),t.query.gdcFileUUID,tn(t),t.cookies.sessionid);n.push({filesize:e})}return n}async function nn(t,e,n,r,i,s,a){const l={compression:!1};a?l.Cookie=`sessionid=${a}`:l["X-Auth-Token"]=r;const c=y().join(o().cachedir_bam,s),u=Ce+"/slicing/view/"+i+"?region="+t+":"+e+"-"+n;try{if(await P.yE(c)&&(await Et(b().stream(u,{method:"GET",headers:l}),m().createWriteStream(c)),await P.yE(c)))throw"BAM file slice is not found after downloading";const t=c+".bai";if(await P.yE(t)&&(await async function(t){await P.UE({isbam:!0,args:["index",t],callback:()=>{}})}(c),await P.yE(t)))throw"index file is missing after indexing";const e=await m().promises.stat(c);return(0,F.bplen)(e.size,!0)}catch(t){throw t.stack&&console.log(t.stack),"Error with BAM slicing: "+(t.message||t)}}const rn="Unannotated";function on(t){return t.file?t.file:t.file2?t.file2:t.url}function sn(t,e,n,r){const o=[];for(const i of t.samples)if(Number.isFinite(i.readcount)&&(i.readcount=Math.floor(i.readcount),!(i.readcount<=0||e.readcountCutoff&&i.readcount<e.readcountCutoff))){if(r.samples&&n.cohort&&n.cohort.annotation){const t=r.samples[i.i];if(!t)continue;const o=n.cohort.annotation[t];if(i.anno=o,e.cohortOnlyAttr&&n.cohort&&n.cohort.annotation){if(!o)continue;let t=!1;for(const n in e.cohortOnlyAttr){const r=o[n];if(r&&e.cohortOnlyAttr[n][r]){t=!0;break}}if(!t)continue}if(e.cohortHiddenAttr&&n.cohort&&n.cohort.annotation&&n.cohort.attributes){if(!o)continue;let t=!1;for(const r in e.cohortHiddenAttr){n.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const i=o[r];if(i){if(e.cohortHiddenAttr[r][i]){t=!0;break}}else if(e.cohortHiddenAttr[r][rn]){t=!0;break}}if(t)continue}}if(i.events&&e.spliceEventPercentage){let n=!1;for(const r in i.events){if(!t.events[r])continue;const o=t.events[r].attrValue,s=e.spliceEventPercentage[o];if(!s)continue;const a=i.events[r].percentage;if(null!=a)if(">"==s.side){if(a<=s.value){n=!0;break}}else if(a>=s.value){n=!0;break}}if(n)continue}o.push(i)}return o}function an(t,...e){if(0==t.length)return 0;const n=t.sort(((t,e)=>t.readcount-e.readcount)),r=[];return e.forEach((t=>{!Number.isFinite(t)||t<0||t>1?r.push(null):r.push(n[Math.floor(n.length*t)].readcount)})),r}var ln=n(1169);function cn(t){return new Promise(((e,n)=>{const r=O().createInterface({input:m().createReadStream(t.file,{encoding:"utf8"})}),o=[];let i=!0;r.on("line",(e=>{if(i)return void(i=!1);const n=e.split("\t"),[s,a,l,c,u,f]=n[0].split(/[:,]/);if(s!=t.chr)return;const d=Number.parseInt(a),h=Number.parseInt(u);if(Number.isNaN(d)||Number.isNaN(h))return;const p=d-1,m=h-1;if(p>t.start&&p<t.stop||m>t.start&&m<t.stop){const t=Number.parseInt(n[1]),e=n[2];o.push({chr:s,start:p,stop:m,type:e,rawdata:[t]})}else p>t.stop&&r.close()})),r.on("close",(()=>{e(o)}))}))}const un=new Set(["-1","0","1","2"]);function fn(t,e){t[0];const n=Number(t[1]),r=(t[2],t[3].split(".")[0]),o=t[5];if("+"!=o&&"-"!=o)return{name:r};const i="+"==o,s=Number(t[6]),a=Number(t[7]);if(!Number.isInteger(s)||!Number.isInteger(a))return{name:r,strand:o};const l=[],c=[],u=[],f=[],d=[],h=t[15],p=t[17],m=t[20];if(!t[10].includes(",")||!t[11].includes(","))return{name:r,strand:o};const g=t[10].split(",");g.pop();const y=g.map(Number),v=t[11].split(",");v.pop();const b=v.map(Number);if(y.includes(NaN)||b.includes(NaN))return{name:r,strand:o};let w=null,_=0,x=0;for(const[t,e]of y.entries()){_+=e;const r=n+b[t],o=r+e;i?d.push([r,o]):d.unshift([r,o]),t>0&&(i?f.push([w,r]):f.unshift([w,r])),w=o,r<s?o<s?i?c.push([r,o]):l.unshift([r,o]):(i?c.push([r,s]):l.unshift([r,s]),o>a?(s<a&&(i?u.push([s,a]):u.unshift([s,a]),x+=a-s),i?l.push([a,o]):c.unshift([a,o])):s<o&&(i?u.push([s,o]):u.unshift([s,o]),x+=o-s)):r<a?o<=a?r<o&&(i?u.push([r,o]):u.unshift([r,o]),x+=o-r):(r<a&&(i?u.push([r,a]):u.unshift([r,a]),x+=a-r),i?l.push([a,o]):c.unshift([a,o])):i?l.push([r,o]):c.unshift([r,o])}const k={name:p,isoform:r,strand:o,exon:d,rnalen:_};26==t.length&&(k.category=m),e&&e.has(r)&&(k.description=e.get(r)),f.length>0&&(k.intron=f),s==a||(k.cdslen=x,k.codingstart=s,k.codingstop=a,k.coding=u,c.length&&(k.utr5=c),l.length&&(k.utr3=l));const q=h.split(",");return q.pop(),q.length<1||q.some((t=>!un.has(t)))||function(t,e){if(!t.codingstart)return;const n="+"==t.strand?t.codingstart:t.codingstop;let r=t.exon.findIndex((t=>t[1]>=n&&t[0]<=n));if(-1==r)throw"start codon not matched to an exon: "+JSON.stringify(t);"-"==t.strand&&(r=t.exon.length-r-1);const o=e.split(",")[r];if("-1"==o)throw"start codon frame is -1: "+t.isoform;if("0"!=o){if("1"!=o&&"2"!=o)throw"start codon frame not 0/1/2: "+o+" "+t.isoform;t.startCodonFrame=Number.parseInt(o)}}(k,h),k}const dn=1,hn=10,pn=400,mn=600,gn=50,yn="rgba(122,103,44,.7)",vn="red",bn="#edad0c",wn="rgba(255,0,0,.5)",_n="#ccc";function xn(t,e,n,r,o){if(!t)return;if(!o.name&&!o.isoform)return;const i=[];o.name&&i.push(o.name),o.isoform&&i.push(o.isoform),t.push({chr:o.chr,start:o.start,stop:o.stop,x1:e,x2:n,y:r,isoform:o.isoform,name:i.join(" ")})}function kn(t,e,n,r,o,i){const s=i/2,a=i/2,l=Math.max(i/2,6);if(o-2*s<a)return;const c=Math.ceil((o-2*s)/(a+l));if(c<=0)return;const u="+"==e;let f=Math.ceil(n+(o-a*c-l*(c-1))/2);for(let e=0;e<c;e++)t.beginPath(),u?(t.moveTo(f,r),t.lineTo(f+a,r+i/2),t.moveTo(f+a,r+i/2+1),t.lineTo(f,r+i)):(t.moveTo(f+a,r),t.lineTo(f,r+i/2),t.moveTo(f,r+i/2+1),t.lineTo(f+a,r+i)),t.stroke(),f+=a+l}function qn(t,e){return new Promise(((n,r)=>{const i=(0,q.spawn)(o().gfServer,["status",e.blat.host,e.blat.port]),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(e=>{a.join("").trim()&&n(t+" OFF");const r=s.join("").trim().split("\n");let o=0;for(const t of r)t.startsWith("blat requests")&&(o=t.split(" ")[2]);n(t+" ON, "+o+" requests")}))}))}function Nn(t,e){const n=y().join(o().cachedir,Math.random().toString());return new Promise(((r,i)=>{const s=(0,q.spawn)(o().gfClient,[t.blat.host,t.blat.port,t.blat.seqDir,e,n,"-q=dna","-nohead","-minScore=20","-minIdentity=0","-out=psl"]),a=[];s.stderr.on("data",(t=>a.push(t))),s.on("close",(t=>{const e=a.join("");e&&(console.log("BLAT error",e),i("blat server problem")),r(n)}))}))}var Sn=n(9064),An=n(1575);const Mn=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",Tn=Mn+(Mn.includes("/v0")?"":"/v0")+"/graphql",Cn="https://uat-api.gdc.cancer.gov",jn=y().join(Mn,"ssm_occurrences/_mapping"),En="ssm_occurrence_centrics";async function On(t){const e=new Map,n=await b()(jn,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid JSON from GDC dictionary"}if(!r._mapping)throw"returned data does not have ._mapping";if(!Array.isArray(r.fields))throw".fields not array";if(!Array.isArray(r.nested))throw".nested not array";const i=new Set(r.nested);let s=0,a=0,l=0,c=0,u=0,f=0;for(const t of r.fields){if(Dn(t)){s++;continue}const n=t.split(".");for(let t=1;t<n.length;t++){const o=n.slice(0,t).join("."),s=o+"."+n[t],f=n[t][0].toUpperCase()+n[t].slice(1).replace(/_/g," "),d={id:s.toLowerCase(),name:f,included_types_set:new Set,child_types_set:new Set};if(t==n.length-1){d.isleaf=!0;const t=r._mapping[En+"."+s];t&&("keyword"==t.type?(d.type="categorical",l++):"long"==t.type?(d.type="integer",c++):"double"==t.type?(d.type="float",u++):console.log("GDC !!! ERR !!! Unknown variable type: "+t.type)),d.type||a++,In(d)}if(1==t);else if(d.parent_id=o,d.type){d.included_types_set.add(d.type);let t=e.get(o);for(;t&&(t.included_types_set.add(d.type),t.child_types_set.add(d.type),t.parent_id);)t=e.get(t.parent_id)}i.has(s)&&(d.isObjectList=!0),e.set(s,d)}}await async function(t){const e=[],n=new Map;for(const r of t.values()){if("integer"!=r.type&&"float"!=r.type)continue;if(Pn[r.id]){r.bins=Pn[r.id];continue}const t=r.id.replace("case.","").replace(/\./g,"__");n.set(t,r.id),e.push(t+" {\n\t\t stats {\n\t\t\t\tMin : min\n\t\t\t\tMax: max\n\t\t\t\tMean: avg\n\t\t\t\tSD: std_deviation\n\t\t\t\tcount\n\t\t\t}\n\t\t\trange(ranges: $filters2) {\n\t\t\t buckets {\n\t\t\t\tdoc_count\n\t\t\t\tkey\n\t\t\t }\n\t\t\t}\n\t\t}")}if(0==e.length)throw"GDC: no numeric terms";const r=`\n\t query ContinuousAggregationQuery($caseFilters: FiltersArgument, $filters: FiltersArgument, $filters2: FiltersArgument) {\n\t viewer {\n\t\texplore {\n\t\t cases {\n\t\t\taggregations(case_filters: $caseFilters, filters: $filters) {\n\t\t\t\t${e.join("\n")}\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}`,o={caseFilters:{},filters:{},filters2:{op:"range",content:[{ranges:[{from:0,to:1}]}]}};try{var i,s,a,l;let e=0,c=0;const u=await b().post(Tn,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:r,variables:o})}),f=JSON.parse(u.body);if("object"!=typeof(null===(i=f.data)||void 0===i||null===(s=i.viewer)||void 0===s||null===(a=s.explore)||void 0===a||null===(l=a.cases)||void 0===l?void 0:l.aggregations))throw"return not object: re.data.viewer.explore.cases.aggregations{}";for(const[r,o]of n){const n=t.get(o);if(!(r in f.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",o),n.bins=Rn,c++;continue}const i=f.data.viewer.explore.cases.aggregations[r].stats;if("object"!=typeof i){console.log("GDC: aggregations[facet].stats{} is not object"),n.bins=Rn,c++;continue}if(!Number.isFinite(i.Max)||!Number.isFinite(i.Min)){n.bins=Rn,c++;continue}if(i.Max<=i.Min){n.bins=Rn,c++;continue}const s=(i.Max-i.Min)/5,a="integer"==n.type?Math.ceil(s):s;n.bins={default:{mode:"discrete",type:"regular-bin",bin_size:a,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:i.Min+a}}},e++}console.log(`GDC default binning: ${e} assigned, ${c} unassigned`)}catch(t){console.log(t.message||t)}}(e);for(const t of e.values())t.type||f++,t.included_types=[...t.included_types_set],t.child_types=[...t.child_types_set],delete t.included_types_set,delete t.child_types_set;console.log("GDC dictionary:",e.size,"total variables,",s,"lines skipped,",a,"lines with unknown term type,","categorical="+l,"integer="+c,"float="+u,"parent="+f),Object.freeze(e),function(t,e){const n=t.cohort.termdb.q={};async function r(e,n){if(0==e.length||!n)return;const r=await t.termdb.termid2totalsize2.get(e.map((t=>t.id)),JSON.parse(n));for(const t of e)if(t){const e=r.get(t.id);"categorical"==t.type&&e?e.length?t.samplecount=e.map((t=>t[1])).reduce(((t,e)=>t+e)):(t.disabled=!0,t.samplecount=0):"integer"!=t.type&&"float"!=t.type||(t.samplecount=e.total,0==e.total&&(t.disabled=!0))}}n.getRootTerms=async(t,n=null)=>{const o=[];for(const t of e.values())null==t.parent_id&&o.push(JSON.parse(JSON.stringify(t)));return await r(o,n),o},n.getTermChildren=async(t,n=null,o=null)=>{const i=[];for(const n of e.values())n.parent_id==t&&i.push(JSON.parse(JSON.stringify(n)));return await r(i,o),i},n.findTermByName=async(t,n=null,o,i=null,s=null)=>{(t=t.toLowerCase()).includes(" ")&&(t=t.replace(/\s/g,"_"));const a=[];for(const n of e.values())s&&!(0,An.CG)(n,s)||n.id.includes(t)&&a.push(JSON.parse(JSON.stringify(n)));return await r(a,i),a},n.getAncestorIDs=t=>{if(!e.has(t))return;const n=t.split("."),r=[];for(let t=1;t<n.length;t++)r.push(n.slice(0,t+1).join("."));return r},n.getAncestorNames=n.getAncestorIDs,n.termjsonByOneid=t=>{const n=e.get(t);return n?JSON.parse(JSON.stringify(n)):null},n.getSupportedChartTypes=()=>{const t={},n={};for(const r of e.values())r.type&&(r.cohort in t||(t[r.cohort]=["barchart","table","regression"],n[r.cohort]=0),"survival"!=r.type||t[r.cohort].includes("survival")||t[r.cohort].push("survival"),"condition"!=r.type||t[r.cohort].includes("cuminc")||t[r.cohort].push("cuminc"),"float"!=r.type&&"integer"!=r.type||(n[r.cohort]+=r.samplecount));for(const e in n)n[e]>0&&t[e].push("boxplot"),n[e]>1&&t[e].push("scatterplot");return t}}(t,e),t.cohort.termdb.termtypeByCohort=[],l&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),c&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"integer"}),u&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"float"}),t.__gdc={aliquot2submitter:{cache:new Map,get:async e=>t.__gdc.aliquot2submitter.cache.has(e)?t.__gdc.aliquot2submitter.cache.get(e):e},map2caseid:{cache:new Map,get:e=>t.__gdc.map2caseid.cache.get(e)},caseid2submitter:new Map,caseIds:new Set,casesWithExpData:new Set,gdcOpenProjects:new Set,doneCaching:0},await async function(t){var e,n,r;const o={"Content-Type":"application/json",Accept:"application/json"},i={filters:{op:"and",content:[{op:"=",content:{field:"access",value:"open"}},{op:"=",content:{field:"data_type",value:"Masked Somatic Mutation"}}]},facets:"cases.project.project_id",size:0},s=await b()(y().join(Mn,"files"),{method:"POST",headers:o,body:JSON.stringify(i)}),a=JSON.parse(s.body);if(!Array.isArray(null==a||null===(e=a.data)||void 0===e||null===(n=e.aggregations)||void 0===n||null===(r=n["cases.project.project_id"])||void 0===r?void 0:r.buckets))return void console.log("getting open project_id but return is not re.data.aggregations['cases.project.project_id'].buckets[]");for(const e of a.data.aggregations["cases.project.project_id"].buckets)e.key&&t.__gdc.gdcOpenProjects.add(e.key);console.log("GDC open-access projects:",t.__gdc.gdcOpenProjects.size)}(t),async function(){try{{const t=y().join(Mn,"ssms"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"ssm_occurrences"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"cases"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"files"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"analysis/top_mutated_genes_by_project"),e=await Ln(t);if(e)throw`${t}: ${e}`}await async function(t){const e=new Date;try{const e="query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\tprimary_site {buckets { doc_count, key }}\n\t\t\t\t}\n\t\t\t}\n\t\t}}";await b().post(t,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:e,variables:{}})})}catch(e){throw"gdc api down: "+t}console.log("GDC GraphQL API okay: "+t,new Date-e,"ms")}(Tn)}catch(t){console.error(`\n##########################################\n#\n# GDC API unavailable\n# ${Mn}\n# ${Tn}\n#\n##########################################`)}}(),async function(t){if("stopGdcCacheAliquot"in o().features){if(!Number.isInteger(o().features.stopGdcCacheAliquot))return void console.log("GDC: sample IDs are not cached!");console.log("GDC: running limited sample ID caching")}else console.log("GDC: caching complete sample ID mapping");try{const e=await $n(t,1,0);if(!Number.isInteger(e))throw"gdc totalCases not integer";const n=new Date;console.log("GDC: Start to cache sample IDs of",e,"cases...");const r=1e3;for(let n=0;n<Math.ceil(e/r)&&(await $n(t,r,1e3*n),!(Number.isInteger(o().features.stopGdcCacheAliquot)&&n>=o().features.stopGdcCacheAliquot));n++);await async function(t){const e=`${Cn}/gene_expression/availability`;{const t=await Ln(e);if("ERR_NON_2XX_3XX_RESPONSE"==t);else if(t)return}try{var n;const r=[...t.__gdc.caseIds],o=await b().post(e,{headers:{"Content-Type":"application/json"},body:JSON.stringify({case_ids:r,gene_ids:["ENSG00000141510"]})}),i=JSON.parse(o.body);if(!Array.isArray(null===(n=i.cases)||void 0===n?void 0:n.details))throw"re.cases.details[] not array";for(const e of i.cases.details)e.has_gene_expression_values&&t.__gdc.casesWithExpData.add(e.case_id);delete t.__gdc.caseIds}catch(t){throw t}}(t),t.__gdc.doneCaching=!0,console.log("GDC: Done caching sample IDs. Time:",Math.ceil((new Date-n)/1e3),"s"),console.log("\t",t.__gdc.aliquot2submitter.cache.size,"aliquot IDs to sample submitter id,"),console.log("\t",t.__gdc.caseid2submitter.size,"case uuid to submitter id,"),console.log("\t",t.__gdc.map2caseid.cache.size,"different ids to case uuid,"),console.log("\t",t.__gdc.casesWithExpData.size,"cases with gene expression data.")}catch(t){console.log("Error at caching: "+t)}}(t)}function In(t){"case.diagnoses.age_at_diagnosis"!=t.id||(t.valueConversion={scaleFactor:1/365,fromUnit:"day",toUnit:"year"})}const Rn={default:{mode:"discrete",type:"regular-bin",bin_size:1,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:0},last_bin:{start:1,stopunbounded:!0}}},Pn={"case.diagnoses.age_at_diagnosis":{default:{type:"custom-bin",mode:"discrete",lst:[{startunbounded:!0,stop:10950,stopinclusive:!0,label:"<=30 years"},{start:10950,stop:21900,stopinclusive:!0,label:"30-60 years"},{start:21900,stopunbounded:!0,startinclusive:!1,label:">60years"}]}}};const Fn=new Set(["case.consent_type","case.days_to_consent","case.days_to_index"]);function Dn(t){return!!(t.startsWith("ssm")||t.startsWith("case.observation")||t.startsWith("case.available_variation_data"))||(!(!t.endsWith("_id")||t.endsWith("project_id"))||(!!Fn.has(t)||void 0))}async function Ln(t){try{const e=new Date;await b()(t),console.log("GDC API okay: "+t,new Date-e,"ms")}catch(e){if(e.code)return e.code;throw"gdc api down: "+t}}async function $n(t,e,n,r){var o,i,s;const a=["fields=submitter_id,samples.portions.analytes.aliquots.aliquot_id,samples.submitter_id"];if(r)a.push('filters={"op":"and","content":[{"op":"=","content":{"field":"samples.portions.analytes.aliquots.aliquot_id","value":["'+r+'"]}}]}');else{if(!Number.isInteger(e)||!Number.isInteger(n))throw"size and from not integers";a.push("size="+e),a.push("from="+n)}const l=await b()(Mn+"/cases?"+a.join("&")),c=JSON.parse(l.body);if(!Array.isArray(null==c||null===(o=c.data)||void 0===o?void 0:o.hits))throw"re.data.hits[] not array";for(const e of c.data.hits){const n=e.id;if(!n)throw"h.id (case uuid) missing";t.__gdc.caseIds.add(n);const r=e.submitter_id;if(!r)throw"h.submitter_id missing";if(t.__gdc.caseid2submitter.set(n,r),t.__gdc.map2caseid.cache.set(r,n),Array.isArray(e.samples))for(const r of e.samples){const e=r.submitter_id;if(!e)throw"sample.submitter_id missing";if(t.__gdc.map2caseid.cache.set(e,n),Array.isArray(r.portions))for(const o of r.portions)if(Array.isArray(o.analytes))for(const r of o.analytes)if(Array.isArray(r.aliquots))for(const o of r.aliquots){const r=o.aliquot_id;if(!r)throw"aliquot.aliquot_id missing";t.__gdc.aliquot2submitter.cache.set(r,e),t.__gdc.map2caseid.cache.set(r,n)}}}return null===(i=c.data)||void 0===i||null===(s=i.pagination)||void 0===s?void 0:s.total}var Zn=n(4973),zn=n(3625),Un=n(478),Bn=n(8907),Gn=n(394);function Jn(t,e){if(e.updateAttr&&!t.label){for(const n of e.updateAttr){let e=t;for(const t of n)if(e)if("object"==typeof t)for(const n in t)e[n]=t[n];else e=e[t]}t.label&&delete e.updateAttr}}function Wn(t,e,n){var r,i;if(null===(r=t.cohort)||void 0===r||null===(i=r.db)||void 0===i||!i.refresh)return;const s=t.cohort.db.refresh;delete t.cohort.db.refresh,e.get(`${n}/${s.route}`,(async(e,n)=>{n.send({label:t.label,files:[]})})),e.post(`${n}/${s.route}`,(async(e,n)=>{try{var r,i;const s=null!==(r=t.cohort.db)&&void 0!==r&&null!==(i=r.file)&&void 0!==i&&i.startsWith(o().tpmasterdir)?t.cohort.db.file:y().join(o().tpmasterdir,t.cohort.db.file||""),a=e.body;if(!a.dbfile)throw"Updating input text files via the termdb-refresh page has been deprecated.Please use the buildTermdb.bundle.js. pipeline before triggering this route to replace the db file.";{const e=y().join(o().tpmasterdir,a.dbfile);if(!await m().stat(e))throw`dbfile not found: '${e}'`;const n=t.cohort.db.file_fullpath||s;if(e===n)throw"db file source and target are the same";console.log(`copying ${e} to ${n}`),await m().copyFile(e,n)}await er(t),n.send({status:"ok"})}catch(t){console.log(t),n.send({error:t.error||t})}}))}var Hn=n(2188),Vn=n(2974),Yn=n(3795),Kn=n(7934);const Xn="Unannotated";async function Qn(t,e,n,r=null,i=null){var s,a;await er(t),t.queries&&(await async function(t,e){const n=t.queries.snvindel;if(!n)return;if(n.url){if(!n.url.base)throw".snvindel.url.base missing";if(!n.url.key)throw".snvindel.url.key missing"}if(!n.byisoform&&!n.byrange)throw"byisoform and byrange are both missing on queries.snvindel";if(n.byrange)if(n.byrange.gdcapi)ln.xq(t);else if(n.byrange.bcffile){var r;n.byrange.bcffile=n.byrange.bcffile.startsWith(o().tpmasterdir)?n.byrange.bcffile:y().join(o().tpmasterdir,n.byrange.bcffile),n.byrange._tk={file:n.byrange.bcffile},n.byrange.get=await or(t,e),null!==(r=n.byrange._tk)&&void 0!==r&&r.samples.length||delete n.byrange._tk.samples,rr(t,n.byrange._tk.samples,"snvindel.byrange.bcffile")}else{if(!n.byrange.chr2bcffile)throw"unknown query method for queries.snvindel.byrange";n.byrange._tk={chr2files:{}};for(const t in n.byrange.chr2bcffile)n.byrange._tk.chr2files[t]={file:y().join(o().tpmasterdir,n.byrange.chr2bcffile[t])};delete n.byrange.chr2bcffile,n.byrange.get=await or(t,e),n.byrange._tk.samples.length||delete n.byrange._tk.samples,rr(t,n.byrange._tk.samples,"snvindel.byrange.bcffile")}if(n.byisoform){if(!n.byisoform.gdcapi)throw"unknown query method for queries.snvindel.byisoform";ln.CN(t)}if(n.m2csq){if(!n.m2csq.by)throw".by missing from queries.snvindel.m2csq";if("ssm_id"!=n.m2csq.by)throw"unknown value of queries.snvindel.m2csq.by";if(!n.m2csq.gdcapi)throw"unknown query method for queries.snvindel.m2csq";ln.wm(t)}}(t,e),await async function(t,e){const n=t.queries.svfusion;if(!n)return;if(!n.byrange)throw"byrange missing from queries.svfusion";if(n.byrange){if(!n.byrange.file)throw"unknown query method for svfusion.byrange";n.byrange.file=n.byrange.file.startsWith(o().tpmasterdir)?n.byrange.file:y().join(o().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.queries.svfusion.byrange;if(n.file)await P.LC(n.file);else{if(!n.url)throw"file and url both missing on svfusion.byrange{}";n.dir=await P.d1(n.url,n.indexURL)}n.nochr=await P.Jy(n.file||n.url,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const r=ir(e),o=await lr(e,n.samples,t);if(0==(null==o?void 0:o.size))return[];const i=new Map;for(const t of e.rglst)await P.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:n=>{const s=n.split("\t"),a=Number(s[1]);let l,c,u,f,d;try{l=JSON.parse(s[3])}catch(t){return}if(l.dt!=F.dtfusionrna&&l.dt!=F.dtsv)return;if(l.class=l.dt==F.dtsv?F.mclasssv:F.mclassfusionrna,e.hiddenmclass&&e.hiddenmclass.has(l.class))return;if(l.sample&&o&&!o.has(l.sample))return;if(l.chrA)c=1,u=l.geneA||l.chrA,f=l.strandA,d=[{a:{chr:l.chrA,pos:l.posA,strand:l.strandA,name:l.geneA},b:{chr:t.chr,pos:a,strand:l.strandB,name:l.geneB}}];else if(l.chrB)c=0,u=l.geneB||l.chrB,f=l.strandB,d=[{a:{chr:t.chr,pos:a,strand:l.strandA,name:l.geneA},b:{chr:l.chrB,pos:l.posB,strand:l.strandB,name:l.geneB}}];else{if(!l.pairlst)throw"missing chrA and chrB";{d=l.pairlst;const t=l.pairlst.findIndex((t=>t.chr==chr&&t.pos==a));if(-1==t)throw"current point missing from pairlst";c=t}}const h=[l.dt,t.chr,a,f,c,encodeURIComponent(u)].join(Zn.dq);let p;if(l.sample&&(p={sample_id:l.sample},l.mattr)){if(r)for(const t in r){const e=t in l.mattr?l.mattr[t]:Xn;if(r[t].has(e))return}e.addFormatValues&&(p.formatK2v=l.mattr)}i.has(h)||i.set(h,{ssm_id:h,dt:l.dt,class:l.class,chr:t.chr,pos:a,strand:f,pairlstIdx:c,mname:u,pairlst:d,samples:[]}),p&&i.get(h).samples.push(p)}});return[...i.values()]}}(t,e),rr(t,n.byrange.samples,"svfusion.byrange")}}(t,e),await async function(t,e){const n=t.queries.geneCnv;if(!n)return;if(!n.bygene)throw"geneCnv.bygene missing";n.bygene.gdcapi&&ln.IK(t)}(t),await async function(t,e){const n=t.queries.cnv;if(!n)return;if(!n.byrange)throw"byrange missing from queries.cnv";if(n.byrange){if(!n.byrange.file)throw"unknown query method for cnv.byrange";n.byrange.file=n.byrange.file.startsWith(o().tpmasterdir)?n.byrange.file:y().join(o().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.queries.cnv.byrange;if(n.file)await P.LC(n.file);else{if(!n.url)throw"file and url both missing on cnv.byrange{}";n.dir=await P.d1(n.url,n.indexURL)}n.nochr=await P.Jy(n.file||n.url,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";if(e.cnvMaxLength&&!Number.isInteger(e.cnvMaxLength))throw"cnvMaxLength is not integer";if(e.cnvGainCutoff&&!Number.isFinite(e.cnvGainCutoff))throw"cnvGainCutoff is not finite";if(e.cnvLossCutoff&&!Number.isFinite(e.cnvLossCutoff))throw"cnvLossCutoff is not finite";const r=ir(e),o=await lr(e,n.samples,t);if(0==(null==o?void 0:o.size))return[];const i=[],s=[];for(const t of e.rglst)s.push(P.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:n=>{const s=n.split("\t"),a=Number(s[1]),l=Number(s[2]);if(e.cnvMaxLength&&l-a>=e.cnvMaxLength)return;let c;try{c=JSON.parse(s[3])}catch(t){return}if(c.dt==F.dtcnv){if(c.start=a,c.stop=l,Number.isFinite(c.value)){if(c.value>0&&e.cnvGainCutoff&&c.value<e.cnvGainCutoff)return;if(c.value<0&&e.cnvLossCutoff&&c.value>e.cnvLossCutoff)return;c.class=c.value>0?F.mclasscnvgain:F.mclasscnvloss}else if(c.class!=F.mclasscnvgain&&c.class!=F.mclasscnvloss)return;if(c.ssm_id=[t.chr,c.start,c.stop,c.class].join(Zn.dq),(!e.hiddenmclass||!e.hiddenmclass.has(c.class))&&(!c.sample||!o||o.has(c.sample))){if(c.sample){const t={sample_id:c.sample};if(c.mattr){if(r)for(const t in r){const e=t in c.mattr?c.mattr[t]:Xn;if(r[t].has(e))return}e.addFormatValues&&(t.formatK2v=c.mattr)}delete c.sample,c.samples=[t]}i.push(c)}}}}));return await Promise.all(s),i}}(t,e),rr(t,n.byrange.samples,"cnv.byrange")}}(t,e),await async function(t,e){const n=t.queries.ld;if(!n)return;if(!Array.isArray(n.tracks)||!n.tracks.length)throw"ld.tracks[] not nonempty array";for(const t of n.tracks){if(!t.name)throw"name missing from one of ld.tracks[]";if(!t.file)throw".file missing from one of ld.tracks[]";t.file0=t.file,t.file=y().join(o().tpmasterdir,t.file),await P.LC(t.file),t.nochr=await P.Jy(t.file,null,e)}if(!n.overlay)throw"ld.overlay{} missing";if(!n.overlay.color_0)throw"ld.overlay.color_0 missing";if(!n.overlay.color_1)throw"ld.overlay.color_1 missing"}(t,e),await async function(t,e){const n=t.queries.geneExpression;if(!n)return;if(n.gdcapi)return void ln.CL(t,e);if(!n.file)throw".file missing from queries.geneExpression";n.file=y().join(o().tpmasterdir,n.file),await P.LC(n.file),n.nochr=await P.Jy(n.file,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}rr(t,n.samples,"geneExpression"),n.get=async r=>{const o=await lr(r,n.samples,t);if(0==(null==o?void 0:o.size))return new Map;const i=new Map;for(const t of r.genes)if(t.gene||(t.gene=t.name),t.gene){if(!t.chr){const n=e.genedb.getjsonbyname.all(t.gene);if(0==n.length)continue;const r=JSON.parse(n.find((t=>t.isdefault)).genemodel||n[0].genemodel);t.start=r.start,t.stop=r.stop,t.chr=r.chr}i.set(t.gene,{}),await P.UE({args:[n.file,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:e=>{const n=e.split("\t");let r;try{r=JSON.parse(n[3])}catch(t){return}r.gene.toLowerCase()==t.gene.toLowerCase()&&(o&&!o.has(r.sample)||(i.get(t.gene)[r.sample]=r.value))}})}return i}}(t,e),await async function(t,e){const n=t.queries.rnaseqGeneCount;if(!n)return;if(!n.file)throw"unknown data type for rnaseqGeneCount";n.file=y().join(o().tpmasterdir,n.file);{const e=(await(r=n.file,new Promise(((t,e)=>{const n=(0,q.spawn)("head",["-1",r]);n.stdout.on("data",(e=>t(e.toString()))),n.stderr.on("data",(t=>e(t.toString())))})))).trim().split("\t").slice(4);n.allSampleSet=new Set(e),console.log(n.allSampleSet.size,`rnaseqGeneCount samples from ${t.label}`)}var r;n.get=async function(e){var r,i,s,a;if(2!=(null===(r=e.samplelst)||void 0===r||null===(i=r.groups)||void 0===i?void 0:i.length))throw".samplelst.groups.length!=2";if((null===(s=e.samplelst.groups[0].values)||void 0===s?void 0:s.length)<1)throw"samplelst.groups[0].values.length<1";if((null===(a=e.samplelst.groups[1].values)||void 0===a?void 0:a.length)<1)throw"samplelst.groups[1].values.length<1";const l=[];let c=0;for(const r of e.samplelst.groups[0].values){if(!Number.isInteger(r.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(r.sampleId);e&&(n.allSampleSet.has(e)?l.push(e):c+=1)}const u=[];let f=0;for(const r of e.samplelst.groups[1].values){if(!Number.isInteger(r.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(r.sampleId);e&&(n.allSampleSet.has(e)?u.push(e):f+=1)}if(console.log("Sample size of group1:",l.length),console.log("Sample size of group2:",u.length),console.log("Number of group1 names not found:",c),console.log("Number of group2 names not found:",f),l.length<1)throw"group1names.length<1";if(u.length<1)throw"group2names.length<1";const d={case:l.map((t=>t)).join(","),control:u.map((t=>t)).join(","),input_file:n.file,output_path:y().join(o().binpath,"utils")},h=8;let p;if(l.length<=h&&u.length<=h){const t=new Date,e=(await async function(t,e){return new Promise(((n,r)=>{y().join(o().Rscript,t);const i=(0,q.spawn)(o().Rscript,[t]),s=[],a=[];try{at.Readable.from(e).pipe(i.stdin)}catch(e){i.kill();let n=e;a.length&&(n+=`killed edgeR('${t}'), stderr: ${a.join("").trim()}`),r(n)}i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("error",(e=>{a.length&&console.log(`edgeR('${t}') ps.on('error') stderr:`,a),r(e)})),i.on("close",(e=>{0!==e?r(`spawned '${t}' exited with a non-zero status and this stderr:\n${a.join("")}`):n(s.toString())}))}))}(y().join(o().binpath,"utils","edge.R"),JSON.stringify(d)),new Date);console.log("Time taken to run edgeR:",e-t,"ms");const n=y().join(o().binpath,"utils","r_output.txt");p=JSON.parse(m().readFileSync(n,"utf8")),m().unlink(n,(()=>{}))}else{const t=new Date,e=await(0,Q.run_rust)("DEanalysis",JSON.stringify(d)),n=new Date;for(const t of e.split("\n"))t.startsWith("adjusted_p_values:")&&(p=JSON.parse(t.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",n-t,"ms")}return p}}(t),await async function(t,e){const n=t.queries.singleSampleMutation;if(!n)return;if(n.gdcapi)ln.P9(t,e);else{if(!n.folder)throw"unknown query method for singleSampleMutation";n.get=async e=>{var r,i,s;let a=e;if(null!==(r=t.cohort)&&void 0!==r&&null!==(i=r.termdb)&&void 0!==i&&null!==(s=i.q)&&void 0!==s&&s.sampleName2id&&(a=t.cohort.termdb.q.sampleName2id(e),null==a))return[];const l=y().join(o().tpmasterdir,n.folder,a.toString());try{await m().promises.stat(l)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.code)throw"no data for this sample";throw"failed to load data"}const c=await P.b5(l);return{mlst:JSON.parse(c)}}}}(t,e),await async function(t,e){const n=t.queries.singleSampleGenomeQuantification;if(!n)return;for(const r in n){if(!Number.isFinite(n[r].min))throw"min not a number";if(!Number.isFinite(n[r].max))throw"max not a number";if(n[r].min>=n[r].max)throw"min>=max";if(!n[r].folder)throw"unknown query method for singleSampleGenomeQuantification";n[r].get=async(i,s)=>{var a,l,c;let u=i;if(null!==(a=t.cohort)&&void 0!==a&&null!==(l=a.termdb)&&void 0!==l&&null!==(c=l.q)&&void 0!==c&&c.sampleName2id&&(u=t.cohort.termdb.q.sampleName2id(i),null==u))return[];const f=y().join(o().tpmasterdir,n[r].folder,u.toString());try{await m().promises.stat(f)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.code)throw"no data for this sample";throw"failed to load data"}return await dr(f,e,n[r],s)}}}(t,e),await async function(t,e){const n=t.queries.singleSampleGbtk;if(!n)return;for(const e in n){if(!Number.isFinite(n[e].min))throw"min not a number";if(!Number.isFinite(n[e].max))throw"max not a number";if(n[e].min>=n[e].max)throw"min>=max";if(!n[e].folder)throw"unknown query method for singleSampleGbtk";n[e].get=async r=>{var i,s,a;let l=r;if(null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.termdb)&&void 0!==s&&null!==(a=s.q)&&void 0!==a&&a.sampleName2id&&(l=t.cohort.termdb.q.sampleName2id(r),null==l))return{};const c=y().join(n[e].folder,l+".gz");try{return await m().promises.stat(y().join(o().tpmasterdir,c)),{path:c}}catch(t){return{}}}}}(t),await(0,Kn.validate_query_singleCell)(t,e),await(0,Zn.uK)(t),await function(t){if(!t.ssm2canonicalisoform)return;if(t.ssm2canonicalisoform.gdcapi)return void ln.vK(t.ssm2canonicalisoform);throw"ssm2canonicalisoform.gdcapi is false"}(t),await function(t,e){if(!e.genedb.hasTable_refseq2ensembl)return;t.refseq2ensembl_query=e.genedb.db.prepare("select ensembl from refseq2ensembl where refseq=?")}(t,e),await function(t,e){if(!t.queries.snvindel&&!t.queries.svfusion&&!t.queries.geneCnv)return;t.mayGetGeneVariantData=async(n,r)=>{if("object"!=typeof n.term)throw"tw.term{} is not object";if("geneVariant"!=n.term.type)throw"tw.term.type is not geneVariant";if("string"!=typeof n.term.name)throw"tw.term.name is not string";if(!n.term.name)throw"tw.term.name should be gene symbol but is empty string";const o=[];if("snp"==n.term.subtype){var i;if(null===(i=t.queries.snvindel)||void 0===i||!i.allowSNPs)throw"snvindel does not allow snp";const a=(await mr(t,n.term,e,r)).find((t=>n.term.alleles.includes(t.ref)&&n.term.alleles.includes(t.alt)));if(a){const t=[];for(const e of a.samples){var s;if(null===(s=e.formatK2v)||void 0===s||!s.GT)continue;const n=[];for(const t of e.formatK2v.GT.split("/"))0==t?n.push(a.ref):1==t?n.push(a.alt):console.log("unknown allele idx");n.join("/"),n.join("/");t.push({sample_id:e.sample_id,GT:n.join("/")})}const e={samples:t};o.push(e)}}else{if(t.queries.snvindel){const i=await mr(t,n.term,e,r);o.push(...i)}if(t.queries.svfusion){const i=await async function(t,e,n,r){const o={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid};if(t.queries.svfusion.byrange)return await pr(e,n),o.rglst=[e],await t.queries.svfusion.byrange.get(o);throw"unknown queries.svfusion method"}(t,n.term,e,r);o.push(...i)}if(t.queries.cnv){const i=await async function(t,e,n,r){var o,i,s;const a={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,cnvMaxLength:null==e||null===(o=e.q)||void 0===o?void 0:o.cnvMaxLength,cnvGainCutoff:null==e||null===(i=e.q)||void 0===i?void 0:i.cnvGainCutoff,cnvLossCutoff:null==e||null===(s=e.q)||void 0===s?void 0:s.cnvLossCutoff,sessionid:r.sessionid};if(t.queries.cnv.byrange)return await pr(e.term,n),a.rglst=[e.term],await t.queries.cnv.byrange.get(a);throw"unknown queries.cnv method"}(t,n,e,r);o.push(...i)}if(t.queries.geneCnv){const e=await async function(t,e,n,r){const o={filter0:r.filter0,sessionid:r.sessionid};if(t.queries.geneCnv.bygene)return e.name?(o.gene=e.name,await t.queries.geneCnv.bygene.get(o)):[];throw"unknown queries.geneCnv method"}(t,n.term,0,r);o.push(...e)}}const a=new Map;for(const e of o)if(Array.isArray(e.samples))for(const r of e.samples){var l,c;if(a.has(r.sample_id)||a.set(r.sample_id,{sample:r.sample_id}),null!==(l=t.cohort)&&void 0!==l&&null!==(c=l.termdb)&&void 0!==c&&c.additionalSampleAttributes)for(const e of t.cohort.termdb.additionalSampleAttributes)e in r&&(a.get(r.sample_id)[e]=r[e]);a.get(r.sample_id)[n.term.name]||(a.get(r.sample_id)[n.term.name]={key:n.term.name,label:n.term.name,values:[]});const o={gene:n.term.name,isoform:e.isoform,dt:e.dt,chr:n.term.chr,class:e.class,pos:e.pos||(e.start?e.start+"-"+e.stop:""),mname:e.mname,_SAMPLEID_:r.sample_id,_SAMPLENAME_:r.sample_id};if(r.__sampleName&&(o._SAMPLENAME_=r.__sampleName),"value"in e&&(o.value=e.value),r.formatK2v)for(const t in r.formatK2v)o[t]=r.formatK2v[t];e.dt==F.dtsnvindel?r.GT&&(o.value=r.GT,o.key=r.GT):e.dt!=F.dtfusionrna&&e.dt!=F.dtsv||(o.pairlst=e.pairlst),t.cohort.termdb.q.id2sampleName&&Number.isInteger(r.sample_id)&&(o._SAMPLENAME_=t.cohort.termdb.q.id2sampleName(r.sample_id)),a.get(r.sample_id)[n.term.name].values.push(o)}return await async function(t,e,n,r){var o;if(null===(o=e.assayAvailability)||void 0===o||!o.byDt)return;const i=t.filter?new Set((await(0,Bn.cf)(t.filter,e)).map((t=>t.id))):null;for(const t in e.assayAvailability.byDt){const o=e.assayAvailability.byDt[t];if(o.byOrigin)for(const e in o.byOrigin){hr(t,o.byOrigin[e],n,r,e,i)}else hr(t,o,n,r,!1,i)}}(r,t,a,n.term.name),a}}(t,e)),await function(t){if(!t.assayAvailability)return;if(t.assayAvailability.byDt)for(const e in t.assayAvailability.byDt){const n=t.assayAvailability.byDt[e];if(n.byOrigin)for(const e in n.byOrigin){const r=n.byOrigin[e];if(!r.yes||!r.no||!r.term_id)throw"ds.assayAvailability.byDt.*.byOrigin properties require .term_id .yes{} .no{}";gr(t,r)}else{if(!n.yes||!n.no||!n.term_id)throw"ds.assayAvailability.byDt properties require .term_id .yes{} .no{}";gr(t,n)}}}(t),await function(t){if(!t.viewModes)return;if(!Array.isArray(t.viewModes))throw"ds.viewModes[] not array";for(const r of t.viewModes)if(r.byInfo){var e,n;if(null==t||null===(e=t.queries)||void 0===e||null===(n=e.snvindel)||void 0===n||!n.info)throw"view mode byInfo but queries.snvindel.info missing";const o=t.queries.snvindel.info[r.byInfo];if(!o)throw"unknown INFO field for viewmode byInfo";if("Float"!=o.Type&&"Integer"!=o.Type)throw"viewmode byInfo Type is not numeric";r.type="numeric",r.label=r.byInfo}else if(!r.byAttribute)throw"view mode not byInfo or byAttribute"}(t),null!==(s=t.cohort)&&void 0!==s&&null!==(a=s.db)&&void 0!==a&&a.refresh&&r&&await Wn(t,r,i)}function tr(t){var e;const n={isMds3:!0,label:t.label};if(t.viewModes&&(n.skewerModes=t.viewModes),t.noGenomicMode4lollipopTk&&(n.noGenomicMode4lollipopTk=!0),function(t,e){if(!t.queries)return;const n={};t.queries.singleSampleMutation&&(n.singleSampleMutation={sample_id_key:t.queries.singleSampleMutation.sample_id_key,discoSkipChrM:t.queries.singleSampleMutation.discoSkipChrM});if(t.queries.singleSampleGenomeQuantification){n.singleSampleGenomeQuantification={};for(const e in t.queries.singleSampleGenomeQuantification)n.singleSampleGenomeQuantification[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGenomeQuantification[e])),delete n.singleSampleGenomeQuantification[e].folder}if(t.queries.singleSampleGbtk){n.singleSampleGbtk={};for(const e in t.queries.singleSampleGbtk)n.singleSampleGbtk[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGbtk[e])),delete n.singleSampleGbtk[e].folder}const r=t.queries.snvindel;r&&(e.has_skewer=!0,n.snvindel={forTrack:r.forTrack,vcfid4skewerName:r.vcfid4skewerName,variantUrl:r.variantUrl,skewerRim:r.skewerRim},r.m2csq&&(n.snvindel.m2csq={by:r.m2csq.by}),r.info&&(e.bcf={info:r.info}),r.format&&(e.bcf||(e.bcf={}),e.bcf.format=r.format));if(t.queries.ld){n.ld=JSON.parse(JSON.stringify(t.queries.ld));for(const t of n.ld.tracks)delete t.file}e.queries=n}(t,n),null!==(e=t.cohort)&&void 0!==e&&e.termdb&&(n.termdb={},t.cohort.termdb.allowCaseDetails&&(n.termdb.allowCaseDetails={sample_id_key:t.cohort.termdb.allowCaseDetails.sample_id_key})),t.variant2samples){const e=t.variant2samples;n.variant2samples={sunburst_twLst:e.sunburst_twLst,twLst:e.twLst,type_samples:e.type_samples,type_summary:e.type_summary,type_sunburst:e.type_sunburst,variantkey:e.variantkey}}return n}async function er(t){var e,r,i,s;if(t.cohort){if(!t.cohort.termdb)throw"ds.cohort is set but cohort.termdb{} missing";if(!t.cohort.db)throw"ds.cohort is set but cohort.db{} missing";if(!t.cohort.db.file&&!t.cohort.db.file_fullpath)throw"ds.cohort.db.file missing"}else{if(!t.termdb)return;t.cohort={},t.cohort.termdb=t.termdb,delete t.termdb}const a=t.cohort.termdb;if(null!=a&&null!==(e=a.dictionary)&&void 0!==e&&e.gdcapi)await On(t);else if(null!=a&&null!==(r=a.dictionary)&&void 0!==r&&r.dbFile)t.cohort.db={file:a.dictionary.dbFile},delete a.dictionary.dbFile,(0,Gn.JV)(t);else{if(!t.cohort.db)throw"unknown method to initiate dictionary";(0,Gn.JV)(t)}if(a.termid2totalsize2&&(a.termid2totalsize2.gdcapi,a.termid2totalsize2.get=async(e,n={},r=null)=>a.termid2totalsize2.gdcapi?await ln.ws(e,n,r,t):await async function(t,e,n,r){const o=nr(e,r),i=new Map;for(const e of t)if(e.term&&"categorical"==e.term.type){var s,a;const t={term1_id:e.id,term1_q:{type:"values"},filter:o},n=await(0,it.e8)(t,r,r.cohort.termdb);if(null==n||null===(s=n.data)||void 0===s||null===(a=s.charts)||void 0===a||!a[0])continue;const l=[];for(const t of n.data.charts[0].serieses)l.push([t.seriesId,t.total]);i.set(e.id,l)}return n?[i,n]:i}(e,n,r,t)),function(t){const e=t.selectCohort;if(!e)return;if("object"!=typeof e)throw"selectCohort{} not object";if(!e.term)throw"term{} missing from termdb.selectCohort";if(!e.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof e.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=e.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';{const n=t.q.termjsonByOneid(e.term.id);if(!n)throw"termdb.selectCohort.term.id is invalid";if("categorical"!=n.type)throw"termdb.selectCohort.term type is not categorical"}if(!e.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(e.values))throw"termdb.selectCohort.values is not array";if(0==e.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const t of e.values){if(!t.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(t.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==t.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}(a),await async function(t){if(!t.restrictAncestries)return;if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!e.tvs.term)throw"tvs.term{} missing from an ancestry";if(!e.tvs.term.id)throw"tvs.term.id missing from an ancestry";{const n=t.q.termjsonByOneid(e.tvs.term.id);if(!n)throw"tvs.term.id is invalid from an ancestry";if("categorical"!=n.type)throw"tvs.term.type is not categorical from an ancestry"}if(!Number.isInteger(e.PCcount))throw"PCcount is not integer";if(e.PCcount<=1)throw"PCcount must be greater than 1";if(e.PCTermId){e.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const r=e.PCTermId+n,o=t.q.termjsonByOneid(r);if(!o)throw"a PC term is not found in termdb";const i=t.q.getAllValues4term(r);if(!i||!i.size)throw"no sample PC values are retrieved by restrictAncestries term: "+r;e.pcs.set(o.name,i)}}else{if(!e.PCBySubcohort)throw"unknown PC source and configuration for restrictAncestries";for(const n in e.PCBySubcohort){let r=!0;for(const e of t.selectCohort.values)if(n==e.keys.sort().join(",")){r=!1;break}if(r)throw"unknown subcohort from PCBySubcohort";const o=e.PCBySubcohort[n];if(!o.termId)throw"termId missing from a subcohort of PCBySubcohort";o.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const e=o.termId+n,r=t.q.termjsonByOneid(e);if(!r)throw"a PC term is not found in termdb";const i=t.q.getAllValues4term(e);if(!i||!i.size)throw"no sample PC values are retrieved by restrictAncestries.PCBySubcohort.<>.termId";o.pcs.set(r.name,i)}}}}}(a),await(0,Hn.wz)(t),await(0,Vn.te)(t),"minTimeSinceDx"in a){if(!Number.isFinite(a.minTimeSinceDx))throw"termdb.minTimeSinceDx not number";if(a.minTimeSinceDx<=0)throw"termdb.minTimeSinceDx<=0"}if("ageEndOffset"in a){if(!Number.isFinite(a.ageEndOffset))throw"termdb.ageEndOffset not number";if(a.ageEndOffset<=0)throw"termdb.ageEndOffset<=0"}if(t.cohort.termdb.additionalSampleAttributes){if(!Array.isArray(t.cohort.termdb.additionalSampleAttributes))throw"termdb.additionalSampleAttributes not array";for(const e of t.cohort.termdb.additionalSampleAttributes)if("string"!=typeof e)throw"non-str key in termdb.additionalSampleAttributes[]"}if(a.convertSampleId){if(!a.convertSampleId.gdcapi)throw"unknown implementation of tdb.convertSampleId";ln.Ak(a,t)}if(await async function(t){var e;if(null===(e=t.cohort)||void 0===e||!e.cumburden)return;t.cohort.cumburden.files;const n=t.cohort.cumburden.files;for(const t of["fit","surv","sample"]){const e=n[t];if(!e)throw`missing ds.cohort.burden.files.${t}`;const r=(0,q.spawnSync)(o().Rscript,["-e",`load('${o().tpmasterdir}/${e}')`],{encoding:"utf-8"});if(null!=r&&r.status||null!=r&&r.stderr)throw console.log(r),`error with ds.cohort.cumburden.files.${t}`}}(t),null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.db)&&void 0!==s&&s.connection){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[r]=t.sampleId2Name.get(+r);return n}}if(t.cohort.mutationset){const{mayGetGeneVariantData:e,getTermTypes:r,mayGetMatchingGeneNames:o}=n(7833);t.mayGetGeneVariantData=e,t.getTermTypes=r,t.mayGetMatchingGeneNames=o}}function nr(t,e){const n=[];if(t.filterObj&&n.push(t.filterObj),t.tid2value&&n.push(cr(t.tid2value,e)),0!=n.length)return 1==n.length?n[0]:(0,Un.xH)(n)}function rr(t,e,n){var r;if(!e)return;let o;if(null!=t&&null!==(r=t.cohort)&&void 0!==r&&r.termdb){for(const t of e){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer sample id from "+n;t.name=e}o=", all integer IDs"}console.log(e.length,"samples from "+n+" of "+t.label+o)}async function or(t,e){var n;const r=t.queries.snvindel.byrange;if(r._tk.file)await P._H(r._tk,e,!0);else if(r._tk.chr2files){let t;for(const n in r._tk.chr2files){if("chr17"!=n)continue;const o=r._tk.chr2files[n];try{await P._H(o,e,!0);const i=JSON.stringify(o.samples);if(t){if(i!=t)throw"Different samples found in bcf file of "+n}else t=i,r._tk.samples=o.samples,r._tk.format=o.format,r._tk.info=o.info,r._tk.nochr=o.nochr}catch(t){console.log("missing file ignored:",o.file)}}}if(null!==(n=r._tk)&&void 0!==n&&n.samples.length){if(!r._tk.format)throw"bcf file has samples but no FORMAT"}else if(r._tk.format)throw"bcf file has FORMAT but no samples";if(r._tk.format){for(const t in r._tk.format)"GT"==t&&(r._tk.format[t].isGT=!0);if(t.queries.snvindel.format4filters){if(!Array.isArray(t.queries.snvindel.format4filters))throw"snvindel.format4filters[] is not array";for(const e of t.queries.snvindel.format4filters)r._tk.format[e]&&(r._tk.format[e].isFilter=!0);delete t.queries.snvindel.format4filters}}if(r._tk.info){if(r.infoFields){for(const t of r.infoFields){if(!t.key)throw".key missing from one of snvindel.byrange.infoFields[]";t.name||(t.name=t.key);const e=r._tk.info[t.key];if(!e)throw"invalid key from one of snvindel.byrange.infoFields[]";e.categories=t.categories,e.name=t.name,e.separator=t.separator}delete r.infoFields}if(t.queries.snvindel.infoUrl){for(const e of t.queries.snvindel.infoUrl){const t=r._tk.info[e.key];if(!t)throw"invalid key from one of snvindel.infoUrl[]";t.urlBase=e.base}delete t.queries.snvindel.infoUrl}}return t.queries.snvindel.info=r._tk.info,t.queries.snvindel.format=r._tk.format,async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const n=ir(e);let o;if(r._tk.chr2files){const t=r._tk.chr2files[e.rglst[0].chr];if(!t)throw"unknown chr for chr2files";o=t.file}else o=r._tk.file||r._tk.url;const i=["query",o,"-r",e.rglst.map((t=>(r._tk.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1))).join(","),"-f","%ID\t%CHROM\t%POS\t%REF\t%ALT\t%INFO\t%FORMAT\n"],s=await lr(e,r._tk.samples,t);if(s){if(0==s.size)return[];i.push("-s",[...s].join(","))}e.variantFilter&&(0,Yn.u)(e.variantFilter,i);const a=[];return await P.UE({isbcf:!0,args:i,dir:r._tk.dir,callback:o=>{const i=o.split("\t"),l=i[0],c=i[1],u=Number(i[2]),f=i[3],d=i[4].split(","),h=i[5],p={pos:u-1};(0,zn.H)(r._tk,f,d,p,h,l,e.isoform);for(const o of p.mlst){var m,g,y;e.hiddenmclass&&e.hiddenmclass.has(o.class)||(sr(o,e)||p.mlst.length>1&&null!==(m=e.variantFilter)&&void 0!==m&&m.lst&&ar(o,e)||(o.chr=(r._tk.nochr?"chr":"")+c,o.ssm_id=[o.chr,o.pos,o.ref,o.alt].join(Zn.dq),null!==(g=r._tk)&&void 0!==g&&null!==(y=g.samples)&&void 0!==y&&y.length&&(ur(r,o,i,e.addFormatValues,t,s,n),!o.samples)||a.push(o)))}}}),a}}function ir(t){var e,n;const r=t.formatFilter||{};return"format"==(null===(e=t.skewerRim)||void 0===e?void 0:e.type)&&null!==(n=t.skewerRim.hiddenvalues)&&void 0!==n&&n.size&&(r[t.skewerRim.formatKey]=t.skewerRim.hiddenvalues),Object.keys(r).length?r:void 0}function sr(t,e){if(!e.infoFilter)return!1;for(const n in e.infoFilter){const r=t.info[n];if(r)if(Array.isArray(r)){for(const t of e.infoFilter[n])if(r.includes(t))return!0}else if(e.infoFilter[n].includes(r))return!0}return!1}function ar(t,e){for(const r of e.variantFilter.lst){const e=t.info[r.tvs.term.id];if(null==e)return!0;if("integer"==r.tvs.term.type||"float"==r.tvs.term.type){var n;const t=Number(e);if(Number.isNaN(t))return!0;const o=null===(n=r.tvs.ranges)||void 0===n?void 0:n[0];if(o){if("start"in o)if(o.startinclusive){if(t<o.start)return!0}else if(t<=o.start)return!0;if("stop"in o)if(o.stopinclusive){if(t>o.stop)return!0}else if(t>=o.stop)return!0}}}return!1}async function lr(t,e,n){if(!e)return;const r=function(t,e){{const e=t.filter||t.filterObj;if(e){if(!Array.isArray(e.lst))throw"filterObj.lst is not array";return 0==e.lst.length?null:e}}if(t.tid2value){if("object"!=typeof t.tid2value)throw"q.tid2value{} not object";return cr(t.tid2value,e)}}(t,n);if(!r)return;const o=[...new Set((await(0,Bn.cf)(r,n)).map((t=>t.id)))],i=new Set(e.map((t=>t.name))),s=new Set;for(const t of o)i.has(t)&&s.add(t);return s}function cr(t,e){const n={type:"tvslst",in:!0,join:"and",lst:[]};for(const r in t){const o=e.cohort.termdb.q.termjsonByOneid(r);if(!o)continue;const i=t[r];n.lst.push({type:"tvs",tvs:{term:o,values:[{key:i}]}})}return n}function ur(t,e,n,r,o,i,s){if(!n[6]||"."==n[6])return;const a=[];for(const e of n[6].split(":")){const n=t._tk.format[e];if(!n)throw"invalid format field: "+n;a.push(n)}const l=[];let c=t._tk.samples;i&&(c=[...i].map((t=>({name:t}))));for(const[t,e]of c.entries()){const o=n[t+7];if(!o||"."==o)continue;const i=fr(o.split(":"),a,e,r);if(i){if(s){let t=!1;for(const e in s){const n=e in i.formatK2v?i.formatK2v[e]:Xn;if(s[e].has(n)){t=!0;break}}if(t)continue}l.push(i)}}l.length&&(e.samples=l)}function fr(t,e,n,r){const o={};for(const[n,r]of e.entries()){const e=t[n];if(e&&"."!=e)if(r.isGT){if("./."==e||".|."==e)continue;o.GT=e}else o[r.ID]=e}if(0==Object.keys(o).length)return null;const i={sample_id:n.name};return r&&(i.formatK2v=o),i}function dr(t,e,n,r=1){r=Number(r);const o=200,i=20;let s=0;for(const t in e.majorchr)s+=e.majorchr[t];const a=800/s,l={};let c=0;const u=[];for(const t in e.majorchr){const n=e.majorchr[t];l[t]=(0,Sn.Z)().domain([0,n]).range([a*c,a*(c+n)]),c+=n,u.push({chr:t,chrLen:n,xStart:a*(c-n),xStop:a*c})}const f=(0,Sn.Z)().domain([n.min,n.max]).range([o,0]),d=(0,S.createCanvas)(890*r,240*r),h=d.getContext("2d");r>1&&h.scale(r,r),g(n.max),g(0),g(n.min);const p=O().createInterface({input:m().createReadStream(t)});return new Promise(((t,r)=>{p.on("line",(t=>{const e=t.split("\t"),r=e[0];if(!r)return;if(!l[r])return;const o=Number(e[1]);if(!Number.isInteger(o))return;const s=Number(e[2]);if(!Number.isFinite(s))return;if(s<n.min||s>n.max)return;h.fillStyle=s>0?n.positiveColor:n.negativeColor;const a=l[r](o),c=i+f(s);h.fillRect(70+a,c,1,1)})),p.on("close",(()=>{!function(){h.strokeStyle="black",h.beginPath();{const t=220-f(0);h.moveTo(70,t),h.lineTo(870,t),h.stroke()}let t=!0;h.fillStyle="black",h.font="12px Arial",h.textAlign="center";for(const n in l){if(h.fillText(n.replace("chr",""),70+l[n](e.majorchr[n]/2),234),t){t=!1;continue}const r=Math.floor(70+l[n](0))+.5;h.moveTo(r,i),h.lineTo(r,220),h.stroke()}h.closePath()}(),t({src:d.toDataURL(),canvasWidth:890,canvasHeight:240,xoff:70,chrLst:u})}))}));function g(t){h.fillStyle="black",h.font="12px Arial",h.textAlign="right";const e=i+f(t);h.fillText(t,64,e+5),h.strokeStyle="black",h.beginPath(),h.moveTo(66,e),h.lineTo(70,e),h.stroke(),h.closePath()}}function hr(t,e,n,r,o,i){for(const s of e.yesSamples){if(i&&!i.has(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:s})}for(const s of e.noSamples){if(i&&!i.has(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:s})}}async function pr(t,e){if(t.chr&&Number.isInteger(t.start)&&Number.isInteger(t.stop))return;if(!t.name)throw"both term.name and term.chr/start/stop missing";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)throw"unknown gene name";const r=n.find((t=>t.isdefault))||n[0],o=JSON.parse(r.genemodel);if(!o.chr||!Number.isInteger(o.start)||!Number.isInteger(o.stop))throw"invalid chr/start/stop from returned gm";return t.chr=o.chr,t.start=o.start,t.stop=o.stop,o.isoform}async function mr(t,e,n,r){const o={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid};if(t.queries.geneCnv&&(o.useCaseid4sample=!0),t.queries.snvindel.byisoform)return await async function(t,e){if(t.isoform&&"string"==typeof t.isoform)return;if(!t.name)throw"both term.name and term.isoform";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)return;const r=n.find((t=>t.isdefault))||n[0],o=JSON.parse(r.genemodel);if(!o.isoform)throw"isoform missing from returned gm";t.isoform=o.isoform}(e,n),e.isoform?(o.isoform=e.isoform,await t.queries.snvindel.byisoform.get(o)):[];if(t.queries.snvindel.byrange)return o.isoform=await pr(e,n),o.rglst=[e],await t.queries.snvindel.byrange.get(o);throw"unknown queries.snvindel method"}function gr(t,e){e.yesSamples=new Set,e.noSamples=new Set;const n=`SELECT sample, value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = '${e.term_id}'`,r=t.cohort.db.connection.prepare(n).all();for(const t of r)e.yes.value.includes(t.value)?e.yesSamples.add(t.sample):e.no.value.includes(t.value)&&e.noSamples.add(t.sample)}function yr(t,e,n){if(e.skewerRim){if("format"!=e.skewerRim.type)throw"unknown skewerRim.type";t.rim1count=0;for(const n of t.samples){var r;(null===(r=n.formatK2v)||void 0===r?void 0:r[e.skewerRim.formatKey])==e.skewerRim.rim1value&&t.rim1count++}}}function vr(t,e){var n;if(null!==(n=e.queries.snvindel)&&void 0!==n&&n.format)for(const n in e.queries.snvindel.format)if(e.queries.snvindel.format[n].isFilter){t.formatK2count||(t.formatK2count={}),t.formatK2count[n]||(t.formatK2count[n]={v2c:{},unannotatedCount:0});for(const e of t.samples){var r;const o=null===(r=e.formatK2v)||void 0===r?void 0:r[n];null==o?t.formatK2count[n].unannotatedCount++:t.formatK2count[n].v2c[o]=1+(t.formatK2count[n].v2c[o]||0)}}}async function br(t,e){let n=1,r=[],o=[];for(const e of t)if(1==n)n=0;else if(0==e.length);else{let t=e.split(/(\s+)/);Number(t[t.length-3])%1!=0&&0==Number(t[t.length-1])?(r.push(Number(t[t.length-3])),o.push(1e-4)):(r.push(Number(t[t.length-3])),o.push(Number(t[t.length-1])))}let i=[],s=[],a=[],l=!1,c=[],u=0;for(let t=0;t<o.length;t++)if(1==l){let n=0;for(let e=0;e<s.length;e++){let l=s.length-e-1;if(s[l]>o[t]){i.push({id1:t,x1:r[t],y1:o[t],id2:l,x2:a[l],y2:s[l]}),n=1;break}}0==n&&console.log("No suitable branch point found"),i.push({id1:t,x1:r[t],y1:o[t],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t]),l=!1}else o[t]>o[t+1]&&t<=o.length-1?(i.push({id1:t,x1:r[t],y1:o[t],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t])):o[t]==o[t+1]&&t<=o.length-1?(i.push({id1:t-1,x1:r[t-1],y1:o[t-1],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t])):(t==o.length-1||(s.push(o[t]),a.push(r[t]),l=!0),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1));return{dendrogram:i,children:c}}async function wr(t,e,n,r){let o=e;if(n.find((t=>t.id==o))){let t=n.findIndex((t=>t.id==o));n[t].children.push(r)}else n.push({id:o,children:[r]});for(;0!=o;){let e,i,s=t.find((t=>t.id1==o));s&&s.y1<=s.y2&&(e=s.id2);let a=t.find((t=>t.id2==o));if(a&&a.y1>=a.y2&&(i=a.id1),!s&&a?o=i:s&&!a?o=e:s&&a?o=s.y2>a.y1?e:i:console.log("No connections found!"),n.find((t=>t.id==o))){let t=n.findIndex((t=>t.id==o));n[t].children.push(r)}else n.push({id:o,children:[r]})}return n}function _r(t,e){if(t.startunbounded){if(t.stopunbounded)throw"both start & stop are unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when start is unbounded from "+e}else if(t.stopunbounded){if(!Number.isFinite(t.start))throw".start undefined when stop is unbounded from "+e}else{if(!Number.isFinite(t.start))throw".start undefined when start is not unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when stop is not unbounded from "+e;if(t.start>=t.stop)throw".start is not lower than stop from "+e}}const xr="Ancestry_PC_";async function kr(t,e=null,r=null){var i,s;if(!t.cohort.termdb)throw"cohort.termdb missing when cohort.db is used";await async function(t){if(t.phewas){if(t.phewas.samplefilter4termtype&&t.phewas.samplefilter4termtype.condition&&!t.phewas.samplefilter4termtype.condition.filter)throw"filter{} missing from tdb.phewas.samplefilter4termtype.condition";if(t.phewas.comparison_groups){if(!Array.isArray(t.phewas.comparison_groups))throw"tdb.phewas.comparison_groups is not array";if(0==t.phewas.comparison_groups.length)throw"tdb.phewas.comparison_groups[] cannot be empty"}}if(t.selectCohort){if(!t.selectCohort.term)throw"term{} missing from termdb.selectCohort";if(!t.selectCohort.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof t.selectCohort.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=t.selectCohort.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';if(!t.selectCohort.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(t.selectCohort.values))throw"termdb.selectCohort.values is not array";if(0==t.selectCohort.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const e of t.selectCohort.values){if(!e.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(e.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==e.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}if(t.restrictAncestries){if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!Number.isInteger(e.PCcount))throw"PCcount is not integer";if(e.PCfile)e.pcs=await Nr(e.PCfile,e.PCcount);else if(e.PCfileBySubcohort)for(const t in e.PCfileBySubcohort){const n=e.PCfileBySubcohort[t];if(!n.file)throw".file missing for a subcohort in PCfileBySubcohort";n.pcs=await Nr(n.file,e.PCcount)}}}}(t.cohort.termdb),await async function(t){if("scatterplots"in t)for(const e of t.scatterplots.plots){const t=y().join(o().tpmasterdir,e.file);await P.Ic(t)}}(t.cohort),(0,Gn.JV)(t),function(t){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[r]=t.sampleId2Name.get(+r);return n}}(t);const{mayGetGeneVariantData:a,getTermTypes:l,mayGetMatchingGeneNames:c}=n(7833);t.mayGetGeneVariantData=a,t.getTermTypes=l,t.mayGetMatchingGeneNames=c,null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.db)&&void 0!==s&&s.refresh&&e&&Wn(t,e,r)}async function qr(t,e){if(!t.track)throw"no mds2 track; missing ds.track{}";const n=t.track;n.name||(n.name=t.label),function(t){if(!t.populations)return;if(!Array.isArray(t.populations))throw"populations should be array";for(const e of t.populations){if(!e.key)throw"key missing from a population";if(e.label||(e.label=e.key),!Array.isArray(e.sets))throw".sets is not an array in population: "+e.key;for(const t of e.sets){if(!t.infokey_AC)throw"infokey_AC missing from a set of population: "+e.key;if(!t.infokey_AN)throw"infokey_AN missing from a set of population: "+e.key;if(e.termfilter&&!t.termfilter_value)throw"termfilter_value missing from a set of population where termfilter is set: "+e.key}}}(n),await async function(t,e,n){if(!t)return;if(!t.chr2bcffile)throw"vcftk.chr2bcffile is missing";{if("object"!=typeof t.chr2bcffile)throw"chr2bcffile not an object";for(const e in t.chr2bcffile)t.chr2bcffile[e]=y().join(o().tpmasterdir,t.chr2bcffile[e]);const n={file:t.chr2bcffile[e.defaultcoord.chr]};if(!n.file)throw"default chr missing from chr2bcffile";await P._H(n,e,!0),t.info=n.info,t.format=n.format,t.samples=n.samples,t.nochr=n.nochr}if(t.AD&&t.AD.chr2bcffile){if("object"!=typeof t.AD.chr2bcffile)throw"AD.chr2bcffile not an object";for(const e in t.AD.chr2bcffile)t.AD.chr2bcffile[e]=y().join(o().tpmasterdir,t.AD.chr2bcffile[e]);const r={file:t.AD.chr2bcffile[e.defaultcoord.chr]};if(!r.file)throw"default chr missing from AD.chr2bcffile";await P._H(r,e,!0),t.AD.info=r.info,t.AD.format=r.format,t.AD.samples=r.samples,t.AD.nochr=r.nochr,console.log(n.label+" vcf: AD: "+t.AD.samples.length+" samples");for(const e of t.AD.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}}if(t.samples){for(const e of t.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}console.log(n.label+" vcf: "+t.samples.length+" samples")}else console.log(n.label+" vcf: no samples");if(t.numerical_axis&&t.numerical_axis.info_keys){if(!Array.isArray(t.numerical_axis.info_keys))throw"numerical_axis.info_keys should be an array";for(const e of t.numerical_axis.info_keys){const n=t.info[e.key];if(!n)throw'INFO field "'+e.key+'" not found for numerical_axis';if("Float"!=n.Type&&"Integer"!=n.Type)throw'INFO field "'+e.key+'" from numerical_axis not of integer or float type';if("1"!=n.Number&&"A"!=n.Number)throw'for numerical axis, INFO field "'+e.key+'" only allows to be Number=1 or Number=A'}}if(t.plot_mafcov){if(!t.AD)throw".plot_mafcov enabled but .AD{} missing from vcf";if(!t.AD.samples)throw".plot_mafcov enabled but no samples from vcf";if(!t.AD.format)throw".plot_mafcov enabled but no FORMAT fields from vcf";if(!t.AD.format.AD)throw".plot_mafcov enabled but the AD FORMAT field is missing";if("R"!=t.AD.format.AD.Number)throw"AD FORMAT field Number=R is not true";if("Integer"!=t.AD.format.AD.Type)throw"AD FORMAT field Type=Integer is not true";if(t.plot_mafcov.overlay_term){if(!n.cohort)throw"ds.cohort missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb)throw"ds.cohort.termdb missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb.q)throw"ERR: termdb.q{} missing while trying to access termdb helper functions";if(!n.cohort.termdb.q.termjsonByOneid)throw"ERR: q.termjsonByOneid missing";const e=n.cohort.termdb.q.termjsonByOneid(t.plot_mafcov.overlay_term);if(!e)throw'unknown term id "'+t.plot_mafcov.overlay_term+'" from vcftk.plot_mafcov.overlay_term';t.plot_mafcov.overlay_term=e}}if(t.termdb_bygenotype){if(!t.samples)throw".termdb_bygenotype enabled but no samples from vcf";if(!t.format)throw".termdb_bygenotype enabled but no FORMAT fields from vcf";if(!t.format.GT)throw".termdb_bygenotype enabled but the GT FORMAT field is missing";if(!n.cohort)throw"termdb_bygenotype but ds.cohort missing";if(!n.cohort.termdb)throw"termdb_bygenotype but ds.cohort.termdb missing";if(t.termdb_bygenotype.getAF){if(!t.termdb_bygenotype.termid_sex)throw"termid_sex missing for getAF at termdb_bygenotype";if(!t.termdb_bygenotype.value_male)throw"value_male missing for getAF at termdb_bygenotype";const e=n.cohort.termdb.q.getSample2value(t.termdb_bygenotype.termid_sex);t.termdb_bygenotype.male_samples=new Set;for(const n of e)n.value==t.termdb_bygenotype.value_male&&t.termdb_bygenotype.male_samples.add(n.sample);if(!t.termdb_bygenotype.sex_chrs)throw"sex_chrs missing for getAF at termdb_bygenotype";if(!Array.isArray(t.termdb_bygenotype.sex_chrs))throw"sex_chrs is not array";t.termdb_bygenotype.sex_chrs=new Set(t.termdb_bygenotype.sex_chrs)}}if(t.samples){t.sample2arrayidx=new Map;for(const[e,n]of t.samples.entries())t.sample2arrayidx.set(n.name,e)}}(n.vcf,e,t),function(t){if(!t.info_fields)return;if(!Array.isArray(t.info_fields))throw"tk.info_fields is not array";for(const e of t.info_fields){if(!e.key)throw".key missing from one of tk.info_fields[]";if(t.vcf&&t.vcf.info&&!t.vcf.info[e.key])throw`info field ${e.key} missing from tk.vcf.info{}`;if(e.label||(e.label=e.key),e.iscategorical){if(!Array.isArray(e.values))throw".values[] not an array of categorical INFO field: "+e.key;for(const t of e.values){if(!t.key)throw"key missing from a value of categorical INFO: "+e.key;t.label||(t.label=t.key)}}else if(e.isfloat||e.isinteger){if(!e.range)throw".range{} missing from a numerical INFO: "+e.key;_r(e.range,"tk.info_fields[]")}else if(!e.isflag)throw"tk.info_fields unknown type: "+e.key}}(n),await async function(t,e,n){if(!t)return;if(!Array.isArray(t.tracks))throw"ld.tracks[] not an array";if(0==t.tracks.length)throw"ld.tracks[] is empty array";for(const n of t.tracks){if(!n.name)throw".name missing from a ld track";if(!Number.isInteger(n.viewrangelimit))throw'viewrangelimit missing from ld track "'+n.name+'"';if(n.file)n.file.startsWith(o().tpmasterdir)||(n.file=y().join(o().tpmasterdir,n.file)),await P.LC(n.file),n.nochr=await P.Jy(n.file,null,e),console.log(n.file+": "+(n.nochr?"no chr":"has chr"));else if(!n.chr2file)throw"ld tk has no file or chr2file"}}(n.ld,e),await async function(t,e){if(!t)return}(n.svcnv,0),function(t){const e=new Set;if(t.vcf&&t.vcf.samples)for(const n of t.vcf.samples)e.add(n.name);t.svcnv;e.size&&(t.samples=[...e])}(n),n.samples&&console.log(t.label+": mds2: "+n.samples.length+" samples")}async function Nr(t,e){const n=new Map;for(let t=1;t<=e;t++)n.set(xr+t,new Map);let r=0;for(const i of(await P.b5(y().join(o().tpmasterdir,t))).trim().split("\n")){r++;const t=i.split("\t"),o=Number(t[0]);if(!Number.isInteger(o))throw"non-integer sample id from a line of restrictAncestries pc file";for(let r=1;r<=e;r++){const e=xr+r,i=Number(t[r]);if(Number.isNaN(i))throw"non-numeric PC value from restrictAncestries file";n.get(e).set(o,i)}}return console.log(r,"samples loaded from "+t),Object.freeze(n)}var Sr=n(9157);const Ar=n(334),Mr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO";async function Tr(t,e,n,r){if(!t.rglst)throw".rglst[] missing";const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";const i={info:o.info,format:o.format,samples:o.samples};await async function(t,e,n){if(t.querymode={},t.AFtest){if(n.iscustom)throw"custom track does not support AFtest";for(const e of t.AFtest.groups)if(!e.is_infofield)if(e.is_termdb)e.columnidx=await Cr(e.filter,n);else{if(!e.is_population)throw"Cannot set query mode: unknown group type";{if(!n.track.populations)throw"ds.track.populations missing";const r=n.track.populations.find((t=>t.key==e.key));if(!r)throw"unknown population key: "+e.key;if(e.population=JSON.parse(JSON.stringify(r)),t.AFtest.termfilter&&t.AFtest.termfilter[0].term.id==e.population.termfilter){const n=e.population.sets.find((e=>e.termfilter_value==t.AFtest.termfilter[0].values[0].key));if(!n)throw"no matching set found for a termfilter from a population";e.population.sets=[n]}}}if(t.AFtest.testby_fisher&&t.AFtest.groups.find((t=>t.is_infofield)))throw"cannot do fisher test for an INFO field";{const e=t.AFtest.groups.find((t=>t.is_population));if(e&&e.adjust_race){const r=t.AFtest.groups.find((t=>t.is_termdb));if(!r)throw"cannot adjust race: termdb group missing";r.pop2average=await async function(t,e,n,r){const o=new Map;let i=0;for(const e of t){const t={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await Bn.J4({ds:n,key:e.key});for(const e of r){if(!n.track.vcf.sample2arrayidx.has(e.sample))continue;const r=Number(e.value);Number.isFinite(r)&&(t.average+=r,i+=r)}o.set(e.key,t)}for(const[t,e]of o)e.average/=i;return o}(e.population.sets,r.columnidx,n)}}return void(t.querymode.range_AFtest=!0)}t.querymode.range_variantonly=!0}(t,0,n),function(t,e){if(e.querymode.range_variantonly||e.querymode.range_AFtest){delete t.samples;for(const t of e.rglst)t.variants=[]}e.bcfformat=Mr,e.exportgenotype||e.querymode.range_AFtest?e.bcfformat+="\t%FORMAT\n":e.querymode.range_variantonly&&(e.querymode.slicecolumnindex||(e.bcfformat+="\\n"))}(i,t),t.exportgenotype&&(r.mlst=[]),function(t,e){const n=(r=t.rglst[0],r.usegm_isoform?{gmmode:"protein",usegm:{isoform:r.usegm_isoform}}:{});var r;t.m_is_filtered=r=>{let o=!1;if(t.info_fields)for(const n of t.info_fields){const t=e.info_fields[n.key];let i;if(r.info&&(i=r.info[n.key]),null==i&&r.altinfo&&(i=r.altinfo[n.key]),n.iscategorical)null==i?(t.unannotated_count=1+(t.unannotated_count||0),n.unannotated_ishidden&&(o=!0)):(t.value2count[i]=1+(t.value2count[i]||0),n.hiddenvalues[i]&&(o=!0));else if(n.isnumerical)null==i&&null!=n.missing_value&&(i=n.missing_value),n.range.startunbounded||(n.range.startinclusive?i<n.range.start&&(o=!0):i<=n.range.start&&(o=!0)),n.range.stopunbounded||(n.range.stopinclusive?i>n.range.stop&&(o=!0):i>=n.range.stop&&(o=!0)),o&&t.filteredcount++;else{if(!n.isflag)throw"unknown info type";i?t.count_yes++:t.count_no++,(n.remove_yes&&i||n.remove_no&&!i)&&(o=!0)}}return!!o||(F.vcfcopymclass(r,n),e.mclass2count[r.class]=(e.mclass2count[r.class]||0)+1,t.hidden_mclass&&t.hidden_mclass.has(r.class)&&(o=!0),o)}}(t,r);for(const e of t.rglst){if(o.viewrangeupperlimit&&e.stop-e.start>=o.viewrangeupperlimit){e.rangetoobig="Zoom in under "+F.bplen(o.viewrangeupperlimit)+" to view VCF data";continue}const n=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop,r=o.chr2bcffile[e.chr];if(!r)throw"chr not found in chr2bcffile";await P.UE({isbcf:!0,args:["query",r,"-r",n,"-f",t.bcfformat],dir:o.dir,callback:s(e)})}function s(e){return n=>{if(t.exportgenotype){const e=n.split("\t"),[o,s,a]=D.S(e.slice(0,8).join("\t"),i);for(const n of s){if(t.m_is_filtered(n))continue;const o=[n.chr+"."+(n.pos+1)+"."+n.ref+"."+n.alt,n.name||""];for(let t=9;t<e.length;t++){const r=e[t].split(":",1)[0];if("."==r){o.push(".");continue}const i=r.split(-1==r.indexOf("/")?"|":"/");o.push(("0"==i[0]?n.ref:n.alt)+("0"==i[1]?n.ref:n.alt))}r.mlst.push(o.join("\t"))}return}let s;if(t.querymode.range_variantonly)if(t.querymode.slicecolumnindex);else{const[e,r,o]=D.S(n,i);s=[];for(const e of r)t.m_is_filtered(e)||s.push(e)}else t.querymode.range_AFtest&&(s=function(t,e,n,r){const o=t.split("\t"),[i,s,a]=D.S(o.slice(0,8).join("\t"),n),l=s.filter((t=>!e.m_is_filtered(t)));if(0==l.length)return;const c=[o[3],...o[4].split(",")],u=[];for(const t of l){const n=Er(o,t,c,e);if(jr(n)){if(u.push(t),e.AFtest.testby_AFdiff){for(const t of n)if(t.is_infofield)t.v=t.infofieldvalue;else{if(!t.is_termdb&&!t.is_population)throw"unknown group type";t.v=t.altcount/(t.refcount+t.altcount)}t.AFtest_group_values=[n[0].v,n[1].v],t.nm_axis_value=n[0].v-n[1].v}else e.AFtest.testby_fisher&&(t.contigencytable=[n[0].altcount,n[0].refcount,n[1].altcount,n[1].refcount]);{const r=e.AFtest.groups.find((t=>t.is_population));if(r&&r.adjust_race){const e=n.find((t=>t.is_population));t.popsetadjvalue=[];for(const[n,r]of e.set2value)t.popsetadjvalue.push([n,r.ACraw,r.ANraw-r.ACraw,Number.parseInt(r.ACadj),Number.parseInt(r.ANadj-r.ACadj)])}}}}return u}(n,t,i));if(s)for(const t of s)t.csq&&(t.csq_count=t.csq.length,delete t.csq),delete t._m,delete t.vcf_ID,delete t.sampledata,o.nochr&&(t.chr="chr"+t.chr),e.variants.push(t)}}await async function(t){if(!t.querymode.range_AFtest)return;if(!t.AFtest.testby_fisher)return;const e=[],n={};for(const r of t.rglst)if(r.variants)for(const t of r.variants)if(t.contigencytable){const r=t.chr+"."+t.pos+"."+t.ref+"."+t.alt;e.push(r+"\t"+t.contigencytable.join("\t")),n[r]=t}if(0==e.length)return;const r=await Sr(y().join(Ar.binpath,"/utils/fisher.R"),e);for(const t of r){const e=t.split("\t"),r=n[e[0]];if(r){const t=Number.parseFloat(e[5]);r.AFtest_pvalue=t,r.nm_axis_value=Number.isNaN(t)?0:-Math.log10(t)}}}(t),function(t,e,n,r){if(e.exportgenotype)return t.exportgenotype="variant\tSNP\t"+n.samples.map((t=>r.cohort.termdb.id2sampleName(t.name))).join("\t")+"\n"+t.mlst.join("\n"),void delete t.mlst;t.vcf={rglst:[]};for(const n of e.rglst){const e={chr:n.chr,start:n.start,stop:n.stop,width:n.width,reverse:n.reverse,xoff:n.xoff};t.vcf.rglst.push(e),n.rangetoobig?(e.rangetoobig=n.rangetoobig,delete n.rangetoobig):n.variants?(e.variants=n.variants,delete n.variants):n.canvas&&(e.img=n.canvas.toDataURL(),delete n.canvas)}if(e.AFtest&&e.AFtest.groups.find((t=>t.is_termdb))){t.AFtest_termdbgroup=[];let n=e.AFtest.groups[0];if(n.is_termdb&&(t.AFtest_termdbgroup[0]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[0].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[0].popsetaverage.push([e,r.average])}if(n=e.AFtest.groups[1],n.is_termdb&&(t.AFtest_termdbgroup[1]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[1].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[1].popsetaverage.push([e,r.average])}}}(r,t,o,n)}async function Cr(t,e){if(!e.track)throw"ds.track{} missing";return(await Bn.cf(t,e)).reduce(((t,n)=>{const r=e.track.vcf.sample2arrayidx.get(n);return r>=0&&t.push(r),t}),[])}function jr(t){if(t.find((t=>t.is_infofield)))return!0;return t[0].altcount+t[1].altcount>0}function Er(t,e,n,r){return r.AFtest.groups.reduce(((o,i)=>{if(i.is_infofield)o.push({is_infofield:!0,infofieldvalue:Or(e,i)});else if(i.is_termdb){const r=function(t,e,n){let r=!0;const o=new Map;for(const e of t)o.set(e,0);for(const i of n){if(!e[9+i])continue;const n=e[9+i].split(":")[0];"."!=n&&n.split(-1==n.indexOf("/")?"|":"/").forEach((e=>{const n=Number.parseInt(e);if(Number.isNaN(n))return;const i=t[n];i&&(0!=n&&(r=!1),o.set(i,1+o.get(i)))}))}return{allref:r,alleles:o}}(n,t,i.columnidx);o.push({is_termdb:!0,allref:r.allref,refcount:r.alleles.get(e.ref)||0,altcount:r.alleles.get(e.alt)||0})}else{if(!i.is_population)throw"unknown group type";{const t=new Map;for(const n of i.population.sets)t.set(n.key,{ACraw:Or(e,{key:n.infokey_AC,missing_value:0}),ANraw:Or(e,{key:n.infokey_AN,missing_value:0})});let n=0,s=0;if(i.adjust_race)[n,s]=function(t,e){if(!e)throw"group_termdb missing";if(!e.pop2average)throw"group_termdb.pop2average missing";let n=0;for(const e of t.values())n+=e.ANraw;let r=0,o=0;for(const[i,s]of t)s.ANadj=n*e.pop2average.get(i).average,s.ACadj=0==s.ANadj?0:s.ACraw*s.ANadj/s.ANraw,r+=s.ACadj,o+=s.ANadj;return[o-r,r]}(t,r.AFtest.groups.find((t=>t.is_termdb)));else for(const e of t.values())s+=e.ACraw,n+=e.ANraw-e.ACraw;o.push({is_population:!0,refcount:n,altcount:s,set2value:t})}}return o}),[])}function Or(t,e){if(t.info){const n=t.info[e.key];if(null!=n)return n}if(t.altinfo){const n=t.altinfo[e.key];if(null!=n)return n}return e.missing_value}var Ir=n(5540),Rr=n(7763);const Pr="#aaa",Fr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO\t%FORMAT\n";async function Dr(t,e,n,r,o){const i=r.track.ld.tracks.find((e=>e.name==t.name));if(!i)throw"ld track not found by name: "+t.name;if(!e.rglst)throw"rglst missing";o.ld[i.name]={rglst:[]};const s=e.trigger_ld.connheight||50;for(const t of e.rglst){const e={chr:t.chr,start:t.start,stop:t.stop,width:t.width,reverse:t.reverse,xoff:t.xoff};if(o.ld[i.name].rglst.push(e),t.stop-t.start>=i.viewrangelimit){e.rangetoobig="Zoom in under "+(0,F.bplen)(i.viewrangelimit)+" to view LD data";continue}const n=[],r=new Set,a=(i.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await P.UE({args:[i.file,a],dir:i.dir,callback:e=>{const i=e.split("\t"),s=Number.parseInt(i[1]);if(s<t.start)return;const a=Number.parseInt(i[2]);if(a>t.stop)return;if(o.__mposset){if(!o.__mposset.has(s))return;if(!o.__mposset.has(a))return}const l=Number.parseFloat(i[5]);n.push({start:s,stop:a,r2:l}),r.add(s),r.add(a)}}),e.img=Lr(t,n,r,s)}}function Lr(t,e,n,r){const[o,i]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const o=new Map,i=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let s=r;for(const t of i)o.set(t,s+n/2),s+=n;return[n,o]}(t,n),s=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?s.set(r,(t.stop-r)/e):s.set(r,(r-t.start)/e)}let a=0;for(const t of e)a=Math.max(a,(i.get(t.stop)-i.get(t.start))/2);const l=r+a+o/2,c=(0,S.createCanvas)(t.width,l),u=c.getContext("2d");u.strokeStyle="black";for(const t of n)u.beginPath(),u.moveTo(s.get(t),0),u.lineTo(i.get(t),r),u.closePath(),u.stroke();for(const t of e){const e=i.get(t.start),n=i.get(t.stop),s=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(s,a-o/2),u.lineTo(s-o/2,a),u.lineTo(s,a+o/2),u.lineTo(s+o/2,a),u.lineTo(s,a-o/2),u.closePath(),u.fill()}return{height:l,src:c.toDataURL()}}var $r=n(6191);function Zr(t,e){const{filename:n,route:r,dslabel:i,embedder:s}=t,a=e.email.replace("@","_at_");return`${o().cachedir}/sessionsByCred/${s}/${a}/${r}/${i}`}const zr=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];function Ur(t){const e=t.toString(16);return 1==e.length?"0"+e:e}function Br(t,e,n){return Ur(t)+Ur(e)+Ur(n)}function Gr(t){if(!t.cellfile)throw"cellfile missing";{const[e,n,r]=P.ZX({query:{file:t.cellfile}});if(e)throw"cellfile error: "+e;t.cellfile=n}if(!t.delimiter)throw"delimiter missing";if(!Number.isInteger(t.barcodecolumnidx))throw"barcodecolumnidx missing";if(!Number.isInteger(t.categorycolumnidx))throw"categorycolumnidx missing";return new Promise(((e,n)=>{const r=new Map,o=O().createInterface({input:m().createReadStream(t.cellfile)});let i=!0;o.on("line",(e=>{if(i)return void(i=!1);const n=e.split(t.delimiter);r.set(n[t.barcodecolumnidx],{category:n[t.categorycolumnidx],expvalue:0})})),o.on("close",(()=>{e(r)}))}))}const Jr=o().fimo||"fimo";async function Wr(t,e,n){const r=y().join(o().cachedir,Math.random().toString());return await P.Sf(r,n),new Promise(((n,o)=>{const i=["--parse-genomic-coord","--verbosity",1,"--text"];t.fimo_thresh&&(i.push("--thresh"),i.push(t.fimo_thresh)),i.push(e.fimo_motif.db),i.push(r);const s=(0,q.spawn)(Jr,i),a=[];s.stdout.on("data",(t=>a.push(t))),s.on("close",(o=>{m().unlink(r,(()=>{}));const i=a.join("").trim();i||n([]);const s=[],l=i.split("\n");for(let n=1;n<l.length;n++){const r=l[n].split("\t"),o=r[0].split("_")[0],i=Number.parseInt(r[3]),a=Number.parseInt(r[4]);if(i>t.m.pos||a<t.m.pos+1)continue;const c=Number.parseFloat(r[7]),u={start:i,stop:a,strand:r[5],name:o,pvalue:c,score:Number.parseFloat(r[6]),logpvalue:-Math.log10(c)};e.fimo_motif.tf2attr&&(u.attr=e.fimo_motif.tf2attr[u.name]),s.push(u)}n(s)}))}))}function Hr(t){!function(t){if(!t.sample2term)throw".sample2term missing";if(!t.terms)throw".terms[] missing";if(!t.config)throw".config{} missing"}(t);const e=function(t){const e=new Map;for(const n of t.sample2term.values())for(const t of n.keys())e.set(t,1+(e.get(t)||0));if(t.config.termidorder){const n=[];for(const r of t.config.termidorder){const t=e.get(r);null!=t&&n.push({id:r,samplecount:t})}return n}return[...e].sort(((t,e)=>e[1]-t[1])).map((t=>({id:t[0],samplecount:t[1]})))}(t),n=function(t,e){const n=[];for(const[r,o]of t.sample2term)e.find((t=>o.has(t.id)))&&n.push(r);return n}(t,e);return function(t,e,n){for(const[r,o]of e.entries()){const i=0==r?[{samples:n}]:e[r-1].blocks;o.blocks=Vr(i,o.id,t)}}(t,e,n),function(t,e){for(const n of t){const t=e.terms.find((t=>t.id==n.id));n.name=t.name;for(const e of n.blocks)e.samplecount=e.samples.length,delete e.samples,e.value&&(e.color=t.values[e.value].color)}}(e,t),function(t){for(let e=t.length-1;e>=0;e--){const n=t[e];for(const t of n.blocks){let e=0;for(const n of t.children)e+=n.symbolwidth;const n=t.isgap?1:t.samplecount.toString().length;t.symbolwidth=Math.max(n,e)}}let e=0;for(const n of t[0].blocks){n.x=e;let t=e;for(const e of n.children)e.x=t,t+=e.symbolwidth;e+=n.symbolwidth}for(let e=1;e<t.length;e++)for(const n of t[e].blocks){let t=n.x;for(const e of n.children)e.x=t,t+=e.symbolwidth}for(const e of t)delete e.children}(e),e}function Vr(t,e,n){const r=[];for(const o of t){const t=new Map,i=[];for(const r of o.samples){const o=n.sample2term.get(r);if(o){const n=o.get(e);null==n?i.push(r):(t.has(n)||t.set(n,[]),t.get(n).push(r))}else i.push(r)}const s=[...t].sort(((t,e)=>e[1].length-t[1].length));for(const t of s){const e={value:t[0],samples:t[1],children:[]};r.push(e),o.children&&o.children.push(e)}if(i.length){const t={isgap:!0,samples:i,children:[]};r.push(t),o.children&&o.children.push(t)}}return r}async function Yr(t){const e=["futime\tfustat\trx"];for(const[n,r]of t.entries())for(const t of r.lst)e.push(t.serialtime+"\t"+t.censored+"\t"+n);const n=await(0,Sr.default)(y().join(o().binpath,"/utils/km.R"),e);return Number(n.join(""))}async function Kr(t,e,n,r){const o=new Set(t.map((t=>t.name))),i=e.samplerule.set;let s,a;for(const t in n.queries){const e=n.queries[t];e.type==F.tkt.mdsvcf?s=e:e.type==F.tkt.mdssvcnv&&(a=e)}const l=new Set;if(i.cnv||i.loh||i.sv||i.fusion||i.itd){if(!a)throw"no svcnv found in ds.queries";if(r)return await Xr(a,o,e,!0);const t=await Xr(a,o,e);for(const e of t)l.add(e)}if(i.snvindel){if(!s)throw"no vcf found in ds.queries";for(const t of s.tracks)await Qr(s,t,o,l,e)}return t.filter((t=>l.has(t.name)))}async function Xr(t,e,n,r){const i=n.samplerule.set,s=t.url?await P.d1(t.url,t.indexURL):null,a=new Set,l=new Set,c=new Set;return await P.UE({args:[t.file?y().join(o().tpmasterdir,t.file):t.url,(t.nochr?i.chr.replace("chr",""):i.chr)+":"+i.start+"-"+(i.stop+1)],dir:s,callback:t=>{const n=t.split("\t"),o=Number.parseInt(n[1]),s=Number.parseInt(n[2]),u=JSON.parse(n[3]);if(e.has(u.sample)){if(u.dt==F.dtcnv){if(!i.cnv)return;if(i.cnv.focalsizelimit&&s-o>=i.cnv.focalsizelimit)return;if(i.cnv.valuecutoff&&Math.abs(u.value)<i.cnv.valuecutoff)return;return r?u.value>0?a.add(u.sample):l.add(u.sample):c.add(u.sample),void i.samples_cnv.add(u.sample)}if(u.dt==F.dtloh){if(!i.loh)return;if(i.loh.focalsizelimit&&s-o>=i.loh.focalsizelimit)return;if(i.loh.valuecutoff&&u.segmean<i.loh.valuecutoff)return;return c.add(u.sample),void i.samples_loh.add(u.sample)}if(u.dt==F.dtsv){if(!i.sv)return;return c.add(u.sample),void i.samples_sv.add(u.sample)}if(u.dt==F.dtfusionrna){if(!i.fusion)return;return c.add(u.sample),void i.samples_fusion.add(u.sample)}if(u.dt==F.dtitd){if(!i.itd)return;return c.add(u.sample),void i.samples_itd.add(u.sample)}}}}),r?[a,l]:c}async function Qr(t,e,n,r,i){const s=i.samplerule.set,a=e.url?await P.d1(e.url,e.indexURL):null;await P.UE({args:[e.file?y().join(o().tpmasterdir,e.file):e.url,(e.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+(s.stop+1)],dir:a,callback:o=>{if(e.type==F.mdsvcftype.vcf){const[i,a,l]=D.S(o,{nochr:e.nochr,samples:e.samples,info:t.info,format:e.format});for(const t of a)if(t.sampledata&&!(s.snvindel.ref&&(t.ref!=s.snvindel.ref||t.alt!=s.snvindel.alt)||s.snvindel.hiddenclass&&(F.vcfcopymclass(t,{}),s.snvindel.hiddenclass[t.class])))for(const e of t.sampledata)n.has(e.sampleobj.name)&&(r.add(e.sampleobj.name),s.samples_snvindel.add(e.sampleobj.name))}}})}async function to(t,e,n){if(!n.queries)throw".queries{} missing from ds";let r;for(const t in n.queries)n.queries[t].isgenenumeric&&(r=n.queries[t]);if(!r)throw"no gene numeric query from ds";const i=r.url?await P.d1(r.url,r.indexURL):null,s=e.samplerule.set,a=new Map;await P.UE({args:[r.file?y().join(o().tpmasterdir,r.file):r.url,s.chr+":"+s.start+"-"+s.stop],dir:i,callback:t=>{const e=JSON.parse(t.split("\t")[3]);e.sample&&Number.isFinite(e.value)&&e.gene==s.gene&&a.set(e.sample,e.value)}});const l=[];for(const e of t)a.has(e.name)&&(e.genevalue=a.get(e.name),l.push(e));return l.sort(((t,e)=>t.genevalue-e.genevalue)),[r,l]}function eo(t){t.lst.sort(((t,e)=>t.serialtime-e.serialtime));let e=t.lst.length,n=[],r=0;t.steps=[];for(const o of t.lst){if(0==o.censored){n.push(o.serialtime);continue}const i=1*(1-r)/(e-n.length);t.steps.push({x:o.serialtime,y:r,drop:i,censored:n}),r+=i,e-=n.length+1,n=[]}n.length>0&&t.steps.push({x:t.lst[t.lst.length-1].serialtime,y:r,drop:0,censored:n})}exports.do_plot=eo;const no={};function ro(t,e,n){const r=+new Date;if(t.ip in no||(no[t.ip]={time:r,count:0}),r-no[t.ip].time>3e4)delete no[t.ip];else{if(no[t.ip].count>10)return void e.send({error:"busy"});no[t.ip].count++}throw e.send({error:n}),new Date+" "+n}const oo={genome(t){if("string"!=typeof t)throw"genome should be a non-empty string";if(/\s+/.test(t))throw"invalid genome character";return t},chr(t){if("string"!=typeof t)throw"chr should be a string";if(/\s+/.test(t))throw"invalid chr character";return t},start:t=>Number(t),term(t){const e="string"==typeof t?JSON.parse(t):t;if(!("id"in e))throw"missing termWrapper.id";if(!("q"in e))throw"missing termWrapper.q";return e}},io=require("cookie-parser");var so=n.n(io),ao=n(2062),lo=n(5708);const co=t=>t.startsWith("[E::idx_test_and_fetch]"),uo=(new Map,Object.freeze(o().features||{})),fo={},ho=o().tabix,po=o().samtools,mo=o().bcftools,go=(o().bigwigsummary,o().hicstraw,"Unannotated"),yo=s()();yo.disable("x-powered-by"),o().users&&yo.use(K()({users:o().users,challenge:!0}));const vo=o().basepath||"";function bo(t){t.header("Vary","Origin"),t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS, HEAD"),t.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, origin, x-requested-with, content-type, accept, authorization, X-Auth-Token, X-Ds-Access-Token, X-SjPPDs-Sessionid, x-auth-token, x-ds-access-token, x-sjppds-sessionid")}if(!o().backend_only){const t=s().static(y().join(process.cwd(),"./public"),{setHeaders:bo});yo.use(t)}function wo(t){const e={};for(const n in t.query)"jwt"!=n&&(e[n]=t.query[n]);console.log("%s\t%s\t%s\t%s",c().parse(t.url).pathname,new Date,t.header("x-forwarded-for")||t.connection.remoteAddress,JSON.stringify(e).replace(/\\"/g,'"'))}async function _o(){try{if(o().preListenScript){const{cmd:t,args:e}=o().preListenScript,n=N().spawnSync(t,e,{encoding:"utf-8"});if(n.stderr.trim())throw n.stderr.trim();console.log(n.stdout)}o().appEnable&&o().appEnable.forEach((t=>yo.enable(t)));const t=o().port,e=`STANDBY AT PORT ${t}`;if(o().ssl){const n={key:m().readFileSync(o().ssl.key),cert:m().readFileSync(o().ssl.cert)},r=await h().createServer(n,yo);return r.listen(t,"0.0.0.0",(()=>{console.log(`HTTPS ${e}`)})),r}{const n=await f().createServer(yo);return n.listen(t,"0.0.0.0",(()=>{process.send&&process.send("ready"),console.log(e)})),n}}catch(t){throw t}}function xo(t){const e=fo[t],n={species:e.species,name:t,hasSNP:!!e.snp,hasIdeogram:e.genedb.hasIdeogram,fimo_motif:!!e.fimo_motif,blat:!!e.blat,geneset:e.geneset,defaultcoord:e.defaultcoord,isdefault:e.isdefault,majorchr:e.majorchr,majorchrorder:e.majorchrorder,minorchr:e.minorchr,tracks:e.tracks,hicenzymefragment:e.hicenzymefragment,datasets:{}};if(e.termdbs){n.termdbs={};for(const t in e.termdbs)n.termdbs[t]={label:e.termdbs[t].label}}for(const t in e.datasets){const r=e.datasets[t];r.isMds3?n.datasets[r.label]={isMds3:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:r.isMds?n.datasets[r.label]={isMds:!0,mdsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:n.datasets[r.label]={isofficial:!0,legacyDsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}}if(e.hicdomain){n.hicdomain={groups:{}};for(const t in e.hicdomain.groups){const r=e.hicdomain.groups[t];n.hicdomain.groups[t]={name:r.name,reference:r.reference,sets:{}};for(const e in r.sets)n.hicdomain.groups[t].sets[e]={name:r.sets[e].name,longname:r.sets[e].longname}}}return n}function ko(t){const e={noHandleOnClient:t.noHandleOnClient,sampleselectable:t.sampleselectable,label:t.label,dsinfo:t.dsinfo,stratify:t.stratify,cohort:t.cohort,vcfinfofilter:t.vcfinfofilter,info2table:t.info2table,info2singletable:t.info2singletable,url4variant:t.url4variant,itemlabelname:t.itemlabelname};if(t.snvindel_attributes){e.snvindel_attributes=[];for(const n of t.snvindel_attributes){const t={};for(const e in n)if("lst"==e){t.lst=[];for(const e of n.lst){const n={};for(const t in e)n[t]=e[t];t.lst.push(n)}}else t[e]=n[e];e.snvindel_attributes.push(t)}}t.snvindel_legend&&(e.snvindel_legend=t.snvindel_legend);const n={};let r=!1;for(const e of t.queries)e.vcf&&(r=!0,n[e.vcf.vcfid]=e.vcf);return r&&(e.id2vcf=n),e}function qo(t){const e={isMds:!0,noHandleOnClient:t.noHandleOnClient,label:t.label,version:t.version,annotationsampleset2matrix:t.annotationsampleset2matrix,mutationAttribute:t.mutationAttribute,locusAttribute:t.locusAttribute,alleleAttribute:t.alleleAttribute,hide_genotypedownload:t.hide_genotypedownload,hide_phewas:t.hide_phewas,sample2bam:t.sample2bam};if(t.queries&&(e.queries={}),t.track&&(e.track=function(t){const e=t.track,n={name:e.name,info_fields:e.info_fields,sample_termfilter:e.sample_termfilter};return e.vcf&&(n.vcf={numerical_axis:e.vcf.numerical_axis,format:e.vcf.format,info:e.vcf.info,check_pecanpie:e.vcf.check_pecanpie},e.vcf.plot_mafcov&&(n.vcf.plot_mafcov={},t.cohort&&t.cohort.termdb&&(n.vcf.plot_mafcov.overlay_term=e.vcf.plot_mafcov.overlay_term||{})),e.vcf.termdb_bygenotype&&(n.vcf.termdb_bygenotype=!0),e.populations&&(n.populations=e.populations)),e.ld&&(n.ld={tracks:e.ld.tracks.map((t=>({name:t.name,shown:t.shown}))),overlay:e.ld.overlay}),n}(t)),t.singlesamplemutationjson&&(e.singlesamplemutationjson=1),t.gene2mutcount&&(e.gene2mutcount=!0,e.mutCountType=t.gene2mutcount.mutationTypes),t.assayAvailability&&(e.assayAvailability=1),t.cohort&&t.cohort.sampleAttribute){const n={};for(const e in t.cohort.sampleAttribute.attributes){const r=t.cohort.sampleAttribute.attributes[e];r.clientnoshow||(n[e]=r)}e.sampleAttribute={attributes:n}}if(t.cohort){if(t.cohort.termdb&&(e.termdb={selectCohort:t.cohort.termdb.selectCohort}),t.cohort.attributes&&t.cohort.attributes.defaulthidden&&(e.cohortHiddenAttr=t.cohort.attributes.defaulthidden),t.cohort.survivalplot){e.survivalplot={samplegroupattrlst:t.cohort.survivalplot.samplegroupattrlst,plots:[]};for(const n in t.cohort.survivalplot.plots){const r=t.cohort.survivalplot.plots[n];e.survivalplot.plots.push({key:n,name:r.name,timelabel:r.timelabel})}}if(t.cohort.mutation_signature){const n={};for(const e in t.cohort.mutation_signature.sets){const r=t.cohort.mutation_signature.sets[e];n[e]={name:r.name,signatures:r.signatures}}e.mutation_signature={sets:n}}}for(const n in t.queries){const r=t.queries[n],o={name:r.name,hideforthemoment:r.hideforthemoment};if(r.istrack){if(o.istrack=!0,o.type=r.type,o.isfull=r.isfull,null!=r.nochr&&(o.nochr=r.nochr),r.infoFilter&&(o.infoFilter=r.infoFilter),r.readcountCutoff&&(o.readcountCutoff=r.readcountCutoff),r.valueLabel&&(o.valueLabel=r.valueLabel),r.valueCutoff&&(o.valueCutoff=r.valueCutoff),r.bplengthUpperLimit&&(o.bplengthUpperLimit=r.bplengthUpperLimit),r.segmeanValueCutoff&&(o.segmeanValueCutoff=r.segmeanValueCutoff),r.lohLengthUpperLimit&&(o.lohLengthUpperLimit=r.lohLengthUpperLimit),r.type==F.tkt.mdssvcnv){if(r.groupsamplebyattr&&(o.groupsamplebyattr=r.groupsamplebyattr),o.multihidelabel_fusion=r.multihidelabel_fusion,o.multihidelabel_sv=r.multihidelabel_sv,o.multihidelabel_vcf=r.multihidelabel_vcf,o.showfullmode=r.showfullmode,o.legend_vorigin=r.legend_vorigin,o.no_loh=r.no_loh,r.expressionrank_querykey){const e=t.queries[r.expressionrank_querykey];if(o.checkexpressionrank={querykey:r.expressionrank_querykey,datatype:e.datatype},e.boxplotbysamplegroup&&e.boxplotbysamplegroup.additionals){const t=[];e.boxplotbysamplegroup.attributes&&t.push(e.boxplotbysamplegroup.attributes.map((t=>t.label)).join(", "));for(const n of e.boxplotbysamplegroup.additionals)t.push(n.label);o.checkexpressionrank.boxplotgroupers=t}}if(r.vcf_querykey){o.checkvcf={querykey:r.vcf_querykey,info:t.queries[r.vcf_querykey].info,format:{}};for(const e of t.queries[r.vcf_querykey].tracks)if(e.format)for(const t in e.format)o.checkvcf.format[t]=e.format[t]}}}else{if(!r.isgenenumeric)continue;o.isgenenumeric=!0,o.datatype=r.datatype,o.no_ase=r.no_ase}e.queries[n]=o}return e}async function No(t,e){if(!e)throw"invalid genome";if(!e.snp)throw"snp is not configured for this genome";const n=[];if(t.byCoord){if(e.genomicNameRegexp.test(t.chr))throw"invalid chr name";if(!Array.isArray(t.ranges))throw"ranges not an array";for(const r of t.ranges){if(!Number.isInteger(r.start)||!Number.isInteger(r.stop)||r.start<0||r.stop<r.start)throw"invalid start/stop";if(r.stop-r.start>=100)throw"range too big";const o=await P.z5(e.snp.bigbedfile,t.chr,r.start,r.stop);for(const e of o){const r=So(e);if(t.alleleLst){let e=!1;for(const n of t.alleleLst)if(n&&!r.alleles.includes(n)){e=!0;break}if(e)continue}n.push(r)}}}else{if(!t.byName)throw"unknown query method";if(!Array.isArray(t.lst))throw".lst[] missing";for(const r of t.lst){if(e.genomicNameRegexp.test(r))continue;const t=await P.mr(e.snp.bigbedfile,r);for(const e of t){const t=So(e);n.push(t)}}}return n}function So(t){const e=t.split("\t"),n=e[4],r=e[6].split(",").filter(Boolean),o=n+"/"+r.join("/");return{chrom:e[0],chromStart:Number(e[1]),chromEnd:Number(e[2]),name:e[3],observed:o,alleles:[n,...r]}}function Ao(t,e,n){if(n.query.isoform&&fo[n.query.genome].genomicNameRegexp.test(n.query.isoform))return;const[r,o]=e.makequery(n.query);if(!r)return;const i=t.newconn.prepare(r).all(o);let s;s=e.tidy?i.map((t=>e.tidy(t))):i;const a={};if(e.isgeneexpression){a.lst=s,a.isgeneexpression=!0,a.config=e.config;for(const e of t.queries)if(e.dsblocktracklst)for(const t of e.dsblocktracklst)t.type==F.tkt.junction&&(a.config.dsjunctiontk=t)}else a.lst=s;return a}function Mo(t,e){const n=[y().join(o().tpmasterdir,t.vcffile),(t.vcf.nochr?e.query.range.chr.replace("chr",""):e.query.range.chr)+":"+e.query.range.start+"-"+e.query.range.stop];return new Promise(((e,r)=>{const o=(0,q.spawn)(ho,n),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(n=>{""!=s.join("").trim()&&r("error querying vcf file");const o=i.join("").trim();e({lines:""==o?[]:o.split("\n"),vcfid:t.vcf.vcfid})}))}))}function To(t){if(!t.genome)return["no genome"];const e=fo[t.genome];if(!e)return["invalid genome"];if(!e.datasets)return["genome is not equipped with datasets"];if(!t.dslabel)return["dslabel missing"];const n=e.datasets[t.dslabel];if(!n)return["invalid dslabel"];if(!n.queries)return["dataset is not equipped with queries"];if(!t.querykey)return["querykey missing"];const r=n.queries[t.querykey];return r?[null,e,n,r]:["invalid querykey"]}async function Co(t,e,n,r,i,s){const a=await async function(t,e,n,r){const i=t.checkvcf.tracks[0],s={file:i.file,url:i.url,indexURL:i.indexURL,dir:i.dir,nochr:i.nochr,samples:i.samples,info:t.checkvcf.info,format:i.format},a=await zo(s.file?y().join(o().tpmasterdir,s.file):s.url,(s.nochr?e.replace("chr",""):e)+":"+n+"-"+r,s.dir),l=[];for(const t of a||[]){const[e,n,r]=D.S(t,s);for(const t of n)F.basecolor[t.ref]&&F.basecolor[t.alt]&&t.sampledata&&l.push(t)}return l}(i,e,n,r),l=[];for(const t in i.checkrnabam.samples){const n=i.checkrnabam.samples[t];n.hetsnps=[];for(const e of a){const r=$o(e,t,i.checkrnabam);r&&r.dnacount.ishet&&n.hetsnps.push(r)}if(n.url?n.dir=await P.d1(n.url,n.indexURL||n.url+".bai"):n.file&&(n.file=y().join(o().tpmasterdir,n.file)),n.hetsnps.length>0){await Oo(n,n.hetsnps,e,i.checkrnabam);for(const e of n.hetsnps)e.rnacount.nocoverage||e.rnacount.ref+e.rnacount.alt<i.checkrnabam.rna_mintotalreads||l.push(t+"."+e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt)}}l.length>0&&await async function(t,e){const n=await function(t){const e=y().join(o().cachedir,Math.random().toString());return new Promise(((n,r)=>{m().writeFile(e,t.join("\n")+"\n",(t=>{t&&r("cannot write"),n(e)}))}))}(t),r=await Do(n);await function(t,e){return new Promise(((n,r)=>{m().readFile(t,"utf8",((t,o)=>{if(t&&r("cannot read binom pvalue"),o){for(const t of o.trim().split("\n")){const n=t.split("\t"),r=n[0].split("."),o=e[r[0]];if(!o)continue;const i=o.hetsnps.find((t=>t.pos+"."+t.ref+"."+t.alt==r[1]+"."+r[2]+"."+r[3]));i&&(i.rnacount.pvalue=Number.parseFloat(n[10]))}n()}else n()}))}))}(r,e),m().unlink(n,(()=>{})),m().unlink(r,(()=>{}))}(l,i.checkrnabam.samples),s.checkrnabam=[];for(const n in i.checkrnabam.samples){const r=i.checkrnabam.samples[n],o=[];for(const[n,s]of t){const t={gene:n,chr:e,start:s.start,stop:s.stop},a=r.hetsnps.filter((t=>t.pos>=s.start&&t.pos<=s.stop)),l=a.filter((t=>!t.rnacount.nocoverage));if(l.length>0){const e=l.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let n=null,r=0;for(const t of l)null!=t.rnacount.pvalue&&(null==n?n=t.rnacount.pvalue:n*=t.rnacount.pvalue,t.rnacount.pvalue<=i.checkrnabam.binompvaluecutoff&&r++);null!=n&&(t.ase={markers:a.filter((t=>t.dnacount.ishet)).length,ase_markers:r,mean_delta:e/l.length,geometricmean:Math.pow(n,1/l.length)})}let c;c=r.pairedend?await Eo(r,e,s):await jo(r,e,s),t.fpkm=1e9*c/(r.totalreads*s.exonlength),t.snps=a,o.push(t)}o.length&&s.checkrnabam.push({sample:n,genes:o})}}async function jo(t,e,n){const r=["view","-c","-M",t.url||t.file];for(const o of n.exonunion)r.push((t.nochr?e.replace("chr",""):e)+":"+(o[0]+1)+"-"+(o[1]+1));let o;return await P.UE({isbam:!0,args:r,dir:t.dir,callback:t=>o=t}),Number.parseInt(o)}function Eo(t,e,n){return new Promise(((r,o)=>{const i=["view","-M",t.url||t.file];for(const r of n.exonunion)i.push((t.nochr?e.replace("chr",""):e)+":"+(r[0]+1)+"-"+(r[1]+1));const s=(0,q.spawn)(po,i,{cwd:t.dir}),a=(0,q.spawn)("cut",["-f1"],{cwd:t.dir}),l=(0,q.spawn)("sort",["-u"],{cwd:t.dir}),c=(0,q.spawn)("wc",["-l"],{cwd:t.dir});s.stdout.pipe(a.stdin),a.stdout.pipe(l.stdin),l.stdout.pipe(c.stdin);const u=[],f=[];c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("close",(()=>{r(Number.parseInt(u.join("")))}))}))}function Oo(t,e,n,r){const o=[];for(const r of e)r.rnacount={nocoverage:1},o.push((t.nochr?n.replace("chr",""):n)+":"+(r.pos+1)+"-"+(r.pos+1));return new Promise(((n,i)=>{const s=(0,q.spawn)(mo,["mpileup","--no-reference","-a","INFO/AD","-d",999999,"-r",o.join(","),"-q",r.rnapileup_q,"-Q",r.rnapileup_Q,t.url||t.file],{cwd:t.dir});O().createInterface({input:s.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Lo(t);if(!n)return;const r=e.find((t=>t.pos==n.pos));if(r){const t=n.allele2count[r.ref]||0,e=n.allele2count[r.alt]||0;t+e>0&&(r.rnacount={ref:t,alt:e,f:e/(t+e)})}})),s.on("close",(()=>{n()}))}))}function Io(t,e,n,r,o,i){e.hideLOHwithCNVoverlap&&Ro(o);const s=[];if(i){const t=new Map;for(const[e,n]of o){const r=i.sample2group.get(e);t.has(r)||t.set(r,[]),t.get(r).push({samplename:e,items:n})}if(r)for(const e of r)if(e.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){const e=i.sample2group.get(n.sampleobj.name);t.has(e)||t.set(e,[]),t.get(e).find((t=>t.samplename==n.sampleobj.name))||t.get(e).push({samplename:n.sampleobj.name,items:[]})}for(const[e,n]of t)s.push({name:e,samples:n})}else if(t.cohort&&t.cohort.annotation&&e.groupsamplebyattr){const n=new Map,i=[];for(const[r,s]of o)Po(r,s,n,i,t,e);if(r)for(const o of r)if(o.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf data: "+o.dt);else for(const r of o.sampledata)Po(r.sampleobj.name,[],n,i,t,e);for(const t of n.values())if(s.push(t),e.groupsamplebyattr.key2group){const n=e.groupsamplebyattr.key2group.get(t.name);n&&(t.sampletotalnum=n.samples.length)}i.length&&s.push({name:"Unannotated",samples:i});for(const e of s)for(const n of e.samples)t.cohort.annotation[n.samplename]&&(n.sampletype=t.cohort.annotation[n.samplename].sample_type)}else{const t=[];for(const[e,n]of o)t.push({samplename:e,items:n});if(r)for(const e of r)if(e.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){let e=!0;for(const r of t)if(r.samplename==n.sampleobj.name){e=!1;break}e&&t.push({samplename:n.sampleobj.name,items:[]})}t.length&&s.push({samples:t})}return s}function Ro(t){for(const[e,n]of t){const r=new Map,o=new Map,i=[];for(const t of n)t.dt!=F.dtloh?(t.dt==F.dtcnv&&(o.has(t.chr)||o.set(t.chr,[]),o.get(t.chr).push(t)),i.push(t)):(r.has(t.chr)||r.set(t.chr,[]),r.get(t.chr).push(t));if(0!=r.size){for(const[t,e]of r){const n=o.get(t);if(n)for(const t of e){let e=!0;for(const r of n)if(Math.max(t.start,r.start)<Math.min(t.stop,r.stop)){e=!1;break}e&&i.push(t)}else for(const t of e)i.push(t)}t.set(e,i)}}}function Po(t,e,n,r,o,i){const s=o.cohort.annotation[t];if(!s)return void r.push({samplename:t,items:e});const a=s[i.groupsamplebyattr.attrlst[0].k];if(null==a)return void r.push({samplename:t,items:e});const l=[];for(let t=1;t<i.groupsamplebyattr.attrlst.length;t++){const e=s[i.groupsamplebyattr.attrlst[t].k];if(null==e)break;l.push(e)}l.unshift(a);const c=l.join(i.groupsamplebyattr.attrnamespacer);if(!n.has(c)){const t=[];for(const e of i.groupsamplebyattr.attrlst){const n=s[e.k];if(null==n)break;const r={k:e.k,kvalue:n};e.full&&(r.full=e.full,r.fullvalue=s[e.full]),t.push(r)}const e=[];for(const t of i.groupsamplebyattr.attrlst){const n=s[t.k];if(null==n)break;const r=(t.full?s[t.full]:null)||n;e.push(r)}n.set(c,{name:c,samples:[],attributes:t})}let u=!0;for(const r of n.get(c).samples)if(r.samplename==t){for(const t of e)r.items.push(t);u=!1;break}u&&n.get(c).samples.push({samplename:t,items:e})}function Fo(t){return Number.isFinite(t.dna_mintotalreads)?Number.isFinite(t.rna_mintotalreads)?Number.isFinite(t.hetsnp_minbaf)?Number.isFinite(t.hetsnp_maxbaf)?Number.isFinite(t.rnapileup_q)?Number.isFinite(t.rnapileup_Q)?void 0:"invalid value for rnapileup_Q":"invalid value for rnapileup_q":"invalid value for hetsnp_maxbaf":"invalid value for hetsnp_minbaf":"invalid value for rna_mintotalreads":"invalid value for dna_mintotalreads"}function Do(t){const e=t+".pvalue";return new Promise(((n,r)=>{const i=(0,q.spawn)("Rscript",[y().join(o().binpath,"utils/binom.R"),t,e]);i.on("close",(()=>{n(e)})),i.on("error",(t=>{r(`cannot do binom test: ${t}`)})),i.stderr.on("data",(t=>{r(`cannot do binom test: ${t}`)}))}))}function Lo(t){const e=t.split("\t");if(e.length<8)return;const n={pos:Number.parseInt(e[1])-1},r=[e[3],...e[4].split(",")],o={};for(const t of e[7].split(";")){const e=t.split("=");o[e[0]]=e[1]}if(o.DP&&(n.DP=Number.parseInt(o.DP)),o.AD){n.allele2count={};const t=o.AD.split(",");for(const[e,o]of r.entries())n.allele2count[o]=Number.parseInt(t[e])}return n}function $o(t,e,n){const r=t.sampledata.find((t=>t.sampleobj.name==e));if(r){if(r.AD){const e=r.AD[t.ref]||0,o=r.AD[t.alt]||0,i={chr:t.chr,pos:t.pos,ref:t.ref,alt:t.alt,dnacount:{ref:e,alt:o}};return i.dnacount.f=o+e==0?0:o/(o+e),e+o>=n.dna_mintotalreads&&i.dnacount.f>=n.hetsnp_minbaf&&i.dnacount.f<=n.hetsnp_maxbaf&&(i.dnacount.ishet=!0),i}return null}}async function Zo(t,e,n,r,i){const s=await zo(y().join(o().tpmasterdir,e.file),n+":"+r+"-"+i),a=new Map;if(s)for(const t of s){const e=t.split("\t"),n=JSON.parse(e[3]),r=Number.parseInt(e[1]),o=Number.parseInt(e[2]);if(a.has(n.name)){const t=a.get(n.name);t.start=Math.min(t.start,r),t.stop=Math.max(t.stop,o)}else a.set(n.name,{gene:n.name,start:r,stop:o,exonunion:[]});const i=a.get(n.name);if(n.exon)for(const t of n.exon){const e=i.exonunion.find((e=>Math.max(e[0],t[0])<Math.min(e[1],t[1])));e?(e[0]=Math.min(t[0],e[0]),e[1]=Math.max(t[1],e[1])):i.exonunion.push([t[0],t[1]])}}for(const[t,e]of a)e.exonlength=e.exonunion.reduce(((t,e)=>t+e[1]-e[0]),0);return a}async function zo(t,e,n){return new Promise(((r,o)=>{const i=(0,q.spawn)(ho,[t,e],{cwd:n}),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(()=>{const t=a.join("");t&&o(t);const e=s.join("").trim();e||r(),r(e.split("\n"))}))}))}function Uo(t,e){return new Promise(((n,r)=>{const o=(0,q.spawn)(ho,["-H",t],{cwd:e}),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(()=>{const t=s.join("");t&&r(t);const e=i.join("").trim();e||r("cannot list vcf meta lines"),n(e.split("\n"))}))}))}function Bo(t,e){const n=e.findIndex((e=>e.value>=t));return-1==n||n==e.length-1?100:0==n?0:Math.ceil(100*n/e.length)}function Go(t,e,n){if(!t.key)return[".key missing"];if(!e.cohort)return["ds.cohort missing"];if(!e.cohort.annotation)return["ds.cohort.annotation missing"];return[null,Promise.resolve().then((()=>{const r=[];for(const o in e.cohort.annotation){if(n&&!n.has(o))continue;const i=e.cohort.annotation[o][t.key];null!=i&&r.push({sample:o,value:i})}return{id:t.id,items:r}}))]}function Jo(t,e,n,r){if(!t.genename)return["genename missing"];const i=t.genename.toLowerCase();if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["gene feature too long (> 10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((s,a)=>{const l=[],c=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:c.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.gene&&n.gene.toLowerCase()==i&&n.sample&&(r&&!r.has(n.sample)||l.push(n))}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(e=>{const n=u.join("");!n||co(n)?s({id:t.id,items:l}):a(n)}))}))))]}function Wo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);o.dt==F.dtcnv&&(t.valuecutoff&&Math.abs(o.value)<t.valuecutoff||(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.focalsizelimit&&o.stop-o.start>=t.focalsizelimit||o.sample&&(r&&!r.has(o.sample)||a.push(o))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Ho(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);o.dt==F.dtloh&&(t.valuecutoff&&o.segmean<t.valuecutoff||(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.focalsizelimit&&o.stop-o.start>=t.focalsizelimit||o.sample&&(r&&!r.has(o.sample)||a.push(o))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Vo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt==F.dtitd&&(n.chr=e[0],n.start=Number.parseInt(e[1]),n.stop=Number.parseInt(e[2]),n.sample&&(r&&!r.has(n.sample)||a.push(n)))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Yo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt!=F.dtsv&&n.dt!=F.dtfusionrna||n.sample&&(r&&!r.has(n.sample)||(n._chr=e[0],n._pos=Number.parseInt(e[1]),n.chrA?(n.chrB=n._chr,n.posB=n._pos):(n.chrA=n._chr,n.posA=n._pos),a.push(n)))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Ko(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);if(o.sample&&(!r||r.has(o.sample))){if(o.dt==F.dtsv||o.dt==F.dtfusionrna){if(o.dt==F.dtsv&&t.sv&&t.sv.hidden)return;if(o.dt==F.dtfusionrna&&t.fusion&&t.fusion.hidden)return;o._chr=n[0],o._pos=Number.parseInt(n[1]),o.chrA?(o.chrB=o._chr,o.posB=o._pos):(o.chrA=o._chr,o.posA=o._pos)}else if(o.dt==F.dtcnv){if(t.cnv&&t.cnv.hidden)return;if(t.cnv&&t.cnv.valuecutoff&&Math.abs(o.value)<t.cnv.valuecutoff)return;if(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.cnv&&t.cnv.focalsizelimit&&o.stop-o.start>=t.cnv.focalsizelimit)return}else if(o.dt==F.dtloh){if(t.loh&&t.loh.hidden)return;if(t.loh&&t.loh.valuecutoff&&o.segmean<t.loh.valuecutoff)return;if(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.loh&&t.loh.focalsizelimit&&o.stop-o.start>=t.loh.focalsizelimit)return}else{if(o.dt!=F.dtitd)return void console.error("unknown datatype",o.dt);if(t.itd&&t.itd.hidden)return;o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2])}a.push(o)}}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const r=c.join("");if(r&&!co(r))return void s(r);const o=new Map;for(const t of a)o.has(t.sample)||o.set(t.sample,[]),o.get(t.sample).push(t);n.hideLOHwithCNVoverlap&&Ro(o);const l=[];for(const[t,e]of o)for(const t of e)l.push(t);i({id:t.id,items:l})}))}))))]}function Xo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];const o=[];for(const i of n)if(i.type==F.tkt.mdsvcf){const[n,s]=Qo(t,e,i,r);if(n)return[n];o.push(s)}else{if(i.type!=F.tkt.mdssvcnv)return["unsupported track type: "+i.type];{const[e,n]=Ko(t,0,i,r);if(e)return[e];o.push(n)}}return[null,Promise.all(o).then((t=>{const e=[];for(const n of t)for(const t of n.items)e.push(t);return{id:t[0].id,items:e}}))]}function Qo(t,e,n,r){if(!n.tracks)return"tracks[] missing from dsquery";if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>3e6)return["look range too big (>3Mb)"];const i=[];for(const e of n.tracks){const s=Promise.resolve().then((()=>{if(!e.file)return P.d1(e.url,e.indexURL)})).then((i=>new Promise(((s,a)=>{const l=[],c=(0,q.spawn)(ho,[e.file?y().join(o().tpmasterdir,e.file):e.url,(e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1)],{cwd:i});O().createInterface({input:c.stdout}).on("line",(o=>{if(n.iscustom)l.push(o);else if(e.type==F.mdsvcftype.vcf){const[i,s,a]=D.S(o,{nochr:e.nochr,samples:e.samples,info:n.info,format:e.format});for(const e of s)if(e.sampledata&&(F.vcfcopymclass(e,{}),!(t.snvindel&&t.snvindel.excludeclasses&&t.snvindel.excludeclasses[e.class]))){if(r){const t=[];for(const n of e.sampledata)r.has(n.sampleobj.name)&&t.push(n);if(0==t.length)continue;e.sampledata=t}for(const t of e.sampledata)delete t.allele2readcount;delete e._m,delete e.vcf_ID,delete e.name,e.dt=F.dtsnvindel,l.push(e)}}else console.error("type not one of mdsvcftype: "+e.type)}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(t=>{const e=u.join("");!e||co(e)?s(l):a(e)}))}))));i.push(s)}return[null,Promise.all(i).then((e=>{const n=[];for(const t of e)for(const e of t)n.push(e);return{id:t.id,items:n}}))]}function ti(t){if(!t.endsWith(".gz"))return["no .gz suffix (file should be compressed by bgzip)"];const e=y().join(o().tpmasterdir,t);return m().existsSync(e)?m().existsSync(e+".tbi")||m().existsSync(e+".csi")?[null,e]:[".tbi/.csi index missing"]:[".gz file not found"]}yo.use(k()()),yo.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&(t.headers["content-type"]="application/json");try{for(const e in t.query){const n=t.query[e];("null"==n||n.startsWith('"')&&n.endsWith('"')||n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&(t.query[e]=JSON.parse(n))}}catch(t){return void e.send({error:t})}n()})),yo.use(so()()),yo.use(T().json({limit:"5mb"})),yo.use(T().text({limit:"5mb"})),yo.use(T().urlencoded({extended:!0})),yo.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&t.body&&"application/json"!=t.headers["content-type"]?e.send({error:"invalid HTTP request.header['content-type'], must be 'application/json'"}):("application/json"==t.headers["content-type"]&&(t.query||(t.query={}),Object.assign(t.query,t.body)),wo(t),bo(e),e.header("Access-Control-Allow-Origin",t.get("origin")||t.get("referrer")||t.protocol+"://"+t.get("host").split(":")[0]||"*"),e.header("Access-Control-Allow-Credentials",!0),"GET"!=t.method||t.path.includes(".")&&!t.path.endsWith("proteinpaint.js")||e.header("Cache-control",`immutable,max-age=${o().responseMaxAge||1}`),n())})),yo.catch=ro,yo.use((function(t,e,n){try{const e=t.query;for(const t in e)t in oo&&(e[t]=oo[t](e[t]));n()}catch(n){ro(t,e,n.message||n)}})),yo.use(((t,e,n,r)=>{wo(e),t&&(t&&"entity.parse.failed"==t.type?n.send({error:"invalid request body, must be a valid JSON-encoded object"}):n.send({error:t}))})),o().jwt&&(console.log("JWT is activated"),yo.use(((t,e,n)=>{let r={};t.body&&"POST"==t.method&&(r=t.body);const i=r.jwt?r.jwt:t.headers&&t.headers.authorization&&t.headers.authorization.startsWith("Bearer ")?t.headers.authorization.split(" ")[1]:null;if(!i)return e.send({error:"json web token missing"});R().verify(i,o().jwt.secret,((t,r)=>t?e.send({error:"Invalid token"}):r[o().jwt.permissioncheck]?void n():e.send({error:"Not authorized"})))}))),function(){if(!o().routeSetters)return;for(const t of o().routeSetters)if(t.endsWith(".js")){require(t)(yo,vo)}}(),$r.i.maySetAuthRoutes(yo,vo,o()),yo.get(vo+"/cardsjson",(async function(t,e){try{if(t.query.datafile&&t.query.tabixCoord)return new Promise(((n,r)=>{const i=(0,q.spawn)(ho,[y().join(o().tpmasterdir,t.query.datafile),t.query.tabixCoord]),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(t=>{""!=a.join("").trim()&&r("error querying bedj file");const o=s.join("").trim();n(e.send({file:o.split("\n")}))}))})).catch((t=>{t.stack&&console.error(t.stack)}));throw"invalid cards request"}catch(t){e.send({error:t.message||t})}})),yo.post(vo+"/mdsjsonform",(async function(t,e){if(!uo.mdsjsonform)return e.send({error:"This feature is not enabled on this server."});if(t.query.deposit){const n=Math.random().toString(),r=await function(){const t=y().join(o().cachedir,"mdsjsonform");return new Promise(((e,n)=>{m().stat(t,((r,o)=>{if(r){if("ENOENT"==r.code)return void m().mkdir(t,(r=>{r&&n("error creating dir"),e(t)}));n("error checking directory")}else o.isDirectory()?e(t):n('"mdsjsonform" exists but not directory')}))}))}(),i=y().join(r,n);return await P.Sf(i,JSON.stringify(t.query.deposit)),void e.send({id:n})}if(t.query.draw){const n=y().join(o().cachedir,"mdsjsonform",t.query.draw),r=await P.b5(n);try{const t=JSON.parse(r);e.send({json:t})}catch(t){e.send({error:"Invalid JSON"})}return}e.send({})})),yo.get(vo+"/genomes",(async function(t,e){var n;wo(t);try{await m().promises.stat(o().tpmasterdir)}catch(t){let n="Error with TP directory ("+t.code+")";const r=o().maintenance||{};if("start"in r&&"stop"in r&&r.tpMessage){const t=+new Date(r.start),e=+new Date(r.stop),o=+new Date;t<=o&&o<=e&&(n=r.tpMessage)}return void e.send({error:n})}const r={};if(t.query&&t.query.genome)r[t.query.genome]=xo(t.query.genome);else for(const t in fo)r[t]=xo(t);let i=!1;for(const t in fo)fo[t].blat&&(i=!0);e.send({genomes:r,debugmode:o().debugmode,headermessage:o().headermessage,base_zindex:o().base_zindex,codedate:ao.A.codedate,launchdate:ao.A.launchdate,hasblat:i,features:uo,dsAuth:$r.i.getDsAuth(t),commonOverrides:o().commonOverrides,targetPortal:o().targetPortal,cardsPath:null===(n=o().cards)||void 0===n?void 0:n.path})})),yo.get(vo+"/getDataset",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"unknown genome";if(!n.datasets)throw"genomeobj.datasets{} missing";let r;for(const e in n.datasets)if(e.toLowerCase()==t.query.dsname.toLowerCase()){r=n.datasets[e];break}if(!r)throw"invalid dsname";return r.isMds3?e.send({ds:tr(r)}):r.isMds?e.send({ds:qo(r)}):e.send({ds:ko(r)})}catch(t){e.send({error:t.message||t})}})),yo.all(vo+"/ntseq",(async function(t,e){try{if(!t.query.coord)throw"coord missing";const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.genomefile)throw"no sequence file available";const r=await P.Kf(n,t.query.coord);e.send({seq:r.split("\n").slice(1).join("")})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/pdomain",(function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";const r=fo[n];if(!r)throw"invalid genome "+n;if(!r.proteindomain)return e.send({lst:[]});if(!Array.isArray(t.query.isoforms))throw"isoforms[] missing";const o=[];for(const e of t.query.isoforms){if(r.genomicNameRegexp.test(e))continue;const t=r.proteindomain.getbyisoform.all(e);o.push({name:e,pdomains:t.map((t=>{const n=JSON.parse(t.data);return n.refseq=e,n}))})}e.send({lst:o})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/tkbedj",function(t){return async(e,n)=>{try{n.send(await async function(t,e){const[n,r,o]=P.ZX(t);if(n)throw n;let i,s,a,l,c;if(t.query.fileIsBigbed=await P.aS(r),t.query.getdata)t.query.getBED;else{if(i=Number(t.query.stackheight),s=Number(t.query.stackspace),a=Number(t.query.regionspace),l=Number(t.query.width),Number.isNaN(i))throw"stackheight is not integer";if(c=Math.max(10,i-2),Number.isNaN(s))throw"stackspace is not integer";if(Number.isNaN(a))throw"regionspace is not integer";if(Number.isNaN(l))throw"width is not a number"}if(t.query.usevalue){if(!t.query.usevalue.key)throw".key missing from .usevalue";if(t.query.usevalue.dropBelowCutoff&&(t.query.usevalue.dropBelowCutoff=Number(t.query.usevalue.dropBelowCutoff),Number.isNaN(t.query.usevalue.dropBelowCutoff)))throw".usevalue.dropBelowCutoff is not number"}if(t.query.bplengthUpperLimit&&(t.query.bplengthUpperLimit=Number(t.query.bplengthUpperLimit),Number.isNaN(t.query.bplengthUpperLimit)))throw"bplengthUpperLimit not number";if(!t.query.rglst)throw"no rglst[]";if(!Array.isArray(t.query.rglst))throw"rglst is not an array";if(0==t.query.rglst.length)throw"empty rglst";for(const e of t.query.rglst)e.reverse?e.scale=t=>Math.ceil(e.width*(e.stop-t)/(e.stop-e.start)):e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start));const u=t.query.color||"#3D7A4B",f=t.query.gmregion||null,d=t.query.isoform,h=t.query.onerow,p=t.query.categories||null,m=t.query.__isgene;let g;!t.query.fileIsBigbed&&o&&(g=await P.d1(r,t.query.indexURL));const y=await async function(t,e,n,r,o){let i;if(r){const s=[];if(t.fileIsBigbed){const n=await P.z5(e,r.chr,r.start,r.stop);for(const e of n){const n=e.split("\t"),r=fn(n);r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&s.push(r)}}else await P.UE({args:[e,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:e=>{const n=e.split("\t");let r={};if(t.getBED)r.rest=n.slice(3);else if(n[3])try{r=JSON.parse(n[3])}catch(t){return void(i=e)}if(!r.isoformonly||r.isoformonly==o){r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&s.push(r)}}});if(i)throw"Line with invalid JSON: "+i;return[s]}const s=[];for(const[r,o]of t.rglst.entries()){const a=[];if(t.fileIsBigbed){const t=await P.z5(e,o.chr,o.start,o.stop);for(const e of t){const t=e.split("\t"),n=fn(t);n.chr=t[0],n.start=Number(t[1]),n.stop=Number(t[2]),n.rglst=[{idx:r}],a.push(n)}}else await P.UE({args:[e,o.chr+":"+o.start+"-"+o.stop],dir:n,callback:e=>{const n=e.split("\t");let o={};if(t.getBED)o.rest=n.slice(3);else if(n[3])try{o=JSON.parse(n[3])}catch(t){return void(i=e)}o.chr=n[0],o.start=Number(n[1]),o.stop=Number(n[2]),o.rglst=[{idx:r}],a.push(o)}});s.push(a)}if(i)throw"Line with invalid JSON: "+i;return s}(t.query,r,g,f,d);let v;t.query.filterByName&&(v=new Set(t.query.filterByName.split(/[\s\n]/).map((t=>t.trim()))));const b=[];for(const e of y)for(const n of e){if(t.query.usevalue){const e=n[t.query.usevalue.key];if(!Number.isFinite(e))continue;if(t.query.usevalue.dropBelowCutoff&&e<t.query.usevalue.dropBelowCutoff)continue}if(!(t.query.bplengthUpperLimit&&n.stop-n.start>t.query.bplengthUpperLimit)){if(v)if(n.isoform){if(!v.has(n.isoform))continue}else{if(!n.name)continue;if(!v.has(n.name))continue}b.push(n)}}if(t.query.getdata)return{items:b};if(0==b.length){const e=(0,S.createCanvas)(l*t.query.devicePixelRatio,i*t.query.devicePixelRatio),n=e.getContext("2d");return t.query.devicePixelRatio>1&&n.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),n.font=i+"px Arial",n.fillStyle="#aaa",n.textAlign="center",n.textBaseline="middle",n.fillText("No data in view range",l/2,i/2),{src:e.toDataURL(),height:i}}const w=Math.ceil(i/4)-1;if(h||b.length>=mn){const e=b.length<200,n=(0,S.createCanvas)(l*t.query.devicePixelRatio,i*t.query.devicePixelRatio),r=n.getContext("2d");t.query.devicePixelRatio>1&&r.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);const o=b.length<=200?[]:null;for(const n of b){const s=p&&n.category&&p[n.category]?p[n.category].color:n.color||u;r.fillStyle=s;for(const s of n.rglst){let l=0;for(let e=0;e<s.idx;e++)l+=t.query.rglst[e].width+a;const c=t.query.rglst[s.idx],u=[];n.utr5&&u.push(...n.utr5),n.utr3&&u.push(...n.utr3),!n.exon||n.coding&&0!=n.coding.length||u.push(...n.exon);for(const t of u){const e=Math.max(c.start,t[0]),s=Math.min(c.stop,t[1]),a=l+c.scale(c.reverse?s:e),u=l+c.scale(c.reverse?e:s);r.fillRect(a,w,Math.max(1,u-a),i-2*w),xn(o,a,u,1,n)}const f=[];n.exon?n.coding&&n.coding.length>0&&f.push(...n.coding):f.push([n.start,n.stop]);for(const t of f){const s=Math.max(c.start,t[0]),a=Math.min(c.stop,t[1]),u=l+c.scale(c.reverse?a:s),f=l+c.scale(c.reverse?s:a);r.fillRect(u,0,Math.max(1,f-u),i),xn(o,u,f,1,n),n.strand&&e&&(r.strokeStyle="white",kn(r,n.strand,u,w,f-u,i-2*w))}}}return{src:n.toDataURL(),height:i,mapisoform:o}}if(t.query.hideItemNames)for(const t of b)delete t.name;let _=null;if(m&&b.length<gn){_=[];for(const t of b){const e={};for(const n in t)"canvas"!=n&&"rglst"!=n&&(e[n]=t[n]);_.push(e)}}const x=t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0),k=t.query.translatecoding&&x<3*l;let q;if(k){if(!t.query.genome)throw"genome missing for translating genes";if(q=e[t.query.genome],!q)throw"invalid genome"}const N=[],A=(0,S.createCanvas)(10,10);let M=A.getContext("2d");t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial";const T=b.length<pn,C=b.length<pn?[]:null;let j=!1;f&&(j=f.reverse);for(const e of t.query.rglst)e.reverse&&(j=!0);b.sort(((t,e)=>j?t.stop==e.stop?t.start-e.start:e.stop-t.stop:t.start==e.start?e.stop-t.stop:t.start-e.start));const E=b.some((t=>t.exon)),O=[0];let I=1,R=null;for(const e of b){let n=null,r=null;for(const o of e.rglst){let i=0;for(let e=0;e<o.idx;e++)i+=t.query.rglst[e].width+a;const s=t.query.rglst[o.idx],l=Math.max(e.start,s.start),c=Math.min(e.stop,s.stop);if(l<c){const t=i+s.scale(s.reverse?c:l),e=i+s.scale(s.reverse?l:c);null==n?(n=t,r=e):(n=Math.min(n,t),r=Math.max(r,e))}}if(null==n)continue;e.canvas={start:n,stop:r,stranded:null!=e.strand},e.coding&&k&&(e.willtranslate=!0,N.push(e));let o=n,i=r;if(T){const t=e.name;if(t){e.canvas.namestr=t;const n=M.measureText(t).width;e.canvas.namewidth=n,E?e.canvas.start>=n+dn?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+dn<=l?(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):n>e.canvas.stop-e.canvas.start?e.canvas.start>l-e.canvas.stop?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):(e.canvas.namehover=!0,e.canvas.textalign="left"):Math.min(l,e.canvas.stop)-Math.max(0,e.canvas.start)>=n+2*hn?e.canvas.namein=!0:e.canvas.start>=n+dn?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+dn<=l?(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):e.canvas.namein=!0}}e.canvas.stop-e.canvas.start>.3*l&&(R=[]);for(let t=1;t<=I;t++)if(null==O[t]||O[t]<o){e.canvas.stack=t,O[t]=i;break}null==e.canvas.stack&&(I++,O[I]=i,e.canvas.stack=I),xn(C,o,i,e.canvas.stack,e)}A.width=l*t.query.devicePixelRatio;const D=(i+s)*I-s;A.height=D*t.query.devicePixelRatio,M=A.getContext("2d"),t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial",M.textBaseline="middle",M.lineWidth=1;for(const e of b){const n=e.canvas;if(!n)continue;const r=p&&e.category&&p[e.category]?p[e.category].color:e.color||u,o=(i+s)*(n.stack-1);M.fillStyle=r,(e.exon||e.rglst.length>1)&&(M.strokeStyle=r,M.beginPath(),M.moveTo(n.start,Math.floor(o+i/2)+.5),M.lineTo(n.stop,Math.floor(o+i/2)+.5),M.stroke());for(const s of e.rglst){let l=0;for(let e=0;e<s.idx;e++)l+=t.query.rglst[e].width+a;const c=t.query.rglst[s.idx],u=[];e.utr3&&u.push(...e.utr3),e.utr5&&u.push(...e.utr5),!e.exon||e.coding&&0!=e.coding.length||u.push(...e.exon);for(const t of u){const n=Math.max(t[0],c.start),s=Math.min(t[1],c.stop);if(n<s){if(e.exon2color)for(const t of e.exon2color)if(n>=t.start&&s<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?s:n),a=l+c.scale(c.reverse?n:s);M.fillRect(t,o+w,Math.max(1,a-t),i-2*w),e.exon2color&&(M.fillStyle=r)}}const f=[];e.exon?e.coding&&e.coding.length>0&&f.push(...e.coding):f.push([e.start,e.stop]);let d=e.strand;n.stranded&&c.reverse&&(d="+"==e.strand?"-":"+");for(const t of f){const s=Math.max(t[0],c.start),a=Math.min(t[1],c.stop);if(s<a){if(e.exon2color)for(const t of e.exon2color)if(s>=t.start&&a<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?a:s),u=l+c.scale(c.reverse?s:a);if(M.fillRect(t,o,Math.max(1,u-t),i),e.exon2color&&(M.fillStyle=r),n.stranded&&!e.willtranslate)if(M.strokeStyle="white",n.namein){const e=(u-t-n.namewidth)/2;kn(M,d,t,o+w,e,i-2*w),kn(M,d,t+e+n.namewidth,o+w,e,i-2*w)}else kn(M,d,t,o+w,u-t,i-2*w)}}if(n.stranded&&e.intron){M.strokeStyle=r;for(const t of e.intron){const e=Math.max(t[0],c.start),n=Math.min(t[1],c.stop);if(e<n){const t=l+c.scale(c.reverse?n:e);kn(M,d,t,o+w,l+c.scale(c.reverse?e:n)-t,i-2*w)}}}if(R&&e.exon){for(let t=0;t<e.exon.length;t++){const r=e.exon[t];if(r[1]<=c.start||r[0]>=c.stop)continue;const o=Math.max(r[0],c.start),i=Math.min(r[1],c.stop);if(o<i){const s=l+c.scale(c.reverse?i:o),a=l+c.scale(c.reverse?o:i);R.push({chr:e.chr,start:Math.min(r[0],r[1]),stop:Math.max(r[0],r[1]),x1:s,x2:a,y:n.stack,name:"Exon "+(t+1)+"/"+e.exon.length})}}for(let t=1;t<e.exon.length;t++){const r=e.exon["+"==e.strand?t-1:t][1],o=e.exon["+"==e.strand?t:t-1][0];if(o<=c.start||r>=c.stop)continue;const i=Math.max(r,c.start),s=Math.min(o,c.stop);if(i<s){const a=l+c.scale(c.reverse?s:i),u=l+c.scale(c.reverse?i:s);if(u<0)continue;R.push({chr:e.chr,start:r,stop:o,x1:a,x2:u,y:n.stack,name:"Intron "+t+"/"+(e.exon.length-1)})}}}}if(null!=n.namestart)M.textAlign=n.textalign,M.fillStyle=r,M.fillText(n.namestr,n.namestart,o+i/2);else if(n.namehover&&!t.query.noNameHover){const t=Math.max(10,n.start+10);M.fillStyle="white",M.fillRect(t,o,n.namewidth+10,i),M.strokeStyle=r,M.strokeRect(t+1.5,o+.5,n.namewidth+10-3,i-2),M.fillStyle=r,M.textAlign="center",M.fillText(n.namestr,t+n.namewidth/2+5,o+i/2)}else n.namein&&(M.textAlign="center",M.fillStyle="white",M.fillText(n.namestr,(Math.max(0,n.start)+Math.min(l,n.stop))/2,o+i/2))}const L={height:D,mapisoform:C,mapexon:R,returngmdata:_};if(0==N.length)return L.src=A.toDataURL(),L;const $=[];M.textAlign="center",M.textBaseline="middle";for(const[e,n]of N.entries()){const e=p&&n.category&&p[n.category]?p[n.category].color:n.color||u,r=n.canvas,o=(i+s)*(r.stack-1);n.genomicseq=(await P.Kf(q,n.chr+":"+(n.start+1)+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase();const l=(0,F.nt2aa)(n);for(const e of n.rglst){const s=t.query.rglst[e.idx];let c=0;for(let n=0;n<e.idx;n++)c+=t.query.rglst[n].width+a;const u=s.width/(s.stop-s.start),f=Math.min(i,3*u),d=f<8?null:f;let h=!1;r.stranded&&"-"==n.strand&&(h=!0);let p=0;d&&(M.font=d+"px Arial");for(const[t,e]of n.coding.entries()){let[r,a]=e;if(h){if(r>=s.stop){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(a<=s.start)break}else{if(a<=s.start){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(r>=s.stop)break}if(0==t&&n.startCodonFrame){h?a-=3-n.startCodonFrame:r+=3-n.startCodonFrame;let t=Math.max(e[0],s.start),l=Math.min(e[1],s.stop);if(h?t=Math.max(a,s.start):l=Math.min(r,s.stop),t<l){M.fillStyle=_n;const e=c+s.scale(s.reverse?l:t),n=c+s.scale(s.reverse?t:l);M.fillRect(e,o,Math.max(1,n-e),i)}}const f=Math.max(s.start,r),m=Math.min(s.stop,a);p+=h?a-m:f-r;let g=0;for(let t=0;t<m-f;t++){let e;if(p++,g++,p%3==0)e=p/3-1;else{if(t<m-f-1)continue;e=Math.floor(p/3)}let r=l[e],a=Math.ceil(p/3)%2==0?yn:null;r?"M"==r?a=bn:"*"==r&&(a=wn):(r=4,a=vn);let y,v=u*g;if(h){const e=m-1-t;y=c+s.scale(e)}else{const e=f+t+1-g;y=c+s.scale(e)}s.reverse&&(y-=v),g=0,y>=c&&y<=c+s.width&&(a&&(M.fillStyle=a,M.fillRect(y,o,v,i)),d&&(M.fillStyle="white",M.fillText(r,y+v/2,o+i/2)),$.push({x1:y,x2:y+v,y:n.canvas.stack,name:r+(e+1)+' <span style="font-size:.7em;color:#858585">AA residue</span>'}))}}}if(r.namehover&&!t.query.noNameHover){M.font="bold "+c+"px Arial";const t=Math.max(10,r.start+10);M.fillStyle="white",M.fillRect(t,o,r.namewidth+10,i),M.strokeStyle=e,M.strokeRect(t+1.5,o+.5,r.namewidth+10-3,i-2),M.fillStyle=e,M.fillText(r.namestr,t+r.namewidth/2+5,o+i/2)}}return L.src=A.toDataURL(),L.mapaa=$,L}(e,t))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/tkbedgraphdot",function(t){return async(e,n)=>{try{const r=e.query,i=t[r.genome];if(!i)throw"unknown genome";let s=null;if(r.file)r.file=y().join(o().tpmasterdir,r.file);else{if(!r.url)throw"file or url missing";s=await P.d1(r.url,r.indexURL)}const a=await P.Jy(r.file||r.url,s,i),l=await st(r,s,a);n.send(l)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.all(vo+"/tkbam",function(t){return async(e,n)=>{try{if(delete e.query.isFileSlice,e.query.gdcFileUUID){const t=e.cookies.sessionid,r=e.get("X-Auth-Token");if(!r&&!t)throw"GDC token or sessionid missing";if(await Tt(e.query.gdcFileUUID,r,t),e.query.stream2download)return void await async function(t,e,n,r,o){const i={compression:!1};r?i.Cookie=`sessionid=${r}`:i["X-Auth-Token"]=o;const s=y().join(Ce,"/slicing/view/",n+"?region="+e);t.statusCode=200,await Et(b().stream(s,{method:"get",headers:i}),t)}(n,e.query.gdcFilePosition,e.query.gdcFileUUID,e.cookies.sessionid,e.get("X-Auth-Token"));e.query.file=tn(e),e.query.isFileSlice=!0}if(e.query.downloadgdc)return void n.send(await en(e));if(e.query.clientdownloadgdcslice){if(!e.query.file||!e.query.isFileSlice)throw"invalid query";const t=y().join(o().cachedir_bam,e.query.file),r=await m().promises.readFile(t);return n.writeHead(200,{"Content-Type":"application/octet-stream","Content-Disposition":"attachment; filename=gdc.bam","Content-Length":r.length}),void n.end(Buffer.from(r,"binary"))}if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(e.query.getread)return void n.send(await async function(t,e){if(!e.query.chr)throw".chr missing";if(!e.query.qname)throw".qname missing";if(e.query.qname=decodeURIComponent(e.query.qname),!e.query.start)throw".start missing";if(!e.query.stop)throw".stop missing";const n={chr:e.query.chr,start:Number(e.query.start),stop:Number(e.query.stop),scale:()=>{},ntwidth:10};if(!Number.isInteger(n.start))throw".start not integer";if(!Number.isInteger(n.stop))throw".stop not integer";const r=await async function(t,e){let n,r,i,s,a,l,c,u,f;if(t.query.isFileSlice)a=y().join(o().cachedir_bam,t.query.file),await Ie(t,a);else{if([s,a,l]=P.ZX(t),s)throw s;i=l?await P.d1(a,t.query.indexURL||a+".bai"):null}if(t.query.unknownorder&&(c=Number(t.query.readstart),u=Number(t.query.readstop),Number.isNaN(c)||Number.isNaN(u)))throw"readstart/stop not provided for read with unknown order";if(await P.UE({isbam:!0,args:["view",a,(t.query.nochr?t.query.chr.replace("chr",""):t.query.chr)+":"+e.start+"-"+e.stop],dir:i,callback:(o,i)=>{if(o.split("\t")[0]!=t.query.qname)return;const s=Ze({sam_info:o,keepallboxes:!0,keepmatepos:!0,keepunmappedread:!0},e);if(s&&(!t.query.show_unmapped||!s.discord_unmapped2))if(t.query.show_unmapped&&t.query.getfirst){if(s.islast)return i.kill(),void(f=[s])}else if(t.query.show_unmapped&&t.query.getlast){if(s.isfirst)return i.kill(),void(f=[s])}else if(t.query.getfirst){if(s.isfirst)return i.kill(),void(f=[s])}else if(t.query.getlast){if(s.islast)return i.kill(),void(f=[s])}else if(t.query.unknownorder){if(s.segstart==c&&s.segstop==u)return i.kill(),void(f=[s])}else if(s.isfirst?n=s:s.islast&&(r=s),n&&r)return i.kill(),void(f=[n,r])}}),f){if(t.query.altseqs){const e={query_seq:f[0].seq,refseqs:t.query.refseqs,altseqs:t.query.altseqs,cigar_seq:f[0].cigarstr,start_position:f[0].segstart,ref_positions:t.query.ref_positions,refalleles:t.query.refalleles,altalleles:t.query.altalleles},n=(await(0,Q.run_rust)("align",JSON.stringify(e))).split("\n");let r;for(let t of n)t.includes("Final_output:")?r=JSON.parse(t.replace("Final_output:","")):console.log(t);f.alignments=r}return f}f=[],n&&f.push(n);r&&f.push(r);return f.length?f:null}(e,n);if(!r){if(e.query.show_unmapped)throw"mate not found";throw"read not found"}const i=[];for(const n of r)n.discord_unmapped1?i.push(await Xe(n,t,e.query)):i.push(await Qe(n,t,e.query));r.alignments&&(i[0].alignments=r.alignments);return{lst:i}}(r,e));const i=o().debugmode?new Date:null,s=await async function(t,e){let n;if(e.query.isFileSlice)n={genome:t,file:y().join(o().cachedir_bam,e.query.file),asPaired:e.query.asPaired,getcolorscale:e.query.getcolorscale,devicePixelRatio:e.query.devicePixelRatio?Number(e.query.devicePixelRatio):1},await Ie(e,n.file);else{const[r,o,i]=P.ZX(e);if(r)throw r;n={genome:t,file:o,asPaired:e.query.asPaired,getcolorscale:e.query.getcolorscale,devicePixelRatio:e.query.devicePixelRatio?Number(e.query.devicePixelRatio):1},i&&(n.dir=await P.d1(o,e.query.indexURL||o+".bai"))}if(e.query.pileupheight&&(n.pileupheight=Number(e.query.pileupheight),Number.isNaN(n.pileupheight)))throw".pileupheight is not integer";e.query.drop_pcrduplicates&&(n.drop_pcrduplicates=!0);if(e.query.variant){n.diff_score_plotwidth=Number(e.query.diff_score_plotwidth),e.query.max_diff_score&&(n.max_diff_score=Number(e.query.max_diff_score),n.min_diff_score=Number(e.query.min_diff_score));const t=e.query.variant.split(".");if(n.strictness=e.query.strictness,!Number.isInteger(t.length%4))throw"invalid variant, not chr.pos.ref.alt";n.alleleAlreadyUpdated=e.query.alleleAlreadyUpdated,n.alleleAlreadyUpdated&&(n.altseqs=e.query.altseqs,n.refseqs=e.query.refseqs,n.altalleles=e.query.altalleles,n.refalleles=e.query.refalleles,n.leftflankseqs=e.query.leftflankseqs,n.rightflankseqs=e.query.rightflankseqs,n.ref_positions=e.query.ref_positions);const r=t.length/4,o=[];for(let e=0;e<r;e++)o.push({chr:t[4*e],pos:Number(t[4*e+1]),ref:t[4*e+2],alt:t[4*e+3]});if(n.variant=o,e.query.alignOneGroup&&(n.alignOneGroup=e.query.alignOneGroup),Number.isNaN(n.variant.pos))throw"variant pos not integer"}else if(e.query.sv){const t=e.query.sv.split(".");if(t.length<6)throw"invalid sv, not chrA.posA.chrB.posB";if(n.sv={chrA:t[0],startA:Number(t[1]),strandA:Number(t[2]),chrB:t[3],startB:Number(t[4]),strandB:Number(t[5])},Number.isNaN(n.sv.startA))throw"sv.startA not integer";if(Number.isNaN(n.sv.startB))throw"sv.startB not integer"}if(Number.isFinite(Number(e.query.stackstart))){if(!e.query.stackstop)throw".stackstop missing";if(n.partstack={start:Number(e.query.stackstart),stop:Number(e.query.stackstop)},Number.isNaN(n.partstack.start))throw".stackstart not integer";if(Number.isNaN(n.partstack.stop))throw".stackstop not integer";if(!e.query.grouptype)throw".grouptype required for partstack";n.grouptype=e.query.grouptype}e.query.gdc||(e.query.nochr?n.nochr="string"==typeof e.query.nochr?JSON.parse(e.query.nochr):e.query.nochr:n.nochr=await P.Dp(n.file,t,n.dir));if(n.regions=e.query.regions,!Array.isArray(n.regions)||0==n.regions.length)throw"q.regions[] not non-empty array";let r=0;for(const t of n.regions){if(!t.chr)throw".chr missing from a region";if(!Number.isInteger(t.start))throw".start not integer of a region";if(!Number.isInteger(t.stop))throw".stop not integer of a region";t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start)),t.ntwidth=t.width/(t.stop-t.start),r=Math.max(r,t.ntwidth)}return n.stacksegspacing=Math.max(xe,ke*r),n.readcount_skipped=0,n}(r,e);n.send(await async function(t){await async function(t){if(t.variant){let e=0,n=0,r=0,o=t.variant[0].pos,i=t.variant[0].pos+Math.max(t.variant[0].ref.length,t.variant[0].alt.length);for(const s of t.variant){const t=Math.abs(s.pos-Math.max(s.ref.length,s.alt.length));t>e&&(e=t,n=r),o>s.pos&&(o=s.pos),i<s.pos+Math.max(s.ref.length,s.alt.length)&&(i=s.pos+Math.max(s.ref.length,s.alt.length)),r+=1}e=Math.floor(1.5*Math.max(t.variant[n].ref.length,t.variant[n].alt.length));const s={chr:t.variant[0].chr,start:o-e,stop:i+e};return await Pe(t,[s]),await Fe(s,t),void(t.regions[0].lines=s.lines)}await Pe(t,t.regions);for(const e of t.regions)await Fe(e,t)}(t),t.totalnumreads=t.regions.reduce(((t,e)=>t+e.lines.length),0);const e={nochr:t.nochr,count:{r:t.totalnumreads},groups:[]};t.read_limit_reached&&(e.count.read_limit_reached=t.read_limit_reached);t.canvaswidth=t.regions[t.regions.length-1].x+t.regions[t.regions.length-1].width;{const n=await async function(t){const e=[],n=[];let r=0;for(const o of t.regions){for(const t of o.lines)e.push({sam_info:t,tempscore:""});r=o.x+o.width,n.push(r)}if(0==e.length)return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]};if(t.variant){if(1==t.regions.length)return await async function(t,e,n){const r=t.regions[0].lines[0].split("\t")[9].length;let o=!1,i=[],s=[],a=[],l=[],c=[],u=[],f=[];if(t.alleleAlreadyUpdated)i=t.leftflankseqs,s=t.rightflankseqs,u=t.refseqs,f=t.altseqs,a=t.refalleles,l=t.altalleles,c=t.ref_positions,0!=u[0].toUpperCase().localeCompare((i[0]+a[0]+s[0]).toUpperCase())&&(console.log("Reference allele is not correct for variant 0"),o=!0);else{let e,n,o=0;for(const i of t.variant){let s="",u="";if(!(0!=i.ref.length&&"-"!=i.ref||"-"!=i.alt&&0!=i.alt.length))throw"Both Ref and Alt alleles are missing";if(0==i.ref.length||"-"==i.ref)s=(await P.Kf(t.genome,i.chr+":"+i.pos+"-"+i.pos)).split("\n").slice(1).join("").toUpperCase(),u=s+i.alt,i.pos-=1;else if("-"==i.alt||0==i.alt.length){const e=(await P.Kf(t.genome,i.chr+":"+i.pos+"-"+i.pos)).split("\n").slice(1).join("").toUpperCase();s=e+i.ref,u=e,i.pos-=1}else u=i.alt,s=i.ref;const f=i.pos,d=s.toUpperCase(),h=u.toUpperCase();0==o?(e=f-r,n=f+s.length+1+r):(f-r<e&&(e=f-r),f+s.length+1+r>n&&(n=f+s.length+1+r)),a.push(d),l.push(h),c.push(f),o+=1}o=0;for(const r of t.variant){const d=(await P.Kf(t.genome,r.chr+":"+e+"-"+c[o])).split("\n").slice(1).join("").toUpperCase(),h=(await P.Kf(t.genome,r.chr+":"+(c[o]+a[o].length+1)+"-"+n)).split("\n").slice(1).join("").toUpperCase(),p=d+a[o]+h,m=d+l[o]+h;console.log(r.chr+"."+c[o]+"."+a[o]+"."+l[o]),o+=1,i.push(d),s.push(h),u.push(p),f.push(m)}}const d=[];for(let t=0;t<e.length;t++){const n=e[t].sam_info.split("\t");d.push({read_sequence:n[9],start_position:Number(n[3]),cigar:n[5],flag:Number(n[1])})}const h=[];for(let t=0;t<a.length;t++)h.push({ref_position:Number(c[t]),refallele:a[t],altallele:l[t],refseq:u[t],altseq:f[t],leftflankseq:i[t],rightflankseq:s[t]});Number.isFinite(Number(t.strictness))||(t.strictness=1);const p={reads:d,alleles:h,strictness:Number(t.strictness)},m=new Date,g=await(0,Q.run_rust)("indel",JSON.stringify(p)),y=new Date;console.log("Time taken to run rust indel pipeline:",y-m,"ms");const v=g.split("\n");let b,w,_,x,k,q,N=0;for(let t of v)t.includes("Final_output:")?b=JSON.parse(JSON.parse(t.replace("Final_output:",""))):1==a.length&&t.includes("fisher_strand:")?(w=JSON.parse(t.replace("fisher_strand:","")),_=w.alternate_forward_count,x=w.alternate_reverse_count,k=w.reference_forward_count,q=w.reference_reverse_count,N=w.p_value):console.log(t);let S=!1;1==t.variant.length&&N>60&&(S=!0);const A=pt(t);t.variant.length;let M=1;for(let n=0;n<b.length;n++){const r=b[n],o=r.read_number,i=r.categories,s=r.categories[0],a=[];if(i.length>1){for(let t=1;t<i.length;t++)a.push(i[t]);i.length-1>M&&(M=i.length-1)}if(s.includes("alt"))for(let n=0;n<t.variant.length;n++)s=="alt"+n.toString()&&A[ut+n.toString()]&&(e[o].tempscore=["alt"+n.toString()],A[ut+n.toString()].templates.push(e[o]));else"ref"==s?A[ct]&&(e[o].tempscore=["ref"],A[ct].templates.push(e[o])):"none"==s?A[ft]&&(e[o].tempscore=a,A[ft].templates.push(e[o])):"amb"==s?A[dt]&&(e[o].tempscore=a,A[dt].templates.push(e[o])):console.log("Unaccounted group, please check")}const T=[];for(const e in A){const r=A[e];if(0!=r.templates.length){if(e.includes(ut))for(let n=0;n<t.variant.length;n++)e==ut+n.toString()&&(1==t.variant.length?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the alternative allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the alternative allele"}):1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read support the alternative allele with "+l[n]+" sequence"}):r.messages.push({isheader:!0,t:r.templates.length+" reads support the alternative allele with "+l[n]+" sequence"}));else e==dt?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" ambiguous read"}):r.messages.push({isheader:!0,t:r.templates.length+" ambiguous reads"}):e==ct?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the reference allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the reference allele"}):e==ft?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting neither reference nor alternative alleles"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting neither reference nor alternative alleles"}):console.log("Unaccounted group, please check");r.widths=n,T.push(r)}}const C=[];for(let t=0;t<T.length;t++)T[t].type.includes("support_alt")&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_ref"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_no"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_amb"==T[t].type&&C.push(T[t]);return{groups:C,refalleleerror:o,ref_positions:c,refalleles:a,altalleles:l,max_diff_score:M,min_diff_score:0,strand_probability:N,strand_significance:S,refseqs:u,altseqs:f,leftflankseqs:i,rightflankseqs:s,alternate_forward_count:_,alternate_reverse_count:x,reference_forward_count:k,reference_reverse_count:q}}(t,e,n);console.log("Indel pipeline works only in single region. Please check!")}if(t.sv&&t.regions.length>1)return async function(t,e,n){const r=pt(e),o=[];for(let t=0;t<e.regions.length;t++){const n=e.regions[t],r=(await P.Kf(e.genome,n.chr+":"+n.start+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase(),i=[];for(const e of n.lines)i.push({sam_info:e,tempscore:"",ridx:t});const s={refseq:r,start:n.start,stop:n.stop,entries:i};0==t?(s.chr=e.sv.chrA,s.pos=e.sv.startA):1==t?(s.chr=e.sv.chrB,s.pos=e.sv.startB):console.log("More than two regions, please check"),o.push(s)}const i=new Date,s=(await(0,Q.run_rust)("sv",JSON.stringify(o))).split("\n"),a=new Date;let l,c;console.log("Time taken to run rust SV pipeline:",a-i,"ms");for(let t of s)t.includes("multi_region_templates:")?l=JSON.parse(t.replace("multi_region_templates:","")):t.includes("single_region_templates:")&&(c=JSON.parse(t.replace("single_region_templates:","")));if(!e.grouptype||"support_sv"==e.grouptype)for(const t of l)r[ht].templates.push(t);if(!e.grouptype||"support_ref"==e.grouptype)for(const t of c)r[ct].templates.push(t);const u=[];for(const t in r){const e=r[t];0!=e.templates.length&&(t==ht?1==e.templates.length?e.messages.push({isheader:!0,t:e.templates.length+" read supporting SV/fusion"}):e.messages.push({isheader:!0,t:e.templates.length+" reads supporting SV/fusion"}):t==ct&&e.messages.push({isheader:!0,t:e.templates.length+" reads supporting reference allele"}),e.widths=n,u.push(e))}return{groups:u}}(0,t,n);return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]}}(t);t.groups=n.groups,t.variant&&(e.ref_alleles=n.refalleles,e.alt_alleles=n.altalleles,e.allele_positions=n.ref_positions,e.strand_probability=n.strand_probability,e.alternate_forward_count=n.alternate_forward_count,e.reference_forward_count=n.reference_forward_count,e.alternate_reverse_count=n.alternate_reverse_count,e.reference_reverse_count=n.reference_reverse_count,1==n.strand_significance&&(e.strand_significance=!0),t.alleleAlreadyUpdated||(e.refseqs=n.refseqs,e.altseqs=n.altseqs,e.leftflankseqs=n.leftflankseqs,e.rightflankseqs=n.rightflankseqs,e.ref_positions=n.ref_positions,e.refalleles=n.refalleles,e.altalleles=n.altalleles)),Number.isFinite(t.max_diff_score)&&t.variant?(e.max_diff_score=t.max_diff_score,e.min_diff_score=t.min_diff_score):Number.isFinite(n.max_diff_score)&&(e.max_diff_score=n.max_diff_score,e.min_diff_score=n.min_diff_score),n.refalleleerror&&(e.refalleleerror=n.refalleleerror)}if(0==e.count.r)throw"No reads in view range.";if(t.alignOneGroup){const e=t.groups.find((e=>e.type==t.alignOneGroup));if(!e)throw"cannot find group for realignment";let n=$e(t,e);return n=Ue(e,t,n),await async function(t,e,n){let r;if(e.variant)if("support_ref"==t.type){let o=e.leftflankseqs[0].length;r=t.partstack?await Re(n,o,t.partstack.start,t.partstack.stop,e.refseqs[0]):await Re(n,o,0,0,e.refseqs[0])}else if("support_no"==t.type){let o=e.leftflankseqs[0].length;r=t.partstack?await Re(n,o,t.partstack.start,t.partstack.stop):await Re(n,o)}else if("support_amb"==t.type)console.log("Realignment of reads in ambiguous group is not currently implemented");else if(t.type.includes("support_alt")){for(let o=0;o<e.variant.length;o++)if(t.type=="support_alt"+o.toString()){let i=e.leftflankseqs[o].length;r=t.partstack?await Re(n,i,t.partstack.start,t.partstack.stop,e.altseqs[o]):await Re(n,i,0,0,e.altseqs[o])}}else console.log("Unaccounted group, please check");return{alignmentData:r}}(e,t,n)}let n=[];for(const r of t.groups){let o=$e(t,r);o=Ue(r,t,o),await ze(r,t,o),await Le(o,t),Ge(r,o,t);const i={type:r.type,width:t.canvaswidth,height:r.canvasheight,stackheight:r.stackheight,stackcount:r.stacks.length,allowpartstack:r.allowpartstack,templatebox:r.returntemplatebox,count:{r:o.reduce(((t,e)=>t+e.segments.length),0)}},s=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,r.canvasheight*t.devicePixelRatio),a=s.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio),a.textAlign="center",a.textBaseline="middle",i.messages=r.messages,i.messagerowheights=0;for(const e of o)Ve(a,e,r,t);Ke(a,r,t,o),t.asPaired&&(i.count.t=o.length),t.variant&&(i.diff_scores_img=await Ee(t,r,o,e.max_diff_score,e.min_diff_score),"support_alt0"==i.type?i.group_color=ie:"support_alt1"==i.type?i.group_color=se:"support_alt2"==i.type?i.group_color=ae:"support_alt3"==i.type?i.group_color=le:"support_alt4"==i.type?i.group_color=ce:"support_alt5"==i.type?i.group_color=ue:"support_ref"==i.type&&(i.group_color=fe)),i.src=s.toDataURL(),e.groups.push(i),n=[...n,...o]}t.readcount_skipped&&(e.count.skipped=t.readcount_skipped);t.getcolorscale&&(e.colorscale=function(t){const e=160,n=20,r=1,o=12,i=5,s=100,a=4,l=s+e+10,c=2*o+i+a+4*(n+r),u=(0,S.createCanvas)(t.devicePixelRatio*l,t.devicePixelRatio*c),f=u.getContext("2d");t.devicePixelRatio>1&&f.scale(t.devicePixelRatio,t.devicePixelRatio);f.fillStyle="black",f.font=o+"pt Arial",f.textAlign="center",f.fillText("Base quality",s+e/2,o);let d=2*o+i;function h(t,r,o){const i=s,a=f.createLinearGradient(i,o,i+e,o);a.addColorStop(0,r),a.addColorStop(1,t),f.fillStyle=a,f.fillRect(i,o,e,n)}return f.strokeStyle="black",f.beginPath(),f.moveTo(s,d),f.lineTo(s,d+a),f.moveTo(s+e/4,d),f.lineTo(s+e/4,d+a),f.moveTo(s+e/2,d),f.lineTo(s+e/2,d+a),f.moveTo(s+3*e/4,d),f.lineTo(s+3*e/4,d+a),f.moveTo(s+e,d),f.lineTo(s+e,d+a),f.closePath(),f.stroke(),f.fillText(40,s,d),f.fillText(30,s+e/4,d),f.fillText(20,s+e/2,d),f.fillText(10,s+3*e/4,d),f.fillText(0,s+e,d),f.textAlign="left",f.textBaseline="middle",d+=a,f.fillText("Match",0,d+n/2),h(It,Ot,d),d+=n+r,f.fillStyle="black",f.fillText("Mismatch",0,d+n/2),h(Zt,$t,d),d+=n+r,f.fillStyle="black",f.fillText("Softclip",0,d+n/2),h(Bt,Ut,d),d+=n+r,f.fillStyle="black",f.fillText("Insertion",0,d+n/2),h(Kt,Yt,d),{width:l,height:c,src:u.toDataURL()}}(t));if(!t.partstack)if(0==e.count.r);else{if(!t.pileupheight)throw"pileupheight missing";e.pileup_data=await async function(t,e){const n=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,t.pileupheight*t.devicePixelRatio),r=n.getContext("2d");t.devicePixelRatio>1&&r.scale(t.devicePixelRatio,t.devicePixelRatio);const o=[];let i=0;for(const[n,r]of t.regions.entries()){o[n]=await De(t,r),Oe(n,r,e,o[n]);for(const t of o[n])t&&(i=Math.max(i,t.total))}for(const[e,n]of t.regions.entries()){const s=t.pileupheight/i;for(const i of o[e]){if(!i)continue;const e=(i.position-n.start)*n.ntwidth+n.x,o=n.ntwidth>=1?e:Math.floor(e),a=Math.max(1,n.ntwidth);{r.fillStyle=oe;const e=i.total*s;r.fillRect(o,t.pileupheight-e,a,e)}let l=0;if(i.A){r.fillStyle=F.basecolor.A;const e=i.A*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.C){r.fillStyle=F.basecolor.C;const e=i.C*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.G){r.fillStyle=F.basecolor.G;const e=i.G*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.T){r.fillStyle=F.basecolor.T;const e=i.T*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.softclip){r.fillStyle=Ut;const e=i.softclip*s;r.fillRect(o,t.pileupheight-l-e,a,e)}}}return{width:t.canvaswidth,maxValue:i,src:n.toDataURL()}}(t,n)}return e}(s)),o().debugmode&&console.log("bam.js time ms",new Date-i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.get(vo+"/gdcbam",(async function(t,e){try{if(t.query.gdc_id){const n=await async function(t,e){const n={file_metadata:[],numFilesSkippedByWorkflow:0},r=await qt(t,n,e);if(!r.data.hits.length){if(n.is_case_id||n.is_case_uuid)throw"No bam files available for this case.";if(e){if((await qt(t,n)).data.hits.length)throw"Case not in current cohort.";throw"Invalid input ID."}throw"Invalid input ID."}for(const t of r.data.hits){if(t.analysis.workflow_type==kt){n.numFilesSkippedByWorkflow++;continue}const e={};e.file_uuid=t.id,e.file_size=bt(t.file_size),e.experimental_strategy=t.experimental_strategy,e.entity_id=t.associated_entities[0].entity_submitter_id,e.case_id=t.associated_entities[0].case_id,e.sample_type=t.cases[0].samples[0].sample_type,n.file_metadata.push(e)}return n}(t.query.gdc_id,t.query.filter0);await async function(t,e){var n;if(null===(n=t.file_metadata)||void 0===n||!n.length)return;const r=e.cookies.sessionid;if(!r)return;try{await Tt(t.file_metadata[0].file_uuid,null,r)}catch(e){"Permission denied"==e&&(t.userHasNoAccess=!0)}}(n,t),e.send(n)}else{const n=await async function(t){var e,n,r;const o=await St(null,null,t,Ct),i={};if(!Array.isArray(null===(e=o.data)||void 0===e?void 0:e.hits))throw"re.data.hits[] not array";for(const t of o.data.hits){var s,a,l,c;if(t.analysis.workflow_type==kt)continue;const e=null===(s=t.cases)||void 0===s||null===(a=s[0])||void 0===a?void 0:a.submitter_id;e&&(i[e]||(i[e]=[]),i[e].push({file_uuid:t.id,sample_type:null===(l=t.cases)||void 0===l||null===(c=l[0].samples)||void 0===c?void 0:c[0].sample_type,experimental_strategy:t.experimental_strategy,file_size:(Number.parseFloat(t.file_size)/1e9).toFixed(2)+" GB"}))}return{case2files:i,total:null===(n=o.data)||void 0===n||null===(r=n.pagination)||void 0===r?void 0:r.total,loaded:Ct}}(t.query.filter0);e.send(n)}}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/gdc_ssms",ln.BM(fo)),yo.get(vo+"/tkaicheck",(async(t,e)=>{try{e.send(await async function(t){const[e,n,r]=P.ZX(t);if(e)throw e;const o=Number(t.query.coveragemax)||100;if(!Number.isInteger(o))throw"invalid coveragemax";const i=Number(t.query.vafheight);if(!Number.isInteger(i))throw"invalid vafheight";const s=Number(t.query.coverageheight);if(!Number.isInteger(s))throw"invalid coverageheight";const a=Number(t.query.rowspace);if(!Number.isInteger(a))throw"invalid rowspace";const l=Number(t.query.dotsize)||1;if(!Number.isInteger(l))throw"invalid dotsize";if(!t.query.rglst)throw".rglst missing";"string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst));const c=t.query.gtotalcutoff,u=t.query.gmafrestrict,f=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,(3*i+4*a+2*s)*t.query.devicePixelRatio),d=f.getContext("2d");let h;t.query.devicePixelRatio>1&&d.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d.fillStyle="#f1f1f1",d.fillRect(0,0,t.query.width,i/2),d.fillRect(0,2*a+i+s,t.query.width,i/2),d.fillStyle="#FAFAD9",d.fillRect(0,i/2,t.query.width,i/2),d.fillRect(0,2*a+1.5*i+s,t.query.width,i/2),r&&(h=await P.d1(n,t.query.indexURL));let p=0;for(const e of t.query.rglst)e.x=p,p+=t.query.regionspace+e.width;const m="#786312",g="#122778",y="#858585",v="red";for(const e of t.query.rglst){const t=e.width/(e.stop-e.start);await P.UE({args:[n,e.chr+":"+e.start+"-"+e.stop],dir:h,callback:n=>{const r=n.split("\t"),f=Number.parseInt(r[1]),h=Number.parseInt(r[2]),p=Number.parseInt(r[3]),b=Number.parseInt(r[4]),w=Number.parseInt(r[5]);if(Number.isNaN(h)||Number.isNaN(p)||Number.isNaN(b)||Number.isNaN(w))return;if(c&&w<c)return;const _=Math.ceil(e.x+t*(e.reverse?e.stop-f:f-e.start)-l/2);d.fillStyle=m;const x=h/p;d.fillRect(_,i*(1-x),l,2);const k=b/w;if(u&&(k<u||k>1-u))return;d.fillRect(_,i+a+s+a+i*(1-k),l,2),d.fillStyle=g;const q=Math.abs(x-k);d.fillRect(_,2*i+4*a+2*s+i*(1-q),l,2),d.fillStyle=y;let N=(p>=o?o:p)*s/o,S=s-N;d.fillRect(_,S+i+a,l,N),d.fillStyle=y,N=(w>=o?o:w)*s/o,S=s-N,d.fillRect(_,S+3*a+2*i+s,l,N),p>=o&&(d.fillStyle=v,d.fillRect(_,i+a,l,2)),w>=o&&(d.fillStyle=v,d.fillRect(_,3*a+2*i+s,l,2))}})}return{src:f.toDataURL(),coveragemax:o}}(t))}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/blat",function(t){return async(e,n)=>{try{if(e.query.serverstat){const e=[];for(const n in t){const r=t[n];r.blat&&e.push(await qn(n,r))}if(0==e.length)throw"found no genome with blat";return void n.send({lst:e})}if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(!r.blat)throw"blat not enabled";if(!e.query.seq)throw".seq missing";n.send(await async function(t,e,n,r){const i=y().join(o().cachedir,await(0,P.tG)(">query\n"+e+"\n")),s=await Nn(t,i),a=(await(0,P.b5)(s)).trim();if(m().unlink(s,(()=>{})),m().unlink(i,(()=>{})),""==a)return{nohit:1};const l=a.split("\n"),c=[];for(const t of l){const e={},n=t.split(" ").filter((function(t){return""!=t}))[0].split("\t");e.query_match=n[0],e.query_startpos=(parseInt(n[11])+1).toString(),e.query_stoppos=n[12],e.query_strand=n[8],e.query_totallen=n[10],e.query_alignlen=Math.abs(parseInt(n[11])-parseInt(n[12])).toString(),e.ref_chr=n[13],e.ref_startpos=(parseInt(n[15])+1).toString(),e.ref_stoppos=n[16],e.ref_alignlen=Math.abs(n[16]-n[15]).toString(),e.ref_totallen=n[14],c.push(e)}return c.sort(((t,e)=>e.query_match-t.query_match)),{hits:c}}(r,e.query.seq,e.query.soft_starts,e.query.soft_stops))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.all(vo+"/mds3",function(t){return async(e,n)=>{try{if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";const i=function(t,e){const n=t.query;t.get("X-Auth-Token")&&(n.token=t.get("X-Auth-Token"));(0,P.Y5)(n,t.cookies),n.hiddenmclasslst&&(n.hiddenmclass=new Set(n.hiddenmclasslst.split(",")),delete n.hiddenmclasslst);return n}(e),s=await async function(t,e){if(t.dslabel){if(!e.datasets)throw".datasets{} missing from genome";const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";return n}const n={queries:{}};if(t.bcffile||t.bcfurl){const[r,o,i]=(0,P.ZX)({query:{file:t.bcffile,url:t.bcfurl}});if(r)throw r;const s={};i?(s.url=o,s.indexURL=t.bcfindexURL):s.file=o,n.queries.snvindel={byrange:{_tk:s}},n.queries.snvindel.byrange.get=await or(n,e)}return n}(i,r);!function(t,e){var n;if(t.filter0){const n="object"==typeof t.filter0?t.filter0:JSON.parse("string"==typeof t.filter0&&t.filter0.startsWith("%")?decodeURIComponent(t.filter0):t.filter0);t.filter0=e.validate_filter0(n)}t.filterObj&&"string"==typeof t.filterObj&&(t.filterObj=JSON.parse("string"==typeof t.filterObj&&t.filterObj.startsWith("%")?decodeURIComponent(t.filterObj):t.filterObj));if(t.skewerRim){if("format"!=t.skewerRim.type)throw"unknown skewerRim.type";var r,o;if(!t.skewerRim.formatKey)throw"skewerRim.formatKey missing when type=format";if(null===(r=e.queries)||void 0===r||null===(o=r.snvindel)||void 0===o||!o.format)throw"snvindel.format{} not found when type=format";if(!e.queries.snvindel.format[t.skewerRim.formatKey])throw"invalid skewerRim.formatKey";if(t.skewerRim.hiddenvalues=new Set,t.skewerRim.hiddenvaluelst){if(!Array.isArray(t.skewerRim.hiddenvaluelst))throw"query.skewerRim.hiddenvaluelst is not array";for(const e of t.skewerRim.hiddenvaluelst)t.skewerRim.hiddenvalues.add(e);delete t.skewerRim.hiddenvaluelst}}if(t.formatFilter){var i,s;if("object"!=typeof t.formatFilter)throw"formatFilter{} not object";if(null===(i=e.queries)||void 0===i||null===(s=i.snvindel)||void 0===s||!s.format)throw"snvindel.format{} not found when formatFilter is used";const n={};for(const r in t.formatFilter){if(!e.queries.snvindel.format[r])throw"invalid format key from formatFilter";if(!Array.isArray(t.formatFilter[r]))throw"formatFilter[k] value is not array";n[r]=new Set(t.formatFilter[r])}t.formatFilter=n}("format"==(null===(n=t.skewerRim)||void 0===n?void 0:n.type)||t.formatFilter)&&(t.addFormatValues=!0)}(i,s);const a=await async function(t,e){if(t.singleSampleMutation){var n;if(null===(n=e.queries.singleSampleMutation)||void 0===n||!n.get)throw"not supported on this dataset";return await e.queries.singleSampleMutation.get(t.singleSampleMutation,t)}if(t.singleSampleGenomeQuantification){if(!e.queries.singleSampleGenomeQuantification)throw"not supported on this dataset";const n=e.queries.singleSampleGenomeQuantification[t.singleSampleGenomeQuantification.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGenomeQuantification.sample,t.devicePixelRatio)}if(t.singleSampleGbtk){if(!e.queries.singleSampleGbtk)throw"not supported on this dataset";const n=e.queries.singleSampleGbtk[t.singleSampleGbtk.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGbtk.sample)}if(t.ssm2canonicalisoform){if(!e.ssm2canonicalisoform)throw"ssm2canonicalisoform not supported on this dataset";return{isoform:await e.ssm2canonicalisoform.get(t)}}if(t.variant2samples){if(!e.variant2samples)throw"not supported by server";return{variant2samples:await e.variant2samples.get(t)}}if(t.m2csq){if(e.queries&&e.queries.snvindel&&e.queries.snvindel.m2csq)return{csq:await e.queries.snvindel.m2csq.get(t)};throw"m2csq not supported on this dataset"}if(t.forTrack){const n={};if(t.skewer){if(n.skewer=[],e.queries.snvindel){const r=await async function(t,e){if(t.isoform){if(t.atgenomic){if(!e.queries.snvindel.byrange)throw".atgenomic but missing byrange query method";return await e.queries.snvindel.byrange.get(t)}if(e.queries.snvindel.byisoform)return await e.queries.snvindel.byisoform.get(t)}if(t.rglst){if(!e.queries.snvindel.byrange)throw"q.rglst[] provided but .byrange{} is missing";return await e.queries.snvindel.byrange.get(t)}throw"insufficient query parameters for snvindel"}(t,e);n.skewer.push(...r)}if(e.queries.svfusion){const r=await async function(t,e){if(t.rglst){if(!e.queries.svfusion.byrange)throw"q.rglst provided but svfusion.byrange missing";return await e.queries.svfusion.byrange.get(t)}throw"insufficient query parameters for svfusion"}(t,e);n.skewer.push(...r)}if(e.queries.geneCnv){const r=await async function(t,e){if(t.gene){if(!e.queries.geneCnv.bygene)throw"q.gene provided but geneCnv.bygene missing";return await e.queries.geneCnv.bygene.get(t)}}(t,e);n.geneCnv=r}!function(t,e){if(e.skewer){const n=[];for(const r of e.skewer)t.rglst&&!t.rglst.find((t=>r.chr==t.chr&&r.pos>=t.start&&r.pos<=t.stop))||n.push(r);e.skewer=n}e.genecnvAtsample}(t,n),n.mclass2variantcount=function(t){const e=new Map;for(const n of t){const t=n.class||n.dt;e.set(t,1+(e.get(t)||0))}return[...e].sort(((t,e)=>e[1]-t[1]))}(n.skewer)}return function(t,e,n){const r=new Set;if(n.skewer)for(const o of n.skewer)if(o.samples){o.occurrence=o.samples.length,yr(o,t,e),vr(o,e);for(const t of o.samples)r.add(t.sample_id);delete o.samples}r.size&&(n.sampleTotalNumber=r.size)}(t,e,n),n}if(t.geneExpression){if(!e.queries.geneExpression)throw"not supported";const{gene2sample2value:n,byTermId:r}=await e.queries.geneExpression.get(t);if(0==n.size)throw"no data";if(1==n.size)return{gene2sample2value:n};const i=new Date,s=await async function(t,e,n){const r=new Set;for(const e of t.values())for(const t in e)r.add(t);const i={matrix:[],row_names:[],col_names:[...r],cluster_method:e.clusterMethod,plot_image:!1};n.queries.geneExpression.valueIsTransformed&&(i.valueIsTransformed=!0);for(const[e,n]of t){i.row_names.push(e);const t=[];for(const e of i.col_names)t.push(n[e]||0);i.matrix.push(t)}const s=y().join(o().cachedir,Math.random().toString()+".json");await(0,P.Sf)(s,JSON.stringify(i));const a=await async function(t,e=[]){try{await m().promises.stat(t)}catch(e){throw`${t} does not exist`}const n=[],r=[];return new Promise(((i,s)=>{const a=(0,q.spawn)(o().Rscript,[t,...e]);a.stdout.on("data",(t=>n.push(t))),a.stderr.on("data",(t=>r.push(t))),a.on("error",(t=>s(t))),a.on("close",(t=>{const e=n.join("").trim().split("\n");i(e)}))}))}(y().join(o().binpath,"utils","fastclust.R"),[s]);m().unlink(s,(()=>{}));let l,c,u,f,d,h=[],p=[],g=!1,v=!1;for(const t of a)t.includes("OutputMatrix")?d=t.replace("OutputMatrix\t","").split("\t").map((t=>parseFloat(t))).filter((t=>t)):t.includes('[1] "RowCoordinates"')?g=!0:t.includes('"ColumnCoordinates"')?(v=!0,g=!1):t.includes("rowindexes")?l=t.replace("rowindexes\t","").split("\t").map((t=>parseInt(t))).filter((t=>t)):t.includes("colindexes")?c=t.replace("colindexes\t","").split("\t").map((t=>parseInt(t))).filter((t=>t)):t.includes("rownames")?u=t.replace("rownames\t","").split("\t").filter((function(t){return""!=t.trim()})):t.includes("colnames")?f=t.replace("colnames\t","").split("\t").filter((function(t){return""!=t.trim()})):t.includes('"Done"')?v=!1:1==g?h.push(t):1==v&&p.push(t);let b=await br(h,l),w=await br(p,c),_=[];for(let t=0;t<u.length;t++)if(f.length>0){let e=[];for(let n=0;n<f.length;n++)e.push(d[n*u.length+t]);_.push(e)}return{geneNameLst:u,sampleNameLst:f,matrix:_,row_dendro:b.dendrogram,row_children:b.children,row_names_index:l,col_dendro:w.dendrogram,col_children:w.children,col_names_index:c}}(n,t,e);return console.log("clustering done:",new Date-i,"ms"),{clustering:s,byTermId:r}}throw"do not know what client wants"}(i,s);n.send(a)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.get(vo+"/tkbampile",(async function(t,e){try{const[n,r,o]=P.ZX(t);if(n)throw n;let i=t.query.usegrade;const s=Number(t.query.allheight),a=Number(t.query.fineheight),l=Number(t.query.fineymax),c=Number(t.query.midpad),u=Number(t.query.regionspace),f=Number(t.query.width);if(!Number.isInteger(s))throw"allheight is not integer";if(!Number.isInteger(a))throw"fineheight is not integer";if(!Number.isInteger(l))throw"fineymax is not integer";if(!Number.isInteger(c))throw"midpad is not integer";if(!Number.isInteger(u))throw"regionspace is not integer";if(!Number.isFinite(f))throw"width is not a number";const d="string"==typeof t.query.rglst?JSON.parse(t.query.rglst):t.query.rglst;if(!d)throw"no rglst[]";if(!Array.isArray(d))throw"rglst is not an array";if(0==d.length)throw"empty rglst";for(const t of d)t.reverse?t.scale=e=>Math.ceil(t.width*(t.stop-e)/(t.stop-t.start)):t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start));let h;o&&(h=await P.d1(r,t.query.indexURL));for(const t of d){t.items=[];let e=0;await P.UE({args:[r,t.chr+":"+t.start+"-"+t.stop],dir:h,callback:n=>{const r=n.split("\t");let o;try{o=JSON.parse(r[2])}catch(t){return void e++}const i=Number.parseInt(r[1]);t.items.push({pos:i,data:o})}})}const p=s+c+a,m=(0,S.createCanvas)(f,p),g=d.reduce(((t,e)=>t+e.items.length),0),y=m.getContext("2d");if(0==g)return y.font="15px Arial",y.fillStyle="#aaa",y.textAlign="center",y.textBaseline="middle",y.fillText("No data in view range",f/2,p/2),void e.send({src:m.toDataURL()});let v=null;if(!i){const t=new Set;for(const e of d)for(const n of e.items)for(const e in n.data)t.add(e);if(v=[...t],v.length>0&&(i=v[0]),!i)return void e.send({src:m.toDataURL()})}let b=0;for(const t of d)for(const e of t.items)if(e.data[i]){let t=0;for(const n in e.data[i])t+=e.data[i][n];b=Math.max(b,t)}const w="#ededed";let _=0;const x=s/b,k=a/l;for(const t of d){const e=t.width/(t.stop-t.start);for(const n of t.items){const r=n.data[i];if(!r)continue;const o=t.scale(n.pos);let a=0;const u=[];for(const t in r)u.push({nt:t,v:r[t]}),a+=r[t];y.fillStyle=w;const f=x*(b-a);if(y.fillRect(_+o,f,e,x*a),u.length>1){u.sort(((t,e)=>e.v-t.v));for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=F.basecolor[u[t].nt],y.fillRect(_+o,f+x*n,e,x*u[t].v)}}y.fillStyle=w;const d=s+c+k*(l-Math.min(a,l));if(y.fillRect(_+o,d,e,k*Math.min(a,l)),u.length>1)for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=F.basecolor[u[t].nt],y.fillRect(_+o,d+k*(l-Math.min(l,a-n)),e,k*Math.min(l,u[t].v))}}_+=t.width+u}e.send({src:m.toDataURL(),allgrades:v,usegrade:i,allmax:b})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/dsdata",(async function(t,e){try{if(!fo[t.query.genome])throw"invalid genome";if(!t.query.dsname)throw".dsname missing";const n=fo[t.query.genome].datasets[t.query.dsname];if(!n)throw"invalid dsname";const r=[];for(const e of n.queries)if((!t.query.expressiononly||e.isgeneexpression)&&!(t.query.noexpression&&e.isgeneexpression||e.dsblocktracklst))if(e.vcffile){const n=await Mo(e,t);r.push(n)}else{if(!e.makequery)throw"unknow type from one of ds.queries[]";{const o=Ao(n,e,t);r.push(o)}}e.send({data:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/tkbigwig",(async function(t,e){try{let n,r,i,s,a=!1,l=!1;const[c,u,f]=P.ZX(t);if(c)throw c;if(u.endsWith(".gz")&&(l=!0,f&&(s=await P.d1(u,t.query.indexURL))),t.query.autoscale)a=!0;else if(t.query.percentile){if(i=t.query.percentile,!Number.isFinite(i))throw"invalid percentile"}else{if(n=t.query.minv,r=t.query.maxv,!Number.isFinite(n))throw"invalid minv";if(!Number.isFinite(r))throw"invalid maxv"}if(!Number.isFinite(t.query.barheight))throw"invalid barheight";if(!Number.isFinite(t.query.regionspace))throw"invalid regionspace";if(!Number.isFinite(t.query.width))throw"invalid width";if(!t.query.rglst)throw"region list missing";if(t.query.dotplotfactor&&!Number.isInteger(t.query.dotplotfactor))throw"dotplotfactor value should be positive integer";if(l)return await async function(t,e,n,r,o,i){if(null==n||null==r)throw"Y axis scale must be defined for bedgraph track";const s=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),a=s.getContext("2d");t.query.devicePixelRatio>1&&a.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);let l=0;for(let e of t.query.rglst)await et(t,e,l,n,r,o,i,a),l+=e.width+t.query.regionspace;e.send({src:s.toDataURL()})}(t,e,n,r,u,s);for(const e of t.query.rglst){let n;if(o().features.bigwig_rust){const r=u+","+e.chr+","+e.start+","+e.stop+","+Math.ceil(e.width*(t.query.dotplotfactor||1));n=await(0,Q.run_rust)("bigwig",r)}else n=await rt(t,e,u);n&&(e.values=n.trim().split("\t").map(Number.parseFloat),t.query.dividefactor&&(e.values=e.values.map((e=>e/t.query.dividefactor))))}let d=!0;for(const e of t.query.rglst)e.values&&(d=!1);const h=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),p=h.getContext("2d");if(t.query.devicePixelRatio>1&&p.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d)return p.font="14px Arial",p.fillStyle="#858585",p.textAlign="center",p.textBaseline="middle",p.fillText(t.query.name+": no data in view range",t.query.width/2,t.query.barheight/2),void e.send({src:h.toDataURL(),nodata:!0});const m=1,g=t.query.dotplotfactor?1/t.query.dotplotfactor:1;let y=0,v=0;const b={};if(a||i){const e=[],n=[];for(const r of t.query.rglst)if(r.values)for(const t of r.values)Number.isNaN(t)||(t>=0&&e.push(t),t<=0&&n.push(t));e.length&&(e.sort(((t,e)=>t-e)),y=a?e[e.length-1]:e[Math.floor(e.length*i/100)]),n.length&&(n.sort(((t,e)=>e-t)),v=a?n[n.length-1]:n[Math.floor(n.length*i/100)]),b.minv=v,b.maxv=y}else v=n,y=r;if(t.query.barheight<10){let e=(0,tt.B8)(t.query.pcolor);const n=e.r+","+e.g+","+e.b;e=(0,tt.B8)(t.query.ncolor);const r=e.r+","+e.g+","+e.b;let o=0;for(const e of t.query.rglst){if(e.values)for(let i=0;i<e.values.length;i++){const s=e.values[i];if(Number.isNaN(s))continue;p.fillStyle=s>=y?t.query.pcolor2:s>=0?"rgba("+n+","+s/y+")":s<=v?t.query.ncolor2:"rgba("+r+","+s/v+")";const a=Math.ceil(o+(e.reverse?e.width-g*i:g*i));p.fillRect(a,0,m,t.query.barheight)}o+=e.width+t.query.regionspace}}else{const e=nt().height(t.query.barheight).min(v).max(y);let n=0;for(const r of t.query.rglst){if(r.values)for(let o=0;o<r.values.length;o++){const i=r.values[o];if(Number.isNaN(i))continue;p.fillStyle=i>0?t.query.pcolor:t.query.ncolor;const s=Math.ceil(n+(r.reverse?r.width-g*o:g*o)),a=e(i);if(i>0)p.fillRect(s,a.y,m,t.query.dotplotfactor?Math.min(2,a.h):a.h);else if(t.query.dotplotfactor){const t=Math.min(2,a.h);p.fillRect(s,a.y+a.h-t,m,t)}else p.fillRect(s,a.y,m,a.h);i>y?(p.fillStyle=t.query.pcolor2,p.fillRect(s,0,m,2)):i<v&&(p.fillStyle=t.query.ncolor2,p.fillRect(s,t.query.barheight-2,m,2))}n+=r.width+t.query.regionspace}}b.src=h.toDataURL(),e.send(b)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/tkld",function(t){return async(e,n)=>{try{const r=t[e.query.genome];if(!r)throw"unknown genome";n.send(await async function(t,e){const[n,r,o]=P.ZX(t);if(n)throw n;let i;o&&(i=await P.d1(r,t.query.indexURL));if(!t.query.rglst)throw"rglst missing";const s=await P.Jy(r,i,e),a=t.query.connheight||50,l={rglst:[]};for(const e of t.query.rglst){const n={chr:e.chr,start:e.start,stop:e.stop,width:e.width,reverse:e.reverse,xoff:e.xoff};l.rglst.push(n);const o=[],c=new Set,u=(s?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;await P.UE({args:[r,u],dir:i,callback:t=>{const n=t.split("\t"),r=Number.parseInt(n[1]);if(r<e.start)return;const i=Number.parseInt(n[2]);if(i>e.stop)return;const s=Number.parseFloat(n[5]);o.push({start:r,stop:i,r2:s}),c.add(r),c.add(i)}}),n.img=ot(e,o,c,a,t.query.devicePixelRatio||1)}return l}(e,r))}catch(t){n.send({error:t.message||t})}}}(fo)),yo.get(vo+"/tabixheader",(async function(t,e){wo(t);try{const[n,r,o]=P.ZX(t);if(n)throw n;const i=o?await P.d1(r,t.query.indexURL):null,s=await P.ZD(r,i);e.send({lines:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.all(vo+"/snp",(async function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";e.send({results:await No(t.query,fo[n])})}catch(t){return t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/isoformlst",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!Array.isArray(t.query.lst))throw".lst missing";const r=[];for(const e of t.query.lst){if(n.genomicNameRegexp.test(e))continue;const t=n.genedb.getjsonbyisoform.all(e);r.push(t.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})))}e.send({lst:r})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/dbdata",(function(t,e){})),yo.get(vo+"/img",(async function(t,e){wo(t);const[n,r,o]=P.ZX(t);try{if(n)throw"invalid image file";const t=await m().promises.readFile(r);e.send({src:"data:image/jpeg;base64,"+new Buffer.from(t).toString("base64"),size:j()(r)})}catch(n){e.send({error:n.message||n})}})),yo.post(vo+"/svmr",(function(t,e){if(t.query.file){const[n,r,o]=P.ZX(t);if(n)return void e.send({error:"illegal file name"});m().readFile(r,"utf8",((t,n)=>{t?e.send({error:"cannot read file"}):e.send({raw:n})}))}else e.send({error:"missing file"})})),yo.post(vo+"/study",(async function(t,e){try{if(P.lY(t.query.file))throw"invalid file path";const n=y().join(o().tpmasterdir,t.query.file.endsWith(".json")?t.query.file:t.query.file+".json"),r=JSON.parse(await P.b5(n));if(!r.genome)throw"genome missing";const i={};let s=0;for(const t of r.mutationset||[]){const e=L.Dz(r.genome);if(!e)throw"init_bulk_flag() failed";if(r.mutationset.length>1&&(e.tpsetname=t.name?t.name:"set"+ ++s),i[Math.random()]=e,t.snvindel){const n=(await P.b5(y().join(o().tpmasterdir,t.snvindel))).trim().split(/\r?\n/),r=$.parseheader(n[0],e);if(r)throw"snvindel header line error: "+r;for(let t=1;t<n.length;t++)$.parseline(t,n[t],e)}if(t.sv){const n=(await P.b5(y().join(o().tpmasterdir,t.sv))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!0);if(r)throw"sv header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!0)}if(t.fusion){const n=(await P.b5(y().join(o().tpmasterdir,t.fusion))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!1);if(r)throw"fusion header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!1)}if(t.svjson){const n=(await P.b5(y().join(o().tpmasterdir,t.svjson))).trim().split(/\r?\n/),[r,i]=G.parseheader(n[0],e);if(r)throw"svjson header line error: "+r;for(let t=1;t<n.length;t++)G.parseline(t,n[t],e,i)}if(t.cnv){const n=(await P.b5(y().join(o().tpmasterdir,t.cnv))).trim().split(/\r?\n/),r=Z.parseheader(n[0],e);if(r)throw"cnv header line error: "+r;for(let t=1;t<n.length;t++)Z.parseline(t,n[t],e)}if(t.itd){const n=(await P.b5(y().join(o().tpmasterdir,t.itd))).trim().split(/\r?\n/),r=U.parseheader(n[0],e);if(r)throw"itd header line error: "+r;for(let t=1;t<n.length;t++)U.parseline(t,n[t],e)}if(t.deletion){const n=(await P.b5(y().join(o().tpmasterdir,t.deletion))).trim().split(/\r?\n/),r=z.parseheader(n[0],e);if(r)throw"deletion header line error: "+r;for(let t=1;t<n.length;t++)z.parseline(t,n[t],e)}if(t.truncation){const n=(await P.b5(y().join(o().tpmasterdir,t.truncation))).trim().split(/\r?\n/),r=J.parseheader(n[0],e);if(r)throw"Truncation header line error: "+r;for(let t=1;t<n.length;t++)J.parseline(t,n[t],e)}}if(r.annotations){const t=r.annotations.idkey?r.annotations.idkey:"sample";r.annotations.data={};for(const e of r.annotations.files){const n=await P.b5(y().join(o().tpmasterdir,e));W.tJ(n).forEach((e=>{const n=e[t].trim();r.annotations.data[n]||(r.annotations.data[n]=[]),r.annotations.data[n].push(e)}))}}for(const t in i)H(i[t]);delete r.mutationset,e.send({cohort:r,flagset:i})}catch(t){return void e.send({error:t.message||t})}})),yo.post(vo+"/textfile",(function(t,e){if(!t.query.file)return e.send({error:"no file"});if(P.lY(t.query.file))return e.send({error:"invalid file name"});const n=y().join(o().tpmasterdir,t.query.file);if(null!=t.query.from){if(!Number.isInteger(t.query.from))return void e.send({error:"invalid value for from"});if(!Number.isInteger(t.query.to))return void e.send({error:"invalid value for to"});const r=[];_()(m().createReadStream(n)).on("end",(()=>{e.send({text:r.join("\n")})})).lines.map(String).skip(t.query.from-1).take(t.query.to).forEach((t=>{r.push(t)}))}else m().readFile(n,{encoding:"utf8"},((t,n)=>{t?e.send({error:"error reading file"}):e.send({text:n})}))})),yo.post(vo+"/urltextfile",(async function(t,e){const n=t.query.url.replace(o().URL,`http://127.0.0.1:${o().port}`);try{const t=await b()(n);switch(t.statusCode){case 200:return void e.send({text:P.cl(t.body)});case 404:return void e.send({error:"File not found: "+n});default:e.send({error:"unknown status code: "+t.status})}}catch(t){return e.send({error:"Error downloading file: "+n})}})),yo.get(vo+"/junction",(async function(t,e){try{const[n,r,i]=P.ZX(t);if(n)throw n;if(!t.query.rglst)throw"rglst[] missing";if("string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst)),!Array.isArray(t.query.rglst))throw"rglst[] not an array";if(t.query.rglst.reduce(((t,e)=>e.stop-e.start+t),0)>1e6)throw"Zoom in below 1 Mb to show junctions";let s;if(t.query.isrnapeg){if(!o().features.junctionrnapeg)throw"rnapeg not supported on this server";if(i)throw"rnapeg file from url is not supported";s=await async function(t,e){try{await m().promises.stat(e)}catch(t){if("EACCES"==t.code)throw"permission denied for rnapeg file";if("ENOENT"==t.code)throw"rnapeg file not found";throw"cannot access rnapeg file ("+t.code+")"}const n=[];for(const r of t.rglst){const t=await cn({file:e,chr:r.chr,start:r.start,stop:r.stop});for(const e of t)n.push(e)}return n}(t.query,r)}else{const e=i?await P.d1(r,t.query.indexURL):null;s=await async function(t,e,n){const r=[];for(const o of t.rglst)await P.UE({args:[e,o.chr+":"+o.start+"-"+o.stop],dir:n,callback:t=>{const e=t.split("\t"),n=Number.parseInt(e[1]),i=Number.parseInt(e[2]);if(n>=o.start&&n<=o.stop||i>=o.start&&i<=o.stop){const t={chr:o.chr,start:n,stop:i,type:e[4],rawdata:[]};for(let n=5;n<e.length;n++)t.rawdata.push(Number.parseInt(e[n]));r.push(t)}}});return r}(t.query,r,e)}e.send({lst:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdsjunction",function(t){return async(e,n)=>{try{const[r,i,s]=await async function(t,e){const n=t.query;if(!n.genome)throw"genome missing";const r=e[n.genome];if(!r)throw"invalid genome";let i={},s={};if(n.iscustom)if(s.listsamples=!0,n.url)s.url=n.url,s.dir=await P.d1(n.url,n.indexURL);else if(n.file)s.file=y().join(o().tpmasterdir,n.file);else{if(!n.file2)throw"no file or url given";s.file2=y().join(o().tpmasterdir,n.file2)}else{if(!r.datasets)throw"genome is not equipped with datasets";if(!n.dslabel)throw"dslabel missing";if(i=r.datasets[n.dslabel],!i)throw"invalid dslabel";if(!i.queries)throw"dataset is not equipped with queries";if(!n.querykey)throw"querykey missing";if(s=i.queries[n.querykey],!s)throw"invalid querykey"}return[n,i,s]}(e,t),a=await async function(t,e,n){if(t.junction)return await async function(t,e,n){const r=t.junction;if(!r.chr||!Number.isInteger(r.start)||!Number.isInteger(r.stop))throw"incomplete/invalid info about querying junction";let o;if(await P.UE({args:[on(n),r.chr+":"+r.start+"-"+r.stop],dir:n.dir,callback:i=>{const s=i.split("\t"),a=Number.parseInt(s[1]),l=Number.parseInt(s[2]);if(a==r.start&&l==r.stop)if(n.file2){o=[];for(let t=5;t<s.length;t++){const e=s[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||o.push({i:t-5,readcount:n}))}}else{const r=JSON.parse(s[5]);o=sn(r,t,e,n)}}}),0==o.length)throw"no sample passing filters";const i={};if(n.listsamples){const t=o.map((t=>{const e={readcount:t.readcount};return t.anno?e.sample_name=t.anno.sample_name:e.i=t.i,e}));t.sort(((t,e)=>e.readcount-t.readcount)),t.length>100?(i.samples=t.slice(0,100),i.sampletotalnumber=t.length):i.samples=t}else if(n.singlejunctionsummary&&n.singlejunctionsummary.readcountboxplotpercohort){i.readcountboxplotpercohort=[];for(const t of n.singlejunctionsummary.readcountboxplotpercohort.groups){const e=new Map;for(const n of o){if(!n.anno)continue;const r=n.anno[t.key];null!=r&&(e.has(r)||e.set(r,[]),e.get(r).push(n))}if(0==e.size)continue;const n=[...e].sort(((t,e)=>e[1].length-t[1].length)),r=[];for(const[t,e]of n){let n=e[0].readcount,o=n;e.forEach((t=>{n=Math.min(n,t.readcount),o=Math.max(o,t.readcount)}));const i=an(e,.05,.25,.5,.75,.95);r.push({label:t,samplecount:e.length,percentile:{p05:i[0],p25:i[1],p50:i[2],p75:i[3],p95:i[4]},minvalue:n,maxvalue:o})}i.readcountboxplotpercohort.push({label:t.label,boxplots:r})}}return i}(t,e,n);if(t.readcountByjBsamples)return await async function(t,e,n){if(!t.junctionAposlst)throw".junctionAposlst[] missing";let r,o=t.junctionB.start,i=t.junctionB.stop;t.junctionAposlst.forEach((t=>{o=Math.min(o,t[0]),i=Math.max(i,t[1])}));let s=[];if(await P.UE({args:[n.file||n.url,t.junctionB.chr+":"+o+"-"+i],dir:n.dir,callback:e=>{const n=e.split("\t"),o=Number.parseInt(n[1]),i=Number.parseInt(n[2]);if(o==t.junctionB.start&&i==t.junctionB.stop)r=JSON.parse(n[5]);else for(const[e,r]of t.junctionAposlst)if(e==o&&r==i){const t=JSON.parse(n[5]);t.start=o,t.stop=i,s.push(t);break}}}),!r)throw"jB not found";if(0==s.length)throw"none of jA is found";const a=sn(r,t,e,n);if(0==a.length)throw"no sample passing filters for junctionB";const l=new Set;a.forEach((t=>l.add(t.i)));const c=[];for(const e of s){const n=[];for(const r of e.samples)l.has(r.i)&&(t.readcountCutoff&&r.readcount<t.readcountCutoff||n.push(r));c.push({start:e.start,stop:e.stop,v:Math.floor(an(n,.5))})}return{lst:c}}(t,e,n);const r={};if(t.iscustom&&t.getsamples){const t=await P.ZD(on(n),n.dir);if(t[0]){const e=t[0].split("\t");e.length>5&&(r.sample2client=e.slice(5))}}if(!t.rglst)throw"rglst missing";if(n.viewrangeupperlimit){if(t.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=n.viewrangeupperlimit)throw"zoom in under "+common.bplen(n.viewrangeupperlimit)+" to view details"}let o=0,i=0;const s=[],a=new Set,l=new Set;for(const r of t.rglst)await P.UE({args:[on(n),r.chr+":"+r.start+"-"+r.stop],dir:n.dir,callback:c=>{const u=c.split("\t"),f=Number.parseInt(u[1]),d=Number.parseInt(u[2]);if(n.file2){u[3];const e=u[4];let n;if("known"==e)n="canonical";else{if("novel"!=e)throw"unknown rnapeg type: "+e;n=rn}if(t.infoFilter&&t.infoFilter.type&&t.infoFilter.type[n])return;const a={chr:r.chr,start:f,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let t=5;t<u.length;t++){const e=u[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||(l.push({readcount:n}),o=Math.max(o,n)))}if(0==l.length)return;if(i++,a.sampleCount=l.length,1==a.sampleCount)a.medianReadCount=l[0].readcount;else{const t=an(l,.05,.25,.5,.75,.95);a.medianReadCount=t[2],a.readcountBoxplot={percentile:t}}s.push(a)}else{u[3],u[4];if(!(f>=r.start&&f<=r.stop||d>=r.start&&d<=r.stop))return;i++;const c={chr:r.chr,start:f,stop:d,info:{type:{lst:[]}}},h=JSON.parse(u[5]);if(h.sv){c.sv=h.sv;const t=c.chr+"."+c.start+"."+c.sv.mate.chr+"."+c.sv.mate.start;if(a.has(t))return;a.add(t),a.add(c.sv.mate.chr+"."+c.sv.mate.start+"."+c.chr+"."+c.start)}if(h.canonical&&c.info.type.lst.push({attrValue:"canonical"}),h.events)for(const t in h.events){const e=h.events[t];e.__ek=t,c.info.type.lst.push(e)}else h.canonical||c.info.type.lst.push({attrValue:rn});if(t.infoFilter&&t.infoFilter.type)for(const e of c.info.type.lst)if(t.infoFilter.type[e.attrValue])return;const p=sn(h,t,e,n);if(0==p.length)return;if((h.exonleft||h.exonright||h.exonleftin||h.exonrightin||h.intronleft||h.intronright||h.leftout||h.rightout)&&(c.ongene={},h.exonleft&&(c.ongene.exonleft=h.exonleft),h.exonright&&(c.ongene.exonright=h.exonright),h.exonleftin&&(c.ongene.exonleftin=h.exonleftin),h.exonrightin&&(c.ongene.exonrightin=h.exonrightin),h.intronleft&&(c.ongene.intronleft=h.intronleft),h.intronright&&(c.ongene.intronright=h.intronright),h.leftout&&(c.ongene.leftout=h.leftout),h.rightout&&(c.ongene.rightout=h.rightout)),p.forEach((t=>{l.add(t.i),o=Math.max(o,t.readcount)})),c.sampleCount=p.length,1==c.sampleCount)c.medianReadCount=p[0].readcount;else{const t=an(p,.05,.25,.5,.75,.95);c.medianReadCount=t[2],c.readcountBoxplot={percentile:t}}s.push(c)}}});r.lst=s,r.maxreadcount=o,r.junctiontotalnumber=i,l.size;return r}(r,i,s);n.send(a)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.post(vo+"/mdscnv",(function(t,e){const[n,r,i,s]=To(t.query);if(n)return e.send({error:n});if(!t.query.rglst)return e.send({error:"rglst missing"});if(!t.query.gain)return e.send({error:".gain missing"});if(!t.query.loss)return e.send({error:".loss missing"});if(s.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=s.viewrangeupperlimit)return e.send({error:"zoom in under "+F.bplen(s.viewrangeupperlimit)+" to view details"})}if(t.query.permanentHierarchy){const n=function(t,e){if(!e.cohort)return".cohort missing from ds";if(!e.cohort.hierarchies)return".hierarchies missing from ds.cohort";if(!e.cohort.hierarchies.lst)return".hierarchies.lst[] missing from ds.cohort";const n=e.cohort.hierarchies.lst.find((e=>e.name==t.permanentHierarchy.hierarchyname));if(!n)return"unknown hierarchy "+t.permanentHierarchy.hierarchyname;if(!n.levels)return".levels[] missing in hierarchy "+n.name;const r=n.levels[t.permanentHierarchy.levelidx];if(!r)return"level not found by array idx "+t.permanentHierarchy.levelidx;const o=r.k;return delete t.cohortHiddenAttr,t.cohortOnlyAttr={},t.cohortOnlyAttr[o]={},t.cohortOnlyAttr[o][t.permanentHierarchy.valuekey]=1,null}(t.query,i);if(n)return e.send({error:"permanentHierarchy error: "+n})}const a=[],l={count:0,samples:new Set},c={count:0,samples:new Set};for(const e of t.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(ho,[s.file?y().join(o().tpmasterdir,s.file):s.url,e.chr+":"+e.start+"-"+e.stop],{cwd:s.usedir}),u=O().createInterface({input:a.stdout}),f=(e.stop-e.start)/e.width,d=[];for(let t=0;t<e.width;t++)d.push({positive:0,negative:0});u.on("line",(n=>{const r=n.split("\t"),o=Number.parseInt(r[1]),s=Number.parseInt(r[2]);if(t.query.bplengthUpperLimit&&s-o>t.query.bplengthUpperLimit)return;const a=JSON.parse(r[3]);if(t.query.valueCutoff&&Math.abs(a.value)<t.query.valueCutoff)return;if(a.sample&&i.cohort&&i.cohort.annotation){const e=i.cohort.annotation[a.sample];if(!e)return;if(t.query.cohortOnlyAttr&&i.cohort&&i.cohort.annotation){let n=!1;for(const r in t.query.cohortOnlyAttr){const o=e[r];if(o&&t.query.cohortOnlyAttr[r][o]){n=!0;break}}if(!n)return}if(t.query.cohortHiddenAttr&&i.cohort.attributes){let n=!1;for(const r in t.query.cohortHiddenAttr){i.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const o=e[r];if(o){if(t.query.cohortHiddenAttr[r][o]){n=!0;break}}else if(t.query.cohortHiddenAttr[r][go]){n=!0;break}}if(n)return}}a.value>0?(l.count++,l.samples.add(a.sample)):a.value<0&&(c.count++,c.samples.add(a.sample));const u=Math.max(e.start,o),h=Math.min(e.stop,s);let p,m;e.reverse?(p=Math.floor((e.stop-h)/f),m=Math.floor((e.stop-u)/f)):(p=Math.floor((u-e.start)/f),m=Math.floor((h-e.start)/f));for(let t=p;t<m;t++)a.value>0?d[t].positive++:a.value<0&&d[t].negative++}));const h=[];a.stderr.on("data",(t=>h.push(t))),a.on("close",(t=>{const e=h.join("");!e||co(e)?n(d):r(e)}))}));a.push(n)}Promise.all(a).then((n=>{const r=t.query.rglst.reduce(((e,n)=>e+n.width+t.query.regionspace),0)-t.query.regionspace,o=(0,S.createCanvas)(r,t.query.gain.barheight+t.query.loss.barheight),a=o.getContext("2d"),u={gain:{count:l.count,samplenumber:l.samples.size},loss:{count:c.count,samplenumber:c.samples.size},maxvalue:0};if(l.count+c.count==0)return a.font="15px Arial",a.fillStyle="#aaa",a.textAlign="center",a.textBaseline="middle",a.fillText("No data in view range",r/2,t.query.gain.barheight),u.src=o.toDataURL(),void e.send(u);for(const t of n)for(const e of t)u.maxvalue=Math.max(u.maxvalue,e.positive,e.negative);const f=t.query.maxvalue||u.maxvalue;let d=0;for(const e of n){for(const n of e){if(n.positive){a.fillStyle=t.query.gain.color||"#67a9cf";const e=Math.ceil(t.query.gain.barheight*Math.min(f,n.positive)/f),r=t.query.gain.barheight-e;a.fillRect(d,r,1,e)}if(n.negative){a.fillStyle=t.query.loss.color||"#ef8a62";const e=Math.ceil(t.query.loss.barheight*Math.min(f,n.negative)/f),r=t.query.gain.barheight;a.fillRect(d,r,1,e)}d++}d+=t.query.regionspace}if(u.src=o.toDataURL(),l.samples.size||c.samples.size){const t=new Set([...l.samples,...c.samples]),[e,n]=function(t,e,n){if(!t.cohort||!t.cohort.annotation||0==n.length)return[null,null];const r=[];for(const e of n){const n=t.cohort.annotation[e];n&&r.push(n)}if(0==r.length)return[null,null];let o,i;if(t.cohort.attributes){o=[];for(const n of t.cohort.attributes.lst){const i={label:n.label,key:n.key};if(n.isNumeric){i.isNumeric=!0;continue}const s=new Map;let a=0;for(const e of r){const r=e[n.key];null!=r?(s.has(r)||s.set(r,new Set),s.get(r).add(e[t.cohort.samplenamekey])):a++}const l=[...s];a&&l.push([go,a]),l.sort(((t,e)=>e[1]-t[1])),i.values=[];for(const[t,r]of l){const o={name:t,sampleset:r};if(n.values&&n.values[t])for(const e in n.values[t])o[e]=n.values[t][e];e.attributeSummary&&e.attributeSummary[n.key]&&e.attributeSummary[n.key][t]&&(o.totalCount=e.attributeSummary[n.key][t]),i.values.push(o)}o.push(i)}}if(t.cohort.hierarchies){i={};for(const n of t.cohort.hierarchies.lst){const o=(0,V.Z)()((0,A.N)(r,n.levels));o.sum((t=>t.value));const s=[];o.eachBefore((r=>{const o={id:r.data.id,name:r.data.name,label:r.data.full,depth:r.depth};if(r.data.lst){o.sampleset=new Set;for(const e of r.data.lst)o.sampleset.add(e[t.cohort.samplenamekey])}r.children||(o.isleaf=1),e.hierarchySummary&&e.hierarchySummary[n.name]&&(o.totalCount=e.hierarchySummary[n.name][r.id]),s.push(o)})),i[n.name]=s}}return[o,i]}(i,s,[...t]);if(e){for(const t of e)for(const e of t.values){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++;delete e.sampleset}u.attributeSummary=e}if(n){for(const t in n)for(const e of n[t])if(e.sampleset){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++}u.hierarchySummary=n}}e.send(u)})).catch((t=>{e.send({error:t}),t.stack&&console.error(t.stack)}))})),yo.post(vo+"/mdssvcnv",(async function(t,e){let n,r,i,s,a,l,c,u,f;if(t.query.iscustom){if(n=fo[t.query.genome],!n)return e.send({error:"invalid genome"});if(r={},i={iscustom:1,file:t.query.file,url:t.query.url,indexURL:t.query.indexURL,allow_getallsamples:!0},t.query.checkexpressionrank){if(!t.query.checkexpressionrank.file&&!t.query.checkexpressionrank.url)return e.send({error:"no file or url for checkexpressionrank"});i.checkexpressionrank={file:t.query.checkexpressionrank.file,url:t.query.checkexpressionrank.url,indexURL:t.query.checkexpressionrank.indexURL}}if(t.query.checkvcf){let n;try{n=JSON.parse(t.query.checkvcf)}catch(t){return e.send({error:"invalid JSON for VCF object"})}if(!n.file&&!n.url)return e.send({error:"no file or url for custom VCF track"});n.type=F.mdsvcftype.vcf,i.checkvcf={info:n.info,tracks:[n]}}if(t.query.checkrnabam){if(!t.query.checkrnabam.samples)return e.send({error:"samples{} missing from checkrnabam"});let n=0;for(const e in t.query.checkrnabam.samples)n++;if(n>13)return e.send({error:"no more than 13 BAM files allowed"});const r=Fo(t.query.checkrnabam);if(r)return e.send({error:r});i.checkrnabam=t.query.checkrnabam}}else{if(n=fo[t.query.genome],!n)return e.send({error:"invalid genome"});if(!n.datasets)return e.send({error:"genome is not equipped with datasets"});if(r=n.datasets[t.query.dslabel],!r)return e.send({error:"invalid dslabel"});if(t.query.getsample4disco)return function(t,e,n,r){if(t.query.iscustom)return e.send({error:"not for custom track"});if(!r.singlesamplemutationjson)return e.send({error:"singlesamplemutationjson not available for this dataset"});const i=t.query.getsample4disco,s=r.singlesamplemutationjson.samples[i];if(!s)return e.send({error:"no data"});const a=y().join(o().tpmasterdir,s);m().readFile(a,{encoding:"utf8"},((t,n)=>{if(t)return e.send({error:"error getting data for this sample"});e.send({text:n})}))}(t,e,0,r);if(t.query.gettrack4singlesample)return function(t,e,n){const r=t.query.gettrack4singlesample;if(t.query.iscustom)return e.send({error:"no server-side config available for custom track"});if(!n.sampleAssayTrack)return e.send({});return e.send({tracks:n.sampleAssayTrack.samples.get(r)})}(t,e,r);if(t.query.findsamplename)return function(t,e,n){if(t.query.iscustom)return e.send({error:"cannot search sample by name in custom track"});const r=t.query.findsamplename.toLowerCase(),o=[];if(!n.cohort.__samplelst){n.cohort.__samplelst=[];for(const t in n.cohort.annotation)n.cohort.__samplelst.push({name:t,low:t.toLowerCase()})}i(n.cohort.__samplelst);for(const t in n.queries){const e=n.queries[t];if(e.type==F.tkt.mdssvcnv&&e.groupsamplebyattr)for(const t of o){const r=n.cohort.annotation[t.name];if(!r)continue;const o=[];for(const t of e.groupsamplebyattr.attrlst){const e=r[t.k];e&&o.push({k:t.k,kvalue:e})}o.length&&(t.attributes=o,t.grouplabel=o.map((t=>t.kvalue)).join(e.groupsamplebyattr.attrnamespacer))}}if(n.cohort&&n.cohort.sampleAttribute&&n.cohort.sampleAttribute.attributes&&n.cohort.annotation)for(const t of o){const e=n.cohort.annotation[t.name];if(!e)continue;const r=[];for(const t in n.cohort.sampleAttribute.attributes){if(n.cohort.sampleAttribute.attributes[t].clientnoshow)continue;const o=e[t];null!=o&&r.push({k:t,v:o})}r.length&&(t.attr=r)}if(n.sampleAssayTrack)for(const t of o){const e=n.sampleAssayTrack.samples.get(t.name);e&&(t.num_assay_tracks=e.length)}if(n.cohort&&n.cohort.mutation_signature)for(const t in n.cohort.mutation_signature.sets){const e=n.cohort.mutation_signature.sets[t];if(e.samples)for(const t of o)e.samples.map.has(t.name)&&(t.mutation_signature=1)}if(n.singlesamplemutationjson)for(const t of o)n.singlesamplemutationjson.samples[t.name]&&(t.disco=1);return e.send({result:o});function i(t){for(const e of t){if(o.length>10)return;-1!=e.low.indexOf(r)&&(o.find((t=>t.name==e.name))||o.push(e))}}}(t,e,r);if(t.query.assaymap)return async function(t,e,n){try{if(!n.assayAvailability)throw"assay availability not enabled for this dataset";const r=new Set(t.query.skip_termids||[]),o=new Map;for(const e in n.cohort.annotation){if(t.query.key){if(n.cohort.annotation[e][t.query.key]!=t.query.value)continue}o.set(e,new Map)}for(const[t,e]of o){const o=n.assayAvailability.samples.get(t);if(o)for(const t of n.assayAvailability.assays)r.has(t.id)||o[t.id]&&e.set(t.id,"yes")}for(const t of o.keys())0==o.get(t).size&&o.delete(t);const i={};i.totalsample=o.size,i.terms=Hr({sample2term:o,terms:n.assayAvailability.assays,config:{termidorder:t.query.termidorder}}),e.send(i)}catch(t){e.send({error:t.message||t})}}(t,e,r);if(!r.queries)return e.send({error:"dataset is not equipped with queries"});if(i=r.queries[t.query.querykey],!i)return e.send({error:"invalid querykey"})}if(t.query.getexpression4gene)return async function(t,e,n,r,i){try{const n=t.query.getexpression4gene;if(!n.chr)throw"chr missing";if(!Number.isFinite(n.start))throw"invalid start pos";if(!Number.isFinite(n.stop))throw"invalid stop pos";if(!n.name)throw"unknown gene name";if(i.checkrnabam){const r=fo[t.query.genome],o=r.tracks.find((t=>t.__isgene)),s=(await Zo(r,o,n.chr,n.start,n.stop)).get(n.name);if(!s)throw"no gene matching with "+n.name;const a={};await Co(new Map([[n.name,s]]),n.chr,n.start,n.stop,i,a);const l={};for(const t of a.checkrnabam)if(t.genes){const e=t.genes.find((t=>t.gene==n.name));e&&(l[t.sample]=e)}return void e.send({sample2rnabam:l})}let s;if(i.iscustom?s=i.checkexpressionrank:i.expressionrank_querykey&&(s=r.queries[i.expressionrank_querykey]),!s)throw"missing expression data source";const a=s.file?null:await P.d1(s.url,s.indexURL),l=[];await P.UE({args:[s.file?y().join(o().tpmasterdir,s.file):s.url,n.chr+":"+n.start+"-"+n.stop],dir:a,callback:t=>{const e=t.split("\t");let r;try{r=JSON.parse(e[3])}catch(t){reject("invalid json from expression data")}r.sample&&r.gene&&Number.isFinite(r.value)&&(delete r.outlier,r.gene.toLowerCase()==n.name.toLowerCase()&&l.push(r))}});const c=function(t,e,n){const r={};if(t&&t.cohort&&t.cohort.annotation&&e.groupsamplebyattr&&e.groupsamplebyattr.attrlst){const o=new Map;for(const r of n){const n=t.cohort.annotation[r.sample];if(!n)continue;const i=[];for(const t of e.groupsamplebyattr.attrlst)i.push(n[t.k]);const s=i.join(",");o.has(s)||o.set(s,[]),o.get(s).push(r)}for(const t of o.values()){t.sort(((t,e)=>t.value-e.value));for(const e of t)e.rank=Bo(e.value,t),r[e.sample]=e}}else{n.sort(((t,e)=>t.value-e.value));for(const t of n)t.rank=Bo(t.value,n),r[t.sample]=t}return r}(r,i,l);e.send({sample2rank:c})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}}(t,e,0,r,i);if(t.query.ifsamplehasvcf)return function(t,e,n,r,o){if(t.query.iscustom)return e.send({no:1});if(!o.vcf_querykey)return e.send({yes:1});const i=r.queries[o.vcf_querykey];if(!i)return e.send({error:"vcf query missing"});e.send(i.singlesamples?{yes:1}:{no:1})}(t,e,0,r,i);if(!t.query.rglst)return e.send({error:"rglst missing"});if(i.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=i.viewrangeupperlimit)return e.send({error:"zoom in under "+F.bplen(i.viewrangeupperlimit)+" to view details"})}t.query.hiddendt&&(s=new Set(t.query.hiddendt));if(t.query.hiddenmattr){a={};for(const e in t.query.hiddenmattr)a[e]=new Set(t.query.hiddenmattr[e])}if(t.query.filteralleleattr){l={};for(const e in t.query.filteralleleattr){const n=t.query.filteralleleattr[e];n.cutoffvalue,l[e]=n}}if(t.query.filterlocusattr){c={};for(const e in t.query.filterlocusattr){const n=t.query.filterlocusattr[e];n.cutoffvalue,c[e]=n}}if(t.query.sampleset){const e=new Set,n=new Map;for(const r of t.query.sampleset)for(const t of r.samples)e.add(t),n.set(t,r.name);e.size&&(u={set:e,sample2group:n})}if(t.query.hiddensampleattr){f={};for(const e in t.query.hiddensampleattr)f[e]=new Set(t.query.hiddensampleattr[e])}if(i.url)try{i.dir=await P.d1(i.url,i.indexURL)}catch(t){return e.send({error:"svcnv file index url error"})}const d=await function(t,e,n,r,i,s,a){if(!e.file&&!e.url)return[];const l=[];for(const c of n.query.rglst){const u=new Promise(((l,u)=>{const f=[],d=(0,q.spawn)(ho,[e.file?y().join(o().tpmasterdir,e.file):e.url,c.chr+":"+c.start+"-"+c.stop],{cwd:e.dir});O().createInterface({input:d.stdout}).on("line",(e=>{const o=e.split("\t"),l=Number.parseInt(o[1]),c=Number.parseInt(o[2]);let u;try{u=JSON.parse(o[3])}catch(t){return}if(!(null==u.dt||r&&r.has(u.dt))){if(u.dt==F.dtloh){if(u.segmean&&n.query.segmeanValueCutoff&&u.segmean<n.query.segmeanValueCutoff)return;if(n.query.lohLengthUpperLimit&&c-l>n.query.lohLengthUpperLimit)return;u.chr=o[0],u.start=l,u.stop=c}else if(u.dt==F.dtfusionrna||u.dt==F.dtsv)u._chr=o[0],u._pos=l,u.chrA?(u.chrB=o[0],u.posB=l):(u.chrA=o[0],u.posA=l);else if(u.dt==F.dtcnv){if(n.query.hide_cnvloss&&u.value<0)return;if(n.query.hide_cnvgain&&u.value>0)return;if(n.query.valueCutoff&&Math.abs(u.value)<n.query.valueCutoff)return;if(n.query.bplengthUpperLimit&&c-l>n.query.bplengthUpperLimit)return;u.chr=o[0],u.start=l,u.stop=c}else{if(u.dt!=F.dtitd)return void console.error("unknown dt from svcnv file: "+u.dt);u.chr=o[0],u.start=l,u.stop=c}if(n.query.singlesample){if(u.sample!=n.query.singlesample)return}else if(a){if(!a.set.has(u.sample))return}else if(u.sample&&t.cohort&&t.cohort.annotation){const e=t.cohort.annotation[u.sample];if(!e)return;if(i)for(const t in i){const n=e[t];if(i[t].has(n))return}}if(s)for(const t in s){let e=u.mattr?u.mattr[t]:void 0;if(null==e&&(e=F.not_annotated),s[t].has(e))return}f.push(u)}}));const h=[];d.stderr.on("data",(t=>h.push(t))),d.on("close",(t=>{const e=h.join("");!e||co(e)?l(f):u(e)}))}));l.push(u)}return Promise.all(l)}(r,i,t,s,f,a,u),[h,p]=await function(t,e,n,r){if(n.query.singlesample)return[];let i;if(e.iscustom?i=e.checkexpressionrank:e.expressionrank_querykey&&t.queries[e.expressionrank_querykey]&&(i=t.queries[e.expressionrank_querykey]),!i)return[];let s=i.viewrangeupperlimit;if(!s&&e.iscustom&&(s=5e6),s&&n.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=s)return[s];return Promise.resolve().then((()=>i.file?"":(0,P.d1)(i.url,i.indexURL))).then((t=>{const e=new Map,r=[];for(const s of n.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(o().tabix,[i.file?y().join(o().tpmasterdir,i.file):i.url,s.chr+":"+s.start+"-"+s.stop],{cwd:t});O().createInterface({input:a.stdout}).on("line",(t=>{const n=t.split("\t");let r;try{r=JSON.parse(n[3])}catch(t){return}r.gene&&r.sample&&Number.isFinite(r.value)&&(e.has(r.gene)||e.set(r.gene,{chr:n[0],start:Number.parseInt(n[1]),stop:Number.parseInt(n[2]),samples:new Map}),e.get(r.gene).samples.set(r.sample,{value:r.value,ase:r.ase}))}));const l=[];a.stderr.on("data",(t=>l.push(t))),a.on("close",(t=>{const e=l.join("");!e||(0,P.sI)(e)?n():r(e)}))}));r.push(n)}return Promise.all(r).then((()=>[!1,e]))}))}(r,i,t),[g,v]=await async function(t,e,n,r,i,s,a,l,c,u){let f;n.iscustom?f=n.checkvcf:n.vcf_querykey&&e.queries[n.vcf_querykey]&&(f=e.queries[n.vcf_querykey]);if(!f)return[null,null];if(r.query.singlesample&&f.singlesamples){const n=f.singlesamples.samples[r.query.singlesample];if(n){const s={file:y().join(o().tpmasterdir,n)};try{await m().promises.stat(s.file)}catch(t){return[null,null]}const a=await Uo(s.file),[u,f,d,h]=D.e(a);if(h)throw h;return s.info=u,s.format=f,s.samples=d,s.nochr=await P.Jy(s.file,null,t),function(t,e,n,r,o,i,s){const a=[],l=[];for(const o of t.query.rglst){const c=new Promise(((l,c)=>{const u=(0,q.spawn)(ho,[n.file,(n.nochr?o.chr.replace("chr",""):o.chr)+":"+o.start+"-"+o.stop]);O().createInterface({input:u.stdout}).on("line",(o=>{const[l,c,u]=D.S(o,n);for(const n of c){if(!n.sampledata)continue;const o=n.sampledata.find((e=>e.sampleobj.name==t.query.singlesample));if(o){if(delete o.allele2readcount,n.sampledata=[o],r){let t=!1;for(const e in r){const o=n.altinfo[e];if(null==o){t=!0;break}const i=r[e];if(null!=i.cutoffvalue){if(!Number.isFinite(o)){t=!0;break}if(i.keeplowerthan){if(o>i.cutoffvalue){t=!0;break}}else if(o<i.cutoffvalue){t=!0;break}}}if(t)continue}if(!o.gtallref){if(o.__gtalleles){if(-1==o.__gtalleles.indexOf(n.alt))continue;delete o.__gtalleles}if(i){const t=[];for(const e of n.sampledata){let n=!0;for(const t in i){let r=e[t];if(null==r&&(r=F.not_annotated),i[t].has(r)){n=!1;break}}n&&t.push(e)}if(0==t.length)continue;n.sampledata=t}if(s&&e.cohort&&e.cohort.annotation){const t=[];for(const r of n.sampledata){const n=e.cohort.annotation[r.sampleobj.name];if(!n)continue;let o=!0;for(const t in s){const e=n[t];if(s[t].has(e)){o=!1;break}}o&&t.push(r)}if(0==t.length)continue;n.sampledata=t}delete n._m,delete n.vcf_ID,delete n.name,n.dt=F.dtsnvindel,a.push(n)}}}}));const f=[];u.stderr.on("data",(t=>f.push(t))),u.on("close",(t=>{const e=f.join("");!e||co(e)?l():c(e)}))}));l.push(c)}return Promise.all(l).then((()=>[null,a]))}(r,e,s,i,0,l,c)}}let d=f.viewrangeupperlimit;!d&&n.iscustom&&(d=uo.customMdsSingleSampleVcfNoRangeLimit?0:2e6);r.query.singlesample&&(d*=5);if(d){if(r.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=d)return[d,null]}const h=[];for(const t of f.tracks){const n=Promise.resolve().then((()=>t.file?"":P.d1(t.url,t.indexURL))).then((n=>{t.dir=n;const a=[],d=[];for(const h of r.query.rglst){const p=new Promise(((d,p)=>{const m=(0,q.spawn)(ho,[t.file?y().join(o().tpmasterdir,t.file):t.url,(t.nochr?h.chr.replace("chr",""):h.chr)+":"+h.start+"-"+h.stop],{cwd:n});O().createInterface({input:m.stdout}).on("line",(n=>{if(t.type==F.mdsvcftype.vcf){const[o,d,h]=D.S(n,{nochr:t.nochr,samples:t.samples,info:f.info,format:t.format});for(const t of d)if(t.sampledata){if(i){let e=!1;for(const n in i){const r=t.altinfo[n];if(null==r){e=!0;break}const o=i[n];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){e=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){e=!0;break}}else if(r<o.cutoffvalue){e=!0;break}}else if(o.includes(r)){e=!0;break}}if(e)continue}if(s){let e=!1;for(const n in s){const r=t.info[n];if(null==r){e=!0;break}let o=r;if(Array.isArray(r)&&(o=r[0],"."==o)){e=!0;break}const i=s[n];if(null!=i.cutoffvalue){if(!Number.isFinite(o)){e=!0;break}if(i.keeplowerthan){if(o>i.cutoffvalue){e=!0;break}}else if(o<i.cutoffvalue){e=!0;break}}else if(i.includes(o)){e=!0;break}}if(e)continue}{const e=[];for(const n of t.sampledata)if(!n.gtallref){if(n.__gtalleles){if(-1==n.__gtalleles.indexOf(t.alt))continue;delete n.__gtalleles}e.push(n)}if(0==e.length)continue;t.sampledata=e}if(r.query.singlesample){let e=null;for(const n of t.sampledata)if(n.sampleobj.name==r.query.singlesample){e=n;break}if(!e)continue;t.sampledata=[e]}else if(u){const e=t.sampledata.filter((t=>u.set.has(t.sampleobj.name)));if(!e.length)continue;t.sampledata=e}if(l){const e=[];for(const n of t.sampledata){let t=!0;for(const e in l){let r=n[e];if(null==r&&(r=F.not_annotated),l[e].has(r)){t=!1;break}}t&&e.push(n)}if(0==e.length)continue;t.sampledata=e}if(c&&e.cohort&&e.cohort.annotation){const n=[];for(const r of t.sampledata){const t=e.cohort.annotation[r.sampleobj.name];if(!t)continue;let o=!0;for(const e in c){const n=t[e];if(c[e].has(n)){o=!1;break}}o&&n.push(r)}if(0==n.length)continue;t.sampledata=n}for(const e of t.sampledata)delete e.allele2readcount;delete t._m,delete t.vcf_ID,delete t.name,t.dt=F.dtsnvindel,a.push(t)}}else console.error('unknown "type" from a vcf file')}));const g=[];m.stderr.on("data",(t=>g.push(t))),m.on("close",(t=>{const e=g.join("");!e||co(e)?d():p(e)}))}));d.push(p)}return Promise.all(d).then((()=>a))}));h.push(n)}return Promise.all(h).then((t=>{const e=[];for(const n of t)for(const t of n)if(t.dt!=F.dtsnvindel)console.error("unknown dt: "+t.dt);else{if(!t.sampledata)continue;let n=!0;for(const r of e)if(t.chr==r.chr&&t.pos==r.pos&&t.ref==r.ref&&t.alt==r.alt){for(const e of t.sampledata)r.sampledata.push(e);n=!1;break}n&&e.push(t)}return e.sort(((t,e)=>t.pos-e.pos)),[null,e]}))}(n,r,i,t,l,c,0,a,f,u),b=function(t){const e=new Map;for(const n of t)for(const t of n){if(!t.sample)continue;const n=t.sample;e.has(n)||e.set(n,[]),t._chr?e.get(n).push(t):(delete t.sample,delete t.sampletype,e.get(n).push(t))}return e}(d);if(t.query.singlesample){const n={lst:b.get(t.query.singlesample)};return g?n.vcfrangelimit=g:n.data_vcf=v,void e.send(n)}const w={samplegroups:Io(r,i,d,v,b,u),vcfrangelimit:g,data_vcf:v};t.query.getallsamples&&i.allow_getallsamples&&(w.getallsamples=!0);i.checkrnabam?await async function(t,e,n,r){if(!n.checkvcf)return;if(t.stop-t.start>=5e5)return void(r.expressionrangelimit=5e5);const o=e.tracks.find((t=>t.__isgene)),i=await Zo(e,o,t.chr,t.start,t.stop);let s,a=null;for(const t of i.values())null==a?(a=t.start,s=t.stop):(a=Math.min(a,t.start),s=Math.max(s,t.stop));await Co(i,t.chr,a,s,n,r)}(t.query.rglst[0],n,i,w):function(t,e,n,r){if(n)return void(t.expressionrangelimit=n);if(r){t.gene2coord={};for(const[e,n]of r)t.gene2coord[e]={chr:n.chr,start:n.start,stop:n.stop};if(0==t.samplegroups.length)return;if(t.getallsamples){const e=new Set(t.samplegroups[0].samples.map((t=>t.samplename))),n=new Set;for(const[t,o]of r)for(const t of o.samples.keys())e.has(t)||n.add(t);for(const e of n)t.samplegroups[0].samples.push({samplename:e,items:[]})}for(const n of t.samplegroups){const t=new Map;for(const[o,i]of r){t.set(o,[]);for(const[r,s]of i.samples)if(n.attributes&&e.cohort&&e.cohort.annotation){const i=e.cohort.annotation[r];if(!i)continue;let a=!0;for(const t of n.attributes)if(i[t.k]!=t.kvalue){a=!1;break}a&&t.get(o).push(s)}else t.get(o).push(s)}for(const[e,n]of t)n.sort(((t,e)=>t.value-e.value));for(const e of n.samples){e.expressionrank={};for(const[n,o]of t){const t=r.get(n).samples.get(e.samplename);if(null==t)continue;const i=Bo(t.value,o);e.expressionrank[n]={rank:i};for(const r in t)e.expressionrank[n][r]=t[r]}}}}}(w,r,h,p);(function(t,e){if(t.cohort&&t.cohort.sampleAttribute&&t.cohort.sampleAttribute.attributes&&t.cohort.annotation){e.sampleannotation={};const n=[];for(const e in t.cohort.sampleAttribute.attributes){t.cohort.sampleAttribute.attributes[e].clientnoshow||n.push(e)}for(const r of e.samplegroups)for(const o of r.samples){const r=t.cohort.annotation[o.samplename];if(r){const t={};let i=!1;for(const e of n){const n=r[e];null!=n&&(i=!0,t[e]=n)}i&&(e.sampleannotation[o.samplename]=t)}}}})(r,w),e.send(w)})),yo.post(vo+"/mdsgenecount",(async function(t,e){wo(t);try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.datasets)throw"no datasets from genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.gene2mutcount)throw"not supported on this dataset";if(!t.query.samples)throw".samples missing";let o,i;o=t.query.selectedMutTypes?t.query.selectedMutTypes.join("+"):"total",i=t.query.nGenes?t.query.nGenes:15;const s=`WITH\n\tfiltered AS (\n\t\tSELECT gene, ${o} AS total FROM genecount\n\t\tWHERE sample IN (${JSON.stringify(t.query.samples).replace(/[[\]\"]/g,"").split(",").map((t=>"'"+t+"'")).join(",")})\n\t)\n\tSELECT gene, SUM(total) AS count\n\tFROM filtered\n\tGROUP BY gene\n\tORDER BY count DESC\n\tLIMIT ${i}`,a=r.gene2mutcount.db.prepare(s).all(),l=[];for(const t of a){const e=n.genedb.getCoordByGene.get(t.gene);e&&(e.gene=t.gene,e.count=t.count,delete e.name,l.push(e))}e.send({genes:l})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/mds2",function(t){return async(e,n)=>{const r=e.query;try{const e=t[r.genome],o=await async function(t,e){if(!e)throw"invalid genome";if(t.dslabel){const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";if(!n.track)throw"no mds2 track found for dataset";return n}const n={iscustom:1,track:{}};t.vcf&&(n.track.vcf=t.vcf,await P._H(n.track.vcf,e));t.ld;return n}(r,e);if(r.trigger_overlayld)return await async function(t,e,n){if(!t.ldtkname)throw".ldtkname missing";const r=e.track.ld.tracks.find((e=>e.name==t.ldtkname));if(!r)throw"ld tk not found by name: "+t.ldtkname;const o=t.m.ref+"."+t.m.alt,i=(r.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),s=[];await P.UE({args:[r.file,i],dir:r.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),i=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&a==o?s.push({pos:i,alleles:l,r2:c}):i==t.m.pos&&l==o&&s.push({pos:r,alleles:a,r2:c})}}),n.send({lst:s})}(r,o,n);r.hidden_mclass&&(r.hidden_mclass=new Set(r.hidden_mclass));const i={mclass2count:{}};if(r.info_fields){i.info_fields={};for(const t of r.info_fields)if(t.iscategorical)i.info_fields[t.key]={value2count:{}};else if(t.isnumerical)i.info_fields[t.key]={filteredcount:0};else{if(!t.isflag)throw"unknown info type";i.info_fields[t.key]={count_yes:0,count_no:0}}}if(r.trigger_mafcovplot&&await async function(t,e,n,r){try{if(!n.track)throw"ds.track missing";const e=n.track.vcf;if(!e)throw"ds.track.vcf missing";if(n.iscustom)e.plot_mafcov={show_samplename:1};else if(!e.plot_mafcov)throw"maf-cov plot is not supported on this track";if(!t.m)throw".m{} missing";if(!e.AD)throw"vcf.AD{} missing";const o=(e.AD.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),i=e.AD.chr2bcffile[t.m.chr];if(!i)throw"chr not in tk.AD.chr2bcffile";let s;if(await P.UE({isbcf:!0,args:["query","-r",o,"-f",Fr,i],dir:e.AD.dir,callback:n=>{const[r,o,i]=D.S(n,e.AD);for(const e of o)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(s=e)}}),!s)throw"variant not found";if(r.plotgroups=function(t,e,n){const r=[],o={name:"?",lst:[]};for(const r of t.sampledata){const i=r.AD[t.ref]||0,s=r.AD[t.alt]||0,a=i+s,l={mut:s,total:i+s,maf:0==a?0:s/a};e.plot_mafcov.show_samplename&&(l.sampleobj={name:n.cohort.termdb.q.id2sampleName(r.sampleobj.name)}),o.lst.push(l)}return r.push(o),r}(s,e,n),t.overlay_term){const e=await Bn.g5({ds:n,term1_id:t.overlay_term,term1_q:t.overlay_term_q}),o=new Map;for(const t of e.lst)o.set(t.sample,t.key1);const i=(0,Ir.Z)(Rr.Z),s=new Map;let a=0;for(const t of r.plotgroups)for(const e of t.lst){const t=o.get(e.sampleobj.name);if(t){const n=i(t);e.sampleobj.color=n,s.has(t)||s.set(t,{count:0,color:n,label:t}),s.get(t).count++}else a++,e.sampleobj.color=Pr}if(r.categories=[],e.CTE1&&e.CTE1.name2bin)for(const t of e.CTE1.name2bin.keys()){const e=s.get(t);e&&r.categories.push(e)}else for(const[t,e]of s)r.categories.push(e);a&&r.categories.push({count:a,color:Pr,label:"Unannotated"})}}catch(t){r.error=t.message||t,t.stack&&console.log(t.stack)}}(r,0,o,i),r.trigger_vcfbyrange&&(await Tr(r,0,o,i),r.trigger_ld)){i.__mposset=new Set;for(const t of i.vcf.rglst)if(t.variants)for(const e of t.variants)i.__mposset.add(e.pos)}if(r.trigger_ld){i.ld={};for(const t of r.trigger_ld.tracks)await Dr(t,r,0,o,i);delete i.__mposset}r.trigger_ssid_onevcfm&&await async function(t,e,n,r){if(n.iscustom)throw"custom ds not allowed";const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const i=(o.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),s=o.chr2bcffile[t.m.chr];if(!s)throw"chr not in chr2bcffile";let a;if(await P.UE({isbcf:!0,args:["query",s,"-r",i,"-f",Mr+"\t%FORMAT\n"],dir:o.dir,callback:e=>{const[n,r,i]=D.S(e,o);for(const e of r)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(a=e)}}),!a)throw"variant not found";const l=[],c=[],u=[];for(const e of a.sampledata){if(!e.genotype)continue;const n=-1!=e.genotype.indexOf(t.m.ref),r=-1!=e.genotype.indexOf(t.m.alt);n?r?c.push(e.sampleobj.name):l.push(e.sampleobj.name):r&&u.push(e.sampleobj.name)}const f=Math.random().toString();r.ssid=f,r.groups={};const d=[];if(l.length){const t="Homozygous reference";r.groups[t]={size:l.length},d.push(t+"\t"+l.join(","))}if(c.length){const t="Heterozygous";r.groups[t]={size:c.length},d.push(t+"\t"+c.join(","))}if(u.length){const t="Homozygous alternative";r.groups[t]={size:u.length},d.push(t+"\t"+u.join(","))}await P.Sf(y().join(Ar.cachedir_ssid,f),d.join("\n"))}(r,0,o,i),r.trigger_getvcfcsq&&await async function(t,e,n,r){const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const i=(o.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),s=o.chr2bcffile[t.m.chr];if(!s)throw"chr not in chr2bcffile";await P.UE({isbcf:!0,args:["query",s,"-r",i,"-f",Mr+"\\n"],dir:o.dir,callback:e=>{const[n,i,s]=D.S(e,o);for(const e of i)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(r.csq=e.csq)}})}(r,0,o,i),n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/mdsexpressionrank",(function(t,e){let n,r,i,s=new Set;Promise.resolve().then((()=>{if(!t.query.rglst)throw"rglst missing";if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>1e7)throw"Zoom in below 10 Mb to show expression rank";if(!t.query.sample)throw"sample missing";if(t.query.iscustom){if(n=fo[t.query.genome],!n)throw"invalid genome";if(!t.query.file&&!t.query.url)throw"no file or url for expression data";r={},i={file:t.query.file,url:t.query.url,indexURL:t.query.indexURL}}else{const[e,o,s,a]=To(t.query);if(e)throw e;if(n=o,r=s,i=a,!i.samples)throw"total samples missing from server config";if(-1==i.samples.indexOf(t.query.sample))throw{nodata:1}}if(i.viewrangeupperlimit&&t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>i.viewrangeupperlimit)throw"zoom in under "+F.bplen(i.viewrangeupperlimit)+" to view data";if(t.query.levelkey){if(!t.query.levelvalue)throw"levelvalue is required when levelkey is used";if(!r.cohort||!r.cohort.annotation)throw".cohort.annotation missing from dataset"}if(!i.file){if(!i.url)throw"file or url missing";return P.d1(i.url,i.indexURL)}})).then((e=>{const n=[];for(const a of t.query.rglst)n.push(new Promise(((n,l)=>{const c=(0,q.spawn)(ho,[i.file?y().join(o().tpmasterdir,i.file):i.url,a.chr+":"+a.start+"-"+a.stop],{cwd:e}),u=O().createInterface({input:c.stdout}),f=new Map;u.on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);if(!o.gene)return;if(!o.sample)return;if(!Number.isFinite(o.value))return;const i=n[0],a=Number.parseInt(n[1]),l=Number.parseInt(n[2]);if(o.sample==t.query.sample)return f.has(o.gene)||f.set(o.gene,{chr:i,start:a,stop:l,allvalues:[]}),f.get(o.gene).thisvalue=o.value,void(o.ase&&(f.get(o.gene).ase=o.ase));if(t.query.attributes){const e=r.cohort.annotation[o.sample];if(!e)return;for(const n of t.query.attributes)if(n.k&&n.kvalue&&n.kvalue!=e[n.k])return}s.add(o.sample),f.has(o.gene)||f.set(o.gene,{chr:i,start:a,stop:l,allvalues:[]}),f.get(o.gene).allvalues.push({value:o.value})}));const d=[];c.stderr.on("data",(t=>d.push(t))),c.on("close",(t=>{const e=d.join("");e&&!co(e)&&l({message:e}),n(f)}))})));return Promise.all(n)})).then((t=>{const n=[];for(const e of t)for(const[t,r]of e)null!=r.thisvalue&&(r.allvalues.sort(((t,e)=>t.value-e.value)),r.rank=Bo(r.thisvalue,r.allvalues),delete r.allvalues,r.gene=t,n.push(r));e.send({result:n,samplecount:s.size})})).catch((t=>{t.stack&&console.log(t),t.nodata?e.send({nodata:1}):e.send({error:t.message?t.message:t})}))})),yo.post(vo+"/mdsgeneboxplot",(t=>async(e,n)=>{try{const[r,i,s,a]=function(t,e){if(!e.query.gene)throw"gene name missing";if(!e.query.chr)throw"chr missing";if(!Number.isInteger(e.query.start))throw"start missing";if(!Number.isInteger(e.query.stop))throw"stop missing";const n=t[e.query.genome];if(!n)throw"invalid genome";let r,o,i;if(e.query.iscustom){if(!e.query.file&&!e.query.url)throw"no file or url for expression data";r={},o={file:e.query.file,url:e.query.url,indexURL:e.query.indexURL}}else{if(!n.datasets)throw"genome is not equipped with datasets";if(!e.query.dslabel)throw"dslabel missing";if(r=n.datasets[e.query.dslabel],!r)throw"invalid dslabel";if(!r.queries)throw"dataset is not equipped with queries";if(!e.query.querykey)throw"querykey missing";if(o=r.queries[e.query.querykey],!o)throw"invalid querykey"}if(e.query.svcnv)if(i={},e.query.iscustom)i.dsquery={file:e.query.svcnv.file,url:e.query.svcnv.url,indexURL:e.query.svcnv.indexURL};else{e.query.svcnv.genome=e.query.genome;const t=n.datasets[e.query.svcnv.dslabel];if(!t)throw"invalid dslabel";if(!t.queries)throw"dataset is not equipped with queries";if(!e.query.svcnv.querykey)throw"querykey missing";const r=t.queries[e.query.svcnv.querykey];if(!r)throw"invalid querykey";i.ds=t,i.dsquery=r}if(e.query.getgroup)if(e.query.sampleset);else{if(!r.cohort||!r.cohort.annotation)throw"no sample annotation for getting group";if(e.query.getgroup_unannotated){if(!o.boxplotbysamplegroup)throw"dsquery.boxplotbysamplegroup{} missing when getgroup_unannotated"}else{if(!Array.isArray(e.query.getgroup))throw"getgroup should be array";for(const t of e.query.getgroup){if(!t.k)throw"k missing from one of getgroup";if(!t.kvalue)throw"kvalue missing from one of getgroup"}}}return[n,r,o,i]}(t,e);e.query.getalllst,n.send(await async function(t,e,n,r,i){n.url&&(n.dir=await P.d1(n.url,n.indexURL));r&&r.dsquery.url&&(r.dsquery.dir=await P.d1(r.dsquery.url,r.dsquery.indexURL));const s=function(t){if(!t.query.sampleset)return;const e=new Map;for(const n of t.query.sampleset)for(const t of n.samples)e.set(t,n.name);return e}(i),a=new Map,l=[],c=[];if(await P.UE({args:[n.file?y().join(o().tpmasterdir,n.file):n.url,i.query.chr+":"+i.query.start+"-"+i.query.stop],dir:n.dir,callback:t=>{const r=t.split("\t"),o=JSON.parse(r[3]);if(o.gene&&o.gene==i.query.gene&&Number.isFinite(o.value))if(i.query.getalllst)l.push({sample:o.sample,value:o.value});else if(i.query.getgroup){if(!o.sample)return;if(s)return void(i.query.getgroup_unannotated?s.has(o.sample)||c.push(o):s.get(o.sample)==i.query.getgroup[0].full&&c.push(o));const t=e.cohort.annotation[o.sample];if(i.query.getgroup_unannotated){if(!t)return void c.push(o);for(const e of n.boxplotbysamplegroup.attributes)if(null==t[e.k])return void c.push(o);return}if(!t)return;for(const e of i.query.getgroup)if(e.kvalue!=t[e.k])return;c.push(o)}else if(n.boxplotbysamplegroup&&e.cohort&&e.cohort.annotation){if(!o.sample)return;let t;t=null==i.query.index_boxplotgroupers||0==i.query.index_boxplotgroupers?n.boxplotbysamplegroup.attributes:n.boxplotbysamplegroup.additionals[i.query.index_boxplotgroupers-1].attributes;const r=e.cohort.annotation[o.sample];if(!r)return void l.push({sample:o.sample,value:o.value});const s=r[t[0].k];if(null==s)return void l.push({sample:o.sample,value:o.value});const c=[];for(let e=1;e<t.length;e++){const n=r[t[e].k];if(null==n)break;c.push(n)}c.unshift(s);const u=c.join(", ");if(!a.has(u)){const e={samples:[],attributes:[]};for(const n of t){const t=r[n.k];if(null==t)break;const o={k:n.k,kvalue:t};n.full&&(o.full=n.full,o.fullvalue=r[n.full]),e.attributes.push(o)}a.set(u,e)}a.get(u).samples.push({sample:o.sample,value:o.value})}else if(s){if(!o.sample)return;const t=s.get(o.sample);if(!t)return void l.push({sample:o.sample,value:o.value});a.has(t)||a.set(t,{samples:[],attributes:[{full:t}]}),a.get(t).samples.push({sample:o.sample,value:o.value})}else l.push({sample:o.sample,value:o.value})}}),i.query.getgroup2boxplot){c.sort(((t,e)=>t.value-e.value));const{w1:t,w2:e,p25:n,p50:r,p75:o,out:i}=P.JC(c);return{n:c.length,min:c[0].value,max:c[c.length-1].value,w1:t,w2:e,p25:n,p50:r,p75:o,out:i}}const u=[];for(const[t,e]of a)u.push({name:t,values:e.samples,attributes:e.attributes});l.length&&u.push({name:"Unannotated",values:l});c.length&&u.push({values:c});if(i.query.getalllst)return{lst:u[0].values};if(i.query.iscustom&&!s||1==u.length){if(u[0]){const t=u[0].values;return t.sort(((t,e)=>e.value-t.value)),{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const f=await async function(t,e){if(!e||!t.query.svcnv.useloss&&!t.query.svcnv.usegain&&!t.query.svcnv.usesv)return;let n=t.query.start,r=t.query.stop;t.query.svcnv.usesv&&Number.isInteger(t.query.svcnv.svflank)&&(n=Math.max(0,n-t.query.svcnv.svflank),r+=t.query.svcnv.svflank);const i=new Map;return await P.UE({args:[e.dsquery.file?y().join(o().tpmasterdir,e.dsquery.file):e.dsquery.url,t.query.chr+":"+n+"-"+r],dir:e.dsquery.dir,callback:e=>{const n=e.split("\t"),r=JSON.parse(n[3]);if(r.sample)if(r.chrA||r.chrB){if(!t.query.svcnv.usesv)return;i.has(r.sample)||i.set(r.sample,{}),i.get(r.sample).sv=1}else{if(!t.query.svcnv.usegain&&!t.query.svcnv.useloss)return;if(t.query.svcnv.usesv&&t.query.svcnv.svflank){const e=Number.parseInt(n[1]),r=Number.parseInt(n[2]);if(Math.max(t.query.start,e)>Math.min(t.query.stop,r))return}if(!Number.isFinite(r.value))return;if(!t.query.svcnv.usegain&&r.value>0)return;if(!t.query.svcnv.useloss&&r.value<0)return;if(t.query.svcnv.valueCutoff&&Math.abs(r.value)<t.query.svcnv.valueCutoff)return;if(t.query.svcnv.bplengthUpperLimit&&Number.parseInt(n[2])-Number.parseInt(n[1])>t.query.svcnv.bplengthUpperLimit)return;i.has(r.sample)||i.set(r.sample,{}),r.value>0?i.get(r.sample).gain=1:r.value<0&&(i.get(r.sample).loss=1)}}}),i}(i,r);if(i.query.getgroup){if(u[0]){const t=u[0].values;if(t.sort(((t,e)=>e.value-t.value)),f)for(const e of t){const t=f.get(e.sample);if(t)for(const n in t)e[n]=t[n]}return{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const d=[];let h=null,p=null;for(const t of u){t.values.sort(((t,e)=>t.value-e.value));const e=t.values.length;null==h?(h=t.values[0].value,p=t.values[e-1].value):(h=Math.min(h,t.values[0].value),p=Math.max(p,t.values[e-1].value));const{w1:n,w2:r,p25:o,p50:s,p75:a,out:l}=P.JC(t.values),c=[{isall:1,w1:n,w2:r,p25:o,p50:s,p75:a,out:l}];if(f){if(i.query.svcnv.usegain){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).gain));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({iscnvgain:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}if(i.query.svcnv.useloss){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).loss));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({iscnvloss:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}if(i.query.svcnv.usesv){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).sv));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({issv:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}}d.push({name:t.name+" ("+t.values.length+")",boxplots:c,attributes:t.attributes})}return d.sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)),{groups:d,min:h,max:p}}(0,i,s,a,e))}catch(t){t.stack&&console.log(t),n.send({error:t.message||t})}})(fo)),yo.post(vo+"/mdsgenevalueonesample",(async function(t,e){const n=t.query;try{if(!n.sample)throw".sample missing";if(!n.genes)throw".genes[] missing";let r,i,s;if(t.query.iscustom){if(r=fo[n.genome],!r)throw"invalid genome";if(!n.file&&!n.url)throw"no file or url for expression data";i={},s={file:n.file,url:n.url,indexURL:n.indexURL}}else{const[t,e,o,a]=To(n);if(t)throw t;r=e,i=o,s=a}const a=s.file?null:await P.d1(s.url,s.indexURL),l={};let c=!0;for(const t of n.genes){let e;await P.UE({args:[s.file?y().join(o().tpmasterdir,s.file):s.url,t.chr+":"+t.start+"-"+t.stop],dir:a,callback:r=>{const o=r.split("\t");if(!o[3])return;const i=JSON.parse(o[3]);i.gene==t.gene&&i.sample==n.sample&&(e=i.value)}}),Number.isFinite(e)&&(l[t.gene]=e,c=!1)}c?e.send({nodata:1}):e.send({result:l})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/vcf",(async function(t,e){try{const[n,r,o]=P.ZX(t);if(n)throw n;const i=o?await P.d1(r,t.query.indexURL):null;if(!t.query.rglst)throw"rglst missing";const s=[];for(const e of t.query.rglst)await P.UE({args:[r,e.chr+":"+e.start+"-"+e.stop],dir:i,callback:t=>s.push(t)});e.send({linestr:s.join("\n")})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.get(vo+"/vcfheader",(async function(t,e){try{if(!t.query.genome)throw"genome missing";const n=fo[t.query.genome];if(!n)throw"invalid genome";const[r,o,i]=P.ZX(t);if(r)throw r;const s=i?await P.d1(o,t.query.indexURL):null;e.send({metastr:(await P.ZD(o,s)).join("\n"),nochr:await P.Jy(o,s,n)})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/translategm",(async function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";const r=t.query.gm;if(!r)throw"missing gm{}";if(!r.chr)throw"gm.chr missing";if(!r.start)throw"gm.start missing";if(!Number.isInteger(r.start))throw"gm.start not integer";if(!r.stop)throw"gm.stop missing";if(!Number.isInteger(r.stop))throw"gm.stop not integer";const o=await P.Kf(n,r.chr+":"+(r.start+1)+"-"+r.stop),i=F.fasta2gmframecheck(r,o);e.send({frame:i})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/samplematrix",(function(t,e){Promise.resolve().then((()=>{const e=fo[t.query.genome];if(!e)throw"invalid genome";let n,r;if(t.query.iscustom){if(!t.query.querykey2tracks)throw"querykey2tracks{} missing for custom dataset";n={queries:{}};for(const e in t.query.querykey2tracks){const r=t.query.querykey2tracks[e];if(!r.type)throw'missing "type" for a data track';if(r.type==F.tkt.mdsvcf){const r=t.query.querykey2tracks[e];r.type=F.mdsvcftype.vcf,n.queries[e]={type:F.tkt.mdsvcf,info:r.info,tracks:[r]}}else if(r.type==F.tkt.mdssvcnv)n.queries[e]=r;else{if(r.type!=F.tkt.mdsexpressionrank)throw"unknown type of data track: "+r.type;n.queries[e]=r}}}else{if(!e.datasets)throw"genome is not equipped with datasets";if(!t.query.dslabel)throw"dslabel missing";if(n=e.datasets[t.query.dslabel],!n)throw"invalid dslabel";if(!n.queries)throw"dataset is not equipped with queries"}if(t.query.sampleset)r=new Set(t.query.sampleset);else if(t.query.limitsamplebyeitherannotation){if(!n.cohort)throw"limitsamplebyeitherannotation but no cohort in ds";if(!n.cohort.annotation)throw"limitsamplebyeitherannotation but no cohort.annotation in ds";r=new Set;for(const e in n.cohort.annotation){const o=n.cohort.annotation[e];for(const n of t.query.limitsamplebyeitherannotation)if(o[n.key]==n.value){r.add(e);break}}}const o=[];for(const e of t.query.features){let t,i=[];if(e.querykey){if(!n.queries)throw"using querykey for a feature but no ds.queries";if(t=n.queries[e.querykey],!t)throw"unknown dsquery by key "+e.querykey}else if(e.querykeylst){if(!n.queries)throw"using querykeylst for a feature but no ds.queries";for(const t of e.querykeylst){const e=n.queries[t];if(!e)throw'unknown key "'+t+'" from querykeylst';i.push(e)}if(0==i.length)throw"no valid keys in querykeylst"}else if(!e.issampleattribute)throw"unknown way to query a feature";if(e.isgenevalue){const[i,s]=Jo(e,n,t,r);if(i)throw"error with isgenevalue: "+i;o.push(s)}else if(e.iscnv){const[i,s]=Wo(e,n,t,r);if(i)throw"error with iscnv: "+i;o.push(s)}else if(e.isloh){const[i,s]=Ho(e,n,t,r);if(i)throw"error with isloh: "+i;o.push(s)}else if(e.isvcf){const[i,s]=Qo(e,n,t,r);if(i)throw"error with isvcf: "+i;o.push(s)}else if(e.isitd){const[i,s]=Vo(e,n,t,r);if(i)throw"error with isitd: "+i;o.push(s)}else if(e.issvfusion){const[i,s]=Yo(e,n,t,r);if(i)throw"error with issvfusion: "+i;o.push(s)}else if(e.issvcnv){const[i,s]=Ko(e,n,t,r);if(i)throw"error with issvcnv: "+i;o.push(s)}else if(e.ismutation){const[t,s]=Xo(e,n,i,r);if(t)throw"error with ismutation: "+t;o.push(s)}else{if(!e.issampleattribute)throw"unknown type of feature";{const[t,i]=Go(e,n,r);if(t)throw"error with issampleattribute: "+t;o.push(i)}}}return Promise.all(o)})).then((t=>{e.send({results:t})})).catch((t=>{e.send({error:"string"==typeof t?t:t.message}),t.stack&&console.error(t.stack)}))})),yo.get(vo+"/mdssamplescatterplot",(async function(t,e){wo(t);try{const n=fo[t.query.genome];if(!n)throw"invalid genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.cohort)throw"no cohort for dataset";if(!r.cohort.annotation)throw"cohort.annotation missing for dataset";const o=r.cohort.scatterplot;if(!o)throw"scatterplot not supported for this dataset";const i=[];for(const e in r.cohort.annotation){const n=r.cohort.annotation[e];if(t.query.subsetkey&&n[t.query.subsetkey]!=t.query.subsetvalue)continue;const s=n[o.x.attribute];if(!Number.isFinite(s))continue;const a=n[o.y.attribute];Number.isFinite(a)&&i.push({sample:e,x:s,y:a,s:n})}e.send({colorbyattributes:o.colorbyattributes,colorbygeneexpression:o.colorbygeneexpression,querykey:o.querykey,dots:i,tracks:o.tracks})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdssamplesignature",(function(t,e){try{const n=t.query;if(!n.sample)throw".sample missing";const r=fo[n.genome];if(!r)throw"invalid genome";const o=r.datasets[n.dslabel];if(!o)throw"invalid dataset";if(!o.cohort)throw"no cohort for dataset";if(!o.cohort.mutation_signature)throw"no mutation_signature for cohort";const i=[];for(const t in o.cohort.mutation_signature.sets){const e=o.cohort.mutation_signature.sets[t];if(!e.samples)continue;const r=e.samples.map.get(n.sample);if(!r)continue;const s=[];for(const t in e.signatures)r[t]&&s.push({k:t,v:r[t]});s.length&&i.push({key:t,valuename:e.samples.valuename,annotation:s.sort(((t,e)=>e.v-t.v))})}e.send({lst:i})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdssurvivalplot",function(t){return async(e,n)=>{try{const r=e.query,o=t[r.genome];if(!o)throw"invalid genome";const i=o.datasets[r.dslabel];if(!i)throw"invalid dataset";if(!i.cohort)throw"no cohort for dataset";if(!i.cohort.annotation)throw"cohort.annotation missing for dataset";const s=i.cohort.survivalplot;if(!s)throw"survivalplot not supported for this dataset";if(!s.plots)throw".plots{} missing";if(e.query.init)return void n.send(s.init);if(!r.type)throw".type missing";const a=s.plots[r.type];if(!a)throw"unknown plot type: "+r.type;const l=function(t,e,n){if(!t.samplerule)throw".samplerule missing";if(!t.samplerule.full)throw".samplerule.full missing";const r=[];if(t.samplerule.full.byattr){const n=t.samplerule.full.key;if(!n)throw"key missing from samplerule.full{}";const o=t.samplerule.full.value;if(null==o)throw"value missing from samplerule.full{}";for(const t in e.cohort.annotation){const i=e.cohort.annotation[t];i[n]==o&&r.push({name:t,o:i})}}else if(t.samplerule.full.useall)for(const t in e.cohort.annotation){const n=e.cohort.annotation[t];r.push({name:t,o:n})}else{if(!t.samplerule.full.usesampleset)throw"unknown rule for samplerule.full";{const n=t.samplerule.full.sampleset;for(const t in n){const o=n[t],i=e.cohort.annotation[o];null!=i&&r.push({name:o,o:i})}}}const o=[];for(const t of r)Number.isFinite(t.o[n.serialtimekey])&&(t.serialtime=t.o[n.serialtimekey],t.censored=t.o[n.iscensoredkey],o.push(t));if(0==o.length)throw"no samples found for full set";return o}(r,i,a),c=await async function(t,e,n,r){if(e.samplerule.mutated_sets){const n=new Set(t.map((t=>t.name))),r=e.samplerule.mutated_sets.reduce(((e,r)=>{const o=new Set(r.samplenames);r.lst=t.filter((t=>o.has(t.name)));for(const t of r.samplenames)n.delete(t);return delete r.samplenames,e.push(r),e}),[]);return r.push({name:"No mutation (n="+n.size+")",lst:t.filter((t=>n.has(t.name))),is_notmutated:!0}),r}const o=e.samplerule.set;if(!o)return[{name:"All",lst:t}];if(o.geneexpression){if(!o.gene)throw".gene missing from samplerule.set";if(!o.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(o.start))throw".start not integer from samplerule.set";if(!Number.isInteger(o.stop))throw".start not integer from samplerule.set";if(o.bymedian)return await async function(t,e,n,r){const o=e.samplerule.set,[i,s]=await to(t,e,n),a=Math.ceil(s.length/2),l=s[a-1].genevalue;return[{name:o.gene+" "+i.datatype+" below median (n="+a+", value<"+l+")",lst:s.slice(0,a)},{name:o.gene+" "+i.datatype+" above median (n="+(s.length-a)+", value>="+l+")",lst:s.slice(a,s.length)}]}(t,e,n);if(o.byquartile)return await async function(t,e,n,r){const o=e.samplerule.set,[i,s]=await to(t,e,n),a=Math.ceil(.25*s.length),l=Math.ceil(.5*s.length),c=Math.ceil(.75*s.length),u=s[a-1].genevalue,f=s[l-1].genevalue,d=s[c-1].genevalue;return[{name:o.gene+" "+i.datatype+" from 1st quartile (n="+a+", value<"+u+")",lst:s.slice(0,a),isfirstquartile:!0},{name:o.gene+" "+i.datatype+" from 2nd quartile (n="+(l-a)+", "+u+"<=value<"+f+")",lst:s.slice(a,l)},{name:o.gene+" "+i.datatype+" from 3rd quartile (n="+(c-l)+", "+f+"<=value<"+d+")",lst:s.slice(l,c)},{name:o.gene+" "+i.datatype+" from 4th quartile (n="+(s.length-c)+", value>="+d+")",lst:s.slice(c,s.length),isfourthquartile:!0}]}(t,e,n)}if(o.mutation){if(!o.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(o.start))throw".start not integer from samplerule.set";if(!Number.isInteger(o.stop))throw".start not integer from samplerule.set";return await async function(t,e,n){const r=e.samplerule.set;if(r.samples_snvindel=new Set,r.samples_cnv=new Set,r.samples_loh=new Set,r.samples_sv=new Set,r.samples_fusion=new Set,r.samples_itd=new Set,r.cnv&&!r.snvindel&&!r.loh&&!r.sv&&!r.fusion&&!r.itd){const[r,o]=await Kr(t,e,n,!0),i=[],s=[],a=[];for(const e of t)r.has(e.name)?i.push(e):o.has(e.name)?s.push(e):a.push(e);const l=[];return s.length&&l.push({name:"Copy number loss (n="+s.length+")",lst:s}),i.length&&l.push({name:"Copy number gain (n="+i.length+")",lst:i}),a.length&&l.push({name:"No copy number variation (n="+a.length+")",lst:a}),l}const o=await Kr(t,e,n),i=[];for(const e of t)o.find((t=>t.name==e.name))||i.push(e);const s=[];o.length&&s.push({name:"With mutation (n="+o.length+")",lst:o});i.length&&s.push({name:"No mutation (n="+i.length+")",lst:i});return s}(t,e,n)}throw"unknown rule for samplerule.set{}"}(l,r,i);let u;c.length>1&&(u=await Yr(c)),await async function(t,e){if(!t.samplerule.mutated_sets)return;const n=e.find((t=>t.is_notmutated));if(!n)return;for(const t of e){if(t.is_notmutated)continue;const e=await Yr([t,n]);t.pvalue=e}}(r,c),await async function(t,e){if(!t.samplerule.set)return;if(!t.samplerule.set.geneexpression)return;if(!t.samplerule.set.byquartile)return;if(4!=e.length)return;if(t.samplerule.set.against1st){for(let t=1;t<4;t++)e[t].pvalue=await Yr([e[0],e[t]]);return}if(t.samplerule.set.against4th){for(let t=0;t<3;t++)e[t].pvalue=await Yr([e[t],e[3]]);return}}(r,c);for(const t of c)eo(t),delete t.lst;const f={samplesets:c,pvalue:u};r.samplerule.set&&r.samplerule.set.mutation&&(f.count_snvindel=r.samplerule.set.samples_snvindel.size,f.count_cnv=r.samplerule.set.samples_cnv.size,f.count_loh=r.samplerule.set.samples_loh.size,f.count_sv=r.samplerule.set.samples_sv.size,f.count_fusion=r.samplerule.set.samples_fusion.size,f.count_itd=r.samplerule.set.samples_itd.size),n.send(f)}catch(t){t.stack&&console.error(t.stack),n.send({error:t.message||t})}}}(fo)),yo.post(vo+"/fimo",function(t){return async(e,n)=>{try{const r=e.query;if(!r.m)throw"no mutation";if(!r.m.chr)throw"mutation chr missing";if(!Number.isInteger(r.m.pos))throw"mutation position is not integer";if(!r.m.ref)throw"mutation ref allele missing";if(!r.m.alt)throw"mutation alt allele missing";const o=t[r.genome];if(!o)throw"invalid genome";if(!o.fimo_motif)throw"motif finding not supported on this genome";const i=await async function(t,e){const n=t.m.pos-t.flankspan,r=t.m.pos+t.flankspan,o=await P.Kf(e,t.m.chr+":"+n+"-"+r);!function(t,e,n){if(!t.m.ref)return;if("-"==t.m.ref)return;const r=n.split("\n").slice(1).join("").toUpperCase(),o=r.substring(t.m.pos-e,t.m.pos-e+t.m.ref.length);if(o==t.m.ref.toUpperCase())return;if(common.reversecompliment(o)==t.m.ref.toUpperCase())t.m.ref=o,"-"!=t.m.alt&&(t.m.alt=common.reversecompliment(t.m.alt))}(t,n,o);const i=await Wr(t,e,o),s=new Map;for(const t of i)t.pvalue_ref=t.pvalue,delete t.pvalue,t.logpvalue_ref=t.logpvalue,delete t.logpvalue,s.has(t.name)||s.set(t.name,[]),s.get(t.name).push(t);const a=function(t,e,n,r){const o=r.split("\n"),i=o.slice(1).join("");return o[0]+"\n"+i.substr(0,t.pos-e)+("-"==t.alt?"":t.alt)+i.substr(t.pos-e+("-"==t.ref?0:t.ref.length))}(t.m,n,0,o),l=await Wr(t,e,a);for(const t of l){t.pvalue_alt=t.pvalue,delete t.pvalue,t.logpvalue_alt=t.logpvalue,delete t.logpvalue,s.has(t.name)||s.set(t.name,[]);let e=!0;for(const n of s.get(t.name))if(null!=n.logpvalue_ref&&n.strand==t.strand&&Math.abs(t.start-n.start)<=2&&Math.abs(t.stop-n.stop)<=2){n.pvalue_alt=t.pvalue_alt,n.logpvalue_alt=t.logpvalue_alt,n.logpvaluediff=t.logpvalue_alt-n.logpvalue_ref,n.logpvaluediff>0?n.gain=!0:n.loss=!0,e=!1;break}e&&s.get(t.name).push(t)}let c=0,u=0;const f=[];for(const e of s.values())for(const n of e)null==n.logpvaluediff&&(null==n.pvalue_ref?(n.gain=!0,n.logpvaluediff=n.logpvalue_alt):null==n.pvalue_alt&&(n.loss=!0,n.logpvaluediff=-n.logpvalue_ref)),null!=t.minabslogp&&Math.abs(n.logpvaluediff)<t.minabslogp||(n.logpvaluediff>0?c=Math.max(c,n.logpvaluediff):u=Math.min(u,n.logpvaluediff),f.push(n));return{items:f,valuemin:u,valuemax:c,refstart:n,refstop:r,refseq:o.split("\n").slice(1).join("")}}(r,o);n.send(i)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.all(vo+"/termdb",X.TO(fo)),yo.all(vo+"/termdb-barsql",it.TO(fo)),yo.post(vo+"/singlecell",function(t){return async(e,n)=>{try{const r=e.query,o=t[r.genome];if(!o)throw"invalid genome";if(r.getpcd)return void await async function(t,e){const n={},r=await async function(t,e){if(!t.textfile)throw".textfile missing";{const[e,n,r]=P.ZX({query:{file:t.textfile}});if(e)throw".textfile error: "+e;if(!r){if(await P.yE(n))throw"file not exist: "+t.textfile;if(await P.t7(n))throw"file not readable: "+t.textfile}t.textfile=n}let n,r,o,i,s;if(t.getpcd.category_autocolor){const e=t.getpcd.values_count&&t.getpcd.values_count<=10?Rr.Z:zr;n=Ir.Z(e),o={},i={}}else if(t.getpcd.category_customcolor){const e=Ir.Z(zr);a=t.getpcd.cat_values,l=e,n=t=>{let e=!1;for(const n of a)if(n.value==t)return e=!0,n.color;if(!e)return l(t)},o={},i={},s={}}else if(t.getpcd.gene_expression){const n=t.getpcd.gene_expression;if(!n.file)throw"gene_expression.file missing";{const[t,e,r]=P.ZX({query:{file:n.file}});if(t)throw t;n.file=e}if(!Number.isInteger(n.barcodecolumnidx))throw"gene_expression.barcodecolumnidx missing";if(!n.chr)throw"gene_expression.chr missing";if(!n.start)throw"gene_expression.start missing";if(!n.stop)throw"gene_expression.stop missing";if(!n.genename)throw"gene_expression.genename missing";if(!n.autoscale)throw"gene_expression: unknown scaling method";if(!n.color_min)throw"gene_expression.color_min missing at autoscale";if(!n.color_max)throw"gene_expression.color_max missing at autoscale";const o=(n.nochr?n.chr.replace("chr",""):n.chr)+":"+n.start+"-"+n.stop,i=new Map;r=new Map;let s=0,a=0;if(e.numbercellwithgeneexp=0,e.numbercelltotal=0,await P.UE({args:[n.file,o],callback:t=>{const r=JSON.parse(t.split("\t")[3]);r.gene==n.genename&&Number.isFinite(r.value)&&(e.numbercellwithgeneexp++,n.autoscale&&(s=Math.min(s,r.value),a=Math.max(a,r.value)),i.set(r.sample,r.value))}}),n.autoscale){e.minexpvalue=s,e.maxexpvalue=a;const t=vt.ZP(n.color_min,n.color_max);for(const[e,n]of i){const o=tt.ZP(t((n-s)/(a-s)));r.set(e,Number.parseInt(Br(o.r,o.g,o.b),16))}}}var a,l;return new Promise(((s,a)=>{const l=[],c=O().createInterface({input:m().createReadStream(t.textfile)});let u=!0,f=0,d=0;c.on("line",(s=>{if(u)return void(u=!1);const a=s.split(t.delimiter),c=[];for(const e of t.getpcd.coord)c.push(a[e]),f=Math.max(f,a[e]),d=Math.min(d,a[e]);if(2==t.getpcd.coord.length&&c.push("0"),n){const e=a[t.getpcd.category_index],r=n(e);if(t.hidden_types.includes(e))if(t.background_color){const e=tt.ZP(t.background_color),n=Number.parseInt(Br(e.r,e.g,e.b),16);c.push(n)}else c.push(16777215);else c.push(Number.parseInt(r.slice(1),16));o&&(o[e]=r),i&&(i[e]=e in i?i[e]+1:1)}else if(r){e.numbercelltotal++;const n=a[t.getpcd.gene_expression.barcodecolumnidx];let o=r.get(n);if(void 0===o)if(t.getpcd.gene_expression.color_no_exp){const e=tt.ZP(t.getpcd.gene_expression.color_no_exp);o=Number.parseInt(Br(e.r,e.g,e.b),16)}else o="2894892";c.push(o)}l.push(c.join(" "))})),c.on("close",(()=>{o&&(t.getpcd.category_customorder&&(o=function(t,e){let n={};const r=Object.keys(t).length;for(var o=1;o<=r;o++){const r=e.find((t=>{if(t.order==o)return t.value}));r&&(n[r.value]=t[r.value])}for(const r of e)r.order||(n[r.value]=t[r.value]);for(const r in t){e.find((t=>{if(t.value==JSON.stringify(r))return!0}))||(n[r]=t[r])}return n}(o,t.getpcd.cat_values)),e.category2color=o,e.categorycount=i),e.data_sphere_r=Math.max(Math.abs(f),Math.abs(d)),s(l)}))}))}(t,n),o="# .PCD v.7 - Point Cloud Data file format\nVERSION .7\nFIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH 1200\nHEIGHT 800\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 960000\nDATA ascii\n";n.pcddata=o+r.join("\n"),e.send(n)}(r,n);if(r.getgeneboxplot)return void await async function(t,e,n){const r=t.getgeneboxplot,o=t.getgeneboxplot.values_count&&t.getgeneboxplot.values_count<=10?Ir.Z(Rr.Z):Ir.Z(zr);if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=P.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}if(!r.chr)throw"getgeneboxplot.chr missing";if(!r.start)throw"getgeneboxplot.start missing";if(!r.stop)throw"getgeneboxplot.stop missing";if(!r.genename)throw"getgeneboxplot.genename missing";const i=await Gr(r),s=(r.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;let a=0,l=0;await P.UE({args:[r.expfile,s],callback:t=>{const e=JSON.parse(t.split("\t")[3]);if(e.gene!=r.genename)return;if(!e.sample)return;if(!Number.isFinite(e.value))return;const n=i.get(e.sample);n&&(n.expvalue=e.value,a=Math.min(a,e.value),l=Math.max(l,e.value))}});const c=new Map;for(const[t,e]of i)c.has(e.category)||c.set(e.category,[]),r.exclude_cells&&0==parseInt(e.expvalue)||c.get(e.category).push({value:e.expvalue});const u=[],f=(d=Sn.Z().domain([a,l]).ticks(20),t=>{const e=[];for(let t=1;t<d.length;t++)e.push(0);for(const n of t)for(let t=1;t<d.length;t++)if(n.value<=d[t]){e[t-1]++;break}return e});var d;for(const[t,e]of c){e.sort(((t,e)=>t.value-e.value));const n=P.JC(e);delete n.out;const r=o(t);n.category=t,n.color=r,n.numberofcells=e.length,n.density=f(e),u.push(n)}let h=[];if(t.getgeneboxplot.cat_values){const e=Object.keys(t.getgeneboxplot.cat_values).length;for(var p=1;p<=e;p++){const e=t.getgeneboxplot.cat_values.find((t=>{if(t.order==p)return t.value}));e&&h.push(u.filter((t=>t.category==e.value))[0])}for(const e of t.getgeneboxplot.cat_values)e.order||h.push(u.filter((t=>t.category==e.value))[0]);for(const e of u){t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return!0}))||h.push(e)}for(const e of h){const n=t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return t}));n&&n.color&&(e.color=n.color)}}else h=u;n.send({boxplots:h,minexpvalue:a,maxexpvalue:l})}(r,0,n);if(r.getheatmap)return void await async function(t,e,n){const r=t.getheatmap,o=[];if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=P.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}r.gene_list.forEach((t=>{if(!t.chr)throw"getgeneboxplot.chr missing";if(!t.start)throw"getgeneboxplot.start missing";if(!t.stop)throw"getgeneboxplot.stop missing";if(!t.gene)throw"getgeneboxplot.genename missing"}));const i=await Gr(r);for(const t of r.gene_list){const e=(t.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;let n=0,s=0;const a=t.gene;await P.UE({args:[r.expfile,e],callback:e=>{const r=JSON.parse(e.split("\t")[3]);if(r.gene.toUpperCase()!==t.gene.toUpperCase())return;if(!r.sample)return;if(!Number.isFinite(r.value))return;const o=i.get(r.sample);o&&(o.expvalue=r.value,n=Math.min(n,r.value),s=Math.max(s,r.value))}});const l=new Map;for(const[t,e]of i)l.has(e.category)||l.set(e.category,[]),l.get(e.category).push({value:e.expvalue});const c=[];for(const[t,e]of l){let n=0;for(const t of e)n+=t.value;const r=e.length,o=(n/r).toFixed(3);c.push({category:t,mean:o,numberofcells:r})}o.push({genename:a,heatmap:c})}n.send({gene_heatmap:o})}(r,0,n)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/massSession",(async function(t,e){try{const n=t.body.__sessionFor__,{filename:r,route:i,dslabel:s,embedder:a}=n||{};let l;if(r){const e={headers:t.headers,query:n};if(l=$r.i.getPayloadFromHeaderAuth(e,i),!l.email)throw"invalid credentials: no jwt.email";if(l.dslabel!=s||l.route!=i||l.embedder!=a)throw"invalid credentials: mismatched payload";delete t.body.__sessionFor__}const c=r||function(){const t=[];for(;t.length<15;){const e=46+Math.floor(80*Math.random());(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)&&t.push(String.fromCharCode(e))}return t.join("")}(),u=JSON.stringify(t.body),f=r?Zr(n,l):o().cachedir_massSession;await m().promises.access(f).then((()=>!0)).catch((()=>!1))||m().mkdirSync(f,{recursive:!0}),await P.Sf(y().join(f,c),u),e.send({id:c})}catch(t){e.send({error:t.message||t})}})),yo.get(vo+"/massSession",(async function(t,e){try{const n=t.query.id;if(!n)throw"session id missing";const{route:r,dslabel:i,embedder:s}=t.query,a=t.query.route?$r.i.getPayloadFromHeaderAuth(t,t.query.route):null,l=t.query.route?Zr(t.query,a):o().cachedir_massSession,c=y().join(l,n);let u;try{u=(await m().promises.stat(c)).birthtime}catch(t){throw"invalid session"}const f=await P.b5(c),d=JSON.parse(f);if(t.query.route)return void e.send({state:d});const h=new Date,p=new Date(u),g=o().features.massSessionDuration||30,v=g-Math.round((h.getTime()-p.getTime())/864e5);e.send({state:d,sessionDaysLeft:v,massSessionDuration:g})}catch(t){e.send({error:t.message||t})}})),yo.delete(vo+"/massSession",(async function(t,e){try{const n=t.query.ids;if(!n)throw"session ids[] missing";const{route:r,dslabel:i,embedder:s}=t.query,a=t.query.route?$r.i.getPayloadFromHeaderAuth(t,t.query.route):null;if(!a)throw"missing credentials";const l=t.query.route?Zr(t.query,a):o().cachedir_massSession,c=[];for(const t of n){const e=y().join(l,t);m().unlink(e,(t=>{if(t)throw c.push(t),t}))}c.length||e.send({status:"ok"})}catch(t){e.send({error:t.message||t})}})),yo.get(vo+"/sessionIds",(async function(t,e){try{const{filename:n,route:r,dslabel:o,embedder:i}=t.query,s=$r.i.getPayloadFromHeaderAuth(t,r);if(!s.email)throw"invalid credentials: no jwt.email";if(s.dslabel!=o||s.route!=r||s.embedder!=i)throw"invalid credentials: mismatched payload";const a=Zr(t.query,s);if(!await m().promises.access(a).then((()=>!0)).catch((()=>!1)))return void e.send({status:"ok",sessionIds:[]});const l=await m().promises.readdir(a);e.send({status:"ok",sessionIds:l})}catch(t){e.status(401),e.send({error:t.message||t})}})),yo.get(vo+"/isoformbycoord",(async function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!t.query.chr)throw"chr missing";const r=Number(t.query.pos);if(!Number.isInteger(r))throw"pos must be positive integer";const i=n.tracks.find((t=>t.__isgene));i||reject("no gene track");const s=[];await P.UE({args:[y().join(o().tpmasterdir,i.file),t.query.chr+":"+r+"-"+r],callback:t=>{const e=t.split("\t")[3];if(!e)return;const r=JSON.parse(e);if(!r.isoform)return;const o={isoform:r.isoform},i=n.genedb.getjsonbyisoform.get(r.isoform);i&&(o.name=JSON.parse(i.genemodel).name,o.isdefault=i.isdefault),s.push(o)}}),e.send({lst:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/ase",(async function(t,e){const n=t.query,r=3e6,i=5e5;try{const t=fo[n.genome];if(!t)throw"invalid genome";if(!n.samplename)throw"samplename missing";if(!n.chr)throw"no chr";if(!n.start||!n.stop)throw"no start/stop";if(!n.rnabarheight)throw"no rnabarheight";if(!n.dnabarheight)throw"no dnabarheight";if(!Number.isInteger(n.barypad))throw"invalid barypad";if(n.rnamax&&!Number.isFinite(n.rnamax))throw"invalid value for rnamax";if(!n.checkrnabam)throw".checkrnabam{} missing";const s=Fo(n.checkrnabam);if(s)throw s;if(n.refcolor||(n.refcolor="blue"),n.altcolor||(n.altcolor="red"),!t.tracks)throw"genome.tracks[] missing";const a=t.tracks.find((t=>t.__isgene));if(!a)throw"no gene track from this genome";await async function(t,e){if(t.rnabamfile)t.rnabamfile=y().join(o().tpmasterdir,t.rnabamfile);else{if(!t.rnabamurl)throw"no file or url for rna bam";t.rnabamurl_dir=await P.d1(t.rnabamurl,t.rnabamindexURL||t.rnabamurl+".bai")}if(t.rnabam_nochr=await P.Dp(t.rnabamfile||t.rnabamurl,e,t.rnabamurl_dir),t.vcffile)t.vcffile=y().join(o().tpmasterdir,t.vcffile);else{if(!t.vcfurl)throw"no file or url for vcf";t.vcfurl_dir=await P.d1(t.vcfurl,t.vcfindexURL)}t.vcf_nochr=await P.Jy(t.vcffile||t.vcfurl,t.vcfurl_dir,e)}(n,t);const l=await Zo(t,a,n.chr,n.start,n.stop),c={};if(n.stop-n.start<r)for(const[t,e]of l){const t={file:n.rnabamfile,url:n.rnabamurl,dir:n.rnabamurl_dir,nochr:n.rnabam_nochr};let r;r=n.rnabamispairedend?await Eo(t,n.chr,e):await jo(t,n.chr,e),e.fpkm=1e9*r/(n.rnabamtotalreads*e.exonlength)}else c.fpkmrangelimit=r;const[u,f,d,h]=function(t,e){let n=t.start,r=t.stop;for(const[t,o]of e)n=Math.min(n,o.start),r=Math.max(r,o.stop);const o=t.start,i=t.stop;return[n,r,o,i]}(n,l),p=await async function(t,e,n,r,o){const i=await Uo(t.vcffile||t.vcfurl,t.vcfurl_dir),[s,a,l,c]=D.e(i);if(c)throw c;const u={info:s,format:a,samples:l},f=await zo(t.vcffile||t.vcfurl,(t.vcf_nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+o,t.vcfurl_dir),d=[];for(const e of f||[]){const[n,r,o]=D.S(e,u);for(const e of r){if(!F.basecolor[e.ref]||!F.basecolor[e.alt])continue;if(!e.sampledata)continue;const n=$o(e,t.samplename,t.checkrnabam);n&&d.push(n)}}const h=[];for(const t of d)for(const[e,r]of n)if(t.pos>=r.start&&t.pos<=r.stop){h.push(t);break}return h}(n,0,l,u,f);for(const t of p)t.rnacount={nocoverage:1};let g,v;h-d>=i?c.covplotrangelimit=i:(n.rnamax?g=n.rnamax:(g=await async function(t,e,n){let r=0;return await P.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:t=>{const e=t.split("\t");if(3!=e.length)return;const n=Number.parseInt(e[2]);Number.isInteger(n)&&(r=Math.max(r,n))}}),r}(n,d,h),c.rnamax=g),v=await async function(t,e,n,r,o){const i=new Map;for(const t of r)t.dnacount.ishet&&t.pos>=e&&t.pos<=n&&i.set(t.pos,t);const s=(0,S.createCanvas)(t.width*t.devicePixelRatio,(t.rnabarheight+t.barypad+t.dnabarheight)*t.devicePixelRatio),a=s.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio);let l,c,u=!1;n-e<=t.width?(u=!0,l=1,c=t.width/(n-e),a.lineWidth=c):(c=1,l=(n-e)/t.width);return await P.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:n=>{const r=n.split("\t");if(3!=r.length)return;const s=Number.parseInt(r[1])-1;if(!Number.isInteger(s))return;const f=Number.parseInt(r[2]);if(!Number.isInteger(f))return;const d=t.rnabarheight*Math.min(f,o)/o,h=u?(s-e)*c:(s-e)/l;a.strokeStyle="#ccc",a.beginPath(),a.moveTo(h+c/2,t.rnabarheight),a.lineTo(h+c/2,t.rnabarheight-d),a.stroke(),a.closePath(),f>o&&(a.strokeStyle="blue",a.beginPath(),a.moveTo(h+c/2,0),a.lineTo(h+c/2,2),a.stroke(),a.closePath());const p=i.get(s);p&&(p.rnacount.h=d)}}),{canvas:s,ctx:a,isbp:u,binpxw:c,binbpsize:l}}(n,d,h,p,g)),c.coveragesrc=await function(t,e,n,r,o,i,s,a){const l=[];for(const n of e)n.dnacount.ishet&&l.push((t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(n.pos+1)+"-"+(n.pos+1));return new Promise(((n,r)=>{const c=(0,q.spawn)(mo,["mpileup","-q",t.checkrnabam.rnapileup_q,"-Q",t.checkrnabam.rnapileup_Q,"--no-reference","-a","INFO/AD","-d",999999,"-r",l.join(","),t.rnabamurl||t.rnabamfile],{cwd:t.rnabamurl_dir});O().createInterface({input:c.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Lo(t);if(!n)return;let r;n.pos>=o&&n.pos<=i&&n.DP;const s=e.find((t=>t.pos==n.pos));if(s){s.__x=r;const t=n.allele2count[s.ref]||0,e=n.allele2count[s.alt]||0;t+e>0&&(delete s.rnacount.nocoverage,s.rnacount.ref=t,s.rnacount.alt=e,s.rnacount.f=e/(t+e))}})),c.on("close",(()=>{if(!s)return void n();const{canvas:r,ctx:l,binpxw:c}=s;l.lineWidth=Math.max(3,c);let u=0;for(const n of e)n.dnacount&&(n.pos<o||n.pos>i||(n.__x=t.width*(n.pos-o)/(i-o),u=Math.max(u,n.dnacount.ref+n.dnacount.alt)));for(const n of e){if(null==n.__x)continue;n.rnacount.nocoverage||(null==n.rnacount.h&&(n.rnacount.h=t.rnabarheight*(n.rnacount.ref+n.rnacount.alt)/a),l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight),l.lineTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.lineTo(n.__x+c/2,t.rnabarheight-n.rnacount.h),l.stroke(),l.closePath());const e=t.dnabarheight*(n.dnacount.ref+n.dnacount.alt)/u;n.dnacount.ishet&&(l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+e),l.stroke(),l.closePath()),delete n.__x}n(r.toDataURL())}))}))}(n,p,0,0,d,h,v,g),await async function(t,e){if(0==t.length)return;const n=[];for(const r of t)r.rnacount.nocoverage||r.rnacount.ref+r.rnacount.alt<e.checkrnabam.rna_mintotalreads||n.push(r);if(0==n.length)return;const r=await function(t){const e=y().join(o().cachedir,Math.random().toString())+".snp",n=[];for(const e of t)e.rnacount.nocoverage||null!=e.rnacount.ref&&null!=e.rnacount.alt&&n.push(e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt);return new Promise(((t,r)=>{m().writeFile(e,n.join("\n")+"\n",(n=>{n&&r("cannot write"),t(e)}))}))}(n),i=await Do(r);await function(t,e){return new Promise(((n,r)=>{m().readFile(e,"utf8",((e,o)=>{e&&r("cannot read binom pvalue"),o||n();for(const e of o.trim().split("\n")){const n=e.split("\t"),r=t.find((t=>n[0]==t.pos+"."+t.ref+"."+t.alt));r&&(r.rnacount.pvalue=Number.parseFloat(n[10]))}n()}))}))}(t,i),m().unlink(r,(()=>{})),m().unlink(i,(()=>{}))}(p,n),c.genes=function(t,e,n){const r=[];for(const[o,i]of e){r.push(i);const e=t.filter((t=>t.pos>=i.start&&t.pos<=i.stop));if(0==e.length){i.nosnp=1;continue}i.snps=e;const o=e.filter((t=>null!=t.rnacount.pvalue));if(0==o.length){i.nornasnp=1;continue}const s=o.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let a=null,l=0;for(const t of o)null==a?a=t.rnacount.pvalue:a*=t.rnacount.pvalue,t.rnacount.pvalue<=n.checkrnabam.binompvaluecutoff&&l++;i.ase={markers:e.filter((t=>t.dnacount.ishet)).length,ase_markers:l,mean_delta:s/o.length,geometricmean:Math.pow(a,1/o.length)}}return r}(p,l,n);let b=0;for(const t of p)t.dnacount&&t.pos>=d&&t.pos<=h&&(b=Math.max(b,t.dnacount.ref+t.dnacount.alt));c.dnamax=b,e.send(c)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/bamnochr",(async function(t,e){const n=t.query;try{const t=fo[n.genome];if(!t)throw"invalid genome";if(n.file)n.file=y().join(o().tpmasterdir,n.file);else{if(!n.url)throw"no bam file or url";n.url_dir=await P.d1(n.url,n.indexURL||n.url+".bai")}const r=await P.Dp(n.file||n.url,t,n.url_dir);e.send({nochr:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.get(vo+"/gene2canonicalisoform",(function(t,e){wo(t);try{if(!t.query.gene)throw".gene missing";const n=fo[t.query.genome];if(!n)throw"unknown genome";if(!n.genedb.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const r=n.genedb.get_gene2canonicalisoform.get(t.query.gene);e.send(r)}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/ideogram",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.genedb.hasIdeogram)throw"ideogram not supported on this genome";if(!t.query.chr)throw".chr missing";const r=n.genedb.getIdeogramByChr.all(t.query.chr);if(!r.length)throw"no ideogram data for this chr";e.send(r)}catch(t){e.send({error:t.message||t})}}));P.lY,P.ZX;function ei(t){const e=t.split(/\r?\n/);if(e.length<=1||!e[0])return[null,[]];const n=e[0].split("\t"),r=[];for(let t=1;t<e.length;t++){if("#"==e[t][0])continue;const o=e[t].split("\t"),i={};for(let t=0;t<n.length;t++){const e=o[t];e&&(i[n[t]]=e)}r.push(i)}return[null,r]}async function ni(t){try{await m().promises.stat(t.tpmasterdir)}catch(e){const n="Error with "+t.tpmasterdir+": "+e.code;if("validate"==process.argv[2])throw n;return void console.log("\n!!! "+n+"\n")}if(function(){if(o().features.skip_checkDependenciesAndVersions)return void console.log("SKIPPED checkDependenciesAndVersions()");const t=["jsonlite","cmprsk","hwde","lmtest"];for(const e of t){const t=N().spawnSync(o().Rscript,["-e",`suppressPackageStartupMessages(library("${e}"))`],{encoding:"utf8"});if(t.stderr.trim())throw t.stderr}const e=10;{const t=N().execSync(o().samtools+" --version",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("samtools"!=n||!r)throw'cannot run "samtools version"';const[i,s]=r.split(".");if("1"!=i)throw"samtools not 1.*";if(Number(s)<e)throw`samtools not >= 1.${e}`}{const t=N().execSync(o().bcftools+" -v",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("bcftools"!=n||!r)throw'cannot run "bcftools version"';const[i,s]=r.split(".");if("1"!=i)throw"bcftools not 1.*";if(Number(s)<e)throw`bcftools not >= 1.${e}`}}(),null!=t.base_zindex){const e=Number.parseInt(t.base_zindex);if(Number.isNaN(e)||e<=0)throw"base_zindex must be positive integer";t.base_zindex=e}if(t.jwt){if(!t.jwt.secret)throw"jwt.secret missing";if(!t.jwt.permissioncheck)throw"jwt.permissioncheck missing"}if(!t.tpmasterdir)throw".tpmasterdir missing";if(!t.cachedir)throw".cachedir missing";if(t.cachedir_massSession=await ii("massSession"),t.cachedir_massSessionTrash=await ii("massSessionTrash"),t.cache_snpgt={dir:await ii("snpgt"),fileNameRegexp:/[^\w]/,sampleColumn:6},t.cachedir_bam=await ii("bam"),t.cachedir_genome=await ii("genome"),t.cachedir_ssid=await ii("ssid"),t.commonOverrides&&F.applyOverrides(t.commonOverrides),!t.genomes)throw".genomes[] missing";if(!Array.isArray(t.genomes))throw".genomes[] not array";for(const e of t.genomes){if(!e.name)throw".name missing from a genome: "+JSON.stringify(e);if(!e.file)throw".file missing from genome "+e.name;const n=y().join(process.cwd(),e.file),r=require(m().existsSync(n)?n:e.file),o=r.default||r;if(fo[e.name]=o,!o.genomefile)throw".genomefile missing from .js file of genome "+e.name;if("NA"==o.genomefile||(o.genomefile=y().join(t.tpmasterdir,o.genomefile)),o.genomicNameRegexp||(o.genomicNameRegexp=/[^a-zA-Z0-9.:_-]/),o.tracks||(o.tracks=[]),e.tracks)for(const t of e.tracks)o.tracks.push(t);if(e.datasets&&(o.rawdslst=e.datasets),e.snp&&(o.snp=e.snp),e.blat){if(!e.blat.host)throw".blat.host missing for "+e.name;if(!e.blat.port)throw".blat.port missing for "+e.name;o.blat=e.blat}if(e.nosnp&&delete o.snp,e.nohicenzyme&&delete o.hicenzymefragment,e.nohicdomain&&delete o.hicdomain,o.genedb&&e.no_gene2canonicalisoform&&delete o.genedb.gene2canonicalisoform,e.updateAttr)for(const t of e.updateAttr){let e=o;for(const[n,r]of t.entries())if(e)if("object"==typeof r)for(const t in r)e[t]=r[t];else{if("string"==typeof e[r]){t[n+1]&&(e[r]=t[n+1]);break}e=e[r]}}}t.defaultgenome&&fo[t.defaultgenome]&&(fo[t.defaultgenome].isdefault=!0);for(const e in fo){const n=fo[e];if(!n.majorchr)throw e+": majorchr missing";if(!n.defaultcoord)throw e+": defaultcoord missing";if(await P.Kf(n,n.defaultcoord.chr+":"+n.defaultcoord.start+"-"+(n.defaultcoord.start+1)),n.tracks||(n.tracks=[]),"string"==typeof n.majorchr){const t=n.majorchr.trim().split(/[\s\t\n]+/),r={},o=[];for(let n=0;n<t.length;n+=2){const i=t[n],s=Number.parseInt(t[n+1]);if(Number.isNaN(s))throw e+" majorchr invalid chr size for "+i+" ("+t[n+1]+")";r[i]=s,o.push(i)}n.majorchr=r,n.majorchrorder=o}n.chrlookup={};for(const t in n.majorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.majorchr[t],major:!0};if(n.minorchr){if("string"==typeof n.minorchr){const t=n.minorchr.trim().split(/[\s\t\n]+/),r={};for(let n=0;n<t.length;n+=2){const o=Number.parseInt(t[n+1]);if(Number.isNaN(o))throw e+" minorchr invalid chr size for "+t[n]+" ("+t[n+1]+")";r[t[n]]=o}n.minorchr=r}for(const t in n.minorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.minorchr[t]}}if(n.genedb){if(!n.genedb.dbfile)throw e+": .genedb.dbfile missing";try{console.log("Connecting",n.genedb.dbfile),n.genedb.db=P.sE(n.genedb.dbfile)}catch(t){throw`Cannot connect genedb: ${n.genedb.dbfile}: ${t}`}n.genedb.getnamebynameorisoform=n.genedb.db.prepare("select name from genes where name=? or isoform=?"),n.genedb.getnamebyisoform=n.genedb.db.prepare("select distinct name from genes where isoform=?"),n.genedb.getjsonbyname=n.genedb.db.prepare("select isdefault,genemodel from genes where name=?"),n.genedb.getjsonbyisoform=n.genedb.db.prepare("select isdefault,genemodel from genes where isoform=?"),n.genedb.getnameslike=n.genedb.db.prepare("select distinct name from genes where name like ? limit 20");const t=(0,Gn.jj)(n.genedb.db);t.has("genealias")&&(n.genedb.getNameByAlias=n.genedb.db.prepare("select name from genealias where alias=?"),n.genedb.getAliasByName=n.genedb.db.prepare("select alias from genealias where name=?")),t.has("gene2coord")&&(n.genedb.getCoordByGene=n.genedb.db.prepare("select * from gene2coord where name=?")),t.has("ideogram")?(n.genedb.hasIdeogram=!0,n.genedb.getIdeogramByChr=n.genedb.db.prepare("select * from ideogram where chromosome=?")):n.genedb.hasIdeogram=!1,t.has("gene2canonicalisoform")&&(n.genedb.get_gene2canonicalisoform=n.genedb.db.prepare("select isoform from gene2canonicalisoform where gene=?")),t.has("buildDate")&&(n.genedb.get_buildDate=n.genedb.db.prepare("select date from buildDate")),n.genedb.hasTable_refseq2ensembl=t.has("refseq2ensembl"),n.genedb.sqlTables=[...t],n.genedb.tableSize={};for(const e of t)"buildDate"!=e&&(n.genedb.tableSize[e]=n.genedb.db.prepare(`select count(*) as size from ${e}`).get().size)}if(n.termdbs)for(const t in n.termdbs)(0,Gn.JV)(n.termdbs[t],uo),console.log(`${t} initiated as ${e}-level termdb`);for(const e of n.tracks)if(e.__isgene){if(!e.file)throw"Tabix file missing for gene track: "+JSON.stringify(e);try{await P.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}if(n.proteindomain){if(!n.proteindomain.dbfile)throw e+".proteindomain: missing dbfile for sqlite db";if(!n.proteindomain.statement)throw e+".proteindomain: missing statement for sqlite db";let t;try{console.log("Connecting",n.proteindomain.dbfile),t=P.sE(n.proteindomain.dbfile)}catch(t){throw"Error with "+n.proteindomain.dbfile+": "+t}n.proteindomain.getbyisoform=t.prepare(n.proteindomain.statement)}if(n.snp){if(!n.snp.bigbedfile)throw e+".snp: missing bigBed file";n.snp.bigbedfile=y().join(t.tpmasterdir,n.snp.bigbedfile),await P.Ic(n.snp.bigbedfile)}if(n.fimo_motif){if(!n.fimo_motif.db)throw e+".fimo_motif: db file missing";if(n.fimo_motif.db=y().join(t.tpmasterdir,n.fimo_motif.db),n.fimo_motif.annotationfile){const[e,r]=ei(m().readFileSync(y().join(t.tpmasterdir,n.fimo_motif.annotationfile),{encoding:"utf8"}).trim());n.fimo_motif.tf2attr={};for(const t of r)n.fimo_motif.tf2attr[t.Model.split("_")[0]]=t}}if(n.hicenzymefragment){if(!Array.isArray(n.hicenzymefragment))throw"hicenzymefragment should be an array";for(const e of n.hicenzymefragment){if(!e.enzyme)throw".enzyme missing for one element of hicenzymefragment[]";if(!e.file)throw".file missing for one element of hicenzymefragment[]";try{await P.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}}if(n.hicdomain){if(!n.hicdomain.groups)throw".groups{} missing from hicdomain";for(const e in n.hicdomain.groups){const r=n.hicdomain.groups[e];if(!r.name)throw".name missing from hicdomain "+e;if(!r.sets)throw".set{} missing from hicdomain "+e;for(const n in r.sets){const o=r.sets[n];if(!o.name)throw".name missing from hicdomain "+e+" > "+n;if(!o.file)throw".file missing from hicdomain "+e+" > "+n;o.file=y().join(t.tpmasterdir,o.file);try{await P.LC(o.file)}catch(t){throw"Error with "+o.file+": "+t}}}}if(n.rawdslst){n.datasets={};for(const t of n.rawdslst){if(!t.name)throw"a nameless dataset from "+e;if(n.datasets[t.name])throw e+" has duplicating dataset name: "+t.name;if(!t.jsfile)throw"jsfile not available for dataset "+t.name+" of "+e;const r=y().join(process.cwd(),t.jsfile),o=require(m().existsSync(r)?r:t.jsfile),i="function"==typeof o?o(F):"function"==typeof(null==o?void 0:o.default)?o.default(F):o.default||o;if(Jn(i,t),i.noHandleOnClient=t.noHandleOnClient,i.label=t.name,i.genomename=e,n.datasets[i.label]=i,i.isMds3)try{await Qn(i,n,0,yo,vo)}catch(t){throw t.stack&&console.log(t.stack),"Error with mds3 dataset "+i.label+": "+t}else if(i.isMds)try{await ai(i,n,t)}catch(t){throw"Error with mds dataset "+i.label+": "+t}else oi(i,n)}ri(),delete n.rawdslst}}}async function ri(){const t=await m().promises.readdir(o().cachedir_massSession);try{t.forEach((async t=>{const e=(await m().promises.stat(y().join(o().cachedir_massSession,t))).birthtime,n=new Date,r=new Date(e),i=o().features.massSessionDuration||30;Math.round((n.getTime()-r.getTime())/864e5)>i&&(await m().promises.copyFile(y().join(o().cachedir_massSession,t),y().join(o().cachedir_massSessionTrash,t)),await m().promises.unlink(y().join(o().cachedir_massSession,t)),console.log("File deleted: ",t,e))}))}catch(t){throw`Error: ${t}`}}function oi(t,e){if(t.dbfile)try{console.log("Connecting",t.dbfile),t.newconn=P.sE(t.dbfile)}catch(e){throw"Error with "+t.dbfile+": "+e}if(t.snvindel_attributes)for(const e of t.snvindel_attributes)if(e.lst)for(const t of e.lst)t.get=t.get.toString();else e.get=e.get.toString();if(t.cohort){if(t.cohort.levels){if(!Array.isArray(t.cohort.levels))throw"cohort.levels must be array for "+t.genomename+"."+t.label;if(0==t.cohort.levels.length)throw"levels is blank array for cohort of "+t.genomename+"."+t.label;for(const e of t.cohort.levels)if(!e.k)throw".k key missing in one of the levels, .cohort, in "+t.genomename+"."+t.label}if(t.cohort.fromdb){if(!t.cohort.fromdb.sql)throw".sql missing from ds.cohort.fromdb in "+t.genomename+"."+t.label;const e=t.newconn.prepare(t.cohort.fromdb.sql).all();delete t.cohort.fromdb,t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.files){let e=[];for(const n of t.cohort.files){if(!n.file)throw".file missing from one of cohort.files[] for "+t.genomename+"."+t.label;const r=m().readFileSync(y().join(o().tpmasterdir,n.file),"utf8").trim();if(!r)throw n.file+" is empty for "+t.genomename+"."+t.label;e=[...e,...W.tJ(r)]}delete t.cohort.files,t.cohort.raw?t.cohort.raw=[...t.cohort.raw,...e]:t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.tosampleannotation){if(!t.cohort.tosampleannotation.samplekey)throw".samplekey missing from .cohort.tosampleannotation for "+t.genomename+"."+t.label;if(!t.cohort.key4annotation)throw".cohort.key4annotation missing when .cohort.tosampleannotation is on for "+t.genomename+"."+t.label}}if(!t.queries)throw".queries missing from dataset "+t.label+", "+t.genomename;if(!Array.isArray(t.queries))throw t.label+".queries is not array";for(const n of t.queries){const r=si(n,t,e);if(r)throw'Error parsing a query in "'+t.label+'": '+r}if(t.vcfinfofilter){const e=F.validate_vcfinfofilter(t.vcfinfofilter);if(e)throw t.label+": vcfinfofilter error: "+e}if(t.url4variant)for(const e of t.url4variant){if(!e.makelabel)throw"makelabel() missing for one item of url4variant from "+t.label;if(!e.makeurl)throw"makeurl() missing for one item of url4variant from "+t.label;e.makelabel=e.makelabel.toString(),e.makeurl=e.makeurl.toString()}}async function ii(t){const e=y().join(o().cachedir,t);try{await m().promises.stat(e)}catch(t){if("ENOENT"!=t.code)throw"error stating dir";try{await m().promises.mkdir(e)}catch(t){throw"cannot make dir"}}return e}function si(t,e,n){if(!t.name)return".name missing";if(t.dsblocktracklst){if(!Array.isArray(t.dsblocktracklst))return"dsblocktracklst not an array in "+e.label;for(const n of t.dsblocktracklst){if(!n.type)return"missing type for a blocktrack of "+e.label;if(!n.file&&!n.url)return"neither file or url given for a blocktrack of "+e.label}}else if(t.vcffile){const e=N().execSync(ho+" -H "+y().join(o().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==e)return"no meta lines in VCF file "+t.vcffile+" of query "+t.name;const[r,i,s,a]=D.e(e.split("\n"));if(a)return"error parsing VCF meta lines of "+t.vcffile+": "+a.join("; ");t.vcf={vcfid:Math.random().toString(),info:r,format:i,samples:s},t.hlinfo&&(t.vcf.hlinfo=t.hlinfo,delete t.hlinfo),t.infopipejoin&&(t.vcf.infopipejoin=t.infopipejoin,delete t.infopipejoin);const l=N().execSync(ho+" -l "+y().join(o().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==l)return"tabix -l found no chromosomes/contigs in "+t.vcffile+" of query "+t.name;t.vcf.nochr=F.contigNameNoChr(n,l.split("\n"));let c=0;if(r)for(const t in r)c++;console.log("Parsed vcf meta from "+t.vcffile+": "+c+" INFO, "+s.length+" sample, "+(t.vcf.nochr?'no "chr"':'has "chr"'))}else{if(!t.makequery)return"do not know how to parse query: "+t.name;if(t.isgeneexpression){if(!t.config)return"config object missing for gene expression query of "+t.name;t.config.maf&&(t.config.maf.get=t.config.maf.get.toString())}}}async function ai(t,e,n){if((t.isMds2||t.isMds3||t.isMds)&&Jn(t,n),t.assayAvailability){if(!t.assayAvailability.file)throw".assayAvailability.file missing";if(!t.assayAvailability.assays)throw".assayAvailability.assays[] missing";Object.freeze(t.assayAvailability.assays),t.assayAvailability.samples=new Map;for(const e of m().readFileSync(y().join(o().tpmasterdir,t.assayAvailability.file),{encoding:"utf8"}).trim().split("\n")){const[n,r]=e.split("\t");t.assayAvailability.samples.set(n,JSON.parse(r))}console.log(t.assayAvailability.samples.size+" samples with assay availability ("+t.label+")")}if(t.gene2mutcount){if(!t.gene2mutcount.dbfile)throw".gene2mutcount.dbfile missing";try{console.log("Connecting",t.gene2mutcount.dbfile),t.gene2mutcount.db=P.sE(t.gene2mutcount.dbfile),console.log("DB connected for "+t.label+": "+t.gene2mutcount.dbfile)}catch(e){throw`Error connecting db at ${t.gene2mutcount.dbfile}`}}if(t.sampleAssayTrack){if(!t.sampleAssayTrack.file)throw".file missing from sampleAssayTrack";t.sampleAssayTrack.samples=new Map;let e=0,n=new Set;for(const r of m().readFileSync(y().join(o().tpmasterdir,t.sampleAssayTrack.file),{encoding:"utf8"}).trim().split("\n")){if(!r)continue;if("#"==r[0])continue;const[o,i,s]=r.split("\t");if(!i||!s)continue;if(!t.sampleAssayTrack.samples.has(o)){if(t.cohort&&t.cohort.annotation&&!t.cohort.annotation[o]){n.add(o);continue}t.sampleAssayTrack.samples.set(o,[])}const a=JSON.parse(s);if(!F.tkt[a.type])throw"invalid type from a sample track: "+s;a.name||(a.name=o+" "+i),a.assayName=i,t.sampleAssayTrack.samples.get(o).push(a),e++}console.log(e+" assay-tracks from "+t.sampleAssayTrack.samples.size+" samples ("+t.label+")"),n.size&&console.log("Error: "+n.size+" samples with assay tracks are unannotated: "+[...n].join(" "))}if(t.singlesamplemutationjson){const e=t.singlesamplemutationjson;if(!e.file)throw".file missing from singlesamplemutationjson";e.samples={};let n=0;for(const t of m().readFileSync(y().join(o().tpmasterdir,e.file),{encoding:"utf8"}).trim().split("\n")){if(!t)continue;if("#"==t[0])continue;const[r,o]=t.split("\t");r&&o&&(n++,e.samples[r]=o)}console.log(n+" samples for disco plot")}if(t.cohort&&t.cohort.db&&t.cohort.termdb&&await kr(t,yo,vo),t.cohort&&t.cohort.files){if(!Array.isArray(t.cohort.files))throw".cohort.files is not array";if(!t.cohort.tohash)throw".tohash() missing from cohort";if("function"!=typeof t.cohort.tohash)throw".cohort.tohash is not function";if(!t.cohort.samplenamekey)throw".samplenamekey missing";if(t.cohort.annotation={},t.cohort.mutation_signature){const e=t.cohort.mutation_signature;if(!e.sets)throw".mutation_signature.sets missing";for(const n in e.sets){const r=e.sets[n];if(r.name||(r.name=n),!r.signatures)throw".signatures{} missing from a signature set";if(r.samples){if(!r.samples.file)throw".samples.file missing from a signature set";const[e,n]=ei(m().readFileSync(y().join(o().tpmasterdir,r.samples.file),{encoding:"utf8"}).trim());r.samples.map=new Map;for(const e of n){const n=e[t.cohort.samplenamekey];if(!n)throw t.cohort.samplenamekey+" missing in file "+r.samples.file;r.samples.map.set(n,e);for(const t in r.signatures)if(e[t]){const o=Number.parseFloat(e[t]);if(Number.isNaN(o))throw"mutation signature value is not float: "+e[t]+" from sample "+n;r.samples.skipzero&&0==o?delete e[t]:e[t]=o}}}}}if(t.cohort.attributes){if(!t.cohort.attributes.lst)throw".lst[] missing for cohort.attributes";if(!Array.isArray(t.cohort.attributes.lst))return".cohort.attributes.lst is not array";for(const e of t.cohort.attributes.lst){if(!e.key)throw".key missing from one of the .cohort.attributes.lst[]";if(!e.label)throw".label missing from one of the .cohort.attributes.lst[]";if(!e.values)throw".values{} missing from "+e.label+" of .cohort.attributes.lst";for(const t in e.values)if(!e.values[t].label)throw".label missing from one value of "+e.label+" in .cohort.attributes.lst"}if(t.cohort.attributes.defaulthidden)for(const e in t.cohort.attributes.defaulthidden){const n=t.cohort.attributes.lst.find((t=>t.key==e));if(!n)throw"invalid defaulthidden key: "+e;for(const r in t.cohort.attributes.defaulthidden[e])if(!n.values[r])throw"invalid defaulthidden value "+r+" for "+e}}if(t.cohort.hierarchies){if(!t.cohort.hierarchies.lst)throw".lst[] missing from .cohort.hierarchies";if(!Array.isArray(t.cohort.hierarchies.lst))throw".cohort.hierarchies.lst is not array";for(const e of t.cohort.hierarchies.lst){if(!e.name)throw".name missing from one hierarchy";if(!e.levels)throw".levels[] missing from one hierarchy";if(!Array.isArray(e.levels))throw".levels is not array from one hierarchy";for(const t of e.levels)if(!t.k)throw".k missing from one level in hierarchy "+e.name}}if(t.cohort.sampleAttribute){if(!t.cohort.sampleAttribute.attributes)throw"attributes{} missing from cohort.sampleAttribute";for(const e in t.cohort.sampleAttribute.attributes){const n=t.cohort.sampleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from cohort.sampleAttribute.attributes";if(n.values)for(const t in n.values){const e=n.values[t];if("object"!=typeof e)throw'value "'+t+'" not pointing to {} from sampleAttribute';e.name||(e.name=t)}if(n.showintrack&&!n.isinteger&&!n.isfloat)throw n.label+": .showintrack requires .isinteger or .isfloat"}}if(t.cohort.scatterplot){if(!t.cohort.sampleAttribute)throw".sampleAttribute missing but required for .cohort.scatterplot";const e=t.cohort.scatterplot;if(!e.querykey)throw".querykey missing from .cohort.scatterplot";{if(!t.queries)throw".cohort.scatterplot.querykey in use but ds.queries{} missing";const n=t.queries[e.querykey];if(!n)throw"unknown query by .cohort.scatterplot.querykey: "+e.querykey;if(n.type!=F.tkt.mdssvcnv)throw"type is not "+F.tkt.mdssvcnv+" of the track pointed to by .cohort.scatterplot.querykey"}if(e.colorbygeneexpression){if(!e.colorbygeneexpression.querykey)throw"querykey missing from .cohort.scatterplot.colorbygeneexpression";if(!t.queries)throw".cohort.scatterplot.colorbygeneexpression in use but ds.queries{} missing";const n=t.queries[e.colorbygeneexpression.querykey];if(!n)throw"unknown query by .cohort.scatterplot.colorbygeneexpression.querykey: "+e.colorbygeneexpression.querykey;if(!n.isgenenumeric)throw"isgenenumeric missing from the track pointed to by .cohort.scatterplot.colorbygeneexpression.querykey"}if(e.tracks,!e.x)throw".x missing from .cohort.scatterplot";if(!e.x.attribute)throw".attribute missing from .cohort.scatterplot.x";const n=t.cohort.sampleAttribute.attributes[e.x.attribute];if(!n)throw"scatterplot.x.attribute is not defined in sampleAttribute";if(!n.isfloat)throw'scatterplot.x is not "isfloat"';if(!e.y)throw".y missing from .cohort.scatterplot";if(!e.y.attribute)throw".attribute missing from .cohort.scatterplot.y";const r=t.cohort.sampleAttribute.attributes[e.y.attribute];if(!r)throw"scatterplot.y.attribute is not defined in sampleAttribute";if(!r.isfloat)throw'scatterplot.y is not "isfloat"';if(e.colorbyattributes)for(const n of e.colorbyattributes){if(!n.key)throw".key missing from one of scatterplot.colorbyattributes";const e=t.cohort.sampleAttribute.attributes[n.key];if(!e)throw"unknown attribute by key "+n.key+" from scatterplot.colorbyattributes";n.label=e.label,n.values=e.values}}for(const e of t.cohort.files){if(!e.file)throw".file missing from one of .cohort.files";const[n,r]=ei(m().readFileSync(y().join(o().tpmasterdir,e.file),{encoding:"utf8"}).trim());if(n)throw'cohort annotation file "'+e.file+'": '+n;console.log(t.label+": "+r.length+" samples loaded from annotation file "+e.file),r.forEach((e=>{for(const n in e){let r;t.cohort.sampleAttribute&&(r=t.cohort.sampleAttribute.attributes[n]),r||t.cohort.termdb&&t.cohort.termdb.termjson&&t.cohort.termdb.termjson.map&&(r=t.cohort.termdb.termjson.map.get(n)),r&&(r.isfloat?e[n]=Number.parseFloat(e[n]):r.isinteger&&(e[n]=Number.parseInt(e[n])))}t.cohort.tohash(e,t)}))}if(t.cohort.annorows=Object.values(t.cohort.annotation),console.log(t.label+": total samples from sample table: "+t.cohort.annorows.length),t.cohort.survivalplot){const e=t.cohort.survivalplot;if(!e.plots)throw".plots{} missing from survivalplot";e.init={plottypes:[]};for(const t in e.plots){const n=e.plots[t];if(!n.name)throw".name missing from survivalplot "+t;if(!n.serialtimekey)throw".serialtimekey missing from survivalplot "+t;if(!n.iscensoredkey)throw".iscensoredkey missing from survivalplot "+t;if(!n.timelabel)throw".timelabel missing from survivalplot "+t;n.key=t,e.init.plottypes.push({key:t,name:n.name,timelabel:n.timelabel})}if(e.samplegroupattrlst){e.init.samplegroupings=[];for(const n of e.samplegroupattrlst){if(!n.key)throw".key missing from an attr of samplegroupattrlst for survival";const r=t.cohort.sampleAttribute.attributes[n.key];if(!r)throw'unknown attribute key "'+n.key+'" from survival samplegroupattrlst';const o=new Map;for(const r in t.cohort.annotation){const i=t.cohort.annotation[r],s=i[n.key];if(null==s)continue;let a=!1;for(const t in e.plots)if(null!=i[e.plots[t].serialtimekey]){a=!0;break}a&&(o.has(s)?o.set(s,o.get(s)+1):o.set(s,1))}if(0==o.size)throw'no value found for "'+n.key+'" from survival samplegroupattrlst';const i=[];for(const[t,e]of o)i.push({value:t,count:e});e.init.samplegroupings.push({key:n.key,label:r.label,values:i})}}}}if(t.mutationAttribute){if(!t.mutationAttribute.attributes)throw"attributes{} missing from mutationAttribute";for(const e in t.mutationAttribute.attributes){const n=t.mutationAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from mutationAttribute.attributes";if(!n.appendto_link&&n.values)for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from mutationAttribute.attributes"}}}if(t.alleleAttribute){if(!t.alleleAttribute.attributes)throw"attributes{} missing from alleleAttribute";for(const e in t.alleleAttribute.attributes){const n=t.alleleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from alleleAttribute.attributes";if(!n.isnumeric){if(!n.values)throw".values{} missing for non-numeric key "+e+" from alleleAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from alleleAttribute.attributes"}}}}if(t.locusAttribute){if(!t.locusAttribute.attributes)throw"attributes{} missing from locusAttribute";for(const e in t.locusAttribute.attributes){const n=t.locusAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from locusAttribute.attributes";if(!n.isnumeric&&!n.appendto_link){if(!n.values)throw".values{} missing for non-numeric key "+e+" from locusAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from locusAttribute.attributes"}}}}if(t.queries)for(const r in t.queries){if(n.remove_queries&&-1!=n.remove_queries.indexOf(r)){delete t.queries[r];continue}const o=t.queries[r];if(n.hide_queries&&-1!=n.hide_queries.indexOf(r)&&(o.hideforthemoment=1),o.istrack){if(!o.type)throw".type missing for track query "+r;if(o.viewrangeupperlimit&&!Number.isInteger(o.viewrangeupperlimit))throw".viewrangeupperlimit should be integer for track query "+r;if(o.type==F.tkt.mdsjunction){const n=ci(o,t,e);if(n)throw r+" (mdsjunction) error: "+n}else if(o.type==F.tkt.mdscnv){const n=di(o,t,e);if(n)throw r+" (mdscnv) error: "+n}else if(o.type==F.tkt.mdssvcnv){const n=hi(o,t,e);if(n)throw r+" (svcnv) error: "+n}else{if(o.type!=F.tkt.mdsvcf)throw"unknown track type for a query: "+o.type+" "+r;{const n=await mi(o,t,e);if(n)throw r+" (vcf) error: "+n}}li(o,t)}else{if(!o.isgenenumeric)throw"unknown type of query from "+r;{const n=pi(o,t,e);if(n)throw r+" (genenumeric) error: "+n}}}if(t.track&&await qr(t,e),t.annotationsampleset2matrix){if(!t.cohort)throw"ds.cohort misssing when annotationsampleset2matrix is in use";if(!t.cohort.annotation)throw"ds.cohort.annotation misssing when annotationsampleset2matrix is in use";if(!t.queries)throw"ds.queries misssing when annotationsampleset2matrix is in use";if(!t.annotationsampleset2matrix.key)throw".key STR missing in annotationsampleset2matrix";if(!t.annotationsampleset2matrix.groups)throw".groups{} missing in annotationsampleset2matrix";if("object"!=typeof t.annotationsampleset2matrix.groups)throw"ds.annotationsampleset2matrix.groups{} not an object";for(const e in t.annotationsampleset2matrix.groups){const n=t.annotationsampleset2matrix.groups[e];if(!n.groups||!Array.isArray(n.groups)||0==n.groups.length)throw".groups[] must be nonempty array in "+e;for(const r of n.groups){if(!r.name)throw".name missing from one of .groups[] in "+e;const n=r.matrixconfig;if(!n)throw".matrixconfig missing from one of .groups[] of "+e;if(!n.features)throw".features[] missing from group "+e;if(!Array.isArray(n.features))throw".features[] should be array from group "+e;if(0==n.features.length)throw".features[] zero length from group "+e;for(const r of n.features){if(t.annotationsampleset2matrix.commonfeatureattributes)for(const e in t.annotationsampleset2matrix.commonfeatureattributes)null==r[e]&&(r[e]=t.annotationsampleset2matrix.commonfeatureattributes[e]);if(!r.ismutation)return"unknown feature type from group "+e;if(!r.position)throw"position missing from feature "+JSON.stringify(r)+" from group "+e;if(!r.querykeylst)throw".querykeylst[] missing from ismutation feature from group "+e;if(!Array.isArray(r.querykeylst))throw".querykeylst[] not an array from ismutation feature from group "+e;if(0==r.querykeylst.length)throw".querykeylst[] zero length from ismutation feature from group "+e;for(const n of r.querykeylst)if(!t.queries[n])throw'unknown query key "'+n+'" from ismutation feature of group '+e}if(!n.limitsamplebyeitherannotation)throw".limitsamplebyeitherannotation[] missing from group "+e;if(!Array.isArray(n.limitsamplebyeitherannotation))throw".limitsamplebyeitherannotation[] should be array from group "+e;if(0==n.limitsamplebyeitherannotation.length)throw".limitsamplebyeitherannotation[] zero length from group "+e;for(const t of n.limitsamplebyeitherannotation){if(!t.key)throw"key missing from one of limitsamplebyeitherannotation from group "+e;if(!t.value)throw"value missing from one of limitsamplebyeitherannotation from group "+e}}}delete t.annotationsampleset2matrix.commonfeatureattributes}}function li(t,e){if(t.groupsamplebyattr){t.groupsamplebyattr.key2group=new Map;for(const n in e.cohort.annotation)Po(n,[],t.groupsamplebyattr.key2group,[],e,t)}}function ci(t,e,n){if(t.readcountCutoff&&(!Number.isInteger(t.readcountCutoff)||t.readcountCutoff<1))return"readcountCutoff must be positive integer";let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;t.file=n,r=n}else{if(!t.url)return"no file or url given for mdsjunction "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=i.split("\n");if(1!=n.length)return"mdsjunction file has multiple header lines (begin with #), but should have just 1";const r=n[0].split("\t");if(r[5]){t.samples=r.slice(5),t.attributeSummary=ui(t.samples,e),t.hierarchySummary=fi(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}if(console.log("(mdsjunction) "+t.name+": "+(t.samples?t.samples.length:0)+" samples, "+(t.nochr?'no "chr"':'has "chr"')),!t.infoFilter)return".infoFilter{} missing";if(!t.infoFilter.lst)return".lst[] missing from .infoFilter";for(const e of t.infoFilter.lst){if(!e.key)return".key missing from one of infoFilter";if(!e.label)return".label missing from one of infoFilter";if(!e.categories)return".categories missing from one of infoFilter";for(const t in e.categories){if(!e.categories[t].label)return".label missing from one category of "+e.label;if(!e.categories[t].color)return".color missing from on category of "+e.label}if(e.hiddenCategories){for(const t in e.hiddenCategories)if(!e.categories[t])return"invalid hidden key "+t+" of "+e.label}else e.hiddenCategories={}}if(!t.singlejunctionsummary)return".singlejunctionsummary missing but is currently required from "+t.name;if(t.singlejunctionsummary.readcountboxplotpercohort){if(!t.singlejunctionsummary.readcountboxplotpercohort.groups)return".groups[] missing from query.singlejunctionsummary.readcountboxplotpercohort for "+t.name;for(const e of t.singlejunctionsummary.readcountboxplotpercohort.groups){if(!e.key)return".key missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups";if(!e.label)return".label missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups"}}}function ui(t,e){if(!(e.cohort&&e.cohort.annotation&&e.cohort.attributes&&t))return;const n={};for(const r of e.cohort.attributes.lst){const o={};for(const t in r.values)o[t]=0;for(const n of t){const t=e.cohort.annotation[n];if(!t)continue;const i=t[r.key];null!=i&&(i in o&&o[i]++)}n[r.key]=o}return n}function fi(t,e){if(!e.cohort||!e.cohort.annotation||!e.cohort.hierarchies||0==t.length)return;const n=[];for(const r of t){const t=e.cohort.annotation[r];t&&n.push(t)}const r={};for(const t of e.cohort.hierarchies.lst){const e=(0,A.N)(n,t.levels),o=(0,V.Z)()(e);o.sum((t=>t.value));const i={};o.eachBefore((t=>{i[t.id]=t.value})),r[t.name]=i}return r}function di(t,e,n){let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (mdscnv) "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=i.split("\n");if(1!=n.length)return"mdscnv file has multiple header lines (begin with #), but should have just 1";const r=n[0].split("\t");t.samples=r.slice(5),t.attributeSummary=ui(t.samples,e),t.hierarchySummary=fi(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function hi(t,e,n){let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (svcnv) "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=new Set;for(const t of i.split("\n"))for(const e of t.split(" ").slice(1))n.add(e);if(0==n.size)return"no samples from the header line";if(t.samples=[...n],e.cohort&&e.cohort.annotation){const n=new Set;for(const r of t.samples)e.cohort.annotation[r]||n.add(r);n.size&&console.log("mdssvcnv unannotated samples: "+(t.noprintunannotatedsamples?n.size:[...n].join(" ")))}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}if(t.expressionrank_querykey){const n=e.queries[t.expressionrank_querykey];if(!n)return"invalid key by expressionrank_querykey";if(!n.isgenenumeric)return"query "+t.expressionrank_querykey+" not tagged as isgenenumeric"}if(t.vcf_querykey){const n=e.queries[t.vcf_querykey];if(!n)return"invalid key by vcf_querykey";if(n.type!=F.tkt.mdsvcf)return"query "+t.vcf_querykey+" not of mdsvcf type"}if(t.groupsamplebyattr){if(!t.groupsamplebyattr.attrlst)return".attrlst[] missing from groupsamplebyattr";if(0==t.groupsamplebyattr.attrlst.length)return"groupsamplebyattr.attrlst[] empty array";if(!e.cohort)return"groupsamplebyattr in use but ds.cohort missing";if(!e.cohort.annotation)return"groupsamplebyattr in use but ds.cohort.annotation missing";e.cohort.sampleAttribute||(e.cohort.sampleAttribute={}),e.cohort.sampleAttribute.attributes||(e.cohort.sampleAttribute.attributes={},console.log("cohort.sampleAttribute added when groupsamplebyattr is in use"));for(const n of t.groupsamplebyattr.attrlst){if(!n.k)return"k missing from one of groupsamplebyattr.attrlst[]";e.cohort.sampleAttribute.attributes[n.k]||(e.cohort.sampleAttribute.attributes[n.k]={label:n.label||n.k})}if(t.groupsamplebyattr.sortgroupby){if(!t.groupsamplebyattr.sortgroupby.key)return".key missing from .sortgroupby";if(!t.groupsamplebyattr.sortgroupby.order)return".order[] missing from .sortgroupby";if(!Array.isArray(t.groupsamplebyattr.sortgroupby.order))return".order must be an array"}t.groupsamplebyattr.attrnamespacer||(t.groupsamplebyattr.attrnamespacer=", ")}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function pi(t,e,n){if(!t.datatype)return"datatype missing";if(t.viewrangeupperlimit&&Number.isNaN(t.viewrangeupperlimit))return"invalid value for viewrangeupperlimit";let r;if(!t.file)return"file missing";{const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}const o={cwd:null,encoding:"utf8"};{const e=N().execSync(ho+" -H "+r,o).trim();if(!e)return"no header line (#sample <sample1> ...)";const n=new Set;for(const t of e.split("\n")){const e=t.split(" ");for(let t=1;t<e.length;t++)n.add(e[t])}if(0==n.size)return"no sample names from header line";t.samples=[...n],console.log("(genenumeric) "+t.name+": "+t.samples.length+" samples")}if(t.boxplotbysamplegroup){if(!t.boxplotbysamplegroup.attributes)return"boxplotbysamplegroup.attributes missing";if(!Array.isArray(t.boxplotbysamplegroup.attributes))return"boxplotbysamplegroup.attributes should be array";for(const e of t.boxplotbysamplegroup.attributes)if(!e.k)return"k missing from one of boxplotbysamplegroup.attributes[]"}}async function mi(t,e,n){if(!t.tracks)return"tracks[] missing";if(!Array.isArray(t.tracks))return"tracks should be array";t.info={};for(const r of t.tracks){if(!r.file)return"file missing from a track (url not supported yet)";const[o,i]=ti(r.file);if(o)return"tabix file error: "+o;if(r.type!=F.mdsvcftype.vcf)return"invalid track type: "+r.type;{r.cwd;const e=await P.ZD(i,r.cwd);if(0==e.length)return"no meta/header lines for "+i;const[n,o,s,a]=D.e(e);if(a)return"error parsing vcf meta for "+i+": "+a.join("\n");if(0==s.length)return"vcf file has no sample: "+i;for(const e in n)t.info[e]=n[e];if(r.format=o,r.samplenameconvert){if("function"!=typeof r.samplenameconvert)return".samplenameconvert must be function";for(const t of s)t.name=r.samplenameconvert(t.name)}r.samples=s}if(e.cohort&&e.cohort.annotation){const t=[];for(const n of r.samples)e.cohort.annotation[n.name]||t.push(n.name);t.length&&console.log(e.label+": VCF "+r.file+" has unannotated samples: "+t.join(","))}{const t=[];if(await P.UE({args:["-l",i],dir:r.cwd,callback:e=>{t.push(e)}}),0==t.length)return"no chr from "+i;r.nochr=F.contigNameNoChr(n,t)}console.log("("+t.type+") "+i+": "+r.samples.length+" samples, "+(r.nochr?"no chr":"has chr"))}if(t.singlesamples){if(!t.singlesamples.tablefile)return".singlesamples.tablefile missing for the VCF query";t.singlesamples.samples={};let e=0;for(const n of m().readFileSync(y().join(o().tpmasterdir,t.singlesamples.tablefile),{encoding:"utf8"}).trim().split("\n")){if(!n)continue;if("#"==n[0])continue;const r=n.split("\t");r[0]&&r[1]&&(t.singlesamples.samples[r[0]]=r[1],e++)}console.log(e+" single-sample VCF files")}}},6191:(t,e,n)=>{"use strict";n.d(e,{i:()=>y});var r=n(7147),o=n(1017),i=n.n(o),s=n(9344),a=n.n(s),l=n(8088);async function c(t,e){!function(t){for(const e in t){const n=t[e];if("login"==n.type){if(n.embedders)throw"unexpected 'embedders' property";n["*"]={"*":{type:"basic",password:n.password,secret:n.secret}},delete n.type,delete n.password}else if("jwt"==n.type){for(const t in n.embedders)n.termdb={[t]:Object.assign({type:n.type},n.embedders[t])},n.headerKey&&(n.termdb[t].headerKey=n.headerKey);delete n.type,delete n.embedders,delete n.headerKey}else if(n.type)throw`unknown legacy credentials type='${n.type}'`}}(t);const n="secrets";if("string"==typeof t[n]){const e=await r.promises.readFile(t[n],"utf8");t[n]=JSON.parse(e)}for(const e in t){const n=t[e];n["*"]&&(n["/**"]=n["*"],delete n["*"]);const r=n.headerKey||"x-ds-access-token";delete n.headerKey;for(const o in n){const i=n[o];for(const n in i){i[n]=JSON.parse(JSON.stringify(i[n]));const s=i[n],a="string"==typeof s?t.secrets[s]:s;if("basic"==a.type)a.secret||(a.secret=a.password),a.authRoute="/dslogin";else if("jwt"==a.type)a.authRoute="/jwt-status",a.headerKey||(a.headerKey=r);else if("forbidden"!=a.type&&"open"!=a.type)throw`unknown cred.type='${a.type}' for dsCredentials[${e}][${n}][${o}]`;a.dslabel=e,a.route=o,a.cookieId="termdb"==o&&a.headerKey||`${e}-${o}-${n}-Id`}}}}const u={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function f(t,e){var n,r,o,i;return(null===(n=t.cookies)||void 0===n?void 0:n[`${null==e?void 0:e.cookieId}`])||(null===(r=t.cookies)||void 0===r?void 0:r[`${t.query.dslabel}SessionId`])||(null===(o=t.headers)||void 0===o?void 0:o["x-sjppds-sessionid"])||(null===(i=t.query)||void 0===i?void 0:i["x-sjppds-sessionid"])}async function d(t,e,n,o,i,s,l=""){if(o.secret)try{const c=Date.now(),u=Math.floor(c/1e3),f={dslabel:e.dslabel,id:n,iat:u,time:c,ip:t.ip,embedder:e.embedder,route:o.route,exp:u+Math.floor(i/1e3),email:l};o.dsnames&&(f.datasets=o.dsnames.map((t=>t.id)));const d=a().sign(f,o.secret);return await r.promises.appendFile(s,`${e.dslabel}\t${n}\t${c}\t${l}\t${t.ip}\t${e.embedder}\t${o.route}\n`),d}catch(t){throw t}}function h(t,e,n,r,o){var i;if(!r.headers.authorization||n&&null!==(i=t[e])&&void 0!==i&&i[n])return;if(!o.secret)throw{status:"error",error:`no credentials set up for this embedder='${r.query.embedder}'`,code:403};const[s,c]=r.headers.authorization.split(" ");if("bearer"!=s.toLowerCase())throw`unsupported authorization type='${s}', allowed: 'Bearer'`;const u=Buffer.from(c,"base64").toString();try{var f;const i=a().verify(u,o.secret);if(n&&i.id!=n&&(null===(f=r.headers)||void 0===f?void 0:f["x-sjppds-sessionid"])!=i.id)return;t[e]||(t[e]={});const s="/"!=r.path[0]||o.route.startsWith("/")?r.path:r.path.slice(1);if((0,l.isMatch)(s,o.route)||"authorizedActions"==s)return t[e][i.id]=i,i.id}catch(t){return}}async function p(t,e,n,o,i,s,a){const l=Date.now(),c=Math.random().toString()+"."+l.toString().slice(4),u=s.ip;return n[t.dslabel]||(n[t.dslabel]={}),n[t.dslabel][c]={id:c,time:l,email:i,ip:u},await r.promises.appendFile(o,`${t.dslabel}\t${c}\t${l}\t${i}\t${u}\t${t.embedder}\t${a.route}\n`),a.cookieMode&&"set-cookie"!=a.cookieMode||e.header("Set-Cookie",`${a.cookieId}=${c}; HttpOnly; SameSite=None; Secure`),c}function m(t,e,n,r,o=null){var i;if(!n)return;if(!t.embedder)throw"missing q.embedder";const s=n.secret;if(!s)throw{status:"error",error:"no credentials set up for this embedder",code:403};const l=Math.floor((r||Date.now())/1e3),c=e[n.headerKey];if(!c)throw`missing header['${n.headerKey}']`;const u=n.processor?require(n.processor):{},f=(null===(i=u.handleToken)||void 0===i?void 0:i.call(u,c))||c,d=a().verify(f,s);if(o)return{iat:d.iat,email:d.email,ip:d.ip};if(u.handlePayload)try{u.handlePayload(n,d,l)}catch(t){if("bad decrypt"==t.reason)throw`Please login again to access this feature. (${t.reason})`;throw t}if(l>d.exp)throw"Please login again to access this feature. (expired token)";const h=(n.dsnames||[t.dslabel]).filter((t=>{var e;return!(null!==(e=d.datasets)&&void 0!==e&&e.includes(t.id))})).map((t=>t.id));if(h.length)throw{error:"Missing access",linkKey:h.join(",")};return{iat:d.iat,email:d.email,ip:d.ip}}function g(t,e,n){var r,o,i;if(!n.looseIpCheck||(null===(r=t.ip)||void 0===r||!r.includes(":"))&&e){if(!e)throw"Server error: missing ip address in saved session";if(t.ip!=e&&(null===(o=t.ips)||void 0===o?void 0:o[0])!=e&&(null===(i=t.connection)||void 0===i?void 0:i.remoteAddress)!=e)throw"Your connection has changed, please refresh your page or sign in again."}}const y={maySetAuthRoutes:async function(t,e="",o=null){var s;const v=o||n(334),b=(null===(s=v.features)||void 0===s?void 0:s.sessionTracking)||"",w=i().join(v.cachedir,"dsSessions"),_=i().join(v.cachedir,"authorizedActions"),x=v.dsCredentials||{};delete v.dsCredentials;const k=v.maxSessionAge||576e5;let q;if(!x||!Object.keys(x).length)return y.getDsAuth=()=>[],y.getForbiddenRoutesForDsEmbedder=()=>[],y.userCanAccess=()=>!0,y.getRequiredCredForDsEmbedder=()=>{},void(y.getPayloadFromHeaderAuth=()=>({}));try{c(x)}catch(t){throw t}function N(t,e,n){if(!t.dslabel)return;const r=x[t.dslabel]||x["*"];if(r){if("/jwt-status"==e){const e=r[t.route]||r.termdb||r["/**"];return e&&(e[t.embedder]||e["*"])}if("/dslogin"==e){const e=r[t.route]||r["/**"];return e&&(e[t.embedder]||e["*"])}if(e.startsWith("/termdb")&&r.termdb){const e=r.termdb;return(n||u.termdb).includes(t.for)&&(e[t.embedder]||e["*"])}if(e.startsWith("/burden")&&r.burden)return r.burden[t.embedder]||r.burden["*"]}for(const n in x){if(n!=t.dslabel&&"*"!=n)continue;const r=x[n];for(const n in r){const o=r[n].routePattern||n;if(!(0,l.isMatch)(e,o))continue;const i=r[n];for(const e in i)if(e==t.embedder||"*"==e)return i[e]}}}t.use(((t,e,n)=>{if("/dslogin"==t.path||"/jwt-status"==t.path||"/dslogout"==t.path)return void n();const r=t.query,o=N(r,t.path);if(!o)return void n();let i;"jwt-only"==b&&(q={});try{var s,a;const l=f(t,o);let c;if(!l){if("OPTIONS"==t.method.toUpperCase())return e.status(204),void e.send();if(c=h(q,r.dslabel,l,t,o),!c)throw i=401,"missing session cookie"}c||(c=h(q,r.dslabel,l,t,o));const u=(null===(s=q[r.dslabel])||void 0===s?void 0:s[l])||(null===(a=q[r.dslabel])||void 0===a?void 0:a[c]);if(!u)throw i=401,"unestablished or expired browser session";g(t,u.ip,o);const d=Date.now();if(d-u.time>k){const{iat:e}=m(r,t.headers,o,u),n=d-e;if(n>k)throw delete q[r.dslabel][l],"Please login again to access this feature. (expired session)";if(n<3e5)return void(u.time=d)}u.time-d<900&&(u.time=d),n()}catch(t){console.log(t);const n=t.code||i;n&&e.status(n),e.send("object"==typeof t?t:{error:t})}}));try{q=await async function(t,e,n){const o={};for(const e in t)o[e]||(o[e]={});try{const t=await r.promises.readFile(e,"utf8"),i=+new Date;for(const e of t.split("\n")){if(!e)continue;const[t,r,s,a,l]=e.split("\t"),c=Number(s);o[t]||(o[t]={}),i-c<n&&(o[t][r]={id:r,time:c,email:a,ip:l})}return o}catch(t){return(0,r.existsSync)(e)&&console.log(t),o}}(x,w,k);const t=[];for(const e in q)for(const n in q[e]){const r=q[e][n];t.push(`${r.dslabel}\t${r.id}\t${r.time}\t${r.email}\t${r.ip}\t${r.embedder}\t${r.route}`)}await r.promises.writeFile(w,t.join("\n"))}catch(t){throw t}var S;await(S=0,new Promise((t=>setTimeout(t,S)))),t.post(e+"/dslogin",(async(t,e)=>{let n=401;try{const r=t.query,o=N(r,t.path);if(!o)throw n=400,`No login required for dataset='${r.dslabel}'`;if("/dslogin"!=o.authRoute)throw n=400,`Incorrect authorization route, use '${o.authRoute}'`;if(!t.headers.authorization)throw"missing authorization header";const[i,s]=t.headers.authorization.split(" ");if("basic"!=i.toLowerCase())throw`unsupported authorization type='${i}', allowed: 'Basic'`;if(Buffer.from(s,"base64").toString()!=o.password)throw"invalid password";const a=await p(r,e,q,w,"",t,o);n=401;const l=await d(t,r,a,o,k,w);e.send({status:"ok",jwt:l,route:o.route})}catch(t){e.status(n),e.send({error:t})}})),t.post(e+"/dslogout",(async(t,e)=>{try{var n;const o=t.query,i=f(t,N(o,t.path));if(!i)throw"missing session cookie";const s=null===(n=q[o.dslabel])||void 0===n?void 0:n[i];if(!s)return void e.send({status:"ok"});delete q[o.dslabel][i];t.ip;await r.promises.appendFile(w,`${o.dslabel}\t${i}\t0\t\t${s.ip}\t${s.embedder}\t${s.route}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send({error:t})}})),t.post(e+"/jwt-status",(async(t,e)=>{let n=401;try{const r=t.query,o=N(r,t.path);if(!o)return void e.send({status:"ok"});if("/jwt-status"!=o.authRoute)throw n=400,`Incorrect authorization route, use ${o.authRoute}'`;const{email:i,ip:s}=await m(r,t.headers,o);g(t,s,o);const a=await p(r,e,q,w,i,t,o);n=401;const l=await d(t,r,a,o,k,w,i);e.send({status:"ok",jwt:l,route:o.route,[o.cookieId]:a})}catch(t){console.log(t),e.status(n),e.send(t instanceof Error||"object"!=typeof t?{error:t}:t)}})),t.post(e+"/authorizedActions",(async(t,e)=>{const n=t.query;try{var o,i;const s=N(n,"termdb");if(!s)return void e.send({status:"ok"});const a=f(t),l=h(q,n.dslabel,a,t,s),c=(null===(o=q[n.dslabel])||void 0===o?void 0:o[a])||(null===(i=q[n.dslabel])||void 0===i?void 0:i[l]),{email:u}=c.email,d=new Date;await r.promises.appendFile(_,`${n.dslabel}\t${u}\t${d}\t${n.action}\t${JSON.stringify(n.details)}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send("object"==typeof t?t:{error:t})}})),y.getDsAuth=function(t){const e=[],n=t.query.embedder||t.get("host").split(":")[0];for(const o in x){if(o.startsWith("__"))continue;const i=x[o];for(const s in i){const a=i[s];for(const i in a){var r;if(!(0,l.isMatch)(n,i))continue;const c=a[i],u=f({query:Object.assign({},t.query,{dslabel:o}),headers:t.headers,cookies:t.cookies},c),d=null===(r=q[o])||void 0===r?void 0:r[u],h=(null==d?void 0:d.time)||0;e.push({dslabel:o,route:s,type:c.type||"basic",insession:("basic"!=c.type||!t.path.startsWith("/genomes"))&&(("jwt"!=c.type||u)&&Date.now()-h<k)})}}}return e},y.getForbiddenRoutesForDsEmbedder=function(t,e){const n=[],r=x[t]||x["*"];if(!r)return n;for(const t in r){const o=r[t][e]||r[t]["*"];"forbidden"==(null==o?void 0:o.type)&&n.push(t)}return n},y.getRequiredCredForDsEmbedder=function(t,e){const n=[];for(const r in x)if((0,l.isMatch)(t,r))for(const t in x[r])for(const o in x[r][t]){if(!(0,l.isMatch)(e,o))continue;const i=x[r][t][o];n.push({route:t,type:i.type,headerKey:i.headerKey})}return n},y.userCanAccess=function(t,e){var n,r;const o=N(t.query,t.path,u.samples);if(!o)return!0;if("basic"==o.type&&t.path.startsWith("/genomes"))return!1;const i=f(t,o),s=h(q,e.label,i,t,o),a=(null===(n=q[e.label])||void 0===n?void 0:n[i])||(null===(r=q[e.label])||void 0===r?void 0:r[s]),l=(null==a?void 0:a.time)||0;return Date.now()-l<k},y.getPayloadFromHeaderAuth=function(t,e){var n;if(null===(n=t.headers)||void 0===n||!n.authorization)return{};const r=N(t.query,e);if(!r)return{};const[o,i]=t.headers.authorization.split(" ");if("bearer"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Bearer'`;const s=Buffer.from(i,"base64").toString();return a().verify(s,r.secret)||{}}},getJwtPayload:m,canDisplaySampleIds:(t,e)=>!!e.cohort.termdb.displaySampleIds&&y.userCanAccess(t,e),getDsAuth:()=>[],getForbiddenRoutesForDsEmbedder:()=>[],userCanAccess:()=>!0,getRequiredCredForDsEmbedder:()=>{},getPayloadFromHeaderAuth:()=>({})}},7833:(t,e,n)=>{"use strict";n.r(e);var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=(n(3345),n(334)),l=n.n(a),c=n(8907),u=n(8064),f=n(5494),d=n(6733),h=n(5558),p=n(3602),m=n(6279);const g={snvindel:f,sv:m,fusion:m,svjson:n(8423),cnv:d,itd:p,deletion:h,truncation:n(8235)};function y(t,e,n,r,o,i){for(const s of e.yesSamples){if(i&&!i.includes(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:s})}for(const s of e.noSamples){if(i&&!i.includes(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:s})}}async function v(t,e){const n=t.cohort;try{if(n.mutationFlagSet)return n.mutationFlagSet;if(!n.mutationset)return;const r={},o=t.sampleName2Id;for(const[t,i]of n.mutationset.entries()){const n=await b(t,i,e);r[Math.random()]=n;for(const t in n.data)for(const e of n.data[t])e._SAMPLENAME_=e.sample.split(";")[0].trim(),e._SAMPLEID_=o.get(e._SAMPLENAME_)||e._SAMPLENAME_}return n.mutationFlagSet=r,r}catch(t){throw t}}async function b(t,e,n){const r=u.Dz(n);if(!r)throw"init_bulk_flag() failed";r.tpsetname=e.name?e.name:"set"+t;for(const t in e){if(!(t in g))throw`unknown mutationset: ${t}`;const n=e[t].startsWith("/")?e[t]:s().join(l().tpmasterdir,e[t]);try{const e=(await o().promises.readFile(n,"utf8")).trim().split(/\r?\n/);if(g[t].parseheader(e[0],r))throw`${t} header line error: herr`;for(let n=1;n<e.length;n++)g[t].parseline(n,e[n],r)}catch(t){throw t}}return r}exports.mayGetGeneVariantData=async function(t,e){var n;const r=this,o=t.term.name,i=await v(r,e.genome),s=new Map;if(!i)return s;let a;(null==e||null===(n=e.filter)||void 0===n?void 0:n.lst.length)>0&&(a=[...new Set((await(0,c.cf)(e.filter,r)).map((t=>t.id)))]);for(const t in i){var l;const e=i[t];if(o in e.data){for(const t of e.data[o]){const e=t._SAMPLEID_;if(a&&!a.includes(e))continue;s.has(e)||s.set(e,{sample:e});const n=s.get(e);o in n||(n[o]={key:o,values:[],label:o}),n[o].values.push(t)}if(null!==(l=r.assayAvailability)&&void 0!==l&&l.byDt)for(const t in r.assayAvailability.byDt){const e=r.assayAvailability.byDt[t];if(e.byOrigin)for(const n in e.byOrigin){y(t,e.byOrigin[n],s,o,n,a)}else y(t,e,s,o,!1,a)}}}return s},exports.getTermTypes=async function(t){const e=this;try{const n="string"==typeof t.ids?JSON.parse(t.ids):t.ids,r=n.map((()=>"?")).join(","),o=`SELECT id, name, type, jsondata, parent_id FROM terms WHERE id IN (${r}) OR name IN (${r})`,i=e.cohort.db.connection.prepare(o).all([...n,...n]),s={};for(const t of i)t.jsondata&&Object.assign(t,JSON.parse(t.jsondata)),s[t.id]=t;const a=n.filter((t=>!s[t])),l=await v(e,t.genome);if(l)for(const t in l){const e=l[t];if(e.data)for(const t of a)t in e.data&&!(t in s)&&(s[t]={name:t,type:"geneVariant"})}return s}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}},exports.mayGetMatchingGeneNames=async function(t,e,n,r=25){const o=await v(this,n.genome);if(o)for(const n in o){const s=o[n];for(const n in s.data){var i;if(n.length>r)continue;if(null===(i=s.data[n])||void 0===i||!i.length)continue;const o={name:n,type:"geneVariant",isleaf:!0};n===e?t.equals.push(o):n.startsWith(e)?t.startsWith.push(o):n.includes(" "+e)?t.startsWord.push(o):n.includes(e)?t.includes.push(o):"TP53"==n&&0}}},exports.get_flagset=v},4065:(t,e,n)=>{"use strict";function r(t,e){if(t.genomicNameRegexp.test(e.input))throw"invalid character in gene name";if(e.deep){const n={};let r;{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);n&&(r=n.name)}if(!r&&t.genedb.getNameByAlias){const n=t.genedb.getNameByAlias.get(e.input);n&&(r=n.name)}if(!r&&t.genedb.get_gene2canonicalisoform&&e.input.toUpperCase().startsWith("ENSG")){const o=t.genedb.get_gene2canonicalisoform.get(e.input);if(o&&o.isoform){const e=o.isoform;n.found_isoform=e;const i=t.genedb.getnamebynameorisoform.get(e,e);if(!i)throw"cannot map enst isoform to symbol";r=i.name}}r||(r=e.input);const o=t.genedb.getjsonbyname.all(r);return n.gmlst=o.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})),n}const n=e.input.toUpperCase(),r=(n.substr(0,2),t.genedb.getnameslike.all(n+"%"));if(r.length)return r.sort(),{hits:r.map((t=>t.name))};if(t.genedb.getNameByAlias){const e=t.genedb.getNameByAlias.all(n);if(e.length)return{hits:e.map((t=>t.name))}}{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);if(n)return{hits:[n.name]}}return{hits:[]}}n.d(e,{S:()=>r})},2062:(t,e,n)=>{"use strict";n.d(e,{W:()=>a,A:()=>l});var r=n(334),o=n.n(r),i=n(7147),s=n.n(i);async function a(t){l.deps||async function(){const t=`${process.cwd()}/package.json`;try{if(s().existsSync(t)){const e=s().readFileSync(t,{encoding:"utf8"}),n=JSON.parse(e);l.deps={"@sjcrh/proteinpaint-server":null==n?void 0:n.dependencies["@sjcrh/proteinpaint-server"],"@sjcrh/proteinpaint-client":null==n?void 0:n.dependencies["@sjcrh/proteinpaint-client"]}}else l.deps={}}catch(t){console.log(t),l.deps={}}}();const e={status:"ok",genomes:{},versionInfo:l};for(const o in t){const i=t[o],s={};var n;if(i.genedb)s.genedb={buildDate:(null===(n=i.genedb.get_buildDate)||void 0===n?void 0:n.get().date)||"unknown",tables:i.genedb.tableSize};if(i.termdbs){s.termdbs={};for(const t in i.termdbs){var r;const e=i.termdbs[t];s.termdbs[t]={buildDate:(null===(r=e.cohort.termdb.q.get_buildDate)||void 0===r?void 0:r.get().date)||"unknown"}}}Object.keys(s).length&&e.genomes&&(e.genomes[o]=s)}return e}const l={pkgver:"2.33.0",codedate:function(){const t=s().existsSync(o().binpath+"/server.js")&&s().statSync(o().binpath+"/server.js").mtime||new Date(0),e=s().existsSync("public/bin/proteinpaint.js")&&s().statSync("public/bin/proteinpaint.js").mtime||new Date(0);return(t>e?t:e).toDateString()}(),launchdate:new Date(Date.now()).toString().split(" ").slice(0,5).join(" ")}},9157:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>c});var r=n(7147),o=n.n(r),i=(n(1017),n(334)),s=n.n(i),a=n(2081),l=n(2781);async function c(t,e,n=[]){try{await o().promises.stat(t)}catch(e){throw`${t} does not exist`}const r=[],i=[];return new Promise(((o,c)=>{const u=(0,a.spawn)(s().Rscript,[t,...n]);if(e&&e.length>0)try{const t=e.join("\n")+"\n";l.Readable.from(t).pipe(u.stdin)}catch(t){u.kill();let e=t;i.length>0&&(e+=`\nR stderr: ${i.join("").trim()}`),c(e)}u.stdout.on("data",(t=>r.push(t))),u.stderr.on("data",(t=>i.push(t))),u.on("error",(t=>c(t))),u.on("close",(t=>{if(0!==t){let e=`R process exited with non-zero status code=${t}`;r.length>0&&(e+=`\nR stdout: ${r.join("").trim()}`),i.length>0&&(e+=`\nR stderr: ${i.join("").trim()}`),c(e)}if(i.length>0){const t=i.join("").trim();c(`R process emitted standard error\nR stderr: ${t}`)}const e=r.join("").trim().split("\n");o(e)}))}))}},1169:(t,e,n)=>{"use strict";n.d(e,{Ak:()=>m,r8:()=>L,z7:()=>D,Pj:()=>b,ws:()=>R,BM:()=>$,nD:()=>j,wm:()=>P,IK:()=>q,CL:()=>v,P9:()=>F,CN:()=>w,xq:()=>y,vK:()=>g});var r=n(2273),o=n(4048),i=n(6452),s=n.n(i),a=n(1017),l=n.n(a),c=n(4973);function u(t){const e={op:"and",content:[]};if(!Array.isArray(t.lst))throw"filter.lst[] not array";for(const n of t.lst){if("tvs"!=n.type)throw'filter.lst[] item.type!="tvs"';if(!n.tvs)throw"item.tvs missing";if(!n.tvs.term)throw"item.tvs.term missing";if(n.tvs.values){const t={op:"in",content:{field:f(n.tvs.term.id),value:n.tvs.values.map((t=>t.key))}};e.content.push(t)}else if(n.tvs.ranges)for(const t of n.tvs.ranges)t.startunbounded?e.content.push({op:t.stopinclusive?"<=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}):t.stopunbounded?e.content.push({op:t.startinclusive?">=":">",content:{field:f(n.tvs.term.id),value:t.start}}):e.content.push({op:"and",content:[{op:t.startinclusive?">=":">",content:{field:f(n.tvs.term.id),value:t.start}},{op:t.stopinclusive?"<=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}]})}return e}function f(t){const e=t.split(".");return"case"==e[0]&&(e[0]="cases"),e.join(".")}const d=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",h=d+(d.includes("/v0")?"":"/v0")+"/graphql",p="https://uat-api.gdc.cancer.gov";function m(t,e){t.convertSampleId.get=t=>{const n={};for(const r of t)n[r]=e.__gdc.map2caseid.get(r)||r;return n}}async function g(t){const e=["consequence.transcript.is_canonical","consequence.transcript.transcript_id"];t.get=async t=>{if(!t.ssm_id)throw".ssm_id missing";const n=await s()(d+"/ssms/"+t.ssm_id+"?fields="+e.join(","),{method:"GET",headers:S(t)});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid json in response"}if(!r.data||!r.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(r.data.consequence))throw".data.consequence not array";const o=r.data.consequence.find((t=>t.transcript.is_canonical));return o?o.transcript.transcript_id:r.data.consequence[0].transcript.transcript_id}}function y(t){t.queries.snvindel.byrange.get=async e=>{var n,o,i,a,l;const c=await s().post(h,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:B,variables:G(e)})});let u;try{u=JSON.parse(c.body)}catch(t){throw"invalid JSON from GDC range2ssm"}if(!Array.isArray(null===(n=u)||void 0===n||null===(o=n.data)||void 0===o||null===(i=o.explore)||void 0===i||null===(a=i.ssms)||void 0===a||null===(l=a.hits)||void 0===l?void 0:l.edges))throw"data.explore.ssms.hits.edges not array";const f=[];for(const n of u.data.explore.ssms.hits.edges){const o={dt:r.dtsnvindel,ssm_id:n.node.ssm_id,chr:n.node.chromosome,pos:n.node.start_position-1,ref:n.node.reference_allele,alt:n.node.tumor_allele,samples:[]};if(n.node.consequence&&n.node.consequence.hits&&n.node.consequence.hits.edges){let t;o.csqcount=n.node.consequence.hits.edges.length,t=e.isoform?n.node.consequence.hits.edges.find((t=>t.node.transcript.transcript_id==e.isoform)):n.node.consequence.hits.edges.find((t=>t.node.transcript.is_canonical));t||n.node.consequence.hits.edges[0];k(o,(t||n.node.consequence.hits.edges[0]).node)}if(n.node.occurrence.hits.edges)for(const e of n.node.occurrence.hits.edges){const n=x(e.node.case,t);n.sample_id=e.node.case.case_id,o.samples.push(n)}f.push(o)}return f}}function v(t,e){t.queries.geneExpression.get=async n=>{if(!Array.isArray(n.genes))throw"q.genes[] not array";const r=new Map,o=new Date,i=await b(n,t);if(0==i.length)return{gene2sample2value:r,byTermId:{}};const a=new Date;console.log(i.length,"cases with exp data:",a-o,"ms");const[l,c]=await async function(t,e,n){const r=[],o=new Map;for(const n of t){const t=n.gene||n.name;if("string"!=typeof t)continue;if(t.startsWith("ENSG")&&15==t.length){r.push(t),o.set(t,t);continue}const i=e.genedb.getAliasByName.all(t);if(Array.isArray(i))for(const e of i)if(e.alias.startsWith("ENSG")){r.push(e.alias),o.set(e.alias,t);break}if(r.length>100)break}try{const t=await s().post(`${p}/gene_expression/gene_selection`,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({case_ids:n,gene_ids:r,selection_size:r.length})}),e=JSON.parse(t.body);if(!Array.isArray(e.gene_selection))throw"re.gene_selection[] not array";const i=[];for(const t of e.gene_selection){if("string"!=typeof t.gene_id)throw".gene_id missing from one of re.gene_selection[]";i.push(t.gene_id)}return[i,o]}catch(t){throw t}}(n.genes,e,i);if(0==l.length)return{gene2sample2value:r,byTermId:{}};const u=new Date;console.log(l.length,"out of",n.genes.length,"genes selected for exp:",u-a,"ms");const f={};for(const t of l){const e=c.get(t);f[e]={gencodeId:t},r.set(e,new Map)}await async function(t,e,n,r,o,i){const a=await s().post(`${p}/gene_expression/values`,{headers:S(t),body:JSON.stringify({case_ids:n,gene_ids:e,format:"tsv",tsv_units:"median_centered_log2_uqfpkm"})});if("string"!=typeof a.body)throw"response.body is not tsv text";const l=a.body.trim().split("\n");if(l.length<=1)throw"less than 1 line from tsv response.body";const c=l[0].split("\t").slice(1);if(c.length!=n.length)throw"sample column length != case_ids.length";const u=[];for(const t of c){const e=i.__gdc.caseid2submitter.get(t);if(!e)throw"case submitter id unknown for a uuid";u.push(e)}for(let t=1;t<l.length;t++){const e=l[t].split("\t");if(e.length!=u.length+1)throw"number of fields in gene line does not equal header";const n=e[0];if(!n)throw"ensg l[0] missing from a line";const i=r.get(n);if(!i)throw"symbol missing for "+n;for(const[t,r]of u.entries()){const s=Number(e[t+1]);Number.isFinite(s)?o.get(i)[r]=s:console.log(n,r,e[t+1])}}}(n,l,i,c,r,t);const d=new Date;return console.log("gene-case matrix built:",d-u,"ms"),{gene2sample2value:r,byTermId:f}}}async function b(t,e){const n={op:"and",content:[]};t.filter0&&n.content.push(t.filter0),t.filterObj&&n.content.push(u(t.filterObj));const r={size:1e4,fields:"case_id"};n.content.length&&(r.filters=n);try{const n=await s().post(l().join(d,"cases"),{headers:S(t),body:JSON.stringify(r)}),o=JSON.parse(n.body);if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";const i=[];for(const t of o.data.hits)if(t.id&&e.__gdc.casesWithExpData.has(t.id)&&(i.push(t.id),i.length>1e3))break;return i}catch(t){throw console.log(t.stack||t),t}}function w(t){t.queries.snvindel.byisoform.get=async e=>{const n=_(e,t),o=await async function(t,e){if(!t.isoform)throw"snvindel_byisoform: .isoform missing";if("string"!=typeof t.isoform)throw".isoform value not string";const n=z,r=U,o=S(t),i=s().post(l().join(d,n.endpoint),{headers:o,body:JSON.stringify({size:n.size,fields:n.fields.join(","),filters:n.filters(t)})}),a=s().post(l().join(d,r.endpoint),{headers:o,body:JSON.stringify({size:r.size,fields:r.fields.join(","),filters:r.filters(t,e)})}),[c,u]=await Promise.all([i,a]);let f,h;try{f=JSON.parse(c.body),h=JSON.parse(u.body)}catch(t){throw"invalid JSON returned by GDC"}if(!f.data||!f.data.hits)throw"query1 did not return .data.hits";if(!h.data||!h.data.hits)throw"query2 did not return .data.hits[]";if(!Array.isArray(f.data.hits)||!Array.isArray(h.data.hits))throw"re.data.hits[] is not array";const p=new Map;for(const e of f.data.hits){if(!e.ssm_id)throw"ssm_id missing from a ssms hit";if(!e.consequence)throw".consequence[] missing from a ssm";if(!Number.isInteger(e.start_position))throw"hit.start_position is not integer";e.csqcount=e.consequence.length;const n=e.consequence.find((e=>e.transcript.transcript_id==t.isoform));e.consequence=n,e.cases=[],p.set(e.ssm_id,e)}for(const t of h.data.hits){if(!t.ssm)throw".ssm{} missing from a case";if(!t.ssm.ssm_id)throw".ssm.ssm_id missing from a case";const e=p.get(t.ssm.ssm_id);if(!e)throw"ssm_id not found in ssms query";if(!t.case)throw".case{} missing from a case";e.cases.push(t.case)}return[...p.values()]}(e,t),i=[];for(const n of o){const o={ssm_id:n.ssm_id,dt:r.dtsnvindel,chr:n.chromosome,pos:n.start_position-1,ref:n.reference_allele,alt:n.tumor_allele,isoform:e.isoform,csqcount:n.csqcount};if(k(o,n.consequence),!e.hiddenmclass||!e.hiddenmclass.has(o.class)){o.samples=[];for(const r of n.cases){const n={sample_id:await E(r,t,e.useCaseid4sample)};e.useCaseid4sample&&(n.__sampleName=r.submitter_id),o.samples.push(n)}i.push(o)}}if(n){e.isoform=n;for(const t of i)t.isoform=n}return i}}function _(t,e){if(!t.isoform)return;let n;if("N"==t.isoform[0]&&e.refseq2ensembl_query){const r=e.refseq2ensembl_query.get(t.isoform);r&&(n=t.isoform,t.isoform=r.ensembl)}return n}function x(t,e){const n={};if(e.sampleSummaries)for(const r of e.sampleSummaries.lst){{const o=e.cohort.termdb.q.termjsonByOneid(r.label1);if(o){n[r.label1]=t[o.fields[0]];for(let t=1;t<o.fields.length;t++)n[r.label1]&&(n[r.label1]=n[r.label1][o.fields[t]])}}if(r.label2){const o=e.cohort.termdb.q.termjsonByOneid(r.label2);if(o){n[r.label2]=t[o.fields[0]];for(let t=1;t<o.fields.length;t++)n[r.label2]&&(n[r.label2]=n[r.label2][o.fields[t]])}}}return n}function k(t,e){if(e&&e.transcript.consequence_type){const[n,o,i]=r.vepinfo(e.transcript.consequence_type);t.class=o,t.mname=e.transcript.aa_change}t.mname||(t.mname=t.ref+">"+t.alt),t.class||(r.basecolor[t.ref]&&r.basecolor[t.alt]?t.class=r.mclasssnv:"-"==t.ref?t.class=r.mclassinsertion:"-"==t.alt?t.class=r.mclassdeletion:t.class=r.mclassmnv)}function q(t){const e=["cnv.cnv_change","cnv.gene_level_cn","cnv.consequence.gene.symbol","case.submitter_id","case.case_id"];function n(t){const n=e.slice();if(t.twLst)for(const e of t.twLst){let t=e.term.id;t.startsWith("case.")&&(t="occurrence."+t),n.push(t)}return n.join(",")}function o(t){if(!t.gene&&"string"!=typeof t.gene)throw"p.gene does not provide non-empty string";const e={op:"and",content:[]};return t.gene&&e.content.push({op:"=",content:{field:"cnv.consequence.gene.symbol",value:t.gene.split(",")}}),t.filter0&&e.content.push(t.filter0),t.filterObj&&e.content.push(u("string"==typeof t.filterObj?JSON.parse(t.filterObj):t.filterObj)),e}t.queries.geneCnv.bygene.get=async t=>{var e;const i=S(t),a=await s().post(l().join(d,"cnv_occurrences"),{headers:i,body:JSON.stringify({size:1e5,fields:n(t),filters:o(t)})}),c=JSON.parse(a.body);if(!Array.isArray(null==c||null===(e=c.data)||void 0===e?void 0:e.hits))throw"geneCnv response body is not {data:hits[]}";const u={ssm_id:"geneCnvGain",dt:r.dtcnv,class:r.mclasscnvgain,samples:[]},f={ssm_id:"geneCnvLoss",dt:r.dtcnv,class:r.mclasscnvloss,samples:[]};for(const e of c.data.hits){if("object"!=typeof e.cnv)throw"hit.cnv{} not obj";if("object"!=typeof e.case)throw"hit.case{} not obj";if(!e.cnv.gene_level_cn)throw"hit.cnv.gene_level_cn is not true";let n;if("Gain"==e.cnv.cnv_change)n=u;else{if("Loss"!=e.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=f}const r={sample_id:e.case.case_id,__sampleName:e.case.submitter_id};if(t.twLst)for(const n of t.twLst)A(r,e.case,n);n.samples.push(r)}const h=[];return u.samples.length&&h.push(u),f.samples.length&&h.push(f),h}}function N(t,e){if(!e)return;const n=e.split(",");for(const e of n){const n=e.split("--");if(2==n.length)return t.geneA=n[0].split("(")[0],void(t.geneB=n[1].split("(")[0])}}function S(t){const e={"Content-Type":"application/json",Accept:"application/json"};return t&&(t.token&&(e["X-Auth-Token"]=t.token),t.sessionid&&(e.Cookie="sessionid="+t.sessionid)),e}function A(t,e,n){const r=n.term.id.split(".");if(function e(o,i){const s=r[i];if(i==r.length-1)return void(t[n.term.id]?t[n.term.id].add(o[s]):t[n.term.id]=o[s]);const a=o[s];if(null==a)return;if(Array.isArray(a)){t[n.term.id]=new Set;for(const t of a)e(t,i+1);return}e(a,i+1)}(e,1),t[n.term.id]instanceof Set&&(t[n.term.id]=[...t[n.term.id]][0]),n.term.id in t&&"categorical"==n.term.type){const e=function(t,e){var n,r,o,i,s,a,l;if("custom-groupset"==(null===(n=e.q)||void 0===n?void 0:n.type)&&Array.isArray(null===(r=e.q)||void 0===r||null===(o=r.groupsetting)||void 0===o||null===(i=o.customset)||void 0===i?void 0:i.groups))for(const n of e.q.groupsetting.customset.groups){if(!Array.isArray(n.values))throw"group.values[] not array from tw.q.groupsetting.customset.groups";if(-1!=n.values.findIndex((e=>e.key==t)))return n.name}if("predefined-groupset"==(null===(s=e.q)||void 0===s?void 0:s.type)&&Number.isInteger(null===(a=e.q.groupsetting)||void 0===a?void 0:a.predefined_groupset_idx)&&null!==(l=e.term.groupsetting)&&void 0!==l&&l.lst[e.q.groupsetting.predefined_groupset_idx])for(const n of e.term.groupsetting.lst[e.q.groupsetting.predefined_groupset_idx]){if(!Array.isArray(n.values))throw"group.values[] not array from tw.term.groupsetting.lst[]";if(-1!=n.values.findIndex((e=>e.key==t)))return n.name}}(t[n.term.id],n);e&&(t[n.term.id]=e)}}function M(t,e){const n={};for(const i of e){var r;if(("integer"==i.term.type||"float"==i.term.type)&&(null!==(r=i.q)&&void 0!==r&&r.mode))if("discrete"==i.q.mode||"binary"==i.q.mode){const e={};for(const n of t){const t=n[i.term.id];Number.isFinite(t)&&("min"in e?(e.min=Math.min(t,e.min),e.max=Math.max(t,e.max)):(e.min=t,e.max=t))}const r=(0,o.gp)(i.q,(t=>e),i.term.valueConversion);for(const t of r)t.name=t.label;n[i.term.id]={bins:r};for(const e of t){const t=e[i.term.id];Number.isFinite(t)&&(e[i.term.id]=T(r,t))}}else if("continuous"!=i.q.mode)throw"mayApplyBinning: unknown numeric q.mode"}return n}function T(t,e){for(const n of t)if(n.startunbounded){if(e<n.stop)return n.label;if(n.stopinclusive&&e==n.stop)return n.label}else if(n.stopunbounded){if(e>n.start)return n.label;if(n.startinclusive&&e==n.start)return n.label}else if((e>n.start||e===n.start&&n.startinclusive)&&(e<n.stop||e===n.stop&&n.stopinclusive))return n.label}function C(t){for(const n of t)if(null==n.id||""==n.id){var e;if(null==n||null===(e=n.term)||void 0===e||!e.id)throw"tw.id and tw.term are both missing";n.id=n.term.id}else n.term||(n.term={id:n.id})}async function j(t,e,n,r){if(t.isHierCluster)return await async function(t,e,n){var r;const o={op:"in",content:{field:"case_id",value:[...n.__gdc.casesWithExpData]}},i=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&i.push({term:e,q:t.q})}const a=["case_id"],c=new Map;for(const t of i){const e=t.term.id.replace(/^case\./,"");a.push(e),c.set(e,t.term.id)}const u=await s().post(l().join(d,"cases"),{headers:S(t),body:JSON.stringify({size:1e4,fields:a.join(","),filters:o})}),f=JSON.parse(u.body);if(!Array.isArray(null==f||null===(r=f.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const h=[];for(const t of f.data.hits){if("string"!=typeof t.case_id)throw"h.case_id missing";const e={sample_id:n.__gdc.caseid2submitter.get(t.case_id),__sampleName:n.__gdc.caseid2submitter.get(t.case_id)};for(const n of i)A(e,t,n);h.push(e)}const p=M(h,i);return{byTermId:p,samples:h}}(t,e,n);if(C(e),r){if(!Array.isArray(r))throw"geneTwLst not array";t.isoforms=[];for(const e of r){var o;if(null==e||null===(o=e.term)||void 0===o||!o.name)throw"gene tw missing .term.name";if(e.term.isoform)t.isoforms.push(e.term.isoform);else{var i,a;if("object"!=typeof t.genome)throw"serverside genome obj missing, needed to map gene name to canonical isoform";if(null===(i=t.genome)||void 0===i||null===(a=i.genedb)||void 0===a||!a.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const n=t.genome.genedb.get_gene2canonicalisoform.get(e.term.name);if(null==n||!n.isoform)continue;t.isoforms.push(n.isoform)}}}"samples"==t.get&&((t.ssm_id_lst||t.isoform)&&(e.some((t=>"ssm.ssm_id"==t.id))||e.push({term:{id:"ssm.ssm_id"}}),e.some((t=>"case.observation.read_depth.t_alt_count"==t.id))||e.push({term:{id:"case.observation.read_depth.t_alt_count"}}),e.some((t=>"case.observation.read_depth.t_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.t_depth"}}),e.some((t=>"case.observation.read_depth.n_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.n_depth"}}),e.some((t=>"case.observation.sample.tumor_sample_uuid"==t.id))||e.push({term:{id:"case.observation.sample.tumor_sample_uuid"}})),e.some((t=>"case.case_id"==t.id))||e.push({term:{id:"case.case_id"}}),e.some((t=>"case.submitter_id"==t.id))||e.push({term:{id:"case.submitter_id"}})),"summary"!=t.get&&"sunburst"!=t.get||e.some((t=>"case.submitter_id"==t.id))||e.push({term:{id:"case.submitter_id"}});const u=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&u.push({term:e,q:t.q})}const f=e.map((t=>t.term.id));t.hiddenmclass&&(f.push("ssm.consequence.transcript.consequence_type"),f.push("ssm.consequence.transcript.transcript_id")),t.rglst&&(f.push("ssm.chromosome"),f.push("ssm.start_position"));const h={size:1e4,fields:f.join(",")};_(t,n),h.filters=U.filters(t,n);const p=S(t),m=await s().post(l().join(d,U.endpoint),{headers:p,body:JSON.stringify(h)});let g;delete t.isoforms;try{g=JSON.parse(m.body)}catch(t){throw"invalid JSON from GDC for variant2samples query"}if(!g.data||!g.data.hits)throw"variant2samples data structure not data.hits[]";if(!Array.isArray(g.data.hits))throw"variant2samples re.data.hits is not array for query";const y=[];for(const e of g.data.hits){if(!e.case)throw"variant2samples .case{} missing from a hit";const r={};if(e.ssm&&(r.ssm_id=e.ssm.ssm_id),t.hiddenmclass){var v;if(!Array.isArray(null===(v=e.ssm)||void 0===v?void 0:v.consequence))continue;const n={};if(k(n,e.ssm.consequence.find((e=>e.transcript.transcript_id==t.isoform))),t.hiddenmclass.has(n.class))continue}if(t.rglst){var b,w;if(null===(b=e.ssm)||void 0===b||!b.chromosome||null===(w=e.ssm)||void 0===w||!w.start_position)continue;if(!t.rglst.find((t=>t.chr==e.ssm.chromosome&&t.start<e.ssm.start_position&&t.stop>=e.ssm.start_position)))continue}var x,q,N,T;if(t.variant2samples?r.sample_id=await E(e.case,n,!1):(r.sample_id=e.case.case_id,r.__sampleName=e.case.submitter_id),e.case.case_id)r.sample_URLid=e.case.case_id,null!==(x=e.case)&&void 0!==x&&null!==(q=x.observation)&&void 0!==q&&null!==(N=q[0])&&void 0!==N&&null!==(T=N.sample)&&void 0!==T&&T.tumor_sample_uuid&&(r.sample_URLid=r.sample_URLid+"?bioId="+e.case.observation[0].sample.tumor_sample_uuid);for(const t of u)A(r,e.case,t);O(e.case,r),I(r,n),y.push(r)}const j=M(y,u);if(r){const t={gene:r.map((t=>t.term.name)).join(","),twLst:u},e=await n.queries.geneCnv.bygene.get(t);for(const t of e)for(const e of t.samples)y.push(e)}const R=new Map;for(const t of y)(0,c.z9)([t],R,t.ssm_id);return{byTermId:j,samples:[...R.values()]}}async function E(t,e,n){var r,o,i;return n&&t.case_id?t.case_id:null!=t&&null!==(r=t.observation)&&void 0!==r&&null!==(o=r[0])&&void 0!==o&&null!==(i=o.sample)&&void 0!==i&&i.tumor_sample_uuid?await e.__gdc.aliquot2submitter.get(t.observation[0].sample.tumor_sample_uuid):t.case_id||t.submitter_id}function O(t,e){if(!t.observation)return;const n=t.observation[0];n&&n.read_depth&&(e.formatK2v={TumorAC:n.read_depth.t_depth-n.read_depth.t_alt_count+","+n.read_depth.t_alt_count,NormalDepth:n.read_depth.n_depth})}function I(t,e){var n;const r=t["case.project.project_id"];r&&(t.caseIsOpenAccess=null===(n=e.__gdc.gdcOpenProjects)||void 0===n?void 0:n.has(r))}async function R(t,e,n,r){C(t);const o=[];for(const e of t)e.term&&"categorical"==e.term.type&&o.push({id:e.id,path:e.id.replace("case.","").replace(/\./g,"__"),type:e.term.type});const i=function(t){const e=[];for(const n of t)if(n.id)if(n.type="categorical")e.push(n.path+" {buckets { doc_count, key }}");else{if("integer"!=n.type&&"float"!=n.type)throw"unknown term type";e.push(n.path+" {stats { count }}")}const n=`query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\t${e.join("\n")}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`;return n}(o),a=function(t,e){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};if(t&&t.tid2value)for(const r in t.tid2value){e.cohort.termdb.q.termjsonByOneid(r)&&n.filters.content.push({op:"in",content:{field:r.replace(/^case\./,"cases."),value:[t.tid2value[r]]}})}t&&t.ssm_id_lst&&n.filters.content.push({op:"=",content:{field:"cases.gene.ssm.ssm_id",value:t.ssm_id_lst.split(",")}});t.filterObj&&n.filters.content.push(u(t.filterObj));return n}(e,r),l=await s().post(h,{headers:S(e),body:JSON.stringify({query:i,variables:a})});let c;try{c=JSON.parse(l.body)}catch(t){throw"invalid JSON from GDC for cohortTotal for query :"+i+" and filter: "+filter}const f=["data","explore","cases","aggregations"];let d=c[f[0]];for(let t=1;t<f.length;t++)if(d=d[f[t]],!d)throw`.${f[t]} missing from data structure of termid2totalsize2 for query :${i} and filter: ${filter}`;for(const t of o){if("categorical"==t.type&&!Array.isArray(d[t.path].buckets))throw f.join(".")+" not array for query :"+i+" and filter: "+filter;if(("integer"==t.type||"float"==t.type)&&"object"!=typeof d[t.path].stats)throw f.join(".")+" not object for query :"+i+" and filter: "+filter}const p=new Map;for(const t of o)if("categorical"==t.type){const e=d[t.path].buckets,n=[];for(const t of e)n.push([t.key.replace(".","__"),t.doc_count]);p.set(t.id,n)}else if("integer"==t.type||"float"==t.type){const e=d[t.path].stats.count;p.set(t.id,{total:e})}return n?[p,n]:p}function P(t){const e=["consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change"];t.queries.snvindel.m2csq.get=async t=>{const n=await s()(d+"/ssms/"+t.ssm_id+"?fields="+e.join(","),{method:"GET",headers:S(t)});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid json in response"}if(!r.data||!r.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(r.data.consequence))throw".data.consequence not array";return r.data.consequence.map((t=>t.transcript))}}function F(t,e){t.queries.singleSampleMutation.get=async(n,r)=>{if(!n)throw"sampleName missing";return r.case_id=t.__gdc.map2caseid.get(n),r.case_id||(r.case_id=await async function(t){const e=await s().post("https://api.gdc.cancer.gov/cases",{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({size:1,fields:"case_id,submitter_id",filters:{op:"or",content:[{op:"=",content:{field:"samples.portions.analytes.aliquots.aliquot_id",value:[t]}},{op:"=",content:{field:"submitter_id",value:[t]}},{op:"=",content:{field:"samples.submitter_id",value:[t]}}]}})}),n=JSON.parse(e.body);for(const t of n.data.hits)if(t.case_id)return t.case_id;throw"cannot convert to case_id (uuid)"}(n)),await Z(r,t,e)}}function D(t,e){t.queries.singleCell.samples.get=async t=>{var e,n,r;const o={op:"and",content:[{op:"=",content:{field:"data_format",value:"tsv"}},{op:"=",content:{field:"data_type",value:"Single Cell Analysis"}},{op:"=",content:{field:"experimental_strategy",value:"scRNA-Seq"}}]};t.filter0&&o.content.push(t.filter0);const i={filters:o,size:100,fields:["id","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},a=await s().post(l().join(d,"files"),{headers:S(t),body:JSON.stringify(i)});let c;try{c=JSON.parse(a.body)}catch(t){throw"invalid JSON from "+api.endpoint}if(!Number.isInteger(null===(e=c.data)||void 0===e||null===(n=e.pagination)||void 0===n?void 0:n.total))throw"re.data.pagination.total is not int";if(!Array.isArray(null===(r=c.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const u=new Map;for(const t of c.data.hits){var f;const e=null===(f=t.cases)||void 0===f?void 0:f[0];if(!e)throw"h.cases[0] missing";u.has(e.submitter_id)||u.set(e.submitter_id,[]),u.get(e.submitter_id).push({fileId:t.id,project_id:e.project.project_id,samples:e.samples})}const h=[];for(const[t,e]of u)h.push({name:t,files:e});return h}}function L(t,e){t.queries.singleCell.data.get=async t=>{const e=(await s()(l().join(d,"data",t.sample),{method:"GET",headers:S(t)})).body.trim().split("\n"),n={name:"UMAP",cells:[]},r={name:"TSNE",cells:[]},o={name:"PCA",cells:[]},i={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},a={cluster:{}};for(let t=1;t<e.length;t++){const s=e[t],l=s.split("\t"),c=l[0];if(!c)throw"cellId missing from a line: "+s;const u=l[3];if(!u)throw"seuratCluster missing from a line";i.values[u]={label:"Cluster "+u},a.cluster[c]=u;const f=Number(l[4]),d=Number(l[5]),h=Number(l[9]),p=Number(l[10]),m=Number(l[14]),g=Number(l[15]);if(Number.isNaN(f))throw"umap1 is nan";if(Number.isNaN(d))throw"umap2 is nan";if(Number.isNaN(h))throw"tsne1 is nan";if(Number.isNaN(p))throw"tsne2 is nan";if(Number.isNaN(m))throw"pc1 is nan";if(Number.isNaN(g))throw"pc2 is nan";n.cells.push({cellId:c,x:f,y:d}),r.cells.push({cellId:c,x:h,y:p}),o.cells.push({cellId:c,x:m,y:g})}return{plots:[o,r,n],terms:[i],tid2cellvalue:a}}}function $(t){return async(e,n)=>{try{const r=t[e.query.genome];if(!r)throw"invalid genome";const o=r.datasets[e.query.dslabel];if(!o)throw"invalid dslabel";if(!e.query.case_id)throw".case_id missing";n.send(await Z(e.query,o,r))}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}async function Z(t,e,n){const o={mlst:[],dt2total:[]};{var i,a,c;const e=await s().post(l().join(d,z.endpoint),{headers:S(t),body:JSON.stringify({size:1e4,fields:z.fields.join(","),filters:z.filters(t)})}),n=JSON.parse(e.body);if(!Number.isInteger(null===(i=n.data)||void 0===i||null===(a=i.pagination)||void 0===a?void 0:a.total))throw"re.data.pagination.total not integer";if(!Array.isArray(null===(c=n.data)||void 0===c?void 0:c.hits))throw"re.data.hits[] not array";n.data.hits.length<n.data.pagination.total&&o.dt2total.push({dt:1,total:n.data.pagination.total});for(const t of n.data.hits){let e=t.consequence.find((t=>1==t.transcript.is_canonical));e||(e=t.consequence[0]);const n=e.transcript.aa_change||e.transcript.consequence_type,[i,s,a]=r.vepinfo(e.transcript.consequence_type);o.mlst.push({dt:r.dtsnvindel,mname:n,class:s,gene:e.transcript.gene.symbol,chr:t.chromosome,pos:t.start_position,ref:t.reference_allele,alt:t.tumor_allele})}}{const e=await async function(t){const e=S(t),n=await s().post(l().join(d,"files"),{headers:e,body:JSON.stringify({size:1e4,fields:["cases.samples.sample_type","data_type","file_id","data_format","experimental_strategy","analysis.workflow_type"].join(","),filters:function(t){if(!t.case_id)throw".case_id missing";return{op:"and",content:[{op:"in",content:{field:"cases.case_id",value:[t.case_id]}},{op:"in",content:{field:"data_type",value:["Masked Copy Number Segment","Copy Number Segment","Transcript Fusion"]}}]}}(t)})}),o=JSON.parse(n.body);if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";let i,a,c;for(const t of o.data.hits)if("BEDPE"!=t.data_format){if("TXT"==t.data_format){if("Genotyping Array"==t.experimental_strategy){var u,f,h;const e=null===(u=t.cases)||void 0===u||null===(f=u[0].samples)||void 0===f||null===(h=f[0])||void 0===h?void 0:h.sample_type;if(!e)continue;if(e.includes("Normal"))continue;if("Masked Copy Number Segment"!=t.data_type)continue;i=t.file_id;continue}if("WGS"==t.experimental_strategy){if(!t.file_id)continue;if("Copy Number Segment"!=t.data_type)continue;a=t.file_id;continue}}}else{var p;if("RNA-Seq"!=t.experimental_strategy)continue;if("Arriba"!=(null===(p=t.analysis)||void 0===p?void 0:p.workflow_type))continue;if("Transcript Fusion"!=t.data_type)continue;c=t.file_id}const m=[];if(a){const t=(await s()(l().join(d,"data")+"/"+a,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(7!=n.length)continue;const o=Number(n[4]),i=Number(n[5]),s=Number(n[6]);if(Number.isNaN(o)||Number.isNaN(i)||Number.isNaN(s))continue;const a={dt:r.dtcnv,chr:n[1],start:Number(n[2]),stop:Number(n[3]),value:o};!a.chr||Number.isNaN(a.start)||Number.isNaN(a.stop)||(m.push(a),o>0&&0==s&&i>0&&m.push({dt:r.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(i){const t=(await s()(l().join(d,"data")+"/"+i,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(6!=n.length)continue;if(!n[1])continue;const o={dt:r.dtcnv,chr:"chr"+n[1],start:Number(n[2]),stop:Number(n[3]),value:Number(n[5])};Number.isNaN(o.start)||Number.isNaN(o.stop)||Number.isNaN(o.value)||m.push(o)}}if(c)try{const t=(await s()(l().join(d,"data")+"/"+c,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t"),o={dt:r.dtfusionrna,chrA:n[0],posA:Number(n[1]),chrB:n[3],posB:Number(n[4])};o.chrA&&o.chrB&&!Number.isNaN(o.posA)&&!Number.isNaN(o.posB)&&(N(o,n[6]),m.push(o))}}catch(t){}return m}(t);o.mlst.push(...e)}return o}const z={endpoint:"/ssms",size:1e5,fields:["ssm_id","chromosome","start_position","reference_allele","tumor_allele","consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change","consequence.transcript.gene.symbol","consequence.transcript.is_canonical"],filters:t=>{const e={op:"and",content:[]};if(t.isoform){if("string"!=typeof t.isoform)throw".isoform value not string";e.content.push({op:"=",content:{field:"consequence.transcript.transcript_id",value:[t.isoform]}})}if(t.case_id){if("string"!=typeof t.case_id)throw".case_id value not string";e.content.push({op:"=",content:{field:"cases.case_id",value:[t.case_id]}})}if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";e.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&e.content.push(t.filter0),t.filterObj&&e.content.push(u(t.filterObj)),e}},U={endpoint:"/ssm_occurrences",size:1e5,fields:["ssm.ssm_id","case.case_id","case.submitter_id","case.observation.sample.tumor_sample_uuid"],filters:(t,e)=>{const n={op:"and",content:[]};if(t.ssm_id_lst){if("string"!=typeof t.ssm_id_lst)throw"ssm_id_lst not string";n.content.push({op:"=",content:{field:"ssm.ssm_id",value:t.ssm_id_lst.split(",")}})}else if(t.isoform)n.content.push({op:"=",content:{field:"ssms.consequence.transcript.transcript_id",value:[t.isoform]}});else{if(!t.isoforms)throw".ssm_id_lst, .isoform, .isoforms are all missing";if(!Array.isArray(t.isoforms))throw".isoforms[] not array";n.content.push({op:"in",content:{field:"ssms.consequence.transcript.transcript_id",value:t.isoforms}})}if(t.rglst&&(n.content.push({op:">=",content:{field:"ssms.start_position",value:t.rglst[0].start}}),n.content.push({op:"<=",content:{field:"ssms.start_position",value:t.rglst[0].stop}})),t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";n.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}if(t.filter0&&n.content.push(t.filter0),t.filterObj&&n.content.push(u(t.filterObj)),t.tid2value)for(const r in t.tid2value){const o=e.cohort.termdb.q.termjsonByOneid(r);if(o)if("categorical"==o.type)n.content.push({op:"in",content:{field:r,value:[t.tid2value[r]]}});else if("integer"==o.type)for(const e of t.tid2value[r])n.content.push({op:e.op,content:{field:r,value:e.range}})}return n}},B="query range2variants($filters: FiltersArgument) {\n explore {\n ssms {\n hits(first: 100000, filters: $filters) {\n total\n edges {\n node {\n ssm_id\n chromosome\n start_position\n end_position\n genomic_dna_change\n\t\t\treference_allele\n tumor_allele\n occurrence {\n hits {\n total\n\t\t\t\tedges {\n\t\t\t\t node {\n\t\t\t\t case {\n\t\t\t\t\t case_id\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\t}\n }\n }\n\t\t\tconsequence{\n hits{\n total\n edges{\n node{\n transcript{\n transcript_id\n\t\t\t\t\t aa_change\n\t\t\t\t\t consequence_type\n\t\t\t\t\t is_canonical\n\t\t\t\t\t gene{\n\t\t\t\t\t \tsymbol\n\t\t\t\t\t }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}";function G(t){if(!t.rglst)throw".rglst missing";const e=t.rglst[0];if(!e)throw".rglst[0] missing";if("string"!=typeof e.chr)throw".rglst[0].chr not string";if(!Number.isInteger(e.start))throw".rglst[0].start not integer";if(!Number.isInteger(e.stop))throw".rglst[0].stop not integer";const n={filters:{op:"and",content:[{op:"=",content:{field:"chromosome",value:[e.chr]}},{op:">=",content:{field:"start_position",value:[e.start]}},{op:"<=",content:{field:"end_position",value:[e.stop]}}]}};if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";n.filters.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&n.filters.content.push(t.filter0),t.filterObj&&n.filters.content.push(u(t.filterObj)),n}},4973:(t,e,n)=>{"use strict";n.d(e,{z9:()=>h,dq:()=>f,uK:()=>d});var r=n(1881),o=n(1169),i=n(9064),s=n(7011);async function a(t,e){const n=[];let r=null,o=null;for(const i of e.map((e=>e[t.id]))){var a,l;if(null!==(a=t.values)&&void 0!==a&&null!==(l=a[i])&&void 0!==l&&l.uncomputable)continue;const e=Number(i);Number.isFinite(e)&&(n.push(e),null===r?r=o=e:(r=Math.min(r,e),o=Math.max(o,e)))}const c=(0,i.Z)().domain([r,o]).range([10,510]),u=(0,s.I)(c,{values:n});if(!Array.isArray(u.bins))throw"violinBins does not return {bins[]}";if(0==u.bins.length)throw"violinBins {bins[]} empty array";const f={minvalue:r,maxvalue:o,densitymax:0,density:[],samplecount:n.length,unit:t.unit};for(const t of u.bins){if(!Number.isFinite(t.x0))throw"b.x0 not number";if(!Number.isFinite(t.x1))throw"b.x1 not number";if(!Number.isFinite(t.binValueCount))throw"b.binValueCount not number";f.density.push([(t.x0+t.x1)/2,t.binValueCount]),f.densitymax=Math.max(f.densitymax,t.binValueCount)}return f}n(3345);var l=n(2273),c=n(4065),u=n(2974);const f=".";function d(t){const e=t.variant2samples;if(e){if(e.type_samples="samples",e.type_sunburst="sunburst",e.type_summary="summary",!e.variantkey)throw".variantkey missing from variant2samples";if(-1==["ssm_id"].indexOf(e.variantkey))throw"invalid value of variantkey";if(e.twLst){if(!Array.isArray(e.twLst))throw"variant2samples.twLst[] is not array";if(0==e.twLst.length)throw"variant2samples.twLst[] empty array";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.twLst is in use";for(const n of e.twLst){if(!n.id)throw"tw.id missing from one of variant2samples.twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.twLst: "+n.id}}if(e.sunburst_twLst){if(!Array.isArray(e.sunburst_twLst))throw".sunburst_twLst[] not array from variant2samples";if(0==e.sunburst_twLst.length)throw".sunburst_twLst[] empty array from variant2samples";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.sunburst_twLst is in use";for(const n of e.sunburst_twLst){if(!n.id)throw"tw.id missing from one of variant2samples.sunburst_twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.sunburst_twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.sunburst_twLst: "+n.id}}if(e.gdcapi);else{var n,i,s,d,y,v,b;let e=!1;if(null!==(n=t.queries)&&void 0!==n&&null!==(i=n.snvindel)&&void 0!==i&&null!==(s=i.byrange)&&void 0!==s&&null!==(d=s._tk)&&void 0!==d&&d.samples&&(e=!0),null!==(y=t.queries)&&void 0!==y&&null!==(v=y.svfusion)&&void 0!==v&&null!==(b=v.byrange)&&void 0!==b&&b.samples&&(e=!0),!e)throw"cannot find a sample source from ds.queries{}"}e.get=async e=>await async function(t,e){!function(t,e){if("samples"==t.get){var n,r;const o=null===(n=e.queries)||void 0===n||null===(r=n.snvindel)||void 0===r?void 0:r.byrange;o&&(o.bcffile||o.chr2bcffile)&&o._tk.format&&(t.addFormatValues=!0)}}(t,e);const n=await async function(t,e){var n;const r=t.twLst?t.twLst.slice():[];if(e.variant2samples.gdcapi)return await(0,o.nD)(t,r,e,t.geneTwLst);if(t.ssm_id_lst)return await async function(t,e,n){const r=new Map;for(const e of t.ssm_id_lst.split(",")){const o=e.split(f);if(4!=o.length){if(6!=o.length)throw"unknown format of ssm id";{if(!n.queries.svfusion||!n.queries.svfusion.byrange)throw"queries.svfusion.byrange missing when id has 6 fields";const[e,i,s,a,c,u]=o,f=decodeURIComponent(u),d=Number(e);if(d!=l.dtsv&&d!=l.dtfusionrna)throw"dt not sv/fusion";const p=Number(s);if(Number.isNaN(p))throw"position not integer";const m=Number(c);if(Number.isNaN(m))throw"pairlstIdx not integer";const g=Object.assign({},t,{rglst:[{chr:i,start:p,stop:p+1}]}),y=await n.queries.svfusion.byrange.get(g);for(const t of y)t.dt==d&&t.pos==p&&t.strand==a&&t.pairlstIdx==m&&t.mname==f&&h(t.samples,r,t.ssm_id)}}else{if(!n.queries.snvindel||!n.queries.snvindel.byrange)throw"queries.snvindel.byrange missing when id has 4 fields";const[e,i,s,a]=o,l=Number(i);if(Number.isNaN(l))throw"no integer position for snvindel from ssm id";const c=Object.assign({},t,{rglst:[{chr:e,start:l,stop:l}]}),u=await n.queries.snvindel.byrange.get(c);for(const t of u)t.pos==l&&t.ref==s&&t.alt==a&&h(t.samples,r,t.ssm_id)}}return p(r,e,n),{samples:[...r.values()]}}(t,r,e);if(t.rglst)return await m(t,r,e);if(t.geneTwLst){if("object"!=typeof t.genome)throw"serverside genome obj needed";t.rglst=[];for(const e of t.geneTwLst)if(e.term.chr&&e.term.start&&e.term.stop)t.rglst.push({chr:e.term.chr,start:e.term.start,stop:e.term.stop});else{const n=c.S(t.genome,{deep:1,input:e.term.name});if(n.gmlst){const e=n.gmlst[0];t.rglst.push({chr:e.chr,start:e.start,stop:e.stop})}}const n=await m(t,r,e);return delete t.rglst,{samples:n}}if(null==e||null===(n=e.cohort)||void 0===n||!n.termdb)throw"unable to do sql query: .cohort.termdb missing for ds";const i={ds:e,filter:t.filter||t.filterObj},s=await(0,u.gh)(i,t.twLst),a=[];for(const e in s.samples){const n=s.samples[e];n.sample_id=n.sample,delete n.sample;for(const e of t.twLst)n[e.term.id]&&(n[e.term.id]=n[e.term.id].key);a.push(n)}return{samples:a}}(t,e);if(t.get==e.variant2samples.type_samples){var i,s,d;return!t.useIntegerSampleId&&null!=e&&null!==(i=e.cohort)&&void 0!==i&&null!==(s=i.termdb)&&void 0!==s&&null!==(d=s.q)&&void 0!==d&&d.id2sampleName&&n.samples.forEach((t=>t.sample_id=e.cohort.termdb.q.id2sampleName(t.sample_id))),n}if(t.get==e.variant2samples.type_sunburst)return n.nodes=await async function(t,e,n){var o,i;const s=(0,r.N)(t,n.twLst.map((t=>({k:t.id}))));for(const t of s)delete t.lst;if(null!=e&&null!==(o=e.cohort)&&void 0!==o&&null!==(i=o.termdb)&&void 0!==i&&i.termid2totalsize2){const t=await async function(t,e,n,r){var o,i;if(0==t.length)throw"zero terms for crosstab";if(t.length>3)throw"crosstab will not work with more than 3 levels";const s=[],a=new Map;for(const e of t)a.set(e.id,new Set);const l=!r;if(r)for(const n of r){if(n.id0){if(!n.v0)continue;a.get(n.id0).add(e.cohort.termdb.useLower?n.v0.toLowerCase():n.v0)}if(n.id1&&t[1]){if(!n.v1)continue;a.get(n.id1).add(e.cohort.termdb.useLower?n.v1.toLowerCase():n.v1)}if(n.id2&&t[2]){if(!n.v2)continue;a.get(n.id2).add(e.cohort.termdb.useLower?n.v2.toLowerCase():n.v2)}}const c=t[0].id;{const r={};n.filterObj&&(r.filterObj=n.filterObj);const o=await e.cohort.termdb.termid2totalsize2.get([t[0]],r);for(const[t,n]of o.get(c)){const r=e.cohort.termdb.useLower?t.toLowerCase():t;l?(a.get(c).add(r),s.push({count:n,id0:c,v0:r})):a.get(c).has(r)&&s.push({count:n,id0:c,v0:r})}}const u=null==t||null===(o=t[1])||void 0===o?void 0:o.id;if(u){const r=[];for(const o of a.get(c)){const i={tid2value:{[c]:o}};n.filterObj&&(i.filterObj=n.filterObj),r.push(e.cohort.termdb.termid2totalsize2.get([t[1]],i,o))}const o=await Promise.all(r);for(const[t,n]of o)for(const[r,o]of t.get(u)){const t=e.cohort.termdb.useLower?r.toLowerCase():r;l?(a.get(u).add(t),s.push({count:o,id0:c,v0:n,id1:u,v1:t})):a.get(u).has(t)&&s.push({count:o,id0:c,v0:n,id1:u,v1:t})}}const f=null==t||null===(i=t[2])||void 0===i?void 0:i.id;if(f){const r=[];for(const o of a.get(c))for(const i of a.get(u)){const s={tid2value:{[c]:o,[u]:i}};n.filterObj&&(s.filterObj=n.filterObj),r.push(e.cohort.termdb.termid2totalsize2.get([t[2]],s,{v0:o,v1:i}))}const o=await Promise.all(r);for(const[t,n]of o)for(const[t,r]of v2counts.get(f)){const o=e.cohort.termdb.useLower?t.toLowerCase():t;l?(a.get(f).add(o),s.push({count:r,id0:c,v0:n.v0,id1:u,v1:n.v1,id2:f,v2:o})):a.get(f).has(o)&&s.push({count:r,id0:c,v0:n.v0,id1:u,v1:n.v1,id2:f,v2:o})}}return s}(n.twLst,e,n,s);await async function(t,e,n){for(const r of t){if(!r.id0)continue;if(!r.v0)continue;const t=n.cohort.termdb.useLower?r.v0.toLowerCase():r.v0;if(!r.id1){const n=e.find((e=>null==e.id1&&e.v0==t));n&&(r.cohortsize=n.count);continue}if(!r.v1)continue;const o=n.cohort.termdb.useLower?r.v1.toLowerCase():r.v1;if(!r.id2){const n=e.find((e=>null==e.id2&&e.v0==t&&e.v1==o));n&&(r.cohortsize=n.count);continue}if(!r.v2)continue;const i=n.cohort.termdb.useLower?r.v2.toLowerCase():r.v2;if(!r.id3){const e=crosstabL2.find((e=>e.v0==t&&e.v1==o&&e.v2==i));e&&(r.cohortsize=e.count)}}}(s,t,e)}return s}(n.samples,e,t),delete n.samples,n;if(t.get==e.variant2samples.type_summary)return n.summary=await async function(t,e,n){if(!n.twLst)throw"q.twLst[] missing for make_summary()";const r=[];for(const e of n.twLst)if(e.term)if("categorical"==e.term.type){const n=g(t,e.id);r.push({termid:e.id,termname:e.term.name,numbycategory:[...n].sort(((t,e)=>e[1]-t[1]))})}else{if("integer"!=e.term.type&&"float"!=e.term.type)throw"unknown term type";{const n=await a(e.term,t);r.push({termid:e.id,termname:e.term.name,density_data:n})}}if(e.cohort.termdb.termid2totalsize2){const t=await e.cohort.termdb.termid2totalsize2.get(n.twLst,n);for(const{termid:e,numbycategory:n}of r){if(!n)continue;const r=t.get(e);if(r)for(const t of n){const e=r.find((e=>e[0].toLowerCase()==t[0].toLowerCase()));e&&t.push(e[1])}}}return r}(n.samples,e,t),delete n.samples,n;throw"unknown get type"}(e,t)}}function h(t,e,n){for(const r of t){e.has(r.sample_id)||(r.ssm_id_lst=[],r.formatK2v&&(r.ssmid2format={}),e.set(r.sample_id,r));const t=e.get(r.sample_id);t.ssm_id_lst.push(n),t.ssmid2format&&(t.ssmid2format[n]=r.formatK2v)}}function p(t,e,n){if(e)for(const r of t.values())for(const t of e){const e=n.cohort.termdb.q.getSample2value(t.id,r.sample_id);e[0]&&(r[t.id]=e[0].value)}}async function m(t,e,n){const r=new Map;if(n.queries.snvindel){const e=await n.queries.snvindel.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}if(n.queries.svfusion){const e=await n.queries.svfusion.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}return p(r,e,n),{samples:[...r.values()]}}function g(t,e){const n=new Map;if("sample_id"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.sample_id))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}if("case_uuid"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.case_uuid))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}for(const e of t){const t=e[term.id];t&&n.set(t,1+(n.get(t)||0))}return n}},334:(t,e,n)=>{var r;const o=n(7147),i=n(1017),s=process.cwd()?process.cwd()+"/serverconfig.json":"",a=i.join(__dirname,"../serverconfig.json"),l=i.join(__dirname,"../../serverconfig.json"),c=s&&o.existsSync(s)?s:o.existsSync(a)?a:o.existsSync(l)?l:"";let u;if(!c)throw"missing serverconfig.json";try{const t=o.readFileSync(c,{encoding:"utf8"});u=JSON.parse(t)}catch(t){throw`Error reading or parsing ${c}:`+t}if(u.port||(u.port=process.env.PP_PORT||3e3),u.tabix||(u.tabix="tabix"),u.samtools||(u.samtools="samtools"),u.bcftools||(u.bcftools="bcftools"),u.hicstraw||(u.hicstraw="straw"),u.bigwigsummary||(u.bigwigsummary="bigWigSummary"),u.bigBedToBed||(u.bigBedToBed="bigBedToBed"),u.bigBedInfo||(u.bigBedInfo="bigBedInfo"),u.bigBedNamedItems||(u.bigBedNamedItems="bigBedNamedItems"),u.clustalo||(u.clustalo="clustalo"),u.Rscript||(u.Rscript="Rscript"),u.gfServer||(u.gfServer="gfServer"),u.gfClient||(u.gfClient="gfClient"),!("allow_env_overrides"in u)&&u.debugmode&&(u.allow_env_overrides=!0),!u.binpath){const t=process.argv.find((t=>t.includes("/build")));if(t)u.binpath=t.split("/build")[0]+"/server";else{if(process.argv.find((t=>t.includes(".spec.js"))))u.binpath=i.dirname(__dirname);else{const t=process.argv.find((t=>t.endsWith("/bin.js")||t.endsWith("/server.js")||t.endsWith("/proteinpaint")||t.endsWith("/proteinpaint-server")));if(t)try{const e=o.realpathSync(t);u.binpath=i.dirname(e)}catch(t){throw t}else if(o.existsSync("./server"))u.binpath=o.realpathSync("./server");else if(o.existsSync("./src"))u.binpath=o.realpathSync("./src/..");else if(__dirname.includes("/server/"))u.binpath=__dirname.split("/server/")[0]+"/server";else{if(!__dirname.includes("/proteinpaint"))throw"unable to determine the serverconfig.binpath";u.binpath=__dirname}}}}if(u.debugmode){const t=[],e=i.join(u.binpath,"src/test/routes"),n=["gdc.js","specs.js","readme.js"];if(u.routeSetters)for(const r of u.routeSetters)if(!n.includes(r))if(o.existsSync(r))t.push(r);else if(o.existsSync(`${e}/${r}`))t.push(`${e}/${r}`);else{const e=i.join(u.binpath,r);o.existsSync(e)&&t.push(e)}for(const r of n){const n=`${e}/${r}`;!t.includes(n)&&o.existsSync(n)&&t.push(n)}u.routeSetters=t}if(u.allow_env_overrides){if(process.env.PP_URL&&(u.URL=process.env.URL),"PP_BASEPATH"in process.env&&(u.basepath=process.env.PP_BASEPATH),o.existsSync("./.ssl")&&!u.ssl){u.ssl={};const t=o.readdirSync("./.ssl");for(const e of t)e.endsWith(".key")&&(u.ssl.key=process.cwd()+"/.ssl/"+e),e.endsWith(".crt")&&(u.ssl.cert=process.cwd()+"/.ssl/"+e)}"PP_BACKEND_ONLY"in process.env&&(u.backend_only=1==+process.env.PP_BACKEND_ONLY||"true"===process.env.PP_BACKEND_ONLY)}if(null!==(r=process.env.PP_MODE)&&void 0!==r&&r.startsWith("container")&&Object.assign(u,{port:3e3,tpmasterdir:"/home/root/pp/tp",cachedir:"/home/root/pp/cache",hicstraw:"/home/root/pp/tools/straw",bigwigsummary:"/home/root/pp/tools/bigWigSummary",bigBedToBed:"/home/root/pp/tools/bigBedToBed",bigBedNamedItems:"/home/root/pp/tools/bigBedNamedItems",bigBedInfo:"/home/root/pp/tools/bigBedInfo"}),u.features||(u.features={}),process.argv.find((t=>"validate"==t))&&(u.features.stopGdcCacheAliquot=!0),!u.backend_only&&o.existsSync(i.join(process.cwd(),"./public"))){const t=i.join(u.binpath,"cards");u.cards||(u.cards={target:t,path:"cards"})}if(o.existsSync("./public/rev.txt")){const t=o.readFileSync("./public/rev.txt",{encoding:"utf8"}).trim().split(" ")[1];t&&(u.commitHash=t)}if(o.existsSync("./package.json")){const t=o.readFileSync("./package.json",{encoding:"utf8"});u.version=JSON.parse(t).version}t.exports=u},938:(t,e,n)=>{"use strict";n.d(e,{e8:()=>f,Tt:()=>h,TO:()=>u});n(1017);var r=n(3345);const o=require("partjson");var i=n.n(o),s=n(2163),a=n(1271),l=n(2974),c=n(2273);(0,s.WU)(".3r");function u(t){return async(e,n)=>{const r=e.query;for(const t of[0,1,2]){const e="term"+t,n=e+"_id";"string"==typeof r[n]?r[n]=decodeURIComponent(r[n]):"string"==typeof r[e]&&(r[e]=JSON.parse(decodeURIComponent(r[e])));const o=e+"_q";"string"==typeof r[o]&&(r[o]=JSON.parse(decodeURIComponent(r[o])))}try{const e=t[r.genome];if(!e)throw"invalid genome";const o=e.datasets[r.dslabel];if(!o)throw"invalid dslabel";if(!o.cohort)throw"ds.cohort missing";const i=o.cohort.termdb;if(!i)throw"no termdb for this dataset";const s=await f(r,o,i);r.term2_q&&await async function(t,e,n){const r=[];for(const e of t.charts){const t={};t.chartId=e.chartId,t.serieses=[];const o=e.serieses.filter((t=>!n.term1.includes(t.seriesId)));for(const e of o){const r={};r.seriesId=e.seriesId,r.data=e.data.filter((t=>!n.term2.includes(t.dataId))),r.total=r.data.reduce(((t,e)=>t+e.total),0),t.serieses.push(r)}t.total=t.serieses.reduce(((t,e)=>t+e.total),0),t.maxSeriesTotal=t.serieses.reduce(((t,e)=>t<e.total?e.total:t),0),r.push(t)}t.tests={};for(const n of r){const r={};for(const t of n.serieses)for(const e of t.data)r[e.dataId]=void 0===r[e.dataId]?e.total:r[e.dataId]+e.total;const o=[];let i=0;const s=new Map;for(const t of n.serieses)for(const e of t.data){const a=e.total,l=r[e.dataId]-e.total,c=t.total-e.total,u=n.total-r[e.dataId]-(t.total-e.total),f=t.seriesId,d=e.dataId;o.push({index:i,n1:a,n2:l,n3:c,n4:u}),s.set(i,{seriesId:f,dataId:d}),i++}const l={input:o},c=e.cohort.termdb.multipleTestingCorrection;c&&(l.mtc=c.method,c.skipLowSampleSize&&(l.skipLowSampleSize=c.skipLowSampleSize));const u=await(0,a.run_rust)("fisher",JSON.stringify(l)),f=[];for(const t of JSON.parse(u)){const e=s.get(t.index).seriesId,n=s.get(t.index).dataId,r=t.n1,o=t.n2,i=t.n3,a=t.n4,l=t.p_value,c="chisq"===t.fisher_chisq,u=null===l,d=t.adjusted_p_value,h=f.find((t=>t.term1comparison===e));h?h.term2tests.push({term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:o,R1C2:i,R2C2:a},isChi:c,skipped:u}):f.push({term1comparison:e,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:o,R1C2:i,R2C2:a},isChi:c,skipped:u}]})}t.tests[n.chartId]=f}}(s.data,o,r.hiddenValues),n.send(s)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}async function f(t,e,n){if(t.ds=e,t.ssid){const[e,n]=await r.L0(t.ssid);t.sample2gt=e,t.genotype2sample=n}const o=+new Date;t.results={};const s=new Map;for(let e=0;e<=2;e++){let n=null;if(t[`term${e}_id`]){const r=t[`term${e}_id`];n={id:r,q:t[`term${e}_q`],term:{id:r}}}else t[`term${e}`]&&(n={term:t[`term${e}`],q:t[`term${e}_q`]});n&&s.set(e,n)}const a=[...s.values()],u=await(0,l.Yu)({filter:t.filter,terms:a},t.ds,t.genome),f=new Map,p=[];var m,g,y,v;if(u.samples)if("geneVariant"==(null===(m=s.get(1))||void 0===m||null===(g=m.term)||void 0===g?void 0:g.type)||"geneVariant"==(null===(y=s.get(2))||void 0===y||null===(v=y.term)||void 0===v?void 0:v.type))!function(t,e,n,r,o){var i,s,a,l;e.push([]);let u=1;const f=t.get(1)?t.get(1).term:null,d=null!=f&&f.id?f.id:null==f?void 0:f.name;d&&null!==(i=n.refs.byTermId[d])&&void 0!==i&&i.bins?e.push(null===(s=n.refs.byTermId[d])||void 0===s?void 0:s.bins):e.push([]);const h=t.get(2)?t.get(2).term:null,p=null!=h&&h.id?h.id:null==h?void 0:h.name;p&&null!==(a=n.refs.byTermId[p])&&void 0!==a&&a.bins?e.push(null===(l=n.refs.byTermId[p])||void 0===l?void 0:l.bins):e.push([]);for(const[e,i]of Object.entries(n.samples)){var m,g,y,v;const n=parseInt(e);if("geneVariant"==(null===(m=t.get(1))||void 0===m||null===(g=m.term)||void 0===g?void 0:g.type)){const t=[],e=i[d];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key1){const t=e.item.key1;e.item.key1={},e.item.key1[t]=1}e.item.key1[c.mclass[r.class].label]=e.item.key1[c.mclass[r.class].label]?e.item.key1[c.mclass[r.class].label]+1:1}else{var b,w,_;const e={sample:u,name:o.sampleId2Name.get(n)};e.key1=c.mclass[r.class].label,e.val1=c.mclass[r.class].label;const s=null===(b=o.assayAvailability)||void 0===b||null===(w=b.byDt)||void 0===w||null===(_=w[r.dt])||void 0===_?void 0:_.byOrigin;var x;if(s)e.key0=e.val0=((null===(x=s[r.origin])||void 0===x?void 0:x.label)||r.origin)+" "+c.dt2label[r.dt];else e.key0=e.val0=c.dt2label[r.dt];e.key2=i[p]?i[p].key:"",e.val2=i[p]?i[p].value:"",t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key1){let t="";for(const[n,r]of Object.entries(e.item.key1))t+=`${n}(${r})+`;e.item.key1=t.slice(0,-1),e.item.val1=t.slice(0,-1)}r.set(u.toString(),e.item),u++}}else if("geneVariant"==(null===(y=t.get(2))||void 0===y||null===(v=y.term)||void 0===v?void 0:v.type)){const t=[],e=i[p],s=i[d];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key2){const t=e.item.key2;e.item.key2={},e.item.key2[t]=1}e.item.key2[c.mclass[r.class].label]=e.item.key2[c.mclass[r.class].label]?e.item.key2[c.mclass[r.class].label]+1:1}else{var k,q,N;const e={sample:u,name:o.sampleId2Name.get(n)};e.key1=s.key,e.val1=s.value;const i=null===(k=o.assayAvailability)||void 0===k||null===(q=k.byDt)||void 0===q||null===(N=q[r.dt])||void 0===N?void 0:N.byOrigin;var S;if(i)e.key0=e.val0=((null===(S=i[r.origin])||void 0===S?void 0:S.label)||r.origin)+" "+c.dt2label[r.dt];else e.key0=e.val0=c.dt2label[r.dt];e.key2=c.mclass[r.class].label,e.val2=c.mclass[r.class].label,t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key2){let t="";for(const[n,r]of Object.entries(e.item.key2))t+=`${n}(${r})+`;e.item.key2=t.slice(0,-1),e.item.val2=t.slice(0,-1)}r.set(u.toString(),e.item),u++}}}}(s,p,u,f,e);else for(let t=0;t<=2;t++){var b,w,_;const e=null===(b=s.get(t))||void 0===b?void 0:b.q,n=s.get(t)?s.get(t).term:null,r=null!=n&&n.id?n.id:null==n?void 0:n.name;if(r&&null!==(w=u.refs.byTermId[r])&&void 0!==w&&w.bins?p.push(null===(_=u.refs.byTermId[r])||void 0===_?void 0:_.bins):p.push([]),null!=e&&e.binColored)for(const n of p[t]){const t=e.binColored;n.start==t.start&&n.stop==t.stop&&(n.color=t.color)}for(const[e,n]of Object.entries(u.samples)){let o;if(f.get(e))o=f.get(e);else if(!f.has(e)){o={sample:parseInt(e)},f.set(e,o)}if(o)if(r){const i=n[r];i?(o[`key${t}`]=i.key,o[`val${t}`]=i.value):f.set(e,null)}else o[`key${t}`]="",o[`val${t}`]=""}}t.results.lst=[...f.values()].filter((t=>null!==t)),t.results.bins=p;const x=+new Date,k=function(t,e,n,o){const s=[0,1,2].map((e=>{const r=function(t,e,n){const r=t["term"+n+"_id"];let o={};t[r]||r?o=e.q.termjsonByOneid(r):t[`term${n}`]&&(o=t[`term${n}`]);const i="integer"==o.type||"float"==o.type,s=o.values?Object.keys(o.values).filter((t=>o.values[t].uncomputable)).map((t=>+t)):[],a=t=>i&&!s.includes(t),l=t["term"+n+"_q"]?t["term"+n+"_q"]:{};return{term:o,isComputableVal:a,q:l}}(t,n,e);r.q.index=e;const o=t.results.bins[e];return Object.assign(r,{key:"key"+e,val:"val"+e,nval:"nval"+e,bins:o,q:r.q,orderedLabels:h(r.term,o,void 0,r.q)})}));return new(i())({data:e,seed:'{"results": {"charts": [], "refs":{}}}',template:d,"=":{prep(t){for(const e of s)"condition"==e.term.type?(t[e.key]=e.q.bar_by_grade&&t[e.key]in e.term.values?e.term.values[t[e.key]].label:t[e.key],t[e.val]=t[e.key]):"float"!=e.term.type&&"integer"!=e.term.type||e.isComputableVal(t[e.val])&&(t[e.nval]=t[e.val]);return!0},sampleCount:(t,e)=>e.self.samples?e.self.samples.size:void 0,maxSeriesTotal(t,e){let n=0;for(const t of e.self.serieses)t&&t.total>n&&(n=t.total);return n},maxAcrossCharts(t,e){let n=0;for(const t of e.self.charts)t.maxSeriesTotal>n&&(n=t.maxSeriesTotal);return n},boxplot(t,e){const n=e.self.values;if(!n||!n.length)return;n.sort(((t,e)=>t-e));const o=r.JC(n.map((t=>({value:+t}))));o.mean=e.self.sum/n.length;let i=0;for(const t of n)i+=Math.pow(t-o.mean,2);return o.sd=Math.sqrt(i/(n.length-1)),o.min=e.self.min,o.max=e.self.max,o},getAF(e,n){if(o.track&&o.track.vcf&&o.track.vcf.termdb_bygenotype&&o.track.vcf.termdb_bygenotype.getAF&&t.term2_is_genotype){if(!t.chr)throw"chr missing for getting AF";if(!t.pos)throw"pos missing for getting AF";return function(t,e,n,o,i){const s=i.track.vcf.termdb_bygenotype,a=o.has(r.EO.href)?o.get(r.EO.href):new Set,l=o.has(r.EO.halt)?o.get(r.EO.halt):new Set,c=o.has(r.EO.het)?o.get(r.EO.het):new Set;let u=0,f=0;for(const r of t){let t=!1;if(s.sex_chrs.has(e))if(s.male_samples.has(r)){if(s.chr2par&&s.chr2par[e])for(const r of s.chr2par[e])if(n>=r.start&&n<=r.stop){t=!0;break}}else t=!0;else t=!0;t?(f+=2,l.has(r)?u+=2:c.has(r)&&u++):(f++,a.has(r)||u++)}return 0==f||0==u?0:(u/f).toFixed(3)}(n.self.samples?[...n.self.samples]:[],t.chr,Number(t.pos),t.genotype2sample,o)}},filterEmptySeries(t){const e=t.serieses.filter((t=>t.total));t.serieses.splice(0,t.serieses.length,...e)},bins:()=>s.map((t=>t.bins)),q:()=>s.map(((t,e)=>{const n={};for(const e in t.q)"index"!=e&&(n[e]=t.q[e]);return n})),useColOrder:()=>s[1].orderedLabels.length>0,useRowOrder:()=>s[2].orderedLabels.length>0,sortColsRows(t){if(s[1].orderedLabels.length){const e=s[1].orderedLabels;t.cols.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}if(s[2].orderedLabels.length){const e=s[2].orderedLabels;t.rows.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}},sortCharts(t){if(s[0].orderedLabels.length){const e=s[0].orderedLabels;t.charts.sort(((t,n)=>e.indexOf(t.chartId)-e.indexOf(n.chartId)))}}}})}(t,t.results.lst,n,e);k.tree.results&&(k.tree.results.times={sql:x-o,pj:k.times});return{data:k.tree.results,bins:p}}const d=JSON.stringify({"@errmode":["","","",""],"@before()":"=prep()",results:{"_2:maxAcrossCharts":"=maxAcrossCharts()","_:_min":">$nval1","_:_max":"<$nval1",charts:[{chartId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()","_1:maxSeriesTotal":"=maxSeriesTotal()","@done()":"=filterEmptySeries()",serieses:[{seriesId:"@key",data:[{dataId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()"},"$key2"],"_:_max":"<$nval2","~values":["$nval2",0],"~sum":"+$nval2","~samples":["$sample","set"],"__:total":"=sampleCount()","__:boxplot":"=boxplot()","__:AF":"=getAF()"},"$key1"]},"$key0"],"~sum":"+$nval1","~values":["$nval1",0],"__:boxplot":"=boxplot()","_:_refs":{cols:["$key1"],colgrps:["-"],rows:["$key2"],rowgrps:["-"],col2name:{$key1:{name:"@branch",grp:"-"}},row2name:{$key2:{name:"@branch",grp:"-"}},"__:useColOrder":"=useColOrder()","__:useRowOrder":"=useRowOrder()","__:bins":"=bins()","__:q":"=q()","@done()":"=sortColsRows()"},"@done()":"=sortCharts()"}});function h(t,e,n,r){if(n)return n.map((t=>t.label));if("condition"==t.type){var o;if(null!=r&&null!==(o=r.groups)&&void 0!==o&&o.length)return r.groups.map((t=>t.name));if(t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label))}const i=Object.values(t.values||{})[0];return i&&"order"in i?Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:"order"in t.values[e]?t.values[e].order:"order"in t.values[n]?t.values[n].order:0)).map((e=>t.values[e].key)):null==e?void 0:e.map((t=>t.name?t.name:t.label))}},4453:(t,e,n)=>{"use strict";n.d(e,{g:()=>d,y:()=>h});var r=n(1017),o=n.n(r),i=n(8907),s=n(3345),a=n(7147),l=n.n(a),c=n(9157),u=n(334),f=n.n(u);async function d(t,e){try{if(!e.cohort)throw"cohort missing from ds";const n=e.cohort.termdb.minTimeSinceDx;if(!n)throw"missing min time since dx";t.ds=e;const r={data:{}},o=await(0,i.g5)(t);if(!o.lst.length)return r;const s={};for(const t of o.lst){const e=t.key0,n=t.val1,r=t.key1,o=t.key2;e in s||(s[e]=[]),s[e].push({time:n,event:r,series:o})}const a=t.term2_id&&o.CTE2.bins?o.CTE2.bins:[];r.refs={bins:a};const l={data:{},startTime:n};r.noEvents={};for(const t in s){const e=s[t],n=new Set(e.map((t=>t.series)));for(const o of n)e.find((t=>t.series==o&&1===t.event))||(t in r.noEvents?r.noEvents[t].push(o):r.noEvents[t]=[o]);const o=e.filter((e=>{var n;return!(null!==(n=r.noEvents[t])&&void 0!==n&&n.includes(e.series))}));o.length?l.data[t]=o:r.data[t]={}}if(!Object.keys(l.data).length)return{data:{}};const c=await h(l);return Object.assign(r.data,c),r}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function h(t){for(let e in t.data)""===e&&(e="*",t.data[e]=t.data[""],delete t.data[""]),t.data[e]=t.data[e].map((t=>({time:t.time,event:t.event,series:""===t.series?"*":t.series})));const e=o().join(f().cachedir,Math.random().toString()+".json");await(0,s.Sf)(e,JSON.stringify(t));const n=await(0,c.default)(o().join(f().binpath,"utils/cuminc.R"),[],[e]),r=JSON.parse(n[0]);for(const t in r)"*"===t&&(r[""]=r[t],delete r[t]);for(const t in r)for(const e in r[t].estimates)"*"===e&&(r[t].estimates[""]=r[t].estimates[e],delete r[t].estimates[e]);return l().unlink(e,(()=>{})),r}},5257:(t,e,n)=>{"use strict";async function r(t,e,n="f"){if(!t)return;if("tvslst"!=t.type)throw'filter.type is not "tvslst" but: '+t.type;if(!Array.isArray(t.lst))throw"filter.lst must be an array";if(0==t.lst.length)return console.error("filter.lst[] is zero length, see if is an error");if(1==t.lst.length){if("tvslst"==t.lst[0].type)throw'only one element at a level: type should not be "tvslst"'}else if("or"!=t.join&&"and"!=t.join)throw'multiple elements at a level: filter.join must equal either "or" or "and"';"in"in t||(t.in=!0);const u=[],f=[],d=[];for(const[h,p]of t.lst.entries()){const t=n+"_"+h;let m;if("tvslst"==p.type)m=await r(p,e,t);else{if(!p.tvs)throw"filter item should have a 'tvs' or 'lst' property";if("categorical"==p.tvs.term.type)m=o(p.tvs,t);else if("survival"==p.tvs.term.type)m=i(p.tvs,t);else if("samplelst"==p.tvs.term.type)m=s(p.tvs,t);else if("integer"==p.tvs.term.type||"float"==p.tvs.term.type)m=l(p.tvs,t,e);else if("condition"==p.tvs.term.type)m=c(p.tvs,t);else{if("geneVariant"!=p.tvs.term.type)throw"unknown term type";m=await a(p.tvs,t,e)}}u.push(m.CTEname),f.push(...m.CTEs),d.push(...m.values)}const h="and"==t.join?"INTERSECT":"UNION",p=u.map((t=>"SELECT * FROM "+t)).join("\n"+h+"\n");return t.in?f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${p}\n\t\t\t\t)\n\t\t\t`):f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\tSELECT id as sample\n\t\t\t\t\tFROM sampleidmap\n\t\t\t\t\tWHERE sample NOT IN (\n\t\t\t\t\t\t${p}\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t`),{filters:f.join(",\n"),CTEs:f,values:d,CTEname:n}}function o(t,e){return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = ?\n\t\t\t\tAND value ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function i(t,e){var n,r;return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM survival\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${null!==(n=t.q)&&void 0!==n&&n.cutoff?"AND tte >= "+(null===(r=t.q)||void 0===r?void 0:r.cutoff):""}\n\t\t\t\tAND exit_code ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function s(t,e){const n=[];for(const e in t.term.values)n.push(...t.term.values[e].list);return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${Array(n.length).fill("?").join(", ")})\n\t\t\t)`],values:[...n.map((t=>t.sampleId))],CTEname:e}}async function a(t,e,n){const r={term:t.term,q:{}},o=await n.mayGetGeneVariantData(r,{genome:n.genomename}),i=[];for(const[e,n]of o){const r=n[t.term.name].values;let o=!0;for(const e of t.values){const t=r.filter((t=>t.dt==e.dt&&(!e.origin||e.origin==t.origin)));for(const n of t)if(e.mclassExcludeLst.includes(null==n?void 0:n.class)){o=!1;break}}o&&i.push(e)}return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${i.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[...i],CTEname:e}}function l(t,e,n){if(!t.ranges)throw".ranges{} missing";const r=[t.term.id],o=n.cohort.termdb.q.termjsonByOneid(t.term.id),i=[];let s,a=!1;for(const e of t.ranges)if("value"in e){const n=t.isnot?"!":"";i.push(`value ${n}= ?`),r.push(""+e.value)}else{a=!0;const n=[];e.startunbounded||(e.startinclusive?n.push("value >= ?"):n.push("value > ? "),r.push(e.start)),e.stopunbounded||(e.stopinclusive?n.push("value <= ?"):n.push("value < ? "),r.push(e.stop));const o=t.isnot?"NOT ":"";n.length&&i.push(o+"("+n.join(" AND ")+")")}a&&o.values&&(s=Object.keys(o.values).filter((t=>o.values[t].uncomputable)).map(Number).filter((e=>t.isnot||!t.ranges.find((t=>"value"in t&&Number(t.value)==e)))),s.length&&r.push(...s));const l=i.join(" OR ");return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_${o.type}\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${l?"AND ("+l+")":""}\n\t\t\t\t${s&&s.length?`AND value NOT IN (${s.map((t=>"?")).join(",")})`:""}\n\t\t\t)`],values:r,CTEname:e}}function c(t,e){let n,r;if(t.bar_by_children)n="child";else{if(!t.bar_by_grade)throw"must set the bar_by_grade or bar_by_children query parameter";n="grade"}if(t.value_by_max_grade)r="max_grade";else if(t.value_by_most_recent)r="most_recent";else{if(!t.value_by_computable_grade)throw"unknown setting of value_by_?";r="computable_grade"}const o=[],i=[];if(!t.values)throw t.grade_and_child?"-- Todo: tvs.grade_and_child":'unknown condition term filter type: expecting term-value "values" or "grade_and_child" key';return i.push(t.term.id,...t.values.map((t=>""+t.key))),o.push(`\n\t\t\t${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM ${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\tWHERE term_id = ? \n\t\t\t\tAND ${r} = 1\n\t\t\t\tAND value ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`),{CTEs:o,values:i,CTEname:e}}n.d(e,{w:()=>r})},2826:(t,e,n)=>{"use strict";n.d(e,{iK:()=>U,TO:()=>z});var r=n(334),o=n.n(r),i=n(394),s=(n(8088),n(6191));function a(t,e,n,r){const i=n.cohort.termdb,a={selectCohort:i.selectCohort,supportedChartTypes:i.q.getSupportedChartTypes(t.embedder),allowedTermTypes:l(n),termMatch2geneSet:i.termMatch2geneSet,massSessionDuration:o().features.massSessionDuration||30,dataDownloadCatch:i.dataDownloadCatch,matrix:i.matrix,hierCluster:i.hierCluster,mclass:i.mclass,alwaysRefillCategoricalTermValues:i.alwaysRefillCategoricalTermValues,isGeneSetTermdb:i.isGeneSetTermdb,lollipop:i.lollipop,urlTemplates:i.urlTemplates};i.chartConfigByType&&(a.chartConfigByType=i.chartConfigByType),i.multipleTestingCorrection&&(a.multipleTestingCorrection=i.multipleTestingCorrection),i.helpPages&&(a.helpPages=i.helpPages),i.minTimeSinceDx&&(a.minTimeSinceDx=i.minTimeSinceDx),i.timeUnit&&(a.timeUnit=i.timeUnit),i.cohortStartTimeMsg&&(a.cohortStartTimeMsg=i.cohortStartTimeMsg),i.displaySampleIds&&(a.displaySampleIds=i.displaySampleIds),i.additionalSampleAttributes&&(a.additionalSampleAttributes=i.additionalSampleAttributes),i.logscaleBase2&&(a.logscaleBase2=i.logscaleBase2),n.assayAvailability&&(a.assayAvailability=n.assayAvailability),n.customTwQByType&&(a.customTwQByType=n.customTwQByType),a.requiredAuth=s.i.getRequiredCredForDsEmbedder(t.dslabel,t.embedder),function(t,e){if(!e.restrictAncestries)return;t.restrictAncestries=e.restrictAncestries.map((t=>({name:t.name,tvs:t.tvs})))}(a,i),function(t,e){if(!e.cohort.scatterplots)return;t.scatterplots=e.cohort.scatterplots.plots.map((t=>({name:t.name,dimensions:t.dimensions,colorTW:t.colorTW,shapeTW:t.shapeTW})))}(a,n),function(t,e){if(!e.cohort.matrixplots)return;t.matrixplots=e.cohort.matrixplots.plots.map((t=>({name:t.name})))}(a,n),function(t,e,n){const r=e.queries;if(!r)return;t.queries={defaultCoord:r.defaultCoord||n.defaultcoord};const o=t.queries;r.defaultBlock2GeneMode&&(o.defaultBlock2GeneMode=r.defaultBlock2GeneMode);r.snvindel&&(o.snvindel={allowSNPs:r.snvindel.allowSNPs});r.topMutatedGenes&&(o.topMutatedGenes=r.topMutatedGenes);r.topVariablyExpressedGenes&&(o.topVariablyExpressedGenes=r.topVariablyExpressedGenes);r.singleSampleMutation&&(o.singleSampleMutation={sample_id_key:r.singleSampleMutation.sample_id_key,discoSkipChrM:r.singleSampleMutation.discoSkipChrM});if(r.singleSampleGenomeQuantification){o.singleSampleGenomeQuantification={};for(const t in r.singleSampleGenomeQuantification)o.singleSampleGenomeQuantification[t]=JSON.parse(JSON.stringify(r.singleSampleGenomeQuantification[t])),delete o.singleSampleGenomeQuantification[t].folder}if(r.singleSampleGbtk){o.singleSampleGbtk={};for(const t in r.singleSampleGbtk)o.singleSampleGbtk[t]=JSON.parse(JSON.stringify(r.singleSampleGbtk[t])),delete o.singleSampleGbtk[t].folder}r.rnaseqGeneCount&&(o.rnaseqGeneCount=!0)}(a,n,r),e.send({termdbConfig:a})}function l(t){var e;(0,i.qN)(t);const n=new Set;for(const e of t.cohort.termdb.termtypeByCohort)e.type&&n.add(e.type);if(t.cohort.termdb.allowedTermTypes)for(const e of t.cohort.termdb.allowedTermTypes)n.add(e);return null!=t&&null!==(e=t.queries)&&void 0!==e&&e.defaultBlock2GeneMode&&n.add("geneVariant"),[...n]}var c=n(8907),u=n(5708),f=n(4453),d=n(1017),h=n.n(d),p=n(2974),m=n(3345),g=n(7147),y=n.n(g),v=n(9157);async function b(t,e){try{var n;if(!e.cohort)throw"cohort missing from ds";t.ds=e;const r=[];for(const e of[0,1,2]){const n="term"+e,o=n+"_id";"string"==typeof t[o]?(t[o]=decodeURIComponent(t[o]),t[n]=t.ds.cohort.termdb.q.termjsonByOneid(t[o])):"string"==typeof t[n]&&(t[n]=JSON.parse(decodeURIComponent(t[n])));const i=n+"_q";t[n]&&r.push({term:t[n],q:t[i]})}if(t.term2){if("survival"==t.term2.type&&"survival"==t.term1.type)throw"term and overlay are both survival terms - only one could be a survival term";if("survival"!=t.term2.type&&"survival"!=t.term1.type)throw"no survival terms, either the main term OR the overlay term must be a survival term"}else if("survival"!=t.term1.type)throw"non-survival term";if(t.term0&&"survival"==t.term0.type)throw"term0 must not be a survival term";const i=function(t){if(t.term1&&"survival"==t.term1.type)return 1;if(!t.term2)throw"term1.type is not survival and term2 is missing";if("survival"!=t.term2.type)throw"both term1 and term2 are not survival type";return 2}(t),s=t[`term${i}`],a=t["term"+(1==i?2:1)],l=await(0,p.Yu)({terms:r,filter:t.filter},e,t.genome);if(l.error)throw l.error;const c=function(t,e){const n=Object.values(t.samples).filter((t=>t[e.id]));return n.sort(((t,n)=>t[e.id].value<n[e.id].value?-1:1))}(l,s),u={},f={chart:new Set,series:new Set};for(const e of c){const n=e[s.id],r=n.value;if(r<0)continue;const o=n.key;let i;if(a)if("id"in a){if(!(a.id in e))continue;i=e[a.id].key}else if("samplelst"==a.type){if(!(a.name in e))continue;i=e[a.name].key}else i=w(a,e);else i="*";f.series.add(i);const l=t.term0&&e[t.term0.id||t.term0.name]||{key:""};l.key in u||(u[l.key]=[],f.chart.add(l.key)),u[l.key].push({time:r,status:o,series:i})}const d=t.term2_id&&(null===(n=l.refs[t.term2.id])||void 0===n?void 0:n.bins)||[],g={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:d}};for(const t in u){const e=u[t],n=h().join(o().cachedir,Math.random().toString()+".json");await(0,m.Sf)(n,JSON.stringify(e));const r=await(0,v.default)(h().join(o().binpath,"utils/survival.R"),[],[n]),i=JSON.parse(r);for(const e of i.estimates){for(const t in e)e[t]="series"==t?"*"==e[t]?"":e[t]:Number(e[t]);g.case.push([t,e.series,e.time,e.surv,e.lower,e.upper,e.nevent,e.ncensor,e.nrisk])}i.tests&&(g.tests||(g.tests={}),g.tests[t]=i.tests),y().unlink(n,(()=>{}))}g.case.sort(((t,e)=>t[2]-e[2]));const b=function(t,e=[]){if(t){if("condition"==t.type&&t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label));if(t.values)return Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:0)).map((e=>t.values[e].label))}return e.map((t=>t.name?t.name:t.label))}(t.term2,d?d.map((t=>t.name?t.name:t.label)):[]);return g.refs.orderedKeys={chart:[...f.chart].sort(),series:[...f.series].sort(b?(t,e)=>b.indexOf(t)-b.indexOf(e):void 0)},g}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function w(t,e){const n=t.name;if("geneVariant"==t.type){if(!e[n]||!e[n].values)return"Wildtype";const t=e[n].values.filter((t=>"Blank"!=t.class));return t.find((t=>"WT"!=t.class))?`${n} Variant`:t.find((t=>"WT"==t.class))?`${n} Wildtype`:e[n].values.length>t.length?"Not tested":"Not sure"}throw`cannot get series key for term='${n}'`}var _=n(8599),x=n(3795),k=n(1575),q=n(2188);var N=n(478),S=n(1271);async function A(t,e,n,r){!function(t,e){if(!t.chr)throw"q.chr missing";if(t.start=Number(t.start),t.stop=Number(t.stop),!Number.isInteger(t.start)||!Number.isInteger(t.stop))throw"q.start/stop is not integer";if("object"!=typeof t.details)throw"q.details{} not object";if(!Array.isArray(t.details.groups))throw"q.details.groups[] not array";if(!t.details.groups[0])throw"q.details.groups[0] missing";if(t.details.groups.length>2)throw"q.details.groups[] has more than 2";for(const r of t.details.groups)if("filter"==r.type){if("object"!=typeof r.filter)throw".filter not an object for group type=filter"}else if("population"==r.type){var n;if(!r.key)throw".key missing from group type=population";if(null===(n=e.queries.snvindel)||void 0===n||!n.populations)throw"group type=population but this ds does not have populations";if(!e.queries.snvindel.populations.find((t=>t.key==r.key)))throw"invalid key of group type=population"}else{if("info"!=r.type)throw"unknown group type from details.groups[]";if(!r.infoKey)throw".infoKey missing from group type=info"}if(t.details.groupTestMethods){if(!Array.isArray(t.details.groupTestMethods))throw"details.groupTestMethods[] not array";if(!Number.isInteger(t.details.groupTestMethodsIdx))throw"details.groupTestMethodsIdx not integer";if(!t.details.groupTestMethods[t.details.groupTestMethodsIdx])throw"invalid array index of details.groupTestMethodsIdx"}}(t,n);const o=await async function(t,e){const n={rglst:[{chr:t.chr,start:t.start,stop:t.stop}],addFormatValues:!0,variantFilter:t.variantFilter},[r,o]=t.details.groups;if("filter"==r.type&&"filter"==(null==o?void 0:o.type)){n.filterObj=C(t,r.filter);const i=T(await e.queries.snvindel.byrange.get(n));n.filterObj=C(t,o.filter);const s=T(await e.queries.snvindel.byrange.get(n)),a=function(t,e,n){const[r,o]=n.details.groups,i=[];for(const n of t){n.groupData=[{refCount:n._refCount,altCount:n._altCount}];const t=e.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt));t?n.groupData.push({refCount:t._refCount,altCount:t._altCount}):n.groupData.push({refCount:0,altCount:0}),i.push(n)}for(const n of e){t.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt))||(n.groupData=[{refCount:0,altCount:0},{refCount:n._refCount,altCount:n._altCount}],i.push(n))}return i}(i.mlst,s.mlst,t);return{mlst:a,totalSampleCount_group1:M(i.mlst),totalSampleCount_group2:M(s.mlst)}}n.filterObj=C(t);const i=await e.queries.snvindel.byrange.get(n),s=T(i);"filter"==r.type?s.totalSampleCount_group1=M(i):"filter"==(null==o?void 0:o.type)&&(s.totalSampleCount_group2=M(i));return s}(t,n);if(1==t.details.groups.length)j(n,o.mlst,t.details.groups[0]);else{if(2!=t.details.groups.length)throw"q.details.groups.length not 1 or 2";await async function(t,e,n){const[r,o]=e.groups;if("filter"==r.type&&"filter"==o.type)return void await async function(t,e,n){const r=e.groupTestMethods[e.groupTestMethodsIdx];if(!r)throw"details.groupTestMethodsIdx out of bound";switch(r.name){case"Allele frequency difference":return void O(t,e,n);case"Fisher's exact test":return void await P(n);default:throw"unknown value from groupTestMethods[]"}}(t,e,n.mlst);if("population"==r.type&&"filter"==o.type||"population"==o.type&&"filter"==r.type)return void await async function(t,e,n){const r=await async function(t,e,n){const r=e.groups.find((t=>"population"==t.type));if(!r)return;if(!r.adjust_race)return;const o=t.queries.snvindel.populations.find((t=>t.key==r.key));if(!o)throw"invalid group.key for population";const i=new Set;for(const t of n.mlst)for(const e of t.samples)i.add(e.sample_id);const s=new Map;let a=0;for(const e of o.sets){const n={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await(0,c.J4)({ds:t,key:e.key});for(const t of r){if(!i.has(t.sample))continue;const e=Number(t.value);Number.isFinite(e)&&(n.average+=e,a+=e)}s.set(e.key,n)}for(const[t,e]of s)e.average/=a;n.pop2average={};for(const[t,e]of s)n.pop2average[t]=e.average;return s}(t,e,n);for(const o of n.mlst)o.groupData=I(t,e,o,r);const o=e.groupTestMethods[e.groupTestMethodsIdx];if(!o)throw"details.groupTestMethodsIdx out of bound";switch(o.name){case"Allele frequency difference":return void O(t,e,n.mlst);case"Fisher's exact test":return void await P(n.mlst);default:throw"unknown value from groupTestMethods[]"}}(t,e,n);O(t,e,n.mlst)}(n,t.details,o)}for(const t of o.mlst)delete t.samples,delete t._altCount,delete t._refCount;e.send(o)}function M(t){const e=new Set;for(const n of t)if(n.samples)for(const t of n.samples)e.add(t.sample_id);return e.size}function T(t){const e={mlst:[],skipMcountWithoutAlt:0};for(const n of t){const[t,r]=E(n);0!=t?(n._altCount=t,n._refCount=r-t,e.mlst.push(n)):e.skipMcountWithoutAlt++}return e}function C(t,e){const n=[t.filter];if(e)n.push(e);else for(const e of t.details.groups)"filter"==e.type&&n.push(e.filter);return(0,N.xH)(n)}function j(t,e,n){if("filter"!=n.type)if("info"!=n.type){if("population"!=n.type)throw"unknown type of single group";{const r=t.queries.snvindel.populations.find((t=>t.key==n.key));if(!r)throw"unknown population";for(const t of e){let e=0,n=0;for(const o of r.sets)e+=Number(t.info[o.infokey_AC]||0),n+=Number(t.info[o.infokey_AN]||0);t.nm_axis_value=e/n}}}else{if(!n.infoKey)throw"infoKey missing on single group.type=info";for(const t of e){const e=t.info[n.infoKey];if(null==e);else{const n=Number(e);Number.isNaN(n)||(t.nm_axis_value=n)}}}else for(const t of e)t.nm_axis_value=Number((t._altCount/(t._altCount+t._refCount)).toPrecision(2))}function E(t){let e=0,n=0;for(const o of t.samples){var r;if(null==o||null===(r=o.formatK2v)||void 0===r||!r.GT)continue;const i=o.formatK2v.GT.split("/").map(Number);n+=i.length;for(const n of i)n==t.altAlleleIdx&&e++}return[e,n]}function O(t,e,n){const[r,o]=e.groups;j(t,n,r);const i=n.map((t=>t.nm_axis_value));j(t,n,o);for(const[t,e]of n.entries())e.nm_axis_value=i[t]-e.nm_axis_value}function I(t,e,n,r){const o=[];for(const i of e.groups)if("info"!=i.type)if("filter"!=i.type){if("population"!=i.type)throw"unknown group.type";{if(!i.key)throw"group.key missing for type=population";const e=t.queries.snvindel.populations.find((t=>t.key==i.key));if(!e)throw"invalid group.key for population";const s=new Map;for(const t of e.sets)s.set(t.key,{ACraw:Number(n.info[t.infokey_AC]||0),ANraw:Number(n.info[t.infokey_AN]||0)});let a=0,l=0;if(i.adjust_race)[a,l]=R(s,r);else for(const t of s.values())l+=t.ACraw,a+=t.ANraw-t.ACraw;o.push({altCount:l,refCount:a})}}else o.push({altCount:n._altCount,refCount:n._refCount});else{if(!i.key)throw"group.key missing for type=info";o.push({value:n.info[i.key]})}return o}function R(t,e){let n=0;for(const e of t.values())n+=e.ANraw;let r=0,o=0;for(const[i,s]of t)s.ANadj=n*e.get(i).average,s.ACadj=0==s.ANadj?0:s.ACraw*s.ANadj/s.ANraw,r+=s.ACadj,o+=s.ANadj;return[o-r,r]}async function P(t){for(let e=0;e<Math.ceil(t.length/200);e++){const n=[];for(let r=200*e;r<200*(e+1);r++){const e=t[r];if(!e)break;const o=e.groupData;o&&o[0]&&o[1]&&Number.isFinite(o[0].altCount)&&Number.isFinite(o[0].refCount)&&Number.isFinite(o[1].altCount)&&Number.isFinite(o[1].refCount)?(n.push({index:r,n1:Math.floor(o[0].altCount),n2:Math.floor(o[0].refCount),n3:Math.floor(o[1].altCount),n4:Math.floor(o[1].refCount)}),e.htmlSections=[{key:"Contigency table",html:`<table style="font-size:.9em">\n\t\t\t\t<tr style="opacity:.5">\n\t\t\t\t <td></td>\n\t\t\t\t <td>Group1</td>\n\t\t\t\t <td>Group 2</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">ALT allele count</td>\n\t\t\t\t <td>${o[0].altCount}</td>\n\t\t\t\t <td>${Math.floor(o[1].altCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">REF allele count</td>\n\t\t\t\t <td>${o[0].refCount}</td>\n\t\t\t\t <td>${Math.floor(o[1].refCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">Allele frequency</td>\n\t\t\t\t <td>${(o[0].altCount/(o[0].altCount+o[0].refCount)).toFixed(3)}</td>\n\t\t\t\t <td>${(o[1].altCount/(o[1].altCount+o[1].refCount)).toFixed(3)}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>`}]):console.log(`${e.chr}.${e.pos}.${e.ref}.${e.alt}\t${JSON.stringify(o)}`)}const r=await(0,S.run_rust)("fisher",JSON.stringify({input:n}));for(const e of JSON.parse(r)){const n=t[e.index];n&&(n.p_value=e.p_value.toPrecision(2),e.p_value>0&&(n.nm_axis_value=Number((-Math.log10(e.p_value)).toPrecision(2))))}}let e=0;for(const n of t)n.p_value>0&&(e=Math.max(e,n.nm_axis_value));for(const n of t)0==n.p_value&&(n.nm_axis_value=Math.max(50,e))}var F=n(5684),D=n(7027),L=n(4065),$=n(141);const Z=10;function z(t){return async(e,n)=>{const r=e.query;(0,m.Y5)(r,e.cookies);try{const o=t[r.genome];if(!o)throw"invalid genome";const[i,l]=function(t,e){{const r=t.datasets[e.dslabel];if(r){var n;if(null!=r&&null!==(n=r.cohort)&&void 0!==n&&n.termdb)return[r,r.cohort.termdb];throw".cohort.termdb not found on this dataset"}}if(!t.termdbs)throw"genome-level termdb not available";const r=t.termdbs[e.dslabel];if(!r)throw"invalid dslabel";if(!r.cohort)throw"ds.cohort missing for genome-level termdb";if(!r.cohort.termdb)throw"ds.cohort.termdb{} missing for a genome-level termdb";return[r,r.cohort.termdb]}(o,r);if(r.getdescrstats)return async function(t,e,n){const r=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!r)throw"invalid termid";if("float"!=r.type&&"integer"!=r.type)throw"not numerical term";const o=await c.J4({ds:n,key:t.tid,filter:t.filter?"string"==typeof t.filter?JSON.parse(t.filter):t.filter:null}),i=[];for(const{value:e}of o){var s,a;r.values&&r.values[e]&&r.values[e].uncomputable||("log"===(null===(s=t.settings)||void 0===s||null===(a=s.violin)||void 0===a?void 0:a.unit)&&0===e||i.push(Number(e)))}const l=i.length,u=i.reduce(((t,e)=>t+e),0)/l,f=(0,D.Z)(i,25),d=(0,D.Z)(i,50),h=(0,D.Z)(i,75),p=i.map((t=>(t-u)**2)).reduce(((t,e)=>t+e),0)/(i.length-1),m=Math.sqrt(p),g=Math.min(...i),y=Math.max(...i);e.send({values:[{id:"total",label:"n",value:l},{id:"min",label:"Minimum",value:(0,F.Z)(g,2)},{id:"p25",label:"1st quartile",value:(0,F.Z)(f,2)},{id:"median",label:"Median",value:(0,F.Z)(d,2)},{id:"mean",label:"Mean",value:(0,F.Z)(u,2)},{id:"p75",label:"3rd quartile",value:(0,F.Z)(h,2)},{id:"max",label:"Maximum",value:(0,F.Z)(y,2)},{id:"sd",label:"Standard deviation",value:(0,F.Z)(m,2)}]})}(r,n,i);if(r.getnumericcategories)return await async function(t,e,n,r){if(!t.tid)throw".tid missing";n.q.termjsonByOneid(t.tid);const o={ds:r,term_id:t.tid};t.filter&&(o.filter=t.filter);const i=await c.tt(o);e.send({lst:i})}(r,n,l,i);if(r.default_rootterm)return await async function(t,e,n){const r=t.cohortValues?t.cohortValues:"",o=t.treeFilter?t.treeFilter:"";e.send({lst:await n.q.getRootTerms(r,o)})}(r,n,l);if(r.get_children)return await async function(t,e,n){if(!t.tid)throw"no parent term id";const r=t.cohortValues?t.cohortValues:"",o=t.treeFilter?t.treeFilter:"",i=await n.q.getTermChildren(t.tid,r,o);e.send({lst:i.map(U)})}(r,n,l);if(r.findterm)return await async function(t,e,n,r,o){const i={equals:[],startsWith:[],startsWord:[],includes:[]},s=decodeURIComponent(t.findterm).toUpperCase(),a=[];try{if("snp"==t.targetType){var l,c;if(null===(l=r.queries)||void 0===l||null===(c=l.snvindel)||void 0===c||!c.allowSNPs)throw"this dataset does not support snp search";const t=await(0,$.SC)({byName:!0,lst:[s.toLowerCase()]},o);for(const e of t)a.push({type:"geneVariant",name:e.name,subtype:"snp",chr:e.chrom,start:e.chromStart,stop:e.chromEnd,alleles:e.alleles})}else{var u;const e=(0,k.CG)({type:"geneVariant"},t.usecase).has("plot");if(r.mayGetMatchingGeneNames&&e&&await r.mayGetMatchingGeneNames(i,s,t),null!==(u=r.queries)&&void 0!==u&&u.defaultBlock2GeneMode&&e)try{const t=(0,L.S)(o,{input:s});if(Array.isArray(t.hits))for(let e=0;e<7&&t.hits[e];e++)a.push({name:t.hits[e],type:"geneVariant"})}catch(t){}}const f=await n.q.findTermByName(s,Z,t.cohortStr,t.treeFilter,t.usecase,i);a.push(...f.map(U));a.forEach((t=>{"geneVariant"!=t.type&&(t.__ancestors=n.q.getAncestorIDs(t.id),t.__ancestorNames=n.q.getAncestorNames(t.id))})),e.send({lst:a})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}}(r,n,l,i,o);if(r.getterminfo)return function(t,e,n){if(!t.tid)throw"no term id";e.send({terminfo:n.q.getTermInfo(t.tid)})}(r,n,l);if(r.phewas)return r.update?await u.update_image(r,n):r.getgroup?await u.getgroup(r,n):await u.trigger(r,n,i);if(r.gettermdbconfig)return a(r,n,i,o);if(r.getcohortsamplecount)return n.send({count:i.cohort.termdb.q.getcohortsamplecount(r.cohort)});if(r.getsamplecount)return n.send(await async function(t,e,n){const r=s.i.canDisplaySampleIds(t,n);if("list"==e.getsamplecount){return await c.cf(e.filter,n,r)}return await c.B9(e,n)}(e,r,i));if(r.getsamples)return await async function(t,e,n){const r=await c.cf(t.filter,n),o=r.map((t=>n.cohort.termdb.q.id2sampleName(t)));e.send({samples:o})}(r,n,i);if(r.getcuminc)return await async function(t,e,n){const r=await(0,f.g)(t,n);e.send(r)}(r,n,i);if(r.getsurvival)return await async function(t,e,n){const r=await b(t,n);e.send(r)}(r,n,i);if(r.getregression)return await async function(t,e,n){const r=await(0,_.j)(t,n);e.send(r)}(r,n,i);if(r.validateSnps)return n.send(await(0,x.G)(r,l,i,o));if(r.getvariantfilter)return function(t,e){var n,r;if(e.track)return void t.send(e.track.variant_filter);t.send((null==e||null===(n=e.queries)||void 0===n||null===(r=n.snvindel)||void 0===r?void 0:r.variant_filter)||{})}(n,i);if(r.getLDdata)return await async function(t,e,n){var r,o;if(!t.ldtkname)throw".ldtkname missing";if(null===(r=e.queries)||void 0===r||null===(o=r.ld)||void 0===o||!o.tracks)throw"no ld tk";const i=e.queries.ld.tracks.find((e=>e.name==t.ldtkname));if(!i)throw"unknown ld tk";if("object"!=typeof t.m)throw"q.m{} not object";if(!t.m.chr)throw"q.m.chr missing";if(!Number.isInteger(t.m.pos))throw"q.m.pos not integer";if(!t.m.ref||!t.m.alt)throw"q.m{} invalid alleles";const s=t.m.ref+"."+t.m.alt,a=(i.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),l=[];await(0,m.UE)({args:[i.file,a],dir:i.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]),i=n[3],a=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&i==s?l.push({pos:o,alleles:a,r2:c}):o==t.m.pos&&a==s&&l.push({pos:r,alleles:i,r2:c})}}),n.send({lst:l})}(r,i,n);if(r.genesetByTermId)return function(t,e,n){if(!n.termMatch2geneSet)throw"this feature is not enabled";if("string"!=typeof t.genesetByTermId||0==t.genesetByTermId.length)throw"invalid query term id";const r=n.q.getGenesetByTermId(t.genesetByTermId);e.send(r)}(r,n,l);if(r.getSampleScatter&&(r.for="scatter"),"scatter"==r.for)return await(0,q.uR)(e,r,n,i,o);if(r.getLowessCurve)return await(0,q.v8)(e,r,n);if(r.getCohortsData)return await async function(t,e,n){const r=function(t){const e=t.cohort.db.connection.prepare("select * from features").all();return{cohorts:t.cohort.db.connection.prepare("select * from cohorts where cohort in (select distinct(cohort) from cohort_features)\n\t\t order by sample_count desc").all(),features:e,cfeatures:t.cohort.db.connection.prepare("select * from cohort_features").all()}}(n);e.send(r)}(0,n,i);if("mds3queryDetails"==r.for)return function(t,e){const n={},r=e.queries||{};r.snvindel&&(n.snvindel={},r.snvindel.details&&(n.snvindel.details=r.snvindel.details),r.snvindel.populations&&(n.snvindel.populations=r.snvindel.populations));r.trackLst&&(n.trackLst=r.trackLst);if(r.ld){n.ld=JSON.parse(JSON.stringify(r.ld));for(const t of n.ld.tracks)delete t.file}t.send(n)}(n,i);if("termTypes"==r.for)return n.send(await i.getTermTypes(r));if("matrix"==r.for)return await async function(t,e,n,r,o){if(t.getPlotDataByName){if(!r.cohort.matrixplots)throw"ds.cohort.matrixplots missing for the dataset";if(!r.cohort.matrixplots.plots)throw"ds.cohort.matrixplots.plots missing for the dataset";const e=r.cohort.matrixplots.plots.find((e=>e.name===t.getPlotDataByName));if(!e)throw`plot name: q.getPlotDataByName=${getPlotDataByName} missing in ds.cohort.matrixplots.plots`;return void n.send(e.matrixConfig)}const i=await(0,p.Yu)(t,r,o);if(s.i.canDisplaySampleIds(e,r))for(const t of Object.values(i.samples))t.sampleName=r.sampleId2Name.get(t.sample);n.send(i)}(r,e,n,i,o);if("mds3variantData"==r.for)return await A(r,n,i);if(r.for,"convertSampleId"==r.for)return function(t,e,n){if(!n.convertSampleId)throw"not supported on this ds";if(!Array.isArray(t.inputs))throw"q.inputs[] not array";e.send({mapping:n.convertSampleId.get(t.inputs)})}(r,n,l);if("singleSampleData"==r.for)return async function(t,e,n,r,o){const i=s.i.canDisplaySampleIds(e,r);let a=[];if(i)try{a=o.q.getSingleSampleData(t.sampleId,t.term_ids),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(r,e,n,i,l);if("getProfileFacilities"==r.for)return async function(t,e,n,r,o){console.log("get profile facilities");const i=s.i.canDisplaySampleIds(e,r);let a=[];if(i)try{a=o.q.getProfileFacilities(),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(0,e,n,i,l);if("getAllSamples"==r.for)return async function(t,e,n,r){const o=s.i.canDisplaySampleIds(e,r);let i=[];o&&(i=Object.fromEntries(r.sampleId2Name));n.send(i)}(0,e,n,i);if("getAllSamplesByName"==r.for)return async function(t,e,n,r){var o,i,a;if(!s.i.canDisplaySampleIds(e,r))return n.send({});if(null!==(o=r.queries)&&void 0!==o&&null!==(i=o.singleCell)&&void 0!==i&&null!==(a=i.samples)&&void 0!==a&&a.get){const t=await r.queries.singleCell.samples.get(),e={};for(const n of t)e[n.name]=r.cohort.termdb.q.sampleName2id(n.name);return void n.send(e)}n.send(Object.fromEntries(r.sampleName2Id))}(0,e,n,i);if("DEanalysis"==r.for)return await async function(t,e,n){var r;if(null===(r=n.queries)||void 0===r||!r.rnaseqGeneCount)throw"not enabled by this dataset";const o=await n.queries.rnaseqGeneCount.get(t);e.send(o)}(r,n,i);throw"termdb: doesn't know what to do"}catch(t){n.send({error:t.message||t}),t.stack?console.log(t.stack):console.log(t)}}}function U(t){return JSON.parse(JSON.stringify(t))}},2974:(t,e,n)=>{"use strict";n.d(e,{Yu:()=>f,gh:()=>d,te:()=>h});var r=n(1017),o=n.n(r),i=n(8907),s=n(5257),a=(n(9157),n(7147),n(7219),n(334)),l=n.n(a),c=n(3345),u=n(8599);async function f(t,e,n){try{return function(t,e,n){if(!e.cohort)throw"cohort missing from ds";if(!t.terms)throw"missing 'terms' parameter";t.ds=e,t.genome=n;for(const e of t.terms)e.term.name||(e.term=t.ds.cohort.termdb.q.termjsonByOneid(e.term.id)),e.q||console.log("do something??");if(t.currentGeneNames&&!Array.isArray(t.currentGeneNames))throw"currentGeneNames[] is not array";t.filter0&&"string"==typeof t.filter0&&(t.filter0=JSON.parse(t.filter0))}(t,e,n),await async function(t){const[e,n]=function(t){const e=[],n=[];for(const r of t){const t=r.term.type;"snplst"==t||"snplocus"==t||"geneVariant"==t?n.push(r):e.push(r)}return[e,n]}(t.terms),{samples:r,refs:o}=await async function(t,e){var n,r,o,i;if(!e.length)return{samples:{},refs:{byTermId:{}}};if(null!==(n=t.ds)&&void 0!==n&&null!==(r=n.cohort)&&void 0!==r&&r.db)return await d(t,e);if(null!==(o=t.ds)&&void 0!==o&&null!==(i=o.variant2samples)&&void 0!==i&&i.get)return await async function(t,e){const n={filter0:t.filter0,filterObj:t.filter,genome:t.genome,get:"samples",twLst:e,useIntegerSampleId:!0,isHierCluster:t.isHierCluster};if(t.currentGeneNames){n.geneTwLst=[];for(const e of t.currentGeneNames)n.geneTwLst.push({term:{name:e,type:"geneVariant"}})}const r=await t.ds.variant2samples.get(n),o={},i={byTermId:r.byTermId};for(const t of r.samples){const n={sample:t.sample_id};t.__sampleName&&(n.sampleName=t.__sampleName);for(const r of e){const e=t[r.term.id];Array.isArray(e)&&null!=e[0]&&null!=e[0]?n[r.term.id]={key:e[0],value:e[0]}:null!=e&&null!=e&&(n[r.term.id]={key:e,value:e})}o[t.sample_id]=n}return{samples:o,refs:i}}(t,e);throw"unknown method for dictionary terms"}(t,e);t.ds.getSampleIdMap&&(o.bySampleId=t.ds.getSampleIdMap(r));if(e.length&&!Object.keys(r).length)return{samples:r,refs:o};const s=await async function(t,e){if(!e.find((t=>"snplst"==t.term.type||"snplocus"==t.term.type)))return;if(!t.filter)return;return new Set((await(0,i.cf)(t.filter,t.ds)).map((t=>t.id)))}(t,n);for(const i of n)if("geneVariant"==i.term.type){var a,l,c,f;null!==(a=t.ds.cohort)&&void 0!==a&&null!==(l=a.termdb)&&void 0!==l&&l.getGeneAlias&&(o.byTermId[i.term.name]=null===(c=t.ds.cohort)||void 0===c||null===(f=c.termdb)||void 0===f?void 0:f.getGeneAlias(t,i));const n=await t.ds.mayGetGeneVariantData(i,t);for(const[o,s]of n.entries()){var h,p;if(i.term.name in s)if(e.length||o in r||(r[o]={sample:o}),r[o])if(r[o][i.term.name]=s[i.term.name],null!==(h=t.ds.cohort)&&void 0!==h&&null!==(p=h.termdb)&&void 0!==p&&p.additionalSampleAttributes)for(const e of null===(m=t.ds.cohort)||void 0===m||null===(g=m.termdb)||void 0===g?void 0:g.additionalSampleAttributes){var m,g;e in s&&(r[o][e]=s[e])}}}else{if("snplst"!=i.term.type&&"snplocus"!=i.term.type)throw"unknown type of non-dictionary term";{i.type=i.term.type;const t=new Map;await(0,u._)(i,t,!0);for(const[e,n]of t){if(s&&!s.has(e))continue;e in r||(r[e]={sample:e});const t={};for(const[e,r]of n.id2value)t[e]=r.value;r[e][i.term.id]=t}}}return{samples:r,refs:o}}(t)}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function d(t,e){const n={},r={byTermId:{}},o={},a=await(0,s.w)(t.filter,t.ds),l=a?a.values.slice():[],c=await Promise.all(e.map((async(e,n)=>{const s=await(0,i.Bi)(t,l,n,a,e);if(s.bins&&(r.byTermId[e.term.id]={bins:s.bins}),s.events&&(r.byTermId[e.term.id]={events:s.events}),e.term.values){const t=Object.values(e.term.values);t.find((t=>"order"in t))&&(r.byTermId[e.term.id]={keyOrder:t.sort(((t,e)=>t.order-e.order)).map((t=>t.key))})}return"id"in e.term&&(o[e.term.id]=e),s}))).catch(console.error);l.push(...e.map((t=>t.term.id||t.term.name)));const u=`WITH\n\t\t${a?a.filters+",":""}\n\t\t${c.map((t=>t.sql)).join(",\n")}\n\t\t${c.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${a?`WHERE sample IN ${a.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,f=t.ds.cohort.db.connection.prepare(u).all(l),d=await async function(t){if(!t.currentGeneNames)return;const e=new Set;for(const n of t.currentGeneNames){const r={term:{name:n,type:"geneVariant"}},o=await t.ds.mayGetGeneVariantData(r,t);for(const[t,n]of o.entries())e.add(t)}return e}(t);for(const{sample:t,term_id:e,key:r,value:i}of f){if(d&&!d.has(t))continue;n[t]||(n[t]={sample:t});o[e];n[t][e]={key:r,value:i}}return{samples:n,refs:r}}async function h(t){if(t.cohort.matrixplots){if(!Array.isArray(t.cohort.matrixplots.plots))throw"cohort.matrixplots.plots is not array";for(const e of t.cohort.matrixplots.plots){if(!e.name)throw".name missing from one of matrixplots.plots[]";if(!e.file)throw"unknown data source of one of matrixplots.plots[]";{const t=await c.b5(o().join(l().tpmasterdir,e.file));e.matrixConfig=JSON.parse(t),e.getConfig&&(e.matrixConfig=e.getConfig(e.matrixConfig))}}}}},5708:(t,e,n)=>{"use strict";n.r(e),n.d(e,{do_precompute:()=>y,getgroup:()=>N,trigger:()=>g,update_image:()=>x});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(8907),c=n(6718),u=n(2826),f=n(4521),d=n.n(f),h=n(334),p=n.n(h),m=n(9157);async function g(t,e,n){if(!n.cohort)throw"ds.cohort missing";if(!n.cohort.termdb)throw"cohort.termdb missing";if(!n.cohort.termdb.phewas)throw"not allowed on this dataset";if(!t.ssid)throw"ssid missing";const r={};let o;t.filter&&(o=new Set(await l.cf(t.filter,n)));const[i,c]=await a.L0(t.ssid,o);r.numberofsamples=i.size;const f=c.has(a.EO.het)?c.get(a.EO.het).size:0,d=c.has(a.EO.href)?c.get(a.EO.href).size:0,h=c.has(a.EO.halt)?c.get(a.EO.halt).size:0,g=function(t,e,n,r,o,i){const s=[];let a;if(e.cohort.termdb.selectCohort&&t){const e=t.lst.find((t=>"cohortFilter"==t.tag));e&&(a=e.tvs.values.map((t=>t.key)).sort().join(","))}for(const t of e.cohort.termdb.q.getcategory2vcfsample()){if(a&&t.subcohort!=a)continue;const l=u.iK(e.cohort.termdb.q.termjsonByOneid(t.term_id));for(const e of t.categories){const[a,c,u]=q(n,e.group1lst);let f,d,h;e.group2lst?[f,d,h]=q(n,e.group2lst):(f=r-a,d=i-c,h=o-u),a+f+c+d+u+h!=0&&s.push({term:l,group_name:t.group_name,parent_name:t.parent_name,group1label:e.group1label,group2label:e.group2label,table:[u,h,a,f,c,d]})}}return s}(t.filter,n,i,f,d,h);r.testcount=g.length;{const t=[];for(let e=0;e<g.length;e++)t.push(e+"\t"+g[e].table.join("\t"));const e=await(0,m.default)(s().join(p().binpath,"utils/fisher.2x3.R"),t);let n=0;for(const t of e)g[n++].pvalue=Number(t.split("\t")[7])}r.maxlogp=function(t){let e=0;for(const n of t)0==n.pvalue?n.logp=100:n.logp=-Math.log10(n.pvalue),e=Math.max(e,n.logp);return e}(g);const y=function(t){const e=new Map;for(const n of t)e.has(n.group_name)||e.set(n.group_name,[]),e.get(n.group_name).push(n);const n=[];for(const[t,r]of e)n.push({group_name:t,categories:r});return n}(g);r.tmpfile=await function(t){const e=[];for(const n of t)for(const t of n.categories)e.push(n.group_name+"\t"+t.logp+"\t"+t.pvalue+"\t"+JSON.stringify(t));return a.tG(e.join("\n"))}(y),k(y,r,t);{const t=.05;r.hoverdots=g.filter((e=>e.pvalue<=t))}e.send(r)}async function y(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.termdb)throw"cohort.termdb missing";if(!t.cohort.termdb.phewas)throw"not allowed on this dataset";t.cohort.termdb.selectCohort?await async function(t){const e=await async function(t){if(!t.cohort.termdb.phewas.precompute_subcohort2totalsamples)return;for(const e in t.cohort.termdb.phewas.precompute_subcohort2totalsamples){const n=t.cohort.termdb.phewas.precompute_subcohort2totalsamples[e];if(n.termtype)for(const e in n.termtype)n.termtype[e].samples=await l.cf(n.termtype[e].filter,t)}return t.cohort.termdb.phewas.precompute_subcohort2totalsamples}(t),n=function(t){const e=new Map,n=t.cohort.db.connection.prepare("SELECT * FROM subcohort_terms");for(const{term_id:t,cohort:r}of n.all())e.has(t)||e.set(t,new Set),e.get(t).add(r);return e}(t),r=o().createWriteStream("category2vcfsample"),i=[];for(const{group_name:o,term:s}of t.cohort.termdb.q.getAlltermsbyorder()){if(!s.type)continue;if(!n.has(s.id)){i.push(s.id);continue}let a="";{const e=t.cohort.termdb.q.getTermParent(s.id);e&&(a=e.name)}const c=b(s,t,n);for(const n of c){const i=await l.g5(n);let c;if("categorical"==s.type||"integer"==s.type||"float"==s.type)c=w(i.lst,s,t);else{if("condition"!=s.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(i.lst,t):w(i.lst,s,t)}c=v({categories:c,q:n,subcohortTermtype2samples:e,term:s});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+s.name+"\t"+n.cohortname);r.write(n.cohortname+"\t"+o+"\t"+s.id+"\t"+a+"\t"+(n.term1_q?JSON.stringify(n.term1_q):"{}")+"\t"+JSON.stringify(c)+"\n")}}r.end((()=>{console.log('Phewas precompute result written to file "category2vcfsample".'),i.length&&(console.log(i.length+" empty terms:"),console.log(i.join("\n")))}))}(t):await async function(t){const[e]=await async function(t){let e=null;if(t.cohort.termdb.phewas.samplefilter4termtype&&t.cohort.termdb.phewas.samplefilter4termtype.condition){const n=await l.cf(t.cohort.termdb.phewas.samplefilter4termtype.condition.filter,t);if(t.track&&t.track.vcf&&t.track.vcf.sample2arrayidx){e=[];for(const r of n)t.track.vcf.sample2arrayidx.has(r)&&e.push(r)}else e=n}return[e]}(t),n=[];for(const{group_name:r,term:o}of t.cohort.termdb.q.getAlltermsbyorder()){if(!o.type)continue;let i="";{const e=t.cohort.termdb.q.getTermParent(o.id);e&&(i=e.name)}const s=b(o,t);for(const a of s){const s=await l.g5(a);let c;if("categorical"==o.type||"integer"==o.type||"float"==o.type)c=w(s.lst,o,t);else{if("condition"!=o.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(s.lst,t):w(s.lst,o,t)}c=v({categories:c,q:a,term:o,condition_samplelst:e});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+o.name);n.push(r+"\t"+o.id+"\t"+i+"\t"+(a.term1_q?JSON.stringify(a.term1_q):"{}")+"\t"+JSON.stringify(c))}}o().writeFileSync("category2vcfsample",n.join("\n")),console.log('Phewas precompute result written to file "category2vcfsample".')}(t)}function v(t){const{categories:e,q:n,term:r,subcohortTermtype2samples:o,condition_samplelst:i}=t;if(o&&o[n.cohortname]&&o[n.cohortname].termtype&&o[n.cohortname].termtype[r.type]){const t=o[n.cohortname].termtype[r.type].samples;for(const n of e)if(n.group2lst)n.group2lst=n.group2lst.filter((e=>-1!=t.indexOf(e)));else if(n.copycontrolfrom1stgroup){n.group2lst=[];for(const t of e[0].group2lst)n.group2lst.push(t)}else{const e=new Set(n.group1lst);n.group2lst=t.filter((t=>!e.has(t)))}return e}if(i&&"condition"==r.type){for(const t of e)if(t.group2lst)t.group2lst=t.group2lst.filter((t=>-1!=i.indexOf(t)));else if(t.copycontrolfrom1stgroup){t.group2lst=[];for(const n of e[0].group2lst)t.group2lst.push(n)}else{const e=new Set(t.group1lst);t.group2lst=i.filter((t=>!e.has(t)))}return e}if(!r.values)return e;const s=new Set;for(const t in r.values)r.values[t].uncomputable&&s.add(r.values[t].label);if(0==s.size)return e;const a=[];for(const t of e)s.has(t.group1label)?console.log("skip "+t.group1label+", "+r.id):a.push(t);for(let t=0;t<a.length;t++){const e=a[t];e.group2lst=[];for(let n=0;n<a.length;n++)n!=t&&e.group2lst.push(...a[n].group1lst)}return a}function b(t,e,n){const r=[];if(e.cohort.termdb.selectCohort){if(!n)throw"term2cohort is required when cohort selection is enabled";for(const o of e.cohort.termdb.selectCohort.values){const i=o.keys.sort().join(",");if(!n.get(t.id).has(i))continue;const s={type:"tvslst",in:!0,join:"",lst:[{type:"tvs",tvs:{term:e.cohort.termdb.selectCohort.term,values:o.keys.map((t=>({key:t})))}}]};if("categorical"==t.type)r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}}}else if("categorical"==t.type)r.push({ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}return r}function w(t,e,n){const r=new Map;for(const o of t){if(n.track&&n.track.vcf&&n.track.vcf.sample2arrayidx&&!n.track.vcf.sample2arrayidx.has(o.sample))continue;const t=o.key1;if(!r.has(t)){let n=t;e.values&&(n=e.values[t]?e.values[t].label:t),r.set(t,{group1label:n,group2label:"All others",group1lst:[]})}r.get(t).group1lst.push(o.sample)}return[...r.values()]}function _(t,e){const n=[];for(const r of e.cohort.termdb.phewas.comparison_groups){const o=[],i=[];for(const n of t){if(e.track&&e.track.vcf&&e.track.vcf.sample2arrayidx&&!e.track.vcf.sample2arrayidx.has(n.sample))continue;const t=Number(n.key1);r.group1grades.has(t)?o.push(n.sample):r.group2grades&&r.group2grades.has(t)&&i.push(n.sample)}0!=o.length?n.push({group1label:r.group1label,group2label:r.group2label,group1lst:o,group2lst:i.length?i:void 0,copycontrolfrom1stgroup:r.copycontrolfrom1stgroup}):console.log("Empty group1: "+r.group1label)}return n}async function x(t,e){const n=await a.b5(s().join(p().cachedir,t.file)),r=[];for(const t of n.trim().split("\n")){const[e,n]=t.split("\t",2),o=Number(n);0!=r.length&&r[r.length-1].group_name==e||r.push({group_name:e,categories:[]}),r[r.length-1].categories.push({logp:o})}const o={maxlogp:Number(t.max)};k(r,o,t),e.send(o)}function k(t,e,n){const r=Number(n.intendwidth),o=Number(n.axisheight),i=Number(n.groupnamefontsize),s=Number(n.dotradius),a=Number(n.groupxspace),l=Number(n.leftpad),u=Number(n.rightpad),f=Number(n.toppad),d=Number(n.bottompad),h=Number(n.devicePixelRatio),p=r/t.reduce(((t,e)=>t+e.categories.length),0),m=(0,c.createCanvas)(10,10),g=m.getContext("2d");let y=0;for(const e of t){const t=e.categories.length*p;e.width=Math.max(t,i)+2*a,e.dotshiftx=t>i?p:i/e.categories.length,y+=e.width}const v=l+y+u;m.width=v*h;const b=f+o+d;m.height=b*h,h>1&&g.scale(h,h),y=0,g.fillStyle="#FDFEE2";for(const[e,n]of t.entries())e%2==0&&g.fillRect(y,f,n.width,o),y+=n.width;y=0,g.fillStyle="black",e.grouplabels=[];for(const n of t){e.grouplabels.push({name:n.group_name,x:y+n.width/2,y:f+o+2*s});let t=0;for(const r of n.categories){const i=0==e.maxlogp?0:r.logp>=e.maxlogp?o:o*r.logp/e.maxlogp;g.beginPath(),g.arc(y+a+t,f+o-i,s,0,2*Math.PI),g.fill(),r.x=y+a+t,t+=n.dotshiftx}y+=n.width}e.canvaswidth=v,e.canvasheight=b,e.toppad=f,e.bottompad=d,e.axisheight=o,e.dotradius=s,e.groupnamefontsize=i,e.src=m.toDataURL()}function q(t,e){const n=new Map;for(const r of e){const e=t.get(r);e&&n.set(e,1+(n.get(e)||0))}return[n.get(a.EO.het)||0,n.get(a.EO.halt)||0,n.get(a.EO.href)||0]}async function N(t,e){if(!t.file)throw"file missing";return new Promise(((n,r)=>{const i=[],a=d().createInterface({input:o().createReadStream(s().join(p().cachedir,t.file))});a.on("line",(e=>{if(!e.startsWith(t.getgroup+"\t"))return;const n=e.split("\t"),r=JSON.parse(n[3]);r.pvalue=Number(n[2]),i.push(r)})),a.on("close",(()=>{e.send({categories:i}),n()}))}))}},8599:(t,e,n)=>{"use strict";n.d(e,{_:()=>j,j:()=>x});var r=n(1017),o=n.n(r),i=n(8907),s=n(5257),a=n(9157),l=n(7147),c=n.n(l),u=n(7219),f=n.n(u),d=n(334),h=n.n(d),p=n(3345),m=n(1271),g=n(4453);const y=["linear","logistic","cox"],v=1;let b,w;const _={NodeJS:{},"regression.R":{}};async function x(t,e){try{!function(t,e){if(!e.cohort)throw"cohort missing from ds";if(t.ds=e,!t.regressionType)throw"regressionType missing";if(!y.includes(t.regressionType))throw"unknown regressionType";if(!t.outcome)throw"missing 'outcome' parameter";if(!("id"in t.outcome))throw"outcome.id missing";if(!t.outcome.q)throw"outcome.q missing";if(t.outcome.q.computableValuesOnly=!0,t.outcome.term=e.cohort.termdb.q.termjsonByOneid(t.outcome.id),!t.outcome.term)throw"invalid outcome term: "+t.outcome.id;if(!t.independent)throw"independent[] missing";if(!Array.isArray(t.independent)||0==t.independent.length)throw"q.independent is not non-empty array";for(const n of t.independent){if(!n.q)throw`missing q for independent term '${n.id}'`;if(k(n,t,e),"snplst"!=n.type&&"snplocus"!=n.type){if(n.q.computableValuesOnly=!0,!n.id)throw".id missing for an independent term";if(n.term=e.cohort.termdb.q.termjsonByOneid(n.id),!n.term)throw`invalid independent term='${n.id}'`}else{if(!n.q.cacheid)throw"q.cacheid missing";if(h().cache_snpgt.fileNameRegexp.test(n.q.cacheid))throw"invalid cacheid";if("object"!=typeof n.q.snp2effAle)throw"q.snp2effAle{} is not object";if(!Number.isInteger(n.q.alleleType))throw"q.alleleType is not integer";if(!Number.isInteger(n.q.geneticModel))throw"q.geneticModel is not integer";if(3==n.q.geneticModel&&"object"!=typeof n.q.snp2refGrp)throw"q.snp2refGrp{} is not object when geneticMode=3";if("snplst"==n.type&&!Number.isInteger(n.q.missingGenotype))throw"q.missingGenotype is not integer for snplst"}}for(const e of t.independent){e.interactions||(e.interactions=[]);for(const n of e.interactions)if(!t.independent.find((t=>t.id==n)))throw"interacting term id missing from independent[]: "+n}}(t,e),b=(new Date).getTime();const n=await async function(t,e,n){const[r,o]=function(t){const e=[],n=[];for(const r of t)"snplst"==r.type||"snplocus"==r.type?n.push(r):e.push(r);return[e,n]}(e),a=await async function(t,e){const n=new Map,r=await(0,s.w)(t.filter,t.ds),o=r?r.values.slice():[],a=await Promise.all(e.map((async(e,n)=>await(0,i.Bi)(t,o,n,r,e)))).catch(console.error);o.push(...e.map((t=>t.id)));const l=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${a.map((t=>t.sql)).join(",\n")}\n\t\t${a.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${r?`WHERE sample IN ${r.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,c=t.ds.cohort.db.connection.prepare(l).all(o),u=[],f=t.ds.cohort.termdb.ageEndOffset;if(!f)throw"missing age end offset";for(const e of c)if("cox"==t.regressionType&&e.term_id==t.outcome.id){const n=e.key,{age_start:r,age_end:o}=JSON.parse(e.value);if(-1==n)continue;const i={age_start:r,age_end:"age"==t.outcome.q.timeScale?o+f:o};u.push({sample:e.sample,key:n,value:i,term_id:e.term_id})}else u.push(e);for(const{sample:t,term_id:r,key:o,value:i}of u){const s=e.find((t=>t.id==r));if(n.has(t)||n.set(t,{sample:t,id2value:new Map}),n.get(t).id2value.has(r))throw`duplicate '${r}' entry for sample='${t}'`;n.get(t).id2value.set(r,{key:s.q.scale?o/s.q.scale:o,value:s.q.scale?i/s.q.scale:i})}const d=new Set;for(const t of n.values())for(const n of e)if(!t.id2value.has(n.id)){d.add(t.sample);break}for(const t of d)n.delete(t);return n}(t,r);for(const t of o){if(C(t,a,n),"snplst"!=t.type&&"snplocus"!=t.type)throw"unknown type of independent non-dictionary term";await j(t,a)}return[...a.values()]}(t,[t.outcome,...t.independent],e);w=(new Date).getTime(),_.NodeJS.getSampleData=(w-b)/1e3+" sec",b=(new Date).getTime();const r=function(t,e){const n={id:t.outcome.id,name:t.outcome.term.name,rtype:"numeric"};"logistic"==t.regressionType&&(n.categories={ref:t.outcome.refGrp,nonref:S(t.outcome)});"cox"==t.regressionType&&(n.timeToEvent={timeId:t.outcome.id+"_time",eventId:t.outcome.id+"_event",timeScale:t.outcome.q.timeScale},"age"==n.timeToEvent.timeScale&&(n.timeToEvent.agestartId=t.outcome.id+"_agestart",n.timeToEvent.ageendId=t.outcome.id+"_ageend"));const r=[];for(const e of t.independent)"snplst"==e.type||"snplocus"==e.type?N(e,r,t):q(e,r,t);const o=[];for(const i of e){const{sample:e,id2value:s}=i;if(!s.has(t.outcome.id)){i.noOutcome=!0;continue}const a=s.get(t.outcome.id);let l=!1;for(const e of t.independent)if("snplocus"!=e.type)if("snplst"==e.type){for(const t of e.highAFsnps.keys())if(!s.get(t)){l=!0;break}}else{if(!s.get(e.id)){l=!0;break}}if(l)continue;const c={};if("linear"==t.regressionType&&(c[n.id]=a.value),"logistic"==t.regressionType&&(c[n.id]=a.key===t.outcome.refGrp?0:1),"cox"==t.regressionType){c[n.timeToEvent.eventId]=a.key;const{age_start:e,age_end:r}=a.value;c[n.timeToEvent.timeId]=r-e,"age"==t.outcome.q.timeScale&&(c[n.timeToEvent.agestartId]=e,c[n.timeToEvent.ageendId]=r)}for(const t of r){const e=s.get(t.id);c[t.id]=e?"numeric"===t.rtype?e.value:e.key:null}o.push(c)}const i={regressionType:t.regressionType,binpath:h().binpath,data:o,outcome:n,independent:r};return i}(t,n);w=(new Date).getTime(),_.NodeJS.makeRinput=(w-b)/1e3+" sec",function(t){const e=t.regressionType,n=t.outcome;if(t.data.length<v)throw"too few samples to fit model";let r=t.independent.length;if("cox"==e)if("time"==n.timeToEvent.timeScale)r+=2;else{if("age"!=n.timeToEvent.timeScale)throw"unknown cox regression time scale";r+=4}else r+=1;if(t.data.find((t=>Object.keys(t).length!=r)))throw"unequal number of variables in data entries";if("logistic"==e){if([...new Set(t.data.map((t=>t[n.id])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome values found"}if("cox"==e){if([...new Set(t.data.map((t=>t[n.timeToEvent.eventId])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome event values found"}for(const e of t.independent)if("numeric"==e.rtype){if(e.refGrp)throw`reference group given for '${e.id}'`}else{if("factor"!=e.rtype)throw`variable rtype='${e.rtype}' not recognized`;{if(!e.refGrp)throw`reference group not given for '${e.id}'`;if("snplst"==e.type||"snplocus"==e.type)continue;const n=new Set(t.data.map((t=>t[e.id])));if(n.size<2)throw`fewer than 2 categories in data of variable='${e.id}'`;if(!n.has(e.refGrp))throw`reference group missing in data of variable='${e.id}'`}}}(r);const[o,a]=function(t){const e={},n={};if(e.outcome=t.outcome.id,n[t.outcome.id]="outcome",t.outcome.timeToEvent){const r=t.outcome.timeToEvent;e.outcome_time=r.timeId,n[r.timeId]="outcome_time",e.outcome_event=r.eventId,n[r.eventId]="outcome_event","age"==r.timeScale&&(e.outcome_agestart=r.agestartId,e.outcome_ageend=r.ageendId,n[r.agestartId]="outcome_agestart",n[r.ageendId]="outcome_ageend")}for(const[r,o]of t.independent.entries())e["id"+r+"_"]=o.id,n[o.id]="id"+r+"_";if(t.outcome.id=n[t.outcome.id],t.outcome.timeToEvent){const e=t.outcome.timeToEvent;e.timeId=n[e.timeId],e.eventId=n[e.eventId],"age"==e.timeScale&&(e.agestartId=n[e.agestartId],e.ageendId=n[e.ageendId])}for(const e of t.independent)if(e.id=n[e.id],e.interactions&&e.interactions.length>0)for(const[t,r]of e.interactions.entries())e.interactions[t]=n[r];for(const e of t.data)for(const t in e)e[n[t]]=e[t],delete e[t];return[e,n]}(r),l={resultLst:[]};return await Promise.all([A(r,o,t,l),M(t,n,r,l)]),console.log("benchmark:",_),l}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function k(t,e,n){if(!t.q.restrictAncestry)return;if(!("name"in t.q.restrictAncestry))throw".name missing from tw.q.restrictAncestry";if(!n.cohort.termdb.restrictAncestries)throw"ds.cohort.termdb.restrictAncestries missing";const r=n.cohort.termdb.restrictAncestries.find((e=>e.name==t.q.restrictAncestry.name));if(!r)throw"unknown ancestry for restriction: "+t.q.restrictAncestry.name;if(r.pcs)t.q.restrictAncestry.pcs=r.pcs;else{if(!r.PCBySubcohort)throw"unknown way of accessing pcs from ds.cohort.termdb.restrictAncestries: "+t.q.restrictAncestry.name;{if(!e.filter)throw"q.filter missing while trying to access subcohort for PCBySubcohort";const n=O(e.filter,"cohortFilter");if(!n)throw"tvs by tag=cohortFilter missing from q.filter.lst[] while trying to access subcohort for PCBySubcohort";const o=n.tvs.values.map((t=>t.key)).sort().join(","),i=r.PCBySubcohort[o];if(!i)throw"unknown key for PCBySubcohort: "+o;if(!i.pcs)throw"pcs Map() missing from PCBySubcohort[]: "+o;t.q.restrictAncestry.pcs=i.pcs}}}function q(t,e,n){const r={id:t.id,name:t.term.name,type:"spline"==t.q.mode?"spline":"other",rtype:"continuous"==t.q.mode||"spline"==t.q.mode?"numeric":"factor"};if(t.interactions.length>0){r.interactions=[];for(const e of t.interactions){const t=n.independent.find((t=>t.id==e));if("snplst"==t.type)for(const e of t.highAFsnps.keys())r.interactions.push(e);else{if("snplocus"==t.type)continue;r.interactions.push(e)}}}"factor"===r.rtype&&(r.refGrp=t.refGrp),"spline"==t.q.mode&&(r.spline={knots:t.q.knots.map((t=>Number(t.value)))},n.independent.find((t=>"snplocus"==t.type))||(r.spline.plotfile=o().join(h().cachedir,Math.random().toString()+".png"))),e.push(r)}function N(t,e,n){for(const r of t.highAFsnps.keys()){const o={id:r,name:r,type:t.type};3==t.q.geneticModel?(o.rtype="factor",o.refGrp=t.q.snp2refGrp[r]):o.rtype="numeric";for(const e of n.independent)e.interactions.includes(t.id)&&(o.interactions||(o.interactions=[]),o.interactions.push(e.id));e.push(o)}if(t.q.restrictAncestry)for(const n of t.q.restrictAncestry.pcs.keys())e.push({id:n,name:n,type:"float",rtype:"numeric"})}function S(t){if("condition"==t.term.type){for(const e of t.q.groups)if(e.name!=t.refGrp)return e;throw"nonref group not found for logistic outcome"}if("predefined-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!Number.isInteger(t.q.groupsetting.predefined_groupset_idx))throw'outcome.q.predefined_groupset_idx not integer when q.type is "predefined-groupset"';if(!t.term.groupsetting)throw"outcome.term.groupsetting missing";const e=t.term.groupsetting.lst[t.q.groupsetting.predefined_groupset_idx];if(!e)throw"groupset not found by outcome.q.predefined_groupset_idx";const n=e.groups.find((e=>e.name!=t.refGrp));if(!n)throw"non-ref group not found for predefined-groupset";return n.name}if("custom-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!t.q.groupsetting.customset)throw"outcome.q.customset missing";const e=t.q.groupsetting.customset.groups.find((e=>e.name!=t.refGrp));if(!e)throw"non-ref group not found for custom-groupset";return e.name}if("values"==t.q.type){if(!t.term.values)throw"outcome.term.values{} missing";for(const e in t.term.values){const n=t.term.values[e];if(n.label!=t.refGrp)return n.label}throw"unknown nonref group from outcome.term.values"}if("custom-bin"==t.q.type){const e=t.q.lst.find((e=>e.label!=t.refGrp));if(!e)throw"non-ref bin is not found for custom-bin";return e.label}if("regular-bin"==t.q.type)throw"do not know a way to find computed bin list for type=regular-bin";throw"unknown outcome.q.type"}async function A(t,e,n,r){b=(new Date).getTime();const i=o().join(h().cachedir,Math.random().toString()+".json");await p.Sf(i,JSON.stringify(t));const s=await(0,a.default)(o().join(h().binpath,"utils","regression.R"),[],[i]);c().unlink(i,(()=>{})),await async function(t,e,n,r,o){if(1!=e.length)throw"expected 1 json line in R output";const i=JSON.parse(e[0]),s=i.data;_["regression.R"]=i.benchmark;for(const e of s){const i={data:{sampleSize:e.data.sampleSize,eventCnt:e.data.eventCnt?e.data.eventCnt:null}};if(e.id){const t=n[e.id];i.id=t;const o=r.independent.find((t=>"snplocus"==t.type));if(!o)throw"snplocus term missing";i.AFstr=o.snpid2AFstr.get(t),i.data.headerRow=T(t,o)}const s=e.data;if(s.residuals&&(i.data.residuals=s.residuals,i.data.residuals.label="linear"==t.regressionType?"Residuals":"Deviance residuals"),"cox"==t.regressionType){if(s.coefficients.rows.length<1)throw"fewer than 1 row in coefficients table"}else if(s.coefficients.rows.length<2)throw"fewer than 2 rows in coefficients table";i.data.coefficients={header:s.coefficients.header,intercept:"cox"==t.regressionType?null:s.coefficients.rows.shift(),terms:{},interactions:[]};for(const t of s.coefficients.rows)if(-1!=t[0].indexOf(":")){const e={},[r,o]=t.shift().split(":"),[s,a]=t.shift().split(":");e.term1=n[r],e.category1=s,e.term2=n[o],e.category2=a,e.lst=t,i.data.coefficients.interactions.push(e)}else{const e=t.shift(),r=t.shift(),o=n[e];i.data.coefficients.terms[o]||(i.data.coefficients.terms[o]={}),r?(i.data.coefficients.terms[o].categories||(i.data.coefficients.terms[o].categories={}),i.data.coefficients.terms[o].categories[r]=t):i.data.coefficients.terms[o].fields=t}i.data.coefficients.label="Coefficients",i.data.type3={header:s.type3.header,terms:{},interactions:[]},"cox"!=t.regressionType&&(i.data.type3.intercept=s.type3.rows.shift());for(const t of s.type3.rows)if(-1!=t[0].indexOf(":")){const e={},[r,o]=t.shift().split(":");e.term1=n[r],e.term2=n[o],e.lst=t,i.data.type3.interactions.push(e)}else{const e=n[t.shift()];i.data.type3.terms[e]||(i.data.type3.terms[e]=t)}if(i.data.type3.label="Type III statistics",s.totalSnpEffect){if(1!=s.totalSnpEffect.rows.length)throw"total SNP effect table should have 1 row";i.data.totalSnpEffect={header:s.totalSnpEffect.header.slice(0,4)};const t=s.totalSnpEffect.rows[0].slice(0,4),e=s.totalSnpEffect.rows[0][4].split(";"),r=e.findIndex((t=>!t.includes(":"))),o=e.splice(r,1)[0];i.data.totalSnpEffect.snp=n[o];const a=[];for(const t of e){if(!t.includes(":"))throw"expected interaction";const[e,r]=t.split(":");a.push({term1:n[e],term2:n[r]})}i.data.totalSnpEffect.interactions=a,i.data.totalSnpEffect.lst=t,i.data.totalSnpEffect.label="Total SNP effect"}s.tests&&(i.data.tests=s.tests,i.data.tests.label="Statistical tests"),i.data.other=s.other,i.data.other.label="Other summary statistics";for(const e of t.independent)if(e.spline&&e.spline.plotfile){i.data.splinePlots||(i.data.splinePlots=[]);const t=e.spline.plotfile,n=await c().promises.readFile(t);i.data.splinePlots.push({src:"data:image/png;base64,"+new Buffer.from(n).toString("base64"),size:f()(t)}),c().unlink(t,(t=>{if(t)throw t}))}s.warnings&&(i.data.warnings=s.warnings);const a=r.independent.find((t=>"snplst"==t.type));if(a){if(a.lowAFsnps&&a.lowAFsnps.size){i.data.warnings||(i.data.warnings=[]);for(const t of a.lowAFsnps.keys())i.data.warnings.push(`${t}: effect allele frequency below cutoff, excluded from analysis`)}if(a.monomorphicLst&&a.monomorphicLst.length){i.data.warnings||(i.data.warnings=[]);for(const t of a.monomorphicLst)i.data.warnings.push(`${t}: monomorphic, excluded from analysis`)}}o.resultLst.push(i)}}(t,s,e,n,r),w=(new Date).getTime(),_.NodeJS.runRegression=(w-b)/1e3+" sec"}async function M(t,e,n,r){const i=t.independent.find((t=>"snplocus"==t.type));if(i){if(b=(new Date).getTime(),function(t,e){for(const n of t.monomorphicLst){const r=t.snpgt2count.get(n),o=[];for(const[t,e]of r)o.push(t+"="+e);const i={id:n,data:{headerRow:T(n,t)}};e.resultLst.push(i)}}(i,r),i.lowAFsnps.size)if("linear"==t.regressionType)await async function(t,e,n,r){const i=[],s=new Map;for(const[r,o]of t.lowAFsnps){let t=0,a=null,l=null;const c=[],u=[];for(const{sample:r,noOutcome:i}of e){if(i)continue;const e=n.data[t++].outcome;if(!Number.isFinite(e))continue;const s=o.samples.get(r);if(!s)continue;null==a?a=l=e:(a=Math.min(a,e),l=Math.max(l,e));const[f,d]=s.split("/");f==o.effAle||d==o.effAle?c.push(e):u.push(e)}i.push({group1_id:r+"_hasEffAllele",group1_values:c,group2_id:r+"_noEffAllele",group2_values:u}),s.set(r,{minv:a,maxv:l})}const l=o().join(h().cachedir,Math.random().toString()+".json");await p.Sf(l,JSON.stringify(i));const u=await(0,a.default)(o().join(h().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const f=JSON.parse(u);for(const e of f){const n=e.group1_id.replace("_hasEffAllele",""),o=e.group1_values,i=e.group2_values;let a;a=null==e.pvalue||"null"==e.pvalue?"NA":e.pvalue.toPrecision(4);const{minv:l,maxv:c}=s.get(n),u=p.JC(o.sort(((t,e)=>t-e)).map((t=>({value:t}))));u.label=`Carry ${0==t.q.alleleType?"minor":"alternative"} allele, n=${o.length}`;const f=p.JC(i.sort(((t,e)=>t-e)).map((t=>({value:t}))));f.label=`No ${0==t.q.alleleType?"minor":"alternative"} allele, n=${i.length}`;const d={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),wilcoxon:{pvalue:a,boxplots:{minv:l,maxv:c,hasEff:u,noEff:f}}}};r.resultLst.push(d)}}(i,e,n,r);else if("logistic"==t.regressionType)await async function(t,e,n,r){const o=[];let i=0;const s=new Map;for(const[r,a]of t.lowAFsnps){let t=0,l=0,c=0,u=0,f=0;for(const{sample:r,noOutcome:o}of e){if(o)continue;const e=n.data[f++],i="outcome"in e?e.outcome:e.outcome_event;if(0!=i&&1!=i)throw"outcome is not 0 or 1";const s=a.samples.get(r);if(!s)continue;const[d,h]=s.split("/"),p=a.effAle==d||a.effAle==h;0==i?p?l++:t++:p?u++:c++}s.set(i,r);const d={index:i,n1:u,n2:l,n3:c,n4:t};o.push(d),i++}const a=await(0,m.run_rust)("fisher",JSON.stringify({input:o}));for(const e of JSON.parse(a)){const n=s.get(e.index),{effAle:o}=t.lowAFsnps.get(n),i=e.p_value,a="chisq"===e.fisher_chisq,l={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),fisher:{isChi:a,pvalue:Number(i.toFixed(4)),rows:[["","Carry "+o+" allele","No "+o+" allele"],["Have event",e.n1,e.n3],["No event",e.n2,e.n4]]}}};r.resultLst.push(l)}}(i,e,n,r);else{if("cox"!=t.regressionType)throw"unknown regression type";await async function(t,e,n,r){const o={data:{}},i=new Set;for(const[r,s]of t.lowAFsnps){const t=[];let a=0;for(const{sample:r,noOutcome:o}of e){if(o)continue;const e=n.data[a++];if(0!==e.outcome_event&&1!==e.outcome_event)throw"d.outcome_event is not 0/1";if(!Number.isFinite(e.outcome_time))throw"d.outcome_time is not numeric";const i={time:e.outcome_time,event:e.outcome_event},l=s.samples.get(r);if(!l)continue;const[c,u]=l.split("/");i.series=s.effAle==c||s.effAle==u?"1":"2",t.push(i)}new Set(t.map((t=>t.series))).size<2?i.add(r):o.data[r]=t}const s=await(0,g.y)(o);let a;for(const[e,n]of t.lowAFsnps){if(i.has(e)){a={pvalue:"NA",msg:"Cannot perform cumulative incidence test on this snp - at least one allele is not found in any sample"}}else{var l;if(1==!(null!==(l=s[e].tests)&&void 0!==l&&l.length))throw"must have a single test";const t=Number(s[e].tests[0].pvalue);if(!Number.isFinite(t))throw"invalid pvalue";a={pvalue:Number(t.toFixed(4)),ci_data:{[e]:s[e]}}}const n={id:e,AFstr:t.snpid2AFstr.get(e),data:{headerRow:T(e,t),cuminc:a}};r.resultLst.push(n)}}(i,e,n,r)}w=(new Date).getTime(),_.NodeJS.snplocusPostprocess=(w-b)/1e3+" sec"}}function T(t,e){const n=e.snpgt2count.get(t);if(!n)return{k:"Error",v:"Variant not found"};if(e.monomorphicLst.includes(t)){const[t,e]=[...n][0];return{k:"Genotype",v:t+"="+e}}const r=[`${0==e.q.alleleType?"Minor":"Alternative"} allele=${e.highAFsnps.has(t)?e.highAFsnps.get(t).effAle:e.lowAFsnps.get(t).effAle}`,"AF="+e.snpid2AFstr.get(t)];for(const[t,e]of n)r.push(t+"="+e);return{k:"Variant:",v:r.join(" ")}}function C(t,e,n){if(t.q.restrictAncestry)for(const[n,r]of t.q.restrictAncestry.pcs)for(const[t,o]of r)e.has(t)&&e.get(t).id2value.set(n,{key:o,value:o})}async function j(t,e,n){const r=(await p.b5(o().join(h().cache_snpgt.dir,t.q.cacheid))).split("\n"),i=r[0].split("\t").slice(h().cache_snpgt.sampleColumn).map(Number);if(n)for(const t of i)e.set(t,{id2value:new Map});const s=i.map((t=>e.has(t))),a=new Map;for(let e=1;e<r.length;e++){const n=r[e].split("\t"),o=n[0],l={refAle:n[3],altAles:n[4].split(","),samples:new Map};t.q.snp2effAle?l.effAle=t.q.snp2effAle[o]:l.effAle=l.altAles[0],a.set(o,l);for(const[t,e]of i.entries()){if(!s[t])continue;const r=n[t+h().cache_snpgt.sampleColumn];r&&a.get(o).samples.set(e,r)}}"snplocus"!=t.type&&function(t,e,n,r){if(0==e.q.missingGenotype){for(const e of t.values()){let t;if(e.refAle!=e.effAle)t=e.refAle;else for(const n of e.altAles)if(n!=e.effAle){t=n;break}if(!t)throw"not finding a non-effect allele";for(const[o,i]of n.entries())r[o]&&(e.samples.has(i)||e.samples.set(i,t+"/"+t))}return}if(1==e.q.missingGenotype){const e=new Set;for(const{samples:o}of t.values())for(const[t,i]of n.entries())r[t]&&(o.has(i)||e.add(i));for(const{samples:n}of t.values())for(const t of e)n.delete(t);return}throw"invalid missingGenotype value"}(a,t,i,s),t.snpgt2count=new Map;for(const[e,n]of a){const r=new Map;for(const[t,e]of n.samples)r.set(e,1+(r.get(e)||0));t.snpgt2count.set(e,r)}!function(t,e){t.lowAFsnps=new Map,t.highAFsnps=new Map,t.monomorphicLst=[],t.snpid2AFstr=new Map;for(const[n,r]of e){if(1==t.snpgt2count.get(n).size){t.monomorphicLst.push(n);continue}const e=r.samples.size;let o=0;for(const[t,e]of r.samples){const[t,n]=e.split("/");o+=(t==r.effAle?1:0)+(n==r.effAle?1:0)}const i=o/(2*e);t.snpid2AFstr.set(n,(100*i).toFixed(1)+"%"),i<t.q.AFcutoff/100?t.lowAFsnps.set(n,r):t.highAFsnps.set(n,r)}}(t,a);for(const[n,r]of t.highAFsnps)for(const[o,i]of r.samples){const[s,a]=i.split("/"),l=E(t,r.effAle,s,a);e.get(o).id2value.set(n,{key:l,value:l})}}function E(t,e,n,r){switch(t.q.geneticModel){case 0:return(n==e?1:0)+(r==e?1:0);case 1:return n==e||r==e?1:0;case 2:return n==e&&r==e?1:0;case 3:return n+"/"+r;default:throw"unknown geneticModel option"}}function O(t,e){if(t.tag===e)return t;if("tvslst"===t.type)for(const n of t.lst){const t=O(n,e);if(t)return t}}},2188:(t,e,n)=>{"use strict";n.d(e,{uR:()=>g,v8:()=>k,wz:()=>m});var r=n(2974),o=n(1017),i=n.n(o),s=n(3345),a=n(334),l=n.n(a),c=n(2273),u=n(8907),f=n(5257),d=n(6191),h=n(9157);const p="#F5F5DC";async function m(t){if(t.cohort.scatterplots){if(!Array.isArray(t.cohort.scatterplots.plots))throw"cohort.scatterplots.plots is not array";for(const e of t.cohort.scatterplots.plots){if(!e.name)throw".name missing from one of scatterplots.plots[]";if(!e.file)throw"unknown data source of one of scatterplots.plots[]";{const n=(await(0,s.b5)(i().join(l().tpmasterdir,e.file))).trim().split("\n"),r=n[0].split("\t");e.filterableSamples=[];const o=[];let a=0,c=0;for(let i=1;i<n.length;i++){const s=n[i].split("\t"),l=Number(s[1]),u=Number(s[2]);if(Number.isNaN(l)||Number.isNaN(u)){a++;continue}const f={sample:s[0],x:l,y:u},d=t.cohort.termdb.q.sampleName2id(s[0]);if(null==d){if(r[3]){f.info={};for(let t=3;t<r.length;t++)f.info[r[t]]=s[t]}o.push(f)}else c++,f.sampleId=d,e.filterableSamples.push(f)}o.length&&(e.referenceSamples=o),console.log(e.filterableSamples.length,`scatterplot lines from ${e.name} of ${t.label},`,e.referenceSamples?e.referenceSamples.length+" reference cases":"",a?a+" lines with invalid X/Y values":"")}}}}async function g(t,e,n,o,i){try{let s,a;if(2==e.coordTWs.length)s=[],a=await async function(t,e,n){e.ds=n;const r=[];if(2!=e.coordTWs.length)return r;const o=await(0,f.w)(e.filter,e.ds);let i="";o&&(i+=(0,u.ig)(`WITH ${o.filters}`,o.values.slice()));const s=e.coordTWs[0].term,a=e.coordTWs[1].term;let l;e.divideByTW&&"continuous"==e.divideByTW.q.mode&&(l=e.divideByTW.term);i+=`SELECT ax.sample AS sampleId, ax.value as x, ay.value AS y , ${l?"az.value AS z":"0 as z"}\n\t\t\tFROM anno_${s.type} ax \n\t\t\tJOIN anno_${a.type} ay on ax.sample = ay.sample and ay.term_id = '${a.id}' \n\t\t\t${l?`JOIN anno_${l.type} az on ax.sample = az.sample and az.term_id = '${l.id}' `:""}\n\t\t\tWHERE ax.term_id = '${s.id}'`,o&&(i+=` AND ax.sample IN ${o.CTEname}`);const c=e.ds.cohort.db.connection.prepare(i).all(),h=d.i.canDisplaySampleIds(t,n);for(const{sampleId:t,x:o,y:i,z:s}of c){var p;if(null!==(p=l)&&void 0!==p&&p.values&&s in l.values)continue;const a={sampleId:t,x:o,y:i,z:s};h&&(a.sample=n.sampleId2Name.get(t));const c=x(e.coordTWs[0].term,o)&&x(e.coordTWs[1].term,i);a&&c&&r.push(a)}return r}(t,e,o);else{if(!e.plotName)throw"Neither plot name or coordinates where provided";if(!o.cohort.scatterplots||!o.cohort.scatterplots.plots)throw"not supported";const t=o.cohort.scatterplots.plots.find((t=>t.name==e.plotName));if(!t)throw`plot not found with plotName ${e.plotName}`;const n=await async function(t,e,n){if(n.filterableSamples){let t=[],e=[];return n.referenceSamples&&(e=r(n.referenceSamples)),n.filterableSamples&&(t=r(n.filterableSamples)),[e,t]}if(n.gdcapi)throw"gdcapi not implemented yet";throw"do not know how to load data from this plot";function r(t){const e=[];for(const n of JSON.parse(JSON.stringify(t)))e.push(n);return e}}(0,0,t);s=n[0],a=n[1]}const l=[];e.coordTWs&&l.push(...e.coordTWs),e.colorTW&&l.push(e.colorTW),e.shapeTW&&l.push(e.shapeTW),e.divideByTW&&l.push(e.divideByTW),e.scaleDotTW&&l.push(e.scaleDotTW);const h=await(0,r.Yu)({filter:e.filter,terms:l},o,i);if(h.error)throw h.error;const m=await async function(t,e,n,r){const o={};for(const c of e){const e=n.samples[c.sampleId.toString()];if(!e)continue;let d=!1;if(r.colorTW&&!y(e,r.colorTW)||r.shapeTW&&!y(e,r.shapeTW))continue;let h="Default";if(r.divideByTW&&"continuous"!=r.divideByTW.q.mode)if(c.z=0,"geneVariant"==r.divideByTW.term.type)h=b(!0,e,r.divideByTW),null==h&&(h=b(!1,e,r.divideByTW),d=!0);else{var i,s,a;const t=null===(i=e[r.divideByTW.term.id||r.divideByTW.term.name])||void 0===i?void 0:i.key;if(null==t)continue;h=(null===(s=r.divideByTW.term.values)||void 0===s||null===(a=s[t])||void 0===a?void 0:a.label)||t}if(!o[h]){const e=t.map((t=>({...t,category:"Ref",shape:"Ref",z:0})));o[h]={samples:e,colorMap:{},shapeMap:{},isLast:d}}if(r.divideByTW||(c.z=0),r.scaleDotTW){var l;const t=null==e||null===(l=e[r.scaleDotTW.id])||void 0===l?void 0:l.key;if(!t||!x(r.scaleDotTW.term,t))continue;c.scale=t}else c.scale=1;var u,f;if(c.cat_info={},c.hidden={},r.colorTW)"continuous"===(null===(u=r.colorTW)||void 0===u||null===(f=u.q)||void 0===f?void 0:f.mode)?e&&(c.category=e[r.colorTW.term.id||r.colorTW.term.name].value):v(e,c,r.colorTW,o[h].colorMap,"category");else c.category="Default";r.shapeTW?v(e,c,r.shapeTW,o[h].shapeMap,"shape"):c.shape="Ref",o[h].samples.push(c)}let d=0;for(const[t,e]of Object.entries(o))d=Math.max(d,Object.keys(e.colorMap).length);const h=(0,c.getColors)(d);for(const[i,s]of Object.entries(o)){var m,g,w;if(r.colorTW&&"continuous"!==r.colorTW.q.mode){let t=20;const e=c.schemeCategory20,o=Object.entries(s.colorMap);for(const[i,s]of o){var k,q,N,S;let o;if(null!==(k=r.colorTW.term.values)&&void 0!==k&&k[i])o=null===(q=r.colorTW.term.values)||void 0===q?void 0:q[i];else for(const t in r.colorTW.term.values){var A,M;(null===(A=r.colorTW.term.values)||void 0===A?void 0:A[t].label)==i&&(o=null===(M=r.colorTW.term.values)||void 0===M?void 0:M[t])}if(o&&"color"in o)s.color=o.color;else if(null!==(N=n.refs)&&void 0!==N&&null!==(S=N.byTermId[r.colorTW.term.id])&&void 0!==S&&S.bins){const o=n.refs.byTermId[r.colorTW.term.id].bins.find((t=>t.name===i));o?s.color=o.color:(s.color=e[t],t--)}else"geneVariant"!=r.colorTW.term.type&&(s.color=h(i))}}let o=1;for(const[t,e]of Object.entries(s.shapeMap))"shape"in e||(e.shape=o),o++;s.colorLegend=r.colorTW?_(s.colorMap,r.colorTW,n.refs):[["Default",{sampleCount:e.length,color:"blue"}]],s.colorLegend.push(["Ref",{sampleCount:t.length,color:null!==(m=r.colorTW)&&void 0!==m&&null!==(g=m.term.values)&&void 0!==g&&g.Ref?null===(w=r.colorTW.term.values)||void 0===w?void 0:w.Ref.color:p}]),s.shapeLegend=_(s.shapeMap,r.shapeTW,n.refs),s.shapeLegend.push(["Ref",{sampleCount:t.length,shape:0}])}return o}(s,a,h,e);n.send(m)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}function y(t,e){var n,r,o;const i=void 0!==(null==t||null===(n=t[(null==e||null===(r=e.term)||void 0===r?void 0:r.id)||(null==e||null===(o=e.term)||void 0===o?void 0:o.name)])||void 0===n?void 0:n.key);return i||console.log(JSON.stringify(t)+" missing value for the term "+JSON.stringify(e)),i}function v(t,e,n,r,o){let i=null;if("geneVariant"==n.term.type)!function(t,e,n,r,o){if("geneVariant"==n.term.type){var i;const s=null==t||null===(i=t[n.term.name])||void 0===i?void 0:i.values;e.cat_info[o]=[];for(const t of s){const n=c.mclass[t.class],i=w(t);let s;e.cat_info[o].push(t),null==r[i]?(s={color:n.color,sampleCount:1,hasOrigin:"origin"in t},r[i]=s):(s=r[i],s.sampleCount=s.sampleCount+1,s.hasOrigin=s.hasOrigin||"origin"in t)}e[o]=b(!0,t,n)||b(!1,t,n),e[o]||(e[o]=w(s[0])),e.hidden[o]=!!n.q.hiddenValues&&e[o]in n.q.hiddenValues}}(t,e,n,r,o);else{var s,a,l,u,f,d;if(i=null==t||null===(s=t[n.id||n.term.name])||void 0===s?void 0:s.key,null!==(a=n.term.values)&&void 0!==a&&null!==(l=a[i])&&void 0!==l&&l.label)i=null===(f=n.term.values)||void 0===f||null===(d=f[i])||void 0===d?void 0:d.label,e.hidden[o]=!!n.q.hiddenValues&&i in n.q.hiddenValues;else e.hidden[o]=!!n.q.hiddenValues&&(null==t||null===(u=t[n.id])||void 0===u?void 0:u.key)in n.q.hiddenValues;i&&(e[o]=i.toString(),null==r[i]?r[i]={sampleCount:1}:r[i].sampleCount++)}}function b(t,e,n){var r;const o=null==e||null===(r=e[n.term.name])||void 0===r?void 0:r.values;for(const[e,r]of Object.entries(c.dt2label)){const r=o.find((t=>{const r=w(t),o=!(n.q.hiddenValues&&r in n.q.hiddenValues);return t.dt==e&&o}));if(!r)continue;const i="WT"==r.class||"Blank"==r.class;if(t&&i)continue;return w(r)}}function w(t){var e;const n=t.dt,r=c.mclass[t.class],o=null===(e=c.morigin[t.origin])||void 0===e?void 0:e.label,i=o?`${o[0]} ${c.dt2label[n]}`:c.dt2label[n];return`${r.label}, ${i}`}function _(t,e,n){var r;let o=[];if(!e||0==t.size)return o;if("geneVariant"==e.term.type)o=Object.entries(t),o.sort(((t,e)=>t[0]<e[0]?-1:t[0]>e[0]?1:0));else if(null!=n&&null!==(r=n.byTermId[e.term.id])&&void 0!==r&&r.bins){const r=n.byTermId[e.term.id].bins;for(const e of r)t[e.name]&&o.push([e.name,t[e.name]]);for(const[e,n]of Object.entries(t))o.some((t=>t[0]===e))||o.push([e,n])}else o=Object.entries(t),o.sort(((t,n)=>{let r,o;for(const i in e.term.values){const s=e.term.values[i];(s.label&&t[0]==s.label||i==t[0])&&(r=s),(s.label&&n[0]==s.label||i==n[0])&&(o=s)}var i,s;return r&&"order"in r?(null===(i=r)||void 0===i?void 0:i.order)<(null===(s=o)||void 0===s?void 0:s.order)?-1:1:t[1].sampleCount>n[1].sampleCount?-1:1}));return o}function x(t,e){var n,r;return!(null!==(n=t.values)&&void 0!==n&&null!==(r=n[e])&&void 0!==r&&r.uncomputable)}async function k(t,e,n){const r=e.coords,o=i().join(l().cachedir,Math.random().toString()+".json");await(0,s.Sf)(o,JSON.stringify(r));let a=await(0,h.default)(i().join(l().binpath,"utils/lowess.R"),[],[o]);a=JSON.parse(a);const c=[];for(const[t,e]of Object.entries(a.x))c.push([e,a.y[t]]);return n.send(c)}},394:(t,e,n)=>{"use strict";n.d(e,{JV:()=>l,jj:()=>c,qN:()=>u});var r=n(334),o=n.n(r),i=n(3345),s=n(1575),a=n(6191);function l(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.db)throw"ds.cohort.db missing";if(!t.cohort.termdb)throw"ds.cohort.termdb missing";const e=t.cohort.db.file_fullpath||t.cohort.db.file;if(!e)throw"both file and file_fullpath missing";let n;try{console.log("Connecting",e),n=(0,i.sE)(e),console.log(`DB connected for ${t.label}: ${e}`)}catch(t){throw`Cannot connect db ${e}: ${t.message||t}`}t.cohort.db.connection=n;const r=c(n),l=["cohorts","sampleidmap","terms","ancestry","alltermsbyorder","termhtmldef","category2vcfsample","chronicevents","precomputed_chc_grade","precomputed_chc_child","precomputed_cuminc","precomputed_cox","subcohort_terms","subcohort_samples","survival","features","cohort_features","anno_integer","anno_float","anno_categorical","buildDate"];for(const t of l)r.has(t)||console.log(`${t} table missing!!!!!!!!!!!!!!!!!!!!`);if(!r.has("terms"))throw"terms table missing";if(!r.has("ancestry"))throw"ancestry table missing";if(t.cohort.termdb.selectCohort&&!r.has("subcohort_terms"))throw"subcohort_terms table is missing while termdb.selectCohort is enabled";t.cohort.termdb.q={};const f=t.cohort.termdb.q;if(r.has("buildDate")&&(f.get_buildDate=n.prepare("select date from buildDate")),r.has("term2genes")){t.cohort.termdb.termMatch2geneSet=!0;const e=n.prepare("SELECT genes FROM term2genes WHERE id=?"),r=new Map;f.getGenesetByTermId=t=>{if(r.has(t))return r.get(t);const n=e.get(t);if(n&&n.genes){const e=JSON.parse(n.genes);return r.set(t,e),e}}}if(r.has("sampleidmap")){const e=new Map,r=new Map,o=n.prepare("SELECT * FROM sampleidmap");let i=0;for(const{id:t,name:n}of o.all())e.set(t,n),r.set(n,t),i++;if(f.id2sampleName=t=>e.get(t),f.sampleName2id=t=>r.get(t),t.cohort.termdb.selectCohort){const t=n.prepare("SELECT cohort,sample_count from cohorts").all(),e={};for(const n of t)e[n.cohort]=n.sample_count;f.getcohortsamplecount=t=>t?e[t]||0:i}else f.getcohortsamplecount=()=>i}if(r.has("category2vcfsample")){const t=n.prepare("SELECT * FROM category2vcfsample");let e;f.getcategory2vcfsample=()=>{if(e)return e;e=t.all();for(const t of e)t.q=JSON.parse(t.q),t.categories=JSON.parse(t.categories);return e}}if(r.has("alltermsbyorder")){const t=n.prepare("SELECT * FROM alltermsbyorder");let e;f.getAlltermsbyorder=()=>{if(e)return e;const n=t.all();e=[];for(const t of n){const n=f.termjsonByOneid(t.id);n&&e.push({group_name:t.group_name,term:n})}return e}}{const t=n.prepare("SELECT name, jsondata FROM terms WHERE id=?"),e=new Map;f.termjsonByOneid=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsondata);return t.id=n,t.name=r.name||t.name,e.set(n,t),t}}}{const t=n.prepare("select id from terms where parent_id=?"),e=new Map;f.termIsLeaf=n=>{if(e.has(n))return e.get(n);let r=!0;const o=t.get(n);return o&&o.id&&(r=!1),e.set(n,r),r}}{const t=n.prepare("SELECT id, name, jsondata, s.included_types, s.child_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE parent_id is null\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),e=new Map;f.getRootTerms=(n="")=>{const r=n;if(e.has(r))return e.get(r);const o=t.all(n).map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):["TO-DO-PLACEHOLDER"],e.child_types=t.child_types?t.child_types.split(","):[],e}));return e.set(r,o),o}}{const t=n.prepare("SELECT parent_id FROM terms WHERE id=?");{const e=new Map;f.termHasParent=n=>{if(e.has(n))return e.get(n);let r=!1;const o=t.get(n);return o&&o.parent_id&&(r=!0),e.set(n,r),r}}{const e=new Map;f.getTermParentId=n=>{if(e.has(n))return e.get(n);let r;const o=t.get(n);return o&&o.parent_id&&(r=o.parent_id),e.set(n,r),r}}{const t=new Map;f.getTermParent=e=>{if(t.has(e))return t.get(e);const n=f.getTermParentId(e);let r;return n&&(r=f.termjsonByOneid(n)),t.set(e,r),r}}}{const t=n.prepare("SELECT id, name, type, jsondata, s.included_types, s.child_types \n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=? \n\t\t\tWHERE id IN (SELECT id FROM terms WHERE parent_id=?)\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),e=new Map;f.getTermChildren=(n,r="")=>{const o=n+";;"+r;if(e.has(o))return e.get(o);const i=t.all([r,n]);let s;return i&&(s=i.map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):[],e.child_types=t.child_types?t.child_types.split(","):[],e}))),e.set(o,s),s}}{const t=n.prepare("SELECT id, name, jsondata, s.included_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE name LIKE ?");f.findTermByName=(e,n=10,r="",o=null,i=null,a=null)=>{const l=t.all([r,"%"+e+"%"]);if(l){const t=a||{equals:[],startsWith:[],startsWord:[],includes:[]};for(const n of l){if(!n.jsondata)continue;const r=n.name.toLowerCase(),o=JSON.parse(n.jsondata);o.id=n.id,o.name=n.name||o.name,o.included_types=n.included_types?n.included_types.split(","):[],i&&!(0,s.CG)(o,i).has("plot")||(r===e?t.equals.push(o):r.startsWith(e)?t.startsWith.push(o):r.includes(" "+e)?t.startsWord.push(o):t.includes.push(o))}return[...t.equals,...t.startsWith,...t.startsWord,...t.includes].slice(0,n)}}}{const t=n.prepare("SELECT MAX(value) AS v FROM anno_integer WHERE term_id=?"),e=n.prepare("SELECT MAX(value) AS v FROM anno_float WHERE term_id=?"),r=new Map;f.findTermMaxvalue=(n,o)=>{if(r.has(n))return r.get(n);const i=(o?t:e).get(n);return i?(r.set(n,i.v),i.v):void 0}}{const t={float:n.prepare("SELECT sample,value FROM anno_float WHERE term_id=?"),integer:n.prepare("SELECT sample,value FROM anno_integer WHERE term_id=?"),categorical:n.prepare("SELECT sample,value FROM anno_categorical WHERE term_id=?")};f.getAllValues4term=e=>{const n=f.termjsonByOneid(e);if(!n)return;const r=t[n.type];if(!r)return;const o=r.all(e);if(!o||0==o.length)return;const i=new Map;for(const t of o)i.set(t.sample,t.value);return i}}{const t=n.prepare("SELECT ancestor_id FROM ancestry WHERE term_id=?"),e=new Map;f.getAncestorIDs=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.ancestor_id));return e.set(n,r),r}}{const t=n.prepare("SELECT t.name FROM ancestry as a, terms as t WHERE a.term_id=? AND t.id=a.ancestor_id"),e=new Map;f.getAncestorNames=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.name));return e.set(n,r),r}}{const t={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=?")},e={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=? AND sample=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=? AND sample=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=? AND sample=?")},r={categorical:n.prepare("SELECT value FROM anno_categorical a,sampleidmap s WHERE term_id=? AND s.name=?"),integer:n.prepare("SELECT value FROM anno_integer a,sampleidmap s WHERE term_id=? AND s.name=?"),float:n.prepare("SELECT value FROM anno_float a, sampleidmap s WHERE term_id=? AND s.name=?")};f.getSample2value=(n,o=null)=>{const i=f.termjsonByOneid(n);return o?"string"==typeof o?r[i.type].all(n,o):e[i.type].all(n,o):t[i.type].all(n)}}if(r.has("termhtmldef")){const t=n.prepare("SELECT jsonhtml FROM termhtmldef WHERE id=?"),e=new Map;f.getTermInfo=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsonhtml);return t.id=n,e.set(n,t),t}}}f.getSupportedChartTypes=e=>{var n;u(t);null===(n=o().dsCredentials)||void 0===n||n[t.label];const r={},i={};for(const n of t.cohort.termdb.termtypeByCohort){var s;if(n.type){if(!(n.cohort in r)){var l;r[n.cohort]=new Set(["regression","summary"]),t.cohort.scatterplots&&r[n.cohort].add("sampleScatter"),i[n.cohort]=0,null!==(l=t.cohort.allowedChartTypes)&&void 0!==l&&l.includes("matrix")&&r[n.cohort].add("matrix");const o=a.i.getForbiddenRoutesForDsEmbedder(t.label,e);o.includes("termdb")||o.includes("*")||(r[n.cohort].add("dataDownload"),r[n.cohort].add("sampleView"))}null!==(s=o().features)&&void 0!==s&&s.draftChartTypes&&r[n.cohort].add(...o().features.draftChartTypes),"survival"!=n.type||r[n.cohort].has("survival")||r[n.cohort].add("survival"),"condition"!=n.type||r[n.cohort].has("cuminc")||r[n.cohort].add("cuminc"),"float"!=n.type&&"integer"!=n.type||(i[n.cohort]+=n.samplecount)}}for(const t in i)i[t]>1&&r[t].add("sampleScatter");for(const t in r)r[t]=[...r[t]];if(t.cohort.allowedChartTypes)for(const e in r)r[e]=r[e].filter((e=>t.cohort.allowedChartTypes.includes(e)));if(t.queries){if(t.queries.snvindel||t.queries.trackLst)for(const t in r)r[t].push("genomeBrowser");if(t.queries.geneExpression)for(const t in r)r[t].push("hierCluster");if(t.queries.rnaseqGeneCount)for(const t in r)r[t].push("DEanalysis")}return r},f.getSingleSampleData=function(t,e=[]){const r=e.length?`and term_id in (${e.map((t=>"?")).join(",")})`:"",o=`select term_id, value, jsondata from ( select term_id, value \n\t\tfrom anno_categorical \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, \n\t\tvalue from anno_float \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, value \n\t\tfrom anno_integer \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, (min_years_to_event || ' ' || value) as value \n\t\tfrom precomputed_chc_grade \n\t\twhere max_grade=1 and sample=? ${r}\n\t\tunion all \n\t\tselect term_id, (tte || ' ' || exit_code) as value \n\t\tfrom survival \n\t\twhere sample=? ${r}) join terms on terms.id = term_id`;return n.prepare(o).all([t,...e,t,...e,t,...e,t,...e,t,...e])},f.getProfileFacilities=function(){return n.prepare("select name from sampleidmap join \n\t\tanno_categorical on sampleidmap.id = anno_categorical.sample\n\t\twhere term_id = 'sampleType' and value = 'Facility'").all()}}function c(t){const e=t.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();return new Set(e.map((t=>t.name)))}function u(t){var e,n;if(t.cohort.termdb.termtypeByCohort){if(!Array.isArray(t.cohort.termdb.termtypeByCohort))throw"termtypeByCohort is not array"}else{if(null===(e=t.cohort)||void 0===e||null===(n=e.db)||void 0===n||!n.connection)throw"termtypeByCohort[] not set but cohort.db.connection missing";t.cohort.termdb.termtypeByCohort=t.cohort.db.connection.prepare("WITH c AS (\n\t\t\tSELECT cohort, term_id\n\t\t\tFROM subcohort_terms s\n\t\t\tGROUP BY cohort, term_id\n\t\t) \n\t\tSELECT cohort, type, count(*) as samplecount\n\t\tFROM terms t\n\t\tJOIN c ON c.term_id = t.id\n\t\tGROUP BY cohort, type").all()}}},3795:(t,e,n)=>{"use strict";n.d(e,{G:()=>g,u:()=>y});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(8907),c=(n(2826),n(4521),n(334)),u=n.n(c),f=n(3625);const d="%CHROM\t%POS\t%REF\t%ALT[\t%TGT]\n",h="%POS\t%ID\t%REF\t%ALT\t%INFO[\t%TGT]\n",p="./.",m=1e3;async function g(t,e,n,r){try{if(t.sumSamples)return await async function(t,e,n,r){if(!t.cacheid)throw"cacheid missing";if(u().cache_snpgt.fileNameRegexp.test(t.cacheid))throw"invalid cacheid";let o,i;if(n.track){if(o=n.track.vcf,!o)throw"ds.track.vcf missing"}else o=n.queries.snvindel.byrange._tk;if(t.filter){const e=new Set((await l.cf(t.filter,n)).map((t=>t.id)));if(0==e.size)throw"no samples from filter";i=o.samples.map((t=>e.has(t.name)))}else i=o.samples.map((t=>!0));const c=(await a.b5(s().join(u().cache_snpgt.dir,t.cacheid))).split("\n"),f=new Set,d=[];for(let t=1;t<c.length;t++){const e=c[t].split("\t"),n=e[0],r=e[3],s={},a={};for(let t=u().cache_snpgt.sampleColumn;t<e.length;t++){const n=e[t];if(!n)continue;if(!i[t-u().cache_snpgt.sampleColumn])continue;f.add(o.samples[t-u().cache_snpgt.sampleColumn].name),a[n]=1+(a[n]||0);const r=n.split("/");for(const t of r)s[t]=1+(s[t]||0)}const l=[];for(const t in s)l.push({allele:t,count:s[t],isRef:t==r});d.push({snpid:n,alleles:l,gt2count:a})}return{numOfSampleWithAnyValidGT:f.size,snps:d}}(t,0,n);if(t.snptext)return await async function(t,e,n){if(!n.snp)throw"snp not supported by genome";if(!t.snptext)throw".snptext missing";const r=function(t){const e=[];for(const n of t.trim().split("\n")){const[t,r]=n.trim().split(/[\s\t]/);if(t&&t.startsWith("rs")){if(e.find((e=>e.rsid==t)))continue;const n={rsid:t,snpid:t};r&&(n.effectAllele=r),e.push(n)}else e.push({rsid:t,snpid:t,invalid:"INVALID RSID"})}return e}(t.snptext);if(!r.length)throw"no snps";await async function(t,e){for(const n of t)if(!n.invalid)if(n.chr&&"string"==typeof n.chr){const t=e.chrlookup[n.chr.toUpperCase()];if(!t){n.invalid=!0;continue}if(!Number.isInteger(n.pos)){n.invalid=!0;continue}if(n.pos<=0||n.pos>=t.len){n.invalid=!0;continue}}else if(n.rsid){const t=await a.mr(e.snp.bigbedfile,n.rsid),r=[];for(const n of t){const t=n.split("\t"),o=e.chrlookup[t[0].toUpperCase()];o&&o.major&&r.push(t)}if(0==r.length){n.invalid=!0;continue}const o=r[0];n.chr=o[0],n.pos=Number.parseInt(o[1]),n.dbsnpRef=o[4],n.dbsnpAlts=o[6].split(",").filter(Boolean)}else n.invalid=!0;if(!t.find((t=>!t.invalid)))throw"no valid variants"}(r,n);const i=await async function(t,e,n){let r;if(n.track){if(r=n.track.vcf,!r)throw"ds.track.vcf missing"}else r=n.queries.snvindel.byrange._tk;const i=new Set,l=[];for(const t of e){if(t.invalid)continue;let e;var c;if(r.chr2files){if(e=null===(c=r.chr2files)||void 0===c?void 0:c[t.chr].file,!e)throw"chr not in chr2files"}else if(r.chr2bcffile){if(e=r.chr2bcffile[t.chr],!e)throw"chr not in chr2bcffile"}else e=r.file||r.url;i.add(e);const n=(r.nochr?t.chr.replace("chr",""):t.chr)+"\t"+(t.pos+1);l.push(n)}const f=s().join(u().cachedir,await a.tG(l.join("\n"))),h=s().join(u().cachedir,await a.tG([...i].join("\n")));await a.UE({isbcf:!0,args:["query","-R",f,"-f",d,"-v",h],dir:r.dir,callback:t=>{const n=t.split("\t"),o=(r.nochr?"chr":"")+n[0],i=n[1],s=n[2],a=n[3].split(","),l=e.find((t=>{if(t.chr==o&&t.pos===i-1&&t.dbsnpRef==s&&t.dbsnpAlts.some((t=>a.includes(t))))return t}));if(l){l.referenceAllele=s,l.altAlleles=a,l.gtlst=[];for(let t=4;t<n.length;t++)l.gtlst.push(n[t]==p?"":n[t])}}}),o().unlink(f,(()=>{})),o().unlink(h,(()=>{}));const m=["snpid\tchr\tpos\tref\talt\teff\t"+r.samples.map((t=>t.name)).join("\t")];for(const t of e)t.invalid||t.gtlst&&(m.push(t.snpid+"\t"+t.chr+"\t"+t.pos+"\t"+t.referenceAllele+"\t"+t.altAlleles.join(",")+"\t"+(t.effectAllele||"")+"\t"+t.gtlst.join("\t")),delete t.gtlst);const g=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random());return await a.Sf(s().join(u().cache_snpgt.dir,g),m.join("\n")),g}(t,r,e);return{snps:r,cacheid:i}}(t,n,r);if(t.chr)return await async function(t,e,n){const r=Number(t.start),o=Number(t.stop);if(!Number.isInteger(r)||!Number.isInteger(o))throw"start/stop are not integers";if(r>o||r<0)throw"invalid start/stop coordinate";let i,l;if(e.track){if(i=e.track.vcf,!i)throw"ds.track.vcf missing";if(l=i.chr2bcffile[t.chr],!l)throw"chr not in chr2bcffile"}else{var c;if(i=e.queries.snvindel.byrange._tk,i.chr2files)l=null===(c=i.chr2files)||void 0===c?void 0:c[t.chr].file;else l=i.file||i.url;if(!l)throw"no bcf file"}const d=(i.nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+o,g=["query",l,"-r",d,"-f",h];t.variant_filter&&y(t.variant_filter,g);const v={snps:[]},b=["snpid\tchr\tpos\tref\talt\teff\t"+i.samples.map((t=>t.name)).join("\t")];return await a.UE({isbcf:!0,args:g,dir:i.dir,callback:(e,n)=>{if(v.snps.length>=m)return n.kill(),void(v.reachedVariantLimit=!0);const r=e.split("\t"),o=Number(r[0])-1,s=r[1],a=r[2],l=r[3].split(","),c=s&&"."!=s?s:o+"."+a+"."+l.join(","),u={snpid:c,chr:t.chr,pos:o};(0,f.H)(i,a,l,u,r[4],r[1]);for(const t of u.mlst)t.vcf_id&&(t.mname=t.vcf_id);v.snps.push(u);const d=[c,t.chr,o,a,l.join(","),""];for(let t=5;t<r.length;t++)d.push(r[t]==p?"":r[t]);b.push(d.join("\t"))}}),v.cacheid=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random()),await a.Sf(s().join(u().cache_snpgt.dir,v.cacheid),b.join("\n")),v}(t,n);throw"unknown how to validate"}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function y(t,e){const n=[];for(const e of t.lst)if(e.tvs.values){const t=e.tvs.isnot?"!=":"=";for(const r of e.tvs.values){const o=isNaN(r.key)?`"${r.key}"`:Number(r.key);n.push(`INFO/${e.tvs.term.id}${t}${o}`)}}else{if(!e.tvs.ranges)throw`unknown tvs spec for info_field: type=${e.type}, term.id=${e.tvs.term.id}`;for(const t of e.tvs.ranges)"start"in t&&n.push(`INFO/${e.tvs.term.id} ${t.startinclusive?">=":">"} ${t.start}`),"stop"in t&&n.push(`INFO/${e.tvs.term.id} ${t.stopinclusive?"<=":"<"} ${t.stop}`)}0!=n.length&&e.push("-i",n.join(" && "))}},8907:(t,e,n)=>{"use strict";n.d(e,{yT:()=>M,YG:()=>C,g5:()=>S,J4:()=>N,B9:()=>k,cf:()=>x,tt:()=>q,Bi:()=>A,ig:()=>j});var r={};n.r(r),n.d(r,{binary:()=>f,continuous:()=>l,cubicSpline:()=>c,discrete:()=>u});var o={};n.r(o),n.d(o,{groupset:()=>p,values:()=>d});var i={};n.r(i),n.d(i,{binary:()=>g,cox:()=>v,cuminc:()=>y,discrete:()=>m});var s=n(4048),a=n(5257);const l={getCTE(t,e,n,r,o,i,s){o.push(e.id);const a=M(e,r);return o.push(...a.values),{sql:`${t} AS (\n\t\t\t\tSELECT \n\t\t\t\t\tsample,\n\t\t\t\t\tvalue as key, \n\t\t\t\t\tvalue\n\t\t\t\tFROM anno_${e.type}\n\t\t\t\tWHERE term_id=? ${a.clause}\n\t\t\t)`,tablename:t}}},c=l,u={getCTE(t,e,n,r,o,i,s){o.push(e.id);const a=C(r,e,n,i,s),l=[],c=new Map;r.bin_size;for(const t of a)!("name"in t)&&t.label&&(t.name=t.label),c.set(t.name,t),l.push(`SELECT '${t.name}' AS name,\n\t\t\t\t${null==t.start?0:t.start} AS start,\n\t\t\t\t${null==t.stop?0:t.stop} AS stop,\n\t\t\t\t0 AS unannotated,\n\t\t\t\t${t.startunbounded?1:0} AS startunbounded,\n\t\t\t\t${t.stopunbounded?1:0} AS stopunbounded,\n\t\t\t\t${t.startinclusive?1:0} AS startinclusive,\n\t\t\t\t${t.stopinclusive?1:0} AS stopinclusive`);const u=[];if(e.values)for(const t in e.values){const n=e.values[t].uncomputable;if(r.computableValuesOnly&&n)continue;if(!r.computableValuesOnly&&!n)continue;u.push(t);const o=e.values[t];l.push(`SELECT '${o.label}' AS name,\n\t ${t} AS start,\n\t 0 AS stop,\n\t 1 AS unannotated,\n\t 0 AS startunbounded,\n\t 0 AS stopunbounded,\n\t 0 AS startinclusive,\n\t 0 AS stopinclusive`),c.set(o.label,{is_unannotated:!0,value:t,label:o.label})}const f="bin_defs_"+i,d=M(e,r,"a");o.push(...d.values);return{sql:`${f} AS (\n\t\t\t\t${l.join("\nUNION ALL\n")}\n\t\t\t),\n\t\t\t${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tb.name AS key,\n\t\t\t\t\tvalue\n\t\t\t\tFROM\n\t\t\t\t\tanno_${e.type} a\n\t\t\t\tJOIN ${f} b ON\n\t\t\t\t\t( b.unannotated=1 AND value=b.start )\n\t\t\t\t\tOR\n\t\t\t\t\t(\n\t\t\t\t\t\tb.unannotated=0 AND\n\t\t\t\t\t\t${u.length?"value NOT IN ("+u.join(",")+") AND":""}\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.startunbounded = 1\n\t\t\t\t\t\t\tOR value > b.start\n\t\t\t\t\t\t\tOR (b.startinclusive=1 AND value = b.start)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.stopunbounded\n\t\t\t\t\t\t\tOR value < b.stop\n\t\t\t\t\t\t\tOR (b.stopinclusive=1 AND value = b.stop)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\tWHERE\n\t\t\t\tterm_id=? ${d.clause}\n\t\t\t)`,tablename:t,name2bin:c,bins:a}}},f=u,d={getCTE(t,e,n,r,o){o.push(e.id);const i=M(e,r);return o.push(...i.values),{sql:`${t} AS (\n\t\t\t\tSELECT sample,value as key, value as value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id=? ${i.clause}\n\t\t\t)`,tablename:t}}};let h=0;const p={async getCTE(t,e,n,r,o,i){if(!i.groups)throw`.groups[] missing from a group-set, term.id='${e.id}'`;const s=[],a=[];for(const t of i.groups)if("values"==t.type)s.push(`SELECT sample, ? as key, value\n\t\t\t\t\tFROM anno_categorical a\n\t\t\t\t\tWHERE term_id=?\n\t\t\t\t\t\tAND value IN (${t.values.map((t=>"?")).join(",")})\n\t\t\t\t`),o.push(t.name,e.id,...t.values.map((t=>t.key.toString())));else{if("filter"!=t.type)throw`unsupported groupset type='${t.type}'`;if(!("activeCohort"in r.groupsetting)||!t.filter4activeCohort)throw`activeCohort error: cannot construct filter statement for group name='${t.name}', term.id=${e.id}`;{const i=t.filter4activeCohort[r.groupsetting.activeCohort],l=await getFilterCTEs(i,n,"xf"+h++);if(!l)throw`unable to construct a group='${t.name}' filter for term.id='${e.id}'`;a.push(l.filters),o.push(...l.values.slice(),t.name,t.name),s.push(`SELECT sample, ? AS key, ? AS value\n\t\t\t\t\t\tFROM ${l.CTEname}`)}}return{sql:`${a.length?a.join("\n,")+",":""}\n\t\t\t${t} AS (\n\t\t\t\t${s.join("\nUNION ALL\n")}\n\t\t\t)`,tablename:t}}},m={getCTE(t,e,n,r,o){if(r.breaks&&r.breaks.length>0)return w(t,e,r,o);{const[n,i]=b(r);o.push(e.id);const s=M(e,r);return o.push(...s.values),{sql:`${t} AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tsample,\n\t\t\t\t\t\tvalue as key,\n\t\t\t\t\t\tvalue\n\t\t\t\t\tFROM\n\t\t\t\t\t\t${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tterm_id = ?\n\t\t\t\t\t\tAND ${i} = 1\n\t\t\t\t\t\t${s.clause}\n\t\t\t\t)`,tablename:t}}}},g={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"binary mode requires one break";return w(t,e,r,o)}},y={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"cuminc mode requires one break";return o.push(e.id,r.breaks[0]),{sql:`${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\ttime AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cuminc\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:t}}},v={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"cox mode requires one break";o.push(e.id,r.breaks[0]);const s=Object.keys(e.values).map(Number),a=Math.max(...s);return{sql:`${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\tjson_object('age_start', age_start, 'age_end', age_end) AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cox\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:t,events:[{event:1,label:`Event (grade ${r.breaks[0]===a?r.breaks[0]:`${r.breaks[0]}-${a}`})`},{event:0,label:"Censored/death"},{event:-1,label:"Event before entry into the cohort"}]}}};function b(t){const e=t.bar_by_children?"child":t.bar_by_grade?"grade":"";if(!e)throw"must set the bar_by_grade or bar_by_children query parameter";const n=t.value_by_max_grade?"max_grade":t.value_by_most_recent?"most_recent":t.value_by_computable_grade?"computable_grade":"";if(!n)throw"must set a valid value_by_*";return[e,n]}function w(t,e,n,r){const[o,i]=b(n);if("grade"!=o)throw"breaks must be used on grade values";const s=[];for(const t of n.groups)s.push(`SELECT sample, ? as key, value\n\t\t\tFROM precomputed_chc_grade\n\t\t\tWHERE\n\t\t\t\tterm_id=?\n\t\t\t\tAND ${i}=1\n\t\t\t\tAND value IN (${t.values.map((t=>"?")).join(",")})\n\t\t`),r.push(t.name,e.id,...t.values.map((t=>t.toString())));return{sql:`${t} AS (\n\t\t\t${s.join("\nUNION ALL\n")}\n\t\t)`,tablename:t}}const _={getCTE(t,e,n){let r,o,i="";for(const[t,s]of e.q.groups.entries())"in"in s||(s.in=!0),r=s.values.map((t=>t.sampleId)),o=r.map((()=>"?")).join(","),i+=`SELECT id as sample, ? as key, ? as value\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE sample ${s.in?"":"NOT"} IN (${o})\n\t\t\t`,t!=e.q.groups.length-1&&(i+="UNION ALL "),n.push(s.name,s.name,...r);return{sql:`${t} AS (${i})`,tablename:t}}};n(334),n(3345);async function x(t,e,n=!1){const r=await(0,a.w)(t,e),o=e.cohort.db.connection.prepare(r?`WITH ${r.filters} SELECT sample as id, name FROM ${r.CTEname} join sampleidmap on sample = sampleidmap.id`:"SELECT id, name FROM sampleidmap");let i;if(i=r?o.all(r.values):o.all(),n)return i;for(const t of i)delete t.name;return i}async function k(t,e){if(!t.filter)throw"filter missing";let n;if("object"==typeof t.filter)n=t.filter;else{if("string"!=typeof t.filter)throw"q.filter not obj or str";n=JSON.parse(t.filter)}const r=await(0,a.w)(n,e),o=`WITH ${r.filters}\n\t\tSELECT 'FILTERED_COHORT' as subcohort, count(distinct sample) as samplecount \n\t\tFROM ${r.CTEname}`;return e.cohort.db.connection.prepare(o).all(r.values)}async function q(t){const e=t.ds.cohort.termdb.q.termjsonByOneid(t.term_id);if("integer"!=e.type&&"float"!=e.type)throw"term is not numeric";if(!e.values)return[];const n=await(0,a.w)(t.filter,t.ds),r=n?n.values.slice():[];r.push(t.term_id);const o=[];for(const t in e.values)o.push("?"),r.push(Number(t));const i=`\n\t\t${n?"WITH "+n.filters:""}\n\t\tSELECT count(sample) AS samplecount,value\n\t\tFROM anno_${e.type}\n\t\tWHERE term_id=?\n\t\t${n?"AND sample IN "+n.CTEname:""}\n\t\tAND value IN (${o.join(",")})\n\t\tGROUP BY value`;return t.ds.cohort.db.connection.prepare(i).all(r)}async function N(t){if(!t.key)throw".key missing";if(!t.ds)throw".ds{} missing";const e=await(0,a.w)(t.filter,t.ds),n=e?e.values.slice():[],r=t.ds.cohort.termdb.q.termjsonByOneid(t.key);n.push(t.key);const o=`\n\t\t${e?"WITH "+e.filters:""}\n\t\tSELECT sample, value\n\t\tFROM anno_${r.type}\n\t\tWHERE term_id=?\n\t\t${e?" AND sample IN "+e.CTEname:""}`;return t.ds.cohort.db.connection.prepare(o).all(n)}async function S(t,e={}){"string"==typeof t.filter&&(t.filter=JSON.parse(decodeURIComponent(t.filter)));const n=Object.assign({withCTEs:!0,columnas:"t1.sample AS sample",groupby:""},e),r=await(0,a.w)(t.filter,t.ds),o=r?r.values.slice():[],i=await A(t,o,0,r),s=await A(t,o,1,r),l=await A(t,o,2,r),c=[i,s,l].map(((t,e)=>`\n\t\tSELECT sample, key, value, ${e} as termNum\n\t\tFROM ${t.tablename}\n\t\t${r?"WHERE sample IN "+r.CTEname:""}\n\t`)).join("\nUNION ALL\n"),u=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${i.sql},\n\t\t${s.sql},\n\t\t${l.sql}\n\t\t${c}`;try{const e=t.ds.cohort.db.connection.prepare(u).all(o),a=new Map;for(const t of e){a.has(t.sample)||a.set(t.sample,{sample:t.sample});const e=a.get(t.sample),n=`key${t.termNum}`;n in e||(e[n]=[]),e[n].push(t)}const c=[],f=new Map;for(const e of a.values())if("key1"in e){if(t.term0_q&&t.term0_id){if(!("key0"in e))continue}else e.key0=[{key:"",value:""}];if(t.term2_q&&(t.term2_id||"samplelst"===t.term2.type)){if(!("key2"in e))continue}else e.key2=[{key:"",value:""}];e.rows=[];for(const t of e.key0)for(const n of e.key1)for(const r of e.key2)e.rows.push({sample:e.sample,key0:t.key,val0:t.value,key1:n.key,val1:n.value,key2:r.key,val2:r.value});for(const t of e.rows)if(n.groupby){if(!f.has(t[n.groupby])){const e=Object.assign({samplecount:0},t);c.push(e),f.set(t[n.groupby],e)}f.get(t[n.groupby]).samplecount++}else c.push(t)}return n.withCTEs?{lst:c,CTE0:i,CTE1:s,CTE2:l,filter:r}:c}catch(t){throw console.log("error in sql:\n",j(u,o)),t}}async function A(t,e,n,s,a=null){const l=a&&a.term||t[`term${n}`],c=l?l.id:t["term"+n+"_id"];if("samplelst"!=(null==l?void 0:l.type))if(a||1!=n){if(!c){const t="samplekey_"+n;return{tablename:t,sql:`${t} AS (\nSELECT null AS sample, '' as key, '' as value\n)`}}}else if(!c)throw"missing term1 id";const u=l&&l.type?l:t.ds.cohort.termdb.q.termjsonByOneid(c);if(!u)throw`no term found by id='${c}'`;let f=a&&a.q||t["term"+n+"_q"]||{};"string"==typeof f&&(f=JSON.parse(decodeURIComponent(f)));const d="samplekey_"+n;let h;if("categorical"==u.type){const n=T(u,f);h=await o[n?"groupset":"values"].getCTE(d,u,t.ds,f,e,n)}else if("integer"==u.type||"float"==u.type){const o="spline"==f.mode?"cubicSpline":f.mode||"discrete";h=await r[o].getCTE(d,u,t.ds,f,e,n,s)}else if("condition"==u.type){const n=f.mode||"discrete";h=await i[n].getCTE(d,u,t.ds,f,e)}else if("survival"==u.type)h=function(t,e,n,r,o){return r.push(e.id),{sql:`${t} AS (\n\t\t\tSELECT sample, exit_code as key, tte AS value\n\t\t\tFROM survival s\n\t\t\tWHERE s.term_id=?\n\t\t\t${o?"AND s.sample IN "+o.CTEname:""}\n\t\t)`,tablename:t}}(d,u,0,e,s);else{if("samplelst"!=u.type)throw"unknown term type";h=await _.getCTE(d,a||{term:u,q:f},e)}return h}function M(t,e,n=""){if(!t.values||!e.computableValuesOnly)return{values:[],clause:""};const r=Object.keys(t.values).filter((e=>t.values[e].uncomputable)),o=n?`${n}.value`:"value";return{values:r,clause:r.length?`AND ${o} NOT IN (${r.map((()=>"?")).join(",")})`:""}}function T(t,e){if(e.groupsetting&&!e.groupsetting.disabled&&e.groupsetting.inuse){if(Number.isInteger(e.groupsetting.predefined_groupset_idx)){if(e.groupsetting.predefined_groupset_idx<0)throw"q.predefined_groupset_idx out of bound";if(!t.groupsetting)throw"term.groupsetting missing when q.predefined_groupset_idx in use";if(!t.groupsetting.lst)throw"term.groupsetting.lst missing when q.predefined_groupset_idx in use";const n=t.groupsetting.lst[e.groupsetting.predefined_groupset_idx];if(!n)throw"q.predefined_groupset_idx out of bound";return n}if(e.groupsetting.customset)return e.groupsetting.customset;throw"do not know how to get groupset"}}function C(t,e,n,r,o){if("continuous"!=t.mode&&"spline"!=t.mode)return s.gp(t,(t=>function(t,e,n,r=[]){const o=[];n&&o.push(...n.values);o.push(e.id);const i=e.values?Object.keys(e.values).filter((t=>e.values[t].uncomputable)):[],s=[],a=[],l=[];let c;for(const t of r)c="pct_"+t,s.push(`\n\t\t${c} AS (\n\t\t SELECT value\n\t\t FROM vals\n\t\t LIMIT 1\n\t\t OFFSET (\n\t\t SELECT cast ( x as int ) - ( x < cast ( x as int ))\n\t\t FROM (\n\t\t SELECT cast(?*pct as int) as x \n\t\t FROM p\n\t\t )\n\t\t )\n\t\t)`),o.push(t),a.push(c),l.push(`${c}.value AS ${"p"+t}`);const u=`WITH\n\t\t${n?n.filters+", ":""} \n\t\tvals AS (\n\t\t\tSELECT value\n\t\t\tFROM anno_${e.type}\n\t\t\tWHERE\n\t\t\t${n?"sample IN "+n.CTEname+" AND ":""}\n\t\t\tterm_id=?\n\t\t\t${i.length?"AND value NOT IN ("+i.join(",")+")":""}\n\t\t\tORDER BY value ASC\n\t\t),\n\t\tp AS (\n\t\t\tSELECT count(value)/100 as pct\n\t\t\tFROM vals\n\t\t)\n\t\t${s.length?",\n"+s.join(","):""}\n\t\tSELECT \n\t\t\tmin(vals.value) as vmin,\n\t\t\tmax(vals.value) as vmax\n\t\t\t${l.length?",\n"+l.join(",\n"):""} \n\t\tFROM vals ${a.length?","+a.join(","):""}`,f=t.cohort.db.connection.prepare(u).all(o),d=f.length?f[0]:{};return d.max=f[0].vmax,d.min=f[0].vmin,d}(n,e,o,t)))}function j(t,e){const n=e.slice();let r;return t.split("").map((t=>{if("?"==t){r=t;const e=n.shift();return"string"==typeof e?`'${e}'`:e}return"\t"==t?"":"\n"!=t&&" "!=t||r!==t?(r=t,t):""})).join("")}},3345:(t,e,n)=>{"use strict";n.d(e,{Dp:()=>V,JC:()=>et,d1:()=>A,sE:()=>B,Ic:()=>E,yE:()=>P,t7:()=>F,ZX:()=>M,EO:()=>J,Kf:()=>U,ZD:()=>D,UE:()=>L,lY:()=>C,_H:()=>O,L0:()=>W,Y5:()=>tt,z5:()=>Y,mr:()=>K,b5:()=>z,cl:()=>H,Jy:()=>R,sI:()=>X,aS:()=>Q,LC:()=>I,Sf:()=>$,tG:()=>Z});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(2081),l=n(4521),c=n.n(l),u=n(2273),f=n(6819);const d=require("node-fetch");var h=n.n(d);const p=require("better-sqlite3");var m=n.n(p),g=n(334),y=n.n(g);n(2781);const v=require("minimatch");var b=n.n(v);const w=y(),{tabix:_,samtools:x,bcftools:k,bigBedToBed:q,bigBedNamedItems:N,bigBedInfo:S}=w;async function A(t,e){if(!t)throw".gz file URL missing";if("string"!=typeof t)throw".gz file URL not string";if(e&&"string"!=typeof e)throw"index URL not string";const[n,r,i]=j(t);if(n)throw".gz file URL error: "+n;const a=s().join(w.cachedir,r,i);try{await o().promises.stat(a)}catch(n){if("ENOENT"!=n.code)throw"stating gz url dir: "+n.code;try{await o().promises.mkdir(a,{recursive:!0})}catch(n){throw"url dir: cannot mkdir"}}if(!e)return a;{const[t,r,i]=j(e);if(t)throw"indexl url error: "+t;const l=s().join(a,s().basename(i));try{return await o().promises.stat(l),a}catch(n){if("ENOENT"==n.code)return await async function(t,e){try{const i=await h()(t);if(200!=i.status)throw"index file not accessible from url with status code "+i.status;await(n=i.body,r=e,new Promise(((t,e)=>{const i=o().createWriteStream(r);n.pipe(i),n.on("end",(()=>t()))})))}catch(t){throw"cannot download from url"}var n,r}(e,l),a;throw"stating indexl url file: "+n.code}}}function M(t,e=!0){let n=null,r=!1;if(t.query.file){if(n=t.query.file,C(n,e,!1))return["illegal file path"];n=s().join(w.tpmasterdir,n)}else if(t.query.url){if(n=t.query.url,n.includes(" "))return["url must not contain whitespace"];if(n.includes('"')||n.includes("'"))return["url must not contain single or double quotes"];r=!0}return n?[null,n,r]:["file unspecified"]}const T=Object.freeze([".bam",".bai",".gz",".tbi",".csi",".bw",".bb"]);function C(t,e=!1,n=!0){if("/"==t[0])return!0;if(t.includes('"')||t.includes("'"))return!0;if(t.includes("|")||t.includes("&"))return!0;if(t.includes(" "))return!0;if(-1!=t.indexOf(".."))return!0;if(t.match(/(\<script|script\>)/i))return!0;if(e&&w.whiteListPaths){let e=!0;for(const n of w.whiteListPaths){if(t.startsWith(n)||"!"!=n[0]&&b()(t,n)){e=!1;break}if("!"==n[0]&&!b()(t,n)){e=!0;break}}if(e)return!0}if(n)for(const e of T)if(e===s().extname(t).toLowerCase())return!0;return!1}function j(t){const e=t.split("://");return 2!=e.length?["improper url"]:e[0].length<3?["protocol string length too short"]:e[1].length<5?["body string length too short"]:[null,e[0],e[1]]}async function E(t){try{await o().promises.stat(t)}catch(e){const n=w.debugmode?`file='${t}'`:"";if("EACCES"==e.code)throw`Permission denied ${n}`;if("ENOENT"==e.code)throw`No such file or directory ${n}`;if("EPERM"==e.code)throw`Operation not permitted ${n}`;throw`cannot access file (' + e.code + ') ${n}`}}async function O(t,e,n){let r;if(t.file)t.file.startsWith(w.tpmasterdir)||(t.file=s().join(w.tpmasterdir,t.file)),r=t.file,await I(t.file);else{if(!t.url)throw"no file or url given for vcf file";r=t.url,t.dir=await utils.cache_index(t.url,t.indexURL)}const[o,i,l,c]=n?await(u=r,d=t.dir,new Promise(((t,e)=>{const n=(0,a.spawn)(k,["view","-h",u],{cwd:d}),r=[];n.stdout.on("data",(t=>r.push(t))),n.on("close",(()=>{t(f.e(r.join("").trim().split("\n")))}))}))):await async function(t,e){return f.e(await D(t,e))}(r,t.dir);var u,d;if(c)throw console.log(c.join("\n")),"got above errors parsing vcf";t.info=o,t.format=i,t.samples=l,await R(r,t.dir,e)&&(t.nochr=!0)}async function I(t){if(!t.endsWith(".gz"))throw"tabix file not ending with .gz";if(await P(t))throw t+" file not exist";if(await F(t))throw".gz file not readable";const e=t+".tbi";if(await P(e)){const e=t+".csi";if(await P(e))throw"neither .tbi .csi index file exist for "+t;if(await F(e))throw".csi index file not readable"}else if(await F(e))throw".tbi index file not readable"}async function R(t,e,n){const r=[];return await L({args:["-l",t],dir:e,callback:t=>{r.push(t)}}),u.contigNameNoChr(n,r)}function P(t){return new Promise(((e,n)=>{o().access(t,o().constants.F_OK,(t=>{t&&e(!0),e(!1)}))}))}function F(t){return new Promise(((e,n)=>{o().access(t,o().constants.R_OK,(t=>{t&&e(!0),e(!1)}))}))}async function D(t,e){const n=[];return await L({args:["-H",t],dir:e,callback:t=>{n.push(t)}}),n}function L({args:t,dir:e,callback:n,isbcf:r,isbam:o}){if(!t)throw"args is missing";if(!Array.isArray(t))throw"args[] is not array";if(0==t.length)throw"args[] empty array";if(!n)throw"callback is missing";if("function"!=typeof n)throw"callback() not a function";return new Promise(((i,s)=>{const l=(0,a.spawn)(r?k:o?x:_,t,{cwd:e}),u=c().createInterface({input:l.stdout}),f=[];u.on("line",(t=>n(t,l))),l.stderr.on("data",(t=>f.push(t))),l.on("close",(()=>{const t=f.join("").trim();t&&!X(t)&&s(t),i()}))}))}function $(t,e){return new Promise(((n,r)=>{o().writeFile(t,e,(t=>{t&&r("cannot write"),n()}))}))}async function Z(t){const e=Math.random().toString();return await $(s().join(w.cachedir,e),t),e}function z(t){return new Promise(((e,n)=>{o().readFile(t,{encoding:"utf8"},((r,o)=>{r&&n("cannot read file: "+t),e(o)}))}))}async function U(t,e){if("NA"==t.genomefile){const t=e.split(/[:-]/),n=[];for(let e=Number(t[1]);e<=Number(t[2]);e++)n.push("N");return`>${e}\n${n.join("")}`}const n=[];return await L({isbam:!0,args:["faidx",t.genomefile,e],callback:t=>n.push(t)}),n.join("\n")}function B(t,e={}){const n="/"==t[0]?t:s().join(w.tpmasterdir,t);try{return new(m())(n,Object.assign({readonly:!0,fileMustExist:!0},e))}catch(t){throw`error connecting to ${n}: ${t}`}}const G=new Set(["Homozygous reference","Homozygous alternative","Heterozygous"]),J={href:"Homozygous reference",halt:"Homozygous alternative",het:"Heterozygous"};async function W(t,e){const n=await z(s().join(w.cachedir_ssid,t)),r=new Map,o=new Map;for(const t of n.trim().split("\n")){if(!t)continue;const[n,i]=t.split("\t");if(!i)continue;if(!G.has(n))throw"unknown hardcoded genotype label: "+n;const s=i.split(",").map((t=>Number(t))),a=e?s.filter((t=>e.has(t))):s;for(const t of a)r.set(t,n);o.set(n,new Set(a))}return[r,o]}function H(t){return t.replace(/\<script|\bon[\w]{1,38}\b[\ \t\n]*\=/gi," _")}async function V(t,e,n){const r=[];if(await L({isbam:!0,args:["view","-H",t],dir:n,callback:t=>r.push(t)}),0==r.length)throw"cannot list bam header lines";const o=[];for(const t of r){if(!t.startsWith("@SQ"))continue;const e=t.split("\t")[1];e||reject("2nd field missing from @SQ line");const n=e.split(":");"SN"!=n[0]&&reject('@SQ line 2nd field is not "SN" but '+n[0]),n[1]||reject("@SQ line no value for SN"),o.push(n[1])}return u.contigNameNoChr(e,o)}function Y(t,e,n,r){return new Promise(((o,i)=>{const s=(0,a.spawn)(q,[`-chrom=${e}`,`-start=${n}`,`-end=${r}`,t,"stdout"]),l=[],c=[];s.stdout.on("data",(t=>l.push(t))),s.stderr.on("data",(t=>c.push(t))),s.on("close",(t=>{0!==t&&i(`bigBed query exited with non-zero status and this standard error:\n${c.join("")}`),c.length>0&&i(c.join(""));const e=l.join("").trim();o(e?e.split("\n"):[])}))}))}function K(t,e){return new Promise(((n,r)=>{const o=(0,a.spawn)(N,[t,e,"stdout"]),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(t=>{0!==t&&r(`bigBed query exited with non-zero status and this standard error:\n${s.join("")}`),s.length>0&&r(s.join(""));const e=i.join("").trim();n(e?e.split("\n"):[])}))}))}function X(t){return t.startsWith("[E::idx_test_and_fetch]")}async function Q(t){return new Promise(((e,n)=>{const r=(0,a.spawn)(S,[t]),o=[],i=[];r.stdout.on("data",(t=>o.push(t))),r.stderr.on("data",(t=>i.push(t))),r.on("close",(t=>{const n=i.join("");n&&(n.includes("is not a big bed file")||n.includes("Couldn't open"),e(!1));o.join("").trim().startsWith("version")&&e(!0)}))}))}function tt(t,e){if(e.sessionid){if("sessionid"in t)throw"q.sessionid already exists so cannot copy from cookies.sessionid";t.sessionid=e.sessionid}}function et(t){const e=t.length;if(e<5)return{out:t};const n=t[Math.floor(e/2)].value,r=t[Math.floor(e/4)].value,o=t[Math.floor(3*e/4)].value,i=t[Math.floor(.05*e)].value,s=t[Math.floor(.95*e)].value,a=(t[Math.floor(.01*e)].value,o-r);let l,c;if(0==a)l=0,c=0;else{const n=t.findIndex((t=>t.value>r-1.5*a));l=t[-1==n?0:n].value;const i=t.findIndex((t=>t.value>o+1.5*a));c=t[-1==i?e-1:i-1].value}const u=t.filter((t=>t.value<r-1.5*a||t.value>o+1.5*a));return{w1:l,w2:c,p05:i,p25:r,p50:n,p75:o,p95:s,iqr:a,out:u}}},3625:(t,e,n)=>{"use strict";n.d(e,{H:()=>a});var r=n(9380),o=n(4298),i=n(736),s=n(2273);function a(t,e,n,a,l,c,u){var f;const d=(0,r.w)(l);for(const e in t.info){if("A"==t.info[e].Number&&e in d&&(d[e]=d[e].split(",")),t.info[e].separator&&e in d){const n=d[e].split(t.info[e].separator);n.length>1&&(d[e]=n)}if("Float"==t.info[e].Type||"Integer"==t.info[e].Type)if(Array.isArray(d[e])){const t=d[e].map(Number);d[e]=t}else d[e]=Number(d[e])}a.mlst=n.map((t=>{const[n,r,o]=function(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substring(0,e.length-1),n=n.substring(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substring(1),n=n.substring(1),t++;return[t,e,n]}(a.pos,e,t),s={allele_original:t,ref:r,alt:o,pos:n,type:(0,i.P)(r,o)};return c&&"."!=c&&(s.vcf_id=c),s})),null!==(f=t.info)&&void 0!==f&&f.CSQ&&d.CSQ&&(0,o.A)(d.CSQ,t.info.CSQ.csqheader,a);const h={};u&&(h.usegm={isoform:u});for(const[n,r]of a.mlst.entries()){(0,s.vcfcopymclass)(r,h),delete r.csq,r.mname||(r.mname="."!=c?c:a.pos+":"+e+">"+r.allele_original),r.altAlleleIdx=n+1,r.info={};for(const e in d){var p,m;"A"==(null===(p=t.info)||void 0===p||null===(m=p[e])||void 0===m?void 0:m.Number)?r.info[e]=d[e][n]:r.info[e]=d[e]}}}},126:(t,e,n)=>{var r={"./burden":5037,"./burden.ts":5037,"./gdc.maf":2538,"./gdc.maf.ts":2538,"./gdc.mafBuild":86,"./gdc.mafBuild.ts":86,"./gdc.topMutatedGenes":889,"./gdc.topMutatedGenes.ts":889,"./gdc.topVariablyExpressedGenes":449,"./gdc.topVariablyExpressedGenes.ts":449,"./genelookup":3202,"./genelookup.ts":3202,"./healthcheck":1746,"./healthcheck.ts":1746,"./hicdata":3932,"./hicdata.ts":3932,"./hicstat":6310,"./hicstat.ts":6310,"./termdb.categories":5852,"./termdb.categories.ts":5852,"./termdb.getpercentile":2630,"./termdb.getpercentile.ts":2630,"./termdb.singlecellData":5707,"./termdb.singlecellData.ts":5707,"./termdb.singlecellSamples":7934,"./termdb.singlecellSamples.ts":7934,"./termdb.termbyid":7071,"./termdb.termbyid.ts":7071,"./termdb.violin":1485,"./termdb.violin.ts":1485};function o(t){var e=i(t);return n(e)}function i(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}o.keys=function(){return Object.keys(r)},o.resolve=i,t.exports=o,o.id=126},1271:t=>{"use strict";t.exports=require("@sjcrh/proteinpaint-rust")},6718:t=>{"use strict";t.exports=require("canvas")},6452:t=>{"use strict";t.exports=require("got")},7219:t=>{"use strict";t.exports=require("image-size")},9344:t=>{"use strict";t.exports=require("jsonwebtoken")},8088:t=>{"use strict";t.exports=require("micromatch")},6464:t=>{"use strict";t.exports=require("util")},2081:t=>{"use strict";t.exports=require("child_process")},7147:t=>{"use strict";t.exports=require("fs")},1017:t=>{"use strict";t.exports=require("path")},4521:t=>{"use strict";t.exports=require("readline")},2781:t=>{"use strict";t.exports=require("stream")},9263:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:t<e?-1:t>e?1:t>=e?0:NaN}n.d(e,{Z:()=>r})},5519:(t,e,n)=>{"use strict";n.d(e,{Nw:()=>l,ZP:()=>u,ZR:()=>c,ml:()=>a});var r=n(9263),o=n(3292),i=n(3745);const s=(0,o.Z)(r.Z),a=s.right,l=s.left,c=(0,o.Z)(i.Z).center,u=a},3292:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(9263),o=n(788);function i(t){let e,n,i;function a(t,r,o=0,i=t.length){if(o<i){if(0!==e(r,r))return i;do{const e=o+i>>>1;n(t[e],r)<0?o=e+1:i=e}while(o<i)}return o}return 2!==t.length?(e=r.Z,n=(e,n)=>(0,r.Z)(t(e),n),i=(e,n)=>t(e)-n):(e=t===r.Z||t===o.Z?t:s,n=t,i=t),{left:a,center:function(t,e,n=0,r=t.length){const o=a(t,e,n,r-1);return o>n&&i(t[o-1],e)>-i(t[o],e)?o-1:o},right:function(t,r,o=0,i=t.length){if(o<i){if(0!==e(r,r))return i;do{const e=o+i>>>1;n(t[e],r)<=0?o=e+1:i=e}while(o<i)}return o}}}function s(){return 0}},1045:(t,e,n)=>{"use strict";function r(t,e){if(!((e=+e)>=0))throw new RangeError("invalid r");let n=t.length;if(!((n=Math.floor(n))>=0))throw new RangeError("invalid length");if(!n||!e)return t;const r=c(e),o=t.slice();return r(t,o,0,n,1),r(o,t,0,n,1),r(t,o,0,n,1),t}n.d(e,{TX:()=>i,u8:()=>o,yv:()=>r});const o=s(c),i=s((function(t){const e=c(t);return(t,n,r,o,i)=>{e(t,n,(r<<=2)+0,(o<<=2)+0,i<<=2),e(t,n,r+1,o+1,i),e(t,n,r+2,o+2,i),e(t,n,r+3,o+3,i)}}));function s(t){return function(e,n,r=n){if(!((n=+n)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:o,width:i,height:s}=e;if(!((i=Math.floor(i))>=0))throw new RangeError("invalid width");if(!((s=Math.floor(void 0!==s?s:o.length/i))>=0))throw new RangeError("invalid height");if(!i||!s||!n&&!r)return e;const c=n&&t(n),u=r&&t(r),f=o.slice();return c&&u?(a(c,f,o,i,s),a(c,o,f,i,s),a(c,f,o,i,s),l(u,o,f,i,s),l(u,f,o,i,s),l(u,o,f,i,s)):c?(a(c,o,f,i,s),a(c,f,o,i,s),a(c,o,f,i,s)):u&&(l(u,o,f,i,s),l(u,f,o,i,s),l(u,o,f,i,s)),e}}function a(t,e,n,r,o){for(let i=0,s=r*o;i<s;)t(e,n,i,i+=r,1)}function l(t,e,n,r,o){for(let i=0,s=r*o;i<r;++i)t(e,n,i,i+s,r)}function c(t){const e=Math.floor(t);if(e===t)return function(t){const e=2*t+1;return(n,r,o,i,s)=>{if(!((i-=s)>=o))return;let a=t*r[o];const l=s*t;for(let t=o,e=o+l;t<e;t+=s)a+=r[Math.min(i,t)];for(let t=o,c=i;t<=c;t+=s)a+=r[Math.min(i,t+l)],n[t]=a/e,a-=r[Math.max(o,t-l)]}}(t);const n=t-e,r=2*t+1;return(t,o,i,s,a)=>{if(!((s-=a)>=i))return;let l=e*o[i];const c=a*e,u=c+a;for(let t=i,e=i+c;t<e;t+=a)l+=o[Math.min(s,t)];for(let e=i,f=s;e<=f;e+=a)l+=o[Math.min(s,e+c)],t[e]=(l+n*(o[Math.max(i,e-u)]+o[Math.min(s,e+u)]))/r,l-=o[Math.max(i,e-c)]}}},879:(t,e,n)=>{"use strict";function r(t,e){let n=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&++n;else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(o=+o)>=o&&++n}return n}n.d(e,{Z:()=>r})},788:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:e<t?-1:e>t?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},2038:(t,e,n)=>{"use strict";function r(t,e){let n,r;if(void 0===e)for(const e of t)null!=e&&(void 0===n?e>=e&&(n=r=e):(n>e&&(n=e),r<e&&(r=e)));else{let o=-1;for(let i of t)null!=(i=e(i,++o,t))&&(void 0===n?i>=i&&(n=r=i):(n>i&&(n=i),r<i&&(r=i)))}return[n,r]}n.d(e,{Z:()=>r})},9343:(t,e,n)=>{"use strict";n.d(e,{Kd:()=>i,dU:()=>r,e3:()=>o});class r{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const e=this._partials;let n=0;for(let r=0;r<this._n&&r<32;r++){const o=e[r],i=t+o,s=Math.abs(t)<Math.abs(o)?t-(i-o):o-(i-t);s&&(e[n++]=s),t=i}return e[n]=t,this._n=n+1,this}valueOf(){const t=this._partials;let e,n,r,o=this._n,i=0;if(o>0){for(i=t[--o];o>0&&(e=i,n=t[--o],i=e+n,r=n-(i-e),!r););o>0&&(r<0&&t[o-1]<0||r>0&&t[o-1]>0)&&(n=2*r,e=i+n,n==e-i&&(i=e))}return i}}function o(t,e){const n=new r;if(void 0===e)for(let e of t)(e=+e)&&n.add(e);else{let r=-1;for(let o of t)(o=+e(o,++r,t))&&n.add(o)}return+n}function i(t,e){const n=new r;let o=-1;return Float64Array.from(t,void 0===e?t=>n.add(+t||0):r=>n.add(+e(r,++o,t)||0))}},2942:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(9263);function o(t,e=r.Z){let n,o=!1;if(1===e.length){let i;for(const s of t){const t=e(s);(o?(0,r.Z)(t,i)>0:0===(0,r.Z)(t,t))&&(n=s,i=t,o=!0)}}else for(const r of t)(o?e(r,n)>0:0===e(r,r))&&(n=r,o=!0);return n}},9060:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>y.dU,InternMap:()=>v.L,InternSet:()=>v.H,ascending:()=>o.Z,bin:()=>L,bisect:()=>r.ZP,bisectCenter:()=>r.ZR,bisectLeft:()=>r.Nw,bisectRight:()=>r.ml,bisector:()=>i.Z,blur:()=>s.yv,blur2:()=>s.u8,blurImage:()=>s.TX,count:()=>a.Z,cross:()=>f,cumsum:()=>d,descending:()=>h.Z,deviation:()=>m,difference:()=>_t,disjoint:()=>xt,every:()=>mt,extent:()=>g.Z,fcumsum:()=>y.Kd,filter:()=>yt,flatGroup:()=>k,flatRollup:()=>q,fsum:()=>y.e3,greatest:()=>st.Z,greatestIndex:()=>at,group:()=>w,groupSort:()=>E,groups:()=>_,histogram:()=>L,index:()=>A,indexes:()=>M,intersection:()=>kt,least:()=>ot,leastIndex:()=>it,map:()=>vt,max:()=>U.Z,maxIndex:()=>B.Z,mean:()=>G,median:()=>J,medianIndex:()=>W,merge:()=>H.Z,min:()=>V.Z,minIndex:()=>Y.Z,mode:()=>K,nice:()=>F,pairs:()=>X,permute:()=>tt.Z,quantile:()=>$.ZP,quantileIndex:()=>$.Cr,quantileSorted:()=>$.s7,quickselect:()=>et.Z,range:()=>nt.Z,rank:()=>rt,reduce:()=>bt,reverse:()=>wt,rollup:()=>N,rollups:()=>S,scan:()=>lt,shuffle:()=>ct,shuffler:()=>ut,some:()=>gt,sort:()=>j.ZP,subset:()=>At,sum:()=>ft,superset:()=>Nt,thresholdFreedmanDiaconis:()=>Z,thresholdScott:()=>z,thresholdSturges:()=>D.Z,tickIncrement:()=>P.G9,tickStep:()=>P.ly,ticks:()=>P.ZP,transpose:()=>dt,union:()=>Mt,variance:()=>p,zip:()=>pt});var r=n(5519),o=n(9263),i=n(3292),s=n(1045),a=n(879);function l(t){return 0|t.length}function c(t){return!(t>0)}function u(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function f(...t){const e="function"==typeof t[t.length-1]&&function(t){return e=>t(...e)}(t.pop()),n=(t=t.map(u)).map(l),r=t.length-1,o=new Array(r+1).fill(0),i=[];if(r<0||n.some(c))return i;for(;;){i.push(o.map(((e,n)=>t[n][e])));let s=r;for(;++o[s]===n[s];){if(0===s)return e?i.map(e):i;o[s--]=0}}}function d(t,e){var n=0,r=0;return Float64Array.from(t,void 0===e?t=>n+=+t||0:o=>n+=+e(o,r++,t)||0)}var h=n(788);function p(t,e){let n,r=0,o=0,i=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(n=e-o,o+=n/++r,i+=n*(e-o));else{let s=-1;for(let a of t)null!=(a=e(a,++s,t))&&(a=+a)>=a&&(n=a-o,o+=n/++r,i+=n*(a-o))}if(r>1)return i/(r-1)}function m(t,e){const n=p(t,e);return n?Math.sqrt(n):n}var g=n(2038),y=n(9343),v=n(8828);function b(t){return t}function w(t,...e){return C(t,b,b,e)}function _(t,...e){return C(t,Array.from,b,e)}function x(t,e){for(let n=1,r=e.length;n<r;++n)t=t.flatMap((t=>t.pop().map((([e,n])=>[...t,e,n]))));return t}function k(t,...e){return x(_(t,...e),e)}function q(t,e,...n){return x(S(t,e,...n),n)}function N(t,e,...n){return C(t,b,e,n)}function S(t,e,...n){return C(t,Array.from,e,n)}function A(t,...e){return C(t,b,T,e)}function M(t,...e){return C(t,Array.from,T,e)}function T(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function C(t,e,n,r){return function t(o,i){if(i>=r.length)return n(o);const s=new v.L,a=r[i++];let l=-1;for(const t of o){const e=a(t,++l,o),n=s.get(e);n?n.push(t):s.set(e,[t])}for(const[e,n]of s)s.set(e,t(n,i));return e(s)}(t,0)}var j=n(3897);function E(t,e,n){return(2!==e.length?(0,j.ZP)(N(t,e,n),(([t,e],[n,r])=>(0,o.Z)(e,r)||(0,o.Z)(t,n))):(0,j.ZP)(w(t,n),(([t,n],[r,i])=>e(n,i)||(0,o.Z)(t,r)))).map((([t])=>t))}var O=Array.prototype,I=O.slice;O.map;function R(t){return()=>t}var P=n(6106);function F(t,e,n){let r;for(;;){const o=(0,P.G9)(t,e,n);if(o===r||0===o||!isFinite(o))return[t,e];o>0?(t=Math.floor(t/o)*o,e=Math.ceil(e/o)*o):o<0&&(t=Math.ceil(t*o)/o,e=Math.floor(e*o)/o),r=o}}var D=n(2327);function L(){var t=b,e=g.Z,n=D.Z;function o(o){Array.isArray(o)||(o=Array.from(o));var i,s,a,l=o.length,c=new Array(l);for(i=0;i<l;++i)c[i]=t(o[i],i,o);var u=e(c),f=u[0],d=u[1],h=n(c,f,d);if(!Array.isArray(h)){const t=d,n=+h;if(e===g.Z&&([f,d]=F(f,d,n)),(h=(0,P.ZP)(f,d,n))[0]<=f&&(a=(0,P.G9)(f,d,n)),h[h.length-1]>=d)if(t>=d&&e===g.Z){const t=(0,P.G9)(f,d,n);isFinite(t)&&(t>0?d=(Math.floor(d/t)+1)*t:t<0&&(d=(Math.ceil(d*-t)+1)/-t))}else h.pop()}for(var p=h.length;h[0]<=f;)h.shift(),--p;for(;h[p-1]>d;)h.pop(),--p;var m,y=new Array(p+1);for(i=0;i<=p;++i)(m=y[i]=[]).x0=i>0?h[i-1]:f,m.x1=i<p?h[i]:d;if(isFinite(a)){if(a>0)for(i=0;i<l;++i)null!=(s=c[i])&&f<=s&&s<=d&&y[Math.min(p,Math.floor((s-f)/a))].push(o[i]);else if(a<0)for(i=0;i<l;++i)if(null!=(s=c[i])&&f<=s&&s<=d){const t=Math.floor((f-s)*a);y[Math.min(p,t+(h[t]<=s))].push(o[i])}}else for(i=0;i<l;++i)null!=(s=c[i])&&f<=s&&s<=d&&y[(0,r.ZP)(h,s,0,p)].push(o[i]);return y}return o.value=function(e){return arguments.length?(t="function"==typeof e?e:R(e),o):t},o.domain=function(t){return arguments.length?(e="function"==typeof t?t:R([t[0],t[1]]),o):e},o.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?R(I.call(t)):R(t),o):n},o}var $=n(1177);function Z(t,e,n){return Math.ceil((n-e)/(2*((0,$.ZP)(t,.75)-(0,$.ZP)(t,.25))*Math.pow((0,a.Z)(t),-1/3)))}function z(t,e,n){return Math.ceil((n-e)*Math.cbrt((0,a.Z)(t))/(3.49*m(t)))}var U=n(8319),B=n(5374);function G(t,e){let n=0,r=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(++n,r+=e);else{let o=-1;for(let i of t)null!=(i=e(i,++o,t))&&(i=+i)>=i&&(++n,r+=i)}if(n)return r/n}function J(t,e){return(0,$.ZP)(t,.5,e)}function W(t,e){return(0,$.Cr)(t,.5,e)}var H=n(1740),V=n(816),Y=n(2980);function K(t,e){const n=new v.L;if(void 0===e)for(let e of t)null!=e&&e>=e&&n.set(e,(n.get(e)||0)+1);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&o>=o&&n.set(o,(n.get(o)||0)+1)}let r,o=0;for(const[t,e]of n)e>o&&(o=e,r=t);return r}function X(t,e=Q){const n=[];let r,o=!1;for(const i of t)o&&n.push(e(r,i)),r=i,o=!0;return n}function Q(t,e){return[t,e]}var tt=n(362),et=n(551),nt=n(1265);function rt(t,e=o.Z){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(t);const r=new Float64Array(n.length);2!==e.length&&(n=n.map(e),e=o.Z);const i=(t,r)=>e(n[t],n[r]);let s,a;return Uint32Array.from(n,((t,e)=>e)).sort(e===o.Z?(t,e)=>(0,j.Wv)(n[t],n[e]):(0,j.di)(i)).forEach(((t,e)=>{const n=i(t,void 0===s?t:s);n>=0?((void 0===s||n>0)&&(s=t,a=e),r[t]=a):r[t]=NaN})),r}function ot(t,e=o.Z){let n,r=!1;if(1===e.length){let i;for(const s of t){const t=e(s);(r?(0,o.Z)(t,i)<0:0===(0,o.Z)(t,t))&&(n=s,i=t,r=!0)}}else for(const o of t)(r?e(o,n)<0:0===e(o,o))&&(n=o,r=!0);return n}function it(t,e=o.Z){if(1===e.length)return(0,Y.Z)(t,e);let n,r=-1,i=-1;for(const o of t)++i,(r<0?0===e(o,o):e(o,n)<0)&&(n=o,r=i);return r}var st=n(2942);function at(t,e=o.Z){if(1===e.length)return(0,B.Z)(t,e);let n,r=-1,i=-1;for(const o of t)++i,(r<0?0===e(o,o):e(o,n)>0)&&(n=o,r=i);return r}function lt(t,e){const n=it(t,e);return n<0?void 0:n}const ct=ut(Math.random);function ut(t){return function(e,n=0,r=e.length){let o=r-(n=+n);for(;o;){const r=t()*o--|0,i=e[o+n];e[o+n]=e[r+n],e[r+n]=i}return e}}function ft(t,e){let n=0;if(void 0===e)for(let e of t)(e=+e)&&(n+=e);else{let r=-1;for(let o of t)(o=+e(o,++r,t))&&(n+=o)}return n}function dt(t){if(!(o=t.length))return[];for(var e=-1,n=(0,V.Z)(t,ht),r=new Array(n);++e<n;)for(var o,i=-1,s=r[e]=new Array(o);++i<o;)s[i]=t[i][e];return r}function ht(t){return t.length}function pt(){return dt(arguments)}function mt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(!e(r,++n,t))return!1;return!0}function gt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(e(r,++n,t))return!0;return!1}function yt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");const n=[];let r=-1;for(const o of t)e(o,++r,t)&&n.push(o);return n}function vt(t,e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof e)throw new TypeError("mapper is not a function");return Array.from(t,((n,r)=>e(n,r,t)))}function bt(t,e,n){if("function"!=typeof e)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let o,i,s=-1;if(arguments.length<3){if(({done:o,value:n}=r.next()),o)return;++s}for(;({done:o,value:i}=r.next()),!o;)n=e(n,i,++s,t);return n}function wt(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()}function _t(t,...e){t=new v.H(t);for(const n of e)for(const e of n)t.delete(e);return t}function xt(t,e){const n=e[Symbol.iterator](),r=new v.H;for(const e of t){if(r.has(e))return!1;let t,o;for(;({value:t,done:o}=n.next())&&!o;){if(Object.is(e,t))return!1;r.add(t)}}return!0}function kt(t,...e){t=new v.H(t),e=e.map(qt);t:for(const n of t)for(const r of e)if(!r.has(n)){t.delete(n);continue t}return t}function qt(t){return t instanceof v.H?t:new v.H(t)}function Nt(t,e){const n=t[Symbol.iterator](),r=new Set;for(const t of e){const e=St(t);if(r.has(e))continue;let o,i;for(;({value:o,done:i}=n.next());){if(i)return!1;const t=St(o);if(r.add(t),Object.is(e,t))break}}return!0}function St(t){return null!==t&&"object"==typeof t?t.valueOf():t}function At(t,e){return Nt(e,t)}function Mt(...t){const e=new v.H;for(const n of t)for(const t of n)e.add(t);return e}},8319:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n<e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(n<o||void 0===n&&o>=o)&&(n=o)}return n}n.d(e,{Z:()=>r})},5374:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,o=-1;if(void 0===e)for(const e of t)++o,null!=e&&(n<e||void 0===n&&e>=e)&&(n=e,r=o);else for(let i of t)null!=(i=e(i,++o,t))&&(n<i||void 0===n&&i>=i)&&(n=i,r=o);return r}n.d(e,{Z:()=>r})},1740:(t,e,n)=>{"use strict";function r(t){return Array.from(function*(t){for(const e of t)yield*e}(t))}n.d(e,{Z:()=>r})},816:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n>e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(n>o||void 0===n&&o>=o)&&(n=o)}return n}n.d(e,{Z:()=>r})},2980:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,o=-1;if(void 0===e)for(const e of t)++o,null!=e&&(n>e||void 0===n&&e>=e)&&(n=e,r=o);else for(let i of t)null!=(i=e(i,++o,t))&&(n>i||void 0===n&&i>=i)&&(n=i,r=o);return r}n.d(e,{Z:()=>r})},3745:(t,e,n)=>{"use strict";function r(t){return null===t?NaN:+t}function*o(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else{let n=-1;for(let r of t)null!=(r=e(r,++n,t))&&(r=+r)>=r&&(yield r)}}n.d(e,{K:()=>o,Z:()=>r})},362:(t,e,n)=>{"use strict";function r(t,e){return Array.from(e,(e=>t[e]))}n.d(e,{Z:()=>r})},1177:(t,e,n)=>{"use strict";n.d(e,{Cr:()=>h,ZP:()=>f,s7:()=>d});var r=n(8319),o=n(5374),i=n(816),s=n(2980),a=n(551),l=n(3745),c=n(3897),u=n(2942);function f(t,e,n){if(o=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||o<2)return(0,i.Z)(t);if(e>=1)return(0,r.Z)(t);var o,s=(o-1)*e,c=Math.floor(s),u=(0,r.Z)((0,a.Z)(t,c).subarray(0,c+1));return u+((0,i.Z)(t.subarray(c+1))-u)*(s-c)}}function d(t,e,n=l.Z){if(r=t.length){if((e=+e)<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,o=(r-1)*e,i=Math.floor(o),s=+n(t[i],i,t);return s+(+n(t[i+1],i+1,t)-s)*(o-i)}}function h(t,e,n){if(r=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||r<2)return(0,s.Z)(t);if(e>=1)return(0,o.Z)(t);var r,i=Math.floor((r-1)*e),f=(0,a.Z)(Uint32Array.from(t,((t,e)=>e)),i,0,r-1,((e,n)=>(0,c.Wv)(t[e],t[n])));return(0,u.Z)(f.subarray(0,i+1),(e=>t[e]))}}},551:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(3897);function o(t,e,n=0,s=t.length-1,a){for(a=void 0===a?r.Wv:(0,r.di)(a);s>n;){if(s-n>600){const r=s-n+1,i=e-n+1,l=Math.log(r),c=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*c*(r-c)/r)*(i-r/2<0?-1:1);o(t,e,Math.max(n,Math.floor(e-i*c/r+u)),Math.min(s,Math.floor(e+(r-i)*c/r+u)),a)}const r=t[e];let l=n,c=s;for(i(t,n,e),a(t[s],r)>0&&i(t,n,s);l<c;){for(i(t,l,c),++l,--c;a(t[l],r)<0;)++l;for(;a(t[c],r)>0;)--c}0===a(t[n],r)?i(t,n,c):(++c,i(t,c,s)),c<=e&&(n=c+1),e<=c&&(s=c-1)}return t}function i(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}},1265:(t,e,n)=>{"use strict";function r(t,e,n){t=+t,e=+e,n=(o=arguments.length)<2?(e=t,t=0,1):o<3?1:+n;for(var r=-1,o=0|Math.max(0,Math.ceil((e-t)/n)),i=new Array(o);++r<o;)i[r]=t+r*n;return i}n.d(e,{Z:()=>r})},3897:(t,e,n)=>{"use strict";n.d(e,{Wv:()=>a,ZP:()=>i,di:()=>s});var r=n(9263),o=n(362);function i(t,...e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[n]=e;if(n&&2!==n.length||e.length>1){const r=Uint32Array.from(t,((t,e)=>e));return e.length>1?(e=e.map((e=>t.map(e))),r.sort(((t,n)=>{for(const r of e){const e=a(r[t],r[n]);if(e)return e}}))):(n=t.map(n),r.sort(((t,e)=>a(n[t],n[e])))),(0,o.Z)(t,r)}return t.sort(s(n))}function s(t=r.Z){if(t===r.Z)return a;if("function"!=typeof t)throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||0===r?r:(0===t(n,n))-(0===t(e,e))}}function a(t,e){return(null==t||!(t>=t))-(null==e||!(e>=e))||(t<e?-1:t>e?1:0)}},2327:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(879);function o(t){return Math.ceil(Math.log((0,r.Z)(t))/Math.LN2)+1}},6106:(t,e,n)=>{"use strict";n.d(e,{G9:()=>a,ZP:()=>s,ly:()=>l});var r=Math.sqrt(50),o=Math.sqrt(10),i=Math.sqrt(2);function s(t,e,n){var r,o,i,s,l=-1;if(n=+n,(t=+t)===(e=+e)&&n>0)return[t];if((r=e<t)&&(o=t,t=e,e=o),0===(s=a(t,e,n))||!isFinite(s))return[];if(s>0){let n=Math.round(t/s),r=Math.round(e/s);for(n*s<t&&++n,r*s>e&&--r,i=new Array(o=r-n+1);++l<o;)i[l]=(n+l)*s}else{s=-s;let n=Math.round(t*s),r=Math.round(e*s);for(n/s<t&&++n,r/s>e&&--r,i=new Array(o=r-n+1);++l<o;)i[l]=(n+l)/s}return r&&i.reverse(),i}function a(t,e,n){var s=(e-t)/Math.max(0,n),a=Math.floor(Math.log(s)/Math.LN10),l=s/Math.pow(10,a);return a>=0?(l>=r?10:l>=o?5:l>=i?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=r?10:l>=o?5:l>=i?2:1)}function l(t,e,n){var s=Math.abs(e-t)/Math.max(0,n),a=Math.pow(10,Math.floor(Math.log(s)/Math.LN10)),l=s/a;return l>=r?a*=10:l>=o?a*=5:l>=i&&(a*=2),e<t?-a:a}},1495:(t,e,n)=>{"use strict";n.d(e,{B8:()=>q,Il:()=>o,J5:()=>s,SU:()=>k,Ss:()=>N,Ym:()=>O,ZP:()=>w,xV:()=>i});var r=n(3456);function o(){}var i=.7,s=1/i,a="\\s*([+-]?\\d+)\\s*",l="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",c="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",u=/^#([0-9a-f]{3,8})$/,f=new RegExp(`^rgb\\(${a},${a},${a}\\)$`),d=new RegExp(`^rgb\\(${c},${c},${c}\\)$`),h=new RegExp(`^rgba\\(${a},${a},${a},${l}\\)$`),p=new RegExp(`^rgba\\(${c},${c},${c},${l}\\)$`),m=new RegExp(`^hsl\\(${l},${c},${c}\\)$`),g=new RegExp(`^hsla\\(${l},${c},${c},${l}\\)$`),y={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function v(){return this.rgb().formatHex()}function b(){return this.rgb().formatRgb()}function w(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=u.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?_(e):3===n?new N(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?x(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?x(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=f.exec(t))?new N(e[1],e[2],e[3],1):(e=d.exec(t))?new N(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?x(e[1],e[2],e[3],e[4]):(e=p.exec(t))?x(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=m.exec(t))?j(e[1],e[2]/100,e[3]/100,1):(e=g.exec(t))?j(e[1],e[2]/100,e[3]/100,e[4]):y.hasOwnProperty(t)?_(y[t]):"transparent"===t?new N(NaN,NaN,NaN,0):null}function _(t){return new N(t>>16&255,t>>8&255,255&t,1)}function x(t,e,n,r){return r<=0&&(t=e=n=NaN),new N(t,e,n,r)}function k(t){return t instanceof o||(t=w(t)),t?new N((t=t.rgb()).r,t.g,t.b,t.opacity):new N}function q(t,e,n,r){return 1===arguments.length?k(t):new N(t,e,n,null==r?1:r)}function N(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function S(){return`#${C(this.r)}${C(this.g)}${C(this.b)}`}function A(){const t=M(this.opacity);return`${1===t?"rgb(":"rgba("}${T(this.r)}, ${T(this.g)}, ${T(this.b)}${1===t?")":`, ${t})`}`}function M(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function T(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function C(t){return((t=T(t))<16?"0":"")+t.toString(16)}function j(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new I(t,e,n,r)}function E(t){if(t instanceof I)return new I(t.h,t.s,t.l,t.opacity);if(t instanceof o||(t=w(t)),!t)return new I;if(t instanceof I)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),a=NaN,l=s-i,c=(s+i)/2;return l?(a=e===s?(n-r)/l+6*(n<r):n===s?(r-e)/l+2:(e-n)/l+4,l/=c<.5?s+i:2-s-i,a*=60):l=c>0&&c<1?0:a,new I(a,l,c,t.opacity)}function O(t,e,n,r){return 1===arguments.length?E(t):new I(t,e,n,null==r?1:r)}function I(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function R(t){return(t=(t||0)%360)<0?t+360:t}function P(t){return Math.max(0,Math.min(1,t||0))}function F(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}(0,r.Z)(o,w,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:v,formatHex:v,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return E(this).formatHsl()},formatRgb:b,toString:b}),(0,r.Z)(N,q,(0,r.l)(o,{brighter(t){return t=null==t?s:Math.pow(s,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?i:Math.pow(i,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new N(T(this.r),T(this.g),T(this.b),M(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:S,formatHex:S,formatHex8:function(){return`#${C(this.r)}${C(this.g)}${C(this.b)}${C(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:A,toString:A})),(0,r.Z)(I,O,(0,r.l)(o,{brighter(t){return t=null==t?s:Math.pow(s,t),new I(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?i:Math.pow(i,t),new I(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,o=2*n-r;return new N(F(t>=240?t-240:t+120,o,r),F(t,o,r),F(t<120?t+240:t-120,o,r),this.opacity)},clamp(){return new I(R(this.h),P(this.s),P(this.l),M(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=M(this.opacity);return`${1===t?"hsl(":"hsla("}${R(this.h)}, ${100*P(this.s)}%, ${100*P(this.l)}%${1===t?")":`, ${t})`}`}}))},3456:(t,e,n)=>{"use strict";function r(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function o(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}n.d(e,{Z:()=>r,l:()=>o})},4476:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r={},o={},i=34,s=10,a=13;function l(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function c(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r)})),n}function u(t,e){var n=t+"",r=n.length;return r<e?new Array(e-r+1).join(0)+n:n}function f(t){var e,n=t.getUTCHours(),r=t.getUTCMinutes(),o=t.getUTCSeconds(),i=t.getUTCMilliseconds();return isNaN(t)?"Invalid Date":((e=t.getUTCFullYear())<0?"-"+u(-e,6):e>9999?"+"+u(e,6):u(e,4))+"-"+u(t.getUTCMonth()+1,2)+"-"+u(t.getUTCDate(),2)+(i?"T"+u(n,2)+":"+u(r,2)+":"+u(o,2)+"."+u(i,3)+"Z":o?"T"+u(n,2)+":"+u(r,2)+":"+u(o,2)+"Z":r||n?"T"+u(n,2)+":"+u(r,2)+"Z":"")}function d(t){var e=new RegExp('["'+t+"\n\r]"),n=t.charCodeAt(0);function u(t,e){var l,c=[],u=t.length,f=0,d=0,h=u<=0,p=!1;function m(){if(h)return o;if(p)return p=!1,r;var e,l,c=f;if(t.charCodeAt(c)===i){for(;f++<u&&t.charCodeAt(f)!==i||t.charCodeAt(++f)===i;);return(e=f)>=u?h=!0:(l=t.charCodeAt(f++))===s?p=!0:l===a&&(p=!0,t.charCodeAt(f)===s&&++f),t.slice(c+1,e-1).replace(/""/g,'"')}for(;f<u;){if((l=t.charCodeAt(e=f++))===s)p=!0;else if(l===a)p=!0,t.charCodeAt(f)===s&&++f;else if(l!==n)continue;return t.slice(c,e)}return h=!0,t.slice(c,u)}for(t.charCodeAt(u-1)===s&&--u,t.charCodeAt(u-1)===a&&--u;(l=m())!==o;){for(var g=[];l!==r&&l!==o;)g.push(l),l=m();e&&null==(g=e(g,d++))||c.push(g)}return c}function d(e,n){return e.map((function(e){return n.map((function(t){return p(e[t])})).join(t)}))}function h(e){return e.map(p).join(t)}function p(t){return null==t?"":t instanceof Date?f(t):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return{parse:function(t,e){var n,r,o=u(t,(function(t,o){if(n)return n(t,o-1);r=t,n=e?function(t,e){var n=l(t);return function(r,o){return e(n(r),o,t)}}(t,e):l(t)}));return o.columns=r||[],o},parseRows:u,format:function(e,n){return null==n&&(n=c(e)),[n.map(p).join(t)].concat(d(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=c(t)),d(t,e).join("\n")},formatRows:function(t){return t.map(h).join("\n")},formatRow:h,formatValue:p}}},5026:(t,e,n)=>{"use strict";n.d(e,{E0:()=>i,Hf:()=>c,n5:()=>l,sS:()=>u,tJ:()=>o,uH:()=>a,vP:()=>s});var r=(0,n(4476).Z)("\t"),o=r.parse,i=r.parseRows,s=r.format,a=r.formatBody,l=r.formatRows,c=r.formatRow,u=r.formatValue},2163:(t,e,n)=>{"use strict";n.d(e,{WU:()=>o,ZP:()=>a,jH:()=>i});var r,o,i,s=n(2107);function a(t){return r=(0,s.Z)(t),o=r.format,i=r.formatPrefix,r}a({thousands:",",grouping:[3],currency:["$",""]})},2313:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(4218);function o(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},4218:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function o(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{V:()=>o,Z:()=>r})},7259:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,v:()=>i});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function o(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new i({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function i(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}o.prototype=i.prototype,i.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},2107:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(2313);var o=n(7259);var i,s=n(4218);function a(t,e){var n=(0,s.V)(t,e);if(!n)return t+"";var r=n[0],o=n[1];return o<0?"0."+new Array(-o).join("0")+r:r.length>o+1?r.slice(0,o+1)+"."+r.slice(o+1):r+new Array(o-r.length+2).join("0")}const l={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:s.Z,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>a(100*t,e),r:a,s:function(t,e){var n=(0,s.V)(t,e);if(!n)return t+"";var r=n[0],o=n[1],a=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,l=r.length;return a===l?r:a>l?r+new Array(a-l+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+(0,s.V)(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function c(t){return t}var u=Array.prototype.map,f=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function d(t){var e,n,s=void 0===t.grouping||void 0===t.thousands?c:(e=u.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var o=t.length,i=[],s=0,a=e[0],l=0;o>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),i.push(t.substring(o-=a,o+a)),!((l+=a+1)>r));)a=e[s=(s+1)%e.length];return i.reverse().join(n)}),a=void 0===t.currency?"":t.currency[0]+"",d=void 0===t.currency?"":t.currency[1]+"",h=void 0===t.decimal?".":t.decimal+"",p=void 0===t.numerals?c:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}(u.call(t.numerals,String)),m=void 0===t.percent?"%":t.percent+"",g=void 0===t.minus?"−":t.minus+"",y=void 0===t.nan?"NaN":t.nan+"";function v(t){var e=(t=(0,o.Z)(t)).fill,n=t.align,r=t.sign,c=t.symbol,u=t.zero,v=t.width,b=t.comma,w=t.precision,_=t.trim,x=t.type;"n"===x?(b=!0,x="g"):l[x]||(void 0===w&&(w=12),_=!0,x="g"),(u||"0"===e&&"="===n)&&(u=!0,e="0",n="=");var k="$"===c?a:"#"===c&&/[boxX]/.test(x)?"0"+x.toLowerCase():"",q="$"===c?d:/[%p]/.test(x)?m:"",N=l[x],S=/[defgprs%]/.test(x);function A(t){var o,a,l,c=k,d=q;if("c"===x)d=N(t)+d,t="";else{var m=(t=+t)<0||1/t<0;if(t=isNaN(t)?y:N(Math.abs(t),w),_&&(t=function(t){t:for(var e,n=t.length,r=1,o=-1;r<n;++r)switch(t[r]){case".":o=e=r;break;case"0":0===o&&(o=r),e=r;break;default:if(!+t[r])break t;o>0&&(o=0)}return o>0?t.slice(0,o)+t.slice(e+1):t}(t)),m&&0==+t&&"+"!==r&&(m=!1),c=(m?"("===r?r:g:"-"===r||"("===r?"":r)+c,d=("s"===x?f[8+i/3]:"")+d+(m&&"("===r?")":""),S)for(o=-1,a=t.length;++o<a;)if(48>(l=t.charCodeAt(o))||l>57){d=(46===l?h+t.slice(o+1):t.slice(o))+d,t=t.slice(0,o);break}}b&&!u&&(t=s(t,1/0));var A=c.length+t.length+d.length,M=A<v?new Array(v-A+1).join(e):"";switch(b&&u&&(t=s(M+t,M.length?v-d.length:1/0),M=""),n){case"<":t=c+t+d+M;break;case"=":t=c+M+t+d;break;case"^":t=M.slice(0,A=M.length>>1)+c+t+d+M.slice(A);break;default:t=M+c+t+d}return p(t)}return w=void 0===w?6:/[gprs]/.test(x)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w)),A.toString=function(){return t+""},A}return{format:v,formatPrefix:function(t,e){var n=v(((t=(0,o.Z)(t)).type="f",t)),i=3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3))),s=Math.pow(10,-i),a=f[8+i/3];return function(t){return n(s*t)+a}}}}},9680:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},3150:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},3621:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},9466:(t,e,n)=>{"use strict";function r(t){return null==t?null:o(t)}function o(t){if("function"!=typeof t)throw new Error;return t}n.d(e,{C:()=>o,j:()=>r})},5220:(t,e,n)=>{"use strict";function r(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function o(t,e){t instanceof Map?(t=[void 0,t],void 0===e&&(e=s)):void 0===e&&(e=i);for(var n,r,o,a,u,f=new c(t),d=[f];n=d.pop();)if((o=e(n.data))&&(u=(o=Array.from(o)).length))for(n.children=o,a=u-1;a>=0;--a)d.push(r=o[a]=new c(o[a])),r.parent=n,r.depth=n.depth+1;return f.eachBefore(l)}function i(t){return t.children}function s(t){return Array.isArray(t)?t[1]:null}function a(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function l(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function c(t){this.data=t,this.depth=this.height=0,this.parent=null}n.d(e,{NB:()=>c,le:()=>l,ZP:()=>o}),c.prototype=o.prototype={constructor:c,count:function(){return this.eachAfter(r)},each:function(t,e){let n=-1;for(const r of this)t.call(e,r,++n,this);return this},eachAfter:function(t,e){for(var n,r,o,i=this,s=[i],a=[],l=-1;i=s.pop();)if(a.push(i),n=i.children)for(r=0,o=n.length;r<o;++r)s.push(n[r]);for(;i=a.pop();)t.call(e,i,++l,this);return this},eachBefore:function(t,e){for(var n,r,o=this,i=[o],s=-1;o=i.pop();)if(t.call(e,o,++s,this),n=o.children)for(r=n.length-1;r>=0;--r)i.push(n[r]);return this},find:function(t,e){let n=-1;for(const r of this)if(t.call(e,r,++n,this))return r},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,o=r&&r.length;--o>=0;)n+=r[o].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),o=null;t=n.pop(),e=r.pop();for(;t===e;)o=t,t=n.pop(),e=r.pop();return o}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var o=r.length;t!==n;)r.splice(o,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return o(this).eachBefore(a)},[Symbol.iterator]:function*(){var t,e,n,r,o=this,i=[o];do{for(t=i.reverse(),i=[];o=t.pop();)if(yield o,e=o.children)for(n=0,r=e.length;n<r;++n)i.push(e[n])}while(i.length)}}},4766:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(9466),o=n(5220),i={depth:-1},s={},a={};function l(t){return t.id}function c(t){return t.parentId}function u(){var t,e=l,n=c;function u(r){var l,c,u,h,p,m,g,y,v=Array.from(r),b=e,w=n,_=new Map;if(null!=t){const e=v.map(((e,n)=>function(t){t=`${t}`;let e=t.length;d(t,e-1)&&!d(t,e-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(e,n,r)))),n=e.map(f),o=new Set(e).add("");for(const t of n)o.has(t)||(o.add(t),e.push(t),n.push(f(t)),v.push(a));b=(t,n)=>e[n],w=(t,e)=>n[e]}for(u=0,l=v.length;u<l;++u)c=v[u],m=v[u]=new o.NB(c),null!=(g=b(c,u,r))&&(g+="")&&(y=m.id=g,_.set(y,_.has(y)?s:m)),null!=(g=w(c,u,r))&&(g+="")&&(m.parent=g);for(u=0;u<l;++u)if(g=(m=v[u]).parent){if(!(p=_.get(g)))throw new Error("missing: "+g);if(p===s)throw new Error("ambiguous: "+g);p.children?p.children.push(m):p.children=[m],m.parent=p}else{if(h)throw new Error("multiple roots");h=m}if(!h)throw new Error("no root");if(null!=t){for(;h.data===a&&1===h.children.length;)h=h.children[0],--l;for(let t=v.length-1;t>=0&&(m=v[t]).data===a;--t)m.data=null}if(h.parent=i,h.eachBefore((function(t){t.depth=t.parent.depth+1,--l})).eachBefore(o.le),h.parent=null,l>0)throw new Error("cycle");return h}return u.id=function(t){return arguments.length?(e=(0,r.j)(t),u):e},u.parentId=function(t){return arguments.length?(n=(0,r.j)(t),u):n},u.path=function(e){return arguments.length?(t=(0,r.j)(e),u):t},u}function f(t){let e=t.length;if(e<2)return"";for(;--e>1&&!d(t,e););return t.slice(0,e)}function d(t,e){if("/"===t[e]){let n=0;for(;e>0&&"\\"===t[--e];)++n;if(0==(1&n))return!0}return!1}},4321:(t,e,n)=>{"use strict";n.d(e,{M:()=>s,Z:()=>i});var r=n(2303),o=n(5003);function i(t,e){return((0,o.v)(e)?o.Z:s)(t,e)}function s(t,e){var n,o=e?e.length:0,i=t?Math.min(o,t.length):0,s=new Array(i),a=new Array(o);for(n=0;n<i;++n)s[n]=(0,r.Z)(t[n],e[n]);for(;n<o;++n)a[n]=e[n];return function(t){for(n=0;n<i;++n)a[n]=s[n](t);return a}}},5409:(t,e,n)=>{"use strict";function r(t,e,n,r,o){var i=t*t,s=i*t;return((1-3*t+3*i-s)*e+(4-6*i+3*s)*n+(1+3*t+3*i-3*s)*r+s*o)/6}function o(t){var e=t.length-1;return function(n){var o=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),i=t[o],s=t[o+1],a=o>0?t[o-1]:2*i-s,l=o<e-1?t[o+2]:2*s-i;return r((n-o/e)*e,a,i,s,l)}}n.d(e,{Z:()=>o,t:()=>r})},7855:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(5409);function o(t){var e=t.length;return function(n){var o=Math.floor(((n%=1)<0?++n:n)*e),i=t[(o+e-1)%e],s=t[o%e],a=t[(o+1)%e],l=t[(o+2)%e];return(0,r.t)((n-o/e)*e,i,s,a,l)}}},8190:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,wx:()=>i,yi:()=>s});var r=n(8486);function o(t,e){return function(n){return t+n*e}}function i(t,e){var n=e-t;return n?o(t,n>180||n<-180?n-360*Math.round(n/360):n):(0,r.Z)(isNaN(t)?e:t)}function s(t){return 1==(t=+t)?a:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):(0,r.Z)(isNaN(e)?n:e)}}function a(t,e){var n=e-t;return n?o(t,n):(0,r.Z)(isNaN(t)?e:t)}},8486:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=t=>()=>t},6261:(t,e,n)=>{"use strict";function r(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}n.d(e,{Z:()=>r})},8403:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}n.d(e,{Z:()=>r})},5003:(t,e,n)=>{"use strict";function r(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,o=e.slice();return function(i){for(n=0;n<r;++n)o[n]=t[n]*(1-i)+e[n]*i;return o}}function o(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}n.d(e,{Z:()=>r,v:()=>o})},8765:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2303);function o(t,e){var n,o={},i={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?o[n]=(0,r.Z)(t[n],e[n]):i[n]=e[n];return function(t){for(n in o)i[n]=o[n](t);return i}}},9444:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2303);function o(t,e){void 0===e&&(e=t,t=r.Z);for(var n=0,o=e.length-1,i=e[0],s=new Array(o<0?0:o);n<o;)s[n]=t(i,i=e[++n]);return function(t){var e=Math.max(0,Math.min(o-1,Math.floor(t*=o)));return s[e](t-e)}}},490:(t,e,n)=>{"use strict";n.d(e,{YD:()=>u,ZP:()=>a,hD:()=>c});var r=n(1495),o=n(5409),i=n(7855),s=n(8190);const a=function t(e){var n=(0,s.yi)(e);function o(t,e){var o=n((t=(0,r.B8)(t)).r,(e=(0,r.B8)(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),l=(0,s.ZP)(t.opacity,e.opacity);return function(e){return t.r=o(e),t.g=i(e),t.b=a(e),t.opacity=l(e),t+""}}return o.gamma=t,o}(1);function l(t){return function(e){var n,o,i=e.length,s=new Array(i),a=new Array(i),l=new Array(i);for(n=0;n<i;++n)o=(0,r.B8)(e[n]),s[n]=o.r||0,a[n]=o.g||0,l[n]=o.b||0;return s=t(s),a=t(a),l=t(l),o.opacity=1,function(t){return o.r=s(t),o.g=a(t),o.b=l(t),o+""}}}var c=l(o.Z),u=l(i.Z)},5250:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}n.d(e,{Z:()=>r})},9009:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(8403),o=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,i=new RegExp(o.source,"g");function s(t,e){var n,s,a,l=o.lastIndex=i.lastIndex=0,c=-1,u=[],f=[];for(t+="",e+="";(n=o.exec(t))&&(s=i.exec(e));)(a=s.index)>l&&(a=e.slice(l,a),u[c]?u[c]+=a:u[++c]=a),(n=n[0])===(s=s[0])?u[c]?u[c]+=s:u[++c]=s:(u[++c]=null,f.push({i:c,x:(0,r.Z)(n,s)})),l=i.lastIndex;return l<e.length&&(a=e.slice(l),u[c]?u[c]+=a:u[++c]=a),u.length<2?f[0]?function(t){return function(e){return t(e)+""}}(f[0].x):function(t){return function(){return t}}(e):(e=f.length,function(t){for(var n,r=0;r<e;++r)u[(n=f[r]).i]=n.x(t);return u.join("")})}},2303:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1495),o=n(490),i=n(4321),s=n(6261),a=n(8403),l=n(8765),c=n(9009),u=n(8486),f=n(5003);function d(t,e){var n,d=typeof e;return null==e||"boolean"===d?(0,u.Z)(e):("number"===d?a.Z:"string"===d?(n=(0,r.ZP)(e))?(e=n,o.ZP):c.Z:e instanceof r.ZP?o.ZP:e instanceof Date?s.Z:(0,f.v)(e)?f.Z:Array.isArray(e)?i.M:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?l.Z:a.Z)(t,e)}},7763:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(4090).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf")},4090:(t,e,n)=>{"use strict";function r(t){for(var e=t.length/6|0,n=new Array(e),r=0;r<e;)n[r]="#"+t.slice(6*r,6*++r);return n}n.d(e,{Z:()=>r})},1303:(t,e,n)=>{"use strict";n.d(e,{JG:()=>h,ZP:()=>m,yR:()=>c,l4:()=>p});var r=n(5519),o=n(2303),i=n(8403),s=n(5250);var a=n(9120),l=[0,1];function c(t){return t}function u(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:(n=isNaN(e)?NaN:.5,function(){return n});var n}function f(t,e,n){var r=t[0],o=t[1],i=e[0],s=e[1];return o<r?(r=u(o,r),i=n(s,i)):(r=u(r,o),i=n(i,s)),function(t){return i(r(t))}}function d(t,e,n){var o=Math.min(t.length,e.length)-1,i=new Array(o),s=new Array(o),a=-1;for(t[o]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++a<o;)i[a]=u(t[a],t[a+1]),s[a]=n(e[a],e[a+1]);return function(e){var n=(0,r.ZP)(t,e,1,o)-1;return s[n](i[n](e))}}function h(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function p(){var t,e,n,r,u,h,p=l,m=l,g=o.Z,y=c;function v(){var t,e,n,o=Math.min(p.length,m.length);return y!==c&&(t=p[0],e=p[o-1],t>e&&(n=t,t=e,e=n),y=function(n){return Math.max(t,Math.min(e,n))}),r=o>2?d:f,u=h=null,b}function b(e){return null==e||isNaN(e=+e)?n:(u||(u=r(p.map(t),m,g)))(t(y(e)))}return b.invert=function(n){return y(e((h||(h=r(m,p.map(t),i.Z)))(n)))},b.domain=function(t){return arguments.length?(p=Array.from(t,a.Z),v()):p.slice()},b.range=function(t){return arguments.length?(m=Array.from(t),v()):m.slice()},b.rangeRound=function(t){return m=Array.from(t),g=s.Z,v()},b.clamp=function(t){return arguments.length?(y=!!t||c,v()):y!==c},b.interpolate=function(t){return arguments.length?(g=t,v()):g},b.unknown=function(t){return arguments.length?(n=t,b):n},function(n,r){return t=n,e=r,v()}}function m(){return p()(c,c)}},4635:(t,e,n)=>{"use strict";n.r(e),n.d(e,{scaleBand:()=>s,scaleDiverging:()=>_t,scaleDivergingLog:()=>xt,scaleDivergingPow:()=>qt,scaleDivergingSqrt:()=>Nt,scaleDivergingSymlog:()=>kt,scaleIdentity:()=>f,scaleImplicit:()=>i.O,scaleLinear:()=>c.Z,scaleLog:()=>q,scaleOrdinal:()=>i.Z,scalePoint:()=>l,scalePow:()=>O,scaleQuantile:()=>$,scaleQuantize:()=>Z,scaleRadial:()=>P,scaleSequential:()=>ht,scaleSequentialLog:()=>pt,scaleSequentialPow:()=>gt,scaleSequentialQuantile:()=>vt,scaleSequentialSqrt:()=>yt,scaleSequentialSymlog:()=>mt,scaleSqrt:()=>I,scaleSymlog:()=>M,scaleThreshold:()=>z,scaleTime:()=>et,scaleUtc:()=>lt,tickFormat:()=>St.Z});var r=n(1265),o=n(2998),i=n(5540);function s(){var t,e,n=(0,i.Z)().unknown(void 0),a=n.domain,l=n.range,c=0,u=1,f=!1,d=0,h=0,p=.5;function m(){var n=a().length,o=u<c,i=o?u:c,s=o?c:u;t=(s-i)/Math.max(1,n-d+2*h),f&&(t=Math.floor(t)),i+=(s-i-t*(n-d))*p,e=t*(1-d),f&&(i=Math.round(i),e=Math.round(e));var m=(0,r.Z)(n).map((function(e){return i+t*e}));return l(o?m.reverse():m)}return delete n.unknown,n.domain=function(t){return arguments.length?(a(t),m()):a()},n.range=function(t){return arguments.length?([c,u]=t,c=+c,u=+u,m()):[c,u]},n.rangeRound=function(t){return[c,u]=t,c=+c,u=+u,f=!0,m()},n.bandwidth=function(){return e},n.step=function(){return t},n.round=function(t){return arguments.length?(f=!!t,m()):f},n.padding=function(t){return arguments.length?(d=Math.min(1,h=+t),m()):d},n.paddingInner=function(t){return arguments.length?(d=Math.min(1,t),m()):d},n.paddingOuter=function(t){return arguments.length?(h=+t,m()):h},n.align=function(t){return arguments.length?(p=Math.max(0,Math.min(1,t)),m()):p},n.copy=function(){return s(a(),[c,u]).round(f).paddingInner(d).paddingOuter(h).align(p)},o.o.apply(m(),arguments)}function a(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return a(e())},t}function l(){return a(s.apply(null,arguments).paddingInner(1))}var c=n(9064),u=n(9120);function f(t){var e;function n(t){return null==t||isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Array.from(e,u.Z),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return f(t).unknown(e)},t=arguments.length?Array.from(t,u.Z):[0,1],(0,c.Q)(n)}var d=n(6106),h=n(7259),p=n(2163);function m(t,e){var n,r=0,o=(t=t.slice()).length-1,i=t[r],s=t[o];return s<i&&(n=r,r=o,o=n,n=i,i=s,s=n),t[r]=e.floor(i),t[o]=e.ceil(s),t}var g=n(1303);function y(t){return Math.log(t)}function v(t){return Math.exp(t)}function b(t){return-Math.log(-t)}function w(t){return-Math.exp(-t)}function _(t){return isFinite(t)?+("1e"+t):t<0?0:t}function x(t){return(e,n)=>-t(-e,n)}function k(t){const e=t(y,v),n=e.domain;let r,o,i=10;function s(){return r=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}(i),o=function(t){return 10===t?_:t===Math.E?Math.exp:e=>Math.pow(t,e)}(i),n()[0]<0?(r=x(r),o=x(o),t(b,w)):t(y,v),e}return e.base=function(t){return arguments.length?(i=+t,s()):i},e.domain=function(t){return arguments.length?(n(t),s()):n()},e.ticks=t=>{const e=n();let s=e[0],a=e[e.length-1];const l=a<s;l&&([s,a]=[a,s]);let c,u,f=r(s),h=r(a);const p=null==t?10:+t;let m=[];if(!(i%1)&&h-f<p){if(f=Math.floor(f),h=Math.ceil(h),s>0){for(;f<=h;++f)for(c=1;c<i;++c)if(u=f<0?c/o(-f):c*o(f),!(u<s)){if(u>a)break;m.push(u)}}else for(;f<=h;++f)for(c=i-1;c>=1;--c)if(u=f>0?c/o(-f):c*o(f),!(u<s)){if(u>a)break;m.push(u)}2*m.length<p&&(m=(0,d.ZP)(s,a,p))}else m=(0,d.ZP)(f,h,Math.min(h-f,p)).map(o);return l?m.reverse():m},e.tickFormat=(t,n)=>{if(null==t&&(t=10),null==n&&(n=10===i?"s":","),"function"!=typeof n&&(i%1||null!=(n=(0,h.Z)(n)).precision||(n.trim=!0),n=(0,p.WU)(n)),t===1/0)return n;const s=Math.max(1,i*t/e.ticks().length);return t=>{let e=t/o(Math.round(r(t)));return e*i<i-.5&&(e*=i),e<=s?n(t):""}},e.nice=()=>n(m(n(),{floor:t=>o(Math.floor(r(t))),ceil:t=>o(Math.ceil(r(t)))})),e}function q(){const t=k((0,g.l4)()).domain([1,10]);return t.copy=()=>(0,g.JG)(t,q()).base(t.base()),o.o.apply(t,arguments),t}function N(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function S(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function A(t){var e=1,n=t(N(e),S(e));return n.constant=function(n){return arguments.length?t(N(e=+n),S(e)):e},(0,c.Q)(n)}function M(){var t=A((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,M()).constant(t.constant())},o.o.apply(t,arguments)}function T(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function C(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function j(t){return t<0?-t*t:t*t}function E(t){var e=t(g.yR,g.yR),n=1;return e.exponent=function(e){return arguments.length?1===(n=+e)?t(g.yR,g.yR):.5===n?t(C,j):t(T(n),T(1/n)):n},(0,c.Q)(e)}function O(){var t=E((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,O()).exponent(t.exponent())},o.o.apply(t,arguments),t}function I(){return O.apply(null,arguments).exponent(.5)}function R(t){return Math.sign(t)*t*t}function P(){var t,e=(0,g.ZP)(),n=[0,1],r=!1;function i(n){var o=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(n));return isNaN(o)?t:r?Math.round(o):o}return i.invert=function(t){return e.invert(R(t))},i.domain=function(t){return arguments.length?(e.domain(t),i):e.domain()},i.range=function(t){return arguments.length?(e.range((n=Array.from(t,u.Z)).map(R)),i):n.slice()},i.rangeRound=function(t){return i.range(t).round(!0)},i.round=function(t){return arguments.length?(r=!!t,i):r},i.clamp=function(t){return arguments.length?(e.clamp(t),i):e.clamp()},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return P(e.domain(),n).round(r).clamp(e.clamp()).unknown(t)},o.o.apply(i,arguments),(0,c.Q)(i)}var F=n(1177),D=n(5519),L=n(9263);function $(){var t,e=[],n=[],r=[];function i(){var t=0,o=Math.max(1,n.length);for(r=new Array(o-1);++t<o;)r[t-1]=(0,F.s7)(e,t/o);return s}function s(e){return null==e||isNaN(e=+e)?t:n[(0,D.ZP)(r,e)]}return s.invertExtent=function(t){var o=n.indexOf(t);return o<0?[NaN,NaN]:[o>0?r[o-1]:e[0],o<r.length?r[o]:e[e.length-1]]},s.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(L.Z),i()},s.range=function(t){return arguments.length?(n=Array.from(t),i()):n.slice()},s.unknown=function(e){return arguments.length?(t=e,s):t},s.quantiles=function(){return r.slice()},s.copy=function(){return $().domain(e).range(n).unknown(t)},o.o.apply(s,arguments)}function Z(){var t,e=0,n=1,r=1,i=[.5],s=[0,1];function a(e){return null!=e&&e<=e?s[(0,D.ZP)(i,e,0,r)]:t}function l(){var t=-1;for(i=new Array(r);++t<r;)i[t]=((t+1)*n-(t-r)*e)/(r+1);return a}return a.domain=function(t){return arguments.length?([e,n]=t,e=+e,n=+n,l()):[e,n]},a.range=function(t){return arguments.length?(r=(s=Array.from(t)).length-1,l()):s.slice()},a.invertExtent=function(t){var o=s.indexOf(t);return o<0?[NaN,NaN]:o<1?[e,i[0]]:o>=r?[i[r-1],n]:[i[o-1],i[o]]},a.unknown=function(e){return arguments.length?(t=e,a):a},a.thresholds=function(){return i.slice()},a.copy=function(){return Z().domain([e,n]).range(s).unknown(t)},o.o.apply((0,c.Q)(a),arguments)}function z(){var t,e=[.5],n=[0,1],r=1;function i(o){return null!=o&&o<=o?n[(0,D.ZP)(e,o,0,r)]:t}return i.domain=function(t){return arguments.length?(e=Array.from(t),r=Math.min(e.length,n.length-1),i):e.slice()},i.range=function(t){return arguments.length?(n=Array.from(t),r=Math.min(e.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return z().domain(e).range(n).unknown(t)},o.o.apply(i,arguments)}var U=n(7150),B=n(2311),G=n(7905),J=n(6018),W=n(8467),H=n(6596),V=n(2991),Y=n(1343),K=n(1852);function X(t){return new Date(t)}function Q(t){return t instanceof Date?+t:+new Date(+t)}function tt(t,e,n,r,o,i,s,a,l,c){var u=(0,g.ZP)(),f=u.invert,d=u.domain,h=c(".%L"),p=c(":%S"),y=c("%I:%M"),v=c("%I %p"),b=c("%a %d"),w=c("%b %d"),_=c("%B"),x=c("%Y");function k(t){return(l(t)<t?h:a(t)<t?p:s(t)<t?y:i(t)<t?v:r(t)<t?o(t)<t?b:w:n(t)<t?_:x)(t)}return u.invert=function(t){return new Date(f(t))},u.domain=function(t){return arguments.length?d(Array.from(t,Q)):d().map(X)},u.ticks=function(e){var n=d();return t(n[0],n[n.length-1],null==e?10:e)},u.tickFormat=function(t,e){return null==e?k:c(e)},u.nice=function(t){var n=d();return t&&"function"==typeof t.range||(t=e(n[0],n[n.length-1],null==t?10:t)),t?d(m(n,t)):u},u.copy=function(){return(0,g.JG)(u,tt(t,e,n,r,o,i,s,a,l,c))},u}function et(){return o.o.apply(tt(U.jK,U._g,B.Z,G.Z,J.OM,W.Z,H.Z,V.Z,Y.Z,K.i$).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}var nt=n(4552),rt=n(7351),ot=n(1887),it=n(7445),st=n(8927),at=n(8593);function lt(){return o.o.apply(tt(U.WG,U.jo,nt.Z,rt.Z,ot.Ox,it.Z,st.Z,at.Z,Y.Z,K.g0).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}var ct=n(2303),ut=n(5250);function ft(){var t,e,n,r,o,i=0,s=1,a=g.yR,l=!1;function c(e){return null==e||isNaN(e=+e)?o:a(0===n?.5:(e=(r(e)-t)*n,l?Math.max(0,Math.min(1,e)):e))}function u(t){return function(e){var n,r;return arguments.length?([n,r]=e,a=t(n,r),c):[a(0),a(1)]}}return c.domain=function(o){return arguments.length?([i,s]=o,t=r(i=+i),e=r(s=+s),n=t===e?0:1/(e-t),c):[i,s]},c.clamp=function(t){return arguments.length?(l=!!t,c):l},c.interpolator=function(t){return arguments.length?(a=t,c):a},c.range=u(ct.Z),c.rangeRound=u(ut.Z),c.unknown=function(t){return arguments.length?(o=t,c):o},function(o){return r=o,t=o(i),e=o(s),n=t===e?0:1/(e-t),c}}function dt(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function ht(){var t=(0,c.Q)(ft()(g.yR));return t.copy=function(){return dt(t,ht())},o.O.apply(t,arguments)}function pt(){var t=k(ft()).domain([1,10]);return t.copy=function(){return dt(t,pt()).base(t.base())},o.O.apply(t,arguments)}function mt(){var t=A(ft());return t.copy=function(){return dt(t,mt()).constant(t.constant())},o.O.apply(t,arguments)}function gt(){var t=E(ft());return t.copy=function(){return dt(t,gt()).exponent(t.exponent())},o.O.apply(t,arguments)}function yt(){return gt.apply(null,arguments).exponent(.5)}function vt(){var t=[],e=g.yR;function n(n){if(null!=n&&!isNaN(n=+n))return e(((0,D.ZP)(t,n,1)-1)/(t.length-1))}return n.domain=function(e){if(!arguments.length)return t.slice();t=[];for(let n of e)null==n||isNaN(n=+n)||t.push(n);return t.sort(L.Z),n},n.interpolator=function(t){return arguments.length?(e=t,n):e},n.range=function(){return t.map(((n,r)=>e(r/(t.length-1))))},n.quantiles=function(e){return Array.from({length:e+1},((n,r)=>(0,F.ZP)(t,r/e)))},n.copy=function(){return vt(e).domain(t)},o.O.apply(n,arguments)}var bt=n(9444);function wt(){var t,e,n,r,o,i,s,a=0,l=.5,c=1,u=1,f=g.yR,d=!1;function h(t){return isNaN(t=+t)?s:(t=.5+((t=+i(t))-e)*(u*t<u*e?r:o),f(d?Math.max(0,Math.min(1,t)):t))}function p(t){return function(e){var n,r,o;return arguments.length?([n,r,o]=e,f=(0,bt.Z)(t,[n,r,o]),h):[f(0),f(.5),f(1)]}}return h.domain=function(s){return arguments.length?([a,l,c]=s,t=i(a=+a),e=i(l=+l),n=i(c=+c),r=t===e?0:.5/(e-t),o=e===n?0:.5/(n-e),u=e<t?-1:1,h):[a,l,c]},h.clamp=function(t){return arguments.length?(d=!!t,h):d},h.interpolator=function(t){return arguments.length?(f=t,h):f},h.range=p(ct.Z),h.rangeRound=p(ut.Z),h.unknown=function(t){return arguments.length?(s=t,h):s},function(s){return i=s,t=s(a),e=s(l),n=s(c),r=t===e?0:.5/(e-t),o=e===n?0:.5/(n-e),u=e<t?-1:1,h}}function _t(){var t=(0,c.Q)(wt()(g.yR));return t.copy=function(){return dt(t,_t())},o.O.apply(t,arguments)}function xt(){var t=k(wt()).domain([.1,1,10]);return t.copy=function(){return dt(t,xt()).base(t.base())},o.O.apply(t,arguments)}function kt(){var t=A(wt());return t.copy=function(){return dt(t,kt()).constant(t.constant())},o.O.apply(t,arguments)}function qt(){var t=E(wt());return t.copy=function(){return dt(t,qt()).exponent(t.exponent())},o.O.apply(t,arguments)}function Nt(){return qt.apply(null,arguments).exponent(.5)}var St=n(8902)},2998:(t,e,n)=>{"use strict";function r(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}function o(t,e){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof e?this.interpolator(e):this.range(e)}return this}n.d(e,{O:()=>o,o:()=>r})},9064:(t,e,n)=>{"use strict";n.d(e,{Q:()=>a,Z:()=>l});var r=n(6106),o=n(1303),i=n(2998),s=n(8902);function a(t){var e=t.domain;return t.ticks=function(t){var n=e();return(0,r.ZP)(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return(0,s.Z)(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var o,i,s=e(),a=0,l=s.length-1,c=s[a],u=s[l],f=10;for(u<c&&(i=c,c=u,u=i,i=a,a=l,l=i);f-- >0;){if((i=(0,r.G9)(c,u,n))===o)return s[a]=c,s[l]=u,e(s);if(i>0)c=Math.floor(c/i)*i,u=Math.ceil(u/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,u=Math.floor(u*i)/i}o=i}return t},t}function l(){var t=(0,o.ZP)();return t.copy=function(){return(0,o.JG)(t,l())},i.o.apply(t,arguments),a(t)}},9120:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{Z:()=>r})},5540:(t,e,n)=>{"use strict";n.d(e,{O:()=>i,Z:()=>s});var r=n(8828),o=n(2998);const i=Symbol("implicit");function s(){var t=new r.L,e=[],n=[],a=i;function l(r){let o=t.get(r);if(void 0===o){if(a!==i)return a;t.set(r,o=e.push(r)-1)}return n[o%n.length]}return l.domain=function(n){if(!arguments.length)return e.slice();e=[],t=new r.L;for(const r of n)t.has(r)||t.set(r,e.push(r)-1);return l},l.range=function(t){return arguments.length?(n=Array.from(t),l):n.slice()},l.unknown=function(t){return arguments.length?(a=t,l):a},l.copy=function(){return s(e,n).unknown(a)},o.o.apply(l,arguments),l}},8902:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=n(6106),o=n(7259),i=n(3150),s=n(2163),a=n(3621),l=n(9680);function c(t,e,n,c){var u,f=(0,r.ly)(t,e,n);switch((c=(0,o.Z)(null==c?",f":c)).type){case"s":var d=Math.max(Math.abs(t),Math.abs(e));return null!=c.precision||isNaN(u=(0,i.Z)(f,d))||(c.precision=u),(0,s.jH)(c,d);case"":case"e":case"g":case"p":case"r":null!=c.precision||isNaN(u=(0,a.Z)(f,Math.max(Math.abs(t),Math.abs(e))))||(c.precision=u-("e"===c.type));break;case"f":case"%":null!=c.precision||isNaN(u=(0,l.Z)(f))||(c.precision=u-2*("%"===c.type))}return(0,s.WU)(c)}},1852:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>i,ZP:()=>c,g0:()=>s,i$:()=>o,wp:()=>a});var r,o,i,s,a,l=n(3015);function c(t){return r=(0,l.Z)(t),o=r.format,i=r.parse,s=r.utcFormat,a=r.utcParse,r}c({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})},3015:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1887),o=n(7445),i=n(6018),s=n(8467),a=n(2311),l=n(4552);function c(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function u(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function f(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function d(t){var e=t.dateTime,n=t.date,a=t.time,l=t.periods,d=t.days,p=t.shortDays,m=t.months,g=t.shortMonths,y=b(l),v=w(l),X=b(d),vt=w(d),Ct=b(p),jt=w(p),Et=b(m),Ot=w(m),It=b(g),Rt=w(g),Pt={a:function(t){return p[t.getDay()]},A:function(t){return d[t.getDay()]},b:function(t){return g[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:null,d:Z,e:Z,f:J,g:rt,G:it,H:z,I:U,j:B,L:G,m:W,M:H,p:function(t){return l[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:Mt,s:Tt,S:V,u:Y,U:K,V:Q,w:tt,W:et,x:null,X:null,y:nt,Y:ot,Z:st,"%":At},Ft={a:function(t){return p[t.getUTCDay()]},A:function(t){return d[t.getUTCDay()]},b:function(t){return g[t.getUTCMonth()]},B:function(t){return m[t.getUTCMonth()]},c:null,d:at,e:at,f:dt,g:kt,G:Nt,H:lt,I:ct,j:ut,L:ft,m:ht,M:pt,p:function(t){return l[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:Mt,s:Tt,S:mt,u:gt,U:yt,V:bt,w:wt,W:_t,x:null,X:null,y:xt,Y:qt,Z:St,"%":At},Dt={a:function(t,e,n){var r=Ct.exec(e.slice(n));return r?(t.w=jt.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=X.exec(e.slice(n));return r?(t.w=vt.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=It.exec(e.slice(n));return r?(t.m=Rt.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=Et.exec(e.slice(n));return r?(t.m=Ot.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return Zt(t,e,n,r)},d:j,e:j,f:F,g:A,G:S,H:O,I:O,j:E,L:P,m:C,M:I,p:function(t,e,n){var r=y.exec(e.slice(n));return r?(t.p=v.get(r[0].toLowerCase()),n+r[0].length):-1},q:T,Q:L,s:$,S:R,u:x,U:k,V:q,w:_,W:N,x:function(t,e,r){return Zt(t,n,e,r)},X:function(t,e,n){return Zt(t,a,e,n)},y:A,Y:S,Z:M,"%":D};function Lt(t,e){return function(n){var r,o,i,s=[],a=-1,l=0,c=t.length;for(n instanceof Date||(n=new Date(+n));++a<c;)37===t.charCodeAt(a)&&(s.push(t.slice(l,a)),null!=(o=h[r=t.charAt(++a)])?r=t.charAt(++a):o="e"===r?" ":"0",(i=e[r])&&(r=i(n,o)),s.push(r),l=a+1);return s.push(t.slice(l,a)),s.join("")}}function $t(t,e){return function(n){var a,l,d=f(1900,void 0,1);if(Zt(d,t,n+="",0)!=n.length)return null;if("Q"in d)return new Date(d.Q);if("s"in d)return new Date(1e3*d.s+("L"in d?d.L:0));if(e&&!("Z"in d)&&(d.Z=0),"p"in d&&(d.H=d.H%12+12*d.p),void 0===d.m&&(d.m="q"in d?d.q:0),"V"in d){if(d.V<1||d.V>53)return null;"w"in d||(d.w=1),"Z"in d?(l=(a=u(f(d.y,0,1))).getUTCDay(),a=l>4||0===l?r.l6.ceil(a):(0,r.l6)(a),a=o.Z.offset(a,7*(d.V-1)),d.y=a.getUTCFullYear(),d.m=a.getUTCMonth(),d.d=a.getUTCDate()+(d.w+6)%7):(l=(a=c(f(d.y,0,1))).getDay(),a=l>4||0===l?i.wA.ceil(a):(0,i.wA)(a),a=s.Z.offset(a,7*(d.V-1)),d.y=a.getFullYear(),d.m=a.getMonth(),d.d=a.getDate()+(d.w+6)%7)}else("W"in d||"U"in d)&&("w"in d||(d.w="u"in d?d.u%7:"W"in d?1:0),l="Z"in d?u(f(d.y,0,1)).getUTCDay():c(f(d.y,0,1)).getDay(),d.m=0,d.d="W"in d?(d.w+6)%7+7*d.W-(l+5)%7:d.w+7*d.U-(l+6)%7);return"Z"in d?(d.H+=d.Z/100|0,d.M+=d.Z%100,u(d)):c(d)}}function Zt(t,e,n,r){for(var o,i,s=0,a=e.length,l=n.length;s<a;){if(r>=l)return-1;if(37===(o=e.charCodeAt(s++))){if(o=e.charAt(s++),!(i=Dt[o in h?e.charAt(s++):o])||(r=i(t,n,r))<0)return-1}else if(o!=n.charCodeAt(r++))return-1}return r}return Pt.x=Lt(n,Pt),Pt.X=Lt(a,Pt),Pt.c=Lt(e,Pt),Ft.x=Lt(n,Ft),Ft.X=Lt(a,Ft),Ft.c=Lt(e,Ft),{format:function(t){var e=Lt(t+="",Pt);return e.toString=function(){return t},e},parse:function(t){var e=$t(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=Lt(t+="",Ft);return e.toString=function(){return t},e},utcParse:function(t){var e=$t(t+="",!0);return e.toString=function(){return t},e}}}var h={"-":"",_:" ",0:"0"},p=/^\s*\d+/,m=/^%/,g=/[\\^$*+?|[\]().{}]/g;function y(t,e,n){var r=t<0?"-":"",o=(r?-t:t)+"",i=o.length;return r+(i<n?new Array(n-i+1).join(e)+o:o)}function v(t){return t.replace(g,"\\$&")}function b(t){return new RegExp("^(?:"+t.map(v).join("|")+")","i")}function w(t){return new Map(t.map(((t,e)=>[t.toLowerCase(),e])))}function _(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function x(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function k(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function q(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function N(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function S(t,e,n){var r=p.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function A(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function M(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function T(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function C(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function j(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function E(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function O(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function I(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function R(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function P(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function F(t,e,n){var r=p.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function D(t,e,n){var r=m.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function L(t,e,n){var r=p.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function $(t,e,n){var r=p.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Z(t,e){return y(t.getDate(),e,2)}function z(t,e){return y(t.getHours(),e,2)}function U(t,e){return y(t.getHours()%12||12,e,2)}function B(t,e){return y(1+s.Z.count((0,a.Z)(t),t),e,3)}function G(t,e){return y(t.getMilliseconds(),e,3)}function J(t,e){return G(t,e)+"000"}function W(t,e){return y(t.getMonth()+1,e,2)}function H(t,e){return y(t.getMinutes(),e,2)}function V(t,e){return y(t.getSeconds(),e,2)}function Y(t){var e=t.getDay();return 0===e?7:e}function K(t,e){return y(i.OM.count((0,a.Z)(t)-1,t),e,2)}function X(t){var e=t.getDay();return e>=4||0===e?(0,i.bL)(t):i.bL.ceil(t)}function Q(t,e){return t=X(t),y(i.bL.count((0,a.Z)(t),t)+(4===(0,a.Z)(t).getDay()),e,2)}function tt(t){return t.getDay()}function et(t,e){return y(i.wA.count((0,a.Z)(t)-1,t),e,2)}function nt(t,e){return y(t.getFullYear()%100,e,2)}function rt(t,e){return y((t=X(t)).getFullYear()%100,e,2)}function ot(t,e){return y(t.getFullYear()%1e4,e,4)}function it(t,e){var n=t.getDay();return y((t=n>=4||0===n?(0,i.bL)(t):i.bL.ceil(t)).getFullYear()%1e4,e,4)}function st(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+y(e/60|0,"0",2)+y(e%60,"0",2)}function at(t,e){return y(t.getUTCDate(),e,2)}function lt(t,e){return y(t.getUTCHours(),e,2)}function ct(t,e){return y(t.getUTCHours()%12||12,e,2)}function ut(t,e){return y(1+o.Z.count((0,l.Z)(t),t),e,3)}function ft(t,e){return y(t.getUTCMilliseconds(),e,3)}function dt(t,e){return ft(t,e)+"000"}function ht(t,e){return y(t.getUTCMonth()+1,e,2)}function pt(t,e){return y(t.getUTCMinutes(),e,2)}function mt(t,e){return y(t.getUTCSeconds(),e,2)}function gt(t){var e=t.getUTCDay();return 0===e?7:e}function yt(t,e){return y(r.Ox.count((0,l.Z)(t)-1,t),e,2)}function vt(t){var e=t.getUTCDay();return e>=4||0===e?(0,r.hB)(t):r.hB.ceil(t)}function bt(t,e){return t=vt(t),y(r.hB.count((0,l.Z)(t),t)+(4===(0,l.Z)(t).getUTCDay()),e,2)}function wt(t){return t.getUTCDay()}function _t(t,e){return y(r.l6.count((0,l.Z)(t)-1,t),e,2)}function xt(t,e){return y(t.getUTCFullYear()%100,e,2)}function kt(t,e){return y((t=vt(t)).getUTCFullYear()%100,e,2)}function qt(t,e){return y(t.getUTCFullYear()%1e4,e,4)}function Nt(t,e){var n=t.getUTCDay();return y((t=n>=4||0===n?(0,r.hB)(t):r.hB.ceil(t)).getUTCFullYear()%1e4,e,4)}function St(){return"+0000"}function At(){return"%"}function Mt(t){return+t}function Tt(t){return Math.floor(+t/1e3)}},8467:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,a:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*o.yB)/o.UD),(t=>t.getDate()-1));const s=i;var a=i.range},9123:(t,e,n)=>{"use strict";n.d(e,{UD:()=>s,Y2:()=>i,Ym:()=>r,iM:()=>a,jz:()=>l,qz:()=>c,yB:()=>o});const r=1e3,o=60*r,i=60*o,s=24*i,a=7*s,l=30*s,c=365*s},6596:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,i:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*o.Ym-t.getMinutes()*o.yB)}),(function(t,e){t.setTime(+t+e*o.Y2)}),(function(t,e){return(e-t)/o.Y2}),(function(t){return t.getHours()}));const s=i;var a=i.range},3606:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=new Date,o=new Date;function i(t,e,n,s){function a(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return a.floor=function(e){return t(e=new Date(+e)),e},a.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},a.round=function(t){var e=a(t),n=a.ceil(t);return t-e<n-t?e:n},a.offset=function(t,n){return e(t=new Date(+t),null==n?1:Math.floor(n)),t},a.range=function(n,r,o){var i,s=[];if(n=a.ceil(n),o=null==o?1:Math.floor(o),!(n<r&&o>0))return s;do{s.push(i=new Date(+n)),e(n,o),t(n)}while(i<n&&n<r);return s},a.filter=function(n){return i((function(e){if(e>=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(a.count=function(e,i){return r.setTime(+e),o.setTime(+i),t(r),t(o),Math.floor(n(r,o))},a.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?a.filter(s?function(e){return s(e)%t==0}:function(e){return a.count(0,e)%t==0}):a:null}),a}},8383:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,m:()=>s});var r=n(3606),o=(0,r.Z)((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));o.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?(0,r.Z)((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):o:null};const i=o;var s=o.range},2991:(t,e,n)=>{"use strict";n.d(e,{L:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*o.Ym)}),(function(t,e){t.setTime(+t+e*o.yB)}),(function(t,e){return(e-t)/o.yB}),(function(t){return t.getMinutes()}));const s=i;var a=i.range},7905:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,e:()=>i});var r=(0,n(3606).Z)((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const o=r;var i=r.range},1343:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,m:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*o.Ym)}),(function(t,e){return(e-t)/o.Ym}),(function(t){return t.getUTCSeconds()}));const s=i;var a=i.range},7150:(t,e,n)=>{"use strict";n.d(e,{WG:()=>_,_g:()=>q,jK:()=>k,jo:()=>x});var r=n(3292),o=n(6106),i=n(9123),s=n(8383),a=n(1343),l=n(2991),c=n(6596),u=n(8467),f=n(6018),d=n(7905),h=n(2311),p=n(8593),m=n(8927),g=n(7445),y=n(1887),v=n(7351),b=n(4552);function w(t,e,n,l,c,u){const f=[[a.Z,1,i.Ym],[a.Z,5,5*i.Ym],[a.Z,15,15*i.Ym],[a.Z,30,30*i.Ym],[u,1,i.yB],[u,5,5*i.yB],[u,15,15*i.yB],[u,30,30*i.yB],[c,1,i.Y2],[c,3,3*i.Y2],[c,6,6*i.Y2],[c,12,12*i.Y2],[l,1,i.UD],[l,2,2*i.UD],[n,1,i.iM],[e,1,i.jz],[e,3,3*i.jz],[t,1,i.qz]];function d(e,n,a){const l=Math.abs(n-e)/a,c=(0,r.Z)((([,,t])=>t)).right(f,l);if(c===f.length)return t.every((0,o.ly)(e/i.qz,n/i.qz,a));if(0===c)return s.Z.every(Math.max((0,o.ly)(e,n,a),1));const[u,d]=f[l/f[c-1][2]<f[c][2]/l?c-1:c];return u.every(d)}return[function(t,e,n){const r=e<t;r&&([t,e]=[e,t]);const o=n&&"function"==typeof n.range?n:d(t,e,n),i=o?o.range(t,+e+1):[];return r?i.reverse():i},d]}const[_,x]=w(b.Z,v.Z,y.Ox,g.Z,m.Z,p.Z),[k,q]=w(h.Z,d.Z,f.OM,u.Z,c.Z,l.Z)},7445:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,y:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/o.UD}),(function(t){return t.getUTCDate()-1}));const s=i;var a=i.range},8927:(t,e,n)=>{"use strict";n.d(e,{X:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*o.Y2)}),(function(t,e){return(e-t)/o.Y2}),(function(t){return t.getUTCHours()}));const s=i;var a=i.range},8593:(t,e,n)=>{"use strict";n.d(e,{N:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*o.yB)}),(function(t,e){return(e-t)/o.yB}),(function(t){return t.getUTCMinutes()}));const s=i;var a=i.range},7351:(t,e,n)=>{"use strict";n.d(e,{K:()=>i,Z:()=>o});var r=(0,n(3606).Z)((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const o=r;var i=r.range},1887:(t,e,n)=>{"use strict";n.d(e,{$3:()=>p,DK:()=>m,J1:()=>l,Ox:()=>s,QQ:()=>f,Q_:()=>b,SU:()=>h,b3:()=>c,fz:()=>v,g4:()=>d,hB:()=>u,l6:()=>a,uy:()=>g,xj:()=>y});var r=n(3606),o=n(9123);function i(t){return(0,r.Z)((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/o.iM}))}var s=i(0),a=i(1),l=i(2),c=i(3),u=i(4),f=i(5),d=i(6),h=s.range,p=a.range,m=l.range,g=c.range,y=u.range,v=f.range,b=d.range},4552:(t,e,n)=>{"use strict";n.d(e,{D:()=>s,Z:()=>i});var r=n(3606),o=(0,r.Z)((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));o.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const i=o;var s=o.range},6018:(t,e,n)=>{"use strict";n.d(e,{$t:()=>y,EY:()=>d,Ff:()=>b,Ld:()=>g,OM:()=>s,aU:()=>m,b$:()=>v,bJ:()=>p,bL:()=>u,mC:()=>f,sy:()=>l,vm:()=>h,wA:()=>a,zg:()=>c});var r=n(3606),o=n(9123);function i(t){return(0,r.Z)((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*o.yB)/o.iM}))}var s=i(0),a=i(1),l=i(2),c=i(3),u=i(4),f=i(5),d=i(6),h=s.range,p=a.range,m=l.range,g=c.range,y=u.range,v=f.range,b=d.range},2311:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,g:()=>s});var r=n(3606),o=(0,r.Z)((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));o.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const i=o;var s=o.range},3016:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>r.Adder,Delaunay:()=>ti,FormatSpecifier:()=>ta.v,InternMap:()=>r.InternMap,InternSet:()=>r.InternSet,Node:()=>ld.NB,Voronoi:()=>Ho,ZoomTransform:()=>Rv,active:()=>gn,arc:()=>eg,area:()=>cg,areaRadial:()=>vg,ascending:()=>r.ascending,autoType:()=>vi,axisBottom:()=>v,axisLeft:()=>b,axisRight:()=>y,axisTop:()=>g,bin:()=>r.bin,bisect:()=>r.bisect,bisectCenter:()=>r.bisectCenter,bisectLeft:()=>r.bisectLeft,bisectRight:()=>r.bisectRight,bisector:()=>r.bisector,blob:()=>as,blur:()=>r.blur,blur2:()=>r.blur2,blurImage:()=>r.blurImage,brush:()=>Gn,brushSelection:()=>zn,brushX:()=>Un,brushY:()=>Bn,buffer:()=>cs,chord:()=>nr,chordDirected:()=>or,chordTranspose:()=>rr,cluster:()=>ad,color:()=>$e.ZP,contourDensity:()=>xo,contours:()=>go,count:()=>r.count,create:()=>Cm,creator:()=>Nt,cross:()=>r.cross,csv:()=>ps,csvFormat:()=>di,csvFormatBody:()=>hi,csvFormatRow:()=>mi,csvFormatRows:()=>pi,csvFormatValue:()=>gi,csvParse:()=>ui,csvParseRows:()=>fi,cubehelix:()=>no,cumsum:()=>r.cumsum,curveBasis:()=>ly,curveBasisClosed:()=>uy,curveBasisOpen:()=>dy,curveBumpX:()=>xg,curveBumpY:()=>kg,curveBundle:()=>py,curveCardinal:()=>yy,curveCardinalClosed:()=>by,curveCardinalOpen:()=>_y,curveCatmullRom:()=>qy,curveCatmullRomClosed:()=>Sy,curveCatmullRomOpen:()=>My,curveLinear:()=>ig,curveLinearClosed:()=>Cy,curveMonotoneX:()=>Dy,curveMonotoneY:()=>Ly,curveNatural:()=>zy,curveStep:()=>By,curveStepAfter:()=>Jy,curveStepBefore:()=>Gy,descending:()=>r.descending,deviation:()=>r.deviation,difference:()=>r.difference,disjoint:()=>r.disjoint,dispatch:()=>N,drag:()=>ai,dragDisable:()=>Bt,dragEnable:()=>Gt,dsv:()=>hs,dsvFormat:()=>li.Z,easeBack:()=>es,easeBackIn:()=>Qi,easeBackInOut:()=>es,easeBackOut:()=>ts,easeBounce:()=>Yi,easeBounceIn:()=>Vi,easeBounceInOut:()=>Ki,easeBounceOut:()=>Yi,easeCircle:()=>Di,easeCircleIn:()=>Pi,easeCircleInOut:()=>Di,easeCircleOut:()=>Fi,easeCubic:()=>dn,easeCubicIn:()=>un,easeCubicInOut:()=>dn,easeCubicOut:()=>fn,easeElastic:()=>os,easeElasticIn:()=>rs,easeElasticInOut:()=>is,easeElasticOut:()=>os,easeExp:()=>Ri,easeExpIn:()=>Oi,easeExpInOut:()=>Ri,easeExpOut:()=>Ii,easeLinear:()=>wi,easePoly:()=>Si,easePolyIn:()=>qi,easePolyInOut:()=>Si,easePolyOut:()=>Ni,easeQuad:()=>ki,easeQuadIn:()=>_i,easeQuadInOut:()=>ki,easeQuadOut:()=>xi,easeSin:()=>ji,easeSinIn:()=>Ti,easeSinInOut:()=>ji,easeSinOut:()=>Ci,every:()=>r.every,extent:()=>r.extent,fcumsum:()=>r.fcumsum,filter:()=>r.filter,flatGroup:()=>r.flatGroup,flatRollup:()=>r.flatRollup,forceCenter:()=>ks,forceCollide:()=>Ps,forceLink:()=>Ls,forceManyBody:()=>Hs,forceRadial:()=>Vs,forceSimulation:()=>Ws,forceX:()=>Ys,forceY:()=>Ks,format:()=>Xs.WU,formatDefaultLocale:()=>Xs.ZP,formatLocale:()=>Qs.Z,formatPrefix:()=>Xs.jH,formatSpecifier:()=>ta.Z,fsum:()=>r.fsum,geoAlbers:()=>xf,geoAlbersUsa:()=>kf,geoArea:()=>il,geoAzimuthalEqualArea:()=>Af,geoAzimuthalEqualAreaRaw:()=>Sf,geoAzimuthalEquidistant:()=>Tf,geoAzimuthalEquidistantRaw:()=>Mf,geoBounds:()=>$l,geoCentroid:()=>Xl,geoCircle:()=>cc,geoClipAntimeridian:()=>_c,geoClipCircle:()=>xc,geoClipExtent:()=>Cc,geoClipRectangle:()=>Tc,geoConicConformal:()=>Rf,geoConicConformalRaw:()=>If,geoConicEqualArea:()=>_f,geoConicEqualAreaRaw:()=>wf,geoConicEquidistant:()=>Lf,geoConicEquidistantRaw:()=>Df,geoContains:()=>Wc,geoDistance:()=>Dc,geoEqualEarth:()=>Jf,geoEqualEarthRaw:()=>Gf,geoEquirectangular:()=>Ff,geoEquirectangularRaw:()=>Pf,geoGnomonic:()=>Hf,geoGnomonicRaw:()=>Wf,geoGraticule:()=>Kc,geoGraticule10:()=>Xc,geoIdentity:()=>Vf,geoInterpolate:()=>Qc,geoLength:()=>Rc,geoMercator:()=>jf,geoMercatorRaw:()=>Cf,geoNaturalEarth1:()=>Kf,geoNaturalEarth1Raw:()=>Yf,geoOrthographic:()=>Qf,geoOrthographicRaw:()=>Xf,geoPath:()=>nf,geoProjection:()=>yf,geoProjectionMutator:()=>vf,geoRotation:()=>sc,geoStereographic:()=>ed,geoStereographicRaw:()=>td,geoStream:()=>Ra,geoTransform:()=>rf,geoTransverseMercator:()=>rd,geoTransverseMercatorRaw:()=>nd,gray:()=>Pr,greatest:()=>r.greatest,greatestIndex:()=>r.greatestIndex,group:()=>r.group,groupSort:()=>r.groupSort,groups:()=>r.groups,hcl:()=>Gr,hierarchy:()=>ld.ZP,histogram:()=>r.histogram,hsl:()=>$e.Ym,html:()=>_s,image:()=>gs,index:()=>r.index,indexes:()=>r.indexes,interpolate:()=>Jt.Z,interpolateArray:()=>eh.Z,interpolateBasis:()=>nh.Z,interpolateBasisClosed:()=>rh.Z,interpolateBlues:()=>rm,interpolateBrBG:()=>mp,interpolateBuGn:()=>Op,interpolateBuPu:()=>Rp,interpolateCividis:()=>pm,interpolateCool:()=>ym,interpolateCubehelix:()=>_h,interpolateCubehelixDefault:()=>mm,interpolateCubehelixLong:()=>xh,interpolateDate:()=>oh.Z,interpolateDiscrete:()=>ih,interpolateGnBu:()=>Fp,interpolateGreens:()=>im,interpolateGreys:()=>am,interpolateHcl:()=>vh,interpolateHclLong:()=>bh,interpolateHsl:()=>ph,interpolateHslLong:()=>mh,interpolateHue:()=>ah,interpolateInferno:()=>Mm,interpolateLab:()=>gh,interpolateMagma:()=>Am,interpolateNumber:()=>Ce.Z,interpolateNumberArray:()=>lh.Z,interpolateObject:()=>ch.Z,interpolateOrRd:()=>Lp,interpolateOranges:()=>hm,interpolatePRGn:()=>yp,interpolatePiYG:()=>bp,interpolatePlasma:()=>Tm,interpolatePuBu:()=>Up,interpolatePuBuGn:()=>Zp,interpolatePuOr:()=>_p,interpolatePuRd:()=>Gp,interpolatePurples:()=>cm,interpolateRainbow:()=>bm,interpolateRdBu:()=>kp,interpolateRdGy:()=>Np,interpolateRdPu:()=>Wp,interpolateRdYlBu:()=>Ap,interpolateRdYlGn:()=>Tp,interpolateReds:()=>fm,interpolateRgb:()=>Ze.ZP,interpolateRgbBasis:()=>Ze.hD,interpolateRgbBasisClosed:()=>Ze.YD,interpolateRound:()=>uh.Z,interpolateSinebow:()=>km,interpolateSpectral:()=>jp,interpolateString:()=>ze.Z,interpolateTransformCss:()=>Re,interpolateTransformSvg:()=>Pe,interpolateTurbo:()=>qm,interpolateViridis:()=>Sm,interpolateWarm:()=>gm,interpolateYlGn:()=>Kp,interpolateYlGnBu:()=>Vp,interpolateYlOrBr:()=>Qp,interpolateYlOrRd:()=>em,interpolateZoom:()=>dh,interrupt:()=>Me,intersection:()=>r.intersection,interval:()=>Ev,isoFormat:()=>Tv,isoParse:()=>jv,json:()=>vs,lab:()=>Fr,lch:()=>Br,least:()=>r.least,leastIndex:()=>r.leastIndex,line:()=>lg,lineRadial:()=>yg,link:()=>Ag,linkHorizontal:()=>Mg,linkRadial:()=>Cg,linkVertical:()=>Tg,local:()=>Em,map:()=>r.map,matcher:()=>j,max:()=>r.max,maxIndex:()=>r.maxIndex,mean:()=>r.mean,median:()=>r.median,medianIndex:()=>r.medianIndex,merge:()=>r.merge,min:()=>r.min,minIndex:()=>r.minIndex,mode:()=>r.mode,namespace:()=>J,namespaces:()=>G,nice:()=>r.nice,now:()=>se,pack:()=>Ed,packEnclose:()=>gd,packSiblings:()=>Cd,pairs:()=>r.pairs,partition:()=>Dd,path:()=>dr,permute:()=>r.permute,pie:()=>dg,piecewise:()=>kh.Z,pointRadial:()=>bg,pointer:()=>Ht,pointers:()=>Im,polygonArea:()=>Nh,polygonCentroid:()=>Sh,polygonContains:()=>jh,polygonHull:()=>Ch,polygonLength:()=>Eh,precisionFixed:()=>ea.Z,precisionPrefix:()=>na.Z,precisionRound:()=>ra.Z,quadtree:()=>Ms,quantile:()=>r.quantile,quantileIndex:()=>r.quantileIndex,quantileSorted:()=>r.quantileSorted,quantize:()=>qh,quickselect:()=>r.quickselect,radialArea:()=>vg,radialLine:()=>yg,randomBates:()=>Lh,randomBernoulli:()=>zh,randomBeta:()=>Gh,randomBinomial:()=>Jh,randomCauchy:()=>Hh,randomExponential:()=>$h,randomGamma:()=>Bh,randomGeometric:()=>Uh,randomInt:()=>Rh,randomIrwinHall:()=>Dh,randomLcg:()=>tp,randomLogNormal:()=>Fh,randomLogistic:()=>Vh,randomNormal:()=>Ph,randomPareto:()=>Zh,randomPoisson:()=>Yh,randomUniform:()=>Ih,randomWeibull:()=>Wh,range:()=>r.range,rank:()=>r.rank,reduce:()=>r.reduce,reverse:()=>r.reverse,rgb:()=>$e.B8,ribbon:()=>kr,ribbonArrow:()=>qr,rollup:()=>r.rollup,rollups:()=>r.rollups,scaleBand:()=>ep.scaleBand,scaleDiverging:()=>ep.scaleDiverging,scaleDivergingLog:()=>ep.scaleDivergingLog,scaleDivergingPow:()=>ep.scaleDivergingPow,scaleDivergingSqrt:()=>ep.scaleDivergingSqrt,scaleDivergingSymlog:()=>ep.scaleDivergingSymlog,scaleIdentity:()=>ep.scaleIdentity,scaleImplicit:()=>ep.scaleImplicit,scaleLinear:()=>ep.scaleLinear,scaleLog:()=>ep.scaleLog,scaleOrdinal:()=>ep.scaleOrdinal,scalePoint:()=>ep.scalePoint,scalePow:()=>ep.scalePow,scaleQuantile:()=>ep.scaleQuantile,scaleQuantize:()=>ep.scaleQuantize,scaleRadial:()=>ep.scaleRadial,scaleSequential:()=>ep.scaleSequential,scaleSequentialLog:()=>ep.scaleSequentialLog,scaleSequentialPow:()=>ep.scaleSequentialPow,scaleSequentialQuantile:()=>ep.scaleSequentialQuantile,scaleSequentialSqrt:()=>ep.scaleSequentialSqrt,scaleSequentialSymlog:()=>ep.scaleSequentialSymlog,scaleSqrt:()=>ep.scaleSqrt,scaleSymlog:()=>ep.scaleSymlog,scaleThreshold:()=>ep.scaleThreshold,scaleTime:()=>ep.scaleTime,scaleUtc:()=>ep.scaleUtc,scan:()=>r.scan,schemeAccent:()=>op,schemeBlues:()=>nm,schemeBrBG:()=>pp,schemeBuGn:()=>Ep,schemeBuPu:()=>Ip,schemeCategory10:()=>np.Z,schemeDark2:()=>ip,schemeGnBu:()=>Pp,schemeGreens:()=>om,schemeGreys:()=>sm,schemeOrRd:()=>Dp,schemeOranges:()=>dm,schemePRGn:()=>gp,schemePaired:()=>sp,schemePastel1:()=>ap,schemePastel2:()=>lp,schemePiYG:()=>vp,schemePuBu:()=>zp,schemePuBuGn:()=>$p,schemePuOr:()=>wp,schemePuRd:()=>Bp,schemePurples:()=>lm,schemeRdBu:()=>xp,schemeRdGy:()=>qp,schemeRdPu:()=>Jp,schemeRdYlBu:()=>Sp,schemeRdYlGn:()=>Mp,schemeReds:()=>um,schemeSet1:()=>cp,schemeSet2:()=>up,schemeSet3:()=>fp,schemeSpectral:()=>Cp,schemeTableau10:()=>dp,schemeYlGn:()=>Yp,schemeYlGnBu:()=>Hp,schemeYlOrBr:()=>Xp,schemeYlOrRd:()=>tm,select:()=>Lt,selectAll:()=>Rm,selection:()=>Dt,selector:()=>A,selectorAll:()=>C,shuffle:()=>r.shuffle,shuffler:()=>r.shuffler,some:()=>r.some,sort:()=>r.sort,stack:()=>Ky,stackOffsetDiverging:()=>Qy,stackOffsetExpand:()=>Xy,stackOffsetNone:()=>Wy,stackOffsetSilhouette:()=>tv,stackOffsetWiggle:()=>ev,stackOrderAppearance:()=>nv,stackOrderAscending:()=>ov,stackOrderDescending:()=>sv,stackOrderInsideOut:()=>av,stackOrderNone:()=>Hy,stackOrderReverse:()=>lv,stratify:()=>Ld.Z,style:()=>rt,subset:()=>r.subset,sum:()=>r.sum,superset:()=>r.superset,svg:()=>xs,symbol:()=>oy,symbolAsterisk:()=>Eg,symbolCircle:()=>Og,symbolCross:()=>Ig,symbolDiamond:()=>Fg,symbolDiamond2:()=>Dg,symbolPlus:()=>Lg,symbolSquare:()=>$g,symbolSquare2:()=>Zg,symbolStar:()=>Gg,symbolTriangle:()=>Wg,symbolTriangle2:()=>Vg,symbolWye:()=>ty,symbolX:()=>ey,symbols:()=>ny,symbolsFill:()=>ny,symbolsStroke:()=>ry,text:()=>fs,thresholdFreedmanDiaconis:()=>r.thresholdFreedmanDiaconis,thresholdScott:()=>r.thresholdScott,thresholdSturges:()=>r.thresholdSturges,tickFormat:()=>ep.tickFormat,tickIncrement:()=>r.tickIncrement,tickStep:()=>r.tickStep,ticks:()=>r.ticks,timeDay:()=>pv.Z,timeDays:()=>pv.a,timeFormat:()=>Nv.i$,timeFormatDefaultLocale:()=>Nv.ZP,timeFormatLocale:()=>Sv.Z,timeFriday:()=>mv.mC,timeFridays:()=>mv.b$,timeHour:()=>hv.Z,timeHours:()=>hv.i,timeInterval:()=>cv.Z,timeMillisecond:()=>uv.Z,timeMilliseconds:()=>uv.m,timeMinute:()=>dv.Z,timeMinutes:()=>dv.L,timeMonday:()=>mv.wA,timeMondays:()=>mv.bJ,timeMonth:()=>gv.Z,timeMonths:()=>gv.e,timeParse:()=>Nv.Z1,timeSaturday:()=>mv.EY,timeSaturdays:()=>mv.Ff,timeSecond:()=>fv.Z,timeSeconds:()=>fv.m,timeSunday:()=>mv.OM,timeSundays:()=>mv.vm,timeThursday:()=>mv.bL,timeThursdays:()=>mv.$t,timeTickInterval:()=>qv._g,timeTicks:()=>qv.jK,timeTuesday:()=>mv.sy,timeTuesdays:()=>mv.aU,timeWednesday:()=>mv.zg,timeWednesdays:()=>mv.Ld,timeWeek:()=>mv.OM,timeWeeks:()=>mv.vm,timeYear:()=>yv.Z,timeYears:()=>yv.g,timeout:()=>pe,timer:()=>ce,timerFlush:()=>ue,transition:()=>an,transpose:()=>r.transpose,tree:()=>Jd,treemap:()=>Kd,treemapBinary:()=>Xd,treemapDice:()=>Fd,treemapResquarify:()=>th,treemapSlice:()=>Wd,treemapSliceDice:()=>Qd,treemapSquarify:()=>Yd,tsv:()=>ms,tsvFormat:()=>yi.vP,tsvFormatBody:()=>yi.uH,tsvFormatRow:()=>yi.Hf,tsvFormatRows:()=>yi.n5,tsvFormatValue:()=>yi.sS,tsvParse:()=>yi.tJ,tsvParseRows:()=>yi.E0,union:()=>r.union,utcDay:()=>wv.Z,utcDays:()=>wv.y,utcFormat:()=>Nv.g0,utcFriday:()=>_v.QQ,utcFridays:()=>_v.fz,utcHour:()=>bv.Z,utcHours:()=>bv.X,utcMillisecond:()=>uv.Z,utcMilliseconds:()=>uv.m,utcMinute:()=>vv.Z,utcMinutes:()=>vv.N,utcMonday:()=>_v.l6,utcMondays:()=>_v.$3,utcMonth:()=>xv.Z,utcMonths:()=>xv.K,utcParse:()=>Nv.wp,utcSaturday:()=>_v.g4,utcSaturdays:()=>_v.Q_,utcSecond:()=>fv.Z,utcSeconds:()=>fv.m,utcSunday:()=>_v.Ox,utcSundays:()=>_v.SU,utcThursday:()=>_v.hB,utcThursdays:()=>_v.xj,utcTickInterval:()=>qv.jo,utcTicks:()=>qv.WG,utcTuesday:()=>_v.J1,utcTuesdays:()=>_v.DK,utcWednesday:()=>_v.b3,utcWednesdays:()=>_v.uy,utcWeek:()=>_v.Ox,utcWeeks:()=>_v.SU,utcYear:()=>kv.Z,utcYears:()=>kv.D,variance:()=>r.variance,window:()=>Q,xml:()=>ws,zip:()=>r.zip,zoom:()=>Jv,zoomIdentity:()=>Pv,zoomTransform:()=>Fv});var r=n(9060);function o(t){return t}var i=1,s=2,a=3,l=4,c=1e-6;function u(t){return"translate("+t+",0)"}function f(t){return"translate(0,"+t+")"}function d(t){return e=>+t(e)}function h(t,e){return e=Math.max(0,t.bandwidth()-2*e)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function p(){return!this.__axis}function m(t,e){var n=[],r=null,m=null,g=6,y=6,v=3,b="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,w=t===i||t===l?-1:1,_=t===l||t===s?"x":"y",x=t===i||t===a?u:f;function k(u){var f=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,k=null==m?e.tickFormat?e.tickFormat.apply(e,n):o:m,q=Math.max(g,0)+v,N=e.range(),S=+N[0]+b,A=+N[N.length-1]+b,M=(e.bandwidth?h:d)(e.copy(),b),T=u.selection?u.selection():u,C=T.selectAll(".domain").data([null]),j=T.selectAll(".tick").data(f,e).order(),E=j.exit(),O=j.enter().append("g").attr("class","tick"),I=j.select("line"),R=j.select("text");C=C.merge(C.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),j=j.merge(O),I=I.merge(O.append("line").attr("stroke","currentColor").attr(_+"2",w*g)),R=R.merge(O.append("text").attr("fill","currentColor").attr(_,w*q).attr("dy",t===i?"0em":t===a?"0.71em":"0.32em")),u!==T&&(C=C.transition(u),j=j.transition(u),I=I.transition(u),R=R.transition(u),E=E.transition(u).attr("opacity",c).attr("transform",(function(t){return isFinite(t=M(t))?x(t+b):this.getAttribute("transform")})),O.attr("opacity",c).attr("transform",(function(t){var e=this.parentNode.__axis;return x((e&&isFinite(e=e(t))?e:M(t))+b)}))),E.remove(),C.attr("d",t===l||t===s?y?"M"+w*y+","+S+"H"+b+"V"+A+"H"+w*y:"M"+b+","+S+"V"+A:y?"M"+S+","+w*y+"V"+b+"H"+A+"V"+w*y:"M"+S+","+b+"H"+A),j.attr("opacity",1).attr("transform",(function(t){return x(M(t)+b)})),I.attr(_+"2",w*g),R.attr(_,w*q).text(k),T.filter(p).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===s?"start":t===l?"end":"middle"),T.each((function(){this.__axis=M}))}return k.scale=function(t){return arguments.length?(e=t,k):e},k.ticks=function(){return n=Array.from(arguments),k},k.tickArguments=function(t){return arguments.length?(n=null==t?[]:Array.from(t),k):n.slice()},k.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),k):r&&r.slice()},k.tickFormat=function(t){return arguments.length?(m=t,k):m},k.tickSize=function(t){return arguments.length?(g=y=+t,k):g},k.tickSizeInner=function(t){return arguments.length?(g=+t,k):g},k.tickSizeOuter=function(t){return arguments.length?(y=+t,k):y},k.tickPadding=function(t){return arguments.length?(v=+t,k):v},k.offset=function(t){return arguments.length?(b=+t,k):b},k}function g(t){return m(i,t)}function y(t){return m(s,t)}function v(t){return m(a,t)}function b(t){return m(l,t)}var w={value:()=>{}};function _(){for(var t,e=0,n=arguments.length,r={};e<n;++e){if(!(t=arguments[e]+"")||t in r||/[\s.]/.test(t))throw new Error("illegal type: "+t);r[t]=[]}return new x(r)}function x(t){this._=t}function k(t,e){for(var n,r=0,o=t.length;r<o;++r)if((n=t[r]).name===e)return n.value}function q(t,e,n){for(var r=0,o=t.length;r<o;++r)if(t[r].name===e){t[r]=w,t=t.slice(0,r).concat(t.slice(r+1));break}return null!=n&&t.push({name:e,value:n}),t}x.prototype=_.prototype={constructor:x,on:function(t,e){var n,r,o=this._,i=(r=o,(t+"").trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");if(n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))),s=-1,a=i.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++s<a;)if(n=(t=i[s]).type)o[n]=q(o[n],t.name,e);else if(null==e)for(n in o)o[n]=q(o[n],t.name,null);return this}for(;++s<a;)if((n=(t=i[s]).type)&&(n=k(o[n],t.name)))return n},copy:function(){var t={},e=this._;for(var n in e)t[n]=e[n].slice();return new x(t)},call:function(t,e){if((n=arguments.length-2)>0)for(var n,r,o=new Array(n),i=0;i<n;++i)o[i]=arguments[i+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(i=0,n=(r=this._[t]).length;i<n;++i)r[i].value.apply(e,o)},apply:function(t,e,n){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],o=0,i=r.length;o<i;++o)r[o].value.apply(e,n)}};const N=_;function S(){}function A(t){return null==t?S:function(){return this.querySelector(t)}}function M(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function T(){return[]}function C(t){return null==t?T:function(){return this.querySelectorAll(t)}}function j(t){return function(){return this.matches(t)}}function E(t){return function(e){return e.matches(t)}}var O=Array.prototype.find;function I(){return this.firstElementChild}var R=Array.prototype.filter;function P(){return Array.from(this.children)}function F(t){return new Array(t.length)}function D(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}function L(t,e,n,r,o,i){for(var s,a=0,l=e.length,c=i.length;a<c;++a)(s=e[a])?(s.__data__=i[a],r[a]=s):n[a]=new D(t,i[a]);for(;a<l;++a)(s=e[a])&&(o[a]=s)}function $(t,e,n,r,o,i,s){var a,l,c,u=new Map,f=e.length,d=i.length,h=new Array(f);for(a=0;a<f;++a)(l=e[a])&&(h[a]=c=s.call(l,l.__data__,a,e)+"",u.has(c)?o[a]=l:u.set(c,l));for(a=0;a<d;++a)c=s.call(t,i[a],a,i)+"",(l=u.get(c))?(r[a]=l,l.__data__=i[a],u.delete(c)):n[a]=new D(t,i[a]);for(a=0;a<f;++a)(l=e[a])&&u.get(h[a])===l&&(o[a]=l)}function Z(t){return t.__data__}function z(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function U(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}D.prototype={constructor:D,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var B="http://www.w3.org/1999/xhtml";const G={svg:"http://www.w3.org/2000/svg",xhtml:B,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function J(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),G.hasOwnProperty(e)?{space:G[e],local:t}:t}function W(t){return function(){this.removeAttribute(t)}}function H(t){return function(){this.removeAttributeNS(t.space,t.local)}}function V(t,e){return function(){this.setAttribute(t,e)}}function Y(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function K(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function X(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function Q(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function tt(t){return function(){this.style.removeProperty(t)}}function et(t,e,n){return function(){this.style.setProperty(t,e,n)}}function nt(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function rt(t,e){return t.style.getPropertyValue(e)||Q(t).getComputedStyle(t,null).getPropertyValue(e)}function ot(t){return function(){delete this[t]}}function it(t,e){return function(){this[t]=e}}function st(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function at(t){return t.trim().split(/^|\s+/)}function lt(t){return t.classList||new ct(t)}function ct(t){this._node=t,this._names=at(t.getAttribute("class")||"")}function ut(t,e){for(var n=lt(t),r=-1,o=e.length;++r<o;)n.add(e[r])}function ft(t,e){for(var n=lt(t),r=-1,o=e.length;++r<o;)n.remove(e[r])}function dt(t){return function(){ut(this,t)}}function ht(t){return function(){ft(this,t)}}function pt(t,e){return function(){(e.apply(this,arguments)?ut:ft)(this,t)}}function mt(){this.textContent=""}function gt(t){return function(){this.textContent=t}}function yt(t){return function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}}function vt(){this.innerHTML=""}function bt(t){return function(){this.innerHTML=t}}function wt(t){return function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}}function _t(){this.nextSibling&&this.parentNode.appendChild(this)}function xt(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kt(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===B&&e.documentElement.namespaceURI===B?e.createElement(t):e.createElementNS(n,t)}}function qt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Nt(t){var e=J(t);return(e.local?qt:kt)(e)}function St(){return null}function At(){var t=this.parentNode;t&&t.removeChild(this)}function Mt(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Tt(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Ct(t){return function(){var e=this.__on;if(e){for(var n,r=0,o=-1,i=e.length;r<i;++r)n=e[r],t.type&&n.type!==t.type||n.name!==t.name?e[++o]=n:this.removeEventListener(n.type,n.listener,n.options);++o?e.length=o:delete this.__on}}}function jt(t,e,n){return function(){var r,o=this.__on,i=function(t){return function(e){t.call(this,e,this.__data__)}}(e);if(o)for(var s=0,a=o.length;s<a;++s)if((r=o[s]).type===t.type&&r.name===t.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=i,r.options=n),void(r.value=e);this.addEventListener(t.type,i,n),r={type:t.type,name:t.name,value:e,listener:i,options:n},o?o.push(r):this.__on=[r]}}function Et(t,e,n){var r=Q(t),o=r.CustomEvent;"function"==typeof o?o=new o(e,n):(o=r.document.createEvent("Event"),n?(o.initEvent(e,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(e,!1,!1)),t.dispatchEvent(o)}function Ot(t,e){return function(){return Et(this,t,e)}}function It(t,e){return function(){return Et(this,t,e.apply(this,arguments))}}ct.prototype={add:function(t){this._names.indexOf(t)<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Rt=[null];function Pt(t,e){this._groups=t,this._parents=e}function Ft(){return new Pt([[document.documentElement]],Rt)}Pt.prototype=Ft.prototype={constructor:Pt,select:function(t){"function"!=typeof t&&(t=A(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s,a=e[o],l=a.length,c=r[o]=new Array(l),u=0;u<l;++u)(i=a[u])&&(s=t.call(i,i.__data__,u,a))&&("__data__"in i&&(s.__data__=i.__data__),c[u]=s);return new Pt(r,this._parents)},selectAll:function(t){t="function"==typeof t?function(t){return function(){return M(t.apply(this,arguments))}}(t):C(t);for(var e=this._groups,n=e.length,r=[],o=[],i=0;i<n;++i)for(var s,a=e[i],l=a.length,c=0;c<l;++c)(s=a[c])&&(r.push(t.call(s,s.__data__,c,a)),o.push(s));return new Pt(r,o)},selectChild:function(t){return this.select(null==t?I:function(t){return function(){return O.call(this.children,t)}}("function"==typeof t?t:E(t)))},selectChildren:function(t){return this.selectAll(null==t?P:function(t){return function(){return R.call(this.children,t)}}("function"==typeof t?t:E(t)))},filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s=e[o],a=s.length,l=r[o]=[],c=0;c<a;++c)(i=s[c])&&t.call(i,i.__data__,c,s)&&l.push(i);return new Pt(r,this._parents)},data:function(t,e){if(!arguments.length)return Array.from(this,Z);var n=e?$:L,r=this._parents,o=this._groups;"function"!=typeof t&&(t=function(t){return function(){return t}}(t));for(var i=o.length,s=new Array(i),a=new Array(i),l=new Array(i),c=0;c<i;++c){var u=r[c],f=o[c],d=f.length,h=z(t.call(u,u&&u.__data__,c,r)),p=h.length,m=a[c]=new Array(p),g=s[c]=new Array(p);n(u,f,m,g,l[c]=new Array(d),h,e);for(var y,v,b=0,w=0;b<p;++b)if(y=m[b]){for(b>=w&&(w=b+1);!(v=g[w])&&++w<p;);y._next=v||null}}return(s=new Pt(s,r))._enter=a,s._exit=l,s},enter:function(){return new Pt(this._enter||this._groups.map(F),this._parents)},exit:function(){return new Pt(this._exit||this._groups.map(F),this._parents)},join:function(t,e,n){var r=this.enter(),o=this,i=this.exit();return"function"==typeof t?(r=t(r))&&(r=r.selection()):r=r.append(t+""),null!=e&&(o=e(o))&&(o=o.selection()),null==n?i.remove():n(i),r&&o?r.merge(o).order():o},merge:function(t){for(var e=t.selection?t.selection():t,n=this._groups,r=e._groups,o=n.length,i=r.length,s=Math.min(o,i),a=new Array(o),l=0;l<s;++l)for(var c,u=n[l],f=r[l],d=u.length,h=a[l]=new Array(d),p=0;p<d;++p)(c=u[p]||f[p])&&(h[p]=c);for(;l<o;++l)a[l]=n[l];return new Pt(a,this._parents)},selection:function(){return this},order:function(){for(var t=this._groups,e=-1,n=t.length;++e<n;)for(var r,o=t[e],i=o.length-1,s=o[i];--i>=0;)(r=o[i])&&(s&&4^r.compareDocumentPosition(s)&&s.parentNode.insertBefore(r,s),s=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=U);for(var n=this._groups,r=n.length,o=new Array(r),i=0;i<r;++i){for(var s,a=n[i],l=a.length,c=o[i]=new Array(l),u=0;u<l;++u)(s=a[u])&&(c[u]=s);c.sort(e)}return new Pt(o,this._parents).order()},call:function(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r=t[e],o=0,i=r.length;o<i;++o){var s=r[o];if(s)return s}return null},size:function(){let t=0;for(const e of this)++t;return t},empty:function(){return!this.node()},each:function(t){for(var e=this._groups,n=0,r=e.length;n<r;++n)for(var o,i=e[n],s=0,a=i.length;s<a;++s)(o=i[s])&&t.call(o,o.__data__,s,i);return this},attr:function(t,e){var n=J(t);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==e?n.local?H:W:"function"==typeof e?n.local?X:K:n.local?Y:V)(n,e))},style:function(t,e,n){return arguments.length>1?this.each((null==e?tt:"function"==typeof e?nt:et)(t,e,null==n?"":n)):rt(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?ot:"function"==typeof e?st:it)(t,e)):this.node()[t]},classed:function(t,e){var n=at(t+"");if(arguments.length<2){for(var r=lt(this.node()),o=-1,i=n.length;++o<i;)if(!r.contains(n[o]))return!1;return!0}return this.each(("function"==typeof e?pt:e?dt:ht)(n,e))},text:function(t){return arguments.length?this.each(null==t?mt:("function"==typeof t?yt:gt)(t)):this.node().textContent},html:function(t){return arguments.length?this.each(null==t?vt:("function"==typeof t?wt:bt)(t)):this.node().innerHTML},raise:function(){return this.each(_t)},lower:function(){return this.each(xt)},append:function(t){var e="function"==typeof t?t:Nt(t);return this.select((function(){return this.appendChild(e.apply(this,arguments))}))},insert:function(t,e){var n="function"==typeof t?t:Nt(t),r=null==e?St:"function"==typeof e?e:A(e);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(At)},clone:function(t){return this.select(t?Tt:Mt)},datum:function(t){return arguments.length?this.property("__data__",t):this.node().__data__},on:function(t,e,n){var r,o,i=function(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}(t+""),s=i.length;if(!(arguments.length<2)){for(a=e?jt:Ct,r=0;r<s;++r)this.each(a(i[r],e,n));return this}var a=this.node().__on;if(a)for(var l,c=0,u=a.length;c<u;++c)for(r=0,l=a[c];r<s;++r)if((o=i[r]).type===l.type&&o.name===l.name)return l.value},dispatch:function(t,e){return this.each(("function"==typeof e?It:Ot)(t,e))},[Symbol.iterator]:function*(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r,o=t[e],i=0,s=o.length;i<s;++i)(r=o[i])&&(yield r)}};const Dt=Ft;function Lt(t){return"string"==typeof t?new Pt([[document.querySelector(t)]],[document.documentElement]):new Pt([[t]],Rt)}const $t={passive:!1},Zt={capture:!0,passive:!1};function zt(t){t.stopImmediatePropagation()}function Ut(t){t.preventDefault(),t.stopImmediatePropagation()}function Bt(t){var e=t.document.documentElement,n=Lt(t).on("dragstart.drag",Ut,Zt);"onselectstart"in e?n.on("selectstart.drag",Ut,Zt):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none")}function Gt(t,e){var n=t.document.documentElement,r=Lt(t).on("dragstart.drag",null);e&&(r.on("click.drag",Ut,Zt),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}var Jt=n(2303);function Wt(t){let e;for(;e=t.sourceEvent;)t=e;return t}function Ht(t,e){if(t=Wt(t),void 0===e&&(e=t.currentTarget),e){var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=t.clientX,r.y=t.clientY,[(r=r.matrixTransform(e.getScreenCTM().inverse())).x,r.y]}if(e.getBoundingClientRect){var o=e.getBoundingClientRect();return[t.clientX-o.left-e.clientLeft,t.clientY-o.top-e.clientTop]}}return[t.pageX,t.pageY]}var Vt,Yt,Kt=0,Xt=0,Qt=0,te=1e3,ee=0,ne=0,re=0,oe="object"==typeof performance&&performance.now?performance:Date,ie="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function se(){return ne||(ie(ae),ne=oe.now()+re)}function ae(){ne=0}function le(){this._call=this._time=this._next=null}function ce(t,e,n){var r=new le;return r.restart(t,e,n),r}function ue(){se(),++Kt;for(var t,e=Vt;e;)(t=ne-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kt}function fe(){ne=(ee=oe.now())+re,Kt=Xt=0;try{ue()}finally{Kt=0,function(){var t,e,n=Vt,r=1/0;for(;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Vt=e);Yt=t,he(r)}(),ne=0}}function de(){var t=oe.now(),e=t-ee;e>te&&(re-=e,ee=t)}function he(t){Kt||(Xt&&(Xt=clearTimeout(Xt)),t-ne>24?(t<1/0&&(Xt=setTimeout(fe,t-oe.now()-re)),Qt&&(Qt=clearInterval(Qt))):(Qt||(ee=oe.now(),Qt=setInterval(de,te)),Kt=1,ie(fe)))}function pe(t,e,n){var r=new le;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}le.prototype=ce.prototype={constructor:le,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?se():+n)+(null==e?0:+e),this._next||Yt===this||(Yt?Yt._next=this:Vt=this,Yt=this),this._call=t,this._time=n,he()},stop:function(){this._call&&(this._call=null,this._time=1/0,he())}};var me=N("start","end","cancel","interrupt"),ge=[],ye=0,ve=1,be=2,we=3,_e=4,xe=5,ke=6;function qe(t,e,n,r,o,i){var s=t.__transition;if(s){if(n in s)return}else t.__transition={};!function(t,e,n){var r,o=t.__transition;function i(t){n.state=ve,n.timer.restart(s,n.delay,n.time),n.delay<=t&&s(t-n.delay)}function s(i){var c,u,f,d;if(n.state!==ve)return l();for(c in o)if((d=o[c]).name===n.name){if(d.state===we)return pe(s);d.state===_e?(d.state=ke,d.timer.stop(),d.on.call("interrupt",t,t.__data__,d.index,d.group),delete o[c]):+c<e&&(d.state=ke,d.timer.stop(),d.on.call("cancel",t,t.__data__,d.index,d.group),delete o[c])}if(pe((function(){n.state===we&&(n.state=_e,n.timer.restart(a,n.delay,n.time),a(i))})),n.state=be,n.on.call("start",t,t.__data__,n.index,n.group),n.state===be){for(n.state=we,r=new Array(f=n.tween.length),c=0,u=-1;c<f;++c)(d=n.tween[c].value.call(t,t.__data__,n.index,n.group))&&(r[++u]=d);r.length=u+1}}function a(e){for(var o=e<n.duration?n.ease.call(null,e/n.duration):(n.timer.restart(l),n.state=xe,1),i=-1,s=r.length;++i<s;)r[i].call(t,o);n.state===xe&&(n.on.call("end",t,t.__data__,n.index,n.group),l())}function l(){for(var r in n.state=ke,n.timer.stop(),delete o[e],o)return;delete t.__transition}o[e]=n,n.timer=ce(i,0,n.time)}(t,n,{name:e,index:r,group:o,on:me,tween:ge,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:ye})}function Ne(t,e){var n=Ae(t,e);if(n.state>ye)throw new Error("too late; already scheduled");return n}function Se(t,e){var n=Ae(t,e);if(n.state>we)throw new Error("too late; already running");return n}function Ae(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function Me(t,e){var n,r,o,i=t.__transition,s=!0;if(i){for(o in e=null==e?null:e+"",i)(n=i[o]).name===e?(r=n.state>be&&n.state<xe,n.state=ke,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete i[o]):s=!1;s&&delete t.__transition}}var Te,Ce=n(8403),je=180/Math.PI,Ee={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Oe(t,e,n,r,o,i){var s,a,l;return(s=Math.sqrt(t*t+e*e))&&(t/=s,e/=s),(l=t*n+e*r)&&(n-=t*l,r-=e*l),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,l/=a),t*r<e*n&&(t=-t,e=-e,l=-l,s=-s),{translateX:o,translateY:i,rotate:Math.atan2(e,t)*je,skewX:Math.atan(l)*je,scaleX:s,scaleY:a}}function Ie(t,e,n,r){function o(t){return t.length?t.pop()+" ":""}return function(i,s){var a=[],l=[];return i=t(i),s=t(s),function(t,r,o,i,s,a){if(t!==o||r!==i){var l=s.push("translate(",null,e,null,n);a.push({i:l-4,x:(0,Ce.Z)(t,o)},{i:l-2,x:(0,Ce.Z)(r,i)})}else(o||i)&&s.push("translate("+o+e+i+n)}(i.translateX,i.translateY,s.translateX,s.translateY,a,l),function(t,e,n,i){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),i.push({i:n.push(o(n)+"rotate(",null,r)-2,x:(0,Ce.Z)(t,e)})):e&&n.push(o(n)+"rotate("+e+r)}(i.rotate,s.rotate,a,l),function(t,e,n,i){t!==e?i.push({i:n.push(o(n)+"skewX(",null,r)-2,x:(0,Ce.Z)(t,e)}):e&&n.push(o(n)+"skewX("+e+r)}(i.skewX,s.skewX,a,l),function(t,e,n,r,i,s){if(t!==n||e!==r){var a=i.push(o(i)+"scale(",null,",",null,")");s.push({i:a-4,x:(0,Ce.Z)(t,n)},{i:a-2,x:(0,Ce.Z)(e,r)})}else 1===n&&1===r||i.push(o(i)+"scale("+n+","+r+")")}(i.scaleX,i.scaleY,s.scaleX,s.scaleY,a,l),i=s=null,function(t){for(var e,n=-1,r=l.length;++n<r;)a[(e=l[n]).i]=e.x(t);return a.join("")}}}var Re=Ie((function(t){const e=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?Ee:Oe(e.a,e.b,e.c,e.d,e.e,e.f)}),"px, ","px)","deg)"),Pe=Ie((function(t){return null==t?Ee:(Te||(Te=document.createElementNS("http://www.w3.org/2000/svg","g")),Te.setAttribute("transform",t),(t=Te.transform.baseVal.consolidate())?Oe((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):Ee)}),", ",")",")");function Fe(t,e){var n,r;return function(){var o=Se(this,t),i=o.tween;if(i!==n)for(var s=0,a=(r=n=i).length;s<a;++s)if(r[s].name===e){(r=r.slice()).splice(s,1);break}o.tween=r}}function De(t,e,n){var r,o;if("function"!=typeof n)throw new Error;return function(){var i=Se(this,t),s=i.tween;if(s!==r){o=(r=s).slice();for(var a={name:e,value:n},l=0,c=o.length;l<c;++l)if(o[l].name===e){o[l]=a;break}l===c&&o.push(a)}i.tween=o}}function Le(t,e,n){var r=t._id;return t.each((function(){var t=Se(this,r);(t.value||(t.value={}))[e]=n.apply(this,arguments)})),function(t){return Ae(t,r).value[e]}}var $e=n(1495),Ze=n(490),ze=n(9009);function Ue(t,e){var n;return("number"==typeof e?Ce.Z:e instanceof $e.ZP?Ze.ZP:(n=(0,$e.ZP)(e))?(e=n,Ze.ZP):ze.Z)(t,e)}function Be(t){return function(){this.removeAttribute(t)}}function Ge(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Je(t,e,n){var r,o,i=n+"";return function(){var s=this.getAttribute(t);return s===i?null:s===r?o:o=e(r=s,n)}}function We(t,e,n){var r,o,i=n+"";return function(){var s=this.getAttributeNS(t.space,t.local);return s===i?null:s===r?o:o=e(r=s,n)}}function He(t,e,n){var r,o,i;return function(){var s,a,l=n(this);if(null!=l)return(s=this.getAttribute(t))===(a=l+"")?null:s===r&&a===o?i:(o=a,i=e(r=s,l));this.removeAttribute(t)}}function Ve(t,e,n){var r,o,i;return function(){var s,a,l=n(this);if(null!=l)return(s=this.getAttributeNS(t.space,t.local))===(a=l+"")?null:s===r&&a===o?i:(o=a,i=e(r=s,l));this.removeAttributeNS(t.space,t.local)}}function Ye(t,e){var n,r;function o(){var o=e.apply(this,arguments);return o!==r&&(n=(r=o)&&function(t,e){return function(n){this.setAttributeNS(t.space,t.local,e.call(this,n))}}(t,o)),n}return o._value=e,o}function Ke(t,e){var n,r;function o(){var o=e.apply(this,arguments);return o!==r&&(n=(r=o)&&function(t,e){return function(n){this.setAttribute(t,e.call(this,n))}}(t,o)),n}return o._value=e,o}function Xe(t,e){return function(){Ne(this,t).delay=+e.apply(this,arguments)}}function Qe(t,e){return e=+e,function(){Ne(this,t).delay=e}}function tn(t,e){return function(){Se(this,t).duration=+e.apply(this,arguments)}}function en(t,e){return e=+e,function(){Se(this,t).duration=e}}var nn=Dt.prototype.constructor;function rn(t){return function(){this.style.removeProperty(t)}}var on=0;function sn(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function an(t){return Dt().transition(t)}function ln(){return++on}var cn=Dt.prototype;function un(t){return t*t*t}function fn(t){return--t*t*t+1}function dn(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}sn.prototype=an.prototype={constructor:sn,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=A(t));for(var r=this._groups,o=r.length,i=new Array(o),s=0;s<o;++s)for(var a,l,c=r[s],u=c.length,f=i[s]=new Array(u),d=0;d<u;++d)(a=c[d])&&(l=t.call(a,a.__data__,d,c))&&("__data__"in a&&(l.__data__=a.__data__),f[d]=l,qe(f[d],e,n,d,f,Ae(a,n)));return new sn(i,this._parents,e,n)},selectAll:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=C(t));for(var r=this._groups,o=r.length,i=[],s=[],a=0;a<o;++a)for(var l,c=r[a],u=c.length,f=0;f<u;++f)if(l=c[f]){for(var d,h=t.call(l,l.__data__,f,c),p=Ae(l,n),m=0,g=h.length;m<g;++m)(d=h[m])&&qe(d,e,n,m,h,p);i.push(h),s.push(l)}return new sn(i,s,e,n)},selectChild:cn.selectChild,selectChildren:cn.selectChildren,filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s=e[o],a=s.length,l=r[o]=[],c=0;c<a;++c)(i=s[c])&&t.call(i,i.__data__,c,s)&&l.push(i);return new sn(r,this._parents,this._name,this._id)},merge:function(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,n=t._groups,r=e.length,o=n.length,i=Math.min(r,o),s=new Array(r),a=0;a<i;++a)for(var l,c=e[a],u=n[a],f=c.length,d=s[a]=new Array(f),h=0;h<f;++h)(l=c[h]||u[h])&&(d[h]=l);for(;a<r;++a)s[a]=e[a];return new sn(s,this._parents,this._name,this._id)},selection:function(){return new nn(this._groups,this._parents)},transition:function(){for(var t=this._name,e=this._id,n=ln(),r=this._groups,o=r.length,i=0;i<o;++i)for(var s,a=r[i],l=a.length,c=0;c<l;++c)if(s=a[c]){var u=Ae(s,e);qe(s,t,n,c,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new sn(r,this._parents,t,n)},call:cn.call,nodes:cn.nodes,node:cn.node,size:cn.size,empty:cn.empty,each:cn.each,on:function(t,e){var n=this._id;return arguments.length<2?Ae(this.node(),n).on.on(t):this.each(function(t,e,n){var r,o,i=function(t){return(t+"").trim().split(/^|\s+/).every((function(t){var e=t.indexOf(".");return e>=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?Ne:Se;return function(){var s=i(this,t),a=s.on;a!==r&&(o=(r=a).copy()).on(e,n),s.on=o}}(n,t,e))},attr:function(t,e){var n=J(t),r="transform"===n?Pe:Ue;return this.attrTween(t,"function"==typeof e?(n.local?Ve:He)(n,r,Le(this,"attr."+t,e)):null==e?(n.local?Ge:Be)(n):(n.local?We:Je)(n,r,e))},attrTween:function(t,e){var n="attr."+t;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==e)return this.tween(n,null);if("function"!=typeof e)throw new Error;var r=J(t);return this.tween(n,(r.local?Ye:Ke)(r,e))},style:function(t,e,n){var r="transform"==(t+="")?Re:Ue;return null==e?this.styleTween(t,function(t,e){var n,r,o;return function(){var i=rt(this,t),s=(this.style.removeProperty(t),rt(this,t));return i===s?null:i===n&&s===r?o:o=e(n=i,r=s)}}(t,r)).on("end.style."+t,rn(t)):"function"==typeof e?this.styleTween(t,function(t,e,n){var r,o,i;return function(){var s=rt(this,t),a=n(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=rt(this,t)),s===l?null:s===r&&l===o?i:(o=l,i=e(r=s,a))}}(t,r,Le(this,"style."+t,e))).each(function(t,e){var n,r,o,i,s="style."+e,a="end."+s;return function(){var l=Se(this,t),c=l.on,u=null==l.value[s]?i||(i=rn(e)):void 0;c===n&&o===u||(r=(n=c).copy()).on(a,o=u),l.on=r}}(this._id,t)):this.styleTween(t,function(t,e,n){var r,o,i=n+"";return function(){var s=rt(this,t);return s===i?null:s===r?o:o=e(r=s,n)}}(t,r,e),n).on("end.style."+t,null)},styleTween:function(t,e,n){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==e)return this.tween(r,null);if("function"!=typeof e)throw new Error;return this.tween(r,function(t,e,n){var r,o;function i(){var i=e.apply(this,arguments);return i!==o&&(r=(o=i)&&function(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}(t,i,n)),r}return i._value=e,i}(t,e,null==n?"":n))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var e=t(this);this.textContent=null==e?"":e}}(Le(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var e="text";if(arguments.length<1)return(e=this.tween(e))&&e._value;if(null==t)return this.tween(e,null);if("function"!=typeof t)throw new Error;return this.tween(e,function(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&function(t){return function(e){this.textContent=t.call(this,e)}}(r)),e}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var e=this.parentNode;for(var n in this.__transition)if(+n!==t)return;e&&e.removeChild(this)}}(this._id))},tween:function(t,e){var n=this._id;if(t+="",arguments.length<2){for(var r,o=Ae(this.node(),n).tween,i=0,s=o.length;i<s;++i)if((r=o[i]).name===t)return r.value;return null}return this.each((null==e?Fe:De)(n,t,e))},delay:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?Xe:Qe)(e,t)):Ae(this.node(),e).delay},duration:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?tn:en)(e,t)):Ae(this.node(),e).duration},ease:function(t){var e=this._id;return arguments.length?this.each(function(t,e){if("function"!=typeof e)throw new Error;return function(){Se(this,t).ease=e}}(e,t)):Ae(this.node(),e).ease},easeVarying:function(t){if("function"!=typeof t)throw new Error;return this.each(function(t,e){return function(){var n=e.apply(this,arguments);if("function"!=typeof n)throw new Error;Se(this,t).ease=n}}(this._id,t))},end:function(){var t,e,n=this,r=n._id,o=n.size();return new Promise((function(i,s){var a={value:s},l={value:function(){0==--o&&i()}};n.each((function(){var n=Se(this,r),o=n.on;o!==t&&((e=(t=o).copy())._.cancel.push(a),e._.interrupt.push(a),e._.end.push(l)),n.on=e})),0===o&&i()}))},[Symbol.iterator]:cn[Symbol.iterator]};var hn={time:null,delay:0,duration:250,ease:dn};function pn(t,e){for(var n;!(n=t.__transition)||!(n=n[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return n}Dt.prototype.interrupt=function(t){return this.each((function(){Me(this,t)}))},Dt.prototype.transition=function(t){var e,n;t instanceof sn?(e=t._id,t=t._name):(e=ln(),(n=hn).time=se(),t=null==t?null:t+"");for(var r=this._groups,o=r.length,i=0;i<o;++i)for(var s,a=r[i],l=a.length,c=0;c<l;++c)(s=a[c])&&qe(s,t,e,c,a,n||pn(s,e));return new sn(r,this._parents,t,e)};var mn=[null];function gn(t,e){var n,r,o=t.__transition;if(o)for(r in e=null==e?null:e+"",o)if((n=o[r]).state>ve&&n.name===e)return new sn([[t]],mn,e,+r);return null}const yn=t=>()=>t;function vn(t,{sourceEvent:e,target:n,selection:r,mode:o,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:o,enumerable:!0,configurable:!0},_:{value:i}})}function bn(t){t.preventDefault(),t.stopImmediatePropagation()}var wn={name:"drag"},_n={name:"space"},xn={name:"handle"},kn={name:"center"};const{abs:qn,max:Nn,min:Sn}=Math;function An(t){return[+t[0],+t[1]]}function Mn(t){return[An(t[0]),An(t[1])]}var Tn={name:"x",handles:["w","e"].map(Fn),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Cn={name:"y",handles:["n","s"].map(Fn),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},jn={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Fn),input:function(t){return null==t?null:Mn(t)},output:function(t){return t}},En={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},On={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},In={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Rn={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},Pn={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Fn(t){return{type:t}}function Dn(t){return!t.ctrlKey&&!t.button}function Ln(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function $n(){return navigator.maxTouchPoints||"ontouchstart"in this}function Zn(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function zn(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Un(){return Jn(Tn)}function Bn(){return Jn(Cn)}function Gn(){return Jn(jn)}function Jn(t){var e,n=Ln,r=Dn,o=$n,i=!0,s=N("start","brush","end"),a=6;function l(e){var n=e.property("__brush",m).selectAll(".overlay").data([Fn("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",En.overlay).merge(n).each((function(){var t=Zn(this).extent;Lt(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([Fn("selection")]).enter().append("rect").attr("class","selection").attr("cursor",En.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return En[t.type]})),e.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",d).filter(o).on("touchstart.brush",d).on("touchmove.brush",h).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function c(){var t=Lt(this),e=Zn(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-a/2:e[0][0]-a/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-a/2:e[0][1]-a/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+a:a})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+a:a}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function u(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new f(t,e,n):r}function f(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function d(n){if((!e||n.touches)&&r.apply(this,arguments)){var o,s,a,l,f,d,h,p,m,g,y,v=this,b=n.target.__data__.type,w="selection"===(i&&n.metaKey?b="overlay":b)?wn:i&&n.altKey?kn:xn,_=t===Cn?null:Rn[b],x=t===Tn?null:Pn[b],k=Zn(v),q=k.extent,N=k.selection,S=q[0][0],A=q[0][1],M=q[1][0],T=q[1][1],C=0,j=0,E=_&&x&&i&&n.shiftKey,O=Array.from(n.touches||[n],(t=>{const e=t.identifier;return(t=Ht(t,v)).point0=t.slice(),t.identifier=e,t}));Me(v);var I=u(v,arguments,!0).beforestart();if("overlay"===b){N&&(m=!0);const e=[O[0],O[1]||O[0]];k.selection=N=[[o=t===Cn?S:Sn(e[0][0],e[1][0]),a=t===Tn?A:Sn(e[0][1],e[1][1])],[f=t===Cn?M:Nn(e[0][0],e[1][0]),h=t===Tn?T:Nn(e[0][1],e[1][1])]],O.length>1&&L(n)}else o=N[0][0],a=N[0][1],f=N[1][0],h=N[1][1];s=o,l=a,d=f,p=h;var R=Lt(v).attr("pointer-events","none"),P=R.selectAll(".overlay").attr("cursor",En[b]);if(n.touches)I.moved=D,I.ended=$;else{var F=Lt(n.view).on("mousemove.brush",D,!0).on("mouseup.brush",$,!0);i&&F.on("keydown.brush",(function(t){switch(t.keyCode){case 16:E=_&&x;break;case 18:w===xn&&(_&&(f=d-C*_,o=s+C*_),x&&(h=p-j*x,a=l+j*x),w=kn,L(t));break;case 32:w!==xn&&w!==kn||(_<0?f=d-C:_>0&&(o=s-C),x<0?h=p-j:x>0&&(a=l-j),w=_n,P.attr("cursor",En.selection),L(t));break;default:return}bn(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:E&&(g=y=E=!1,L(t));break;case 18:w===kn&&(_<0?f=d:_>0&&(o=s),x<0?h=p:x>0&&(a=l),w=xn,L(t));break;case 32:w===_n&&(t.altKey?(_&&(f=d-C*_,o=s+C*_),x&&(h=p-j*x,a=l+j*x),w=kn):(_<0?f=d:_>0&&(o=s),x<0?h=p:x>0&&(a=l),w=xn),P.attr("cursor",En[b]),L(t));break;default:return}bn(t)}),!0),Bt(n.view)}c.call(v),I.start(n,w.name)}function D(t){for(const e of t.changedTouches||[t])for(const t of O)t.identifier===e.identifier&&(t.cur=Ht(e,v));if(E&&!g&&!y&&1===O.length){const t=O[0];qn(t.cur[0]-t[0])>qn(t.cur[1]-t[1])?y=!0:g=!0}for(const t of O)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);m=!0,bn(t),L(t)}function L(t){const e=O[0],n=e.point0;var r;switch(C=e[0]-n[0],j=e[1]-n[1],w){case _n:case wn:_&&(C=Nn(S-o,Sn(M-f,C)),s=o+C,d=f+C),x&&(j=Nn(A-a,Sn(T-h,j)),l=a+j,p=h+j);break;case xn:O[1]?(_&&(s=Nn(S,Sn(M,O[0][0])),d=Nn(S,Sn(M,O[1][0])),_=1),x&&(l=Nn(A,Sn(T,O[0][1])),p=Nn(A,Sn(T,O[1][1])),x=1)):(_<0?(C=Nn(S-o,Sn(M-o,C)),s=o+C,d=f):_>0&&(C=Nn(S-f,Sn(M-f,C)),s=o,d=f+C),x<0?(j=Nn(A-a,Sn(T-a,j)),l=a+j,p=h):x>0&&(j=Nn(A-h,Sn(T-h,j)),l=a,p=h+j));break;case kn:_&&(s=Nn(S,Sn(M,o-C*_)),d=Nn(S,Sn(M,f+C*_))),x&&(l=Nn(A,Sn(T,a-j*x)),p=Nn(A,Sn(T,h+j*x)))}d<s&&(_*=-1,r=o,o=f,f=r,r=s,s=d,d=r,b in On&&P.attr("cursor",En[b=On[b]])),p<l&&(x*=-1,r=a,a=h,h=r,r=l,l=p,p=r,b in In&&P.attr("cursor",En[b=In[b]])),k.selection&&(N=k.selection),g&&(s=N[0][0],d=N[1][0]),y&&(l=N[0][1],p=N[1][1]),N[0][0]===s&&N[0][1]===l&&N[1][0]===d&&N[1][1]===p||(k.selection=[[s,l],[d,p]],c.call(v),I.brush(t,w.name))}function $(t){if(function(t){t.stopImmediatePropagation()}(t),t.touches){if(t.touches.length)return;e&&clearTimeout(e),e=setTimeout((function(){e=null}),500)}else Gt(t.view,m),F.on("keydown.brush keyup.brush mousemove.brush mouseup.brush",null);R.attr("pointer-events","all"),P.attr("cursor",En.overlay),k.selection&&(N=k.selection),function(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}(N)&&(k.selection=null,c.call(v)),I.end(t,w.name)}}function h(t){u(this,arguments).moved(t)}function p(t){u(this,arguments).ended(t)}function m(){var e=this.__brush||{selection:null};return e.extent=Mn(n.apply(this,arguments)),e.dim=t,e}return l.move=function(e,n,r){e.tween?e.on("start.brush",(function(t){u(this,arguments).beforestart().start(t)})).on("interrupt.brush end.brush",(function(t){u(this,arguments).end(t)})).tween("brush",(function(){var e=this,r=e.__brush,o=u(e,arguments),i=r.selection,s=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),a=(0,Jt.Z)(i,s);function l(t){r.selection=1===t&&null===s?null:a(t),c.call(e),o.brush()}return null!==i&&null!==s?l:l(1)})):e.each((function(){var e=this,o=arguments,i=e.__brush,s=t.input("function"==typeof n?n.apply(e,o):n,i.extent),a=u(e,o).beforestart();Me(e),i.selection=null===s?null:s,c.call(e),a.start(r).brush(r).end(r)}))},l.clear=function(t,e){l.move(t,null,e)},f.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(t,e){return this.starting?(this.starting=!1,this.emit("start",t,e)):this.emit("brush",t),this},brush:function(t,e){return this.emit("brush",t,e),this},end:function(t,e){return 0==--this.active&&(delete this.state.emitter,this.emit("end",t,e)),this},emit:function(e,n,r){var o=Lt(this.that).datum();s.call(e,this.that,new vn(e,{sourceEvent:n,target:l,selection:t.output(this.state.selection),mode:r,dispatch:s}),o)}},l.extent=function(t){return arguments.length?(n="function"==typeof t?t:yn(Mn(t)),l):n},l.filter=function(t){return arguments.length?(r="function"==typeof t?t:yn(!!t),l):r},l.touchable=function(t){return arguments.length?(o="function"==typeof t?t:yn(!!t),l):o},l.handleSize=function(t){return arguments.length?(a=+t,l):a},l.keyModifiers=function(t){return arguments.length?(i=!!t,l):i},l.on=function(){var t=s.on.apply(s,arguments);return t===s?l:t},l}var Wn=Math.abs,Hn=Math.cos,Vn=Math.sin,Yn=Math.PI,Kn=Yn/2,Xn=2*Yn,Qn=Math.max,tr=1e-12;function er(t,e){return Array.from({length:e-t},((e,n)=>t+n))}function nr(){return ir(!1,!1)}function rr(){return ir(!1,!0)}function or(){return ir(!0,!1)}function ir(t,e){var n=0,r=null,o=null,i=null;function s(s){var a,l=s.length,c=new Array(l),u=er(0,l),f=new Array(l*l),d=new Array(l),h=0;s=Float64Array.from({length:l*l},e?(t,e)=>s[e%l][e/l|0]:(t,e)=>s[e/l|0][e%l]);for(let e=0;e<l;++e){let n=0;for(let r=0;r<l;++r)n+=s[e*l+r]+t*s[r*l+e];h+=c[e]=n}a=(h=Qn(0,Xn-n*l)/h)?n:Xn/l;{let e=0;r&&u.sort(((t,e)=>r(c[t],c[e])));for(const n of u){const r=e;if(t){const t=er(1+~l,l).filter((t=>t<0?s[~t*l+n]:s[n*l+t]));o&&t.sort(((t,e)=>o(t<0?-s[~t*l+n]:s[n*l+t],e<0?-s[~e*l+n]:s[n*l+e])));for(const r of t)if(r<0){(f[~r*l+n]||(f[~r*l+n]={source:null,target:null})).target={index:n,startAngle:e,endAngle:e+=s[~r*l+n]*h,value:s[~r*l+n]}}else{(f[n*l+r]||(f[n*l+r]={source:null,target:null})).source={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}else{const t=er(0,l).filter((t=>s[n*l+t]||s[t*l+n]));o&&t.sort(((t,e)=>o(s[n*l+t],s[n*l+e])));for(const r of t){let t;if(n<r?(t=f[n*l+r]||(f[n*l+r]={source:null,target:null}),t.source={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]}):(t=f[r*l+n]||(f[r*l+n]={source:null,target:null}),t.target={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]},n===r&&(t.source=t.target)),t.source&&t.target&&t.source.value<t.target.value){const e=t.source;t.source=t.target,t.target=e}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}e+=a}}return(f=Object.values(f)).groups=d,i?f.sort(i):f}return s.padAngle=function(t){return arguments.length?(n=Qn(0,t),s):n},s.sortGroups=function(t){return arguments.length?(r=t,s):r},s.sortSubgroups=function(t){return arguments.length?(o=t,s):o},s.sortChords=function(t){return arguments.length?(null==t?i=null:(e=t,i=function(t,n){return e(t.source.value+t.target.value,n.source.value+n.target.value)})._=t,s):i&&i._;var e},s}const sr=Math.PI,ar=2*sr,lr=1e-6,cr=ar-lr;function ur(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function fr(){return new ur}ur.prototype=fr.prototype={constructor:ur,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r)},bezierCurveTo:function(t,e,n,r,o,i){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+o)+","+(this._y1=+i)},arcTo:function(t,e,n,r,o){t=+t,e=+e,n=+n,r=+r,o=+o;var i=this._x1,s=this._y1,a=n-t,l=r-e,c=i-t,u=s-e,f=c*c+u*u;if(o<0)throw new Error("negative radius: "+o);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(f>lr)if(Math.abs(u*a-l*c)>lr&&o){var d=n-i,h=r-s,p=a*a+l*l,m=d*d+h*h,g=Math.sqrt(p),y=Math.sqrt(f),v=o*Math.tan((sr-Math.acos((p+f-m)/(2*g*y)))/2),b=v/y,w=v/g;Math.abs(b-1)>lr&&(this._+="L"+(t+b*c)+","+(e+b*u)),this._+="A"+o+","+o+",0,0,"+ +(u*d>c*h)+","+(this._x1=t+w*a)+","+(this._y1=e+w*l)}else this._+="L"+(this._x1=t)+","+(this._y1=e);else;},arc:function(t,e,n,r,o,i){t=+t,e=+e,i=!!i;var s=(n=+n)*Math.cos(r),a=n*Math.sin(r),l=t+s,c=e+a,u=1^i,f=i?r-o:o-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+l+","+c:(Math.abs(this._x1-l)>lr||Math.abs(this._y1-c)>lr)&&(this._+="L"+l+","+c),n&&(f<0&&(f=f%ar+ar),f>cr?this._+="A"+n+","+n+",0,1,"+u+","+(t-s)+","+(e-a)+"A"+n+","+n+",0,1,"+u+","+(this._x1=l)+","+(this._y1=c):f>lr&&(this._+="A"+n+","+n+",0,"+ +(f>=sr)+","+u+","+(this._x1=t+n*Math.cos(o))+","+(this._y1=e+n*Math.sin(o))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const dr=fr;var hr=Array.prototype.slice;function pr(t){return function(){return t}}function mr(t){return t.source}function gr(t){return t.target}function yr(t){return t.radius}function vr(t){return t.startAngle}function br(t){return t.endAngle}function wr(){return 0}function _r(){return 10}function xr(t){var e=mr,n=gr,r=yr,o=yr,i=vr,s=br,a=wr,l=null;function c(){var c,u=e.apply(this,arguments),f=n.apply(this,arguments),d=a.apply(this,arguments)/2,h=hr.call(arguments),p=+r.apply(this,(h[0]=u,h)),m=i.apply(this,h)-Kn,g=s.apply(this,h)-Kn,y=+o.apply(this,(h[0]=f,h)),v=i.apply(this,h)-Kn,b=s.apply(this,h)-Kn;if(l||(l=c=dr()),d>tr&&(Wn(g-m)>2*d+tr?g>m?(m+=d,g-=d):(m-=d,g+=d):m=g=(m+g)/2,Wn(b-v)>2*d+tr?b>v?(v+=d,b-=d):(v-=d,b+=d):v=b=(v+b)/2),l.moveTo(p*Hn(m),p*Vn(m)),l.arc(0,0,p,m,g),m!==v||g!==b)if(t){var w=y-+t.apply(this,arguments),_=(v+b)/2;l.quadraticCurveTo(0,0,w*Hn(v),w*Vn(v)),l.lineTo(y*Hn(_),y*Vn(_)),l.lineTo(w*Hn(b),w*Vn(b))}else l.quadraticCurveTo(0,0,y*Hn(v),y*Vn(v)),l.arc(0,0,y,v,b);if(l.quadraticCurveTo(0,0,p*Hn(m),p*Vn(m)),l.closePath(),c)return l=null,c+""||null}return t&&(c.headRadius=function(e){return arguments.length?(t="function"==typeof e?e:pr(+e),c):t}),c.radius=function(t){return arguments.length?(r=o="function"==typeof t?t:pr(+t),c):r},c.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:pr(+t),c):r},c.targetRadius=function(t){return arguments.length?(o="function"==typeof t?t:pr(+t),c):o},c.startAngle=function(t){return arguments.length?(i="function"==typeof t?t:pr(+t),c):i},c.endAngle=function(t){return arguments.length?(s="function"==typeof t?t:pr(+t),c):s},c.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:pr(+t),c):a},c.source=function(t){return arguments.length?(e=t,c):e},c.target=function(t){return arguments.length?(n=t,c):n},c.context=function(t){return arguments.length?(l=null==t?null:t,c):l},c}function kr(){return xr()}function qr(){return xr(_r)}var Nr=n(3456);const Sr=Math.PI/180,Ar=180/Math.PI,Mr=.96422,Tr=1,Cr=.82521,jr=4/29,Er=6/29,Or=3*Er*Er,Ir=Er*Er*Er;function Rr(t){if(t instanceof Dr)return new Dr(t.l,t.a,t.b,t.opacity);if(t instanceof Jr)return Wr(t);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e,n,r=zr(t.r),o=zr(t.g),i=zr(t.b),s=Lr((.2225045*r+.7168786*o+.0606169*i)/Tr);return r===o&&o===i?e=n=s:(e=Lr((.4360747*r+.3850649*o+.1430804*i)/Mr),n=Lr((.0139322*r+.0971045*o+.7141733*i)/Cr)),new Dr(116*s-16,500*(e-s),200*(s-n),t.opacity)}function Pr(t,e){return new Dr(t,0,0,null==e?1:e)}function Fr(t,e,n,r){return 1===arguments.length?Rr(t):new Dr(t,e,n,null==r?1:r)}function Dr(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function Lr(t){return t>Ir?Math.pow(t,1/3):t/Or+jr}function $r(t){return t>Er?t*t*t:Or*(t-jr)}function Zr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function zr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ur(t){if(t instanceof Jr)return new Jr(t.h,t.c,t.l,t.opacity);if(t instanceof Dr||(t=Rr(t)),0===t.a&&0===t.b)return new Jr(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);var e=Math.atan2(t.b,t.a)*Ar;return new Jr(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Br(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(n,e,t,null==r?1:r)}function Gr(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(t,e,n,null==r?1:r)}function Jr(t,e,n,r){this.h=+t,this.c=+e,this.l=+n,this.opacity=+r}function Wr(t){if(isNaN(t.h))return new Dr(t.l,0,0,t.opacity);var e=t.h*Sr;return new Dr(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}(0,Nr.Z)(Dr,Fr,(0,Nr.l)($e.Il,{brighter(t){return new Dr(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker(t){return new Dr(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,n=isNaN(this.b)?t:t-this.b/200;return e=Mr*$r(e),t=Tr*$r(t),n=Cr*$r(n),new $e.Ss(Zr(3.1338561*e-1.6168667*t-.4906146*n),Zr(-.9787684*e+1.9161415*t+.033454*n),Zr(.0719453*e-.2289914*t+1.4052427*n),this.opacity)}})),(0,Nr.Z)(Jr,Gr,(0,Nr.l)($e.Il,{brighter(t){return new Jr(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker(t){return new Jr(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb(){return Wr(this).rgb()}}));var Hr=-.14861,Vr=1.78277,Yr=-.29227,Kr=-.90649,Xr=1.97294,Qr=Xr*Kr,to=Xr*Vr,eo=Vr*Yr-Kr*Hr;function no(t,e,n,r){return 1===arguments.length?function(t){if(t instanceof ro)return new ro(t.h,t.s,t.l,t.opacity);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e=t.r/255,n=t.g/255,r=t.b/255,o=(eo*r+Qr*e-to*n)/(eo+Qr-to),i=r-o,s=(Xr*(n-o)-Yr*i)/Kr,a=Math.sqrt(s*s+i*i)/(Xr*o*(1-o)),l=a?Math.atan2(s,i)*Ar-120:NaN;return new ro(l<0?l+360:l,a,o,t.opacity)}(t):new ro(t,e,n,null==r?1:r)}function ro(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}(0,Nr.Z)(ro,no,(0,Nr.l)($e.Il,{brighter(t){return t=null==t?$e.J5:Math.pow($e.J5,t),new ro(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?$e.xV:Math.pow($e.xV,t),new ro(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=isNaN(this.h)?0:(this.h+120)*Sr,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),o=Math.sin(t);return new $e.Ss(255*(e+n*(Hr*r+Vr*o)),255*(e+n*(Yr*r+Kr*o)),255*(e+n*(Xr*r)),this.opacity)}}));var oo=n(2327),io=n(2038),so=n(6106),ao=Array.prototype.slice;function lo(t,e){return t-e}const co=t=>()=>t;function uo(t,e){for(var n,r=-1,o=e.length;++r<o;)if(n=fo(t,e[r]))return n;return 0}function fo(t,e){for(var n=e[0],r=e[1],o=-1,i=0,s=t.length,a=s-1;i<s;a=i++){var l=t[i],c=l[0],u=l[1],f=t[a],d=f[0],h=f[1];if(ho(l,f,e))return 0;u>r!=h>r&&n<(d-c)*(r-u)/(h-u)+c&&(o=-o)}return o}function ho(t,e,n){var r,o,i,s;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(o=t[r=+(t[0]===e[0])],i=n[r],s=e[r],o<=i&&i<=s||s<=i&&i<=o)}function po(){}var mo=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function go(){var t=1,e=1,n=oo.Z,r=a;function o(t){var e=n(t);if(Array.isArray(e))e=e.slice().sort(lo);else{const n=(0,io.Z)(t),r=(0,so.ly)(n[0],n[1],e);e=(0,so.ZP)(Math.floor(n[0]/r)*r,Math.floor(n[1]/r-1)*r,e)}return e.map((e=>i(t,e)))}function i(n,o){var i=[],a=[];return function(n,r,o){var i,a,l,c,u,f,d=new Array,h=new Array;i=a=-1,c=n[0]>=r,mo[c<<1].forEach(p);for(;++i<t-1;)l=c,c=n[i+1]>=r,mo[l|c<<1].forEach(p);mo[c<<0].forEach(p);for(;++a<e-1;){for(i=-1,c=n[a*t+t]>=r,u=n[a*t]>=r,mo[c<<1|u<<2].forEach(p);++i<t-1;)l=c,c=n[a*t+t+i+1]>=r,f=u,u=n[a*t+i+1]>=r,mo[l|c<<1|u<<2|f<<3].forEach(p);mo[c|u<<3].forEach(p)}i=-1,u=n[a*t]>=r,mo[u<<2].forEach(p);for(;++i<t-1;)f=u,u=n[a*t+i+1]>=r,mo[u<<2|f<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+i,t[0][1]+a],l=[t[1][0]+i,t[1][1]+a],c=s(r),u=s(l);(e=h[c])?(n=d[u])?(delete h[e.end],delete d[n.start],e===n?(e.ring.push(l),o(e.ring)):d[e.start]=h[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[e.end],e.ring.push(l),h[e.end=u]=e):(e=d[u])?(n=h[c])?(delete d[e.start],delete h[n.end],e===n?(e.ring.push(l),o(e.ring)):d[n.start]=h[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[e.start],e.ring.unshift(r),d[e.start=c]=e):d[c]=h[u]={start:c,end:u,ring:[r,l]}}mo[u<<3].forEach(p)}(n,o,(function(t){r(t,n,o),function(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++e<n;)r+=t[e-1][1]*t[e][0]-t[e-1][0]*t[e][1];return r}(t)>0?i.push([t]):a.push(t)})),a.forEach((function(t){for(var e,n=0,r=i.length;n<r;++n)if(-1!==uo((e=i[n])[0],t))return void e.push(t)})),{type:"MultiPolygon",value:o,coordinates:i}}function s(e){return 2*e[0]+e[1]*(t+1)*4}function a(n,r,o){n.forEach((function(n){var i,s=n[0],a=n[1],l=0|s,c=0|a,u=r[c*t+l];s>0&&s<t&&l===s&&(i=r[c*t+l-1],n[0]=s+(o-i)/(u-i)-.5),a>0&&a<e&&c===a&&(i=r[(c-1)*t+l],n[1]=a+(o-i)/(u-i)-.5)}))}return o.contour=i,o.size=function(n){if(!arguments.length)return[t,e];var r=Math.floor(n[0]),i=Math.floor(n[1]);if(!(r>=0&&i>=0))throw new Error("invalid size");return t=r,e=i,o},o.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?co(ao.call(t)):co(t),o):n},o.smooth=function(t){return arguments.length?(r=t?a:po,o):r===a},o}var yo=n(1045),vo=n(8319);function bo(t){return t[0]}function wo(t){return t[1]}function _o(){return 1}function xo(){var t=bo,e=wo,n=_o,r=960,o=500,i=20,s=2,a=3*i,l=r+2*a>>s,c=o+2*a>>s,u=co(20);function f(r){var o=new Float32Array(l*c),u=Math.pow(2,-s),f=-1;for(const i of r){var d=(t(i,++f,r)+a)*u,h=(e(i,f,r)+a)*u,p=+n(i,f,r);if(d>=0&&d<l&&h>=0&&h<c){var m=Math.floor(d),g=Math.floor(h),y=d-m-.5,v=h-g-.5;o[m+g*l]+=(1-y)*(1-v)*p,o[m+1+g*l]+=y*(1-v)*p,o[m+1+(g+1)*l]+=y*v*p,o[m+(g+1)*l]+=(1-y)*v*p}}return(0,yo.u8)({data:o,width:l,height:c},i*u),o}function d(t){var e=f(t),n=u(e),r=Math.pow(2,2*s);return Array.isArray(n)||(n=(0,so.ZP)(Number.MIN_VALUE,(0,vo.Z)(e)/r,n)),go().size([l,c]).thresholds(n.map((t=>t*r)))(e).map(((t,e)=>(t.value=+n[e],h(t))))}function h(t){return t.coordinates.forEach(p),t}function p(t){t.forEach(m)}function m(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,s)-a,t[1]=t[1]*Math.pow(2,s)-a}function y(){return l=r+2*(a=3*i)>>s,c=o+2*a>>s,d}return d.contours=function(t){var e=f(t),n=go().size([l,c]),r=Math.pow(2,2*s),o=t=>{t=+t;var o=h(n.contour(e,t*r));return o.value=t,o};return Object.defineProperty(o,"max",{get:()=>(0,vo.Z)(e)/r}),o},d.x=function(e){return arguments.length?(t="function"==typeof e?e:co(+e),d):t},d.y=function(t){return arguments.length?(e="function"==typeof t?t:co(+t),d):e},d.weight=function(t){return arguments.length?(n="function"==typeof t?t:co(+t),d):n},d.size=function(t){if(!arguments.length)return[r,o];var e=+t[0],n=+t[1];if(!(e>=0&&n>=0))throw new Error("invalid size");return r=e,o=n,y()},d.cellSize=function(t){if(!arguments.length)return 1<<s;if(!((t=+t)>=1))throw new Error("invalid cell size");return s=Math.floor(Math.log(t)/Math.LN2),y()},d.thresholds=function(t){return arguments.length?(u="function"==typeof t?t:Array.isArray(t)?co(ao.call(t)):co(t),d):u},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(i*(i+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return i=(Math.sqrt(4*t*t+1)-1)/2,y()},d}const ko=134217729,qo=33306690738754706e-32;function No(t,e,n,r,o){let i,s,a,l,c=e[0],u=r[0],f=0,d=0;u>c==u>-c?(i=c,c=e[++f]):(i=u,u=r[++d]);let h=0;if(f<t&&d<n)for(u>c==u>-c?(s=c+i,a=i-(s-c),c=e[++f]):(s=u+i,a=i-(s-u),u=r[++d]),i=s,0!==a&&(o[h++]=a);f<t&&d<n;)u>c==u>-c?(s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++f]):(s=i+u,l=s-i,a=i-(s-l)+(u-l),u=r[++d]),i=s,0!==a&&(o[h++]=a);for(;f<t;)s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++f],i=s,0!==a&&(o[h++]=a);for(;d<n;)s=i+u,l=s-i,a=i-(s-l)+(u-l),u=r[++d],i=s,0!==a&&(o[h++]=a);return 0===i&&0!==h||(o[h++]=i),h}function So(t){return new Float64Array(t)}const Ao=22204460492503146e-32,Mo=11093356479670487e-47,To=So(4),Co=So(8),jo=So(12),Eo=So(16),Oo=So(4);function Io(t,e,n,r,o,i){const s=(e-i)*(n-o),a=(t-o)*(r-i),l=s-a;if(0===s||0===a||s>0!=a>0)return l;const c=Math.abs(s+a);return Math.abs(l)>=33306690738754716e-32*c?l:-function(t,e,n,r,o,i,s){let a,l,c,u,f,d,h,p,m,g,y,v,b,w,_,x,k,q;const N=t-o,S=n-o,A=e-i,M=r-i;w=N*M,d=ko*N,h=d-(d-N),p=N-h,d=ko*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=A*S,d=ko*A,h=d-(d-A),p=A-h,d=ko*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,To[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,To[1]=b-(y+f)+(f-x),q=v+y,f=q-v,To[2]=v-(q-f)+(y-f),To[3]=q;let T=function(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}(4,To),C=Ao*s;if(T>=C||-T>=C)return T;if(f=t-N,a=t-(N+f)+(f-o),f=n-S,c=n-(S+f)+(f-o),f=e-A,l=e-(A+f)+(f-i),f=r-M,u=r-(M+f)+(f-i),0===a&&0===l&&0===c&&0===u)return T;if(C=Mo*s+qo*Math.abs(T),T+=N*u+M*a-(A*c+S*l),T>=C||-T>=C)return T;w=a*M,d=ko*a,h=d-(d-a),p=a-h,d=ko*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=l*S,d=ko*l,h=d-(d-l),p=l-h,d=ko*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const j=No(4,To,4,Oo,Co);w=N*u,d=ko*N,h=d-(d-N),p=N-h,d=ko*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=A*c,d=ko*A,h=d-(d-A),p=A-h,d=ko*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const E=No(j,Co,4,Oo,jo);w=a*u,d=ko*a,h=d-(d-a),p=a-h,d=ko*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=l*c,d=ko*l,h=d-(d-l),p=l-h,d=ko*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const O=No(E,jo,4,Oo,Eo);return Eo[O-1]}(t,e,n,r,o,i,c)}So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(8),So(8),So(8),So(4),So(8),So(8),So(8),So(12);So(192),So(192);So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(4),So(4),So(4),So(8),So(16),So(16),So(16),So(32),So(32),So(48),So(64);So(1152),So(1152);So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(1152),So(1152),So(1152),So(1152),So(1152),So(2304),So(2304),So(3456),So(5760),So(8),So(8),So(8),So(16),So(24),So(48),So(48),So(96),So(192),So(384),So(384),So(384),So(768);So(96),So(96),So(96),So(1152);const Ro=Math.pow(2,-52),Po=new Uint32Array(512);class Fo{static from(t,e=Uo,n=Bo){const r=t.length,o=new Float64Array(2*r);for(let i=0;i<r;i++){const r=t[i];o[2*i]=e(r),o[2*i+1]=n(r)}return new Fo(o)}constructor(t){const e=t.length>>1;if(e>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const n=Math.max(2*e-5,0);this._triangles=new Uint32Array(3*n),this._halfedges=new Int32Array(3*n),this._hashSize=Math.ceil(Math.sqrt(e)),this._hullPrev=new Uint32Array(e),this._hullNext=new Uint32Array(e),this._hullTri=new Uint32Array(e),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(e),this._dists=new Float64Array(e),this.update()}update(){const{coords:t,_hullPrev:e,_hullNext:n,_hullTri:r,_hullHash:o}=this,i=t.length>>1;let s=1/0,a=1/0,l=-1/0,c=-1/0;for(let e=0;e<i;e++){const n=t[2*e],r=t[2*e+1];n<s&&(s=n),r<a&&(a=r),n>l&&(l=n),r>c&&(c=r),this._ids[e]=e}const u=(s+l)/2,f=(a+c)/2;let d,h,p,m=1/0;for(let e=0;e<i;e++){const n=Do(u,f,t[2*e],t[2*e+1]);n<m&&(d=e,m=n)}const g=t[2*d],y=t[2*d+1];m=1/0;for(let e=0;e<i;e++){if(e===d)continue;const n=Do(g,y,t[2*e],t[2*e+1]);n<m&&n>0&&(h=e,m=n)}let v=t[2*h],b=t[2*h+1],w=1/0;for(let e=0;e<i;e++){if(e===d||e===h)continue;const n=$o(g,y,v,b,t[2*e],t[2*e+1]);n<w&&(p=e,w=n)}let _=t[2*p],x=t[2*p+1];if(w===1/0){for(let e=0;e<i;e++)this._dists[e]=t[2*e]-t[0]||t[2*e+1]-t[1];Zo(this._ids,this._dists,0,i-1);const e=new Uint32Array(i);let n=0;for(let t=0,r=-1/0;t<i;t++){const o=this._ids[t];this._dists[o]>r&&(e[n++]=o,r=this._dists[o])}return this.hull=e.subarray(0,n),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Io(g,y,v,b,_,x)<0){const t=h,e=v,n=b;h=p,v=_,b=x,p=t,_=e,x=n}const k=function(t,e,n,r,o,i){const s=n-t,a=r-e,l=o-t,c=i-e,u=s*s+a*a,f=l*l+c*c,d=.5/(s*c-a*l),h=t+(c*u-a*f)*d,p=e+(s*f-l*u)*d;return{x:h,y:p}}(g,y,v,b,_,x);this._cx=k.x,this._cy=k.y;for(let e=0;e<i;e++)this._dists[e]=Do(t[2*e],t[2*e+1],k.x,k.y);Zo(this._ids,this._dists,0,i-1),this._hullStart=d;let q=3;n[d]=e[p]=h,n[h]=e[d]=p,n[p]=e[h]=d,r[d]=0,r[h]=1,r[p]=2,o.fill(-1),o[this._hashKey(g,y)]=d,o[this._hashKey(v,b)]=h,o[this._hashKey(_,x)]=p,this.trianglesLen=0,this._addTriangle(d,h,p,-1,-1,-1);for(let i,s,a=0;a<this._ids.length;a++){const l=this._ids[a],c=t[2*l],u=t[2*l+1];if(a>0&&Math.abs(c-i)<=Ro&&Math.abs(u-s)<=Ro)continue;if(i=c,s=u,l===d||l===h||l===p)continue;let f=0;for(let t=0,e=this._hashKey(c,u);t<this._hashSize&&(f=o[(e+t)%this._hashSize],-1===f||f===n[f]);t++);f=e[f];let m,g=f;for(;m=n[g],Io(c,u,t[2*g],t[2*g+1],t[2*m],t[2*m+1])>=0;)if(g=m,g===f){g=-1;break}if(-1===g)continue;let y=this._addTriangle(g,l,n[g],-1,-1,r[g]);r[l]=this._legalize(y+2),r[g]=y,q++;let v=n[g];for(;m=n[v],Io(c,u,t[2*v],t[2*v+1],t[2*m],t[2*m+1])<0;)y=this._addTriangle(v,l,m,r[l],-1,r[v]),r[l]=this._legalize(y+2),n[v]=v,q--,v=m;if(g===f)for(;m=e[g],Io(c,u,t[2*m],t[2*m+1],t[2*g],t[2*g+1])<0;)y=this._addTriangle(m,l,g,-1,r[g],r[m]),this._legalize(y+2),r[m]=y,n[g]=g,q--,g=m;this._hullStart=e[l]=g,n[g]=e[v]=l,n[l]=v,o[this._hashKey(c,u)]=l,o[this._hashKey(t[2*g],t[2*g+1])]=g}this.hull=new Uint32Array(q);for(let t=0,e=this._hullStart;t<q;t++)this.hull[t]=e,e=n[e];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(t,e){return Math.floor(function(t,e){const n=t/(Math.abs(t)+Math.abs(e));return(e>0?3-n:1+n)/4}(t-this._cx,e-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:e,_halfedges:n,coords:r}=this;let o=0,i=0;for(;;){const s=n[t],a=t-t%3;if(i=a+(t+2)%3,-1===s){if(0===o)break;t=Po[--o];continue}const l=s-s%3,c=a+(t+1)%3,u=l+(s+2)%3,f=e[i],d=e[t],h=e[c],p=e[u];if(Lo(r[2*f],r[2*f+1],r[2*d],r[2*d+1],r[2*h],r[2*h+1],r[2*p],r[2*p+1])){e[t]=p,e[s]=f;const r=n[u];if(-1===r){let e=this._hullStart;do{if(this._hullTri[e]===u){this._hullTri[e]=t;break}e=this._hullPrev[e]}while(e!==this._hullStart)}this._link(t,r),this._link(s,n[i]),this._link(i,u);const a=l+(s+1)%3;o<Po.length&&(Po[o++]=a)}else{if(0===o)break;t=Po[--o]}}return i}_link(t,e){this._halfedges[t]=e,-1!==e&&(this._halfedges[e]=t)}_addTriangle(t,e,n,r,o,i){const s=this.trianglesLen;return this._triangles[s]=t,this._triangles[s+1]=e,this._triangles[s+2]=n,this._link(s,r),this._link(s+1,o),this._link(s+2,i),this.trianglesLen+=3,s}}function Do(t,e,n,r){const o=t-n,i=e-r;return o*o+i*i}function Lo(t,e,n,r,o,i,s,a){const l=t-s,c=e-a,u=n-s,f=r-a,d=o-s,h=i-a,p=u*u+f*f,m=d*d+h*h;return l*(f*m-p*h)-c*(u*m-p*d)+(l*l+c*c)*(u*h-f*d)<0}function $o(t,e,n,r,o,i){const s=n-t,a=r-e,l=o-t,c=i-e,u=s*s+a*a,f=l*l+c*c,d=.5/(s*c-a*l),h=(c*u-a*f)*d,p=(s*f-l*u)*d;return h*h+p*p}function Zo(t,e,n,r){if(r-n<=20)for(let o=n+1;o<=r;o++){const r=t[o],i=e[r];let s=o-1;for(;s>=n&&e[t[s]]>i;)t[s+1]=t[s--];t[s+1]=r}else{let o=n+1,i=r;zo(t,n+r>>1,o),e[t[n]]>e[t[r]]&&zo(t,n,r),e[t[o]]>e[t[r]]&&zo(t,o,r),e[t[n]]>e[t[o]]&&zo(t,n,o);const s=t[o],a=e[s];for(;;){do{o++}while(e[t[o]]<a);do{i--}while(e[t[i]]>a);if(i<o)break;zo(t,o,i)}t[n+1]=t[i],t[i]=s,r-o+1>=i-n?(Zo(t,e,o,r),Zo(t,e,n,i-1)):(Zo(t,e,n,i-1),Zo(t,e,o,r))}}function zo(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function Uo(t){return t[0]}function Bo(t){return t[1]}const Go=1e-6;class Jo{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,e){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,e){this._+=`L${this._x1=+t},${this._y1=+e}`}arc(t,e,n){const r=(t=+t)+(n=+n),o=e=+e;if(n<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${o}`:(Math.abs(this._x1-r)>Go||Math.abs(this._y1-o)>Go)&&(this._+="L"+r+","+o),n&&(this._+=`A${n},${n},0,1,1,${t-n},${e}A${n},${n},0,1,1,${this._x1=r},${this._y1=o}`)}rect(t,e,n,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${+n}v${+r}h${-n}Z`}value(){return this._||null}}class Wo{constructor(){this._=[]}moveTo(t,e){this._.push([t,e])}closePath(){this._.push(this._[0].slice())}lineTo(t,e){this._.push([t,e])}value(){return this._.length?this._:null}}class Ho{constructor(t,[e,n,r,o]=[0,0,960,500]){if(!((r=+r)>=(e=+e)&&(o=+o)>=(n=+n)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=e,this.ymax=o,this.ymin=n,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:e,triangles:n},vectors:r}=this,o=this.circumcenters=this._circumcenters.subarray(0,n.length/3*2);for(let e,r,i=0,s=0,a=n.length;i<a;i+=3,s+=2){const a=2*n[i],l=2*n[i+1],c=2*n[i+2],u=t[a],f=t[a+1],d=t[l],h=t[l+1],p=t[c],m=t[c+1],g=d-u,y=h-f,v=p-u,b=m-f,w=2*(g*b-y*v);if(Math.abs(w)<1e-9){let o=1e9;const i=2*n[0];o*=Math.sign((t[i]-u)*b-(t[i+1]-f)*v),e=(u+p)/2-o*b,r=(f+m)/2+o*v}else{const t=1/w,n=g*g+y*y,o=v*v+b*b;e=u+(b*n-y*o)*t,r=f+(g*o-v*n)*t}o[s]=e,o[s+1]=r}let i,s,a,l=e[e.length-1],c=4*l,u=t[2*l],f=t[2*l+1];r.fill(0);for(let n=0;n<e.length;++n)l=e[n],i=c,s=u,a=f,c=4*l,u=t[2*l],f=t[2*l+1],r[i+2]=r[c]=a-f,r[i+3]=r[c+1]=u-s}render(t){const e=null==t?t=new Jo:void 0,{delaunay:{halfedges:n,inedges:r,hull:o},circumcenters:i,vectors:s}=this;if(o.length<=1)return null;for(let e=0,r=n.length;e<r;++e){const r=n[e];if(r<e)continue;const o=2*Math.floor(e/3),s=2*Math.floor(r/3),a=i[o],l=i[o+1],c=i[s],u=i[s+1];this._renderSegment(a,l,c,u,t)}let a,l=o[o.length-1];for(let e=0;e<o.length;++e){a=l,l=o[e];const n=2*Math.floor(r[l]/3),c=i[n],u=i[n+1],f=4*a,d=this._project(c,u,s[f+2],s[f+3]);d&&this._renderSegment(c,u,d[0],d[1],t)}return e&&e.value()}renderBounds(t){const e=null==t?t=new Jo:void 0;return t.rect(this.xmin,this.ymin,this.xmax-this.xmin,this.ymax-this.ymin),e&&e.value()}renderCell(t,e){const n=null==e?e=new Jo:void 0,r=this._clip(t);if(null===r||!r.length)return;e.moveTo(r[0],r[1]);let o=r.length;for(;r[0]===r[o-2]&&r[1]===r[o-1]&&o>1;)o-=2;for(let t=2;t<o;t+=2)r[t]===r[t-2]&&r[t+1]===r[t-1]||e.lineTo(r[t],r[t+1]);return e.closePath(),n&&n.value()}*cellPolygons(){const{delaunay:{points:t}}=this;for(let e=0,n=t.length/2;e<n;++e){const t=this.cellPolygon(e);t&&(t.index=e,yield t)}}cellPolygon(t){const e=new Wo;return this.renderCell(t,e),e.value()}_renderSegment(t,e,n,r,o){let i;const s=this._regioncode(t,e),a=this._regioncode(n,r);0===s&&0===a?(o.moveTo(t,e),o.lineTo(n,r)):(i=this._clipSegment(t,e,n,r,s,a))&&(o.moveTo(i[0],i[1]),o.lineTo(i[2],i[3]))}contains(t,e,n){return(e=+e)==e&&(n=+n)==n&&this.delaunay._step(t,e,n)===t}*neighbors(t){const e=this._clip(t);if(e)for(const n of this.delaunay.neighbors(t)){const t=this._clip(n);if(t)t:for(let r=0,o=e.length;r<o;r+=2)for(let i=0,s=t.length;i<s;i+=2)if(e[r]==t[i]&&e[r+1]==t[i+1]&&e[(r+2)%o]==t[(i+s-2)%s]&&e[(r+3)%o]==t[(i+s-1)%s]){yield n;break t}}}_cell(t){const{circumcenters:e,delaunay:{inedges:n,halfedges:r,triangles:o}}=this,i=n[t];if(-1===i)return null;const s=[];let a=i;do{const n=Math.floor(a/3);if(s.push(e[2*n],e[2*n+1]),a=a%3==2?a-2:a+1,o[a]!==t)break;a=r[a]}while(a!==i&&-1!==a);return s}_clip(t){if(0===t&&1===this.delaunay.hull.length)return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];const e=this._cell(t);if(null===e)return null;const{vectors:n}=this,r=4*t;return n[r]||n[r+1]?this._clipInfinite(t,e,n[r],n[r+1],n[r+2],n[r+3]):this._clipFinite(t,e)}_clipFinite(t,e){const n=e.length;let r,o,i,s,a=null,l=e[n-2],c=e[n-1],u=this._regioncode(l,c),f=0;for(let d=0;d<n;d+=2)if(r=l,o=c,l=e[d],c=e[d+1],i=u,u=this._regioncode(l,c),0===i&&0===u)s=f,f=0,a?a.push(l,c):a=[l,c];else{let e,n,d,h,p;if(0===i){if(null===(e=this._clipSegment(r,o,l,c,i,u)))continue;[n,d,h,p]=e}else{if(null===(e=this._clipSegment(l,c,r,o,u,i)))continue;[h,p,n,d]=e,s=f,f=this._edgecode(n,d),s&&f&&this._edge(t,s,f,a,a.length),a?a.push(n,d):a=[n,d]}s=f,f=this._edgecode(h,p),s&&f&&this._edge(t,s,f,a,a.length),a?a.push(h,p):a=[h,p]}if(a)s=f,f=this._edgecode(a[0],a[1]),s&&f&&this._edge(t,s,f,a,a.length);else if(this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2))return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];return a}_clipSegment(t,e,n,r,o,i){for(;;){if(0===o&&0===i)return[t,e,n,r];if(o&i)return null;let s,a,l=o||i;8&l?(s=t+(n-t)*(this.ymax-e)/(r-e),a=this.ymax):4&l?(s=t+(n-t)*(this.ymin-e)/(r-e),a=this.ymin):2&l?(a=e+(r-e)*(this.xmax-t)/(n-t),s=this.xmax):(a=e+(r-e)*(this.xmin-t)/(n-t),s=this.xmin),o?(t=s,e=a,o=this._regioncode(t,e)):(n=s,r=a,i=this._regioncode(n,r))}}_clipInfinite(t,e,n,r,o,i){let s,a=Array.from(e);if((s=this._project(a[0],a[1],n,r))&&a.unshift(s[0],s[1]),(s=this._project(a[a.length-2],a[a.length-1],o,i))&&a.push(s[0],s[1]),a=this._clipFinite(t,a))for(let e,n=0,r=a.length,o=this._edgecode(a[r-2],a[r-1]);n<r;n+=2)e=o,o=this._edgecode(a[n],a[n+1]),e&&o&&(n=this._edge(t,e,o,a,n),r=a.length);else this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)&&(a=[this.xmin,this.ymin,this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax]);return a}_edge(t,e,n,r,o){for(;e!==n;){let n,i;switch(e){case 5:e=4;continue;case 4:e=6,n=this.xmax,i=this.ymin;break;case 6:e=2;continue;case 2:e=10,n=this.xmax,i=this.ymax;break;case 10:e=8;continue;case 8:e=9,n=this.xmin,i=this.ymax;break;case 9:e=1;continue;case 1:e=5,n=this.xmin,i=this.ymin}r[o]===n&&r[o+1]===i||!this.contains(t,n,i)||(r.splice(o,0,n,i),o+=2)}if(r.length>4)for(let t=0;t<r.length;t+=2){const e=(t+2)%r.length,n=(t+4)%r.length;(r[t]===r[e]&&r[e]===r[n]||r[t+1]===r[e+1]&&r[e+1]===r[n+1])&&(r.splice(e,2),t-=2)}return o}_project(t,e,n,r){let o,i,s,a=1/0;if(r<0){if(e<=this.ymin)return null;(o=(this.ymin-e)/r)<a&&(s=this.ymin,i=t+(a=o)*n)}else if(r>0){if(e>=this.ymax)return null;(o=(this.ymax-e)/r)<a&&(s=this.ymax,i=t+(a=o)*n)}if(n>0){if(t>=this.xmax)return null;(o=(this.xmax-t)/n)<a&&(i=this.xmax,s=e+(a=o)*r)}else if(n<0){if(t<=this.xmin)return null;(o=(this.xmin-t)/n)<a&&(i=this.xmin,s=e+(a=o)*r)}return[i,s]}_edgecode(t,e){return(t===this.xmin?1:t===this.xmax?2:0)|(e===this.ymin?4:e===this.ymax?8:0)}_regioncode(t,e){return(t<this.xmin?1:t>this.xmax?2:0)|(e<this.ymin?4:e>this.ymax?8:0)}}const Vo=2*Math.PI,Yo=Math.pow;function Ko(t){return t[0]}function Xo(t){return t[1]}function Qo(t,e,n){return[t+Math.sin(t+e)*n,e+Math.cos(t-e)*n]}class ti{static from(t,e=Ko,n=Xo,r){return new ti("length"in t?function(t,e,n,r){const o=t.length,i=new Float64Array(2*o);for(let s=0;s<o;++s){const o=t[s];i[2*s]=e.call(r,o,s,t),i[2*s+1]=n.call(r,o,s,t)}return i}(t,e,n,r):Float64Array.from(function*(t,e,n,r){let o=0;for(const i of t)yield e.call(r,i,o,t),yield n.call(r,i,o,t),++o}(t,e,n,r)))}constructor(t){this._delaunator=new Fo(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init()}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,e=this.points;if(t.hull&&t.hull.length>2&&function(t){const{triangles:e,coords:n}=t;for(let t=0;t<e.length;t+=3){const r=2*e[t],o=2*e[t+1],i=2*e[t+2];if((n[i]-n[r])*(n[o+1]-n[r+1])-(n[o]-n[r])*(n[i+1]-n[r+1])>1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:e.length/2},((t,e)=>e)).sort(((t,n)=>e[2*t]-e[2*n]||e[2*t+1]-e[2*n+1]));const t=this.collinear[0],n=this.collinear[this.collinear.length-1],r=[e[2*t],e[2*t+1],e[2*n],e[2*n+1]],o=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,n=e.length/2;t<n;++t){const n=Qo(e[2*t],e[2*t+1],o);e[2*t]=n[0],e[2*t+1]=n[1]}this._delaunator=new Fo(e)}else delete this.collinear;const n=this.halfedges=this._delaunator.halfedges,r=this.hull=this._delaunator.hull,o=this.triangles=this._delaunator.triangles,i=this.inedges.fill(-1),s=this._hullIndex.fill(-1);for(let t=0,e=n.length;t<e;++t){const e=o[t%3==2?t-2:t+1];-1!==n[t]&&-1!==i[e]||(i[e]=t)}for(let t=0,e=r.length;t<e;++t)s[r[t]]=t;r.length<=2&&r.length>0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],i[r[0]]=1,2===r.length&&(i[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new Ho(this,t)}*neighbors(t){const{inedges:e,hull:n,_hullIndex:r,halfedges:o,triangles:i,collinear:s}=this;if(s){const e=s.indexOf(t);return e>0&&(yield s[e-1]),void(e<s.length-1&&(yield s[e+1]))}const a=e[t];if(-1===a)return;let l=a,c=-1;do{if(yield c=i[l],l=l%3==2?l-2:l+1,i[l]!==t)return;if(l=o[l],-1===l){const e=n[(r[t]+1)%n.length];return void(e!==c&&(yield e))}}while(l!==a)}find(t,e,n=0){if((t=+t)!=t||(e=+e)!=e)return-1;const r=n;let o;for(;(o=this._step(n,t,e))>=0&&o!==n&&o!==r;)n=o;return o}_step(t,e,n){const{inedges:r,hull:o,_hullIndex:i,halfedges:s,triangles:a,points:l}=this;if(-1===r[t]||!l.length)return(t+1)%(l.length>>1);let c=t,u=Yo(e-l[2*t],2)+Yo(n-l[2*t+1],2);const f=r[t];let d=f;do{let r=a[d];const f=Yo(e-l[2*r],2)+Yo(n-l[2*r+1],2);if(f<u&&(u=f,c=r),d=d%3==2?d-2:d+1,a[d]!==t)break;if(d=s[d],-1===d){if(d=o[(i[t]+1)%o.length],d!==r&&Yo(e-l[2*d],2)+Yo(n-l[2*d+1],2)<u)return d;break}}while(d!==f);return c}render(t){const e=null==t?t=new Jo:void 0,{points:n,halfedges:r,triangles:o}=this;for(let e=0,i=r.length;e<i;++e){const i=r[e];if(i<e)continue;const s=2*o[e],a=2*o[i];t.moveTo(n[s],n[s+1]),t.lineTo(n[a],n[a+1])}return this.renderHull(t),e&&e.value()}renderPoints(t,e){void 0!==e||t&&"function"==typeof t.moveTo||(e=t,t=null),e=null==e?2:+e;const n=null==t?t=new Jo:void 0,{points:r}=this;for(let n=0,o=r.length;n<o;n+=2){const o=r[n],i=r[n+1];t.moveTo(o+e,i),t.arc(o,i,e,0,Vo)}return n&&n.value()}renderHull(t){const e=null==t?t=new Jo:void 0,{hull:n,points:r}=this,o=2*n[0],i=n.length;t.moveTo(r[o],r[o+1]);for(let e=1;e<i;++e){const o=2*n[e];t.lineTo(r[o],r[o+1])}return t.closePath(),e&&e.value()}hullPolygon(){const t=new Wo;return this.renderHull(t),t.value()}renderTriangle(t,e){const n=null==e?e=new Jo:void 0,{points:r,triangles:o}=this,i=2*o[t*=3],s=2*o[t+1],a=2*o[t+2];return e.moveTo(r[i],r[i+1]),e.lineTo(r[s],r[s+1]),e.lineTo(r[a],r[a+1]),e.closePath(),n&&n.value()}*trianglePolygons(){const{triangles:t}=this;for(let e=0,n=t.length/3;e<n;++e)yield this.trianglePolygon(e)}trianglePolygon(t){const e=new Wo;return this.renderTriangle(t,e),e.value()}}const ei=t=>()=>t;function ni(t,{sourceEvent:e,subject:n,target:r,identifier:o,active:i,x:s,y:a,dx:l,dy:c,dispatch:u}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:i,enumerable:!0,configurable:!0},x:{value:s,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:u}})}function ri(t){return!t.ctrlKey&&!t.button}function oi(){return this.parentNode}function ii(t,e){return null==e?{x:t.x,y:t.y}:e}function si(){return navigator.maxTouchPoints||"ontouchstart"in this}function ai(){var t,e,n,r,o=ri,i=oi,s=ii,a=si,l={},c=N("start","drag","end"),u=0,f=0;function d(t){t.on("mousedown.drag",h).filter(a).on("touchstart.drag",g).on("touchmove.drag",y,$t).on("touchend.drag touchcancel.drag",v).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(s,a){if(!r&&o.call(this,s,a)){var l=b(this,i.call(this,s,a),s,a,"mouse");l&&(Lt(s.view).on("mousemove.drag",p,Zt).on("mouseup.drag",m,Zt),Bt(s.view),zt(s),n=!1,t=s.clientX,e=s.clientY,l("start",s))}}function p(r){if(Ut(r),!n){var o=r.clientX-t,i=r.clientY-e;n=o*o+i*i>f}l.mouse("drag",r)}function m(t){Lt(t.view).on("mousemove.drag mouseup.drag",null),Gt(t.view,n),Ut(t),l.mouse("end",t)}function g(t,e){if(o.call(this,t,e)){var n,r,s=t.changedTouches,a=i.call(this,t,e),l=s.length;for(n=0;n<l;++n)(r=b(this,a,t,e,s[n].identifier,s[n]))&&(zt(t),r("start",t,s[n]))}}function y(t){var e,n,r=t.changedTouches,o=r.length;for(e=0;e<o;++e)(n=l[r[e].identifier])&&(Ut(t),n("drag",t,r[e]))}function v(t){var e,n,o=t.changedTouches,i=o.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),e=0;e<i;++e)(n=l[o[e].identifier])&&(zt(t),n("end",t,o[e]))}function b(t,e,n,r,o,i){var a,f,h,p=c.copy(),m=Ht(i||n,e);if(null!=(h=s.call(t,new ni("beforestart",{sourceEvent:n,target:d,identifier:o,active:u,x:m[0],y:m[1],dx:0,dy:0,dispatch:p}),r)))return a=h.x-m[0]||0,f=h.y-m[1]||0,function n(i,s,c){var g,y=m;switch(i){case"start":l[o]=n,g=u++;break;case"end":delete l[o],--u;case"drag":m=Ht(c||s,e),g=u}p.call(i,t,new ni(i,{sourceEvent:s,subject:h,target:d,identifier:o,active:g,x:m[0]+a,y:m[1]+f,dx:m[0]-y[0],dy:m[1]-y[1],dispatch:p}),r)}}return d.filter=function(t){return arguments.length?(o="function"==typeof t?t:ei(!!t),d):o},d.container=function(t){return arguments.length?(i="function"==typeof t?t:ei(t),d):i},d.subject=function(t){return arguments.length?(s="function"==typeof t?t:ei(t),d):s},d.touchable=function(t){return arguments.length?(a="function"==typeof t?t:ei(!!t),d):a},d.on=function(){var t=c.on.apply(c,arguments);return t===c?d:t},d.clickDistance=function(t){return arguments.length?(f=(t=+t)*t,d):Math.sqrt(f)},d}ni.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var li=n(4476),ci=(0,li.Z)(","),ui=ci.parse,fi=ci.parseRows,di=ci.format,hi=ci.formatBody,pi=ci.formatRows,mi=ci.formatRow,gi=ci.formatValue,yi=n(5026);function vi(t){for(var e in t){var n,r,o=t[e].trim();if(o)if("true"===o)o=!0;else if("false"===o)o=!1;else if("NaN"===o)o=NaN;else if(isNaN(n=+o)){if(!(r=o.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;bi&&r[4]&&!r[7]&&(o=o.replace(/-/g,"/").replace(/T/," ")),o=new Date(o)}else o=n;else o=null;t[e]=o}return t}const bi=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours(),wi=t=>+t;function _i(t){return t*t}function xi(t){return t*(2-t)}function ki(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}var qi=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),Ni=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),Si=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3),Ai=Math.PI,Mi=Ai/2;function Ti(t){return 1==+t?1:1-Math.cos(t*Mi)}function Ci(t){return Math.sin(t*Mi)}function ji(t){return(1-Math.cos(Ai*t))/2}function Ei(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function Oi(t){return Ei(1-+t)}function Ii(t){return 1-Ei(t)}function Ri(t){return((t*=2)<=1?Ei(1-t):2-Ei(t-1))/2}function Pi(t){return 1-Math.sqrt(1-t*t)}function Fi(t){return Math.sqrt(1- --t*t)}function Di(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var Li=4/11,$i=6/11,Zi=8/11,zi=3/4,Ui=9/11,Bi=10/11,Gi=15/16,Ji=21/22,Wi=63/64,Hi=1/Li/Li;function Vi(t){return 1-Yi(1-t)}function Yi(t){return(t=+t)<Li?Hi*t*t:t<Zi?Hi*(t-=$i)*t+zi:t<Bi?Hi*(t-=Ui)*t+Gi:Hi*(t-=Ji)*t+Wi}function Ki(t){return((t*=2)<=1?1-Yi(1-t):Yi(t-1)+1)/2}var Xi=1.70158,Qi=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(Xi),ts=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(Xi),es=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(Xi),ns=2*Math.PI,rs=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return e*Ei(- --t)*Math.sin((r-t)/n)}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3),os=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return 1-e*Ei(t=+t)*Math.sin((t+r)/n)}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3),is=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return((t=2*t-1)<0?e*Ei(-t)*Math.sin((r-t)/n):2-e*Ei(t)*Math.sin((r+t)/n))/2}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3);function ss(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function as(t,e){return fetch(t,e).then(ss)}function ls(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function cs(t,e){return fetch(t,e).then(ls)}function us(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function fs(t,e){return fetch(t,e).then(us)}function ds(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),fs(e,n).then((function(e){return t(e,r)}))}}function hs(t,e,n,r){3===arguments.length&&"function"==typeof n&&(r=n,n=void 0);var o=(0,li.Z)(t);return fs(e,n).then((function(t){return o.parse(t,r)}))}var ps=ds(ui),ms=ds(yi.tJ);function gs(t,e){return new Promise((function(n,r){var o=new Image;for(var i in e)o[i]=e[i];o.onerror=r,o.onload=function(){n(o)},o.src=t}))}function ys(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function vs(t,e){return fetch(t,e).then(ys)}function bs(t){return(e,n)=>fs(e,n).then((e=>(new DOMParser).parseFromString(e,t)))}const ws=bs("application/xml");var _s=bs("text/html"),xs=bs("image/svg+xml");function ks(t,e){var n,r=1;function o(){var o,i,s=n.length,a=0,l=0;for(o=0;o<s;++o)a+=(i=n[o]).x,l+=i.y;for(a=(a/s-t)*r,l=(l/s-e)*r,o=0;o<s;++o)(i=n[o]).x-=a,i.y-=l}return null==t&&(t=0),null==e&&(e=0),o.initialize=function(t){n=t},o.x=function(e){return arguments.length?(t=+e,o):t},o.y=function(t){return arguments.length?(e=+t,o):e},o.strength=function(t){return arguments.length?(r=+t,o):r},o}function qs(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var o,i,s,a,l,c,u,f,d,h=t._root,p={data:r},m=t._x0,g=t._y0,y=t._x1,v=t._y1;if(!h)return t._root=p,t;for(;h.length;)if((c=e>=(i=(m+y)/2))?m=i:y=i,(u=n>=(s=(g+v)/2))?g=s:v=s,o=h,!(h=h[f=u<<1|c]))return o[f]=p,t;if(a=+t._x.call(null,h.data),l=+t._y.call(null,h.data),e===a&&n===l)return p.next=h,o?o[f]=p:t._root=p,t;do{o=o?o[f]=new Array(4):t._root=new Array(4),(c=e>=(i=(m+y)/2))?m=i:y=i,(u=n>=(s=(g+v)/2))?g=s:v=s}while((f=u<<1|c)==(d=(l>=s)<<1|a>=i));return o[d]=h,o[f]=p,t}function Ns(t,e,n,r,o){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=o}function Ss(t){return t[0]}function As(t){return t[1]}function Ms(t,e,n){var r=new Ts(null==e?Ss:e,null==n?As:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Ts(t,e,n,r,o,i){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=o,this._y1=i,this._root=void 0}function Cs(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var js=Ms.prototype=Ts.prototype;function Es(t){return function(){return t}}function Os(t){return 1e-6*(t()-.5)}function Is(t){return t.x+t.vx}function Rs(t){return t.y+t.vy}function Ps(t){var e,n,r,o=1,i=1;function s(){for(var t,s,l,c,u,f,d,h=e.length,p=0;p<i;++p)for(s=Ms(e,Is,Rs).visitAfter(a),t=0;t<h;++t)l=e[t],f=n[l.index],d=f*f,c=l.x+l.vx,u=l.y+l.vy,s.visit(m);function m(t,e,n,i,s){var a=t.data,h=t.r,p=f+h;if(!a)return e>c+p||i<c-p||n>u+p||s<u-p;if(a.index>l.index){var m=c-a.x-a.vx,g=u-a.y-a.vy,y=m*m+g*g;y<p*p&&(0===m&&(y+=(m=Os(r))*m),0===g&&(y+=(g=Os(r))*g),y=(p-(y=Math.sqrt(y)))/y*o,l.vx+=(m*=y)*(p=(h*=h)/(d+h)),l.vy+=(g*=y)*p,a.vx-=m*(p=1-p),a.vy-=g*p)}}}function a(t){if(t.data)return t.r=n[t.data.index];for(var e=t.r=0;e<4;++e)t[e]&&t[e].r>t.r&&(t.r=t[e].r)}function l(){if(e){var r,o,i=e.length;for(n=new Array(i),r=0;r<i;++r)o=e[r],n[o.index]=+t(o,r,e)}}return"function"!=typeof t&&(t=Es(null==t?1:+t)),s.initialize=function(t,n){e=t,r=n,l()},s.iterations=function(t){return arguments.length?(i=+t,s):i},s.strength=function(t){return arguments.length?(o=+t,s):o},s.radius=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),l(),s):t},s}function Fs(t){return t.index}function Ds(t,e){var n=t.get(e);if(!n)throw new Error("node not found: "+e);return n}function Ls(t){var e,n,r,o,i,s,a=Fs,l=function(t){return 1/Math.min(o[t.source.index],o[t.target.index])},c=Es(30),u=1;function f(r){for(var o=0,a=t.length;o<u;++o)for(var l,c,f,d,h,p,m,g=0;g<a;++g)c=(l=t[g]).source,d=(f=l.target).x+f.vx-c.x-c.vx||Os(s),h=f.y+f.vy-c.y-c.vy||Os(s),d*=p=((p=Math.sqrt(d*d+h*h))-n[g])/p*r*e[g],h*=p,f.vx-=d*(m=i[g]),f.vy-=h*m,c.vx+=d*(m=1-m),c.vy+=h*m}function d(){if(r){var s,l,c=r.length,u=t.length,f=new Map(r.map(((t,e)=>[a(t,e,r),t])));for(s=0,o=new Array(c);s<u;++s)(l=t[s]).index=s,"object"!=typeof l.source&&(l.source=Ds(f,l.source)),"object"!=typeof l.target&&(l.target=Ds(f,l.target)),o[l.source.index]=(o[l.source.index]||0)+1,o[l.target.index]=(o[l.target.index]||0)+1;for(s=0,i=new Array(u);s<u;++s)l=t[s],i[s]=o[l.source.index]/(o[l.source.index]+o[l.target.index]);e=new Array(u),h(),n=new Array(u),p()}}function h(){if(r)for(var n=0,o=t.length;n<o;++n)e[n]=+l(t[n],n,t)}function p(){if(r)for(var e=0,o=t.length;e<o;++e)n[e]=+c(t[e],e,t)}return null==t&&(t=[]),f.initialize=function(t,e){r=t,s=e,d()},f.links=function(e){return arguments.length?(t=e,d(),f):t},f.id=function(t){return arguments.length?(a=t,f):a},f.iterations=function(t){return arguments.length?(u=+t,f):u},f.strength=function(t){return arguments.length?(l="function"==typeof t?t:Es(+t),h(),f):l},f.distance=function(t){return arguments.length?(c="function"==typeof t?t:Es(+t),p(),f):c},f}js.copy=function(){var t,e,n=new Ts(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=Cs(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var o=0;o<4;++o)(e=r.source[o])&&(e.length?t.push({source:e,target:r.target[o]=new Array(4)}):r.target[o]=Cs(e));return n},js.add=function(t){const e=+this._x.call(null,t),n=+this._y.call(null,t);return qs(this.cover(e,n),e,n,t)},js.addAll=function(t){var e,n,r,o,i=t.length,s=new Array(i),a=new Array(i),l=1/0,c=1/0,u=-1/0,f=-1/0;for(n=0;n<i;++n)isNaN(r=+this._x.call(null,e=t[n]))||isNaN(o=+this._y.call(null,e))||(s[n]=r,a[n]=o,r<l&&(l=r),r>u&&(u=r),o<c&&(c=o),o>f&&(f=o));if(l>u||c>f)return this;for(this.cover(l,c).cover(u,f),n=0;n<i;++n)qs(this,s[n],a[n],t[n]);return this},js.cover=function(t,e){if(isNaN(t=+t)||isNaN(e=+e))return this;var n=this._x0,r=this._y0,o=this._x1,i=this._y1;if(isNaN(n))o=(n=Math.floor(t))+1,i=(r=Math.floor(e))+1;else{for(var s,a,l=o-n||1,c=this._root;n>t||t>=o||r>e||e>=i;)switch(a=(e<r)<<1|t<n,(s=new Array(4))[a]=c,c=s,l*=2,a){case 0:o=n+l,i=r+l;break;case 1:n=o-l,i=r+l;break;case 2:o=n+l,r=i-l;break;case 3:n=o-l,r=i-l}this._root&&this._root.length&&(this._root=c)}return this._x0=n,this._y0=r,this._x1=o,this._y1=i,this},js.data=function(){var t=[];return this.visit((function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)})),t},js.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},js.find=function(t,e,n){var r,o,i,s,a,l,c,u=this._x0,f=this._y0,d=this._x1,h=this._y1,p=[],m=this._root;for(m&&p.push(new Ns(m,u,f,d,h)),null==n?n=1/0:(u=t-n,f=e-n,d=t+n,h=e+n,n*=n);l=p.pop();)if(!(!(m=l.node)||(o=l.x0)>d||(i=l.y0)>h||(s=l.x1)<u||(a=l.y1)<f))if(m.length){var g=(o+s)/2,y=(i+a)/2;p.push(new Ns(m[3],g,y,s,a),new Ns(m[2],o,y,g,a),new Ns(m[1],g,i,s,y),new Ns(m[0],o,i,g,y)),(c=(e>=y)<<1|t>=g)&&(l=p[p.length-1],p[p.length-1]=p[p.length-1-c],p[p.length-1-c]=l)}else{var v=t-+this._x.call(null,m.data),b=e-+this._y.call(null,m.data),w=v*v+b*b;if(w<n){var _=Math.sqrt(n=w);u=t-_,f=e-_,d=t+_,h=e+_,r=m.data}}return r},js.remove=function(t){if(isNaN(i=+this._x.call(null,t))||isNaN(s=+this._y.call(null,t)))return this;var e,n,r,o,i,s,a,l,c,u,f,d,h=this._root,p=this._x0,m=this._y0,g=this._x1,y=this._y1;if(!h)return this;if(h.length)for(;;){if((c=i>=(a=(p+g)/2))?p=a:g=a,(u=s>=(l=(m+y)/2))?m=l:y=l,e=h,!(h=h[f=u<<1|c]))return this;if(!h.length)break;(e[f+1&3]||e[f+2&3]||e[f+3&3])&&(n=e,d=f)}for(;h.data!==t;)if(r=h,!(h=h.next))return this;return(o=h.next)&&delete h.next,r?(o?r.next=o:delete r.next,this):e?(o?e[f]=o:delete e[f],(h=e[0]||e[1]||e[2]||e[3])&&h===(e[3]||e[2]||e[1]||e[0])&&!h.length&&(n?n[d]=h:this._root=h),this):(this._root=o,this)},js.removeAll=function(t){for(var e=0,n=t.length;e<n;++e)this.remove(t[e]);return this},js.root=function(){return this._root},js.size=function(){var t=0;return this.visit((function(e){if(!e.length)do{++t}while(e=e.next)})),t},js.visit=function(t){var e,n,r,o,i,s,a=[],l=this._root;for(l&&a.push(new Ns(l,this._x0,this._y0,this._x1,this._y1));e=a.pop();)if(!t(l=e.node,r=e.x0,o=e.y0,i=e.x1,s=e.y1)&&l.length){var c=(r+i)/2,u=(o+s)/2;(n=l[3])&&a.push(new Ns(n,c,u,i,s)),(n=l[2])&&a.push(new Ns(n,r,u,c,s)),(n=l[1])&&a.push(new Ns(n,c,o,i,u)),(n=l[0])&&a.push(new Ns(n,r,o,c,u))}return this},js.visitAfter=function(t){var e,n=[],r=[];for(this._root&&n.push(new Ns(this._root,this._x0,this._y0,this._x1,this._y1));e=n.pop();){var o=e.node;if(o.length){var i,s=e.x0,a=e.y0,l=e.x1,c=e.y1,u=(s+l)/2,f=(a+c)/2;(i=o[0])&&n.push(new Ns(i,s,a,u,f)),(i=o[1])&&n.push(new Ns(i,u,a,l,f)),(i=o[2])&&n.push(new Ns(i,s,f,u,c)),(i=o[3])&&n.push(new Ns(i,u,f,l,c))}r.push(e)}for(;e=r.pop();)t(e.node,e.x0,e.y0,e.x1,e.y1);return this},js.x=function(t){return arguments.length?(this._x=t,this):this._x},js.y=function(t){return arguments.length?(this._y=t,this):this._y};const $s=1664525,Zs=1013904223,zs=4294967296;function Us(t){return t.x}function Bs(t){return t.y}var Gs=10,Js=Math.PI*(3-Math.sqrt(5));function Ws(t){var e,n=1,r=.001,o=1-Math.pow(r,1/300),i=0,s=.6,a=new Map,l=ce(f),c=N("tick","end"),u=function(){let t=1;return()=>(t=($s*t+Zs)%zs)/zs}();function f(){d(),c.call("tick",e),n<r&&(l.stop(),c.call("end",e))}function d(r){var l,c,u=t.length;void 0===r&&(r=1);for(var f=0;f<r;++f)for(n+=(i-n)*o,a.forEach((function(t){t(n)})),l=0;l<u;++l)null==(c=t[l]).fx?c.x+=c.vx*=s:(c.x=c.fx,c.vx=0),null==c.fy?c.y+=c.vy*=s:(c.y=c.fy,c.vy=0);return e}function h(){for(var e,n=0,r=t.length;n<r;++n){if((e=t[n]).index=n,null!=e.fx&&(e.x=e.fx),null!=e.fy&&(e.y=e.fy),isNaN(e.x)||isNaN(e.y)){var o=Gs*Math.sqrt(.5+n),i=n*Js;e.x=o*Math.cos(i),e.y=o*Math.sin(i)}(isNaN(e.vx)||isNaN(e.vy))&&(e.vx=e.vy=0)}}function p(e){return e.initialize&&e.initialize(t,u),e}return null==t&&(t=[]),h(),e={tick:d,restart:function(){return l.restart(f),e},stop:function(){return l.stop(),e},nodes:function(n){return arguments.length?(t=n,h(),a.forEach(p),e):t},alpha:function(t){return arguments.length?(n=+t,e):n},alphaMin:function(t){return arguments.length?(r=+t,e):r},alphaDecay:function(t){return arguments.length?(o=+t,e):+o},alphaTarget:function(t){return arguments.length?(i=+t,e):i},velocityDecay:function(t){return arguments.length?(s=1-t,e):1-s},randomSource:function(t){return arguments.length?(u=t,a.forEach(p),e):u},force:function(t,n){return arguments.length>1?(null==n?a.delete(t):a.set(t,p(n)),e):a.get(t)},find:function(e,n,r){var o,i,s,a,l,c=0,u=t.length;for(null==r?r=1/0:r*=r,c=0;c<u;++c)(s=(o=e-(a=t[c]).x)*o+(i=n-a.y)*i)<r&&(l=a,r=s);return l},on:function(t,n){return arguments.length>1?(c.on(t,n),e):c.on(t)}}}function Hs(){var t,e,n,r,o,i=Es(-30),s=1,a=1/0,l=.81;function c(n){var o,i=t.length,s=Ms(t,Us,Bs).visitAfter(f);for(r=n,o=0;o<i;++o)e=t[o],s.visit(d)}function u(){if(t){var e,n,r=t.length;for(o=new Array(r),e=0;e<r;++e)n=t[e],o[n.index]=+i(n,e,t)}}function f(t){var e,n,r,i,s,a=0,l=0;if(t.length){for(r=i=s=0;s<4;++s)(e=t[s])&&(n=Math.abs(e.value))&&(a+=e.value,l+=n,r+=n*e.x,i+=n*e.y);t.x=r/l,t.y=i/l}else{(e=t).x=e.data.x,e.y=e.data.y;do{a+=o[e.data.index]}while(e=e.next)}t.value=a}function d(t,i,c,u){if(!t.value)return!0;var f=t.x-e.x,d=t.y-e.y,h=u-i,p=f*f+d*d;if(h*h/l<p)return p<a&&(0===f&&(p+=(f=Os(n))*f),0===d&&(p+=(d=Os(n))*d),p<s&&(p=Math.sqrt(s*p)),e.vx+=f*t.value*r/p,e.vy+=d*t.value*r/p),!0;if(!(t.length||p>=a)){(t.data!==e||t.next)&&(0===f&&(p+=(f=Os(n))*f),0===d&&(p+=(d=Os(n))*d),p<s&&(p=Math.sqrt(s*p)));do{t.data!==e&&(h=o[t.data.index]*r/p,e.vx+=f*h,e.vy+=d*h)}while(t=t.next)}}return c.initialize=function(e,r){t=e,n=r,u()},c.strength=function(t){return arguments.length?(i="function"==typeof t?t:Es(+t),u(),c):i},c.distanceMin=function(t){return arguments.length?(s=t*t,c):Math.sqrt(s)},c.distanceMax=function(t){return arguments.length?(a=t*t,c):Math.sqrt(a)},c.theta=function(t){return arguments.length?(l=t*t,c):Math.sqrt(l)},c}function Vs(t,e,n){var r,o,i,s=Es(.1);function a(t){for(var s=0,a=r.length;s<a;++s){var l=r[s],c=l.x-e||1e-6,u=l.y-n||1e-6,f=Math.sqrt(c*c+u*u),d=(i[s]-f)*o[s]*t/f;l.vx+=c*d,l.vy+=u*d}}function l(){if(r){var e,n=r.length;for(o=new Array(n),i=new Array(n),e=0;e<n;++e)i[e]=+t(r[e],e,r),o[e]=isNaN(i[e])?0:+s(r[e],e,r)}}return"function"!=typeof t&&(t=Es(+t)),null==e&&(e=0),null==n&&(n=0),a.initialize=function(t){r=t,l()},a.strength=function(t){return arguments.length?(s="function"==typeof t?t:Es(+t),l(),a):s},a.radius=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),l(),a):t},a.x=function(t){return arguments.length?(e=+t,a):e},a.y=function(t){return arguments.length?(n=+t,a):n},a}function Ys(t){var e,n,r,o=Es(.1);function i(t){for(var o,i=0,s=e.length;i<s;++i)(o=e[i]).vx+=(r[i]-o.x)*n[i]*t}function s(){if(e){var i,s=e.length;for(n=new Array(s),r=new Array(s),i=0;i<s;++i)n[i]=isNaN(r[i]=+t(e[i],i,e))?0:+o(e[i],i,e)}}return"function"!=typeof t&&(t=Es(null==t?0:+t)),i.initialize=function(t){e=t,s()},i.strength=function(t){return arguments.length?(o="function"==typeof t?t:Es(+t),s(),i):o},i.x=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),s(),i):t},i}function Ks(t){var e,n,r,o=Es(.1);function i(t){for(var o,i=0,s=e.length;i<s;++i)(o=e[i]).vy+=(r[i]-o.y)*n[i]*t}function s(){if(e){var i,s=e.length;for(n=new Array(s),r=new Array(s),i=0;i<s;++i)n[i]=isNaN(r[i]=+t(e[i],i,e))?0:+o(e[i],i,e)}}return"function"!=typeof t&&(t=Es(null==t?0:+t)),i.initialize=function(t){e=t,s()},i.strength=function(t){return arguments.length?(o="function"==typeof t?t:Es(+t),s(),i):o},i.y=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),s(),i):t},i}var Xs=n(2163),Qs=n(2107),ta=n(7259),ea=n(9680),na=n(3150),ra=n(3621),oa=n(9343),ia=1e-6,sa=1e-12,aa=Math.PI,la=aa/2,ca=aa/4,ua=2*aa,fa=180/aa,da=aa/180,ha=Math.abs,pa=Math.atan,ma=Math.atan2,ga=Math.cos,ya=Math.ceil,va=Math.exp,ba=(Math.floor,Math.hypot),wa=Math.log,_a=Math.pow,xa=Math.sin,ka=Math.sign||function(t){return t>0?1:t<0?-1:0},qa=Math.sqrt,Na=Math.tan;function Sa(t){return t>1?0:t<-1?aa:Math.acos(t)}function Aa(t){return t>1?la:t<-1?-la:Math.asin(t)}function Ma(t){return(t=xa(t/2))*t}function Ta(){}function Ca(t,e){t&&Ea.hasOwnProperty(t.type)&&Ea[t.type](t,e)}var ja={Feature:function(t,e){Ca(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,o=n.length;++r<o;)Ca(n[r].geometry,e)}},Ea={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)t=n[r],e.point(t[0],t[1],t[2])},LineString:function(t,e){Oa(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)Oa(n[r],e,0)},Polygon:function(t,e){Ia(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)Ia(n[r],e)},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,o=n.length;++r<o;)Ca(n[r],e)}};function Oa(t,e,n){var r,o=-1,i=t.length-n;for(e.lineStart();++o<i;)r=t[o],e.point(r[0],r[1],r[2]);e.lineEnd()}function Ia(t,e){var n=-1,r=t.length;for(e.polygonStart();++n<r;)Oa(t[n],e,1);e.polygonEnd()}function Ra(t,e){t&&ja.hasOwnProperty(t.type)?ja[t.type](t,e):Ca(t,e)}var Pa,Fa,Da,La,$a,Za,za,Ua,Ba,Ga,Ja,Wa,Ha,Va,Ya,Ka,Xa=new oa.dU,Qa=new oa.dU,tl={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){Xa=new oa.dU,tl.lineStart=el,tl.lineEnd=nl},polygonEnd:function(){var t=+Xa;Qa.add(t<0?ua+t:t),this.lineStart=this.lineEnd=this.point=Ta},sphere:function(){Qa.add(ua)}};function el(){tl.point=rl}function nl(){ol(Pa,Fa)}function rl(t,e){tl.point=ol,Pa=t,Fa=e,Da=t*=da,La=ga(e=(e*=da)/2+ca),$a=xa(e)}function ol(t,e){var n=(t*=da)-Da,r=n>=0?1:-1,o=r*n,i=ga(e=(e*=da)/2+ca),s=xa(e),a=$a*s,l=La*i+a*ga(o),c=a*r*xa(o);Xa.add(ma(c,l)),Da=t,La=i,$a=s}function il(t){return Qa=new oa.dU,Ra(t,tl),2*Qa}function sl(t){return[ma(t[1],t[0]),Aa(t[2])]}function al(t){var e=t[0],n=t[1],r=ga(n);return[r*ga(e),r*xa(e),xa(n)]}function ll(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function cl(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function ul(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function fl(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function dl(t){var e=qa(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var hl,pl,ml,gl,yl,vl,bl,wl,_l,xl,kl,ql,Nl,Sl,Al,Ml,Tl={point:Cl,lineStart:El,lineEnd:Ol,polygonStart:function(){Tl.point=Il,Tl.lineStart=Rl,Tl.lineEnd=Pl,Va=new oa.dU,tl.polygonStart()},polygonEnd:function(){tl.polygonEnd(),Tl.point=Cl,Tl.lineStart=El,Tl.lineEnd=Ol,Xa<0?(Za=-(Ua=180),za=-(Ba=90)):Va>ia?Ba=90:Va<-ia&&(za=-90),Ka[0]=Za,Ka[1]=Ua},sphere:function(){Za=-(Ua=180),za=-(Ba=90)}};function Cl(t,e){Ya.push(Ka=[Za=t,Ua=t]),e<za&&(za=e),e>Ba&&(Ba=e)}function jl(t,e){var n=al([t*da,e*da]);if(Ha){var r=cl(Ha,n),o=cl([r[1],-r[0],0],r);dl(o),o=sl(o);var i,s=t-Ga,a=s>0?1:-1,l=o[0]*fa*a,c=ha(s)>180;c^(a*Ga<l&&l<a*t)?(i=o[1]*fa)>Ba&&(Ba=i):c^(a*Ga<(l=(l+360)%360-180)&&l<a*t)?(i=-o[1]*fa)<za&&(za=i):(e<za&&(za=e),e>Ba&&(Ba=e)),c?t<Ga?Fl(Za,t)>Fl(Za,Ua)&&(Ua=t):Fl(t,Ua)>Fl(Za,Ua)&&(Za=t):Ua>=Za?(t<Za&&(Za=t),t>Ua&&(Ua=t)):t>Ga?Fl(Za,t)>Fl(Za,Ua)&&(Ua=t):Fl(t,Ua)>Fl(Za,Ua)&&(Za=t)}else Ya.push(Ka=[Za=t,Ua=t]);e<za&&(za=e),e>Ba&&(Ba=e),Ha=n,Ga=t}function El(){Tl.point=jl}function Ol(){Ka[0]=Za,Ka[1]=Ua,Tl.point=Cl,Ha=null}function Il(t,e){if(Ha){var n=t-Ga;Va.add(ha(n)>180?n+(n>0?360:-360):n)}else Ja=t,Wa=e;tl.point(t,e),jl(t,e)}function Rl(){tl.lineStart()}function Pl(){Il(Ja,Wa),tl.lineEnd(),ha(Va)>ia&&(Za=-(Ua=180)),Ka[0]=Za,Ka[1]=Ua,Ha=null}function Fl(t,e){return(e-=t)<0?e+360:e}function Dl(t,e){return t[0]-e[0]}function Ll(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}function $l(t){var e,n,r,o,i,s,a;if(Ba=Ua=-(Za=za=1/0),Ya=[],Ra(t,Tl),n=Ya.length){for(Ya.sort(Dl),e=1,i=[r=Ya[0]];e<n;++e)Ll(r,(o=Ya[e])[0])||Ll(r,o[1])?(Fl(r[0],o[1])>Fl(r[0],r[1])&&(r[1]=o[1]),Fl(o[0],r[1])>Fl(r[0],r[1])&&(r[0]=o[0])):i.push(r=o);for(s=-1/0,e=0,r=i[n=i.length-1];e<=n;r=o,++e)o=i[e],(a=Fl(r[1],o[0]))>s&&(s=a,Za=o[0],Ua=r[1])}return Ya=Ka=null,Za===1/0||za===1/0?[[NaN,NaN],[NaN,NaN]]:[[Za,za],[Ua,Ba]]}var Zl={sphere:Ta,point:zl,lineStart:Bl,lineEnd:Wl,polygonStart:function(){Zl.lineStart=Hl,Zl.lineEnd=Vl},polygonEnd:function(){Zl.lineStart=Bl,Zl.lineEnd=Wl}};function zl(t,e){t*=da;var n=ga(e*=da);Ul(n*ga(t),n*xa(t),xa(e))}function Ul(t,e,n){++hl,ml+=(t-ml)/hl,gl+=(e-gl)/hl,yl+=(n-yl)/hl}function Bl(){Zl.point=Gl}function Gl(t,e){t*=da;var n=ga(e*=da);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),Zl.point=Jl,Ul(Sl,Al,Ml)}function Jl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),o=n*xa(t),i=xa(e),s=ma(qa((s=Al*i-Ml*o)*s+(s=Ml*r-Sl*i)*s+(s=Sl*o-Al*r)*s),Sl*r+Al*o+Ml*i);pl+=s,vl+=s*(Sl+(Sl=r)),bl+=s*(Al+(Al=o)),wl+=s*(Ml+(Ml=i)),Ul(Sl,Al,Ml)}function Wl(){Zl.point=zl}function Hl(){Zl.point=Yl}function Vl(){Kl(ql,Nl),Zl.point=zl}function Yl(t,e){ql=t,Nl=e,t*=da,e*=da,Zl.point=Kl;var n=ga(e);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),Ul(Sl,Al,Ml)}function Kl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),o=n*xa(t),i=xa(e),s=Al*i-Ml*o,a=Ml*r-Sl*i,l=Sl*o-Al*r,c=ba(s,a,l),u=Aa(c),f=c&&-u/c;_l.add(f*s),xl.add(f*a),kl.add(f*l),pl+=u,vl+=u*(Sl+(Sl=r)),bl+=u*(Al+(Al=o)),wl+=u*(Ml+(Ml=i)),Ul(Sl,Al,Ml)}function Xl(t){hl=pl=ml=gl=yl=vl=bl=wl=0,_l=new oa.dU,xl=new oa.dU,kl=new oa.dU,Ra(t,Zl);var e=+_l,n=+xl,r=+kl,o=ba(e,n,r);return o<sa&&(e=vl,n=bl,r=wl,pl<ia&&(e=ml,n=gl,r=yl),(o=ba(e,n,r))<sa)?[NaN,NaN]:[ma(n,e)*fa,Aa(r/o)*fa]}function Ql(t){return function(){return t}}function tc(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return(n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}function ec(t,e){return[ha(t)>aa?t+Math.round(-t/ua)*ua:t,e]}function nc(t,e,n){return(t%=ua)?e||n?tc(oc(t),ic(e,n)):oc(t):e||n?ic(e,n):ec}function rc(t){return function(e,n){return[(e+=t)>aa?e-ua:e<-aa?e+ua:e,n]}}function oc(t){var e=rc(t);return e.invert=rc(-t),e}function ic(t,e){var n=ga(t),r=xa(t),o=ga(e),i=xa(e);function s(t,e){var s=ga(e),a=ga(t)*s,l=xa(t)*s,c=xa(e),u=c*n+a*r;return[ma(l*o-u*i,a*n-c*r),Aa(u*o+l*i)]}return s.invert=function(t,e){var s=ga(e),a=ga(t)*s,l=xa(t)*s,c=xa(e),u=c*o-l*i;return[ma(l*o+c*i,a*n+u*r),Aa(u*n-a*r)]},s}function sc(t){function e(e){return(e=t(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e}return t=nc(t[0]*da,t[1]*da,t.length>2?t[2]*da:0),e.invert=function(e){return(e=t.invert(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e},e}function ac(t,e,n,r,o,i){if(n){var s=ga(e),a=xa(e),l=r*n;null==o?(o=e+r*ua,i=e-l/2):(o=lc(s,o),i=lc(s,i),(r>0?o<i:o>i)&&(o+=r*ua));for(var c,u=o;r>0?u>i:u<i;u-=l)c=sl([s,-a*ga(u),-a*xa(u)]),t.point(c[0],c[1])}}function lc(t,e){(e=al(e))[0]-=t,dl(e);var n=Sa(-e[1]);return((-e[2]<0?-n:n)+ua-ia)%ua}function cc(){var t,e,n=Ql([0,0]),r=Ql(90),o=Ql(6),i={point:function(n,r){t.push(n=e(n,r)),n[0]*=fa,n[1]*=fa}};function s(){var s=n.apply(this,arguments),a=r.apply(this,arguments)*da,l=o.apply(this,arguments)*da;return t=[],e=nc(-s[0]*da,-s[1]*da,0).invert,ac(i,a,l,1),s={type:"Polygon",coordinates:[t]},t=e=null,s}return s.center=function(t){return arguments.length?(n="function"==typeof t?t:Ql([+t[0],+t[1]]),s):n},s.radius=function(t){return arguments.length?(r="function"==typeof t?t:Ql(+t),s):r},s.precision=function(t){return arguments.length?(o="function"==typeof t?t:Ql(+t),s):o},s}function uc(){var t,e=[];return{point:function(e,n,r){t.push([e,n,r])},lineStart:function(){e.push(t=[])},lineEnd:Ta,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function fc(t,e){return ha(t[0]-e[0])<ia&&ha(t[1]-e[1])<ia}function dc(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function hc(t,e,n,r,o){var i,s,a=[],l=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,r=t[0],s=t[e];if(fc(r,s)){if(!r[2]&&!s[2]){for(o.lineStart(),i=0;i<e;++i)o.point((r=t[i])[0],r[1]);return void o.lineEnd()}s[0]+=2*ia}a.push(n=new dc(r,t,null,!0)),l.push(n.o=new dc(r,null,n,!1)),a.push(n=new dc(s,t,null,!1)),l.push(n.o=new dc(s,null,n,!0))}})),a.length){for(l.sort(e),pc(a),pc(l),i=0,s=l.length;i<s;++i)l[i].e=n=!n;for(var c,u,f=a[0];;){for(var d=f,h=!0;d.v;)if((d=d.n)===f)return;c=d.z,o.lineStart();do{if(d.v=d.o.v=!0,d.e){if(h)for(i=0,s=c.length;i<s;++i)o.point((u=c[i])[0],u[1]);else r(d.x,d.n.x,1,o);d=d.n}else{if(h)for(c=d.p.z,i=c.length-1;i>=0;--i)o.point((u=c[i])[0],u[1]);else r(d.x,d.p.x,-1,o);d=d.p}c=(d=d.o).z,h=!h}while(!d.v);o.lineEnd()}}}function pc(t){if(e=t.length){for(var e,n,r=0,o=t[0];++r<e;)o.n=n=t[r],n.p=o,o=n;o.n=n=t[0],n.p=o}}function mc(t){return ha(t[0])<=aa?t[0]:ka(t[0])*((ha(t[0])+aa)%ua-aa)}function gc(t,e){var n=mc(e),r=e[1],o=xa(r),i=[xa(n),-ga(n),0],s=0,a=0,l=new oa.dU;1===o?r=la+ia:-1===o&&(r=-la-ia);for(var c=0,u=t.length;c<u;++c)if(d=(f=t[c]).length)for(var f,d,h=f[d-1],p=mc(h),m=h[1]/2+ca,g=xa(m),y=ga(m),v=0;v<d;++v,p=w,g=x,y=k,h=b){var b=f[v],w=mc(b),_=b[1]/2+ca,x=xa(_),k=ga(_),q=w-p,N=q>=0?1:-1,S=N*q,A=S>aa,M=g*x;if(l.add(ma(M*N*xa(S),y*k+M*ga(S))),s+=A?q+N*ua:q,A^p>=n^w>=n){var T=cl(al(h),al(b));dl(T);var C=cl(i,T);dl(C);var j=(A^q>=0?-1:1)*Aa(C[2]);(r>j||r===j&&(T[0]||T[1]))&&(a+=A^q>=0?1:-1)}}return(s<-ia||s<ia&&l<-sa)^1&a}ec.invert=ec;var yc=n(1740);function vc(t,e,n,r){return function(o){var i,s,a,l=e(o),c=uc(),u=e(c),f=!1,d={point:h,lineStart:m,lineEnd:g,polygonStart:function(){d.point=y,d.lineStart=v,d.lineEnd=b,s=[],i=[]},polygonEnd:function(){d.point=h,d.lineStart=m,d.lineEnd=g,s=(0,yc.Z)(s);var t=gc(i,r);s.length?(f||(o.polygonStart(),f=!0),hc(s,wc,t,n,o)):t&&(f||(o.polygonStart(),f=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),f&&(o.polygonEnd(),f=!1),s=i=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function h(e,n){t(e,n)&&o.point(e,n)}function p(t,e){l.point(t,e)}function m(){d.point=p,l.lineStart()}function g(){d.point=h,l.lineEnd()}function y(t,e){a.push([t,e]),u.point(t,e)}function v(){u.lineStart(),a=[]}function b(){y(a[0][0],a[0][1]),u.lineEnd();var t,e,n,r,l=u.clean(),d=c.result(),h=d.length;if(a.pop(),i.push(a),a=null,h)if(1&l){if((e=(n=d[0]).length-1)>0){for(f||(o.polygonStart(),f=!0),o.lineStart(),t=0;t<e;++t)o.point((r=n[t])[0],r[1]);o.lineEnd()}}else h>1&&2&l&&d.push(d.pop().concat(d.shift())),s.push(d.filter(bc))}return d}}function bc(t){return t.length>1}function wc(t,e){return((t=t.x)[0]<0?t[1]-la-ia:la-t[1])-((e=e.x)[0]<0?e[1]-la-ia:la-e[1])}const _c=vc((function(){return!0}),(function(t){var e,n=NaN,r=NaN,o=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,s){var a=i>0?aa:-aa,l=ha(i-n);ha(l-aa)<ia?(t.point(n,r=(r+s)/2>0?la:-la),t.point(o,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(i,r),e=0):o!==a&&l>=aa&&(ha(n-o)<ia&&(n-=o*ia),ha(i-a)<ia&&(i-=a*ia),r=function(t,e,n,r){var o,i,s=xa(t-n);return ha(s)>ia?pa((xa(e)*(i=ga(r))*xa(n)-xa(r)*(o=ga(e))*xa(t))/(o*i*s)):(e+r)/2}(n,r,i,s),t.point(o,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=i,r=s),o=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var o;if(null==t)o=n*la,r.point(-aa,o),r.point(0,o),r.point(aa,o),r.point(aa,0),r.point(aa,-o),r.point(0,-o),r.point(-aa,-o),r.point(-aa,0),r.point(-aa,o);else if(ha(t[0]-e[0])>ia){var i=t[0]<e[0]?aa:-aa;o=n*i/2,r.point(-i,o),r.point(0,o),r.point(i,o)}else r.point(e[0],e[1])}),[-aa,-la]);function xc(t){var e=ga(t),n=6*da,r=e>0,o=ha(e)>ia;function i(t,n){return ga(t)*ga(n)>e}function s(t,n,r){var o=[1,0,0],i=cl(al(t),al(n)),s=ll(i,i),a=i[0],l=s-a*a;if(!l)return!r&&t;var c=e*s/l,u=-e*a/l,f=cl(o,i),d=fl(o,c);ul(d,fl(i,u));var h=f,p=ll(d,h),m=ll(h,h),g=p*p-m*(ll(d,d)-1);if(!(g<0)){var y=qa(g),v=fl(h,(-p-y)/m);if(ul(v,d),v=sl(v),!r)return v;var b,w=t[0],_=n[0],x=t[1],k=n[1];_<w&&(b=w,w=_,_=b);var q=_-w,N=ha(q-aa)<ia;if(!N&&k<x&&(b=x,x=k,k=b),N||q<ia?N?x+k>0^v[1]<(ha(v[0]-w)<ia?x:k):x<=v[1]&&v[1]<=k:q>aa^(w<=v[0]&&v[0]<=_)){var S=fl(h,(-p+y)/m);return ul(S,d),[v,sl(S)]}}}function a(e,n){var o=r?t:aa-t,i=0;return e<-o?i|=1:e>o&&(i|=2),n<-o?i|=4:n>o&&(i|=8),i}return vc(i,(function(t){var e,n,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,d){var h,p=[f,d],m=i(f,d),g=r?m?0:a(f,d):m?a(f+(f<0?aa:-aa),d):0;if(!e&&(c=l=m)&&t.lineStart(),m!==l&&(!(h=s(e,p))||fc(e,h)||fc(p,h))&&(p[2]=1),m!==l)u=0,m?(t.lineStart(),h=s(p,e),t.point(h[0],h[1])):(h=s(e,p),t.point(h[0],h[1],2),t.lineEnd()),e=h;else if(o&&e&&r^m){var y;g&n||!(y=s(p,e,!0))||(u=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!m||e&&fc(e,p)||t.point(p[0],p[1]),e=p,l=m,n=g},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return u|(c&&l)<<1}}}),(function(e,r,o,i){ac(i,t,n,o,e,r)}),r?[0,-t]:[-aa,t-aa])}var kc,qc,Nc,Sc,Ac=1e9,Mc=-Ac;function Tc(t,e,n,r){function o(o,i){return t<=o&&o<=n&&e<=i&&i<=r}function i(o,i,a,c){var u=0,f=0;if(null==o||(u=s(o,a))!==(f=s(i,a))||l(o,i)<0^a>0)do{c.point(0===u||3===u?t:n,u>1?r:e)}while((u=(u+a+4)%4)!==f);else c.point(i[0],i[1])}function s(r,o){return ha(r[0]-t)<ia?o>0?0:3:ha(r[0]-n)<ia?o>0?2:1:ha(r[1]-e)<ia?o>0?1:0:o>0?3:2}function a(t,e){return l(t.x,e.x)}function l(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var l,c,u,f,d,h,p,m,g,y,v,b=s,w=uc(),_={point:x,lineStart:function(){_.point=k,c&&c.push(u=[]);y=!0,g=!1,p=m=NaN},lineEnd:function(){l&&(k(f,d),h&&g&&w.rejoin(),l.push(w.result()));_.point=x,g&&b.lineEnd()},polygonStart:function(){b=w,l=[],c=[],v=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,o=c.length;n<o;++n)for(var i,s,a=c[n],l=1,u=a.length,f=a[0],d=f[0],h=f[1];l<u;++l)i=d,s=h,d=(f=a[l])[0],h=f[1],s<=r?h>r&&(d-i)*(r-s)>(h-s)*(t-i)&&++e:h<=r&&(d-i)*(r-s)<(h-s)*(t-i)&&--e;return e}(),n=v&&e,o=(l=(0,yc.Z)(l)).length;(n||o)&&(s.polygonStart(),n&&(s.lineStart(),i(null,null,1,s),s.lineEnd()),o&&hc(l,a,e,i,s),s.polygonEnd());b=s,l=c=u=null}};function x(t,e){o(t,e)&&b.point(t,e)}function k(i,s){var a=o(i,s);if(c&&u.push([i,s]),y)f=i,d=s,h=a,y=!1,a&&(b.lineStart(),b.point(i,s));else if(a&&g)b.point(i,s);else{var l=[p=Math.max(Mc,Math.min(Ac,p)),m=Math.max(Mc,Math.min(Ac,m))],w=[i=Math.max(Mc,Math.min(Ac,i)),s=Math.max(Mc,Math.min(Ac,s))];!function(t,e,n,r,o,i){var s,a=t[0],l=t[1],c=0,u=1,f=e[0]-a,d=e[1]-l;if(s=n-a,f||!(s>0)){if(s/=f,f<0){if(s<c)return;s<u&&(u=s)}else if(f>0){if(s>u)return;s>c&&(c=s)}if(s=o-a,f||!(s<0)){if(s/=f,f<0){if(s>u)return;s>c&&(c=s)}else if(f>0){if(s<c)return;s<u&&(u=s)}if(s=r-l,d||!(s>0)){if(s/=d,d<0){if(s<c)return;s<u&&(u=s)}else if(d>0){if(s>u)return;s>c&&(c=s)}if(s=i-l,d||!(s<0)){if(s/=d,d<0){if(s>u)return;s>c&&(c=s)}else if(d>0){if(s<c)return;s<u&&(u=s)}return c>0&&(t[0]=a+c*f,t[1]=l+c*d),u<1&&(e[0]=a+u*f,e[1]=l+u*d),!0}}}}}(l,w,t,e,n,r)?a&&(b.lineStart(),b.point(i,s),v=!1):(g||(b.lineStart(),b.point(l[0],l[1])),b.point(w[0],w[1]),a||b.lineEnd(),v=!1)}p=i,m=s,g=a}return _}}function Cc(){var t,e,n,r=0,o=0,i=960,s=500;return n={stream:function(n){return t&&e===n?t:t=Tc(r,o,i,s)(e=n)},extent:function(a){return arguments.length?(r=+a[0][0],o=+a[0][1],i=+a[1][0],s=+a[1][1],t=e=null,n):[[r,o],[i,s]]}}}var jc={sphere:Ta,point:Ta,lineStart:function(){jc.point=Oc,jc.lineEnd=Ec},lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta};function Ec(){jc.point=jc.lineEnd=Ta}function Oc(t,e){qc=t*=da,Nc=xa(e*=da),Sc=ga(e),jc.point=Ic}function Ic(t,e){t*=da;var n=xa(e*=da),r=ga(e),o=ha(t-qc),i=ga(o),s=r*xa(o),a=Sc*n-Nc*r*i,l=Nc*n+Sc*r*i;kc.add(ma(qa(s*s+a*a),l)),qc=t,Nc=n,Sc=r}function Rc(t){return kc=new oa.dU,Ra(t,jc),+kc}var Pc=[null,null],Fc={type:"LineString",coordinates:Pc};function Dc(t,e){return Pc[0]=t,Pc[1]=e,Rc(Fc)}var Lc={Feature:function(t,e){return Zc(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,o=n.length;++r<o;)if(Zc(n[r].geometry,e))return!0;return!1}},$c={Sphere:function(){return!0},Point:function(t,e){return zc(t.coordinates,e)},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(zc(n[r],e))return!0;return!1},LineString:function(t,e){return Uc(t.coordinates,e)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(Uc(n[r],e))return!0;return!1},Polygon:function(t,e){return Bc(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(Bc(n[r],e))return!0;return!1},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,o=n.length;++r<o;)if(Zc(n[r],e))return!0;return!1}};function Zc(t,e){return!(!t||!$c.hasOwnProperty(t.type))&&$c[t.type](t,e)}function zc(t,e){return 0===Dc(t,e)}function Uc(t,e){for(var n,r,o,i=0,s=t.length;i<s;i++){if(0===(r=Dc(t[i],e)))return!0;if(i>0&&(o=Dc(t[i],t[i-1]))>0&&n<=o&&r<=o&&(n+r-o)*(1-Math.pow((n-r)/o,2))<sa*o)return!0;n=r}return!1}function Bc(t,e){return!!gc(t.map(Gc),Jc(e))}function Gc(t){return(t=t.map(Jc)).pop(),t}function Jc(t){return[t[0]*da,t[1]*da]}function Wc(t,e){return(t&&Lc.hasOwnProperty(t.type)?Lc[t.type]:Zc)(t,e)}var Hc=n(1265);function Vc(t,e,n){var r=(0,Hc.Z)(t,e-ia,n).concat(e);return function(t){return r.map((function(e){return[t,e]}))}}function Yc(t,e,n){var r=(0,Hc.Z)(t,e-ia,n).concat(e);return function(t){return r.map((function(e){return[e,t]}))}}function Kc(){var t,e,n,r,o,i,s,a,l,c,u,f,d=10,h=d,p=90,m=360,g=2.5;function y(){return{type:"MultiLineString",coordinates:v()}}function v(){return(0,Hc.Z)(ya(r/p)*p,n,p).map(u).concat((0,Hc.Z)(ya(a/m)*m,s,m).map(f)).concat((0,Hc.Z)(ya(e/d)*d,t,d).filter((function(t){return ha(t%p)>ia})).map(l)).concat((0,Hc.Z)(ya(i/h)*h,o,h).filter((function(t){return ha(t%m)>ia})).map(c))}return y.lines=function(){return v().map((function(t){return{type:"LineString",coordinates:t}}))},y.outline=function(){return{type:"Polygon",coordinates:[u(r).concat(f(s).slice(1),u(n).reverse().slice(1),f(a).reverse().slice(1))]}},y.extent=function(t){return arguments.length?y.extentMajor(t).extentMinor(t):y.extentMinor()},y.extentMajor=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],a=+t[0][1],s=+t[1][1],r>n&&(t=r,r=n,n=t),a>s&&(t=a,a=s,s=t),y.precision(g)):[[r,a],[n,s]]},y.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],i=+n[0][1],o=+n[1][1],e>t&&(n=e,e=t,t=n),i>o&&(n=i,i=o,o=n),y.precision(g)):[[e,i],[t,o]]},y.step=function(t){return arguments.length?y.stepMajor(t).stepMinor(t):y.stepMinor()},y.stepMajor=function(t){return arguments.length?(p=+t[0],m=+t[1],y):[p,m]},y.stepMinor=function(t){return arguments.length?(d=+t[0],h=+t[1],y):[d,h]},y.precision=function(d){return arguments.length?(g=+d,l=Vc(i,o,90),c=Yc(e,t,g),u=Vc(a,s,90),f=Yc(r,n,g),y):g},y.extentMajor([[-180,-90+ia],[180,90-ia]]).extentMinor([[-180,-80-ia],[180,80+ia]])}function Xc(){return Kc()()}function Qc(t,e){var n=t[0]*da,r=t[1]*da,o=e[0]*da,i=e[1]*da,s=ga(r),a=xa(r),l=ga(i),c=xa(i),u=s*ga(n),f=s*xa(n),d=l*ga(o),h=l*xa(o),p=2*Aa(qa(Ma(i-r)+s*l*Ma(o-n))),m=xa(p),g=p?function(t){var e=xa(t*=p)/m,n=xa(p-t)/m,r=n*u+e*d,o=n*f+e*h,i=n*a+e*c;return[ma(o,r)*fa,ma(i,qa(r*r+o*o))*fa]}:function(){return[n*fa,r*fa]};return g.distance=p,g}const tu=t=>t;var eu,nu,ru,ou,iu=new oa.dU,su=new oa.dU,au={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){au.lineStart=lu,au.lineEnd=fu},polygonEnd:function(){au.lineStart=au.lineEnd=au.point=Ta,iu.add(ha(su)),su=new oa.dU},result:function(){var t=iu/2;return iu=new oa.dU,t}};function lu(){au.point=cu}function cu(t,e){au.point=uu,eu=ru=t,nu=ou=e}function uu(t,e){su.add(ou*t-ru*e),ru=t,ou=e}function fu(){uu(eu,nu)}const du=au;var hu=1/0,pu=hu,mu=-hu,gu=mu,yu={point:function(t,e){t<hu&&(hu=t);t>mu&&(mu=t);e<pu&&(pu=e);e>gu&&(gu=e)},lineStart:Ta,lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta,result:function(){var t=[[hu,pu],[mu,gu]];return mu=gu=-(pu=hu=1/0),t}};const vu=yu;var bu,wu,_u,xu,ku=0,qu=0,Nu=0,Su=0,Au=0,Mu=0,Tu=0,Cu=0,ju=0,Eu={point:Ou,lineStart:Iu,lineEnd:Fu,polygonStart:function(){Eu.lineStart=Du,Eu.lineEnd=Lu},polygonEnd:function(){Eu.point=Ou,Eu.lineStart=Iu,Eu.lineEnd=Fu},result:function(){var t=ju?[Tu/ju,Cu/ju]:Mu?[Su/Mu,Au/Mu]:Nu?[ku/Nu,qu/Nu]:[NaN,NaN];return ku=qu=Nu=Su=Au=Mu=Tu=Cu=ju=0,t}};function Ou(t,e){ku+=t,qu+=e,++Nu}function Iu(){Eu.point=Ru}function Ru(t,e){Eu.point=Pu,Ou(_u=t,xu=e)}function Pu(t,e){var n=t-_u,r=e-xu,o=qa(n*n+r*r);Su+=o*(_u+t)/2,Au+=o*(xu+e)/2,Mu+=o,Ou(_u=t,xu=e)}function Fu(){Eu.point=Ou}function Du(){Eu.point=$u}function Lu(){Zu(bu,wu)}function $u(t,e){Eu.point=Zu,Ou(bu=_u=t,wu=xu=e)}function Zu(t,e){var n=t-_u,r=e-xu,o=qa(n*n+r*r);Su+=o*(_u+t)/2,Au+=o*(xu+e)/2,Mu+=o,Tu+=(o=xu*t-_u*e)*(_u+t),Cu+=o*(xu+e),ju+=3*o,Ou(_u=t,xu=e)}const zu=Eu;function Uu(t){this._context=t}Uu.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,ua)}},result:Ta};var Bu,Gu,Ju,Wu,Hu,Vu=new oa.dU,Yu={point:Ta,lineStart:function(){Yu.point=Ku},lineEnd:function(){Bu&&Xu(Gu,Ju),Yu.point=Ta},polygonStart:function(){Bu=!0},polygonEnd:function(){Bu=null},result:function(){var t=+Vu;return Vu=new oa.dU,t}};function Ku(t,e){Yu.point=Xu,Gu=Wu=t,Ju=Hu=e}function Xu(t,e){Wu-=t,Hu-=e,Vu.add(qa(Wu*Wu+Hu*Hu)),Wu=t,Hu=e}const Qu=Yu;function tf(){this._string=[]}function ef(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function nf(t,e){var n,r,o=4.5;function i(t){return t&&("function"==typeof o&&r.pointRadius(+o.apply(this,arguments)),Ra(t,n(r))),r.result()}return i.area=function(t){return Ra(t,n(du)),du.result()},i.measure=function(t){return Ra(t,n(Qu)),Qu.result()},i.bounds=function(t){return Ra(t,n(vu)),vu.result()},i.centroid=function(t){return Ra(t,n(zu)),zu.result()},i.projection=function(e){return arguments.length?(n=null==e?(t=null,tu):(t=e).stream,i):t},i.context=function(t){return arguments.length?(r=null==t?(e=null,new tf):new Uu(e=t),"function"!=typeof o&&r.pointRadius(o),i):e},i.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(r.pointRadius(+t),+t),i):o},i.projection(t).context(e)}function rf(t){return{stream:of(t)}}function of(t){return function(e){var n=new sf;for(var r in t)n[r]=t[r];return n.stream=e,n}}function sf(){}function af(t,e,n){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Ra(n,t.stream(vu)),e(vu.result()),null!=r&&t.clipExtent(r),t}function lf(t,e,n){return af(t,(function(n){var r=e[1][0]-e[0][0],o=e[1][1]-e[0][1],i=Math.min(r/(n[1][0]-n[0][0]),o/(n[1][1]-n[0][1])),s=+e[0][0]+(r-i*(n[1][0]+n[0][0]))/2,a=+e[0][1]+(o-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([s,a])}),n)}function cf(t,e,n){return lf(t,[[0,0],e],n)}function uf(t,e,n){return af(t,(function(n){var r=+e,o=r/(n[1][0]-n[0][0]),i=(r-o*(n[1][0]+n[0][0]))/2,s=-o*n[0][1];t.scale(150*o).translate([i,s])}),n)}function ff(t,e,n){return af(t,(function(n){var r=+e,o=r/(n[1][1]-n[0][1]),i=-o*n[0][0],s=(r-o*(n[1][1]+n[0][1]))/2;t.scale(150*o).translate([i,s])}),n)}tf.prototype={_radius:4.5,_circle:ef(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=ef(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},sf.prototype={constructor:sf,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var df=16,hf=ga(30*da);function pf(t,e){return+e?function(t,e){function n(r,o,i,s,a,l,c,u,f,d,h,p,m,g){var y=c-r,v=u-o,b=y*y+v*v;if(b>4*e&&m--){var w=s+d,_=a+h,x=l+p,k=qa(w*w+_*_+x*x),q=Aa(x/=k),N=ha(ha(x)-1)<ia||ha(i-f)<ia?(i+f)/2:ma(_,w),S=t(N,q),A=S[0],M=S[1],T=A-r,C=M-o,j=v*T-y*C;(j*j/b>e||ha((y*T+v*C)/b-.5)>.3||s*d+a*h+l*p<hf)&&(n(r,o,i,s,a,l,A,M,N,w/=k,_/=k,x,m,g),g.point(A,M),n(A,M,N,w,_,x,c,u,f,d,h,p,m,g))}}return function(e){var r,o,i,s,a,l,c,u,f,d,h,p,m={point:g,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),m.lineStart=w},polygonEnd:function(){e.polygonEnd(),m.lineStart=y}};function g(n,r){n=t(n,r),e.point(n[0],n[1])}function y(){u=NaN,m.point=v,e.lineStart()}function v(r,o){var i=al([r,o]),s=t(r,o);n(u,f,c,d,h,p,u=s[0],f=s[1],c=r,d=i[0],h=i[1],p=i[2],df,e),e.point(u,f)}function b(){m.point=g,e.lineEnd()}function w(){y(),m.point=_,m.lineEnd=x}function _(t,e){v(r=t,e),o=u,i=f,s=d,a=h,l=p,m.point=v}function x(){n(u,f,c,d,h,p,o,i,r,s,a,l,df,e),m.lineEnd=b,b()}return m}}(t,e):function(t){return of({point:function(e,n){e=t(e,n),this.stream.point(e[0],e[1])}})}(t)}var mf=of({point:function(t,e){this.stream.point(t*da,e*da)}});function gf(t,e,n,r,o,i){if(!i)return function(t,e,n,r,o){function i(i,s){return[e+t*(i*=r),n-t*(s*=o)]}return i.invert=function(i,s){return[(i-e)/t*r,(n-s)/t*o]},i}(t,e,n,r,o);var s=ga(i),a=xa(i),l=s*t,c=a*t,u=s/t,f=a/t,d=(a*n-s*e)/t,h=(a*e+s*n)/t;function p(t,i){return[l*(t*=r)-c*(i*=o)+e,n-c*t-l*i]}return p.invert=function(t,e){return[r*(u*t-f*e+d),o*(h-f*t-u*e)]},p}function yf(t){return vf((function(){return t}))()}function vf(t){var e,n,r,o,i,s,a,l,c,u,f=150,d=480,h=250,p=0,m=0,g=0,y=0,v=0,b=0,w=1,_=1,x=null,k=_c,q=null,N=tu,S=.5;function A(t){return l(t[0]*da,t[1]*da)}function M(t){return(t=l.invert(t[0],t[1]))&&[t[0]*fa,t[1]*fa]}function T(){var t=gf(f,0,0,w,_,b).apply(null,e(p,m)),r=gf(f,d-t[0],h-t[1],w,_,b);return n=nc(g,y,v),a=tc(e,r),l=tc(n,a),s=pf(a,S),C()}function C(){return c=u=null,A}return A.stream=function(t){return c&&u===t?c:c=mf(function(t){return of({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(k(s(N(u=t)))))},A.preclip=function(t){return arguments.length?(k=t,x=void 0,C()):k},A.postclip=function(t){return arguments.length?(N=t,q=r=o=i=null,C()):N},A.clipAngle=function(t){return arguments.length?(k=+t?xc(x=t*da):(x=null,_c),C()):x*fa},A.clipExtent=function(t){return arguments.length?(N=null==t?(q=r=o=i=null,tu):Tc(q=+t[0][0],r=+t[0][1],o=+t[1][0],i=+t[1][1]),C()):null==q?null:[[q,r],[o,i]]},A.scale=function(t){return arguments.length?(f=+t,T()):f},A.translate=function(t){return arguments.length?(d=+t[0],h=+t[1],T()):[d,h]},A.center=function(t){return arguments.length?(p=t[0]%360*da,m=t[1]%360*da,T()):[p*fa,m*fa]},A.rotate=function(t){return arguments.length?(g=t[0]%360*da,y=t[1]%360*da,v=t.length>2?t[2]%360*da:0,T()):[g*fa,y*fa,v*fa]},A.angle=function(t){return arguments.length?(b=t%360*da,T()):b*fa},A.reflectX=function(t){return arguments.length?(w=t?-1:1,T()):w<0},A.reflectY=function(t){return arguments.length?(_=t?-1:1,T()):_<0},A.precision=function(t){return arguments.length?(s=pf(a,S=t*t),C()):qa(S)},A.fitExtent=function(t,e){return lf(A,t,e)},A.fitSize=function(t,e){return cf(A,t,e)},A.fitWidth=function(t,e){return uf(A,t,e)},A.fitHeight=function(t,e){return ff(A,t,e)},function(){return e=t.apply(this,arguments),A.invert=e.invert&&M,T()}}function bf(t){var e=0,n=aa/3,r=vf(t),o=r(e,n);return o.parallels=function(t){return arguments.length?r(e=t[0]*da,n=t[1]*da):[e*fa,n*fa]},o}function wf(t,e){var n=xa(t),r=(n+xa(e))/2;if(ha(r)<ia)return function(t){var e=ga(t);function n(t,n){return[t*e,xa(n)/e]}return n.invert=function(t,n){return[t/e,Aa(n*e)]},n}(t);var o=1+n*(2*r-n),i=qa(o)/r;function s(t,e){var n=qa(o-2*r*xa(e))/r;return[n*xa(t*=r),i-n*ga(t)]}return s.invert=function(t,e){var n=i-e,s=ma(t,ha(n))*ka(n);return n*r<0&&(s-=aa*ka(t)*ka(n)),[s/r,Aa((o-(t*t+n*n)*r*r)/(2*r))]},s}function _f(){return bf(wf).scale(155.424).center([0,33.6442])}function xf(){return _f().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function kf(){var t,e,n,r,o,i,s=xf(),a=_f().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=_f().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(t,e){i=[t,e]}};function u(t){var e=t[0],s=t[1];return i=null,n.point(e,s),i||(r.point(e,s),i)||(o.point(e,s),i)}function f(){return t=e=null,u}return u.invert=function(t){var e=s.scale(),n=s.translate(),r=(t[0]-n[0])/e,o=(t[1]-n[1])/e;return(o>=.12&&o<.234&&r>=-.425&&r<-.214?a:o>=.166&&o<.234&&r>=-.214&&r<-.115?l:s).invert(t)},u.stream=function(n){return t&&e===n?t:(r=[s.stream(e=n),a.stream(n),l.stream(n)],o=r.length,t={point:function(t,e){for(var n=-1;++n<o;)r[n].point(t,e)},sphere:function(){for(var t=-1;++t<o;)r[t].sphere()},lineStart:function(){for(var t=-1;++t<o;)r[t].lineStart()},lineEnd:function(){for(var t=-1;++t<o;)r[t].lineEnd()},polygonStart:function(){for(var t=-1;++t<o;)r[t].polygonStart()},polygonEnd:function(){for(var t=-1;++t<o;)r[t].polygonEnd()}});var r,o},u.precision=function(t){return arguments.length?(s.precision(t),a.precision(t),l.precision(t),f()):s.precision()},u.scale=function(t){return arguments.length?(s.scale(t),a.scale(.35*t),l.scale(t),u.translate(s.translate())):s.scale()},u.translate=function(t){if(!arguments.length)return s.translate();var e=s.scale(),i=+t[0],u=+t[1];return n=s.translate(t).clipExtent([[i-.455*e,u-.238*e],[i+.455*e,u+.238*e]]).stream(c),r=a.translate([i-.307*e,u+.201*e]).clipExtent([[i-.425*e+ia,u+.12*e+ia],[i-.214*e-ia,u+.234*e-ia]]).stream(c),o=l.translate([i-.205*e,u+.212*e]).clipExtent([[i-.214*e+ia,u+.166*e+ia],[i-.115*e-ia,u+.234*e-ia]]).stream(c),f()},u.fitExtent=function(t,e){return lf(u,t,e)},u.fitSize=function(t,e){return cf(u,t,e)},u.fitWidth=function(t,e){return uf(u,t,e)},u.fitHeight=function(t,e){return ff(u,t,e)},u.scale(1070)}function qf(t){return function(e,n){var r=ga(e),o=ga(n),i=t(r*o);return i===1/0?[2,0]:[i*o*xa(e),i*xa(n)]}}function Nf(t){return function(e,n){var r=qa(e*e+n*n),o=t(r),i=xa(o),s=ga(o);return[ma(e*i,r*s),Aa(r&&n*i/r)]}}var Sf=qf((function(t){return qa(2/(1+t))}));function Af(){return yf(Sf).scale(124.75).clipAngle(179.999)}Sf.invert=Nf((function(t){return 2*Aa(t/2)}));var Mf=qf((function(t){return(t=Sa(t))&&t/xa(t)}));function Tf(){return yf(Mf).scale(79.4188).clipAngle(179.999)}function Cf(t,e){return[t,wa(Na((la+e)/2))]}function jf(){return Ef(Cf).scale(961/ua)}function Ef(t){var e,n,r,o=yf(t),i=o.center,s=o.scale,a=o.translate,l=o.clipExtent,c=null;function u(){var i=aa*s(),a=o(sc(o.rotate()).invert([0,0]));return l(null==c?[[a[0]-i,a[1]-i],[a[0]+i,a[1]+i]]:t===Cf?[[Math.max(a[0]-i,c),e],[Math.min(a[0]+i,n),r]]:[[c,Math.max(a[1]-i,e)],[n,Math.min(a[1]+i,r)]])}return o.scale=function(t){return arguments.length?(s(t),u()):s()},o.translate=function(t){return arguments.length?(a(t),u()):a()},o.center=function(t){return arguments.length?(i(t),u()):i()},o.clipExtent=function(t){return arguments.length?(null==t?c=e=n=r=null:(c=+t[0][0],e=+t[0][1],n=+t[1][0],r=+t[1][1]),u()):null==c?null:[[c,e],[n,r]]},u()}function Of(t){return Na((la+t)/2)}function If(t,e){var n=ga(t),r=t===e?xa(t):wa(n/ga(e))/wa(Of(e)/Of(t)),o=n*_a(Of(t),r)/r;if(!r)return Cf;function i(t,e){o>0?e<-la+ia&&(e=-la+ia):e>la-ia&&(e=la-ia);var n=o/_a(Of(e),r);return[n*xa(r*t),o-n*ga(r*t)]}return i.invert=function(t,e){var n=o-e,i=ka(r)*qa(t*t+n*n),s=ma(t,ha(n))*ka(n);return n*r<0&&(s-=aa*ka(t)*ka(n)),[s/r,2*pa(_a(o/i,1/r))-la]},i}function Rf(){return bf(If).scale(109.5).parallels([30,30])}function Pf(t,e){return[t,e]}function Ff(){return yf(Pf).scale(152.63)}function Df(t,e){var n=ga(t),r=t===e?xa(t):(n-ga(e))/(e-t),o=n/r+t;if(ha(r)<ia)return Pf;function i(t,e){var n=o-e,i=r*t;return[n*xa(i),o-n*ga(i)]}return i.invert=function(t,e){var n=o-e,i=ma(t,ha(n))*ka(n);return n*r<0&&(i-=aa*ka(t)*ka(n)),[i/r,o-ka(r)*qa(t*t+n*n)]},i}function Lf(){return bf(Df).scale(131.154).center([0,13.9389])}Mf.invert=Nf((function(t){return t})),Cf.invert=function(t,e){return[t,2*pa(va(e))-la]},Pf.invert=Pf;var $f=1.340264,Zf=-.081106,zf=893e-6,Uf=.003796,Bf=qa(3)/2;function Gf(t,e){var n=Aa(Bf*xa(e)),r=n*n,o=r*r*r;return[t*ga(n)/(Bf*($f+3*Zf*r+o*(7*zf+9*Uf*r))),n*($f+Zf*r+o*(zf+Uf*r))]}function Jf(){return yf(Gf).scale(177.158)}function Wf(t,e){var n=ga(e),r=ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function Hf(){return yf(Wf).scale(144.049).clipAngle(60)}function Vf(){var t,e,n,r,o,i,s,a=1,l=0,c=0,u=1,f=1,d=0,h=null,p=1,m=1,g=of({point:function(t,e){var n=b([t,e]);this.stream.point(n[0],n[1])}}),y=tu;function v(){return p=a*u,m=a*f,i=s=null,b}function b(n){var r=n[0]*p,o=n[1]*m;if(d){var i=o*t-r*e;r=r*t+o*e,o=i}return[r+l,o+c]}return b.invert=function(n){var r=n[0]-l,o=n[1]-c;if(d){var i=o*t+r*e;r=r*t-o*e,o=i}return[r/p,o/m]},b.stream=function(t){return i&&s===t?i:i=g(y(s=t))},b.postclip=function(t){return arguments.length?(y=t,h=n=r=o=null,v()):y},b.clipExtent=function(t){return arguments.length?(y=null==t?(h=n=r=o=null,tu):Tc(h=+t[0][0],n=+t[0][1],r=+t[1][0],o=+t[1][1]),v()):null==h?null:[[h,n],[r,o]]},b.scale=function(t){return arguments.length?(a=+t,v()):a},b.translate=function(t){return arguments.length?(l=+t[0],c=+t[1],v()):[l,c]},b.angle=function(n){return arguments.length?(e=xa(d=n%360*da),t=ga(d),v()):d*fa},b.reflectX=function(t){return arguments.length?(u=t?-1:1,v()):u<0},b.reflectY=function(t){return arguments.length?(f=t?-1:1,v()):f<0},b.fitExtent=function(t,e){return lf(b,t,e)},b.fitSize=function(t,e){return cf(b,t,e)},b.fitWidth=function(t,e){return uf(b,t,e)},b.fitHeight=function(t,e){return ff(b,t,e)},b}function Yf(t,e){var n=e*e,r=n*n;return[t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function Kf(){return yf(Yf).scale(175.295)}function Xf(t,e){return[ga(e)*xa(t),xa(e)]}function Qf(){return yf(Xf).scale(249.5).clipAngle(90+ia)}function td(t,e){var n=ga(e),r=1+ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function ed(){return yf(td).scale(250).clipAngle(142)}function nd(t,e){return[wa(Na((la+e)/2)),-t]}function rd(){var t=Ef(nd),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}function od(t,e){return t.parent===e.parent?1:2}function id(t,e){return t+e.x}function sd(t,e){return Math.max(t,e.y)}function ad(){var t=od,e=1,n=1,r=!1;function o(o){var i,s=0;o.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(id,0)/t.length}(n),e.y=function(t){return 1+t.reduce(sd,0)}(n)):(e.x=i?s+=t(e,i):0,e.y=0,i=e)}));var a=function(t){for(var e;e=t.children;)t=e[0];return t}(o),l=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(o),c=a.x-t(a,l)/2,u=l.x+t(l,a)/2;return o.eachAfter(r?function(t){t.x=(t.x-o.x)*e,t.y=(o.y-t.y)*n}:function(t){t.x=(t.x-c)/(u-c)*e,t.y=(1-(o.y?t.y/o.y:1))*n})}return o.separation=function(e){return arguments.length?(t=e,o):t},o.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],o):r?null:[e,n]},o.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],o):r?[e,n]:null},o}Gf.invert=function(t,e){for(var n,r=e,o=r*r,i=o*o*o,s=0;s<12&&(i=(o=(r-=n=(r*($f+Zf*o+i*(zf+Uf*o))-e)/($f+3*Zf*o+i*(7*zf+9*Uf*o)))*r)*o*o,!(ha(n)<sa));++s);return[Bf*t*($f+3*Zf*o+i*(7*zf+9*Uf*o))/ga(r),Aa(xa(r)/Bf)]},Wf.invert=Nf(pa),Yf.invert=function(t,e){var n,r=e,o=25;do{var i=r*r,s=i*i;r-=n=(r*(1.007226+i*(.015085+s*(.028874*i-.044475-.005916*s)))-e)/(1.007226+i*(.045255+s*(.259866*i-.311325-.005916*11*s)))}while(ha(n)>ia&&--o>0);return[t/(.8707+(i=r*r)*(i*(i*i*i*(.003971-.001529*i)-.013791)-.131979)),r]},Xf.invert=Nf(Aa),td.invert=Nf((function(t){return 2*pa(t)})),nd.invert=function(t,e){return[-e,2*pa(va(t))-la]};var ld=n(5220),cd=n(9466);function ud(){return 0}function fd(t){return function(){return t}}const dd=1664525,hd=1013904223,pd=4294967296;function md(){let t=1;return()=>(t=(dd*t+hd)%pd)/pd}function gd(t){return yd(t,md())}function yd(t,e){for(var n,r,o=0,i=(t=function(t,e){let n,r,o=t.length;for(;o;)r=e()*o--|0,n=t[o],t[o]=t[r],t[r]=n;return t}(Array.from(t),e)).length,s=[];o<i;)n=t[o],r&&wd(r,n)?++o:(r=xd(s=vd(s,n)),o=0);return r}function vd(t,e){var n,r;if(_d(e,t))return[e];for(n=0;n<t.length;++n)if(bd(e,t[n])&&_d(kd(t[n],e),t))return[t[n],e];for(n=0;n<t.length-1;++n)for(r=n+1;r<t.length;++r)if(bd(kd(t[n],t[r]),e)&&bd(kd(t[n],e),t[r])&&bd(kd(t[r],e),t[n])&&_d(qd(t[n],t[r],e),t))return[t[n],t[r],e];throw new Error}function bd(t,e){var n=t.r-e.r,r=e.x-t.x,o=e.y-t.y;return n<0||n*n<r*r+o*o}function wd(t,e){var n=t.r-e.r+1e-9*Math.max(t.r,e.r,1),r=e.x-t.x,o=e.y-t.y;return n>0&&n*n>r*r+o*o}function _d(t,e){for(var n=0;n<e.length;++n)if(!wd(t,e[n]))return!1;return!0}function xd(t){switch(t.length){case 1:return function(t){return{x:t.x,y:t.y,r:t.r}}(t[0]);case 2:return kd(t[0],t[1]);case 3:return qd(t[0],t[1],t[2])}}function kd(t,e){var n=t.x,r=t.y,o=t.r,i=e.x,s=e.y,a=e.r,l=i-n,c=s-r,u=a-o,f=Math.sqrt(l*l+c*c);return{x:(n+i+l/f*u)/2,y:(r+s+c/f*u)/2,r:(f+o+a)/2}}function qd(t,e,n){var r=t.x,o=t.y,i=t.r,s=e.x,a=e.y,l=e.r,c=n.x,u=n.y,f=n.r,d=r-s,h=r-c,p=o-a,m=o-u,g=l-i,y=f-i,v=r*r+o*o-i*i,b=v-s*s-a*a+l*l,w=v-c*c-u*u+f*f,_=h*p-d*m,x=(p*w-m*b)/(2*_)-r,k=(m*g-p*y)/_,q=(h*b-d*w)/(2*_)-o,N=(d*y-h*g)/_,S=k*k+N*N-1,A=2*(i+x*k+q*N),M=x*x+q*q-i*i,T=-(Math.abs(S)>1e-6?(A+Math.sqrt(A*A-4*S*M))/(2*S):M/A);return{x:r+x+k*T,y:o+q+N*T,r:T}}function Nd(t,e,n){var r,o,i,s,a=t.x-e.x,l=t.y-e.y,c=a*a+l*l;c?(o=e.r+n.r,o*=o,s=t.r+n.r,o>(s*=s)?(r=(c+s-o)/(2*c),i=Math.sqrt(Math.max(0,s/c-r*r)),n.x=t.x-r*a-i*l,n.y=t.y-r*l+i*a):(r=(c+o-s)/(2*c),i=Math.sqrt(Math.max(0,o/c-r*r)),n.x=e.x+r*a-i*l,n.y=e.y+r*l+i*a)):(n.x=e.x+n.r,n.y=e.y)}function Sd(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,o=e.y-t.y;return n>0&&n*n>r*r+o*o}function Ad(t){var e=t._,n=t.next._,r=e.r+n.r,o=(e.x*n.r+n.x*e.r)/r,i=(e.y*n.r+n.y*e.r)/r;return o*o+i*i}function Md(t){this._=t,this.next=null,this.previous=null}function Td(t,e){if(!(i=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var n,r,o,i,s,a,l,c,u,f,d;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(r=t[1],n.x=-r.r,r.x=n.r,r.y=0,!(i>2))return n.r+r.r;Nd(r,n,o=t[2]),n=new Md(n),r=new Md(r),o=new Md(o),n.next=o.previous=r,r.next=n.previous=o,o.next=r.previous=n;t:for(l=3;l<i;++l){Nd(n._,r._,o=t[l]),o=new Md(o),c=r.next,u=n.previous,f=r._.r,d=n._.r;do{if(f<=d){if(Sd(c._,o._)){r=c,n.next=r,r.previous=n,--l;continue t}f+=c._.r,c=c.next}else{if(Sd(u._,o._)){(n=u).next=r,r.previous=n,--l;continue t}d+=u._.r,u=u.previous}}while(c!==u.next);for(o.previous=n,o.next=r,n.next=r.previous=r=o,s=Ad(n);(o=o.next)!==r;)(a=Ad(o))<s&&(n=o,s=a);r=n.next}for(n=[r._],o=r;(o=o.next)!==r;)n.push(o._);for(o=yd(n,e),l=0;l<i;++l)(n=t[l]).x-=o.x,n.y-=o.y;return o.r}function Cd(t){return Td(t,md()),t}function jd(t){return Math.sqrt(t.value)}function Ed(){var t=null,e=1,n=1,r=ud;function o(o){const i=md();return o.x=e/2,o.y=n/2,t?o.eachBefore(Od(t)).eachAfter(Id(r,.5,i)).eachBefore(Rd(1)):o.eachBefore(Od(jd)).eachAfter(Id(ud,1,i)).eachAfter(Id(r,o.r/Math.min(e,n),i)).eachBefore(Rd(Math.min(e,n)/(2*o.r))),o}return o.radius=function(e){return arguments.length?(t=(0,cd.j)(e),o):t},o.size=function(t){return arguments.length?(e=+t[0],n=+t[1],o):[e,n]},o.padding=function(t){return arguments.length?(r="function"==typeof t?t:fd(+t),o):r},o}function Od(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0))}}function Id(t,e,n){return function(r){if(o=r.children){var o,i,s,a=o.length,l=t(r)*e||0;if(l)for(i=0;i<a;++i)o[i].r+=l;if(s=Td(o,n),l)for(i=0;i<a;++i)o[i].r-=l;r.r=s+l}}}function Rd(t){return function(e){var n=e.parent;e.r*=t,n&&(e.x=n.x+t*e.x,e.y=n.y+t*e.y)}}function Pd(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Fd(t,e,n,r,o){for(var i,s=t.children,a=-1,l=s.length,c=t.value&&(r-e)/t.value;++a<l;)(i=s[a]).y0=n,i.y1=o,i.x0=e,i.x1=e+=i.value*c}function Dd(){var t=1,e=1,n=0,r=!1;function o(o){var i=o.height+1;return o.x0=o.y0=n,o.x1=t,o.y1=e/i,o.eachBefore(function(t,e){return function(r){r.children&&Fd(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var o=r.x0,i=r.y0,s=r.x1-n,a=r.y1-n;s<o&&(o=s=(o+s)/2),a<i&&(i=a=(i+a)/2),r.x0=o,r.y0=i,r.x1=s,r.y1=a}}(e,i)),r&&o.eachBefore(Pd),o}return o.round=function(t){return arguments.length?(r=!!t,o):r},o.size=function(n){return arguments.length?(t=+n[0],e=+n[1],o):[t,e]},o.padding=function(t){return arguments.length?(n=+t,o):n},o}var Ld=n(4766);function $d(t,e){return t.parent===e.parent?1:2}function Zd(t){var e=t.children;return e?e[0]:t.t}function zd(t){var e=t.children;return e?e[e.length-1]:t.t}function Ud(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function Bd(t,e,n){return t.a.parent===e.parent?t.a:n}function Gd(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function Jd(){var t=$d,e=1,n=1,r=null;function o(o){var l=function(t){for(var e,n,r,o,i,s=new Gd(t,0),a=[s];e=a.pop();)if(r=e._.children)for(e.children=new Array(i=r.length),o=i-1;o>=0;--o)a.push(n=e.children[o]=new Gd(r[o],o)),n.parent=e;return(s.parent=new Gd(null,0)).children=[s],s}(o);if(l.eachAfter(i),l.parent.m=-l.z,l.eachBefore(s),r)o.eachBefore(a);else{var c=o,u=o,f=o;o.eachBefore((function(t){t.x<c.x&&(c=t),t.x>u.x&&(u=t),t.depth>f.depth&&(f=t)}));var d=c===u?1:t(c,u)/2,h=d-c.x,p=e/(u.x+d+h),m=n/(f.depth||1);o.eachBefore((function(t){t.x=(t.x+h)*p,t.y=t.depth*m}))}return o}function i(e){var n=e.children,r=e.parent.children,o=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,o=t.children,i=o.length;--i>=0;)(e=o[i]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var i=(n[0].z+n[n.length-1].z)/2;o?(e.z=o.z+t(e._,o._),e.m=e.z-i):e.z=i}else o&&(e.z=o.z+t(e._,o._));e.parent.A=function(e,n,r){if(n){for(var o,i=e,s=e,a=n,l=i.parent.children[0],c=i.m,u=s.m,f=a.m,d=l.m;a=zd(a),i=Zd(i),a&&i;)l=Zd(l),(s=zd(s)).a=e,(o=a.z+f-i.z-c+t(a._,i._))>0&&(Ud(Bd(a,e,r),e,o),c+=o,u+=o),f+=a.m,c+=i.m,d+=l.m,u+=s.m;a&&!zd(s)&&(s.t=a,s.m+=f-u),i&&!Zd(l)&&(l.t=i,l.m+=c-d,r=e)}return r}(e,o,e.parent.A||r[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function a(t){t.x*=e,t.y=t.depth*n}return o.separation=function(e){return arguments.length?(t=e,o):t},o.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],o):r?null:[e,n]},o.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],o):r?[e,n]:null},o}function Wd(t,e,n,r,o){for(var i,s=t.children,a=-1,l=s.length,c=t.value&&(o-n)/t.value;++a<l;)(i=s[a]).x0=e,i.x1=r,i.y0=n,i.y1=n+=i.value*c}Gd.prototype=Object.create(ld.NB.prototype);var Hd=(1+Math.sqrt(5))/2;function Vd(t,e,n,r,o,i){for(var s,a,l,c,u,f,d,h,p,m,g,y=[],v=e.children,b=0,w=0,_=v.length,x=e.value;b<_;){l=o-n,c=i-r;do{u=v[w++].value}while(!u&&w<_);for(f=d=u,g=u*u*(m=Math.max(c/l,l/c)/(x*t)),p=Math.max(d/g,g/f);w<_;++w){if(u+=a=v[w].value,a<f&&(f=a),a>d&&(d=a),g=u*u*m,(h=Math.max(d/g,g/f))>p){u-=a;break}p=h}y.push(s={value:u,dice:l<c,children:v.slice(b,w)}),s.dice?Fd(s,n,r,o,x?r+=c*u/x:i):Wd(s,n,r,x?n+=l*u/x:o,i),x-=u,b=w}return y}const Yd=function t(e){function n(t,n,r,o,i){Vd(e,t,n,r,o,i)}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Hd);function Kd(){var t=Yd,e=!1,n=1,r=1,o=[0],i=ud,s=ud,a=ud,l=ud,c=ud;function u(t){return t.x0=t.y0=0,t.x1=n,t.y1=r,t.eachBefore(f),o=[0],e&&t.eachBefore(Pd),t}function f(e){var n=o[e.depth],r=e.x0+n,u=e.y0+n,f=e.x1-n,d=e.y1-n;f<r&&(r=f=(r+f)/2),d<u&&(u=d=(u+d)/2),e.x0=r,e.y0=u,e.x1=f,e.y1=d,e.children&&(n=o[e.depth+1]=i(e)/2,r+=c(e)-n,u+=s(e)-n,(f-=a(e)-n)<r&&(r=f=(r+f)/2),(d-=l(e)-n)<u&&(u=d=(u+d)/2),t(e,r,u,f,d))}return u.round=function(t){return arguments.length?(e=!!t,u):e},u.size=function(t){return arguments.length?(n=+t[0],r=+t[1],u):[n,r]},u.tile=function(e){return arguments.length?(t=(0,cd.C)(e),u):t},u.padding=function(t){return arguments.length?u.paddingInner(t).paddingOuter(t):u.paddingInner()},u.paddingInner=function(t){return arguments.length?(i="function"==typeof t?t:fd(+t),u):i},u.paddingOuter=function(t){return arguments.length?u.paddingTop(t).paddingRight(t).paddingBottom(t).paddingLeft(t):u.paddingTop()},u.paddingTop=function(t){return arguments.length?(s="function"==typeof t?t:fd(+t),u):s},u.paddingRight=function(t){return arguments.length?(a="function"==typeof t?t:fd(+t),u):a},u.paddingBottom=function(t){return arguments.length?(l="function"==typeof t?t:fd(+t),u):l},u.paddingLeft=function(t){return arguments.length?(c="function"==typeof t?t:fd(+t),u):c},u}function Xd(t,e,n,r,o){var i,s,a=t.children,l=a.length,c=new Array(l+1);for(c[0]=s=i=0;i<l;++i)c[i+1]=s+=a[i].value;!function t(e,n,r,o,i,s,l){if(e>=n-1){var u=a[e];return u.x0=o,u.y0=i,u.x1=s,void(u.y1=l)}var f=c[e],d=r/2+f,h=e+1,p=n-1;for(;h<p;){var m=h+p>>>1;c[m]<d?h=m+1:p=m}d-c[h-1]<c[h]-d&&e+1<h&&--h;var g=c[h]-f,y=r-g;if(s-o>l-i){var v=r?(o*y+s*g)/r:s;t(e,h,g,o,i,v,l),t(h,n,y,v,i,s,l)}else{var b=r?(i*y+l*g)/r:l;t(e,h,g,o,i,s,b),t(h,n,y,o,b,s,l)}}(0,l,t.value,e,n,r,o)}function Qd(t,e,n,r,o){(1&t.depth?Wd:Fd)(t,e,n,r,o)}const th=function t(e){function n(t,n,r,o,i){if((s=t._squarify)&&s.ratio===e)for(var s,a,l,c,u,f=-1,d=s.length,h=t.value;++f<d;){for(l=(a=s[f]).children,c=a.value=0,u=l.length;c<u;++c)a.value+=l[c].value;a.dice?Fd(a,n,r,o,h?r+=(i-r)*a.value/h:i):Wd(a,n,r,h?n+=(o-n)*a.value/h:o,i),h-=a.value}else t._squarify=s=Vd(e,t,n,r,o,i),s.ratio=e}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Hd);var eh=n(4321),nh=n(5409),rh=n(7855),oh=n(6261);function ih(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}var sh=n(8190);function ah(t,e){var n=(0,sh.wx)(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}var lh=n(5003),ch=n(8765),uh=n(5250);function fh(t){return((t=Math.exp(t))+1/t)/2}const dh=function t(e,n,r){function o(t,o){var i,s,a=t[0],l=t[1],c=t[2],u=o[0],f=o[1],d=o[2],h=u-a,p=f-l,m=h*h+p*p;if(m<1e-12)s=Math.log(d/c)/e,i=function(t){return[a+t*h,l+t*p,c*Math.exp(e*t*s)]};else{var g=Math.sqrt(m),y=(d*d-c*c+r*m)/(2*c*n*g),v=(d*d-c*c-r*m)/(2*d*n*g),b=Math.log(Math.sqrt(y*y+1)-y),w=Math.log(Math.sqrt(v*v+1)-v);s=(w-b)/e,i=function(t){var r=t*s,o=fh(b),i=c/(n*g)*(o*function(t){return((t=Math.exp(2*t))-1)/(t+1)}(e*r+b)-function(t){return((t=Math.exp(t))-1/t)/2}(b));return[a+i*h,l+i*p,c*o/fh(e*r+b)]}}return i.duration=1e3*s*e/Math.SQRT2,i}return o.rho=function(e){var n=Math.max(.001,+e),r=n*n;return t(n,r,r*r)},o}(Math.SQRT2,2,4);function hh(t){return function(e,n){var r=t((e=(0,$e.Ym)(e)).h,(n=(0,$e.Ym)(n)).h),o=(0,sh.ZP)(e.s,n.s),i=(0,sh.ZP)(e.l,n.l),s=(0,sh.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.s=o(t),e.l=i(t),e.opacity=s(t),e+""}}}const ph=hh(sh.wx);var mh=hh(sh.ZP);function gh(t,e){var n=(0,sh.ZP)((t=Fr(t)).l,(e=Fr(e)).l),r=(0,sh.ZP)(t.a,e.a),o=(0,sh.ZP)(t.b,e.b),i=(0,sh.ZP)(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=r(e),t.b=o(e),t.opacity=i(e),t+""}}function yh(t){return function(e,n){var r=t((e=Gr(e)).h,(n=Gr(n)).h),o=(0,sh.ZP)(e.c,n.c),i=(0,sh.ZP)(e.l,n.l),s=(0,sh.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=o(t),e.l=i(t),e.opacity=s(t),e+""}}}const vh=yh(sh.wx);var bh=yh(sh.ZP);function wh(t){return function e(n){function r(e,r){var o=t((e=no(e)).h,(r=no(r)).h),i=(0,sh.ZP)(e.s,r.s),s=(0,sh.ZP)(e.l,r.l),a=(0,sh.ZP)(e.opacity,r.opacity);return function(t){return e.h=o(t),e.s=i(t),e.l=s(Math.pow(t,n)),e.opacity=a(t),e+""}}return n=+n,r.gamma=e,r}(1)}const _h=wh(sh.wx);var xh=wh(sh.ZP),kh=n(9444);function qh(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t(r/(e-1));return n}function Nh(t){for(var e,n=-1,r=t.length,o=t[r-1],i=0;++n<r;)e=o,o=t[n],i+=e[1]*o[0]-e[0]*o[1];return i/2}function Sh(t){for(var e,n,r=-1,o=t.length,i=0,s=0,a=t[o-1],l=0;++r<o;)e=a,a=t[r],l+=n=e[0]*a[1]-a[0]*e[1],i+=(e[0]+a[0])*n,s+=(e[1]+a[1])*n;return[i/(l*=3),s/l]}function Ah(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function Mh(t,e){return t[0]-e[0]||t[1]-e[1]}function Th(t){const e=t.length,n=[0,1];let r,o=2;for(r=2;r<e;++r){for(;o>1&&Ah(t[n[o-2]],t[n[o-1]],t[r])<=0;)--o;n[o++]=r}return n.slice(0,o)}function Ch(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),o=new Array(n);for(e=0;e<n;++e)r[e]=[+t[e][0],+t[e][1],e];for(r.sort(Mh),e=0;e<n;++e)o[e]=[r[e][0],-r[e][1]];var i=Th(r),s=Th(o),a=s[0]===i[0],l=s[s.length-1]===i[i.length-1],c=[];for(e=i.length-1;e>=0;--e)c.push(t[r[i[e]][2]]);for(e=+a;e<s.length-l;++e)c.push(t[r[s[e]][2]]);return c}function jh(t,e){for(var n,r,o=t.length,i=t[o-1],s=e[0],a=e[1],l=i[0],c=i[1],u=!1,f=0;f<o;++f)n=(i=t[f])[0],(r=i[1])>a!=c>a&&s<(l-n)*(a-r)/(c-r)+n&&(u=!u),l=n,c=r;return u}function Eh(t){for(var e,n,r=-1,o=t.length,i=t[o-1],s=i[0],a=i[1],l=0;++r<o;)e=s,n=a,e-=s=(i=t[r])[0],n-=a=i[1],l+=Math.hypot(e,n);return l}const Oh=Math.random,Ih=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,1===arguments.length?(n=t,t=0):n-=t,function(){return e()*n+t}}return n.source=t,n}(Oh),Rh=function t(e){function n(t,n){return arguments.length<2&&(n=t,t=0),t=Math.floor(t),n=Math.floor(n)-t,function(){return Math.floor(e()*n+t)}}return n.source=t,n}(Oh),Ph=function t(e){function n(t,n){var r,o;return t=null==t?0:+t,n=null==n?1:+n,function(){var i;if(null!=r)i=r,r=null;else do{r=2*e()-1,i=2*e()-1,o=r*r+i*i}while(!o||o>1);return t+n*i*Math.sqrt(-2*Math.log(o)/o)}}return n.source=t,n}(Oh),Fh=function t(e){var n=Ph.source(e);function r(){var t=n.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Oh),Dh=function t(e){function n(t){return(t=+t)<=0?()=>0:function(){for(var n=0,r=t;r>1;--r)n+=e();return n+r*e()}}return n.source=t,n}(Oh),Lh=function t(e){var n=Dh.source(e);function r(t){if(0==(t=+t))return e;var r=n(t);return function(){return r()/t}}return r.source=t,r}(Oh),$h=function t(e){function n(t){return function(){return-Math.log1p(-e())/t}}return n.source=t,n}(Oh),Zh=function t(e){function n(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-e(),t)}}return n.source=t,n}(Oh),zh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(e()+t)}}return n.source=t,n}(Oh),Uh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-e())/t)})}return n.source=t,n}(Oh),Bh=function t(e){var n=Ph.source(e)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-e())*r;var o=(t<1?t+1:t)-1/3,i=1/(3*Math.sqrt(o)),s=t<1?()=>Math.pow(e(),1/t):()=>1;return function(){do{do{var t=n(),a=1+i*t}while(a<=0);a*=a*a;var l=1-e()}while(l>=1-.0331*t*t*t*t&&Math.log(l)>=.5*t*t+o*(1-a+Math.log(a)));return o*a*s()*r}}return r.source=t,r}(Oh),Gh=function t(e){var n=Bh.source(e);function r(t,e){var r=n(t),o=n(e);return function(){var t=r();return 0===t?0:t/(t+o())}}return r.source=t,r}(Oh),Jh=function t(e){var n=Uh.source(e),r=Gh.source(e);function o(t,e){return t=+t,(e=+e)>=1?()=>t:e<=0?()=>0:function(){for(var o=0,i=t,s=e;i*s>16&&i*(1-s)>16;){var a=Math.floor((i+1)*s),l=r(a,i-a+1)();l<=s?(o+=a,i-=a,s=(s-l)/(1-l)):(i=a-1,s/=l)}for(var c=s<.5,u=n(c?s:1-s),f=u(),d=0;f<=i;++d)f+=u();return o+(c?d:i-d)}}return o.source=t,o}(Oh),Wh=function t(e){function n(t,n,r){var o;return 0==(t=+t)?o=t=>-Math.log(t):(t=1/t,o=e=>Math.pow(e,t)),n=null==n?0:+n,r=null==r?1:+r,function(){return n+r*o(-Math.log1p(-e()))}}return n.source=t,n}(Oh),Hh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){return t+n*Math.tan(Math.PI*e())}}return n.source=t,n}(Oh),Vh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){var r=e();return t+n*Math.log(r/(1-r))}}return n.source=t,n}(Oh),Yh=function t(e){var n=Bh.source(e),r=Jh.source(e);function o(t){return function(){for(var o=0,i=t;i>16;){var s=Math.floor(.875*i),a=n(s)();if(a>i)return o+r(s-1,i/a)();o+=s,i-=a}for(var l=-Math.log1p(-e()),c=0;l<=i;++c)l-=Math.log1p(-e());return o+c}}return o.source=t,o}(Oh),Kh=1664525,Xh=1013904223,Qh=1/4294967296;function tp(t=Math.random()){let e=0|(0<=t&&t<1?t/Qh:Math.abs(t));return()=>(e=Kh*e+Xh|0,Qh*(e>>>0))}var ep=n(4635),np=n(7763),rp=n(4090);const op=(0,rp.Z)("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),ip=(0,rp.Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),sp=(0,rp.Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),ap=(0,rp.Z)("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),lp=(0,rp.Z)("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),cp=(0,rp.Z)("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),up=(0,rp.Z)("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),fp=(0,rp.Z)("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),dp=(0,rp.Z)("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),hp=t=>(0,Ze.hD)(t[t.length-1]);var pp=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(rp.Z);const mp=hp(pp);var gp=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(rp.Z);const yp=hp(gp);var vp=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(rp.Z);const bp=hp(vp);var wp=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(rp.Z);const _p=hp(wp);var xp=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(rp.Z);const kp=hp(xp);var qp=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(rp.Z);const Np=hp(qp);var Sp=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(rp.Z);const Ap=hp(Sp);var Mp=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(rp.Z);const Tp=hp(Mp);var Cp=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(rp.Z);const jp=hp(Cp);var Ep=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(rp.Z);const Op=hp(Ep);var Ip=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(rp.Z);const Rp=hp(Ip);var Pp=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(rp.Z);const Fp=hp(Pp);var Dp=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(rp.Z);const Lp=hp(Dp);var $p=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(rp.Z);const Zp=hp($p);var zp=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(rp.Z);const Up=hp(zp);var Bp=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(rp.Z);const Gp=hp(Bp);var Jp=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(rp.Z);const Wp=hp(Jp);var Hp=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(rp.Z);const Vp=hp(Hp);var Yp=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(rp.Z);const Kp=hp(Yp);var Xp=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(rp.Z);const Qp=hp(Xp);var tm=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(rp.Z);const em=hp(tm);var nm=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(rp.Z);const rm=hp(nm);var om=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(rp.Z);const im=hp(om);var sm=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(rp.Z);const am=hp(sm);var lm=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(rp.Z);const cm=hp(lm);var um=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(rp.Z);const fm=hp(um);var dm=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(rp.Z);const hm=hp(dm);function pm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}const mm=xh(no(300,.5,0),no(-240,.5,1));var gm=xh(no(-100,.75,.35),no(80,1.5,.8)),ym=xh(no(260,.75,.35),no(80,1.5,.8)),vm=no();function bm(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return vm.h=360*t-100,vm.s=1.5-1.5*e,vm.l=.8-.9*e,vm+""}var wm=(0,$e.B8)(),_m=Math.PI/3,xm=2*Math.PI/3;function km(t){var e;return t=(.5-t)*Math.PI,wm.r=255*(e=Math.sin(t))*e,wm.g=255*(e=Math.sin(t+_m))*e,wm.b=255*(e=Math.sin(t+xm))*e,wm+""}function qm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}function Nm(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const Sm=Nm((0,rp.Z)("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Am=Nm((0,rp.Z)("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Mm=Nm((0,rp.Z)("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Tm=Nm((0,rp.Z)("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Cm(t){return Lt(Nt(t).call(document.documentElement))}var jm=0;function Em(){return new Om}function Om(){this._="@"+(++jm).toString(36)}function Im(t,e){return t.target&&(t=Wt(t),void 0===e&&(e=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>Ht(t,e)))}function Rm(t){return"string"==typeof t?new Pt([document.querySelectorAll(t)],[document.documentElement]):new Pt([M(t)],Rt)}function Pm(t){return function(){return t}}Om.prototype=Em.prototype={constructor:Om,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}};const Fm=Math.abs,Dm=Math.atan2,Lm=Math.cos,$m=Math.max,Zm=Math.min,zm=Math.sin,Um=Math.sqrt,Bm=1e-12,Gm=Math.PI,Jm=Gm/2,Wm=2*Gm;function Hm(t){return t>=1?Jm:t<=-1?-Jm:Math.asin(t)}function Vm(t){return t.innerRadius}function Ym(t){return t.outerRadius}function Km(t){return t.startAngle}function Xm(t){return t.endAngle}function Qm(t){return t&&t.padAngle}function tg(t,e,n,r,o,i,s){var a=t-n,l=e-r,c=(s?i:-i)/Um(a*a+l*l),u=c*l,f=-c*a,d=t+u,h=e+f,p=n+u,m=r+f,g=(d+p)/2,y=(h+m)/2,v=p-d,b=m-h,w=v*v+b*b,_=o-i,x=d*m-p*h,k=(b<0?-1:1)*Um($m(0,_*_*w-x*x)),q=(x*b-v*k)/w,N=(-x*v-b*k)/w,S=(x*b+v*k)/w,A=(-x*v+b*k)/w,M=q-g,T=N-y,C=S-g,j=A-y;return M*M+T*T>C*C+j*j&&(q=S,N=A),{cx:q,cy:N,x01:-u,y01:-f,x11:q*(o/_-1),y11:N*(o/_-1)}}function eg(){var t=Vm,e=Ym,n=Pm(0),r=null,o=Km,i=Xm,s=Qm,a=null;function l(){var l,c,u=+t.apply(this,arguments),f=+e.apply(this,arguments),d=o.apply(this,arguments)-Jm,h=i.apply(this,arguments)-Jm,p=Fm(h-d),m=h>d;if(a||(a=l=dr()),f<u&&(c=f,f=u,u=c),f>Bm)if(p>Wm-Bm)a.moveTo(f*Lm(d),f*zm(d)),a.arc(0,0,f,d,h,!m),u>Bm&&(a.moveTo(u*Lm(h),u*zm(h)),a.arc(0,0,u,h,d,m));else{var g,y,v=d,b=h,w=d,_=h,x=p,k=p,q=s.apply(this,arguments)/2,N=q>Bm&&(r?+r.apply(this,arguments):Um(u*u+f*f)),S=Zm(Fm(f-u)/2,+n.apply(this,arguments)),A=S,M=S;if(N>Bm){var T=Hm(N/u*zm(q)),C=Hm(N/f*zm(q));(x-=2*T)>Bm?(w+=T*=m?1:-1,_-=T):(x=0,w=_=(d+h)/2),(k-=2*C)>Bm?(v+=C*=m?1:-1,b-=C):(k=0,v=b=(d+h)/2)}var j=f*Lm(v),E=f*zm(v),O=u*Lm(_),I=u*zm(_);if(S>Bm){var R,P=f*Lm(b),F=f*zm(b),D=u*Lm(w),L=u*zm(w);if(p<Gm&&(R=function(t,e,n,r,o,i,s,a){var l=n-t,c=r-e,u=s-o,f=a-i,d=f*l-u*c;if(!(d*d<Bm))return[t+(d=(u*(e-i)-f*(t-o))/d)*l,e+d*c]}(j,E,D,L,P,F,O,I))){var $=j-R[0],Z=E-R[1],z=P-R[0],U=F-R[1],B=1/zm(function(t){return t>1?0:t<-1?Gm:Math.acos(t)}(($*z+Z*U)/(Um($*$+Z*Z)*Um(z*z+U*U)))/2),G=Um(R[0]*R[0]+R[1]*R[1]);A=Zm(S,(u-G)/(B-1)),M=Zm(S,(f-G)/(B+1))}}k>Bm?M>Bm?(g=tg(D,L,j,E,f,M,m),y=tg(P,F,O,I,f,M,m),a.moveTo(g.cx+g.x01,g.cy+g.y01),M<S?a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,f,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),!m),a.arc(y.cx,y.cy,M,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):(a.moveTo(j,E),a.arc(0,0,f,v,b,!m)):a.moveTo(j,E),u>Bm&&x>Bm?A>Bm?(g=tg(O,I,P,F,u,-A,m),y=tg(j,E,D,L,u,-A,m),a.lineTo(g.cx+g.x01,g.cy+g.y01),A<S?a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,u,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),m),a.arc(y.cx,y.cy,A,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):a.arc(0,0,u,_,w,m):a.lineTo(O,I)}else a.moveTo(0,0);if(a.closePath(),l)return a=null,l+""||null}return l.centroid=function(){var n=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,r=(+o.apply(this,arguments)+ +i.apply(this,arguments))/2-Gm/2;return[Lm(r)*n,zm(r)*n]},l.innerRadius=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),l):t},l.outerRadius=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),l):e},l.cornerRadius=function(t){return arguments.length?(n="function"==typeof t?t:Pm(+t),l):n},l.padRadius=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Pm(+t),l):r},l.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),l):o},l.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:Pm(+t),l):i},l.padAngle=function(t){return arguments.length?(s="function"==typeof t?t:Pm(+t),l):s},l.context=function(t){return arguments.length?(a=null==t?null:t,l):a},l}var ng=Array.prototype.slice;function rg(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function og(t){this._context=t}function ig(t){return new og(t)}function sg(t){return t[0]}function ag(t){return t[1]}function lg(t,e){var n=Pm(!0),r=null,o=ig,i=null;function s(s){var a,l,c,u=(s=rg(s)).length,f=!1;for(null==r&&(i=o(c=dr())),a=0;a<=u;++a)!(a<u&&n(l=s[a],a,s))===f&&((f=!f)?i.lineStart():i.lineEnd()),f&&i.point(+t(l,a,s),+e(l,a,s));if(c)return i=null,c+""||null}return t="function"==typeof t?t:void 0===t?sg:Pm(t),e="function"==typeof e?e:void 0===e?ag:Pm(e),s.x=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),s):t},s.y=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),s):e},s.defined=function(t){return arguments.length?(n="function"==typeof t?t:Pm(!!t),s):n},s.curve=function(t){return arguments.length?(o=t,null!=r&&(i=o(r)),s):o},s.context=function(t){return arguments.length?(null==t?r=i=null:i=o(r=t),s):r},s}function cg(t,e,n){var r=null,o=Pm(!0),i=null,s=ig,a=null;function l(l){var c,u,f,d,h,p=(l=rg(l)).length,m=!1,g=new Array(p),y=new Array(p);for(null==i&&(a=s(h=dr())),c=0;c<=p;++c){if(!(c<p&&o(d=l[c],c,l))===m)if(m=!m)u=c,a.areaStart(),a.lineStart();else{for(a.lineEnd(),a.lineStart(),f=c-1;f>=u;--f)a.point(g[f],y[f]);a.lineEnd(),a.areaEnd()}m&&(g[c]=+t(d,c,l),y[c]=+e(d,c,l),a.point(r?+r(d,c,l):g[c],n?+n(d,c,l):y[c]))}if(h)return a=null,h+""||null}function c(){return lg().defined(o).curve(s).context(i)}return t="function"==typeof t?t:void 0===t?sg:Pm(+t),e="function"==typeof e?e:Pm(void 0===e?0:+e),n="function"==typeof n?n:void 0===n?ag:Pm(+n),l.x=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),r=null,l):t},l.x0=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),l):t},l.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Pm(+t),l):r},l.y=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),n=null,l):e},l.y0=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),l):e},l.y1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:Pm(+t),l):n},l.lineX0=l.lineY0=function(){return c().x(t).y(e)},l.lineY1=function(){return c().x(t).y(n)},l.lineX1=function(){return c().x(r).y(e)},l.defined=function(t){return arguments.length?(o="function"==typeof t?t:Pm(!!t),l):o},l.curve=function(t){return arguments.length?(s=t,null!=i&&(a=s(i)),l):s},l.context=function(t){return arguments.length?(null==t?i=a=null:a=s(i=t),l):i},l}function ug(t,e){return e<t?-1:e>t?1:e>=t?0:NaN}function fg(t){return t}function dg(){var t=fg,e=ug,n=null,r=Pm(0),o=Pm(Wm),i=Pm(0);function s(s){var a,l,c,u,f,d=(s=rg(s)).length,h=0,p=new Array(d),m=new Array(d),g=+r.apply(this,arguments),y=Math.min(Wm,Math.max(-Wm,o.apply(this,arguments)-g)),v=Math.min(Math.abs(y)/d,i.apply(this,arguments)),b=v*(y<0?-1:1);for(a=0;a<d;++a)(f=m[p[a]=a]=+t(s[a],a,s))>0&&(h+=f);for(null!=e?p.sort((function(t,n){return e(m[t],m[n])})):null!=n&&p.sort((function(t,e){return n(s[t],s[e])})),a=0,c=h?(y-d*b)/h:0;a<d;++a,g=u)l=p[a],u=g+((f=m[l])>0?f*c:0)+b,m[l]={data:s[l],index:a,value:f,startAngle:g,endAngle:u,padAngle:v};return m}return s.value=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),s):t},s.sortValues=function(t){return arguments.length?(e=t,n=null,s):e},s.sort=function(t){return arguments.length?(n=t,e=null,s):n},s.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),s):r},s.endAngle=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),s):o},s.padAngle=function(t){return arguments.length?(i="function"==typeof t?t:Pm(+t),s):i},s}og.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}};var hg=mg(ig);function pg(t){this._curve=t}function mg(t){function e(e){return new pg(t(e))}return e._curve=t,e}function gg(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function yg(){return gg(lg().curve(hg))}function vg(){var t=cg().curve(hg),e=t.curve,n=t.lineX0,r=t.lineX1,o=t.lineY0,i=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return gg(n())},delete t.lineX0,t.lineEndAngle=function(){return gg(r())},delete t.lineX1,t.lineInnerRadius=function(){return gg(o())},delete t.lineY0,t.lineOuterRadius=function(){return gg(i())},delete t.lineY1,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function bg(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}pg.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}};class wg{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e)}this._x0=t,this._y0=e}}class _g{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,e){if(t=+t,e=+e,0==this._point++)this._x0=t,this._y0=e;else{const n=bg(this._x0,this._y0),r=bg(this._x0,this._y0=(this._y0+e)/2),o=bg(t,this._y0),i=bg(t,e);this._context.moveTo(...n),this._context.bezierCurveTo(...r,...o,...i)}}}function xg(t){return new wg(t,!0)}function kg(t){return new wg(t,!1)}function qg(t){return new _g(t)}function Ng(t){return t.source}function Sg(t){return t.target}function Ag(t){let e=Ng,n=Sg,r=sg,o=ag,i=null,s=null;function a(){let a;const l=ng.call(arguments),c=e.apply(this,l),u=n.apply(this,l);if(null==i&&(s=t(a=dr())),s.lineStart(),l[0]=c,s.point(+r.apply(this,l),+o.apply(this,l)),l[0]=u,s.point(+r.apply(this,l),+o.apply(this,l)),s.lineEnd(),a)return s=null,a+""||null}return a.source=function(t){return arguments.length?(e=t,a):e},a.target=function(t){return arguments.length?(n=t,a):n},a.x=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),a):r},a.y=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),a):o},a.context=function(e){return arguments.length?(null==e?i=s=null:s=t(i=e),a):i},a}function Mg(){return Ag(xg)}function Tg(){return Ag(kg)}function Cg(){const t=Ag(qg);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}const jg=Um(3),Eg={draw(t,e){const n=.59436*Um(e+Zm(e/28,.75)),r=n/2,o=r*jg;t.moveTo(0,n),t.lineTo(0,-n),t.moveTo(-o,-r),t.lineTo(o,r),t.moveTo(-o,r),t.lineTo(o,-r)}},Og={draw(t,e){const n=Um(e/Gm);t.moveTo(n,0),t.arc(0,0,n,0,Wm)}},Ig={draw(t,e){const n=Um(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},Rg=Um(1/3),Pg=2*Rg,Fg={draw(t,e){const n=Um(e/Pg),r=n*Rg;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},Dg={draw(t,e){const n=.62625*Um(e);t.moveTo(0,-n),t.lineTo(n,0),t.lineTo(0,n),t.lineTo(-n,0),t.closePath()}},Lg={draw(t,e){const n=.87559*Um(e-Zm(e/7,2));t.moveTo(-n,0),t.lineTo(n,0),t.moveTo(0,n),t.lineTo(0,-n)}},$g={draw(t,e){const n=Um(e),r=-n/2;t.rect(r,r,n,n)}},Zg={draw(t,e){const n=.4431*Um(e);t.moveTo(n,n),t.lineTo(n,-n),t.lineTo(-n,-n),t.lineTo(-n,n),t.closePath()}},zg=zm(Gm/10)/zm(7*Gm/10),Ug=zm(Wm/10)*zg,Bg=-Lm(Wm/10)*zg,Gg={draw(t,e){const n=Um(.8908130915292852*e),r=Ug*n,o=Bg*n;t.moveTo(0,-n),t.lineTo(r,o);for(let e=1;e<5;++e){const i=Wm*e/5,s=Lm(i),a=zm(i);t.lineTo(a*n,-s*n),t.lineTo(s*r-a*o,a*r+s*o)}t.closePath()}},Jg=Um(3),Wg={draw(t,e){const n=-Um(e/(3*Jg));t.moveTo(0,2*n),t.lineTo(-Jg*n,-n),t.lineTo(Jg*n,-n),t.closePath()}},Hg=Um(3),Vg={draw(t,e){const n=.6824*Um(e),r=n/2,o=n*Hg/2;t.moveTo(0,-n),t.lineTo(o,r),t.lineTo(-o,r),t.closePath()}},Yg=-.5,Kg=Um(3)/2,Xg=1/Um(12),Qg=3*(Xg/2+1),ty={draw(t,e){const n=Um(e/Qg),r=n/2,o=n*Xg,i=r,s=n*Xg+n,a=-i,l=s;t.moveTo(r,o),t.lineTo(i,s),t.lineTo(a,l),t.lineTo(Yg*r-Kg*o,Kg*r+Yg*o),t.lineTo(Yg*i-Kg*s,Kg*i+Yg*s),t.lineTo(Yg*a-Kg*l,Kg*a+Yg*l),t.lineTo(Yg*r+Kg*o,Yg*o-Kg*r),t.lineTo(Yg*i+Kg*s,Yg*s-Kg*i),t.lineTo(Yg*a+Kg*l,Yg*l-Kg*a),t.closePath()}},ey={draw(t,e){const n=.6189*Um(e-Zm(e/6,1.7));t.moveTo(-n,-n),t.lineTo(n,n),t.moveTo(-n,n),t.lineTo(n,-n)}},ny=[Og,Ig,Fg,$g,Gg,Wg,ty],ry=[Og,Lg,ey,Vg,Eg,Zg,Dg];function oy(t,e){let n=null;function r(){let r;if(n||(n=r=dr()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),r)return n=null,r+""||null}return t="function"==typeof t?t:Pm(t||Og),e="function"==typeof e?e:Pm(void 0===e?64:+e),r.type=function(e){return arguments.length?(t="function"==typeof e?e:Pm(e),r):t},r.size=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),r):e},r.context=function(t){return arguments.length?(n=null==t?null:t,r):n},r}function iy(){}function sy(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function ay(t){this._context=t}function ly(t){return new ay(t)}function cy(t){this._context=t}function uy(t){return new cy(t)}function fy(t){this._context=t}function dy(t){return new fy(t)}function hy(t,e){this._basis=new ay(t),this._beta=e}ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:sy(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},cy.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},fy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},hy.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,o=t[0],i=e[0],s=t[n]-o,a=e[n]-i,l=-1;++l<=n;)r=l/n,this._basis.point(this._beta*t[l]+(1-this._beta)*(o+r*s),this._beta*e[l]+(1-this._beta)*(i+r*a));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const py=function t(e){function n(t){return 1===e?new ay(t):new hy(t,e)}return n.beta=function(e){return t(+e)},n}(.85);function my(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function gy(t,e){this._context=t,this._k=(1-e)/6}gy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:my(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const yy=function t(e){function n(t){return new gy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function vy(t,e){this._context=t,this._k=(1-e)/6}vy.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const by=function t(e){function n(t){return new vy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function wy(t,e){this._context=t,this._k=(1-e)/6}wy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const _y=function t(e){function n(t){return new wy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function xy(t,e,n){var r=t._x1,o=t._y1,i=t._x2,s=t._y2;if(t._l01_a>Bm){var a=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,l=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*a-t._x0*t._l12_2a+t._x2*t._l01_2a)/l,o=(o*a-t._y0*t._l12_2a+t._y2*t._l01_2a)/l}if(t._l23_a>Bm){var c=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,u=3*t._l23_a*(t._l23_a+t._l12_a);i=(i*c+t._x1*t._l23_2a-e*t._l12_2a)/u,s=(s*c+t._y1*t._l23_2a-n*t._l12_2a)/u}t._context.bezierCurveTo(r,o,i,s,t._x2,t._y2)}function ky(t,e){this._context=t,this._alpha=e}ky.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const qy=function t(e){function n(t){return e?new ky(t,e):new gy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ny(t,e){this._context=t,this._alpha=e}Ny.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const Sy=function t(e){function n(t){return e?new Ny(t,e):new vy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ay(t,e){this._context=t,this._alpha=e}Ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const My=function t(e){function n(t){return e?new Ay(t,e):new wy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ty(t){this._context=t}function Cy(t){return new Ty(t)}function jy(t){return t<0?-1:1}function Ey(t,e,n){var r=t._x1-t._x0,o=e-t._x1,i=(t._y1-t._y0)/(r||o<0&&-0),s=(n-t._y1)/(o||r<0&&-0),a=(i*o+s*r)/(r+o);return(jy(i)+jy(s))*Math.min(Math.abs(i),Math.abs(s),.5*Math.abs(a))||0}function Oy(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function Iy(t,e,n){var r=t._x0,o=t._y0,i=t._x1,s=t._y1,a=(i-r)/3;t._context.bezierCurveTo(r+a,o+a*e,i-a,s-a*n,i,s)}function Ry(t){this._context=t}function Py(t){this._context=new Fy(t)}function Fy(t){this._context=t}function Dy(t){return new Ry(t)}function Ly(t){return new Py(t)}function $y(t){this._context=t}function Zy(t){var e,n,r=t.length-1,o=new Array(r),i=new Array(r),s=new Array(r);for(o[0]=0,i[0]=2,s[0]=t[0]+2*t[1],e=1;e<r-1;++e)o[e]=1,i[e]=4,s[e]=4*t[e]+2*t[e+1];for(o[r-1]=2,i[r-1]=7,s[r-1]=8*t[r-1]+t[r],e=1;e<r;++e)n=o[e]/i[e-1],i[e]-=n,s[e]-=n*s[e-1];for(o[r-1]=s[r-1]/i[r-1],e=r-2;e>=0;--e)o[e]=(s[e]-o[e+1])/i[e];for(i[r-1]=(t[r]+o[r-1])/2,e=0;e<r-1;++e)i[e]=2*t[e+1]-o[e+1];return[o,i]}function zy(t){return new $y(t)}function Uy(t,e){this._context=t,this._t=e}function By(t){return new Uy(t,.5)}function Gy(t){return new Uy(t,0)}function Jy(t){return new Uy(t,1)}function Wy(t,e){if((o=t.length)>1)for(var n,r,o,i=1,s=t[e[0]],a=s.length;i<o;++i)for(r=s,s=t[e[i]],n=0;n<a;++n)s[n][1]+=s[n][0]=isNaN(r[n][1])?r[n][0]:r[n][1]}function Hy(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function Vy(t,e){return t[e]}function Yy(t){const e=[];return e.key=t,e}function Ky(){var t=Pm([]),e=Hy,n=Wy,r=Vy;function o(o){var i,s,a=Array.from(t.apply(this,arguments),Yy),l=a.length,c=-1;for(const t of o)for(i=0,++c;i<l;++i)(a[i][c]=[0,+r(t,a[i].key,c,o)]).data=t;for(i=0,s=rg(e(a));i<l;++i)a[s[i]].index=i;return n(a,s),a}return o.keys=function(e){return arguments.length?(t="function"==typeof e?e:Pm(Array.from(e)),o):t},o.value=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),o):r},o.order=function(t){return arguments.length?(e=null==t?Hy:"function"==typeof t?t:Pm(Array.from(t)),o):e},o.offset=function(t){return arguments.length?(n=null==t?Wy:t,o):n},o}function Xy(t,e){if((r=t.length)>0){for(var n,r,o,i=0,s=t[0].length;i<s;++i){for(o=n=0;n<r;++n)o+=t[n][i][1]||0;if(o)for(n=0;n<r;++n)t[n][i][1]/=o}Wy(t,e)}}function Qy(t,e){if((a=t.length)>0)for(var n,r,o,i,s,a,l=0,c=t[e[0]].length;l<c;++l)for(i=s=0,n=0;n<a;++n)(o=(r=t[e[n]][l])[1]-r[0])>0?(r[0]=i,r[1]=i+=o):o<0?(r[1]=s,r[0]=s+=o):(r[0]=0,r[1]=o)}function tv(t,e){if((n=t.length)>0){for(var n,r=0,o=t[e[0]],i=o.length;r<i;++r){for(var s=0,a=0;s<n;++s)a+=t[s][r][1]||0;o[r][1]+=o[r][0]=-a/2}Wy(t,e)}}function ev(t,e){if((o=t.length)>0&&(r=(n=t[e[0]]).length)>0){for(var n,r,o,i=0,s=1;s<r;++s){for(var a=0,l=0,c=0;a<o;++a){for(var u=t[e[a]],f=u[s][1]||0,d=(f-(u[s-1][1]||0))/2,h=0;h<a;++h){var p=t[e[h]];d+=(p[s][1]||0)-(p[s-1][1]||0)}l+=f,c+=d*f}n[s-1][1]+=n[s-1][0]=i,l&&(i-=c/l)}n[s-1][1]+=n[s-1][0]=i,Wy(t,e)}}function nv(t){var e=t.map(rv);return Hy(t).sort((function(t,n){return e[t]-e[n]}))}function rv(t){for(var e,n=-1,r=0,o=t.length,i=-1/0;++n<o;)(e=+t[n][1])>i&&(i=e,r=n);return r}function ov(t){var e=t.map(iv);return Hy(t).sort((function(t,n){return e[t]-e[n]}))}function iv(t){for(var e,n=0,r=-1,o=t.length;++r<o;)(e=+t[r][1])&&(n+=e);return n}function sv(t){return ov(t).reverse()}function av(t){var e,n,r=t.length,o=t.map(iv),i=nv(t),s=0,a=0,l=[],c=[];for(e=0;e<r;++e)n=i[e],s<a?(s+=o[n],l.push(n)):(a+=o[n],c.push(n));return c.reverse().concat(l)}function lv(t){return Hy(t).reverse()}Ty.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}},Ry.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Iy(this,this._t0,Oy(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,Iy(this,Oy(this,n=Ey(this,t,e)),n);break;default:Iy(this,this._t0,n=Ey(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}},(Py.prototype=Object.create(Ry.prototype)).point=function(t,e){Ry.prototype.point.call(this,e,t)},Fy.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,o,i){this._context.bezierCurveTo(e,t,r,n,i,o)}},$y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=Zy(t),o=Zy(e),i=0,s=1;s<n;++i,++s)this._context.bezierCurveTo(r[0][i],o[0][i],r[1][i],o[1][i],t[s],e[s]);(this._line||0!==this._line&&1===n)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}},Uy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}};var cv=n(3606),uv=n(8383),fv=n(1343),dv=n(2991),hv=n(6596),pv=n(8467),mv=n(6018),gv=n(7905),yv=n(2311),vv=n(8593),bv=n(8927),wv=n(7445),_v=n(1887),xv=n(7351),kv=n(4552),qv=n(7150),Nv=n(1852),Sv=n(3015),Av="%Y-%m-%dT%H:%M:%S.%LZ";var Mv=Date.prototype.toISOString?function(t){return t.toISOString()}:(0,Nv.g0)(Av);const Tv=Mv;var Cv=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:(0,Nv.wp)(Av);const jv=Cv;function Ev(t,e,n){var r=new le,o=e;return null==e?(r.restart(t,e,n),r):(r._restart=r.restart,r.restart=function(t,e,n){e=+e,n=null==n?se():+n,r._restart((function i(s){s+=o,r._restart(i,o+=e,n),t(s)}),e,n)},r.restart(t,e,n),r)}const Ov=t=>()=>t;function Iv(t,{sourceEvent:e,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function Rv(t,e,n){this.k=t,this.x=e,this.y=n}Rv.prototype={constructor:Rv,scale:function(t){return 1===t?this:new Rv(this.k*t,this.x,this.y)},translate:function(t,e){return 0===t&0===e?this:new Rv(this.k,this.x+this.k*t,this.y+this.k*e)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pv=new Rv(1,0,0);function Fv(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Pv;return t.__zoom}function Dv(t){t.stopImmediatePropagation()}function Lv(t){t.preventDefault(),t.stopImmediatePropagation()}function $v(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function Zv(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function zv(){return this.__zoom||Pv}function Uv(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Bv(){return navigator.maxTouchPoints||"ontouchstart"in this}function Gv(t,e,n){var r=t.invertX(e[0][0])-n[0][0],o=t.invertX(e[1][0])-n[1][0],i=t.invertY(e[0][1])-n[0][1],s=t.invertY(e[1][1])-n[1][1];return t.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),s>i?(i+s)/2:Math.min(0,i)||Math.max(0,s))}function Jv(){var t,e,n,r=$v,o=Zv,i=Gv,s=Uv,a=Bv,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,f=dh,d=N("start","zoom","end"),h=500,p=150,m=0,g=10;function y(t){t.property("__zoom",zv).on("wheel.zoom",q,{passive:!1}).on("mousedown.zoom",S).on("dblclick.zoom",A).filter(a).on("touchstart.zoom",M).on("touchmove.zoom",T).on("touchend.zoom touchcancel.zoom",C).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function v(t,e){return(e=Math.max(l[0],Math.min(l[1],e)))===t.k?t:new Rv(e,t.x,t.y)}function b(t,e,n){var r=e[0]-n[0]*t.k,o=e[1]-n[1]*t.k;return r===t.x&&o===t.y?t:new Rv(t.k,r,o)}function w(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function _(t,e,n,r){t.on("start.zoom",(function(){x(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){x(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,i=arguments,s=x(t,i).event(r),a=o.apply(t,i),l=null==n?w(a):"function"==typeof n?n.apply(t,i):n,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),u=t.__zoom,d="function"==typeof e?e.apply(t,i):e,h=f(u.invert(l).concat(c/u.k),d.invert(l).concat(c/d.k));return function(t){if(1===t)t=d;else{var e=h(t),n=c/e[2];t=new Rv(n,l[0]-e[0]*n,l[1]-e[1]*n)}s.zoom(null,t)}}))}function x(t,e,n){return!n&&t.__zooming||new k(t,e)}function k(t,e){this.that=t,this.args=e,this.active=0,this.sourceEvent=null,this.extent=o.apply(t,e),this.taps=0}function q(t,...e){if(r.apply(this,arguments)){var n=x(this,e).event(t),o=this.__zoom,a=Math.max(l[0],Math.min(l[1],o.k*Math.pow(2,s.apply(this,arguments)))),u=Ht(t);if(n.wheel)n.mouse[0][0]===u[0]&&n.mouse[0][1]===u[1]||(n.mouse[1]=o.invert(n.mouse[0]=u)),clearTimeout(n.wheel);else{if(o.k===a)return;n.mouse=[u,o.invert(u)],Me(this),n.start()}Lv(t),n.wheel=setTimeout((function(){n.wheel=null,n.end()}),p),n.zoom("mouse",i(b(v(o,a),n.mouse[0],n.mouse[1]),n.extent,c))}}function S(t,...e){if(!n&&r.apply(this,arguments)){var o=t.currentTarget,s=x(this,e,!0).event(t),a=Lt(t.view).on("mousemove.zoom",(function(t){if(Lv(t),!s.moved){var e=t.clientX-u,n=t.clientY-f;s.moved=e*e+n*n>m}s.event(t).zoom("mouse",i(b(s.that.__zoom,s.mouse[0]=Ht(t,o),s.mouse[1]),s.extent,c))}),!0).on("mouseup.zoom",(function(t){a.on("mousemove.zoom mouseup.zoom",null),Gt(t.view,s.moved),Lv(t),s.event(t).end()}),!0),l=Ht(t,o),u=t.clientX,f=t.clientY;Bt(t.view),Dv(t),s.mouse=[l,this.__zoom.invert(l)],Me(this),s.start()}}function A(t,...e){if(r.apply(this,arguments)){var n=this.__zoom,s=Ht(t.changedTouches?t.changedTouches[0]:t,this),a=n.invert(s),l=n.k*(t.shiftKey?.5:2),f=i(b(v(n,l),s,a),o.apply(this,e),c);Lv(t),u>0?Lt(this).transition().duration(u).call(_,f,s,t):Lt(this).call(y.transform,f,s,t)}}function M(n,...o){if(r.apply(this,arguments)){var i,s,a,l,c=n.touches,u=c.length,f=x(this,o,n.changedTouches.length===u).event(n);for(Dv(n),s=0;s<u;++s)l=[l=Ht(a=c[s],this),this.__zoom.invert(l),a.identifier],f.touch0?f.touch1||f.touch0[2]===l[2]||(f.touch1=l,f.taps=0):(f.touch0=l,i=!0,f.taps=1+!!t);t&&(t=clearTimeout(t)),i&&(f.taps<2&&(e=l[0],t=setTimeout((function(){t=null}),h)),Me(this),f.start())}}function T(t,...e){if(this.__zooming){var n,r,o,s,a=x(this,e).event(t),l=t.changedTouches,u=l.length;for(Lv(t),n=0;n<u;++n)o=Ht(r=l[n],this),a.touch0&&a.touch0[2]===r.identifier?a.touch0[0]=o:a.touch1&&a.touch1[2]===r.identifier&&(a.touch1[0]=o);if(r=a.that.__zoom,a.touch1){var f=a.touch0[0],d=a.touch0[1],h=a.touch1[0],p=a.touch1[1],m=(m=h[0]-f[0])*m+(m=h[1]-f[1])*m,g=(g=p[0]-d[0])*g+(g=p[1]-d[1])*g;r=v(r,Math.sqrt(m/g)),o=[(f[0]+h[0])/2,(f[1]+h[1])/2],s=[(d[0]+p[0])/2,(d[1]+p[1])/2]}else{if(!a.touch0)return;o=a.touch0[0],s=a.touch0[1]}a.zoom("touch",i(b(r,o,s),a.extent,c))}}function C(t,...r){if(this.__zooming){var o,i,s=x(this,r).event(t),a=t.changedTouches,l=a.length;for(Dv(t),n&&clearTimeout(n),n=setTimeout((function(){n=null}),h),o=0;o<l;++o)i=a[o],s.touch0&&s.touch0[2]===i.identifier?delete s.touch0:s.touch1&&s.touch1[2]===i.identifier&&delete s.touch1;if(s.touch1&&!s.touch0&&(s.touch0=s.touch1,delete s.touch1),s.touch0)s.touch0[1]=this.__zoom.invert(s.touch0[0]);else if(s.end(),2===s.taps&&(i=Ht(i,this),Math.hypot(e[0]-i[0],e[1]-i[1])<g)){var c=Lt(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return y.transform=function(t,e,n,r){var o=t.selection?t.selection():t;o.property("__zoom",zv),t!==o?_(t,e,n,r):o.interrupt().each((function(){x(this,arguments).event(r).start().zoom(null,"function"==typeof e?e.apply(this,arguments):e).end()}))},y.scaleBy=function(t,e,n,r){y.scaleTo(t,(function(){return this.__zoom.k*("function"==typeof e?e.apply(this,arguments):e)}),n,r)},y.scaleTo=function(t,e,n,r){y.transform(t,(function(){var t=o.apply(this,arguments),r=this.__zoom,s=null==n?w(t):"function"==typeof n?n.apply(this,arguments):n,a=r.invert(s),l="function"==typeof e?e.apply(this,arguments):e;return i(b(v(r,l),s,a),t,c)}),n,r)},y.translateBy=function(t,e,n,r){y.transform(t,(function(){return i(this.__zoom.translate("function"==typeof e?e.apply(this,arguments):e,"function"==typeof n?n.apply(this,arguments):n),o.apply(this,arguments),c)}),null,r)},y.translateTo=function(t,e,n,r,s){y.transform(t,(function(){var t=o.apply(this,arguments),s=this.__zoom,a=null==r?w(t):"function"==typeof r?r.apply(this,arguments):r;return i(Pv.translate(a[0],a[1]).scale(s.k).translate("function"==typeof e?-e.apply(this,arguments):-e,"function"==typeof n?-n.apply(this,arguments):-n),t,c)}),r,s)},k.prototype={event:function(t){return t&&(this.sourceEvent=t),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(t,e){return this.mouse&&"mouse"!==t&&(this.mouse[1]=e.invert(this.mouse[0])),this.touch0&&"touch"!==t&&(this.touch0[1]=e.invert(this.touch0[0])),this.touch1&&"touch"!==t&&(this.touch1[1]=e.invert(this.touch1[0])),this.that.__zoom=e,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(t){var e=Lt(this.that).datum();d.call(t,this.that,new Iv(t,{sourceEvent:this.sourceEvent,target:y,type:t,transform:this.that.__zoom,dispatch:d}),e)}},y.wheelDelta=function(t){return arguments.length?(s="function"==typeof t?t:Ov(+t),y):s},y.filter=function(t){return arguments.length?(r="function"==typeof t?t:Ov(!!t),y):r},y.touchable=function(t){return arguments.length?(a="function"==typeof t?t:Ov(!!t),y):a},y.extent=function(t){return arguments.length?(o="function"==typeof t?t:Ov([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),y):o},y.scaleExtent=function(t){return arguments.length?(l[0]=+t[0],l[1]=+t[1],y):[l[0],l[1]]},y.translateExtent=function(t){return arguments.length?(c[0][0]=+t[0][0],c[1][0]=+t[1][0],c[0][1]=+t[0][1],c[1][1]=+t[1][1],y):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},y.constrain=function(t){return arguments.length?(i=t,y):i},y.duration=function(t){return arguments.length?(u=+t,y):u},y.interpolate=function(t){return arguments.length?(f=t,y):f},y.on=function(){var t=d.on.apply(d,arguments);return t===d?y:t},y.clickDistance=function(t){return arguments.length?(m=(t=+t)*t,y):Math.sqrt(m)},y.tapDistance=function(t){return arguments.length?(g=+t,y):g},y}Fv.prototype=Rv.prototype},8828:(t,e,n)=>{"use strict";n.d(e,{H:()=>o,L:()=>r});class r extends Map{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const[e,n]of t)this.set(e,n)}get(t){return super.get(i(this,t))}has(t){return super.has(i(this,t))}set(t,e){return super.set(s(this,t),e)}delete(t){return super.delete(a(this,t))}}class o extends Set{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const e of t)this.add(e)}has(t){return super.has(i(this,t))}add(t){return super.add(s(this,t))}delete(t){return super.delete(a(this,t))}}function i({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function s({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function a({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function l(t){return null!==t&&"object"==typeof t?t.valueOf():t}}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,n),i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{"use strict";var t=n(334),e=n.n(t),r=n(141),o=n(7147),i=n.n(o),s=n(1017),a=n.n(s);{const t=i().readdirSync(a().join(e().binpath,"/routes")).filter((t=>t.endsWith(".ts"))).map((t=>{const e=n(126)(`./${t}`);return e.file=t,e}));!function(t,e,n={}){const r=Object.assign({basepath:""},n);for(const n of e){const e=n.api;for(const n in e.methods){const o=e.methods[n];t[n](`${r.basepath}/${e.endpoint}`,o.init(r))}}!function(t,e){if(e.apiJson){const n=JSON.stringify(t.map((t=>t.api))),r=s.dirname(e.apiJson);o.existsSync(r)||o.mkdirSync(r,{recursive:!0}),o.writeFileSync(e.apiJson,n)}if(e.types){const n=function(t,e){const n={};for(const{file:e,route:r}of t){const t=r.api;for(const r in t.methods){const o=t.methods[r];o.alternativeFor||(n[e]||(n[e]=new Set),o.request.typeId&&n[e].add(o.request.typeId),o.response.typeId&&n[e].add(o.response.typeId))}}const r=["import { createValidate } from 'typia'"],o=[];for(const t in n){const i=Array.from(n[t]);r.push(`import { ${i.join(", ")} } from '${e}/${t}'`);for(const t of i)o.push(`export const valid${t} = createValidate<${t}>()`)}return r.join("\n")+"\n\n"+o.join("\n")}(t.map((t=>({file:t.file,route:t}))),e.types.importDir),r=s.dirname(e.types.outputFile);o.existsSync(r)||o.mkdirSync(r,{recursive:!0}),o.writeFileSync(e.types.outputFile,n)}}(e,r)}(r.l2,t,{app:r.l2,genomes:r.g_,basepath:r.LJ,apiJson:a().join(__dirname,"../../public/docs/server-api.json"),types:{importDir:"../types/routes",outputFile:a().join(__dirname,"./shared/checkers-raw/index.ts")}})}(0,r.lE)(e()).then((async()=>{if(console.log(`\n${new Date} ${e().commitHash||""}`),console.log("\nValidation succeeded.\n"),"validate"!=process.argv[2])if("phewas-precompute"!=process.argv[2])await(0,r.OG)();else{const t=process.argv[3],e=process.argv[4],n=r.g_[t];if(!n)throw"invalid genome name: "+t;const o=n.datasets[e];if(!o)throw"invalid dataset: "+e;r.U_.do_precompute(o)}else console.log("You may now run the server.")})).catch((t=>{let n=1;if(!i().existsSync(e().tpmasterdir)){const t=e().maintenance||{};if("start"in t&&"stop"in t&&"tpErrorCode"in t){const e=+new Date(t.start),r=+new Date(t.stop),o=+new Date;e<=o&&o<=r&&(n=t.tpErrorCode)}}t.stack&&console.log(t.stack),n?console.error("\n!!!\n"+t+"\n\n"):console.log("\n!!!\n"+t+"\n\n"),process.exit(n)}))})()})();
|
|
1
|
+
(()=>{var t={5037:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(9157),o=n(1017),i=n.n(o),s=n(334),a=n.n(s),l=n(3345);const c={endpoint:"burden",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{var o;const s=t[e.query.genome];if(!s)throw`invalid q.genome=${e.query.genome}`;const c=e.query,f=s.datasets[c.dslabel];if(!f)throw`invalid q.genome=${e.query.dslabel}`;if(null===(o=f.cohort.cumburden)||void 0===o||!o.files)throw"missing ds.cohort.cumburden.files";const d=await async function(t,e){const n=i().join(a().cachedir,Math.random().toString()+".json");for(const e in t.query)t.query[e]=Number(t.query[e]);const o=Object.assign({},u,t.query);await(0,l.Sf)(n,JSON.stringify(o));const{fit:s,surv:c,sample:f}=e.cohort.cumburden.files;if(!s||!c||!f)throw"missing one or more of ds.cohort.burden.files.{fit, surv, sample}";const d=[n,`${a().tpmasterdir}/${s}`,`${a().tpmasterdir}/${c}`,`${a().tpmasterdir}/${f}`],h=await(0,r.default)(i().join(a().binpath,"utils/burden.R"),[],d),p=JSON.parse(h[0]);return p}(e,f),{keys:h,rows:p}=function(t){const e=Object.keys(t[0]),n=[],r=[];for(const t of e)if("chc"==t)r.push(t),n.push(t);else{const e=Number(t.slice(1).split(",")[0]);e<=60&&e%2==0&&(r.push(t),n.push(`burden${e}`))}const o=[];for(const e of t)o.push(r.map((t=>e[t])));return{keys:n,rows:o}}(d);n.send({status:"ok",keys:h,rows:p})}catch(t){n.send({status:"error",error:t.message||t})}},request:{typeId:"BurdenRequest"},response:{typeId:"BurdenResponse"},examples:[{request:{body:{genome:"hg38",dslabel:"SJLife",diaggrp:5,sex:1,white:1,agedx:1,bleo:0,etop:0,cisp:0,carbo:0,steriod:0,vcr:0,hdmtx:0,itmt:0,ced:0,dox:0,heart:0,brain:0,abd:0,pelvis:0,chest:0}},response:{header:{status:200}}}]}}};const u=Object.freeze({diaggrp:5,sex:0,white:1,agedx:1,steriod:0,bleo:0,vcr:0,etop:0,itmt:0,ced:0,cisp:0,dox:0,carbo:0,hdmtx:0,brain:0,chest:0,heart:0,pelvis:0,abd:0})},2538:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>h});var r=n(1017),o=n.n(r),i=n(6452),s=n.n(i),a=n(334),l=n.n(a);const c=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",u=1e3,f="Aliquot Ensemble Somatic Variant Merging and Masking",d=l().features.gdcMafMaxFileSize||5e7,h={endpoint:"gdc/maf",methods:{get:{init:function({genomes:t}){return async(e,n)=>{try{const r=t.hg38;if(!r)throw"hg38 missing";if(!r.datasets.GDC)throw"hg38 GDC missing";const i=await async function(t){var e,n,r;const i={op:"and",content:[{op:"=",content:{field:"data_format",value:"MAF"}},{op:"=",content:{field:"experimental_strategy",value:t.experimentalStrategy}},{op:"=",content:{field:"analysis.workflow_type",value:f}},{op:"=",content:{field:"access",value:"open"}}]};t.filter0&&i.content.push(t.filter0);const a={"Content-Type":"application/json",Accept:"application/json"},l={filters:i,size:u,fields:["id","file_size","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},p=await s().post(o().join(c,"files"),{headers:a,body:JSON.stringify(l)});let m;try{m=JSON.parse(p.body)}catch(t){throw"invalid JSON from "+h.endpoint}if(!Number.isInteger(null===(e=m.data)||void 0===e||null===(n=e.pagination)||void 0===n?void 0:n.total))throw"re.data.pagination.total is not int";if(!Array.isArray(null===(r=m.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const g=[];for(const t of m.data.hits){var y;const e=null===(y=t.cases)||void 0===y?void 0:y[0];if(!e)throw"h.cases[0] missing";const n={id:t.id,project_id:e.project.project_id,file_size:t.file_size};n.case_submitter_id=e.submitter_id,e.samples&&(n.sample_types=e.samples.map((t=>t.sample_type)).sort()),g.push(n)}return{files:g,filesTotal:m.data.pagination.total,maxTotalSizeCompressed:d}}(e.query);n.send(i)}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafRequest"},response:{typeId:"GdcMafResponse"},examples:[{request:{body:{experimentalStrategy:"WXS",embedder:"localhost"}},response:{header:{status:200}}}]}}}},86:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>d});var r=n(6452),o=n.n(r),i=n(1017),s=n.n(i),a=n(1271),l=n(334),c=n.n(l);const u=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",f=c().features.gdcMafMaxFileSize||5e7,d={endpoint:"gdc/mafBuild",methods:{all:{init:function({genomes:t}){return async(t,e)=>{try{await async function(t,e){const n=Date.now(),r=await async function(t){var e;if(0==t.length)throw"fileIdLst[] not array or blank";const n={filters:{op:"in",content:{field:"file_id",value:t}},size:1e3,fields:"file_size"},r={"Content-Type":"application/json",Accept:"application/json"},i=await o().post(s().join(u,"files"),{headers:r,body:JSON.stringify(n)});let a;try{a=JSON.parse(i.body)}catch(t){throw"invalid json from getFileLstUnderSizeLimit"}if(!Array.isArray(null===(e=a.data)||void 0===e?void 0:e.hits))throw"re.data.hits[] not array";const l=[];let c=0;for(const t of a.data.hits){if(c>=f)break;if(!t.id)throw".id missing";if(!Number.isInteger(t.file_size))throw".file_size not integer";c+=t.file_size,l.push(t.id)}if(0==l.length)throw"no file available";return l}(t.fileIdLst);console.log("test gdc maf sizes",Date.now()-n);const i={fileIdLst:r,host:s().join(u,"data")},l=(0,a.run_rust_stream)("gdcmaf",JSON.stringify(i));e.setHeader("Content-Type","application/octet-stream"),e.setHeader("Content-Disposition","attachment; filename=cohort.maf.gz"),l.pipe(e),console.log("rust gdcmaf",Date.now()-n),l.on("end",(()=>{e.end()})),l.on("error",(t=>{console.error(t),e.statusCode=500,e.end("Internal Server Error")}))}(t.query,e)}catch(t){t.stack&&console.log(t.stack),e.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcMafBuildRequest"},response:{typeId:null}}}}},889:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>l});var r=n(1017),o=n.n(r),i=n(6452),s=n.n(i);const a=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",l={endpoint:"gdc/topMutatedGenes",methods:{get:{init:({genomes:t})=>async(t,e)=>{try{const n={genes:await async function(t){let e={op:"and",content:[]};if(t.filter0){if("object"!=typeof t.filter0)throw"filter0 not object";e=t.filter0}const n=await s().post(o().join(a,"/analysis/top_mutated_genes_by_project"),{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({size:t.maxGenes||50,fields:"symbol",filters:c(e,t.geneFilter)})}),r=JSON.parse(n.body),i=[];for(const t of r.data.hits)t.symbol&&i.push(t.symbol);return i}(t.query)};e.send(n)}catch(t){e.send({status:"error",error:t.message||t})}},request:{typeId:null},response:{typeId:"GdcTopMutatedGeneResponse"}}}};function c(t,e){let n;if("in"==t.op)n={op:"and",content:[t]};else{if("and"!=t.op)throw'f.op not "in" or "and"';n=t}return n.content.push({op:"NOT",content:{field:"ssms.consequence.transcript.annotation.vep_impact",value:"missing"}}),n.content.push({op:"in",content:{field:"ssms.consequence.transcript.consequence_type",value:["missense_variant","frameshift_variant","start_lost","stop_lost","stop_gained"]}}),"CGC"==e&&n.content.push({op:"in",content:{field:"genes.is_cancer_gene_census",value:["true"]}}),n}},449:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f});var r=n(1169),o=n(1017),i=n.n(o),s=n(6452),a=n.n(s),l=n(334),c=n.n(l);const u="https://uat-api.gdc.cancer.gov",f={endpoint:"gdc/topVariablyExpressedGenes",methods:{get:{init:function({genomes:t}){return async(e,n)=>{try{var o;const s=t.hg38;if(!s)throw"hg38 genome missing";const l=null===(o=s.datasets)||void 0===o?void 0:o.GDC;if(!l)throw"gdc dataset missing";const f=await async function(t,e,n){if(c().features.gdcGenes)return c().features.gdcGenes;if(!e.__gdc.doneCaching)throw"The server has not finished caching the case IDs: try again in ~2 minutes";const o=await(0,r.Pj)(t,e);if(0==o.length)return[];const s=i().join(u,"/gene_expression/gene_selection");try{const e=await a().post(s,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({case_ids:o.slice(0,20),gene_ids:d(n),selection_size:Number(t.maxGenes)})}),r=JSON.parse(e.body),i=[];if(!Array.isArray(r.gene_selection))throw"re.gene_selection[] is not array";for(const t of r.gene_selection)if(t.gene_id&&"string"==typeof t.gene_id){const e=n.genedb.getNameByAlias.get(t.gene_id);e&&i.push(e.name)}else{if(!t.symbol||"string"!=typeof t.symbol)throw"one of re.gene_selection[] is missing both gene_id and symbol";i.push(t.symbol)}return i}catch(t){throw console.log(t.stack||t),t}}(e.query,l,s),h={genes:f};n.send(h)}catch(t){n.send({status:"error",error:t.message||t})}}},request:{typeId:"GdcTopVariablyExpressedGenesRequest"},response:{typeId:"GdcTopVariablyExpressedGenesResponse"}}}};function d(t){const e=[];for(const n of t.geneset[0].lst){const r=t.genedb.getAliasByName.all(n);if(r)for(const t of r)t.alias.startsWith("ENSG")&&e.push(t.alias)}return e}},3202:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(4065);function o({genomes:t}){return(e,n)=>{try{e.query;const o=t[e.query.genome];if(!o)throw"invalid genome name";const i=(0,r.S)(o,e.query);n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}const i={endpoint:"genelookup",methods:{get:{init:o,request:{typeId:"GeneLookupRequest"},response:{typeId:"GeneLookupResponse"},examples:[{request:{body:{input:"kr",genome:"hg38-test"}},response:{header:{status:200},body:{hits:["KRAS"]}}}]},post:{alternativeFor:"get",init:o}}}},1746:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(2062);const o={endpoint:"healthcheck",methods:{get:{init:({genomes:t})=>async(e,n)=>{try{const e=await(0,r.W)(t);n.send(e)}catch(t){n.send({status:"error",error:t.message||t})}},request:{typeId:null},response:{typeId:"HealthCheckResponse"}}}}},3932:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>c});var r=n(3345),o=n(2081),i=n(4521),s=n.n(i),a=n(334),l=n.n(a);const c={endpoint:"hicdata",methods:{get:{init:u,request:{typeId:"HicdataRequest"},response:{typeId:"HicdataResponse"}},post:{alternativeFor:"get",init:u}}};function u({genomes:t}){return async(t,e)=>{try{const i=await(n=t.query,new Promise(((t,e)=>{const[i,a,c]=(0,r.ZX)({query:n});i&&e({error:"illegal file name"});const u=[n.nmeth||"NONE",a,n.pos1,n.pos2,n.isfrag?"FRAG":"BP",n.resolution],f=(0,o.spawn)(l().hicstraw,u),d=s().createInterface({input:f.stdout}),h=[],p=[];let m=0,g=0;d.on("line",(t=>{const e=t.split("\t");if(3!=e.length)return void m++;const r=Number.parseInt(e[0]),o=Number.parseInt(e[1]),i=Number.parseFloat(e[2]);Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(i)?g++:null!=n.mincutoff&&i<=n.mincutoff||h.push([r,o,i])})),f.stderr.on("data",(t=>p.push(t))),f.on("close",(()=>{const n=p.join("");n&&e({error:n}),m&&e({error:m+" lines have other than 3 fields"}),g&&e({error:g+" lines have non-numerical values in any of the 3 fields"}),t({items:h})}))})));e.send(i)}catch(t){e.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}var n}}},6310:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>u});var r=n(3345),o=n(7147),i=n.n(o),s=n(6464),a=n.n(s),l=n(6452),c=n.n(l);const u={endpoint:"hicstat",methods:{get:{init:f,request:{typeId:"HicstatRequest"},response:{typeId:"HicstatResponse"},examples:[{request:{body:{genome:"hg19",file:"proteinpaint_demo/hg19/hic/hic_demo.hic",embedder:"localhost"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:f}}};function f(){return async(t,e)=>{try{const[n,o,s]=(0,r.ZX)(t);if(n)throw"illegal file name";s||await(0,r.Ic)(o);const l=await async function(t,e){const n={},r=e?await S(t,0,32e3):await N(t,0,32e3),o=new DataView(r);let s=0;if("HIC"!==A())throw Error("Unsupported hic file");const l=M();if(7!==l&&8!==l&&9!=l)throw Error("Unsupported hic version: "+l);n.version=l;const u=Number(T());let f=[];const d=1e5;if(8==l||7==l){let e=await k(t,u,d);const n=e.getInt32(0,!0);n>0&&(e=await k(t,u+n+4,d),f=await q(e,u+n+4))}const h=A();if(n["Genome ID"]=h,9==l){const e=Number(T()),n=Number(T());if(e>0&&n>0){const r=await k(t,e,n);f=await q(r,0)}}const p={},m=M();let g=0;for(;g!==m;)p[A()]=A(),g++;n.Chromosomes={},n.chrorder=[];const y=M();let v=0;for(;v!==y;){const t=A();n.chrorder.push(t),n.Chromosomes[t]=7==l||8==l?M():T(),v++}n["Base pair-delimited resolutions"]=[];const b=M();let w=0;for(;w!==b;){const t=M();n["Base pair-delimited resolutions"].push(t),w++}n["Fragment-delimited resolutions"]=[];const _=M();let x=0;for(;x!==_;){const t=M();n["Fragment-delimited resolutions"].push(t),x++}return BigInt.prototype.toJSON||Object.defineProperty(BigInt.prototype,"toJSON",{get(){return()=>String(this)}}),n.normalization=f,n;async function k(t,n,r){const o=e?await S(t,n,r):await N(t,n,r);return new DataView(o)}async function q(e,n){const r=Date.now();let o=[];const i=e.getInt32(0,!0);let s=4;for(let t=1;t<=i;t++){let t=await f("string");o.push(t),8==l||7==l?(t=await f("string"),c(4),c(8*await f("int32")),c(12*await f("int32"))):9==l&&(s+=4,t=await f("string"),s+=20)}o=[...new Set(o)];const a=Date.now()-r;return console.log(`Read normalization on ${t} on ${a/1e3} seconds`),o;async function c(t){s+t>d&&u(),s+=t}async function u(){e=await k(t,n+s,d),n+=s,s=0}async function f(t){let n;if("string"==t){let t,r="";for(;0!=(t=e.getUint8(s++));)s>d&&await u(),r+=String.fromCharCode(t);n=r}else{if("int32"!=t)throw"No value assigned [server/src/hicstat.ts getViewValue()]";s+4>d&&await u(),n=e.getInt32(s,!0),s+=4}return n}}async function N(t,e,n){const r=a().promisify(i().open),o=a().promisify(i().read),s=Buffer.alloc(n),l=await r(t,"r"),c=await o(l,s,0,n,e);i().close(l,(function(t){return t}));const u=c.buffer;return u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}async function S(t,e,n){try{const r=e+"-"+(e+n-1);return(await c()(t,{headers:{Range:"bytes="+r}}).buffer()).buffer}catch(t){throw console.log(t.response),"error reading file, check file details"}}function A(){let t,e="";for(;0!=(t=o.getUint8(s++));)e+=String.fromCharCode(t);return e}function M(){const t=o.getInt32(s,!0);return s+=4,t}function T(){const t=o.getBigInt64(s,!0);return s+=8,t}}(o,s);e.send({out:l})}catch(t){e.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5852:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(938),o=n(2974);const i={endpoint:"termdb/categories",methods:{get:{init:s,request:{typeId:"getcategoriesRequest"},response:{typeId:"getcategoriesResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getcategories:1,tid:"diaggrp",term1_q:{isAtomic:!0,hiddenValues:{},type:"values",groupsetting:{disabled:!0},mode:"discrete"},filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:s}}};function s({genomes:t}){return async(e,n)=>{const i=e.query;try{const s=t[e.query.genome];if(!s)throw"invalid genome name";const l=s.datasets[e.query.dslabel];if(!l)throw"invalid dataset name";const c=l.cohort.termdb;if(!c)throw"invalid termdb object";await async function(t,e,n,i,s){var l,c,u,f,d,h;if(!t.tid)throw".tid missing";const p="geneVariant"==t.type?{name:t.tid,type:"geneVariant",isleaf:!0}:n.q.termjsonByOneid(t.tid),m={filter:t.filter,terms:"geneVariant"==t.type?[{term:p,q:{isAtomic:!0}}]:[{id:t.tid,term:p,q:t.term1_q||a(p,t)}],currentGeneNames:t.currentGeneNames},g=await(0,o.Yu)(m,i,s);if(g.error)throw g.error;const y=[];if("geneVariant"==t.type){var v;const e=g.samples,n=new Map;if(null!==(v=i.assayAvailability)&&void 0!==v&&v.byDt)for(const[t,e]of Object.entries(i.assayAvailability.byDt))e.byOrigin&&n.set(parseInt(t),{byOrigin:{germline:{},somatic:{}}});const r=new Set;for(const[o,i]of Object.entries(e)){const e=i[t.tid].values;r.clear();for(const t of e){n.has(t.dt)||n.set(t.dt,{});const e=n.get(t.dt);e.byOrigin?(e.byOrigin[t.origin][t.class]||(e.byOrigin[t.origin][t.class]=1,r.add(`${t.dt} ${t.origin} ${t.class}`)),r.has(`${t.dt} ${t.origin} ${t.class}`)||(r.add(`${t.dt} ${t.origin} ${t.class}`),e.byOrigin[t.origin][t.class]+=1)):(e[t.class]||(r.add(`${t.dt} ${t.class}`),e[t.class]=1),r.has(`${t.dt} ${t.class}`)||(r.add(`${t.dt} ${t.class}`),e[t.class]+=1))}}for(const[t,e]of n)y.push({dt:t,classes:e})}else{const e=new Map;for(const n in g.samples){const r=g.samples[n][t.tid];r&&("key"in r&&e.set(r.key,1+(e.get(r.key)||0)))}for(const[n,r]of e){var b,w,_,x,k,q;y.push({samplecount:r,key:n,label:(null===(b=g.refs)||void 0===b||null===(w=b.byTermId)||void 0===w||null===(_=w[t.tid])||void 0===_||null===(x=_.events)||void 0===x?void 0:x.find((t=>t.event===n)).label)||(null==p||null===(k=p.values)||void 0===k||null===(q=k[n])||void 0===q?void 0:q.label)||n})}}const N=(0,r.Tt)(p,(null===(l=g.refs)||void 0===l||null===(c=l.byTermId)||void 0===c||null===(u=c[t.tid])||void 0===u?void 0:u.bins)||[],null===(f=g.refs)||void 0===f||null===(d=f.byTermId)||void 0===d||null===(h=d[t.tid])||void 0===h?void 0:h.events,t.term1_q);N.length&&y.sort(((t,e)=>N.indexOf(t.label)-N.indexOf(e.label)));e.send({lst:y,orderedLabels:N})}(i,n,c,l,s)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}function a(t,e){if("categorical"==t.type)return{};if("survival"==t.type)return{};if("integer"==t.type||"float"==t.type)return t.bins.default;if("condition"==t.type)return{mode:e.mode,breaks:e.breaks,bar_by_grade:e.bar_by_grade,bar_by_children:e.bar_by_children,value_by_max_grade:e.value_by_max_grade,value_by_most_recent:e.value_by_most_recent,value_by_computable_grade:e.value_by_computable_grade};if("geneVariant"==t.type)return{};throw"unknown term type"}},2630:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>i});var r=n(8907),o=n(7027);const i={endpoint:"termdb/getpercentile",methods:{get:{init:s,request:{typeId:"getpercentileRequest"},response:{typeId:"getpercentileResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",getpercentile:[50],tid:"agedx",filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{name:"Cohort",type:"categorical",values:{ABC:{label:"ABC"},XYZ:{label:"XYZ"}},id:"subcohort",isleaf:!1,groupsetting:{disabled:!0}},values:[{key:"ABC",label:"ABC"}]}}]}}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:s}}};function s({genomes:t}){return async(e,n)=>{const i=e.query;try{const s=t[e.query.genome];if(!s)throw"invalid genome name";const a=s.datasets[e.query.dslabel];if(!a)throw"invalid dataset name";await async function(t,e,n){const i=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!i)throw"invalid termid";if("float"!=i.type&&"integer"!=i.type)throw"not numerical term";const s=t.getpercentile,a=[],l=[],c=await r.J4({ds:n,key:t.tid,filter:t.filter?"string"==typeof t.filter?JSON.parse(t.filter):t.filter:null});for(const{value:t}of c)i.values&&i.values[t]&&i.values[t].uncomputable||i.skip0forPercentile&&0==t||l.push(Number(t));for(const t of s){const e=(0,o.Z)(l,t);a.push(e)}e.send({values:a})}(i,n,a)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},5707:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>r});const r={endpoint:"termdb/singlecellData",methods:{get:{init:o,request:{typeId:"TermdbSinglecellDataRequest"},response:{typeId:"TermdbSinglecellDataResponse"}},post:{alternativeFor:"get",init:o}}};function o({genomes:t}){return async(e,n)=>{const r=e.query;try{var o;const e=t[r.genome];if(!e)throw"invalid genome name";const i=e.datasets[r.dslabel];if(!i)throw"invalid dataset name";if(null===(o=i.queries)||void 0===o||!o.singleCell)throw"no singlecell data on this dataset";const s=await i.queries.singleCell.data.get(r);n.send(s)}catch(t){t instanceof Error&&t.stack&&console.log(t),n.send({error:t.message||t})}}}},7934:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>f,validate_query_singleCell:()=>h});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(334),c=n.n(l),u=n(1169);const f={endpoint:"termdb/singlecellSamples",methods:{get:{init:d,request:{typeId:"TermdbSinglecellsamplesRequest"},response:{typeId:"TermdbSinglecellsamplesResponse"}},post:{alternativeFor:"get",init:d}}};function d({genomes:t}){return async(e,n)=>{const r=e.query;try{var o;const e=t[r.genome];if(!e)throw"invalid genome name";const i=e.datasets[r.dslabel];if(!i)throw"invalid dataset name";if(null===(o=i.queries)||void 0===o||!o.singleCell)throw"no singlecell data on this dataset";const s=await i.queries.singleCell.samples.get(r);n.send({samples:s})}catch(t){t instanceof Error&&t.stack&&console.log(t),n.send({error:t.message||t})}}}async function h(t,e){const n=t.queries.singleCell;n&&("gdcapi"==n.samples.src?(0,u.z7)(t,e):function(t,e){const n=[],r=e.cohort.termdb.q.getAllValues4term(t.isSampleTerm);for(const t of r.keys())n.push({sample:e.cohort.termdb.q.id2sampleName(t)});if(0==n.length)throw"no sample with sc data";t.get=()=>n}(n.samples,t),"gdcapi"==n.data.src?(0,u.r8)(t,e):function(t,e){const n=new Set;for(const e of t.plots){if(n.has(e.name))throw"duplicate plot.name";n.add(e.name)}const r=[],i={};for(const n of t.termIds){const t=e.cohort.termdb.q.termjsonByOneid(n);if(!t)throw"invalid term id from queries.singleCell.data.termIds[]";r.push(t),i[n]=e.cohort.termdb.q.getAllValues4term(n)}t.get=async e=>{try{const n={};for(const e of t.termIds)n[e]={};const l=[];for(const r of t.plots){const u=s().join(c().tpmasterdir,r.folder,e,r.fileSuffix);try{await o().promises.stat(u)}catch(t){if("ENOENT"==t.code)continue;if("EACCES"==t.code)throw"cannot read file, permission denied";throw"failed to load sc data file"}const f=(await(0,a.b5)(u)).trim().split("\n"),d=[];for(let e=1;e<f.length;e++){const r=f[e].split("\t"),o=r[0],s=Number(r[4]),a=Number(r[5]);if(!o)throw"cell id missing";if(!Number.isFinite(s)||!Number.isFinite(a))throw"x/y not number";d.push({cellId:o,x:s,y:a});for(const e of t.termIds)i[e].has(o)&&(n[e][o]=i[e].get(o))}l.push({name:r.name,cells:d})}return 0==l.length?{nodata:!0}:{plots:l,terms:r,tid2cellvalue:n}}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}}(n.data,t))}},7071:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>o});var r=n(2826);const o={endpoint:"termdb/termbyid",methods:{get:{init:i,request:{typeId:"gettermbyidRequest"},response:{typeId:"gettermbyidResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",gettermbyid:"subcohort"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:i}}};function i({genomes:t}){return async(e,n)=>{const o=e.query;try{const i=t[e.query.genome];if(!i)throw"invalid genome name";const s=i.datasets[e.query.dslabel];if(!s)throw"invalid dataset name";const a=s.cohort.termdb;if(!a)throw"invalid termdb object";await async function(t,e,n){const o=n.q.termjsonByOneid(t.gettermbyid);e.send({term:o?(0,r.iK)(o):void 0})}(o,n,a)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},1485:(t,e,n)=>{"use strict";n.r(e),n.d(e,{api:()=>_});var r=n(7147),o=n(3016),i=n(334),s=n.n(i),a=n(9157),l=n(1017),c=n.n(l),u=n(3345),f=n(2974),d=n(6718),h=n(7011),p=n(7027),m=n(5684);function g(t){let e=t;"string"==typeof t[0]&&(e=t.map(Number));const n=e.length;function r(t){return t.reduce(((t,e)=>t+e))/n}const o=(0,p.Z)(e,50),i=e.map((t=>(t-r(e))**2)).reduce(((t,e)=>t+e),0)/(n-1),s=Math.sqrt(i),a=(0,p.Z)(e,25),l=(0,p.Z)(e,75),c=l-a,u=Math.min(...e),f=Math.max(...e);return{values:[{id:"total",label:"Total",value:n},{id:"min",label:"Minimum",value:(0,m.Z)(u,2)},{id:"p25",label:"1st quartile",value:(0,m.Z)(a,2)},{id:"median",label:"Median",value:(0,m.Z)(o,2)},{id:"mean",label:"Mean",value:(0,m.Z)(r(e),2)},{id:"p75",label:"3rd quartile",value:(0,m.Z)(l,2)},{id:"max",label:"Maximum",value:(0,m.Z)(f,2)},{id:"SD",label:"Standard deviation",value:(0,m.Z)(s,2)},{id:"variance",label:"Variance",value:(0,m.Z)(i,2)},{id:"IQR",label:"Inter-quartile range",value:(0,m.Z)(c,2)}]}}var y=n(938);async function v(t,e,n,i){var l;const p=n.cohort.termdb.q.termjsonByOneid(t.termid);if(!p)throw".termid invalid";if("integer"!=p.type&&"float"!=p.type)throw"term type is not integer/float.";const m=[{id:t.termid,term:p,q:{mode:"continuous"}}];t.divideTw&&(null===t.divideTw||void 0===t.divideTw||"object"!=typeof t.divideTw||"id"in t.divideTw||(t.divideTw.id=t.divideTw.term.name,t.divideTw.term.id=t.divideTw.term.name),m.push(t.divideTw),t.term2_q=t.divideTw.q);const v=await(0,f.Yu)({terms:m,filter:t.filter,currentGeneNames:t.currentGeneNames},n,i);if(v.error)throw v.error;var _,x,k;t.divideTw&&v.refs.byTermId[null===(l=t.divideTw)||void 0===l?void 0:l.id]&&(v.refs.byTermId[null===(_=t.divideTw)||void 0===_?void 0:_.id].orderedLabels=(0,y.Tt)(t.divideTw,null===(x=v.refs.byTermId[null===(k=t.divideTw)||void 0===k?void 0:k.id])||void 0===x?void 0:x.bins,void 0,t.divideTw.q));t.scale&&function(t,e,n){if(!t.scale)return;const r=Number(t.scale);for(const[t,a]of Object.entries(e.samples)){var o,i,s;a[n.id]&&(null!==(o=n.values)&&void 0!==o&&null!==(i=o[null===(s=a[n.id])||void 0===s?void 0:s.value])&&void 0!==i&&i.uncomputable||(a[n.id].key=a[n.id].key/r,a[n.id].value=a[n.id].value/r))}}(t,v,p);const q=function(t,e,n,r){const o="log"==t.unit,i=new Map;let s=1/0,a=-1/0;const l={};let c=0;for(const[t,w]of Object.entries(e.samples)){var u,f,d;const t=null===(u=w[n.id])||void 0===u?void 0:u.value;if(Number.isFinite(t))if(null!==(f=n.values)&&void 0!==f&&null!==(d=f[t])&&void 0!==d&&d.uncomputable){const e=n.values[t].label;l[e]=(l[e]||0)+1}else if(o&&t<=0)c++;else if(s>t&&(s=t),a<t&&(a=t),"log"===o&&0===s&&(s=Math.max(s,t)),r){var h,p,m,g,y,v,b;if(!w[null==r?void 0:r.id])continue;if(null!==(h=r.term)&&void 0!==h&&null!==(p=h.values)&&void 0!==p&&null!==(m=p[null===(g=w[r.id])||void 0===g?void 0:g.key])&&void 0!==m&&m.uncomputable){var _,x;const t=null===(_=r.term.values[null===(x=w[r.id])||void 0===x?void 0:x.value])||void 0===_?void 0:_.label;l[t]=(l[t]||0)+1}i.has(null===(y=w[r.id])||void 0===y?void 0:y.key)||i.set(null===(v=w[r.id])||void 0===v?void 0:v.key,[]),i.get(null===(b=w[r.id])||void 0===b?void 0:b.key).push(t)}else i.has("All samples")||i.set("All samples",[]),i.get("All samples").push(t)}return{key2values:i,minMaxValues:{min:s,max:a},uncomputableValueObj:w(l),skipNonPositiveCount:c}}(t,v,p,t.divideTw),N=function(t,e,n){const r=n.divideTw,o={min:t.minMaxValues.min,max:t.minMaxValues.max,plots:[],pvalues:[],plotThickness:Number,uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null};for(const[n,f]of function(t,e,n){var r,o,i,s;const a=null===(r=t.refs.byTermId[null==n||null===(o=n.term)||void 0===o?void 0:o.id])||void 0===r?void 0:r.orderedLabels;return e=new Map([...e].sort(a?(t,e)=>a.indexOf(t[0])-a.indexOf(e[0]):"categorical"===(null==n||null===(i=n.term)||void 0===i?void 0:i.type)?(t,e)=>e[1].length-t[1].length:"condition"===(null==n||null===(s=n.term)||void 0===s?void 0:s.type)?(t,e)=>t[0]-e[0]:(t,e)=>t.toString().replace(/[^a-zA-Z0-9<]/g,"").localeCompare(e.toString().replace(/[^a-zA-Z0-9<]/g,""),void 0,{numeric:!0}))),e}(e,t.key2values,r)){var i,s,a,l,c,u;if(r)o.plots.push({label:(null==r||null===(i=r.term)||void 0===i||null===(s=i.values)||void 0===s||null===(a=s[n])||void 0===a?void 0:a.label)||n,values:f,seriesId:n,plotValueCount:null==f?void 0:f.length,color:(null==r||null===(l=r.term)||void 0===l||null===(c=l.values)||void 0===c||null===(u=c[n])||void 0===u?void 0:u.color)||null,divideTwBins:b(r,e).has(n)?b(r,e).get(n):null,uncomputableValueObj:Object.keys(t.uncomputableValueObj).length>0?t.uncomputableValueObj:null});else o.plots.push({label:"All samples",values:f,plotValueCount:f.length})}o.plots.length>=1&&(o.plotThickness=n.plotThickness?Number(n.plotThickness):function(t,e){const n=e.screenThickness/t.plots.length,r=Math.round(Math.min(n,e.maxThickness));return r}(o,n));return o}(q,v,t);if(await async function(t,e){if(!t)return;const n=e.plots.length;if(n<2)return;const o=[];for(let t=0;t<n;t++){const r=e.plots[t].label,i=e.plots[t].values;for(let s=t+1;s<n;s++){const t=e.plots[s].label,n=e.plots[s].values;o.push({group1_id:r,group1_values:i,group2_id:t,group2_values:n})}}const i=c().join(s().cachedir,Math.random().toString()+".json");await(0,u.Sf)(i,JSON.stringify(o));const l=await(0,a.default)(c().join(s().binpath,"utils/wilcoxon.R"),[],[i]);(0,r.unlink)(i,(()=>{}));const f=JSON.parse(l);for(const t of f)null==t.pvalue||"null"==t.pvalue?e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:"NA"}]):e.pvalues.push([{value:t.group1_id},{value:t.group2_id},{html:t.pvalue.toPrecision(4)}])}(t.divideTw,N),function(t,e,n){t.radius||(t.radius=5);if(t.radius<=0)throw"q.radius is not a number";t.radius=+t.radius;t.strokeWidth||(t.strokeWidth=.2);const r=4*t.radius;let i;const s="log"==t.unit;i=s?(0,o.scaleLog)().base(n.cohort.termdb.logscaleBase2?2:10).domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]):(0,o.scaleLinear)().domain([e.min,e.max]).range("horizontal"===t.orientation?[0,t.svgw]:[t.svgw,0]);const[a,l]="horizontal"==t.orientation?[t.svgw*t.devicePixelRatio,r*t.devicePixelRatio]:[r*t.devicePixelRatio,t.svgw*t.devicePixelRatio],c=t.radius/t.devicePixelRatio,u=c*Math.PI;for(const n of e.plots){const e=(0,d.createCanvas)(a,l),r=e.getContext("2d");r.strokeStyle="rgba(0,0,0,0.8)",r.lineWidth=t.strokeWidth/t.devicePixelRatio,r.globalAlpha=.5,r.fillStyle="#ffe6e6",1!=t.devicePixelRatio&&r.scale(t.devicePixelRatio,t.devicePixelRatio),"rug"===t.datasymbol?n.values.forEach((e=>{r.beginPath(),"horizontal"==t.orientation?(r.moveTo(+i(e),0),r.lineTo(+i(e),2*c)):(r.moveTo(0,+i(e)),r.lineTo(2*c,+i(e))),r.stroke()})):"bean"===t.datasymbol&&n.values.forEach((e=>{r.beginPath(),"horizontal"===t.orientation?r.arc(+i(e),t.radius,c,0,u):r.arc(t.radius,+i(e),c,0,u),r.fill(),r.stroke()})),n.src=e.toDataURL();const o=(0,h.I)(i,n);n.bins=o.bins,n.biggestBin=Math.max(...o.bins0.map((t=>t.length))),n.summaryStats=g(n.values),delete n.values}}(t,N,n),!e)return N;e.send(N)}function b(t,e){var n,r;const o=new Map,i=null===(n=e.refs.byTermId[null==t||null===(r=t.term)||void 0===r?void 0:r.id])||void 0===n?void 0:n.bins;if(i)for(const t of i)o.set(t.label,t);return o}function w(t){return Object.fromEntries(Object.entries(t).sort((([,t],[,e])=>t-e)))}const _={endpoint:"termdb/violin",methods:{get:{init:x,request:{typeId:"getViolinRequest"},response:{typeId:"getViolinResponse"},examples:[{request:{body:{genome:"hg38-test",dslabel:"TermdbTest",embedder:"localhost",devicePixelRatio:2.200000047683716,maxThickness:150,screenThickness:1218,filter:{type:"tvslst",in:!0,join:"",lst:[{tag:"cohortFilter",type:"tvs",tvs:{term:{id:"subcohort",type:"categorical"},values:[{key:"ABC",label:"ABC"}]}}]},svgw:227.27272234672367,orientation:"horizontal",datasymbol:"bean",radius:5,strokeWidth:.2,axisHeight:60,rightMargin:50,unit:"abs",plotThickness:150,termid:"agedx"}},response:{header:{status:200}}}]},post:{alternativeFor:"get",init:x}}};function x({genomes:t}){return async(e,n)=>{e.query;try{const r=t[e.query.genome],o=r.datasets[e.query.dslabel];if(!r)throw"invalid genome name";const i=await v(e.query,null,o,r);n.send(i)}catch(t){n.send({error:(null==t?void 0:t.message)||t}),t instanceof Error&&t.stack&&console.log(t)}}}},6733:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for CNV";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");return-1==o?"gene missing from header":(n[o]="gene",o=r("cnv"),-1==o?"CNV missing from header":(n[o]="cnv",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.cnv.header=n,e.cnv.loaded=!0,!1))}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.cnv.header.length;t++)s[n.cnv.header[t]]=i[t];if(!s.gene)return void n.cnv.badlines.push([t,"missing gene",i]);if(!s.cnv)return void n.cnv.badlines.push([t,"missing cnv value",i]);switch(s.cnv.toLowerCase()){case"amplification":case"gain":s.class=r.mclasscnvgain;break;case"deletion":case"loss":s.class=r.mclasscnvloss;break;case"loh":s.class=r.mclasscnvloh;break;default:n.cnv.badlines.push([t,"invalid cnv value: "+s.cnv,i]),s.class=null}if(!s.class)return;if(o.EJ(s,n,t,i,n.cnv.badlines))return;s.dt=r.dtcnv,n.good++;const a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}},5558:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for intragenic deletion";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";if(n[o]="isoform",o=r("rnaposition"),-1!=o){if(n[o]="rnaposition",o=r("rnadellength"),-1==o)return"rnadellength is required when rnaPosition is used";n[o]="rnadellength"}if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("chr_start"),-1==o)return"chr_start is required when chr is used";if(n[o]="chrpos1",o=r("chr_stop"),-1==o)return"chr_stop is required when chr is used";n[o]="chrpos2"}return o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.del.header=n,e.del.loaded=!0,!1}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.del.header.length&&null!=i[t];t++)s[n.del.header[t]]=i[t];if(s.gene){if(s.rnaposition){let e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaPosition value",i]);if(s.rnaposition=e,!s.rnadellength)return void n.del.badlines.push([t,"missing rnaDellength value",i]);if(e=Number.parseInt(s.rnadellength),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid rnaDellength value",i]);s.rnadellength=e}if(s.chr){let e=Number.parseInt(s.chrpos1);if(Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_start value",i]);if(s.chrpos1=e,e=Number.parseInt(s.chrpos2),Number.isNaN(e)||e<0)return void n.del.badlines.push([t,"invalid chr_stop value",i]);s.chrpos2=e}if(!o.EJ(s,n,t,i,n.del.badlines)){s.dt=r.dtdel,s.class=r.mclassdel,s.mname="DEL",n.good++;var a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}}else n.del.badlines.push([t,"missing gene",i])}},3602:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for ITD";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";if(n[o]="isoform",o=r("rnaposition"),-1!=o){if(n[o]="rnaposition",o=r("rnaduplength"),-1==o)return"rnaduplength is required when rnaposition is present";n[o]="rnaduplength"}if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("chr_start"),-1==o)return"chr_start is required when chr is present";if(n[o]="chrpos1",o=r("chr_stop"),-1==o)return"chr_stop is required when chr is present";n[o]="chrpos2"}return o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.itd.header=n,e.itd.loaded=!0,!1}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.itd.header.length&&null!=i[t];t++)s[n.itd.header[t]]=i[t];if(s.gene){if(s.rnaposition){let e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaPosition value",i]);if(s.rnaposition=e,!s.rnaduplength)return void n.itd.badlines.push([t,"missing rnaDuplength value",i]);if(e=Number.parseInt(s.rnaduplength),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid rnaDuplength value",i]);s.rnaduplength=e}if(s.chr){let e=Number.parseInt(s.chrpos1);if(Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_start value",i]);if(s.chrpos1=e,e=Number.parseInt(s.chrpos2),Number.isNaN(e)||e<0)return void n.itd.badlines.push([t,"invalid chr_stop value",i]);s.chrpos2=e}if(!o.EJ(s,n,t,i,n.itd.badlines)){s.dt=r.dtitd,s.class=r.mclassitd,s.mname="ITD",n.good++;var a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}}else n.itd.badlines.push([t,"missing gene",i])}},8064:(t,e,n)=>{"use strict";n.d(e,{Dz:()=>o,EJ:()=>i});var r=n(2273);function o(t){if(!t)return null;const e={};for(const t in r.mclass)e[r.mclass[t].label.toUpperCase()]=t;return{genome:t,mclasslabel2key:e,data:{},sample2disease:{},patient2st:{},good:0,geneToUpper:!0,snv:{loaded:!1,header:null,badlines:[],missense:0,silent:0},svjson:{loaded:!1,header:null,badlines:[]},fusion:{loaded:!1,header:null,badlines:[],original:[]},sv:{loaded:!1,header:null,badlines:[],original:[]},cnv:{loaded:!1,header:null,badlines:[]},itd:{loaded:!1,header:null,badlines:[]},del:{loaded:!1,header:null,badlines:[]},truncation:{loaded:!1,header:null,badlines:[]}}}function i(t,e,n,o,i){let s=r.moriginsomatic;if(t.sampletype){switch(t.sampletype.toLowerCase()){case"relapse":s=r.moriginrelapse;break;case"germline":s=r.morigingermline}t.sample?t.patient||(t.patient=t.sample+" "+t.sampletype):t.patient&&(t.sample=t.patient+" "+t.sampletype)}else t.patient?t.sample?t.sampletype=t.sample:t.sample=t.sampletype=t.patient:t.sample&&(t.sampletype=t.sample);if(t.origin){switch(t.origin.toLowerCase()){case"r":case"relapse":s=r.moriginrelapse,t.isrim2=!0;break;case"g":case"germline":s=r.morigingermline,t.isrim1=!0;break;case"gp":case"germline pathogenic":s=r.morigingermlinepathogenic,t.isrim1=!0;break;case"gnp":case"germline nonpathogenic":case"germline non-pathogenic":s=r.morigingermlinenonpathogenic,t.isrim1=!0;break;case"s":case"somatic":case"diagnosis":s=r.moriginsomatic}}if(t.origin=s,!t.sample&&!t.patient)return;const a="no patient/individual name";if(t.patient?(e.patient2st[t.patient]||(e.patient2st[t.patient]={}),e.patient2st[t.patient][t.sampletype]=t.sample):(e.patient2st[a]||(e.patient2st[a]={}),e.patient2st[a][t.sampletype]=t.sample),t.sample&&t.disease)if(t.sample in e.sample2disease){if(t.disease!=e.sample2disease[t.sample])return e.snv.badlines.push([n,'conflict of disease types for sample "'+t.sample+'": '+t.disease+", "+e.sample2disease[t.sample],o]),!0}else e.sample2disease[t.sample]=t.disease;return!1}},5494:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for snv/indel";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("annovar_gene","annovar_sj_gene","gene","genename","gene_symbol","hugo_symbol");return-1==o?"gene missing from header":(n[o]="gene",o=r("annovar_aachange","amino_acid_change","annovar_sj_aachange","aachange","protein_change","variant"),-1==o?"amino_acid_change missing from header":(n[o]="mname",o=r("annovar_class","class","mclass","variant_class","variant_classification","annovar_sj_class"),-1==o?"variant_class missing from header":(n[o]="class",o=r("chromosome","chr"),-1==o?"chromosome missing from header":(n[o]="chr",o=r("wu_hg19_pos","start","start_position","chr_position","position"),-1==o?"start missing from header":(n[o]="pos",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o?"isoform missing from header":(n[o]="isoform",o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("quantitative_measurements"),-1!=o&&(n[o]="qmset"),o=r("mutant_reads_in_case","mutant_in_tumor","tumor_readcount_alt"),-1!=o&&(n[o]="maf_tumor_v1"),o=r("total_reads_in_case","total_in_tumor","tumor_readcount_total"),-1!=o&&(n[o]="maf_tumor_v2"),o=r("mutant_reads_in_control","mutant_in_normal","normal_readcount_alt"),-1!=o&&(n[o]="maf_normal_v1"),o=r("total_reads_in_control","total_in_normal","normal_readcount_total"),-1!=o&&(n[o]="maf_normal_v2"),o=r("cdna_change"),-1!=o&&(n[o]="cdna_change"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("cancer","disease","diagnosis"),-1!=o&&(n[o]="disease"),e.snv.header=n,e.snv.loaded=!0,!1))))))}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.snv.header.length&&null!=i[t];t++)s[n.snv.header[t]]=i[t];if(!s.gene)return void n.snv.badlines.push([t,"missing gene",i]);if("UNKNOWN"==s.gene.toUpperCase())return void n.snv.badlines.push([t,"gene name is UNKNOWN",i]);if(!s.isoform)return void n.snv.badlines.push([t,"missing isoform",i]);if(s.mname)0==s.mname.indexOf("p.")&&(s.mname=s.mname.replace(/^p\./,""));else if(s.mname=s.cdna_change,!s.mname)return void n.snv.badlines.push([t,"missing amino acid change",i]);if(!s.class)return void n.snv.badlines.push([t,"missing mutation class",i]);let a=n.mclasslabel2key[s.class.toUpperCase()];if(a)s.class=a;else{if(a=r.mclasstester(s.class),!a)return void n.snv.badlines.push([t,"wrong mutation class: "+s.class,i]);s.class=a}if(o.EJ(s,n,t,i,n.snv.badlines))return;if(!s.chr)return void n.snv.badlines.push([t,"missing chromosome",i]);if(0!=s.chr.toLowerCase().indexOf("chr")&&(s.chr="chr"+s.chr),!s.pos)return void n.snv.badlines.push([t,"missing chromosome position",i]);const l=Number.parseInt(s.pos);if(Number.isNaN(l))return void n.snv.badlines.push([t,"invalid chromosome position",i]);if(s.pos=l-1,null!=s.maf_tumor_v2&&null!=s.maf_tumor_v1){if(""==s.maf_tumor_v2);else{let e=Number.parseInt(s.maf_tumor_v1),r=Number.parseInt(s.maf_tumor_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_tumor mutant and/or total read count",i]);s.maf_tumor={f:e/r,v1:e,v2:r}}delete s.maf_tumor_v1,delete s.maf_tumor_v2}if(null!=s.maf_normal_v1&&null!=s.maf_normal_v2){if(""==s.maf_normal_v2);else{let e=Number.parseInt(s.maf_normal_v1),r=Number.parseInt(s.maf_normal_v2);if(Number.isNaN(e)||Number.isNaN(r))return void n.snv.badlines.push([t,"invalid maf_normal mutant and/or total read count",i]);s.maf_normal={f:e/r,v1:e,v2:r}}delete s.maf_normal_v1,delete s.maf_normal_v2}n.good++,"M"==s.class?n.snv.missense++:"S"==s.class&&n.snv.silent++;const c=n.geneToUpper?s.gene.toUpperCase():s.gene;n.data[c]||(n.data[c]=[]),s.dt=r.dtsnvindel,n.data[c].push(s)}},6279:(t,e,n)=>{"use strict";n.r(e),n.d(e,{duplicate:()=>a,parseheader:()=>i,parseline:()=>s});var r=n(8064),o=n(2273);function i(t,e,n){const r=t.toLowerCase().split("\t");if(r.length<=1)return"invalid file header for fusions";const o=(...t)=>{for(const e of t){const t=r.indexOf(e);if(-1!=t)return t}return-1};let i=o("gene_a","gene1","genea");return-1==i?"gene_a missing from header":(r[i]="gene1",i=o("gene_b","gene2","geneb"),-1==i?"gene_b missing from header":(r[i]="gene2",i=o("chr_a","chr1","chra"),-1==i?"chr_a missing from header":(r[i]="chr1",i=o("chr_b","chr2","chrb"),-1==i?"chr_b missing from header":(r[i]="chr2",i=o("pos_a","position_a","position1","posa"),-1==i?"pos_a missing from header":(r[i]="position1",i=o("pos_b","position_b","position2","posb"),-1==i?"pos_b missing from header":(r[i]="position2",i=o("isoform_a","refseq_a","refseq1","isoform1","sv_refseqa"),-1==i?"isoform_a missing from header":(r[i]="isoform1",i=o("isoform_b","refseq_b","refseq2","isoform2","sv_refseqb"),-1==i?"isoform_b missing from header":(r[i]="isoform2",i=o("strand_a","orta"),-1==i?"strand_a missing from header":(r[i]="strand1",i=o("strand_b","ortb"),-1==i?"strand_b missing from header":(r[i]="strand2",i=o("sample","sample_name","tumor_sample_barcode"),-1!=i&&(r[i]="sample"),i=o("patient","donor","target_case_id"),-1!=i&&(r[i]="patient"),i=o("sampletype","sample type","sample_type"),-1!=i&&(r[i]="sampletype"),i=o("disease"),-1!=i&&(r[i]="disease"),i=o("origin"),-1!=i&&(r[i]="origin"),n?(e.sv.loaded=!0,e.sv.header=r):(e.fusion.loaded=!0,e.fusion.header=r),!1))))))))))}function s(t,e,n,i){if(""==e||"#"==e[0])return;const s=e.split("\t"),a={},l=i?n.sv.header:n.fusion.header,c=i?n.sv.badlines:n.fusion.badlines;for(let t=0;t<l.length;t++)a[l[t]]=s[t];if(!a.chr1)return void c.push([t,"missing chr1",s]);if(0!=a.chr1.toLowerCase().indexOf("chr")&&(a.chr1="chr"+a.chr1),!a.chr2)return void c.push([t,"missing chr2",s]);0!=a.chr2.toLowerCase().indexOf("chr")&&(a.chr2="chr"+a.chr2);let u=a.position1;if(!u)return void c.push([t,"missing position1",s]);let f=Number.parseInt(u);if(Number.isNaN(f)||f<=0)c.push([t,"invalid value for position1",s]);else if(a.position1=f,u=a.position2,u){if(f=Number.parseInt(u),Number.isNaN(f)||f<=0)c.push([t,"invalid value for position2",s]);else if(a.position2=f,!r.EJ(a,n,t,s,c)){if(a.isoform1&&-1!=a.isoform1.indexOf(",")){const t=a.isoform1.split(",");a.isoform1=void 0;for(const e of t)""!=e&&(a.isoform1=e)}if(a.isoform2&&-1!=a.isoform2.indexOf(",")){const t=a.isoform2.split(",");a.isoform2=void 0;for(const e of t)""!=e&&(a.isoform2=e)}if(a.gene1||(a.isoform1=void 0),a.gene2||(a.isoform2=void 0),a.gene1){n.good++;const t={dt:i?o.dtsv:o.dtfusionrna,class:i?o.mclasssv:o.mclassfusionrna,isoform:a.isoform1,mname:a.gene2||a.chr2,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},e=n.geneToUpper?a.gene1.toUpperCase():a.gene1;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}if(a.gene2&&a.gene2!=a.gene1){n.good++;const t={dt:i?o.dtsv:o.dtfusionrna,class:i?o.mclasssv:o.mclassfusionrna,isoform:a.isoform2,mname:a.gene1||a.chr1,sample:a.sample,patient:a.patient,sampletype:a.sampletype,origin:a.origin,disease:a.disease,pairlst:[{a:{name:a.gene1,isoform:a.isoform1,strand:a.strand1,chr:a.chr1,position:a.position1},b:{name:a.gene2,isoform:a.isoform2,strand:a.strand2,chr:a.chr2,position:a.position2}}]},e=n.geneToUpper?a.gene2.toUpperCase():a.gene2;n.data[e]||(n.data[e]=[]),n.data[e].push(t)}}}else c.push([t,"missing position2",s])}function a(t){const e={};for(const n in t){if("pairlst"==n)continue;const r=t[n];"object"!=typeof r&&(e[n]=r)}if(t.pairlst){e.pairlst=[];for(const n of t.pairlst){const t={};for(const e in n)"a"!=e&&"b"!=e&&"interstitial"!=e&&(t[e]=n[e]);if(n.a){t.a={};for(const e in n.a){const r=n.a[e];"object"!=typeof r&&(t.a[e]=r)}}if(n.b){t.b={};for(const e in n.b){const r=n.b[e];"object"!=typeof r&&(t.b[e]=r)}}if(n.interstitial){t.interstitial={};for(const e in n.interstitial){const r=n.interstitial[e];"object"!=typeof r&&(t.interstitial[e]=r)}}e.pairlst.push(t)}}return e}},8423:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid file header for svjson";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("sample");return-1!=o&&(n[o]="sample"),o=r("sampletype"),-1!=o&&(n[o]="sampletype"),o=r("patient"),-1!=o&&(n[o]="patient"),o=r("json","jsontext"),-1==o?["json missing from header"]:(n[o]="jsontext",[null,n])}function s(t,e,n,i){if(""==e||"#"==e[0])return;const s=e.split("\t"),l={},c=n.svjson.badlines;for(let t=0;t<i.length;t++)l[i[t]]=s[t];if(!l.jsontext)return void c.push([t,"missing jsontext",s]);if(o.EJ(l,n,t,s,c))return;let u;try{u=JSON.parse(l.jsontext)}catch(e){return void c.push([t,"invalid JSON text",s])}if(Array.isArray(u))for(const t of u){if(t.a&&t.a.name&&t.a.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.a.isoform,mname:t.b.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const o=t.a.name.toUpperCase();n.data[o]||(n.data[o]=[]),n.data[o].push(e)}if(t.b&&t.b.name&&t.b.isoform){n.good++;const e={dt:r.dtfusionrna,class:r.mclassfusionrna,isoform:t.b.isoform,mname:t.a.name};for(const t in l)"jsontext"!=t&&(e[t]=l[t]);e.pairlst=a(u);const o=t.b.name.toUpperCase();n.data[o]||(n.data[o]=[]),n.data[o].push(e)}}else{switch(u.dt=u.typecode,delete u.typecode,u.dt){case r.dtitd:u.class=r.mclassitd,u.mname="ITD";break;case r.dtnloss:u.class=r.mclassnloss,u.mname="N-loss";break;case r.dtcloss:u.class=r.mclasscloss,u.mname="C-loss";break;case r.dtdel:u.class=r.mclassdel,u.mname="Del";break;case r.dtsv:u.class=r.mclasssv,u.mname="SV";break;default:return void c.push([t,"unknown datatype",s])}if(!u.gene)return void c.push([t,"json.gene missing",s]);n.good++;for(const t in l)"jsontext"!=t&&(u[t]=l[t]);const e=(n.geneToUpper,u.gene.toUpperCase());n.data[e]||(n.data[e]=[]),n.data[e].push(u)}}function a(t){const e=[];for(const n of t){const t={a:{},b:{}};for(const e in n)"a"!=e&&"b"!=e&&(t[e]=n[e]);for(const e in n.a)t.a[e]=n.a[e];for(const e in n.b)t.b[e]=n.b[e];e.push(t)}return e}},8235:(t,e,n)=>{"use strict";n.r(e),n.d(e,{parseheader:()=>i,parseline:()=>s});var r=n(2273),o=n(8064);function i(t,e){const n=t.toLowerCase().split("\t");if(n.length<=1)return"invalid header line for truncation";const r=(...t)=>{for(const e of t){const t=n.indexOf(e);if(-1!=t)return t}return-1};let o=r("gene");if(-1==o)return"gene missing from header";if(n[o]="gene",o=r("annovar_isoform","mrna_accession","mrna accession","refseq_mrna_id","annovar_sj_filter_isoform","refseq","isoform"),-1==o)return"isoform missing from header";n[o]="isoform";let i=!1;if(o=r("rnaposition"),-1!=o&&(n[o]="rnaposition",i=!0),o=r("losstype"),-1==o)return"lossType missing from header";n[o]="losstype";let s=!1;if(o=r("chromosome","chr"),-1!=o){if(n[o]="chr",o=r("start","start_position","wu_hg19_pos","chr_position","position"),-1==o)return"genomic position missing from header";n[o]="pos",s=!0}return i||s?(o=r("sample","sample_name","tumor_sample_barcode"),-1!=o&&(n[o]="sample"),o=r("patient","donor","target_case_id"),-1!=o&&(n[o]="patient"),o=r("disease"),-1!=o&&(n[o]="disease"),o=r("origin"),-1!=o&&(n[o]="origin"),o=r("sampletype","sample type","sample_type"),-1!=o&&(n[o]="sampletype"),e.truncation.header=n,e.truncation.loaded=!0,!1):"neither rnaposition nor genomic position is given"}function s(t,e,n){if(""==e||"#"==e[0])return;const i=e.split("\t"),s={};for(let t=0;t<n.truncation.header.length;t++)s[n.truncation.header[t]]=i[t];if(!s.gene)return void n.truncation.badlines.push([t,"missing gene",i]);if(s.rnaposition){const e=Number.parseInt(s.rnaposition);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid rnaPosition value",i]);s.rnaposition=e}if(s.pos){const e=Number.parseInt(s.pos);if(Number.isNaN(e)||e<0)return void n.truncation.badlines.push([t,"invalid genomic position",i]);s.pos=e}if(!s.losstype)return void n.truncation.badlines.push([t,"missing lossType value",i]);if("n"!=s.losstype&&"c"!=s.losstype)return void n.truncation.badlines.push([t,'lossType value not "n" or "c"',i]);if(o.EJ(s,n,t,i,n.truncation.badlines))return;"n"==s.losstype?(s.dt=r.dtnloss,s.class=r.mclassnloss,s.mname="N-loss"):(s.dt=r.dtcloss,s.class=r.mclasscloss,s.mname="C-loss"),n.good++;const a=n.geneToUpper?s.gene.toUpperCase():s.gene;a in n.data||(n.data[a]=[]),n.data[a].push(s)}},2273:(t,e,n)=>{"use strict";n.r(e),n.d(e,{IN_frame:()=>c,OUT_frame:()=>u,alleleInGenotypeStr:()=>ht,applyOverrides:()=>Z,basecolor:()=>ot,basecompliment:()=>it,bplen:()=>rt,codon:()=>tt,codon_stop:()=>et,contigNameNoChr:()=>ut,contigNameNoChr2:()=>ft,custommdstktype:()=>Q,default_text_color:()=>a,defaultcolor:()=>s,dt2label:()=>_,dtcloss:()=>b,dtcnv:()=>p,dtdel:()=>y,dtfusionrna:()=>d,dtgeneexpression:()=>h,dtitd:()=>g,dtloh:()=>w,dtnloss:()=>v,dtsnvindel:()=>f,dtsv:()=>m,exoncolor:()=>l,fasta2gmframecheck:()=>lt,germlinelegend:()=>U,getColorScheme:()=>_t,getColors:()=>xt,getMax_byiqr:()=>dt,gmmode:()=>pt,kernelDensityEstimator:()=>yt,kernelEpanechnikov:()=>vt,mclass:()=>x,mclasscloss:()=>S,mclasscnvgain:()=>I,mclasscnvloh:()=>P,mclasscnvloss:()=>R,mclassdel:()=>q,mclassdeletion:()=>$,mclassfusionrna:()=>E,mclassinsertion:()=>L,mclassitd:()=>k,mclassmnv:()=>D,mclassnloss:()=>N,mclassnoncoding:()=>C,mclassnonstandard:()=>T,mclasssnv:()=>F,mclasssv:()=>O,mclasstester:()=>j,mclassutr3:()=>A,mclassutr5:()=>M,mdsvcftype:()=>X,morigin:()=>B,morigingermline:()=>J,morigingermlinenonpathogenic:()=>V,morigingermlinepathogenic:()=>H,moriginrelapse:()=>W,moriginsomatic:()=>G,not_annotated:()=>gt,nt2aa:()=>nt,proteinChangingMutations:()=>qt,reversecompliment:()=>st,schemeCategory2:()=>wt,schemeCategory20:()=>bt,spliceeventchangegmexon:()=>at,tkt:()=>Y,truncatingMutations:()=>kt,validate_vcfinfofilter:()=>ct,validtkt:()=>K,vcfcopymclass:()=>mt,vepinfo:()=>z});var r=n(1495);const o=n(4635),i=n(3016),s=(0,r.B8)("#8AB1D4").darker(),a=(0,r.B8)("#aaa").darker().darker(),l="#4F8053",c=!0,u=!1,f=1,d=2,h=3,p=4,m=5,g=6,y=7,v=8,b=9,w=10,_={[f]:"SNV/indel",[d]:"Fusion RNA",[p]:"CNV",[m]:"SV",[g]:"ITD",[y]:"Deletion",[v]:"N-loss",[b]:"C-loss",[w]:"LOH",[h]:"Gene Expression"},x={M:{label:"MISSENSE",color:"#3987CC",dt:f,desc:"A substitution variant in the coding region resulting in altered protein coding.",key:"M"},E:{label:"EXON",color:"#bcbd22",dt:f,desc:"A variant in the exon of a non-coding RNA.",key:"E"},F:{label:"FRAMESHIFT",color:"#db3d3d",dt:f,desc:"An insertion or deletion variant that alters the protein coding frame.",key:"F"},N:{label:"NONSENSE",color:"#ff7f0e",dt:f,desc:"A variant altering protein coding to produce a premature stopgain or stoploss.",key:"N"},S:{label:"SILENT",color:"#2ca02c",dt:f,desc:"A substitution variant in the coding region that does not alter protein coding.",key:"S"},D:{label:"PROTEINDEL",color:"#7f7f7f",dt:f,desc:"A deletion resulting in a loss of one or more codons from the product, but not altering the protein coding frame.",key:"D"},I:{label:"PROTEININS",color:"#8c564b",dt:f,desc:"An insertion introducing one or more codons into the product, but not altering the protein coding frame.",key:"I"},P:{label:"SPLICE_REGION",color:"#9467bd",dt:f,desc:"A variant in an intron within 10 nt of an exon boundary.",key:"P"},L:{label:"SPLICE",color:"#6633FF",dt:f,desc:"A variant near an exon edge that may affect splicing functionality.",key:"L"},Intron:{label:"INTRON",color:"#656565",dt:f,desc:"An intronic variant.",key:"Intron"},Blank:{label:"Not tested",color:"#fff",dt:f,desc:"This gene is not tested.",key:"Blank"},WT:{label:"Wildtype",color:"#D3D3D3",dt:f,desc:"Wildtype",key:"WT"}},k="ITD";x[k]={label:"ITD",color:"#ff70ff",dt:g,desc:"In-frame internal tandem duplication.",key:k};const q="DEL";x[q]={label:"DELETION, intragenic",color:"#858585",dt:y,desc:"Intragenic deletion.",key:q};const N="NLOSS";x[N]={label:"N-terminus loss",color:"#545454",dt:v,desc:"N-terminus loss due to translocation",key:N};const S="CLOSS";x[S]={label:"C-terminus loss",color:"#545454",dt:b,desc:"C-terminus loss due to translocation",key:S};const A="Utr3";x[A]={label:"UTR_3",color:"#998199",dt:f,desc:"A variant in the 3' untranslated region.",key:A};const M="Utr5";x[M]={label:"UTR_5",color:"#819981",dt:f,desc:"A variant in the 5' untranslated region.",key:M};const T="X";x[T]={label:"NONSTANDARD",color:"black",dt:f,desc:"A mutation class that either does not match our notation, or is unspecified.",key:T};const C="noncoding";function j(t){switch(t.toLowerCase()){case"missense_mutation":return"M";case"nonsense_mutation":case"nonstop_mutation":return"N";case"splice_site":return"L";case"rna":case"3'flank":case"5'flank":return C;case"frame_shift_del":case"frame_shift_ins":return"F";case"in_frame_del":return"D";case"in_frame_ins":return"I";case"translation_start_site":return T;case"3'utr":return A;case"5'utr":return M;case"blank":return"Blank";default:return null}}x[C]={label:"NONCODING",color:"black",dt:f,desc:"Noncoding mutation.",key:C};const E="Fuserna";x[E]={label:"Fusion transcript",color:"#545454",dt:d,desc:"Marks the break points leading to fusion transcripts.<br><span style=\"font-size:150%\">◐</span> - 3' end of the break point is fused to the 5' end of another break point in a different gene.<br><span style=\"font-size:150%\">◑</span> - 5' end of the break point is fused to the 3' end of another break point in a different gene.",key:E};const O="SV";x[O]={label:"Structural variation",color:"#858585",dt:m,desc:"Structural variation detected in genomic DNA.",key:O};const I="CNV_amp";x[I]={label:"Copy number gain",color:"#e9a3c9",dt:p,desc:"Copy number gain",key:I};const R="CNV_loss";x[R]={label:"Copy number loss",color:"#a1d76a",dt:p,desc:"Copy number loss",key:R};const P="CNV_loh";x[P]={label:"LOH",color:"#12EDFC",dt:p,desc:"Loss of heterozygosity",key:P};const F="snv";x[F]={label:"SNV",color:"#92a2d4",dt:f,desc:"Single nucleotide variation",key:F};const D="mnv";x[D]={label:"MNV",color:"#92a2d4",dt:f,desc:"Multiple nucleotide variation",key:D};const L="insertion";x[L]={label:"Sequence insertion",color:"#bd8e91",dt:f,desc:"Sequence insertion",key:L};const $="deletion";function Z(t={}){if(t.mclass)for(const e in t.mclass){x[e]||(x[e]={});for(const n in t.mclass[e])x[e][n]=t.mclass[e][n]}}x[$]={label:"Sequence deletion",color:"#b5a174",dt:f,desc:"Sequence deletion",key:$};const z=function(t){const e=t.toLowerCase().split(",");let n=1;return-1!=e.indexOf("transcript_ablation")?[y,q,n]:(n++,-1!=e.indexOf("splice_acceptor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("splice_donor_variant")?[f,"L",n]:(n++,-1!=e.indexOf("stop_gained")?[f,"N",n]:(n++,-1!=e.indexOf("frameshift_variant")?[f,"F",n]:(n++,-1!=e.indexOf("stop_lost")?[f,"N",n]:(n++,-1!=e.indexOf("start_lost")?[f,"N",n]:(n++,-1!=e.indexOf("transcript_amplification")?[f,T,n]:(n++,-1!=e.indexOf("inframe_insertion")||-1!=e.indexOf("conservative_inframe_insertion")||-1!=e.indexOf("disruptive_inframe_insertion")?[f,"I",n]:(n++,-1!=e.indexOf("inframe_deletion")||-1!=e.indexOf("conservative_inframe_deletion")||-1!=e.indexOf("disruptive_inframe_deletion")?[f,"D",n]:(n++,-1!=e.indexOf("missense_variant")?[f,"M",n]:(n++,-1!=e.indexOf("protein_altering_variant")?[f,"N",n]:(n++,-1!=e.indexOf("splice_region_variant")?[f,"P",n]:(n++,-1!=e.indexOf("incomplete_terminal_codon_variant")?[f,"N",n]:(n++,-1!=e.indexOf("stop_retained_variant")?[f,"S",n]:(n++,-1!=e.indexOf("synonymous_variant")?[f,"S",n]:(n++,-1!=e.indexOf("coding_sequence_variant")?[f,T,n]:(n++,-1!=e.indexOf("mature_mirna_variant")?[f,"E",n]:(n++,-1!=e.indexOf("5_prime_utr_variant")?[f,M,n]:(n++,-1!=e.indexOf("3_prime_utr_variant")?[f,A,n]:(n++,-1!=e.indexOf("non_coding_transcript_exon_variant")?[f,"E",n]:(n++,-1!=e.indexOf("intron_variant")?[f,"Intron",n]:(n++,-1!=e.indexOf("nmd_transcript_variant")?[f,"S",n]:(n++,-1!=e.indexOf("non_coding_transcript_variant")?[f,"E",n]:(n++,-1!=e.indexOf("upstream_gene_variant")?[f,C,n]:(n++,-1!=e.indexOf("downstream_gene_variant")?[f,C,n]:(n++,-1!=e.indexOf("tfbs_ablation")?[f,C,n]:(n++,-1!=e.indexOf("tfbs_amplification")?[f,C,n]:(n++,-1!=e.indexOf("tf_binding_site_variant")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_ablation")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_amplification")?[f,C,n]:(n++,-1!=e.indexOf("feature_elongation")?[f,C,n]:(n++,-1!=e.indexOf("regulatory_region_variant")?[f,C,n]:(n++,-1!=e.indexOf("feature_truncation")?[f,C,n]:(n++,-1!=e.indexOf("intergenic_variant")?[f,C,n]:(n++,[f,T,n])))))))))))))))))))))))))))))))))))},U='<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="#858585" stroke="none"></path>',B={},G="S";B[G]={label:"Somatic",desc:"A variant found only in a tumor sample. The proportion is indicated by lack of any arc.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle>'};const J="G";B[J]={label:"Germline",desc:"A constitutional variant found in a normal sample. The proportion is indicated by the span of the solid arc within the whole circle.",legend:U},B.germline=B[J],B.somatic=B[G];const W="R";B[W]={label:"Relapse",desc:"A somatic variant found only in a relapse sample. The proportion is indicated by the span of the hollow arc within the whole circle.",legend:'<circle cx="7" cy="12" r="7" fill="#b1b1b1"></circle><path d="M6.735557395310443e-16,-11A11,11 0 0,1 11,0L9,0A9,9 0 0,0 5.51091059616309e-16,-9Z" transform="translate(7,12)" fill="none" stroke="#858585"></path>'};const H="GP";B[H]={label:"Germline pathogenic",desc:"A constitutional variant with pathogenic allele.",legend:U};const V="GNP";B[V]={label:"Germline non-pathogenic",desc:"A constitutional variant with non-pathogenic allele.",legend:U,hidden:!0};const Y={usegm:"usegm",ds:"dataset",bigwig:"bigwig",bigwigstranded:"bigwigstranded",junction:"junction",mdsjunction:"mdsjunction",mdscnv:"mdscnv",mdssvcnv:"mdssvcnv",mdsexpressionrank:"mdsexpressionrank",mdsvcf:"mdsvcf",bedj:"bedj",pgv:"profilegenevalue",bampile:"bampile",hicstraw:"hicstraw",expressionrank:"expressionrank",aicheck:"aicheck",ase:"ase",mds2:"mds2",mds3:"mds3",bedgraphdot:"bedgraphdot",bam:"bam",ld:"ld"};function K(t){for(const e in Y)if(t==Y[e])return!0;return!1}const X={vcf:"vcf"},Q={vcf:"vcf",svcnvitd:"svcnvitd",geneexpression:"geneexpression"},tt={GCT:"A",GCC:"A",GCA:"A",GCG:"A",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGA:"R",AGG:"R",AAT:"N",AAC:"N",GAT:"D",GAC:"D",TGT:"C",TGC:"C",CAA:"Q",CAG:"Q",GAA:"E",GAG:"E",GGT:"G",GGC:"G",GGA:"G",GGG:"G",CAT:"H",CAC:"H",ATT:"I",ATC:"I",ATA:"I",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",AAA:"K",AAG:"K",ATG:"M",TTT:"F",TTC:"F",CCT:"P",CCC:"P",CCA:"P",CCG:"P",TCT:"S",TCC:"S",TCA:"S",TCG:"S",AGT:"S",AGC:"S",ACT:"T",ACC:"T",ACA:"T",ACG:"T",TGG:"W",TAT:"Y",TAC:"Y",GTT:"V",GTC:"V",GTA:"V",GTG:"V"},et="*";function nt(t){if(!t.genomicseq)return;const e=[];if(t.coding)for(const[n,r]of t.coding.entries()){const n=t.genomicseq.substr(r[0]-t.start,r[1]-r[0]);"-"==t.strand?e.push(st(n)):e.push(n)}const n=e.join(""),r=[];for(let e=t.startCodonFrame?3-t.startCodonFrame:0;e<n.length;e+=3){const t=tt[n.substr(e,3)];r.push(t||et)}return t.cdseq=n,r.join("")}function rt(t,e){return t>=1e9?(t/1e9).toFixed(1)+" Gb":t>=1e7?Math.ceil(t/1e6)+" Mb":t>=1e6?(t/1e6).toFixed(1)+" Mb":t>=1e4?Math.ceil(t/1e3)+" Kb":t>=1e3?(t/1e3).toFixed(1)+" Kb":t+(e?"bytes":" bp")}const ot={A:"#ca0020",T:"#f4a582",C:"#92c5de",G:"#0571b0"};function it(t){switch(t){case"A":return"T";case"T":return"A";case"C":return"G";case"G":return"C";case"a":return"t";case"t":return"a";case"c":return"g";case"g":return"c";default:return t}}function st(t){const e=[];for(let n=t.length-1;n>=0;n--)e.push(it(t[n]));return e.join("")}function at(t,e){const n={chr:t.chr,start:t.start,stop:t.stop,strand:t.strand,coding:[]};if(e.isskipexon||e.isaltexon)for(let r=0;r<t.exon.length;r++){const o=Math.max(t.codingstart,t.exon[r][0]),i=Math.min(t.codingstop,t.exon[r][1]);o>i||-1==e.skippedexon.indexOf(r)&&n.coding.push([o,i])}else if(e.a5ss||e.a3ss){const r=t.exon.map((t=>[t[0],t[1]])),o="+"==t.strand;e.a5ss?o?r[e.exon5idx][1]=e.junctionB.start:r[e.exon5idx+1][0]=e.junctionB.stop:o?r[e.exon5idx+1][0]=e.junctionB.stop:r[e.exon5idx][1]=e.junctionB.start;for(const e of r){const r=Math.max(t.codingstart,e[0]),o=Math.min(t.codingstop,e[1]);r>o||n.coding.push([r,o])}}return n}function lt(t,e){const n=e.split("\n");n.shift(),t.genomicseq=n.join("").toUpperCase();const r=nt(t);let o=u;return r.indexOf(et)==r.length-1&&(o=c),o}function ct(t){if(!t.lst)return".lst missing";if(!Array.isArray(t.lst))return"input is not an array";for(const e of t.lst){if(!e.name)return"name missing from a set of .vcfinfofilter.lst";if(e.autocategory||e.categories){if(!e.autocategory)for(const t in e.categories){const n=e.categories[t];if(!e.autocolor&&!n.color)return".color missing for class "+t+" from .categories of set "+e.name;n.label||(n.label=t)}if(e.categoryhidden){for(const t in e.categoryhidden)if(!e.categories[t])return"unknown hidden-by-default category "+t+" from set "+e.name}else e.categoryhidden={}}else if(e.numericfilter){const t=[];for(const n of e.numericfilter)"number"==typeof n?t.push({side:"<",value:n}):t.push({side:n.side||"<",value:n.value});e.numericfilter=t}if(e.altalleleinfo){if(!e.altalleleinfo.key)return".key missing from .altalleleinfo from set "+e.name}else{if(!e.locusinfo)return"neither .altalleleinfo or .locusinfo is available from set "+e.name;if(!e.locusinfo.key)return".key missing from .locusinfo from set "+e.name}}}function ut(t,e){for(const n in t.majorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;if(t.minorchr)for(const n in t.minorchr)if(-1!=e.indexOf(n.replace("chr","")))return!0;return!1}function ft(t,e){let n=0,r=0;for(const o in t.majorchr)e.includes(o)?r++:e.includes(o.replace("chr",""))&&n++;if(t.minorchr)for(const o in t.minorchr)e.includes(o)?r++:e.includes(o.replace("chr",""))&&n++;return[n,r]}function dt(t,e){if(0==t.length)return e;t.sort(((t,e)=>t-e));const n=t[t.length-1];if(t.length<=5)return n;const r=t[Math.floor(t.length/4)],o=t[Math.floor(3*t.length/4)];return Math.min(o+1.5*(o-r),n)}function ht(t,e){return!!t&&(-1!=t.indexOf("/")?-1!=t.split("/").indexOf(e):-1!=t.split("|").indexOf(e))}const pt={genomic:"genomic",splicingrna:"splicing RNA",exononly:"exon only",protein:"protein",gmsum:"aggregated exons"};function mt(t,e){if(t.csq){let n;if(e.usegm&&(n=t.csq.find((t=>t._isoform==e.usegm.isoform))),!n&&(n=t.csq.find((t=>t.CANONICAL)),!n)){n=t.csq[0];for(const e of t.csq)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==C&&delete t.class)}else if(t.ann){let n=null;if(e.usegm){for(const r of t.ann)r._isoform==e.usegm.isoform&&(n?r._csqrank<n._csqrank&&(n=r):n=r);n||e.gmmode!=pt.genomic||(n=t.ann[0])}else{n=t.ann[0];for(const e of t.ann)e._csqrank<n._csqrank&&(n=e)}n&&(t.gene=n._gene,t.isoform=n._isoform,t.class=n._class,t.dt=n._dt,t.mname=n._mname,t.class==C&&delete t.class)}null==t.class&&(x[t.type]?(t.class=t.type,t.dt=x[t.type].dt,t.mname=t.id&&"."!=t.id?t.id:t.ref+">"+t.alt,t.mname.length>15&&(t.mname=t.type)):(t.class=T,t.dt=f,t.mname=t.type)),delete t.type}const gt="Unannotated";function yt(t,e){return function(n){return e.map((e=>[e,n.map((n=>t(e-n))).reduce(((t,e)=>t+e),0)/n.length]))}}function vt(t){return function(e){return Math.abs(e/=t)<=1?.75*(1-e*e)/t:0}}const bt=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],wt=["#e75480","blue"];function _t(t){return t>12?bt:t>8?i.schemePaired:t>2?i.schemeDark2:wt}function xt(t){return o.scaleOrdinal(_t(t))}const kt=["F","N","D","I","L"],qt=["F","N","D","I","L","M","P"]},7027:(t,e,n)=>{"use strict";function r(t,e){t.sort(((t,e)=>t-e));const n=Math.abs(e/100*t.length-1);return Number.isInteger(n)?(t[n]+t[n+1])/2:t[Math.ceil(n)]}n.d(e,{Z:()=>r})},478:(t,e,n)=>{"use strict";function r(t){if(!t||0==t.length)return;let e=JSON.parse(JSON.stringify(t[0]));if(1==t.length)return e;if(e.lst.length<2){if(""!==e.join)throw'filter.join must be an empty string "" when filter.lst.length < 2';e.join="and"}else if("or"==e.join)e={type:"tvslst",join:"and",in:!0,lst:[e]};else if("and"!=e.join)throw'filter.join must be either "and" or "or" when .lst length > 1';for(let n=1;n<t.length;n++){const r=JSON.parse(JSON.stringify(t[n]));"or"==r.join?e.lst.push(r):e.lst.push(...r.lst)}return 1==e.lst.length&&"tvs"==e.lst[0].type&&(e.join=""),e}n.d(e,{xH:()=>r})},5684:(t,e,n)=>{"use strict";function r(t,e){const n=Number(t);return Number.isInteger(n)?n:Math.abs(n)<1?Number(n.toPrecision(e)):Number(n.toFixed(e))}n.d(e,{Z:()=>r})},4048:(t,e,n)=>{"use strict";n.d(e,{gp:()=>a});var r=n(2163),o=n(2273);function i(t){return!isNaN(parseFloat(t))&&isFinite(t)}function s(t,e,n,r,o){if(r>=1){const e=Math.floor(t*r);return o?`${e}${n.charAt(0)}`:`${e} ${e>1?n+"s":""}`}const i=Math.floor(t*r),s=Math.ceil(t%(1/r));return 0==s?o?`${i}${n.charAt(0)}`:`${i} ${i>1?n+"s":""}`:o?`${i}${n.charAt(0)}${s}${e.charAt(0)}`:`${i} ${i>1?n+"s":""} ${s} ${s>1?e+"s":""}`}function a(t,e,n){const r=t;if(function(t){const e=t;if(!e||"object"!=typeof e)throw"bin schema must be an object";if("type"in e||(e.type="regular-bin"),"custom-bin"==e.type){if(!Array.isArray(e.lst))throw"binconfig.lst must be an array";if(!e.lst.length)throw"binconfig.lst must have entries";const t=e.lst[0],n=e.lst[e.lst.length-1];for(const r of e.lst){if(!("startinclusive"in r)&&!("stopinclusive"in r))throw"custom bin.startinclusive and/or bin.stopinclusive must be defined";if(r==t){if("startunbounded"in r&&!r.startunbounded)throw"a custom first bin must not set bin.startunbounded to false";if(r.startunbounded=!0,"start"in r)throw"a custom first bin must not set a bin.start value";if("start_percentile"in r)throw"the first bin must not set a bin.start_percentile value";if(!("stop"in r))throw"a custom first bin must define a bin.stop value";if(!i(r.stop))throw"a custom first bin.stop value should be numeric"}else if(r==n){if(!("start"in r))throw"a custom last bin must define a bin.start value";if(!i(r.start))throw"a custom last bin.start must be numeric";if("stopunbounded"in r&&!r.stopunbounded)throw"a custom last bin must not set bin.stopunbounded to false";if(r.stopunbounded=!0,"stop"in r)throw"a custom last bin must not set a bin.stop value"}else{if(!i(r.start))throw"bin.start must be numeric for a non-first bin";if(!i(r.stop))throw"bin.stop must be numeric for a non-last bin"}}}else{if("regular-bin"!=e.type)throw`invalid binconfig.type="${e.type}"`;if(!Number.isFinite(e.bin_size))throw"non-numeric bin_size";if(e.bin_size<=0)throw"bin_size must be greater than 0";if(e.startinclusive||e.stopinclusive||(e.startinclusive=1,e.stopinclusive=0),!e.first_bin)throw"first_bin{} missing";if("object"!=typeof e.first_bin)throw"first_bin{} is not an object";if(!Object.keys(e.first_bin).length)throw"first_bin is an empty object";{const t=e.first_bin;if(t.startunbounded=!0,t.stop_percentile){if(!Number.isInteger(t.stop_percentile))throw"first_bin.stop_percentile should be integer";if(t.stop_percentile<=0||t.stop_percentile>=100)throw"first_bin.stop_percentile out of bound (0-100)"}else if(!Number.isFinite(t.stop))throw"first_bin.stop not a number when stop_percentile is not set"}if(e.last_bin){const t=e.last_bin;if(t.start_percentile){if(!Number.isInteger(t.start_percentile))throw"last_bin.start_percentile should be integer";if(t.start_percentile<=0||t.start_percentile>=100)throw"last_bin.start_percentile out of bound (0-100)"}else if(!Number.isFinite(t.start))throw"last_bin.start not a number when start_percentile is not set";if(t.stopunbounded=!0,"stop"in t)throw"a regular last bin must not set a bin.stop value"}}}(r),r.lst){const t=(0,o.getColors)(r.lst.length);for(const e of r.lst)e.color=t(e.label)}if("custom-bin"==r.type)return JSON.parse(JSON.stringify(r.lst));if("function"!=typeof e)throw"summaryfxn required for modules/termdb.bins.js compute_bins()";const s=function(t){const e=[],n=t.first_bin;n&&i(n.start_percentile)&&e.push(n.start_percentile);n&&i(n.stop_percentile)&&e.push(n.stop_percentile);const r=t.last_bin;r&&i(r.start_percentile)&&e.push(r.start_percentile);r&&i(r.stop_percentile)&&e.push(r.stop_percentile);return e}(r),a=e(s);if(!a||"object"!=typeof a)throw"invalid returned value by summaryfxn";r.results={summary:a},r.binLabelFormatter||(r.binLabelFormatter=l(r));const u=Math.floor(100*a.min)/100,f=Math.ceil(100*a.max)/100,d=r.first_bin.startunbounded?u:r.first_bin.start_percentile?a["p"+r.first_bin.start_percentile]:r.first_bin.start;let h,p,m=f;if(r.last_bin)m=r.last_bin.stopunbounded?f:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:i(r.last_bin.stop)&&r.last_bin.stop<=a.max?r.last_bin.stop:f,h=i(r.last_bin.start_percentile)?a["p"+r.last_bin.start_percentile]:i(r.last_bin.start)?r.last_bin.start:void 0,p=r.last_bin.stopunbounded?null:r.last_bin.stop_percentile?a["p"+r.last_bin.stop_percentile]:i(r.last_bin.stop)?r.last_bin.stop:null;else if(r.lst){const t=r.lst[r.lst.length-1];h=t.start,p="stop"in t&&!t.stopunbounded?t.stop:f,m=p}else h=f,p=f;const g=i(m),y=i(h),v=i(p);if(!g&&!y)return[];const b=[];let w={startunbounded:r.first_bin.startunbounded,start:r.first_bin.startunbounded?void 0:d,stop:i(r.first_bin.stop_percentile)?+a["p"+r.first_bin.stop_percentile]:i(r.first_bin.stop)?+r.first_bin.stop:d+r.bin_size,startinclusive:r.startinclusive,stopinclusive:r.stopinclusive};if(!i(w.stop))throw"the computed first_bin.stop is non-numeric"+w.stop;for(;(g&&w.stop<=m||w.startunbounded&&!b.length||w.stopunbounded)&&(b.push(w),w.stop>=m&&(w.stopunbounded=!0,b.length>1&&delete w.stop),w.label=c(w,r,n),!w.stopunbounded);){const t=w.stop+r.bin_size,e=w.stop;if(w={startinclusive:r.startinclusive,stopinclusive:r.stopinclusive,start:e,stop:v&&(e==h||t>p)?p:y&&t>h&&e!=h?h:t},w.stop>=m&&(w.stop=m,r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),r.last_bin&&r.last_bin.stopinclusive&&(w.stopinclusive=1)),y&&w.start==h&&r.last_bin&&r.last_bin.stopunbounded&&(w.stopunbounded=1),w.start>w.stop){if(!(y&&w.stop==h&&r.last_bin&&r.last_bin.stopunbounded))break;w.stopunbounded=!0}if(b.length+1>=100){r.error="max_num_bins_reached";break}}delete r.binLabelFormatter,b.length>1&&delete b[b.length-1].stop;const _=(0,o.getColors)(b.length);for(const t of b)t.color=_(t.label);return b}function l(t){return"rounding"in t?(0,r.WU)(t.rounding):t=>t}function c(t,e,n){const r=e;r.binLabelFormatter||(r.binLabelFormatter=l(r)),t.startunbounded||t.stopunbounded||"startinclusive"in t||"stopinclusive"in t||(r.startinclusive?t.startinclusive=!0:r.stopinclusive&&(t.stopinclusive=!0));const o="bins"==r.use_as||t.start,i="bins"==r.use_as||t.stop;let a=0;if("label_offset"in r?(r.label_offset_ignored="bin_size"in r&&r.bin_size<r.label_offset,r.label_offset_ignored||(a=r.label_offset)):1===r.bin_size&&"integer"==r.termtype&&(a=1),t.startunbounded){return(t.stopinclusive?"≤":"<")+(n?s(i,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(i))}if(t.stopunbounded||o===i){return(t.startinclusive?"≥":">")+(n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o))}if(a&&t.startinclusive&&!t.stopinclusive){if(Number.isInteger(r.bin_size)&&Math.abs(o-i)===a)return""+(n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o));{const t=n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(o),e=n?s(i-a,n.fromUnit,n.toUnit,n.scaleFactor,!0):r.binLabelFormatter(i-a);return+t>=+e?t.toString():t+" to "+e}}{const e=t.startinclusive?"":">",a=t.stopinclusive?"":"<",l=n?s(o,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(o)?o:r.binLabelFormatter(o),c=n?s(i,n.fromUnit,n.toUnit,n.scaleFactor,!0):Number.isInteger(i)?i:r.binLabelFormatter(i);if(+l>=+c){return(t.startinclusive?"≥":">")+l}return e+l+" to "+a+c}}},1575:(t,e,n)=>{"use strict";n.d(e,{CG:()=>o});new Set(["snplst","prs","snplocus","geneVariant","samplelst"]);const r=new Set(["categorical","integer","float","condition","survival","snplst","snplocus","geneVariant","samplelst"]);function o(t,e,n){const o=e||{};if(n&&n.usecase&&use.target in n.usecase)return n.usecase[use.target](t,use);const a=new Set,l=t.child_types||[];switch(o.target){case"barchart":case"summary":case"matrix":return"term0"==o.detail&&"geneVariant"==t.type||("term2"==o.detail&&"geneVariant"==t.type&&"geneVariant"==o.term1type||(t.type&&"survival"!==t.type&&a.add("plot"),i(l)&&a.add("branch"))),a;case"table":return"term"==o.detail&&a.add("plot"),l.length>1&&a.add("branch"),a;case"scatterplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch"),a;case"sampleScatter":return"numeric"==o.detail?("float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch")):(r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch")),a;case"boxplot":return"float"!=t.type&&"integer"!=t.type||a.add("plot"),"term2"===o.detail&&s(l)&&a.add("branch"),a;case"cuminc":if("term"==o.detail)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a;if("term2"===o.detail)return t.type&&"survival"!=t.type&&a.add("plot"),i(l)&&a.add("branch"),a;if("term0"==o.detail)return a.add("plot"),a;case"survival":return"term"==o.detail?("survival"==t.type&&a.add("plot"),l.includes("survival")&&a.add("branch"),a):"term2"===o.detail?("survival"!=t.type&&(t.type&&a.add("plot"),i(l)&&a.add("branch")),a):"term0"==o.detail?(t.type&&a.add("plot"),i(l)&&a.add("branch"),a):(t.isleaf?a.add("plot"):a.add("branch"),a);case"regression":if("outcome"==o.detail){if("linear"==o.regressionType)return"float"!=t.type&&"integer"!=t.type||a.add("plot"),s(l)&&a.add("branch"),a;if("logistic"==o.regressionType)return t.type&&"survival"!=t.type&&a.add("plot"),i(l)&&a.add("branch"),a;if("cox"==o.regressionType)return"condition"==t.type&&a.add("plot"),l.includes("condition")&&a.add("branch"),a}if("independent"==o.detail)return"float"!=t.type&&"integer"!=t.type&&"categorical"!=t.type||a.add("plot"),function(t,e){for(const n of e)if(t.includes(n))return!0}(l,["categorical","float","integer"])&&a.add("branch"),a;default:return r.has(t.type)&&a.add("plot"),t.isleaf||a.add("branch"),a}}function i(t){return!!t.length&&(t.length>1||"survival"!=t[0])}function s(t){return t.includes("float")||t.includes("integer")}},1881:(t,e,n)=>{"use strict";n.d(e,{N:()=>i});const r="root",o="...";function i(t,e){const n=Object.create(null),i=Object.create(null),a=Object.create(null);for(const r of t)for(const[t,o]of e.entries()){const l=s(r,t,e),c=s(r,t-1,e);if(!r[o.k]){t>0&&(a[c]+=1);break}if(n[l]=c,l in a||(a[l]=0),!(l in i)){const n={lst:[]};o.full&&(n.full=r[o.full]),n.id0=e[0].k,n.v0=r[e[0].k],1==t&&(n.id1=e[1].k,n.v1=r[e[1].k]),2==t&&(n.id2=e[2].k,n.v1=r[e[2].k]),i[l]=n}i[l].lst.push(r),t==e.length-1&&(a[l]+=1)}const l=[{id:r,name:r}];for(const t in n){const e=n[t],r=i[t],s=t.split(o);l.push({id:t,parentId:e,lst:r.lst,value:a[t],name:s[s.length-1],full:r.full,id0:r.id0,v0:r.v0,id1:r.id1,v1:r.v1,id2:r.id2,v2:r.v2})}return l}function s(t,e,n){const i=[r];for(let r=0;r<e;r++)i.push(t[n[r].k]);return e>=0&&i.push(t[n[e].k]),i.join(o)}},4298:(t,e,n)=>{"use strict";n.d(e,{A:()=>o});var r=n(2273);function o(t,e,n){if(!e)return null;for(const o of t.split(",")){const t=o.replace(/&/g,",").split("|"),i={};for(let n=0;n<e.length;n++)t[n]&&(i[e[n].name]=t[n]);if(!i.Allele)continue;let s=null;for(const t of n.mlst||n.alleles)if(t.allele_original==i.Allele){s=t;break}if(!s){if("-"==i.Allele)n.mlst?1==n.mlst.length&&(s=n.mlst[0]):n.alleles&&1==n.alleles.length&&(s=n.alleles[0]);else for(const t of n.mlst||n.alleles)if(t.allele_original.substr(1)==i.Allele){s=t;break}if(!s)continue}if(s.csq||(s.csq=[]),s.csq.push(i),i._gene=i.SYMBOL||i.Gene,i.Feature_type&&"Transcript"==i.Feature_type?i._isoform=i.Feature.split(".")[0]:i._isoform=i._gene,i.Consequence){const[t,e,n]=(0,r.vepinfo)(i.Consequence);i._dt=t,i._class=e,i._csqrank=n}else i._dt=dtsnvindel,i._class=mclassnonstandard;i.HGVSp?i._mname=decodeURIComponent(i.HGVSp.substr(i.HGVSp.indexOf(":")+1)):i.Protein_position&&i.Amino_acids?i._mname=decodeURIComponent(i.Protein_position+i.Amino_acids):i.HGVSc?i._mname=i.HGVSc.substr(i.HGVSc.indexOf(":")+1):i.Existing_variation&&(i._name=i.Existing_variation)}return!0}},9380:(t,e,n)=>{"use strict";function r(t){let e=!1,n=!0,r=0,o=0;const i={};let s;for(;r<t.length;){const a=t[r];n?"="==a?(e=!0,n=!1,s=t.substring(o,r),o=r+1):";"==a&&(i[t.substring(o,r)]=1,o=r+1):e&&";"==a&&(n=!0,e=!1,i[s]=t.substring(o,r),s=null,o=r+1),r++}const a=t.substr(o,r);return s?i[s]=a:i[a]=1,i}n.d(e,{w:()=>r})},6819:(t,e,n)=>{"use strict";n.d(e,{S:()=>d,e:()=>f});var r=n(2273),o=n(9380),s=n(4298);function a(t,e,n){if(!e)return null;for(const o of t.split(",")){const t=o.replace(/&/g,",").split("|"),i={};for(let n=0;n<e.length;n++)t[n]&&(i[e[n].name]=t[n]);if(!i.Allele)continue;let s=null;for(const t of n.alleles)if(t.allele==i.Allele){s=t;break}if(s){if(s.ann||(s.ann=[]),s.ann.push(i),i._gene=i.Gene_Name,i.Feature_Type&&"transcript"==i.Feature_Type&&i.Feature_ID&&(i._isoform=i.Feature_ID.split(".")[0]),i.Annotation){const[t,e,n]=(0,r.vepinfo)(i.Annotation);i._dt=t,i._class=e,i._csqrank=n}else i._dt=dtsnvindel,i._class=mclassnonstandard;i["HGVS.p"]?i._mname=i["HGVS.p"]:i["HGVS.c"]&&(i._mname=i["HGVS.c"])}}return!0}var l=n(736);const c=new RegExp(/<(.+)>/),u={};for(const t in r.mclass)u[r.mclass[t].label.toUpperCase()]=t;function f(t){let e=[],n=[],r={},o=!1,i={},s=!1;for(const a of t)if(a.startsWith("#"))if(a.startsWith("#C"))e=a.split("\t").slice(9);else if(a.startsWith("##INFO")){const t=p(a.substring(8,a.length-1),r);t?n.push("INFO error: "+t):o=!0}else if(a.startsWith("##FORMAT")){const t=p(a.substring(10,a.length-1),i);t?n.push("FORMAT error: "+t):s=!0}const a=[];for(const t of e){const e={name:t};a.push(e)}if(r.CSQ){const t=r.CSQ.Description.split(" Format: ");if(t[1]){const e=t[1].split("|");if(e.length>1){r.CSQ.csqheader=[];for(const t of e){const e={name:t};r.CSQ.csqheader.push(e)}}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}else n.push("unknown format for CSQ header: "+r.CSQ.Description)}if(r.ANN){const t=r.ANN.Description.split("'");if(t[1]){const e=t[1].split(" | ");if(e.length){r.ANN.annheader=[];for(const t of e){const e={name:t};r.ANN.annheader.push(e)}}else n.push('no " | " joined annotation fields for ANN (snpEff annotation): '+r.ANN.Description)}else n.push("no single-quote enclosed annotation fields for ANN (snpEff annotation): "+r.ANN.Description)}return[o?r:null,s?i:null,a,n.length?n:null]}function d(t,e){const n=t.split("\t");if(n.length<8)return["line has less than 8 fields",null,null];const r=Number.parseInt(n[1]);if(!Number.isInteger(r))return["invalid value for genomic position",null,null];const i=n[3],u={vcf_ID:n[2],chr:(e.nochr?"chr":"")+n[0],pos:r-1,ref:i,altstr:n[4],alleles:[{allele:i,sampledata:[]}],info:{},name:"."==n[2]?null:n[2]},f=[];for(const t of n[4].split(",")){const e={ref:u.ref,allele:t,allele_original:t,sampledata:[],_m:u,info:{}};if(u.alleles.push(e),"<"==t[0]){const n=t.match(c);if(!n){f.push(t);continue}e.type=n[1],e.allele=n[1],e.issymbolicallele=!0}else{const[t,n,r]=h(u.pos,u.ref,e.allele);e.pos=t,e.ref=n,e.allele=r}}n[8]&&n[9]&&function(t,e,n){const r=t[8].split(":");for(let o=9;o<t.length;o++){const i=t[o].split(":");{let t=!0;for(const e of i)if("."!=e){t=!1;break}if(t)continue}const s=o-9;for(let t=1;t<e.alleles.length;t++){const r={};if(n.samples&&n.samples[s])for(const t in n.samples[s])r[t]=n.samples[s][t];else r.name="missing_samplename_from_vcf_header";e.alleles[t].sampledata.push({sampleobj:r})}for(let t=0;t<r.length;t++){const o=r[t],s=i[t];if("."==s)continue;if("GT"==o){const t=-1!=s.indexOf("/")?"/":"|";let n=0,r=!1;const o=[];for(const i of s.split(t)){if("."==i){r=!0;continue}const t=Number.parseInt(i);if(Number.isNaN(t)){r=!0;continue}n+=t;const s=e.alleles[t];s&&o.push(s.allele)}let i=!1;r||(i=0==n);const a=o.join(t);for(let t=1;t<e.alleles.length;t++){const n=e.alleles[t].sampledata[e.alleles[t].sampledata.length-1];n.GT=s,n.genotype=a,i&&(n.gtallref=!0),n.__gtalleles=o}continue}const a=n.format?n.format[o]:null;if(!a){for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][o]=s;continue}const l="Integer"==a.Type,c="Float"==a.Type;if(a.Number&&"R"==a.Number||"AD"==o){const t=s.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n]){const r=e.alleles[n],i=r.sampledata[r.sampledata.length-1];i[o]={},i[o][r.ref]=t[0],i[o][r.allele]=t[n]}}else if(a.Number&&"A"==a.Number){const t=s.split(",").map((t=>l?Number.parseInt(t):c?Number.parseFloat(t):t));for(let n=1;n<e.alleles.length;n++)if(null!=t[n-1]){const r=e.alleles[n],i=r.sampledata[r.sampledata.length-1];i[o]={},i[o][r.allele]=t[n-1]}}else for(let t=1;t<e.alleles.length;t++)e.alleles[t].sampledata[e.alleles[t].sampledata.length-1][o]=s}}for(const t of e.alleles)for(const e of t.sampledata)if(e.AD){e.allele2readcount={};for(const t in e.AD)e.allele2readcount[t]=e.AD[t]}}(n,u,e),u.alleles.shift();const d="."==n[7]?[]:(0,o.w)(n[7]);let p=[];e.info?p=function(t,e,n){const r=[];for(const o in t){if(null==n.info[o]){r.push(o);continue}const i=t[o];if("CSQ"==o){(0,s.A)(i,n.info.CSQ.csqheader,e)||(e.info[o]=i);continue}if("ANN"==o){a(i,n.info.ANN.annheader,e)||(e.info[o]=i);continue}if("Flag"==n.info[o].Type){e.info[o]=o;continue}const l=n.info[o].Number,c="Integer"==n.info[o].Type,u="Float"==n.info[o].Type;if("0"==l){e.info[o]=o;continue}if("A"==l){const t=i.split(",");for(let n=0;n<t.length;n++)e.alleles[n]&&(e.alleles[n].info[o]=c?Number.parseInt(t[n]):u?Number.parseFloat(t[n]):t[n]);continue}if("1"==l){e.info[o]=c?Number.parseInt(i):u?Number.parseFloat(i):i;continue}if(!i.split)continue;const f=i.split(",");e.info[o]=c?f.map(Number.parseInt):u?f.map(Number.parseFloat):f}return r}(d,u,e):u.info=d;const m=[];for(const t of u.alleles){const e={};for(const t in u)"alleles"!=t&&(e[t]=u[t]);for(const n in t)"allele"==n?e.alt=t[n]:"info"==n?e.altinfo=t[n]:e[n]=t[n];e.issymbolicallele||"NON_REF"==e.alt||(e.type=(0,l.P)(e.ref,e.alt)),m.push(e)}return[p.length?"unknown info keys: "+p.join(","):null,m,f.length>0?f:null]}function h(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substr(0,e.length-1),n=n.substr(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substr(1),n=n.substr(1),t++;return[t,e,n]}function p(t,e){const n={},r=[];let o=0,s=!1,a=null;for(let e=0;e<t.length;e++)if('"'!=t[e])"="!=t[e]?","!=t[e]||(s?s=!1:a?(n[a]=t.substring(o,e),a=null):r.push("k undefined"),o=e+1):(a=t.substring(o,e),o=e+1);else{e++;const o=e;for(;'"'!=t[e];)e++;a?(n[a]=t.substring(o,e),a=null):r.push("k undefined before double quotes"),s=!0}return a&&(n[a]=t.substring(o,i)),n.ID?(e[n.ID]=n,r.length?r.join("\n"):void 0):"no ID"}},736:(t,e,n)=>{"use strict";n.d(e,{P:()=>o});var r=n(2273);function o(t,e){return 1==t.length&&1==e.length?"."==e?r.mclassdeletion:r.mclasssnv:t.length==e.length?r.mclassmnv:t.length<e.length?r.mclassinsertion:t.length>e.length?r.mclassdeletion:r.mclassnonstandard}},7011:(t,e,n)=>{"use strict";n.d(e,{I:()=>o});const{bin:r}=n(9060);function o(t,e){const n=function(t,e){const n=r().domain(t.domain()).thresholds(t.ticks(15)).value((t=>t));return n(e)}(t,e.values),o=[];for(const t of n){const e={x0:t.x0,x1:t.x1,binValueCount:t.length};delete t.x0,delete t.x1,o.push(e)}const i=o[o.length-1].x1,s={x0:i,x1:i,binValueCount:0};return o.push(s),{bins0:n,bins:o}}},141:(t,e,n)=>{"use strict";n.d(e,{l2:()=>yo,LJ:()=>vo,g_:()=>fo,U_:()=>lo,lE:()=>ni,SC:()=>No,OG:()=>_o});var r=n(334),o=n.n(r);const i=require("express");var s=n.n(i),a=n(6464);const l=require("url");var c=n.n(l);const u=require("http");var f=n.n(u);const d=require("https");var h=n.n(d),p=n(7147),m=n.n(p),g=n(1017),y=n.n(g),v=n(6452),b=n.n(v);const w=require("lazy");var _=n.n(w);const x=require("compression");var k=n.n(x),q=n(2081),N=n.n(q),S=n(6718),A=n(1881);const M=require("body-parser");var T=n.n(M),C=n(7219),j=n.n(C),E=n(4521),O=n.n(E),I=n(9344),R=n.n(I),P=n(3345),F=n(2273),D=n(6819),L=n(8064),$=n(5494),Z=n(6733),z=n(5558),U=n(3602),B=n(6279),G=n(8423),J=n(8235),W=n(5026);function H(t){delete t.mclasslabel2key,delete t.sample2disease,delete t.patient2ori2sample}var V=n(4766);const Y=require("express-basic-auth");var K=n.n(Y),X=n(2826),Q=n(1271),tt=n(1495);async function et(t,e,n,r,o,i,s,a){const l=nt().height(t.query.barheight).min(r).max(o),c=e.width/(e.stop-e.start);await P.UE({args:[i,e.chr+":"+e.start+"-"+e.stop],dir:s,callback:i=>{const s=i.split("\t"),u=Number.parseInt(s[1]);if(Number.isNaN(u))return;const f=Number.parseInt(s[2]);if(Number.isNaN(f))return;const d=Number.parseFloat(s[3]);if(Number.isNaN(d))return;a.fillStyle=d>0?t.query.pcolor:t.query.ncolor;const h=l(d),p=n+(Math.max(u,e.start)-e.start)*c,m=n+(Math.min(f,e.stop)-e.start)*c,g=Math.max(1,m-p);a.fillRect(p,h.y,g,h.h),d>o?(a.fillStyle=t.query.pcolor2,a.fillRect(p,0,g,2)):d<r&&(a.fillStyle=t.query.ncolor2,a.fillRect(p,t.query.barheight-2,g,2))}})}function nt(){var t=50,e=0,n=100;function r(r){var o,i=!1,s=0;return 0==e&&0==n||e<=0&&n>=0&&(i=!0,s=t*n/(n-e)),i?r>=n?{y:0,h:s}:r>=0?{y:s-(o=s*r/n),h:o}:r<=e?{y:s,h:t-s}:{y:s,h:o=(t-s)*r/e}:r<=e?{y:t,h:0}:{y:t-(o=t*(r-e)/(n-e)),h:o}}return r.height=function(e){return t=e,r},r.min=function(t){return e=t,r},r.max=function(t){return n=t,r},r}function rt(t,e,n){return new Promise(((r,i)=>{const s=(0,q.spawn)(o().bigwigsummary,["-udcDir="+o().cachedir,n,e.chr,e.start,e.stop,Math.ceil(e.width*(t.query.dotplotfactor||1))]),a=[],l=[];s.stdout.on("data",(t=>a.push(t))),s.stderr.on("data",(t=>l.push(t))),s.on("close",(t=>{const e=l.join("");e.length?e.startsWith("no data")?r():i("Cannot read bigWig file"):r(a.join(""))}))}))}function ot(t,e,n,r,o){const[i,s]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const o=new Map,i=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let s=r;for(const t of i)o.set(t,s+n/2),s+=n;return[n,o]}(t,n),a=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?a.set(r,(t.stop-r)/e):a.set(r,(r-t.start)/e)}let l=0;for(const t of e)l=Math.max(l,(s.get(t.stop)-s.get(t.start))/2);const c=r+l+i/2,u=(0,S.createCanvas)(t.width*o,c*o),f=u.getContext("2d");o>1&&f.scale(o,o),f.strokeStyle="black";for(const t of n)f.beginPath(),f.moveTo(a.get(t),0),f.lineTo(s.get(t),r),f.closePath(),f.stroke();for(const t of e){const e=s.get(t.start),n=s.get(t.stop),o=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));f.fillStyle="rgb(255,"+l+","+l+")",f.beginPath(),f.moveTo(o,a-i/2),f.lineTo(o-i/2,a),f.lineTo(o,a+i/2),f.lineTo(o+i/2,a),f.lineTo(o,a-i/2),f.closePath(),f.fill()}return{height:c,src:u.toDataURL()}}var it=n(938);async function st(t,e,n){const r={rglst:[]};let o=0,i=0;if(t.autoscale){for(const r of t.rglst){const s=(n?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;await P.UE({args:[t.file,s],dir:e,callback:t=>{const[e,n,r,s]=t.split("\t");for(const t of s.split(",")){const e=Number(t);o=Math.min(o,e),i=Math.max(i,e)}}})}r.minv=o,r.maxv=i}else o=t.minv,i=t.maxv;const s=app.makeyscale().height(t.barheight).min(o).max(i);for(const a of t.rglst){const l={chr:a.chr,start:a.start,stop:a.stop,width:a.width,reverse:a.reverse,xoff:a.xoff},c=(0,S.createCanvas)(a.width,t.barheight),u=c.getContext("2d"),f=(n?a.chr.replace("chr",""):a.chr)+":"+a.start+"-"+a.stop;await P.UE({args:[t.file,f],dir:e,callback:e=>{const[n,r,l,c]=e.split("\t"),f=Math.max(Number.parseInt(r),a.start),d=Math.min(Number.parseInt(l),a.stop),h=(a.reverse?a.stop-d:f-a.start)*a.width/(a.stop-a.start),p=(a.reverse?a.stop-f:d-a.start)*a.width/(a.stop-a.start);for(const e of c.split(",")){const n=Number(e);u.fillStyle=n>0?t.pcolor:t.ncolor;const r=s(n),a=Math.max(1,p-h);u.fillRect(h,r.y,a,2),n>i?(u.fillStyle=req.query.pcolor2,u.fillRect(h,0,a,2)):n<o&&(u.fillStyle=req.query.ncolor2,u.fillRect(h,t.barheight-2,a,2))}}}),l.img=c.toDataURL(),r.rglst.push(l)}return r}var at=n(2781);const lt="all",ct="support_ref",ut="support_alt",ft="support_no",dt="support_amb",ht="support_sv";function pt(t){const e={};if(t.variant)if(t.grouptype)e[t.grouptype]={partstack:t.partstack};else{e[ct]={},e[ft]={},e[dt]={};for(let n=0;n<t.variant.length;n++)e[ut+n.toString()]={}}else{if(!t.sv)throw"q.variant or q.sv missing";t.grouptype?e[t.grouptype]={partstack:t.partstack}:(e[ht]={},e[ct]={})}for(const n in e){const r=e[n];r.type=n,r.templates=[],r.regions=mt(t.regions),r.messages=[]}return e}function mt(t){return t.map((t=>({x:t.x,scale:t.scale,ntwidth:t.ntwidth})))}const gt=require("crypto");var yt=n.n(gt),vt=n(490);require("jstat"),o().features,o().clustalo;function bt(t){return t>1e9?(t/1e9).toFixed(2)+" GB":t>1e6?(t/1e6).toFixed(2)+" MB":t>1e3?(t/1e3).toFixed(2)+" KB":t+" Bytes"}const wt=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",_t={end_point:y().join(wt,"files/"),fields:["id","file_size","experimental_strategy","cases.submitter_id","associated_entities.entity_submitter_id","associated_entities.case_id","cases.samples.sample_type","analysis.workflow_type"],size:100},xt={end_point:y().join(wt,"cases/"),fields:["case_id"]},kt="STAR 2-Pass Transcriptome";async function qt(t,e,n){if(await Nt(t,"cases.case_id",n))return e.is_case_uuid=!0,await St(t,"cases.case_id",n);if(await Nt(t,"cases.submitter_id",n))return e.is_case_id=!0,await St(t,"cases.submitter_id",n);const r=await At(t,"file_id",n);if(r.data.hits.length)return e.is_file_uuid=!0,r;const o=await At(t,"file_name",n);return o.data.hits.length&&(e.is_file_id=!0),o}async function Nt(t,e,n){const r={op:"and",content:[{op:"in",content:{field:e,value:t}}]};n&&r.content.push(n);return(await Mt(r,xt)).data.hits.length>0}async function St(t,e,n,r){const o={op:"and",content:[{op:"=",content:{field:"data_category",value:"Sequencing Reads"}},{op:"=",content:{field:"index_files.data_format",value:"bai"}},{op:"=",content:{field:"data_type",value:"Aligned Reads"}},{op:"=",content:{field:"data_format",value:"bam"}}]};return t&&e&&o.content.push({op:"in",content:{field:e,value:t}}),n&&o.content.push(n),await Mt(o,_t,r)}async function At(t,e,n){const r={op:"and",content:[{op:"in",content:{field:e,value:t}}]};return n&&r.content.push(n),await Mt(r,_t)}async function Mt(t,e,n){const r={filters:t,size:n||10,fields:e.fields.join(",")},o=await b()(e.end_point,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});let i;try{i=JSON.parse(o.body)}catch(t){throw"invalid JSON from "+e.end_point}if(!i.data||!i.data.hits)throw"data structure not data.hits[]";return i}async function Tt(t,e,n){const r={Range:"bytes=0-0"};n?r.Cookie=`sessionid=${n}`:r["X-Auth-Token"]=e;const o=wt+"/data/"+t;try{const t=await b()(o,{headers:r,decompress:!1});if(!(t.statusCode>=200&&t.statusCode<400))throw console.log(`gdcCheckPermission() error for got(${o})`,t),"Invalid status code: "+t.statusCode}catch(t){throw console.log("gdcCheckPermission error: ",(null==t?void 0:t.code)||t),"Permission denied"}}const Ct=1e3;const jt=o().clustalo,Et=(0,a.promisify)(at.pipeline),Ot="rgb(120,120,120)",It="rgb(230,230,230)",Rt=(0,vt.ZP)(It,Ot),Pt="#d48b37",Ft=(0,vt.ZP)("#dbc6ad",Pt),Dt="#3B7A57",Lt=(0,vt.ZP)("#E5FFCC",Dt),$t="#d13232",Zt="#ffdbdd",zt=(0,vt.ZP)(Zt,$t),Ut="#4888bf",Bt="#c9e6ff",Gt=(0,vt.ZP)(Bt,Ut),Jt="#6B4423",Wt=(0,vt.ZP)("#987654",Jt),Ht="#fc6df3",Vt=(0,vt.ZP)("#dea4da",Ht),Yt="#47FFFC",Kt="#B2D7D7",Xt=(0,vt.ZP)(Kt,Yt),Qt=12,te=7,ee="black",ne="#ededed",re="blue",oe="#e0e0e0",ie="#FF0000",se="#6cc24a",ae="#ffff00",le="#DEB887",ce="#CD853F",ue="#9a92ec",fe="#47C8FF",de=1,he=1,pe=.4,me=.9,ge=7,ye=7,ve=10,be=7,we=40,_e=.5,xe=2,ke=5,qe=7e3,Ne=1500,Se=2e3,Ae=7,Me=200,Te=20,Ce=(new Set(["A","T","C","G"]),process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov"),je=Math.random.toString();async function Ee(t,e,n,r,o){const i=t.diff_score_plotwidth/(r-o),s=r*i-o*i,a=(0,S.createCanvas)(s*t.devicePixelRatio,e.canvasheight*t.devicePixelRatio),l=a.getContext("2d");t.devicePixelRatio>1&&l.scale(t.devicePixelRatio,t.devicePixelRatio);const c=n.map((t=>t.__tempscore)),u=e.canvasheight/c.length;let f=0;const d=e.stackspace/e.canvasheight;for(const t of c){let e=0;for(const n of t)"alt0"==n?l.fillStyle=ie:"ref"==n?l.fillStyle=fe:"alt1"==n?l.fillStyle=se:"alt2"==n?l.fillStyle=ae:"alt3"==n?l.fillStyle=le:"alt4"==n?l.fillStyle=ce:"alt5"==n&&(l.fillStyle=ue),l.fillRect(i*e,f*u,i,u-d*u),e+=1;f+=1}return{height:e.canvasheight,width:s,src:a.toDataURL(),read_height:u}}function Oe(t,e,n,r){for(const o of n)for(const n of o.segments)if(!(n.ridx!=t||Math.max(n.segstart,e.start)>Math.min(n.segstop,e.stop)))for(const t of n.boxes)if(e.ntwidth>=1){if(("S"==t.opr||"X"==t.opr)&&t.s)for(let e=0;e<t.s.length;e++){const n=t.start+e,o=r.find((t=>t.position==n));if(!o)continue;const i=t.s[e];o[i]=1+(o[i]||0),"S"==t.opr&&o.total++}}else if("S"==t.opr){const n=Math.floor((t.start-e.start)*e.ntwidth),o=Math.floor((t.start+t.len-e.start)*e.ntwidth);for(let t=n;t<=o;t++){const e=r[t];e&&(e.softclip=1+(e.softclip||0),e.total++)}}}async function Ie(t,e){if(!await P.yE(e))return;if(!t.query.gdcFilePosition)throw".gdcFilePosition missing";const n=t.query.regions,r=t.query.gdcFilePosition.split(".");t.query.regions=[{chr:r[0],start:Number(r[1]),stop:Number(r[2])}],await en(t),t.query.regions=n}async function Re(t,e,n,r,o){const i=t.map((t=>t.segments[0].seq)),s=t.map((t=>t.segments[0].qual));let a="",l="";o&&(a+=">seq\n"+o.replace("\n","")+"\n");let c=0;for(const t of i){if(!(c<Me))break;a+=">seq\n"+t.replace("\n","")+"\n",l+=Je(s[c].replace("\n",""))+"\n",c+=1}return await function(t,e,n,r,o,i,s,a){return new Promise(((n,l)=>{const c=(0,q.spawn)(jt,["-i","-","-t","DNA","--outfmt=clu","--wrap=5000","--maxnumseq="+(e+1),"--maxseqlen=1000"]),u=[],f=[];at.Readable.from(t).pipe(c.stdin),c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("error",(t=>{console.log("stderr (clustalo):",f),l(t)})),c.on("close",(t=>{let e=0;const c=[],f={final_read_align:[],qual_r:[],qual_g:[],qual_b:[]};let d=0;for(const t of u.toString().split("\n"))if(t.includes("seq ")){let n=0,l="",u=0,h="";0!=e&&a?h=r.split("\n")[e-1].split(","):a||(h=r.split("\n")[e].split(","));let p="",m="",g="";for(const r of t.replace("seq ",""))if(","!=r){if("-"!=r){if(n+=1,l+=r,0==e&&a)c.push(r);else if(r==c[u]&&a||!a){const t=Rt(h[n-1]/we).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}else if(r!=c[u]&&a){const t=zt(h[n-1]/we).replace("rgb(","").replace(")","").split(",");p+=t[0]+",",m+=t[1]+",",g+=t[2]+","}}else n>0&&n<t.replace(/-/g,"").replace(/,/g,"").replace("seq ","").length?(l+=r,0==e&&(c.push(r),u<o&&(d+=1))):(l+=" ",0==e&&c.push(r)),p+="255,",m+="255,",g+="255,";u+=1}e+=1,f.gaps_before_variant=d,f.read_count=a?e-1:e,f.qual_r.push(p),f.qual_g.push(m),f.qual_b.push(g),f.final_read_align.push(l),0!=i&&0!=s&&(f.partstack_start=i,f.partstack_stop=s)}else(t.includes("FATAL:")||t.includes("ERROR:"))&&(console.log(t),l(t));n(f)}))}))}(a,Me,i.length,l,e,n,r,o)}async function Pe(t,e){let n=0;for(const r of e){const e=["view","-c",t.file];t.gdc_case_id||e.push((t.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop),await P.UE({isbam:!0,args:e,dir:t.dir,callback:t=>{const e=Number(t);if(!Number.isInteger(e))throw"total number of reads from a region not integer";n+=e}})}if(n<1.1*qe)return;const r=(n-qe)/(.1*qe);t.downsample={keep:10,skip:Math.floor(r),pointer:0},t.read_limit_reached=n}async function Fe(t,e){t.lines=[];const n=["view",e.file];e.gdc_case_id||n.push((e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop),await P.UE({isbam:!0,args:n,dir:e.dir,callback:(n,r)=>{if(!(1024&n.split("\t")[1]&&e.drop_pcrduplicates)){if(e.downsample){const t=e.downsample;if(t.pointer++,t.pointer>=t.keep&&t.pointer<t.keep+t.skip)return;t.pointer>=t.keep+t.skip&&(t.pointer=0)}t.lines.push(n)}}})}async function De(t,e){const n=[],r=["depth","-r",(t.nochr?e.chr.replace("chr",""):e.chr)+":"+(e.start+1)+"-"+e.stop,"-g","DUP",t.file||t.url];if(t.drop_pcrduplicates&&(r.push("-G"),r.push("0x400")),await P.UE({isbam:!0,args:r,dir:t.dir,callback:t=>{const r=t.split("\t"),o=Number.parseInt(r[1])-1,i=Number.parseInt(r[2]);if(e.ntwidth>=1)return void n.push({position:o,total:i});const s=Math.floor((o-e.start)*e.ntwidth);n[s]||(n[s]={position:o,sum:0,count:0}),n[s].sum+=i,n[s].count++}}),e.ntwidth<1)for(const t of n)t&&(t.total=t.sum/t.count,delete t.sum,delete t.count);return n}async function Le(t,e){for(const t of e.regions)t.lines.length>0&&t.ntwidth>=me&&(t.to_checkmismatch=!0,t.referenceseq=await Be(e.genome,t.chr+":"+(t.start+1)+"-"+t.stop));for(const n of t)for(const t of n.segments){const n=e.regions[t.ridx];if(!n.to_checkmismatch)continue;const r=[];for(const e of t.boxes)null!=e.cidx&&"M"==e.opr&&(e.s=t.seq.substr(e.cidx,e.len),He(r,n,e,e.s));r.length&&t.boxes.push(...r)}for(const t of e.regions)delete t.to_checkmismatch,delete t.referenceseq}function $e(t,e){if(!t.asPaired){const n=[];for(let r=0;r<t.regions.length;r++){const o=t.regions[r];for(const i of e.templates){i.ridx=r;const e=Ze(i,o,t);e&&n.push({x1:e.x1,x2:e.x2,__tempscore:e.tempscore,segments:[e]})}}return n}const n=new Map;for(let r=0;r<t.regions.length;r++){const o=t.regions[r];for(const i of e.templates){i.ridx=r;const e=Ze(i,o,t);if(!e||!e.qname)continue;const s=n.get(e.qname);s?(s.segments.push(e),s.x2=Math.max(s.x2,e.x2)):n.set(e.qname,{x1:Math.max(e.x1,o.x),x2:Math.min(e.x2,o.x+o.width),__tempscore:e.tempscore,segments:[e]})}}return[...n.values()]}function Ze(t,e,n){const{sam_info:r,tempscore:o,ridx:i,keepallboxes:s,keepmatepos:a,keepunmappedread:l}=t,c=r.trim().split("\t");if(c.length<11)return;const u=c[0],f=c[1],d=Number.parseInt(c[3]),h=c[5],p=c[6],m=c[7],g=Number.parseInt(c[8]),y=c[9],v=c[10];if(Number.isNaN(d)||d<=0)return;const b=d-1,w={qname:u,segstart:b,segstart_original:b,segstop:b,boxes:[],forward:!(16&f),ridx:i,seq:y,qual:v,cigarstr:h,tlen:g,flag:f,tempscore:o};if(function(t,e,n,r,o,i){const s=t.flag;if(!(1&s))return;64&s?t.isfirst=!0:128&s&&(t.islast=!0);if("="!=e&&"*"!=e&&e!=r.chr)return t.rnext=e,void(t.pnext=n);if(8&s)return void(t.discord_unmapped2=!0);32&s&&!(16&s)&&64&s||16&s&&!(32&s)&&128&s||16&s&&!(32&s)&&64&s||32&s&&!(16&s)&&128&s||(t.discord_orientation=!0,o&&(16&s?32&s?t.discord_orientation_direction="R1R2":n>i&&(t.discord_orientation_direction="R1F2"):32&s?n<i&&(t.discord_orientation_direction="R1F2"):t.discord_orientation_direction="F1F2")),2&s||(t.discord_wrong_insertsize=!0,o&&(t.pnext=n))}(w,p,m,e,a,d),4&f)return l?(w.boxes.push({opr:h,start:b,len:y.length,cidx:0,qual:v}),w.discord_unmapped1=!0,w):void 0;if("*"!=h){let t=b,r=0,o=0;for(let n=0;n<h.length;n++){const i=h[n];if(i.match(/[0-9]/))continue;const a=Number.parseInt(h.substring(r,n));if("H"!=i)if("N"==i||"P"==i||"D"==i||(o+=a),r=n+1,"="!=i&&"M"!=i)if("I"!=i)if("N"!=i&&"D"!=i)if("X"!=i)if("S"!=i){if("P"!=i)console.log("unknown cigar: "+i);else if(s||t>e.start&&t<e.stop){const e={opr:"P",start:t,len:a,cidx:o-a};w.boxes.push(e)}}else{const n={opr:i,start:t,len:a,cidx:o-a};0==w.boxes.length?(n.start-=a,(s||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push(n)):w.boxes.push(n)}else{if(s||Math.max(t,e.start)<Math.min(t+a-1,e.stop)){const e={opr:i,start:t,len:a,cidx:o-a};w.boxes.push(e)}t+=a}else(t>=e.start&&t<=e.stop||t+a-1>=e.start&&t+a-1<=e.stop||s)&&w.boxes.push({opr:i,start:t,len:a}),t+=a;else(s||t>e.start&&t<e.stop)&&a*e.ntwidth>=de&&w.boxes.push({opr:"I",start:t,len:a,cidx:o-a});else(s||Math.max(t,e.start)<=Math.min(t+a-1,e.stop))&&w.boxes.push({opr:i,start:t,len:a,cidx:o-a}),t+=a;else w.boxes.push({opr:i,start:t,len:a,cidx:o-a}),r=n+1}if(0==w.boxes.length)return void(n&&n.readcount_skipped++);w.segstop=t,w.x1=e.x+e.scale(w.boxes[0].start),w.x2=e.x+e.scale((_=w.boxes,Math.max(..._.map((t=>t.start+t.len)))))}var _;return w}async function ze(t,e,n){const[r,o]=function(t,e){let n=(e.groups.length>1?Ne/2:Ne)/t;return n>10?[Math.min(15,Math.floor(n)),1]:n>7?[Math.floor(n),1]:n>3?[Math.ceil(n),0]:n>1?[Math.floor(n),0]:[n,0]}(t.stacks.length,e);t.stackheight=r,t.stackspace=o;for(const e of t.regions)e.to_printnt=t.stackheight>7&&e.ntwidth>=7,e.to_qual=e.ntwidth>=he;if(t.stacks.length&&(t.stackheight>=Ae&&n.length<Se?t.returntemplatebox=[]:t.partstack||(t.allowpartstack=!0)),t.stackheight>=ge){let e=0;for(const t of n)for(const n of t.segments)e=Math.max(e,n.x2-n.x1);e>.7*t.stackheight&&(t.canClipArrowhead=!0)}}function Ue(t,e,n){if(e.asPaired){t.stacks=[];const r=[],o=[];for(const t of n){let n=t.segments[0].ridx;1==t.segments.length||2==t.segments.length&&t.segments[0].ridx==t.segments[1].ridx?(t.x1=Math.max(e.regions[n].x,t.x1),t.x2=Math.min(e.regions[n].x+e.regions[n].width,t.x2),r.push(t)):2==t.segments.length&&t.segments[0].ridx!=t.segments[1].ridx&&(t.x1=t.x1,t.x2=t.x2,o.push(t))}if(r.sort(((t,e)=>t.x1-e.x1)),o.sort(((t,e)=>t.x1-e.x1)),o.length>0){const t=[],e=[],i=o[0];for(const n of r)n.x1<i.x1&&n.x2<i.x1?t.push(n):e.push(n);n=[...t,...o,...e]}for(const r of n){let n=r.segments[0].ridx,o=null;if(!e.variant)for(let i=0;i<t.stacks.length;i++){if(r.x2==e.regions[n].x+e.regions[n].width&&t.stacks[i]<r.x1){o=i,t.stacks[i]=r.x2;break}if(t.stacks[i]+e.stacksegspacing<r.x1){o=i,t.stacks[i]=r.x2;break}}null==o&&(o=t.stacks.length,t.stacks[o]=r.x2),r.y=o}}else{n.sort(((t,e)=>t.x1-e.x1)),t.stacks=[];for(let r=0;r<e.regions.length;r++)for(const o of n)if(o.segments[0].ridx==r){let n=null;if(!e.variant&&!e.sv)for(let i=0;i<t.stacks.length;i++)if(t.stacks[i]+e.stacksegspacing<o.x1&&t.stacks[i]+e.stacksegspacing<e.regions[r].x+e.regions[r].width){n=i,t.stacks[i]=o.x2;break}null==n&&(n=t.stacks.length,t.stacks[n]=o.x2),o.y=n}}return n=function(t,e,n){if(!t.partstack)return e;const r=e.filter((e=>e.y>=t.partstack.start&&e.y<=t.partstack.stop));r.forEach((e=>e.y-=t.partstack.start)),e=r,t.stacks=[];for(let e=t.partstack.start;e<=t.partstack.stop;e++)t.stacks.push(0);return t.returntemplatebox=[],e}(t,n),n}async function Be(t,e){const n=(await P.Kf(t,e)).split("\n");return n.shift(),n.join("").toUpperCase()}function Ge(t,e,n){const r=function(t,e,n){const r=[];for(let e=0;e<t.stacks.length;e++)r.push(t.stackheight);if(function(t,e){if(!e.asPaired)return;for(const e of t.regions)if(e.ntwidth<=pe)return;t.overlapRP_multirows=!0,t.overlapRP_hlline=t.stackspace>0}(t,n),t.overlapRP_multirows)for(const n of e)n.segments.length<=1||n.segments[0].ridx!=n.segments[1].ridx||(n.height=We(n,t.stackheight),r[n.y]=Math.max(r[n.y],n.height));const o=[];let i=t.stackspace;for(const e of r)o.push(i),i+=e+t.stackspace;return t.canvasheight=i,o}(t,e,n);for(const n of e){n.y=r[n.y];for(const e of n.segments){const n=t.regions[e.ridx].to_qual?Je(e.qual):null;for(const t of e.boxes)null!=t.cidx&&"H"!=t.opr&&(n&&(t.qual=n.slice(t.cidx,t.cidx+t.len)),"I"==t.opr?t.s=e.seq.substr(t.cidx,t.len):"X"!=t.opr&&"S"!=t.opr||(t.s=e.seq.substr(t.cidx,t.len)),delete t.cidx);delete e.seq,delete e.qual}}}function Je(t){if("*"==t)return null;const e=[];for(let n=0;n<t.length;n++){const r=t[n].charCodeAt(0)-33;e.push(r)}return e}function We(t,e){if(2==t.segments.length){const[n,r]=t.segments;return n.x2>r.x1?(r.shiftdownrow=1,2*e):e}console.log("more than 2 segments",t.segments.length);const n=[];for(const e of t.segments){let t=null;for(let r=0;r<n.length;r++)if(n[r]<e.x1){t=r,n[r]=e.x2;break}null==t&&(t=n.length,n[t]=e.x2),e.shiftdownrow=t}return e*n.length}function He(t,e,n,r){for(let o=0;o<r.length;o++){if(n.start+o<e.start||n.start+o>e.stop)continue;const i=r[o];if(e.referenceseq[n.start+o-e.start]!=i.toUpperCase()){const e={opr:"X",start:n.start+o,len:1,s:i,cidx:n.cidx+o};t.push(e)}}}function Ve(t,e,n,r){if(n.returntemplatebox){const t=n.regions[e.segments[0].ridx];let o;if(t.width=n.widths[e.segments[0].ridx],r.asPaired)if(2==e.segments.length)o=e.segments[0].ridx!=e.segments[1].ridx?{qname:e.segments[0].qname,x1:e.x1,x2:e.x2,y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop))),multi_region:!0}:{qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))};else{const t=e.segments[0],r=n.regions[t.ridx];r.width=n.widths[t.ridx],o={qname:e.segments[0].qname,x1:Math.max(r.x,e.x1),x2:Math.min(e.x2,r.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))}}else o={qname:e.segments[0].qname,x1:Math.max(t.x,e.x1),x2:Math.min(e.x2,t.x+t.width),y1:e.y,y2:e.y+(e.height||n.stackheight),start:Math.min(...e.segments.map((t=>t.segstart))),stop:Math.max(...e.segments.map((t=>t.segstop)))},e.segments[0].isfirst&&(o.isfirst=!0),e.segments[0].islast&&(o.islast=!0);n.returntemplatebox.push(o)}for(let o=0;o<e.segments.length;o++){const i=e.segments[o],s=n.regions[i.ridx];if(s.width=n.widths[i.ridx],0==o){Ye(t,i,e.y,n,r);continue}const a=e.segments[o-1],l=n.regions[a.ridx];if(l.width=n.widths[a.ridx],a.x2<=i.x1||e.segments[0].ridx!=e.segments[1].ridx){Ye(t,i,e.y,n,r);const o=Math.floor(e.y+n.stackheight/2)+.5;if(t.strokeStyle=n.stackheight<=2?ne:Ot,t.setLineDash([5,3]),t.beginPath(),l.x==s.x?(t.moveTo(a.x2,o),t.lineTo(i.x1,o)):l.x<a.x2&&i.x1<s.width&&(t.moveTo(Math.min(a.x2,l.width),o),t.lineTo(Math.max(i.x1,s.x),o)),t.stroke(),n.overlapRP_hlline){const r=a.boxes.reduce(((t,e)=>t.start+t.len>e.start+e.len?t:e));if(r.start+r.len==i.boxes[0].start){t.strokeStyle=re,t.setLineDash([]),t.beginPath();const r=Math.floor(i.x1)+.5;t.moveTo(r,e.y),t.lineTo(r,e.y+n.stackheight),t.stroke()}}}else if(n.overlapRP_multirows){if(Ye(t,i,e.y+n.stackheight,n,r),n.overlapRP_hlline){const r=Math.floor(e.y+n.stackheight)+.5;t.strokeStyle=re,t.setLineDash([]),t.beginPath(),l.x<=a.x2&&i.x1<=s.width&&(t.moveTo(Math.max(i.x1,s.x),r),t.lineTo(Math.min(a.x2,l.width),r)),t.stroke()}}else Ye(t,i,e.y,n,r)}null!=e.__tempscore&&o().features.indel_read_alignment_scores&&(t.fillStyle="blue",t.font=n.stackheight+"pt Arial",t.fillText(e.__tempscore,r.regions[0].width-100,e.y+n.stackheight/2))}function Ye(t,e,n,r,o){const i=r.regions[e.ridx];i.width=r.widths[e.ridx];for(const o of e.boxes){const s=i.x+i.scale(o.start);if("P"!=o.opr&&"H"!=o.opr&&"I"!=o.opr)if("D"!=o.opr&&"N"!=o.opr)if("*"!=o.opr){if("X"!=o.opr&&"S"!=o.opr){if("M"!=o.opr&&"="!=o.opr)throw"unknown opr at rendering: "+o.opr;if(i.to_qual&&o.qual){let a=s;o.qual.forEach((o=>{e.rnext?t.fillStyle=Ft(o/we):e.discord_orientation?t.fillStyle=Vt(o/we):e.discord_wrong_insertsize?t.fillStyle=Lt(o/we):e.discord_unmapped2?t.fillStyle=Wt(o/we):t.fillStyle=Rt(o/we),a+i.ntwidth+_e<i.width&&i.x<=a?t.fillRect(a,n,i.ntwidth+_e,r.stackheight):a<i.width&&a+i.ntwidth+_e>=i.width&&i.x<=a?t.fillRect(a,n,i.width-a,r.stackheight):a<=i.x&&a+i.ntwidth+_e>i.x&&t.fillRect(i.x,n,i.ntwidth+_e+a-i.x,r.stackheight),a+=i.ntwidth}))}else o.qual?e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Ht:e.discord_wrong_insertsize?t.fillStyle=Dt:e.discord_unmapped2?t.fillStyle=Jt:t.fillStyle=Ot:i.to_printnt?t.fillStyle="white":e.rnext?t.fillStyle=Pt:e.discord_orientation?t.fillStyle=Ht:e.discord_wrong_insertsize?t.fillStyle=Dt:e.discord_unmapped2?t.fillStyle=Jt:t.fillStyle=Ot,s+o.len*i.ntwidth+_e<i.width&&s<i.width&&i.x<s+_e?t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight):s+o.len*i.ntwidth+_e<i.width&&i.x>=s?t.fillRect(i.x,n,o.len*i.ntwidth+_e+s-i.x,r.stackheight):s+o.len*i.ntwidth+_e>=i.width&&i.x<s?t.fillRect(s,n,i.width-s,r.stackheight):s+o.len*i.ntwidth+_e>=i.width&&i.x>=s&&t.fillRect(i.x,n,i.width-s,r.stackheight);if(i.to_printnt){t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial",o.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<o.s.length;e++)s+i.ntwidth*(e+.5)<i.width&&s<i.width&&i.x<=s+i.ntwidth*(e+.5)&&t.fillText(o.s[e],s+i.ntwidth*(e+.5),n+r.stackheight/2)}}else if(i.to_qual&&o.qual){i.to_printnt&&(t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial");let e=s;for(let s=0;s<o.qual.length;s++){const a=o.qual[s]/we;t.fillStyle="S"==o.opr?Gt(a):zt(a),e+i.ntwidth+_e<i.x+i.width&&i.x<=e?t.fillRect(e,n,i.ntwidth+_e,r.stackheight):e<i.x+i.width&&e+i.ntwidth+_e>=i.x+i.width&&i.x<=e?t.fillRect(e,n,i.width+i.x-e,r.stackheight):e<=i.x&&e+i.ntwidth+_e>i.x&&t.fillRect(i.x,n,i.ntwidth+_e+e-i.x,r.stackheight),i.to_printnt&&(o.qual?t.fillStyle="white":t.fillStyle="black",e+i.ntwidth/2<i.width&&e<i.width&&i.x<=e+i.ntwidth/2&&t.fillText(o.s[s],e+i.ntwidth/2,n+r.stackheight/2)),e+=i.ntwidth}}else if(t.fillStyle="S"==o.opr?Ut:$t,s+o.len*i.ntwidth+_e<i.width&&i.x<s?t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight):s+o.len*i.ntwidth+_e<i.width&&i.x>=s?t.fillRect(i.x,n,o.len*i.ntwidth+_e+s-i.x,r.stackheight):s+o.len*i.ntwidth+_e<=i.width&&i.x<s&&t.fillRect(s,n,i.width-s,r.stackheight),i.to_printnt&&!o.qual){t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial",o.qual?t.fillStyle="white":t.fillStyle="black";for(let e=0;e<o.s.length;e++)s+i.ntwidth*(e+.5)<i.width&&s<i.width&&i.x<=s+i.ntwidth*(e+.5)&&t.fillText(o.s[e],s+i.ntwidth*(e+.5),n+r.stackheight/2)}}else{if(i.to_qual&&o.qual){let a=s;o.qual.forEach((o=>{e.discord_unmapped2&&(t.fillStyle=Wt(o/we)),t.fillRect(a,n,i.ntwidth+_e,r.stackheight),a+=i.ntwidth}))}else e.discord_unmapped2&&(t.fillStyle=Jt),t.fillRect(s,n,o.len*i.ntwidth+_e,r.stackheight);i.to_printnt&&(t.font=Math.min(i.ntwidth,r.stackheight-2)+"pt Arial")}else{"D"==o.opr?t.strokeStyle=ee:t.strokeStyle=r.stackheight<=2?ne:Ot,t.setLineDash([]);const e=Math.floor(n+r.stackheight/2)+.5;if(t.beginPath(),t.moveTo(Math.max(s,i.x),e),t.lineTo(Math.min(s+o.len*i.ntwidth,i.x+i.width),e),t.stroke(),r.stackheight>ye){const e=Math.max(i.x,s),a=Math.min(i.x+i.width,s+o.len*i.ntwidth);if(a-e>=50){const s=Math.min(ve,Math.max(be,r.stackheight-2));t.font=s+"pt Arial";const l=t.measureText(o.len+" bp").width;l<a-e-20&&(t.fillStyle="white",(a+e)/2+l/2<i.width&&i.x<(a+e)/2-l/2?(t.fillRect((a+e)/2-l/2,n,l,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2<i.width&&i.x>=(a+e)/2-l/2?(t.fillRect(i.x,n,l+(a+e)/2-l/2-i.x,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)):(a+e)/2+l/2>=i.width&&i.x<(a+e)/2-l/2&&(t.fillRect((a+e)/2-l/2,n,i.width-(a+e)/2+l/2,r.stackheight),t.fillStyle=Ot,t.fillText(o.len+" bp",(a+e)/2,n+r.stackheight/2)))}}}}!function(t,e,n,r,o){if(!n.canClipArrowhead)return;if(e.x2-e.x1<5)return;if(e.forward){const i=Math.ceil(e.x2+_e);i<=r.width+n.stackheight/2&&(t.fillStyle="white",t.beginPath(),t.moveTo(i-n.stackheight/2,o),t.lineTo(i,o),t.lineTo(i,o+n.stackheight/2),t.lineTo(i-n.stackheight/2,o),t.closePath(),t.fill(),t.beginPath(),t.moveTo(i-n.stackheight/2,o+n.stackheight),t.lineTo(i,o+n.stackheight),t.lineTo(i,o+n.stackheight/2),t.lineTo(i-n.stackheight/2,o+n.stackheight),t.closePath(),t.fill())}else{const i=e.x1;i>=r.x&&(t.fillStyle="white",t.beginPath(),t.moveTo(i+n.stackheight/2,o),t.lineTo(i,o),t.lineTo(i,o+n.stackheight/2),t.lineTo(i+n.stackheight/2,o),t.closePath(),t.fill(),t.beginPath(),t.moveTo(i+n.stackheight/2,o+n.stackheight),t.lineTo(i,o+n.stackheight),t.lineTo(i,o+n.stackheight/2),t.lineTo(i+n.stackheight/2,o+n.stackheight),t.closePath(),t.fill())}}(t,e,r,i,n),e.rnext&&(i.to_qual||e.x2-e.x1>=20&&r.stackheight>=7&&(t.font=Math.min(Qt,Math.max(te,r.stackheight-4))+"pt Arial",t.fillStyle="white",t.fillText((o.nochr?"chr":"")+e.rnext,(e.x1+e.x2)/2,n+r.stackheight/2,e.x2-e.x1)))}function Ke(t,e,n,r){for(const[t,n]of e.regions.entries()){if(!n.to_printnt)continue;const e=new Set;for(const o of r)for(const r of o.segments){if(r.ridx!=t)continue;const o=r.boxes.filter((t=>"I"==t.opr));if(o.length)for(const t of o)e.add(n.x+n.scale(t.start))}}for(const n of r)for(const r of n.segments){const o=e.regions[r.ridx],i=r.boxes.filter((t=>"I"==t.opr));if(i.length){t.font=Math.max(Qt,e.stackheight-2)+"pt Arial";for(const s of i){const i=o.x+o.scale(s.start);s.qual?t.fillStyle=Xt(s.qual.reduce(((t,e)=>t+e),0)/s.qual.length/we):t.fillStyle=Yt;const a=1==s.s.length?s.s:s.s.length;t.fillText(a,i,n.y+e.stackheight*(r.on2ndrow||0)+e.stackheight/2)}}}}async function Xe(t,e,n){const r=Je(t.qual),o=['<td style="color:black;text-align:left">Read</td>'];for(const e of t.boxes)for(let n=0;n<e.len;n++){t.seq[e.cidx+n];o.push('<td style="background:'+Rt(r[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>")}const i=[];i.push('<li><span style="background:'+Jt+';color:white">This segment in template is unmapped</span></li>'),1&t.flag&&i.push("<li>Template has multiple segments</li>"),2&t.flag&&i.push("<li>Each segment properly aligned</li>"),16&t.flag&&i.push("<li>Reverse complemented</li>"),32&t.flag&&i.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&i.push("<li>This is the first segment in the template</li>"),128&t.flag&&i.push("<li>This is the last segment in the template</li>"),256&t.flag&&i.push("<li>Secondary alignment</li>"),512&t.flag&&i.push("<li>Not passing filters</li>"),1024&t.flag&&i.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&i.push("<li>Supplementary alignment</li>");let s={seq:t.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center">\n\t\t\t <tr style="color:white">${o.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE</span>: ${Math.abs(t.seq.length)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${i.join("")}</ul>`};return t.discord_unmapped2&&(s.unmapped_mate=!0),s}async function Qe(t,e,n){const r=t.boxes[0].start,o=t.boxes[t.boxes.length-1],i=o.start+o.len,s=await Be(e,n.chr+":"+(r+1)+"-"+i),a=Je(t.qual),l=["<td>Reference</td>"],c=['<td style="color:black;text-align:left">Read</td>'];for(const e of t.boxes)if("H"!=e.opr)if("I"!=e.opr)if("D"!=e.opr&&"N"!=e.opr)if("S"!=e.opr)if("M"!=e.opr&&"="!=e.opr&&"X"!=e.opr&&"*"!=e.opr);else for(let n=0;n<e.len;n++){const o=s[e.start-r+n],i=t.seq[e.cidx+n];l.push("<td>"+o+"</td>"),"*"==t.qual?c.push('<td style="color:black;background:'+(o.toUpperCase()==i.toUpperCase()?Rt:zt)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+(o.toUpperCase()==i.toUpperCase()?Rt:zt)(a[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>")}else for(let n=0;n<e.len;n++)l.push("<td>"+s[e.start-r+n]+"</td>"),"*"==t.qual?c.push('<td style="background:'+Gt(1)+'">'+t.seq[e.cidx+n]+"</td>"):c.push('<td style="background:'+Gt(a[e.cidx+n]/we)+'">'+t.seq[e.cidx+n]+"</td>");else if(e.len>=Te)l.push('<td style="font-size:.8em;opacity:.5;white-space:nowrap">'+e.len+" bp</td>"),c.push('<td style="color:black;white-space:nowrap">-----------</td>');else for(let t=0;t<e.len;t++)l.push("<td>"+s[e.start-r+t]+"</td>"),c.push('<td style="color:black">-</td>');else for(let n=e.cidx;n<e.cidx+e.len;n++)l.push("<td>-</td>"),"*"==t.qual?c.push('<td style="color:'+Yt+';background:white">'+t.seq[n]+"</td>"):c.push('<td style="color:'+Yt+";background:"+Rt(a[n]/we)+'">'+t.seq[n]+"</td>");let u=0,f=0,d=[],h=[],p=0;for(const e of t.boxes)u=f,f+=e.len,"S"==e.opr&&(p=1,d.push(u),h.push(f));const m=[];t.rnext&&m.push('<li>Next segment on <span style="background:'+Pt+'">'+(n.nochr?"chr":"")+t.rnext+", "+t.pnext+"</span></li>"),t.discord_wrong_insertsize&&t.discord_orientation?m.push('<li><span style="background:'+Dt+';color:white">Wrong insert size</span> mate position: '+t.pnext+'</li><li><span style="background:'+Ht+';color:white">Segments also having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_wrong_insertsize?m.push('<li><span style="background:'+Dt+';color:white">Wrong insert size</span> mate position: '+t.pnext+"</li>"):t.discord_orientation?m.push('<li><span style="background:'+Ht+';color:white">Segments having wrong orientation</span> '+t.discord_orientation_direction+"</li>"):t.discord_unmapped2&&m.push('<li><span style="background:'+Jt+';color:white">Other segment in template is unmapped</span></li>'),1&t.flag&&m.push("<li>Template has multiple segments</li>"),2&t.flag&&m.push("<li>Each segment properly aligned</li>"),16&t.flag&&m.push("<li>Reverse complemented</li>"),32&t.flag&&m.push("<li>Next segment in the template is reverse complemented</li>"),64&t.flag&&m.push("<li>This is the first segment in the template</li>"),128&t.flag&&m.push("<li>This is the last segment in the template</li>"),256&t.flag&&m.push("<li>Secondary alignment</li>"),512&t.flag&&m.push("<li>Not passing filters</li>"),1024&t.flag&&m.push("<li>PCR or optical duplicate</li>"),2048&t.flag&&m.push("<li>Supplementary alignment</li>");let g={seq:t.seq,alignment:`<table style="border-spacing:0px;border-collapse:separate;text-align:center;font-family:courier">\n\t\t\t <tr style="opacity:.6">${l.join("")}</tr>\n\t\t\t <tr style="color:white">${c.join("")}</tr>\n\t\t\t</table>`,info:`<div style='margin-top:10px'>\n\t\t\t<span style="opacity:.5;font-size:.7em">CHR</span>: ${n.chr.replace("chr","")},\n\t\t\t<span style="opacity:.5;font-size:.7em">START</span>: ${t.segstart_original+1},\n\t\t\t<span style="opacity:.5;font-size:.7em">STOP</span>: ${i},\n\t\t\t<span style="opacity:.5;font-size:.7em">READ LENGTH</span>: ${t.seq.length} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">TEMPLATE LENGTH</span>: ${Math.abs(t.tlen)} bp,\n\t\t\t<span style="opacity:.5;font-size:.7em">CIGAR</span>: ${t.cigarstr}\n\t\t\t<span style="opacity:.5;font-size:.7em">FLAG</span>: ${t.flag}\n\t\t\t<span style="opacity:.5;font-size:.7em">NAME: ${t.qname}</span>\n\t\t </div>\n\t\t <ul style='padding-left:15px'>${m.join("")}</ul>`,start_readpos:r+1,boxes:t.boxes,readpanel_DN_maxlength:Te};return 1==p&&(g.soft_starts=d,g.soft_stops=h),t.discord_unmapped2&&(g.unmapped_mate=!0),g}function tn(t){const e=yt().createHmac("md5",je),n=[t.get("X-Auth-Token")||t.cookies.sessionid,t.query.gdcFileUUID,t.query.gdcFilePosition];return e.update(n.join("")).digest("hex")+".bam"}async function en(t){const e=t.query.regions;if(!Array.isArray(e)||0==e.length)throw"req.query.regions[] not non-empty array";const n=[];for(const r of e){const e=await nn(r.chr,r.start,r.stop,t.get("X-Auth-Token"),t.query.gdcFileUUID,tn(t),t.cookies.sessionid);n.push({filesize:e})}return n}async function nn(t,e,n,r,i,s,a){const l={compression:!1};a?l.Cookie=`sessionid=${a}`:l["X-Auth-Token"]=r;const c=y().join(o().cachedir_bam,s),u=Ce+"/slicing/view/"+i+"?region="+t+":"+e+"-"+n;try{if(await P.yE(c)&&(await Et(b().stream(u,{method:"GET",headers:l}),m().createWriteStream(c)),await P.yE(c)))throw"BAM file slice is not found after downloading";const t=c+".bai";if(await P.yE(t)&&(await async function(t){await P.UE({isbam:!0,args:["index",t],callback:()=>{}})}(c),await P.yE(t)))throw"index file is missing after indexing";const e=await m().promises.stat(c);return(0,F.bplen)(e.size,!0)}catch(t){throw t.stack&&console.log(t.stack),"Error with BAM slicing: "+(t.message||t)}}const rn="Unannotated";function on(t){return t.file?t.file:t.file2?t.file2:t.url}function sn(t,e,n,r){const o=[];for(const i of t.samples)if(Number.isFinite(i.readcount)&&(i.readcount=Math.floor(i.readcount),!(i.readcount<=0||e.readcountCutoff&&i.readcount<e.readcountCutoff))){if(r.samples&&n.cohort&&n.cohort.annotation){const t=r.samples[i.i];if(!t)continue;const o=n.cohort.annotation[t];if(i.anno=o,e.cohortOnlyAttr&&n.cohort&&n.cohort.annotation){if(!o)continue;let t=!1;for(const n in e.cohortOnlyAttr){const r=o[n];if(r&&e.cohortOnlyAttr[n][r]){t=!0;break}}if(!t)continue}if(e.cohortHiddenAttr&&n.cohort&&n.cohort.annotation&&n.cohort.attributes){if(!o)continue;let t=!1;for(const r in e.cohortHiddenAttr){n.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const i=o[r];if(i){if(e.cohortHiddenAttr[r][i]){t=!0;break}}else if(e.cohortHiddenAttr[r][rn]){t=!0;break}}if(t)continue}}if(i.events&&e.spliceEventPercentage){let n=!1;for(const r in i.events){if(!t.events[r])continue;const o=t.events[r].attrValue,s=e.spliceEventPercentage[o];if(!s)continue;const a=i.events[r].percentage;if(null!=a)if(">"==s.side){if(a<=s.value){n=!0;break}}else if(a>=s.value){n=!0;break}}if(n)continue}o.push(i)}return o}function an(t,...e){if(0==t.length)return 0;const n=t.sort(((t,e)=>t.readcount-e.readcount)),r=[];return e.forEach((t=>{!Number.isFinite(t)||t<0||t>1?r.push(null):r.push(n[Math.floor(n.length*t)].readcount)})),r}var ln=n(1169);function cn(t){return new Promise(((e,n)=>{const r=O().createInterface({input:m().createReadStream(t.file,{encoding:"utf8"})}),o=[];let i=!0;r.on("line",(e=>{if(i)return void(i=!1);const n=e.split("\t"),[s,a,l,c,u,f]=n[0].split(/[:,]/);if(s!=t.chr)return;const d=Number.parseInt(a),h=Number.parseInt(u);if(Number.isNaN(d)||Number.isNaN(h))return;const p=d-1,m=h-1;if(p>t.start&&p<t.stop||m>t.start&&m<t.stop){const t=Number.parseInt(n[1]),e=n[2];o.push({chr:s,start:p,stop:m,type:e,rawdata:[t]})}else p>t.stop&&r.close()})),r.on("close",(()=>{e(o)}))}))}const un=new Set(["-1","0","1","2"]);function fn(t,e){t[0];const n=Number(t[1]),r=(t[2],t[3].split(".")[0]),o=t[5];if("+"!=o&&"-"!=o)return{name:r};const i="+"==o,s=Number(t[6]),a=Number(t[7]);if(!Number.isInteger(s)||!Number.isInteger(a))return{name:r,strand:o};const l=[],c=[],u=[],f=[],d=[],h=t[15],p=t[17],m=t[20];if(!t[10].includes(",")||!t[11].includes(","))return{name:r,strand:o};const g=t[10].split(",");g.pop();const y=g.map(Number),v=t[11].split(",");v.pop();const b=v.map(Number);if(y.includes(NaN)||b.includes(NaN))return{name:r,strand:o};let w=null,_=0,x=0;for(const[t,e]of y.entries()){_+=e;const r=n+b[t],o=r+e;i?d.push([r,o]):d.unshift([r,o]),t>0&&(i?f.push([w,r]):f.unshift([w,r])),w=o,r<s?o<s?i?c.push([r,o]):l.unshift([r,o]):(i?c.push([r,s]):l.unshift([r,s]),o>a?(s<a&&(i?u.push([s,a]):u.unshift([s,a]),x+=a-s),i?l.push([a,o]):c.unshift([a,o])):s<o&&(i?u.push([s,o]):u.unshift([s,o]),x+=o-s)):r<a?o<=a?r<o&&(i?u.push([r,o]):u.unshift([r,o]),x+=o-r):(r<a&&(i?u.push([r,a]):u.unshift([r,a]),x+=a-r),i?l.push([a,o]):c.unshift([a,o])):i?l.push([r,o]):c.unshift([r,o])}const k={name:p,isoform:r,strand:o,exon:d,rnalen:_};26==t.length&&(k.category=m),e&&e.has(r)&&(k.description=e.get(r)),f.length>0&&(k.intron=f),s==a||(k.cdslen=x,k.codingstart=s,k.codingstop=a,k.coding=u,c.length&&(k.utr5=c),l.length&&(k.utr3=l));const q=h.split(",");return q.pop(),q.length<1||q.some((t=>!un.has(t)))||function(t,e){if(!t.codingstart)return;const n="+"==t.strand?t.codingstart:t.codingstop;let r=t.exon.findIndex((t=>t[1]>=n&&t[0]<=n));if(-1==r)throw"start codon not matched to an exon: "+JSON.stringify(t);"-"==t.strand&&(r=t.exon.length-r-1);const o=e.split(",")[r];if("-1"==o)throw"start codon frame is -1: "+t.isoform;if("0"!=o){if("1"!=o&&"2"!=o)throw"start codon frame not 0/1/2: "+o+" "+t.isoform;t.startCodonFrame=Number.parseInt(o)}}(k,h),k}const dn=1,hn=10,pn=400,mn=600,gn=50,yn="rgba(122,103,44,.7)",vn="red",bn="#edad0c",wn="rgba(255,0,0,.5)",_n="#ccc";function xn(t,e,n,r,o){if(!t)return;if(!o.name&&!o.isoform)return;const i=[];o.name&&i.push(o.name),o.isoform&&i.push(o.isoform),t.push({chr:o.chr,start:o.start,stop:o.stop,x1:e,x2:n,y:r,isoform:o.isoform,name:i.join(" ")})}function kn(t,e,n,r,o,i){const s=i/2,a=i/2,l=Math.max(i/2,6);if(o-2*s<a)return;const c=Math.ceil((o-2*s)/(a+l));if(c<=0)return;const u="+"==e;let f=Math.ceil(n+(o-a*c-l*(c-1))/2);for(let e=0;e<c;e++)t.beginPath(),u?(t.moveTo(f,r),t.lineTo(f+a,r+i/2),t.moveTo(f+a,r+i/2+1),t.lineTo(f,r+i)):(t.moveTo(f+a,r),t.lineTo(f,r+i/2),t.moveTo(f,r+i/2+1),t.lineTo(f+a,r+i)),t.stroke(),f+=a+l}function qn(t,e){return new Promise(((n,r)=>{const i=(0,q.spawn)(o().gfServer,["status",e.blat.host,e.blat.port]),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(e=>{a.join("").trim()&&n(t+" OFF");const r=s.join("").trim().split("\n");let o=0;for(const t of r)t.startsWith("blat requests")&&(o=t.split(" ")[2]);n(t+" ON, "+o+" requests")}))}))}function Nn(t,e){const n=y().join(o().cachedir,Math.random().toString());return new Promise(((r,i)=>{const s=(0,q.spawn)(o().gfClient,[t.blat.host,t.blat.port,t.blat.seqDir,e,n,"-q=dna","-nohead","-minScore=20","-minIdentity=0","-out=psl"]),a=[];s.stderr.on("data",(t=>a.push(t))),s.on("close",(t=>{const e=a.join("");e&&(console.log("BLAT error",e),i("blat server problem")),r(n)}))}))}var Sn=n(9064),An=n(1575);const Mn=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",Tn=Mn+(Mn.includes("/v0")?"":"/v0")+"/graphql",Cn="https://uat-api.gdc.cancer.gov",jn=y().join(Mn,"ssm_occurrences/_mapping"),En="ssm_occurrence_centrics";async function On(t){const e=new Map,n=await b()(jn,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid JSON from GDC dictionary"}if(!r._mapping)throw"returned data does not have ._mapping";if(!Array.isArray(r.fields))throw".fields not array";if(!Array.isArray(r.nested))throw".nested not array";const i=new Set(r.nested);let s=0,a=0,l=0,c=0,u=0,f=0;for(const t of r.fields){if(Dn(t)){s++;continue}const n=t.split(".");for(let t=1;t<n.length;t++){const o=n.slice(0,t).join("."),s=o+"."+n[t],f=n[t][0].toUpperCase()+n[t].slice(1).replace(/_/g," "),d={id:s.toLowerCase(),name:f,included_types_set:new Set,child_types_set:new Set};if(t==n.length-1){d.isleaf=!0;const t=r._mapping[En+"."+s];t&&("keyword"==t.type?(d.type="categorical",l++):"long"==t.type?(d.type="integer",c++):"double"==t.type?(d.type="float",u++):console.log("GDC !!! ERR !!! Unknown variable type: "+t.type)),d.type||a++,In(d)}if(1==t);else if(d.parent_id=o,d.type){d.included_types_set.add(d.type);let t=e.get(o);for(;t&&(t.included_types_set.add(d.type),t.child_types_set.add(d.type),t.parent_id);)t=e.get(t.parent_id)}i.has(s)&&(d.isObjectList=!0),e.set(s,d)}}await async function(t){const e=[],n=new Map;for(const r of t.values()){if("integer"!=r.type&&"float"!=r.type)continue;if(Pn[r.id]){r.bins=Pn[r.id];continue}const t=r.id.replace("case.","").replace(/\./g,"__");n.set(t,r.id),e.push(t+" {\n\t\t stats {\n\t\t\t\tMin : min\n\t\t\t\tMax: max\n\t\t\t\tMean: avg\n\t\t\t\tSD: std_deviation\n\t\t\t\tcount\n\t\t\t}\n\t\t\trange(ranges: $filters2) {\n\t\t\t buckets {\n\t\t\t\tdoc_count\n\t\t\t\tkey\n\t\t\t }\n\t\t\t}\n\t\t}")}if(0==e.length)throw"GDC: no numeric terms";const r=`\n\t query ContinuousAggregationQuery($caseFilters: FiltersArgument, $filters: FiltersArgument, $filters2: FiltersArgument) {\n\t viewer {\n\t\texplore {\n\t\t cases {\n\t\t\taggregations(case_filters: $caseFilters, filters: $filters) {\n\t\t\t\t${e.join("\n")}\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t}`,o={caseFilters:{},filters:{},filters2:{op:"range",content:[{ranges:[{from:0,to:1}]}]}};try{var i,s,a,l;let e=0,c=0;const u=await b().post(Tn,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:r,variables:o})}),f=JSON.parse(u.body);if("object"!=typeof(null===(i=f.data)||void 0===i||null===(s=i.viewer)||void 0===s||null===(a=s.explore)||void 0===a||null===(l=a.cases)||void 0===l?void 0:l.aggregations))throw"return not object: re.data.viewer.explore.cases.aggregations{}";for(const[r,o]of n){const n=t.get(o);if(!(r in f.data.viewer.explore.cases.aggregations)){console.log("GDC: no stats object returned for numeric term",o),n.bins=Rn,c++;continue}const i=f.data.viewer.explore.cases.aggregations[r].stats;if("object"!=typeof i){console.log("GDC: aggregations[facet].stats{} is not object"),n.bins=Rn,c++;continue}if(!Number.isFinite(i.Max)||!Number.isFinite(i.Min)){n.bins=Rn,c++;continue}if(i.Max<=i.Min){n.bins=Rn,c++;continue}const s=(i.Max-i.Min)/5,a="integer"==n.type?Math.ceil(s):s;n.bins={default:{mode:"discrete",type:"regular-bin",bin_size:a,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:i.Min+a}}},e++}console.log(`GDC default binning: ${e} assigned, ${c} unassigned`)}catch(t){console.log(t.message||t)}}(e);for(const t of e.values())t.type||f++,t.included_types=[...t.included_types_set],t.child_types=[...t.child_types_set],delete t.included_types_set,delete t.child_types_set;console.log("GDC dictionary:",e.size,"total variables,",s,"lines skipped,",a,"lines with unknown term type,","categorical="+l,"integer="+c,"float="+u,"parent="+f),Object.freeze(e),function(t,e){const n=t.cohort.termdb.q={};async function r(e,n){if(0==e.length||!n)return;const r=await t.termdb.termid2totalsize2.get(e.map((t=>t.id)),JSON.parse(n));for(const t of e)if(t){const e=r.get(t.id);"categorical"==t.type&&e?e.length?t.samplecount=e.map((t=>t[1])).reduce(((t,e)=>t+e)):(t.disabled=!0,t.samplecount=0):"integer"!=t.type&&"float"!=t.type||(t.samplecount=e.total,0==e.total&&(t.disabled=!0))}}n.getRootTerms=async(t,n=null)=>{const o=[];for(const t of e.values())null==t.parent_id&&o.push(JSON.parse(JSON.stringify(t)));return await r(o,n),o},n.getTermChildren=async(t,n=null,o=null)=>{const i=[];for(const n of e.values())n.parent_id==t&&i.push(JSON.parse(JSON.stringify(n)));return await r(i,o),i},n.findTermByName=async(t,n=null,o,i=null,s=null)=>{(t=t.toLowerCase()).includes(" ")&&(t=t.replace(/\s/g,"_"));const a=[];for(const n of e.values())s&&!(0,An.CG)(n,s)||n.id.includes(t)&&a.push(JSON.parse(JSON.stringify(n)));return await r(a,i),a},n.getAncestorIDs=t=>{if(!e.has(t))return;const n=t.split("."),r=[];for(let t=1;t<n.length;t++)r.push(n.slice(0,t+1).join("."));return r},n.getAncestorNames=n.getAncestorIDs,n.termjsonByOneid=t=>{const n=e.get(t);return n?JSON.parse(JSON.stringify(n)):null},n.getSupportedChartTypes=()=>{const t={},n={};for(const r of e.values())r.type&&(r.cohort in t||(t[r.cohort]=["barchart","table","regression"],n[r.cohort]=0),"survival"!=r.type||t[r.cohort].includes("survival")||t[r.cohort].push("survival"),"condition"!=r.type||t[r.cohort].includes("cuminc")||t[r.cohort].push("cuminc"),"float"!=r.type&&"integer"!=r.type||(n[r.cohort]+=r.samplecount));for(const e in n)n[e]>0&&t[e].push("boxplot"),n[e]>1&&t[e].push("scatterplot");return t}}(t,e),t.cohort.termdb.termtypeByCohort=[],l&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"categorical"}),c&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"integer"}),u&&t.cohort.termdb.termtypeByCohort.push({cohort:"",type:"float"}),t.__gdc={aliquot2submitter:{cache:new Map,get:async e=>t.__gdc.aliquot2submitter.cache.has(e)?t.__gdc.aliquot2submitter.cache.get(e):e},map2caseid:{cache:new Map,get:e=>t.__gdc.map2caseid.cache.get(e)},caseid2submitter:new Map,caseIds:new Set,casesWithExpData:new Set,gdcOpenProjects:new Set,doneCaching:0},await async function(t){var e,n,r;const o={"Content-Type":"application/json",Accept:"application/json"},i={filters:{op:"and",content:[{op:"=",content:{field:"access",value:"open"}},{op:"=",content:{field:"data_type",value:"Masked Somatic Mutation"}}]},facets:"cases.project.project_id",size:0},s=await b()(y().join(Mn,"files"),{method:"POST",headers:o,body:JSON.stringify(i)}),a=JSON.parse(s.body);if(!Array.isArray(null==a||null===(e=a.data)||void 0===e||null===(n=e.aggregations)||void 0===n||null===(r=n["cases.project.project_id"])||void 0===r?void 0:r.buckets))return void console.log("getting open project_id but return is not re.data.aggregations['cases.project.project_id'].buckets[]");for(const e of a.data.aggregations["cases.project.project_id"].buckets)e.key&&t.__gdc.gdcOpenProjects.add(e.key);console.log("GDC open-access projects:",t.__gdc.gdcOpenProjects.size)}(t),async function(){try{{const t=y().join(Mn,"ssms"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"ssm_occurrences"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"cases"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"files"),e=await Ln(t);if(e)throw`${t}: ${e}`}{const t=y().join(Mn,"analysis/top_mutated_genes_by_project"),e=await Ln(t);if(e)throw`${t}: ${e}`}await async function(t){const e=new Date;try{const e="query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\tprimary_site {buckets { doc_count, key }}\n\t\t\t\t}\n\t\t\t}\n\t\t}}";await b().post(t,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:e,variables:{}})})}catch(e){throw"gdc api down: "+t}console.log("GDC GraphQL API okay: "+t,new Date-e,"ms")}(Tn)}catch(t){console.error(`\n##########################################\n#\n# GDC API unavailable\n# ${Mn}\n# ${Tn}\n#\n##########################################`)}}(),async function(t){if("stopGdcCacheAliquot"in o().features){if(!Number.isInteger(o().features.stopGdcCacheAliquot))return void console.log("GDC: sample IDs are not cached!");console.log("GDC: running limited sample ID caching")}else console.log("GDC: caching complete sample ID mapping");try{const e=await $n(t,1,0);if(!Number.isInteger(e))throw"gdc totalCases not integer";const n=new Date;console.log("GDC: Start to cache sample IDs of",e,"cases...");const r=1e3;for(let n=0;n<Math.ceil(e/r)&&(await $n(t,r,1e3*n),!(Number.isInteger(o().features.stopGdcCacheAliquot)&&n>=o().features.stopGdcCacheAliquot));n++);await async function(t){const e=`${Cn}/gene_expression/availability`;{const t=await Ln(e);if("ERR_NON_2XX_3XX_RESPONSE"==t);else if(t)return}try{var n;const r=[...t.__gdc.caseIds],o=await b().post(e,{headers:{"Content-Type":"application/json"},body:JSON.stringify({case_ids:r,gene_ids:["ENSG00000141510"]})}),i=JSON.parse(o.body);if(!Array.isArray(null===(n=i.cases)||void 0===n?void 0:n.details))throw"re.cases.details[] not array";for(const e of i.cases.details)e.has_gene_expression_values&&t.__gdc.casesWithExpData.add(e.case_id);delete t.__gdc.caseIds}catch(t){throw t}}(t),t.__gdc.doneCaching=!0,console.log("GDC: Done caching sample IDs. Time:",Math.ceil((new Date-n)/1e3),"s"),console.log("\t",t.__gdc.aliquot2submitter.cache.size,"aliquot IDs to sample submitter id,"),console.log("\t",t.__gdc.caseid2submitter.size,"case uuid to submitter id,"),console.log("\t",t.__gdc.map2caseid.cache.size,"different ids to case uuid,"),console.log("\t",t.__gdc.casesWithExpData.size,"cases with gene expression data.")}catch(t){console.log("Error at caching: "+t)}}(t)}function In(t){"case.diagnoses.age_at_diagnosis"!=t.id||(t.valueConversion={scaleFactor:1/365,fromUnit:"day",toUnit:"year"})}const Rn={default:{mode:"discrete",type:"regular-bin",bin_size:1,startinclusive:!1,stopinclusive:!0,first_bin:{startunbounded:!0,stop:0},last_bin:{start:1,stopunbounded:!0}}},Pn={"case.diagnoses.age_at_diagnosis":{default:{type:"custom-bin",mode:"discrete",lst:[{startunbounded:!0,stop:10950,stopinclusive:!0,label:"<=30 years"},{start:10950,stop:21900,stopinclusive:!0,label:"30-60 years"},{start:21900,stopunbounded:!0,startinclusive:!1,label:">60years"}]}}};const Fn=new Set(["case.consent_type","case.days_to_consent","case.days_to_index"]);function Dn(t){return!!(t.startsWith("ssm")||t.startsWith("case.observation")||t.startsWith("case.available_variation_data"))||(!(!t.endsWith("_id")||t.endsWith("project_id"))||(!!Fn.has(t)||void 0))}async function Ln(t){try{const e=new Date;await b()(t),console.log("GDC API okay: "+t,new Date-e,"ms")}catch(e){if(e.code)return e.code;throw"gdc api down: "+t}}async function $n(t,e,n,r){var o,i,s;const a=["fields=submitter_id,samples.portions.analytes.aliquots.aliquot_id,samples.submitter_id"];if(r)a.push('filters={"op":"and","content":[{"op":"=","content":{"field":"samples.portions.analytes.aliquots.aliquot_id","value":["'+r+'"]}}]}');else{if(!Number.isInteger(e)||!Number.isInteger(n))throw"size and from not integers";a.push("size="+e),a.push("from="+n)}const l=await b()(Mn+"/cases?"+a.join("&")),c=JSON.parse(l.body);if(!Array.isArray(null==c||null===(o=c.data)||void 0===o?void 0:o.hits))throw"re.data.hits[] not array";for(const e of c.data.hits){const n=e.id;if(!n)throw"h.id (case uuid) missing";t.__gdc.caseIds.add(n);const r=e.submitter_id;if(!r)throw"h.submitter_id missing";if(t.__gdc.caseid2submitter.set(n,r),t.__gdc.map2caseid.cache.set(r,n),Array.isArray(e.samples))for(const r of e.samples){const e=r.submitter_id;if(!e)throw"sample.submitter_id missing";if(t.__gdc.map2caseid.cache.set(e,n),Array.isArray(r.portions))for(const o of r.portions)if(Array.isArray(o.analytes))for(const r of o.analytes)if(Array.isArray(r.aliquots))for(const o of r.aliquots){const r=o.aliquot_id;if(!r)throw"aliquot.aliquot_id missing";t.__gdc.aliquot2submitter.cache.set(r,e),t.__gdc.map2caseid.cache.set(r,n)}}}return null===(i=c.data)||void 0===i||null===(s=i.pagination)||void 0===s?void 0:s.total}var Zn=n(4973),zn=n(3625),Un=n(478),Bn=n(8907),Gn=n(394);function Jn(t,e){if(e.updateAttr&&!t.label){for(const n of e.updateAttr){let e=t;for(const t of n)if(e)if("object"==typeof t)for(const n in t)e[n]=t[n];else e=e[t]}t.label&&delete e.updateAttr}}function Wn(t,e,n){var r,i;if(null===(r=t.cohort)||void 0===r||null===(i=r.db)||void 0===i||!i.refresh)return;const s=t.cohort.db.refresh;delete t.cohort.db.refresh,e.get(`${n}/${s.route}`,(async(e,n)=>{n.send({label:t.label,files:[]})})),e.post(`${n}/${s.route}`,(async(e,n)=>{try{var r,i;const s=null!==(r=t.cohort.db)&&void 0!==r&&null!==(i=r.file)&&void 0!==i&&i.startsWith(o().tpmasterdir)?t.cohort.db.file:y().join(o().tpmasterdir,t.cohort.db.file||""),a=e.body;if(!a.dbfile)throw"Updating input text files via the termdb-refresh page has been deprecated.Please use the buildTermdb.bundle.js. pipeline before triggering this route to replace the db file.";{const e=y().join(o().tpmasterdir,a.dbfile);if(!await m().stat(e))throw`dbfile not found: '${e}'`;const n=t.cohort.db.file_fullpath||s;if(e===n)throw"db file source and target are the same";console.log(`copying ${e} to ${n}`),await m().copyFile(e,n)}await er(t),n.send({status:"ok"})}catch(t){console.log(t),n.send({error:t.error||t})}}))}var Hn=n(2188),Vn=n(2974),Yn=n(3795),Kn=n(7934);const Xn="Unannotated";async function Qn(t,e,n,r=null,i=null){var s,a;await er(t),t.queries&&(await async function(t,e){const n=t.queries.snvindel;if(!n)return;if(n.url){if(!n.url.base)throw".snvindel.url.base missing";if(!n.url.key)throw".snvindel.url.key missing"}if(!n.byisoform&&!n.byrange)throw"byisoform and byrange are both missing on queries.snvindel";if(n.byrange)if(n.byrange.gdcapi)ln.xq(t);else if(n.byrange.bcffile){var r;n.byrange.bcffile=n.byrange.bcffile.startsWith(o().tpmasterdir)?n.byrange.bcffile:y().join(o().tpmasterdir,n.byrange.bcffile),n.byrange._tk={file:n.byrange.bcffile},n.byrange.get=await or(t,e),null!==(r=n.byrange._tk)&&void 0!==r&&r.samples.length||delete n.byrange._tk.samples,rr(t,n.byrange._tk.samples,"snvindel.byrange.bcffile")}else{if(!n.byrange.chr2bcffile)throw"unknown query method for queries.snvindel.byrange";n.byrange._tk={chr2files:{}};for(const t in n.byrange.chr2bcffile)n.byrange._tk.chr2files[t]={file:y().join(o().tpmasterdir,n.byrange.chr2bcffile[t])};delete n.byrange.chr2bcffile,n.byrange.get=await or(t,e),n.byrange._tk.samples.length||delete n.byrange._tk.samples,rr(t,n.byrange._tk.samples,"snvindel.byrange.bcffile")}if(n.byisoform){if(!n.byisoform.gdcapi)throw"unknown query method for queries.snvindel.byisoform";ln.CN(t)}if(n.m2csq){if(!n.m2csq.by)throw".by missing from queries.snvindel.m2csq";if("ssm_id"!=n.m2csq.by)throw"unknown value of queries.snvindel.m2csq.by";if(!n.m2csq.gdcapi)throw"unknown query method for queries.snvindel.m2csq";ln.wm(t)}}(t,e),await async function(t,e){const n=t.queries.svfusion;if(!n)return;if(!n.byrange)throw"byrange missing from queries.svfusion";if(n.byrange){if(!n.byrange.file)throw"unknown query method for svfusion.byrange";n.byrange.file=n.byrange.file.startsWith(o().tpmasterdir)?n.byrange.file:y().join(o().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.queries.svfusion.byrange;if(n.file)await P.LC(n.file);else{if(!n.url)throw"file and url both missing on svfusion.byrange{}";n.dir=await P.d1(n.url,n.indexURL)}n.nochr=await P.Jy(n.file||n.url,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const r=ir(e),o=await lr(e,n.samples,t);if(0==(null==o?void 0:o.size))return[];const i=new Map;for(const t of e.rglst)await P.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:n=>{const s=n.split("\t"),a=Number(s[1]);let l,c,u,f,d;try{l=JSON.parse(s[3])}catch(t){return}if(l.dt!=F.dtfusionrna&&l.dt!=F.dtsv)return;if(l.class=l.dt==F.dtsv?F.mclasssv:F.mclassfusionrna,e.hiddenmclass&&e.hiddenmclass.has(l.class))return;if(l.sample&&o&&!o.has(l.sample))return;if(l.chrA)c=1,u=l.geneA||l.chrA,f=l.strandA,d=[{a:{chr:l.chrA,pos:l.posA,strand:l.strandA,name:l.geneA},b:{chr:t.chr,pos:a,strand:l.strandB,name:l.geneB}}];else if(l.chrB)c=0,u=l.geneB||l.chrB,f=l.strandB,d=[{a:{chr:t.chr,pos:a,strand:l.strandA,name:l.geneA},b:{chr:l.chrB,pos:l.posB,strand:l.strandB,name:l.geneB}}];else{if(!l.pairlst)throw"missing chrA and chrB";{d=l.pairlst;const t=l.pairlst.findIndex((t=>t.chr==chr&&t.pos==a));if(-1==t)throw"current point missing from pairlst";c=t}}const h=[l.dt,t.chr,a,f,c,encodeURIComponent(u)].join(Zn.dq);let p;if(l.sample&&(p={sample_id:l.sample},l.mattr)){if(r)for(const t in r){const e=t in l.mattr?l.mattr[t]:Xn;if(r[t].has(e))return}e.addFormatValues&&(p.formatK2v=l.mattr)}i.has(h)||i.set(h,{ssm_id:h,dt:l.dt,class:l.class,chr:t.chr,pos:a,strand:f,pairlstIdx:c,mname:u,pairlst:d,samples:[]}),p&&i.get(h).samples.push(p)}});return[...i.values()]}}(t,e),rr(t,n.byrange.samples,"svfusion.byrange")}}(t,e),await async function(t,e){const n=t.queries.geneCnv;if(!n)return;if(!n.bygene)throw"geneCnv.bygene missing";n.bygene.gdcapi&&ln.IK(t)}(t),await async function(t,e){const n=t.queries.cnv;if(!n)return;if(!n.byrange)throw"byrange missing from queries.cnv";if(n.byrange){if(!n.byrange.file)throw"unknown query method for cnv.byrange";n.byrange.file=n.byrange.file.startsWith(o().tpmasterdir)?n.byrange.file:y().join(o().tpmasterdir,n.byrange.file),n.byrange.get=await async function(t,e){const n=t.queries.cnv.byrange;if(n.file)await P.LC(n.file);else{if(!n.url)throw"file and url both missing on cnv.byrange{}";n.dir=await P.d1(n.url,n.indexURL)}n.nochr=await P.Jy(n.file||n.url,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}return async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";if(e.cnvMaxLength&&!Number.isInteger(e.cnvMaxLength))throw"cnvMaxLength is not integer";if(e.cnvGainCutoff&&!Number.isFinite(e.cnvGainCutoff))throw"cnvGainCutoff is not finite";if(e.cnvLossCutoff&&!Number.isFinite(e.cnvLossCutoff))throw"cnvLossCutoff is not finite";const r=ir(e),o=await lr(e,n.samples,t);if(0==(null==o?void 0:o.size))return[];const i=[],s=[];for(const t of e.rglst)s.push(P.UE({args:[n.file||n.url,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:n=>{const s=n.split("\t"),a=Number(s[1]),l=Number(s[2]);if(e.cnvMaxLength&&l-a>=e.cnvMaxLength)return;let c;try{c=JSON.parse(s[3])}catch(t){return}if(c.dt==F.dtcnv){if(c.start=a,c.stop=l,Number.isFinite(c.value)){if(c.value>0&&e.cnvGainCutoff&&c.value<e.cnvGainCutoff)return;if(c.value<0&&e.cnvLossCutoff&&c.value>e.cnvLossCutoff)return;c.class=c.value>0?F.mclasscnvgain:F.mclasscnvloss}else if(c.class!=F.mclasscnvgain&&c.class!=F.mclasscnvloss)return;if(c.ssm_id=[t.chr,c.start,c.stop,c.class].join(Zn.dq),(!e.hiddenmclass||!e.hiddenmclass.has(c.class))&&(!c.sample||!o||o.has(c.sample))){if(c.sample){const t={sample_id:c.sample};if(c.mattr){if(r)for(const t in r){const e=t in c.mattr?c.mattr[t]:Xn;if(r[t].has(e))return}e.addFormatValues&&(t.formatK2v=c.mattr)}delete c.sample,c.samples=[t]}i.push(c)}}}}));return await Promise.all(s),i}}(t,e),rr(t,n.byrange.samples,"cnv.byrange")}}(t,e),await async function(t,e){const n=t.queries.ld;if(!n)return;if(!Array.isArray(n.tracks)||!n.tracks.length)throw"ld.tracks[] not nonempty array";for(const t of n.tracks){if(!t.name)throw"name missing from one of ld.tracks[]";if(!t.file)throw".file missing from one of ld.tracks[]";t.file0=t.file,t.file=y().join(o().tpmasterdir,t.file),await P.LC(t.file),t.nochr=await P.Jy(t.file,null,e)}if(!n.overlay)throw"ld.overlay{} missing";if(!n.overlay.color_0)throw"ld.overlay.color_0 missing";if(!n.overlay.color_1)throw"ld.overlay.color_1 missing"}(t,e),await async function(t,e){const n=t.queries.geneExpression;if(!n)return;if(n.gdcapi)return void ln.CL(t,e);if(!n.file)throw".file missing from queries.geneExpression";n.file=y().join(o().tpmasterdir,n.file),await P.LC(n.file),n.nochr=await P.Jy(n.file,null,e);{const t=await P.ZD(n.file);if(!t[0])throw"header line missing from "+n.file;const e=t[0].split(" ");if("#sample"!=e[0])throw"header line not starting with #sample: "+n.file;n.samples=e.slice(1).map((t=>({name:t})))}rr(t,n.samples,"geneExpression"),n.get=async r=>{const o=await lr(r,n.samples,t);if(0==(null==o?void 0:o.size))return new Map;const i=new Map;for(const t of r.genes)if(t.gene||(t.gene=t.name),t.gene){if(!t.chr){const n=e.genedb.getjsonbyname.all(t.gene);if(0==n.length)continue;const r=JSON.parse(n.find((t=>t.isdefault)).genemodel||n[0].genemodel);t.start=r.start,t.stop=r.stop,t.chr=r.chr}i.set(t.gene,{}),await P.UE({args:[n.file,(n.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop],dir:n.dir,callback:e=>{const n=e.split("\t");let r;try{r=JSON.parse(n[3])}catch(t){return}r.gene.toLowerCase()==t.gene.toLowerCase()&&(o&&!o.has(r.sample)||(i.get(t.gene)[r.sample]=r.value))}})}return{gene2sample2value:i,byTermId:{}}}}(t,e),await async function(t,e){const n=t.queries.rnaseqGeneCount;if(!n)return;if(!n.file)throw"unknown data type for rnaseqGeneCount";n.file=y().join(o().tpmasterdir,n.file);{const e=(await(r=n.file,new Promise(((t,e)=>{const n=(0,q.spawn)("head",["-1",r]);n.stdout.on("data",(e=>t(e.toString()))),n.stderr.on("data",(t=>e(t.toString())))})))).trim().split("\t").slice(4);n.allSampleSet=new Set(e),console.log(n.allSampleSet.size,`rnaseqGeneCount samples from ${t.label}`)}var r;n.get=async function(e){var r,i,s,a;if(2!=(null===(r=e.samplelst)||void 0===r||null===(i=r.groups)||void 0===i?void 0:i.length))throw".samplelst.groups.length!=2";if((null===(s=e.samplelst.groups[0].values)||void 0===s?void 0:s.length)<1)throw"samplelst.groups[0].values.length<1";if((null===(a=e.samplelst.groups[1].values)||void 0===a?void 0:a.length)<1)throw"samplelst.groups[1].values.length<1";const l=[];let c=0;for(const r of e.samplelst.groups[0].values){if(!Number.isInteger(r.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(r.sampleId);e&&(n.allSampleSet.has(e)?l.push(e):c+=1)}const u=[];let f=0;for(const r of e.samplelst.groups[1].values){if(!Number.isInteger(r.sampleId))continue;const e=t.cohort.termdb.q.id2sampleName(r.sampleId);e&&(n.allSampleSet.has(e)?u.push(e):f+=1)}if(console.log("Sample size of group1:",l.length),console.log("Sample size of group2:",u.length),console.log("Number of group1 names not found:",c),console.log("Number of group2 names not found:",f),l.length<1)throw"group1names.length<1";if(u.length<1)throw"group2names.length<1";const d={case:l.map((t=>t)).join(","),control:u.map((t=>t)).join(","),input_file:n.file,output_path:y().join(o().binpath,"utils")},h=8;let p;if(l.length<=h&&u.length<=h){const t=new Date,e=(await async function(t,e){return new Promise(((n,r)=>{y().join(o().Rscript,t);const i=(0,q.spawn)(o().Rscript,[t]),s=[],a=[];try{at.Readable.from(e).pipe(i.stdin)}catch(e){i.kill();let n=e;a.length&&(n+=`killed edgeR('${t}'), stderr: ${a.join("").trim()}`),r(n)}i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("error",(e=>{a.length&&console.log(`edgeR('${t}') ps.on('error') stderr:`,a),r(e)})),i.on("close",(e=>{0!==e?r(`spawned '${t}' exited with a non-zero status and this stderr:\n${a.join("")}`):n(s.toString())}))}))}(y().join(o().binpath,"utils","edge.R"),JSON.stringify(d)),new Date);console.log("Time taken to run edgeR:",e-t,"ms");const n=y().join(o().binpath,"utils","r_output.txt");p=JSON.parse(m().readFileSync(n,"utf8")),m().unlink(n,(()=>{}))}else{const t=new Date,e=await(0,Q.run_rust)("DEanalysis",JSON.stringify(d)),n=new Date;for(const t of e.split("\n"))t.startsWith("adjusted_p_values:")&&(p=JSON.parse(t.replace("adjusted_p_values:","")));console.log("Time taken to run rust DE pipeline:",n-t,"ms")}return p}}(t),await async function(t,e){const n=t.queries.singleSampleMutation;if(!n)return;if(n.gdcapi)ln.P9(t,e);else{if(!n.folder)throw"unknown query method for singleSampleMutation";n.get=async e=>{var r,i,s;let a=e;if(null!==(r=t.cohort)&&void 0!==r&&null!==(i=r.termdb)&&void 0!==i&&null!==(s=i.q)&&void 0!==s&&s.sampleName2id&&(a=t.cohort.termdb.q.sampleName2id(e),null==a))return[];const l=y().join(o().tpmasterdir,n.folder,a.toString());try{await m().promises.stat(l)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.code)throw"no data for this sample";throw"failed to load data"}const c=await P.b5(l);return{mlst:JSON.parse(c)}}}}(t,e),await async function(t,e){const n=t.queries.singleSampleGenomeQuantification;if(!n)return;for(const r in n){if(!Number.isFinite(n[r].min))throw"min not a number";if(!Number.isFinite(n[r].max))throw"max not a number";if(n[r].min>=n[r].max)throw"min>=max";if(!n[r].folder)throw"unknown query method for singleSampleGenomeQuantification";n[r].get=async(i,s)=>{var a,l,c;let u=i;if(null!==(a=t.cohort)&&void 0!==a&&null!==(l=a.termdb)&&void 0!==l&&null!==(c=l.q)&&void 0!==c&&c.sampleName2id&&(u=t.cohort.termdb.q.sampleName2id(i),null==u))return[];const f=y().join(o().tpmasterdir,n[r].folder,u.toString());try{await m().promises.stat(f)}catch(t){if("EACCES"==t.code)throw"cannot read file, permission denied";if("ENOENT"==t.code)throw"no data for this sample";throw"failed to load data"}return await dr(f,e,n[r],s)}}}(t,e),await async function(t,e){const n=t.queries.singleSampleGbtk;if(!n)return;for(const e in n){if(!Number.isFinite(n[e].min))throw"min not a number";if(!Number.isFinite(n[e].max))throw"max not a number";if(n[e].min>=n[e].max)throw"min>=max";if(!n[e].folder)throw"unknown query method for singleSampleGbtk";n[e].get=async r=>{var i,s,a;let l=r;if(null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.termdb)&&void 0!==s&&null!==(a=s.q)&&void 0!==a&&a.sampleName2id&&(l=t.cohort.termdb.q.sampleName2id(r),null==l))return{};const c=y().join(n[e].folder,l+".gz");try{return await m().promises.stat(y().join(o().tpmasterdir,c)),{path:c}}catch(t){return{}}}}}(t),await(0,Kn.validate_query_singleCell)(t,e),await(0,Zn.uK)(t),await function(t){if(!t.ssm2canonicalisoform)return;if(t.ssm2canonicalisoform.gdcapi)return void ln.vK(t.ssm2canonicalisoform);throw"ssm2canonicalisoform.gdcapi is false"}(t),await function(t,e){if(!e.genedb.hasTable_refseq2ensembl)return;t.refseq2ensembl_query=e.genedb.db.prepare("select ensembl from refseq2ensembl where refseq=?")}(t,e),await function(t,e){if(!t.queries.snvindel&&!t.queries.svfusion&&!t.queries.geneCnv)return;t.mayGetGeneVariantData=async(n,r)=>{if("object"!=typeof n.term)throw"tw.term{} is not object";if("geneVariant"!=n.term.type)throw"tw.term.type is not geneVariant";if("string"!=typeof n.term.name)throw"tw.term.name is not string";if(!n.term.name)throw"tw.term.name should be gene symbol but is empty string";const o=[];if("snp"==n.term.subtype){var i;if(null===(i=t.queries.snvindel)||void 0===i||!i.allowSNPs)throw"snvindel does not allow snp";const a=(await mr(t,n.term,e,r)).find((t=>n.term.alleles.includes(t.ref)&&n.term.alleles.includes(t.alt)));if(a){const t=[];for(const e of a.samples){var s;if(null===(s=e.formatK2v)||void 0===s||!s.GT)continue;const n=[];for(const t of e.formatK2v.GT.split("/"))0==t?n.push(a.ref):1==t?n.push(a.alt):console.log("unknown allele idx");n.join("/"),n.join("/");t.push({sample_id:e.sample_id,GT:n.join("/")})}const e={samples:t};o.push(e)}}else{if(t.queries.snvindel){const i=await mr(t,n.term,e,r);o.push(...i)}if(t.queries.svfusion){const i=await async function(t,e,n,r){const o={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid};if(t.queries.svfusion.byrange)return await pr(e,n),o.rglst=[e],await t.queries.svfusion.byrange.get(o);throw"unknown queries.svfusion method"}(t,n.term,e,r);o.push(...i)}if(t.queries.cnv){const i=await async function(t,e,n,r){var o,i,s;const a={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,cnvMaxLength:null==e||null===(o=e.q)||void 0===o?void 0:o.cnvMaxLength,cnvGainCutoff:null==e||null===(i=e.q)||void 0===i?void 0:i.cnvGainCutoff,cnvLossCutoff:null==e||null===(s=e.q)||void 0===s?void 0:s.cnvLossCutoff,sessionid:r.sessionid};if(t.queries.cnv.byrange)return await pr(e.term,n),a.rglst=[e.term],await t.queries.cnv.byrange.get(a);throw"unknown queries.cnv method"}(t,n,e,r);o.push(...i)}if(t.queries.geneCnv){const e=await async function(t,e,n,r){const o={filter0:r.filter0,sessionid:r.sessionid};if(t.queries.geneCnv.bygene)return e.name?(o.gene=e.name,await t.queries.geneCnv.bygene.get(o)):[];throw"unknown queries.geneCnv method"}(t,n.term,0,r);o.push(...e)}}const a=new Map;for(const e of o)if(Array.isArray(e.samples))for(const r of e.samples){var l,c;if(a.has(r.sample_id)||a.set(r.sample_id,{sample:r.sample_id}),null!==(l=t.cohort)&&void 0!==l&&null!==(c=l.termdb)&&void 0!==c&&c.additionalSampleAttributes)for(const e of t.cohort.termdb.additionalSampleAttributes)e in r&&(a.get(r.sample_id)[e]=r[e]);a.get(r.sample_id)[n.term.name]||(a.get(r.sample_id)[n.term.name]={key:n.term.name,label:n.term.name,values:[]});const o={gene:n.term.name,isoform:e.isoform,dt:e.dt,chr:n.term.chr,class:e.class,pos:e.pos||(e.start?e.start+"-"+e.stop:""),mname:e.mname,_SAMPLEID_:r.sample_id,_SAMPLENAME_:r.sample_id};if(r.__sampleName&&(o._SAMPLENAME_=r.__sampleName),"value"in e&&(o.value=e.value),r.formatK2v)for(const t in r.formatK2v)o[t]=r.formatK2v[t];e.dt==F.dtsnvindel?r.GT&&(o.value=r.GT,o.key=r.GT):e.dt!=F.dtfusionrna&&e.dt!=F.dtsv||(o.pairlst=e.pairlst),t.cohort.termdb.q.id2sampleName&&Number.isInteger(r.sample_id)&&(o._SAMPLENAME_=t.cohort.termdb.q.id2sampleName(r.sample_id)),a.get(r.sample_id)[n.term.name].values.push(o)}return await async function(t,e,n,r){var o;if(null===(o=e.assayAvailability)||void 0===o||!o.byDt)return;const i=t.filter?new Set((await(0,Bn.cf)(t.filter,e)).map((t=>t.id))):null;for(const t in e.assayAvailability.byDt){const o=e.assayAvailability.byDt[t];if(o.byOrigin)for(const e in o.byOrigin){hr(t,o.byOrigin[e],n,r,e,i)}else hr(t,o,n,r,!1,i)}}(r,t,a,n.term.name),a}}(t,e)),await function(t){if(!t.assayAvailability)return;if(t.assayAvailability.byDt)for(const e in t.assayAvailability.byDt){const n=t.assayAvailability.byDt[e];if(n.byOrigin)for(const e in n.byOrigin){const r=n.byOrigin[e];if(!r.yes||!r.no||!r.term_id)throw"ds.assayAvailability.byDt.*.byOrigin properties require .term_id .yes{} .no{}";gr(t,r)}else{if(!n.yes||!n.no||!n.term_id)throw"ds.assayAvailability.byDt properties require .term_id .yes{} .no{}";gr(t,n)}}}(t),await function(t){if(!t.viewModes)return;if(!Array.isArray(t.viewModes))throw"ds.viewModes[] not array";for(const r of t.viewModes)if(r.byInfo){var e,n;if(null==t||null===(e=t.queries)||void 0===e||null===(n=e.snvindel)||void 0===n||!n.info)throw"view mode byInfo but queries.snvindel.info missing";const o=t.queries.snvindel.info[r.byInfo];if(!o)throw"unknown INFO field for viewmode byInfo";if("Float"!=o.Type&&"Integer"!=o.Type)throw"viewmode byInfo Type is not numeric";r.type="numeric",r.label=r.byInfo}else if(!r.byAttribute)throw"view mode not byInfo or byAttribute"}(t),null!==(s=t.cohort)&&void 0!==s&&null!==(a=s.db)&&void 0!==a&&a.refresh&&r&&await Wn(t,r,i)}function tr(t){var e;const n={isMds3:!0,label:t.label};if(t.viewModes&&(n.skewerModes=t.viewModes),t.noGenomicMode4lollipopTk&&(n.noGenomicMode4lollipopTk=!0),function(t,e){if(!t.queries)return;const n={};t.queries.singleSampleMutation&&(n.singleSampleMutation={sample_id_key:t.queries.singleSampleMutation.sample_id_key,discoSkipChrM:t.queries.singleSampleMutation.discoSkipChrM});if(t.queries.singleSampleGenomeQuantification){n.singleSampleGenomeQuantification={};for(const e in t.queries.singleSampleGenomeQuantification)n.singleSampleGenomeQuantification[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGenomeQuantification[e])),delete n.singleSampleGenomeQuantification[e].folder}if(t.queries.singleSampleGbtk){n.singleSampleGbtk={};for(const e in t.queries.singleSampleGbtk)n.singleSampleGbtk[e]=JSON.parse(JSON.stringify(t.queries.singleSampleGbtk[e])),delete n.singleSampleGbtk[e].folder}const r=t.queries.snvindel;r&&(e.has_skewer=!0,n.snvindel={forTrack:r.forTrack,vcfid4skewerName:r.vcfid4skewerName,skewerRim:r.skewerRim,ssmUrl:r.ssmUrl},r.m2csq&&(n.snvindel.m2csq={by:r.m2csq.by}),r.info&&(e.bcf={info:r.info}),r.format&&(e.bcf||(e.bcf={}),e.bcf.format=r.format));if(t.queries.ld){n.ld=JSON.parse(JSON.stringify(t.queries.ld));for(const t of n.ld.tracks)delete t.file}e.queries=n}(t,n),null!==(e=t.cohort)&&void 0!==e&&e.termdb&&(n.termdb={},t.cohort.termdb.allowCaseDetails&&(n.termdb.allowCaseDetails={sample_id_key:t.cohort.termdb.allowCaseDetails.sample_id_key})),t.variant2samples){const e=t.variant2samples;n.variant2samples={sunburst_twLst:e.sunburst_twLst,twLst:e.twLst,type_samples:e.type_samples,type_summary:e.type_summary,type_sunburst:e.type_sunburst,variantkey:e.variantkey}}return n}async function er(t){var e,r,i,s;if(t.cohort){if(!t.cohort.termdb)throw"ds.cohort is set but cohort.termdb{} missing";if(!t.cohort.db)throw"ds.cohort is set but cohort.db{} missing";if(!t.cohort.db.file&&!t.cohort.db.file_fullpath)throw"ds.cohort.db.file missing"}else{if(!t.termdb)return;t.cohort={},t.cohort.termdb=t.termdb,delete t.termdb}const a=t.cohort.termdb;if(null!=a&&null!==(e=a.dictionary)&&void 0!==e&&e.gdcapi)await On(t);else if(null!=a&&null!==(r=a.dictionary)&&void 0!==r&&r.dbFile)t.cohort.db={file:a.dictionary.dbFile},delete a.dictionary.dbFile,(0,Gn.JV)(t);else{if(!t.cohort.db)throw"unknown method to initiate dictionary";(0,Gn.JV)(t)}if(a.termid2totalsize2&&(a.termid2totalsize2.gdcapi,a.termid2totalsize2.get=async(e,n={},r=null)=>a.termid2totalsize2.gdcapi?await ln.ws(e,n,r,t):await async function(t,e,n,r){const o=nr(e,r),i=new Map;for(const e of t)if(e.term&&"categorical"==e.term.type){var s,a;const t={term1_id:e.id,term1_q:{type:"values"},filter:o},n=await(0,it.e8)(t,r,r.cohort.termdb);if(null==n||null===(s=n.data)||void 0===s||null===(a=s.charts)||void 0===a||!a[0])continue;const l=[];for(const t of n.data.charts[0].serieses)l.push([t.seriesId,t.total]);i.set(e.id,l)}return n?[i,n]:i}(e,n,r,t)),function(t){const e=t.selectCohort;if(!e)return;if("object"!=typeof e)throw"selectCohort{} not object";if(!e.term)throw"term{} missing from termdb.selectCohort";if(!e.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof e.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=e.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';{const n=t.q.termjsonByOneid(e.term.id);if(!n)throw"termdb.selectCohort.term.id is invalid";if("categorical"!=n.type)throw"termdb.selectCohort.term type is not categorical"}if(!e.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(e.values))throw"termdb.selectCohort.values is not array";if(0==e.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const t of e.values){if(!t.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(t.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==t.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}(a),await async function(t){if(!t.restrictAncestries)return;if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!e.tvs.term)throw"tvs.term{} missing from an ancestry";if(!e.tvs.term.id)throw"tvs.term.id missing from an ancestry";{const n=t.q.termjsonByOneid(e.tvs.term.id);if(!n)throw"tvs.term.id is invalid from an ancestry";if("categorical"!=n.type)throw"tvs.term.type is not categorical from an ancestry"}if(!Number.isInteger(e.PCcount))throw"PCcount is not integer";if(e.PCcount<=1)throw"PCcount must be greater than 1";if(e.PCTermId){e.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const r=e.PCTermId+n,o=t.q.termjsonByOneid(r);if(!o)throw"a PC term is not found in termdb";const i=t.q.getAllValues4term(r);if(!i||!i.size)throw"no sample PC values are retrieved by restrictAncestries term: "+r;e.pcs.set(o.name,i)}}else{if(!e.PCBySubcohort)throw"unknown PC source and configuration for restrictAncestries";for(const n in e.PCBySubcohort){let r=!0;for(const e of t.selectCohort.values)if(n==e.keys.sort().join(",")){r=!1;break}if(r)throw"unknown subcohort from PCBySubcohort";const o=e.PCBySubcohort[n];if(!o.termId)throw"termId missing from a subcohort of PCBySubcohort";o.pcs=new Map;for(let n=1;n<=e.PCcount;n++){const e=o.termId+n,r=t.q.termjsonByOneid(e);if(!r)throw"a PC term is not found in termdb";const i=t.q.getAllValues4term(e);if(!i||!i.size)throw"no sample PC values are retrieved by restrictAncestries.PCBySubcohort.<>.termId";o.pcs.set(r.name,i)}}}}}(a),await(0,Hn.wz)(t),await(0,Vn.te)(t),"minTimeSinceDx"in a){if(!Number.isFinite(a.minTimeSinceDx))throw"termdb.minTimeSinceDx not number";if(a.minTimeSinceDx<=0)throw"termdb.minTimeSinceDx<=0"}if("ageEndOffset"in a){if(!Number.isFinite(a.ageEndOffset))throw"termdb.ageEndOffset not number";if(a.ageEndOffset<=0)throw"termdb.ageEndOffset<=0"}if(t.cohort.termdb.additionalSampleAttributes){if(!Array.isArray(t.cohort.termdb.additionalSampleAttributes))throw"termdb.additionalSampleAttributes not array";for(const e of t.cohort.termdb.additionalSampleAttributes)if("string"!=typeof e)throw"non-str key in termdb.additionalSampleAttributes[]"}if(a.convertSampleId){if(!a.convertSampleId.gdcapi)throw"unknown implementation of tdb.convertSampleId";ln.Ak(a,t)}if(await async function(t){var e;if(null===(e=t.cohort)||void 0===e||!e.cumburden)return;t.cohort.cumburden.files;const n=t.cohort.cumburden.files;for(const t of["fit","surv","sample"]){const e=n[t];if(!e)throw`missing ds.cohort.burden.files.${t}`;const r=(0,q.spawnSync)(o().Rscript,["-e",`load('${o().tpmasterdir}/${e}')`],{encoding:"utf-8"});if(null!=r&&r.status||null!=r&&r.stderr)throw console.log(r),`error with ds.cohort.cumburden.files.${t}`}}(t),null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.db)&&void 0!==s&&s.connection){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[r]=t.sampleId2Name.get(+r);return n}}if(t.cohort.mutationset){const{mayGetGeneVariantData:e,getTermTypes:r,mayGetMatchingGeneNames:o}=n(7833);t.mayGetGeneVariantData=e,t.getTermTypes=r,t.mayGetMatchingGeneNames=o}}function nr(t,e){const n=[];if(t.filterObj&&n.push(t.filterObj),t.tid2value&&n.push(cr(t.tid2value,e)),0!=n.length)return 1==n.length?n[0]:(0,Un.xH)(n)}function rr(t,e,n){var r;if(!e)return;let o;if(null!=t&&null!==(r=t.cohort)&&void 0!==r&&r.termdb){for(const t of e){const e=Number(t.name);if(!Number.isInteger(e))throw"non-integer sample id from "+n;t.name=e}o=", all integer IDs"}console.log(e.length,"samples from "+n+" of "+t.label+o)}async function or(t,e){var n;const r=t.queries.snvindel.byrange;if(r._tk.file)await P._H(r._tk,e,!0);else if(r._tk.chr2files){let t;for(const n in r._tk.chr2files){if("chr17"!=n)continue;const o=r._tk.chr2files[n];try{await P._H(o,e,!0);const i=JSON.stringify(o.samples);if(t){if(i!=t)throw"Different samples found in bcf file of "+n}else t=i,r._tk.samples=o.samples,r._tk.format=o.format,r._tk.info=o.info,r._tk.nochr=o.nochr}catch(t){console.log("missing file ignored:",o.file)}}}if(null!==(n=r._tk)&&void 0!==n&&n.samples.length){if(!r._tk.format)throw"bcf file has samples but no FORMAT"}else if(r._tk.format)throw"bcf file has FORMAT but no samples";if(r._tk.format){for(const t in r._tk.format)"GT"==t&&(r._tk.format[t].isGT=!0);if(t.queries.snvindel.format4filters){if(!Array.isArray(t.queries.snvindel.format4filters))throw"snvindel.format4filters[] is not array";for(const e of t.queries.snvindel.format4filters)r._tk.format[e]&&(r._tk.format[e].isFilter=!0);delete t.queries.snvindel.format4filters}}if(r._tk.info){if(r.infoFields){for(const t of r.infoFields){if(!t.key)throw".key missing from one of snvindel.byrange.infoFields[]";t.name||(t.name=t.key);const e=r._tk.info[t.key];if(!e)throw"invalid key from one of snvindel.byrange.infoFields[]";e.categories=t.categories,e.name=t.name,e.separator=t.separator}delete r.infoFields}if(t.queries.snvindel.infoUrl){for(const e of t.queries.snvindel.infoUrl){const t=r._tk.info[e.key];if(!t)throw"invalid key from one of snvindel.infoUrl[]";t.urlBase=e.base}delete t.queries.snvindel.infoUrl}}return t.queries.snvindel.info=r._tk.info,t.queries.snvindel.format=r._tk.format,async e=>{if(!Array.isArray(e.rglst))throw"q.rglst[] is not array";if(0==e.rglst.length)throw"q.rglst[] blank array";const n=ir(e);let o;if(r._tk.chr2files){const t=r._tk.chr2files[e.rglst[0].chr];if(!t)throw"unknown chr for chr2files";o=t.file}else o=r._tk.file||r._tk.url;const i=["query",o,"-r",e.rglst.map((t=>(r._tk.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1))).join(","),"-f","%ID\t%CHROM\t%POS\t%REF\t%ALT\t%INFO\t%FORMAT\n"],s=await lr(e,r._tk.samples,t);if(s){if(0==s.size)return[];i.push("-s",[...s].join(","))}e.variantFilter&&(0,Yn.u)(e.variantFilter,i);const a=[];return await P.UE({isbcf:!0,args:i,dir:r._tk.dir,callback:o=>{const i=o.split("\t"),l=i[0],c=i[1],u=Number(i[2]),f=i[3],d=i[4].split(","),h=i[5],p={pos:u-1};(0,zn.H)(r._tk,f,d,p,h,l,e.isoform);for(const o of p.mlst){var m,g,y;e.hiddenmclass&&e.hiddenmclass.has(o.class)||(sr(o,e)||p.mlst.length>1&&null!==(m=e.variantFilter)&&void 0!==m&&m.lst&&ar(o,e)||(o.chr=(r._tk.nochr?"chr":"")+c,o.ssm_id=[o.chr,o.pos,o.ref,o.alt].join(Zn.dq),null!==(g=r._tk)&&void 0!==g&&null!==(y=g.samples)&&void 0!==y&&y.length&&(ur(r,o,i,e.addFormatValues,t,s,n),!o.samples)||a.push(o)))}}}),a}}function ir(t){var e,n;const r=t.formatFilter||{};return"format"==(null===(e=t.skewerRim)||void 0===e?void 0:e.type)&&null!==(n=t.skewerRim.hiddenvalues)&&void 0!==n&&n.size&&(r[t.skewerRim.formatKey]=t.skewerRim.hiddenvalues),Object.keys(r).length?r:void 0}function sr(t,e){if(!e.infoFilter)return!1;for(const n in e.infoFilter){const r=t.info[n];if(r)if(Array.isArray(r)){for(const t of e.infoFilter[n])if(r.includes(t))return!0}else if(e.infoFilter[n].includes(r))return!0}return!1}function ar(t,e){for(const r of e.variantFilter.lst){const e=t.info[r.tvs.term.id];if(null==e)return!0;if("integer"==r.tvs.term.type||"float"==r.tvs.term.type){var n;const t=Number(e);if(Number.isNaN(t))return!0;const o=null===(n=r.tvs.ranges)||void 0===n?void 0:n[0];if(o){if("start"in o)if(o.startinclusive){if(t<o.start)return!0}else if(t<=o.start)return!0;if("stop"in o)if(o.stopinclusive){if(t>o.stop)return!0}else if(t>=o.stop)return!0}}}return!1}async function lr(t,e,n){if(!e)return;const r=function(t,e){{const e=t.filter||t.filterObj;if(e){if(!Array.isArray(e.lst))throw"filterObj.lst is not array";return 0==e.lst.length?null:e}}if(t.tid2value){if("object"!=typeof t.tid2value)throw"q.tid2value{} not object";return cr(t.tid2value,e)}}(t,n);if(!r)return;const o=[...new Set((await(0,Bn.cf)(r,n)).map((t=>t.id)))],i=new Set(e.map((t=>t.name))),s=new Set;for(const t of o)i.has(t)&&s.add(t);return s}function cr(t,e){const n={type:"tvslst",in:!0,join:"and",lst:[]};for(const r in t){const o=e.cohort.termdb.q.termjsonByOneid(r);if(!o)continue;const i=t[r];n.lst.push({type:"tvs",tvs:{term:o,values:[{key:i}]}})}return n}function ur(t,e,n,r,o,i,s){if(!n[6]||"."==n[6])return;const a=[];for(const e of n[6].split(":")){const n=t._tk.format[e];if(!n)throw"invalid format field: "+n;a.push(n)}const l=[];let c=t._tk.samples;i&&(c=[...i].map((t=>({name:t}))));for(const[t,e]of c.entries()){const o=n[t+7];if(!o||"."==o)continue;const i=fr(o.split(":"),a,e,r);if(i){if(s){let t=!1;for(const e in s){const n=e in i.formatK2v?i.formatK2v[e]:Xn;if(s[e].has(n)){t=!0;break}}if(t)continue}l.push(i)}}l.length&&(e.samples=l)}function fr(t,e,n,r){const o={};for(const[n,r]of e.entries()){const e=t[n];if(e&&"."!=e)if(r.isGT){if("./."==e||".|."==e)continue;o.GT=e}else o[r.ID]=e}if(0==Object.keys(o).length)return null;const i={sample_id:n.name};return r&&(i.formatK2v=o),i}function dr(t,e,n,r=1){r=Number(r);const o=200,i=20;let s=0;for(const t in e.majorchr)s+=e.majorchr[t];const a=800/s,l={};let c=0;const u=[];for(const t in e.majorchr){const n=e.majorchr[t];l[t]=(0,Sn.Z)().domain([0,n]).range([a*c,a*(c+n)]),c+=n,u.push({chr:t,chrLen:n,xStart:a*(c-n),xStop:a*c})}const f=(0,Sn.Z)().domain([n.min,n.max]).range([o,0]),d=(0,S.createCanvas)(890*r,240*r),h=d.getContext("2d");r>1&&h.scale(r,r),g(n.max),g(0),g(n.min);const p=O().createInterface({input:m().createReadStream(t)});return new Promise(((t,r)=>{p.on("line",(t=>{const e=t.split("\t"),r=e[0];if(!r)return;if(!l[r])return;const o=Number(e[1]);if(!Number.isInteger(o))return;const s=Number(e[2]);if(!Number.isFinite(s))return;if(s<n.min||s>n.max)return;h.fillStyle=s>0?n.positiveColor:n.negativeColor;const a=l[r](o),c=i+f(s);h.fillRect(70+a,c,1,1)})),p.on("close",(()=>{!function(){h.strokeStyle="black",h.beginPath();{const t=220-f(0);h.moveTo(70,t),h.lineTo(870,t),h.stroke()}let t=!0;h.fillStyle="black",h.font="12px Arial",h.textAlign="center";for(const n in l){if(h.fillText(n.replace("chr",""),70+l[n](e.majorchr[n]/2),234),t){t=!1;continue}const r=Math.floor(70+l[n](0))+.5;h.moveTo(r,i),h.lineTo(r,220),h.stroke()}h.closePath()}(),t({src:d.toDataURL(),canvasWidth:890,canvasHeight:240,xoff:70,chrLst:u})}))}));function g(t){h.fillStyle="black",h.font="12px Arial",h.textAlign="right";const e=i+f(t);h.fillText(t,64,e+5),h.strokeStyle="black",h.beginPath(),h.moveTo(66,e),h.lineTo(70,e),h.stroke(),h.closePath()}}function hr(t,e,n,r,o,i){for(const s of e.yesSamples){if(i&&!i.has(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"WT",_SAMPLEID_:s})}for(const s of e.noSamples){if(i&&!i.has(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:Number.parseInt(t),class:"Blank",_SAMPLEID_:s})}}async function pr(t,e){if(t.chr&&Number.isInteger(t.start)&&Number.isInteger(t.stop))return;if(!t.name)throw"both term.name and term.chr/start/stop missing";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)throw"unknown gene name";const r=n.find((t=>t.isdefault))||n[0],o=JSON.parse(r.genemodel);if(!o.chr||!Number.isInteger(o.start)||!Number.isInteger(o.stop))throw"invalid chr/start/stop from returned gm";return t.chr=o.chr,t.start=o.start,t.stop=o.stop,o.isoform}async function mr(t,e,n,r){const o={addFormatValues:!0,filter0:r.filter0,filterObj:r.filter,sessionid:r.sessionid};if(t.queries.geneCnv&&(o.useCaseid4sample=!0),t.queries.snvindel.byisoform)return await async function(t,e){if(t.isoform&&"string"==typeof t.isoform)return;if(!t.name)throw"both term.name and term.isoform";const n=e.genedb.getjsonbyname.all(t.name);if(0==n.length)return;const r=n.find((t=>t.isdefault))||n[0],o=JSON.parse(r.genemodel);if(!o.isoform)throw"isoform missing from returned gm";t.isoform=o.isoform}(e,n),e.isoform?(o.isoform=e.isoform,await t.queries.snvindel.byisoform.get(o)):[];if(t.queries.snvindel.byrange)return o.isoform=await pr(e,n),o.rglst=[e],await t.queries.snvindel.byrange.get(o);throw"unknown queries.snvindel method"}function gr(t,e){e.yesSamples=new Set,e.noSamples=new Set;const n=`SELECT sample, value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = '${e.term_id}'`,r=t.cohort.db.connection.prepare(n).all();for(const t of r)e.yes.value.includes(t.value)?e.yesSamples.add(t.sample):e.no.value.includes(t.value)&&e.noSamples.add(t.sample)}function yr(t,e,n){if(e.skewerRim){if("format"!=e.skewerRim.type)throw"unknown skewerRim.type";t.rim1count=0;for(const n of t.samples){var r;(null===(r=n.formatK2v)||void 0===r?void 0:r[e.skewerRim.formatKey])==e.skewerRim.rim1value&&t.rim1count++}}}function vr(t,e){var n;if(null!==(n=e.queries.snvindel)&&void 0!==n&&n.format)for(const n in e.queries.snvindel.format)if(e.queries.snvindel.format[n].isFilter){t.formatK2count||(t.formatK2count={}),t.formatK2count[n]||(t.formatK2count[n]={v2c:{},unannotatedCount:0});for(const e of t.samples){var r;const o=null===(r=e.formatK2v)||void 0===r?void 0:r[n];null==o?t.formatK2count[n].unannotatedCount++:t.formatK2count[n].v2c[o]=1+(t.formatK2count[n].v2c[o]||0)}}}async function br(t,e){let n=1,r=[],o=[];for(const e of t)if(1==n)n=0;else if(0==e.length);else{let t=e.split(/(\s+)/);Number(t[t.length-3])%1!=0&&0==Number(t[t.length-1])?(r.push(Number(t[t.length-3])),o.push(1e-4)):(r.push(Number(t[t.length-3])),o.push(Number(t[t.length-1])))}let i=[],s=[],a=[],l=!1,c=[],u=0;for(let t=0;t<o.length;t++)if(1==l){let n=0;for(let e=0;e<s.length;e++){let l=s.length-e-1;if(s[l]>o[t]){i.push({id1:t,x1:r[t],y1:o[t],id2:l,x2:a[l],y2:s[l]}),n=1;break}}0==n&&console.log("No suitable branch point found"),i.push({id1:t,x1:r[t],y1:o[t],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t]),l=!1}else o[t]>o[t+1]&&t<=o.length-1?(i.push({id1:t,x1:r[t],y1:o[t],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t])):o[t]==o[t+1]&&t<=o.length-1?(i.push({id1:t-1,x1:r[t-1],y1:o[t-1],id2:t+1,x2:r[t+1],y2:o[t+1]}),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1),s.push(o[t]),a.push(r[t])):(t==o.length-1||(s.push(o[t]),a.push(r[t]),l=!0),0==o[t]&&(c=await wr(i,t,c,e[u]),u+=1));return{dendrogram:i,children:c}}async function wr(t,e,n,r){let o=e;if(n.find((t=>t.id==o))){let t=n.findIndex((t=>t.id==o));n[t].children.push(r)}else n.push({id:o,children:[r]});for(;0!=o;){let e,i,s=t.find((t=>t.id1==o));s&&s.y1<=s.y2&&(e=s.id2);let a=t.find((t=>t.id2==o));if(a&&a.y1>=a.y2&&(i=a.id1),!s&&a?o=i:s&&!a?o=e:s&&a?o=s.y2>a.y1?e:i:console.log("No connections found!"),n.find((t=>t.id==o))){let t=n.findIndex((t=>t.id==o));n[t].children.push(r)}else n.push({id:o,children:[r]})}return n}function _r(t,e){if(t.startunbounded){if(t.stopunbounded)throw"both start & stop are unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when start is unbounded from "+e}else if(t.stopunbounded){if(!Number.isFinite(t.start))throw".start undefined when stop is unbounded from "+e}else{if(!Number.isFinite(t.start))throw".start undefined when start is not unbounded from "+e;if(!Number.isFinite(t.stop))throw".stop undefined when stop is not unbounded from "+e;if(t.start>=t.stop)throw".start is not lower than stop from "+e}}const xr="Ancestry_PC_";async function kr(t,e=null,r=null){var i,s;if(!t.cohort.termdb)throw"cohort.termdb missing when cohort.db is used";await async function(t){if(t.phewas){if(t.phewas.samplefilter4termtype&&t.phewas.samplefilter4termtype.condition&&!t.phewas.samplefilter4termtype.condition.filter)throw"filter{} missing from tdb.phewas.samplefilter4termtype.condition";if(t.phewas.comparison_groups){if(!Array.isArray(t.phewas.comparison_groups))throw"tdb.phewas.comparison_groups is not array";if(0==t.phewas.comparison_groups.length)throw"tdb.phewas.comparison_groups[] cannot be empty"}}if(t.selectCohort){if(!t.selectCohort.term)throw"term{} missing from termdb.selectCohort";if(!t.selectCohort.term.id)throw"id missing from termdb.selectCohort.term";if("string"!=typeof t.selectCohort.term.id)throw"termdb.selectCohort.term.id is not string";if("categorical"!=t.selectCohort.term.type)throw'type is not hardcoded "categorical" from termdb.selectCohort.term';if(!t.selectCohort.values)throw"values[] missing from termdb.selectCohort";if(!Array.isArray(t.selectCohort.values))throw"termdb.selectCohort.values is not array";if(0==t.selectCohort.values.length)throw"termdb.selectCohort.values[] cannot be empty";for(const e of t.selectCohort.values){if(!e.keys)throw"keys[] missing from one of selectCohort.values[]";if(!Array.isArray(e.keys))throw"keys[] is not array from one of selectCohort.values[]";if(0==e.keys.length)throw"keys[] is empty from one of selectCohort.values[]"}}if(t.restrictAncestries){if(!Array.isArray(t.restrictAncestries)||0==t.restrictAncestries.length)throw"termdb.restrictAncestries[] is not non-empty array";for(const e of t.restrictAncestries){if(!e.name)throw"name missing from one of restrictAncestries";if("object"!=typeof e.tvs)throw".tvs{} missing from one of restrictAncestries";if(!Number.isInteger(e.PCcount))throw"PCcount is not integer";if(e.PCfile)e.pcs=await Nr(e.PCfile,e.PCcount);else if(e.PCfileBySubcohort)for(const t in e.PCfileBySubcohort){const n=e.PCfileBySubcohort[t];if(!n.file)throw".file missing for a subcohort in PCfileBySubcohort";n.pcs=await Nr(n.file,e.PCcount)}}}}(t.cohort.termdb),await async function(t){if("scatterplots"in t)for(const e of t.scatterplots.plots){const t=y().join(o().tpmasterdir,e.file);await P.Ic(t)}}(t.cohort),(0,Gn.JV)(t),function(t){t.sampleName2Id=new Map,t.sampleId2Name=new Map;const e="SELECT * FROM sampleidmap",n=t.cohort.db.connection.prepare(e).all();for(const e of n)t.sampleId2Name.set(e.id,e.name),t.sampleName2Id.set(e.name,e.id);t.getSampleIdMap=e=>{const n={};for(const r in e)n[r]=t.sampleId2Name.get(+r);return n}}(t);const{mayGetGeneVariantData:a,getTermTypes:l,mayGetMatchingGeneNames:c}=n(7833);t.mayGetGeneVariantData=a,t.getTermTypes=l,t.mayGetMatchingGeneNames=c,null!==(i=t.cohort)&&void 0!==i&&null!==(s=i.db)&&void 0!==s&&s.refresh&&e&&Wn(t,e,r)}async function qr(t,e){if(!t.track)throw"no mds2 track; missing ds.track{}";const n=t.track;n.name||(n.name=t.label),function(t){if(!t.populations)return;if(!Array.isArray(t.populations))throw"populations should be array";for(const e of t.populations){if(!e.key)throw"key missing from a population";if(e.label||(e.label=e.key),!Array.isArray(e.sets))throw".sets is not an array in population: "+e.key;for(const t of e.sets){if(!t.infokey_AC)throw"infokey_AC missing from a set of population: "+e.key;if(!t.infokey_AN)throw"infokey_AN missing from a set of population: "+e.key;if(e.termfilter&&!t.termfilter_value)throw"termfilter_value missing from a set of population where termfilter is set: "+e.key}}}(n),await async function(t,e,n){if(!t)return;if(!t.chr2bcffile)throw"vcftk.chr2bcffile is missing";{if("object"!=typeof t.chr2bcffile)throw"chr2bcffile not an object";for(const e in t.chr2bcffile)t.chr2bcffile[e]=y().join(o().tpmasterdir,t.chr2bcffile[e]);const n={file:t.chr2bcffile[e.defaultcoord.chr]};if(!n.file)throw"default chr missing from chr2bcffile";await P._H(n,e,!0),t.info=n.info,t.format=n.format,t.samples=n.samples,t.nochr=n.nochr}if(t.AD&&t.AD.chr2bcffile){if("object"!=typeof t.AD.chr2bcffile)throw"AD.chr2bcffile not an object";for(const e in t.AD.chr2bcffile)t.AD.chr2bcffile[e]=y().join(o().tpmasterdir,t.AD.chr2bcffile[e]);const r={file:t.AD.chr2bcffile[e.defaultcoord.chr]};if(!r.file)throw"default chr missing from AD.chr2bcffile";await P._H(r,e,!0),t.AD.info=r.info,t.AD.format=r.format,t.AD.samples=r.samples,t.AD.nochr=r.nochr,console.log(n.label+" vcf: AD: "+t.AD.samples.length+" samples");for(const e of t.AD.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}}if(t.samples){for(const e of t.samples){const t=Number(e.name);if(!Number.isInteger(t))throw"non-integer vcf sample: "+e.name;e.name=t}console.log(n.label+" vcf: "+t.samples.length+" samples")}else console.log(n.label+" vcf: no samples");if(t.numerical_axis&&t.numerical_axis.info_keys){if(!Array.isArray(t.numerical_axis.info_keys))throw"numerical_axis.info_keys should be an array";for(const e of t.numerical_axis.info_keys){const n=t.info[e.key];if(!n)throw'INFO field "'+e.key+'" not found for numerical_axis';if("Float"!=n.Type&&"Integer"!=n.Type)throw'INFO field "'+e.key+'" from numerical_axis not of integer or float type';if("1"!=n.Number&&"A"!=n.Number)throw'for numerical axis, INFO field "'+e.key+'" only allows to be Number=1 or Number=A'}}if(t.plot_mafcov){if(!t.AD)throw".plot_mafcov enabled but .AD{} missing from vcf";if(!t.AD.samples)throw".plot_mafcov enabled but no samples from vcf";if(!t.AD.format)throw".plot_mafcov enabled but no FORMAT fields from vcf";if(!t.AD.format.AD)throw".plot_mafcov enabled but the AD FORMAT field is missing";if("R"!=t.AD.format.AD.Number)throw"AD FORMAT field Number=R is not true";if("Integer"!=t.AD.format.AD.Type)throw"AD FORMAT field Type=Integer is not true";if(t.plot_mafcov.overlay_term){if(!n.cohort)throw"ds.cohort missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb)throw"ds.cohort.termdb missing when plot_mafcov.overlay_term defined";if(!n.cohort.termdb.q)throw"ERR: termdb.q{} missing while trying to access termdb helper functions";if(!n.cohort.termdb.q.termjsonByOneid)throw"ERR: q.termjsonByOneid missing";const e=n.cohort.termdb.q.termjsonByOneid(t.plot_mafcov.overlay_term);if(!e)throw'unknown term id "'+t.plot_mafcov.overlay_term+'" from vcftk.plot_mafcov.overlay_term';t.plot_mafcov.overlay_term=e}}if(t.termdb_bygenotype){if(!t.samples)throw".termdb_bygenotype enabled but no samples from vcf";if(!t.format)throw".termdb_bygenotype enabled but no FORMAT fields from vcf";if(!t.format.GT)throw".termdb_bygenotype enabled but the GT FORMAT field is missing";if(!n.cohort)throw"termdb_bygenotype but ds.cohort missing";if(!n.cohort.termdb)throw"termdb_bygenotype but ds.cohort.termdb missing";if(t.termdb_bygenotype.getAF){if(!t.termdb_bygenotype.termid_sex)throw"termid_sex missing for getAF at termdb_bygenotype";if(!t.termdb_bygenotype.value_male)throw"value_male missing for getAF at termdb_bygenotype";const e=n.cohort.termdb.q.getSample2value(t.termdb_bygenotype.termid_sex);t.termdb_bygenotype.male_samples=new Set;for(const n of e)n.value==t.termdb_bygenotype.value_male&&t.termdb_bygenotype.male_samples.add(n.sample);if(!t.termdb_bygenotype.sex_chrs)throw"sex_chrs missing for getAF at termdb_bygenotype";if(!Array.isArray(t.termdb_bygenotype.sex_chrs))throw"sex_chrs is not array";t.termdb_bygenotype.sex_chrs=new Set(t.termdb_bygenotype.sex_chrs)}}if(t.samples){t.sample2arrayidx=new Map;for(const[e,n]of t.samples.entries())t.sample2arrayidx.set(n.name,e)}}(n.vcf,e,t),function(t){if(!t.info_fields)return;if(!Array.isArray(t.info_fields))throw"tk.info_fields is not array";for(const e of t.info_fields){if(!e.key)throw".key missing from one of tk.info_fields[]";if(t.vcf&&t.vcf.info&&!t.vcf.info[e.key])throw`info field ${e.key} missing from tk.vcf.info{}`;if(e.label||(e.label=e.key),e.iscategorical){if(!Array.isArray(e.values))throw".values[] not an array of categorical INFO field: "+e.key;for(const t of e.values){if(!t.key)throw"key missing from a value of categorical INFO: "+e.key;t.label||(t.label=t.key)}}else if(e.isfloat||e.isinteger){if(!e.range)throw".range{} missing from a numerical INFO: "+e.key;_r(e.range,"tk.info_fields[]")}else if(!e.isflag)throw"tk.info_fields unknown type: "+e.key}}(n),await async function(t,e,n){if(!t)return;if(!Array.isArray(t.tracks))throw"ld.tracks[] not an array";if(0==t.tracks.length)throw"ld.tracks[] is empty array";for(const n of t.tracks){if(!n.name)throw".name missing from a ld track";if(!Number.isInteger(n.viewrangelimit))throw'viewrangelimit missing from ld track "'+n.name+'"';if(n.file)n.file.startsWith(o().tpmasterdir)||(n.file=y().join(o().tpmasterdir,n.file)),await P.LC(n.file),n.nochr=await P.Jy(n.file,null,e),console.log(n.file+": "+(n.nochr?"no chr":"has chr"));else if(!n.chr2file)throw"ld tk has no file or chr2file"}}(n.ld,e),await async function(t,e){if(!t)return}(n.svcnv,0),function(t){const e=new Set;if(t.vcf&&t.vcf.samples)for(const n of t.vcf.samples)e.add(n.name);t.svcnv;e.size&&(t.samples=[...e])}(n),n.samples&&console.log(t.label+": mds2: "+n.samples.length+" samples")}async function Nr(t,e){const n=new Map;for(let t=1;t<=e;t++)n.set(xr+t,new Map);let r=0;for(const i of(await P.b5(y().join(o().tpmasterdir,t))).trim().split("\n")){r++;const t=i.split("\t"),o=Number(t[0]);if(!Number.isInteger(o))throw"non-integer sample id from a line of restrictAncestries pc file";for(let r=1;r<=e;r++){const e=xr+r,i=Number(t[r]);if(Number.isNaN(i))throw"non-numeric PC value from restrictAncestries file";n.get(e).set(o,i)}}return console.log(r,"samples loaded from "+t),Object.freeze(n)}var Sr=n(9157);const Ar=n(334),Mr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO";async function Tr(t,e,n,r){if(!t.rglst)throw".rglst[] missing";const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";const i={info:o.info,format:o.format,samples:o.samples};await async function(t,e,n){if(t.querymode={},t.AFtest){if(n.iscustom)throw"custom track does not support AFtest";for(const e of t.AFtest.groups)if(!e.is_infofield)if(e.is_termdb)e.columnidx=await Cr(e.filter,n);else{if(!e.is_population)throw"Cannot set query mode: unknown group type";{if(!n.track.populations)throw"ds.track.populations missing";const r=n.track.populations.find((t=>t.key==e.key));if(!r)throw"unknown population key: "+e.key;if(e.population=JSON.parse(JSON.stringify(r)),t.AFtest.termfilter&&t.AFtest.termfilter[0].term.id==e.population.termfilter){const n=e.population.sets.find((e=>e.termfilter_value==t.AFtest.termfilter[0].values[0].key));if(!n)throw"no matching set found for a termfilter from a population";e.population.sets=[n]}}}if(t.AFtest.testby_fisher&&t.AFtest.groups.find((t=>t.is_infofield)))throw"cannot do fisher test for an INFO field";{const e=t.AFtest.groups.find((t=>t.is_population));if(e&&e.adjust_race){const r=t.AFtest.groups.find((t=>t.is_termdb));if(!r)throw"cannot adjust race: termdb group missing";r.pop2average=await async function(t,e,n,r){const o=new Map;let i=0;for(const e of t){const t={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await Bn.J4({ds:n,key:e.key});for(const e of r){if(!n.track.vcf.sample2arrayidx.has(e.sample))continue;const r=Number(e.value);Number.isFinite(r)&&(t.average+=r,i+=r)}o.set(e.key,t)}for(const[t,e]of o)e.average/=i;return o}(e.population.sets,r.columnidx,n)}}return void(t.querymode.range_AFtest=!0)}t.querymode.range_variantonly=!0}(t,0,n),function(t,e){if(e.querymode.range_variantonly||e.querymode.range_AFtest){delete t.samples;for(const t of e.rglst)t.variants=[]}e.bcfformat=Mr,e.exportgenotype||e.querymode.range_AFtest?e.bcfformat+="\t%FORMAT\n":e.querymode.range_variantonly&&(e.querymode.slicecolumnindex||(e.bcfformat+="\\n"))}(i,t),t.exportgenotype&&(r.mlst=[]),function(t,e){const n=(r=t.rglst[0],r.usegm_isoform?{gmmode:"protein",usegm:{isoform:r.usegm_isoform}}:{});var r;t.m_is_filtered=r=>{let o=!1;if(t.info_fields)for(const n of t.info_fields){const t=e.info_fields[n.key];let i;if(r.info&&(i=r.info[n.key]),null==i&&r.altinfo&&(i=r.altinfo[n.key]),n.iscategorical)null==i?(t.unannotated_count=1+(t.unannotated_count||0),n.unannotated_ishidden&&(o=!0)):(t.value2count[i]=1+(t.value2count[i]||0),n.hiddenvalues[i]&&(o=!0));else if(n.isnumerical)null==i&&null!=n.missing_value&&(i=n.missing_value),n.range.startunbounded||(n.range.startinclusive?i<n.range.start&&(o=!0):i<=n.range.start&&(o=!0)),n.range.stopunbounded||(n.range.stopinclusive?i>n.range.stop&&(o=!0):i>=n.range.stop&&(o=!0)),o&&t.filteredcount++;else{if(!n.isflag)throw"unknown info type";i?t.count_yes++:t.count_no++,(n.remove_yes&&i||n.remove_no&&!i)&&(o=!0)}}return!!o||(F.vcfcopymclass(r,n),e.mclass2count[r.class]=(e.mclass2count[r.class]||0)+1,t.hidden_mclass&&t.hidden_mclass.has(r.class)&&(o=!0),o)}}(t,r);for(const e of t.rglst){if(o.viewrangeupperlimit&&e.stop-e.start>=o.viewrangeupperlimit){e.rangetoobig="Zoom in under "+F.bplen(o.viewrangeupperlimit)+" to view VCF data";continue}const n=(o.nochr?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop,r=o.chr2bcffile[e.chr];if(!r)throw"chr not found in chr2bcffile";await P.UE({isbcf:!0,args:["query",r,"-r",n,"-f",t.bcfformat],dir:o.dir,callback:s(e)})}function s(e){return n=>{if(t.exportgenotype){const e=n.split("\t"),[o,s,a]=D.S(e.slice(0,8).join("\t"),i);for(const n of s){if(t.m_is_filtered(n))continue;const o=[n.chr+"."+(n.pos+1)+"."+n.ref+"."+n.alt,n.name||""];for(let t=9;t<e.length;t++){const r=e[t].split(":",1)[0];if("."==r){o.push(".");continue}const i=r.split(-1==r.indexOf("/")?"|":"/");o.push(("0"==i[0]?n.ref:n.alt)+("0"==i[1]?n.ref:n.alt))}r.mlst.push(o.join("\t"))}return}let s;if(t.querymode.range_variantonly)if(t.querymode.slicecolumnindex);else{const[e,r,o]=D.S(n,i);s=[];for(const e of r)t.m_is_filtered(e)||s.push(e)}else t.querymode.range_AFtest&&(s=function(t,e,n,r){const o=t.split("\t"),[i,s,a]=D.S(o.slice(0,8).join("\t"),n),l=s.filter((t=>!e.m_is_filtered(t)));if(0==l.length)return;const c=[o[3],...o[4].split(",")],u=[];for(const t of l){const n=Er(o,t,c,e);if(jr(n)){if(u.push(t),e.AFtest.testby_AFdiff){for(const t of n)if(t.is_infofield)t.v=t.infofieldvalue;else{if(!t.is_termdb&&!t.is_population)throw"unknown group type";t.v=t.altcount/(t.refcount+t.altcount)}t.AFtest_group_values=[n[0].v,n[1].v],t.nm_axis_value=n[0].v-n[1].v}else e.AFtest.testby_fisher&&(t.contigencytable=[n[0].altcount,n[0].refcount,n[1].altcount,n[1].refcount]);{const r=e.AFtest.groups.find((t=>t.is_population));if(r&&r.adjust_race){const e=n.find((t=>t.is_population));t.popsetadjvalue=[];for(const[n,r]of e.set2value)t.popsetadjvalue.push([n,r.ACraw,r.ANraw-r.ACraw,Number.parseInt(r.ACadj),Number.parseInt(r.ANadj-r.ACadj)])}}}}return u}(n,t,i));if(s)for(const t of s)t.csq&&(t.csq_count=t.csq.length,delete t.csq),delete t._m,delete t.vcf_ID,delete t.sampledata,o.nochr&&(t.chr="chr"+t.chr),e.variants.push(t)}}await async function(t){if(!t.querymode.range_AFtest)return;if(!t.AFtest.testby_fisher)return;const e=[],n={};for(const r of t.rglst)if(r.variants)for(const t of r.variants)if(t.contigencytable){const r=t.chr+"."+t.pos+"."+t.ref+"."+t.alt;e.push(r+"\t"+t.contigencytable.join("\t")),n[r]=t}if(0==e.length)return;const r=await Sr(y().join(Ar.binpath,"/utils/fisher.R"),e);for(const t of r){const e=t.split("\t"),r=n[e[0]];if(r){const t=Number.parseFloat(e[5]);r.AFtest_pvalue=t,r.nm_axis_value=Number.isNaN(t)?0:-Math.log10(t)}}}(t),function(t,e,n,r){if(e.exportgenotype)return t.exportgenotype="variant\tSNP\t"+n.samples.map((t=>r.cohort.termdb.id2sampleName(t.name))).join("\t")+"\n"+t.mlst.join("\n"),void delete t.mlst;t.vcf={rglst:[]};for(const n of e.rglst){const e={chr:n.chr,start:n.start,stop:n.stop,width:n.width,reverse:n.reverse,xoff:n.xoff};t.vcf.rglst.push(e),n.rangetoobig?(e.rangetoobig=n.rangetoobig,delete n.rangetoobig):n.variants?(e.variants=n.variants,delete n.variants):n.canvas&&(e.img=n.canvas.toDataURL(),delete n.canvas)}if(e.AFtest&&e.AFtest.groups.find((t=>t.is_termdb))){t.AFtest_termdbgroup=[];let n=e.AFtest.groups[0];if(n.is_termdb&&(t.AFtest_termdbgroup[0]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[0].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[0].popsetaverage.push([e,r.average])}if(n=e.AFtest.groups[1],n.is_termdb&&(t.AFtest_termdbgroup[1]={samplecount:n.columnidx.length},n.pop2average)){t.AFtest_termdbgroup[1].popsetaverage=[];for(const[e,r]of n.pop2average)t.AFtest_termdbgroup[1].popsetaverage.push([e,r.average])}}}(r,t,o,n)}async function Cr(t,e){if(!e.track)throw"ds.track{} missing";return(await Bn.cf(t,e)).reduce(((t,n)=>{const r=e.track.vcf.sample2arrayidx.get(n);return r>=0&&t.push(r),t}),[])}function jr(t){if(t.find((t=>t.is_infofield)))return!0;return t[0].altcount+t[1].altcount>0}function Er(t,e,n,r){return r.AFtest.groups.reduce(((o,i)=>{if(i.is_infofield)o.push({is_infofield:!0,infofieldvalue:Or(e,i)});else if(i.is_termdb){const r=function(t,e,n){let r=!0;const o=new Map;for(const e of t)o.set(e,0);for(const i of n){if(!e[9+i])continue;const n=e[9+i].split(":")[0];"."!=n&&n.split(-1==n.indexOf("/")?"|":"/").forEach((e=>{const n=Number.parseInt(e);if(Number.isNaN(n))return;const i=t[n];i&&(0!=n&&(r=!1),o.set(i,1+o.get(i)))}))}return{allref:r,alleles:o}}(n,t,i.columnidx);o.push({is_termdb:!0,allref:r.allref,refcount:r.alleles.get(e.ref)||0,altcount:r.alleles.get(e.alt)||0})}else{if(!i.is_population)throw"unknown group type";{const t=new Map;for(const n of i.population.sets)t.set(n.key,{ACraw:Or(e,{key:n.infokey_AC,missing_value:0}),ANraw:Or(e,{key:n.infokey_AN,missing_value:0})});let n=0,s=0;if(i.adjust_race)[n,s]=function(t,e){if(!e)throw"group_termdb missing";if(!e.pop2average)throw"group_termdb.pop2average missing";let n=0;for(const e of t.values())n+=e.ANraw;let r=0,o=0;for(const[i,s]of t)s.ANadj=n*e.pop2average.get(i).average,s.ACadj=0==s.ANadj?0:s.ACraw*s.ANadj/s.ANraw,r+=s.ACadj,o+=s.ANadj;return[o-r,r]}(t,r.AFtest.groups.find((t=>t.is_termdb)));else for(const e of t.values())s+=e.ACraw,n+=e.ANraw-e.ACraw;o.push({is_population:!0,refcount:n,altcount:s,set2value:t})}}return o}),[])}function Or(t,e){if(t.info){const n=t.info[e.key];if(null!=n)return n}if(t.altinfo){const n=t.altinfo[e.key];if(null!=n)return n}return e.missing_value}var Ir=n(5540),Rr=n(7763);const Pr="#aaa",Fr="%CHROM\t%POS\t%ID\t%REF\t%ALT\t%QUAL\t%FILTER\t%INFO\t%FORMAT\n";async function Dr(t,e,n,r,o){const i=r.track.ld.tracks.find((e=>e.name==t.name));if(!i)throw"ld track not found by name: "+t.name;if(!e.rglst)throw"rglst missing";o.ld[i.name]={rglst:[]};const s=e.trigger_ld.connheight||50;for(const t of e.rglst){const e={chr:t.chr,start:t.start,stop:t.stop,width:t.width,reverse:t.reverse,xoff:t.xoff};if(o.ld[i.name].rglst.push(e),t.stop-t.start>=i.viewrangelimit){e.rangetoobig="Zoom in under "+(0,F.bplen)(i.viewrangelimit)+" to view LD data";continue}const n=[],r=new Set,a=(i.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;await P.UE({args:[i.file,a],dir:i.dir,callback:e=>{const i=e.split("\t"),s=Number.parseInt(i[1]);if(s<t.start)return;const a=Number.parseInt(i[2]);if(a>t.stop)return;if(o.__mposset){if(!o.__mposset.has(s))return;if(!o.__mposset.has(a))return}const l=Number.parseFloat(i[5]);n.push({start:s,stop:a,r2:l}),r.add(s),r.add(a)}}),e.img=Lr(t,n,r,s)}}function Lr(t,e,n,r){const[o,i]=function(t,e){let n=t.width/e.size,r=0;n>40&&(n=40,r=(t.width-n*e.size)/2);const o=new Map,i=t.reverse?[...e].sort(((t,e)=>e-t)):[...e].sort(((t,e)=>t-e));let s=r;for(const t of i)o.set(t,s+n/2),s+=n;return[n,o]}(t,n),s=new Map;{const e=(t.stop-t.start)/t.width;for(const r of n)t.reverse?s.set(r,(t.stop-r)/e):s.set(r,(r-t.start)/e)}let a=0;for(const t of e)a=Math.max(a,(i.get(t.stop)-i.get(t.start))/2);const l=r+a+o/2,c=(0,S.createCanvas)(t.width,l),u=c.getContext("2d");u.strokeStyle="black";for(const t of n)u.beginPath(),u.moveTo(s.get(t),0),u.lineTo(i.get(t),r),u.closePath(),u.stroke();for(const t of e){const e=i.get(t.start),n=i.get(t.stop),s=(e+n)/2,a=r+Math.abs(n-e)/2,l=Math.floor(255*(1-t.r2));u.fillStyle="rgb(255,"+l+","+l+")",u.beginPath(),u.moveTo(s,a-o/2),u.lineTo(s-o/2,a),u.lineTo(s,a+o/2),u.lineTo(s+o/2,a),u.lineTo(s,a-o/2),u.closePath(),u.fill()}return{height:l,src:c.toDataURL()}}var $r=n(6191);function Zr(t,e){const{filename:n,route:r,dslabel:i,embedder:s}=t,a=e.email.replace("@","_at_");return`${o().cachedir}/sessionsByCred/${s}/${a}/${r}/${i}`}const zr=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"];function Ur(t){const e=t.toString(16);return 1==e.length?"0"+e:e}function Br(t,e,n){return Ur(t)+Ur(e)+Ur(n)}function Gr(t){if(!t.cellfile)throw"cellfile missing";{const[e,n,r]=P.ZX({query:{file:t.cellfile}});if(e)throw"cellfile error: "+e;t.cellfile=n}if(!t.delimiter)throw"delimiter missing";if(!Number.isInteger(t.barcodecolumnidx))throw"barcodecolumnidx missing";if(!Number.isInteger(t.categorycolumnidx))throw"categorycolumnidx missing";return new Promise(((e,n)=>{const r=new Map,o=O().createInterface({input:m().createReadStream(t.cellfile)});let i=!0;o.on("line",(e=>{if(i)return void(i=!1);const n=e.split(t.delimiter);r.set(n[t.barcodecolumnidx],{category:n[t.categorycolumnidx],expvalue:0})})),o.on("close",(()=>{e(r)}))}))}const Jr=o().fimo||"fimo";async function Wr(t,e,n){const r=y().join(o().cachedir,Math.random().toString());return await P.Sf(r,n),new Promise(((n,o)=>{const i=["--parse-genomic-coord","--verbosity",1,"--text"];t.fimo_thresh&&(i.push("--thresh"),i.push(t.fimo_thresh)),i.push(e.fimo_motif.db),i.push(r);const s=(0,q.spawn)(Jr,i),a=[];s.stdout.on("data",(t=>a.push(t))),s.on("close",(o=>{m().unlink(r,(()=>{}));const i=a.join("").trim();i||n([]);const s=[],l=i.split("\n");for(let n=1;n<l.length;n++){const r=l[n].split("\t"),o=r[0].split("_")[0],i=Number.parseInt(r[3]),a=Number.parseInt(r[4]);if(i>t.m.pos||a<t.m.pos+1)continue;const c=Number.parseFloat(r[7]),u={start:i,stop:a,strand:r[5],name:o,pvalue:c,score:Number.parseFloat(r[6]),logpvalue:-Math.log10(c)};e.fimo_motif.tf2attr&&(u.attr=e.fimo_motif.tf2attr[u.name]),s.push(u)}n(s)}))}))}function Hr(t){!function(t){if(!t.sample2term)throw".sample2term missing";if(!t.terms)throw".terms[] missing";if(!t.config)throw".config{} missing"}(t);const e=function(t){const e=new Map;for(const n of t.sample2term.values())for(const t of n.keys())e.set(t,1+(e.get(t)||0));if(t.config.termidorder){const n=[];for(const r of t.config.termidorder){const t=e.get(r);null!=t&&n.push({id:r,samplecount:t})}return n}return[...e].sort(((t,e)=>e[1]-t[1])).map((t=>({id:t[0],samplecount:t[1]})))}(t),n=function(t,e){const n=[];for(const[r,o]of t.sample2term)e.find((t=>o.has(t.id)))&&n.push(r);return n}(t,e);return function(t,e,n){for(const[r,o]of e.entries()){const i=0==r?[{samples:n}]:e[r-1].blocks;o.blocks=Vr(i,o.id,t)}}(t,e,n),function(t,e){for(const n of t){const t=e.terms.find((t=>t.id==n.id));n.name=t.name;for(const e of n.blocks)e.samplecount=e.samples.length,delete e.samples,e.value&&(e.color=t.values[e.value].color)}}(e,t),function(t){for(let e=t.length-1;e>=0;e--){const n=t[e];for(const t of n.blocks){let e=0;for(const n of t.children)e+=n.symbolwidth;const n=t.isgap?1:t.samplecount.toString().length;t.symbolwidth=Math.max(n,e)}}let e=0;for(const n of t[0].blocks){n.x=e;let t=e;for(const e of n.children)e.x=t,t+=e.symbolwidth;e+=n.symbolwidth}for(let e=1;e<t.length;e++)for(const n of t[e].blocks){let t=n.x;for(const e of n.children)e.x=t,t+=e.symbolwidth}for(const e of t)delete e.children}(e),e}function Vr(t,e,n){const r=[];for(const o of t){const t=new Map,i=[];for(const r of o.samples){const o=n.sample2term.get(r);if(o){const n=o.get(e);null==n?i.push(r):(t.has(n)||t.set(n,[]),t.get(n).push(r))}else i.push(r)}const s=[...t].sort(((t,e)=>e[1].length-t[1].length));for(const t of s){const e={value:t[0],samples:t[1],children:[]};r.push(e),o.children&&o.children.push(e)}if(i.length){const t={isgap:!0,samples:i,children:[]};r.push(t),o.children&&o.children.push(t)}}return r}async function Yr(t){const e=["futime\tfustat\trx"];for(const[n,r]of t.entries())for(const t of r.lst)e.push(t.serialtime+"\t"+t.censored+"\t"+n);const n=await(0,Sr.default)(y().join(o().binpath,"/utils/km.R"),e);return Number(n.join(""))}async function Kr(t,e,n,r){const o=new Set(t.map((t=>t.name))),i=e.samplerule.set;let s,a;for(const t in n.queries){const e=n.queries[t];e.type==F.tkt.mdsvcf?s=e:e.type==F.tkt.mdssvcnv&&(a=e)}const l=new Set;if(i.cnv||i.loh||i.sv||i.fusion||i.itd){if(!a)throw"no svcnv found in ds.queries";if(r)return await Xr(a,o,e,!0);const t=await Xr(a,o,e);for(const e of t)l.add(e)}if(i.snvindel){if(!s)throw"no vcf found in ds.queries";for(const t of s.tracks)await Qr(s,t,o,l,e)}return t.filter((t=>l.has(t.name)))}async function Xr(t,e,n,r){const i=n.samplerule.set,s=t.url?await P.d1(t.url,t.indexURL):null,a=new Set,l=new Set,c=new Set;return await P.UE({args:[t.file?y().join(o().tpmasterdir,t.file):t.url,(t.nochr?i.chr.replace("chr",""):i.chr)+":"+i.start+"-"+(i.stop+1)],dir:s,callback:t=>{const n=t.split("\t"),o=Number.parseInt(n[1]),s=Number.parseInt(n[2]),u=JSON.parse(n[3]);if(e.has(u.sample)){if(u.dt==F.dtcnv){if(!i.cnv)return;if(i.cnv.focalsizelimit&&s-o>=i.cnv.focalsizelimit)return;if(i.cnv.valuecutoff&&Math.abs(u.value)<i.cnv.valuecutoff)return;return r?u.value>0?a.add(u.sample):l.add(u.sample):c.add(u.sample),void i.samples_cnv.add(u.sample)}if(u.dt==F.dtloh){if(!i.loh)return;if(i.loh.focalsizelimit&&s-o>=i.loh.focalsizelimit)return;if(i.loh.valuecutoff&&u.segmean<i.loh.valuecutoff)return;return c.add(u.sample),void i.samples_loh.add(u.sample)}if(u.dt==F.dtsv){if(!i.sv)return;return c.add(u.sample),void i.samples_sv.add(u.sample)}if(u.dt==F.dtfusionrna){if(!i.fusion)return;return c.add(u.sample),void i.samples_fusion.add(u.sample)}if(u.dt==F.dtitd){if(!i.itd)return;return c.add(u.sample),void i.samples_itd.add(u.sample)}}}}),r?[a,l]:c}async function Qr(t,e,n,r,i){const s=i.samplerule.set,a=e.url?await P.d1(e.url,e.indexURL):null;await P.UE({args:[e.file?y().join(o().tpmasterdir,e.file):e.url,(e.nochr?s.chr.replace("chr",""):s.chr)+":"+s.start+"-"+(s.stop+1)],dir:a,callback:o=>{if(e.type==F.mdsvcftype.vcf){const[i,a,l]=D.S(o,{nochr:e.nochr,samples:e.samples,info:t.info,format:e.format});for(const t of a)if(t.sampledata&&!(s.snvindel.ref&&(t.ref!=s.snvindel.ref||t.alt!=s.snvindel.alt)||s.snvindel.hiddenclass&&(F.vcfcopymclass(t,{}),s.snvindel.hiddenclass[t.class])))for(const e of t.sampledata)n.has(e.sampleobj.name)&&(r.add(e.sampleobj.name),s.samples_snvindel.add(e.sampleobj.name))}}})}async function to(t,e,n){if(!n.queries)throw".queries{} missing from ds";let r;for(const t in n.queries)n.queries[t].isgenenumeric&&(r=n.queries[t]);if(!r)throw"no gene numeric query from ds";const i=r.url?await P.d1(r.url,r.indexURL):null,s=e.samplerule.set,a=new Map;await P.UE({args:[r.file?y().join(o().tpmasterdir,r.file):r.url,s.chr+":"+s.start+"-"+s.stop],dir:i,callback:t=>{const e=JSON.parse(t.split("\t")[3]);e.sample&&Number.isFinite(e.value)&&e.gene==s.gene&&a.set(e.sample,e.value)}});const l=[];for(const e of t)a.has(e.name)&&(e.genevalue=a.get(e.name),l.push(e));return l.sort(((t,e)=>t.genevalue-e.genevalue)),[r,l]}function eo(t){t.lst.sort(((t,e)=>t.serialtime-e.serialtime));let e=t.lst.length,n=[],r=0;t.steps=[];for(const o of t.lst){if(0==o.censored){n.push(o.serialtime);continue}const i=1*(1-r)/(e-n.length);t.steps.push({x:o.serialtime,y:r,drop:i,censored:n}),r+=i,e-=n.length+1,n=[]}n.length>0&&t.steps.push({x:t.lst[t.lst.length-1].serialtime,y:r,drop:0,censored:n})}exports.do_plot=eo;const no={};function ro(t,e,n){const r=+new Date;if(t.ip in no||(no[t.ip]={time:r,count:0}),r-no[t.ip].time>3e4)delete no[t.ip];else{if(no[t.ip].count>10)return void e.send({error:"busy"});no[t.ip].count++}throw e.send({error:n}),new Date+" "+n}const oo={genome(t){if("string"!=typeof t)throw"genome should be a non-empty string";if(/\s+/.test(t))throw"invalid genome character";return t},chr(t){if("string"!=typeof t)throw"chr should be a string";if(/\s+/.test(t))throw"invalid chr character";return t},start:t=>Number(t),term(t){const e="string"==typeof t?JSON.parse(t):t;if(!("id"in e))throw"missing termWrapper.id";if(!("q"in e))throw"missing termWrapper.q";return e}},io=require("cookie-parser");var so=n.n(io),ao=n(2062),lo=n(5708);const co=t=>t.startsWith("[E::idx_test_and_fetch]"),uo=(new Map,Object.freeze(o().features||{})),fo={},ho=o().tabix,po=o().samtools,mo=o().bcftools,go=(o().bigwigsummary,o().hicstraw,"Unannotated"),yo=s()();yo.disable("x-powered-by"),o().users&&yo.use(K()({users:o().users,challenge:!0}));const vo=o().basepath||"";function bo(t){t.header("Vary","Origin"),t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS, HEAD"),t.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, origin, x-requested-with, content-type, accept, authorization, X-Auth-Token, X-Ds-Access-Token, X-SjPPDs-Sessionid, x-auth-token, x-ds-access-token, x-sjppds-sessionid")}if(!o().backend_only){const t=s().static(y().join(process.cwd(),"./public"),{setHeaders:bo});yo.use(t)}function wo(t){const e={};for(const n in t.query)"jwt"!=n&&(e[n]=t.query[n]);console.log("%s\t%s\t%s\t%s",c().parse(t.url).pathname,new Date,t.header("x-forwarded-for")||t.connection.remoteAddress,JSON.stringify(e).replace(/\\"/g,'"'))}async function _o(){try{if(o().preListenScript){const{cmd:t,args:e}=o().preListenScript,n=N().spawnSync(t,e,{encoding:"utf-8"});if(n.stderr.trim())throw n.stderr.trim();console.log(n.stdout)}o().appEnable&&o().appEnable.forEach((t=>yo.enable(t)));const t=o().port,e=`STANDBY AT PORT ${t}`;if(o().ssl){const n={key:m().readFileSync(o().ssl.key),cert:m().readFileSync(o().ssl.cert)},r=await h().createServer(n,yo);return r.listen(t,"0.0.0.0",(()=>{console.log(`HTTPS ${e}`)})),r}{const n=await f().createServer(yo);return n.listen(t,"0.0.0.0",(()=>{process.send&&process.send("ready"),console.log(e)})),n}}catch(t){throw t}}function xo(t){const e=fo[t],n={species:e.species,name:t,hasSNP:!!e.snp,hasIdeogram:e.genedb.hasIdeogram,fimo_motif:!!e.fimo_motif,blat:!!e.blat,geneset:e.geneset,defaultcoord:e.defaultcoord,isdefault:e.isdefault,majorchr:e.majorchr,majorchrorder:e.majorchrorder,minorchr:e.minorchr,tracks:e.tracks,hicenzymefragment:e.hicenzymefragment,datasets:{}};if(e.termdbs){n.termdbs={};for(const t in e.termdbs)n.termdbs[t]={label:e.termdbs[t].label}}for(const t in e.datasets){const r=e.datasets[t];r.isMds3?n.datasets[r.label]={isMds3:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:r.isMds?n.datasets[r.label]={isMds:!0,mdsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}:n.datasets[r.label]={isofficial:!0,legacyDsIsUninitiated:!0,noHandleOnClient:r.noHandleOnClient,label:r.label}}if(e.hicdomain){n.hicdomain={groups:{}};for(const t in e.hicdomain.groups){const r=e.hicdomain.groups[t];n.hicdomain.groups[t]={name:r.name,reference:r.reference,sets:{}};for(const e in r.sets)n.hicdomain.groups[t].sets[e]={name:r.sets[e].name,longname:r.sets[e].longname}}}return n}function ko(t){const e={noHandleOnClient:t.noHandleOnClient,sampleselectable:t.sampleselectable,label:t.label,dsinfo:t.dsinfo,stratify:t.stratify,cohort:t.cohort,vcfinfofilter:t.vcfinfofilter,info2table:t.info2table,info2singletable:t.info2singletable,url4variant:t.url4variant,itemlabelname:t.itemlabelname};if(t.snvindel_attributes){e.snvindel_attributes=[];for(const n of t.snvindel_attributes){const t={};for(const e in n)if("lst"==e){t.lst=[];for(const e of n.lst){const n={};for(const t in e)n[t]=e[t];t.lst.push(n)}}else t[e]=n[e];e.snvindel_attributes.push(t)}}t.snvindel_legend&&(e.snvindel_legend=t.snvindel_legend);const n={};let r=!1;for(const e of t.queries)e.vcf&&(r=!0,n[e.vcf.vcfid]=e.vcf);return r&&(e.id2vcf=n),e}function qo(t){const e={isMds:!0,noHandleOnClient:t.noHandleOnClient,label:t.label,version:t.version,annotationsampleset2matrix:t.annotationsampleset2matrix,mutationAttribute:t.mutationAttribute,locusAttribute:t.locusAttribute,alleleAttribute:t.alleleAttribute,hide_genotypedownload:t.hide_genotypedownload,hide_phewas:t.hide_phewas,sample2bam:t.sample2bam};if(t.queries&&(e.queries={}),t.track&&(e.track=function(t){const e=t.track,n={name:e.name,info_fields:e.info_fields,sample_termfilter:e.sample_termfilter};return e.vcf&&(n.vcf={numerical_axis:e.vcf.numerical_axis,format:e.vcf.format,info:e.vcf.info,check_pecanpie:e.vcf.check_pecanpie},e.vcf.plot_mafcov&&(n.vcf.plot_mafcov={},t.cohort&&t.cohort.termdb&&(n.vcf.plot_mafcov.overlay_term=e.vcf.plot_mafcov.overlay_term||{})),e.vcf.termdb_bygenotype&&(n.vcf.termdb_bygenotype=!0),e.populations&&(n.populations=e.populations)),e.ld&&(n.ld={tracks:e.ld.tracks.map((t=>({name:t.name,shown:t.shown}))),overlay:e.ld.overlay}),n}(t)),t.singlesamplemutationjson&&(e.singlesamplemutationjson=1),t.gene2mutcount&&(e.gene2mutcount=!0,e.mutCountType=t.gene2mutcount.mutationTypes),t.assayAvailability&&(e.assayAvailability=1),t.cohort&&t.cohort.sampleAttribute){const n={};for(const e in t.cohort.sampleAttribute.attributes){const r=t.cohort.sampleAttribute.attributes[e];r.clientnoshow||(n[e]=r)}e.sampleAttribute={attributes:n}}if(t.cohort){if(t.cohort.termdb&&(e.termdb={selectCohort:t.cohort.termdb.selectCohort}),t.cohort.attributes&&t.cohort.attributes.defaulthidden&&(e.cohortHiddenAttr=t.cohort.attributes.defaulthidden),t.cohort.survivalplot){e.survivalplot={samplegroupattrlst:t.cohort.survivalplot.samplegroupattrlst,plots:[]};for(const n in t.cohort.survivalplot.plots){const r=t.cohort.survivalplot.plots[n];e.survivalplot.plots.push({key:n,name:r.name,timelabel:r.timelabel})}}if(t.cohort.mutation_signature){const n={};for(const e in t.cohort.mutation_signature.sets){const r=t.cohort.mutation_signature.sets[e];n[e]={name:r.name,signatures:r.signatures}}e.mutation_signature={sets:n}}}for(const n in t.queries){const r=t.queries[n],o={name:r.name,hideforthemoment:r.hideforthemoment};if(r.istrack){if(o.istrack=!0,o.type=r.type,o.isfull=r.isfull,null!=r.nochr&&(o.nochr=r.nochr),r.infoFilter&&(o.infoFilter=r.infoFilter),r.readcountCutoff&&(o.readcountCutoff=r.readcountCutoff),r.valueLabel&&(o.valueLabel=r.valueLabel),r.valueCutoff&&(o.valueCutoff=r.valueCutoff),r.bplengthUpperLimit&&(o.bplengthUpperLimit=r.bplengthUpperLimit),r.segmeanValueCutoff&&(o.segmeanValueCutoff=r.segmeanValueCutoff),r.lohLengthUpperLimit&&(o.lohLengthUpperLimit=r.lohLengthUpperLimit),r.type==F.tkt.mdssvcnv){if(r.groupsamplebyattr&&(o.groupsamplebyattr=r.groupsamplebyattr),o.multihidelabel_fusion=r.multihidelabel_fusion,o.multihidelabel_sv=r.multihidelabel_sv,o.multihidelabel_vcf=r.multihidelabel_vcf,o.showfullmode=r.showfullmode,o.legend_vorigin=r.legend_vorigin,o.no_loh=r.no_loh,r.expressionrank_querykey){const e=t.queries[r.expressionrank_querykey];if(o.checkexpressionrank={querykey:r.expressionrank_querykey,datatype:e.datatype},e.boxplotbysamplegroup&&e.boxplotbysamplegroup.additionals){const t=[];e.boxplotbysamplegroup.attributes&&t.push(e.boxplotbysamplegroup.attributes.map((t=>t.label)).join(", "));for(const n of e.boxplotbysamplegroup.additionals)t.push(n.label);o.checkexpressionrank.boxplotgroupers=t}}if(r.vcf_querykey){o.checkvcf={querykey:r.vcf_querykey,info:t.queries[r.vcf_querykey].info,format:{}};for(const e of t.queries[r.vcf_querykey].tracks)if(e.format)for(const t in e.format)o.checkvcf.format[t]=e.format[t]}}}else{if(!r.isgenenumeric)continue;o.isgenenumeric=!0,o.datatype=r.datatype,o.no_ase=r.no_ase}e.queries[n]=o}return e}async function No(t,e){if(!e)throw"invalid genome";if(!e.snp)throw"snp is not configured for this genome";const n=[];if(t.byCoord){if(e.genomicNameRegexp.test(t.chr))throw"invalid chr name";if(!Array.isArray(t.ranges))throw"ranges not an array";for(const r of t.ranges){if(!Number.isInteger(r.start)||!Number.isInteger(r.stop)||r.start<0||r.stop<r.start)throw"invalid start/stop";if(r.stop-r.start>=100)throw"range too big";const o=await P.z5(e.snp.bigbedfile,t.chr,r.start,r.stop);for(const e of o){const r=So(e);if(t.alleleLst){let e=!1;for(const n of t.alleleLst)if(n&&!r.alleles.includes(n)){e=!0;break}if(e)continue}n.push(r)}}}else{if(!t.byName)throw"unknown query method";if(!Array.isArray(t.lst))throw".lst[] missing";for(const r of t.lst){if(e.genomicNameRegexp.test(r))continue;const t=await P.mr(e.snp.bigbedfile,r);for(const e of t){const t=So(e);n.push(t)}}}return n}function So(t){const e=t.split("\t"),n=e[4],r=e[6].split(",").filter(Boolean),o=n+"/"+r.join("/");return{chrom:e[0],chromStart:Number(e[1]),chromEnd:Number(e[2]),name:e[3],observed:o,alleles:[n,...r]}}function Ao(t,e,n){if(n.query.isoform&&fo[n.query.genome].genomicNameRegexp.test(n.query.isoform))return;const[r,o]=e.makequery(n.query);if(!r)return;const i=t.newconn.prepare(r).all(o);let s;s=e.tidy?i.map((t=>e.tidy(t))):i;const a={};if(e.isgeneexpression){a.lst=s,a.isgeneexpression=!0,a.config=e.config;for(const e of t.queries)if(e.dsblocktracklst)for(const t of e.dsblocktracklst)t.type==F.tkt.junction&&(a.config.dsjunctiontk=t)}else a.lst=s;return a}function Mo(t,e){const n=[y().join(o().tpmasterdir,t.vcffile),(t.vcf.nochr?e.query.range.chr.replace("chr",""):e.query.range.chr)+":"+e.query.range.start+"-"+e.query.range.stop];return new Promise(((e,r)=>{const o=(0,q.spawn)(ho,n),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(n=>{""!=s.join("").trim()&&r("error querying vcf file");const o=i.join("").trim();e({lines:""==o?[]:o.split("\n"),vcfid:t.vcf.vcfid})}))}))}function To(t){if(!t.genome)return["no genome"];const e=fo[t.genome];if(!e)return["invalid genome"];if(!e.datasets)return["genome is not equipped with datasets"];if(!t.dslabel)return["dslabel missing"];const n=e.datasets[t.dslabel];if(!n)return["invalid dslabel"];if(!n.queries)return["dataset is not equipped with queries"];if(!t.querykey)return["querykey missing"];const r=n.queries[t.querykey];return r?[null,e,n,r]:["invalid querykey"]}async function Co(t,e,n,r,i,s){const a=await async function(t,e,n,r){const i=t.checkvcf.tracks[0],s={file:i.file,url:i.url,indexURL:i.indexURL,dir:i.dir,nochr:i.nochr,samples:i.samples,info:t.checkvcf.info,format:i.format},a=await zo(s.file?y().join(o().tpmasterdir,s.file):s.url,(s.nochr?e.replace("chr",""):e)+":"+n+"-"+r,s.dir),l=[];for(const t of a||[]){const[e,n,r]=D.S(t,s);for(const t of n)F.basecolor[t.ref]&&F.basecolor[t.alt]&&t.sampledata&&l.push(t)}return l}(i,e,n,r),l=[];for(const t in i.checkrnabam.samples){const n=i.checkrnabam.samples[t];n.hetsnps=[];for(const e of a){const r=$o(e,t,i.checkrnabam);r&&r.dnacount.ishet&&n.hetsnps.push(r)}if(n.url?n.dir=await P.d1(n.url,n.indexURL||n.url+".bai"):n.file&&(n.file=y().join(o().tpmasterdir,n.file)),n.hetsnps.length>0){await Oo(n,n.hetsnps,e,i.checkrnabam);for(const e of n.hetsnps)e.rnacount.nocoverage||e.rnacount.ref+e.rnacount.alt<i.checkrnabam.rna_mintotalreads||l.push(t+"."+e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt)}}l.length>0&&await async function(t,e){const n=await function(t){const e=y().join(o().cachedir,Math.random().toString());return new Promise(((n,r)=>{m().writeFile(e,t.join("\n")+"\n",(t=>{t&&r("cannot write"),n(e)}))}))}(t),r=await Do(n);await function(t,e){return new Promise(((n,r)=>{m().readFile(t,"utf8",((t,o)=>{if(t&&r("cannot read binom pvalue"),o){for(const t of o.trim().split("\n")){const n=t.split("\t"),r=n[0].split("."),o=e[r[0]];if(!o)continue;const i=o.hetsnps.find((t=>t.pos+"."+t.ref+"."+t.alt==r[1]+"."+r[2]+"."+r[3]));i&&(i.rnacount.pvalue=Number.parseFloat(n[10]))}n()}else n()}))}))}(r,e),m().unlink(n,(()=>{})),m().unlink(r,(()=>{}))}(l,i.checkrnabam.samples),s.checkrnabam=[];for(const n in i.checkrnabam.samples){const r=i.checkrnabam.samples[n],o=[];for(const[n,s]of t){const t={gene:n,chr:e,start:s.start,stop:s.stop},a=r.hetsnps.filter((t=>t.pos>=s.start&&t.pos<=s.stop)),l=a.filter((t=>!t.rnacount.nocoverage));if(l.length>0){const e=l.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let n=null,r=0;for(const t of l)null!=t.rnacount.pvalue&&(null==n?n=t.rnacount.pvalue:n*=t.rnacount.pvalue,t.rnacount.pvalue<=i.checkrnabam.binompvaluecutoff&&r++);null!=n&&(t.ase={markers:a.filter((t=>t.dnacount.ishet)).length,ase_markers:r,mean_delta:e/l.length,geometricmean:Math.pow(n,1/l.length)})}let c;c=r.pairedend?await Eo(r,e,s):await jo(r,e,s),t.fpkm=1e9*c/(r.totalreads*s.exonlength),t.snps=a,o.push(t)}o.length&&s.checkrnabam.push({sample:n,genes:o})}}async function jo(t,e,n){const r=["view","-c","-M",t.url||t.file];for(const o of n.exonunion)r.push((t.nochr?e.replace("chr",""):e)+":"+(o[0]+1)+"-"+(o[1]+1));let o;return await P.UE({isbam:!0,args:r,dir:t.dir,callback:t=>o=t}),Number.parseInt(o)}function Eo(t,e,n){return new Promise(((r,o)=>{const i=["view","-M",t.url||t.file];for(const r of n.exonunion)i.push((t.nochr?e.replace("chr",""):e)+":"+(r[0]+1)+"-"+(r[1]+1));const s=(0,q.spawn)(po,i,{cwd:t.dir}),a=(0,q.spawn)("cut",["-f1"],{cwd:t.dir}),l=(0,q.spawn)("sort",["-u"],{cwd:t.dir}),c=(0,q.spawn)("wc",["-l"],{cwd:t.dir});s.stdout.pipe(a.stdin),a.stdout.pipe(l.stdin),l.stdout.pipe(c.stdin);const u=[],f=[];c.stdout.on("data",(t=>u.push(t))),c.stderr.on("data",(t=>f.push(t))),c.on("close",(()=>{r(Number.parseInt(u.join("")))}))}))}function Oo(t,e,n,r){const o=[];for(const r of e)r.rnacount={nocoverage:1},o.push((t.nochr?n.replace("chr",""):n)+":"+(r.pos+1)+"-"+(r.pos+1));return new Promise(((n,i)=>{const s=(0,q.spawn)(mo,["mpileup","--no-reference","-a","INFO/AD","-d",999999,"-r",o.join(","),"-q",r.rnapileup_q,"-Q",r.rnapileup_Q,t.url||t.file],{cwd:t.dir});O().createInterface({input:s.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Lo(t);if(!n)return;const r=e.find((t=>t.pos==n.pos));if(r){const t=n.allele2count[r.ref]||0,e=n.allele2count[r.alt]||0;t+e>0&&(r.rnacount={ref:t,alt:e,f:e/(t+e)})}})),s.on("close",(()=>{n()}))}))}function Io(t,e,n,r,o,i){e.hideLOHwithCNVoverlap&&Ro(o);const s=[];if(i){const t=new Map;for(const[e,n]of o){const r=i.sample2group.get(e);t.has(r)||t.set(r,[]),t.get(r).push({samplename:e,items:n})}if(r)for(const e of r)if(e.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){const e=i.sample2group.get(n.sampleobj.name);t.has(e)||t.set(e,[]),t.get(e).find((t=>t.samplename==n.sampleobj.name))||t.get(e).push({samplename:n.sampleobj.name,items:[]})}for(const[e,n]of t)s.push({name:e,samples:n})}else if(t.cohort&&t.cohort.annotation&&e.groupsamplebyattr){const n=new Map,i=[];for(const[r,s]of o)Po(r,s,n,i,t,e);if(r)for(const o of r)if(o.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf data: "+o.dt);else for(const r of o.sampledata)Po(r.sampleobj.name,[],n,i,t,e);for(const t of n.values())if(s.push(t),e.groupsamplebyattr.key2group){const n=e.groupsamplebyattr.key2group.get(t.name);n&&(t.sampletotalnum=n.samples.length)}i.length&&s.push({name:"Unannotated",samples:i});for(const e of s)for(const n of e.samples)t.cohort.annotation[n.samplename]&&(n.sampletype=t.cohort.annotation[n.samplename].sample_type)}else{const t=[];for(const[e,n]of o)t.push({samplename:e,items:n});if(r)for(const e of r)if(e.dt!=F.dtsnvindel)console.log("unknown dt when grouping samples from vcf: "+e.dt);else for(const n of e.sampledata){let e=!0;for(const r of t)if(r.samplename==n.sampleobj.name){e=!1;break}e&&t.push({samplename:n.sampleobj.name,items:[]})}t.length&&s.push({samples:t})}return s}function Ro(t){for(const[e,n]of t){const r=new Map,o=new Map,i=[];for(const t of n)t.dt!=F.dtloh?(t.dt==F.dtcnv&&(o.has(t.chr)||o.set(t.chr,[]),o.get(t.chr).push(t)),i.push(t)):(r.has(t.chr)||r.set(t.chr,[]),r.get(t.chr).push(t));if(0!=r.size){for(const[t,e]of r){const n=o.get(t);if(n)for(const t of e){let e=!0;for(const r of n)if(Math.max(t.start,r.start)<Math.min(t.stop,r.stop)){e=!1;break}e&&i.push(t)}else for(const t of e)i.push(t)}t.set(e,i)}}}function Po(t,e,n,r,o,i){const s=o.cohort.annotation[t];if(!s)return void r.push({samplename:t,items:e});const a=s[i.groupsamplebyattr.attrlst[0].k];if(null==a)return void r.push({samplename:t,items:e});const l=[];for(let t=1;t<i.groupsamplebyattr.attrlst.length;t++){const e=s[i.groupsamplebyattr.attrlst[t].k];if(null==e)break;l.push(e)}l.unshift(a);const c=l.join(i.groupsamplebyattr.attrnamespacer);if(!n.has(c)){const t=[];for(const e of i.groupsamplebyattr.attrlst){const n=s[e.k];if(null==n)break;const r={k:e.k,kvalue:n};e.full&&(r.full=e.full,r.fullvalue=s[e.full]),t.push(r)}const e=[];for(const t of i.groupsamplebyattr.attrlst){const n=s[t.k];if(null==n)break;const r=(t.full?s[t.full]:null)||n;e.push(r)}n.set(c,{name:c,samples:[],attributes:t})}let u=!0;for(const r of n.get(c).samples)if(r.samplename==t){for(const t of e)r.items.push(t);u=!1;break}u&&n.get(c).samples.push({samplename:t,items:e})}function Fo(t){return Number.isFinite(t.dna_mintotalreads)?Number.isFinite(t.rna_mintotalreads)?Number.isFinite(t.hetsnp_minbaf)?Number.isFinite(t.hetsnp_maxbaf)?Number.isFinite(t.rnapileup_q)?Number.isFinite(t.rnapileup_Q)?void 0:"invalid value for rnapileup_Q":"invalid value for rnapileup_q":"invalid value for hetsnp_maxbaf":"invalid value for hetsnp_minbaf":"invalid value for rna_mintotalreads":"invalid value for dna_mintotalreads"}function Do(t){const e=t+".pvalue";return new Promise(((n,r)=>{const i=(0,q.spawn)("Rscript",[y().join(o().binpath,"utils/binom.R"),t,e]);i.on("close",(()=>{n(e)})),i.on("error",(t=>{r(`cannot do binom test: ${t}`)})),i.stderr.on("data",(t=>{r(`cannot do binom test: ${t}`)}))}))}function Lo(t){const e=t.split("\t");if(e.length<8)return;const n={pos:Number.parseInt(e[1])-1},r=[e[3],...e[4].split(",")],o={};for(const t of e[7].split(";")){const e=t.split("=");o[e[0]]=e[1]}if(o.DP&&(n.DP=Number.parseInt(o.DP)),o.AD){n.allele2count={};const t=o.AD.split(",");for(const[e,o]of r.entries())n.allele2count[o]=Number.parseInt(t[e])}return n}function $o(t,e,n){const r=t.sampledata.find((t=>t.sampleobj.name==e));if(r){if(r.AD){const e=r.AD[t.ref]||0,o=r.AD[t.alt]||0,i={chr:t.chr,pos:t.pos,ref:t.ref,alt:t.alt,dnacount:{ref:e,alt:o}};return i.dnacount.f=o+e==0?0:o/(o+e),e+o>=n.dna_mintotalreads&&i.dnacount.f>=n.hetsnp_minbaf&&i.dnacount.f<=n.hetsnp_maxbaf&&(i.dnacount.ishet=!0),i}return null}}async function Zo(t,e,n,r,i){const s=await zo(y().join(o().tpmasterdir,e.file),n+":"+r+"-"+i),a=new Map;if(s)for(const t of s){const e=t.split("\t"),n=JSON.parse(e[3]),r=Number.parseInt(e[1]),o=Number.parseInt(e[2]);if(a.has(n.name)){const t=a.get(n.name);t.start=Math.min(t.start,r),t.stop=Math.max(t.stop,o)}else a.set(n.name,{gene:n.name,start:r,stop:o,exonunion:[]});const i=a.get(n.name);if(n.exon)for(const t of n.exon){const e=i.exonunion.find((e=>Math.max(e[0],t[0])<Math.min(e[1],t[1])));e?(e[0]=Math.min(t[0],e[0]),e[1]=Math.max(t[1],e[1])):i.exonunion.push([t[0],t[1]])}}for(const[t,e]of a)e.exonlength=e.exonunion.reduce(((t,e)=>t+e[1]-e[0]),0);return a}async function zo(t,e,n){return new Promise(((r,o)=>{const i=(0,q.spawn)(ho,[t,e],{cwd:n}),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(()=>{const t=a.join("");t&&o(t);const e=s.join("").trim();e||r(),r(e.split("\n"))}))}))}function Uo(t,e){return new Promise(((n,r)=>{const o=(0,q.spawn)(ho,["-H",t],{cwd:e}),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(()=>{const t=s.join("");t&&r(t);const e=i.join("").trim();e||r("cannot list vcf meta lines"),n(e.split("\n"))}))}))}function Bo(t,e){const n=e.findIndex((e=>e.value>=t));return-1==n||n==e.length-1?100:0==n?0:Math.ceil(100*n/e.length)}function Go(t,e,n){if(!t.key)return[".key missing"];if(!e.cohort)return["ds.cohort missing"];if(!e.cohort.annotation)return["ds.cohort.annotation missing"];return[null,Promise.resolve().then((()=>{const r=[];for(const o in e.cohort.annotation){if(n&&!n.has(o))continue;const i=e.cohort.annotation[o][t.key];null!=i&&r.push({sample:o,value:i})}return{id:t.id,items:r}}))]}function Jo(t,e,n,r){if(!t.genename)return["genename missing"];const i=t.genename.toLowerCase();if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["gene feature too long (> 10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((s,a)=>{const l=[],c=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:c.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.gene&&n.gene.toLowerCase()==i&&n.sample&&(r&&!r.has(n.sample)||l.push(n))}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(e=>{const n=u.join("");!n||co(n)?s({id:t.id,items:l}):a(n)}))}))))]}function Wo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);o.dt==F.dtcnv&&(t.valuecutoff&&Math.abs(o.value)<t.valuecutoff||(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.focalsizelimit&&o.stop-o.start>=t.focalsizelimit||o.sample&&(r&&!r.has(o.sample)||a.push(o))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Ho(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];if(null!=t.valuecutoff&&!Number.isFinite(t.valuecutoff))return["invalid value for valuecutoff"];if(null!=t.focalsizelimit&&!Number.isInteger(t.focalsizelimit))return["invalid value for focalsizelimit"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);o.dt==F.dtloh&&(t.valuecutoff&&o.segmean<t.valuecutoff||(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.focalsizelimit&&o.stop-o.start>=t.focalsizelimit||o.sample&&(r&&!r.has(o.sample)||a.push(o))))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Vo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt==F.dtitd&&(n.chr=e[0],n.start=Number.parseInt(e[1]),n.stop=Number.parseInt(e[2]),n.sample&&(r&&!r.has(n.sample)||a.push(n)))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Yo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(t=>{const e=t.split("\t"),n=JSON.parse(e[3]);n.dt!=F.dtsv&&n.dt!=F.dtfusionrna||n.sample&&(r&&!r.has(n.sample)||(n._chr=e[0],n._pos=Number.parseInt(e[1]),n.chrA?(n.chrB=n._chr,n.posB=n._pos):(n.chrA=n._chr,n.posA=n._pos),a.push(n)))}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const n=c.join("");!n||co(n)?i({id:t.id,items:a}):s(n)}))}))))]}function Ko(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];return[null,Promise.resolve().then((()=>{if(!n.file)return P.d1(n.url,n.indexURL)})).then((e=>new Promise(((i,s)=>{const a=[],l=(0,q.spawn)(ho,[n.file?y().join(o().tpmasterdir,n.file):n.url,t.chr+":"+t.start+"-"+t.stop],{cwd:e});O().createInterface({input:l.stdout}).on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);if(o.sample&&(!r||r.has(o.sample))){if(o.dt==F.dtsv||o.dt==F.dtfusionrna){if(o.dt==F.dtsv&&t.sv&&t.sv.hidden)return;if(o.dt==F.dtfusionrna&&t.fusion&&t.fusion.hidden)return;o._chr=n[0],o._pos=Number.parseInt(n[1]),o.chrA?(o.chrB=o._chr,o.posB=o._pos):(o.chrA=o._chr,o.posA=o._pos)}else if(o.dt==F.dtcnv){if(t.cnv&&t.cnv.hidden)return;if(t.cnv&&t.cnv.valuecutoff&&Math.abs(o.value)<t.cnv.valuecutoff)return;if(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.cnv&&t.cnv.focalsizelimit&&o.stop-o.start>=t.cnv.focalsizelimit)return}else if(o.dt==F.dtloh){if(t.loh&&t.loh.hidden)return;if(t.loh&&t.loh.valuecutoff&&o.segmean<t.loh.valuecutoff)return;if(o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2]),t.loh&&t.loh.focalsizelimit&&o.stop-o.start>=t.loh.focalsizelimit)return}else{if(o.dt!=F.dtitd)return void console.error("unknown datatype",o.dt);if(t.itd&&t.itd.hidden)return;o.chr=n[0],o.start=Number.parseInt(n[1]),o.stop=Number.parseInt(n[2])}a.push(o)}}));const c=[];l.stderr.on("data",(t=>c.push(t))),l.on("close",(e=>{const r=c.join("");if(r&&!co(r))return void s(r);const o=new Map;for(const t of a)o.has(t.sample)||o.set(t.sample,[]),o.get(t.sample).push(t);n.hideLOHwithCNVoverlap&&Ro(o);const l=[];for(const[t,e]of o)for(const t of e)l.push(t);i({id:t.id,items:l})}))}))))]}function Xo(t,e,n,r){if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>1e7)return["look range too big (>10Mb)"];const o=[];for(const i of n)if(i.type==F.tkt.mdsvcf){const[n,s]=Qo(t,e,i,r);if(n)return[n];o.push(s)}else{if(i.type!=F.tkt.mdssvcnv)return["unsupported track type: "+i.type];{const[e,n]=Ko(t,0,i,r);if(e)return[e];o.push(n)}}return[null,Promise.all(o).then((t=>{const e=[];for(const n of t)for(const t of n.items)e.push(t);return{id:t[0].id,items:e}}))]}function Qo(t,e,n,r){if(!n.tracks)return"tracks[] missing from dsquery";if(!t.chr)return["chr missing"];if(!Number.isInteger(t.start)||!Number.isInteger(t.stop))return["invalid start/stop coordinate"];if(t.stop-t.start>3e6)return["look range too big (>3Mb)"];const i=[];for(const e of n.tracks){const s=Promise.resolve().then((()=>{if(!e.file)return P.d1(e.url,e.indexURL)})).then((i=>new Promise(((s,a)=>{const l=[],c=(0,q.spawn)(ho,[e.file?y().join(o().tpmasterdir,e.file):e.url,(e.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+(t.stop+1)],{cwd:i});O().createInterface({input:c.stdout}).on("line",(o=>{if(n.iscustom)l.push(o);else if(e.type==F.mdsvcftype.vcf){const[i,s,a]=D.S(o,{nochr:e.nochr,samples:e.samples,info:n.info,format:e.format});for(const e of s)if(e.sampledata&&(F.vcfcopymclass(e,{}),!(t.snvindel&&t.snvindel.excludeclasses&&t.snvindel.excludeclasses[e.class]))){if(r){const t=[];for(const n of e.sampledata)r.has(n.sampleobj.name)&&t.push(n);if(0==t.length)continue;e.sampledata=t}for(const t of e.sampledata)delete t.allele2readcount;delete e._m,delete e.vcf_ID,delete e.name,e.dt=F.dtsnvindel,l.push(e)}}else console.error("type not one of mdsvcftype: "+e.type)}));const u=[];c.stderr.on("data",(t=>u.push(t))),c.on("close",(t=>{const e=u.join("");!e||co(e)?s(l):a(e)}))}))));i.push(s)}return[null,Promise.all(i).then((e=>{const n=[];for(const t of e)for(const e of t)n.push(e);return{id:t.id,items:n}}))]}function ti(t){if(!t.endsWith(".gz"))return["no .gz suffix (file should be compressed by bgzip)"];const e=y().join(o().tpmasterdir,t);return m().existsSync(e)?m().existsSync(e+".tbi")||m().existsSync(e+".csi")?[null,e]:[".tbi/.csi index missing"]:[".gz file not found"]}yo.use(k()()),yo.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&(t.headers["content-type"]="application/json");try{for(const e in t.query){const n=t.query[e];("null"==n||n.startsWith('"')&&n.endsWith('"')||n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&(t.query[e]=JSON.parse(n))}}catch(t){return void e.send({error:t})}n()})),yo.use(so()()),yo.use(T().json({limit:"5mb"})),yo.use(T().text({limit:"5mb"})),yo.use(T().urlencoded({extended:!0})),yo.use(((t,e,n)=>{"POST"==t.method.toUpperCase()&&t.body&&"application/json"!=t.headers["content-type"]?e.send({error:"invalid HTTP request.header['content-type'], must be 'application/json'"}):("application/json"==t.headers["content-type"]&&(t.query||(t.query={}),Object.assign(t.query,t.body)),wo(t),bo(e),e.header("Access-Control-Allow-Origin",t.get("origin")||t.get("referrer")||t.protocol+"://"+t.get("host").split(":")[0]||"*"),e.header("Access-Control-Allow-Credentials",!0),"GET"!=t.method||t.path.includes(".")&&!t.path.endsWith("proteinpaint.js")||e.header("Cache-control",`immutable,max-age=${o().responseMaxAge||1}`),n())})),yo.catch=ro,yo.use((function(t,e,n){try{const e=t.query;for(const t in e)t in oo&&(e[t]=oo[t](e[t]));n()}catch(n){ro(t,e,n.message||n)}})),yo.use(((t,e,n,r)=>{wo(e),t&&(t&&"entity.parse.failed"==t.type?n.send({error:"invalid request body, must be a valid JSON-encoded object"}):n.send({error:t}))})),o().jwt&&(console.log("JWT is activated"),yo.use(((t,e,n)=>{let r={};t.body&&"POST"==t.method&&(r=t.body);const i=r.jwt?r.jwt:t.headers&&t.headers.authorization&&t.headers.authorization.startsWith("Bearer ")?t.headers.authorization.split(" ")[1]:null;if(!i)return e.send({error:"json web token missing"});R().verify(i,o().jwt.secret,((t,r)=>t?e.send({error:"Invalid token"}):r[o().jwt.permissioncheck]?void n():e.send({error:"Not authorized"})))}))),function(){if(!o().routeSetters)return;for(const t of o().routeSetters)if(t.endsWith(".js")){require(t)(yo,vo)}}(),$r.i.maySetAuthRoutes(yo,vo,o()),yo.get(vo+"/cardsjson",(async function(t,e){try{if(t.query.datafile&&t.query.tabixCoord)return new Promise(((n,r)=>{const i=(0,q.spawn)(ho,[y().join(o().tpmasterdir,t.query.datafile),t.query.tabixCoord]),s=[],a=[];i.stdout.on("data",(t=>s.push(t))),i.stderr.on("data",(t=>a.push(t))),i.on("close",(t=>{""!=a.join("").trim()&&r("error querying bedj file");const o=s.join("").trim();n(e.send({file:o.split("\n")}))}))})).catch((t=>{t.stack&&console.error(t.stack)}));throw"invalid cards request"}catch(t){e.send({error:t.message||t})}})),yo.post(vo+"/mdsjsonform",(async function(t,e){if(!uo.mdsjsonform)return e.send({error:"This feature is not enabled on this server."});if(t.query.deposit){const n=Math.random().toString(),r=await function(){const t=y().join(o().cachedir,"mdsjsonform");return new Promise(((e,n)=>{m().stat(t,((r,o)=>{if(r){if("ENOENT"==r.code)return void m().mkdir(t,(r=>{r&&n("error creating dir"),e(t)}));n("error checking directory")}else o.isDirectory()?e(t):n('"mdsjsonform" exists but not directory')}))}))}(),i=y().join(r,n);return await P.Sf(i,JSON.stringify(t.query.deposit)),void e.send({id:n})}if(t.query.draw){const n=y().join(o().cachedir,"mdsjsonform",t.query.draw),r=await P.b5(n);try{const t=JSON.parse(r);e.send({json:t})}catch(t){e.send({error:"Invalid JSON"})}return}e.send({})})),yo.get(vo+"/genomes",(async function(t,e){var n;wo(t);try{await m().promises.stat(o().tpmasterdir)}catch(t){let n="Error with TP directory ("+t.code+")";const r=o().maintenance||{};if("start"in r&&"stop"in r&&r.tpMessage){const t=+new Date(r.start),e=+new Date(r.stop),o=+new Date;t<=o&&o<=e&&(n=r.tpMessage)}return void e.send({error:n})}const r={};if(t.query&&t.query.genome)r[t.query.genome]=xo(t.query.genome);else for(const t in fo)r[t]=xo(t);let i=!1;for(const t in fo)fo[t].blat&&(i=!0);e.send({genomes:r,debugmode:o().debugmode,headermessage:o().headermessage,base_zindex:o().base_zindex,codedate:ao.A.codedate,launchdate:ao.A.launchdate,hasblat:i,features:uo,dsAuth:$r.i.getDsAuth(t),commonOverrides:o().commonOverrides,targetPortal:o().targetPortal,cardsPath:null===(n=o().cards)||void 0===n?void 0:n.path})})),yo.get(vo+"/getDataset",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"unknown genome";if(!n.datasets)throw"genomeobj.datasets{} missing";let r;for(const e in n.datasets)if(e.toLowerCase()==t.query.dsname.toLowerCase()){r=n.datasets[e];break}if(!r)throw"invalid dsname";return r.isMds3?e.send({ds:tr(r)}):r.isMds?e.send({ds:qo(r)}):e.send({ds:ko(r)})}catch(t){e.send({error:t.message||t})}})),yo.all(vo+"/ntseq",(async function(t,e){try{if(!t.query.coord)throw"coord missing";const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.genomefile)throw"no sequence file available";const r=await P.Kf(n,t.query.coord);e.send({seq:r.split("\n").slice(1).join("")})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/pdomain",(function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";const r=fo[n];if(!r)throw"invalid genome "+n;if(!r.proteindomain)return e.send({lst:[]});if(!Array.isArray(t.query.isoforms))throw"isoforms[] missing";const o=[];for(const e of t.query.isoforms){if(r.genomicNameRegexp.test(e))continue;const t=r.proteindomain.getbyisoform.all(e);o.push({name:e,pdomains:t.map((t=>{const n=JSON.parse(t.data);return n.refseq=e,n}))})}e.send({lst:o})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/tkbedj",function(t){return async(e,n)=>{try{n.send(await async function(t,e){const[n,r,o]=P.ZX(t);if(n)throw n;let i,s,a,l,c;if(t.query.fileIsBigbed=await P.aS(r),t.query.getdata)t.query.getBED;else{if(i=Number(t.query.stackheight),s=Number(t.query.stackspace),a=Number(t.query.regionspace),l=Number(t.query.width),Number.isNaN(i))throw"stackheight is not integer";if(c=Math.max(10,i-2),Number.isNaN(s))throw"stackspace is not integer";if(Number.isNaN(a))throw"regionspace is not integer";if(Number.isNaN(l))throw"width is not a number"}if(t.query.usevalue){if(!t.query.usevalue.key)throw".key missing from .usevalue";if(t.query.usevalue.dropBelowCutoff&&(t.query.usevalue.dropBelowCutoff=Number(t.query.usevalue.dropBelowCutoff),Number.isNaN(t.query.usevalue.dropBelowCutoff)))throw".usevalue.dropBelowCutoff is not number"}if(t.query.bplengthUpperLimit&&(t.query.bplengthUpperLimit=Number(t.query.bplengthUpperLimit),Number.isNaN(t.query.bplengthUpperLimit)))throw"bplengthUpperLimit not number";if(!t.query.rglst)throw"no rglst[]";if(!Array.isArray(t.query.rglst))throw"rglst is not an array";if(0==t.query.rglst.length)throw"empty rglst";for(const e of t.query.rglst)e.reverse?e.scale=t=>Math.ceil(e.width*(e.stop-t)/(e.stop-e.start)):e.scale=t=>Math.ceil(e.width*(t-e.start)/(e.stop-e.start));const u=t.query.color||"#3D7A4B",f=t.query.gmregion||null,d=t.query.isoform,h=t.query.onerow,p=t.query.categories||null,m=t.query.__isgene;let g;!t.query.fileIsBigbed&&o&&(g=await P.d1(r,t.query.indexURL));const y=await async function(t,e,n,r,o){let i;if(r){const s=[];if(t.fileIsBigbed){const n=await P.z5(e,r.chr,r.start,r.stop);for(const e of n){const n=e.split("\t"),r=fn(n);r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&s.push(r)}}else await P.UE({args:[e,r.chr+":"+r.start+"-"+r.stop],dir:n,callback:e=>{const n=e.split("\t");let r={};if(t.getBED)r.rest=n.slice(3);else if(n[3])try{r=JSON.parse(n[3])}catch(t){return void(i=e)}if(!r.isoformonly||r.isoformonly==o){r.chr=n[0],r.start=Number(n[1]),r.stop=Number(n[2]),r.rglst=[];for(let e=0;e<t.rglst.length;e++){const n=t.rglst[e];Math.max(r.start,n.start)<Math.min(r.stop,n.stop)&&r.rglst.push({idx:e})}0!=r.rglst.length&&s.push(r)}}});if(i)throw"Line with invalid JSON: "+i;return[s]}const s=[];for(const[r,o]of t.rglst.entries()){const a=[];if(t.fileIsBigbed){const t=await P.z5(e,o.chr,o.start,o.stop);for(const e of t){const t=e.split("\t"),n=fn(t);n.chr=t[0],n.start=Number(t[1]),n.stop=Number(t[2]),n.rglst=[{idx:r}],a.push(n)}}else await P.UE({args:[e,o.chr+":"+o.start+"-"+o.stop],dir:n,callback:e=>{const n=e.split("\t");let o={};if(t.getBED)o.rest=n.slice(3);else if(n[3])try{o=JSON.parse(n[3])}catch(t){return void(i=e)}o.chr=n[0],o.start=Number(n[1]),o.stop=Number(n[2]),o.rglst=[{idx:r}],a.push(o)}});s.push(a)}if(i)throw"Line with invalid JSON: "+i;return s}(t.query,r,g,f,d);let v;t.query.filterByName&&(v=new Set(t.query.filterByName.split(/[\s\n]/).map((t=>t.trim()))));const b=[];for(const e of y)for(const n of e){if(t.query.usevalue){const e=n[t.query.usevalue.key];if(!Number.isFinite(e))continue;if(t.query.usevalue.dropBelowCutoff&&e<t.query.usevalue.dropBelowCutoff)continue}if(!(t.query.bplengthUpperLimit&&n.stop-n.start>t.query.bplengthUpperLimit)){if(v)if(n.isoform){if(!v.has(n.isoform))continue}else{if(!n.name)continue;if(!v.has(n.name))continue}b.push(n)}}if(t.query.getdata)return{items:b};if(0==b.length){const e=(0,S.createCanvas)(l*t.query.devicePixelRatio,i*t.query.devicePixelRatio),n=e.getContext("2d");return t.query.devicePixelRatio>1&&n.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),n.font=i+"px Arial",n.fillStyle="#aaa",n.textAlign="center",n.textBaseline="middle",n.fillText("No data in view range",l/2,i/2),{src:e.toDataURL(),height:i}}const w=Math.ceil(i/4)-1;if(h||b.length>=mn){const e=b.length<200,n=(0,S.createCanvas)(l*t.query.devicePixelRatio,i*t.query.devicePixelRatio),r=n.getContext("2d");t.query.devicePixelRatio>1&&r.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);const o=b.length<=200?[]:null;for(const n of b){const s=p&&n.category&&p[n.category]?p[n.category].color:n.color||u;r.fillStyle=s;for(const s of n.rglst){let l=0;for(let e=0;e<s.idx;e++)l+=t.query.rglst[e].width+a;const c=t.query.rglst[s.idx],u=[];n.utr5&&u.push(...n.utr5),n.utr3&&u.push(...n.utr3),!n.exon||n.coding&&0!=n.coding.length||u.push(...n.exon);for(const t of u){const e=Math.max(c.start,t[0]),s=Math.min(c.stop,t[1]),a=l+c.scale(c.reverse?s:e),u=l+c.scale(c.reverse?e:s);r.fillRect(a,w,Math.max(1,u-a),i-2*w),xn(o,a,u,1,n)}const f=[];n.exon?n.coding&&n.coding.length>0&&f.push(...n.coding):f.push([n.start,n.stop]);for(const t of f){const s=Math.max(c.start,t[0]),a=Math.min(c.stop,t[1]),u=l+c.scale(c.reverse?a:s),f=l+c.scale(c.reverse?s:a);r.fillRect(u,0,Math.max(1,f-u),i),xn(o,u,f,1,n),n.strand&&e&&(r.strokeStyle="white",kn(r,n.strand,u,w,f-u,i-2*w))}}}return{src:n.toDataURL(),height:i,mapisoform:o}}if(t.query.hideItemNames)for(const t of b)delete t.name;let _=null;if(m&&b.length<gn){_=[];for(const t of b){const e={};for(const n in t)"canvas"!=n&&"rglst"!=n&&(e[n]=t[n]);_.push(e)}}const x=t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0),k=t.query.translatecoding&&x<3*l;let q;if(k){if(!t.query.genome)throw"genome missing for translating genes";if(q=e[t.query.genome],!q)throw"invalid genome"}const N=[],A=(0,S.createCanvas)(10,10);let M=A.getContext("2d");t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial";const T=b.length<pn,C=b.length<pn?[]:null;let j=!1;f&&(j=f.reverse);for(const e of t.query.rglst)e.reverse&&(j=!0);b.sort(((t,e)=>j?t.stop==e.stop?t.start-e.start:e.stop-t.stop:t.start==e.start?e.stop-t.stop:t.start-e.start));const E=b.some((t=>t.exon)),O=[0];let I=1,R=null;for(const e of b){let n=null,r=null;for(const o of e.rglst){let i=0;for(let e=0;e<o.idx;e++)i+=t.query.rglst[e].width+a;const s=t.query.rglst[o.idx],l=Math.max(e.start,s.start),c=Math.min(e.stop,s.stop);if(l<c){const t=i+s.scale(s.reverse?c:l),e=i+s.scale(s.reverse?l:c);null==n?(n=t,r=e):(n=Math.min(n,t),r=Math.max(r,e))}}if(null==n)continue;e.canvas={start:n,stop:r,stranded:null!=e.strand},e.coding&&k&&(e.willtranslate=!0,N.push(e));let o=n,i=r;if(T){const t=e.name;if(t){e.canvas.namestr=t;const n=M.measureText(t).width;e.canvas.namewidth=n,E?e.canvas.start>=n+dn?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+dn<=l?(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):n>e.canvas.stop-e.canvas.start?e.canvas.start>l-e.canvas.stop?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):(e.canvas.namehover=!0,e.canvas.textalign="left"):Math.min(l,e.canvas.stop)-Math.max(0,e.canvas.start)>=n+2*hn?e.canvas.namein=!0:e.canvas.start>=n+dn?(e.canvas.namestart=e.canvas.start-dn,o=e.canvas.namestart-n,e.canvas.textalign="right"):e.canvas.stop+n+dn<=l?(e.canvas.namestart=e.canvas.stop+dn,i=e.canvas.namestart+n,e.canvas.textalign="left"):e.canvas.namein=!0}}e.canvas.stop-e.canvas.start>.3*l&&(R=[]);for(let t=1;t<=I;t++)if(null==O[t]||O[t]<o){e.canvas.stack=t,O[t]=i;break}null==e.canvas.stack&&(I++,O[I]=i,e.canvas.stack=I),xn(C,o,i,e.canvas.stack,e)}A.width=l*t.query.devicePixelRatio;const D=(i+s)*I-s;A.height=D*t.query.devicePixelRatio,M=A.getContext("2d"),t.query.devicePixelRatio>1&&M.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);M.font="bold "+c+"px Arial",M.textBaseline="middle",M.lineWidth=1;for(const e of b){const n=e.canvas;if(!n)continue;const r=p&&e.category&&p[e.category]?p[e.category].color:e.color||u,o=(i+s)*(n.stack-1);M.fillStyle=r,(e.exon||e.rglst.length>1)&&(M.strokeStyle=r,M.beginPath(),M.moveTo(n.start,Math.floor(o+i/2)+.5),M.lineTo(n.stop,Math.floor(o+i/2)+.5),M.stroke());for(const s of e.rglst){let l=0;for(let e=0;e<s.idx;e++)l+=t.query.rglst[e].width+a;const c=t.query.rglst[s.idx],u=[];e.utr3&&u.push(...e.utr3),e.utr5&&u.push(...e.utr5),!e.exon||e.coding&&0!=e.coding.length||u.push(...e.exon);for(const t of u){const n=Math.max(t[0],c.start),s=Math.min(t[1],c.stop);if(n<s){if(e.exon2color)for(const t of e.exon2color)if(n>=t.start&&s<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?s:n),a=l+c.scale(c.reverse?n:s);M.fillRect(t,o+w,Math.max(1,a-t),i-2*w),e.exon2color&&(M.fillStyle=r)}}const f=[];e.exon?e.coding&&e.coding.length>0&&f.push(...e.coding):f.push([e.start,e.stop]);let d=e.strand;n.stranded&&c.reverse&&(d="+"==e.strand?"-":"+");for(const t of f){const s=Math.max(t[0],c.start),a=Math.min(t[1],c.stop);if(s<a){if(e.exon2color)for(const t of e.exon2color)if(s>=t.start&&a<=t.stop){M.fillStyle=t.color;break}const t=l+c.scale(c.reverse?a:s),u=l+c.scale(c.reverse?s:a);if(M.fillRect(t,o,Math.max(1,u-t),i),e.exon2color&&(M.fillStyle=r),n.stranded&&!e.willtranslate)if(M.strokeStyle="white",n.namein){const e=(u-t-n.namewidth)/2;kn(M,d,t,o+w,e,i-2*w),kn(M,d,t+e+n.namewidth,o+w,e,i-2*w)}else kn(M,d,t,o+w,u-t,i-2*w)}}if(n.stranded&&e.intron){M.strokeStyle=r;for(const t of e.intron){const e=Math.max(t[0],c.start),n=Math.min(t[1],c.stop);if(e<n){const t=l+c.scale(c.reverse?n:e);kn(M,d,t,o+w,l+c.scale(c.reverse?e:n)-t,i-2*w)}}}if(R&&e.exon){for(let t=0;t<e.exon.length;t++){const r=e.exon[t];if(r[1]<=c.start||r[0]>=c.stop)continue;const o=Math.max(r[0],c.start),i=Math.min(r[1],c.stop);if(o<i){const s=l+c.scale(c.reverse?i:o),a=l+c.scale(c.reverse?o:i);R.push({chr:e.chr,start:Math.min(r[0],r[1]),stop:Math.max(r[0],r[1]),x1:s,x2:a,y:n.stack,name:"Exon "+(t+1)+"/"+e.exon.length})}}for(let t=1;t<e.exon.length;t++){const r=e.exon["+"==e.strand?t-1:t][1],o=e.exon["+"==e.strand?t:t-1][0];if(o<=c.start||r>=c.stop)continue;const i=Math.max(r,c.start),s=Math.min(o,c.stop);if(i<s){const a=l+c.scale(c.reverse?s:i),u=l+c.scale(c.reverse?i:s);if(u<0)continue;R.push({chr:e.chr,start:r,stop:o,x1:a,x2:u,y:n.stack,name:"Intron "+t+"/"+(e.exon.length-1)})}}}}if(null!=n.namestart)M.textAlign=n.textalign,M.fillStyle=r,M.fillText(n.namestr,n.namestart,o+i/2);else if(n.namehover&&!t.query.noNameHover){const t=Math.max(10,n.start+10);M.fillStyle="white",M.fillRect(t,o,n.namewidth+10,i),M.strokeStyle=r,M.strokeRect(t+1.5,o+.5,n.namewidth+10-3,i-2),M.fillStyle=r,M.textAlign="center",M.fillText(n.namestr,t+n.namewidth/2+5,o+i/2)}else n.namein&&(M.textAlign="center",M.fillStyle="white",M.fillText(n.namestr,(Math.max(0,n.start)+Math.min(l,n.stop))/2,o+i/2))}const L={height:D,mapisoform:C,mapexon:R,returngmdata:_};if(0==N.length)return L.src=A.toDataURL(),L;const $=[];M.textAlign="center",M.textBaseline="middle";for(const[e,n]of N.entries()){const e=p&&n.category&&p[n.category]?p[n.category].color:n.color||u,r=n.canvas,o=(i+s)*(r.stack-1);n.genomicseq=(await P.Kf(q,n.chr+":"+(n.start+1)+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase();const l=(0,F.nt2aa)(n);for(const e of n.rglst){const s=t.query.rglst[e.idx];let c=0;for(let n=0;n<e.idx;n++)c+=t.query.rglst[n].width+a;const u=s.width/(s.stop-s.start),f=Math.min(i,3*u),d=f<8?null:f;let h=!1;r.stranded&&"-"==n.strand&&(h=!0);let p=0;d&&(M.font=d+"px Arial");for(const[t,e]of n.coding.entries()){let[r,a]=e;if(h){if(r>=s.stop){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(a<=s.start)break}else{if(a<=s.start){p+=a-r,0==t&&n.startCodonFrame&&(p-=3-n.startCodonFrame);continue}if(r>=s.stop)break}if(0==t&&n.startCodonFrame){h?a-=3-n.startCodonFrame:r+=3-n.startCodonFrame;let t=Math.max(e[0],s.start),l=Math.min(e[1],s.stop);if(h?t=Math.max(a,s.start):l=Math.min(r,s.stop),t<l){M.fillStyle=_n;const e=c+s.scale(s.reverse?l:t),n=c+s.scale(s.reverse?t:l);M.fillRect(e,o,Math.max(1,n-e),i)}}const f=Math.max(s.start,r),m=Math.min(s.stop,a);p+=h?a-m:f-r;let g=0;for(let t=0;t<m-f;t++){let e;if(p++,g++,p%3==0)e=p/3-1;else{if(t<m-f-1)continue;e=Math.floor(p/3)}let r=l[e],a=Math.ceil(p/3)%2==0?yn:null;r?"M"==r?a=bn:"*"==r&&(a=wn):(r=4,a=vn);let y,v=u*g;if(h){const e=m-1-t;y=c+s.scale(e)}else{const e=f+t+1-g;y=c+s.scale(e)}s.reverse&&(y-=v),g=0,y>=c&&y<=c+s.width&&(a&&(M.fillStyle=a,M.fillRect(y,o,v,i)),d&&(M.fillStyle="white",M.fillText(r,y+v/2,o+i/2)),$.push({x1:y,x2:y+v,y:n.canvas.stack,name:r+(e+1)+' <span style="font-size:.7em;color:#858585">AA residue</span>'}))}}}if(r.namehover&&!t.query.noNameHover){M.font="bold "+c+"px Arial";const t=Math.max(10,r.start+10);M.fillStyle="white",M.fillRect(t,o,r.namewidth+10,i),M.strokeStyle=e,M.strokeRect(t+1.5,o+.5,r.namewidth+10-3,i-2),M.fillStyle=e,M.fillText(r.namestr,t+r.namewidth/2+5,o+i/2)}}return L.src=A.toDataURL(),L.mapaa=$,L}(e,t))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/tkbedgraphdot",function(t){return async(e,n)=>{try{const r=e.query,i=t[r.genome];if(!i)throw"unknown genome";let s=null;if(r.file)r.file=y().join(o().tpmasterdir,r.file);else{if(!r.url)throw"file or url missing";s=await P.d1(r.url,r.indexURL)}const a=await P.Jy(r.file||r.url,s,i),l=await st(r,s,a);n.send(l)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.all(vo+"/tkbam",function(t){return async(e,n)=>{try{if(delete e.query.isFileSlice,e.query.gdcFileUUID){const t=e.cookies.sessionid,r=e.get("X-Auth-Token");if(!r&&!t)throw"GDC token or sessionid missing";if(await Tt(e.query.gdcFileUUID,r,t),e.query.stream2download)return void await async function(t,e,n,r,o){const i={compression:!1};r?i.Cookie=`sessionid=${r}`:i["X-Auth-Token"]=o;const s=y().join(Ce,"/slicing/view/",n+"?region="+e);t.statusCode=200,await Et(b().stream(s,{method:"get",headers:i}),t)}(n,e.query.gdcFilePosition,e.query.gdcFileUUID,e.cookies.sessionid,e.get("X-Auth-Token"));e.query.file=tn(e),e.query.isFileSlice=!0}if(e.query.downloadgdc)return void n.send(await en(e));if(e.query.clientdownloadgdcslice){if(!e.query.file||!e.query.isFileSlice)throw"invalid query";const t=y().join(o().cachedir_bam,e.query.file),r=await m().promises.readFile(t);return n.writeHead(200,{"Content-Type":"application/octet-stream","Content-Disposition":"attachment; filename=gdc.bam","Content-Length":r.length}),void n.end(Buffer.from(r,"binary"))}if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(e.query.getread)return void n.send(await async function(t,e){if(!e.query.chr)throw".chr missing";if(!e.query.qname)throw".qname missing";if(e.query.qname=decodeURIComponent(e.query.qname),!e.query.start)throw".start missing";if(!e.query.stop)throw".stop missing";const n={chr:e.query.chr,start:Number(e.query.start),stop:Number(e.query.stop),scale:()=>{},ntwidth:10};if(!Number.isInteger(n.start))throw".start not integer";if(!Number.isInteger(n.stop))throw".stop not integer";const r=await async function(t,e){let n,r,i,s,a,l,c,u,f;if(t.query.isFileSlice)a=y().join(o().cachedir_bam,t.query.file),await Ie(t,a);else{if([s,a,l]=P.ZX(t),s)throw s;i=l?await P.d1(a,t.query.indexURL||a+".bai"):null}if(t.query.unknownorder&&(c=Number(t.query.readstart),u=Number(t.query.readstop),Number.isNaN(c)||Number.isNaN(u)))throw"readstart/stop not provided for read with unknown order";if(await P.UE({isbam:!0,args:["view",a,(t.query.nochr?t.query.chr.replace("chr",""):t.query.chr)+":"+e.start+"-"+e.stop],dir:i,callback:(o,i)=>{if(o.split("\t")[0]!=t.query.qname)return;const s=Ze({sam_info:o,keepallboxes:!0,keepmatepos:!0,keepunmappedread:!0},e);if(s&&(!t.query.show_unmapped||!s.discord_unmapped2))if(t.query.show_unmapped&&t.query.getfirst){if(s.islast)return i.kill(),void(f=[s])}else if(t.query.show_unmapped&&t.query.getlast){if(s.isfirst)return i.kill(),void(f=[s])}else if(t.query.getfirst){if(s.isfirst)return i.kill(),void(f=[s])}else if(t.query.getlast){if(s.islast)return i.kill(),void(f=[s])}else if(t.query.unknownorder){if(s.segstart==c&&s.segstop==u)return i.kill(),void(f=[s])}else if(s.isfirst?n=s:s.islast&&(r=s),n&&r)return i.kill(),void(f=[n,r])}}),f){if(t.query.altseqs){const e={query_seq:f[0].seq,refseqs:t.query.refseqs,altseqs:t.query.altseqs,cigar_seq:f[0].cigarstr,start_position:f[0].segstart,ref_positions:t.query.ref_positions,refalleles:t.query.refalleles,altalleles:t.query.altalleles},n=(await(0,Q.run_rust)("align",JSON.stringify(e))).split("\n");let r;for(let t of n)t.includes("Final_output:")?r=JSON.parse(t.replace("Final_output:","")):console.log(t);f.alignments=r}return f}f=[],n&&f.push(n);r&&f.push(r);return f.length?f:null}(e,n);if(!r){if(e.query.show_unmapped)throw"mate not found";throw"read not found"}const i=[];for(const n of r)n.discord_unmapped1?i.push(await Xe(n,t,e.query)):i.push(await Qe(n,t,e.query));r.alignments&&(i[0].alignments=r.alignments);return{lst:i}}(r,e));const i=o().debugmode?new Date:null,s=await async function(t,e){let n;if(e.query.isFileSlice)n={genome:t,file:y().join(o().cachedir_bam,e.query.file),asPaired:e.query.asPaired,getcolorscale:e.query.getcolorscale,devicePixelRatio:e.query.devicePixelRatio?Number(e.query.devicePixelRatio):1},await Ie(e,n.file);else{const[r,o,i]=P.ZX(e);if(r)throw r;n={genome:t,file:o,asPaired:e.query.asPaired,getcolorscale:e.query.getcolorscale,devicePixelRatio:e.query.devicePixelRatio?Number(e.query.devicePixelRatio):1},i&&(n.dir=await P.d1(o,e.query.indexURL||o+".bai"))}if(e.query.pileupheight&&(n.pileupheight=Number(e.query.pileupheight),Number.isNaN(n.pileupheight)))throw".pileupheight is not integer";e.query.drop_pcrduplicates&&(n.drop_pcrduplicates=!0);if(e.query.variant){n.diff_score_plotwidth=Number(e.query.diff_score_plotwidth),e.query.max_diff_score&&(n.max_diff_score=Number(e.query.max_diff_score),n.min_diff_score=Number(e.query.min_diff_score));const t=e.query.variant.split(".");if(n.strictness=e.query.strictness,!Number.isInteger(t.length%4))throw"invalid variant, not chr.pos.ref.alt";n.alleleAlreadyUpdated=e.query.alleleAlreadyUpdated,n.alleleAlreadyUpdated&&(n.altseqs=e.query.altseqs,n.refseqs=e.query.refseqs,n.altalleles=e.query.altalleles,n.refalleles=e.query.refalleles,n.leftflankseqs=e.query.leftflankseqs,n.rightflankseqs=e.query.rightflankseqs,n.ref_positions=e.query.ref_positions);const r=t.length/4,o=[];for(let e=0;e<r;e++)o.push({chr:t[4*e],pos:Number(t[4*e+1]),ref:t[4*e+2],alt:t[4*e+3]});if(n.variant=o,e.query.alignOneGroup&&(n.alignOneGroup=e.query.alignOneGroup),Number.isNaN(n.variant.pos))throw"variant pos not integer"}else if(e.query.sv){const t=e.query.sv.split(".");if(t.length<6)throw"invalid sv, not chrA.posA.chrB.posB";if(n.sv={chrA:t[0],startA:Number(t[1]),strandA:Number(t[2]),chrB:t[3],startB:Number(t[4]),strandB:Number(t[5])},Number.isNaN(n.sv.startA))throw"sv.startA not integer";if(Number.isNaN(n.sv.startB))throw"sv.startB not integer"}if(Number.isFinite(Number(e.query.stackstart))){if(!e.query.stackstop)throw".stackstop missing";if(n.partstack={start:Number(e.query.stackstart),stop:Number(e.query.stackstop)},Number.isNaN(n.partstack.start))throw".stackstart not integer";if(Number.isNaN(n.partstack.stop))throw".stackstop not integer";if(!e.query.grouptype)throw".grouptype required for partstack";n.grouptype=e.query.grouptype}e.query.gdc||(e.query.nochr?n.nochr="string"==typeof e.query.nochr?JSON.parse(e.query.nochr):e.query.nochr:n.nochr=await P.Dp(n.file,t,n.dir));if(n.regions=e.query.regions,!Array.isArray(n.regions)||0==n.regions.length)throw"q.regions[] not non-empty array";let r=0;for(const t of n.regions){if(!t.chr)throw".chr missing from a region";if(!Number.isInteger(t.start))throw".start not integer of a region";if(!Number.isInteger(t.stop))throw".stop not integer of a region";t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start)),t.ntwidth=t.width/(t.stop-t.start),r=Math.max(r,t.ntwidth)}return n.stacksegspacing=Math.max(xe,ke*r),n.readcount_skipped=0,n}(r,e);n.send(await async function(t){await async function(t){if(t.variant){let e=0,n=0,r=0,o=t.variant[0].pos,i=t.variant[0].pos+Math.max(t.variant[0].ref.length,t.variant[0].alt.length);for(const s of t.variant){const t=Math.abs(s.pos-Math.max(s.ref.length,s.alt.length));t>e&&(e=t,n=r),o>s.pos&&(o=s.pos),i<s.pos+Math.max(s.ref.length,s.alt.length)&&(i=s.pos+Math.max(s.ref.length,s.alt.length)),r+=1}e=Math.floor(1.5*Math.max(t.variant[n].ref.length,t.variant[n].alt.length));const s={chr:t.variant[0].chr,start:o-e,stop:i+e};return await Pe(t,[s]),await Fe(s,t),void(t.regions[0].lines=s.lines)}await Pe(t,t.regions);for(const e of t.regions)await Fe(e,t)}(t),t.totalnumreads=t.regions.reduce(((t,e)=>t+e.lines.length),0);const e={nochr:t.nochr,count:{r:t.totalnumreads},groups:[]};t.read_limit_reached&&(e.count.read_limit_reached=t.read_limit_reached);t.canvaswidth=t.regions[t.regions.length-1].x+t.regions[t.regions.length-1].width;{const n=await async function(t){const e=[],n=[];let r=0;for(const o of t.regions){for(const t of o.lines)e.push({sam_info:t,tempscore:""});r=o.x+o.width,n.push(r)}if(0==e.length)return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]};if(t.variant){if(1==t.regions.length)return await async function(t,e,n){const r=t.regions[0].lines[0].split("\t")[9].length;let o=!1,i=[],s=[],a=[],l=[],c=[],u=[],f=[];if(t.alleleAlreadyUpdated)i=t.leftflankseqs,s=t.rightflankseqs,u=t.refseqs,f=t.altseqs,a=t.refalleles,l=t.altalleles,c=t.ref_positions,0!=u[0].toUpperCase().localeCompare((i[0]+a[0]+s[0]).toUpperCase())&&(console.log("Reference allele is not correct for variant 0"),o=!0);else{let e,n,o=0;for(const i of t.variant){let s="",u="";if(!(0!=i.ref.length&&"-"!=i.ref||"-"!=i.alt&&0!=i.alt.length))throw"Both Ref and Alt alleles are missing";if(0==i.ref.length||"-"==i.ref)s=(await P.Kf(t.genome,i.chr+":"+i.pos+"-"+i.pos)).split("\n").slice(1).join("").toUpperCase(),u=s+i.alt,i.pos-=1;else if("-"==i.alt||0==i.alt.length){const e=(await P.Kf(t.genome,i.chr+":"+i.pos+"-"+i.pos)).split("\n").slice(1).join("").toUpperCase();s=e+i.ref,u=e,i.pos-=1}else u=i.alt,s=i.ref;const f=i.pos,d=s.toUpperCase(),h=u.toUpperCase();0==o?(e=f-r,n=f+s.length+1+r):(f-r<e&&(e=f-r),f+s.length+1+r>n&&(n=f+s.length+1+r)),a.push(d),l.push(h),c.push(f),o+=1}o=0;for(const r of t.variant){const d=(await P.Kf(t.genome,r.chr+":"+e+"-"+c[o])).split("\n").slice(1).join("").toUpperCase(),h=(await P.Kf(t.genome,r.chr+":"+(c[o]+a[o].length+1)+"-"+n)).split("\n").slice(1).join("").toUpperCase(),p=d+a[o]+h,m=d+l[o]+h;console.log(r.chr+"."+c[o]+"."+a[o]+"."+l[o]),o+=1,i.push(d),s.push(h),u.push(p),f.push(m)}}const d=[];for(let t=0;t<e.length;t++){const n=e[t].sam_info.split("\t");d.push({read_sequence:n[9],start_position:Number(n[3]),cigar:n[5],flag:Number(n[1])})}const h=[];for(let t=0;t<a.length;t++)h.push({ref_position:Number(c[t]),refallele:a[t],altallele:l[t],refseq:u[t],altseq:f[t],leftflankseq:i[t],rightflankseq:s[t]});Number.isFinite(Number(t.strictness))||(t.strictness=1);const p={reads:d,alleles:h,strictness:Number(t.strictness)},m=new Date,g=await(0,Q.run_rust)("indel",JSON.stringify(p)),y=new Date;console.log("Time taken to run rust indel pipeline:",y-m,"ms");const v=g.split("\n");let b,w,_,x,k,q,N=0;for(let t of v)t.includes("Final_output:")?b=JSON.parse(JSON.parse(t.replace("Final_output:",""))):1==a.length&&t.includes("fisher_strand:")?(w=JSON.parse(t.replace("fisher_strand:","")),_=w.alternate_forward_count,x=w.alternate_reverse_count,k=w.reference_forward_count,q=w.reference_reverse_count,N=w.p_value):console.log(t);let S=!1;1==t.variant.length&&N>60&&(S=!0);const A=pt(t);t.variant.length;let M=1;for(let n=0;n<b.length;n++){const r=b[n],o=r.read_number,i=r.categories,s=r.categories[0],a=[];if(i.length>1){for(let t=1;t<i.length;t++)a.push(i[t]);i.length-1>M&&(M=i.length-1)}if(s.includes("alt"))for(let n=0;n<t.variant.length;n++)s=="alt"+n.toString()&&A[ut+n.toString()]&&(e[o].tempscore=["alt"+n.toString()],A[ut+n.toString()].templates.push(e[o]));else"ref"==s?A[ct]&&(e[o].tempscore=["ref"],A[ct].templates.push(e[o])):"none"==s?A[ft]&&(e[o].tempscore=a,A[ft].templates.push(e[o])):"amb"==s?A[dt]&&(e[o].tempscore=a,A[dt].templates.push(e[o])):console.log("Unaccounted group, please check")}const T=[];for(const e in A){const r=A[e];if(0!=r.templates.length){if(e.includes(ut))for(let n=0;n<t.variant.length;n++)e==ut+n.toString()&&(1==t.variant.length?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the alternative allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the alternative allele"}):1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read support the alternative allele with "+l[n]+" sequence"}):r.messages.push({isheader:!0,t:r.templates.length+" reads support the alternative allele with "+l[n]+" sequence"}));else e==dt?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" ambiguous read"}):r.messages.push({isheader:!0,t:r.templates.length+" ambiguous reads"}):e==ct?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting the reference allele"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting the reference allele"}):e==ft?1==r.templates.length?r.messages.push({isheader:!0,t:r.templates.length+" read supporting neither reference nor alternative alleles"}):r.messages.push({isheader:!0,t:r.templates.length+" reads supporting neither reference nor alternative alleles"}):console.log("Unaccounted group, please check");r.widths=n,T.push(r)}}const C=[];for(let t=0;t<T.length;t++)T[t].type.includes("support_alt")&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_ref"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_no"==T[t].type&&C.push(T[t]);for(let t=0;t<T.length;t++)"support_amb"==T[t].type&&C.push(T[t]);return{groups:C,refalleleerror:o,ref_positions:c,refalleles:a,altalleles:l,max_diff_score:M,min_diff_score:0,strand_probability:N,strand_significance:S,refseqs:u,altseqs:f,leftflankseqs:i,rightflankseqs:s,alternate_forward_count:_,alternate_reverse_count:x,reference_forward_count:k,reference_reverse_count:q}}(t,e,n);console.log("Indel pipeline works only in single region. Please check!")}if(t.sv&&t.regions.length>1)return async function(t,e,n){const r=pt(e),o=[];for(let t=0;t<e.regions.length;t++){const n=e.regions[t],r=(await P.Kf(e.genome,n.chr+":"+n.start+"-"+n.stop)).split("\n").slice(1).join("").toUpperCase(),i=[];for(const e of n.lines)i.push({sam_info:e,tempscore:"",ridx:t});const s={refseq:r,start:n.start,stop:n.stop,entries:i};0==t?(s.chr=e.sv.chrA,s.pos=e.sv.startA):1==t?(s.chr=e.sv.chrB,s.pos=e.sv.startB):console.log("More than two regions, please check"),o.push(s)}const i=new Date,s=(await(0,Q.run_rust)("sv",JSON.stringify(o))).split("\n"),a=new Date;let l,c;console.log("Time taken to run rust SV pipeline:",a-i,"ms");for(let t of s)t.includes("multi_region_templates:")?l=JSON.parse(t.replace("multi_region_templates:","")):t.includes("single_region_templates:")&&(c=JSON.parse(t.replace("single_region_templates:","")));if(!e.grouptype||"support_sv"==e.grouptype)for(const t of l)r[ht].templates.push(t);if(!e.grouptype||"support_ref"==e.grouptype)for(const t of c)r[ct].templates.push(t);const u=[];for(const t in r){const e=r[t];0!=e.templates.length&&(t==ht?1==e.templates.length?e.messages.push({isheader:!0,t:e.templates.length+" read supporting SV/fusion"}):e.messages.push({isheader:!0,t:e.templates.length+" reads supporting SV/fusion"}):t==ct&&e.messages.push({isheader:!0,t:e.templates.length+" reads supporting reference allele"}),e.widths=n,u.push(e))}return{groups:u}}(0,t,n);return{groups:[{type:lt,regions:mt(t.regions),templates:e,messages:[],partstack:t.partstack,widths:n}]}}(t);t.groups=n.groups,t.variant&&(e.ref_alleles=n.refalleles,e.alt_alleles=n.altalleles,e.allele_positions=n.ref_positions,e.strand_probability=n.strand_probability,e.alternate_forward_count=n.alternate_forward_count,e.reference_forward_count=n.reference_forward_count,e.alternate_reverse_count=n.alternate_reverse_count,e.reference_reverse_count=n.reference_reverse_count,1==n.strand_significance&&(e.strand_significance=!0),t.alleleAlreadyUpdated||(e.refseqs=n.refseqs,e.altseqs=n.altseqs,e.leftflankseqs=n.leftflankseqs,e.rightflankseqs=n.rightflankseqs,e.ref_positions=n.ref_positions,e.refalleles=n.refalleles,e.altalleles=n.altalleles)),Number.isFinite(t.max_diff_score)&&t.variant?(e.max_diff_score=t.max_diff_score,e.min_diff_score=t.min_diff_score):Number.isFinite(n.max_diff_score)&&(e.max_diff_score=n.max_diff_score,e.min_diff_score=n.min_diff_score),n.refalleleerror&&(e.refalleleerror=n.refalleleerror)}if(0==e.count.r)throw"No reads in view range.";if(t.alignOneGroup){const e=t.groups.find((e=>e.type==t.alignOneGroup));if(!e)throw"cannot find group for realignment";let n=$e(t,e);return n=Ue(e,t,n),await async function(t,e,n){let r;if(e.variant)if("support_ref"==t.type){let o=e.leftflankseqs[0].length;r=t.partstack?await Re(n,o,t.partstack.start,t.partstack.stop,e.refseqs[0]):await Re(n,o,0,0,e.refseqs[0])}else if("support_no"==t.type){let o=e.leftflankseqs[0].length;r=t.partstack?await Re(n,o,t.partstack.start,t.partstack.stop):await Re(n,o)}else if("support_amb"==t.type)console.log("Realignment of reads in ambiguous group is not currently implemented");else if(t.type.includes("support_alt")){for(let o=0;o<e.variant.length;o++)if(t.type=="support_alt"+o.toString()){let i=e.leftflankseqs[o].length;r=t.partstack?await Re(n,i,t.partstack.start,t.partstack.stop,e.altseqs[o]):await Re(n,i,0,0,e.altseqs[o])}}else console.log("Unaccounted group, please check");return{alignmentData:r}}(e,t,n)}let n=[];for(const r of t.groups){let o=$e(t,r);o=Ue(r,t,o),await ze(r,t,o),await Le(o,t),Ge(r,o,t);const i={type:r.type,width:t.canvaswidth,height:r.canvasheight,stackheight:r.stackheight,stackcount:r.stacks.length,allowpartstack:r.allowpartstack,templatebox:r.returntemplatebox,count:{r:o.reduce(((t,e)=>t+e.segments.length),0)}},s=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,r.canvasheight*t.devicePixelRatio),a=s.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio),a.textAlign="center",a.textBaseline="middle",i.messages=r.messages,i.messagerowheights=0;for(const e of o)Ve(a,e,r,t);Ke(a,r,t,o),t.asPaired&&(i.count.t=o.length),t.variant&&(i.diff_scores_img=await Ee(t,r,o,e.max_diff_score,e.min_diff_score),"support_alt0"==i.type?i.group_color=ie:"support_alt1"==i.type?i.group_color=se:"support_alt2"==i.type?i.group_color=ae:"support_alt3"==i.type?i.group_color=le:"support_alt4"==i.type?i.group_color=ce:"support_alt5"==i.type?i.group_color=ue:"support_ref"==i.type&&(i.group_color=fe)),i.src=s.toDataURL(),e.groups.push(i),n=[...n,...o]}t.readcount_skipped&&(e.count.skipped=t.readcount_skipped);t.getcolorscale&&(e.colorscale=function(t){const e=160,n=20,r=1,o=12,i=5,s=100,a=4,l=s+e+10,c=2*o+i+a+4*(n+r),u=(0,S.createCanvas)(t.devicePixelRatio*l,t.devicePixelRatio*c),f=u.getContext("2d");t.devicePixelRatio>1&&f.scale(t.devicePixelRatio,t.devicePixelRatio);f.fillStyle="black",f.font=o+"pt Arial",f.textAlign="center",f.fillText("Base quality",s+e/2,o);let d=2*o+i;function h(t,r,o){const i=s,a=f.createLinearGradient(i,o,i+e,o);a.addColorStop(0,r),a.addColorStop(1,t),f.fillStyle=a,f.fillRect(i,o,e,n)}return f.strokeStyle="black",f.beginPath(),f.moveTo(s,d),f.lineTo(s,d+a),f.moveTo(s+e/4,d),f.lineTo(s+e/4,d+a),f.moveTo(s+e/2,d),f.lineTo(s+e/2,d+a),f.moveTo(s+3*e/4,d),f.lineTo(s+3*e/4,d+a),f.moveTo(s+e,d),f.lineTo(s+e,d+a),f.closePath(),f.stroke(),f.fillText(40,s,d),f.fillText(30,s+e/4,d),f.fillText(20,s+e/2,d),f.fillText(10,s+3*e/4,d),f.fillText(0,s+e,d),f.textAlign="left",f.textBaseline="middle",d+=a,f.fillText("Match",0,d+n/2),h(It,Ot,d),d+=n+r,f.fillStyle="black",f.fillText("Mismatch",0,d+n/2),h(Zt,$t,d),d+=n+r,f.fillStyle="black",f.fillText("Softclip",0,d+n/2),h(Bt,Ut,d),d+=n+r,f.fillStyle="black",f.fillText("Insertion",0,d+n/2),h(Kt,Yt,d),{width:l,height:c,src:u.toDataURL()}}(t));if(!t.partstack)if(0==e.count.r);else{if(!t.pileupheight)throw"pileupheight missing";e.pileup_data=await async function(t,e){const n=(0,S.createCanvas)(t.canvaswidth*t.devicePixelRatio,t.pileupheight*t.devicePixelRatio),r=n.getContext("2d");t.devicePixelRatio>1&&r.scale(t.devicePixelRatio,t.devicePixelRatio);const o=[];let i=0;for(const[n,r]of t.regions.entries()){o[n]=await De(t,r),Oe(n,r,e,o[n]);for(const t of o[n])t&&(i=Math.max(i,t.total))}for(const[e,n]of t.regions.entries()){const s=t.pileupheight/i;for(const i of o[e]){if(!i)continue;const e=(i.position-n.start)*n.ntwidth+n.x,o=n.ntwidth>=1?e:Math.floor(e),a=Math.max(1,n.ntwidth);{r.fillStyle=oe;const e=i.total*s;r.fillRect(o,t.pileupheight-e,a,e)}let l=0;if(i.A){r.fillStyle=F.basecolor.A;const e=i.A*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.C){r.fillStyle=F.basecolor.C;const e=i.C*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.G){r.fillStyle=F.basecolor.G;const e=i.G*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.T){r.fillStyle=F.basecolor.T;const e=i.T*s;r.fillRect(o,t.pileupheight-l-e,a,e),l+=e}if(i.softclip){r.fillStyle=Ut;const e=i.softclip*s;r.fillRect(o,t.pileupheight-l-e,a,e)}}}return{width:t.canvaswidth,maxValue:i,src:n.toDataURL()}}(t,n)}return e}(s)),o().debugmode&&console.log("bam.js time ms",new Date-i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.get(vo+"/gdcbam",(async function(t,e){try{if(t.query.gdc_id){const n=await async function(t,e){const n={file_metadata:[],numFilesSkippedByWorkflow:0},r=await qt(t,n,e);if(!r.data.hits.length){if(n.is_case_id||n.is_case_uuid)throw"No bam files available for this case.";if(e){if((await qt(t,n)).data.hits.length)throw"Case not in current cohort.";throw"Invalid input ID."}throw"Invalid input ID."}for(const t of r.data.hits){if(t.analysis.workflow_type==kt){n.numFilesSkippedByWorkflow++;continue}const e={};e.file_uuid=t.id,e.file_size=bt(t.file_size),e.experimental_strategy=t.experimental_strategy,e.entity_id=t.associated_entities[0].entity_submitter_id,e.case_id=t.associated_entities[0].case_id,e.sample_type=t.cases[0].samples[0].sample_type,n.file_metadata.push(e)}return n}(t.query.gdc_id,t.query.filter0);await async function(t,e){var n;if(null===(n=t.file_metadata)||void 0===n||!n.length)return;const r=e.cookies.sessionid;if(!r)return;try{await Tt(t.file_metadata[0].file_uuid,null,r)}catch(e){"Permission denied"==e&&(t.userHasNoAccess=!0)}}(n,t),e.send(n)}else{const n=await async function(t){var e,n,r;const o=await St(null,null,t,Ct),i={};if(!Array.isArray(null===(e=o.data)||void 0===e?void 0:e.hits))throw"re.data.hits[] not array";for(const t of o.data.hits){var s,a,l,c;if(t.analysis.workflow_type==kt)continue;const e=null===(s=t.cases)||void 0===s||null===(a=s[0])||void 0===a?void 0:a.submitter_id;e&&(i[e]||(i[e]=[]),i[e].push({file_uuid:t.id,sample_type:null===(l=t.cases)||void 0===l||null===(c=l[0].samples)||void 0===c?void 0:c[0].sample_type,experimental_strategy:t.experimental_strategy,file_size:(Number.parseFloat(t.file_size)/1e9).toFixed(2)+" GB"}))}return{case2files:i,total:null===(n=o.data)||void 0===n||null===(r=n.pagination)||void 0===r?void 0:r.total,loaded:Ct}}(t.query.filter0);e.send(n)}}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/gdc_ssms",ln.BM(fo)),yo.get(vo+"/tkaicheck",(async(t,e)=>{try{e.send(await async function(t){const[e,n,r]=P.ZX(t);if(e)throw e;const o=Number(t.query.coveragemax)||100;if(!Number.isInteger(o))throw"invalid coveragemax";const i=Number(t.query.vafheight);if(!Number.isInteger(i))throw"invalid vafheight";const s=Number(t.query.coverageheight);if(!Number.isInteger(s))throw"invalid coverageheight";const a=Number(t.query.rowspace);if(!Number.isInteger(a))throw"invalid rowspace";const l=Number(t.query.dotsize)||1;if(!Number.isInteger(l))throw"invalid dotsize";if(!t.query.rglst)throw".rglst missing";"string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst));const c=t.query.gtotalcutoff,u=t.query.gmafrestrict,f=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,(3*i+4*a+2*s)*t.query.devicePixelRatio),d=f.getContext("2d");let h;t.query.devicePixelRatio>1&&d.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d.fillStyle="#f1f1f1",d.fillRect(0,0,t.query.width,i/2),d.fillRect(0,2*a+i+s,t.query.width,i/2),d.fillStyle="#FAFAD9",d.fillRect(0,i/2,t.query.width,i/2),d.fillRect(0,2*a+1.5*i+s,t.query.width,i/2),r&&(h=await P.d1(n,t.query.indexURL));let p=0;for(const e of t.query.rglst)e.x=p,p+=t.query.regionspace+e.width;const m="#786312",g="#122778",y="#858585",v="red";for(const e of t.query.rglst){const t=e.width/(e.stop-e.start);await P.UE({args:[n,e.chr+":"+e.start+"-"+e.stop],dir:h,callback:n=>{const r=n.split("\t"),f=Number.parseInt(r[1]),h=Number.parseInt(r[2]),p=Number.parseInt(r[3]),b=Number.parseInt(r[4]),w=Number.parseInt(r[5]);if(Number.isNaN(h)||Number.isNaN(p)||Number.isNaN(b)||Number.isNaN(w))return;if(c&&w<c)return;const _=Math.ceil(e.x+t*(e.reverse?e.stop-f:f-e.start)-l/2);d.fillStyle=m;const x=h/p;d.fillRect(_,i*(1-x),l,2);const k=b/w;if(u&&(k<u||k>1-u))return;d.fillRect(_,i+a+s+a+i*(1-k),l,2),d.fillStyle=g;const q=Math.abs(x-k);d.fillRect(_,2*i+4*a+2*s+i*(1-q),l,2),d.fillStyle=y;let N=(p>=o?o:p)*s/o,S=s-N;d.fillRect(_,S+i+a,l,N),d.fillStyle=y,N=(w>=o?o:w)*s/o,S=s-N,d.fillRect(_,S+3*a+2*i+s,l,N),p>=o&&(d.fillStyle=v,d.fillRect(_,i+a,l,2)),w>=o&&(d.fillStyle=v,d.fillRect(_,3*a+2*i+s,l,2))}})}return{src:f.toDataURL(),coveragemax:o}}(t))}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/blat",function(t){return async(e,n)=>{try{if(e.query.serverstat){const e=[];for(const n in t){const r=t[n];r.blat&&e.push(await qn(n,r))}if(0==e.length)throw"found no genome with blat";return void n.send({lst:e})}if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";if(!r.blat)throw"blat not enabled";if(!e.query.seq)throw".seq missing";n.send(await async function(t,e,n,r){const i=y().join(o().cachedir,await(0,P.tG)(">query\n"+e+"\n")),s=await Nn(t,i),a=(await(0,P.b5)(s)).trim();if(m().unlink(s,(()=>{})),m().unlink(i,(()=>{})),""==a)return{nohit:1};const l=a.split("\n"),c=[];for(const t of l){const e={},n=t.split(" ").filter((function(t){return""!=t}))[0].split("\t");e.query_match=n[0],e.query_startpos=(parseInt(n[11])+1).toString(),e.query_stoppos=n[12],e.query_strand=n[8],e.query_totallen=n[10],e.query_alignlen=Math.abs(parseInt(n[11])-parseInt(n[12])).toString(),e.ref_chr=n[13],e.ref_startpos=(parseInt(n[15])+1).toString(),e.ref_stoppos=n[16],e.ref_alignlen=Math.abs(n[16]-n[15]).toString(),e.ref_totallen=n[14],c.push(e)}return c.sort(((t,e)=>e.query_match-t.query_match)),{hits:c}}(r,e.query.seq,e.query.soft_starts,e.query.soft_stops))}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.all(vo+"/mds3",function(t){return async(e,n)=>{try{if(!e.query.genome)throw".genome missing";const r=t[e.query.genome];if(!r)throw"invalid genome";const i=function(t,e){const n=t.query;t.get("X-Auth-Token")&&(n.token=t.get("X-Auth-Token"));(0,P.Y5)(n,t.cookies),n.hiddenmclasslst&&(n.hiddenmclass=new Set(n.hiddenmclasslst.split(",")),delete n.hiddenmclasslst);return n}(e),s=await async function(t,e){if(t.dslabel){if(!e.datasets)throw".datasets{} missing from genome";const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";return n}const n={queries:{}};if(t.bcffile||t.bcfurl){const[r,o,i]=(0,P.ZX)({query:{file:t.bcffile,url:t.bcfurl}});if(r)throw r;const s={};i?(s.url=o,s.indexURL=t.bcfindexURL):s.file=o,n.queries.snvindel={byrange:{_tk:s}},n.queries.snvindel.byrange.get=await or(n,e)}return n}(i,r);!function(t,e){var n;if(t.filter0){const n="object"==typeof t.filter0?t.filter0:JSON.parse("string"==typeof t.filter0&&t.filter0.startsWith("%")?decodeURIComponent(t.filter0):t.filter0);t.filter0=e.validate_filter0(n)}t.filterObj&&"string"==typeof t.filterObj&&(t.filterObj=JSON.parse("string"==typeof t.filterObj&&t.filterObj.startsWith("%")?decodeURIComponent(t.filterObj):t.filterObj));if(t.skewerRim){if("format"!=t.skewerRim.type)throw"unknown skewerRim.type";var r,o;if(!t.skewerRim.formatKey)throw"skewerRim.formatKey missing when type=format";if(null===(r=e.queries)||void 0===r||null===(o=r.snvindel)||void 0===o||!o.format)throw"snvindel.format{} not found when type=format";if(!e.queries.snvindel.format[t.skewerRim.formatKey])throw"invalid skewerRim.formatKey";if(t.skewerRim.hiddenvalues=new Set,t.skewerRim.hiddenvaluelst){if(!Array.isArray(t.skewerRim.hiddenvaluelst))throw"query.skewerRim.hiddenvaluelst is not array";for(const e of t.skewerRim.hiddenvaluelst)t.skewerRim.hiddenvalues.add(e);delete t.skewerRim.hiddenvaluelst}}if(t.formatFilter){var i,s;if("object"!=typeof t.formatFilter)throw"formatFilter{} not object";if(null===(i=e.queries)||void 0===i||null===(s=i.snvindel)||void 0===s||!s.format)throw"snvindel.format{} not found when formatFilter is used";const n={};for(const r in t.formatFilter){if(!e.queries.snvindel.format[r])throw"invalid format key from formatFilter";if(!Array.isArray(t.formatFilter[r]))throw"formatFilter[k] value is not array";n[r]=new Set(t.formatFilter[r])}t.formatFilter=n}("format"==(null===(n=t.skewerRim)||void 0===n?void 0:n.type)||t.formatFilter)&&(t.addFormatValues=!0)}(i,s);const a=await async function(t,e){if(t.singleSampleMutation){var n;if(null===(n=e.queries.singleSampleMutation)||void 0===n||!n.get)throw"not supported on this dataset";return await e.queries.singleSampleMutation.get(t.singleSampleMutation,t)}if(t.singleSampleGenomeQuantification){if(!e.queries.singleSampleGenomeQuantification)throw"not supported on this dataset";const n=e.queries.singleSampleGenomeQuantification[t.singleSampleGenomeQuantification.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGenomeQuantification.sample,t.devicePixelRatio)}if(t.singleSampleGbtk){if(!e.queries.singleSampleGbtk)throw"not supported on this dataset";const n=e.queries.singleSampleGbtk[t.singleSampleGbtk.dataType];if(!n)throw"invalid dataType";return await n.get(t.singleSampleGbtk.sample)}if(t.ssm2canonicalisoform){if(!e.ssm2canonicalisoform)throw"ssm2canonicalisoform not supported on this dataset";return{isoform:await e.ssm2canonicalisoform.get(t)}}if(t.variant2samples){if(!e.variant2samples)throw"not supported by server";return{variant2samples:await e.variant2samples.get(t)}}if(t.m2csq){if(e.queries&&e.queries.snvindel&&e.queries.snvindel.m2csq)return{csq:await e.queries.snvindel.m2csq.get(t)};throw"m2csq not supported on this dataset"}if(t.forTrack){const n={};if(t.skewer){if(n.skewer=[],e.queries.snvindel){const r=await async function(t,e){if(t.isoform){if(t.atgenomic){if(!e.queries.snvindel.byrange)throw".atgenomic but missing byrange query method";return await e.queries.snvindel.byrange.get(t)}if(e.queries.snvindel.byisoform)return await e.queries.snvindel.byisoform.get(t)}if(t.rglst){if(!e.queries.snvindel.byrange)throw"q.rglst[] provided but .byrange{} is missing";return await e.queries.snvindel.byrange.get(t)}throw"insufficient query parameters for snvindel"}(t,e);n.skewer.push(...r)}if(e.queries.svfusion){const r=await async function(t,e){if(t.rglst){if(!e.queries.svfusion.byrange)throw"q.rglst provided but svfusion.byrange missing";return await e.queries.svfusion.byrange.get(t)}throw"insufficient query parameters for svfusion"}(t,e);n.skewer.push(...r)}if(e.queries.geneCnv){const r=await async function(t,e){if(t.gene){if(!e.queries.geneCnv.bygene)throw"q.gene provided but geneCnv.bygene missing";return await e.queries.geneCnv.bygene.get(t)}}(t,e);n.geneCnv=r}!function(t,e){if(e.skewer){const n=[];for(const r of e.skewer)t.rglst&&!t.rglst.find((t=>r.chr==t.chr&&r.pos>=t.start&&r.pos<=t.stop))||n.push(r);e.skewer=n}e.genecnvAtsample}(t,n),n.mclass2variantcount=function(t){const e=new Map;for(const n of t){const t=n.class||n.dt;e.set(t,1+(e.get(t)||0))}return[...e].sort(((t,e)=>e[1]-t[1]))}(n.skewer)}return function(t,e,n){const r=new Set;if(n.skewer)for(const o of n.skewer)if(o.samples){o.occurrence=o.samples.length,yr(o,t,e),vr(o,e);for(const t of o.samples)r.add(t.sample_id);delete o.samples}r.size&&(n.sampleTotalNumber=r.size)}(t,e,n),n}if(t.geneExpression){if(!e.queries.geneExpression)throw"not supported";const{gene2sample2value:n,byTermId:r}=await e.queries.geneExpression.get(t);if(0==n.size)throw"no data";if(1==n.size)return{gene2sample2value:n};const i=new Date,s=await async function(t,e,n){const r=new Set;for(const e of t.values())for(const t in e)r.add(t);const i={matrix:[],row_names:[],col_names:[...r],cluster_method:e.clusterMethod,plot_image:!1};n.queries.geneExpression.valueIsTransformed&&(i.valueIsTransformed=!0);for(const[e,n]of t){i.row_names.push(e);const t=[];for(const e of i.col_names)t.push(n[e]||0);i.matrix.push(t)}const s=y().join(o().cachedir,Math.random().toString()+".json");await(0,P.Sf)(s,JSON.stringify(i));const a=await async function(t,e=[]){try{await m().promises.stat(t)}catch(e){throw`${t} does not exist`}const n=[],r=[];return new Promise(((i,s)=>{const a=(0,q.spawn)(o().Rscript,[t,...e]);a.stdout.on("data",(t=>n.push(t))),a.stderr.on("data",(t=>r.push(t))),a.on("error",(t=>s(t))),a.on("close",(t=>{const e=n.join("").trim().split("\n");i(e)}))}))}(y().join(o().binpath,"utils","fastclust.R"),[s]);m().unlink(s,(()=>{}));let l,c,u,f,d,h=[],p=[],g=!1,v=!1;for(const t of a)t.includes("OutputMatrix")?d=t.replace("OutputMatrix\t","").split("\t").map((t=>parseFloat(t))).filter((t=>t)):t.includes('[1] "RowCoordinates"')?g=!0:t.includes('"ColumnCoordinates"')?(v=!0,g=!1):t.includes("rowindexes")?l=t.replace("rowindexes\t","").split("\t").map((t=>parseInt(t))).filter((t=>t)):t.includes("colindexes")?c=t.replace("colindexes\t","").split("\t").map((t=>parseInt(t))).filter((t=>t)):t.includes("rownames")?u=t.replace("rownames\t","").split("\t").filter((function(t){return""!=t.trim()})):t.includes("colnames")?f=t.replace("colnames\t","").split("\t").filter((function(t){return""!=t.trim()})):t.includes('"Done"')?v=!1:1==g?h.push(t):1==v&&p.push(t);let b=await br(h,l),w=await br(p,c),_=[];for(let t=0;t<u.length;t++)if(f.length>0){let e=[];for(let n=0;n<f.length;n++)e.push(d[n*u.length+t]);_.push(e)}return{geneNameLst:u,sampleNameLst:f,matrix:_,row_dendro:b.dendrogram,row_children:b.children,row_names_index:l,col_dendro:w.dendrogram,col_children:w.children,col_names_index:c}}(n,t,e);return console.log("clustering done:",new Date-i,"ms"),{clustering:s,byTermId:r}}throw"do not know what client wants"}(i,s);n.send(a)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.get(vo+"/tkbampile",(async function(t,e){try{const[n,r,o]=P.ZX(t);if(n)throw n;let i=t.query.usegrade;const s=Number(t.query.allheight),a=Number(t.query.fineheight),l=Number(t.query.fineymax),c=Number(t.query.midpad),u=Number(t.query.regionspace),f=Number(t.query.width);if(!Number.isInteger(s))throw"allheight is not integer";if(!Number.isInteger(a))throw"fineheight is not integer";if(!Number.isInteger(l))throw"fineymax is not integer";if(!Number.isInteger(c))throw"midpad is not integer";if(!Number.isInteger(u))throw"regionspace is not integer";if(!Number.isFinite(f))throw"width is not a number";const d="string"==typeof t.query.rglst?JSON.parse(t.query.rglst):t.query.rglst;if(!d)throw"no rglst[]";if(!Array.isArray(d))throw"rglst is not an array";if(0==d.length)throw"empty rglst";for(const t of d)t.reverse?t.scale=e=>Math.ceil(t.width*(t.stop-e)/(t.stop-t.start)):t.scale=e=>Math.ceil(t.width*(e-t.start)/(t.stop-t.start));let h;o&&(h=await P.d1(r,t.query.indexURL));for(const t of d){t.items=[];let e=0;await P.UE({args:[r,t.chr+":"+t.start+"-"+t.stop],dir:h,callback:n=>{const r=n.split("\t");let o;try{o=JSON.parse(r[2])}catch(t){return void e++}const i=Number.parseInt(r[1]);t.items.push({pos:i,data:o})}})}const p=s+c+a,m=(0,S.createCanvas)(f,p),g=d.reduce(((t,e)=>t+e.items.length),0),y=m.getContext("2d");if(0==g)return y.font="15px Arial",y.fillStyle="#aaa",y.textAlign="center",y.textBaseline="middle",y.fillText("No data in view range",f/2,p/2),void e.send({src:m.toDataURL()});let v=null;if(!i){const t=new Set;for(const e of d)for(const n of e.items)for(const e in n.data)t.add(e);if(v=[...t],v.length>0&&(i=v[0]),!i)return void e.send({src:m.toDataURL()})}let b=0;for(const t of d)for(const e of t.items)if(e.data[i]){let t=0;for(const n in e.data[i])t+=e.data[i][n];b=Math.max(b,t)}const w="#ededed";let _=0;const x=s/b,k=a/l;for(const t of d){const e=t.width/(t.stop-t.start);for(const n of t.items){const r=n.data[i];if(!r)continue;const o=t.scale(n.pos);let a=0;const u=[];for(const t in r)u.push({nt:t,v:r[t]}),a+=r[t];y.fillStyle=w;const f=x*(b-a);if(y.fillRect(_+o,f,e,x*a),u.length>1){u.sort(((t,e)=>e.v-t.v));for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=F.basecolor[u[t].nt],y.fillRect(_+o,f+x*n,e,x*u[t].v)}}y.fillStyle=w;const d=s+c+k*(l-Math.min(a,l));if(y.fillRect(_+o,d,e,k*Math.min(a,l)),u.length>1)for(let t=1;t<u.length;t++){let n=0;for(let e=0;e<t;e++)n+=u[e].v;y.fillStyle=F.basecolor[u[t].nt],y.fillRect(_+o,d+k*(l-Math.min(l,a-n)),e,k*Math.min(l,u[t].v))}}_+=t.width+u}e.send({src:m.toDataURL(),allgrades:v,usegrade:i,allmax:b})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/dsdata",(async function(t,e){try{if(!fo[t.query.genome])throw"invalid genome";if(!t.query.dsname)throw".dsname missing";const n=fo[t.query.genome].datasets[t.query.dsname];if(!n)throw"invalid dsname";const r=[];for(const e of n.queries)if((!t.query.expressiononly||e.isgeneexpression)&&!(t.query.noexpression&&e.isgeneexpression||e.dsblocktracklst))if(e.vcffile){const n=await Mo(e,t);r.push(n)}else{if(!e.makequery)throw"unknow type from one of ds.queries[]";{const o=Ao(n,e,t);r.push(o)}}e.send({data:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/tkbigwig",(async function(t,e){try{let n,r,i,s,a=!1,l=!1;const[c,u,f]=P.ZX(t);if(c)throw c;if(u.endsWith(".gz")&&(l=!0,f&&(s=await P.d1(u,t.query.indexURL))),t.query.autoscale)a=!0;else if(t.query.percentile){if(i=t.query.percentile,!Number.isFinite(i))throw"invalid percentile"}else{if(n=t.query.minv,r=t.query.maxv,!Number.isFinite(n))throw"invalid minv";if(!Number.isFinite(r))throw"invalid maxv"}if(!Number.isFinite(t.query.barheight))throw"invalid barheight";if(!Number.isFinite(t.query.regionspace))throw"invalid regionspace";if(!Number.isFinite(t.query.width))throw"invalid width";if(!t.query.rglst)throw"region list missing";if(t.query.dotplotfactor&&!Number.isInteger(t.query.dotplotfactor))throw"dotplotfactor value should be positive integer";if(l)return await async function(t,e,n,r,o,i){if(null==n||null==r)throw"Y axis scale must be defined for bedgraph track";const s=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),a=s.getContext("2d");t.query.devicePixelRatio>1&&a.scale(t.query.devicePixelRatio,t.query.devicePixelRatio);let l=0;for(let e of t.query.rglst)await et(t,e,l,n,r,o,i,a),l+=e.width+t.query.regionspace;e.send({src:s.toDataURL()})}(t,e,n,r,u,s);for(const e of t.query.rglst){let n;if(o().features.bigwig_rust){const r=u+","+e.chr+","+e.start+","+e.stop+","+Math.ceil(e.width*(t.query.dotplotfactor||1));n=await(0,Q.run_rust)("bigwig",r)}else n=await rt(t,e,u);n&&(e.values=n.trim().split("\t").map(Number.parseFloat),t.query.dividefactor&&(e.values=e.values.map((e=>e/t.query.dividefactor))))}let d=!0;for(const e of t.query.rglst)e.values&&(d=!1);const h=(0,S.createCanvas)(t.query.width*t.query.devicePixelRatio,t.query.barheight*t.query.devicePixelRatio),p=h.getContext("2d");if(t.query.devicePixelRatio>1&&p.scale(t.query.devicePixelRatio,t.query.devicePixelRatio),d)return p.font="14px Arial",p.fillStyle="#858585",p.textAlign="center",p.textBaseline="middle",p.fillText(t.query.name+": no data in view range",t.query.width/2,t.query.barheight/2),void e.send({src:h.toDataURL(),nodata:!0});const m=1,g=t.query.dotplotfactor?1/t.query.dotplotfactor:1;let y=0,v=0;const b={};if(a||i){const e=[],n=[];for(const r of t.query.rglst)if(r.values)for(const t of r.values)Number.isNaN(t)||(t>=0&&e.push(t),t<=0&&n.push(t));e.length&&(e.sort(((t,e)=>t-e)),y=a?e[e.length-1]:e[Math.floor(e.length*i/100)]),n.length&&(n.sort(((t,e)=>e-t)),v=a?n[n.length-1]:n[Math.floor(n.length*i/100)]),b.minv=v,b.maxv=y}else v=n,y=r;if(t.query.barheight<10){let e=(0,tt.B8)(t.query.pcolor);const n=e.r+","+e.g+","+e.b;e=(0,tt.B8)(t.query.ncolor);const r=e.r+","+e.g+","+e.b;let o=0;for(const e of t.query.rglst){if(e.values)for(let i=0;i<e.values.length;i++){const s=e.values[i];if(Number.isNaN(s))continue;p.fillStyle=s>=y?t.query.pcolor2:s>=0?"rgba("+n+","+s/y+")":s<=v?t.query.ncolor2:"rgba("+r+","+s/v+")";const a=Math.ceil(o+(e.reverse?e.width-g*i:g*i));p.fillRect(a,0,m,t.query.barheight)}o+=e.width+t.query.regionspace}}else{const e=nt().height(t.query.barheight).min(v).max(y);let n=0;for(const r of t.query.rglst){if(r.values)for(let o=0;o<r.values.length;o++){const i=r.values[o];if(Number.isNaN(i))continue;p.fillStyle=i>0?t.query.pcolor:t.query.ncolor;const s=Math.ceil(n+(r.reverse?r.width-g*o:g*o)),a=e(i);if(i>0)p.fillRect(s,a.y,m,t.query.dotplotfactor?Math.min(2,a.h):a.h);else if(t.query.dotplotfactor){const t=Math.min(2,a.h);p.fillRect(s,a.y+a.h-t,m,t)}else p.fillRect(s,a.y,m,a.h);i>y?(p.fillStyle=t.query.pcolor2,p.fillRect(s,0,m,2)):i<v&&(p.fillStyle=t.query.ncolor2,p.fillRect(s,t.query.barheight-2,m,2))}n+=r.width+t.query.regionspace}}b.src=h.toDataURL(),e.send(b)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/tkld",function(t){return async(e,n)=>{try{const r=t[e.query.genome];if(!r)throw"unknown genome";n.send(await async function(t,e){const[n,r,o]=P.ZX(t);if(n)throw n;let i;o&&(i=await P.d1(r,t.query.indexURL));if(!t.query.rglst)throw"rglst missing";const s=await P.Jy(r,i,e),a=t.query.connheight||50,l={rglst:[]};for(const e of t.query.rglst){const n={chr:e.chr,start:e.start,stop:e.stop,width:e.width,reverse:e.reverse,xoff:e.xoff};l.rglst.push(n);const o=[],c=new Set,u=(s?e.chr.replace("chr",""):e.chr)+":"+e.start+"-"+e.stop;await P.UE({args:[r,u],dir:i,callback:t=>{const n=t.split("\t"),r=Number.parseInt(n[1]);if(r<e.start)return;const i=Number.parseInt(n[2]);if(i>e.stop)return;const s=Number.parseFloat(n[5]);o.push({start:r,stop:i,r2:s}),c.add(r),c.add(i)}}),n.img=ot(e,o,c,a,t.query.devicePixelRatio||1)}return l}(e,r))}catch(t){n.send({error:t.message||t})}}}(fo)),yo.get(vo+"/tabixheader",(async function(t,e){wo(t);try{const[n,r,o]=P.ZX(t);if(n)throw n;const i=o?await P.d1(r,t.query.indexURL):null,s=await P.ZD(r,i);e.send({lines:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.all(vo+"/snp",(async function(t,e){try{const n=t.query.genome;if(!n)throw"no genome";e.send({results:await No(t.query,fo[n])})}catch(t){return t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/isoformlst",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!Array.isArray(t.query.lst))throw".lst missing";const r=[];for(const e of t.query.lst){if(n.genomicNameRegexp.test(e))continue;const t=n.genedb.getjsonbyisoform.all(e);r.push(t.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})))}e.send({lst:r})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/dbdata",(function(t,e){})),yo.get(vo+"/img",(async function(t,e){wo(t);const[n,r,o]=P.ZX(t);try{if(n)throw"invalid image file";const t=await m().promises.readFile(r);e.send({src:"data:image/jpeg;base64,"+new Buffer.from(t).toString("base64"),size:j()(r)})}catch(n){e.send({error:n.message||n})}})),yo.post(vo+"/svmr",(function(t,e){if(t.query.file){const[n,r,o]=P.ZX(t);if(n)return void e.send({error:"illegal file name"});m().readFile(r,"utf8",((t,n)=>{t?e.send({error:"cannot read file"}):e.send({raw:n})}))}else e.send({error:"missing file"})})),yo.post(vo+"/study",(async function(t,e){try{if(P.lY(t.query.file))throw"invalid file path";const n=y().join(o().tpmasterdir,t.query.file.endsWith(".json")?t.query.file:t.query.file+".json"),r=JSON.parse(await P.b5(n));if(!r.genome)throw"genome missing";const i={};let s=0;for(const t of r.mutationset||[]){const e=L.Dz(r.genome);if(!e)throw"init_bulk_flag() failed";if(r.mutationset.length>1&&(e.tpsetname=t.name?t.name:"set"+ ++s),i[Math.random()]=e,t.snvindel){const n=(await P.b5(y().join(o().tpmasterdir,t.snvindel))).trim().split(/\r?\n/),r=$.parseheader(n[0],e);if(r)throw"snvindel header line error: "+r;for(let t=1;t<n.length;t++)$.parseline(t,n[t],e)}if(t.sv){const n=(await P.b5(y().join(o().tpmasterdir,t.sv))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!0);if(r)throw"sv header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!0)}if(t.fusion){const n=(await P.b5(y().join(o().tpmasterdir,t.fusion))).trim().split(/\r?\n/),r=B.parseheader(n[0],e,!1);if(r)throw"fusion header line error: "+r;for(let t=1;t<n.length;t++)B.parseline(t,n[t],e,!1)}if(t.svjson){const n=(await P.b5(y().join(o().tpmasterdir,t.svjson))).trim().split(/\r?\n/),[r,i]=G.parseheader(n[0],e);if(r)throw"svjson header line error: "+r;for(let t=1;t<n.length;t++)G.parseline(t,n[t],e,i)}if(t.cnv){const n=(await P.b5(y().join(o().tpmasterdir,t.cnv))).trim().split(/\r?\n/),r=Z.parseheader(n[0],e);if(r)throw"cnv header line error: "+r;for(let t=1;t<n.length;t++)Z.parseline(t,n[t],e)}if(t.itd){const n=(await P.b5(y().join(o().tpmasterdir,t.itd))).trim().split(/\r?\n/),r=U.parseheader(n[0],e);if(r)throw"itd header line error: "+r;for(let t=1;t<n.length;t++)U.parseline(t,n[t],e)}if(t.deletion){const n=(await P.b5(y().join(o().tpmasterdir,t.deletion))).trim().split(/\r?\n/),r=z.parseheader(n[0],e);if(r)throw"deletion header line error: "+r;for(let t=1;t<n.length;t++)z.parseline(t,n[t],e)}if(t.truncation){const n=(await P.b5(y().join(o().tpmasterdir,t.truncation))).trim().split(/\r?\n/),r=J.parseheader(n[0],e);if(r)throw"Truncation header line error: "+r;for(let t=1;t<n.length;t++)J.parseline(t,n[t],e)}}if(r.annotations){const t=r.annotations.idkey?r.annotations.idkey:"sample";r.annotations.data={};for(const e of r.annotations.files){const n=await P.b5(y().join(o().tpmasterdir,e));W.tJ(n).forEach((e=>{const n=e[t].trim();r.annotations.data[n]||(r.annotations.data[n]=[]),r.annotations.data[n].push(e)}))}}for(const t in i)H(i[t]);delete r.mutationset,e.send({cohort:r,flagset:i})}catch(t){return void e.send({error:t.message||t})}})),yo.post(vo+"/textfile",(function(t,e){if(!t.query.file)return e.send({error:"no file"});if(P.lY(t.query.file))return e.send({error:"invalid file name"});const n=y().join(o().tpmasterdir,t.query.file);if(null!=t.query.from){if(!Number.isInteger(t.query.from))return void e.send({error:"invalid value for from"});if(!Number.isInteger(t.query.to))return void e.send({error:"invalid value for to"});const r=[];_()(m().createReadStream(n)).on("end",(()=>{e.send({text:r.join("\n")})})).lines.map(String).skip(t.query.from-1).take(t.query.to).forEach((t=>{r.push(t)}))}else m().readFile(n,{encoding:"utf8"},((t,n)=>{t?e.send({error:"error reading file"}):e.send({text:n})}))})),yo.post(vo+"/urltextfile",(async function(t,e){const n=t.query.url.replace(o().URL,`http://127.0.0.1:${o().port}`);try{const t=await b()(n);switch(t.statusCode){case 200:return void e.send({text:P.cl(t.body)});case 404:return void e.send({error:"File not found: "+n});default:e.send({error:"unknown status code: "+t.status})}}catch(t){return e.send({error:"Error downloading file: "+n})}})),yo.get(vo+"/junction",(async function(t,e){try{const[n,r,i]=P.ZX(t);if(n)throw n;if(!t.query.rglst)throw"rglst[] missing";if("string"==typeof t.query.rglst&&(t.query.rglst=JSON.parse(t.query.rglst)),!Array.isArray(t.query.rglst))throw"rglst[] not an array";if(t.query.rglst.reduce(((t,e)=>e.stop-e.start+t),0)>1e6)throw"Zoom in below 1 Mb to show junctions";let s;if(t.query.isrnapeg){if(!o().features.junctionrnapeg)throw"rnapeg not supported on this server";if(i)throw"rnapeg file from url is not supported";s=await async function(t,e){try{await m().promises.stat(e)}catch(t){if("EACCES"==t.code)throw"permission denied for rnapeg file";if("ENOENT"==t.code)throw"rnapeg file not found";throw"cannot access rnapeg file ("+t.code+")"}const n=[];for(const r of t.rglst){const t=await cn({file:e,chr:r.chr,start:r.start,stop:r.stop});for(const e of t)n.push(e)}return n}(t.query,r)}else{const e=i?await P.d1(r,t.query.indexURL):null;s=await async function(t,e,n){const r=[];for(const o of t.rglst)await P.UE({args:[e,o.chr+":"+o.start+"-"+o.stop],dir:n,callback:t=>{const e=t.split("\t"),n=Number.parseInt(e[1]),i=Number.parseInt(e[2]);if(n>=o.start&&n<=o.stop||i>=o.start&&i<=o.stop){const t={chr:o.chr,start:n,stop:i,type:e[4],rawdata:[]};for(let n=5;n<e.length;n++)t.rawdata.push(Number.parseInt(e[n]));r.push(t)}}});return r}(t.query,r,e)}e.send({lst:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdsjunction",function(t){return async(e,n)=>{try{const[r,i,s]=await async function(t,e){const n=t.query;if(!n.genome)throw"genome missing";const r=e[n.genome];if(!r)throw"invalid genome";let i={},s={};if(n.iscustom)if(s.listsamples=!0,n.url)s.url=n.url,s.dir=await P.d1(n.url,n.indexURL);else if(n.file)s.file=y().join(o().tpmasterdir,n.file);else{if(!n.file2)throw"no file or url given";s.file2=y().join(o().tpmasterdir,n.file2)}else{if(!r.datasets)throw"genome is not equipped with datasets";if(!n.dslabel)throw"dslabel missing";if(i=r.datasets[n.dslabel],!i)throw"invalid dslabel";if(!i.queries)throw"dataset is not equipped with queries";if(!n.querykey)throw"querykey missing";if(s=i.queries[n.querykey],!s)throw"invalid querykey"}return[n,i,s]}(e,t),a=await async function(t,e,n){if(t.junction)return await async function(t,e,n){const r=t.junction;if(!r.chr||!Number.isInteger(r.start)||!Number.isInteger(r.stop))throw"incomplete/invalid info about querying junction";let o;if(await P.UE({args:[on(n),r.chr+":"+r.start+"-"+r.stop],dir:n.dir,callback:i=>{const s=i.split("\t"),a=Number.parseInt(s[1]),l=Number.parseInt(s[2]);if(a==r.start&&l==r.stop)if(n.file2){o=[];for(let t=5;t<s.length;t++){const e=s[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||o.push({i:t-5,readcount:n}))}}else{const r=JSON.parse(s[5]);o=sn(r,t,e,n)}}}),0==o.length)throw"no sample passing filters";const i={};if(n.listsamples){const t=o.map((t=>{const e={readcount:t.readcount};return t.anno?e.sample_name=t.anno.sample_name:e.i=t.i,e}));t.sort(((t,e)=>e.readcount-t.readcount)),t.length>100?(i.samples=t.slice(0,100),i.sampletotalnumber=t.length):i.samples=t}else if(n.singlejunctionsummary&&n.singlejunctionsummary.readcountboxplotpercohort){i.readcountboxplotpercohort=[];for(const t of n.singlejunctionsummary.readcountboxplotpercohort.groups){const e=new Map;for(const n of o){if(!n.anno)continue;const r=n.anno[t.key];null!=r&&(e.has(r)||e.set(r,[]),e.get(r).push(n))}if(0==e.size)continue;const n=[...e].sort(((t,e)=>e[1].length-t[1].length)),r=[];for(const[t,e]of n){let n=e[0].readcount,o=n;e.forEach((t=>{n=Math.min(n,t.readcount),o=Math.max(o,t.readcount)}));const i=an(e,.05,.25,.5,.75,.95);r.push({label:t,samplecount:e.length,percentile:{p05:i[0],p25:i[1],p50:i[2],p75:i[3],p95:i[4]},minvalue:n,maxvalue:o})}i.readcountboxplotpercohort.push({label:t.label,boxplots:r})}}return i}(t,e,n);if(t.readcountByjBsamples)return await async function(t,e,n){if(!t.junctionAposlst)throw".junctionAposlst[] missing";let r,o=t.junctionB.start,i=t.junctionB.stop;t.junctionAposlst.forEach((t=>{o=Math.min(o,t[0]),i=Math.max(i,t[1])}));let s=[];if(await P.UE({args:[n.file||n.url,t.junctionB.chr+":"+o+"-"+i],dir:n.dir,callback:e=>{const n=e.split("\t"),o=Number.parseInt(n[1]),i=Number.parseInt(n[2]);if(o==t.junctionB.start&&i==t.junctionB.stop)r=JSON.parse(n[5]);else for(const[e,r]of t.junctionAposlst)if(e==o&&r==i){const t=JSON.parse(n[5]);t.start=o,t.stop=i,s.push(t);break}}}),!r)throw"jB not found";if(0==s.length)throw"none of jA is found";const a=sn(r,t,e,n);if(0==a.length)throw"no sample passing filters for junctionB";const l=new Set;a.forEach((t=>l.add(t.i)));const c=[];for(const e of s){const n=[];for(const r of e.samples)l.has(r.i)&&(t.readcountCutoff&&r.readcount<t.readcountCutoff||n.push(r));c.push({start:e.start,stop:e.stop,v:Math.floor(an(n,.5))})}return{lst:c}}(t,e,n);const r={};if(t.iscustom&&t.getsamples){const t=await P.ZD(on(n),n.dir);if(t[0]){const e=t[0].split("\t");e.length>5&&(r.sample2client=e.slice(5))}}if(!t.rglst)throw"rglst missing";if(n.viewrangeupperlimit){if(t.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=n.viewrangeupperlimit)throw"zoom in under "+common.bplen(n.viewrangeupperlimit)+" to view details"}let o=0,i=0;const s=[],a=new Set,l=new Set;for(const r of t.rglst)await P.UE({args:[on(n),r.chr+":"+r.start+"-"+r.stop],dir:n.dir,callback:c=>{const u=c.split("\t"),f=Number.parseInt(u[1]),d=Number.parseInt(u[2]);if(n.file2){u[3];const e=u[4];let n;if("known"==e)n="canonical";else{if("novel"!=e)throw"unknown rnapeg type: "+e;n=rn}if(t.infoFilter&&t.infoFilter.type&&t.infoFilter.type[n])return;const a={chr:r.chr,start:f,stop:d,info:{type:{lst:[{attrValue:n}]}}},l=[];for(let t=5;t<u.length;t++){const e=u[t];if(!e)continue;const n=Number.parseInt(e);Number.isNaN(n)||(n<=0||(l.push({readcount:n}),o=Math.max(o,n)))}if(0==l.length)return;if(i++,a.sampleCount=l.length,1==a.sampleCount)a.medianReadCount=l[0].readcount;else{const t=an(l,.05,.25,.5,.75,.95);a.medianReadCount=t[2],a.readcountBoxplot={percentile:t}}s.push(a)}else{u[3],u[4];if(!(f>=r.start&&f<=r.stop||d>=r.start&&d<=r.stop))return;i++;const c={chr:r.chr,start:f,stop:d,info:{type:{lst:[]}}},h=JSON.parse(u[5]);if(h.sv){c.sv=h.sv;const t=c.chr+"."+c.start+"."+c.sv.mate.chr+"."+c.sv.mate.start;if(a.has(t))return;a.add(t),a.add(c.sv.mate.chr+"."+c.sv.mate.start+"."+c.chr+"."+c.start)}if(h.canonical&&c.info.type.lst.push({attrValue:"canonical"}),h.events)for(const t in h.events){const e=h.events[t];e.__ek=t,c.info.type.lst.push(e)}else h.canonical||c.info.type.lst.push({attrValue:rn});if(t.infoFilter&&t.infoFilter.type)for(const e of c.info.type.lst)if(t.infoFilter.type[e.attrValue])return;const p=sn(h,t,e,n);if(0==p.length)return;if((h.exonleft||h.exonright||h.exonleftin||h.exonrightin||h.intronleft||h.intronright||h.leftout||h.rightout)&&(c.ongene={},h.exonleft&&(c.ongene.exonleft=h.exonleft),h.exonright&&(c.ongene.exonright=h.exonright),h.exonleftin&&(c.ongene.exonleftin=h.exonleftin),h.exonrightin&&(c.ongene.exonrightin=h.exonrightin),h.intronleft&&(c.ongene.intronleft=h.intronleft),h.intronright&&(c.ongene.intronright=h.intronright),h.leftout&&(c.ongene.leftout=h.leftout),h.rightout&&(c.ongene.rightout=h.rightout)),p.forEach((t=>{l.add(t.i),o=Math.max(o,t.readcount)})),c.sampleCount=p.length,1==c.sampleCount)c.medianReadCount=p[0].readcount;else{const t=an(p,.05,.25,.5,.75,.95);c.medianReadCount=t[2],c.readcountBoxplot={percentile:t}}s.push(c)}}});r.lst=s,r.maxreadcount=o,r.junctiontotalnumber=i,l.size;return r}(r,i,s);n.send(a)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.post(vo+"/mdscnv",(function(t,e){const[n,r,i,s]=To(t.query);if(n)return e.send({error:n});if(!t.query.rglst)return e.send({error:"rglst missing"});if(!t.query.gain)return e.send({error:".gain missing"});if(!t.query.loss)return e.send({error:".loss missing"});if(s.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=s.viewrangeupperlimit)return e.send({error:"zoom in under "+F.bplen(s.viewrangeupperlimit)+" to view details"})}if(t.query.permanentHierarchy){const n=function(t,e){if(!e.cohort)return".cohort missing from ds";if(!e.cohort.hierarchies)return".hierarchies missing from ds.cohort";if(!e.cohort.hierarchies.lst)return".hierarchies.lst[] missing from ds.cohort";const n=e.cohort.hierarchies.lst.find((e=>e.name==t.permanentHierarchy.hierarchyname));if(!n)return"unknown hierarchy "+t.permanentHierarchy.hierarchyname;if(!n.levels)return".levels[] missing in hierarchy "+n.name;const r=n.levels[t.permanentHierarchy.levelidx];if(!r)return"level not found by array idx "+t.permanentHierarchy.levelidx;const o=r.k;return delete t.cohortHiddenAttr,t.cohortOnlyAttr={},t.cohortOnlyAttr[o]={},t.cohortOnlyAttr[o][t.permanentHierarchy.valuekey]=1,null}(t.query,i);if(n)return e.send({error:"permanentHierarchy error: "+n})}const a=[],l={count:0,samples:new Set},c={count:0,samples:new Set};for(const e of t.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(ho,[s.file?y().join(o().tpmasterdir,s.file):s.url,e.chr+":"+e.start+"-"+e.stop],{cwd:s.usedir}),u=O().createInterface({input:a.stdout}),f=(e.stop-e.start)/e.width,d=[];for(let t=0;t<e.width;t++)d.push({positive:0,negative:0});u.on("line",(n=>{const r=n.split("\t"),o=Number.parseInt(r[1]),s=Number.parseInt(r[2]);if(t.query.bplengthUpperLimit&&s-o>t.query.bplengthUpperLimit)return;const a=JSON.parse(r[3]);if(t.query.valueCutoff&&Math.abs(a.value)<t.query.valueCutoff)return;if(a.sample&&i.cohort&&i.cohort.annotation){const e=i.cohort.annotation[a.sample];if(!e)return;if(t.query.cohortOnlyAttr&&i.cohort&&i.cohort.annotation){let n=!1;for(const r in t.query.cohortOnlyAttr){const o=e[r];if(o&&t.query.cohortOnlyAttr[r][o]){n=!0;break}}if(!n)return}if(t.query.cohortHiddenAttr&&i.cohort.attributes){let n=!1;for(const r in t.query.cohortHiddenAttr){i.cohort.attributes.lst.find((t=>t.key==r)).isNumeric;const o=e[r];if(o){if(t.query.cohortHiddenAttr[r][o]){n=!0;break}}else if(t.query.cohortHiddenAttr[r][go]){n=!0;break}}if(n)return}}a.value>0?(l.count++,l.samples.add(a.sample)):a.value<0&&(c.count++,c.samples.add(a.sample));const u=Math.max(e.start,o),h=Math.min(e.stop,s);let p,m;e.reverse?(p=Math.floor((e.stop-h)/f),m=Math.floor((e.stop-u)/f)):(p=Math.floor((u-e.start)/f),m=Math.floor((h-e.start)/f));for(let t=p;t<m;t++)a.value>0?d[t].positive++:a.value<0&&d[t].negative++}));const h=[];a.stderr.on("data",(t=>h.push(t))),a.on("close",(t=>{const e=h.join("");!e||co(e)?n(d):r(e)}))}));a.push(n)}Promise.all(a).then((n=>{const r=t.query.rglst.reduce(((e,n)=>e+n.width+t.query.regionspace),0)-t.query.regionspace,o=(0,S.createCanvas)(r,t.query.gain.barheight+t.query.loss.barheight),a=o.getContext("2d"),u={gain:{count:l.count,samplenumber:l.samples.size},loss:{count:c.count,samplenumber:c.samples.size},maxvalue:0};if(l.count+c.count==0)return a.font="15px Arial",a.fillStyle="#aaa",a.textAlign="center",a.textBaseline="middle",a.fillText("No data in view range",r/2,t.query.gain.barheight),u.src=o.toDataURL(),void e.send(u);for(const t of n)for(const e of t)u.maxvalue=Math.max(u.maxvalue,e.positive,e.negative);const f=t.query.maxvalue||u.maxvalue;let d=0;for(const e of n){for(const n of e){if(n.positive){a.fillStyle=t.query.gain.color||"#67a9cf";const e=Math.ceil(t.query.gain.barheight*Math.min(f,n.positive)/f),r=t.query.gain.barheight-e;a.fillRect(d,r,1,e)}if(n.negative){a.fillStyle=t.query.loss.color||"#ef8a62";const e=Math.ceil(t.query.loss.barheight*Math.min(f,n.negative)/f),r=t.query.gain.barheight;a.fillRect(d,r,1,e)}d++}d+=t.query.regionspace}if(u.src=o.toDataURL(),l.samples.size||c.samples.size){const t=new Set([...l.samples,...c.samples]),[e,n]=function(t,e,n){if(!t.cohort||!t.cohort.annotation||0==n.length)return[null,null];const r=[];for(const e of n){const n=t.cohort.annotation[e];n&&r.push(n)}if(0==r.length)return[null,null];let o,i;if(t.cohort.attributes){o=[];for(const n of t.cohort.attributes.lst){const i={label:n.label,key:n.key};if(n.isNumeric){i.isNumeric=!0;continue}const s=new Map;let a=0;for(const e of r){const r=e[n.key];null!=r?(s.has(r)||s.set(r,new Set),s.get(r).add(e[t.cohort.samplenamekey])):a++}const l=[...s];a&&l.push([go,a]),l.sort(((t,e)=>e[1]-t[1])),i.values=[];for(const[t,r]of l){const o={name:t,sampleset:r};if(n.values&&n.values[t])for(const e in n.values[t])o[e]=n.values[t][e];e.attributeSummary&&e.attributeSummary[n.key]&&e.attributeSummary[n.key][t]&&(o.totalCount=e.attributeSummary[n.key][t]),i.values.push(o)}o.push(i)}}if(t.cohort.hierarchies){i={};for(const n of t.cohort.hierarchies.lst){const o=(0,V.Z)()((0,A.N)(r,n.levels));o.sum((t=>t.value));const s=[];o.eachBefore((r=>{const o={id:r.data.id,name:r.data.name,label:r.data.full,depth:r.depth};if(r.data.lst){o.sampleset=new Set;for(const e of r.data.lst)o.sampleset.add(e[t.cohort.samplenamekey])}r.children||(o.isleaf=1),e.hierarchySummary&&e.hierarchySummary[n.name]&&(o.totalCount=e.hierarchySummary[n.name][r.id]),s.push(o)})),i[n.name]=s}}return[o,i]}(i,s,[...t]);if(e){for(const t of e)for(const e of t.values){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++;delete e.sampleset}u.attributeSummary=e}if(n){for(const t in n)for(const e of n[t])if(e.sampleset){e.gain=0,e.loss=0;for(const t of e.sampleset)l.samples.has(t)&&e.gain++,c.samples.has(t)&&e.loss++}u.hierarchySummary=n}}e.send(u)})).catch((t=>{e.send({error:t}),t.stack&&console.error(t.stack)}))})),yo.post(vo+"/mdssvcnv",(async function(t,e){let n,r,i,s,a,l,c,u,f;if(t.query.iscustom){if(n=fo[t.query.genome],!n)return e.send({error:"invalid genome"});if(r={},i={iscustom:1,file:t.query.file,url:t.query.url,indexURL:t.query.indexURL,allow_getallsamples:!0},t.query.checkexpressionrank){if(!t.query.checkexpressionrank.file&&!t.query.checkexpressionrank.url)return e.send({error:"no file or url for checkexpressionrank"});i.checkexpressionrank={file:t.query.checkexpressionrank.file,url:t.query.checkexpressionrank.url,indexURL:t.query.checkexpressionrank.indexURL}}if(t.query.checkvcf){let n;try{n=JSON.parse(t.query.checkvcf)}catch(t){return e.send({error:"invalid JSON for VCF object"})}if(!n.file&&!n.url)return e.send({error:"no file or url for custom VCF track"});n.type=F.mdsvcftype.vcf,i.checkvcf={info:n.info,tracks:[n]}}if(t.query.checkrnabam){if(!t.query.checkrnabam.samples)return e.send({error:"samples{} missing from checkrnabam"});let n=0;for(const e in t.query.checkrnabam.samples)n++;if(n>13)return e.send({error:"no more than 13 BAM files allowed"});const r=Fo(t.query.checkrnabam);if(r)return e.send({error:r});i.checkrnabam=t.query.checkrnabam}}else{if(n=fo[t.query.genome],!n)return e.send({error:"invalid genome"});if(!n.datasets)return e.send({error:"genome is not equipped with datasets"});if(r=n.datasets[t.query.dslabel],!r)return e.send({error:"invalid dslabel"});if(t.query.getsample4disco)return function(t,e,n,r){if(t.query.iscustom)return e.send({error:"not for custom track"});if(!r.singlesamplemutationjson)return e.send({error:"singlesamplemutationjson not available for this dataset"});const i=t.query.getsample4disco,s=r.singlesamplemutationjson.samples[i];if(!s)return e.send({error:"no data"});const a=y().join(o().tpmasterdir,s);m().readFile(a,{encoding:"utf8"},((t,n)=>{if(t)return e.send({error:"error getting data for this sample"});e.send({text:n})}))}(t,e,0,r);if(t.query.gettrack4singlesample)return function(t,e,n){const r=t.query.gettrack4singlesample;if(t.query.iscustom)return e.send({error:"no server-side config available for custom track"});if(!n.sampleAssayTrack)return e.send({});return e.send({tracks:n.sampleAssayTrack.samples.get(r)})}(t,e,r);if(t.query.findsamplename)return function(t,e,n){if(t.query.iscustom)return e.send({error:"cannot search sample by name in custom track"});const r=t.query.findsamplename.toLowerCase(),o=[];if(!n.cohort.__samplelst){n.cohort.__samplelst=[];for(const t in n.cohort.annotation)n.cohort.__samplelst.push({name:t,low:t.toLowerCase()})}i(n.cohort.__samplelst);for(const t in n.queries){const e=n.queries[t];if(e.type==F.tkt.mdssvcnv&&e.groupsamplebyattr)for(const t of o){const r=n.cohort.annotation[t.name];if(!r)continue;const o=[];for(const t of e.groupsamplebyattr.attrlst){const e=r[t.k];e&&o.push({k:t.k,kvalue:e})}o.length&&(t.attributes=o,t.grouplabel=o.map((t=>t.kvalue)).join(e.groupsamplebyattr.attrnamespacer))}}if(n.cohort&&n.cohort.sampleAttribute&&n.cohort.sampleAttribute.attributes&&n.cohort.annotation)for(const t of o){const e=n.cohort.annotation[t.name];if(!e)continue;const r=[];for(const t in n.cohort.sampleAttribute.attributes){if(n.cohort.sampleAttribute.attributes[t].clientnoshow)continue;const o=e[t];null!=o&&r.push({k:t,v:o})}r.length&&(t.attr=r)}if(n.sampleAssayTrack)for(const t of o){const e=n.sampleAssayTrack.samples.get(t.name);e&&(t.num_assay_tracks=e.length)}if(n.cohort&&n.cohort.mutation_signature)for(const t in n.cohort.mutation_signature.sets){const e=n.cohort.mutation_signature.sets[t];if(e.samples)for(const t of o)e.samples.map.has(t.name)&&(t.mutation_signature=1)}if(n.singlesamplemutationjson)for(const t of o)n.singlesamplemutationjson.samples[t.name]&&(t.disco=1);return e.send({result:o});function i(t){for(const e of t){if(o.length>10)return;-1!=e.low.indexOf(r)&&(o.find((t=>t.name==e.name))||o.push(e))}}}(t,e,r);if(t.query.assaymap)return async function(t,e,n){try{if(!n.assayAvailability)throw"assay availability not enabled for this dataset";const r=new Set(t.query.skip_termids||[]),o=new Map;for(const e in n.cohort.annotation){if(t.query.key){if(n.cohort.annotation[e][t.query.key]!=t.query.value)continue}o.set(e,new Map)}for(const[t,e]of o){const o=n.assayAvailability.samples.get(t);if(o)for(const t of n.assayAvailability.assays)r.has(t.id)||o[t.id]&&e.set(t.id,"yes")}for(const t of o.keys())0==o.get(t).size&&o.delete(t);const i={};i.totalsample=o.size,i.terms=Hr({sample2term:o,terms:n.assayAvailability.assays,config:{termidorder:t.query.termidorder}}),e.send(i)}catch(t){e.send({error:t.message||t})}}(t,e,r);if(!r.queries)return e.send({error:"dataset is not equipped with queries"});if(i=r.queries[t.query.querykey],!i)return e.send({error:"invalid querykey"})}if(t.query.getexpression4gene)return async function(t,e,n,r,i){try{const n=t.query.getexpression4gene;if(!n.chr)throw"chr missing";if(!Number.isFinite(n.start))throw"invalid start pos";if(!Number.isFinite(n.stop))throw"invalid stop pos";if(!n.name)throw"unknown gene name";if(i.checkrnabam){const r=fo[t.query.genome],o=r.tracks.find((t=>t.__isgene)),s=(await Zo(r,o,n.chr,n.start,n.stop)).get(n.name);if(!s)throw"no gene matching with "+n.name;const a={};await Co(new Map([[n.name,s]]),n.chr,n.start,n.stop,i,a);const l={};for(const t of a.checkrnabam)if(t.genes){const e=t.genes.find((t=>t.gene==n.name));e&&(l[t.sample]=e)}return void e.send({sample2rnabam:l})}let s;if(i.iscustom?s=i.checkexpressionrank:i.expressionrank_querykey&&(s=r.queries[i.expressionrank_querykey]),!s)throw"missing expression data source";const a=s.file?null:await P.d1(s.url,s.indexURL),l=[];await P.UE({args:[s.file?y().join(o().tpmasterdir,s.file):s.url,n.chr+":"+n.start+"-"+n.stop],dir:a,callback:t=>{const e=t.split("\t");let r;try{r=JSON.parse(e[3])}catch(t){reject("invalid json from expression data")}r.sample&&r.gene&&Number.isFinite(r.value)&&(delete r.outlier,r.gene.toLowerCase()==n.name.toLowerCase()&&l.push(r))}});const c=function(t,e,n){const r={};if(t&&t.cohort&&t.cohort.annotation&&e.groupsamplebyattr&&e.groupsamplebyattr.attrlst){const o=new Map;for(const r of n){const n=t.cohort.annotation[r.sample];if(!n)continue;const i=[];for(const t of e.groupsamplebyattr.attrlst)i.push(n[t.k]);const s=i.join(",");o.has(s)||o.set(s,[]),o.get(s).push(r)}for(const t of o.values()){t.sort(((t,e)=>t.value-e.value));for(const e of t)e.rank=Bo(e.value,t),r[e.sample]=e}}else{n.sort(((t,e)=>t.value-e.value));for(const t of n)t.rank=Bo(t.value,n),r[t.sample]=t}return r}(r,i,l);e.send({sample2rank:c})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}}(t,e,0,r,i);if(t.query.ifsamplehasvcf)return function(t,e,n,r,o){if(t.query.iscustom)return e.send({no:1});if(!o.vcf_querykey)return e.send({yes:1});const i=r.queries[o.vcf_querykey];if(!i)return e.send({error:"vcf query missing"});e.send(i.singlesamples?{yes:1}:{no:1})}(t,e,0,r,i);if(!t.query.rglst)return e.send({error:"rglst missing"});if(i.viewrangeupperlimit){if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=i.viewrangeupperlimit)return e.send({error:"zoom in under "+F.bplen(i.viewrangeupperlimit)+" to view details"})}t.query.hiddendt&&(s=new Set(t.query.hiddendt));if(t.query.hiddenmattr){a={};for(const e in t.query.hiddenmattr)a[e]=new Set(t.query.hiddenmattr[e])}if(t.query.filteralleleattr){l={};for(const e in t.query.filteralleleattr){const n=t.query.filteralleleattr[e];n.cutoffvalue,l[e]=n}}if(t.query.filterlocusattr){c={};for(const e in t.query.filterlocusattr){const n=t.query.filterlocusattr[e];n.cutoffvalue,c[e]=n}}if(t.query.sampleset){const e=new Set,n=new Map;for(const r of t.query.sampleset)for(const t of r.samples)e.add(t),n.set(t,r.name);e.size&&(u={set:e,sample2group:n})}if(t.query.hiddensampleattr){f={};for(const e in t.query.hiddensampleattr)f[e]=new Set(t.query.hiddensampleattr[e])}if(i.url)try{i.dir=await P.d1(i.url,i.indexURL)}catch(t){return e.send({error:"svcnv file index url error"})}const d=await function(t,e,n,r,i,s,a){if(!e.file&&!e.url)return[];const l=[];for(const c of n.query.rglst){const u=new Promise(((l,u)=>{const f=[],d=(0,q.spawn)(ho,[e.file?y().join(o().tpmasterdir,e.file):e.url,c.chr+":"+c.start+"-"+c.stop],{cwd:e.dir});O().createInterface({input:d.stdout}).on("line",(e=>{const o=e.split("\t"),l=Number.parseInt(o[1]),c=Number.parseInt(o[2]);let u;try{u=JSON.parse(o[3])}catch(t){return}if(!(null==u.dt||r&&r.has(u.dt))){if(u.dt==F.dtloh){if(u.segmean&&n.query.segmeanValueCutoff&&u.segmean<n.query.segmeanValueCutoff)return;if(n.query.lohLengthUpperLimit&&c-l>n.query.lohLengthUpperLimit)return;u.chr=o[0],u.start=l,u.stop=c}else if(u.dt==F.dtfusionrna||u.dt==F.dtsv)u._chr=o[0],u._pos=l,u.chrA?(u.chrB=o[0],u.posB=l):(u.chrA=o[0],u.posA=l);else if(u.dt==F.dtcnv){if(n.query.hide_cnvloss&&u.value<0)return;if(n.query.hide_cnvgain&&u.value>0)return;if(n.query.valueCutoff&&Math.abs(u.value)<n.query.valueCutoff)return;if(n.query.bplengthUpperLimit&&c-l>n.query.bplengthUpperLimit)return;u.chr=o[0],u.start=l,u.stop=c}else{if(u.dt!=F.dtitd)return void console.error("unknown dt from svcnv file: "+u.dt);u.chr=o[0],u.start=l,u.stop=c}if(n.query.singlesample){if(u.sample!=n.query.singlesample)return}else if(a){if(!a.set.has(u.sample))return}else if(u.sample&&t.cohort&&t.cohort.annotation){const e=t.cohort.annotation[u.sample];if(!e)return;if(i)for(const t in i){const n=e[t];if(i[t].has(n))return}}if(s)for(const t in s){let e=u.mattr?u.mattr[t]:void 0;if(null==e&&(e=F.not_annotated),s[t].has(e))return}f.push(u)}}));const h=[];d.stderr.on("data",(t=>h.push(t))),d.on("close",(t=>{const e=h.join("");!e||co(e)?l(f):u(e)}))}));l.push(u)}return Promise.all(l)}(r,i,t,s,f,a,u),[h,p]=await function(t,e,n,r){if(n.query.singlesample)return[];let i;if(e.iscustom?i=e.checkexpressionrank:e.expressionrank_querykey&&t.queries[e.expressionrank_querykey]&&(i=t.queries[e.expressionrank_querykey]),!i)return[];let s=i.viewrangeupperlimit;if(!s&&e.iscustom&&(s=5e6),s&&n.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=s)return[s];return Promise.resolve().then((()=>i.file?"":(0,P.d1)(i.url,i.indexURL))).then((t=>{const e=new Map,r=[];for(const s of n.query.rglst){const n=new Promise(((n,r)=>{const a=(0,q.spawn)(o().tabix,[i.file?y().join(o().tpmasterdir,i.file):i.url,s.chr+":"+s.start+"-"+s.stop],{cwd:t});O().createInterface({input:a.stdout}).on("line",(t=>{const n=t.split("\t");let r;try{r=JSON.parse(n[3])}catch(t){return}r.gene&&r.sample&&Number.isFinite(r.value)&&(e.has(r.gene)||e.set(r.gene,{chr:n[0],start:Number.parseInt(n[1]),stop:Number.parseInt(n[2]),samples:new Map}),e.get(r.gene).samples.set(r.sample,{value:r.value,ase:r.ase}))}));const l=[];a.stderr.on("data",(t=>l.push(t))),a.on("close",(t=>{const e=l.join("");!e||(0,P.sI)(e)?n():r(e)}))}));r.push(n)}return Promise.all(r).then((()=>[!1,e]))}))}(r,i,t),[g,v]=await async function(t,e,n,r,i,s,a,l,c,u){let f;n.iscustom?f=n.checkvcf:n.vcf_querykey&&e.queries[n.vcf_querykey]&&(f=e.queries[n.vcf_querykey]);if(!f)return[null,null];if(r.query.singlesample&&f.singlesamples){const n=f.singlesamples.samples[r.query.singlesample];if(n){const s={file:y().join(o().tpmasterdir,n)};try{await m().promises.stat(s.file)}catch(t){return[null,null]}const a=await Uo(s.file),[u,f,d,h]=D.e(a);if(h)throw h;return s.info=u,s.format=f,s.samples=d,s.nochr=await P.Jy(s.file,null,t),function(t,e,n,r,o,i,s){const a=[],l=[];for(const o of t.query.rglst){const c=new Promise(((l,c)=>{const u=(0,q.spawn)(ho,[n.file,(n.nochr?o.chr.replace("chr",""):o.chr)+":"+o.start+"-"+o.stop]);O().createInterface({input:u.stdout}).on("line",(o=>{const[l,c,u]=D.S(o,n);for(const n of c){if(!n.sampledata)continue;const o=n.sampledata.find((e=>e.sampleobj.name==t.query.singlesample));if(o){if(delete o.allele2readcount,n.sampledata=[o],r){let t=!1;for(const e in r){const o=n.altinfo[e];if(null==o){t=!0;break}const i=r[e];if(null!=i.cutoffvalue){if(!Number.isFinite(o)){t=!0;break}if(i.keeplowerthan){if(o>i.cutoffvalue){t=!0;break}}else if(o<i.cutoffvalue){t=!0;break}}}if(t)continue}if(!o.gtallref){if(o.__gtalleles){if(-1==o.__gtalleles.indexOf(n.alt))continue;delete o.__gtalleles}if(i){const t=[];for(const e of n.sampledata){let n=!0;for(const t in i){let r=e[t];if(null==r&&(r=F.not_annotated),i[t].has(r)){n=!1;break}}n&&t.push(e)}if(0==t.length)continue;n.sampledata=t}if(s&&e.cohort&&e.cohort.annotation){const t=[];for(const r of n.sampledata){const n=e.cohort.annotation[r.sampleobj.name];if(!n)continue;let o=!0;for(const t in s){const e=n[t];if(s[t].has(e)){o=!1;break}}o&&t.push(r)}if(0==t.length)continue;n.sampledata=t}delete n._m,delete n.vcf_ID,delete n.name,n.dt=F.dtsnvindel,a.push(n)}}}}));const f=[];u.stderr.on("data",(t=>f.push(t))),u.on("close",(t=>{const e=f.join("");!e||co(e)?l():c(e)}))}));l.push(c)}return Promise.all(l).then((()=>[null,a]))}(r,e,s,i,0,l,c)}}let d=f.viewrangeupperlimit;!d&&n.iscustom&&(d=uo.customMdsSingleSampleVcfNoRangeLimit?0:2e6);r.query.singlesample&&(d*=5);if(d){if(r.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>=d)return[d,null]}const h=[];for(const t of f.tracks){const n=Promise.resolve().then((()=>t.file?"":P.d1(t.url,t.indexURL))).then((n=>{t.dir=n;const a=[],d=[];for(const h of r.query.rglst){const p=new Promise(((d,p)=>{const m=(0,q.spawn)(ho,[t.file?y().join(o().tpmasterdir,t.file):t.url,(t.nochr?h.chr.replace("chr",""):h.chr)+":"+h.start+"-"+h.stop],{cwd:n});O().createInterface({input:m.stdout}).on("line",(n=>{if(t.type==F.mdsvcftype.vcf){const[o,d,h]=D.S(n,{nochr:t.nochr,samples:t.samples,info:f.info,format:t.format});for(const t of d)if(t.sampledata){if(i){let e=!1;for(const n in i){const r=t.altinfo[n];if(null==r){e=!0;break}const o=i[n];if(null!=o.cutoffvalue){if(!Number.isFinite(r)){e=!0;break}if(o.keeplowerthan){if(r>o.cutoffvalue){e=!0;break}}else if(r<o.cutoffvalue){e=!0;break}}else if(o.includes(r)){e=!0;break}}if(e)continue}if(s){let e=!1;for(const n in s){const r=t.info[n];if(null==r){e=!0;break}let o=r;if(Array.isArray(r)&&(o=r[0],"."==o)){e=!0;break}const i=s[n];if(null!=i.cutoffvalue){if(!Number.isFinite(o)){e=!0;break}if(i.keeplowerthan){if(o>i.cutoffvalue){e=!0;break}}else if(o<i.cutoffvalue){e=!0;break}}else if(i.includes(o)){e=!0;break}}if(e)continue}{const e=[];for(const n of t.sampledata)if(!n.gtallref){if(n.__gtalleles){if(-1==n.__gtalleles.indexOf(t.alt))continue;delete n.__gtalleles}e.push(n)}if(0==e.length)continue;t.sampledata=e}if(r.query.singlesample){let e=null;for(const n of t.sampledata)if(n.sampleobj.name==r.query.singlesample){e=n;break}if(!e)continue;t.sampledata=[e]}else if(u){const e=t.sampledata.filter((t=>u.set.has(t.sampleobj.name)));if(!e.length)continue;t.sampledata=e}if(l){const e=[];for(const n of t.sampledata){let t=!0;for(const e in l){let r=n[e];if(null==r&&(r=F.not_annotated),l[e].has(r)){t=!1;break}}t&&e.push(n)}if(0==e.length)continue;t.sampledata=e}if(c&&e.cohort&&e.cohort.annotation){const n=[];for(const r of t.sampledata){const t=e.cohort.annotation[r.sampleobj.name];if(!t)continue;let o=!0;for(const e in c){const n=t[e];if(c[e].has(n)){o=!1;break}}o&&n.push(r)}if(0==n.length)continue;t.sampledata=n}for(const e of t.sampledata)delete e.allele2readcount;delete t._m,delete t.vcf_ID,delete t.name,t.dt=F.dtsnvindel,a.push(t)}}else console.error('unknown "type" from a vcf file')}));const g=[];m.stderr.on("data",(t=>g.push(t))),m.on("close",(t=>{const e=g.join("");!e||co(e)?d():p(e)}))}));d.push(p)}return Promise.all(d).then((()=>a))}));h.push(n)}return Promise.all(h).then((t=>{const e=[];for(const n of t)for(const t of n)if(t.dt!=F.dtsnvindel)console.error("unknown dt: "+t.dt);else{if(!t.sampledata)continue;let n=!0;for(const r of e)if(t.chr==r.chr&&t.pos==r.pos&&t.ref==r.ref&&t.alt==r.alt){for(const e of t.sampledata)r.sampledata.push(e);n=!1;break}n&&e.push(t)}return e.sort(((t,e)=>t.pos-e.pos)),[null,e]}))}(n,r,i,t,l,c,0,a,f,u),b=function(t){const e=new Map;for(const n of t)for(const t of n){if(!t.sample)continue;const n=t.sample;e.has(n)||e.set(n,[]),t._chr?e.get(n).push(t):(delete t.sample,delete t.sampletype,e.get(n).push(t))}return e}(d);if(t.query.singlesample){const n={lst:b.get(t.query.singlesample)};return g?n.vcfrangelimit=g:n.data_vcf=v,void e.send(n)}const w={samplegroups:Io(r,i,d,v,b,u),vcfrangelimit:g,data_vcf:v};t.query.getallsamples&&i.allow_getallsamples&&(w.getallsamples=!0);i.checkrnabam?await async function(t,e,n,r){if(!n.checkvcf)return;if(t.stop-t.start>=5e5)return void(r.expressionrangelimit=5e5);const o=e.tracks.find((t=>t.__isgene)),i=await Zo(e,o,t.chr,t.start,t.stop);let s,a=null;for(const t of i.values())null==a?(a=t.start,s=t.stop):(a=Math.min(a,t.start),s=Math.max(s,t.stop));await Co(i,t.chr,a,s,n,r)}(t.query.rglst[0],n,i,w):function(t,e,n,r){if(n)return void(t.expressionrangelimit=n);if(r){t.gene2coord={};for(const[e,n]of r)t.gene2coord[e]={chr:n.chr,start:n.start,stop:n.stop};if(0==t.samplegroups.length)return;if(t.getallsamples){const e=new Set(t.samplegroups[0].samples.map((t=>t.samplename))),n=new Set;for(const[t,o]of r)for(const t of o.samples.keys())e.has(t)||n.add(t);for(const e of n)t.samplegroups[0].samples.push({samplename:e,items:[]})}for(const n of t.samplegroups){const t=new Map;for(const[o,i]of r){t.set(o,[]);for(const[r,s]of i.samples)if(n.attributes&&e.cohort&&e.cohort.annotation){const i=e.cohort.annotation[r];if(!i)continue;let a=!0;for(const t of n.attributes)if(i[t.k]!=t.kvalue){a=!1;break}a&&t.get(o).push(s)}else t.get(o).push(s)}for(const[e,n]of t)n.sort(((t,e)=>t.value-e.value));for(const e of n.samples){e.expressionrank={};for(const[n,o]of t){const t=r.get(n).samples.get(e.samplename);if(null==t)continue;const i=Bo(t.value,o);e.expressionrank[n]={rank:i};for(const r in t)e.expressionrank[n][r]=t[r]}}}}}(w,r,h,p);(function(t,e){if(t.cohort&&t.cohort.sampleAttribute&&t.cohort.sampleAttribute.attributes&&t.cohort.annotation){e.sampleannotation={};const n=[];for(const e in t.cohort.sampleAttribute.attributes){t.cohort.sampleAttribute.attributes[e].clientnoshow||n.push(e)}for(const r of e.samplegroups)for(const o of r.samples){const r=t.cohort.annotation[o.samplename];if(r){const t={};let i=!1;for(const e of n){const n=r[e];null!=n&&(i=!0,t[e]=n)}i&&(e.sampleannotation[o.samplename]=t)}}}})(r,w),e.send(w)})),yo.post(vo+"/mdsgenecount",(async function(t,e){wo(t);try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.datasets)throw"no datasets from genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.gene2mutcount)throw"not supported on this dataset";if(!t.query.samples)throw".samples missing";let o,i;o=t.query.selectedMutTypes?t.query.selectedMutTypes.join("+"):"total",i=t.query.nGenes?t.query.nGenes:15;const s=`WITH\n\tfiltered AS (\n\t\tSELECT gene, ${o} AS total FROM genecount\n\t\tWHERE sample IN (${JSON.stringify(t.query.samples).replace(/[[\]\"]/g,"").split(",").map((t=>"'"+t+"'")).join(",")})\n\t)\n\tSELECT gene, SUM(total) AS count\n\tFROM filtered\n\tGROUP BY gene\n\tORDER BY count DESC\n\tLIMIT ${i}`,a=r.gene2mutcount.db.prepare(s).all(),l=[];for(const t of a){const e=n.genedb.getCoordByGene.get(t.gene);e&&(e.gene=t.gene,e.count=t.count,delete e.name,l.push(e))}e.send({genes:l})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/mds2",function(t){return async(e,n)=>{const r=e.query;try{const e=t[r.genome],o=await async function(t,e){if(!e)throw"invalid genome";if(t.dslabel){const n=e.datasets[t.dslabel];if(!n)throw"invalid dslabel";if(!n.track)throw"no mds2 track found for dataset";return n}const n={iscustom:1,track:{}};t.vcf&&(n.track.vcf=t.vcf,await P._H(n.track.vcf,e));t.ld;return n}(r,e);if(r.trigger_overlayld)return await async function(t,e,n){if(!t.ldtkname)throw".ldtkname missing";const r=e.track.ld.tracks.find((e=>e.name==t.ldtkname));if(!r)throw"ld tk not found by name: "+t.ldtkname;const o=t.m.ref+"."+t.m.alt,i=(r.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),s=[];await P.UE({args:[r.file,i],dir:r.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),i=Number.parseInt(n[2]),a=n[3],l=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&a==o?s.push({pos:i,alleles:l,r2:c}):i==t.m.pos&&l==o&&s.push({pos:r,alleles:a,r2:c})}}),n.send({lst:s})}(r,o,n);r.hidden_mclass&&(r.hidden_mclass=new Set(r.hidden_mclass));const i={mclass2count:{}};if(r.info_fields){i.info_fields={};for(const t of r.info_fields)if(t.iscategorical)i.info_fields[t.key]={value2count:{}};else if(t.isnumerical)i.info_fields[t.key]={filteredcount:0};else{if(!t.isflag)throw"unknown info type";i.info_fields[t.key]={count_yes:0,count_no:0}}}if(r.trigger_mafcovplot&&await async function(t,e,n,r){try{if(!n.track)throw"ds.track missing";const e=n.track.vcf;if(!e)throw"ds.track.vcf missing";if(n.iscustom)e.plot_mafcov={show_samplename:1};else if(!e.plot_mafcov)throw"maf-cov plot is not supported on this track";if(!t.m)throw".m{} missing";if(!e.AD)throw"vcf.AD{} missing";const o=(e.AD.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),i=e.AD.chr2bcffile[t.m.chr];if(!i)throw"chr not in tk.AD.chr2bcffile";let s;if(await P.UE({isbcf:!0,args:["query","-r",o,"-f",Fr,i],dir:e.AD.dir,callback:n=>{const[r,o,i]=D.S(n,e.AD);for(const e of o)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(s=e)}}),!s)throw"variant not found";if(r.plotgroups=function(t,e,n){const r=[],o={name:"?",lst:[]};for(const r of t.sampledata){const i=r.AD[t.ref]||0,s=r.AD[t.alt]||0,a=i+s,l={mut:s,total:i+s,maf:0==a?0:s/a};e.plot_mafcov.show_samplename&&(l.sampleobj={name:n.cohort.termdb.q.id2sampleName(r.sampleobj.name)}),o.lst.push(l)}return r.push(o),r}(s,e,n),t.overlay_term){const e=await Bn.g5({ds:n,term1_id:t.overlay_term,term1_q:t.overlay_term_q}),o=new Map;for(const t of e.lst)o.set(t.sample,t.key1);const i=(0,Ir.Z)(Rr.Z),s=new Map;let a=0;for(const t of r.plotgroups)for(const e of t.lst){const t=o.get(e.sampleobj.name);if(t){const n=i(t);e.sampleobj.color=n,s.has(t)||s.set(t,{count:0,color:n,label:t}),s.get(t).count++}else a++,e.sampleobj.color=Pr}if(r.categories=[],e.CTE1&&e.CTE1.name2bin)for(const t of e.CTE1.name2bin.keys()){const e=s.get(t);e&&r.categories.push(e)}else for(const[t,e]of s)r.categories.push(e);a&&r.categories.push({count:a,color:Pr,label:"Unannotated"})}}catch(t){r.error=t.message||t,t.stack&&console.log(t.stack)}}(r,0,o,i),r.trigger_vcfbyrange&&(await Tr(r,0,o,i),r.trigger_ld)){i.__mposset=new Set;for(const t of i.vcf.rglst)if(t.variants)for(const e of t.variants)i.__mposset.add(e.pos)}if(r.trigger_ld){i.ld={};for(const t of r.trigger_ld.tracks)await Dr(t,r,0,o,i);delete i.__mposset}r.trigger_ssid_onevcfm&&await async function(t,e,n,r){if(n.iscustom)throw"custom ds not allowed";const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const i=(o.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),s=o.chr2bcffile[t.m.chr];if(!s)throw"chr not in chr2bcffile";let a;if(await P.UE({isbcf:!0,args:["query",s,"-r",i,"-f",Mr+"\t%FORMAT\n"],dir:o.dir,callback:e=>{const[n,r,i]=D.S(e,o);for(const e of r)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(a=e)}}),!a)throw"variant not found";const l=[],c=[],u=[];for(const e of a.sampledata){if(!e.genotype)continue;const n=-1!=e.genotype.indexOf(t.m.ref),r=-1!=e.genotype.indexOf(t.m.alt);n?r?c.push(e.sampleobj.name):l.push(e.sampleobj.name):r&&u.push(e.sampleobj.name)}const f=Math.random().toString();r.ssid=f,r.groups={};const d=[];if(l.length){const t="Homozygous reference";r.groups[t]={size:l.length},d.push(t+"\t"+l.join(","))}if(c.length){const t="Heterozygous";r.groups[t]={size:c.length},d.push(t+"\t"+c.join(","))}if(u.length){const t="Homozygous alternative";r.groups[t]={size:u.length},d.push(t+"\t"+u.join(","))}await P.Sf(y().join(Ar.cachedir_ssid,f),d.join("\n"))}(r,0,o,i),r.trigger_getvcfcsq&&await async function(t,e,n,r){const o=n.track.vcf;if(!o)throw"ds.track.vcf missing";if(!t.m)throw"q.m missing";const i=(o.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+(t.m.pos+1)+"-"+(t.m.pos+1),s=o.chr2bcffile[t.m.chr];if(!s)throw"chr not in chr2bcffile";await P.UE({isbcf:!0,args:["query",s,"-r",i,"-f",Mr+"\\n"],dir:o.dir,callback:e=>{const[n,i,s]=D.S(e,o);for(const e of i)if(e.pos==t.m.pos&&e.ref==t.m.ref&&e.alt==t.m.alt)return void(r.csq=e.csq)}})}(r,0,o,i),n.send(i)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/mdsexpressionrank",(function(t,e){let n,r,i,s=new Set;Promise.resolve().then((()=>{if(!t.query.rglst)throw"rglst missing";if(t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>1e7)throw"Zoom in below 10 Mb to show expression rank";if(!t.query.sample)throw"sample missing";if(t.query.iscustom){if(n=fo[t.query.genome],!n)throw"invalid genome";if(!t.query.file&&!t.query.url)throw"no file or url for expression data";r={},i={file:t.query.file,url:t.query.url,indexURL:t.query.indexURL}}else{const[e,o,s,a]=To(t.query);if(e)throw e;if(n=o,r=s,i=a,!i.samples)throw"total samples missing from server config";if(-1==i.samples.indexOf(t.query.sample))throw{nodata:1}}if(i.viewrangeupperlimit&&t.query.rglst.reduce(((t,e)=>t+e.stop-e.start),0)>i.viewrangeupperlimit)throw"zoom in under "+F.bplen(i.viewrangeupperlimit)+" to view data";if(t.query.levelkey){if(!t.query.levelvalue)throw"levelvalue is required when levelkey is used";if(!r.cohort||!r.cohort.annotation)throw".cohort.annotation missing from dataset"}if(!i.file){if(!i.url)throw"file or url missing";return P.d1(i.url,i.indexURL)}})).then((e=>{const n=[];for(const a of t.query.rglst)n.push(new Promise(((n,l)=>{const c=(0,q.spawn)(ho,[i.file?y().join(o().tpmasterdir,i.file):i.url,a.chr+":"+a.start+"-"+a.stop],{cwd:e}),u=O().createInterface({input:c.stdout}),f=new Map;u.on("line",(e=>{const n=e.split("\t"),o=JSON.parse(n[3]);if(!o.gene)return;if(!o.sample)return;if(!Number.isFinite(o.value))return;const i=n[0],a=Number.parseInt(n[1]),l=Number.parseInt(n[2]);if(o.sample==t.query.sample)return f.has(o.gene)||f.set(o.gene,{chr:i,start:a,stop:l,allvalues:[]}),f.get(o.gene).thisvalue=o.value,void(o.ase&&(f.get(o.gene).ase=o.ase));if(t.query.attributes){const e=r.cohort.annotation[o.sample];if(!e)return;for(const n of t.query.attributes)if(n.k&&n.kvalue&&n.kvalue!=e[n.k])return}s.add(o.sample),f.has(o.gene)||f.set(o.gene,{chr:i,start:a,stop:l,allvalues:[]}),f.get(o.gene).allvalues.push({value:o.value})}));const d=[];c.stderr.on("data",(t=>d.push(t))),c.on("close",(t=>{const e=d.join("");e&&!co(e)&&l({message:e}),n(f)}))})));return Promise.all(n)})).then((t=>{const n=[];for(const e of t)for(const[t,r]of e)null!=r.thisvalue&&(r.allvalues.sort(((t,e)=>t.value-e.value)),r.rank=Bo(r.thisvalue,r.allvalues),delete r.allvalues,r.gene=t,n.push(r));e.send({result:n,samplecount:s.size})})).catch((t=>{t.stack&&console.log(t),t.nodata?e.send({nodata:1}):e.send({error:t.message?t.message:t})}))})),yo.post(vo+"/mdsgeneboxplot",(t=>async(e,n)=>{try{const[r,i,s,a]=function(t,e){if(!e.query.gene)throw"gene name missing";if(!e.query.chr)throw"chr missing";if(!Number.isInteger(e.query.start))throw"start missing";if(!Number.isInteger(e.query.stop))throw"stop missing";const n=t[e.query.genome];if(!n)throw"invalid genome";let r,o,i;if(e.query.iscustom){if(!e.query.file&&!e.query.url)throw"no file or url for expression data";r={},o={file:e.query.file,url:e.query.url,indexURL:e.query.indexURL}}else{if(!n.datasets)throw"genome is not equipped with datasets";if(!e.query.dslabel)throw"dslabel missing";if(r=n.datasets[e.query.dslabel],!r)throw"invalid dslabel";if(!r.queries)throw"dataset is not equipped with queries";if(!e.query.querykey)throw"querykey missing";if(o=r.queries[e.query.querykey],!o)throw"invalid querykey"}if(e.query.svcnv)if(i={},e.query.iscustom)i.dsquery={file:e.query.svcnv.file,url:e.query.svcnv.url,indexURL:e.query.svcnv.indexURL};else{e.query.svcnv.genome=e.query.genome;const t=n.datasets[e.query.svcnv.dslabel];if(!t)throw"invalid dslabel";if(!t.queries)throw"dataset is not equipped with queries";if(!e.query.svcnv.querykey)throw"querykey missing";const r=t.queries[e.query.svcnv.querykey];if(!r)throw"invalid querykey";i.ds=t,i.dsquery=r}if(e.query.getgroup)if(e.query.sampleset);else{if(!r.cohort||!r.cohort.annotation)throw"no sample annotation for getting group";if(e.query.getgroup_unannotated){if(!o.boxplotbysamplegroup)throw"dsquery.boxplotbysamplegroup{} missing when getgroup_unannotated"}else{if(!Array.isArray(e.query.getgroup))throw"getgroup should be array";for(const t of e.query.getgroup){if(!t.k)throw"k missing from one of getgroup";if(!t.kvalue)throw"kvalue missing from one of getgroup"}}}return[n,r,o,i]}(t,e);e.query.getalllst,n.send(await async function(t,e,n,r,i){n.url&&(n.dir=await P.d1(n.url,n.indexURL));r&&r.dsquery.url&&(r.dsquery.dir=await P.d1(r.dsquery.url,r.dsquery.indexURL));const s=function(t){if(!t.query.sampleset)return;const e=new Map;for(const n of t.query.sampleset)for(const t of n.samples)e.set(t,n.name);return e}(i),a=new Map,l=[],c=[];if(await P.UE({args:[n.file?y().join(o().tpmasterdir,n.file):n.url,i.query.chr+":"+i.query.start+"-"+i.query.stop],dir:n.dir,callback:t=>{const r=t.split("\t"),o=JSON.parse(r[3]);if(o.gene&&o.gene==i.query.gene&&Number.isFinite(o.value))if(i.query.getalllst)l.push({sample:o.sample,value:o.value});else if(i.query.getgroup){if(!o.sample)return;if(s)return void(i.query.getgroup_unannotated?s.has(o.sample)||c.push(o):s.get(o.sample)==i.query.getgroup[0].full&&c.push(o));const t=e.cohort.annotation[o.sample];if(i.query.getgroup_unannotated){if(!t)return void c.push(o);for(const e of n.boxplotbysamplegroup.attributes)if(null==t[e.k])return void c.push(o);return}if(!t)return;for(const e of i.query.getgroup)if(e.kvalue!=t[e.k])return;c.push(o)}else if(n.boxplotbysamplegroup&&e.cohort&&e.cohort.annotation){if(!o.sample)return;let t;t=null==i.query.index_boxplotgroupers||0==i.query.index_boxplotgroupers?n.boxplotbysamplegroup.attributes:n.boxplotbysamplegroup.additionals[i.query.index_boxplotgroupers-1].attributes;const r=e.cohort.annotation[o.sample];if(!r)return void l.push({sample:o.sample,value:o.value});const s=r[t[0].k];if(null==s)return void l.push({sample:o.sample,value:o.value});const c=[];for(let e=1;e<t.length;e++){const n=r[t[e].k];if(null==n)break;c.push(n)}c.unshift(s);const u=c.join(", ");if(!a.has(u)){const e={samples:[],attributes:[]};for(const n of t){const t=r[n.k];if(null==t)break;const o={k:n.k,kvalue:t};n.full&&(o.full=n.full,o.fullvalue=r[n.full]),e.attributes.push(o)}a.set(u,e)}a.get(u).samples.push({sample:o.sample,value:o.value})}else if(s){if(!o.sample)return;const t=s.get(o.sample);if(!t)return void l.push({sample:o.sample,value:o.value});a.has(t)||a.set(t,{samples:[],attributes:[{full:t}]}),a.get(t).samples.push({sample:o.sample,value:o.value})}else l.push({sample:o.sample,value:o.value})}}),i.query.getgroup2boxplot){c.sort(((t,e)=>t.value-e.value));const{w1:t,w2:e,p25:n,p50:r,p75:o,out:i}=P.JC(c);return{n:c.length,min:c[0].value,max:c[c.length-1].value,w1:t,w2:e,p25:n,p50:r,p75:o,out:i}}const u=[];for(const[t,e]of a)u.push({name:t,values:e.samples,attributes:e.attributes});l.length&&u.push({name:"Unannotated",values:l});c.length&&u.push({values:c});if(i.query.getalllst)return{lst:u[0].values};if(i.query.iscustom&&!s||1==u.length){if(u[0]){const t=u[0].values;return t.sort(((t,e)=>e.value-t.value)),{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const f=await async function(t,e){if(!e||!t.query.svcnv.useloss&&!t.query.svcnv.usegain&&!t.query.svcnv.usesv)return;let n=t.query.start,r=t.query.stop;t.query.svcnv.usesv&&Number.isInteger(t.query.svcnv.svflank)&&(n=Math.max(0,n-t.query.svcnv.svflank),r+=t.query.svcnv.svflank);const i=new Map;return await P.UE({args:[e.dsquery.file?y().join(o().tpmasterdir,e.dsquery.file):e.dsquery.url,t.query.chr+":"+n+"-"+r],dir:e.dsquery.dir,callback:e=>{const n=e.split("\t"),r=JSON.parse(n[3]);if(r.sample)if(r.chrA||r.chrB){if(!t.query.svcnv.usesv)return;i.has(r.sample)||i.set(r.sample,{}),i.get(r.sample).sv=1}else{if(!t.query.svcnv.usegain&&!t.query.svcnv.useloss)return;if(t.query.svcnv.usesv&&t.query.svcnv.svflank){const e=Number.parseInt(n[1]),r=Number.parseInt(n[2]);if(Math.max(t.query.start,e)>Math.min(t.query.stop,r))return}if(!Number.isFinite(r.value))return;if(!t.query.svcnv.usegain&&r.value>0)return;if(!t.query.svcnv.useloss&&r.value<0)return;if(t.query.svcnv.valueCutoff&&Math.abs(r.value)<t.query.svcnv.valueCutoff)return;if(t.query.svcnv.bplengthUpperLimit&&Number.parseInt(n[2])-Number.parseInt(n[1])>t.query.svcnv.bplengthUpperLimit)return;i.has(r.sample)||i.set(r.sample,{}),r.value>0?i.get(r.sample).gain=1:r.value<0&&(i.get(r.sample).loss=1)}}}),i}(i,r);if(i.query.getgroup){if(u[0]){const t=u[0].values;if(t.sort(((t,e)=>e.value-t.value)),f)for(const e of t){const t=f.get(e.sample);if(t)for(const n in t)e[n]=t[n]}return{lst:t,max:t[0].value,min:t[t.length-1].value}}return{nodata:1}}const d=[];let h=null,p=null;for(const t of u){t.values.sort(((t,e)=>t.value-e.value));const e=t.values.length;null==h?(h=t.values[0].value,p=t.values[e-1].value):(h=Math.min(h,t.values[0].value),p=Math.max(p,t.values[e-1].value));const{w1:n,w2:r,p25:o,p50:s,p75:a,out:l}=P.JC(t.values),c=[{isall:1,w1:n,w2:r,p25:o,p50:s,p75:a,out:l}];if(f){if(i.query.svcnv.usegain){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).gain));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({iscnvgain:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}if(i.query.svcnv.useloss){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).loss));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({iscnvloss:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}if(i.query.svcnv.usesv){const e=t.values.filter((t=>f.has(t.sample)&&f.get(t.sample).sv));if(e.length){const{w1:t,w2:n,p25:r,p50:o,p75:i,out:s}=P.JC(e);c.push({issv:1,samplecount:e.length,w1:t,w2:n,p25:r,p50:o,p75:i,out:s})}}}d.push({name:t.name+" ("+t.values.length+")",boxplots:c,attributes:t.attributes})}return d.sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)),{groups:d,min:h,max:p}}(0,i,s,a,e))}catch(t){t.stack&&console.log(t),n.send({error:t.message||t})}})(fo)),yo.post(vo+"/mdsgenevalueonesample",(async function(t,e){const n=t.query;try{if(!n.sample)throw".sample missing";if(!n.genes)throw".genes[] missing";let r,i,s;if(t.query.iscustom){if(r=fo[n.genome],!r)throw"invalid genome";if(!n.file&&!n.url)throw"no file or url for expression data";i={},s={file:n.file,url:n.url,indexURL:n.indexURL}}else{const[t,e,o,a]=To(n);if(t)throw t;r=e,i=o,s=a}const a=s.file?null:await P.d1(s.url,s.indexURL),l={};let c=!0;for(const t of n.genes){let e;await P.UE({args:[s.file?y().join(o().tpmasterdir,s.file):s.url,t.chr+":"+t.start+"-"+t.stop],dir:a,callback:r=>{const o=r.split("\t");if(!o[3])return;const i=JSON.parse(o[3]);i.gene==t.gene&&i.sample==n.sample&&(e=i.value)}}),Number.isFinite(e)&&(l[t.gene]=e,c=!1)}c?e.send({nodata:1}):e.send({result:l})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/vcf",(async function(t,e){try{const[n,r,o]=P.ZX(t);if(n)throw n;const i=o?await P.d1(r,t.query.indexURL):null;if(!t.query.rglst)throw"rglst missing";const s=[];for(const e of t.query.rglst)await P.UE({args:[r,e.chr+":"+e.start+"-"+e.stop],dir:i,callback:t=>s.push(t)});e.send({linestr:s.join("\n")})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.get(vo+"/vcfheader",(async function(t,e){try{if(!t.query.genome)throw"genome missing";const n=fo[t.query.genome];if(!n)throw"invalid genome";const[r,o,i]=P.ZX(t);if(r)throw r;const s=i?await P.d1(o,t.query.indexURL):null;e.send({metastr:(await P.ZD(o,s)).join("\n"),nochr:await P.Jy(o,s,n)})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/translategm",(async function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";const r=t.query.gm;if(!r)throw"missing gm{}";if(!r.chr)throw"gm.chr missing";if(!r.start)throw"gm.start missing";if(!Number.isInteger(r.start))throw"gm.start not integer";if(!r.stop)throw"gm.stop missing";if(!Number.isInteger(r.stop))throw"gm.stop not integer";const o=await P.Kf(n,r.chr+":"+(r.start+1)+"-"+r.stop),i=F.fasta2gmframecheck(r,o);e.send({frame:i})}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.post(vo+"/samplematrix",(function(t,e){Promise.resolve().then((()=>{const e=fo[t.query.genome];if(!e)throw"invalid genome";let n,r;if(t.query.iscustom){if(!t.query.querykey2tracks)throw"querykey2tracks{} missing for custom dataset";n={queries:{}};for(const e in t.query.querykey2tracks){const r=t.query.querykey2tracks[e];if(!r.type)throw'missing "type" for a data track';if(r.type==F.tkt.mdsvcf){const r=t.query.querykey2tracks[e];r.type=F.mdsvcftype.vcf,n.queries[e]={type:F.tkt.mdsvcf,info:r.info,tracks:[r]}}else if(r.type==F.tkt.mdssvcnv)n.queries[e]=r;else{if(r.type!=F.tkt.mdsexpressionrank)throw"unknown type of data track: "+r.type;n.queries[e]=r}}}else{if(!e.datasets)throw"genome is not equipped with datasets";if(!t.query.dslabel)throw"dslabel missing";if(n=e.datasets[t.query.dslabel],!n)throw"invalid dslabel";if(!n.queries)throw"dataset is not equipped with queries"}if(t.query.sampleset)r=new Set(t.query.sampleset);else if(t.query.limitsamplebyeitherannotation){if(!n.cohort)throw"limitsamplebyeitherannotation but no cohort in ds";if(!n.cohort.annotation)throw"limitsamplebyeitherannotation but no cohort.annotation in ds";r=new Set;for(const e in n.cohort.annotation){const o=n.cohort.annotation[e];for(const n of t.query.limitsamplebyeitherannotation)if(o[n.key]==n.value){r.add(e);break}}}const o=[];for(const e of t.query.features){let t,i=[];if(e.querykey){if(!n.queries)throw"using querykey for a feature but no ds.queries";if(t=n.queries[e.querykey],!t)throw"unknown dsquery by key "+e.querykey}else if(e.querykeylst){if(!n.queries)throw"using querykeylst for a feature but no ds.queries";for(const t of e.querykeylst){const e=n.queries[t];if(!e)throw'unknown key "'+t+'" from querykeylst';i.push(e)}if(0==i.length)throw"no valid keys in querykeylst"}else if(!e.issampleattribute)throw"unknown way to query a feature";if(e.isgenevalue){const[i,s]=Jo(e,n,t,r);if(i)throw"error with isgenevalue: "+i;o.push(s)}else if(e.iscnv){const[i,s]=Wo(e,n,t,r);if(i)throw"error with iscnv: "+i;o.push(s)}else if(e.isloh){const[i,s]=Ho(e,n,t,r);if(i)throw"error with isloh: "+i;o.push(s)}else if(e.isvcf){const[i,s]=Qo(e,n,t,r);if(i)throw"error with isvcf: "+i;o.push(s)}else if(e.isitd){const[i,s]=Vo(e,n,t,r);if(i)throw"error with isitd: "+i;o.push(s)}else if(e.issvfusion){const[i,s]=Yo(e,n,t,r);if(i)throw"error with issvfusion: "+i;o.push(s)}else if(e.issvcnv){const[i,s]=Ko(e,n,t,r);if(i)throw"error with issvcnv: "+i;o.push(s)}else if(e.ismutation){const[t,s]=Xo(e,n,i,r);if(t)throw"error with ismutation: "+t;o.push(s)}else{if(!e.issampleattribute)throw"unknown type of feature";{const[t,i]=Go(e,n,r);if(t)throw"error with issampleattribute: "+t;o.push(i)}}}return Promise.all(o)})).then((t=>{e.send({results:t})})).catch((t=>{e.send({error:"string"==typeof t?t:t.message}),t.stack&&console.error(t.stack)}))})),yo.get(vo+"/mdssamplescatterplot",(async function(t,e){wo(t);try{const n=fo[t.query.genome];if(!n)throw"invalid genome";const r=n.datasets[t.query.dslabel];if(!r)throw"invalid dataset";if(!r.cohort)throw"no cohort for dataset";if(!r.cohort.annotation)throw"cohort.annotation missing for dataset";const o=r.cohort.scatterplot;if(!o)throw"scatterplot not supported for this dataset";const i=[];for(const e in r.cohort.annotation){const n=r.cohort.annotation[e];if(t.query.subsetkey&&n[t.query.subsetkey]!=t.query.subsetvalue)continue;const s=n[o.x.attribute];if(!Number.isFinite(s))continue;const a=n[o.y.attribute];Number.isFinite(a)&&i.push({sample:e,x:s,y:a,s:n})}e.send({colorbyattributes:o.colorbyattributes,colorbygeneexpression:o.colorbygeneexpression,querykey:o.querykey,dots:i,tracks:o.tracks})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdssamplesignature",(function(t,e){try{const n=t.query;if(!n.sample)throw".sample missing";const r=fo[n.genome];if(!r)throw"invalid genome";const o=r.datasets[n.dslabel];if(!o)throw"invalid dataset";if(!o.cohort)throw"no cohort for dataset";if(!o.cohort.mutation_signature)throw"no mutation_signature for cohort";const i=[];for(const t in o.cohort.mutation_signature.sets){const e=o.cohort.mutation_signature.sets[t];if(!e.samples)continue;const r=e.samples.map.get(n.sample);if(!r)continue;const s=[];for(const t in e.signatures)r[t]&&s.push({k:t,v:r[t]});s.length&&i.push({key:t,valuename:e.samples.valuename,annotation:s.sort(((t,e)=>e.v-t.v))})}e.send({lst:i})}catch(t){t.stack&&console.error(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/mdssurvivalplot",function(t){return async(e,n)=>{try{const r=e.query,o=t[r.genome];if(!o)throw"invalid genome";const i=o.datasets[r.dslabel];if(!i)throw"invalid dataset";if(!i.cohort)throw"no cohort for dataset";if(!i.cohort.annotation)throw"cohort.annotation missing for dataset";const s=i.cohort.survivalplot;if(!s)throw"survivalplot not supported for this dataset";if(!s.plots)throw".plots{} missing";if(e.query.init)return void n.send(s.init);if(!r.type)throw".type missing";const a=s.plots[r.type];if(!a)throw"unknown plot type: "+r.type;const l=function(t,e,n){if(!t.samplerule)throw".samplerule missing";if(!t.samplerule.full)throw".samplerule.full missing";const r=[];if(t.samplerule.full.byattr){const n=t.samplerule.full.key;if(!n)throw"key missing from samplerule.full{}";const o=t.samplerule.full.value;if(null==o)throw"value missing from samplerule.full{}";for(const t in e.cohort.annotation){const i=e.cohort.annotation[t];i[n]==o&&r.push({name:t,o:i})}}else if(t.samplerule.full.useall)for(const t in e.cohort.annotation){const n=e.cohort.annotation[t];r.push({name:t,o:n})}else{if(!t.samplerule.full.usesampleset)throw"unknown rule for samplerule.full";{const n=t.samplerule.full.sampleset;for(const t in n){const o=n[t],i=e.cohort.annotation[o];null!=i&&r.push({name:o,o:i})}}}const o=[];for(const t of r)Number.isFinite(t.o[n.serialtimekey])&&(t.serialtime=t.o[n.serialtimekey],t.censored=t.o[n.iscensoredkey],o.push(t));if(0==o.length)throw"no samples found for full set";return o}(r,i,a),c=await async function(t,e,n,r){if(e.samplerule.mutated_sets){const n=new Set(t.map((t=>t.name))),r=e.samplerule.mutated_sets.reduce(((e,r)=>{const o=new Set(r.samplenames);r.lst=t.filter((t=>o.has(t.name)));for(const t of r.samplenames)n.delete(t);return delete r.samplenames,e.push(r),e}),[]);return r.push({name:"No mutation (n="+n.size+")",lst:t.filter((t=>n.has(t.name))),is_notmutated:!0}),r}const o=e.samplerule.set;if(!o)return[{name:"All",lst:t}];if(o.geneexpression){if(!o.gene)throw".gene missing from samplerule.set";if(!o.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(o.start))throw".start not integer from samplerule.set";if(!Number.isInteger(o.stop))throw".start not integer from samplerule.set";if(o.bymedian)return await async function(t,e,n,r){const o=e.samplerule.set,[i,s]=await to(t,e,n),a=Math.ceil(s.length/2),l=s[a-1].genevalue;return[{name:o.gene+" "+i.datatype+" below median (n="+a+", value<"+l+")",lst:s.slice(0,a)},{name:o.gene+" "+i.datatype+" above median (n="+(s.length-a)+", value>="+l+")",lst:s.slice(a,s.length)}]}(t,e,n);if(o.byquartile)return await async function(t,e,n,r){const o=e.samplerule.set,[i,s]=await to(t,e,n),a=Math.ceil(.25*s.length),l=Math.ceil(.5*s.length),c=Math.ceil(.75*s.length),u=s[a-1].genevalue,f=s[l-1].genevalue,d=s[c-1].genevalue;return[{name:o.gene+" "+i.datatype+" from 1st quartile (n="+a+", value<"+u+")",lst:s.slice(0,a),isfirstquartile:!0},{name:o.gene+" "+i.datatype+" from 2nd quartile (n="+(l-a)+", "+u+"<=value<"+f+")",lst:s.slice(a,l)},{name:o.gene+" "+i.datatype+" from 3rd quartile (n="+(c-l)+", "+f+"<=value<"+d+")",lst:s.slice(l,c)},{name:o.gene+" "+i.datatype+" from 4th quartile (n="+(s.length-c)+", value>="+d+")",lst:s.slice(c,s.length),isfourthquartile:!0}]}(t,e,n)}if(o.mutation){if(!o.chr)throw".chr missing from samplerule.set";if(!Number.isInteger(o.start))throw".start not integer from samplerule.set";if(!Number.isInteger(o.stop))throw".start not integer from samplerule.set";return await async function(t,e,n){const r=e.samplerule.set;if(r.samples_snvindel=new Set,r.samples_cnv=new Set,r.samples_loh=new Set,r.samples_sv=new Set,r.samples_fusion=new Set,r.samples_itd=new Set,r.cnv&&!r.snvindel&&!r.loh&&!r.sv&&!r.fusion&&!r.itd){const[r,o]=await Kr(t,e,n,!0),i=[],s=[],a=[];for(const e of t)r.has(e.name)?i.push(e):o.has(e.name)?s.push(e):a.push(e);const l=[];return s.length&&l.push({name:"Copy number loss (n="+s.length+")",lst:s}),i.length&&l.push({name:"Copy number gain (n="+i.length+")",lst:i}),a.length&&l.push({name:"No copy number variation (n="+a.length+")",lst:a}),l}const o=await Kr(t,e,n),i=[];for(const e of t)o.find((t=>t.name==e.name))||i.push(e);const s=[];o.length&&s.push({name:"With mutation (n="+o.length+")",lst:o});i.length&&s.push({name:"No mutation (n="+i.length+")",lst:i});return s}(t,e,n)}throw"unknown rule for samplerule.set{}"}(l,r,i);let u;c.length>1&&(u=await Yr(c)),await async function(t,e){if(!t.samplerule.mutated_sets)return;const n=e.find((t=>t.is_notmutated));if(!n)return;for(const t of e){if(t.is_notmutated)continue;const e=await Yr([t,n]);t.pvalue=e}}(r,c),await async function(t,e){if(!t.samplerule.set)return;if(!t.samplerule.set.geneexpression)return;if(!t.samplerule.set.byquartile)return;if(4!=e.length)return;if(t.samplerule.set.against1st){for(let t=1;t<4;t++)e[t].pvalue=await Yr([e[0],e[t]]);return}if(t.samplerule.set.against4th){for(let t=0;t<3;t++)e[t].pvalue=await Yr([e[t],e[3]]);return}}(r,c);for(const t of c)eo(t),delete t.lst;const f={samplesets:c,pvalue:u};r.samplerule.set&&r.samplerule.set.mutation&&(f.count_snvindel=r.samplerule.set.samples_snvindel.size,f.count_cnv=r.samplerule.set.samples_cnv.size,f.count_loh=r.samplerule.set.samples_loh.size,f.count_sv=r.samplerule.set.samples_sv.size,f.count_fusion=r.samplerule.set.samples_fusion.size,f.count_itd=r.samplerule.set.samples_itd.size),n.send(f)}catch(t){t.stack&&console.error(t.stack),n.send({error:t.message||t})}}}(fo)),yo.post(vo+"/fimo",function(t){return async(e,n)=>{try{const r=e.query;if(!r.m)throw"no mutation";if(!r.m.chr)throw"mutation chr missing";if(!Number.isInteger(r.m.pos))throw"mutation position is not integer";if(!r.m.ref)throw"mutation ref allele missing";if(!r.m.alt)throw"mutation alt allele missing";const o=t[r.genome];if(!o)throw"invalid genome";if(!o.fimo_motif)throw"motif finding not supported on this genome";const i=await async function(t,e){const n=t.m.pos-t.flankspan,r=t.m.pos+t.flankspan,o=await P.Kf(e,t.m.chr+":"+n+"-"+r);!function(t,e,n){if(!t.m.ref)return;if("-"==t.m.ref)return;const r=n.split("\n").slice(1).join("").toUpperCase(),o=r.substring(t.m.pos-e,t.m.pos-e+t.m.ref.length);if(o==t.m.ref.toUpperCase())return;if(common.reversecompliment(o)==t.m.ref.toUpperCase())t.m.ref=o,"-"!=t.m.alt&&(t.m.alt=common.reversecompliment(t.m.alt))}(t,n,o);const i=await Wr(t,e,o),s=new Map;for(const t of i)t.pvalue_ref=t.pvalue,delete t.pvalue,t.logpvalue_ref=t.logpvalue,delete t.logpvalue,s.has(t.name)||s.set(t.name,[]),s.get(t.name).push(t);const a=function(t,e,n,r){const o=r.split("\n"),i=o.slice(1).join("");return o[0]+"\n"+i.substr(0,t.pos-e)+("-"==t.alt?"":t.alt)+i.substr(t.pos-e+("-"==t.ref?0:t.ref.length))}(t.m,n,0,o),l=await Wr(t,e,a);for(const t of l){t.pvalue_alt=t.pvalue,delete t.pvalue,t.logpvalue_alt=t.logpvalue,delete t.logpvalue,s.has(t.name)||s.set(t.name,[]);let e=!0;for(const n of s.get(t.name))if(null!=n.logpvalue_ref&&n.strand==t.strand&&Math.abs(t.start-n.start)<=2&&Math.abs(t.stop-n.stop)<=2){n.pvalue_alt=t.pvalue_alt,n.logpvalue_alt=t.logpvalue_alt,n.logpvaluediff=t.logpvalue_alt-n.logpvalue_ref,n.logpvaluediff>0?n.gain=!0:n.loss=!0,e=!1;break}e&&s.get(t.name).push(t)}let c=0,u=0;const f=[];for(const e of s.values())for(const n of e)null==n.logpvaluediff&&(null==n.pvalue_ref?(n.gain=!0,n.logpvaluediff=n.logpvalue_alt):null==n.pvalue_alt&&(n.loss=!0,n.logpvaluediff=-n.logpvalue_ref)),null!=t.minabslogp&&Math.abs(n.logpvaluediff)<t.minabslogp||(n.logpvaluediff>0?c=Math.max(c,n.logpvaluediff):u=Math.min(u,n.logpvaluediff),f.push(n));return{items:f,valuemin:u,valuemax:c,refstart:n,refstop:r,refseq:o.split("\n").slice(1).join("")}}(r,o);n.send(i)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}(fo)),yo.all(vo+"/termdb",X.TO(fo)),yo.all(vo+"/termdb-barsql",it.TO(fo)),yo.post(vo+"/singlecell",function(t){return async(e,n)=>{try{const r=e.query,o=t[r.genome];if(!o)throw"invalid genome";if(r.getpcd)return void await async function(t,e){const n={},r=await async function(t,e){if(!t.textfile)throw".textfile missing";{const[e,n,r]=P.ZX({query:{file:t.textfile}});if(e)throw".textfile error: "+e;if(!r){if(await P.yE(n))throw"file not exist: "+t.textfile;if(await P.t7(n))throw"file not readable: "+t.textfile}t.textfile=n}let n,r,o,i,s;if(t.getpcd.category_autocolor){const e=t.getpcd.values_count&&t.getpcd.values_count<=10?Rr.Z:zr;n=Ir.Z(e),o={},i={}}else if(t.getpcd.category_customcolor){const e=Ir.Z(zr);a=t.getpcd.cat_values,l=e,n=t=>{let e=!1;for(const n of a)if(n.value==t)return e=!0,n.color;if(!e)return l(t)},o={},i={},s={}}else if(t.getpcd.gene_expression){const n=t.getpcd.gene_expression;if(!n.file)throw"gene_expression.file missing";{const[t,e,r]=P.ZX({query:{file:n.file}});if(t)throw t;n.file=e}if(!Number.isInteger(n.barcodecolumnidx))throw"gene_expression.barcodecolumnidx missing";if(!n.chr)throw"gene_expression.chr missing";if(!n.start)throw"gene_expression.start missing";if(!n.stop)throw"gene_expression.stop missing";if(!n.genename)throw"gene_expression.genename missing";if(!n.autoscale)throw"gene_expression: unknown scaling method";if(!n.color_min)throw"gene_expression.color_min missing at autoscale";if(!n.color_max)throw"gene_expression.color_max missing at autoscale";const o=(n.nochr?n.chr.replace("chr",""):n.chr)+":"+n.start+"-"+n.stop,i=new Map;r=new Map;let s=0,a=0;if(e.numbercellwithgeneexp=0,e.numbercelltotal=0,await P.UE({args:[n.file,o],callback:t=>{const r=JSON.parse(t.split("\t")[3]);r.gene==n.genename&&Number.isFinite(r.value)&&(e.numbercellwithgeneexp++,n.autoscale&&(s=Math.min(s,r.value),a=Math.max(a,r.value)),i.set(r.sample,r.value))}}),n.autoscale){e.minexpvalue=s,e.maxexpvalue=a;const t=vt.ZP(n.color_min,n.color_max);for(const[e,n]of i){const o=tt.ZP(t((n-s)/(a-s)));r.set(e,Number.parseInt(Br(o.r,o.g,o.b),16))}}}var a,l;return new Promise(((s,a)=>{const l=[],c=O().createInterface({input:m().createReadStream(t.textfile)});let u=!0,f=0,d=0;c.on("line",(s=>{if(u)return void(u=!1);const a=s.split(t.delimiter),c=[];for(const e of t.getpcd.coord)c.push(a[e]),f=Math.max(f,a[e]),d=Math.min(d,a[e]);if(2==t.getpcd.coord.length&&c.push("0"),n){const e=a[t.getpcd.category_index],r=n(e);if(t.hidden_types.includes(e))if(t.background_color){const e=tt.ZP(t.background_color),n=Number.parseInt(Br(e.r,e.g,e.b),16);c.push(n)}else c.push(16777215);else c.push(Number.parseInt(r.slice(1),16));o&&(o[e]=r),i&&(i[e]=e in i?i[e]+1:1)}else if(r){e.numbercelltotal++;const n=a[t.getpcd.gene_expression.barcodecolumnidx];let o=r.get(n);if(void 0===o)if(t.getpcd.gene_expression.color_no_exp){const e=tt.ZP(t.getpcd.gene_expression.color_no_exp);o=Number.parseInt(Br(e.r,e.g,e.b),16)}else o="2894892";c.push(o)}l.push(c.join(" "))})),c.on("close",(()=>{o&&(t.getpcd.category_customorder&&(o=function(t,e){let n={};const r=Object.keys(t).length;for(var o=1;o<=r;o++){const r=e.find((t=>{if(t.order==o)return t.value}));r&&(n[r.value]=t[r.value])}for(const r of e)r.order||(n[r.value]=t[r.value]);for(const r in t){e.find((t=>{if(t.value==JSON.stringify(r))return!0}))||(n[r]=t[r])}return n}(o,t.getpcd.cat_values)),e.category2color=o,e.categorycount=i),e.data_sphere_r=Math.max(Math.abs(f),Math.abs(d)),s(l)}))}))}(t,n),o="# .PCD v.7 - Point Cloud Data file format\nVERSION .7\nFIELDS x y z rgb\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH 1200\nHEIGHT 800\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 960000\nDATA ascii\n";n.pcddata=o+r.join("\n"),e.send(n)}(r,n);if(r.getgeneboxplot)return void await async function(t,e,n){const r=t.getgeneboxplot,o=t.getgeneboxplot.values_count&&t.getgeneboxplot.values_count<=10?Ir.Z(Rr.Z):Ir.Z(zr);if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=P.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}if(!r.chr)throw"getgeneboxplot.chr missing";if(!r.start)throw"getgeneboxplot.start missing";if(!r.stop)throw"getgeneboxplot.stop missing";if(!r.genename)throw"getgeneboxplot.genename missing";const i=await Gr(r),s=(r.nochr?r.chr.replace("chr",""):r.chr)+":"+r.start+"-"+r.stop;let a=0,l=0;await P.UE({args:[r.expfile,s],callback:t=>{const e=JSON.parse(t.split("\t")[3]);if(e.gene!=r.genename)return;if(!e.sample)return;if(!Number.isFinite(e.value))return;const n=i.get(e.sample);n&&(n.expvalue=e.value,a=Math.min(a,e.value),l=Math.max(l,e.value))}});const c=new Map;for(const[t,e]of i)c.has(e.category)||c.set(e.category,[]),r.exclude_cells&&0==parseInt(e.expvalue)||c.get(e.category).push({value:e.expvalue});const u=[],f=(d=Sn.Z().domain([a,l]).ticks(20),t=>{const e=[];for(let t=1;t<d.length;t++)e.push(0);for(const n of t)for(let t=1;t<d.length;t++)if(n.value<=d[t]){e[t-1]++;break}return e});var d;for(const[t,e]of c){e.sort(((t,e)=>t.value-e.value));const n=P.JC(e);delete n.out;const r=o(t);n.category=t,n.color=r,n.numberofcells=e.length,n.density=f(e),u.push(n)}let h=[];if(t.getgeneboxplot.cat_values){const e=Object.keys(t.getgeneboxplot.cat_values).length;for(var p=1;p<=e;p++){const e=t.getgeneboxplot.cat_values.find((t=>{if(t.order==p)return t.value}));e&&h.push(u.filter((t=>t.category==e.value))[0])}for(const e of t.getgeneboxplot.cat_values)e.order||h.push(u.filter((t=>t.category==e.value))[0]);for(const e of u){t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return!0}))||h.push(e)}for(const e of h){const n=t.getgeneboxplot.cat_values.find((t=>{if(t.value==e.category)return t}));n&&n.color&&(e.color=n.color)}}else h=u;n.send({boxplots:h,minexpvalue:a,maxexpvalue:l})}(r,0,n);if(r.getheatmap)return void await async function(t,e,n){const r=t.getheatmap,o=[];if(!r.expfile)throw"getgeneboxplot.expfile missing";{const[t,e,n]=P.ZX({query:{file:r.expfile}});if(t)throw"getgeneboxplot.expfile error: "+t;r.expfile=e}r.gene_list.forEach((t=>{if(!t.chr)throw"getgeneboxplot.chr missing";if(!t.start)throw"getgeneboxplot.start missing";if(!t.stop)throw"getgeneboxplot.stop missing";if(!t.gene)throw"getgeneboxplot.genename missing"}));const i=await Gr(r);for(const t of r.gene_list){const e=(t.nochr?t.chr.replace("chr",""):t.chr)+":"+t.start+"-"+t.stop;let n=0,s=0;const a=t.gene;await P.UE({args:[r.expfile,e],callback:e=>{const r=JSON.parse(e.split("\t")[3]);if(r.gene.toUpperCase()!==t.gene.toUpperCase())return;if(!r.sample)return;if(!Number.isFinite(r.value))return;const o=i.get(r.sample);o&&(o.expvalue=r.value,n=Math.min(n,r.value),s=Math.max(s,r.value))}});const l=new Map;for(const[t,e]of i)l.has(e.category)||l.set(e.category,[]),l.get(e.category).push({value:e.expvalue});const c=[];for(const[t,e]of l){let n=0;for(const t of e)n+=t.value;const r=e.length,o=(n/r).toFixed(3);c.push({category:t,mean:o,numberofcells:r})}o.push({genename:a,heatmap:c})}n.send({gene_heatmap:o})}(r,0,n)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}(fo)),yo.post(vo+"/massSession",(async function(t,e){try{const n=t.body.__sessionFor__,{filename:r,route:i,dslabel:s,embedder:a}=n||{};let l;if(r){const e={headers:t.headers,query:n};if(l=$r.i.getPayloadFromHeaderAuth(e,i),!l.email)throw"invalid credentials: no jwt.email";if(l.dslabel!=s||l.route!=i||l.embedder!=a)throw"invalid credentials: mismatched payload";delete t.body.__sessionFor__}const c=r||function(){const t=[];for(;t.length<15;){const e=46+Math.floor(80*Math.random());(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)&&t.push(String.fromCharCode(e))}return t.join("")}(),u=JSON.stringify(t.body),f=r?Zr(n,l):o().cachedir_massSession;await m().promises.access(f).then((()=>!0)).catch((()=>!1))||m().mkdirSync(f,{recursive:!0}),await P.Sf(y().join(f,c),u),e.send({id:c})}catch(t){e.send({error:t.message||t})}})),yo.get(vo+"/massSession",(async function(t,e){try{const n=t.query.id;if(!n)throw"session id missing";const{route:r,dslabel:i,embedder:s}=t.query,a=t.query.route?$r.i.getPayloadFromHeaderAuth(t,t.query.route):null,l=t.query.route?Zr(t.query,a):o().cachedir_massSession,c=y().join(l,n);let u;try{u=(await m().promises.stat(c)).birthtime}catch(t){throw"invalid session"}const f=await P.b5(c),d=JSON.parse(f);if(t.query.route)return void e.send({state:d});const h=new Date,p=new Date(u),g=o().features.massSessionDuration||30,v=g-Math.round((h.getTime()-p.getTime())/864e5);e.send({state:d,sessionDaysLeft:v,massSessionDuration:g})}catch(t){e.send({error:t.message||t})}})),yo.delete(vo+"/massSession",(async function(t,e){try{const n=t.query.ids;if(!n)throw"session ids[] missing";const{route:r,dslabel:i,embedder:s}=t.query,a=t.query.route?$r.i.getPayloadFromHeaderAuth(t,t.query.route):null;if(!a)throw"missing credentials";const l=t.query.route?Zr(t.query,a):o().cachedir_massSession,c=[];for(const t of n){const e=y().join(l,t);m().unlink(e,(t=>{if(t)throw c.push(t),t}))}c.length||e.send({status:"ok"})}catch(t){e.send({error:t.message||t})}})),yo.get(vo+"/sessionIds",(async function(t,e){try{const{filename:n,route:r,dslabel:o,embedder:i}=t.query,s=$r.i.getPayloadFromHeaderAuth(t,r);if(!s.email)throw"invalid credentials: no jwt.email";if(s.dslabel!=o||s.route!=r||s.embedder!=i)throw"invalid credentials: mismatched payload";const a=Zr(t.query,s);if(!await m().promises.access(a).then((()=>!0)).catch((()=>!1)))return void e.send({status:"ok",sessionIds:[]});const l=await m().promises.readdir(a);e.send({status:"ok",sessionIds:l})}catch(t){e.status(401),e.send({error:t.message||t})}})),yo.get(vo+"/isoformbycoord",(async function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!t.query.chr)throw"chr missing";const r=Number(t.query.pos);if(!Number.isInteger(r))throw"pos must be positive integer";const i=n.tracks.find((t=>t.__isgene));i||reject("no gene track");const s=[];await P.UE({args:[y().join(o().tpmasterdir,i.file),t.query.chr+":"+r+"-"+r],callback:t=>{const e=t.split("\t")[3];if(!e)return;const r=JSON.parse(e);if(!r.isoform)return;const o={isoform:r.isoform},i=n.genedb.getjsonbyisoform.get(r.isoform);i&&(o.name=JSON.parse(i.genemodel).name,o.isdefault=i.isdefault),s.push(o)}}),e.send({lst:s})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/ase",(async function(t,e){const n=t.query,r=3e6,i=5e5;try{const t=fo[n.genome];if(!t)throw"invalid genome";if(!n.samplename)throw"samplename missing";if(!n.chr)throw"no chr";if(!n.start||!n.stop)throw"no start/stop";if(!n.rnabarheight)throw"no rnabarheight";if(!n.dnabarheight)throw"no dnabarheight";if(!Number.isInteger(n.barypad))throw"invalid barypad";if(n.rnamax&&!Number.isFinite(n.rnamax))throw"invalid value for rnamax";if(!n.checkrnabam)throw".checkrnabam{} missing";const s=Fo(n.checkrnabam);if(s)throw s;if(n.refcolor||(n.refcolor="blue"),n.altcolor||(n.altcolor="red"),!t.tracks)throw"genome.tracks[] missing";const a=t.tracks.find((t=>t.__isgene));if(!a)throw"no gene track from this genome";await async function(t,e){if(t.rnabamfile)t.rnabamfile=y().join(o().tpmasterdir,t.rnabamfile);else{if(!t.rnabamurl)throw"no file or url for rna bam";t.rnabamurl_dir=await P.d1(t.rnabamurl,t.rnabamindexURL||t.rnabamurl+".bai")}if(t.rnabam_nochr=await P.Dp(t.rnabamfile||t.rnabamurl,e,t.rnabamurl_dir),t.vcffile)t.vcffile=y().join(o().tpmasterdir,t.vcffile);else{if(!t.vcfurl)throw"no file or url for vcf";t.vcfurl_dir=await P.d1(t.vcfurl,t.vcfindexURL)}t.vcf_nochr=await P.Jy(t.vcffile||t.vcfurl,t.vcfurl_dir,e)}(n,t);const l=await Zo(t,a,n.chr,n.start,n.stop),c={};if(n.stop-n.start<r)for(const[t,e]of l){const t={file:n.rnabamfile,url:n.rnabamurl,dir:n.rnabamurl_dir,nochr:n.rnabam_nochr};let r;r=n.rnabamispairedend?await Eo(t,n.chr,e):await jo(t,n.chr,e),e.fpkm=1e9*r/(n.rnabamtotalreads*e.exonlength)}else c.fpkmrangelimit=r;const[u,f,d,h]=function(t,e){let n=t.start,r=t.stop;for(const[t,o]of e)n=Math.min(n,o.start),r=Math.max(r,o.stop);const o=t.start,i=t.stop;return[n,r,o,i]}(n,l),p=await async function(t,e,n,r,o){const i=await Uo(t.vcffile||t.vcfurl,t.vcfurl_dir),[s,a,l,c]=D.e(i);if(c)throw c;const u={info:s,format:a,samples:l},f=await zo(t.vcffile||t.vcfurl,(t.vcf_nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+o,t.vcfurl_dir),d=[];for(const e of f||[]){const[n,r,o]=D.S(e,u);for(const e of r){if(!F.basecolor[e.ref]||!F.basecolor[e.alt])continue;if(!e.sampledata)continue;const n=$o(e,t.samplename,t.checkrnabam);n&&d.push(n)}}const h=[];for(const t of d)for(const[e,r]of n)if(t.pos>=r.start&&t.pos<=r.stop){h.push(t);break}return h}(n,0,l,u,f);for(const t of p)t.rnacount={nocoverage:1};let g,v;h-d>=i?c.covplotrangelimit=i:(n.rnamax?g=n.rnamax:(g=await async function(t,e,n){let r=0;return await P.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:t=>{const e=t.split("\t");if(3!=e.length)return;const n=Number.parseInt(e[2]);Number.isInteger(n)&&(r=Math.max(r,n))}}),r}(n,d,h),c.rnamax=g),v=await async function(t,e,n,r,o){const i=new Map;for(const t of r)t.dnacount.ishet&&t.pos>=e&&t.pos<=n&&i.set(t.pos,t);const s=(0,S.createCanvas)(t.width*t.devicePixelRatio,(t.rnabarheight+t.barypad+t.dnabarheight)*t.devicePixelRatio),a=s.getContext("2d");t.devicePixelRatio>1&&a.scale(t.devicePixelRatio,t.devicePixelRatio);let l,c,u=!1;n-e<=t.width?(u=!0,l=1,c=t.width/(n-e),a.lineWidth=c):(c=1,l=(n-e)/t.width);return await P.UE({isbam:!0,args:["depth","-r",(t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(e+1)+"-"+(n+1),"-g","DUP",t.rnabamurl||t.rnabamfile],dir:t.rnabamurl_dir,callback:n=>{const r=n.split("\t");if(3!=r.length)return;const s=Number.parseInt(r[1])-1;if(!Number.isInteger(s))return;const f=Number.parseInt(r[2]);if(!Number.isInteger(f))return;const d=t.rnabarheight*Math.min(f,o)/o,h=u?(s-e)*c:(s-e)/l;a.strokeStyle="#ccc",a.beginPath(),a.moveTo(h+c/2,t.rnabarheight),a.lineTo(h+c/2,t.rnabarheight-d),a.stroke(),a.closePath(),f>o&&(a.strokeStyle="blue",a.beginPath(),a.moveTo(h+c/2,0),a.lineTo(h+c/2,2),a.stroke(),a.closePath());const p=i.get(s);p&&(p.rnacount.h=d)}}),{canvas:s,ctx:a,isbp:u,binpxw:c,binbpsize:l}}(n,d,h,p,g)),c.coveragesrc=await function(t,e,n,r,o,i,s,a){const l=[];for(const n of e)n.dnacount.ishet&&l.push((t.rnabam_nochr?t.chr.replace("chr",""):t.chr)+":"+(n.pos+1)+"-"+(n.pos+1));return new Promise(((n,r)=>{const c=(0,q.spawn)(mo,["mpileup","-q",t.checkrnabam.rnapileup_q,"-Q",t.checkrnabam.rnapileup_Q,"--no-reference","-a","INFO/AD","-d",999999,"-r",l.join(","),t.rnabamurl||t.rnabamfile],{cwd:t.rnabamurl_dir});O().createInterface({input:c.stdout}).on("line",(t=>{if("#"==t[0])return;const n=Lo(t);if(!n)return;let r;n.pos>=o&&n.pos<=i&&n.DP;const s=e.find((t=>t.pos==n.pos));if(s){s.__x=r;const t=n.allele2count[s.ref]||0,e=n.allele2count[s.alt]||0;t+e>0&&(delete s.rnacount.nocoverage,s.rnacount.ref=t,s.rnacount.alt=e,s.rnacount.f=e/(t+e))}})),c.on("close",(()=>{if(!s)return void n();const{canvas:r,ctx:l,binpxw:c}=s;l.lineWidth=Math.max(3,c);let u=0;for(const n of e)n.dnacount&&(n.pos<o||n.pos>i||(n.__x=t.width*(n.pos-o)/(i-o),u=Math.max(u,n.dnacount.ref+n.dnacount.alt)));for(const n of e){if(null==n.__x)continue;n.rnacount.nocoverage||(null==n.rnacount.h&&(n.rnacount.h=t.rnabarheight*(n.rnacount.ref+n.rnacount.alt)/a),l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight),l.lineTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight-(1-n.rnacount.f)*n.rnacount.h),l.lineTo(n.__x+c/2,t.rnabarheight-n.rnacount.h),l.stroke(),l.closePath());const e=t.dnabarheight*(n.dnacount.ref+n.dnacount.alt)/u;n.dnacount.ishet&&(l.strokeStyle=t.refcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.stroke(),l.closePath(),l.strokeStyle=t.altcolor,l.beginPath(),l.moveTo(n.__x+c/2,t.rnabarheight+t.barypad+(1-n.dnacount.f)*e),l.lineTo(n.__x+c/2,t.rnabarheight+t.barypad+e),l.stroke(),l.closePath()),delete n.__x}n(r.toDataURL())}))}))}(n,p,0,0,d,h,v,g),await async function(t,e){if(0==t.length)return;const n=[];for(const r of t)r.rnacount.nocoverage||r.rnacount.ref+r.rnacount.alt<e.checkrnabam.rna_mintotalreads||n.push(r);if(0==n.length)return;const r=await function(t){const e=y().join(o().cachedir,Math.random().toString())+".snp",n=[];for(const e of t)e.rnacount.nocoverage||null!=e.rnacount.ref&&null!=e.rnacount.alt&&n.push(e.pos+"."+e.ref+"."+e.alt+"\t\t\t\t\t\t\t\t"+e.rnacount.ref+"\t"+e.rnacount.alt);return new Promise(((t,r)=>{m().writeFile(e,n.join("\n")+"\n",(n=>{n&&r("cannot write"),t(e)}))}))}(n),i=await Do(r);await function(t,e){return new Promise(((n,r)=>{m().readFile(e,"utf8",((e,o)=>{e&&r("cannot read binom pvalue"),o||n();for(const e of o.trim().split("\n")){const n=e.split("\t"),r=t.find((t=>n[0]==t.pos+"."+t.ref+"."+t.alt));r&&(r.rnacount.pvalue=Number.parseFloat(n[10]))}n()}))}))}(t,i),m().unlink(r,(()=>{})),m().unlink(i,(()=>{}))}(p,n),c.genes=function(t,e,n){const r=[];for(const[o,i]of e){r.push(i);const e=t.filter((t=>t.pos>=i.start&&t.pos<=i.stop));if(0==e.length){i.nosnp=1;continue}i.snps=e;const o=e.filter((t=>null!=t.rnacount.pvalue));if(0==o.length){i.nornasnp=1;continue}const s=o.reduce(((t,e)=>t+Math.abs(e.rnacount.f-.5)),0);let a=null,l=0;for(const t of o)null==a?a=t.rnacount.pvalue:a*=t.rnacount.pvalue,t.rnacount.pvalue<=n.checkrnabam.binompvaluecutoff&&l++;i.ase={markers:e.filter((t=>t.dnacount.ishet)).length,ase_markers:l,mean_delta:s/o.length,geometricmean:Math.pow(a,1/o.length)}}return r}(p,l,n);let b=0;for(const t of p)t.dnacount&&t.pos>=d&&t.pos<=h&&(b=Math.max(b,t.dnacount.ref+t.dnacount.alt));c.dnamax=b,e.send(c)}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.post(vo+"/bamnochr",(async function(t,e){const n=t.query;try{const t=fo[n.genome];if(!t)throw"invalid genome";if(n.file)n.file=y().join(o().tpmasterdir,n.file);else{if(!n.url)throw"no bam file or url";n.url_dir=await P.d1(n.url,n.indexURL||n.url+".bai")}const r=await P.Dp(n.file||n.url,t,n.url_dir);e.send({nochr:r})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}})),yo.get(vo+"/gene2canonicalisoform",(function(t,e){wo(t);try{if(!t.query.gene)throw".gene missing";const n=fo[t.query.genome];if(!n)throw"unknown genome";if(!n.genedb.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const r=n.genedb.get_gene2canonicalisoform.get(t.query.gene);e.send(r)}catch(t){e.send({error:t.message||t}),t.stack&&console.log(t.stack)}})),yo.get(vo+"/ideogram",(function(t,e){try{const n=fo[t.query.genome];if(!n)throw"invalid genome";if(!n.genedb.hasIdeogram)throw"ideogram not supported on this genome";if(!t.query.chr)throw".chr missing";const r=n.genedb.getIdeogramByChr.all(t.query.chr);if(!r.length)throw"no ideogram data for this chr";e.send(r)}catch(t){e.send({error:t.message||t})}}));P.lY,P.ZX;function ei(t){const e=t.split(/\r?\n/);if(e.length<=1||!e[0])return[null,[]];const n=e[0].split("\t"),r=[];for(let t=1;t<e.length;t++){if("#"==e[t][0])continue;const o=e[t].split("\t"),i={};for(let t=0;t<n.length;t++){const e=o[t];e&&(i[n[t]]=e)}r.push(i)}return[null,r]}async function ni(t){try{await m().promises.stat(t.tpmasterdir)}catch(e){const n="Error with "+t.tpmasterdir+": "+e.code;if("validate"==process.argv[2])throw n;return void console.log("\n!!! "+n+"\n")}if(function(){if(o().features.skip_checkDependenciesAndVersions)return void console.log("SKIPPED checkDependenciesAndVersions()");const t=["jsonlite","cmprsk","hwde","lmtest"];for(const e of t){const t=N().spawnSync(o().Rscript,["-e",`suppressPackageStartupMessages(library("${e}"))`],{encoding:"utf8"});if(t.stderr.trim())throw t.stderr}const e=10;{const t=N().execSync(o().samtools+" --version",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("samtools"!=n||!r)throw'cannot run "samtools version"';const[i,s]=r.split(".");if("1"!=i)throw"samtools not 1.*";if(Number(s)<e)throw`samtools not >= 1.${e}`}{const t=N().execSync(o().bcftools+" -v",{encoding:"utf8"}).trim().split("\n"),[n,r]=t[0].split(" ");if("bcftools"!=n||!r)throw'cannot run "bcftools version"';const[i,s]=r.split(".");if("1"!=i)throw"bcftools not 1.*";if(Number(s)<e)throw`bcftools not >= 1.${e}`}}(),null!=t.base_zindex){const e=Number.parseInt(t.base_zindex);if(Number.isNaN(e)||e<=0)throw"base_zindex must be positive integer";t.base_zindex=e}if(t.jwt){if(!t.jwt.secret)throw"jwt.secret missing";if(!t.jwt.permissioncheck)throw"jwt.permissioncheck missing"}if(!t.tpmasterdir)throw".tpmasterdir missing";if(!t.cachedir)throw".cachedir missing";if(t.cachedir_massSession=await ii("massSession"),t.cachedir_massSessionTrash=await ii("massSessionTrash"),t.cache_snpgt={dir:await ii("snpgt"),fileNameRegexp:/[^\w]/,sampleColumn:6},t.cachedir_bam=await ii("bam"),t.cachedir_genome=await ii("genome"),t.cachedir_ssid=await ii("ssid"),t.commonOverrides&&F.applyOverrides(t.commonOverrides),!t.genomes)throw".genomes[] missing";if(!Array.isArray(t.genomes))throw".genomes[] not array";for(const e of t.genomes){if(!e.name)throw".name missing from a genome: "+JSON.stringify(e);if(!e.file)throw".file missing from genome "+e.name;const n=y().join(process.cwd(),e.file),r=require(m().existsSync(n)?n:e.file),o=r.default||r;if(fo[e.name]=o,!o.genomefile)throw".genomefile missing from .js file of genome "+e.name;if("NA"==o.genomefile||(o.genomefile=y().join(t.tpmasterdir,o.genomefile)),o.genomicNameRegexp||(o.genomicNameRegexp=/[^a-zA-Z0-9.:_-]/),o.tracks||(o.tracks=[]),e.tracks)for(const t of e.tracks)o.tracks.push(t);if(e.datasets&&(o.rawdslst=e.datasets),e.snp&&(o.snp=e.snp),e.blat){if(!e.blat.host)throw".blat.host missing for "+e.name;if(!e.blat.port)throw".blat.port missing for "+e.name;o.blat=e.blat}if(e.nosnp&&delete o.snp,e.nohicenzyme&&delete o.hicenzymefragment,e.nohicdomain&&delete o.hicdomain,o.genedb&&e.no_gene2canonicalisoform&&delete o.genedb.gene2canonicalisoform,e.updateAttr)for(const t of e.updateAttr){let e=o;for(const[n,r]of t.entries())if(e)if("object"==typeof r)for(const t in r)e[t]=r[t];else{if("string"==typeof e[r]){t[n+1]&&(e[r]=t[n+1]);break}e=e[r]}}}t.defaultgenome&&fo[t.defaultgenome]&&(fo[t.defaultgenome].isdefault=!0);for(const e in fo){const n=fo[e];if(!n.majorchr)throw e+": majorchr missing";if(!n.defaultcoord)throw e+": defaultcoord missing";if(await P.Kf(n,n.defaultcoord.chr+":"+n.defaultcoord.start+"-"+(n.defaultcoord.start+1)),n.tracks||(n.tracks=[]),"string"==typeof n.majorchr){const t=n.majorchr.trim().split(/[\s\t\n]+/),r={},o=[];for(let n=0;n<t.length;n+=2){const i=t[n],s=Number.parseInt(t[n+1]);if(Number.isNaN(s))throw e+" majorchr invalid chr size for "+i+" ("+t[n+1]+")";r[i]=s,o.push(i)}n.majorchr=r,n.majorchrorder=o}n.chrlookup={};for(const t in n.majorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.majorchr[t],major:!0};if(n.minorchr){if("string"==typeof n.minorchr){const t=n.minorchr.trim().split(/[\s\t\n]+/),r={};for(let n=0;n<t.length;n+=2){const o=Number.parseInt(t[n+1]);if(Number.isNaN(o))throw e+" minorchr invalid chr size for "+t[n]+" ("+t[n+1]+")";r[t[n]]=o}n.minorchr=r}for(const t in n.minorchr)n.chrlookup[t.toUpperCase()]={name:t,len:n.minorchr[t]}}if(n.genedb){if(!n.genedb.dbfile)throw e+": .genedb.dbfile missing";try{console.log("Connecting",n.genedb.dbfile),n.genedb.db=P.sE(n.genedb.dbfile)}catch(t){throw`Cannot connect genedb: ${n.genedb.dbfile}: ${t}`}n.genedb.getnamebynameorisoform=n.genedb.db.prepare("select name from genes where name=? or isoform=?"),n.genedb.getnamebyisoform=n.genedb.db.prepare("select distinct name from genes where isoform=?"),n.genedb.getjsonbyname=n.genedb.db.prepare("select isdefault,genemodel from genes where name=?"),n.genedb.getjsonbyisoform=n.genedb.db.prepare("select isdefault,genemodel from genes where isoform=?"),n.genedb.getnameslike=n.genedb.db.prepare("select distinct name from genes where name like ? limit 20");const t=(0,Gn.jj)(n.genedb.db);t.has("genealias")&&(n.genedb.getNameByAlias=n.genedb.db.prepare("select name from genealias where alias=?"),n.genedb.getAliasByName=n.genedb.db.prepare("select alias from genealias where name=?")),t.has("gene2coord")&&(n.genedb.getCoordByGene=n.genedb.db.prepare("select * from gene2coord where name=?")),t.has("ideogram")?(n.genedb.hasIdeogram=!0,n.genedb.getIdeogramByChr=n.genedb.db.prepare("select * from ideogram where chromosome=?")):n.genedb.hasIdeogram=!1,t.has("gene2canonicalisoform")&&(n.genedb.get_gene2canonicalisoform=n.genedb.db.prepare("select isoform from gene2canonicalisoform where gene=?")),t.has("buildDate")&&(n.genedb.get_buildDate=n.genedb.db.prepare("select date from buildDate")),n.genedb.hasTable_refseq2ensembl=t.has("refseq2ensembl"),n.genedb.sqlTables=[...t],n.genedb.tableSize={};for(const e of t)"buildDate"!=e&&(n.genedb.tableSize[e]=n.genedb.db.prepare(`select count(*) as size from ${e}`).get().size)}if(n.termdbs)for(const t in n.termdbs)(0,Gn.JV)(n.termdbs[t],uo),console.log(`${t} initiated as ${e}-level termdb`);for(const e of n.tracks)if(e.__isgene){if(!e.file)throw"Tabix file missing for gene track: "+JSON.stringify(e);try{await P.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}if(n.proteindomain){if(!n.proteindomain.dbfile)throw e+".proteindomain: missing dbfile for sqlite db";if(!n.proteindomain.statement)throw e+".proteindomain: missing statement for sqlite db";let t;try{console.log("Connecting",n.proteindomain.dbfile),t=P.sE(n.proteindomain.dbfile)}catch(t){throw"Error with "+n.proteindomain.dbfile+": "+t}n.proteindomain.getbyisoform=t.prepare(n.proteindomain.statement)}if(n.snp){if(!n.snp.bigbedfile)throw e+".snp: missing bigBed file";n.snp.bigbedfile=y().join(t.tpmasterdir,n.snp.bigbedfile),await P.Ic(n.snp.bigbedfile)}if(n.fimo_motif){if(!n.fimo_motif.db)throw e+".fimo_motif: db file missing";if(n.fimo_motif.db=y().join(t.tpmasterdir,n.fimo_motif.db),n.fimo_motif.annotationfile){const[e,r]=ei(m().readFileSync(y().join(t.tpmasterdir,n.fimo_motif.annotationfile),{encoding:"utf8"}).trim());n.fimo_motif.tf2attr={};for(const t of r)n.fimo_motif.tf2attr[t.Model.split("_")[0]]=t}}if(n.hicenzymefragment){if(!Array.isArray(n.hicenzymefragment))throw"hicenzymefragment should be an array";for(const e of n.hicenzymefragment){if(!e.enzyme)throw".enzyme missing for one element of hicenzymefragment[]";if(!e.file)throw".file missing for one element of hicenzymefragment[]";try{await P.LC(y().join(t.tpmasterdir,e.file))}catch(t){throw"Error with "+e.file+": "+t}}}if(n.hicdomain){if(!n.hicdomain.groups)throw".groups{} missing from hicdomain";for(const e in n.hicdomain.groups){const r=n.hicdomain.groups[e];if(!r.name)throw".name missing from hicdomain "+e;if(!r.sets)throw".set{} missing from hicdomain "+e;for(const n in r.sets){const o=r.sets[n];if(!o.name)throw".name missing from hicdomain "+e+" > "+n;if(!o.file)throw".file missing from hicdomain "+e+" > "+n;o.file=y().join(t.tpmasterdir,o.file);try{await P.LC(o.file)}catch(t){throw"Error with "+o.file+": "+t}}}}if(n.rawdslst){n.datasets={};for(const t of n.rawdslst){if(!t.name)throw"a nameless dataset from "+e;if(n.datasets[t.name])throw e+" has duplicating dataset name: "+t.name;if(!t.jsfile)throw"jsfile not available for dataset "+t.name+" of "+e;const r=y().join(process.cwd(),t.jsfile),o=require(m().existsSync(r)?r:t.jsfile),i="function"==typeof o?o(F):"function"==typeof(null==o?void 0:o.default)?o.default(F):o.default||o;if(Jn(i,t),i.noHandleOnClient=t.noHandleOnClient,i.label=t.name,i.genomename=e,n.datasets[i.label]=i,i.isMds3)try{await Qn(i,n,0,yo,vo)}catch(t){throw t.stack&&console.log(t.stack),"Error with mds3 dataset "+i.label+": "+t}else if(i.isMds)try{await ai(i,n,t)}catch(t){throw"Error with mds dataset "+i.label+": "+t}else oi(i,n)}ri(),delete n.rawdslst}}}async function ri(){const t=await m().promises.readdir(o().cachedir_massSession);try{t.forEach((async t=>{const e=(await m().promises.stat(y().join(o().cachedir_massSession,t))).birthtime,n=new Date,r=new Date(e),i=o().features.massSessionDuration||30;Math.round((n.getTime()-r.getTime())/864e5)>i&&(await m().promises.copyFile(y().join(o().cachedir_massSession,t),y().join(o().cachedir_massSessionTrash,t)),await m().promises.unlink(y().join(o().cachedir_massSession,t)),console.log("File deleted: ",t,e))}))}catch(t){throw`Error: ${t}`}}function oi(t,e){if(t.dbfile)try{console.log("Connecting",t.dbfile),t.newconn=P.sE(t.dbfile)}catch(e){throw"Error with "+t.dbfile+": "+e}if(t.snvindel_attributes)for(const e of t.snvindel_attributes)if(e.lst)for(const t of e.lst)t.get=t.get.toString();else e.get=e.get.toString();if(t.cohort){if(t.cohort.levels){if(!Array.isArray(t.cohort.levels))throw"cohort.levels must be array for "+t.genomename+"."+t.label;if(0==t.cohort.levels.length)throw"levels is blank array for cohort of "+t.genomename+"."+t.label;for(const e of t.cohort.levels)if(!e.k)throw".k key missing in one of the levels, .cohort, in "+t.genomename+"."+t.label}if(t.cohort.fromdb){if(!t.cohort.fromdb.sql)throw".sql missing from ds.cohort.fromdb in "+t.genomename+"."+t.label;const e=t.newconn.prepare(t.cohort.fromdb.sql).all();delete t.cohort.fromdb,t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.files){let e=[];for(const n of t.cohort.files){if(!n.file)throw".file missing from one of cohort.files[] for "+t.genomename+"."+t.label;const r=m().readFileSync(y().join(o().tpmasterdir,n.file),"utf8").trim();if(!r)throw n.file+" is empty for "+t.genomename+"."+t.label;e=[...e,...W.tJ(r)]}delete t.cohort.files,t.cohort.raw?t.cohort.raw=[...t.cohort.raw,...e]:t.cohort.raw=e,console.log(e.length+" rows retrieved for "+t.label+" sample annotation")}if(t.cohort.tosampleannotation){if(!t.cohort.tosampleannotation.samplekey)throw".samplekey missing from .cohort.tosampleannotation for "+t.genomename+"."+t.label;if(!t.cohort.key4annotation)throw".cohort.key4annotation missing when .cohort.tosampleannotation is on for "+t.genomename+"."+t.label}}if(!t.queries)throw".queries missing from dataset "+t.label+", "+t.genomename;if(!Array.isArray(t.queries))throw t.label+".queries is not array";for(const n of t.queries){const r=si(n,t,e);if(r)throw'Error parsing a query in "'+t.label+'": '+r}if(t.vcfinfofilter){const e=F.validate_vcfinfofilter(t.vcfinfofilter);if(e)throw t.label+": vcfinfofilter error: "+e}if(t.url4variant)for(const e of t.url4variant){if(!e.makelabel)throw"makelabel() missing for one item of url4variant from "+t.label;if(!e.makeurl)throw"makeurl() missing for one item of url4variant from "+t.label;e.makelabel=e.makelabel.toString(),e.makeurl=e.makeurl.toString()}}async function ii(t){const e=y().join(o().cachedir,t);try{await m().promises.stat(e)}catch(t){if("ENOENT"!=t.code)throw"error stating dir";try{await m().promises.mkdir(e)}catch(t){throw"cannot make dir"}}return e}function si(t,e,n){if(!t.name)return".name missing";if(t.dsblocktracklst){if(!Array.isArray(t.dsblocktracklst))return"dsblocktracklst not an array in "+e.label;for(const n of t.dsblocktracklst){if(!n.type)return"missing type for a blocktrack of "+e.label;if(!n.file&&!n.url)return"neither file or url given for a blocktrack of "+e.label}}else if(t.vcffile){const e=N().execSync(ho+" -H "+y().join(o().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==e)return"no meta lines in VCF file "+t.vcffile+" of query "+t.name;const[r,i,s,a]=D.e(e.split("\n"));if(a)return"error parsing VCF meta lines of "+t.vcffile+": "+a.join("; ");t.vcf={vcfid:Math.random().toString(),info:r,format:i,samples:s},t.hlinfo&&(t.vcf.hlinfo=t.hlinfo,delete t.hlinfo),t.infopipejoin&&(t.vcf.infopipejoin=t.infopipejoin,delete t.infopipejoin);const l=N().execSync(ho+" -l "+y().join(o().tpmasterdir,t.vcffile),{encoding:"utf8"}).trim();if(""==l)return"tabix -l found no chromosomes/contigs in "+t.vcffile+" of query "+t.name;t.vcf.nochr=F.contigNameNoChr(n,l.split("\n"));let c=0;if(r)for(const t in r)c++;console.log("Parsed vcf meta from "+t.vcffile+": "+c+" INFO, "+s.length+" sample, "+(t.vcf.nochr?'no "chr"':'has "chr"'))}else{if(!t.makequery)return"do not know how to parse query: "+t.name;if(t.isgeneexpression){if(!t.config)return"config object missing for gene expression query of "+t.name;t.config.maf&&(t.config.maf.get=t.config.maf.get.toString())}}}async function ai(t,e,n){if((t.isMds2||t.isMds3||t.isMds)&&Jn(t,n),t.assayAvailability){if(!t.assayAvailability.file)throw".assayAvailability.file missing";if(!t.assayAvailability.assays)throw".assayAvailability.assays[] missing";Object.freeze(t.assayAvailability.assays),t.assayAvailability.samples=new Map;for(const e of m().readFileSync(y().join(o().tpmasterdir,t.assayAvailability.file),{encoding:"utf8"}).trim().split("\n")){const[n,r]=e.split("\t");t.assayAvailability.samples.set(n,JSON.parse(r))}console.log(t.assayAvailability.samples.size+" samples with assay availability ("+t.label+")")}if(t.gene2mutcount){if(!t.gene2mutcount.dbfile)throw".gene2mutcount.dbfile missing";try{console.log("Connecting",t.gene2mutcount.dbfile),t.gene2mutcount.db=P.sE(t.gene2mutcount.dbfile),console.log("DB connected for "+t.label+": "+t.gene2mutcount.dbfile)}catch(e){throw`Error connecting db at ${t.gene2mutcount.dbfile}`}}if(t.sampleAssayTrack){if(!t.sampleAssayTrack.file)throw".file missing from sampleAssayTrack";t.sampleAssayTrack.samples=new Map;let e=0,n=new Set;for(const r of m().readFileSync(y().join(o().tpmasterdir,t.sampleAssayTrack.file),{encoding:"utf8"}).trim().split("\n")){if(!r)continue;if("#"==r[0])continue;const[o,i,s]=r.split("\t");if(!i||!s)continue;if(!t.sampleAssayTrack.samples.has(o)){if(t.cohort&&t.cohort.annotation&&!t.cohort.annotation[o]){n.add(o);continue}t.sampleAssayTrack.samples.set(o,[])}const a=JSON.parse(s);if(!F.tkt[a.type])throw"invalid type from a sample track: "+s;a.name||(a.name=o+" "+i),a.assayName=i,t.sampleAssayTrack.samples.get(o).push(a),e++}console.log(e+" assay-tracks from "+t.sampleAssayTrack.samples.size+" samples ("+t.label+")"),n.size&&console.log("Error: "+n.size+" samples with assay tracks are unannotated: "+[...n].join(" "))}if(t.singlesamplemutationjson){const e=t.singlesamplemutationjson;if(!e.file)throw".file missing from singlesamplemutationjson";e.samples={};let n=0;for(const t of m().readFileSync(y().join(o().tpmasterdir,e.file),{encoding:"utf8"}).trim().split("\n")){if(!t)continue;if("#"==t[0])continue;const[r,o]=t.split("\t");r&&o&&(n++,e.samples[r]=o)}console.log(n+" samples for disco plot")}if(t.cohort&&t.cohort.db&&t.cohort.termdb&&await kr(t,yo,vo),t.cohort&&t.cohort.files){if(!Array.isArray(t.cohort.files))throw".cohort.files is not array";if(!t.cohort.tohash)throw".tohash() missing from cohort";if("function"!=typeof t.cohort.tohash)throw".cohort.tohash is not function";if(!t.cohort.samplenamekey)throw".samplenamekey missing";if(t.cohort.annotation={},t.cohort.mutation_signature){const e=t.cohort.mutation_signature;if(!e.sets)throw".mutation_signature.sets missing";for(const n in e.sets){const r=e.sets[n];if(r.name||(r.name=n),!r.signatures)throw".signatures{} missing from a signature set";if(r.samples){if(!r.samples.file)throw".samples.file missing from a signature set";const[e,n]=ei(m().readFileSync(y().join(o().tpmasterdir,r.samples.file),{encoding:"utf8"}).trim());r.samples.map=new Map;for(const e of n){const n=e[t.cohort.samplenamekey];if(!n)throw t.cohort.samplenamekey+" missing in file "+r.samples.file;r.samples.map.set(n,e);for(const t in r.signatures)if(e[t]){const o=Number.parseFloat(e[t]);if(Number.isNaN(o))throw"mutation signature value is not float: "+e[t]+" from sample "+n;r.samples.skipzero&&0==o?delete e[t]:e[t]=o}}}}}if(t.cohort.attributes){if(!t.cohort.attributes.lst)throw".lst[] missing for cohort.attributes";if(!Array.isArray(t.cohort.attributes.lst))return".cohort.attributes.lst is not array";for(const e of t.cohort.attributes.lst){if(!e.key)throw".key missing from one of the .cohort.attributes.lst[]";if(!e.label)throw".label missing from one of the .cohort.attributes.lst[]";if(!e.values)throw".values{} missing from "+e.label+" of .cohort.attributes.lst";for(const t in e.values)if(!e.values[t].label)throw".label missing from one value of "+e.label+" in .cohort.attributes.lst"}if(t.cohort.attributes.defaulthidden)for(const e in t.cohort.attributes.defaulthidden){const n=t.cohort.attributes.lst.find((t=>t.key==e));if(!n)throw"invalid defaulthidden key: "+e;for(const r in t.cohort.attributes.defaulthidden[e])if(!n.values[r])throw"invalid defaulthidden value "+r+" for "+e}}if(t.cohort.hierarchies){if(!t.cohort.hierarchies.lst)throw".lst[] missing from .cohort.hierarchies";if(!Array.isArray(t.cohort.hierarchies.lst))throw".cohort.hierarchies.lst is not array";for(const e of t.cohort.hierarchies.lst){if(!e.name)throw".name missing from one hierarchy";if(!e.levels)throw".levels[] missing from one hierarchy";if(!Array.isArray(e.levels))throw".levels is not array from one hierarchy";for(const t of e.levels)if(!t.k)throw".k missing from one level in hierarchy "+e.name}}if(t.cohort.sampleAttribute){if(!t.cohort.sampleAttribute.attributes)throw"attributes{} missing from cohort.sampleAttribute";for(const e in t.cohort.sampleAttribute.attributes){const n=t.cohort.sampleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from cohort.sampleAttribute.attributes";if(n.values)for(const t in n.values){const e=n.values[t];if("object"!=typeof e)throw'value "'+t+'" not pointing to {} from sampleAttribute';e.name||(e.name=t)}if(n.showintrack&&!n.isinteger&&!n.isfloat)throw n.label+": .showintrack requires .isinteger or .isfloat"}}if(t.cohort.scatterplot){if(!t.cohort.sampleAttribute)throw".sampleAttribute missing but required for .cohort.scatterplot";const e=t.cohort.scatterplot;if(!e.querykey)throw".querykey missing from .cohort.scatterplot";{if(!t.queries)throw".cohort.scatterplot.querykey in use but ds.queries{} missing";const n=t.queries[e.querykey];if(!n)throw"unknown query by .cohort.scatterplot.querykey: "+e.querykey;if(n.type!=F.tkt.mdssvcnv)throw"type is not "+F.tkt.mdssvcnv+" of the track pointed to by .cohort.scatterplot.querykey"}if(e.colorbygeneexpression){if(!e.colorbygeneexpression.querykey)throw"querykey missing from .cohort.scatterplot.colorbygeneexpression";if(!t.queries)throw".cohort.scatterplot.colorbygeneexpression in use but ds.queries{} missing";const n=t.queries[e.colorbygeneexpression.querykey];if(!n)throw"unknown query by .cohort.scatterplot.colorbygeneexpression.querykey: "+e.colorbygeneexpression.querykey;if(!n.isgenenumeric)throw"isgenenumeric missing from the track pointed to by .cohort.scatterplot.colorbygeneexpression.querykey"}if(e.tracks,!e.x)throw".x missing from .cohort.scatterplot";if(!e.x.attribute)throw".attribute missing from .cohort.scatterplot.x";const n=t.cohort.sampleAttribute.attributes[e.x.attribute];if(!n)throw"scatterplot.x.attribute is not defined in sampleAttribute";if(!n.isfloat)throw'scatterplot.x is not "isfloat"';if(!e.y)throw".y missing from .cohort.scatterplot";if(!e.y.attribute)throw".attribute missing from .cohort.scatterplot.y";const r=t.cohort.sampleAttribute.attributes[e.y.attribute];if(!r)throw"scatterplot.y.attribute is not defined in sampleAttribute";if(!r.isfloat)throw'scatterplot.y is not "isfloat"';if(e.colorbyattributes)for(const n of e.colorbyattributes){if(!n.key)throw".key missing from one of scatterplot.colorbyattributes";const e=t.cohort.sampleAttribute.attributes[n.key];if(!e)throw"unknown attribute by key "+n.key+" from scatterplot.colorbyattributes";n.label=e.label,n.values=e.values}}for(const e of t.cohort.files){if(!e.file)throw".file missing from one of .cohort.files";const[n,r]=ei(m().readFileSync(y().join(o().tpmasterdir,e.file),{encoding:"utf8"}).trim());if(n)throw'cohort annotation file "'+e.file+'": '+n;console.log(t.label+": "+r.length+" samples loaded from annotation file "+e.file),r.forEach((e=>{for(const n in e){let r;t.cohort.sampleAttribute&&(r=t.cohort.sampleAttribute.attributes[n]),r||t.cohort.termdb&&t.cohort.termdb.termjson&&t.cohort.termdb.termjson.map&&(r=t.cohort.termdb.termjson.map.get(n)),r&&(r.isfloat?e[n]=Number.parseFloat(e[n]):r.isinteger&&(e[n]=Number.parseInt(e[n])))}t.cohort.tohash(e,t)}))}if(t.cohort.annorows=Object.values(t.cohort.annotation),console.log(t.label+": total samples from sample table: "+t.cohort.annorows.length),t.cohort.survivalplot){const e=t.cohort.survivalplot;if(!e.plots)throw".plots{} missing from survivalplot";e.init={plottypes:[]};for(const t in e.plots){const n=e.plots[t];if(!n.name)throw".name missing from survivalplot "+t;if(!n.serialtimekey)throw".serialtimekey missing from survivalplot "+t;if(!n.iscensoredkey)throw".iscensoredkey missing from survivalplot "+t;if(!n.timelabel)throw".timelabel missing from survivalplot "+t;n.key=t,e.init.plottypes.push({key:t,name:n.name,timelabel:n.timelabel})}if(e.samplegroupattrlst){e.init.samplegroupings=[];for(const n of e.samplegroupattrlst){if(!n.key)throw".key missing from an attr of samplegroupattrlst for survival";const r=t.cohort.sampleAttribute.attributes[n.key];if(!r)throw'unknown attribute key "'+n.key+'" from survival samplegroupattrlst';const o=new Map;for(const r in t.cohort.annotation){const i=t.cohort.annotation[r],s=i[n.key];if(null==s)continue;let a=!1;for(const t in e.plots)if(null!=i[e.plots[t].serialtimekey]){a=!0;break}a&&(o.has(s)?o.set(s,o.get(s)+1):o.set(s,1))}if(0==o.size)throw'no value found for "'+n.key+'" from survival samplegroupattrlst';const i=[];for(const[t,e]of o)i.push({value:t,count:e});e.init.samplegroupings.push({key:n.key,label:r.label,values:i})}}}}if(t.mutationAttribute){if(!t.mutationAttribute.attributes)throw"attributes{} missing from mutationAttribute";for(const e in t.mutationAttribute.attributes){const n=t.mutationAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from mutationAttribute.attributes";if(!n.appendto_link&&n.values)for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from mutationAttribute.attributes"}}}if(t.alleleAttribute){if(!t.alleleAttribute.attributes)throw"attributes{} missing from alleleAttribute";for(const e in t.alleleAttribute.attributes){const n=t.alleleAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from alleleAttribute.attributes";if(!n.isnumeric){if(!n.values)throw".values{} missing for non-numeric key "+e+" from alleleAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from alleleAttribute.attributes"}}}}if(t.locusAttribute){if(!t.locusAttribute.attributes)throw"attributes{} missing from locusAttribute";for(const e in t.locusAttribute.attributes){const n=t.locusAttribute.attributes[e];if(!n.label)throw".label missing for key "+e+" from locusAttribute.attributes";if(!n.isnumeric&&!n.appendto_link){if(!n.values)throw".values{} missing for non-numeric key "+e+" from locusAttribute.attributes";for(const t in n.values){if(!n.values[t].name)throw".name missing for value "+t+" of key "+e+" from locusAttribute.attributes"}}}}if(t.queries)for(const r in t.queries){if(n.remove_queries&&-1!=n.remove_queries.indexOf(r)){delete t.queries[r];continue}const o=t.queries[r];if(n.hide_queries&&-1!=n.hide_queries.indexOf(r)&&(o.hideforthemoment=1),o.istrack){if(!o.type)throw".type missing for track query "+r;if(o.viewrangeupperlimit&&!Number.isInteger(o.viewrangeupperlimit))throw".viewrangeupperlimit should be integer for track query "+r;if(o.type==F.tkt.mdsjunction){const n=ci(o,t,e);if(n)throw r+" (mdsjunction) error: "+n}else if(o.type==F.tkt.mdscnv){const n=di(o,t,e);if(n)throw r+" (mdscnv) error: "+n}else if(o.type==F.tkt.mdssvcnv){const n=hi(o,t,e);if(n)throw r+" (svcnv) error: "+n}else{if(o.type!=F.tkt.mdsvcf)throw"unknown track type for a query: "+o.type+" "+r;{const n=await mi(o,t,e);if(n)throw r+" (vcf) error: "+n}}li(o,t)}else{if(!o.isgenenumeric)throw"unknown type of query from "+r;{const n=pi(o,t,e);if(n)throw r+" (genenumeric) error: "+n}}}if(t.track&&await qr(t,e),t.annotationsampleset2matrix){if(!t.cohort)throw"ds.cohort misssing when annotationsampleset2matrix is in use";if(!t.cohort.annotation)throw"ds.cohort.annotation misssing when annotationsampleset2matrix is in use";if(!t.queries)throw"ds.queries misssing when annotationsampleset2matrix is in use";if(!t.annotationsampleset2matrix.key)throw".key STR missing in annotationsampleset2matrix";if(!t.annotationsampleset2matrix.groups)throw".groups{} missing in annotationsampleset2matrix";if("object"!=typeof t.annotationsampleset2matrix.groups)throw"ds.annotationsampleset2matrix.groups{} not an object";for(const e in t.annotationsampleset2matrix.groups){const n=t.annotationsampleset2matrix.groups[e];if(!n.groups||!Array.isArray(n.groups)||0==n.groups.length)throw".groups[] must be nonempty array in "+e;for(const r of n.groups){if(!r.name)throw".name missing from one of .groups[] in "+e;const n=r.matrixconfig;if(!n)throw".matrixconfig missing from one of .groups[] of "+e;if(!n.features)throw".features[] missing from group "+e;if(!Array.isArray(n.features))throw".features[] should be array from group "+e;if(0==n.features.length)throw".features[] zero length from group "+e;for(const r of n.features){if(t.annotationsampleset2matrix.commonfeatureattributes)for(const e in t.annotationsampleset2matrix.commonfeatureattributes)null==r[e]&&(r[e]=t.annotationsampleset2matrix.commonfeatureattributes[e]);if(!r.ismutation)return"unknown feature type from group "+e;if(!r.position)throw"position missing from feature "+JSON.stringify(r)+" from group "+e;if(!r.querykeylst)throw".querykeylst[] missing from ismutation feature from group "+e;if(!Array.isArray(r.querykeylst))throw".querykeylst[] not an array from ismutation feature from group "+e;if(0==r.querykeylst.length)throw".querykeylst[] zero length from ismutation feature from group "+e;for(const n of r.querykeylst)if(!t.queries[n])throw'unknown query key "'+n+'" from ismutation feature of group '+e}if(!n.limitsamplebyeitherannotation)throw".limitsamplebyeitherannotation[] missing from group "+e;if(!Array.isArray(n.limitsamplebyeitherannotation))throw".limitsamplebyeitherannotation[] should be array from group "+e;if(0==n.limitsamplebyeitherannotation.length)throw".limitsamplebyeitherannotation[] zero length from group "+e;for(const t of n.limitsamplebyeitherannotation){if(!t.key)throw"key missing from one of limitsamplebyeitherannotation from group "+e;if(!t.value)throw"value missing from one of limitsamplebyeitherannotation from group "+e}}}delete t.annotationsampleset2matrix.commonfeatureattributes}}function li(t,e){if(t.groupsamplebyattr){t.groupsamplebyattr.key2group=new Map;for(const n in e.cohort.annotation)Po(n,[],t.groupsamplebyattr.key2group,[],e,t)}}function ci(t,e,n){if(t.readcountCutoff&&(!Number.isInteger(t.readcountCutoff)||t.readcountCutoff<1))return"readcountCutoff must be positive integer";let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;t.file=n,r=n}else{if(!t.url)return"no file or url given for mdsjunction "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=i.split("\n");if(1!=n.length)return"mdsjunction file has multiple header lines (begin with #), but should have just 1";const r=n[0].split("\t");if(r[5]){t.samples=r.slice(5),t.attributeSummary=ui(t.samples,e),t.hierarchySummary=fi(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}if(console.log("(mdsjunction) "+t.name+": "+(t.samples?t.samples.length:0)+" samples, "+(t.nochr?'no "chr"':'has "chr"')),!t.infoFilter)return".infoFilter{} missing";if(!t.infoFilter.lst)return".lst[] missing from .infoFilter";for(const e of t.infoFilter.lst){if(!e.key)return".key missing from one of infoFilter";if(!e.label)return".label missing from one of infoFilter";if(!e.categories)return".categories missing from one of infoFilter";for(const t in e.categories){if(!e.categories[t].label)return".label missing from one category of "+e.label;if(!e.categories[t].color)return".color missing from on category of "+e.label}if(e.hiddenCategories){for(const t in e.hiddenCategories)if(!e.categories[t])return"invalid hidden key "+t+" of "+e.label}else e.hiddenCategories={}}if(!t.singlejunctionsummary)return".singlejunctionsummary missing but is currently required from "+t.name;if(t.singlejunctionsummary.readcountboxplotpercohort){if(!t.singlejunctionsummary.readcountboxplotpercohort.groups)return".groups[] missing from query.singlejunctionsummary.readcountboxplotpercohort for "+t.name;for(const e of t.singlejunctionsummary.readcountboxplotpercohort.groups){if(!e.key)return".key missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups";if(!e.label)return".label missing from one group of query.singlejunctionsummary.readcountboxplotpercohort.groups"}}}function ui(t,e){if(!(e.cohort&&e.cohort.annotation&&e.cohort.attributes&&t))return;const n={};for(const r of e.cohort.attributes.lst){const o={};for(const t in r.values)o[t]=0;for(const n of t){const t=e.cohort.annotation[n];if(!t)continue;const i=t[r.key];null!=i&&(i in o&&o[i]++)}n[r.key]=o}return n}function fi(t,e){if(!e.cohort||!e.cohort.annotation||!e.cohort.hierarchies||0==t.length)return;const n=[];for(const r of t){const t=e.cohort.annotation[r];t&&n.push(t)}const r={};for(const t of e.cohort.hierarchies.lst){const e=(0,A.N)(n,t.levels),o=(0,V.Z)()(e);o.sum((t=>t.value));const i={};o.eachBefore((t=>{i[t.id]=t.value})),r[t.name]=i}return r}function di(t,e,n){let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (mdscnv) "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=i.split("\n");if(1!=n.length)return"mdscnv file has multiple header lines (begin with #), but should have just 1";const r=n[0].split("\t");t.samples=r.slice(5),t.attributeSummary=ui(t.samples,e),t.hierarchySummary=fi(t.samples,e);for(const e in t.hierarchySummary){let n=0;for(const r in t.hierarchySummary[e])n++;console.log(n+" "+e+" hierarchy levels for "+t.name)}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function hi(t,e,n){let r;if(t.file){const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}else{if(!t.url)return"no file or url given for (svcnv) "+t.name;r=t.url}const o={encoding:"utf8"};const i=N().execSync(ho+" -H "+r,o).trim();if(i){const n=new Set;for(const t of i.split("\n"))for(const e of t.split(" ").slice(1))n.add(e);if(0==n.size)return"no samples from the header line";if(t.samples=[...n],e.cohort&&e.cohort.annotation){const n=new Set;for(const r of t.samples)e.cohort.annotation[r]||n.add(r);n.size&&console.log("mdssvcnv unannotated samples: "+(t.noprintunannotatedsamples?n.size:[...n].join(" ")))}}{const e=N().execSync(ho+" -l "+r,o).trim();if(!e)return"no chromosomes found";t.nochr=F.contigNameNoChr(n,e.split("\n"))}if(t.expressionrank_querykey){const n=e.queries[t.expressionrank_querykey];if(!n)return"invalid key by expressionrank_querykey";if(!n.isgenenumeric)return"query "+t.expressionrank_querykey+" not tagged as isgenenumeric"}if(t.vcf_querykey){const n=e.queries[t.vcf_querykey];if(!n)return"invalid key by vcf_querykey";if(n.type!=F.tkt.mdsvcf)return"query "+t.vcf_querykey+" not of mdsvcf type"}if(t.groupsamplebyattr){if(!t.groupsamplebyattr.attrlst)return".attrlst[] missing from groupsamplebyattr";if(0==t.groupsamplebyattr.attrlst.length)return"groupsamplebyattr.attrlst[] empty array";if(!e.cohort)return"groupsamplebyattr in use but ds.cohort missing";if(!e.cohort.annotation)return"groupsamplebyattr in use but ds.cohort.annotation missing";e.cohort.sampleAttribute||(e.cohort.sampleAttribute={}),e.cohort.sampleAttribute.attributes||(e.cohort.sampleAttribute.attributes={},console.log("cohort.sampleAttribute added when groupsamplebyattr is in use"));for(const n of t.groupsamplebyattr.attrlst){if(!n.k)return"k missing from one of groupsamplebyattr.attrlst[]";e.cohort.sampleAttribute.attributes[n.k]||(e.cohort.sampleAttribute.attributes[n.k]={label:n.label||n.k})}if(t.groupsamplebyattr.sortgroupby){if(!t.groupsamplebyattr.sortgroupby.key)return".key missing from .sortgroupby";if(!t.groupsamplebyattr.sortgroupby.order)return".order[] missing from .sortgroupby";if(!Array.isArray(t.groupsamplebyattr.sortgroupby.order))return".order must be an array"}t.groupsamplebyattr.attrnamespacer||(t.groupsamplebyattr.attrnamespacer=", ")}console.log("("+t.type+") "+t.name+": "+(t.samples?t.samples.length:"no")+" samples, "+(t.nochr?'no "chr"':'has "chr"'))}function pi(t,e,n){if(!t.datatype)return"datatype missing";if(t.viewrangeupperlimit&&Number.isNaN(t.viewrangeupperlimit))return"invalid value for viewrangeupperlimit";let r;if(!t.file)return"file missing";{const[e,n]=ti(t.file);if(e)return"tabix file error: "+e;r=n}const o={cwd:null,encoding:"utf8"};{const e=N().execSync(ho+" -H "+r,o).trim();if(!e)return"no header line (#sample <sample1> ...)";const n=new Set;for(const t of e.split("\n")){const e=t.split(" ");for(let t=1;t<e.length;t++)n.add(e[t])}if(0==n.size)return"no sample names from header line";t.samples=[...n],console.log("(genenumeric) "+t.name+": "+t.samples.length+" samples")}if(t.boxplotbysamplegroup){if(!t.boxplotbysamplegroup.attributes)return"boxplotbysamplegroup.attributes missing";if(!Array.isArray(t.boxplotbysamplegroup.attributes))return"boxplotbysamplegroup.attributes should be array";for(const e of t.boxplotbysamplegroup.attributes)if(!e.k)return"k missing from one of boxplotbysamplegroup.attributes[]"}}async function mi(t,e,n){if(!t.tracks)return"tracks[] missing";if(!Array.isArray(t.tracks))return"tracks should be array";t.info={};for(const r of t.tracks){if(!r.file)return"file missing from a track (url not supported yet)";const[o,i]=ti(r.file);if(o)return"tabix file error: "+o;if(r.type!=F.mdsvcftype.vcf)return"invalid track type: "+r.type;{r.cwd;const e=await P.ZD(i,r.cwd);if(0==e.length)return"no meta/header lines for "+i;const[n,o,s,a]=D.e(e);if(a)return"error parsing vcf meta for "+i+": "+a.join("\n");if(0==s.length)return"vcf file has no sample: "+i;for(const e in n)t.info[e]=n[e];if(r.format=o,r.samplenameconvert){if("function"!=typeof r.samplenameconvert)return".samplenameconvert must be function";for(const t of s)t.name=r.samplenameconvert(t.name)}r.samples=s}if(e.cohort&&e.cohort.annotation){const t=[];for(const n of r.samples)e.cohort.annotation[n.name]||t.push(n.name);t.length&&console.log(e.label+": VCF "+r.file+" has unannotated samples: "+t.join(","))}{const t=[];if(await P.UE({args:["-l",i],dir:r.cwd,callback:e=>{t.push(e)}}),0==t.length)return"no chr from "+i;r.nochr=F.contigNameNoChr(n,t)}console.log("("+t.type+") "+i+": "+r.samples.length+" samples, "+(r.nochr?"no chr":"has chr"))}if(t.singlesamples){if(!t.singlesamples.tablefile)return".singlesamples.tablefile missing for the VCF query";t.singlesamples.samples={};let e=0;for(const n of m().readFileSync(y().join(o().tpmasterdir,t.singlesamples.tablefile),{encoding:"utf8"}).trim().split("\n")){if(!n)continue;if("#"==n[0])continue;const r=n.split("\t");r[0]&&r[1]&&(t.singlesamples.samples[r[0]]=r[1],e++)}console.log(e+" single-sample VCF files")}}},6191:(t,e,n)=>{"use strict";n.d(e,{i:()=>y});var r=n(7147),o=n(1017),i=n.n(o),s=n(9344),a=n.n(s),l=n(8088);async function c(t,e){!function(t){for(const e in t){const n=t[e];if("login"==n.type){if(n.embedders)throw"unexpected 'embedders' property";n["*"]={"*":{type:"basic",password:n.password,secret:n.secret}},delete n.type,delete n.password}else if("jwt"==n.type){for(const t in n.embedders)n.termdb={[t]:Object.assign({type:n.type},n.embedders[t])},n.headerKey&&(n.termdb[t].headerKey=n.headerKey);delete n.type,delete n.embedders,delete n.headerKey}else if(n.type)throw`unknown legacy credentials type='${n.type}'`}}(t);const n="secrets";if("string"==typeof t[n]){const e=await r.promises.readFile(t[n],"utf8");t[n]=JSON.parse(e)}for(const e in t){const n=t[e];n["*"]&&(n["/**"]=n["*"],delete n["*"]);const r=n.headerKey||"x-ds-access-token";delete n.headerKey;for(const o in n){const i=n[o];for(const n in i){i[n]=JSON.parse(JSON.stringify(i[n]));const s=i[n],a="string"==typeof s?t.secrets[s]:s;if("basic"==a.type)a.secret||(a.secret=a.password),a.authRoute="/dslogin";else if("jwt"==a.type)a.authRoute="/jwt-status",a.headerKey||(a.headerKey=r);else if("forbidden"!=a.type&&"open"!=a.type)throw`unknown cred.type='${a.type}' for dsCredentials[${e}][${n}][${o}]`;a.dslabel=e,a.route=o,a.cookieId="termdb"==o&&a.headerKey||`${e}-${o}-${n}-Id`}}}}const u={termdb:["matrix"],samples:["singleSampleData","getAllSamples","scatter","convertSampleId","getAllSamplesByName"]};function f(t,e){var n,r,o,i;return(null===(n=t.cookies)||void 0===n?void 0:n[`${null==e?void 0:e.cookieId}`])||(null===(r=t.cookies)||void 0===r?void 0:r[`${t.query.dslabel}SessionId`])||(null===(o=t.headers)||void 0===o?void 0:o["x-sjppds-sessionid"])||(null===(i=t.query)||void 0===i?void 0:i["x-sjppds-sessionid"])}async function d(t,e,n,o,i,s,l=""){if(o.secret)try{const c=Date.now(),u=Math.floor(c/1e3),f={dslabel:e.dslabel,id:n,iat:u,time:c,ip:t.ip,embedder:e.embedder,route:o.route,exp:u+Math.floor(i/1e3),email:l};o.dsnames&&(f.datasets=o.dsnames.map((t=>t.id)));const d=a().sign(f,o.secret);return await r.promises.appendFile(s,`${e.dslabel}\t${n}\t${c}\t${l}\t${t.ip}\t${e.embedder}\t${o.route}\n`),d}catch(t){throw t}}function h(t,e,n,r,o){var i;if(!r.headers.authorization||n&&null!==(i=t[e])&&void 0!==i&&i[n])return;if(!o.secret)throw{status:"error",error:`no credentials set up for this embedder='${r.query.embedder}'`,code:403};const[s,c]=r.headers.authorization.split(" ");if("bearer"!=s.toLowerCase())throw`unsupported authorization type='${s}', allowed: 'Bearer'`;const u=Buffer.from(c,"base64").toString();try{var f;const i=a().verify(u,o.secret);if(n&&i.id!=n&&(null===(f=r.headers)||void 0===f?void 0:f["x-sjppds-sessionid"])!=i.id)return;t[e]||(t[e]={});const s="/"!=r.path[0]||o.route.startsWith("/")?r.path:r.path.slice(1);if((0,l.isMatch)(s,o.route)||"authorizedActions"==s)return t[e][i.id]=i,i.id}catch(t){return}}async function p(t,e,n,o,i,s,a){const l=Date.now(),c=Math.random().toString()+"."+l.toString().slice(4),u=s.ip;return n[t.dslabel]||(n[t.dslabel]={}),n[t.dslabel][c]={id:c,time:l,email:i,ip:u},await r.promises.appendFile(o,`${t.dslabel}\t${c}\t${l}\t${i}\t${u}\t${t.embedder}\t${a.route}\n`),a.cookieMode&&"set-cookie"!=a.cookieMode||e.header("Set-Cookie",`${a.cookieId}=${c}; HttpOnly; SameSite=None; Secure`),c}function m(t,e,n,r,o=null){var i;if(!n)return;if(!t.embedder)throw"missing q.embedder";const s=n.secret;if(!s)throw{status:"error",error:"no credentials set up for this embedder",code:403};const l=Math.floor((r||Date.now())/1e3),c=e[n.headerKey];if(!c)throw`missing header['${n.headerKey}']`;const u=n.processor?require(n.processor):{},f=(null===(i=u.handleToken)||void 0===i?void 0:i.call(u,c))||c,d=a().verify(f,s);if(o)return{iat:d.iat,email:d.email,ip:d.ip};if(u.handlePayload)try{u.handlePayload(n,d,l)}catch(t){if("bad decrypt"==t.reason)throw`Please login again to access this feature. (${t.reason})`;throw t}if(l>d.exp)throw"Please login again to access this feature. (expired token)";const h=(n.dsnames||[t.dslabel]).filter((t=>{var e;return!(null!==(e=d.datasets)&&void 0!==e&&e.includes(t.id))})).map((t=>t.id));if(h.length)throw{error:"Missing access",linkKey:h.join(",")};return{iat:d.iat,email:d.email,ip:d.ip}}function g(t,e,n){var r,o,i;if(!n.looseIpCheck||(null===(r=t.ip)||void 0===r||!r.includes(":"))&&e){if(!e)throw"Server error: missing ip address in saved session";if(t.ip!=e&&(null===(o=t.ips)||void 0===o?void 0:o[0])!=e&&(null===(i=t.connection)||void 0===i?void 0:i.remoteAddress)!=e)throw"Your connection has changed, please refresh your page or sign in again."}}const y={maySetAuthRoutes:async function(t,e="",o=null){var s;const v=o||n(334),b=(null===(s=v.features)||void 0===s?void 0:s.sessionTracking)||"",w=i().join(v.cachedir,"dsSessions"),_=i().join(v.cachedir,"authorizedActions"),x=v.dsCredentials||{};delete v.dsCredentials;const k=v.maxSessionAge||576e5;let q;if(!x||!Object.keys(x).length)return y.getDsAuth=()=>[],y.getForbiddenRoutesForDsEmbedder=()=>[],y.userCanAccess=()=>!0,y.getRequiredCredForDsEmbedder=()=>{},void(y.getPayloadFromHeaderAuth=()=>({}));try{c(x)}catch(t){throw t}function N(t,e,n){if(!t.dslabel)return;const r=x[t.dslabel]||x["*"];if(r){if("/jwt-status"==e){const e=r[t.route]||r.termdb||r["/**"];return e&&(e[t.embedder]||e["*"])}if("/dslogin"==e){const e=r[t.route]||r["/**"];return e&&(e[t.embedder]||e["*"])}if(e.startsWith("/termdb")&&r.termdb){const e=r.termdb;return(n||u.termdb).includes(t.for)&&(e[t.embedder]||e["*"])}if(e.startsWith("/burden")&&r.burden)return r.burden[t.embedder]||r.burden["*"]}for(const n in x){if(n!=t.dslabel&&"*"!=n)continue;const r=x[n];for(const n in r){const o=r[n].routePattern||n;if(!(0,l.isMatch)(e,o))continue;const i=r[n];for(const e in i)if(e==t.embedder||"*"==e)return i[e]}}}t.use(((t,e,n)=>{if("/dslogin"==t.path||"/jwt-status"==t.path||"/dslogout"==t.path)return void n();const r=t.query,o=N(r,t.path);if(!o)return void n();let i;"jwt-only"==b&&(q={});try{var s,a;const l=f(t,o);let c;if(!l){if("OPTIONS"==t.method.toUpperCase())return e.status(204),void e.send();if(c=h(q,r.dslabel,l,t,o),!c)throw i=401,"missing session cookie"}c||(c=h(q,r.dslabel,l,t,o));const u=(null===(s=q[r.dslabel])||void 0===s?void 0:s[l])||(null===(a=q[r.dslabel])||void 0===a?void 0:a[c]);if(!u)throw i=401,"unestablished or expired browser session";g(t,u.ip,o);const d=Date.now();if(d-u.time>k){const{iat:e}=m(r,t.headers,o,u),n=d-e;if(n>k)throw delete q[r.dslabel][l],"Please login again to access this feature. (expired session)";if(n<3e5)return void(u.time=d)}u.time-d<900&&(u.time=d),n()}catch(t){console.log(t);const n=t.code||i;n&&e.status(n),e.send("object"==typeof t?t:{error:t})}}));try{q=await async function(t,e,n){const o={};for(const e in t)o[e]||(o[e]={});try{const t=await r.promises.readFile(e,"utf8"),i=+new Date;for(const e of t.split("\n")){if(!e)continue;const[t,r,s,a,l]=e.split("\t"),c=Number(s);o[t]||(o[t]={}),i-c<n&&(o[t][r]={id:r,time:c,email:a,ip:l})}return o}catch(t){return(0,r.existsSync)(e)&&console.log(t),o}}(x,w,k);const t=[];for(const e in q)for(const n in q[e]){const r=q[e][n];t.push(`${r.dslabel}\t${r.id}\t${r.time}\t${r.email}\t${r.ip}\t${r.embedder}\t${r.route}`)}await r.promises.writeFile(w,t.join("\n"))}catch(t){throw t}var S;await(S=0,new Promise((t=>setTimeout(t,S)))),t.post(e+"/dslogin",(async(t,e)=>{let n=401;try{const r=t.query,o=N(r,t.path);if(!o)throw n=400,`No login required for dataset='${r.dslabel}'`;if("/dslogin"!=o.authRoute)throw n=400,`Incorrect authorization route, use '${o.authRoute}'`;if(!t.headers.authorization)throw"missing authorization header";const[i,s]=t.headers.authorization.split(" ");if("basic"!=i.toLowerCase())throw`unsupported authorization type='${i}', allowed: 'Basic'`;if(Buffer.from(s,"base64").toString()!=o.password)throw"invalid password";const a=await p(r,e,q,w,"",t,o);n=401;const l=await d(t,r,a,o,k,w);e.send({status:"ok",jwt:l,route:o.route})}catch(t){e.status(n),e.send({error:t})}})),t.post(e+"/dslogout",(async(t,e)=>{try{var n;const o=t.query,i=f(t,N(o,t.path));if(!i)throw"missing session cookie";const s=null===(n=q[o.dslabel])||void 0===n?void 0:n[i];if(!s)return void e.send({status:"ok"});delete q[o.dslabel][i];t.ip;await r.promises.appendFile(w,`${o.dslabel}\t${i}\t0\t\t${s.ip}\t${s.embedder}\t${s.route}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send({error:t})}})),t.post(e+"/jwt-status",(async(t,e)=>{let n=401;try{const r=t.query,o=N(r,t.path);if(!o)return void e.send({status:"ok"});if("/jwt-status"!=o.authRoute)throw n=400,`Incorrect authorization route, use ${o.authRoute}'`;const{email:i,ip:s}=await m(r,t.headers,o);g(t,s,o);const a=await p(r,e,q,w,i,t,o);n=401;const l=await d(t,r,a,o,k,w,i);e.send({status:"ok",jwt:l,route:o.route,[o.cookieId]:a})}catch(t){console.log(t),e.status(n),e.send(t instanceof Error||"object"!=typeof t?{error:t}:t)}})),t.post(e+"/authorizedActions",(async(t,e)=>{const n=t.query;try{var o,i;const s=N(n,"termdb");if(!s)return void e.send({status:"ok"});const a=f(t),l=h(q,n.dslabel,a,t,s),c=(null===(o=q[n.dslabel])||void 0===o?void 0:o[a])||(null===(i=q[n.dslabel])||void 0===i?void 0:i[l]),{email:u}=c.email,d=new Date;await r.promises.appendFile(_,`${n.dslabel}\t${u}\t${d}\t${n.action}\t${JSON.stringify(n.details)}\n`),e.send({status:"ok"})}catch(t){e.status(401),e.send("object"==typeof t?t:{error:t})}})),y.getDsAuth=function(t){const e=[],n=t.query.embedder||t.get("host").split(":")[0];for(const o in x){if(o.startsWith("__"))continue;const i=x[o];for(const s in i){const a=i[s];for(const i in a){var r;if(!(0,l.isMatch)(n,i))continue;const c=a[i],u=f({query:Object.assign({},t.query,{dslabel:o}),headers:t.headers,cookies:t.cookies},c),d=null===(r=q[o])||void 0===r?void 0:r[u],h=(null==d?void 0:d.time)||0;e.push({dslabel:o,route:s,type:c.type||"basic",insession:("basic"!=c.type||!t.path.startsWith("/genomes"))&&(("jwt"!=c.type||u)&&Date.now()-h<k)})}}}return e},y.getForbiddenRoutesForDsEmbedder=function(t,e){const n=[],r=x[t]||x["*"];if(!r)return n;for(const t in r){const o=r[t][e]||r[t]["*"];"forbidden"==(null==o?void 0:o.type)&&n.push(t)}return n},y.getRequiredCredForDsEmbedder=function(t,e){const n=[];for(const r in x)if((0,l.isMatch)(t,r))for(const t in x[r])for(const o in x[r][t]){if(!(0,l.isMatch)(e,o))continue;const i=x[r][t][o];n.push({route:t,type:i.type,headerKey:i.headerKey})}return n},y.userCanAccess=function(t,e){var n,r;const o=N(t.query,t.path,u.samples);if(!o)return!0;if("basic"==o.type&&t.path.startsWith("/genomes"))return!1;const i=f(t,o),s=h(q,e.label,i,t,o),a=(null===(n=q[e.label])||void 0===n?void 0:n[i])||(null===(r=q[e.label])||void 0===r?void 0:r[s]),l=(null==a?void 0:a.time)||0;return Date.now()-l<k},y.getPayloadFromHeaderAuth=function(t,e){var n;if(null===(n=t.headers)||void 0===n||!n.authorization)return{};const r=N(t.query,e);if(!r)return{};const[o,i]=t.headers.authorization.split(" ");if("bearer"!=o.toLowerCase())throw`unsupported authorization type='${o}', allowed: 'Bearer'`;const s=Buffer.from(i,"base64").toString();return a().verify(s,r.secret)||{}}},getJwtPayload:m,canDisplaySampleIds:(t,e)=>!!e.cohort.termdb.displaySampleIds&&y.userCanAccess(t,e),getDsAuth:()=>[],getForbiddenRoutesForDsEmbedder:()=>[],userCanAccess:()=>!0,getRequiredCredForDsEmbedder:()=>{},getPayloadFromHeaderAuth:()=>({})}},7833:(t,e,n)=>{"use strict";n.r(e);var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=(n(3345),n(334)),l=n.n(a),c=n(8907),u=n(8064),f=n(5494),d=n(6733),h=n(5558),p=n(3602),m=n(6279);const g={snvindel:f,sv:m,fusion:m,svjson:n(8423),cnv:d,itd:p,deletion:h,truncation:n(8235)};function y(t,e,n,r,o,i){for(const s of e.yesSamples){if(i&&!i.includes(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"WT",_SAMPLEID_:s})}for(const s of e.noSamples){if(i&&!i.includes(s))continue;n.has(s)||n.set(s,{sample:s});const e=n.get(s);r in e||(e[r]={key:r,values:[],label:r}),o?e[r].values.some((e=>e.dt==t&&e.origin==o))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:s,origin:o}):e[r].values.some((e=>e.dt==t))||e[r].values.push({dt:parseInt(t),class:"Blank",_SAMPLEID_:s})}}async function v(t,e){const n=t.cohort;try{if(n.mutationFlagSet)return n.mutationFlagSet;if(!n.mutationset)return;const r={},o=t.sampleName2Id;for(const[t,i]of n.mutationset.entries()){const n=await b(t,i,e);r[Math.random()]=n;for(const t in n.data)for(const e of n.data[t])e._SAMPLENAME_=e.sample.split(";")[0].trim(),e._SAMPLEID_=o.get(e._SAMPLENAME_)||e._SAMPLENAME_}return n.mutationFlagSet=r,r}catch(t){throw t}}async function b(t,e,n){const r=u.Dz(n);if(!r)throw"init_bulk_flag() failed";r.tpsetname=e.name?e.name:"set"+t;for(const t in e){if(!(t in g))throw`unknown mutationset: ${t}`;const n=e[t].startsWith("/")?e[t]:s().join(l().tpmasterdir,e[t]);try{const e=(await o().promises.readFile(n,"utf8")).trim().split(/\r?\n/);if(g[t].parseheader(e[0],r))throw`${t} header line error: herr`;for(let n=1;n<e.length;n++)g[t].parseline(n,e[n],r)}catch(t){throw t}}return r}exports.mayGetGeneVariantData=async function(t,e){var n;const r=this,o=t.term.name,i=await v(r,e.genome),s=new Map;if(!i)return s;let a;(null==e||null===(n=e.filter)||void 0===n?void 0:n.lst.length)>0&&(a=[...new Set((await(0,c.cf)(e.filter,r)).map((t=>t.id)))]);for(const t in i){var l;const e=i[t];if(o in e.data){for(const t of e.data[o]){const e=t._SAMPLEID_;if(a&&!a.includes(e))continue;s.has(e)||s.set(e,{sample:e});const n=s.get(e);o in n||(n[o]={key:o,values:[],label:o}),n[o].values.push(t)}if(null!==(l=r.assayAvailability)&&void 0!==l&&l.byDt)for(const t in r.assayAvailability.byDt){const e=r.assayAvailability.byDt[t];if(e.byOrigin)for(const n in e.byOrigin){y(t,e.byOrigin[n],s,o,n,a)}else y(t,e,s,o,!1,a)}}}return s},exports.getTermTypes=async function(t){const e=this;try{const n="string"==typeof t.ids?JSON.parse(t.ids):t.ids,r=n.map((()=>"?")).join(","),o=`SELECT id, name, type, jsondata, parent_id FROM terms WHERE id IN (${r}) OR name IN (${r})`,i=e.cohort.db.connection.prepare(o).all([...n,...n]),s={};for(const t of i)t.jsondata&&Object.assign(t,JSON.parse(t.jsondata)),s[t.id]=t;const a=n.filter((t=>!s[t])),l=await v(e,t.genome);if(l)for(const t in l){const e=l[t];if(e.data)for(const t of a)t in e.data&&!(t in s)&&(s[t]={name:t,type:"geneVariant"})}return s}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}},exports.mayGetMatchingGeneNames=async function(t,e,n,r=25){const o=await v(this,n.genome);if(o)for(const n in o){const s=o[n];for(const n in s.data){var i;if(n.length>r)continue;if(null===(i=s.data[n])||void 0===i||!i.length)continue;const o={name:n,type:"geneVariant",isleaf:!0};n===e?t.equals.push(o):n.startsWith(e)?t.startsWith.push(o):n.includes(" "+e)?t.startsWord.push(o):n.includes(e)?t.includes.push(o):"TP53"==n&&0}}},exports.get_flagset=v},4065:(t,e,n)=>{"use strict";function r(t,e){if(t.genomicNameRegexp.test(e.input))throw"invalid character in gene name";if(e.deep){const n={};let r;{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);n&&(r=n.name)}if(!r&&t.genedb.getNameByAlias){const n=t.genedb.getNameByAlias.get(e.input);n&&(r=n.name)}if(!r&&t.genedb.get_gene2canonicalisoform&&e.input.toUpperCase().startsWith("ENSG")){const o=t.genedb.get_gene2canonicalisoform.get(e.input);if(o&&o.isoform){const e=o.isoform;n.found_isoform=e;const i=t.genedb.getnamebynameorisoform.get(e,e);if(!i)throw"cannot map enst isoform to symbol";r=i.name}}r||(r=e.input);const o=t.genedb.getjsonbyname.all(r);return n.gmlst=o.map((t=>{const e=JSON.parse(t.genemodel);return t.isdefault&&(e.isdefault=!0),e})),n}const n=e.input.toUpperCase(),r=(n.substr(0,2),t.genedb.getnameslike.all(n+"%"));if(r.length)return r.sort(),{hits:r.map((t=>t.name))};if(t.genedb.getNameByAlias){const e=t.genedb.getNameByAlias.all(n);if(e.length)return{hits:e.map((t=>t.name))}}{const n=t.genedb.getnamebynameorisoform.get(e.input,e.input);if(n)return{hits:[n.name]}}return{hits:[]}}n.d(e,{S:()=>r})},2062:(t,e,n)=>{"use strict";n.d(e,{W:()=>a,A:()=>l});var r=n(334),o=n.n(r),i=n(7147),s=n.n(i);async function a(t){l.deps||async function(){const t=`${process.cwd()}/package.json`;try{if(s().existsSync(t)){const e=s().readFileSync(t,{encoding:"utf8"}),n=JSON.parse(e);l.deps={"@sjcrh/proteinpaint-server":null==n?void 0:n.dependencies["@sjcrh/proteinpaint-server"],"@sjcrh/proteinpaint-client":null==n?void 0:n.dependencies["@sjcrh/proteinpaint-client"]}}else l.deps={}}catch(t){console.log(t),l.deps={}}}();const e={status:"ok",genomes:{},versionInfo:l};for(const o in t){const i=t[o],s={};var n;if(i.genedb)s.genedb={buildDate:(null===(n=i.genedb.get_buildDate)||void 0===n?void 0:n.get().date)||"unknown",tables:i.genedb.tableSize};if(i.termdbs){s.termdbs={};for(const t in i.termdbs){var r;const e=i.termdbs[t];s.termdbs[t]={buildDate:(null===(r=e.cohort.termdb.q.get_buildDate)||void 0===r?void 0:r.get().date)||"unknown"}}}Object.keys(s).length&&e.genomes&&(e.genomes[o]=s)}return e}const l={pkgver:"2.34.0",codedate:function(){const t=s().existsSync(o().binpath+"/server.js")&&s().statSync(o().binpath+"/server.js").mtime||new Date(0),e=s().existsSync("public/bin/proteinpaint.js")&&s().statSync("public/bin/proteinpaint.js").mtime||new Date(0);return(t>e?t:e).toDateString()}(),launchdate:new Date(Date.now()).toString().split(" ").slice(0,5).join(" ")}},9157:(t,e,n)=>{"use strict";n.r(e),n.d(e,{default:()=>c});var r=n(7147),o=n.n(r),i=(n(1017),n(334)),s=n.n(i),a=n(2081),l=n(2781);async function c(t,e,n=[]){try{await o().promises.stat(t)}catch(e){throw`${t} does not exist`}const r=[],i=[];return new Promise(((o,c)=>{const u=(0,a.spawn)(s().Rscript,[t,...n]);if(e&&e.length>0)try{const t=e.join("\n")+"\n";l.Readable.from(t).pipe(u.stdin)}catch(t){u.kill();let e=t;i.length>0&&(e+=`\nR stderr: ${i.join("").trim()}`),c(e)}u.stdout.on("data",(t=>r.push(t))),u.stderr.on("data",(t=>i.push(t))),u.on("error",(t=>c(t))),u.on("close",(t=>{if(0!==t){let e=`R process exited with non-zero status code=${t}`;r.length>0&&(e+=`\nR stdout: ${r.join("").trim()}`),i.length>0&&(e+=`\nR stderr: ${i.join("").trim()}`),c(e)}if(i.length>0){const t=i.join("").trim();c(`R process emitted standard error\nR stderr: ${t}`)}const e=r.join("").trim().split("\n");o(e)}))}))}},1169:(t,e,n)=>{"use strict";n.d(e,{Ak:()=>m,r8:()=>L,z7:()=>D,Pj:()=>b,ws:()=>R,BM:()=>$,nD:()=>j,wm:()=>P,IK:()=>q,CL:()=>v,P9:()=>F,CN:()=>w,xq:()=>y,vK:()=>g});var r=n(2273),o=n(4048),i=n(6452),s=n.n(i),a=n(1017),l=n.n(a),c=n(4973);function u(t){const e={op:"and",content:[]};if(!Array.isArray(t.lst))throw"filter.lst[] not array";for(const n of t.lst){if("tvs"!=n.type)throw'filter.lst[] item.type!="tvs"';if(!n.tvs)throw"item.tvs missing";if(!n.tvs.term)throw"item.tvs.term missing";if(n.tvs.values){const t={op:"in",content:{field:f(n.tvs.term.id),value:n.tvs.values.map((t=>t.key))}};e.content.push(t)}else if(n.tvs.ranges)for(const t of n.tvs.ranges)t.startunbounded?e.content.push({op:t.stopinclusive?"<=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}):t.stopunbounded?e.content.push({op:t.startinclusive?">=":">",content:{field:f(n.tvs.term.id),value:t.start}}):e.content.push({op:"and",content:[{op:t.startinclusive?">=":">",content:{field:f(n.tvs.term.id),value:t.start}},{op:t.stopinclusive?"<=":"<",content:{field:f(n.tvs.term.id),value:t.stop}}]})}return e}function f(t){const e=t.split(".");return"case"==e[0]&&(e[0]="cases"),e.join(".")}const d=process.env.PP_GDC_HOST||"https://api.gdc.cancer.gov",h=d+(d.includes("/v0")?"":"/v0")+"/graphql",p="https://uat-api.gdc.cancer.gov";function m(t,e){t.convertSampleId.get=t=>{const n={};for(const r of t)n[r]=e.__gdc.map2caseid.get(r)||r;return n}}async function g(t){const e=["consequence.transcript.is_canonical","consequence.transcript.transcript_id"];t.get=async t=>{if(!t.ssm_id)throw".ssm_id missing";const n=await s()(d+"/ssms/"+t.ssm_id+"?fields="+e.join(","),{method:"GET",headers:S(t)});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid json in response"}if(!r.data||!r.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(r.data.consequence))throw".data.consequence not array";const o=r.data.consequence.find((t=>t.transcript.is_canonical));return o?o.transcript.transcript_id:r.data.consequence[0].transcript.transcript_id}}function y(t){t.queries.snvindel.byrange.get=async e=>{var n,o,i,a,l;const c=await s().post(h,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:B,variables:G(e)})});let u;try{u=JSON.parse(c.body)}catch(t){throw"invalid JSON from GDC range2ssm"}if(!Array.isArray(null===(n=u)||void 0===n||null===(o=n.data)||void 0===o||null===(i=o.explore)||void 0===i||null===(a=i.ssms)||void 0===a||null===(l=a.hits)||void 0===l?void 0:l.edges))throw"data.explore.ssms.hits.edges not array";const f=[];for(const n of u.data.explore.ssms.hits.edges){const o={dt:r.dtsnvindel,ssm_id:n.node.ssm_id,chr:n.node.chromosome,pos:n.node.start_position-1,ref:n.node.reference_allele,alt:n.node.tumor_allele,samples:[]};if(n.node.consequence&&n.node.consequence.hits&&n.node.consequence.hits.edges){let t;o.csqcount=n.node.consequence.hits.edges.length,t=e.isoform?n.node.consequence.hits.edges.find((t=>t.node.transcript.transcript_id==e.isoform)):n.node.consequence.hits.edges.find((t=>t.node.transcript.is_canonical));t||n.node.consequence.hits.edges[0];k(o,(t||n.node.consequence.hits.edges[0]).node)}if(n.node.occurrence.hits.edges)for(const e of n.node.occurrence.hits.edges){const n=x(e.node.case,t);n.sample_id=e.node.case.case_id,o.samples.push(n)}f.push(o)}return f}}function v(t,e){t.queries.geneExpression.get=async n=>{if(!Array.isArray(n.genes))throw"q.genes[] not array";const r=new Map,o=new Date,i=await b(n,t);if(0==i.length)return{gene2sample2value:r,byTermId:{}};const a=new Date;console.log(i.length,"cases with exp data:",a-o,"ms");const[l,c]=await async function(t,e,n){const r=[],o=new Map;for(const n of t){const t=n.gene||n.name;if("string"!=typeof t)continue;if(t.startsWith("ENSG")&&15==t.length){r.push(t),o.set(t,t);continue}const i=e.genedb.getAliasByName.all(t);if(Array.isArray(i))for(const e of i)if(e.alias.startsWith("ENSG")){r.push(e.alias),o.set(e.alias,t);break}if(r.length>100)break}try{const t=await s().post(`${p}/gene_expression/gene_selection`,{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({case_ids:n,gene_ids:r,selection_size:r.length})}),e=JSON.parse(t.body);if(!Array.isArray(e.gene_selection))throw"re.gene_selection[] not array";const i=[];for(const t of e.gene_selection){if("string"!=typeof t.gene_id)throw".gene_id missing from one of re.gene_selection[]";i.push(t.gene_id)}return[i,o]}catch(t){throw t}}(n.genes,e,i);if(0==l.length)return{gene2sample2value:r,byTermId:{}};const u=new Date;console.log(l.length,"out of",n.genes.length,"genes selected for exp:",u-a,"ms");const f={};for(const t of l){const e=c.get(t);f[e]={gencodeId:t},r.set(e,new Map)}await async function(t,e,n,r,o,i){const a=await s().post(`${p}/gene_expression/values`,{headers:S(t),body:JSON.stringify({case_ids:n,gene_ids:e,format:"tsv",tsv_units:"median_centered_log2_uqfpkm"})});if("string"!=typeof a.body)throw"response.body is not tsv text";const l=a.body.trim().split("\n");if(l.length<=1)throw"less than 1 line from tsv response.body";const c=l[0].split("\t").slice(1);if(c.length!=n.length)throw"sample column length != case_ids.length";const u=[];for(const t of c){const e=i.__gdc.caseid2submitter.get(t);if(!e)throw"case submitter id unknown for a uuid";u.push(e)}for(let t=1;t<l.length;t++){const e=l[t].split("\t");if(e.length!=u.length+1)throw"number of fields in gene line does not equal header";const n=e[0];if(!n)throw"ensg l[0] missing from a line";const i=r.get(n);if(!i)throw"symbol missing for "+n;for(const[t,r]of u.entries()){const s=Number(e[t+1]);Number.isFinite(s)?o.get(i)[r]=s:console.log(n,r,e[t+1])}}}(n,l,i,c,r,t);const d=new Date;return console.log("gene-case matrix built:",d-u,"ms"),{gene2sample2value:r,byTermId:f}}}async function b(t,e){const n={op:"and",content:[]};t.filter0&&n.content.push(t.filter0),t.filterObj&&n.content.push(u(t.filterObj));const r={size:1e4,fields:"case_id"};n.content.length&&(r.filters=n);try{const n=await s().post(l().join(d,"cases"),{headers:S(t),body:JSON.stringify(r)}),o=JSON.parse(n.body);if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";const i=[];for(const t of o.data.hits)if(t.id&&e.__gdc.casesWithExpData.has(t.id)&&(i.push(t.id),i.length>1e3))break;return i}catch(t){throw console.log(t.stack||t),t}}function w(t){t.queries.snvindel.byisoform.get=async e=>{const n=_(e,t),o=await async function(t,e){if(!t.isoform)throw"snvindel_byisoform: .isoform missing";if("string"!=typeof t.isoform)throw".isoform value not string";const n=z,r=U,o=S(t),i=s().post(l().join(d,n.endpoint),{headers:o,body:JSON.stringify({size:n.size,fields:n.fields.join(","),filters:n.filters(t)})}),a=s().post(l().join(d,r.endpoint),{headers:o,body:JSON.stringify({size:r.size,fields:r.fields.join(","),filters:r.filters(t,e)})}),[c,u]=await Promise.all([i,a]);let f,h;try{f=JSON.parse(c.body),h=JSON.parse(u.body)}catch(t){throw"invalid JSON returned by GDC"}if(!f.data||!f.data.hits)throw"query1 did not return .data.hits";if(!h.data||!h.data.hits)throw"query2 did not return .data.hits[]";if(!Array.isArray(f.data.hits)||!Array.isArray(h.data.hits))throw"re.data.hits[] is not array";const p=new Map;for(const e of f.data.hits){if(!e.ssm_id)throw"ssm_id missing from a ssms hit";if(!e.consequence)throw".consequence[] missing from a ssm";if(!Number.isInteger(e.start_position))throw"hit.start_position is not integer";e.csqcount=e.consequence.length;const n=e.consequence.find((e=>e.transcript.transcript_id==t.isoform));e.consequence=n,e.cases=[],p.set(e.ssm_id,e)}for(const t of h.data.hits){if(!t.ssm)throw".ssm{} missing from a case";if(!t.ssm.ssm_id)throw".ssm.ssm_id missing from a case";const e=p.get(t.ssm.ssm_id);if(!e)throw"ssm_id not found in ssms query";if(!t.case)throw".case{} missing from a case";e.cases.push(t.case)}return[...p.values()]}(e,t),i=[];for(const n of o){const o={ssm_id:n.ssm_id,dt:r.dtsnvindel,chr:n.chromosome,pos:n.start_position-1,ref:n.reference_allele,alt:n.tumor_allele,isoform:e.isoform,csqcount:n.csqcount};if(k(o,n.consequence),!e.hiddenmclass||!e.hiddenmclass.has(o.class)){o.samples=[];for(const r of n.cases){const n={sample_id:await E(r,t,e.useCaseid4sample)};e.useCaseid4sample&&(n.__sampleName=r.submitter_id),o.samples.push(n)}i.push(o)}}if(n){e.isoform=n;for(const t of i)t.isoform=n}return i}}function _(t,e){if(!t.isoform)return;let n;if("N"==t.isoform[0]&&e.refseq2ensembl_query){const r=e.refseq2ensembl_query.get(t.isoform);r&&(n=t.isoform,t.isoform=r.ensembl)}return n}function x(t,e){const n={};if(e.sampleSummaries)for(const r of e.sampleSummaries.lst){{const o=e.cohort.termdb.q.termjsonByOneid(r.label1);if(o){n[r.label1]=t[o.fields[0]];for(let t=1;t<o.fields.length;t++)n[r.label1]&&(n[r.label1]=n[r.label1][o.fields[t]])}}if(r.label2){const o=e.cohort.termdb.q.termjsonByOneid(r.label2);if(o){n[r.label2]=t[o.fields[0]];for(let t=1;t<o.fields.length;t++)n[r.label2]&&(n[r.label2]=n[r.label2][o.fields[t]])}}}return n}function k(t,e){if(e&&e.transcript.consequence_type){const[n,o,i]=r.vepinfo(e.transcript.consequence_type);t.class=o,t.mname=e.transcript.aa_change}t.mname||(t.mname=t.ref+">"+t.alt),t.class||(r.basecolor[t.ref]&&r.basecolor[t.alt]?t.class=r.mclasssnv:"-"==t.ref?t.class=r.mclassinsertion:"-"==t.alt?t.class=r.mclassdeletion:t.class=r.mclassmnv)}function q(t){const e=["cnv.cnv_change","cnv.gene_level_cn","cnv.consequence.gene.symbol","case.submitter_id","case.case_id"];function n(t){const n=e.slice();if(t.twLst)for(const e of t.twLst){let t=e.term.id;t.startsWith("case.")&&(t="occurrence."+t),n.push(t)}return n.join(",")}function o(t){if(!t.gene&&"string"!=typeof t.gene)throw"p.gene does not provide non-empty string";const e={op:"and",content:[]};return t.gene&&e.content.push({op:"=",content:{field:"cnv.consequence.gene.symbol",value:t.gene.split(",")}}),t.filter0&&e.content.push(t.filter0),t.filterObj&&e.content.push(u("string"==typeof t.filterObj?JSON.parse(t.filterObj):t.filterObj)),e}t.queries.geneCnv.bygene.get=async t=>{var e;const i=S(t),a=await s().post(l().join(d,"cnv_occurrences"),{headers:i,body:JSON.stringify({size:1e5,fields:n(t),filters:o(t)})}),c=JSON.parse(a.body);if(!Array.isArray(null==c||null===(e=c.data)||void 0===e?void 0:e.hits))throw"geneCnv response body is not {data:hits[]}";const u={ssm_id:"geneCnvGain",dt:r.dtcnv,class:r.mclasscnvgain,samples:[]},f={ssm_id:"geneCnvLoss",dt:r.dtcnv,class:r.mclasscnvloss,samples:[]};for(const e of c.data.hits){if("object"!=typeof e.cnv)throw"hit.cnv{} not obj";if("object"!=typeof e.case)throw"hit.case{} not obj";if(!e.cnv.gene_level_cn)throw"hit.cnv.gene_level_cn is not true";let n;if("Gain"==e.cnv.cnv_change)n=u;else{if("Loss"!=e.cnv.cnv_change)throw"hit.cnv.cnv_change is not Gain/Loss";n=f}const r={sample_id:e.case.case_id,__sampleName:e.case.submitter_id};if(t.twLst)for(const n of t.twLst)A(r,e.case,n);n.samples.push(r)}const h=[];return u.samples.length&&h.push(u),f.samples.length&&h.push(f),h}}function N(t,e){if(!e)return;const n=e.split(",");for(const e of n){const n=e.split("--");if(2==n.length)return t.geneA=n[0].split("(")[0],void(t.geneB=n[1].split("(")[0])}}function S(t){const e={"Content-Type":"application/json",Accept:"application/json"};return t&&(t.token&&(e["X-Auth-Token"]=t.token),t.sessionid&&(e.Cookie="sessionid="+t.sessionid)),e}function A(t,e,n){const r=n.term.id.split(".");if(function e(o,i){const s=r[i];if(i==r.length-1)return void(t[n.term.id]?t[n.term.id].add(o[s]):t[n.term.id]=o[s]);const a=o[s];if(null==a)return;if(Array.isArray(a)){t[n.term.id]=new Set;for(const t of a)e(t,i+1);return}e(a,i+1)}(e,1),t[n.term.id]instanceof Set&&(t[n.term.id]=[...t[n.term.id]][0]),n.term.id in t&&"categorical"==n.term.type){const e=function(t,e){var n,r,o,i,s,a,l;if("custom-groupset"==(null===(n=e.q)||void 0===n?void 0:n.type)&&Array.isArray(null===(r=e.q)||void 0===r||null===(o=r.groupsetting)||void 0===o||null===(i=o.customset)||void 0===i?void 0:i.groups))for(const n of e.q.groupsetting.customset.groups){if(!Array.isArray(n.values))throw"group.values[] not array from tw.q.groupsetting.customset.groups";if(-1!=n.values.findIndex((e=>e.key==t)))return n.name}if("predefined-groupset"==(null===(s=e.q)||void 0===s?void 0:s.type)&&Number.isInteger(null===(a=e.q.groupsetting)||void 0===a?void 0:a.predefined_groupset_idx)&&null!==(l=e.term.groupsetting)&&void 0!==l&&l.lst[e.q.groupsetting.predefined_groupset_idx])for(const n of e.term.groupsetting.lst[e.q.groupsetting.predefined_groupset_idx]){if(!Array.isArray(n.values))throw"group.values[] not array from tw.term.groupsetting.lst[]";if(-1!=n.values.findIndex((e=>e.key==t)))return n.name}}(t[n.term.id],n);e&&(t[n.term.id]=e)}}function M(t,e){const n={};for(const i of e){var r;if(("integer"==i.term.type||"float"==i.term.type)&&(null!==(r=i.q)&&void 0!==r&&r.mode))if("discrete"==i.q.mode||"binary"==i.q.mode){const e={};for(const n of t){const t=n[i.term.id];Number.isFinite(t)&&("min"in e?(e.min=Math.min(t,e.min),e.max=Math.max(t,e.max)):(e.min=t,e.max=t))}const r=(0,o.gp)(i.q,(t=>e),i.term.valueConversion);for(const t of r)t.name=t.label;n[i.term.id]={bins:r};for(const e of t){const t=e[i.term.id];Number.isFinite(t)&&(e[i.term.id]=T(r,t))}}else if("continuous"!=i.q.mode)throw"mayApplyBinning: unknown numeric q.mode"}return n}function T(t,e){for(const n of t)if(n.startunbounded){if(e<n.stop)return n.label;if(n.stopinclusive&&e==n.stop)return n.label}else if(n.stopunbounded){if(e>n.start)return n.label;if(n.startinclusive&&e==n.start)return n.label}else if((e>n.start||e===n.start&&n.startinclusive)&&(e<n.stop||e===n.stop&&n.stopinclusive))return n.label}function C(t){for(const n of t)if(null==n.id||""==n.id){var e;if(null==n||null===(e=n.term)||void 0===e||!e.id)throw"tw.id and tw.term are both missing";n.id=n.term.id}else n.term||(n.term={id:n.id})}async function j(t,e,n,r){if(t.isHierCluster)return await async function(t,e,n){var r;const o={op:"in",content:{field:"case_id",value:[...n.__gdc.casesWithExpData]}},i=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&i.push({term:e,q:t.q})}const a=["case_id"],c=new Map;for(const t of i){const e=t.term.id.replace(/^case\./,"");a.push(e),c.set(e,t.term.id)}const u=await s().post(l().join(d,"cases"),{headers:S(t),body:JSON.stringify({size:1e4,fields:a.join(","),filters:o})}),f=JSON.parse(u.body);if(!Array.isArray(null==f||null===(r=f.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const h=[];for(const t of f.data.hits){if("string"!=typeof t.case_id)throw"h.case_id missing";const e={sample_id:n.__gdc.caseid2submitter.get(t.case_id),__sampleName:n.__gdc.caseid2submitter.get(t.case_id)};for(const n of i)A(e,t,n);h.push(e)}const p=M(h,i);return{byTermId:p,samples:h}}(t,e,n);if(C(e),r){if(!Array.isArray(r))throw"geneTwLst not array";t.isoforms=[];for(const e of r){var o;if(null==e||null===(o=e.term)||void 0===o||!o.name)throw"gene tw missing .term.name";if(e.term.isoform)t.isoforms.push(e.term.isoform);else{var i,a;if("object"!=typeof t.genome)throw"serverside genome obj missing, needed to map gene name to canonical isoform";if(null===(i=t.genome)||void 0===i||null===(a=i.genedb)||void 0===a||!a.get_gene2canonicalisoform)throw"gene2canonicalisoform not supported on this genome";const n=t.genome.genedb.get_gene2canonicalisoform.get(e.term.name);if(null==n||!n.isoform)continue;t.isoforms.push(n.isoform)}}}"samples"==t.get&&((t.ssm_id_lst||t.isoform)&&(e.some((t=>"ssm.ssm_id"==t.id))||e.push({term:{id:"ssm.ssm_id"}}),e.some((t=>"case.observation.read_depth.t_alt_count"==t.id))||e.push({term:{id:"case.observation.read_depth.t_alt_count"}}),e.some((t=>"case.observation.read_depth.t_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.t_depth"}}),e.some((t=>"case.observation.read_depth.n_depth"==t.id))||e.push({term:{id:"case.observation.read_depth.n_depth"}}),e.some((t=>"case.observation.sample.tumor_sample_uuid"==t.id))||e.push({term:{id:"case.observation.sample.tumor_sample_uuid"}})),e.some((t=>"case.case_id"==t.id))||e.push({term:{id:"case.case_id"}}),e.some((t=>"case.submitter_id"==t.id))||e.push({term:{id:"case.submitter_id"}})),"summary"!=t.get&&"sunburst"!=t.get||e.some((t=>"case.submitter_id"==t.id))||e.push({term:{id:"case.submitter_id"}});const u=[];for(const t of e){const e=n.cohort.termdb.q.termjsonByOneid(t.term.id);e&&u.push({term:e,q:t.q})}const f=e.map((t=>t.term.id));t.hiddenmclass&&(f.push("ssm.consequence.transcript.consequence_type"),f.push("ssm.consequence.transcript.transcript_id")),t.rglst&&(f.push("ssm.chromosome"),f.push("ssm.start_position"));const h={size:1e4,fields:f.join(",")};_(t,n),h.filters=U.filters(t,n);const p=S(t),m=await s().post(l().join(d,U.endpoint),{headers:p,body:JSON.stringify(h)});let g;delete t.isoforms;try{g=JSON.parse(m.body)}catch(t){throw"invalid JSON from GDC for variant2samples query"}if(!g.data||!g.data.hits)throw"variant2samples data structure not data.hits[]";if(!Array.isArray(g.data.hits))throw"variant2samples re.data.hits is not array for query";const y=[];for(const e of g.data.hits){if(!e.case)throw"variant2samples .case{} missing from a hit";const r={};if(e.ssm&&(r.ssm_id=e.ssm.ssm_id),t.hiddenmclass){var v;if(!Array.isArray(null===(v=e.ssm)||void 0===v?void 0:v.consequence))continue;const n={};if(k(n,e.ssm.consequence.find((e=>e.transcript.transcript_id==t.isoform))),t.hiddenmclass.has(n.class))continue}if(t.rglst){var b,w;if(null===(b=e.ssm)||void 0===b||!b.chromosome||null===(w=e.ssm)||void 0===w||!w.start_position)continue;if(!t.rglst.find((t=>t.chr==e.ssm.chromosome&&t.start<e.ssm.start_position&&t.stop>=e.ssm.start_position)))continue}var x,q,N,T;if(t.variant2samples?r.sample_id=await E(e.case,n,!1):(r.sample_id=e.case.case_id,r.__sampleName=e.case.submitter_id),e.case.case_id)r.sample_URLid=e.case.case_id,null!==(x=e.case)&&void 0!==x&&null!==(q=x.observation)&&void 0!==q&&null!==(N=q[0])&&void 0!==N&&null!==(T=N.sample)&&void 0!==T&&T.tumor_sample_uuid&&(r.sample_URLid=r.sample_URLid+"?bioId="+e.case.observation[0].sample.tumor_sample_uuid);for(const t of u)A(r,e.case,t);O(e.case,r),I(r,n),y.push(r)}const j=M(y,u);if(r){const t={gene:r.map((t=>t.term.name)).join(","),twLst:u},e=await n.queries.geneCnv.bygene.get(t);for(const t of e)for(const e of t.samples)y.push(e)}const R=new Map;for(const t of y)(0,c.z9)([t],R,t.ssm_id);return{byTermId:j,samples:[...R.values()]}}async function E(t,e,n){var r,o,i;return n&&t.case_id?t.case_id:null!=t&&null!==(r=t.observation)&&void 0!==r&&null!==(o=r[0])&&void 0!==o&&null!==(i=o.sample)&&void 0!==i&&i.tumor_sample_uuid?await e.__gdc.aliquot2submitter.get(t.observation[0].sample.tumor_sample_uuid):t.case_id||t.submitter_id}function O(t,e){if(!t.observation)return;const n=t.observation[0];n&&n.read_depth&&(e.formatK2v={TumorAC:n.read_depth.t_depth-n.read_depth.t_alt_count+","+n.read_depth.t_alt_count,NormalDepth:n.read_depth.n_depth})}function I(t,e){var n;const r=t["case.project.project_id"];r&&(t.caseIsOpenAccess=null===(n=e.__gdc.gdcOpenProjects)||void 0===n?void 0:n.has(r))}async function R(t,e,n,r){C(t);const o=[];for(const e of t)e.term&&"categorical"==e.term.type&&o.push({id:e.id,path:e.id.replace("case.","").replace(/\./g,"__"),type:e.term.type});const i=function(t){const e=[];for(const n of t)if(n.id)if(n.type="categorical")e.push(n.path+" {buckets { doc_count, key }}");else{if("integer"!=n.type&&"float"!=n.type)throw"unknown term type";e.push(n.path+" {stats { count }}")}const n=`query termislst2total( $filters: FiltersArgument) {\n\t\texplore {\n\t\t\tcases {\n\t\t\t\taggregations (filters: $filters, aggregations_filter_themselves: true) {\n\t\t\t\t\t${e.join("\n")}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}`;return n}(o),a=function(t,e){const n={filters:{op:"and",content:[{op:"in",content:{field:"cases.available_variation_data",value:["ssm"]}}]}};if(t&&t.tid2value)for(const r in t.tid2value){e.cohort.termdb.q.termjsonByOneid(r)&&n.filters.content.push({op:"in",content:{field:r.replace(/^case\./,"cases."),value:[t.tid2value[r]]}})}t&&t.ssm_id_lst&&n.filters.content.push({op:"=",content:{field:"cases.gene.ssm.ssm_id",value:t.ssm_id_lst.split(",")}});t.filterObj&&n.filters.content.push(u(t.filterObj));return n}(e,r),l=await s().post(h,{headers:S(e),body:JSON.stringify({query:i,variables:a})});let c;try{c=JSON.parse(l.body)}catch(t){throw"invalid JSON from GDC for cohortTotal for query :"+i+" and filter: "+filter}const f=["data","explore","cases","aggregations"];let d=c[f[0]];for(let t=1;t<f.length;t++)if(d=d[f[t]],!d)throw`.${f[t]} missing from data structure of termid2totalsize2 for query :${i} and filter: ${filter}`;for(const t of o){if("categorical"==t.type&&!Array.isArray(d[t.path].buckets))throw f.join(".")+" not array for query :"+i+" and filter: "+filter;if(("integer"==t.type||"float"==t.type)&&"object"!=typeof d[t.path].stats)throw f.join(".")+" not object for query :"+i+" and filter: "+filter}const p=new Map;for(const t of o)if("categorical"==t.type){const e=d[t.path].buckets,n=[];for(const t of e)n.push([t.key.replace(".","__"),t.doc_count]);p.set(t.id,n)}else if("integer"==t.type||"float"==t.type){const e=d[t.path].stats.count;p.set(t.id,{total:e})}return n?[p,n]:p}function P(t){const e=["consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change"];t.queries.snvindel.m2csq.get=async t=>{const n=await s()(d+"/ssms/"+t.ssm_id+"?fields="+e.join(","),{method:"GET",headers:S(t)});let r;try{r=JSON.parse(n.body)}catch(t){throw"invalid json in response"}if(!r.data||!r.data.consequence)throw"returned data not .data.consequence";if(!Array.isArray(r.data.consequence))throw".data.consequence not array";return r.data.consequence.map((t=>t.transcript))}}function F(t,e){t.queries.singleSampleMutation.get=async(n,r)=>{if(!n)throw"sampleName missing";return r.case_id=t.__gdc.map2caseid.get(n),r.case_id||(r.case_id=await async function(t){const e=await s().post("https://api.gdc.cancer.gov/cases",{headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({size:1,fields:"case_id,submitter_id",filters:{op:"or",content:[{op:"=",content:{field:"samples.portions.analytes.aliquots.aliquot_id",value:[t]}},{op:"=",content:{field:"submitter_id",value:[t]}},{op:"=",content:{field:"samples.submitter_id",value:[t]}}]}})}),n=JSON.parse(e.body);for(const t of n.data.hits)if(t.case_id)return t.case_id;throw"cannot convert to case_id (uuid)"}(n)),await Z(r,t,e)}}function D(t,e){t.queries.singleCell.samples.get=async t=>{var e,n,r;const o={op:"and",content:[{op:"=",content:{field:"data_format",value:"tsv"}},{op:"=",content:{field:"data_type",value:"Single Cell Analysis"}},{op:"=",content:{field:"experimental_strategy",value:"scRNA-Seq"}}]};t.filter0&&o.content.push(t.filter0);const i={filters:o,size:100,fields:["id","cases.project.project_id","cases.submitter_id","cases.samples.sample_type"].join(",")},a=await s().post(l().join(d,"files"),{headers:S(t),body:JSON.stringify(i)});let c;try{c=JSON.parse(a.body)}catch(t){throw"invalid JSON from "+api.endpoint}if(!Number.isInteger(null===(e=c.data)||void 0===e||null===(n=e.pagination)||void 0===n?void 0:n.total))throw"re.data.pagination.total is not int";if(!Array.isArray(null===(r=c.data)||void 0===r?void 0:r.hits))throw"re.data.hits[] not array";const u=new Map;for(const t of c.data.hits){var f;const e=null===(f=t.cases)||void 0===f?void 0:f[0];if(!e)throw"h.cases[0] missing";u.has(e.submitter_id)||u.set(e.submitter_id,[]),u.get(e.submitter_id).push({fileId:t.id,project_id:e.project.project_id,samples:e.samples})}const h=[];for(const[t,e]of u)h.push({name:t,files:e});return h}}function L(t,e){t.queries.singleCell.data.get=async t=>{const e=(await s()(l().join(d,"data",t.sample),{method:"GET",headers:S(t)})).body.trim().split("\n"),n={name:"UMAP",cells:[]},r={name:"TSNE",cells:[]},o={name:"PCA",cells:[]},i={id:"cluster",name:"Seurat cluster",type:"categorical",values:{}},a={cluster:{}};for(let t=1;t<e.length;t++){const s=e[t],l=s.split("\t"),c=l[0];if(!c)throw"cellId missing from a line: "+s;const u=l[3];if(!u)throw"seuratCluster missing from a line";i.values[u]={label:"Cluster "+u},a.cluster[c]=u;const f=Number(l[4]),d=Number(l[5]),h=Number(l[9]),p=Number(l[10]),m=Number(l[14]),g=Number(l[15]);if(Number.isNaN(f))throw"umap1 is nan";if(Number.isNaN(d))throw"umap2 is nan";if(Number.isNaN(h))throw"tsne1 is nan";if(Number.isNaN(p))throw"tsne2 is nan";if(Number.isNaN(m))throw"pc1 is nan";if(Number.isNaN(g))throw"pc2 is nan";n.cells.push({cellId:c,x:f,y:d}),r.cells.push({cellId:c,x:h,y:p}),o.cells.push({cellId:c,x:m,y:g})}return{plots:[o,r,n],terms:[i],tid2cellvalue:a}}}function $(t){return async(e,n)=>{try{const r=t[e.query.genome];if(!r)throw"invalid genome";const o=r.datasets[e.query.dslabel];if(!o)throw"invalid dslabel";if(!e.query.case_id)throw".case_id missing";n.send(await Z(e.query,o,r))}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}}async function Z(t,e,n){const o={mlst:[],dt2total:[]};{var i,a,c;const e=await s().post(l().join(d,z.endpoint),{headers:S(t),body:JSON.stringify({size:1e4,fields:z.fields.join(","),filters:z.filters(t)})}),n=JSON.parse(e.body);if(!Number.isInteger(null===(i=n.data)||void 0===i||null===(a=i.pagination)||void 0===a?void 0:a.total))throw"re.data.pagination.total not integer";if(!Array.isArray(null===(c=n.data)||void 0===c?void 0:c.hits))throw"re.data.hits[] not array";n.data.hits.length<n.data.pagination.total&&o.dt2total.push({dt:1,total:n.data.pagination.total});for(const t of n.data.hits){let e=t.consequence.find((t=>1==t.transcript.is_canonical));e||(e=t.consequence[0]);const n=e.transcript.aa_change||e.transcript.consequence_type,[i,s,a]=r.vepinfo(e.transcript.consequence_type);o.mlst.push({dt:r.dtsnvindel,mname:n,class:s,gene:e.transcript.gene.symbol,chr:t.chromosome,pos:t.start_position,ref:t.reference_allele,alt:t.tumor_allele})}}{const e=await async function(t){const e=S(t),n=await s().post(l().join(d,"files"),{headers:e,body:JSON.stringify({size:1e4,fields:["cases.samples.sample_type","data_type","file_id","data_format","experimental_strategy","analysis.workflow_type"].join(","),filters:function(t){if(!t.case_id)throw".case_id missing";return{op:"and",content:[{op:"in",content:{field:"cases.case_id",value:[t.case_id]}},{op:"in",content:{field:"data_type",value:["Masked Copy Number Segment","Copy Number Segment","Transcript Fusion"]}}]}}(t)})}),o=JSON.parse(n.body);if(!Array.isArray(o.data.hits))throw"re.data.hits[] not array";let i,a,c;for(const t of o.data.hits)if("BEDPE"!=t.data_format){if("TXT"==t.data_format){if("Genotyping Array"==t.experimental_strategy){var u,f,h;const e=null===(u=t.cases)||void 0===u||null===(f=u[0].samples)||void 0===f||null===(h=f[0])||void 0===h?void 0:h.sample_type;if(!e)continue;if(e.includes("Normal"))continue;if("Masked Copy Number Segment"!=t.data_type)continue;i=t.file_id;continue}if("WGS"==t.experimental_strategy){if(!t.file_id)continue;if("Copy Number Segment"!=t.data_type)continue;a=t.file_id;continue}}}else{var p;if("RNA-Seq"!=t.experimental_strategy)continue;if("Arriba"!=(null===(p=t.analysis)||void 0===p?void 0:p.workflow_type))continue;if("Transcript Fusion"!=t.data_type)continue;c=t.file_id}const m=[];if(a){const t=(await s()(l().join(d,"data")+"/"+a,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(7!=n.length)continue;const o=Number(n[4]),i=Number(n[5]),s=Number(n[6]);if(Number.isNaN(o)||Number.isNaN(i)||Number.isNaN(s))continue;const a={dt:r.dtcnv,chr:n[1],start:Number(n[2]),stop:Number(n[3]),value:o};!a.chr||Number.isNaN(a.start)||Number.isNaN(a.stop)||(m.push(a),o>0&&0==s&&i>0&&m.push({dt:r.dtloh,chr:a.chr,start:a.start,stop:a.stop,segmean:.5}))}}else if(i){const t=(await s()(l().join(d,"data")+"/"+i,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t");if(6!=n.length)continue;if(!n[1])continue;const o={dt:r.dtcnv,chr:"chr"+n[1],start:Number(n[2]),stop:Number(n[3]),value:Number(n[5])};Number.isNaN(o.start)||Number.isNaN(o.stop)||Number.isNaN(o.value)||m.push(o)}}if(c)try{const t=(await s()(l().join(d,"data")+"/"+c,{method:"GET",headers:e})).body.split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t"),o={dt:r.dtfusionrna,chrA:n[0],posA:Number(n[1]),chrB:n[3],posB:Number(n[4])};o.chrA&&o.chrB&&!Number.isNaN(o.posA)&&!Number.isNaN(o.posB)&&(N(o,n[6]),m.push(o))}}catch(t){}return m}(t);o.mlst.push(...e)}return o}const z={endpoint:"/ssms",size:1e5,fields:["ssm_id","chromosome","start_position","reference_allele","tumor_allele","consequence.transcript.transcript_id","consequence.transcript.consequence_type","consequence.transcript.aa_change","consequence.transcript.gene.symbol","consequence.transcript.is_canonical"],filters:t=>{const e={op:"and",content:[]};if(t.isoform){if("string"!=typeof t.isoform)throw".isoform value not string";e.content.push({op:"=",content:{field:"consequence.transcript.transcript_id",value:[t.isoform]}})}if(t.case_id){if("string"!=typeof t.case_id)throw".case_id value not string";e.content.push({op:"=",content:{field:"cases.case_id",value:[t.case_id]}})}if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";e.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&e.content.push(t.filter0),t.filterObj&&e.content.push(u(t.filterObj)),e}},U={endpoint:"/ssm_occurrences",size:1e5,fields:["ssm.ssm_id","case.case_id","case.submitter_id","case.observation.sample.tumor_sample_uuid"],filters:(t,e)=>{const n={op:"and",content:[]};if(t.ssm_id_lst){if("string"!=typeof t.ssm_id_lst)throw"ssm_id_lst not string";n.content.push({op:"=",content:{field:"ssm.ssm_id",value:t.ssm_id_lst.split(",")}})}else if(t.isoform)n.content.push({op:"=",content:{field:"ssms.consequence.transcript.transcript_id",value:[t.isoform]}});else{if(!t.isoforms)throw".ssm_id_lst, .isoform, .isoforms are all missing";if(!Array.isArray(t.isoforms))throw".isoforms[] not array";n.content.push({op:"in",content:{field:"ssms.consequence.transcript.transcript_id",value:t.isoforms}})}if(t.rglst&&(n.content.push({op:">=",content:{field:"ssms.start_position",value:t.rglst[0].start}}),n.content.push({op:"<=",content:{field:"ssms.start_position",value:t.rglst[0].stop}})),t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";n.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}if(t.filter0&&n.content.push(t.filter0),t.filterObj&&n.content.push(u(t.filterObj)),t.tid2value)for(const r in t.tid2value){const o=e.cohort.termdb.q.termjsonByOneid(r);if(o)if("categorical"==o.type)n.content.push({op:"in",content:{field:r,value:[t.tid2value[r]]}});else if("integer"==o.type)for(const e of t.tid2value[r])n.content.push({op:e.op,content:{field:r,value:e.range}})}return n}},B="query range2variants($filters: FiltersArgument) {\n explore {\n ssms {\n hits(first: 100000, filters: $filters) {\n total\n edges {\n node {\n ssm_id\n chromosome\n start_position\n end_position\n genomic_dna_change\n\t\t\treference_allele\n tumor_allele\n occurrence {\n hits {\n total\n\t\t\t\tedges {\n\t\t\t\t node {\n\t\t\t\t case {\n\t\t\t\t\t case_id\n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\t}\n }\n }\n\t\t\tconsequence{\n hits{\n total\n edges{\n node{\n transcript{\n transcript_id\n\t\t\t\t\t aa_change\n\t\t\t\t\t consequence_type\n\t\t\t\t\t is_canonical\n\t\t\t\t\t gene{\n\t\t\t\t\t \tsymbol\n\t\t\t\t\t }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}";function G(t){if(!t.rglst)throw".rglst missing";const e=t.rglst[0];if(!e)throw".rglst[0] missing";if("string"!=typeof e.chr)throw".rglst[0].chr not string";if(!Number.isInteger(e.start))throw".rglst[0].start not integer";if(!Number.isInteger(e.stop))throw".rglst[0].stop not integer";const n={filters:{op:"and",content:[{op:"=",content:{field:"chromosome",value:[e.chr]}},{op:">=",content:{field:"start_position",value:[e.start]}},{op:"<=",content:{field:"end_position",value:[e.stop]}}]}};if(t.set_id){if("string"!=typeof t.set_id)throw".set_id value not string";n.filters.content.push({op:"in",content:{field:"cases.case_id",value:[t.set_id]}})}return t.filter0&&n.filters.content.push(t.filter0),t.filterObj&&n.filters.content.push(u(t.filterObj)),n}},4973:(t,e,n)=>{"use strict";n.d(e,{z9:()=>h,dq:()=>f,uK:()=>d});var r=n(1881),o=n(1169),i=n(9064),s=n(7011);async function a(t,e){const n=[];let r=null,o=null;for(const i of e.map((e=>e[t.id]))){var a,l;if(null!==(a=t.values)&&void 0!==a&&null!==(l=a[i])&&void 0!==l&&l.uncomputable)continue;const e=Number(i);Number.isFinite(e)&&(n.push(e),null===r?r=o=e:(r=Math.min(r,e),o=Math.max(o,e)))}const c=(0,i.Z)().domain([r,o]).range([10,510]),u=(0,s.I)(c,{values:n});if(!Array.isArray(u.bins))throw"violinBins does not return {bins[]}";if(0==u.bins.length)throw"violinBins {bins[]} empty array";const f={minvalue:r,maxvalue:o,densitymax:0,density:[],samplecount:n.length,unit:t.unit};for(const t of u.bins){if(!Number.isFinite(t.x0))throw"b.x0 not number";if(!Number.isFinite(t.x1))throw"b.x1 not number";if(!Number.isFinite(t.binValueCount))throw"b.binValueCount not number";f.density.push([(t.x0+t.x1)/2,t.binValueCount]),f.densitymax=Math.max(f.densitymax,t.binValueCount)}return f}n(3345);var l=n(2273),c=n(4065),u=n(2974);const f=".";function d(t){const e=t.variant2samples;if(e){if(e.type_samples="samples",e.type_sunburst="sunburst",e.type_summary="summary",!e.variantkey)throw".variantkey missing from variant2samples";if(-1==["ssm_id"].indexOf(e.variantkey))throw"invalid value of variantkey";if(e.twLst){if(!Array.isArray(e.twLst))throw"variant2samples.twLst[] is not array";if(0==e.twLst.length)throw"variant2samples.twLst[] empty array";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.twLst is in use";for(const n of e.twLst){if(!n.id)throw"tw.id missing from one of variant2samples.twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.twLst: "+n.id}}if(e.sunburst_twLst){if(!Array.isArray(e.sunburst_twLst))throw".sunburst_twLst[] not array from variant2samples";if(0==e.sunburst_twLst.length)throw".sunburst_twLst[] empty array from variant2samples";if(!t.cohort||!t.cohort.termdb)throw"ds.cohort.termdb missing when variant2samples.sunburst_twLst is in use";for(const n of e.sunburst_twLst){if(!n.id)throw"tw.id missing from one of variant2samples.sunburst_twLst[]";const e=t.cohort.termdb.q.termjsonByOneid(n.id);if(!e)throw"term not found for one of variant2samples.sunburst_twLst: "+n.id;if(n.term=e,!n.q)throw"tw.q{} missing for one of variant2samples.sunburst_twLst: "+n.id}}if(e.gdcapi);else{var n,i,s,d,y,v,b;let e=!1;if(null!==(n=t.queries)&&void 0!==n&&null!==(i=n.snvindel)&&void 0!==i&&null!==(s=i.byrange)&&void 0!==s&&null!==(d=s._tk)&&void 0!==d&&d.samples&&(e=!0),null!==(y=t.queries)&&void 0!==y&&null!==(v=y.svfusion)&&void 0!==v&&null!==(b=v.byrange)&&void 0!==b&&b.samples&&(e=!0),!e)throw"cannot find a sample source from ds.queries{}"}e.get=async e=>await async function(t,e){!function(t,e){if("samples"==t.get){var n,r;const o=null===(n=e.queries)||void 0===n||null===(r=n.snvindel)||void 0===r?void 0:r.byrange;o&&(o.bcffile||o.chr2bcffile)&&o._tk.format&&(t.addFormatValues=!0)}}(t,e);const n=await async function(t,e){var n;const r=t.twLst?t.twLst.slice():[];if(e.variant2samples.gdcapi)return await(0,o.nD)(t,r,e,t.geneTwLst);if(t.ssm_id_lst)return await async function(t,e,n){const r=new Map;for(const e of t.ssm_id_lst.split(",")){const o=e.split(f);if(4!=o.length){if(6!=o.length)throw"unknown format of ssm id";{if(!n.queries.svfusion||!n.queries.svfusion.byrange)throw"queries.svfusion.byrange missing when id has 6 fields";const[e,i,s,a,c,u]=o,f=decodeURIComponent(u),d=Number(e);if(d!=l.dtsv&&d!=l.dtfusionrna)throw"dt not sv/fusion";const p=Number(s);if(Number.isNaN(p))throw"position not integer";const m=Number(c);if(Number.isNaN(m))throw"pairlstIdx not integer";const g=Object.assign({},t,{rglst:[{chr:i,start:p,stop:p+1}]}),y=await n.queries.svfusion.byrange.get(g);for(const t of y)t.dt==d&&t.pos==p&&t.strand==a&&t.pairlstIdx==m&&t.mname==f&&h(t.samples,r,t.ssm_id)}}else{if(!n.queries.snvindel||!n.queries.snvindel.byrange)throw"queries.snvindel.byrange missing when id has 4 fields";const[e,i,s,a]=o,l=Number(i);if(Number.isNaN(l))throw"no integer position for snvindel from ssm id";const c=Object.assign({},t,{rglst:[{chr:e,start:l,stop:l}]}),u=await n.queries.snvindel.byrange.get(c);for(const t of u)t.pos==l&&t.ref==s&&t.alt==a&&h(t.samples,r,t.ssm_id)}}return p(r,e,n),{samples:[...r.values()]}}(t,r,e);if(t.rglst)return await m(t,r,e);if(t.geneTwLst){if("object"!=typeof t.genome)throw"serverside genome obj needed";t.rglst=[];for(const e of t.geneTwLst)if(e.term.chr&&e.term.start&&e.term.stop)t.rglst.push({chr:e.term.chr,start:e.term.start,stop:e.term.stop});else{const n=c.S(t.genome,{deep:1,input:e.term.name});if(n.gmlst){const e=n.gmlst[0];t.rglst.push({chr:e.chr,start:e.start,stop:e.stop})}}const n=await m(t,r,e);return delete t.rglst,{samples:n}}if(null==e||null===(n=e.cohort)||void 0===n||!n.termdb)throw"unable to do sql query: .cohort.termdb missing for ds";const i={ds:e,filter:t.filter||t.filterObj},s=await(0,u.gh)(i,t.twLst),a=[];for(const e in s.samples){const n=s.samples[e];n.sample_id=n.sample,delete n.sample;for(const e of t.twLst)n[e.term.id]&&(n[e.term.id]=n[e.term.id].key);a.push(n)}return{samples:a}}(t,e);if(t.get==e.variant2samples.type_samples){var i,s,d;return!t.useIntegerSampleId&&null!=e&&null!==(i=e.cohort)&&void 0!==i&&null!==(s=i.termdb)&&void 0!==s&&null!==(d=s.q)&&void 0!==d&&d.id2sampleName&&n.samples.forEach((t=>t.sample_id=e.cohort.termdb.q.id2sampleName(t.sample_id))),n}if(t.get==e.variant2samples.type_sunburst)return n.nodes=await async function(t,e,n){var o,i;const s=(0,r.N)(t,n.twLst.map((t=>({k:t.id}))));for(const t of s)delete t.lst;if(null!=e&&null!==(o=e.cohort)&&void 0!==o&&null!==(i=o.termdb)&&void 0!==i&&i.termid2totalsize2){const t=await async function(t,e,n,r){var o,i;if(0==t.length)throw"zero terms for crosstab";if(t.length>3)throw"crosstab will not work with more than 3 levels";const s=[],a=new Map;for(const e of t)a.set(e.id,new Set);const l=!r;if(r)for(const n of r){if(n.id0){if(!n.v0)continue;a.get(n.id0).add(e.cohort.termdb.useLower?n.v0.toLowerCase():n.v0)}if(n.id1&&t[1]){if(!n.v1)continue;a.get(n.id1).add(e.cohort.termdb.useLower?n.v1.toLowerCase():n.v1)}if(n.id2&&t[2]){if(!n.v2)continue;a.get(n.id2).add(e.cohort.termdb.useLower?n.v2.toLowerCase():n.v2)}}const c=t[0].id;{const r={};n.filterObj&&(r.filterObj=n.filterObj);const o=await e.cohort.termdb.termid2totalsize2.get([t[0]],r);for(const[t,n]of o.get(c)){const r=e.cohort.termdb.useLower?t.toLowerCase():t;l?(a.get(c).add(r),s.push({count:n,id0:c,v0:r})):a.get(c).has(r)&&s.push({count:n,id0:c,v0:r})}}const u=null==t||null===(o=t[1])||void 0===o?void 0:o.id;if(u){const r=[];for(const o of a.get(c)){const i={tid2value:{[c]:o}};n.filterObj&&(i.filterObj=n.filterObj),r.push(e.cohort.termdb.termid2totalsize2.get([t[1]],i,o))}const o=await Promise.all(r);for(const[t,n]of o)for(const[r,o]of t.get(u)){const t=e.cohort.termdb.useLower?r.toLowerCase():r;l?(a.get(u).add(t),s.push({count:o,id0:c,v0:n,id1:u,v1:t})):a.get(u).has(t)&&s.push({count:o,id0:c,v0:n,id1:u,v1:t})}}const f=null==t||null===(i=t[2])||void 0===i?void 0:i.id;if(f){const r=[];for(const o of a.get(c))for(const i of a.get(u)){const s={tid2value:{[c]:o,[u]:i}};n.filterObj&&(s.filterObj=n.filterObj),r.push(e.cohort.termdb.termid2totalsize2.get([t[2]],s,{v0:o,v1:i}))}const o=await Promise.all(r);for(const[t,n]of o)for(const[t,r]of v2counts.get(f)){const o=e.cohort.termdb.useLower?t.toLowerCase():t;l?(a.get(f).add(o),s.push({count:r,id0:c,v0:n.v0,id1:u,v1:n.v1,id2:f,v2:o})):a.get(f).has(o)&&s.push({count:r,id0:c,v0:n.v0,id1:u,v1:n.v1,id2:f,v2:o})}}return s}(n.twLst,e,n,s);await async function(t,e,n){for(const r of t){if(!r.id0)continue;if(!r.v0)continue;const t=n.cohort.termdb.useLower?r.v0.toLowerCase():r.v0;if(!r.id1){const n=e.find((e=>null==e.id1&&e.v0==t));n&&(r.cohortsize=n.count);continue}if(!r.v1)continue;const o=n.cohort.termdb.useLower?r.v1.toLowerCase():r.v1;if(!r.id2){const n=e.find((e=>null==e.id2&&e.v0==t&&e.v1==o));n&&(r.cohortsize=n.count);continue}if(!r.v2)continue;const i=n.cohort.termdb.useLower?r.v2.toLowerCase():r.v2;if(!r.id3){const e=crosstabL2.find((e=>e.v0==t&&e.v1==o&&e.v2==i));e&&(r.cohortsize=e.count)}}}(s,t,e)}return s}(n.samples,e,t),delete n.samples,n;if(t.get==e.variant2samples.type_summary)return n.summary=await async function(t,e,n){if(!n.twLst)throw"q.twLst[] missing for make_summary()";const r=[];for(const e of n.twLst)if(e.term)if("categorical"==e.term.type){const n=g(t,e.id);r.push({termid:e.id,termname:e.term.name,numbycategory:[...n].sort(((t,e)=>e[1]-t[1]))})}else{if("integer"!=e.term.type&&"float"!=e.term.type)throw"unknown term type";{const n=await a(e.term,t);r.push({termid:e.id,termname:e.term.name,density_data:n})}}if(e.cohort.termdb.termid2totalsize2){const t=await e.cohort.termdb.termid2totalsize2.get(n.twLst,n);for(const{termid:e,numbycategory:n}of r){if(!n)continue;const r=t.get(e);if(r)for(const t of n){const e=r.find((e=>e[0].toLowerCase()==t[0].toLowerCase()));e&&t.push(e[1])}}}return r}(n.samples,e,t),delete n.samples,n;throw"unknown get type"}(e,t)}}function h(t,e,n){for(const r of t){e.has(r.sample_id)||(r.ssm_id_lst=[],r.formatK2v&&(r.ssmid2format={}),e.set(r.sample_id,r));const t=e.get(r.sample_id);t.ssm_id_lst.push(n),t.ssmid2format&&(t.ssmid2format[n]=r.formatK2v)}}function p(t,e,n){if(e)for(const r of t.values())for(const t of e){const e=n.cohort.termdb.q.getSample2value(t.id,r.sample_id);e[0]&&(r[t.id]=e[0].value)}}async function m(t,e,n){const r=new Map;if(n.queries.snvindel){const e=await n.queries.snvindel.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}if(n.queries.svfusion){const e=await n.queries.svfusion.byrange.get(t);for(const t of e)h(t.samples,r,t.ssm_id)}return p(r,e,n),{samples:[...r.values()]}}function g(t,e){const n=new Map;if("sample_id"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.sample_id))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}if("case_uuid"in t[0]){for(const r of t){const t=r[e];t&&(n.has(t)||n.set(t,new Set),n.get(t).add(r.case_uuid))}const r=new Map;for(const[t,e]of n)r.set(t,e.size);return r}for(const e of t){const t=e[term.id];t&&n.set(t,1+(n.get(t)||0))}return n}},334:(t,e,n)=>{var r;const o=n(7147),i=n(1017),s=process.cwd()?process.cwd()+"/serverconfig.json":"",a=i.join(__dirname,"../serverconfig.json"),l=i.join(__dirname,"../../serverconfig.json"),c=s&&o.existsSync(s)?s:o.existsSync(a)?a:o.existsSync(l)?l:"";let u;if(!c)throw"missing serverconfig.json";try{const t=o.readFileSync(c,{encoding:"utf8"});u=JSON.parse(t)}catch(t){throw`Error reading or parsing ${c}:`+t}if(u.port||(u.port=process.env.PP_PORT||3e3),u.tabix||(u.tabix="tabix"),u.samtools||(u.samtools="samtools"),u.bcftools||(u.bcftools="bcftools"),u.hicstraw||(u.hicstraw="straw"),u.bigwigsummary||(u.bigwigsummary="bigWigSummary"),u.bigBedToBed||(u.bigBedToBed="bigBedToBed"),u.bigBedInfo||(u.bigBedInfo="bigBedInfo"),u.bigBedNamedItems||(u.bigBedNamedItems="bigBedNamedItems"),u.clustalo||(u.clustalo="clustalo"),u.Rscript||(u.Rscript="Rscript"),u.gfServer||(u.gfServer="gfServer"),u.gfClient||(u.gfClient="gfClient"),!("allow_env_overrides"in u)&&u.debugmode&&(u.allow_env_overrides=!0),!u.binpath){const t=process.argv.find((t=>t.includes("/build")));if(t)u.binpath=t.split("/build")[0]+"/server";else{if(process.argv.find((t=>t.includes(".spec.js"))))u.binpath=i.dirname(__dirname);else{const t=process.argv.find((t=>t.endsWith("/bin.js")||t.endsWith("/server.js")||t.endsWith("/proteinpaint")||t.endsWith("/proteinpaint-server")));if(t)try{const e=o.realpathSync(t);u.binpath=i.dirname(e)}catch(t){throw t}else if(o.existsSync("./server"))u.binpath=o.realpathSync("./server");else if(o.existsSync("./src"))u.binpath=o.realpathSync("./src/..");else if(__dirname.includes("/server/"))u.binpath=__dirname.split("/server/")[0]+"/server";else{if(!__dirname.includes("/proteinpaint"))throw"unable to determine the serverconfig.binpath";u.binpath=__dirname}}}}if(u.debugmode){const t=[],e=i.join(u.binpath,"src/test/routes"),n=["gdc.js","specs.js","readme.js"];if(u.routeSetters)for(const r of u.routeSetters)if(!n.includes(r))if(o.existsSync(r))t.push(r);else if(o.existsSync(`${e}/${r}`))t.push(`${e}/${r}`);else{const e=i.join(u.binpath,r);o.existsSync(e)&&t.push(e)}for(const r of n){const n=`${e}/${r}`;!t.includes(n)&&o.existsSync(n)&&t.push(n)}u.routeSetters=t}if(u.allow_env_overrides){if(process.env.PP_URL&&(u.URL=process.env.URL),"PP_BASEPATH"in process.env&&(u.basepath=process.env.PP_BASEPATH),o.existsSync("./.ssl")&&!u.ssl){u.ssl={};const t=o.readdirSync("./.ssl");for(const e of t)e.endsWith(".key")&&(u.ssl.key=process.cwd()+"/.ssl/"+e),e.endsWith(".crt")&&(u.ssl.cert=process.cwd()+"/.ssl/"+e)}"PP_BACKEND_ONLY"in process.env&&(u.backend_only=1==+process.env.PP_BACKEND_ONLY||"true"===process.env.PP_BACKEND_ONLY)}if(null!==(r=process.env.PP_MODE)&&void 0!==r&&r.startsWith("container")&&Object.assign(u,{port:3e3,tpmasterdir:"/home/root/pp/tp",cachedir:"/home/root/pp/cache",hicstraw:"/home/root/pp/tools/straw",bigwigsummary:"/home/root/pp/tools/bigWigSummary",bigBedToBed:"/home/root/pp/tools/bigBedToBed",bigBedNamedItems:"/home/root/pp/tools/bigBedNamedItems",bigBedInfo:"/home/root/pp/tools/bigBedInfo"}),u.features||(u.features={}),process.argv.find((t=>"validate"==t))&&(u.features.stopGdcCacheAliquot=!0),!u.backend_only&&o.existsSync(i.join(process.cwd(),"./public"))){const t=i.join(u.binpath,"cards");u.cards||(u.cards={target:t,path:"cards"})}if(o.existsSync("./public/rev.txt")){const t=o.readFileSync("./public/rev.txt",{encoding:"utf8"}).trim().split(" ")[1];t&&(u.commitHash=t)}if(o.existsSync("./package.json")){const t=o.readFileSync("./package.json",{encoding:"utf8"});u.version=JSON.parse(t).version}t.exports=u},938:(t,e,n)=>{"use strict";n.d(e,{e8:()=>f,Tt:()=>h,TO:()=>u});n(1017);var r=n(3345);const o=require("partjson");var i=n.n(o),s=n(2163),a=n(1271),l=n(2974),c=n(2273);(0,s.WU)(".3r");function u(t){return async(e,n)=>{const r=e.query;for(const t of[0,1,2]){const e="term"+t,n=e+"_id";"string"==typeof r[n]?r[n]=decodeURIComponent(r[n]):"string"==typeof r[e]&&(r[e]=JSON.parse(decodeURIComponent(r[e])));const o=e+"_q";"string"==typeof r[o]&&(r[o]=JSON.parse(decodeURIComponent(r[o])))}try{const e=t[r.genome];if(!e)throw"invalid genome";const o=e.datasets[r.dslabel];if(!o)throw"invalid dslabel";if(!o.cohort)throw"ds.cohort missing";const i=o.cohort.termdb;if(!i)throw"no termdb for this dataset";const s=await f(r,o,i);r.term2_q&&await async function(t,e,n){const r=[];for(const e of t.charts){const t={};t.chartId=e.chartId,t.serieses=[];const o=e.serieses.filter((t=>!n.term1.includes(t.seriesId)));for(const e of o){const r={};r.seriesId=e.seriesId,r.data=e.data.filter((t=>!n.term2.includes(t.dataId))),r.total=r.data.reduce(((t,e)=>t+e.total),0),t.serieses.push(r)}t.total=t.serieses.reduce(((t,e)=>t+e.total),0),t.maxSeriesTotal=t.serieses.reduce(((t,e)=>t<e.total?e.total:t),0),r.push(t)}t.tests={};for(const n of r){const r={};for(const t of n.serieses)for(const e of t.data)r[e.dataId]=void 0===r[e.dataId]?e.total:r[e.dataId]+e.total;const o=[];let i=0;const s=new Map;for(const t of n.serieses)for(const e of t.data){const a=e.total,l=r[e.dataId]-e.total,c=t.total-e.total,u=n.total-r[e.dataId]-(t.total-e.total),f=t.seriesId,d=e.dataId;o.push({index:i,n1:a,n2:l,n3:c,n4:u}),s.set(i,{seriesId:f,dataId:d}),i++}const l={input:o},c=e.cohort.termdb.multipleTestingCorrection;c&&(l.mtc=c.method,c.skipLowSampleSize&&(l.skipLowSampleSize=c.skipLowSampleSize));const u=await(0,a.run_rust)("fisher",JSON.stringify(l)),f=[];for(const t of JSON.parse(u)){const e=s.get(t.index).seriesId,n=s.get(t.index).dataId,r=t.n1,o=t.n2,i=t.n3,a=t.n4,l=t.p_value,c="chisq"===t.fisher_chisq,u=null===l,d=t.adjusted_p_value,h=f.find((t=>t.term1comparison===e));h?h.term2tests.push({term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:o,R1C2:i,R2C2:a},isChi:c,skipped:u}):f.push({term1comparison:e,term2tests:[{term2id:n,pvalue:l,adjusted_p_value:d,tableValues:{R1C1:r,R2C1:o,R1C2:i,R2C2:a},isChi:c,skipped:u}]})}t.tests[n.chartId]=f}}(s.data,o,r.hiddenValues),n.send(s)}catch(t){n.send({error:t.message||t}),t.stack&&console.log(t.stack)}}}async function f(t,e,n){if(t.ds=e,t.ssid){const[e,n]=await r.L0(t.ssid);t.sample2gt=e,t.genotype2sample=n}const o=+new Date;t.results={};const s=new Map;for(let e=0;e<=2;e++){let n=null;if(t[`term${e}_id`]){const r=t[`term${e}_id`];n={id:r,q:t[`term${e}_q`],term:{id:r}}}else t[`term${e}`]&&(n={term:t[`term${e}`],q:t[`term${e}_q`]});n&&s.set(e,n)}const a=[...s.values()],u=await(0,l.Yu)({filter:t.filter,terms:a},t.ds,t.genome),f=new Map,p=[];var m,g,y,v;if(u.samples)if("geneVariant"==(null===(m=s.get(1))||void 0===m||null===(g=m.term)||void 0===g?void 0:g.type)||"geneVariant"==(null===(y=s.get(2))||void 0===y||null===(v=y.term)||void 0===v?void 0:v.type))!function(t,e,n,r,o){var i,s,a,l;e.push([]);let u=1;const f=t.get(1)?t.get(1).term:null,d=null!=f&&f.id?f.id:null==f?void 0:f.name;d&&null!==(i=n.refs.byTermId[d])&&void 0!==i&&i.bins?e.push(null===(s=n.refs.byTermId[d])||void 0===s?void 0:s.bins):e.push([]);const h=t.get(2)?t.get(2).term:null,p=null!=h&&h.id?h.id:null==h?void 0:h.name;p&&null!==(a=n.refs.byTermId[p])&&void 0!==a&&a.bins?e.push(null===(l=n.refs.byTermId[p])||void 0===l?void 0:l.bins):e.push([]);for(const[e,i]of Object.entries(n.samples)){var m,g,y,v;const n=parseInt(e);if("geneVariant"==(null===(m=t.get(1))||void 0===m||null===(g=m.term)||void 0===g?void 0:g.type)){const t=[],e=i[d];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key1){const t=e.item.key1;e.item.key1={},e.item.key1[t]=1}e.item.key1[c.mclass[r.class].label]=e.item.key1[c.mclass[r.class].label]?e.item.key1[c.mclass[r.class].label]+1:1}else{var b,w,_;const e={sample:u,name:o.sampleId2Name.get(n)};e.key1=c.mclass[r.class].label,e.val1=c.mclass[r.class].label;const s=null===(b=o.assayAvailability)||void 0===b||null===(w=b.byDt)||void 0===w||null===(_=w[r.dt])||void 0===_?void 0:_.byOrigin;var x;if(s)e.key0=e.val0=((null===(x=s[r.origin])||void 0===x?void 0:x.label)||r.origin)+" "+c.dt2label[r.dt];else e.key0=e.val0=c.dt2label[r.dt];e.key2=i[p]?i[p].key:"",e.val2=i[p]?i[p].value:"",t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key1){let t="";for(const[n,r]of Object.entries(e.item.key1))t+=`${n}(${r})+`;e.item.key1=t.slice(0,-1),e.item.val1=t.slice(0,-1)}r.set(u.toString(),e.item),u++}}else if("geneVariant"==(null===(y=t.get(2))||void 0===y||null===(v=y.term)||void 0===v?void 0:v.type)){const t=[],e=i[p],s=i[d];for(const r of e.values)if(t.some((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))){const e=t.filter((t=>t.value.dt==r.dt&&(!r.origin||r.origin==t.value.origin)))[0];if("object"!=typeof e.item.key2){const t=e.item.key2;e.item.key2={},e.item.key2[t]=1}e.item.key2[c.mclass[r.class].label]=e.item.key2[c.mclass[r.class].label]?e.item.key2[c.mclass[r.class].label]+1:1}else{var k,q,N;const e={sample:u,name:o.sampleId2Name.get(n)};e.key1=s.key,e.val1=s.value;const i=null===(k=o.assayAvailability)||void 0===k||null===(q=k.byDt)||void 0===q||null===(N=q[r.dt])||void 0===N?void 0:N.byOrigin;var S;if(i)e.key0=e.val0=((null===(S=i[r.origin])||void 0===S?void 0:S.label)||r.origin)+" "+c.dt2label[r.dt];else e.key0=e.val0=c.dt2label[r.dt];e.key2=c.mclass[r.class].label,e.val2=c.mclass[r.class].label,t.push({value:r,item:e})}for(const e of t){if("object"==typeof e.item.key2){let t="";for(const[n,r]of Object.entries(e.item.key2))t+=`${n}(${r})+`;e.item.key2=t.slice(0,-1),e.item.val2=t.slice(0,-1)}r.set(u.toString(),e.item),u++}}}}(s,p,u,f,e);else for(let t=0;t<=2;t++){var b,w,_;const e=null===(b=s.get(t))||void 0===b?void 0:b.q,n=s.get(t)?s.get(t).term:null,r=null!=n&&n.id?n.id:null==n?void 0:n.name;if(r&&null!==(w=u.refs.byTermId[r])&&void 0!==w&&w.bins?p.push(null===(_=u.refs.byTermId[r])||void 0===_?void 0:_.bins):p.push([]),null!=e&&e.binColored)for(const n of p[t]){const t=e.binColored;n.start==t.start&&n.stop==t.stop&&(n.color=t.color)}for(const[e,n]of Object.entries(u.samples)){let o;if(f.get(e))o=f.get(e);else if(!f.has(e)){o={sample:parseInt(e)},f.set(e,o)}if(o)if(r){const i=n[r];i?(o[`key${t}`]=i.key,o[`val${t}`]=i.value):f.set(e,null)}else o[`key${t}`]="",o[`val${t}`]=""}}t.results.lst=[...f.values()].filter((t=>null!==t)),t.results.bins=p;const x=+new Date,k=function(t,e,n,o){const s=[0,1,2].map((e=>{const r=function(t,e,n){const r=t["term"+n+"_id"];let o={};t[r]||r?o=e.q.termjsonByOneid(r):t[`term${n}`]&&(o=t[`term${n}`]);const i="integer"==o.type||"float"==o.type,s=o.values?Object.keys(o.values).filter((t=>o.values[t].uncomputable)).map((t=>+t)):[],a=t=>i&&!s.includes(t),l=t["term"+n+"_q"]?t["term"+n+"_q"]:{};return{term:o,isComputableVal:a,q:l}}(t,n,e);r.q.index=e;const o=t.results.bins[e];return Object.assign(r,{key:"key"+e,val:"val"+e,nval:"nval"+e,bins:o,q:r.q,orderedLabels:h(r.term,o,void 0,r.q)})}));return new(i())({data:e,seed:'{"results": {"charts": [], "refs":{}}}',template:d,"=":{prep(t){for(const e of s)"condition"==e.term.type?(t[e.key]=e.q.bar_by_grade&&t[e.key]in e.term.values?e.term.values[t[e.key]].label:t[e.key],t[e.val]=t[e.key]):"float"!=e.term.type&&"integer"!=e.term.type||e.isComputableVal(t[e.val])&&(t[e.nval]=t[e.val]);return!0},sampleCount:(t,e)=>e.self.samples?e.self.samples.size:void 0,maxSeriesTotal(t,e){let n=0;for(const t of e.self.serieses)t&&t.total>n&&(n=t.total);return n},maxAcrossCharts(t,e){let n=0;for(const t of e.self.charts)t.maxSeriesTotal>n&&(n=t.maxSeriesTotal);return n},boxplot(t,e){const n=e.self.values;if(!n||!n.length)return;n.sort(((t,e)=>t-e));const o=r.JC(n.map((t=>({value:+t}))));o.mean=e.self.sum/n.length;let i=0;for(const t of n)i+=Math.pow(t-o.mean,2);return o.sd=Math.sqrt(i/(n.length-1)),o.min=e.self.min,o.max=e.self.max,o},getAF(e,n){if(o.track&&o.track.vcf&&o.track.vcf.termdb_bygenotype&&o.track.vcf.termdb_bygenotype.getAF&&t.term2_is_genotype){if(!t.chr)throw"chr missing for getting AF";if(!t.pos)throw"pos missing for getting AF";return function(t,e,n,o,i){const s=i.track.vcf.termdb_bygenotype,a=o.has(r.EO.href)?o.get(r.EO.href):new Set,l=o.has(r.EO.halt)?o.get(r.EO.halt):new Set,c=o.has(r.EO.het)?o.get(r.EO.het):new Set;let u=0,f=0;for(const r of t){let t=!1;if(s.sex_chrs.has(e))if(s.male_samples.has(r)){if(s.chr2par&&s.chr2par[e])for(const r of s.chr2par[e])if(n>=r.start&&n<=r.stop){t=!0;break}}else t=!0;else t=!0;t?(f+=2,l.has(r)?u+=2:c.has(r)&&u++):(f++,a.has(r)||u++)}return 0==f||0==u?0:(u/f).toFixed(3)}(n.self.samples?[...n.self.samples]:[],t.chr,Number(t.pos),t.genotype2sample,o)}},filterEmptySeries(t){const e=t.serieses.filter((t=>t.total));t.serieses.splice(0,t.serieses.length,...e)},bins:()=>s.map((t=>t.bins)),q:()=>s.map(((t,e)=>{const n={};for(const e in t.q)"index"!=e&&(n[e]=t.q[e]);return n})),useColOrder:()=>s[1].orderedLabels.length>0,useRowOrder:()=>s[2].orderedLabels.length>0,sortColsRows(t){if(s[1].orderedLabels.length){const e=s[1].orderedLabels;t.cols.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}if(s[2].orderedLabels.length){const e=s[2].orderedLabels;t.rows.sort(((t,n)=>e.indexOf(t)-e.indexOf(n)))}},sortCharts(t){if(s[0].orderedLabels.length){const e=s[0].orderedLabels;t.charts.sort(((t,n)=>e.indexOf(t.chartId)-e.indexOf(n.chartId)))}}}})}(t,t.results.lst,n,e);k.tree.results&&(k.tree.results.times={sql:x-o,pj:k.times});return{data:k.tree.results,bins:p}}const d=JSON.stringify({"@errmode":["","","",""],"@before()":"=prep()",results:{"_2:maxAcrossCharts":"=maxAcrossCharts()","_:_min":">$nval1","_:_max":"<$nval1",charts:[{chartId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()","_1:maxSeriesTotal":"=maxSeriesTotal()","@done()":"=filterEmptySeries()",serieses:[{seriesId:"@key",data:[{dataId:"@key","~samples":["$sample","set"],"__:total":"=sampleCount()"},"$key2"],"_:_max":"<$nval2","~values":["$nval2",0],"~sum":"+$nval2","~samples":["$sample","set"],"__:total":"=sampleCount()","__:boxplot":"=boxplot()","__:AF":"=getAF()"},"$key1"]},"$key0"],"~sum":"+$nval1","~values":["$nval1",0],"__:boxplot":"=boxplot()","_:_refs":{cols:["$key1"],colgrps:["-"],rows:["$key2"],rowgrps:["-"],col2name:{$key1:{name:"@branch",grp:"-"}},row2name:{$key2:{name:"@branch",grp:"-"}},"__:useColOrder":"=useColOrder()","__:useRowOrder":"=useRowOrder()","__:bins":"=bins()","__:q":"=q()","@done()":"=sortColsRows()"},"@done()":"=sortCharts()"}});function h(t,e,n,r){if(n)return n.map((t=>t.label));if("condition"==t.type){var o;if(null!=r&&null!==(o=r.groups)&&void 0!==o&&o.length)return r.groups.map((t=>t.name));if(t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label))}const i=Object.values(t.values||{})[0];return i&&"order"in i?Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:"order"in t.values[e]?t.values[e].order:"order"in t.values[n]?t.values[n].order:0)).map((e=>t.values[e].key)):null==e?void 0:e.map((t=>t.name?t.name:t.label))}},4453:(t,e,n)=>{"use strict";n.d(e,{g:()=>d,y:()=>h});var r=n(1017),o=n.n(r),i=n(8907),s=n(3345),a=n(7147),l=n.n(a),c=n(9157),u=n(334),f=n.n(u);async function d(t,e){try{if(!e.cohort)throw"cohort missing from ds";const n=e.cohort.termdb.minTimeSinceDx;if(!n)throw"missing min time since dx";t.ds=e;const r={data:{}},o=await(0,i.g5)(t);if(!o.lst.length)return r;const s={};for(const t of o.lst){const e=t.key0,n=t.val1,r=t.key1,o=t.key2;e in s||(s[e]=[]),s[e].push({time:n,event:r,series:o})}const a=t.term2_id&&o.CTE2.bins?o.CTE2.bins:[];r.refs={bins:a};const l={data:{},startTime:n};r.noEvents={};for(const t in s){const e=s[t],n=new Set(e.map((t=>t.series)));for(const o of n)e.find((t=>t.series==o&&1===t.event))||(t in r.noEvents?r.noEvents[t].push(o):r.noEvents[t]=[o]);const o=e.filter((e=>{var n;return!(null!==(n=r.noEvents[t])&&void 0!==n&&n.includes(e.series))}));o.length?l.data[t]=o:r.data[t]={}}if(!Object.keys(l.data).length)return{data:{}};const c=await h(l);return Object.assign(r.data,c),r}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function h(t){for(let e in t.data)""===e&&(e="*",t.data[e]=t.data[""],delete t.data[""]),t.data[e]=t.data[e].map((t=>({time:t.time,event:t.event,series:""===t.series?"*":t.series})));const e=o().join(f().cachedir,Math.random().toString()+".json");await(0,s.Sf)(e,JSON.stringify(t));const n=await(0,c.default)(o().join(f().binpath,"utils/cuminc.R"),[],[e]),r=JSON.parse(n[0]);for(const t in r)"*"===t&&(r[""]=r[t],delete r[t]);for(const t in r)for(const e in r[t].estimates)"*"===e&&(r[t].estimates[""]=r[t].estimates[e],delete r[t].estimates[e]);return l().unlink(e,(()=>{})),r}},5257:(t,e,n)=>{"use strict";async function r(t,e,n="f"){if(!t)return;if("tvslst"!=t.type)throw'filter.type is not "tvslst" but: '+t.type;if(!Array.isArray(t.lst))throw"filter.lst must be an array";if(0==t.lst.length)return console.error("filter.lst[] is zero length, see if is an error");if(1==t.lst.length){if("tvslst"==t.lst[0].type)throw'only one element at a level: type should not be "tvslst"'}else if("or"!=t.join&&"and"!=t.join)throw'multiple elements at a level: filter.join must equal either "or" or "and"';"in"in t||(t.in=!0);const u=[],f=[],d=[];for(const[h,p]of t.lst.entries()){const t=n+"_"+h;let m;if("tvslst"==p.type)m=await r(p,e,t);else{if(!p.tvs)throw"filter item should have a 'tvs' or 'lst' property";if("categorical"==p.tvs.term.type)m=o(p.tvs,t);else if("survival"==p.tvs.term.type)m=i(p.tvs,t);else if("samplelst"==p.tvs.term.type)m=s(p.tvs,t);else if("integer"==p.tvs.term.type||"float"==p.tvs.term.type)m=l(p.tvs,t,e);else if("condition"==p.tvs.term.type)m=c(p.tvs,t);else{if("geneVariant"!=p.tvs.term.type)throw"unknown term type";m=await a(p.tvs,t,e)}}u.push(m.CTEname),f.push(...m.CTEs),d.push(...m.values)}const h="and"==t.join?"INTERSECT":"UNION",p=u.map((t=>"SELECT * FROM "+t)).join("\n"+h+"\n");return t.in?f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\t${p}\n\t\t\t\t)\n\t\t\t`):f.push(`\n\t\t\t\t${n} AS (\n\t\t\t\t\tSELECT id as sample\n\t\t\t\t\tFROM sampleidmap\n\t\t\t\t\tWHERE sample NOT IN (\n\t\t\t\t\t\t${p}\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t`),{filters:f.join(",\n"),CTEs:f,values:d,CTEname:n}}function o(t,e){return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id = ?\n\t\t\t\tAND value ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function i(t,e){var n,r;return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM survival\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${null!==(n=t.q)&&void 0!==n&&n.cutoff?"AND tte >= "+(null===(r=t.q)||void 0===r?void 0:r.cutoff):""}\n\t\t\t\tAND exit_code ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[t.term.id,...t.values.map((t=>t.key))],CTEname:e}}function s(t,e){const n=[];for(const e in t.term.values)n.push(...t.term.values[e].list);return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${Array(n.length).fill("?").join(", ")})\n\t\t\t)`],values:[...n.map((t=>t.sampleId))],CTEname:e}}async function a(t,e,n){const r={term:t.term,q:{}},o=await n.mayGetGeneVariantData(r,{genome:n.genomename}),i=[];for(const[e,n]of o){const r=n[t.term.name].values;let o=!0;for(const e of t.values){const t=r.filter((t=>t.dt==e.dt&&(!e.origin||e.origin==t.origin)));for(const n of t)if(e.mclassExcludeLst.includes(null==n?void 0:n.class)){o=!1;break}}o&&i.push(e)}return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT id as sample\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE id IN (${i.map((t=>"?")).join(", ")})\n\t\t\t)`],values:[...i],CTEname:e}}function l(t,e,n){if(!t.ranges)throw".ranges{} missing";const r=[t.term.id],o=n.cohort.termdb.q.termjsonByOneid(t.term.id),i=[];let s,a=!1;for(const e of t.ranges)if("value"in e){const n=t.isnot?"!":"";i.push(`value ${n}= ?`),r.push(""+e.value)}else{a=!0;const n=[];e.startunbounded||(e.startinclusive?n.push("value >= ?"):n.push("value > ? "),r.push(e.start)),e.stopunbounded||(e.stopinclusive?n.push("value <= ?"):n.push("value < ? "),r.push(e.stop));const o=t.isnot?"NOT ":"";n.length&&i.push(o+"("+n.join(" AND ")+")")}a&&o.values&&(s=Object.keys(o.values).filter((t=>o.values[t].uncomputable)).map(Number).filter((e=>t.isnot||!t.ranges.find((t=>"value"in t&&Number(t.value)==e)))),s.length&&r.push(...s));const l=i.join(" OR ");return{CTEs:[`\n\t\t ${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM anno_${o.type}\n\t\t\t\tWHERE term_id = ?\n\t\t\t\t${l?"AND ("+l+")":""}\n\t\t\t\t${s&&s.length?`AND value NOT IN (${s.map((t=>"?")).join(",")})`:""}\n\t\t\t)`],values:r,CTEname:e}}function c(t,e){let n,r;if(t.bar_by_children)n="child";else{if(!t.bar_by_grade)throw"must set the bar_by_grade or bar_by_children query parameter";n="grade"}if(t.value_by_max_grade)r="max_grade";else if(t.value_by_most_recent)r="most_recent";else{if(!t.value_by_computable_grade)throw"unknown setting of value_by_?";r="computable_grade"}const o=[],i=[];if(!t.values)throw t.grade_and_child?"-- Todo: tvs.grade_and_child":'unknown condition term filter type: expecting term-value "values" or "grade_and_child" key';return i.push(t.term.id,...t.values.map((t=>""+t.key))),o.push(`\n\t\t\t${e} AS (\n\t\t\t\tSELECT sample\n\t\t\t\tFROM ${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\tWHERE term_id = ? \n\t\t\t\tAND ${r} = 1\n\t\t\t\tAND value ${t.isnot?"NOT":""} IN (${t.values.map((t=>"?")).join(", ")})\n\t\t\t)`),{CTEs:o,values:i,CTEname:e}}n.d(e,{w:()=>r})},2826:(t,e,n)=>{"use strict";n.d(e,{iK:()=>U,TO:()=>z});var r=n(334),o=n.n(r),i=n(394),s=(n(8088),n(6191));function a(t,e,n,r){const i=n.cohort.termdb,a={selectCohort:i.selectCohort,supportedChartTypes:i.q.getSupportedChartTypes(t.embedder),allowedTermTypes:l(n),termMatch2geneSet:i.termMatch2geneSet,massSessionDuration:o().features.massSessionDuration||30,dataDownloadCatch:i.dataDownloadCatch,matrix:i.matrix,hierCluster:i.hierCluster,mclass:i.mclass,alwaysRefillCategoricalTermValues:i.alwaysRefillCategoricalTermValues,isGeneSetTermdb:i.isGeneSetTermdb,lollipop:i.lollipop,urlTemplates:i.urlTemplates};i.chartConfigByType&&(a.chartConfigByType=i.chartConfigByType),i.multipleTestingCorrection&&(a.multipleTestingCorrection=i.multipleTestingCorrection),i.helpPages&&(a.helpPages=i.helpPages),i.minTimeSinceDx&&(a.minTimeSinceDx=i.minTimeSinceDx),i.timeUnit&&(a.timeUnit=i.timeUnit),i.cohortStartTimeMsg&&(a.cohortStartTimeMsg=i.cohortStartTimeMsg),i.displaySampleIds&&(a.displaySampleIds=i.displaySampleIds),i.additionalSampleAttributes&&(a.additionalSampleAttributes=i.additionalSampleAttributes),i.logscaleBase2&&(a.logscaleBase2=i.logscaleBase2),n.assayAvailability&&(a.assayAvailability=n.assayAvailability),n.customTwQByType&&(a.customTwQByType=n.customTwQByType),a.requiredAuth=s.i.getRequiredCredForDsEmbedder(t.dslabel,t.embedder),function(t,e){if(!e.restrictAncestries)return;t.restrictAncestries=e.restrictAncestries.map((t=>({name:t.name,tvs:t.tvs})))}(a,i),function(t,e){if(!e.cohort.scatterplots)return;t.scatterplots=e.cohort.scatterplots.plots.map((t=>({name:t.name,dimensions:t.dimensions,colorTW:t.colorTW,shapeTW:t.shapeTW})))}(a,n),function(t,e){if(!e.cohort.matrixplots)return;t.matrixplots=e.cohort.matrixplots.plots.map((t=>({name:t.name})))}(a,n),function(t,e,n){const r=e.queries;if(!r)return;t.queries={defaultCoord:r.defaultCoord||n.defaultcoord};const o=t.queries;r.defaultBlock2GeneMode&&(o.defaultBlock2GeneMode=r.defaultBlock2GeneMode);r.snvindel&&(o.snvindel={allowSNPs:r.snvindel.allowSNPs});r.topMutatedGenes&&(o.topMutatedGenes=r.topMutatedGenes);r.topVariablyExpressedGenes&&(o.topVariablyExpressedGenes=r.topVariablyExpressedGenes);r.singleSampleMutation&&(o.singleSampleMutation={sample_id_key:r.singleSampleMutation.sample_id_key,discoSkipChrM:r.singleSampleMutation.discoSkipChrM});if(r.singleSampleGenomeQuantification){o.singleSampleGenomeQuantification={};for(const t in r.singleSampleGenomeQuantification)o.singleSampleGenomeQuantification[t]=JSON.parse(JSON.stringify(r.singleSampleGenomeQuantification[t])),delete o.singleSampleGenomeQuantification[t].folder}if(r.singleSampleGbtk){o.singleSampleGbtk={};for(const t in r.singleSampleGbtk)o.singleSampleGbtk[t]=JSON.parse(JSON.stringify(r.singleSampleGbtk[t])),delete o.singleSampleGbtk[t].folder}r.rnaseqGeneCount&&(o.rnaseqGeneCount=!0)}(a,n,r),e.send({termdbConfig:a})}function l(t){var e;(0,i.qN)(t);const n=new Set;for(const e of t.cohort.termdb.termtypeByCohort)e.type&&n.add(e.type);if(t.cohort.termdb.allowedTermTypes)for(const e of t.cohort.termdb.allowedTermTypes)n.add(e);return null!=t&&null!==(e=t.queries)&&void 0!==e&&e.defaultBlock2GeneMode&&n.add("geneVariant"),[...n]}var c=n(8907),u=n(5708),f=n(4453),d=n(1017),h=n.n(d),p=n(2974),m=n(3345),g=n(7147),y=n.n(g),v=n(9157);async function b(t,e){try{var n;if(!e.cohort)throw"cohort missing from ds";t.ds=e;const r=[];for(const e of[0,1,2]){const n="term"+e,o=n+"_id";"string"==typeof t[o]?(t[o]=decodeURIComponent(t[o]),t[n]=t.ds.cohort.termdb.q.termjsonByOneid(t[o])):"string"==typeof t[n]&&(t[n]=JSON.parse(decodeURIComponent(t[n])));const i=n+"_q";t[n]&&r.push({term:t[n],q:t[i]})}if(t.term2){if("survival"==t.term2.type&&"survival"==t.term1.type)throw"term and overlay are both survival terms - only one could be a survival term";if("survival"!=t.term2.type&&"survival"!=t.term1.type)throw"no survival terms, either the main term OR the overlay term must be a survival term"}else if("survival"!=t.term1.type)throw"non-survival term";if(t.term0&&"survival"==t.term0.type)throw"term0 must not be a survival term";const i=function(t){if(t.term1&&"survival"==t.term1.type)return 1;if(!t.term2)throw"term1.type is not survival and term2 is missing";if("survival"!=t.term2.type)throw"both term1 and term2 are not survival type";return 2}(t),s=t[`term${i}`],a=t["term"+(1==i?2:1)],l=await(0,p.Yu)({terms:r,filter:t.filter},e,t.genome);if(l.error)throw l.error;const c=function(t,e){const n=Object.values(t.samples).filter((t=>t[e.id]));return n.sort(((t,n)=>t[e.id].value<n[e.id].value?-1:1))}(l,s),u={},f={chart:new Set,series:new Set};for(const e of c){const n=e[s.id],r=n.value;if(r<0)continue;const o=n.key;let i;if(a)if("id"in a){if(!(a.id in e))continue;i=e[a.id].key}else if("samplelst"==a.type){if(!(a.name in e))continue;i=e[a.name].key}else i=w(a,e);else i="*";f.series.add(i);const l=t.term0&&e[t.term0.id||t.term0.name]||{key:""};l.key in u||(u[l.key]=[],f.chart.add(l.key)),u[l.key].push({time:r,status:o,series:i})}const d=t.term2_id&&(null===(n=l.refs[t.term2.id])||void 0===n?void 0:n.bins)||[],g={keys:["chartId","seriesId","time","survival","lower","upper","nevent","ncensor","nrisk"],case:[],refs:{bins:d}};for(const t in u){const e=u[t],n=h().join(o().cachedir,Math.random().toString()+".json");await(0,m.Sf)(n,JSON.stringify(e));const r=await(0,v.default)(h().join(o().binpath,"utils/survival.R"),[],[n]),i=JSON.parse(r);for(const e of i.estimates){for(const t in e)e[t]="series"==t?"*"==e[t]?"":e[t]:Number(e[t]);g.case.push([t,e.series,e.time,e.surv,e.lower,e.upper,e.nevent,e.ncensor,e.nrisk])}i.tests&&(g.tests||(g.tests={}),g.tests[t]=i.tests),y().unlink(n,(()=>{}))}g.case.sort(((t,e)=>t[2]-e[2]));const b=function(t,e=[]){if(t){if("condition"==t.type&&t.values)return Object.keys(t.values).map(Number).sort(((t,e)=>t-e)).map((e=>t.values[e].label));if(t.values)return Object.keys(t.values).sort(((e,n)=>"order"in t.values[e]&&"order"in t.values[n]?t.values[e].order-t.values[n].order:0)).map((e=>t.values[e].label))}return e.map((t=>t.name?t.name:t.label))}(t.term2,d?d.map((t=>t.name?t.name:t.label)):[]);return g.refs.orderedKeys={chart:[...f.chart].sort(),series:[...f.series].sort(b?(t,e)=>b.indexOf(t)-b.indexOf(e):void 0)},g}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function w(t,e){const n=t.name;if("geneVariant"==t.type){if(!e[n]||!e[n].values)return"Wildtype";const t=e[n].values.filter((t=>"Blank"!=t.class));return t.find((t=>"WT"!=t.class))?`${n} Variant`:t.find((t=>"WT"==t.class))?`${n} Wildtype`:e[n].values.length>t.length?"Not tested":"Not sure"}throw`cannot get series key for term='${n}'`}var _=n(8599),x=n(3795),k=n(1575),q=n(2188);var N=n(478),S=n(1271);async function A(t,e,n,r){!function(t,e){if(!t.chr)throw"q.chr missing";if(t.start=Number(t.start),t.stop=Number(t.stop),!Number.isInteger(t.start)||!Number.isInteger(t.stop))throw"q.start/stop is not integer";if("object"!=typeof t.details)throw"q.details{} not object";if(!Array.isArray(t.details.groups))throw"q.details.groups[] not array";if(!t.details.groups[0])throw"q.details.groups[0] missing";if(t.details.groups.length>2)throw"q.details.groups[] has more than 2";for(const r of t.details.groups)if("filter"==r.type){if("object"!=typeof r.filter)throw".filter not an object for group type=filter"}else if("population"==r.type){var n;if(!r.key)throw".key missing from group type=population";if(null===(n=e.queries.snvindel)||void 0===n||!n.populations)throw"group type=population but this ds does not have populations";if(!e.queries.snvindel.populations.find((t=>t.key==r.key)))throw"invalid key of group type=population"}else{if("info"!=r.type)throw"unknown group type from details.groups[]";if(!r.infoKey)throw".infoKey missing from group type=info"}if(t.details.groupTestMethods){if(!Array.isArray(t.details.groupTestMethods))throw"details.groupTestMethods[] not array";if(!Number.isInteger(t.details.groupTestMethodsIdx))throw"details.groupTestMethodsIdx not integer";if(!t.details.groupTestMethods[t.details.groupTestMethodsIdx])throw"invalid array index of details.groupTestMethodsIdx"}}(t,n);const o=await async function(t,e){const n={rglst:[{chr:t.chr,start:t.start,stop:t.stop}],addFormatValues:!0,variantFilter:t.variantFilter},[r,o]=t.details.groups;if("filter"==r.type&&"filter"==(null==o?void 0:o.type)){n.filterObj=C(t,r.filter);const i=T(await e.queries.snvindel.byrange.get(n));n.filterObj=C(t,o.filter);const s=T(await e.queries.snvindel.byrange.get(n)),a=function(t,e,n){const[r,o]=n.details.groups,i=[];for(const n of t){n.groupData=[{refCount:n._refCount,altCount:n._altCount}];const t=e.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt));t?n.groupData.push({refCount:t._refCount,altCount:t._altCount}):n.groupData.push({refCount:0,altCount:0}),i.push(n)}for(const n of e){t.find((t=>t.chr==n.chr&&t.pos==n.pos&&t.ref==n.ref&&t.alt==n.alt))||(n.groupData=[{refCount:0,altCount:0},{refCount:n._refCount,altCount:n._altCount}],i.push(n))}return i}(i.mlst,s.mlst,t);return{mlst:a,totalSampleCount_group1:M(i.mlst),totalSampleCount_group2:M(s.mlst)}}n.filterObj=C(t);const i=await e.queries.snvindel.byrange.get(n),s=T(i);"filter"==r.type?s.totalSampleCount_group1=M(i):"filter"==(null==o?void 0:o.type)&&(s.totalSampleCount_group2=M(i));return s}(t,n);if(1==t.details.groups.length)j(n,o.mlst,t.details.groups[0]);else{if(2!=t.details.groups.length)throw"q.details.groups.length not 1 or 2";await async function(t,e,n){const[r,o]=e.groups;if("filter"==r.type&&"filter"==o.type)return void await async function(t,e,n){const r=e.groupTestMethods[e.groupTestMethodsIdx];if(!r)throw"details.groupTestMethodsIdx out of bound";switch(r.name){case"Allele frequency difference":return void O(t,e,n);case"Fisher's exact test":return void await P(n);default:throw"unknown value from groupTestMethods[]"}}(t,e,n.mlst);if("population"==r.type&&"filter"==o.type||"population"==o.type&&"filter"==r.type)return void await async function(t,e,n){const r=await async function(t,e,n){const r=e.groups.find((t=>"population"==t.type));if(!r)return;if(!r.adjust_race)return;const o=t.queries.snvindel.populations.find((t=>t.key==r.key));if(!o)throw"invalid group.key for population";const i=new Set;for(const t of n.mlst)for(const e of t.samples)i.add(e.sample_id);const s=new Map;let a=0;for(const e of o.sets){const n={infokey_AC:e.infokey_AC,infokey_AN:e.infokey_AN,average:0},r=await(0,c.J4)({ds:t,key:e.key});for(const t of r){if(!i.has(t.sample))continue;const e=Number(t.value);Number.isFinite(e)&&(n.average+=e,a+=e)}s.set(e.key,n)}for(const[t,e]of s)e.average/=a;n.pop2average={};for(const[t,e]of s)n.pop2average[t]=e.average;return s}(t,e,n);for(const o of n.mlst)o.groupData=I(t,e,o,r);const o=e.groupTestMethods[e.groupTestMethodsIdx];if(!o)throw"details.groupTestMethodsIdx out of bound";switch(o.name){case"Allele frequency difference":return void O(t,e,n.mlst);case"Fisher's exact test":return void await P(n.mlst);default:throw"unknown value from groupTestMethods[]"}}(t,e,n);O(t,e,n.mlst)}(n,t.details,o)}for(const t of o.mlst)delete t.samples,delete t._altCount,delete t._refCount;e.send(o)}function M(t){const e=new Set;for(const n of t)if(n.samples)for(const t of n.samples)e.add(t.sample_id);return e.size}function T(t){const e={mlst:[],skipMcountWithoutAlt:0};for(const n of t){const[t,r]=E(n);0!=t?(n._altCount=t,n._refCount=r-t,e.mlst.push(n)):e.skipMcountWithoutAlt++}return e}function C(t,e){const n=[t.filter];if(e)n.push(e);else for(const e of t.details.groups)"filter"==e.type&&n.push(e.filter);return(0,N.xH)(n)}function j(t,e,n){if("filter"!=n.type)if("info"!=n.type){if("population"!=n.type)throw"unknown type of single group";{const r=t.queries.snvindel.populations.find((t=>t.key==n.key));if(!r)throw"unknown population";for(const t of e){let e=0,n=0;for(const o of r.sets)e+=Number(t.info[o.infokey_AC]||0),n+=Number(t.info[o.infokey_AN]||0);t.nm_axis_value=e/n}}}else{if(!n.infoKey)throw"infoKey missing on single group.type=info";for(const t of e){const e=t.info[n.infoKey];if(null==e);else{const n=Number(e);Number.isNaN(n)||(t.nm_axis_value=n)}}}else for(const t of e)t.nm_axis_value=Number((t._altCount/(t._altCount+t._refCount)).toPrecision(2))}function E(t){let e=0,n=0;for(const o of t.samples){var r;if(null==o||null===(r=o.formatK2v)||void 0===r||!r.GT)continue;const i=o.formatK2v.GT.split("/").map(Number);n+=i.length;for(const n of i)n==t.altAlleleIdx&&e++}return[e,n]}function O(t,e,n){const[r,o]=e.groups;j(t,n,r);const i=n.map((t=>t.nm_axis_value));j(t,n,o);for(const[t,e]of n.entries())e.nm_axis_value=i[t]-e.nm_axis_value}function I(t,e,n,r){const o=[];for(const i of e.groups)if("info"!=i.type)if("filter"!=i.type){if("population"!=i.type)throw"unknown group.type";{if(!i.key)throw"group.key missing for type=population";const e=t.queries.snvindel.populations.find((t=>t.key==i.key));if(!e)throw"invalid group.key for population";const s=new Map;for(const t of e.sets)s.set(t.key,{ACraw:Number(n.info[t.infokey_AC]||0),ANraw:Number(n.info[t.infokey_AN]||0)});let a=0,l=0;if(i.adjust_race)[a,l]=R(s,r);else for(const t of s.values())l+=t.ACraw,a+=t.ANraw-t.ACraw;o.push({altCount:l,refCount:a})}}else o.push({altCount:n._altCount,refCount:n._refCount});else{if(!i.key)throw"group.key missing for type=info";o.push({value:n.info[i.key]})}return o}function R(t,e){let n=0;for(const e of t.values())n+=e.ANraw;let r=0,o=0;for(const[i,s]of t)s.ANadj=n*e.get(i).average,s.ACadj=0==s.ANadj?0:s.ACraw*s.ANadj/s.ANraw,r+=s.ACadj,o+=s.ANadj;return[o-r,r]}async function P(t){for(let e=0;e<Math.ceil(t.length/200);e++){const n=[];for(let r=200*e;r<200*(e+1);r++){const e=t[r];if(!e)break;const o=e.groupData;o&&o[0]&&o[1]&&Number.isFinite(o[0].altCount)&&Number.isFinite(o[0].refCount)&&Number.isFinite(o[1].altCount)&&Number.isFinite(o[1].refCount)?(n.push({index:r,n1:Math.floor(o[0].altCount),n2:Math.floor(o[0].refCount),n3:Math.floor(o[1].altCount),n4:Math.floor(o[1].refCount)}),e.htmlSections=[{key:"Contigency table",html:`<table style="font-size:.9em">\n\t\t\t\t<tr style="opacity:.5">\n\t\t\t\t <td></td>\n\t\t\t\t <td>Group1</td>\n\t\t\t\t <td>Group 2</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">ALT allele count</td>\n\t\t\t\t <td>${o[0].altCount}</td>\n\t\t\t\t <td>${Math.floor(o[1].altCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">REF allele count</td>\n\t\t\t\t <td>${o[0].refCount}</td>\n\t\t\t\t <td>${Math.floor(o[1].refCount)}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t <td style="opacity:.5">Allele frequency</td>\n\t\t\t\t <td>${(o[0].altCount/(o[0].altCount+o[0].refCount)).toFixed(3)}</td>\n\t\t\t\t <td>${(o[1].altCount/(o[1].altCount+o[1].refCount)).toFixed(3)}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>`}]):console.log(`${e.chr}.${e.pos}.${e.ref}.${e.alt}\t${JSON.stringify(o)}`)}const r=await(0,S.run_rust)("fisher",JSON.stringify({input:n}));for(const e of JSON.parse(r)){const n=t[e.index];n&&(n.p_value=e.p_value.toPrecision(2),e.p_value>0&&(n.nm_axis_value=Number((-Math.log10(e.p_value)).toPrecision(2))))}}let e=0;for(const n of t)n.p_value>0&&(e=Math.max(e,n.nm_axis_value));for(const n of t)0==n.p_value&&(n.nm_axis_value=Math.max(50,e))}var F=n(5684),D=n(7027),L=n(4065),$=n(141);const Z=10;function z(t){return async(e,n)=>{const r=e.query;(0,m.Y5)(r,e.cookies);try{const o=t[r.genome];if(!o)throw"invalid genome";const[i,l]=function(t,e){{const r=t.datasets[e.dslabel];if(r){var n;if(null!=r&&null!==(n=r.cohort)&&void 0!==n&&n.termdb)return[r,r.cohort.termdb];throw".cohort.termdb not found on this dataset"}}if(!t.termdbs)throw"genome-level termdb not available";const r=t.termdbs[e.dslabel];if(!r)throw"invalid dslabel";if(!r.cohort)throw"ds.cohort missing for genome-level termdb";if(!r.cohort.termdb)throw"ds.cohort.termdb{} missing for a genome-level termdb";return[r,r.cohort.termdb]}(o,r);if(r.getdescrstats)return async function(t,e,n){const r=n.cohort.termdb.q.termjsonByOneid(t.tid);if(!r)throw"invalid termid";if("float"!=r.type&&"integer"!=r.type)throw"not numerical term";const o=await c.J4({ds:n,key:t.tid,filter:t.filter?"string"==typeof t.filter?JSON.parse(t.filter):t.filter:null}),i=[];for(const{value:e}of o){var s,a;r.values&&r.values[e]&&r.values[e].uncomputable||("log"===(null===(s=t.settings)||void 0===s||null===(a=s.violin)||void 0===a?void 0:a.unit)&&0===e||i.push(Number(e)))}const l=i.length,u=i.reduce(((t,e)=>t+e),0)/l,f=(0,D.Z)(i,25),d=(0,D.Z)(i,50),h=(0,D.Z)(i,75),p=i.map((t=>(t-u)**2)).reduce(((t,e)=>t+e),0)/(i.length-1),m=Math.sqrt(p),g=Math.min(...i),y=Math.max(...i);e.send({values:[{id:"total",label:"n",value:l},{id:"min",label:"Minimum",value:(0,F.Z)(g,2)},{id:"p25",label:"1st quartile",value:(0,F.Z)(f,2)},{id:"median",label:"Median",value:(0,F.Z)(d,2)},{id:"mean",label:"Mean",value:(0,F.Z)(u,2)},{id:"p75",label:"3rd quartile",value:(0,F.Z)(h,2)},{id:"max",label:"Maximum",value:(0,F.Z)(y,2)},{id:"sd",label:"Standard deviation",value:(0,F.Z)(m,2)}]})}(r,n,i);if(r.getnumericcategories)return await async function(t,e,n,r){if(!t.tid)throw".tid missing";n.q.termjsonByOneid(t.tid);const o={ds:r,term_id:t.tid};t.filter&&(o.filter=t.filter);const i=await c.tt(o);e.send({lst:i})}(r,n,l,i);if(r.default_rootterm)return await async function(t,e,n){const r=t.cohortValues?t.cohortValues:"",o=t.treeFilter?t.treeFilter:"";e.send({lst:await n.q.getRootTerms(r,o)})}(r,n,l);if(r.get_children)return await async function(t,e,n){if(!t.tid)throw"no parent term id";const r=t.cohortValues?t.cohortValues:"",o=t.treeFilter?t.treeFilter:"",i=await n.q.getTermChildren(t.tid,r,o);e.send({lst:i.map(U)})}(r,n,l);if(r.findterm)return await async function(t,e,n,r,o){const i={equals:[],startsWith:[],startsWord:[],includes:[]},s=decodeURIComponent(t.findterm).toUpperCase(),a=[];try{if("snp"==t.targetType){var l,c;if(null===(l=r.queries)||void 0===l||null===(c=l.snvindel)||void 0===c||!c.allowSNPs)throw"this dataset does not support snp search";const t=await(0,$.SC)({byName:!0,lst:[s.toLowerCase()]},o);for(const e of t)a.push({type:"geneVariant",name:e.name,subtype:"snp",chr:e.chrom,start:e.chromStart,stop:e.chromEnd,alleles:e.alleles})}else{var u;const e=(0,k.CG)({type:"geneVariant"},t.usecase).has("plot");if(r.mayGetMatchingGeneNames&&e&&await r.mayGetMatchingGeneNames(i,s,t),null!==(u=r.queries)&&void 0!==u&&u.defaultBlock2GeneMode&&e)try{const t=(0,L.S)(o,{input:s});if(Array.isArray(t.hits))for(let e=0;e<7&&t.hits[e];e++)a.push({name:t.hits[e],type:"geneVariant"})}catch(t){}}const f=await n.q.findTermByName(s,Z,t.cohortStr,t.treeFilter,t.usecase,i);a.push(...f.map(U));a.forEach((t=>{"geneVariant"!=t.type&&(t.__ancestors=n.q.getAncestorIDs(t.id),t.__ancestorNames=n.q.getAncestorNames(t.id))})),e.send({lst:a})}catch(t){t.stack&&console.log(t.stack),e.send({error:t.message||t})}}(r,n,l,i,o);if(r.getterminfo)return function(t,e,n){if(!t.tid)throw"no term id";e.send({terminfo:n.q.getTermInfo(t.tid)})}(r,n,l);if(r.phewas)return r.update?await u.update_image(r,n):r.getgroup?await u.getgroup(r,n):await u.trigger(r,n,i);if(r.gettermdbconfig)return a(r,n,i,o);if(r.getcohortsamplecount)return n.send({count:i.cohort.termdb.q.getcohortsamplecount(r.cohort)});if(r.getsamplecount)return n.send(await async function(t,e,n){const r=s.i.canDisplaySampleIds(t,n);if("list"==e.getsamplecount){return await c.cf(e.filter,n,r)}return await c.B9(e,n)}(e,r,i));if(r.getsamples)return await async function(t,e,n){const r=await c.cf(t.filter,n),o=r.map((t=>n.cohort.termdb.q.id2sampleName(t)));e.send({samples:o})}(r,n,i);if(r.getcuminc)return await async function(t,e,n){const r=await(0,f.g)(t,n);e.send(r)}(r,n,i);if(r.getsurvival)return await async function(t,e,n){const r=await b(t,n);e.send(r)}(r,n,i);if(r.getregression)return await async function(t,e,n){const r=await(0,_.j)(t,n);e.send(r)}(r,n,i);if(r.validateSnps)return n.send(await(0,x.G)(r,l,i,o));if(r.getvariantfilter)return function(t,e){var n,r;if(e.track)return void t.send(e.track.variant_filter);t.send((null==e||null===(n=e.queries)||void 0===n||null===(r=n.snvindel)||void 0===r?void 0:r.variant_filter)||{})}(n,i);if(r.getLDdata)return await async function(t,e,n){var r,o;if(!t.ldtkname)throw".ldtkname missing";if(null===(r=e.queries)||void 0===r||null===(o=r.ld)||void 0===o||!o.tracks)throw"no ld tk";const i=e.queries.ld.tracks.find((e=>e.name==t.ldtkname));if(!i)throw"unknown ld tk";if("object"!=typeof t.m)throw"q.m{} not object";if(!t.m.chr)throw"q.m.chr missing";if(!Number.isInteger(t.m.pos))throw"q.m.pos not integer";if(!t.m.ref||!t.m.alt)throw"q.m{} invalid alleles";const s=t.m.ref+"."+t.m.alt,a=(i.nochr?t.m.chr.replace("chr",""):t.m.chr)+":"+t.m.pos+"-"+(t.m.pos+1),l=[];await(0,m.UE)({args:[i.file,a],dir:i.dir,callback:e=>{const n=e.split("\t"),r=Number.parseInt(n[1]),o=Number.parseInt(n[2]),i=n[3],a=n[4],c=Number.parseFloat(n[5]);r==t.m.pos&&i==s?l.push({pos:o,alleles:a,r2:c}):o==t.m.pos&&a==s&&l.push({pos:r,alleles:i,r2:c})}}),n.send({lst:l})}(r,i,n);if(r.genesetByTermId)return function(t,e,n){if(!n.termMatch2geneSet)throw"this feature is not enabled";if("string"!=typeof t.genesetByTermId||0==t.genesetByTermId.length)throw"invalid query term id";const r=n.q.getGenesetByTermId(t.genesetByTermId);e.send(r)}(r,n,l);if(r.getSampleScatter&&(r.for="scatter"),"scatter"==r.for)return await(0,q.uR)(e,r,n,i,o);if(r.getLowessCurve)return await(0,q.v8)(e,r,n);if(r.getCohortsData)return await async function(t,e,n){const r=function(t){const e=t.cohort.db.connection.prepare("select * from features").all();return{cohorts:t.cohort.db.connection.prepare("select * from cohorts where cohort in (select distinct(cohort) from cohort_features)\n\t\t order by sample_count desc").all(),features:e,cfeatures:t.cohort.db.connection.prepare("select * from cohort_features").all()}}(n);e.send(r)}(0,n,i);if("mds3queryDetails"==r.for)return function(t,e){const n={},r=e.queries||{};r.snvindel&&(n.snvindel={},r.snvindel.details&&(n.snvindel.details=r.snvindel.details),r.snvindel.populations&&(n.snvindel.populations=r.snvindel.populations));r.trackLst&&(n.trackLst=r.trackLst);if(r.ld){n.ld=JSON.parse(JSON.stringify(r.ld));for(const t of n.ld.tracks)delete t.file}t.send(n)}(n,i);if("termTypes"==r.for)return n.send(await i.getTermTypes(r));if("matrix"==r.for)return await async function(t,e,n,r,o){if(t.getPlotDataByName){if(!r.cohort.matrixplots)throw"ds.cohort.matrixplots missing for the dataset";if(!r.cohort.matrixplots.plots)throw"ds.cohort.matrixplots.plots missing for the dataset";const e=r.cohort.matrixplots.plots.find((e=>e.name===t.getPlotDataByName));if(!e)throw`plot name: q.getPlotDataByName=${getPlotDataByName} missing in ds.cohort.matrixplots.plots`;return void n.send(e.matrixConfig)}const i=await(0,p.Yu)(t,r,o);if(s.i.canDisplaySampleIds(e,r))for(const t of Object.values(i.samples))t.sampleName=r.sampleId2Name.get(t.sample);n.send(i)}(r,e,n,i,o);if("mds3variantData"==r.for)return await A(r,n,i);if(r.for,"convertSampleId"==r.for)return function(t,e,n){if(!n.convertSampleId)throw"not supported on this ds";if(!Array.isArray(t.inputs))throw"q.inputs[] not array";e.send({mapping:n.convertSampleId.get(t.inputs)})}(r,n,l);if("singleSampleData"==r.for)return async function(t,e,n,r,o){const i=s.i.canDisplaySampleIds(e,r);let a=[];if(i)try{a=o.q.getSingleSampleData(t.sampleId,t.term_ids),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(r,e,n,i,l);if("getProfileFacilities"==r.for)return async function(t,e,n,r,o){console.log("get profile facilities");const i=s.i.canDisplaySampleIds(e,r);let a=[];if(i)try{a=o.q.getProfileFacilities(),n.send(a)}catch(t){n.send({error:t.message||t})}else n.send({error:"Requires sign in to access the sample data"})}(0,e,n,i,l);if("getAllSamples"==r.for)return async function(t,e,n,r){const o=s.i.canDisplaySampleIds(e,r);let i=[];o&&(i=Object.fromEntries(r.sampleId2Name));n.send(i)}(0,e,n,i);if("getAllSamplesByName"==r.for)return async function(t,e,n,r){var o,i,a;if(!s.i.canDisplaySampleIds(e,r))return n.send({});if(null!==(o=r.queries)&&void 0!==o&&null!==(i=o.singleCell)&&void 0!==i&&null!==(a=i.samples)&&void 0!==a&&a.get){const t=await r.queries.singleCell.samples.get(),e={};for(const n of t)e[n.sample]=r.cohort.termdb.q.sampleName2id(n.sample);return void n.send(e)}n.send(Object.fromEntries(r.sampleName2Id))}(0,e,n,i);if("DEanalysis"==r.for)return await async function(t,e,n){var r;if(null===(r=n.queries)||void 0===r||!r.rnaseqGeneCount)throw"not enabled by this dataset";const o=await n.queries.rnaseqGeneCount.get(t);e.send(o)}(r,n,i);throw"termdb: doesn't know what to do"}catch(t){n.send({error:t.message||t}),t.stack?console.log(t.stack):console.log(t)}}}function U(t){return JSON.parse(JSON.stringify(t))}},2974:(t,e,n)=>{"use strict";n.d(e,{Yu:()=>f,gh:()=>d,te:()=>h});var r=n(1017),o=n.n(r),i=n(8907),s=n(5257),a=(n(9157),n(7147),n(7219),n(334)),l=n.n(a),c=n(3345),u=n(8599);async function f(t,e,n){try{return function(t,e,n){if(!e.cohort)throw"cohort missing from ds";if(!t.terms)throw"missing 'terms' parameter";t.ds=e,t.genome=n;for(const e of t.terms)e.term.name||(e.term=t.ds.cohort.termdb.q.termjsonByOneid(e.term.id)),e.q||console.log("do something??");if(t.currentGeneNames&&!Array.isArray(t.currentGeneNames))throw"currentGeneNames[] is not array";t.filter0&&"string"==typeof t.filter0&&(t.filter0=JSON.parse(t.filter0))}(t,e,n),await async function(t){const[e,n]=function(t){const e=[],n=[];for(const r of t){const t=r.term.type;"snplst"==t||"snplocus"==t||"geneVariant"==t?n.push(r):e.push(r)}return[e,n]}(t.terms),{samples:r,refs:o}=await async function(t,e){var n,r,o,i;if(!e.length)return{samples:{},refs:{byTermId:{}}};if(null!==(n=t.ds)&&void 0!==n&&null!==(r=n.cohort)&&void 0!==r&&r.db)return await d(t,e);if(null!==(o=t.ds)&&void 0!==o&&null!==(i=o.variant2samples)&&void 0!==i&&i.get)return await async function(t,e){const n={filter0:t.filter0,filterObj:t.filter,genome:t.genome,get:"samples",twLst:e,useIntegerSampleId:!0,isHierCluster:t.isHierCluster};if(t.currentGeneNames){n.geneTwLst=[];for(const e of t.currentGeneNames)n.geneTwLst.push({term:{name:e,type:"geneVariant"}})}const r=await t.ds.variant2samples.get(n),o={},i={byTermId:r.byTermId};for(const t of r.samples){const n={sample:t.sample_id};t.__sampleName&&(n.sampleName=t.__sampleName);for(const r of e){const e=t[r.term.id];Array.isArray(e)&&null!=e[0]&&null!=e[0]?n[r.term.id]={key:e[0],value:e[0]}:null!=e&&null!=e&&(n[r.term.id]={key:e,value:e})}o[t.sample_id]=n}return{samples:o,refs:i}}(t,e);throw"unknown method for dictionary terms"}(t,e);t.ds.getSampleIdMap&&(o.bySampleId=t.ds.getSampleIdMap(r));if(e.length&&!Object.keys(r).length)return{samples:r,refs:o};const s=await async function(t,e){if(!e.find((t=>"snplst"==t.term.type||"snplocus"==t.term.type)))return;if(!t.filter)return;return new Set((await(0,i.cf)(t.filter,t.ds)).map((t=>t.id)))}(t,n);for(const i of n)if("geneVariant"==i.term.type){var a,l,c,f;null!==(a=t.ds.cohort)&&void 0!==a&&null!==(l=a.termdb)&&void 0!==l&&l.getGeneAlias&&(o.byTermId[i.term.name]=null===(c=t.ds.cohort)||void 0===c||null===(f=c.termdb)||void 0===f?void 0:f.getGeneAlias(t,i));const n=await t.ds.mayGetGeneVariantData(i,t);for(const[o,s]of n.entries()){var h,p;if(i.term.name in s)if(e.length||o in r||(r[o]={sample:o}),r[o])if(r[o][i.term.name]=s[i.term.name],null!==(h=t.ds.cohort)&&void 0!==h&&null!==(p=h.termdb)&&void 0!==p&&p.additionalSampleAttributes)for(const e of null===(m=t.ds.cohort)||void 0===m||null===(g=m.termdb)||void 0===g?void 0:g.additionalSampleAttributes){var m,g;e in s&&(r[o][e]=s[e])}}}else{if("snplst"!=i.term.type&&"snplocus"!=i.term.type)throw"unknown type of non-dictionary term";{i.type=i.term.type;const t=new Map;await(0,u._)(i,t,!0);for(const[e,n]of t){if(s&&!s.has(e))continue;e in r||(r[e]={sample:e});const t={};for(const[e,r]of n.id2value)t[e]=r.value;r[e][i.term.id]=t}}}return{samples:r,refs:o}}(t)}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}async function d(t,e){const n={},r={byTermId:{}},o={},a=await(0,s.w)(t.filter,t.ds),l=a?a.values.slice():[],c=await Promise.all(e.map((async(e,n)=>{const s=await(0,i.Bi)(t,l,n,a,e);if(s.bins&&(r.byTermId[e.term.id]={bins:s.bins}),s.events&&(r.byTermId[e.term.id]={events:s.events}),e.term.values){const t=Object.values(e.term.values);t.find((t=>"order"in t))&&(r.byTermId[e.term.id]={keyOrder:t.sort(((t,e)=>t.order-e.order)).map((t=>t.key))})}return"id"in e.term&&(o[e.term.id]=e),s}))).catch(console.error);l.push(...e.map((t=>t.term.id||t.term.name)));const u=`WITH\n\t\t${a?a.filters+",":""}\n\t\t${c.map((t=>t.sql)).join(",\n")}\n\t\t${c.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${a?`WHERE sample IN ${a.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,f=t.ds.cohort.db.connection.prepare(u).all(l),d=await async function(t){if(!t.currentGeneNames)return;const e=new Set;for(const n of t.currentGeneNames){const r={term:{name:n,type:"geneVariant"}},o=await t.ds.mayGetGeneVariantData(r,t);for(const[t,n]of o.entries())e.add(t)}return e}(t);for(const{sample:t,term_id:e,key:r,value:i}of f){if(d&&!d.has(t))continue;n[t]||(n[t]={sample:t});o[e];n[t][e]={key:r,value:i}}return{samples:n,refs:r}}async function h(t){if(t.cohort.matrixplots){if(!Array.isArray(t.cohort.matrixplots.plots))throw"cohort.matrixplots.plots is not array";for(const e of t.cohort.matrixplots.plots){if(!e.name)throw".name missing from one of matrixplots.plots[]";if(!e.file)throw"unknown data source of one of matrixplots.plots[]";{const t=await c.b5(o().join(l().tpmasterdir,e.file));e.matrixConfig=JSON.parse(t),e.getConfig&&(e.matrixConfig=e.getConfig(e.matrixConfig))}}}}},5708:(t,e,n)=>{"use strict";n.r(e),n.d(e,{do_precompute:()=>y,getgroup:()=>N,trigger:()=>g,update_image:()=>x});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(8907),c=n(6718),u=n(2826),f=n(4521),d=n.n(f),h=n(334),p=n.n(h),m=n(9157);async function g(t,e,n){if(!n.cohort)throw"ds.cohort missing";if(!n.cohort.termdb)throw"cohort.termdb missing";if(!n.cohort.termdb.phewas)throw"not allowed on this dataset";if(!t.ssid)throw"ssid missing";const r={};let o;t.filter&&(o=new Set(await l.cf(t.filter,n)));const[i,c]=await a.L0(t.ssid,o);r.numberofsamples=i.size;const f=c.has(a.EO.het)?c.get(a.EO.het).size:0,d=c.has(a.EO.href)?c.get(a.EO.href).size:0,h=c.has(a.EO.halt)?c.get(a.EO.halt).size:0,g=function(t,e,n,r,o,i){const s=[];let a;if(e.cohort.termdb.selectCohort&&t){const e=t.lst.find((t=>"cohortFilter"==t.tag));e&&(a=e.tvs.values.map((t=>t.key)).sort().join(","))}for(const t of e.cohort.termdb.q.getcategory2vcfsample()){if(a&&t.subcohort!=a)continue;const l=u.iK(e.cohort.termdb.q.termjsonByOneid(t.term_id));for(const e of t.categories){const[a,c,u]=q(n,e.group1lst);let f,d,h;e.group2lst?[f,d,h]=q(n,e.group2lst):(f=r-a,d=i-c,h=o-u),a+f+c+d+u+h!=0&&s.push({term:l,group_name:t.group_name,parent_name:t.parent_name,group1label:e.group1label,group2label:e.group2label,table:[u,h,a,f,c,d]})}}return s}(t.filter,n,i,f,d,h);r.testcount=g.length;{const t=[];for(let e=0;e<g.length;e++)t.push(e+"\t"+g[e].table.join("\t"));const e=await(0,m.default)(s().join(p().binpath,"utils/fisher.2x3.R"),t);let n=0;for(const t of e)g[n++].pvalue=Number(t.split("\t")[7])}r.maxlogp=function(t){let e=0;for(const n of t)0==n.pvalue?n.logp=100:n.logp=-Math.log10(n.pvalue),e=Math.max(e,n.logp);return e}(g);const y=function(t){const e=new Map;for(const n of t)e.has(n.group_name)||e.set(n.group_name,[]),e.get(n.group_name).push(n);const n=[];for(const[t,r]of e)n.push({group_name:t,categories:r});return n}(g);r.tmpfile=await function(t){const e=[];for(const n of t)for(const t of n.categories)e.push(n.group_name+"\t"+t.logp+"\t"+t.pvalue+"\t"+JSON.stringify(t));return a.tG(e.join("\n"))}(y),k(y,r,t);{const t=.05;r.hoverdots=g.filter((e=>e.pvalue<=t))}e.send(r)}async function y(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.termdb)throw"cohort.termdb missing";if(!t.cohort.termdb.phewas)throw"not allowed on this dataset";t.cohort.termdb.selectCohort?await async function(t){const e=await async function(t){if(!t.cohort.termdb.phewas.precompute_subcohort2totalsamples)return;for(const e in t.cohort.termdb.phewas.precompute_subcohort2totalsamples){const n=t.cohort.termdb.phewas.precompute_subcohort2totalsamples[e];if(n.termtype)for(const e in n.termtype)n.termtype[e].samples=await l.cf(n.termtype[e].filter,t)}return t.cohort.termdb.phewas.precompute_subcohort2totalsamples}(t),n=function(t){const e=new Map,n=t.cohort.db.connection.prepare("SELECT * FROM subcohort_terms");for(const{term_id:t,cohort:r}of n.all())e.has(t)||e.set(t,new Set),e.get(t).add(r);return e}(t),r=o().createWriteStream("category2vcfsample"),i=[];for(const{group_name:o,term:s}of t.cohort.termdb.q.getAlltermsbyorder()){if(!s.type)continue;if(!n.has(s.id)){i.push(s.id);continue}let a="";{const e=t.cohort.termdb.q.getTermParent(s.id);e&&(a=e.name)}const c=b(s,t,n);for(const n of c){const i=await l.g5(n);let c;if("categorical"==s.type||"integer"==s.type||"float"==s.type)c=w(i.lst,s,t);else{if("condition"!=s.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(i.lst,t):w(i.lst,s,t)}c=v({categories:c,q:n,subcohortTermtype2samples:e,term:s});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+s.name+"\t"+n.cohortname);r.write(n.cohortname+"\t"+o+"\t"+s.id+"\t"+a+"\t"+(n.term1_q?JSON.stringify(n.term1_q):"{}")+"\t"+JSON.stringify(c)+"\n")}}r.end((()=>{console.log('Phewas precompute result written to file "category2vcfsample".'),i.length&&(console.log(i.length+" empty terms:"),console.log(i.join("\n")))}))}(t):await async function(t){const[e]=await async function(t){let e=null;if(t.cohort.termdb.phewas.samplefilter4termtype&&t.cohort.termdb.phewas.samplefilter4termtype.condition){const n=await l.cf(t.cohort.termdb.phewas.samplefilter4termtype.condition.filter,t);if(t.track&&t.track.vcf&&t.track.vcf.sample2arrayidx){e=[];for(const r of n)t.track.vcf.sample2arrayidx.has(r)&&e.push(r)}else e=n}return[e]}(t),n=[];for(const{group_name:r,term:o}of t.cohort.termdb.q.getAlltermsbyorder()){if(!o.type)continue;let i="";{const e=t.cohort.termdb.q.getTermParent(o.id);e&&(i=e.name)}const s=b(o,t);for(const a of s){const s=await l.g5(a);let c;if("categorical"==o.type||"integer"==o.type||"float"==o.type)c=w(s.lst,o,t);else{if("condition"!=o.type)throw"unknown term type";c=t.cohort.termdb.phewas.comparison_groups?_(s.lst,t):w(s.lst,o,t)}c=v({categories:c,q:a,term:o,condition_samplelst:e});for(const t of c)console.log(t.group1lst.length+(t.group2lst?"/"+t.group2lst.length:"")+"\t"+t.group1label+"\t"+o.name);n.push(r+"\t"+o.id+"\t"+i+"\t"+(a.term1_q?JSON.stringify(a.term1_q):"{}")+"\t"+JSON.stringify(c))}}o().writeFileSync("category2vcfsample",n.join("\n")),console.log('Phewas precompute result written to file "category2vcfsample".')}(t)}function v(t){const{categories:e,q:n,term:r,subcohortTermtype2samples:o,condition_samplelst:i}=t;if(o&&o[n.cohortname]&&o[n.cohortname].termtype&&o[n.cohortname].termtype[r.type]){const t=o[n.cohortname].termtype[r.type].samples;for(const n of e)if(n.group2lst)n.group2lst=n.group2lst.filter((e=>-1!=t.indexOf(e)));else if(n.copycontrolfrom1stgroup){n.group2lst=[];for(const t of e[0].group2lst)n.group2lst.push(t)}else{const e=new Set(n.group1lst);n.group2lst=t.filter((t=>!e.has(t)))}return e}if(i&&"condition"==r.type){for(const t of e)if(t.group2lst)t.group2lst=t.group2lst.filter((t=>-1!=i.indexOf(t)));else if(t.copycontrolfrom1stgroup){t.group2lst=[];for(const n of e[0].group2lst)t.group2lst.push(n)}else{const e=new Set(t.group1lst);t.group2lst=i.filter((t=>!e.has(t)))}return e}if(!r.values)return e;const s=new Set;for(const t in r.values)r.values[t].uncomputable&&s.add(r.values[t].label);if(0==s.size)return e;const a=[];for(const t of e)s.has(t.group1label)?console.log("skip "+t.group1label+", "+r.id):a.push(t);for(let t=0;t<a.length;t++){const e=a[t];e.group2lst=[];for(let n=0;n<a.length;n++)n!=t&&e.group2lst.push(...a[n].group1lst)}return a}function b(t,e,n){const r=[];if(e.cohort.termdb.selectCohort){if(!n)throw"term2cohort is required when cohort selection is enabled";for(const o of e.cohort.termdb.selectCohort.values){const i=o.keys.sort().join(",");if(!n.get(t.id).has(i))continue;const s={type:"tvslst",in:!0,join:"",lst:[{type:"tvs",tvs:{term:e.cohort.termdb.selectCohort.term,values:o.keys.map((t=>({key:t})))}}]};if("categorical"==t.type)r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({cohortname:i,filter:JSON.parse(JSON.stringify(s)),ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}}}else if("categorical"==t.type)r.push({ds:e,term1_id:t.id});else if("float"==t.type||"integer"==t.type)r.push({ds:e,term1_id:t.id,term1_q:t.bins.default});else{if("condition"!=t.type)throw"unknown term type";r.push({ds:e,term1_id:t.id,term1_q:{bar_by_grade:!0,value_by_max_grade:!0}})}return r}function w(t,e,n){const r=new Map;for(const o of t){if(n.track&&n.track.vcf&&n.track.vcf.sample2arrayidx&&!n.track.vcf.sample2arrayidx.has(o.sample))continue;const t=o.key1;if(!r.has(t)){let n=t;e.values&&(n=e.values[t]?e.values[t].label:t),r.set(t,{group1label:n,group2label:"All others",group1lst:[]})}r.get(t).group1lst.push(o.sample)}return[...r.values()]}function _(t,e){const n=[];for(const r of e.cohort.termdb.phewas.comparison_groups){const o=[],i=[];for(const n of t){if(e.track&&e.track.vcf&&e.track.vcf.sample2arrayidx&&!e.track.vcf.sample2arrayidx.has(n.sample))continue;const t=Number(n.key1);r.group1grades.has(t)?o.push(n.sample):r.group2grades&&r.group2grades.has(t)&&i.push(n.sample)}0!=o.length?n.push({group1label:r.group1label,group2label:r.group2label,group1lst:o,group2lst:i.length?i:void 0,copycontrolfrom1stgroup:r.copycontrolfrom1stgroup}):console.log("Empty group1: "+r.group1label)}return n}async function x(t,e){const n=await a.b5(s().join(p().cachedir,t.file)),r=[];for(const t of n.trim().split("\n")){const[e,n]=t.split("\t",2),o=Number(n);0!=r.length&&r[r.length-1].group_name==e||r.push({group_name:e,categories:[]}),r[r.length-1].categories.push({logp:o})}const o={maxlogp:Number(t.max)};k(r,o,t),e.send(o)}function k(t,e,n){const r=Number(n.intendwidth),o=Number(n.axisheight),i=Number(n.groupnamefontsize),s=Number(n.dotradius),a=Number(n.groupxspace),l=Number(n.leftpad),u=Number(n.rightpad),f=Number(n.toppad),d=Number(n.bottompad),h=Number(n.devicePixelRatio),p=r/t.reduce(((t,e)=>t+e.categories.length),0),m=(0,c.createCanvas)(10,10),g=m.getContext("2d");let y=0;for(const e of t){const t=e.categories.length*p;e.width=Math.max(t,i)+2*a,e.dotshiftx=t>i?p:i/e.categories.length,y+=e.width}const v=l+y+u;m.width=v*h;const b=f+o+d;m.height=b*h,h>1&&g.scale(h,h),y=0,g.fillStyle="#FDFEE2";for(const[e,n]of t.entries())e%2==0&&g.fillRect(y,f,n.width,o),y+=n.width;y=0,g.fillStyle="black",e.grouplabels=[];for(const n of t){e.grouplabels.push({name:n.group_name,x:y+n.width/2,y:f+o+2*s});let t=0;for(const r of n.categories){const i=0==e.maxlogp?0:r.logp>=e.maxlogp?o:o*r.logp/e.maxlogp;g.beginPath(),g.arc(y+a+t,f+o-i,s,0,2*Math.PI),g.fill(),r.x=y+a+t,t+=n.dotshiftx}y+=n.width}e.canvaswidth=v,e.canvasheight=b,e.toppad=f,e.bottompad=d,e.axisheight=o,e.dotradius=s,e.groupnamefontsize=i,e.src=m.toDataURL()}function q(t,e){const n=new Map;for(const r of e){const e=t.get(r);e&&n.set(e,1+(n.get(e)||0))}return[n.get(a.EO.het)||0,n.get(a.EO.halt)||0,n.get(a.EO.href)||0]}async function N(t,e){if(!t.file)throw"file missing";return new Promise(((n,r)=>{const i=[],a=d().createInterface({input:o().createReadStream(s().join(p().cachedir,t.file))});a.on("line",(e=>{if(!e.startsWith(t.getgroup+"\t"))return;const n=e.split("\t"),r=JSON.parse(n[3]);r.pvalue=Number(n[2]),i.push(r)})),a.on("close",(()=>{e.send({categories:i}),n()}))}))}},8599:(t,e,n)=>{"use strict";n.d(e,{_:()=>j,j:()=>x});var r=n(1017),o=n.n(r),i=n(8907),s=n(5257),a=n(9157),l=n(7147),c=n.n(l),u=n(7219),f=n.n(u),d=n(334),h=n.n(d),p=n(3345),m=n(1271),g=n(4453);const y=["linear","logistic","cox"],v=1;let b,w;const _={NodeJS:{},"regression.R":{}};async function x(t,e){try{!function(t,e){if(!e.cohort)throw"cohort missing from ds";if(t.ds=e,!t.regressionType)throw"regressionType missing";if(!y.includes(t.regressionType))throw"unknown regressionType";if(!t.outcome)throw"missing 'outcome' parameter";if(!("id"in t.outcome))throw"outcome.id missing";if(!t.outcome.q)throw"outcome.q missing";if(t.outcome.q.computableValuesOnly=!0,t.outcome.term=e.cohort.termdb.q.termjsonByOneid(t.outcome.id),!t.outcome.term)throw"invalid outcome term: "+t.outcome.id;if(!t.independent)throw"independent[] missing";if(!Array.isArray(t.independent)||0==t.independent.length)throw"q.independent is not non-empty array";for(const n of t.independent){if(!n.q)throw`missing q for independent term '${n.id}'`;if(k(n,t,e),"snplst"!=n.type&&"snplocus"!=n.type){if(n.q.computableValuesOnly=!0,!n.id)throw".id missing for an independent term";if(n.term=e.cohort.termdb.q.termjsonByOneid(n.id),!n.term)throw`invalid independent term='${n.id}'`}else{if(!n.q.cacheid)throw"q.cacheid missing";if(h().cache_snpgt.fileNameRegexp.test(n.q.cacheid))throw"invalid cacheid";if("object"!=typeof n.q.snp2effAle)throw"q.snp2effAle{} is not object";if(!Number.isInteger(n.q.alleleType))throw"q.alleleType is not integer";if(!Number.isInteger(n.q.geneticModel))throw"q.geneticModel is not integer";if(3==n.q.geneticModel&&"object"!=typeof n.q.snp2refGrp)throw"q.snp2refGrp{} is not object when geneticMode=3";if("snplst"==n.type&&!Number.isInteger(n.q.missingGenotype))throw"q.missingGenotype is not integer for snplst"}}for(const e of t.independent){e.interactions||(e.interactions=[]);for(const n of e.interactions)if(!t.independent.find((t=>t.id==n)))throw"interacting term id missing from independent[]: "+n}}(t,e),b=(new Date).getTime();const n=await async function(t,e,n){const[r,o]=function(t){const e=[],n=[];for(const r of t)"snplst"==r.type||"snplocus"==r.type?n.push(r):e.push(r);return[e,n]}(e),a=await async function(t,e){const n=new Map,r=await(0,s.w)(t.filter,t.ds),o=r?r.values.slice():[],a=await Promise.all(e.map((async(e,n)=>await(0,i.Bi)(t,o,n,r,e)))).catch(console.error);o.push(...e.map((t=>t.id)));const l=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${a.map((t=>t.sql)).join(",\n")}\n\t\t${a.map((t=>`\n\t\t\tSELECT sample, key, value, ? as term_id\n\t\t\tFROM ${t.tablename}\n\t\t\t${r?`WHERE sample IN ${r.CTEname}`:""}\n\t\t\t`)).join("UNION ALL")}`,c=t.ds.cohort.db.connection.prepare(l).all(o),u=[],f=t.ds.cohort.termdb.ageEndOffset;if(!f)throw"missing age end offset";for(const e of c)if("cox"==t.regressionType&&e.term_id==t.outcome.id){const n=e.key,{age_start:r,age_end:o}=JSON.parse(e.value);if(-1==n)continue;const i={age_start:r,age_end:"age"==t.outcome.q.timeScale?o+f:o};u.push({sample:e.sample,key:n,value:i,term_id:e.term_id})}else u.push(e);for(const{sample:t,term_id:r,key:o,value:i}of u){const s=e.find((t=>t.id==r));if(n.has(t)||n.set(t,{sample:t,id2value:new Map}),n.get(t).id2value.has(r))throw`duplicate '${r}' entry for sample='${t}'`;n.get(t).id2value.set(r,{key:s.q.scale?o/s.q.scale:o,value:s.q.scale?i/s.q.scale:i})}const d=new Set;for(const t of n.values())for(const n of e)if(!t.id2value.has(n.id)){d.add(t.sample);break}for(const t of d)n.delete(t);return n}(t,r);for(const t of o){if(C(t,a,n),"snplst"!=t.type&&"snplocus"!=t.type)throw"unknown type of independent non-dictionary term";await j(t,a)}return[...a.values()]}(t,[t.outcome,...t.independent],e);w=(new Date).getTime(),_.NodeJS.getSampleData=(w-b)/1e3+" sec",b=(new Date).getTime();const r=function(t,e){const n={id:t.outcome.id,name:t.outcome.term.name,rtype:"numeric"};"logistic"==t.regressionType&&(n.categories={ref:t.outcome.refGrp,nonref:S(t.outcome)});"cox"==t.regressionType&&(n.timeToEvent={timeId:t.outcome.id+"_time",eventId:t.outcome.id+"_event",timeScale:t.outcome.q.timeScale},"age"==n.timeToEvent.timeScale&&(n.timeToEvent.agestartId=t.outcome.id+"_agestart",n.timeToEvent.ageendId=t.outcome.id+"_ageend"));const r=[];for(const e of t.independent)"snplst"==e.type||"snplocus"==e.type?N(e,r,t):q(e,r,t);const o=[];for(const i of e){const{sample:e,id2value:s}=i;if(!s.has(t.outcome.id)){i.noOutcome=!0;continue}const a=s.get(t.outcome.id);let l=!1;for(const e of t.independent)if("snplocus"!=e.type)if("snplst"==e.type){for(const t of e.highAFsnps.keys())if(!s.get(t)){l=!0;break}}else{if(!s.get(e.id)){l=!0;break}}if(l)continue;const c={};if("linear"==t.regressionType&&(c[n.id]=a.value),"logistic"==t.regressionType&&(c[n.id]=a.key===t.outcome.refGrp?0:1),"cox"==t.regressionType){c[n.timeToEvent.eventId]=a.key;const{age_start:e,age_end:r}=a.value;c[n.timeToEvent.timeId]=r-e,"age"==t.outcome.q.timeScale&&(c[n.timeToEvent.agestartId]=e,c[n.timeToEvent.ageendId]=r)}for(const t of r){const e=s.get(t.id);c[t.id]=e?"numeric"===t.rtype?e.value:e.key:null}o.push(c)}const i={regressionType:t.regressionType,binpath:h().binpath,data:o,outcome:n,independent:r};return i}(t,n);w=(new Date).getTime(),_.NodeJS.makeRinput=(w-b)/1e3+" sec",function(t){const e=t.regressionType,n=t.outcome;if(t.data.length<v)throw"too few samples to fit model";let r=t.independent.length;if("cox"==e)if("time"==n.timeToEvent.timeScale)r+=2;else{if("age"!=n.timeToEvent.timeScale)throw"unknown cox regression time scale";r+=4}else r+=1;if(t.data.find((t=>Object.keys(t).length!=r)))throw"unequal number of variables in data entries";if("logistic"==e){if([...new Set(t.data.map((t=>t[n.id])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome values found"}if("cox"==e){if([...new Set(t.data.map((t=>t[n.timeToEvent.eventId])))].find((t=>![0,1].includes(t))))throw"non-0/1 outcome event values found"}for(const e of t.independent)if("numeric"==e.rtype){if(e.refGrp)throw`reference group given for '${e.id}'`}else{if("factor"!=e.rtype)throw`variable rtype='${e.rtype}' not recognized`;{if(!e.refGrp)throw`reference group not given for '${e.id}'`;if("snplst"==e.type||"snplocus"==e.type)continue;const n=new Set(t.data.map((t=>t[e.id])));if(n.size<2)throw`fewer than 2 categories in data of variable='${e.id}'`;if(!n.has(e.refGrp))throw`reference group missing in data of variable='${e.id}'`}}}(r);const[o,a]=function(t){const e={},n={};if(e.outcome=t.outcome.id,n[t.outcome.id]="outcome",t.outcome.timeToEvent){const r=t.outcome.timeToEvent;e.outcome_time=r.timeId,n[r.timeId]="outcome_time",e.outcome_event=r.eventId,n[r.eventId]="outcome_event","age"==r.timeScale&&(e.outcome_agestart=r.agestartId,e.outcome_ageend=r.ageendId,n[r.agestartId]="outcome_agestart",n[r.ageendId]="outcome_ageend")}for(const[r,o]of t.independent.entries())e["id"+r+"_"]=o.id,n[o.id]="id"+r+"_";if(t.outcome.id=n[t.outcome.id],t.outcome.timeToEvent){const e=t.outcome.timeToEvent;e.timeId=n[e.timeId],e.eventId=n[e.eventId],"age"==e.timeScale&&(e.agestartId=n[e.agestartId],e.ageendId=n[e.ageendId])}for(const e of t.independent)if(e.id=n[e.id],e.interactions&&e.interactions.length>0)for(const[t,r]of e.interactions.entries())e.interactions[t]=n[r];for(const e of t.data)for(const t in e)e[n[t]]=e[t],delete e[t];return[e,n]}(r),l={resultLst:[]};return await Promise.all([A(r,o,t,l),M(t,n,r,l)]),console.log("benchmark:",_),l}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function k(t,e,n){if(!t.q.restrictAncestry)return;if(!("name"in t.q.restrictAncestry))throw".name missing from tw.q.restrictAncestry";if(!n.cohort.termdb.restrictAncestries)throw"ds.cohort.termdb.restrictAncestries missing";const r=n.cohort.termdb.restrictAncestries.find((e=>e.name==t.q.restrictAncestry.name));if(!r)throw"unknown ancestry for restriction: "+t.q.restrictAncestry.name;if(r.pcs)t.q.restrictAncestry.pcs=r.pcs;else{if(!r.PCBySubcohort)throw"unknown way of accessing pcs from ds.cohort.termdb.restrictAncestries: "+t.q.restrictAncestry.name;{if(!e.filter)throw"q.filter missing while trying to access subcohort for PCBySubcohort";const n=O(e.filter,"cohortFilter");if(!n)throw"tvs by tag=cohortFilter missing from q.filter.lst[] while trying to access subcohort for PCBySubcohort";const o=n.tvs.values.map((t=>t.key)).sort().join(","),i=r.PCBySubcohort[o];if(!i)throw"unknown key for PCBySubcohort: "+o;if(!i.pcs)throw"pcs Map() missing from PCBySubcohort[]: "+o;t.q.restrictAncestry.pcs=i.pcs}}}function q(t,e,n){const r={id:t.id,name:t.term.name,type:"spline"==t.q.mode?"spline":"other",rtype:"continuous"==t.q.mode||"spline"==t.q.mode?"numeric":"factor"};if(t.interactions.length>0){r.interactions=[];for(const e of t.interactions){const t=n.independent.find((t=>t.id==e));if("snplst"==t.type)for(const e of t.highAFsnps.keys())r.interactions.push(e);else{if("snplocus"==t.type)continue;r.interactions.push(e)}}}"factor"===r.rtype&&(r.refGrp=t.refGrp),"spline"==t.q.mode&&(r.spline={knots:t.q.knots.map((t=>Number(t.value)))},n.independent.find((t=>"snplocus"==t.type))||(r.spline.plotfile=o().join(h().cachedir,Math.random().toString()+".png"))),e.push(r)}function N(t,e,n){for(const r of t.highAFsnps.keys()){const o={id:r,name:r,type:t.type};3==t.q.geneticModel?(o.rtype="factor",o.refGrp=t.q.snp2refGrp[r]):o.rtype="numeric";for(const e of n.independent)e.interactions.includes(t.id)&&(o.interactions||(o.interactions=[]),o.interactions.push(e.id));e.push(o)}if(t.q.restrictAncestry)for(const n of t.q.restrictAncestry.pcs.keys())e.push({id:n,name:n,type:"float",rtype:"numeric"})}function S(t){if("condition"==t.term.type){for(const e of t.q.groups)if(e.name!=t.refGrp)return e;throw"nonref group not found for logistic outcome"}if("predefined-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!Number.isInteger(t.q.groupsetting.predefined_groupset_idx))throw'outcome.q.predefined_groupset_idx not integer when q.type is "predefined-groupset"';if(!t.term.groupsetting)throw"outcome.term.groupsetting missing";const e=t.term.groupsetting.lst[t.q.groupsetting.predefined_groupset_idx];if(!e)throw"groupset not found by outcome.q.predefined_groupset_idx";const n=e.groups.find((e=>e.name!=t.refGrp));if(!n)throw"non-ref group not found for predefined-groupset";return n.name}if("custom-groupset"==t.q.type){if(!t.q.groupsetting)throw"outcome.q.groupsetting{} missing when type=predefined-groupset";if(!t.q.groupsetting.customset)throw"outcome.q.customset missing";const e=t.q.groupsetting.customset.groups.find((e=>e.name!=t.refGrp));if(!e)throw"non-ref group not found for custom-groupset";return e.name}if("values"==t.q.type){if(!t.term.values)throw"outcome.term.values{} missing";for(const e in t.term.values){const n=t.term.values[e];if(n.label!=t.refGrp)return n.label}throw"unknown nonref group from outcome.term.values"}if("custom-bin"==t.q.type){const e=t.q.lst.find((e=>e.label!=t.refGrp));if(!e)throw"non-ref bin is not found for custom-bin";return e.label}if("regular-bin"==t.q.type)throw"do not know a way to find computed bin list for type=regular-bin";throw"unknown outcome.q.type"}async function A(t,e,n,r){b=(new Date).getTime();const i=o().join(h().cachedir,Math.random().toString()+".json");await p.Sf(i,JSON.stringify(t));const s=await(0,a.default)(o().join(h().binpath,"utils","regression.R"),[],[i]);c().unlink(i,(()=>{})),await async function(t,e,n,r,o){if(1!=e.length)throw"expected 1 json line in R output";const i=JSON.parse(e[0]),s=i.data;_["regression.R"]=i.benchmark;for(const e of s){const i={data:{sampleSize:e.data.sampleSize,eventCnt:e.data.eventCnt?e.data.eventCnt:null}};if(e.id){const t=n[e.id];i.id=t;const o=r.independent.find((t=>"snplocus"==t.type));if(!o)throw"snplocus term missing";i.AFstr=o.snpid2AFstr.get(t),i.data.headerRow=T(t,o)}const s=e.data;if(s.residuals&&(i.data.residuals=s.residuals,i.data.residuals.label="linear"==t.regressionType?"Residuals":"Deviance residuals"),"cox"==t.regressionType){if(s.coefficients.rows.length<1)throw"fewer than 1 row in coefficients table"}else if(s.coefficients.rows.length<2)throw"fewer than 2 rows in coefficients table";i.data.coefficients={header:s.coefficients.header,intercept:"cox"==t.regressionType?null:s.coefficients.rows.shift(),terms:{},interactions:[]};for(const t of s.coefficients.rows)if(-1!=t[0].indexOf(":")){const e={},[r,o]=t.shift().split(":"),[s,a]=t.shift().split(":");e.term1=n[r],e.category1=s,e.term2=n[o],e.category2=a,e.lst=t,i.data.coefficients.interactions.push(e)}else{const e=t.shift(),r=t.shift(),o=n[e];i.data.coefficients.terms[o]||(i.data.coefficients.terms[o]={}),r?(i.data.coefficients.terms[o].categories||(i.data.coefficients.terms[o].categories={}),i.data.coefficients.terms[o].categories[r]=t):i.data.coefficients.terms[o].fields=t}i.data.coefficients.label="Coefficients",i.data.type3={header:s.type3.header,terms:{},interactions:[]},"cox"!=t.regressionType&&(i.data.type3.intercept=s.type3.rows.shift());for(const t of s.type3.rows)if(-1!=t[0].indexOf(":")){const e={},[r,o]=t.shift().split(":");e.term1=n[r],e.term2=n[o],e.lst=t,i.data.type3.interactions.push(e)}else{const e=n[t.shift()];i.data.type3.terms[e]||(i.data.type3.terms[e]=t)}if(i.data.type3.label="Type III statistics",s.totalSnpEffect){if(1!=s.totalSnpEffect.rows.length)throw"total SNP effect table should have 1 row";i.data.totalSnpEffect={header:s.totalSnpEffect.header.slice(0,4)};const t=s.totalSnpEffect.rows[0].slice(0,4),e=s.totalSnpEffect.rows[0][4].split(";"),r=e.findIndex((t=>!t.includes(":"))),o=e.splice(r,1)[0];i.data.totalSnpEffect.snp=n[o];const a=[];for(const t of e){if(!t.includes(":"))throw"expected interaction";const[e,r]=t.split(":");a.push({term1:n[e],term2:n[r]})}i.data.totalSnpEffect.interactions=a,i.data.totalSnpEffect.lst=t,i.data.totalSnpEffect.label="Total SNP effect"}s.tests&&(i.data.tests=s.tests,i.data.tests.label="Statistical tests"),i.data.other=s.other,i.data.other.label="Other summary statistics";for(const e of t.independent)if(e.spline&&e.spline.plotfile){i.data.splinePlots||(i.data.splinePlots=[]);const t=e.spline.plotfile,n=await c().promises.readFile(t);i.data.splinePlots.push({src:"data:image/png;base64,"+new Buffer.from(n).toString("base64"),size:f()(t)}),c().unlink(t,(t=>{if(t)throw t}))}s.warnings&&(i.data.warnings=s.warnings);const a=r.independent.find((t=>"snplst"==t.type));if(a){if(a.lowAFsnps&&a.lowAFsnps.size){i.data.warnings||(i.data.warnings=[]);for(const t of a.lowAFsnps.keys())i.data.warnings.push(`${t}: effect allele frequency below cutoff, excluded from analysis`)}if(a.monomorphicLst&&a.monomorphicLst.length){i.data.warnings||(i.data.warnings=[]);for(const t of a.monomorphicLst)i.data.warnings.push(`${t}: monomorphic, excluded from analysis`)}}o.resultLst.push(i)}}(t,s,e,n,r),w=(new Date).getTime(),_.NodeJS.runRegression=(w-b)/1e3+" sec"}async function M(t,e,n,r){const i=t.independent.find((t=>"snplocus"==t.type));if(i){if(b=(new Date).getTime(),function(t,e){for(const n of t.monomorphicLst){const r=t.snpgt2count.get(n),o=[];for(const[t,e]of r)o.push(t+"="+e);const i={id:n,data:{headerRow:T(n,t)}};e.resultLst.push(i)}}(i,r),i.lowAFsnps.size)if("linear"==t.regressionType)await async function(t,e,n,r){const i=[],s=new Map;for(const[r,o]of t.lowAFsnps){let t=0,a=null,l=null;const c=[],u=[];for(const{sample:r,noOutcome:i}of e){if(i)continue;const e=n.data[t++].outcome;if(!Number.isFinite(e))continue;const s=o.samples.get(r);if(!s)continue;null==a?a=l=e:(a=Math.min(a,e),l=Math.max(l,e));const[f,d]=s.split("/");f==o.effAle||d==o.effAle?c.push(e):u.push(e)}i.push({group1_id:r+"_hasEffAllele",group1_values:c,group2_id:r+"_noEffAllele",group2_values:u}),s.set(r,{minv:a,maxv:l})}const l=o().join(h().cachedir,Math.random().toString()+".json");await p.Sf(l,JSON.stringify(i));const u=await(0,a.default)(o().join(h().binpath,"utils/wilcoxon.R"),[],[l]);c().unlink(l,(()=>{}));const f=JSON.parse(u);for(const e of f){const n=e.group1_id.replace("_hasEffAllele",""),o=e.group1_values,i=e.group2_values;let a;a=null==e.pvalue||"null"==e.pvalue?"NA":e.pvalue.toPrecision(4);const{minv:l,maxv:c}=s.get(n),u=p.JC(o.sort(((t,e)=>t-e)).map((t=>({value:t}))));u.label=`Carry ${0==t.q.alleleType?"minor":"alternative"} allele, n=${o.length}`;const f=p.JC(i.sort(((t,e)=>t-e)).map((t=>({value:t}))));f.label=`No ${0==t.q.alleleType?"minor":"alternative"} allele, n=${i.length}`;const d={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),wilcoxon:{pvalue:a,boxplots:{minv:l,maxv:c,hasEff:u,noEff:f}}}};r.resultLst.push(d)}}(i,e,n,r);else if("logistic"==t.regressionType)await async function(t,e,n,r){const o=[];let i=0;const s=new Map;for(const[r,a]of t.lowAFsnps){let t=0,l=0,c=0,u=0,f=0;for(const{sample:r,noOutcome:o}of e){if(o)continue;const e=n.data[f++],i="outcome"in e?e.outcome:e.outcome_event;if(0!=i&&1!=i)throw"outcome is not 0 or 1";const s=a.samples.get(r);if(!s)continue;const[d,h]=s.split("/"),p=a.effAle==d||a.effAle==h;0==i?p?l++:t++:p?u++:c++}s.set(i,r);const d={index:i,n1:u,n2:l,n3:c,n4:t};o.push(d),i++}const a=await(0,m.run_rust)("fisher",JSON.stringify({input:o}));for(const e of JSON.parse(a)){const n=s.get(e.index),{effAle:o}=t.lowAFsnps.get(n),i=e.p_value,a="chisq"===e.fisher_chisq,l={id:n,AFstr:t.snpid2AFstr.get(n),data:{headerRow:T(n,t),fisher:{isChi:a,pvalue:Number(i.toFixed(4)),rows:[["","Carry "+o+" allele","No "+o+" allele"],["Have event",e.n1,e.n3],["No event",e.n2,e.n4]]}}};r.resultLst.push(l)}}(i,e,n,r);else{if("cox"!=t.regressionType)throw"unknown regression type";await async function(t,e,n,r){const o={data:{}},i=new Set;for(const[r,s]of t.lowAFsnps){const t=[];let a=0;for(const{sample:r,noOutcome:o}of e){if(o)continue;const e=n.data[a++];if(0!==e.outcome_event&&1!==e.outcome_event)throw"d.outcome_event is not 0/1";if(!Number.isFinite(e.outcome_time))throw"d.outcome_time is not numeric";const i={time:e.outcome_time,event:e.outcome_event},l=s.samples.get(r);if(!l)continue;const[c,u]=l.split("/");i.series=s.effAle==c||s.effAle==u?"1":"2",t.push(i)}new Set(t.map((t=>t.series))).size<2?i.add(r):o.data[r]=t}const s=await(0,g.y)(o);let a;for(const[e,n]of t.lowAFsnps){if(i.has(e)){a={pvalue:"NA",msg:"Cannot perform cumulative incidence test on this snp - at least one allele is not found in any sample"}}else{var l;if(1==!(null!==(l=s[e].tests)&&void 0!==l&&l.length))throw"must have a single test";const t=Number(s[e].tests[0].pvalue);if(!Number.isFinite(t))throw"invalid pvalue";a={pvalue:Number(t.toFixed(4)),ci_data:{[e]:s[e]}}}const n={id:e,AFstr:t.snpid2AFstr.get(e),data:{headerRow:T(e,t),cuminc:a}};r.resultLst.push(n)}}(i,e,n,r)}w=(new Date).getTime(),_.NodeJS.snplocusPostprocess=(w-b)/1e3+" sec"}}function T(t,e){const n=e.snpgt2count.get(t);if(!n)return{k:"Error",v:"Variant not found"};if(e.monomorphicLst.includes(t)){const[t,e]=[...n][0];return{k:"Genotype",v:t+"="+e}}const r=[`${0==e.q.alleleType?"Minor":"Alternative"} allele=${e.highAFsnps.has(t)?e.highAFsnps.get(t).effAle:e.lowAFsnps.get(t).effAle}`,"AF="+e.snpid2AFstr.get(t)];for(const[t,e]of n)r.push(t+"="+e);return{k:"Variant:",v:r.join(" ")}}function C(t,e,n){if(t.q.restrictAncestry)for(const[n,r]of t.q.restrictAncestry.pcs)for(const[t,o]of r)e.has(t)&&e.get(t).id2value.set(n,{key:o,value:o})}async function j(t,e,n){const r=(await p.b5(o().join(h().cache_snpgt.dir,t.q.cacheid))).split("\n"),i=r[0].split("\t").slice(h().cache_snpgt.sampleColumn).map(Number);if(n)for(const t of i)e.set(t,{id2value:new Map});const s=i.map((t=>e.has(t))),a=new Map;for(let e=1;e<r.length;e++){const n=r[e].split("\t"),o=n[0],l={refAle:n[3],altAles:n[4].split(","),samples:new Map};t.q.snp2effAle?l.effAle=t.q.snp2effAle[o]:l.effAle=l.altAles[0],a.set(o,l);for(const[t,e]of i.entries()){if(!s[t])continue;const r=n[t+h().cache_snpgt.sampleColumn];r&&a.get(o).samples.set(e,r)}}"snplocus"!=t.type&&function(t,e,n,r){if(0==e.q.missingGenotype){for(const e of t.values()){let t;if(e.refAle!=e.effAle)t=e.refAle;else for(const n of e.altAles)if(n!=e.effAle){t=n;break}if(!t)throw"not finding a non-effect allele";for(const[o,i]of n.entries())r[o]&&(e.samples.has(i)||e.samples.set(i,t+"/"+t))}return}if(1==e.q.missingGenotype){const e=new Set;for(const{samples:o}of t.values())for(const[t,i]of n.entries())r[t]&&(o.has(i)||e.add(i));for(const{samples:n}of t.values())for(const t of e)n.delete(t);return}throw"invalid missingGenotype value"}(a,t,i,s),t.snpgt2count=new Map;for(const[e,n]of a){const r=new Map;for(const[t,e]of n.samples)r.set(e,1+(r.get(e)||0));t.snpgt2count.set(e,r)}!function(t,e){t.lowAFsnps=new Map,t.highAFsnps=new Map,t.monomorphicLst=[],t.snpid2AFstr=new Map;for(const[n,r]of e){if(1==t.snpgt2count.get(n).size){t.monomorphicLst.push(n);continue}const e=r.samples.size;let o=0;for(const[t,e]of r.samples){const[t,n]=e.split("/");o+=(t==r.effAle?1:0)+(n==r.effAle?1:0)}const i=o/(2*e);t.snpid2AFstr.set(n,(100*i).toFixed(1)+"%"),i<t.q.AFcutoff/100?t.lowAFsnps.set(n,r):t.highAFsnps.set(n,r)}}(t,a);for(const[n,r]of t.highAFsnps)for(const[o,i]of r.samples){const[s,a]=i.split("/"),l=E(t,r.effAle,s,a);e.get(o).id2value.set(n,{key:l,value:l})}}function E(t,e,n,r){switch(t.q.geneticModel){case 0:return(n==e?1:0)+(r==e?1:0);case 1:return n==e||r==e?1:0;case 2:return n==e&&r==e?1:0;case 3:return n+"/"+r;default:throw"unknown geneticModel option"}}function O(t,e){if(t.tag===e)return t;if("tvslst"===t.type)for(const n of t.lst){const t=O(n,e);if(t)return t}}},2188:(t,e,n)=>{"use strict";n.d(e,{uR:()=>g,v8:()=>k,wz:()=>m});var r=n(2974),o=n(1017),i=n.n(o),s=n(3345),a=n(334),l=n.n(a),c=n(2273),u=n(8907),f=n(5257),d=n(6191),h=n(9157);const p="#F5F5DC";async function m(t){if(t.cohort.scatterplots){if(!Array.isArray(t.cohort.scatterplots.plots))throw"cohort.scatterplots.plots is not array";for(const e of t.cohort.scatterplots.plots){if(!e.name)throw".name missing from one of scatterplots.plots[]";if(!e.file)throw"unknown data source of one of scatterplots.plots[]";{const n=(await(0,s.b5)(i().join(l().tpmasterdir,e.file))).trim().split("\n"),r=n[0].split("\t");e.filterableSamples=[];const o=[];let a=0,c=0;for(let i=1;i<n.length;i++){const s=n[i].split("\t"),l=Number(s[1]),u=Number(s[2]);if(Number.isNaN(l)||Number.isNaN(u)){a++;continue}const f={sample:s[0],x:l,y:u},d=t.cohort.termdb.q.sampleName2id(s[0]);if(null==d){if(r[3]){f.info={};for(let t=3;t<r.length;t++)f.info[r[t]]=s[t]}o.push(f)}else c++,f.sampleId=d,e.filterableSamples.push(f)}o.length&&(e.referenceSamples=o),console.log(e.filterableSamples.length,`scatterplot lines from ${e.name} of ${t.label},`,e.referenceSamples?e.referenceSamples.length+" reference cases":"",a?a+" lines with invalid X/Y values":"")}}}}async function g(t,e,n,o,i){try{let s,a;if(2==e.coordTWs.length)s=[],a=await async function(t,e,n){e.ds=n;const r=[];if(2!=e.coordTWs.length)return r;const o=await(0,f.w)(e.filter,e.ds);let i="";o&&(i+=(0,u.ig)(`WITH ${o.filters}`,o.values.slice()));const s=e.coordTWs[0].term,a=e.coordTWs[1].term;let l;e.divideByTW&&"continuous"==e.divideByTW.q.mode&&(l=e.divideByTW.term);i+=`SELECT ax.sample AS sampleId, ax.value as x, ay.value AS y , ${l?"az.value AS z":"0 as z"}\n\t\t\tFROM anno_${s.type} ax \n\t\t\tJOIN anno_${a.type} ay on ax.sample = ay.sample and ay.term_id = '${a.id}' \n\t\t\t${l?`JOIN anno_${l.type} az on ax.sample = az.sample and az.term_id = '${l.id}' `:""}\n\t\t\tWHERE ax.term_id = '${s.id}'`,o&&(i+=` AND ax.sample IN ${o.CTEname}`);const c=e.ds.cohort.db.connection.prepare(i).all(),h=d.i.canDisplaySampleIds(t,n);for(const{sampleId:t,x:o,y:i,z:s}of c){var p;if(null!==(p=l)&&void 0!==p&&p.values&&s in l.values)continue;const a={sampleId:t,x:o,y:i,z:s};h&&(a.sample=n.sampleId2Name.get(t));const c=x(e.coordTWs[0].term,o)&&x(e.coordTWs[1].term,i);a&&c&&r.push(a)}return r}(t,e,o);else{if(!e.plotName)throw"Neither plot name or coordinates where provided";if(!o.cohort.scatterplots||!o.cohort.scatterplots.plots)throw"not supported";const t=o.cohort.scatterplots.plots.find((t=>t.name==e.plotName));if(!t)throw`plot not found with plotName ${e.plotName}`;const n=await async function(t,e,n){if(n.filterableSamples){let t=[],e=[];return n.referenceSamples&&(e=r(n.referenceSamples)),n.filterableSamples&&(t=r(n.filterableSamples)),[e,t]}if(n.gdcapi)throw"gdcapi not implemented yet";throw"do not know how to load data from this plot";function r(t){const e=[];for(const n of JSON.parse(JSON.stringify(t)))e.push(n);return e}}(0,0,t);s=n[0],a=n[1]}const l=[];e.coordTWs&&l.push(...e.coordTWs),e.colorTW&&l.push(e.colorTW),e.shapeTW&&l.push(e.shapeTW),e.divideByTW&&l.push(e.divideByTW),e.scaleDotTW&&l.push(e.scaleDotTW);const h=await(0,r.Yu)({filter:e.filter,terms:l},o,i);if(h.error)throw h.error;const m=await async function(t,e,n,r){const o={};for(const c of e){const e=n.samples[c.sampleId.toString()];if(!e)continue;let d=!1;if(r.colorTW&&!y(e,r.colorTW)||r.shapeTW&&!y(e,r.shapeTW))continue;let h="Default";if(r.divideByTW&&"continuous"!=r.divideByTW.q.mode)if(c.z=0,"geneVariant"==r.divideByTW.term.type)h=b(!0,e,r.divideByTW),null==h&&(h=b(!1,e,r.divideByTW),d=!0);else{var i,s,a;const t=null===(i=e[r.divideByTW.term.id||r.divideByTW.term.name])||void 0===i?void 0:i.key;if(null==t)continue;h=(null===(s=r.divideByTW.term.values)||void 0===s||null===(a=s[t])||void 0===a?void 0:a.label)||t}if(!o[h]){const e=t.map((t=>({...t,category:"Ref",shape:"Ref",z:0})));o[h]={samples:e,colorMap:{},shapeMap:{},isLast:d}}if(r.divideByTW||(c.z=0),r.scaleDotTW){var l;const t=null==e||null===(l=e[r.scaleDotTW.id])||void 0===l?void 0:l.key;if(!t||!x(r.scaleDotTW.term,t))continue;c.scale=t}else c.scale=1;var u,f;if(c.cat_info={},c.hidden={},r.colorTW)"continuous"===(null===(u=r.colorTW)||void 0===u||null===(f=u.q)||void 0===f?void 0:f.mode)?e&&(c.category=e[r.colorTW.term.id||r.colorTW.term.name].value):v(e,c,r.colorTW,o[h].colorMap,"category");else c.category="Default";r.shapeTW?v(e,c,r.shapeTW,o[h].shapeMap,"shape"):c.shape="Ref",o[h].samples.push(c)}let d=0;for(const[t,e]of Object.entries(o))d=Math.max(d,Object.keys(e.colorMap).length);const h=(0,c.getColors)(d);for(const[i,s]of Object.entries(o)){var m,g,w;if(r.colorTW&&"continuous"!==r.colorTW.q.mode){let t=20;const e=c.schemeCategory20,o=Object.entries(s.colorMap);for(const[i,s]of o){var k,q,N,S;let o;if(null!==(k=r.colorTW.term.values)&&void 0!==k&&k[i])o=null===(q=r.colorTW.term.values)||void 0===q?void 0:q[i];else for(const t in r.colorTW.term.values){var A,M;(null===(A=r.colorTW.term.values)||void 0===A?void 0:A[t].label)==i&&(o=null===(M=r.colorTW.term.values)||void 0===M?void 0:M[t])}if(o&&"color"in o)s.color=o.color;else if(null!==(N=n.refs)&&void 0!==N&&null!==(S=N.byTermId[r.colorTW.term.id])&&void 0!==S&&S.bins){const o=n.refs.byTermId[r.colorTW.term.id].bins.find((t=>t.name===i));o?s.color=o.color:(s.color=e[t],t--)}else"geneVariant"!=r.colorTW.term.type&&(s.color=h(i))}}let o=1;for(const[t,e]of Object.entries(s.shapeMap))"shape"in e||(e.shape=o),o++;s.colorLegend=r.colorTW?_(s.colorMap,r.colorTW,n.refs):[["Default",{sampleCount:e.length,color:"blue"}]],s.colorLegend.push(["Ref",{sampleCount:t.length,color:null!==(m=r.colorTW)&&void 0!==m&&null!==(g=m.term.values)&&void 0!==g&&g.Ref?null===(w=r.colorTW.term.values)||void 0===w?void 0:w.Ref.color:p}]),s.shapeLegend=_(s.shapeMap,r.shapeTW,n.refs),s.shapeLegend.push(["Ref",{sampleCount:t.length,shape:0}])}return o}(s,a,h,e);n.send(m)}catch(t){t.stack&&console.log(t.stack),n.send({error:t.message||t})}}function y(t,e){var n,r,o;const i=void 0!==(null==t||null===(n=t[(null==e||null===(r=e.term)||void 0===r?void 0:r.id)||(null==e||null===(o=e.term)||void 0===o?void 0:o.name)])||void 0===n?void 0:n.key);return i||console.log(JSON.stringify(t)+" missing value for the term "+JSON.stringify(e)),i}function v(t,e,n,r,o){let i=null;if("geneVariant"==n.term.type)!function(t,e,n,r,o){if("geneVariant"==n.term.type){var i;const s=null==t||null===(i=t[n.term.name])||void 0===i?void 0:i.values;e.cat_info[o]=[];for(const t of s){const n=c.mclass[t.class],i=w(t);let s;e.cat_info[o].push(t),null==r[i]?(s={color:n.color,sampleCount:1,hasOrigin:"origin"in t},r[i]=s):(s=r[i],s.sampleCount=s.sampleCount+1,s.hasOrigin=s.hasOrigin||"origin"in t)}e[o]=b(!0,t,n)||b(!1,t,n),e[o]||(e[o]=w(s[0])),e.hidden[o]=!!n.q.hiddenValues&&e[o]in n.q.hiddenValues}}(t,e,n,r,o);else{var s,a,l,u,f,d;if(i=null==t||null===(s=t[n.id||n.term.name])||void 0===s?void 0:s.key,null!==(a=n.term.values)&&void 0!==a&&null!==(l=a[i])&&void 0!==l&&l.label)i=null===(f=n.term.values)||void 0===f||null===(d=f[i])||void 0===d?void 0:d.label,e.hidden[o]=!!n.q.hiddenValues&&i in n.q.hiddenValues;else e.hidden[o]=!!n.q.hiddenValues&&(null==t||null===(u=t[n.id])||void 0===u?void 0:u.key)in n.q.hiddenValues;i&&(e[o]=i.toString(),null==r[i]?r[i]={sampleCount:1}:r[i].sampleCount++)}}function b(t,e,n){var r;const o=null==e||null===(r=e[n.term.name])||void 0===r?void 0:r.values;for(const[e,r]of Object.entries(c.dt2label)){const r=o.find((t=>{const r=w(t),o=!(n.q.hiddenValues&&r in n.q.hiddenValues);return t.dt==e&&o}));if(!r)continue;const i="WT"==r.class||"Blank"==r.class;if(t&&i)continue;return w(r)}}function w(t){var e;const n=t.dt,r=c.mclass[t.class],o=null===(e=c.morigin[t.origin])||void 0===e?void 0:e.label,i=o?`${o[0]} ${c.dt2label[n]}`:c.dt2label[n];return`${r.label}, ${i}`}function _(t,e,n){var r;let o=[];if(!e||0==t.size)return o;if("geneVariant"==e.term.type)o=Object.entries(t),o.sort(((t,e)=>t[0]<e[0]?-1:t[0]>e[0]?1:0));else if(null!=n&&null!==(r=n.byTermId[e.term.id])&&void 0!==r&&r.bins){const r=n.byTermId[e.term.id].bins;for(const e of r)t[e.name]&&o.push([e.name,t[e.name]]);for(const[e,n]of Object.entries(t))o.some((t=>t[0]===e))||o.push([e,n])}else o=Object.entries(t),o.sort(((t,n)=>{let r,o;for(const i in e.term.values){const s=e.term.values[i];(s.label&&t[0]==s.label||i==t[0])&&(r=s),(s.label&&n[0]==s.label||i==n[0])&&(o=s)}var i,s;return r&&"order"in r?(null===(i=r)||void 0===i?void 0:i.order)<(null===(s=o)||void 0===s?void 0:s.order)?-1:1:t[1].sampleCount>n[1].sampleCount?-1:1}));return o}function x(t,e){var n,r;return!(null!==(n=t.values)&&void 0!==n&&null!==(r=n[e])&&void 0!==r&&r.uncomputable)}async function k(t,e,n){const r=e.coords,o=i().join(l().cachedir,Math.random().toString()+".json");await(0,s.Sf)(o,JSON.stringify(r));let a=await(0,h.default)(i().join(l().binpath,"utils/lowess.R"),[],[o]);a=JSON.parse(a);const c=[];for(const[t,e]of Object.entries(a.x))c.push([e,a.y[t]]);return n.send(c)}},394:(t,e,n)=>{"use strict";n.d(e,{JV:()=>l,jj:()=>c,qN:()=>u});var r=n(334),o=n.n(r),i=n(3345),s=n(1575),a=n(6191);function l(t){if(!t.cohort)throw"ds.cohort missing";if(!t.cohort.db)throw"ds.cohort.db missing";if(!t.cohort.termdb)throw"ds.cohort.termdb missing";const e=t.cohort.db.file_fullpath||t.cohort.db.file;if(!e)throw"both file and file_fullpath missing";let n;try{console.log("Connecting",e),n=(0,i.sE)(e),console.log(`DB connected for ${t.label}: ${e}`)}catch(t){throw`Cannot connect db ${e}: ${t.message||t}`}t.cohort.db.connection=n;const r=c(n),l=["cohorts","sampleidmap","terms","ancestry","alltermsbyorder","termhtmldef","category2vcfsample","chronicevents","precomputed_chc_grade","precomputed_chc_child","precomputed_cuminc","precomputed_cox","subcohort_terms","subcohort_samples","survival","features","cohort_features","anno_integer","anno_float","anno_categorical","buildDate"];for(const t of l)r.has(t)||console.log(`${t} table missing!!!!!!!!!!!!!!!!!!!!`);if(!r.has("terms"))throw"terms table missing";if(!r.has("ancestry"))throw"ancestry table missing";if(t.cohort.termdb.selectCohort&&!r.has("subcohort_terms"))throw"subcohort_terms table is missing while termdb.selectCohort is enabled";t.cohort.termdb.q={};const f=t.cohort.termdb.q;if(r.has("buildDate")&&(f.get_buildDate=n.prepare("select date from buildDate")),r.has("term2genes")){t.cohort.termdb.termMatch2geneSet=!0;const e=n.prepare("SELECT genes FROM term2genes WHERE id=?"),r=new Map;f.getGenesetByTermId=t=>{if(r.has(t))return r.get(t);const n=e.get(t);if(n&&n.genes){const e=JSON.parse(n.genes);return r.set(t,e),e}}}if(r.has("sampleidmap")){const e=new Map,r=new Map,o=n.prepare("SELECT * FROM sampleidmap");let i=0;for(const{id:t,name:n}of o.all())e.set(t,n),r.set(n,t),i++;if(f.id2sampleName=t=>e.get(t),f.sampleName2id=t=>r.get(t),t.cohort.termdb.selectCohort){const t=n.prepare("SELECT cohort,sample_count from cohorts").all(),e={};for(const n of t)e[n.cohort]=n.sample_count;f.getcohortsamplecount=t=>t?e[t]||0:i}else f.getcohortsamplecount=()=>i}if(r.has("category2vcfsample")){const t=n.prepare("SELECT * FROM category2vcfsample");let e;f.getcategory2vcfsample=()=>{if(e)return e;e=t.all();for(const t of e)t.q=JSON.parse(t.q),t.categories=JSON.parse(t.categories);return e}}if(r.has("alltermsbyorder")){const t=n.prepare("SELECT * FROM alltermsbyorder");let e;f.getAlltermsbyorder=()=>{if(e)return e;const n=t.all();e=[];for(const t of n){const n=f.termjsonByOneid(t.id);n&&e.push({group_name:t.group_name,term:n})}return e}}{const t=n.prepare("SELECT name, jsondata FROM terms WHERE id=?"),e=new Map;f.termjsonByOneid=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsondata);return t.id=n,t.name=r.name||t.name,e.set(n,t),t}}}{const t=n.prepare("select id from terms where parent_id=?"),e=new Map;f.termIsLeaf=n=>{if(e.has(n))return e.get(n);let r=!0;const o=t.get(n);return o&&o.id&&(r=!1),e.set(n,r),r}}{const t=n.prepare("SELECT id, name, jsondata, s.included_types, s.child_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE parent_id is null\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),e=new Map;f.getRootTerms=(n="")=>{const r=n;if(e.has(r))return e.get(r);const o=t.all(n).map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):["TO-DO-PLACEHOLDER"],e.child_types=t.child_types?t.child_types.split(","):[],e}));return e.set(r,o),o}}{const t=n.prepare("SELECT parent_id FROM terms WHERE id=?");{const e=new Map;f.termHasParent=n=>{if(e.has(n))return e.get(n);let r=!1;const o=t.get(n);return o&&o.parent_id&&(r=!0),e.set(n,r),r}}{const e=new Map;f.getTermParentId=n=>{if(e.has(n))return e.get(n);let r;const o=t.get(n);return o&&o.parent_id&&(r=o.parent_id),e.set(n,r),r}}{const t=new Map;f.getTermParent=e=>{if(t.has(e))return t.get(e);const n=f.getTermParentId(e);let r;return n&&(r=f.termjsonByOneid(n)),t.set(e,r),r}}}{const t=n.prepare("SELECT id, name, type, jsondata, s.included_types, s.child_types \n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=? \n\t\t\tWHERE id IN (SELECT id FROM terms WHERE parent_id=?)\n\t\t\tGROUP BY id\n\t\t\tORDER BY child_order ASC"),e=new Map;f.getTermChildren=(n,r="")=>{const o=n+";;"+r;if(e.has(o))return e.get(o);const i=t.all([r,n]);let s;return i&&(s=i.map((t=>{const e=JSON.parse(t.jsondata);return e.id=t.id,e.name=t.name||e.name,e.included_types=t.included_types?t.included_types.split(","):[],e.child_types=t.child_types?t.child_types.split(","):[],e}))),e.set(o,s),s}}{const t=n.prepare("SELECT id, name, jsondata, s.included_types\n\t\t\tFROM terms t\n\t\t\tJOIN subcohort_terms s ON s.term_id = t.id AND s.cohort=?\n\t\t\tWHERE name LIKE ?");f.findTermByName=(e,n=10,r="",o=null,i=null,a=null)=>{const l=t.all([r,"%"+e+"%"]);if(l){const t=a||{equals:[],startsWith:[],startsWord:[],includes:[]};for(const n of l){if(!n.jsondata)continue;const r=n.name.toLowerCase(),o=JSON.parse(n.jsondata);o.id=n.id,o.name=n.name||o.name,o.included_types=n.included_types?n.included_types.split(","):[],i&&!(0,s.CG)(o,i).has("plot")||(r===e?t.equals.push(o):r.startsWith(e)?t.startsWith.push(o):r.includes(" "+e)?t.startsWord.push(o):t.includes.push(o))}return[...t.equals,...t.startsWith,...t.startsWord,...t.includes].slice(0,n)}}}{const t=n.prepare("SELECT MAX(value) AS v FROM anno_integer WHERE term_id=?"),e=n.prepare("SELECT MAX(value) AS v FROM anno_float WHERE term_id=?"),r=new Map;f.findTermMaxvalue=(n,o)=>{if(r.has(n))return r.get(n);const i=(o?t:e).get(n);return i?(r.set(n,i.v),i.v):void 0}}{const t={float:n.prepare("SELECT sample,value FROM anno_float WHERE term_id=?"),integer:n.prepare("SELECT sample,value FROM anno_integer WHERE term_id=?"),categorical:n.prepare("SELECT sample,value FROM anno_categorical WHERE term_id=?")};f.getAllValues4term=e=>{const n=f.termjsonByOneid(e);if(!n)return;const r=t[n.type];if(!r)return;const o=r.all(e);if(!o||0==o.length)return;const i=new Map;for(const t of o)i.set(t.sample,t.value);return i}}{const t=n.prepare("SELECT ancestor_id FROM ancestry WHERE term_id=?"),e=new Map;f.getAncestorIDs=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.ancestor_id));return e.set(n,r),r}}{const t=n.prepare("SELECT t.name FROM ancestry as a, terms as t WHERE a.term_id=? AND t.id=a.ancestor_id"),e=new Map;f.getAncestorNames=n=>{if(e.has(n))return e.get(n);const r=t.all(n).map((t=>t.name));return e.set(n,r),r}}{const t={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=?")},e={categorical:n.prepare("SELECT value FROM anno_categorical WHERE term_id=? AND sample=?"),integer:n.prepare("SELECT value FROM anno_integer WHERE term_id=? AND sample=?"),float:n.prepare("SELECT value FROM anno_float WHERE term_id=? AND sample=?")},r={categorical:n.prepare("SELECT value FROM anno_categorical a,sampleidmap s WHERE term_id=? AND s.name=?"),integer:n.prepare("SELECT value FROM anno_integer a,sampleidmap s WHERE term_id=? AND s.name=?"),float:n.prepare("SELECT value FROM anno_float a, sampleidmap s WHERE term_id=? AND s.name=?")};f.getSample2value=(n,o=null)=>{const i=f.termjsonByOneid(n);return o?"string"==typeof o?r[i.type].all(n,o):e[i.type].all(n,o):t[i.type].all(n)}}if(r.has("termhtmldef")){const t=n.prepare("SELECT jsonhtml FROM termhtmldef WHERE id=?"),e=new Map;f.getTermInfo=n=>{if(e.has(n))return e.get(n);const r=t.get(n);if(r){const t=JSON.parse(r.jsonhtml);return t.id=n,e.set(n,t),t}}}f.getSupportedChartTypes=e=>{var n;u(t);null===(n=o().dsCredentials)||void 0===n||n[t.label];const r={},i={};for(const n of t.cohort.termdb.termtypeByCohort){var s;if(n.type){if(!(n.cohort in r)){var l;r[n.cohort]=new Set(["regression","summary"]),t.cohort.scatterplots&&r[n.cohort].add("sampleScatter"),i[n.cohort]=0,null!==(l=t.cohort.allowedChartTypes)&&void 0!==l&&l.includes("matrix")&&r[n.cohort].add("matrix");const o=a.i.getForbiddenRoutesForDsEmbedder(t.label,e);o.includes("termdb")||o.includes("*")||(r[n.cohort].add("dataDownload"),r[n.cohort].add("sampleView"))}null!==(s=o().features)&&void 0!==s&&s.draftChartTypes&&r[n.cohort].add(...o().features.draftChartTypes),"survival"!=n.type||r[n.cohort].has("survival")||r[n.cohort].add("survival"),"condition"!=n.type||r[n.cohort].has("cuminc")||r[n.cohort].add("cuminc"),"float"!=n.type&&"integer"!=n.type||(i[n.cohort]+=n.samplecount)}}for(const t in i)i[t]>1&&r[t].add("sampleScatter");for(const t in r)r[t]=[...r[t]];if(t.cohort.allowedChartTypes)for(const e in r)r[e]=r[e].filter((e=>t.cohort.allowedChartTypes.includes(e)));if(t.queries){if(t.queries.snvindel||t.queries.trackLst)for(const t in r)r[t].push("genomeBrowser");if(t.queries.geneExpression)for(const t in r)r[t].push("hierCluster");if(t.queries.rnaseqGeneCount)for(const t in r)r[t].push("DEanalysis")}return r},f.getSingleSampleData=function(t,e=[]){const r=e.length?`and term_id in (${e.map((t=>"?")).join(",")})`:"",o=`select term_id, value, jsondata from ( select term_id, value \n\t\tfrom anno_categorical \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, \n\t\tvalue from anno_float \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, value \n\t\tfrom anno_integer \n\t\twhere sample=? ${r}\n\t\tunion all \n\t\tselect term_id, (min_years_to_event || ' ' || value) as value \n\t\tfrom precomputed_chc_grade \n\t\twhere max_grade=1 and sample=? ${r}\n\t\tunion all \n\t\tselect term_id, (tte || ' ' || exit_code) as value \n\t\tfrom survival \n\t\twhere sample=? ${r}) join terms on terms.id = term_id`;return n.prepare(o).all([t,...e,t,...e,t,...e,t,...e,t,...e])},f.getProfileFacilities=function(){return n.prepare("select name from sampleidmap join \n\t\tanno_categorical on sampleidmap.id = anno_categorical.sample\n\t\twhere term_id = 'sampleType' and value = 'Facility'").all()}}function c(t){const e=t.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();return new Set(e.map((t=>t.name)))}function u(t){var e,n;if(t.cohort.termdb.termtypeByCohort){if(!Array.isArray(t.cohort.termdb.termtypeByCohort))throw"termtypeByCohort is not array"}else{if(null===(e=t.cohort)||void 0===e||null===(n=e.db)||void 0===n||!n.connection)throw"termtypeByCohort[] not set but cohort.db.connection missing";t.cohort.termdb.termtypeByCohort=t.cohort.db.connection.prepare("WITH c AS (\n\t\t\tSELECT cohort, term_id\n\t\t\tFROM subcohort_terms s\n\t\t\tGROUP BY cohort, term_id\n\t\t) \n\t\tSELECT cohort, type, count(*) as samplecount\n\t\tFROM terms t\n\t\tJOIN c ON c.term_id = t.id\n\t\tGROUP BY cohort, type").all()}}},3795:(t,e,n)=>{"use strict";n.d(e,{G:()=>g,u:()=>y});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(3345),l=n(8907),c=(n(2826),n(4521),n(334)),u=n.n(c),f=n(3625);const d="%CHROM\t%POS\t%REF\t%ALT[\t%TGT]\n",h="%POS\t%ID\t%REF\t%ALT\t%INFO[\t%TGT]\n",p="./.",m=1e3;async function g(t,e,n,r){try{if(t.sumSamples)return await async function(t,e,n,r){if(!t.cacheid)throw"cacheid missing";if(u().cache_snpgt.fileNameRegexp.test(t.cacheid))throw"invalid cacheid";let o,i;if(n.track){if(o=n.track.vcf,!o)throw"ds.track.vcf missing"}else o=n.queries.snvindel.byrange._tk;if(t.filter){const e=new Set((await l.cf(t.filter,n)).map((t=>t.id)));if(0==e.size)throw"no samples from filter";i=o.samples.map((t=>e.has(t.name)))}else i=o.samples.map((t=>!0));const c=(await a.b5(s().join(u().cache_snpgt.dir,t.cacheid))).split("\n"),f=new Set,d=[];for(let t=1;t<c.length;t++){const e=c[t].split("\t"),n=e[0],r=e[3],s={},a={};for(let t=u().cache_snpgt.sampleColumn;t<e.length;t++){const n=e[t];if(!n)continue;if(!i[t-u().cache_snpgt.sampleColumn])continue;f.add(o.samples[t-u().cache_snpgt.sampleColumn].name),a[n]=1+(a[n]||0);const r=n.split("/");for(const t of r)s[t]=1+(s[t]||0)}const l=[];for(const t in s)l.push({allele:t,count:s[t],isRef:t==r});d.push({snpid:n,alleles:l,gt2count:a})}return{numOfSampleWithAnyValidGT:f.size,snps:d}}(t,0,n);if(t.snptext)return await async function(t,e,n){if(!n.snp)throw"snp not supported by genome";if(!t.snptext)throw".snptext missing";const r=function(t){const e=[];for(const n of t.trim().split("\n")){const[t,r]=n.trim().split(/[\s\t]/);if(t&&t.startsWith("rs")){if(e.find((e=>e.rsid==t)))continue;const n={rsid:t,snpid:t};r&&(n.effectAllele=r),e.push(n)}else e.push({rsid:t,snpid:t,invalid:"INVALID RSID"})}return e}(t.snptext);if(!r.length)throw"no snps";await async function(t,e){for(const n of t)if(!n.invalid)if(n.chr&&"string"==typeof n.chr){const t=e.chrlookup[n.chr.toUpperCase()];if(!t){n.invalid=!0;continue}if(!Number.isInteger(n.pos)){n.invalid=!0;continue}if(n.pos<=0||n.pos>=t.len){n.invalid=!0;continue}}else if(n.rsid){const t=await a.mr(e.snp.bigbedfile,n.rsid),r=[];for(const n of t){const t=n.split("\t"),o=e.chrlookup[t[0].toUpperCase()];o&&o.major&&r.push(t)}if(0==r.length){n.invalid=!0;continue}const o=r[0];n.chr=o[0],n.pos=Number.parseInt(o[1]),n.dbsnpRef=o[4],n.dbsnpAlts=o[6].split(",").filter(Boolean)}else n.invalid=!0;if(!t.find((t=>!t.invalid)))throw"no valid variants"}(r,n);const i=await async function(t,e,n){let r;if(n.track){if(r=n.track.vcf,!r)throw"ds.track.vcf missing"}else r=n.queries.snvindel.byrange._tk;const i=new Set,l=[];for(const t of e){if(t.invalid)continue;let e;var c;if(r.chr2files){if(e=null===(c=r.chr2files)||void 0===c?void 0:c[t.chr].file,!e)throw"chr not in chr2files"}else if(r.chr2bcffile){if(e=r.chr2bcffile[t.chr],!e)throw"chr not in chr2bcffile"}else e=r.file||r.url;i.add(e);const n=(r.nochr?t.chr.replace("chr",""):t.chr)+"\t"+(t.pos+1);l.push(n)}const f=s().join(u().cachedir,await a.tG(l.join("\n"))),h=s().join(u().cachedir,await a.tG([...i].join("\n")));await a.UE({isbcf:!0,args:["query","-R",f,"-f",d,"-v",h],dir:r.dir,callback:t=>{const n=t.split("\t"),o=(r.nochr?"chr":"")+n[0],i=n[1],s=n[2],a=n[3].split(","),l=e.find((t=>{if(t.chr==o&&t.pos===i-1&&t.dbsnpRef==s&&t.dbsnpAlts.some((t=>a.includes(t))))return t}));if(l){l.referenceAllele=s,l.altAlleles=a,l.gtlst=[];for(let t=4;t<n.length;t++)l.gtlst.push(n[t]==p?"":n[t])}}}),o().unlink(f,(()=>{})),o().unlink(h,(()=>{}));const m=["snpid\tchr\tpos\tref\talt\teff\t"+r.samples.map((t=>t.name)).join("\t")];for(const t of e)t.invalid||t.gtlst&&(m.push(t.snpid+"\t"+t.chr+"\t"+t.pos+"\t"+t.referenceAllele+"\t"+t.altAlleles.join(",")+"\t"+(t.effectAllele||"")+"\t"+t.gtlst.join("\t")),delete t.gtlst);const g=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random());return await a.Sf(s().join(u().cache_snpgt.dir,g),m.join("\n")),g}(t,r,e);return{snps:r,cacheid:i}}(t,n,r);if(t.chr)return await async function(t,e,n){const r=Number(t.start),o=Number(t.stop);if(!Number.isInteger(r)||!Number.isInteger(o))throw"start/stop are not integers";if(r>o||r<0)throw"invalid start/stop coordinate";let i,l;if(e.track){if(i=e.track.vcf,!i)throw"ds.track.vcf missing";if(l=i.chr2bcffile[t.chr],!l)throw"chr not in chr2bcffile"}else{var c;if(i=e.queries.snvindel.byrange._tk,i.chr2files)l=null===(c=i.chr2files)||void 0===c?void 0:c[t.chr].file;else l=i.file||i.url;if(!l)throw"no bcf file"}const d=(i.nochr?t.chr.replace("chr",""):t.chr)+":"+r+"-"+o,g=["query",l,"-r",d,"-f",h];t.variant_filter&&y(t.variant_filter,g);const v={snps:[]},b=["snpid\tchr\tpos\tref\talt\teff\t"+i.samples.map((t=>t.name)).join("\t")];return await a.UE({isbcf:!0,args:g,dir:i.dir,callback:(e,n)=>{if(v.snps.length>=m)return n.kill(),void(v.reachedVariantLimit=!0);const r=e.split("\t"),o=Number(r[0])-1,s=r[1],a=r[2],l=r[3].split(","),c=s&&"."!=s?s:o+"."+a+"."+l.join(","),u={snpid:c,chr:t.chr,pos:o};(0,f.H)(i,a,l,u,r[4],r[1]);for(const t of u.mlst)t.vcf_id&&(t.mname=t.vcf_id);v.snps.push(u);const d=[c,t.chr,o,a,l.join(","),""];for(let t=5;t<r.length;t++)d.push(r[t]==p?"":r[t]);b.push(d.join("\t"))}}),v.cacheid=t.genome+"_"+t.dslabel+"_"+new Date/1+"_"+Math.ceil(1e4*Math.random()),await a.Sf(s().join(u().cache_snpgt.dir,v.cacheid),b.join("\n")),v}(t,n);throw"unknown how to validate"}catch(t){return t.stack&&console.log(t.stack),{error:t.message||t}}}function y(t,e){const n=[];for(const e of t.lst)if(e.tvs.values){const t=e.tvs.isnot?"!=":"=";for(const r of e.tvs.values){const o=isNaN(r.key)?`"${r.key}"`:Number(r.key);n.push(`INFO/${e.tvs.term.id}${t}${o}`)}}else{if(!e.tvs.ranges)throw`unknown tvs spec for info_field: type=${e.type}, term.id=${e.tvs.term.id}`;for(const t of e.tvs.ranges)"start"in t&&n.push(`INFO/${e.tvs.term.id} ${t.startinclusive?">=":">"} ${t.start}`),"stop"in t&&n.push(`INFO/${e.tvs.term.id} ${t.stopinclusive?"<=":"<"} ${t.stop}`)}0!=n.length&&e.push("-i",n.join(" && "))}},8907:(t,e,n)=>{"use strict";n.d(e,{yT:()=>M,YG:()=>C,g5:()=>S,J4:()=>N,B9:()=>k,cf:()=>x,tt:()=>q,Bi:()=>A,ig:()=>j});var r={};n.r(r),n.d(r,{binary:()=>f,continuous:()=>l,cubicSpline:()=>c,discrete:()=>u});var o={};n.r(o),n.d(o,{groupset:()=>p,values:()=>d});var i={};n.r(i),n.d(i,{binary:()=>g,cox:()=>v,cuminc:()=>y,discrete:()=>m});var s=n(4048),a=n(5257);const l={getCTE(t,e,n,r,o,i,s){o.push(e.id);const a=M(e,r);return o.push(...a.values),{sql:`${t} AS (\n\t\t\t\tSELECT \n\t\t\t\t\tsample,\n\t\t\t\t\tvalue as key, \n\t\t\t\t\tvalue\n\t\t\t\tFROM anno_${e.type}\n\t\t\t\tWHERE term_id=? ${a.clause}\n\t\t\t)`,tablename:t}}},c=l,u={getCTE(t,e,n,r,o,i,s){o.push(e.id);const a=C(r,e,n,i,s),l=[],c=new Map;r.bin_size;for(const t of a)!("name"in t)&&t.label&&(t.name=t.label),c.set(t.name,t),l.push(`SELECT '${t.name}' AS name,\n\t\t\t\t${null==t.start?0:t.start} AS start,\n\t\t\t\t${null==t.stop?0:t.stop} AS stop,\n\t\t\t\t0 AS unannotated,\n\t\t\t\t${t.startunbounded?1:0} AS startunbounded,\n\t\t\t\t${t.stopunbounded?1:0} AS stopunbounded,\n\t\t\t\t${t.startinclusive?1:0} AS startinclusive,\n\t\t\t\t${t.stopinclusive?1:0} AS stopinclusive`);const u=[];if(e.values)for(const t in e.values){const n=e.values[t].uncomputable;if(r.computableValuesOnly&&n)continue;if(!r.computableValuesOnly&&!n)continue;u.push(t);const o=e.values[t];l.push(`SELECT '${o.label}' AS name,\n\t ${t} AS start,\n\t 0 AS stop,\n\t 1 AS unannotated,\n\t 0 AS startunbounded,\n\t 0 AS stopunbounded,\n\t 0 AS startinclusive,\n\t 0 AS stopinclusive`),c.set(o.label,{is_unannotated:!0,value:t,label:o.label})}const f="bin_defs_"+i,d=M(e,r,"a");o.push(...d.values);return{sql:`${f} AS (\n\t\t\t\t${l.join("\nUNION ALL\n")}\n\t\t\t),\n\t\t\t${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tb.name AS key,\n\t\t\t\t\tvalue\n\t\t\t\tFROM\n\t\t\t\t\tanno_${e.type} a\n\t\t\t\tJOIN ${f} b ON\n\t\t\t\t\t( b.unannotated=1 AND value=b.start )\n\t\t\t\t\tOR\n\t\t\t\t\t(\n\t\t\t\t\t\tb.unannotated=0 AND\n\t\t\t\t\t\t${u.length?"value NOT IN ("+u.join(",")+") AND":""}\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.startunbounded = 1\n\t\t\t\t\t\t\tOR value > b.start\n\t\t\t\t\t\t\tOR (b.startinclusive=1 AND value = b.start)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tb.stopunbounded\n\t\t\t\t\t\t\tOR value < b.stop\n\t\t\t\t\t\t\tOR (b.stopinclusive=1 AND value = b.stop)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\tWHERE\n\t\t\t\tterm_id=? ${d.clause}\n\t\t\t)`,tablename:t,name2bin:c,bins:a}}},f=u,d={getCTE(t,e,n,r,o){o.push(e.id);const i=M(e,r);return o.push(...i.values),{sql:`${t} AS (\n\t\t\t\tSELECT sample,value as key, value as value\n\t\t\t\tFROM anno_categorical\n\t\t\t\tWHERE term_id=? ${i.clause}\n\t\t\t)`,tablename:t}}};let h=0;const p={async getCTE(t,e,n,r,o,i){if(!i.groups)throw`.groups[] missing from a group-set, term.id='${e.id}'`;const s=[],a=[];for(const t of i.groups)if("values"==t.type)s.push(`SELECT sample, ? as key, value\n\t\t\t\t\tFROM anno_categorical a\n\t\t\t\t\tWHERE term_id=?\n\t\t\t\t\t\tAND value IN (${t.values.map((t=>"?")).join(",")})\n\t\t\t\t`),o.push(t.name,e.id,...t.values.map((t=>t.key.toString())));else{if("filter"!=t.type)throw`unsupported groupset type='${t.type}'`;if(!("activeCohort"in r.groupsetting)||!t.filter4activeCohort)throw`activeCohort error: cannot construct filter statement for group name='${t.name}', term.id=${e.id}`;{const i=t.filter4activeCohort[r.groupsetting.activeCohort],l=await getFilterCTEs(i,n,"xf"+h++);if(!l)throw`unable to construct a group='${t.name}' filter for term.id='${e.id}'`;a.push(l.filters),o.push(...l.values.slice(),t.name,t.name),s.push(`SELECT sample, ? AS key, ? AS value\n\t\t\t\t\t\tFROM ${l.CTEname}`)}}return{sql:`${a.length?a.join("\n,")+",":""}\n\t\t\t${t} AS (\n\t\t\t\t${s.join("\nUNION ALL\n")}\n\t\t\t)`,tablename:t}}},m={getCTE(t,e,n,r,o){if(r.breaks&&r.breaks.length>0)return w(t,e,r,o);{const[n,i]=b(r);o.push(e.id);const s=M(e,r);return o.push(...s.values),{sql:`${t} AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tsample,\n\t\t\t\t\t\tvalue as key,\n\t\t\t\t\t\tvalue\n\t\t\t\t\tFROM\n\t\t\t\t\t\t${"grade"==n?"precomputed_chc_grade":"precomputed_chc_child"}\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tterm_id = ?\n\t\t\t\t\t\tAND ${i} = 1\n\t\t\t\t\t\t${s.clause}\n\t\t\t\t)`,tablename:t}}}},g={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"binary mode requires one break";return w(t,e,r,o)}},y={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"cuminc mode requires one break";return o.push(e.id,r.breaks[0]),{sql:`${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\ttime AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cuminc\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:t}}},v={getCTE(t,e,n,r,o){var i;if(1!=(null===(i=r.breaks)||void 0===i?void 0:i.length))throw"cox mode requires one break";o.push(e.id,r.breaks[0]);const s=Object.keys(e.values).map(Number),a=Math.max(...s);return{sql:`${t} AS (\n\t\t\t\tSELECT\n\t\t\t\t\tsample,\n\t\t\t\t\tevent AS key,\n\t\t\t\t\tjson_object('age_start', age_start, 'age_end', age_end) AS value\n\t\t\t\tFROM\n\t\t\t\t\tprecomputed_cox\n\t\t\t\tWHERE\n\t\t\t\t\tterm_id = ?\n\t\t\t\t\tAND grade_cutoff = ?\n\t\t\t)`,tablename:t,events:[{event:1,label:`Event (grade ${r.breaks[0]===a?r.breaks[0]:`${r.breaks[0]}-${a}`})`},{event:0,label:"Censored/death"},{event:-1,label:"Event before entry into the cohort"}]}}};function b(t){const e=t.bar_by_children?"child":t.bar_by_grade?"grade":"";if(!e)throw"must set the bar_by_grade or bar_by_children query parameter";const n=t.value_by_max_grade?"max_grade":t.value_by_most_recent?"most_recent":t.value_by_computable_grade?"computable_grade":"";if(!n)throw"must set a valid value_by_*";return[e,n]}function w(t,e,n,r){const[o,i]=b(n);if("grade"!=o)throw"breaks must be used on grade values";const s=[];for(const t of n.groups)s.push(`SELECT sample, ? as key, value\n\t\t\tFROM precomputed_chc_grade\n\t\t\tWHERE\n\t\t\t\tterm_id=?\n\t\t\t\tAND ${i}=1\n\t\t\t\tAND value IN (${t.values.map((t=>"?")).join(",")})\n\t\t`),r.push(t.name,e.id,...t.values.map((t=>t.toString())));return{sql:`${t} AS (\n\t\t\t${s.join("\nUNION ALL\n")}\n\t\t)`,tablename:t}}const _={getCTE(t,e,n){let r,o,i="";for(const[t,s]of e.q.groups.entries())"in"in s||(s.in=!0),r=s.values.map((t=>t.sampleId)),o=r.map((()=>"?")).join(","),i+=`SELECT id as sample, ? as key, ? as value\n\t\t\t\tFROM sampleidmap\n\t\t\t\tWHERE sample ${s.in?"":"NOT"} IN (${o})\n\t\t\t`,t!=e.q.groups.length-1&&(i+="UNION ALL "),n.push(s.name,s.name,...r);return{sql:`${t} AS (${i})`,tablename:t}}};n(334),n(3345);async function x(t,e,n=!1){const r=await(0,a.w)(t,e),o=e.cohort.db.connection.prepare(r?`WITH ${r.filters} SELECT sample as id, name FROM ${r.CTEname} join sampleidmap on sample = sampleidmap.id`:"SELECT id, name FROM sampleidmap");let i;if(i=r?o.all(r.values):o.all(),n)return i;for(const t of i)delete t.name;return i}async function k(t,e){if(!t.filter)throw"filter missing";let n;if("object"==typeof t.filter)n=t.filter;else{if("string"!=typeof t.filter)throw"q.filter not obj or str";n=JSON.parse(t.filter)}const r=await(0,a.w)(n,e),o=`WITH ${r.filters}\n\t\tSELECT 'FILTERED_COHORT' as subcohort, count(distinct sample) as samplecount \n\t\tFROM ${r.CTEname}`;return e.cohort.db.connection.prepare(o).all(r.values)}async function q(t){const e=t.ds.cohort.termdb.q.termjsonByOneid(t.term_id);if("integer"!=e.type&&"float"!=e.type)throw"term is not numeric";if(!e.values)return[];const n=await(0,a.w)(t.filter,t.ds),r=n?n.values.slice():[];r.push(t.term_id);const o=[];for(const t in e.values)o.push("?"),r.push(Number(t));const i=`\n\t\t${n?"WITH "+n.filters:""}\n\t\tSELECT count(sample) AS samplecount,value\n\t\tFROM anno_${e.type}\n\t\tWHERE term_id=?\n\t\t${n?"AND sample IN "+n.CTEname:""}\n\t\tAND value IN (${o.join(",")})\n\t\tGROUP BY value`;return t.ds.cohort.db.connection.prepare(i).all(r)}async function N(t){if(!t.key)throw".key missing";if(!t.ds)throw".ds{} missing";const e=await(0,a.w)(t.filter,t.ds),n=e?e.values.slice():[],r=t.ds.cohort.termdb.q.termjsonByOneid(t.key);n.push(t.key);const o=`\n\t\t${e?"WITH "+e.filters:""}\n\t\tSELECT sample, value\n\t\tFROM anno_${r.type}\n\t\tWHERE term_id=?\n\t\t${e?" AND sample IN "+e.CTEname:""}`;return t.ds.cohort.db.connection.prepare(o).all(n)}async function S(t,e={}){"string"==typeof t.filter&&(t.filter=JSON.parse(decodeURIComponent(t.filter)));const n=Object.assign({withCTEs:!0,columnas:"t1.sample AS sample",groupby:""},e),r=await(0,a.w)(t.filter,t.ds),o=r?r.values.slice():[],i=await A(t,o,0,r),s=await A(t,o,1,r),l=await A(t,o,2,r),c=[i,s,l].map(((t,e)=>`\n\t\tSELECT sample, key, value, ${e} as termNum\n\t\tFROM ${t.tablename}\n\t\t${r?"WHERE sample IN "+r.CTEname:""}\n\t`)).join("\nUNION ALL\n"),u=`WITH\n\t\t${r?r.filters+",":""}\n\t\t${i.sql},\n\t\t${s.sql},\n\t\t${l.sql}\n\t\t${c}`;try{const e=t.ds.cohort.db.connection.prepare(u).all(o),a=new Map;for(const t of e){a.has(t.sample)||a.set(t.sample,{sample:t.sample});const e=a.get(t.sample),n=`key${t.termNum}`;n in e||(e[n]=[]),e[n].push(t)}const c=[],f=new Map;for(const e of a.values())if("key1"in e){if(t.term0_q&&t.term0_id){if(!("key0"in e))continue}else e.key0=[{key:"",value:""}];if(t.term2_q&&(t.term2_id||"samplelst"===t.term2.type)){if(!("key2"in e))continue}else e.key2=[{key:"",value:""}];e.rows=[];for(const t of e.key0)for(const n of e.key1)for(const r of e.key2)e.rows.push({sample:e.sample,key0:t.key,val0:t.value,key1:n.key,val1:n.value,key2:r.key,val2:r.value});for(const t of e.rows)if(n.groupby){if(!f.has(t[n.groupby])){const e=Object.assign({samplecount:0},t);c.push(e),f.set(t[n.groupby],e)}f.get(t[n.groupby]).samplecount++}else c.push(t)}return n.withCTEs?{lst:c,CTE0:i,CTE1:s,CTE2:l,filter:r}:c}catch(t){throw console.log("error in sql:\n",j(u,o)),t}}async function A(t,e,n,s,a=null){const l=a&&a.term||t[`term${n}`],c=l?l.id:t["term"+n+"_id"];if("samplelst"!=(null==l?void 0:l.type))if(a||1!=n){if(!c){const t="samplekey_"+n;return{tablename:t,sql:`${t} AS (\nSELECT null AS sample, '' as key, '' as value\n)`}}}else if(!c)throw"missing term1 id";const u=l&&l.type?l:t.ds.cohort.termdb.q.termjsonByOneid(c);if(!u)throw`no term found by id='${c}'`;let f=a&&a.q||t["term"+n+"_q"]||{};"string"==typeof f&&(f=JSON.parse(decodeURIComponent(f)));const d="samplekey_"+n;let h;if("categorical"==u.type){const n=T(u,f);h=await o[n?"groupset":"values"].getCTE(d,u,t.ds,f,e,n)}else if("integer"==u.type||"float"==u.type){const o="spline"==f.mode?"cubicSpline":f.mode||"discrete";h=await r[o].getCTE(d,u,t.ds,f,e,n,s)}else if("condition"==u.type){const n=f.mode||"discrete";h=await i[n].getCTE(d,u,t.ds,f,e)}else if("survival"==u.type)h=function(t,e,n,r,o){return r.push(e.id),{sql:`${t} AS (\n\t\t\tSELECT sample, exit_code as key, tte AS value\n\t\t\tFROM survival s\n\t\t\tWHERE s.term_id=?\n\t\t\t${o?"AND s.sample IN "+o.CTEname:""}\n\t\t)`,tablename:t}}(d,u,0,e,s);else{if("samplelst"!=u.type)throw"unknown term type";h=await _.getCTE(d,a||{term:u,q:f},e)}return h}function M(t,e,n=""){if(!t.values||!e.computableValuesOnly)return{values:[],clause:""};const r=Object.keys(t.values).filter((e=>t.values[e].uncomputable)),o=n?`${n}.value`:"value";return{values:r,clause:r.length?`AND ${o} NOT IN (${r.map((()=>"?")).join(",")})`:""}}function T(t,e){if(e.groupsetting&&!e.groupsetting.disabled&&e.groupsetting.inuse){if(Number.isInteger(e.groupsetting.predefined_groupset_idx)){if(e.groupsetting.predefined_groupset_idx<0)throw"q.predefined_groupset_idx out of bound";if(!t.groupsetting)throw"term.groupsetting missing when q.predefined_groupset_idx in use";if(!t.groupsetting.lst)throw"term.groupsetting.lst missing when q.predefined_groupset_idx in use";const n=t.groupsetting.lst[e.groupsetting.predefined_groupset_idx];if(!n)throw"q.predefined_groupset_idx out of bound";return n}if(e.groupsetting.customset)return e.groupsetting.customset;throw"do not know how to get groupset"}}function C(t,e,n,r,o){if("continuous"!=t.mode&&"spline"!=t.mode)return s.gp(t,(t=>function(t,e,n,r=[]){const o=[];n&&o.push(...n.values);o.push(e.id);const i=e.values?Object.keys(e.values).filter((t=>e.values[t].uncomputable)):[],s=[],a=[],l=[];let c;for(const t of r)c="pct_"+t,s.push(`\n\t\t${c} AS (\n\t\t SELECT value\n\t\t FROM vals\n\t\t LIMIT 1\n\t\t OFFSET (\n\t\t SELECT cast ( x as int ) - ( x < cast ( x as int ))\n\t\t FROM (\n\t\t SELECT cast(?*pct as int) as x \n\t\t FROM p\n\t\t )\n\t\t )\n\t\t)`),o.push(t),a.push(c),l.push(`${c}.value AS ${"p"+t}`);const u=`WITH\n\t\t${n?n.filters+", ":""} \n\t\tvals AS (\n\t\t\tSELECT value\n\t\t\tFROM anno_${e.type}\n\t\t\tWHERE\n\t\t\t${n?"sample IN "+n.CTEname+" AND ":""}\n\t\t\tterm_id=?\n\t\t\t${i.length?"AND value NOT IN ("+i.join(",")+")":""}\n\t\t\tORDER BY value ASC\n\t\t),\n\t\tp AS (\n\t\t\tSELECT count(value)/100 as pct\n\t\t\tFROM vals\n\t\t)\n\t\t${s.length?",\n"+s.join(","):""}\n\t\tSELECT \n\t\t\tmin(vals.value) as vmin,\n\t\t\tmax(vals.value) as vmax\n\t\t\t${l.length?",\n"+l.join(",\n"):""} \n\t\tFROM vals ${a.length?","+a.join(","):""}`,f=t.cohort.db.connection.prepare(u).all(o),d=f.length?f[0]:{};return d.max=f[0].vmax,d.min=f[0].vmin,d}(n,e,o,t)))}function j(t,e){const n=e.slice();let r;return t.split("").map((t=>{if("?"==t){r=t;const e=n.shift();return"string"==typeof e?`'${e}'`:e}return"\t"==t?"":"\n"!=t&&" "!=t||r!==t?(r=t,t):""})).join("")}},3345:(t,e,n)=>{"use strict";n.d(e,{Dp:()=>V,JC:()=>et,d1:()=>A,sE:()=>B,Ic:()=>E,yE:()=>P,t7:()=>F,ZX:()=>M,EO:()=>J,Kf:()=>U,ZD:()=>D,UE:()=>L,lY:()=>C,_H:()=>O,L0:()=>W,Y5:()=>tt,z5:()=>Y,mr:()=>K,b5:()=>z,cl:()=>H,Jy:()=>R,sI:()=>X,aS:()=>Q,LC:()=>I,Sf:()=>$,tG:()=>Z});var r=n(7147),o=n.n(r),i=n(1017),s=n.n(i),a=n(2081),l=n(4521),c=n.n(l),u=n(2273),f=n(6819);const d=require("node-fetch");var h=n.n(d);const p=require("better-sqlite3");var m=n.n(p),g=n(334),y=n.n(g);n(2781);const v=require("minimatch");var b=n.n(v);const w=y(),{tabix:_,samtools:x,bcftools:k,bigBedToBed:q,bigBedNamedItems:N,bigBedInfo:S}=w;async function A(t,e){if(!t)throw".gz file URL missing";if("string"!=typeof t)throw".gz file URL not string";if(e&&"string"!=typeof e)throw"index URL not string";const[n,r,i]=j(t);if(n)throw".gz file URL error: "+n;const a=s().join(w.cachedir,r,i);try{await o().promises.stat(a)}catch(n){if("ENOENT"!=n.code)throw"stating gz url dir: "+n.code;try{await o().promises.mkdir(a,{recursive:!0})}catch(n){throw"url dir: cannot mkdir"}}if(!e)return a;{const[t,r,i]=j(e);if(t)throw"indexl url error: "+t;const l=s().join(a,s().basename(i));try{return await o().promises.stat(l),a}catch(n){if("ENOENT"==n.code)return await async function(t,e){try{const i=await h()(t);if(200!=i.status)throw"index file not accessible from url with status code "+i.status;await(n=i.body,r=e,new Promise(((t,e)=>{const i=o().createWriteStream(r);n.pipe(i),n.on("end",(()=>t()))})))}catch(t){throw"cannot download from url"}var n,r}(e,l),a;throw"stating indexl url file: "+n.code}}}function M(t,e=!0){let n=null,r=!1;if(t.query.file){if(n=t.query.file,C(n,e,!1))return["illegal file path"];n=s().join(w.tpmasterdir,n)}else if(t.query.url){if(n=t.query.url,n.includes(" "))return["url must not contain whitespace"];if(n.includes('"')||n.includes("'"))return["url must not contain single or double quotes"];r=!0}return n?[null,n,r]:["file unspecified"]}const T=Object.freeze([".bam",".bai",".gz",".tbi",".csi",".bw",".bb"]);function C(t,e=!1,n=!0){if("/"==t[0])return!0;if(t.includes('"')||t.includes("'"))return!0;if(t.includes("|")||t.includes("&"))return!0;if(t.includes(" "))return!0;if(-1!=t.indexOf(".."))return!0;if(t.match(/(\<script|script\>)/i))return!0;if(e&&w.whiteListPaths){let e=!0;for(const n of w.whiteListPaths){if(t.startsWith(n)||"!"!=n[0]&&b()(t,n)){e=!1;break}if("!"==n[0]&&!b()(t,n)){e=!0;break}}if(e)return!0}if(n)for(const e of T)if(e===s().extname(t).toLowerCase())return!0;return!1}function j(t){const e=t.split("://");return 2!=e.length?["improper url"]:e[0].length<3?["protocol string length too short"]:e[1].length<5?["body string length too short"]:[null,e[0],e[1]]}async function E(t){try{await o().promises.stat(t)}catch(e){const n=w.debugmode?`file='${t}'`:"";if("EACCES"==e.code)throw`Permission denied ${n}`;if("ENOENT"==e.code)throw`No such file or directory ${n}`;if("EPERM"==e.code)throw`Operation not permitted ${n}`;throw`cannot access file (' + e.code + ') ${n}`}}async function O(t,e,n){let r;if(t.file)t.file.startsWith(w.tpmasterdir)||(t.file=s().join(w.tpmasterdir,t.file)),r=t.file,await I(t.file);else{if(!t.url)throw"no file or url given for vcf file";r=t.url,t.dir=await utils.cache_index(t.url,t.indexURL)}const[o,i,l,c]=n?await(u=r,d=t.dir,new Promise(((t,e)=>{const n=(0,a.spawn)(k,["view","-h",u],{cwd:d}),r=[];n.stdout.on("data",(t=>r.push(t))),n.on("close",(()=>{t(f.e(r.join("").trim().split("\n")))}))}))):await async function(t,e){return f.e(await D(t,e))}(r,t.dir);var u,d;if(c)throw console.log(c.join("\n")),"got above errors parsing vcf";t.info=o,t.format=i,t.samples=l,await R(r,t.dir,e)&&(t.nochr=!0)}async function I(t){if(!t.endsWith(".gz"))throw"tabix file not ending with .gz";if(await P(t))throw t+" file not exist";if(await F(t))throw".gz file not readable";const e=t+".tbi";if(await P(e)){const e=t+".csi";if(await P(e))throw"neither .tbi .csi index file exist for "+t;if(await F(e))throw".csi index file not readable"}else if(await F(e))throw".tbi index file not readable"}async function R(t,e,n){const r=[];return await L({args:["-l",t],dir:e,callback:t=>{r.push(t)}}),u.contigNameNoChr(n,r)}function P(t){return new Promise(((e,n)=>{o().access(t,o().constants.F_OK,(t=>{t&&e(!0),e(!1)}))}))}function F(t){return new Promise(((e,n)=>{o().access(t,o().constants.R_OK,(t=>{t&&e(!0),e(!1)}))}))}async function D(t,e){const n=[];return await L({args:["-H",t],dir:e,callback:t=>{n.push(t)}}),n}function L({args:t,dir:e,callback:n,isbcf:r,isbam:o}){if(!t)throw"args is missing";if(!Array.isArray(t))throw"args[] is not array";if(0==t.length)throw"args[] empty array";if(!n)throw"callback is missing";if("function"!=typeof n)throw"callback() not a function";return new Promise(((i,s)=>{const l=(0,a.spawn)(r?k:o?x:_,t,{cwd:e}),u=c().createInterface({input:l.stdout}),f=[];u.on("line",(t=>n(t,l))),l.stderr.on("data",(t=>f.push(t))),l.on("close",(()=>{const t=f.join("").trim();t&&!X(t)&&s(t),i()}))}))}function $(t,e){return new Promise(((n,r)=>{o().writeFile(t,e,(t=>{t&&r("cannot write"),n()}))}))}async function Z(t){const e=Math.random().toString();return await $(s().join(w.cachedir,e),t),e}function z(t){return new Promise(((e,n)=>{o().readFile(t,{encoding:"utf8"},((r,o)=>{r&&n("cannot read file: "+t),e(o)}))}))}async function U(t,e){if("NA"==t.genomefile){const t=e.split(/[:-]/),n=[];for(let e=Number(t[1]);e<=Number(t[2]);e++)n.push("N");return`>${e}\n${n.join("")}`}const n=[];return await L({isbam:!0,args:["faidx",t.genomefile,e],callback:t=>n.push(t)}),n.join("\n")}function B(t,e={}){const n="/"==t[0]?t:s().join(w.tpmasterdir,t);try{return new(m())(n,Object.assign({readonly:!0,fileMustExist:!0},e))}catch(t){throw`error connecting to ${n}: ${t}`}}const G=new Set(["Homozygous reference","Homozygous alternative","Heterozygous"]),J={href:"Homozygous reference",halt:"Homozygous alternative",het:"Heterozygous"};async function W(t,e){const n=await z(s().join(w.cachedir_ssid,t)),r=new Map,o=new Map;for(const t of n.trim().split("\n")){if(!t)continue;const[n,i]=t.split("\t");if(!i)continue;if(!G.has(n))throw"unknown hardcoded genotype label: "+n;const s=i.split(",").map((t=>Number(t))),a=e?s.filter((t=>e.has(t))):s;for(const t of a)r.set(t,n);o.set(n,new Set(a))}return[r,o]}function H(t){return t.replace(/\<script|\bon[\w]{1,38}\b[\ \t\n]*\=/gi," _")}async function V(t,e,n){const r=[];if(await L({isbam:!0,args:["view","-H",t],dir:n,callback:t=>r.push(t)}),0==r.length)throw"cannot list bam header lines";const o=[];for(const t of r){if(!t.startsWith("@SQ"))continue;const e=t.split("\t")[1];e||reject("2nd field missing from @SQ line");const n=e.split(":");"SN"!=n[0]&&reject('@SQ line 2nd field is not "SN" but '+n[0]),n[1]||reject("@SQ line no value for SN"),o.push(n[1])}return u.contigNameNoChr(e,o)}function Y(t,e,n,r){return new Promise(((o,i)=>{const s=(0,a.spawn)(q,[`-chrom=${e}`,`-start=${n}`,`-end=${r}`,t,"stdout"]),l=[],c=[];s.stdout.on("data",(t=>l.push(t))),s.stderr.on("data",(t=>c.push(t))),s.on("close",(t=>{0!==t&&i(`bigBed query exited with non-zero status and this standard error:\n${c.join("")}`),c.length>0&&i(c.join(""));const e=l.join("").trim();o(e?e.split("\n"):[])}))}))}function K(t,e){return new Promise(((n,r)=>{const o=(0,a.spawn)(N,[t,e,"stdout"]),i=[],s=[];o.stdout.on("data",(t=>i.push(t))),o.stderr.on("data",(t=>s.push(t))),o.on("close",(t=>{0!==t&&r(`bigBed query exited with non-zero status and this standard error:\n${s.join("")}`),s.length>0&&r(s.join(""));const e=i.join("").trim();n(e?e.split("\n"):[])}))}))}function X(t){return t.startsWith("[E::idx_test_and_fetch]")}async function Q(t){return new Promise(((e,n)=>{const r=(0,a.spawn)(S,[t]),o=[],i=[];r.stdout.on("data",(t=>o.push(t))),r.stderr.on("data",(t=>i.push(t))),r.on("close",(t=>{const n=i.join("");n&&(n.includes("is not a big bed file")||n.includes("Couldn't open"),e(!1));o.join("").trim().startsWith("version")&&e(!0)}))}))}function tt(t,e){if(e.sessionid){if("sessionid"in t)throw"q.sessionid already exists so cannot copy from cookies.sessionid";t.sessionid=e.sessionid}}function et(t){const e=t.length;if(e<5)return{out:t};const n=t[Math.floor(e/2)].value,r=t[Math.floor(e/4)].value,o=t[Math.floor(3*e/4)].value,i=t[Math.floor(.05*e)].value,s=t[Math.floor(.95*e)].value,a=(t[Math.floor(.01*e)].value,o-r);let l,c;if(0==a)l=0,c=0;else{const n=t.findIndex((t=>t.value>r-1.5*a));l=t[-1==n?0:n].value;const i=t.findIndex((t=>t.value>o+1.5*a));c=t[-1==i?e-1:i-1].value}const u=t.filter((t=>t.value<r-1.5*a||t.value>o+1.5*a));return{w1:l,w2:c,p05:i,p25:r,p50:n,p75:o,p95:s,iqr:a,out:u}}},3625:(t,e,n)=>{"use strict";n.d(e,{H:()=>a});var r=n(9380),o=n(4298),i=n(736),s=n(2273);function a(t,e,n,a,l,c,u){var f;const d=(0,r.w)(l);for(const e in t.info){if("A"==t.info[e].Number&&e in d&&(d[e]=d[e].split(",")),t.info[e].separator&&e in d){const n=d[e].split(t.info[e].separator);n.length>1&&(d[e]=n)}if("Float"==t.info[e].Type||"Integer"==t.info[e].Type)if(Array.isArray(d[e])){const t=d[e].map(Number);d[e]=t}else d[e]=Number(d[e])}a.mlst=n.map((t=>{const[n,r,o]=function(t,e,n){for(;e.length>1&&n.length>1&&e[e.length-1]==n[n.length-1];)e=e.substring(0,e.length-1),n=n.substring(0,n.length-1);for(;e.length>1&&n.length>1&&e[0]==n[0];)e=e.substring(1),n=n.substring(1),t++;return[t,e,n]}(a.pos,e,t),s={allele_original:t,ref:r,alt:o,pos:n,type:(0,i.P)(r,o)};return c&&"."!=c&&(s.vcf_id=c),s})),null!==(f=t.info)&&void 0!==f&&f.CSQ&&d.CSQ&&(0,o.A)(d.CSQ,t.info.CSQ.csqheader,a);const h={};u&&(h.usegm={isoform:u});for(const[n,r]of a.mlst.entries()){(0,s.vcfcopymclass)(r,h),delete r.csq,r.mname||(r.mname="."!=c?c:a.pos+":"+e+">"+r.allele_original),r.altAlleleIdx=n+1,r.info={};for(const e in d){var p,m;"A"==(null===(p=t.info)||void 0===p||null===(m=p[e])||void 0===m?void 0:m.Number)?r.info[e]=d[e][n]:r.info[e]=d[e]}}}},126:(t,e,n)=>{var r={"./burden":5037,"./burden.ts":5037,"./gdc.maf":2538,"./gdc.maf.ts":2538,"./gdc.mafBuild":86,"./gdc.mafBuild.ts":86,"./gdc.topMutatedGenes":889,"./gdc.topMutatedGenes.ts":889,"./gdc.topVariablyExpressedGenes":449,"./gdc.topVariablyExpressedGenes.ts":449,"./genelookup":3202,"./genelookup.ts":3202,"./healthcheck":1746,"./healthcheck.ts":1746,"./hicdata":3932,"./hicdata.ts":3932,"./hicstat":6310,"./hicstat.ts":6310,"./termdb.categories":5852,"./termdb.categories.ts":5852,"./termdb.getpercentile":2630,"./termdb.getpercentile.ts":2630,"./termdb.singlecellData":5707,"./termdb.singlecellData.ts":5707,"./termdb.singlecellSamples":7934,"./termdb.singlecellSamples.ts":7934,"./termdb.termbyid":7071,"./termdb.termbyid.ts":7071,"./termdb.violin":1485,"./termdb.violin.ts":1485};function o(t){var e=i(t);return n(e)}function i(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}o.keys=function(){return Object.keys(r)},o.resolve=i,t.exports=o,o.id=126},1271:t=>{"use strict";t.exports=require("@sjcrh/proteinpaint-rust")},6718:t=>{"use strict";t.exports=require("canvas")},6452:t=>{"use strict";t.exports=require("got")},7219:t=>{"use strict";t.exports=require("image-size")},9344:t=>{"use strict";t.exports=require("jsonwebtoken")},8088:t=>{"use strict";t.exports=require("micromatch")},6464:t=>{"use strict";t.exports=require("util")},2081:t=>{"use strict";t.exports=require("child_process")},7147:t=>{"use strict";t.exports=require("fs")},1017:t=>{"use strict";t.exports=require("path")},4521:t=>{"use strict";t.exports=require("readline")},2781:t=>{"use strict";t.exports=require("stream")},9263:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:t<e?-1:t>e?1:t>=e?0:NaN}n.d(e,{Z:()=>r})},5519:(t,e,n)=>{"use strict";n.d(e,{Nw:()=>l,ZP:()=>u,ZR:()=>c,ml:()=>a});var r=n(9263),o=n(3292),i=n(3745);const s=(0,o.Z)(r.Z),a=s.right,l=s.left,c=(0,o.Z)(i.Z).center,u=a},3292:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(9263),o=n(788);function i(t){let e,n,i;function a(t,r,o=0,i=t.length){if(o<i){if(0!==e(r,r))return i;do{const e=o+i>>>1;n(t[e],r)<0?o=e+1:i=e}while(o<i)}return o}return 2!==t.length?(e=r.Z,n=(e,n)=>(0,r.Z)(t(e),n),i=(e,n)=>t(e)-n):(e=t===r.Z||t===o.Z?t:s,n=t,i=t),{left:a,center:function(t,e,n=0,r=t.length){const o=a(t,e,n,r-1);return o>n&&i(t[o-1],e)>-i(t[o],e)?o-1:o},right:function(t,r,o=0,i=t.length){if(o<i){if(0!==e(r,r))return i;do{const e=o+i>>>1;n(t[e],r)<=0?o=e+1:i=e}while(o<i)}return o}}}function s(){return 0}},1045:(t,e,n)=>{"use strict";function r(t,e){if(!((e=+e)>=0))throw new RangeError("invalid r");let n=t.length;if(!((n=Math.floor(n))>=0))throw new RangeError("invalid length");if(!n||!e)return t;const r=c(e),o=t.slice();return r(t,o,0,n,1),r(o,t,0,n,1),r(t,o,0,n,1),t}n.d(e,{TX:()=>i,u8:()=>o,yv:()=>r});const o=s(c),i=s((function(t){const e=c(t);return(t,n,r,o,i)=>{e(t,n,(r<<=2)+0,(o<<=2)+0,i<<=2),e(t,n,r+1,o+1,i),e(t,n,r+2,o+2,i),e(t,n,r+3,o+3,i)}}));function s(t){return function(e,n,r=n){if(!((n=+n)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:o,width:i,height:s}=e;if(!((i=Math.floor(i))>=0))throw new RangeError("invalid width");if(!((s=Math.floor(void 0!==s?s:o.length/i))>=0))throw new RangeError("invalid height");if(!i||!s||!n&&!r)return e;const c=n&&t(n),u=r&&t(r),f=o.slice();return c&&u?(a(c,f,o,i,s),a(c,o,f,i,s),a(c,f,o,i,s),l(u,o,f,i,s),l(u,f,o,i,s),l(u,o,f,i,s)):c?(a(c,o,f,i,s),a(c,f,o,i,s),a(c,o,f,i,s)):u&&(l(u,o,f,i,s),l(u,f,o,i,s),l(u,o,f,i,s)),e}}function a(t,e,n,r,o){for(let i=0,s=r*o;i<s;)t(e,n,i,i+=r,1)}function l(t,e,n,r,o){for(let i=0,s=r*o;i<r;++i)t(e,n,i,i+s,r)}function c(t){const e=Math.floor(t);if(e===t)return function(t){const e=2*t+1;return(n,r,o,i,s)=>{if(!((i-=s)>=o))return;let a=t*r[o];const l=s*t;for(let t=o,e=o+l;t<e;t+=s)a+=r[Math.min(i,t)];for(let t=o,c=i;t<=c;t+=s)a+=r[Math.min(i,t+l)],n[t]=a/e,a-=r[Math.max(o,t-l)]}}(t);const n=t-e,r=2*t+1;return(t,o,i,s,a)=>{if(!((s-=a)>=i))return;let l=e*o[i];const c=a*e,u=c+a;for(let t=i,e=i+c;t<e;t+=a)l+=o[Math.min(s,t)];for(let e=i,f=s;e<=f;e+=a)l+=o[Math.min(s,e+c)],t[e]=(l+n*(o[Math.max(i,e-u)]+o[Math.min(s,e+u)]))/r,l-=o[Math.max(i,e-c)]}}},879:(t,e,n)=>{"use strict";function r(t,e){let n=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&++n;else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(o=+o)>=o&&++n}return n}n.d(e,{Z:()=>r})},788:(t,e,n)=>{"use strict";function r(t,e){return null==t||null==e?NaN:e<t?-1:e>t?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},2038:(t,e,n)=>{"use strict";function r(t,e){let n,r;if(void 0===e)for(const e of t)null!=e&&(void 0===n?e>=e&&(n=r=e):(n>e&&(n=e),r<e&&(r=e)));else{let o=-1;for(let i of t)null!=(i=e(i,++o,t))&&(void 0===n?i>=i&&(n=r=i):(n>i&&(n=i),r<i&&(r=i)))}return[n,r]}n.d(e,{Z:()=>r})},9343:(t,e,n)=>{"use strict";n.d(e,{Kd:()=>i,dU:()=>r,e3:()=>o});class r{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const e=this._partials;let n=0;for(let r=0;r<this._n&&r<32;r++){const o=e[r],i=t+o,s=Math.abs(t)<Math.abs(o)?t-(i-o):o-(i-t);s&&(e[n++]=s),t=i}return e[n]=t,this._n=n+1,this}valueOf(){const t=this._partials;let e,n,r,o=this._n,i=0;if(o>0){for(i=t[--o];o>0&&(e=i,n=t[--o],i=e+n,r=n-(i-e),!r););o>0&&(r<0&&t[o-1]<0||r>0&&t[o-1]>0)&&(n=2*r,e=i+n,n==e-i&&(i=e))}return i}}function o(t,e){const n=new r;if(void 0===e)for(let e of t)(e=+e)&&n.add(e);else{let r=-1;for(let o of t)(o=+e(o,++r,t))&&n.add(o)}return+n}function i(t,e){const n=new r;let o=-1;return Float64Array.from(t,void 0===e?t=>n.add(+t||0):r=>n.add(+e(r,++o,t)||0))}},2942:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(9263);function o(t,e=r.Z){let n,o=!1;if(1===e.length){let i;for(const s of t){const t=e(s);(o?(0,r.Z)(t,i)>0:0===(0,r.Z)(t,t))&&(n=s,i=t,o=!0)}}else for(const r of t)(o?e(r,n)>0:0===e(r,r))&&(n=r,o=!0);return n}},9060:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>y.dU,InternMap:()=>v.L,InternSet:()=>v.H,ascending:()=>o.Z,bin:()=>L,bisect:()=>r.ZP,bisectCenter:()=>r.ZR,bisectLeft:()=>r.Nw,bisectRight:()=>r.ml,bisector:()=>i.Z,blur:()=>s.yv,blur2:()=>s.u8,blurImage:()=>s.TX,count:()=>a.Z,cross:()=>f,cumsum:()=>d,descending:()=>h.Z,deviation:()=>m,difference:()=>_t,disjoint:()=>xt,every:()=>mt,extent:()=>g.Z,fcumsum:()=>y.Kd,filter:()=>yt,flatGroup:()=>k,flatRollup:()=>q,fsum:()=>y.e3,greatest:()=>st.Z,greatestIndex:()=>at,group:()=>w,groupSort:()=>E,groups:()=>_,histogram:()=>L,index:()=>A,indexes:()=>M,intersection:()=>kt,least:()=>ot,leastIndex:()=>it,map:()=>vt,max:()=>U.Z,maxIndex:()=>B.Z,mean:()=>G,median:()=>J,medianIndex:()=>W,merge:()=>H.Z,min:()=>V.Z,minIndex:()=>Y.Z,mode:()=>K,nice:()=>F,pairs:()=>X,permute:()=>tt.Z,quantile:()=>$.ZP,quantileIndex:()=>$.Cr,quantileSorted:()=>$.s7,quickselect:()=>et.Z,range:()=>nt.Z,rank:()=>rt,reduce:()=>bt,reverse:()=>wt,rollup:()=>N,rollups:()=>S,scan:()=>lt,shuffle:()=>ct,shuffler:()=>ut,some:()=>gt,sort:()=>j.ZP,subset:()=>At,sum:()=>ft,superset:()=>Nt,thresholdFreedmanDiaconis:()=>Z,thresholdScott:()=>z,thresholdSturges:()=>D.Z,tickIncrement:()=>P.G9,tickStep:()=>P.ly,ticks:()=>P.ZP,transpose:()=>dt,union:()=>Mt,variance:()=>p,zip:()=>pt});var r=n(5519),o=n(9263),i=n(3292),s=n(1045),a=n(879);function l(t){return 0|t.length}function c(t){return!(t>0)}function u(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function f(...t){const e="function"==typeof t[t.length-1]&&function(t){return e=>t(...e)}(t.pop()),n=(t=t.map(u)).map(l),r=t.length-1,o=new Array(r+1).fill(0),i=[];if(r<0||n.some(c))return i;for(;;){i.push(o.map(((e,n)=>t[n][e])));let s=r;for(;++o[s]===n[s];){if(0===s)return e?i.map(e):i;o[s--]=0}}}function d(t,e){var n=0,r=0;return Float64Array.from(t,void 0===e?t=>n+=+t||0:o=>n+=+e(o,r++,t)||0)}var h=n(788);function p(t,e){let n,r=0,o=0,i=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(n=e-o,o+=n/++r,i+=n*(e-o));else{let s=-1;for(let a of t)null!=(a=e(a,++s,t))&&(a=+a)>=a&&(n=a-o,o+=n/++r,i+=n*(a-o))}if(r>1)return i/(r-1)}function m(t,e){const n=p(t,e);return n?Math.sqrt(n):n}var g=n(2038),y=n(9343),v=n(8828);function b(t){return t}function w(t,...e){return C(t,b,b,e)}function _(t,...e){return C(t,Array.from,b,e)}function x(t,e){for(let n=1,r=e.length;n<r;++n)t=t.flatMap((t=>t.pop().map((([e,n])=>[...t,e,n]))));return t}function k(t,...e){return x(_(t,...e),e)}function q(t,e,...n){return x(S(t,e,...n),n)}function N(t,e,...n){return C(t,b,e,n)}function S(t,e,...n){return C(t,Array.from,e,n)}function A(t,...e){return C(t,b,T,e)}function M(t,...e){return C(t,Array.from,T,e)}function T(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function C(t,e,n,r){return function t(o,i){if(i>=r.length)return n(o);const s=new v.L,a=r[i++];let l=-1;for(const t of o){const e=a(t,++l,o),n=s.get(e);n?n.push(t):s.set(e,[t])}for(const[e,n]of s)s.set(e,t(n,i));return e(s)}(t,0)}var j=n(3897);function E(t,e,n){return(2!==e.length?(0,j.ZP)(N(t,e,n),(([t,e],[n,r])=>(0,o.Z)(e,r)||(0,o.Z)(t,n))):(0,j.ZP)(w(t,n),(([t,n],[r,i])=>e(n,i)||(0,o.Z)(t,r)))).map((([t])=>t))}var O=Array.prototype,I=O.slice;O.map;function R(t){return()=>t}var P=n(6106);function F(t,e,n){let r;for(;;){const o=(0,P.G9)(t,e,n);if(o===r||0===o||!isFinite(o))return[t,e];o>0?(t=Math.floor(t/o)*o,e=Math.ceil(e/o)*o):o<0&&(t=Math.ceil(t*o)/o,e=Math.floor(e*o)/o),r=o}}var D=n(2327);function L(){var t=b,e=g.Z,n=D.Z;function o(o){Array.isArray(o)||(o=Array.from(o));var i,s,a,l=o.length,c=new Array(l);for(i=0;i<l;++i)c[i]=t(o[i],i,o);var u=e(c),f=u[0],d=u[1],h=n(c,f,d);if(!Array.isArray(h)){const t=d,n=+h;if(e===g.Z&&([f,d]=F(f,d,n)),(h=(0,P.ZP)(f,d,n))[0]<=f&&(a=(0,P.G9)(f,d,n)),h[h.length-1]>=d)if(t>=d&&e===g.Z){const t=(0,P.G9)(f,d,n);isFinite(t)&&(t>0?d=(Math.floor(d/t)+1)*t:t<0&&(d=(Math.ceil(d*-t)+1)/-t))}else h.pop()}for(var p=h.length;h[0]<=f;)h.shift(),--p;for(;h[p-1]>d;)h.pop(),--p;var m,y=new Array(p+1);for(i=0;i<=p;++i)(m=y[i]=[]).x0=i>0?h[i-1]:f,m.x1=i<p?h[i]:d;if(isFinite(a)){if(a>0)for(i=0;i<l;++i)null!=(s=c[i])&&f<=s&&s<=d&&y[Math.min(p,Math.floor((s-f)/a))].push(o[i]);else if(a<0)for(i=0;i<l;++i)if(null!=(s=c[i])&&f<=s&&s<=d){const t=Math.floor((f-s)*a);y[Math.min(p,t+(h[t]<=s))].push(o[i])}}else for(i=0;i<l;++i)null!=(s=c[i])&&f<=s&&s<=d&&y[(0,r.ZP)(h,s,0,p)].push(o[i]);return y}return o.value=function(e){return arguments.length?(t="function"==typeof e?e:R(e),o):t},o.domain=function(t){return arguments.length?(e="function"==typeof t?t:R([t[0],t[1]]),o):e},o.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?R(I.call(t)):R(t),o):n},o}var $=n(1177);function Z(t,e,n){return Math.ceil((n-e)/(2*((0,$.ZP)(t,.75)-(0,$.ZP)(t,.25))*Math.pow((0,a.Z)(t),-1/3)))}function z(t,e,n){return Math.ceil((n-e)*Math.cbrt((0,a.Z)(t))/(3.49*m(t)))}var U=n(8319),B=n(5374);function G(t,e){let n=0,r=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(++n,r+=e);else{let o=-1;for(let i of t)null!=(i=e(i,++o,t))&&(i=+i)>=i&&(++n,r+=i)}if(n)return r/n}function J(t,e){return(0,$.ZP)(t,.5,e)}function W(t,e){return(0,$.Cr)(t,.5,e)}var H=n(1740),V=n(816),Y=n(2980);function K(t,e){const n=new v.L;if(void 0===e)for(let e of t)null!=e&&e>=e&&n.set(e,(n.get(e)||0)+1);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&o>=o&&n.set(o,(n.get(o)||0)+1)}let r,o=0;for(const[t,e]of n)e>o&&(o=e,r=t);return r}function X(t,e=Q){const n=[];let r,o=!1;for(const i of t)o&&n.push(e(r,i)),r=i,o=!0;return n}function Q(t,e){return[t,e]}var tt=n(362),et=n(551),nt=n(1265);function rt(t,e=o.Z){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(t);const r=new Float64Array(n.length);2!==e.length&&(n=n.map(e),e=o.Z);const i=(t,r)=>e(n[t],n[r]);let s,a;return Uint32Array.from(n,((t,e)=>e)).sort(e===o.Z?(t,e)=>(0,j.Wv)(n[t],n[e]):(0,j.di)(i)).forEach(((t,e)=>{const n=i(t,void 0===s?t:s);n>=0?((void 0===s||n>0)&&(s=t,a=e),r[t]=a):r[t]=NaN})),r}function ot(t,e=o.Z){let n,r=!1;if(1===e.length){let i;for(const s of t){const t=e(s);(r?(0,o.Z)(t,i)<0:0===(0,o.Z)(t,t))&&(n=s,i=t,r=!0)}}else for(const o of t)(r?e(o,n)<0:0===e(o,o))&&(n=o,r=!0);return n}function it(t,e=o.Z){if(1===e.length)return(0,Y.Z)(t,e);let n,r=-1,i=-1;for(const o of t)++i,(r<0?0===e(o,o):e(o,n)<0)&&(n=o,r=i);return r}var st=n(2942);function at(t,e=o.Z){if(1===e.length)return(0,B.Z)(t,e);let n,r=-1,i=-1;for(const o of t)++i,(r<0?0===e(o,o):e(o,n)>0)&&(n=o,r=i);return r}function lt(t,e){const n=it(t,e);return n<0?void 0:n}const ct=ut(Math.random);function ut(t){return function(e,n=0,r=e.length){let o=r-(n=+n);for(;o;){const r=t()*o--|0,i=e[o+n];e[o+n]=e[r+n],e[r+n]=i}return e}}function ft(t,e){let n=0;if(void 0===e)for(let e of t)(e=+e)&&(n+=e);else{let r=-1;for(let o of t)(o=+e(o,++r,t))&&(n+=o)}return n}function dt(t){if(!(o=t.length))return[];for(var e=-1,n=(0,V.Z)(t,ht),r=new Array(n);++e<n;)for(var o,i=-1,s=r[e]=new Array(o);++i<o;)s[i]=t[i][e];return r}function ht(t){return t.length}function pt(){return dt(arguments)}function mt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(!e(r,++n,t))return!1;return!0}function gt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(e(r,++n,t))return!0;return!1}function yt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");const n=[];let r=-1;for(const o of t)e(o,++r,t)&&n.push(o);return n}function vt(t,e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof e)throw new TypeError("mapper is not a function");return Array.from(t,((n,r)=>e(n,r,t)))}function bt(t,e,n){if("function"!=typeof e)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let o,i,s=-1;if(arguments.length<3){if(({done:o,value:n}=r.next()),o)return;++s}for(;({done:o,value:i}=r.next()),!o;)n=e(n,i,++s,t);return n}function wt(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()}function _t(t,...e){t=new v.H(t);for(const n of e)for(const e of n)t.delete(e);return t}function xt(t,e){const n=e[Symbol.iterator](),r=new v.H;for(const e of t){if(r.has(e))return!1;let t,o;for(;({value:t,done:o}=n.next())&&!o;){if(Object.is(e,t))return!1;r.add(t)}}return!0}function kt(t,...e){t=new v.H(t),e=e.map(qt);t:for(const n of t)for(const r of e)if(!r.has(n)){t.delete(n);continue t}return t}function qt(t){return t instanceof v.H?t:new v.H(t)}function Nt(t,e){const n=t[Symbol.iterator](),r=new Set;for(const t of e){const e=St(t);if(r.has(e))continue;let o,i;for(;({value:o,done:i}=n.next());){if(i)return!1;const t=St(o);if(r.add(t),Object.is(e,t))break}}return!0}function St(t){return null!==t&&"object"==typeof t?t.valueOf():t}function At(t,e){return Nt(e,t)}function Mt(...t){const e=new v.H;for(const n of t)for(const t of n)e.add(t);return e}},8319:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n<e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(n<o||void 0===n&&o>=o)&&(n=o)}return n}n.d(e,{Z:()=>r})},5374:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,o=-1;if(void 0===e)for(const e of t)++o,null!=e&&(n<e||void 0===n&&e>=e)&&(n=e,r=o);else for(let i of t)null!=(i=e(i,++o,t))&&(n<i||void 0===n&&i>=i)&&(n=i,r=o);return r}n.d(e,{Z:()=>r})},1740:(t,e,n)=>{"use strict";function r(t){return Array.from(function*(t){for(const e of t)yield*e}(t))}n.d(e,{Z:()=>r})},816:(t,e,n)=>{"use strict";function r(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n>e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let o of t)null!=(o=e(o,++r,t))&&(n>o||void 0===n&&o>=o)&&(n=o)}return n}n.d(e,{Z:()=>r})},2980:(t,e,n)=>{"use strict";function r(t,e){let n,r=-1,o=-1;if(void 0===e)for(const e of t)++o,null!=e&&(n>e||void 0===n&&e>=e)&&(n=e,r=o);else for(let i of t)null!=(i=e(i,++o,t))&&(n>i||void 0===n&&i>=i)&&(n=i,r=o);return r}n.d(e,{Z:()=>r})},3745:(t,e,n)=>{"use strict";function r(t){return null===t?NaN:+t}function*o(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else{let n=-1;for(let r of t)null!=(r=e(r,++n,t))&&(r=+r)>=r&&(yield r)}}n.d(e,{K:()=>o,Z:()=>r})},362:(t,e,n)=>{"use strict";function r(t,e){return Array.from(e,(e=>t[e]))}n.d(e,{Z:()=>r})},1177:(t,e,n)=>{"use strict";n.d(e,{Cr:()=>h,ZP:()=>f,s7:()=>d});var r=n(8319),o=n(5374),i=n(816),s=n(2980),a=n(551),l=n(3745),c=n(3897),u=n(2942);function f(t,e,n){if(o=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||o<2)return(0,i.Z)(t);if(e>=1)return(0,r.Z)(t);var o,s=(o-1)*e,c=Math.floor(s),u=(0,r.Z)((0,a.Z)(t,c).subarray(0,c+1));return u+((0,i.Z)(t.subarray(c+1))-u)*(s-c)}}function d(t,e,n=l.Z){if(r=t.length){if((e=+e)<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,o=(r-1)*e,i=Math.floor(o),s=+n(t[i],i,t);return s+(+n(t[i+1],i+1,t)-s)*(o-i)}}function h(t,e,n){if(r=(t=Float64Array.from((0,l.K)(t,n))).length){if((e=+e)<=0||r<2)return(0,s.Z)(t);if(e>=1)return(0,o.Z)(t);var r,i=Math.floor((r-1)*e),f=(0,a.Z)(Uint32Array.from(t,((t,e)=>e)),i,0,r-1,((e,n)=>(0,c.Wv)(t[e],t[n])));return(0,u.Z)(f.subarray(0,i+1),(e=>t[e]))}}},551:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(3897);function o(t,e,n=0,s=t.length-1,a){for(a=void 0===a?r.Wv:(0,r.di)(a);s>n;){if(s-n>600){const r=s-n+1,i=e-n+1,l=Math.log(r),c=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*c*(r-c)/r)*(i-r/2<0?-1:1);o(t,e,Math.max(n,Math.floor(e-i*c/r+u)),Math.min(s,Math.floor(e+(r-i)*c/r+u)),a)}const r=t[e];let l=n,c=s;for(i(t,n,e),a(t[s],r)>0&&i(t,n,s);l<c;){for(i(t,l,c),++l,--c;a(t[l],r)<0;)++l;for(;a(t[c],r)>0;)--c}0===a(t[n],r)?i(t,n,c):(++c,i(t,c,s)),c<=e&&(n=c+1),e<=c&&(s=c-1)}return t}function i(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}},1265:(t,e,n)=>{"use strict";function r(t,e,n){t=+t,e=+e,n=(o=arguments.length)<2?(e=t,t=0,1):o<3?1:+n;for(var r=-1,o=0|Math.max(0,Math.ceil((e-t)/n)),i=new Array(o);++r<o;)i[r]=t+r*n;return i}n.d(e,{Z:()=>r})},3897:(t,e,n)=>{"use strict";n.d(e,{Wv:()=>a,ZP:()=>i,di:()=>s});var r=n(9263),o=n(362);function i(t,...e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[n]=e;if(n&&2!==n.length||e.length>1){const r=Uint32Array.from(t,((t,e)=>e));return e.length>1?(e=e.map((e=>t.map(e))),r.sort(((t,n)=>{for(const r of e){const e=a(r[t],r[n]);if(e)return e}}))):(n=t.map(n),r.sort(((t,e)=>a(n[t],n[e])))),(0,o.Z)(t,r)}return t.sort(s(n))}function s(t=r.Z){if(t===r.Z)return a;if("function"!=typeof t)throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||0===r?r:(0===t(n,n))-(0===t(e,e))}}function a(t,e){return(null==t||!(t>=t))-(null==e||!(e>=e))||(t<e?-1:t>e?1:0)}},2327:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(879);function o(t){return Math.ceil(Math.log((0,r.Z)(t))/Math.LN2)+1}},6106:(t,e,n)=>{"use strict";n.d(e,{G9:()=>a,ZP:()=>s,ly:()=>l});var r=Math.sqrt(50),o=Math.sqrt(10),i=Math.sqrt(2);function s(t,e,n){var r,o,i,s,l=-1;if(n=+n,(t=+t)===(e=+e)&&n>0)return[t];if((r=e<t)&&(o=t,t=e,e=o),0===(s=a(t,e,n))||!isFinite(s))return[];if(s>0){let n=Math.round(t/s),r=Math.round(e/s);for(n*s<t&&++n,r*s>e&&--r,i=new Array(o=r-n+1);++l<o;)i[l]=(n+l)*s}else{s=-s;let n=Math.round(t*s),r=Math.round(e*s);for(n/s<t&&++n,r/s>e&&--r,i=new Array(o=r-n+1);++l<o;)i[l]=(n+l)/s}return r&&i.reverse(),i}function a(t,e,n){var s=(e-t)/Math.max(0,n),a=Math.floor(Math.log(s)/Math.LN10),l=s/Math.pow(10,a);return a>=0?(l>=r?10:l>=o?5:l>=i?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=r?10:l>=o?5:l>=i?2:1)}function l(t,e,n){var s=Math.abs(e-t)/Math.max(0,n),a=Math.pow(10,Math.floor(Math.log(s)/Math.LN10)),l=s/a;return l>=r?a*=10:l>=o?a*=5:l>=i&&(a*=2),e<t?-a:a}},1495:(t,e,n)=>{"use strict";n.d(e,{B8:()=>q,Il:()=>o,J5:()=>s,SU:()=>k,Ss:()=>N,Ym:()=>O,ZP:()=>w,xV:()=>i});var r=n(3456);function o(){}var i=.7,s=1/i,a="\\s*([+-]?\\d+)\\s*",l="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",c="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",u=/^#([0-9a-f]{3,8})$/,f=new RegExp(`^rgb\\(${a},${a},${a}\\)$`),d=new RegExp(`^rgb\\(${c},${c},${c}\\)$`),h=new RegExp(`^rgba\\(${a},${a},${a},${l}\\)$`),p=new RegExp(`^rgba\\(${c},${c},${c},${l}\\)$`),m=new RegExp(`^hsl\\(${l},${c},${c}\\)$`),g=new RegExp(`^hsla\\(${l},${c},${c},${l}\\)$`),y={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function v(){return this.rgb().formatHex()}function b(){return this.rgb().formatRgb()}function w(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=u.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?_(e):3===n?new N(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?x(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?x(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=f.exec(t))?new N(e[1],e[2],e[3],1):(e=d.exec(t))?new N(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?x(e[1],e[2],e[3],e[4]):(e=p.exec(t))?x(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=m.exec(t))?j(e[1],e[2]/100,e[3]/100,1):(e=g.exec(t))?j(e[1],e[2]/100,e[3]/100,e[4]):y.hasOwnProperty(t)?_(y[t]):"transparent"===t?new N(NaN,NaN,NaN,0):null}function _(t){return new N(t>>16&255,t>>8&255,255&t,1)}function x(t,e,n,r){return r<=0&&(t=e=n=NaN),new N(t,e,n,r)}function k(t){return t instanceof o||(t=w(t)),t?new N((t=t.rgb()).r,t.g,t.b,t.opacity):new N}function q(t,e,n,r){return 1===arguments.length?k(t):new N(t,e,n,null==r?1:r)}function N(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function S(){return`#${C(this.r)}${C(this.g)}${C(this.b)}`}function A(){const t=M(this.opacity);return`${1===t?"rgb(":"rgba("}${T(this.r)}, ${T(this.g)}, ${T(this.b)}${1===t?")":`, ${t})`}`}function M(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function T(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function C(t){return((t=T(t))<16?"0":"")+t.toString(16)}function j(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new I(t,e,n,r)}function E(t){if(t instanceof I)return new I(t.h,t.s,t.l,t.opacity);if(t instanceof o||(t=w(t)),!t)return new I;if(t instanceof I)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),a=NaN,l=s-i,c=(s+i)/2;return l?(a=e===s?(n-r)/l+6*(n<r):n===s?(r-e)/l+2:(e-n)/l+4,l/=c<.5?s+i:2-s-i,a*=60):l=c>0&&c<1?0:a,new I(a,l,c,t.opacity)}function O(t,e,n,r){return 1===arguments.length?E(t):new I(t,e,n,null==r?1:r)}function I(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function R(t){return(t=(t||0)%360)<0?t+360:t}function P(t){return Math.max(0,Math.min(1,t||0))}function F(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}(0,r.Z)(o,w,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:v,formatHex:v,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return E(this).formatHsl()},formatRgb:b,toString:b}),(0,r.Z)(N,q,(0,r.l)(o,{brighter(t){return t=null==t?s:Math.pow(s,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?i:Math.pow(i,t),new N(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new N(T(this.r),T(this.g),T(this.b),M(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:S,formatHex:S,formatHex8:function(){return`#${C(this.r)}${C(this.g)}${C(this.b)}${C(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:A,toString:A})),(0,r.Z)(I,O,(0,r.l)(o,{brighter(t){return t=null==t?s:Math.pow(s,t),new I(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?i:Math.pow(i,t),new I(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,o=2*n-r;return new N(F(t>=240?t-240:t+120,o,r),F(t,o,r),F(t<120?t+240:t-120,o,r),this.opacity)},clamp(){return new I(R(this.h),P(this.s),P(this.l),M(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=M(this.opacity);return`${1===t?"hsl(":"hsla("}${R(this.h)}, ${100*P(this.s)}%, ${100*P(this.l)}%${1===t?")":`, ${t})`}`}}))},3456:(t,e,n)=>{"use strict";function r(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function o(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}n.d(e,{Z:()=>r,l:()=>o})},4476:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r={},o={},i=34,s=10,a=13;function l(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function c(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r)})),n}function u(t,e){var n=t+"",r=n.length;return r<e?new Array(e-r+1).join(0)+n:n}function f(t){var e,n=t.getUTCHours(),r=t.getUTCMinutes(),o=t.getUTCSeconds(),i=t.getUTCMilliseconds();return isNaN(t)?"Invalid Date":((e=t.getUTCFullYear())<0?"-"+u(-e,6):e>9999?"+"+u(e,6):u(e,4))+"-"+u(t.getUTCMonth()+1,2)+"-"+u(t.getUTCDate(),2)+(i?"T"+u(n,2)+":"+u(r,2)+":"+u(o,2)+"."+u(i,3)+"Z":o?"T"+u(n,2)+":"+u(r,2)+":"+u(o,2)+"Z":r||n?"T"+u(n,2)+":"+u(r,2)+"Z":"")}function d(t){var e=new RegExp('["'+t+"\n\r]"),n=t.charCodeAt(0);function u(t,e){var l,c=[],u=t.length,f=0,d=0,h=u<=0,p=!1;function m(){if(h)return o;if(p)return p=!1,r;var e,l,c=f;if(t.charCodeAt(c)===i){for(;f++<u&&t.charCodeAt(f)!==i||t.charCodeAt(++f)===i;);return(e=f)>=u?h=!0:(l=t.charCodeAt(f++))===s?p=!0:l===a&&(p=!0,t.charCodeAt(f)===s&&++f),t.slice(c+1,e-1).replace(/""/g,'"')}for(;f<u;){if((l=t.charCodeAt(e=f++))===s)p=!0;else if(l===a)p=!0,t.charCodeAt(f)===s&&++f;else if(l!==n)continue;return t.slice(c,e)}return h=!0,t.slice(c,u)}for(t.charCodeAt(u-1)===s&&--u,t.charCodeAt(u-1)===a&&--u;(l=m())!==o;){for(var g=[];l!==r&&l!==o;)g.push(l),l=m();e&&null==(g=e(g,d++))||c.push(g)}return c}function d(e,n){return e.map((function(e){return n.map((function(t){return p(e[t])})).join(t)}))}function h(e){return e.map(p).join(t)}function p(t){return null==t?"":t instanceof Date?f(t):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return{parse:function(t,e){var n,r,o=u(t,(function(t,o){if(n)return n(t,o-1);r=t,n=e?function(t,e){var n=l(t);return function(r,o){return e(n(r),o,t)}}(t,e):l(t)}));return o.columns=r||[],o},parseRows:u,format:function(e,n){return null==n&&(n=c(e)),[n.map(p).join(t)].concat(d(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=c(t)),d(t,e).join("\n")},formatRows:function(t){return t.map(h).join("\n")},formatRow:h,formatValue:p}}},5026:(t,e,n)=>{"use strict";n.d(e,{E0:()=>i,Hf:()=>c,n5:()=>l,sS:()=>u,tJ:()=>o,uH:()=>a,vP:()=>s});var r=(0,n(4476).Z)("\t"),o=r.parse,i=r.parseRows,s=r.format,a=r.formatBody,l=r.formatRows,c=r.formatRow,u=r.formatValue},2163:(t,e,n)=>{"use strict";n.d(e,{WU:()=>o,ZP:()=>a,jH:()=>i});var r,o,i,s=n(2107);function a(t){return r=(0,s.Z)(t),o=r.format,i=r.formatPrefix,r}a({thousands:",",grouping:[3],currency:["$",""]})},2313:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(4218);function o(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},4218:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function o(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{V:()=>o,Z:()=>r})},7259:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,v:()=>i});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function o(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new i({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function i(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}o.prototype=i.prototype,i.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},2107:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(2313);var o=n(7259);var i,s=n(4218);function a(t,e){var n=(0,s.V)(t,e);if(!n)return t+"";var r=n[0],o=n[1];return o<0?"0."+new Array(-o).join("0")+r:r.length>o+1?r.slice(0,o+1)+"."+r.slice(o+1):r+new Array(o-r.length+2).join("0")}const l={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:s.Z,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>a(100*t,e),r:a,s:function(t,e){var n=(0,s.V)(t,e);if(!n)return t+"";var r=n[0],o=n[1],a=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,l=r.length;return a===l?r:a>l?r+new Array(a-l+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+(0,s.V)(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function c(t){return t}var u=Array.prototype.map,f=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function d(t){var e,n,s=void 0===t.grouping||void 0===t.thousands?c:(e=u.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var o=t.length,i=[],s=0,a=e[0],l=0;o>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),i.push(t.substring(o-=a,o+a)),!((l+=a+1)>r));)a=e[s=(s+1)%e.length];return i.reverse().join(n)}),a=void 0===t.currency?"":t.currency[0]+"",d=void 0===t.currency?"":t.currency[1]+"",h=void 0===t.decimal?".":t.decimal+"",p=void 0===t.numerals?c:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}(u.call(t.numerals,String)),m=void 0===t.percent?"%":t.percent+"",g=void 0===t.minus?"−":t.minus+"",y=void 0===t.nan?"NaN":t.nan+"";function v(t){var e=(t=(0,o.Z)(t)).fill,n=t.align,r=t.sign,c=t.symbol,u=t.zero,v=t.width,b=t.comma,w=t.precision,_=t.trim,x=t.type;"n"===x?(b=!0,x="g"):l[x]||(void 0===w&&(w=12),_=!0,x="g"),(u||"0"===e&&"="===n)&&(u=!0,e="0",n="=");var k="$"===c?a:"#"===c&&/[boxX]/.test(x)?"0"+x.toLowerCase():"",q="$"===c?d:/[%p]/.test(x)?m:"",N=l[x],S=/[defgprs%]/.test(x);function A(t){var o,a,l,c=k,d=q;if("c"===x)d=N(t)+d,t="";else{var m=(t=+t)<0||1/t<0;if(t=isNaN(t)?y:N(Math.abs(t),w),_&&(t=function(t){t:for(var e,n=t.length,r=1,o=-1;r<n;++r)switch(t[r]){case".":o=e=r;break;case"0":0===o&&(o=r),e=r;break;default:if(!+t[r])break t;o>0&&(o=0)}return o>0?t.slice(0,o)+t.slice(e+1):t}(t)),m&&0==+t&&"+"!==r&&(m=!1),c=(m?"("===r?r:g:"-"===r||"("===r?"":r)+c,d=("s"===x?f[8+i/3]:"")+d+(m&&"("===r?")":""),S)for(o=-1,a=t.length;++o<a;)if(48>(l=t.charCodeAt(o))||l>57){d=(46===l?h+t.slice(o+1):t.slice(o))+d,t=t.slice(0,o);break}}b&&!u&&(t=s(t,1/0));var A=c.length+t.length+d.length,M=A<v?new Array(v-A+1).join(e):"";switch(b&&u&&(t=s(M+t,M.length?v-d.length:1/0),M=""),n){case"<":t=c+t+d+M;break;case"=":t=c+M+t+d;break;case"^":t=M.slice(0,A=M.length>>1)+c+t+d+M.slice(A);break;default:t=M+c+t+d}return p(t)}return w=void 0===w?6:/[gprs]/.test(x)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w)),A.toString=function(){return t+""},A}return{format:v,formatPrefix:function(t,e){var n=v(((t=(0,o.Z)(t)).type="f",t)),i=3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3))),s=Math.pow(10,-i),a=f[8+i/3];return function(t){return n(s*t)+a}}}}},9680:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},3150:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},3621:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2313);function o(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},9466:(t,e,n)=>{"use strict";function r(t){return null==t?null:o(t)}function o(t){if("function"!=typeof t)throw new Error;return t}n.d(e,{C:()=>o,j:()=>r})},5220:(t,e,n)=>{"use strict";function r(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function o(t,e){t instanceof Map?(t=[void 0,t],void 0===e&&(e=s)):void 0===e&&(e=i);for(var n,r,o,a,u,f=new c(t),d=[f];n=d.pop();)if((o=e(n.data))&&(u=(o=Array.from(o)).length))for(n.children=o,a=u-1;a>=0;--a)d.push(r=o[a]=new c(o[a])),r.parent=n,r.depth=n.depth+1;return f.eachBefore(l)}function i(t){return t.children}function s(t){return Array.isArray(t)?t[1]:null}function a(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function l(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function c(t){this.data=t,this.depth=this.height=0,this.parent=null}n.d(e,{NB:()=>c,le:()=>l,ZP:()=>o}),c.prototype=o.prototype={constructor:c,count:function(){return this.eachAfter(r)},each:function(t,e){let n=-1;for(const r of this)t.call(e,r,++n,this);return this},eachAfter:function(t,e){for(var n,r,o,i=this,s=[i],a=[],l=-1;i=s.pop();)if(a.push(i),n=i.children)for(r=0,o=n.length;r<o;++r)s.push(n[r]);for(;i=a.pop();)t.call(e,i,++l,this);return this},eachBefore:function(t,e){for(var n,r,o=this,i=[o],s=-1;o=i.pop();)if(t.call(e,o,++s,this),n=o.children)for(r=n.length-1;r>=0;--r)i.push(n[r]);return this},find:function(t,e){let n=-1;for(const r of this)if(t.call(e,r,++n,this))return r},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,o=r&&r.length;--o>=0;)n+=r[o].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),o=null;t=n.pop(),e=r.pop();for(;t===e;)o=t,t=n.pop(),e=r.pop();return o}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var o=r.length;t!==n;)r.splice(o,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return o(this).eachBefore(a)},[Symbol.iterator]:function*(){var t,e,n,r,o=this,i=[o];do{for(t=i.reverse(),i=[];o=t.pop();)if(yield o,e=o.children)for(n=0,r=e.length;n<r;++n)i.push(e[n])}while(i.length)}}},4766:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(9466),o=n(5220),i={depth:-1},s={},a={};function l(t){return t.id}function c(t){return t.parentId}function u(){var t,e=l,n=c;function u(r){var l,c,u,h,p,m,g,y,v=Array.from(r),b=e,w=n,_=new Map;if(null!=t){const e=v.map(((e,n)=>function(t){t=`${t}`;let e=t.length;d(t,e-1)&&!d(t,e-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(e,n,r)))),n=e.map(f),o=new Set(e).add("");for(const t of n)o.has(t)||(o.add(t),e.push(t),n.push(f(t)),v.push(a));b=(t,n)=>e[n],w=(t,e)=>n[e]}for(u=0,l=v.length;u<l;++u)c=v[u],m=v[u]=new o.NB(c),null!=(g=b(c,u,r))&&(g+="")&&(y=m.id=g,_.set(y,_.has(y)?s:m)),null!=(g=w(c,u,r))&&(g+="")&&(m.parent=g);for(u=0;u<l;++u)if(g=(m=v[u]).parent){if(!(p=_.get(g)))throw new Error("missing: "+g);if(p===s)throw new Error("ambiguous: "+g);p.children?p.children.push(m):p.children=[m],m.parent=p}else{if(h)throw new Error("multiple roots");h=m}if(!h)throw new Error("no root");if(null!=t){for(;h.data===a&&1===h.children.length;)h=h.children[0],--l;for(let t=v.length-1;t>=0&&(m=v[t]).data===a;--t)m.data=null}if(h.parent=i,h.eachBefore((function(t){t.depth=t.parent.depth+1,--l})).eachBefore(o.le),h.parent=null,l>0)throw new Error("cycle");return h}return u.id=function(t){return arguments.length?(e=(0,r.j)(t),u):e},u.parentId=function(t){return arguments.length?(n=(0,r.j)(t),u):n},u.path=function(e){return arguments.length?(t=(0,r.j)(e),u):t},u}function f(t){let e=t.length;if(e<2)return"";for(;--e>1&&!d(t,e););return t.slice(0,e)}function d(t,e){if("/"===t[e]){let n=0;for(;e>0&&"\\"===t[--e];)++n;if(0==(1&n))return!0}return!1}},4321:(t,e,n)=>{"use strict";n.d(e,{M:()=>s,Z:()=>i});var r=n(2303),o=n(5003);function i(t,e){return((0,o.v)(e)?o.Z:s)(t,e)}function s(t,e){var n,o=e?e.length:0,i=t?Math.min(o,t.length):0,s=new Array(i),a=new Array(o);for(n=0;n<i;++n)s[n]=(0,r.Z)(t[n],e[n]);for(;n<o;++n)a[n]=e[n];return function(t){for(n=0;n<i;++n)a[n]=s[n](t);return a}}},5409:(t,e,n)=>{"use strict";function r(t,e,n,r,o){var i=t*t,s=i*t;return((1-3*t+3*i-s)*e+(4-6*i+3*s)*n+(1+3*t+3*i-3*s)*r+s*o)/6}function o(t){var e=t.length-1;return function(n){var o=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),i=t[o],s=t[o+1],a=o>0?t[o-1]:2*i-s,l=o<e-1?t[o+2]:2*s-i;return r((n-o/e)*e,a,i,s,l)}}n.d(e,{Z:()=>o,t:()=>r})},7855:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(5409);function o(t){var e=t.length;return function(n){var o=Math.floor(((n%=1)<0?++n:n)*e),i=t[(o+e-1)%e],s=t[o%e],a=t[(o+1)%e],l=t[(o+2)%e];return(0,r.t)((n-o/e)*e,i,s,a,l)}}},8190:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,wx:()=>i,yi:()=>s});var r=n(8486);function o(t,e){return function(n){return t+n*e}}function i(t,e){var n=e-t;return n?o(t,n>180||n<-180?n-360*Math.round(n/360):n):(0,r.Z)(isNaN(t)?e:t)}function s(t){return 1==(t=+t)?a:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):(0,r.Z)(isNaN(e)?n:e)}}function a(t,e){var n=e-t;return n?o(t,n):(0,r.Z)(isNaN(t)?e:t)}},8486:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=t=>()=>t},6261:(t,e,n)=>{"use strict";function r(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}n.d(e,{Z:()=>r})},8403:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}n.d(e,{Z:()=>r})},5003:(t,e,n)=>{"use strict";function r(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,o=e.slice();return function(i){for(n=0;n<r;++n)o[n]=t[n]*(1-i)+e[n]*i;return o}}function o(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}n.d(e,{Z:()=>r,v:()=>o})},8765:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2303);function o(t,e){var n,o={},i={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?o[n]=(0,r.Z)(t[n],e[n]):i[n]=e[n];return function(t){for(n in o)i[n]=o[n](t);return i}}},9444:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(2303);function o(t,e){void 0===e&&(e=t,t=r.Z);for(var n=0,o=e.length-1,i=e[0],s=new Array(o<0?0:o);n<o;)s[n]=t(i,i=e[++n]);return function(t){var e=Math.max(0,Math.min(o-1,Math.floor(t*=o)));return s[e](t-e)}}},490:(t,e,n)=>{"use strict";n.d(e,{YD:()=>u,ZP:()=>a,hD:()=>c});var r=n(1495),o=n(5409),i=n(7855),s=n(8190);const a=function t(e){var n=(0,s.yi)(e);function o(t,e){var o=n((t=(0,r.B8)(t)).r,(e=(0,r.B8)(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),l=(0,s.ZP)(t.opacity,e.opacity);return function(e){return t.r=o(e),t.g=i(e),t.b=a(e),t.opacity=l(e),t+""}}return o.gamma=t,o}(1);function l(t){return function(e){var n,o,i=e.length,s=new Array(i),a=new Array(i),l=new Array(i);for(n=0;n<i;++n)o=(0,r.B8)(e[n]),s[n]=o.r||0,a[n]=o.g||0,l[n]=o.b||0;return s=t(s),a=t(a),l=t(l),o.opacity=1,function(t){return o.r=s(t),o.g=a(t),o.b=l(t),o+""}}}var c=l(o.Z),u=l(i.Z)},5250:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}n.d(e,{Z:()=>r})},9009:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(8403),o=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,i=new RegExp(o.source,"g");function s(t,e){var n,s,a,l=o.lastIndex=i.lastIndex=0,c=-1,u=[],f=[];for(t+="",e+="";(n=o.exec(t))&&(s=i.exec(e));)(a=s.index)>l&&(a=e.slice(l,a),u[c]?u[c]+=a:u[++c]=a),(n=n[0])===(s=s[0])?u[c]?u[c]+=s:u[++c]=s:(u[++c]=null,f.push({i:c,x:(0,r.Z)(n,s)})),l=i.lastIndex;return l<e.length&&(a=e.slice(l),u[c]?u[c]+=a:u[++c]=a),u.length<2?f[0]?function(t){return function(e){return t(e)+""}}(f[0].x):function(t){return function(){return t}}(e):(e=f.length,function(t){for(var n,r=0;r<e;++r)u[(n=f[r]).i]=n.x(t);return u.join("")})}},2303:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1495),o=n(490),i=n(4321),s=n(6261),a=n(8403),l=n(8765),c=n(9009),u=n(8486),f=n(5003);function d(t,e){var n,d=typeof e;return null==e||"boolean"===d?(0,u.Z)(e):("number"===d?a.Z:"string"===d?(n=(0,r.ZP)(e))?(e=n,o.ZP):c.Z:e instanceof r.ZP?o.ZP:e instanceof Date?s.Z:(0,f.v)(e)?f.Z:Array.isArray(e)?i.M:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?l.Z:a.Z)(t,e)}},7763:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(4090).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf")},4090:(t,e,n)=>{"use strict";function r(t){for(var e=t.length/6|0,n=new Array(e),r=0;r<e;)n[r]="#"+t.slice(6*r,6*++r);return n}n.d(e,{Z:()=>r})},1303:(t,e,n)=>{"use strict";n.d(e,{JG:()=>h,ZP:()=>m,yR:()=>c,l4:()=>p});var r=n(5519),o=n(2303),i=n(8403),s=n(5250);var a=n(9120),l=[0,1];function c(t){return t}function u(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:(n=isNaN(e)?NaN:.5,function(){return n});var n}function f(t,e,n){var r=t[0],o=t[1],i=e[0],s=e[1];return o<r?(r=u(o,r),i=n(s,i)):(r=u(r,o),i=n(i,s)),function(t){return i(r(t))}}function d(t,e,n){var o=Math.min(t.length,e.length)-1,i=new Array(o),s=new Array(o),a=-1;for(t[o]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++a<o;)i[a]=u(t[a],t[a+1]),s[a]=n(e[a],e[a+1]);return function(e){var n=(0,r.ZP)(t,e,1,o)-1;return s[n](i[n](e))}}function h(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function p(){var t,e,n,r,u,h,p=l,m=l,g=o.Z,y=c;function v(){var t,e,n,o=Math.min(p.length,m.length);return y!==c&&(t=p[0],e=p[o-1],t>e&&(n=t,t=e,e=n),y=function(n){return Math.max(t,Math.min(e,n))}),r=o>2?d:f,u=h=null,b}function b(e){return null==e||isNaN(e=+e)?n:(u||(u=r(p.map(t),m,g)))(t(y(e)))}return b.invert=function(n){return y(e((h||(h=r(m,p.map(t),i.Z)))(n)))},b.domain=function(t){return arguments.length?(p=Array.from(t,a.Z),v()):p.slice()},b.range=function(t){return arguments.length?(m=Array.from(t),v()):m.slice()},b.rangeRound=function(t){return m=Array.from(t),g=s.Z,v()},b.clamp=function(t){return arguments.length?(y=!!t||c,v()):y!==c},b.interpolate=function(t){return arguments.length?(g=t,v()):g},b.unknown=function(t){return arguments.length?(n=t,b):n},function(n,r){return t=n,e=r,v()}}function m(){return p()(c,c)}},4635:(t,e,n)=>{"use strict";n.r(e),n.d(e,{scaleBand:()=>s,scaleDiverging:()=>_t,scaleDivergingLog:()=>xt,scaleDivergingPow:()=>qt,scaleDivergingSqrt:()=>Nt,scaleDivergingSymlog:()=>kt,scaleIdentity:()=>f,scaleImplicit:()=>i.O,scaleLinear:()=>c.Z,scaleLog:()=>q,scaleOrdinal:()=>i.Z,scalePoint:()=>l,scalePow:()=>O,scaleQuantile:()=>$,scaleQuantize:()=>Z,scaleRadial:()=>P,scaleSequential:()=>ht,scaleSequentialLog:()=>pt,scaleSequentialPow:()=>gt,scaleSequentialQuantile:()=>vt,scaleSequentialSqrt:()=>yt,scaleSequentialSymlog:()=>mt,scaleSqrt:()=>I,scaleSymlog:()=>M,scaleThreshold:()=>z,scaleTime:()=>et,scaleUtc:()=>lt,tickFormat:()=>St.Z});var r=n(1265),o=n(2998),i=n(5540);function s(){var t,e,n=(0,i.Z)().unknown(void 0),a=n.domain,l=n.range,c=0,u=1,f=!1,d=0,h=0,p=.5;function m(){var n=a().length,o=u<c,i=o?u:c,s=o?c:u;t=(s-i)/Math.max(1,n-d+2*h),f&&(t=Math.floor(t)),i+=(s-i-t*(n-d))*p,e=t*(1-d),f&&(i=Math.round(i),e=Math.round(e));var m=(0,r.Z)(n).map((function(e){return i+t*e}));return l(o?m.reverse():m)}return delete n.unknown,n.domain=function(t){return arguments.length?(a(t),m()):a()},n.range=function(t){return arguments.length?([c,u]=t,c=+c,u=+u,m()):[c,u]},n.rangeRound=function(t){return[c,u]=t,c=+c,u=+u,f=!0,m()},n.bandwidth=function(){return e},n.step=function(){return t},n.round=function(t){return arguments.length?(f=!!t,m()):f},n.padding=function(t){return arguments.length?(d=Math.min(1,h=+t),m()):d},n.paddingInner=function(t){return arguments.length?(d=Math.min(1,t),m()):d},n.paddingOuter=function(t){return arguments.length?(h=+t,m()):h},n.align=function(t){return arguments.length?(p=Math.max(0,Math.min(1,t)),m()):p},n.copy=function(){return s(a(),[c,u]).round(f).paddingInner(d).paddingOuter(h).align(p)},o.o.apply(m(),arguments)}function a(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return a(e())},t}function l(){return a(s.apply(null,arguments).paddingInner(1))}var c=n(9064),u=n(9120);function f(t){var e;function n(t){return null==t||isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Array.from(e,u.Z),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return f(t).unknown(e)},t=arguments.length?Array.from(t,u.Z):[0,1],(0,c.Q)(n)}var d=n(6106),h=n(7259),p=n(2163);function m(t,e){var n,r=0,o=(t=t.slice()).length-1,i=t[r],s=t[o];return s<i&&(n=r,r=o,o=n,n=i,i=s,s=n),t[r]=e.floor(i),t[o]=e.ceil(s),t}var g=n(1303);function y(t){return Math.log(t)}function v(t){return Math.exp(t)}function b(t){return-Math.log(-t)}function w(t){return-Math.exp(-t)}function _(t){return isFinite(t)?+("1e"+t):t<0?0:t}function x(t){return(e,n)=>-t(-e,n)}function k(t){const e=t(y,v),n=e.domain;let r,o,i=10;function s(){return r=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}(i),o=function(t){return 10===t?_:t===Math.E?Math.exp:e=>Math.pow(t,e)}(i),n()[0]<0?(r=x(r),o=x(o),t(b,w)):t(y,v),e}return e.base=function(t){return arguments.length?(i=+t,s()):i},e.domain=function(t){return arguments.length?(n(t),s()):n()},e.ticks=t=>{const e=n();let s=e[0],a=e[e.length-1];const l=a<s;l&&([s,a]=[a,s]);let c,u,f=r(s),h=r(a);const p=null==t?10:+t;let m=[];if(!(i%1)&&h-f<p){if(f=Math.floor(f),h=Math.ceil(h),s>0){for(;f<=h;++f)for(c=1;c<i;++c)if(u=f<0?c/o(-f):c*o(f),!(u<s)){if(u>a)break;m.push(u)}}else for(;f<=h;++f)for(c=i-1;c>=1;--c)if(u=f>0?c/o(-f):c*o(f),!(u<s)){if(u>a)break;m.push(u)}2*m.length<p&&(m=(0,d.ZP)(s,a,p))}else m=(0,d.ZP)(f,h,Math.min(h-f,p)).map(o);return l?m.reverse():m},e.tickFormat=(t,n)=>{if(null==t&&(t=10),null==n&&(n=10===i?"s":","),"function"!=typeof n&&(i%1||null!=(n=(0,h.Z)(n)).precision||(n.trim=!0),n=(0,p.WU)(n)),t===1/0)return n;const s=Math.max(1,i*t/e.ticks().length);return t=>{let e=t/o(Math.round(r(t)));return e*i<i-.5&&(e*=i),e<=s?n(t):""}},e.nice=()=>n(m(n(),{floor:t=>o(Math.floor(r(t))),ceil:t=>o(Math.ceil(r(t)))})),e}function q(){const t=k((0,g.l4)()).domain([1,10]);return t.copy=()=>(0,g.JG)(t,q()).base(t.base()),o.o.apply(t,arguments),t}function N(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function S(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function A(t){var e=1,n=t(N(e),S(e));return n.constant=function(n){return arguments.length?t(N(e=+n),S(e)):e},(0,c.Q)(n)}function M(){var t=A((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,M()).constant(t.constant())},o.o.apply(t,arguments)}function T(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function C(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function j(t){return t<0?-t*t:t*t}function E(t){var e=t(g.yR,g.yR),n=1;return e.exponent=function(e){return arguments.length?1===(n=+e)?t(g.yR,g.yR):.5===n?t(C,j):t(T(n),T(1/n)):n},(0,c.Q)(e)}function O(){var t=E((0,g.l4)());return t.copy=function(){return(0,g.JG)(t,O()).exponent(t.exponent())},o.o.apply(t,arguments),t}function I(){return O.apply(null,arguments).exponent(.5)}function R(t){return Math.sign(t)*t*t}function P(){var t,e=(0,g.ZP)(),n=[0,1],r=!1;function i(n){var o=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(n));return isNaN(o)?t:r?Math.round(o):o}return i.invert=function(t){return e.invert(R(t))},i.domain=function(t){return arguments.length?(e.domain(t),i):e.domain()},i.range=function(t){return arguments.length?(e.range((n=Array.from(t,u.Z)).map(R)),i):n.slice()},i.rangeRound=function(t){return i.range(t).round(!0)},i.round=function(t){return arguments.length?(r=!!t,i):r},i.clamp=function(t){return arguments.length?(e.clamp(t),i):e.clamp()},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return P(e.domain(),n).round(r).clamp(e.clamp()).unknown(t)},o.o.apply(i,arguments),(0,c.Q)(i)}var F=n(1177),D=n(5519),L=n(9263);function $(){var t,e=[],n=[],r=[];function i(){var t=0,o=Math.max(1,n.length);for(r=new Array(o-1);++t<o;)r[t-1]=(0,F.s7)(e,t/o);return s}function s(e){return null==e||isNaN(e=+e)?t:n[(0,D.ZP)(r,e)]}return s.invertExtent=function(t){var o=n.indexOf(t);return o<0?[NaN,NaN]:[o>0?r[o-1]:e[0],o<r.length?r[o]:e[e.length-1]]},s.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(L.Z),i()},s.range=function(t){return arguments.length?(n=Array.from(t),i()):n.slice()},s.unknown=function(e){return arguments.length?(t=e,s):t},s.quantiles=function(){return r.slice()},s.copy=function(){return $().domain(e).range(n).unknown(t)},o.o.apply(s,arguments)}function Z(){var t,e=0,n=1,r=1,i=[.5],s=[0,1];function a(e){return null!=e&&e<=e?s[(0,D.ZP)(i,e,0,r)]:t}function l(){var t=-1;for(i=new Array(r);++t<r;)i[t]=((t+1)*n-(t-r)*e)/(r+1);return a}return a.domain=function(t){return arguments.length?([e,n]=t,e=+e,n=+n,l()):[e,n]},a.range=function(t){return arguments.length?(r=(s=Array.from(t)).length-1,l()):s.slice()},a.invertExtent=function(t){var o=s.indexOf(t);return o<0?[NaN,NaN]:o<1?[e,i[0]]:o>=r?[i[r-1],n]:[i[o-1],i[o]]},a.unknown=function(e){return arguments.length?(t=e,a):a},a.thresholds=function(){return i.slice()},a.copy=function(){return Z().domain([e,n]).range(s).unknown(t)},o.o.apply((0,c.Q)(a),arguments)}function z(){var t,e=[.5],n=[0,1],r=1;function i(o){return null!=o&&o<=o?n[(0,D.ZP)(e,o,0,r)]:t}return i.domain=function(t){return arguments.length?(e=Array.from(t),r=Math.min(e.length,n.length-1),i):e.slice()},i.range=function(t){return arguments.length?(n=Array.from(t),r=Math.min(e.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return z().domain(e).range(n).unknown(t)},o.o.apply(i,arguments)}var U=n(7150),B=n(2311),G=n(7905),J=n(6018),W=n(8467),H=n(6596),V=n(2991),Y=n(1343),K=n(1852);function X(t){return new Date(t)}function Q(t){return t instanceof Date?+t:+new Date(+t)}function tt(t,e,n,r,o,i,s,a,l,c){var u=(0,g.ZP)(),f=u.invert,d=u.domain,h=c(".%L"),p=c(":%S"),y=c("%I:%M"),v=c("%I %p"),b=c("%a %d"),w=c("%b %d"),_=c("%B"),x=c("%Y");function k(t){return(l(t)<t?h:a(t)<t?p:s(t)<t?y:i(t)<t?v:r(t)<t?o(t)<t?b:w:n(t)<t?_:x)(t)}return u.invert=function(t){return new Date(f(t))},u.domain=function(t){return arguments.length?d(Array.from(t,Q)):d().map(X)},u.ticks=function(e){var n=d();return t(n[0],n[n.length-1],null==e?10:e)},u.tickFormat=function(t,e){return null==e?k:c(e)},u.nice=function(t){var n=d();return t&&"function"==typeof t.range||(t=e(n[0],n[n.length-1],null==t?10:t)),t?d(m(n,t)):u},u.copy=function(){return(0,g.JG)(u,tt(t,e,n,r,o,i,s,a,l,c))},u}function et(){return o.o.apply(tt(U.jK,U._g,B.Z,G.Z,J.OM,W.Z,H.Z,V.Z,Y.Z,K.i$).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}var nt=n(4552),rt=n(7351),ot=n(1887),it=n(7445),st=n(8927),at=n(8593);function lt(){return o.o.apply(tt(U.WG,U.jo,nt.Z,rt.Z,ot.Ox,it.Z,st.Z,at.Z,Y.Z,K.g0).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}var ct=n(2303),ut=n(5250);function ft(){var t,e,n,r,o,i=0,s=1,a=g.yR,l=!1;function c(e){return null==e||isNaN(e=+e)?o:a(0===n?.5:(e=(r(e)-t)*n,l?Math.max(0,Math.min(1,e)):e))}function u(t){return function(e){var n,r;return arguments.length?([n,r]=e,a=t(n,r),c):[a(0),a(1)]}}return c.domain=function(o){return arguments.length?([i,s]=o,t=r(i=+i),e=r(s=+s),n=t===e?0:1/(e-t),c):[i,s]},c.clamp=function(t){return arguments.length?(l=!!t,c):l},c.interpolator=function(t){return arguments.length?(a=t,c):a},c.range=u(ct.Z),c.rangeRound=u(ut.Z),c.unknown=function(t){return arguments.length?(o=t,c):o},function(o){return r=o,t=o(i),e=o(s),n=t===e?0:1/(e-t),c}}function dt(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function ht(){var t=(0,c.Q)(ft()(g.yR));return t.copy=function(){return dt(t,ht())},o.O.apply(t,arguments)}function pt(){var t=k(ft()).domain([1,10]);return t.copy=function(){return dt(t,pt()).base(t.base())},o.O.apply(t,arguments)}function mt(){var t=A(ft());return t.copy=function(){return dt(t,mt()).constant(t.constant())},o.O.apply(t,arguments)}function gt(){var t=E(ft());return t.copy=function(){return dt(t,gt()).exponent(t.exponent())},o.O.apply(t,arguments)}function yt(){return gt.apply(null,arguments).exponent(.5)}function vt(){var t=[],e=g.yR;function n(n){if(null!=n&&!isNaN(n=+n))return e(((0,D.ZP)(t,n,1)-1)/(t.length-1))}return n.domain=function(e){if(!arguments.length)return t.slice();t=[];for(let n of e)null==n||isNaN(n=+n)||t.push(n);return t.sort(L.Z),n},n.interpolator=function(t){return arguments.length?(e=t,n):e},n.range=function(){return t.map(((n,r)=>e(r/(t.length-1))))},n.quantiles=function(e){return Array.from({length:e+1},((n,r)=>(0,F.ZP)(t,r/e)))},n.copy=function(){return vt(e).domain(t)},o.O.apply(n,arguments)}var bt=n(9444);function wt(){var t,e,n,r,o,i,s,a=0,l=.5,c=1,u=1,f=g.yR,d=!1;function h(t){return isNaN(t=+t)?s:(t=.5+((t=+i(t))-e)*(u*t<u*e?r:o),f(d?Math.max(0,Math.min(1,t)):t))}function p(t){return function(e){var n,r,o;return arguments.length?([n,r,o]=e,f=(0,bt.Z)(t,[n,r,o]),h):[f(0),f(.5),f(1)]}}return h.domain=function(s){return arguments.length?([a,l,c]=s,t=i(a=+a),e=i(l=+l),n=i(c=+c),r=t===e?0:.5/(e-t),o=e===n?0:.5/(n-e),u=e<t?-1:1,h):[a,l,c]},h.clamp=function(t){return arguments.length?(d=!!t,h):d},h.interpolator=function(t){return arguments.length?(f=t,h):f},h.range=p(ct.Z),h.rangeRound=p(ut.Z),h.unknown=function(t){return arguments.length?(s=t,h):s},function(s){return i=s,t=s(a),e=s(l),n=s(c),r=t===e?0:.5/(e-t),o=e===n?0:.5/(n-e),u=e<t?-1:1,h}}function _t(){var t=(0,c.Q)(wt()(g.yR));return t.copy=function(){return dt(t,_t())},o.O.apply(t,arguments)}function xt(){var t=k(wt()).domain([.1,1,10]);return t.copy=function(){return dt(t,xt()).base(t.base())},o.O.apply(t,arguments)}function kt(){var t=A(wt());return t.copy=function(){return dt(t,kt()).constant(t.constant())},o.O.apply(t,arguments)}function qt(){var t=E(wt());return t.copy=function(){return dt(t,qt()).exponent(t.exponent())},o.O.apply(t,arguments)}function Nt(){return qt.apply(null,arguments).exponent(.5)}var St=n(8902)},2998:(t,e,n)=>{"use strict";function r(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}function o(t,e){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof e?this.interpolator(e):this.range(e)}return this}n.d(e,{O:()=>o,o:()=>r})},9064:(t,e,n)=>{"use strict";n.d(e,{Q:()=>a,Z:()=>l});var r=n(6106),o=n(1303),i=n(2998),s=n(8902);function a(t){var e=t.domain;return t.ticks=function(t){var n=e();return(0,r.ZP)(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return(0,s.Z)(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var o,i,s=e(),a=0,l=s.length-1,c=s[a],u=s[l],f=10;for(u<c&&(i=c,c=u,u=i,i=a,a=l,l=i);f-- >0;){if((i=(0,r.G9)(c,u,n))===o)return s[a]=c,s[l]=u,e(s);if(i>0)c=Math.floor(c/i)*i,u=Math.ceil(u/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,u=Math.floor(u*i)/i}o=i}return t},t}function l(){var t=(0,o.ZP)();return t.copy=function(){return(0,o.JG)(t,l())},i.o.apply(t,arguments),a(t)}},9120:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{Z:()=>r})},5540:(t,e,n)=>{"use strict";n.d(e,{O:()=>i,Z:()=>s});var r=n(8828),o=n(2998);const i=Symbol("implicit");function s(){var t=new r.L,e=[],n=[],a=i;function l(r){let o=t.get(r);if(void 0===o){if(a!==i)return a;t.set(r,o=e.push(r)-1)}return n[o%n.length]}return l.domain=function(n){if(!arguments.length)return e.slice();e=[],t=new r.L;for(const r of n)t.has(r)||t.set(r,e.push(r)-1);return l},l.range=function(t){return arguments.length?(n=Array.from(t),l):n.slice()},l.unknown=function(t){return arguments.length?(a=t,l):a},l.copy=function(){return s(e,n).unknown(a)},o.o.apply(l,arguments),l}},8902:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=n(6106),o=n(7259),i=n(3150),s=n(2163),a=n(3621),l=n(9680);function c(t,e,n,c){var u,f=(0,r.ly)(t,e,n);switch((c=(0,o.Z)(null==c?",f":c)).type){case"s":var d=Math.max(Math.abs(t),Math.abs(e));return null!=c.precision||isNaN(u=(0,i.Z)(f,d))||(c.precision=u),(0,s.jH)(c,d);case"":case"e":case"g":case"p":case"r":null!=c.precision||isNaN(u=(0,a.Z)(f,Math.max(Math.abs(t),Math.abs(e))))||(c.precision=u-("e"===c.type));break;case"f":case"%":null!=c.precision||isNaN(u=(0,l.Z)(f))||(c.precision=u-2*("%"===c.type))}return(0,s.WU)(c)}},1852:(t,e,n)=>{"use strict";n.d(e,{Z1:()=>i,ZP:()=>c,g0:()=>s,i$:()=>o,wp:()=>a});var r,o,i,s,a,l=n(3015);function c(t){return r=(0,l.Z)(t),o=r.format,i=r.parse,s=r.utcFormat,a=r.utcParse,r}c({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})},3015:(t,e,n)=>{"use strict";n.d(e,{Z:()=>d});var r=n(1887),o=n(7445),i=n(6018),s=n(8467),a=n(2311),l=n(4552);function c(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function u(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function f(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function d(t){var e=t.dateTime,n=t.date,a=t.time,l=t.periods,d=t.days,p=t.shortDays,m=t.months,g=t.shortMonths,y=b(l),v=w(l),X=b(d),vt=w(d),Ct=b(p),jt=w(p),Et=b(m),Ot=w(m),It=b(g),Rt=w(g),Pt={a:function(t){return p[t.getDay()]},A:function(t){return d[t.getDay()]},b:function(t){return g[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:null,d:Z,e:Z,f:J,g:rt,G:it,H:z,I:U,j:B,L:G,m:W,M:H,p:function(t){return l[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:Mt,s:Tt,S:V,u:Y,U:K,V:Q,w:tt,W:et,x:null,X:null,y:nt,Y:ot,Z:st,"%":At},Ft={a:function(t){return p[t.getUTCDay()]},A:function(t){return d[t.getUTCDay()]},b:function(t){return g[t.getUTCMonth()]},B:function(t){return m[t.getUTCMonth()]},c:null,d:at,e:at,f:dt,g:kt,G:Nt,H:lt,I:ct,j:ut,L:ft,m:ht,M:pt,p:function(t){return l[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:Mt,s:Tt,S:mt,u:gt,U:yt,V:bt,w:wt,W:_t,x:null,X:null,y:xt,Y:qt,Z:St,"%":At},Dt={a:function(t,e,n){var r=Ct.exec(e.slice(n));return r?(t.w=jt.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=X.exec(e.slice(n));return r?(t.w=vt.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=It.exec(e.slice(n));return r?(t.m=Rt.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=Et.exec(e.slice(n));return r?(t.m=Ot.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return Zt(t,e,n,r)},d:j,e:j,f:F,g:A,G:S,H:O,I:O,j:E,L:P,m:C,M:I,p:function(t,e,n){var r=y.exec(e.slice(n));return r?(t.p=v.get(r[0].toLowerCase()),n+r[0].length):-1},q:T,Q:L,s:$,S:R,u:x,U:k,V:q,w:_,W:N,x:function(t,e,r){return Zt(t,n,e,r)},X:function(t,e,n){return Zt(t,a,e,n)},y:A,Y:S,Z:M,"%":D};function Lt(t,e){return function(n){var r,o,i,s=[],a=-1,l=0,c=t.length;for(n instanceof Date||(n=new Date(+n));++a<c;)37===t.charCodeAt(a)&&(s.push(t.slice(l,a)),null!=(o=h[r=t.charAt(++a)])?r=t.charAt(++a):o="e"===r?" ":"0",(i=e[r])&&(r=i(n,o)),s.push(r),l=a+1);return s.push(t.slice(l,a)),s.join("")}}function $t(t,e){return function(n){var a,l,d=f(1900,void 0,1);if(Zt(d,t,n+="",0)!=n.length)return null;if("Q"in d)return new Date(d.Q);if("s"in d)return new Date(1e3*d.s+("L"in d?d.L:0));if(e&&!("Z"in d)&&(d.Z=0),"p"in d&&(d.H=d.H%12+12*d.p),void 0===d.m&&(d.m="q"in d?d.q:0),"V"in d){if(d.V<1||d.V>53)return null;"w"in d||(d.w=1),"Z"in d?(l=(a=u(f(d.y,0,1))).getUTCDay(),a=l>4||0===l?r.l6.ceil(a):(0,r.l6)(a),a=o.Z.offset(a,7*(d.V-1)),d.y=a.getUTCFullYear(),d.m=a.getUTCMonth(),d.d=a.getUTCDate()+(d.w+6)%7):(l=(a=c(f(d.y,0,1))).getDay(),a=l>4||0===l?i.wA.ceil(a):(0,i.wA)(a),a=s.Z.offset(a,7*(d.V-1)),d.y=a.getFullYear(),d.m=a.getMonth(),d.d=a.getDate()+(d.w+6)%7)}else("W"in d||"U"in d)&&("w"in d||(d.w="u"in d?d.u%7:"W"in d?1:0),l="Z"in d?u(f(d.y,0,1)).getUTCDay():c(f(d.y,0,1)).getDay(),d.m=0,d.d="W"in d?(d.w+6)%7+7*d.W-(l+5)%7:d.w+7*d.U-(l+6)%7);return"Z"in d?(d.H+=d.Z/100|0,d.M+=d.Z%100,u(d)):c(d)}}function Zt(t,e,n,r){for(var o,i,s=0,a=e.length,l=n.length;s<a;){if(r>=l)return-1;if(37===(o=e.charCodeAt(s++))){if(o=e.charAt(s++),!(i=Dt[o in h?e.charAt(s++):o])||(r=i(t,n,r))<0)return-1}else if(o!=n.charCodeAt(r++))return-1}return r}return Pt.x=Lt(n,Pt),Pt.X=Lt(a,Pt),Pt.c=Lt(e,Pt),Ft.x=Lt(n,Ft),Ft.X=Lt(a,Ft),Ft.c=Lt(e,Ft),{format:function(t){var e=Lt(t+="",Pt);return e.toString=function(){return t},e},parse:function(t){var e=$t(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=Lt(t+="",Ft);return e.toString=function(){return t},e},utcParse:function(t){var e=$t(t+="",!0);return e.toString=function(){return t},e}}}var h={"-":"",_:" ",0:"0"},p=/^\s*\d+/,m=/^%/,g=/[\\^$*+?|[\]().{}]/g;function y(t,e,n){var r=t<0?"-":"",o=(r?-t:t)+"",i=o.length;return r+(i<n?new Array(n-i+1).join(e)+o:o)}function v(t){return t.replace(g,"\\$&")}function b(t){return new RegExp("^(?:"+t.map(v).join("|")+")","i")}function w(t){return new Map(t.map(((t,e)=>[t.toLowerCase(),e])))}function _(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function x(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function k(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function q(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function N(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function S(t,e,n){var r=p.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function A(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function M(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function T(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function C(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function j(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function E(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function O(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function I(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function R(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function P(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function F(t,e,n){var r=p.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function D(t,e,n){var r=m.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function L(t,e,n){var r=p.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function $(t,e,n){var r=p.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Z(t,e){return y(t.getDate(),e,2)}function z(t,e){return y(t.getHours(),e,2)}function U(t,e){return y(t.getHours()%12||12,e,2)}function B(t,e){return y(1+s.Z.count((0,a.Z)(t),t),e,3)}function G(t,e){return y(t.getMilliseconds(),e,3)}function J(t,e){return G(t,e)+"000"}function W(t,e){return y(t.getMonth()+1,e,2)}function H(t,e){return y(t.getMinutes(),e,2)}function V(t,e){return y(t.getSeconds(),e,2)}function Y(t){var e=t.getDay();return 0===e?7:e}function K(t,e){return y(i.OM.count((0,a.Z)(t)-1,t),e,2)}function X(t){var e=t.getDay();return e>=4||0===e?(0,i.bL)(t):i.bL.ceil(t)}function Q(t,e){return t=X(t),y(i.bL.count((0,a.Z)(t),t)+(4===(0,a.Z)(t).getDay()),e,2)}function tt(t){return t.getDay()}function et(t,e){return y(i.wA.count((0,a.Z)(t)-1,t),e,2)}function nt(t,e){return y(t.getFullYear()%100,e,2)}function rt(t,e){return y((t=X(t)).getFullYear()%100,e,2)}function ot(t,e){return y(t.getFullYear()%1e4,e,4)}function it(t,e){var n=t.getDay();return y((t=n>=4||0===n?(0,i.bL)(t):i.bL.ceil(t)).getFullYear()%1e4,e,4)}function st(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+y(e/60|0,"0",2)+y(e%60,"0",2)}function at(t,e){return y(t.getUTCDate(),e,2)}function lt(t,e){return y(t.getUTCHours(),e,2)}function ct(t,e){return y(t.getUTCHours()%12||12,e,2)}function ut(t,e){return y(1+o.Z.count((0,l.Z)(t),t),e,3)}function ft(t,e){return y(t.getUTCMilliseconds(),e,3)}function dt(t,e){return ft(t,e)+"000"}function ht(t,e){return y(t.getUTCMonth()+1,e,2)}function pt(t,e){return y(t.getUTCMinutes(),e,2)}function mt(t,e){return y(t.getUTCSeconds(),e,2)}function gt(t){var e=t.getUTCDay();return 0===e?7:e}function yt(t,e){return y(r.Ox.count((0,l.Z)(t)-1,t),e,2)}function vt(t){var e=t.getUTCDay();return e>=4||0===e?(0,r.hB)(t):r.hB.ceil(t)}function bt(t,e){return t=vt(t),y(r.hB.count((0,l.Z)(t),t)+(4===(0,l.Z)(t).getUTCDay()),e,2)}function wt(t){return t.getUTCDay()}function _t(t,e){return y(r.l6.count((0,l.Z)(t)-1,t),e,2)}function xt(t,e){return y(t.getUTCFullYear()%100,e,2)}function kt(t,e){return y((t=vt(t)).getUTCFullYear()%100,e,2)}function qt(t,e){return y(t.getUTCFullYear()%1e4,e,4)}function Nt(t,e){var n=t.getUTCDay();return y((t=n>=4||0===n?(0,r.hB)(t):r.hB.ceil(t)).getUTCFullYear()%1e4,e,4)}function St(){return"+0000"}function At(){return"%"}function Mt(t){return+t}function Tt(t){return Math.floor(+t/1e3)}},8467:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,a:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*o.yB)/o.UD),(t=>t.getDate()-1));const s=i;var a=i.range},9123:(t,e,n)=>{"use strict";n.d(e,{UD:()=>s,Y2:()=>i,Ym:()=>r,iM:()=>a,jz:()=>l,qz:()=>c,yB:()=>o});const r=1e3,o=60*r,i=60*o,s=24*i,a=7*s,l=30*s,c=365*s},6596:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,i:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*o.Ym-t.getMinutes()*o.yB)}),(function(t,e){t.setTime(+t+e*o.Y2)}),(function(t,e){return(e-t)/o.Y2}),(function(t){return t.getHours()}));const s=i;var a=i.range},3606:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=new Date,o=new Date;function i(t,e,n,s){function a(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return a.floor=function(e){return t(e=new Date(+e)),e},a.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},a.round=function(t){var e=a(t),n=a.ceil(t);return t-e<n-t?e:n},a.offset=function(t,n){return e(t=new Date(+t),null==n?1:Math.floor(n)),t},a.range=function(n,r,o){var i,s=[];if(n=a.ceil(n),o=null==o?1:Math.floor(o),!(n<r&&o>0))return s;do{s.push(i=new Date(+n)),e(n,o),t(n)}while(i<n&&n<r);return s},a.filter=function(n){return i((function(e){if(e>=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(a.count=function(e,i){return r.setTime(+e),o.setTime(+i),t(r),t(o),Math.floor(n(r,o))},a.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?a.filter(s?function(e){return s(e)%t==0}:function(e){return a.count(0,e)%t==0}):a:null}),a}},8383:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,m:()=>s});var r=n(3606),o=(0,r.Z)((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));o.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?(0,r.Z)((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):o:null};const i=o;var s=o.range},2991:(t,e,n)=>{"use strict";n.d(e,{L:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*o.Ym)}),(function(t,e){t.setTime(+t+e*o.yB)}),(function(t,e){return(e-t)/o.yB}),(function(t){return t.getMinutes()}));const s=i;var a=i.range},7905:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,e:()=>i});var r=(0,n(3606).Z)((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const o=r;var i=r.range},1343:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,m:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*o.Ym)}),(function(t,e){return(e-t)/o.Ym}),(function(t){return t.getUTCSeconds()}));const s=i;var a=i.range},7150:(t,e,n)=>{"use strict";n.d(e,{WG:()=>_,_g:()=>q,jK:()=>k,jo:()=>x});var r=n(3292),o=n(6106),i=n(9123),s=n(8383),a=n(1343),l=n(2991),c=n(6596),u=n(8467),f=n(6018),d=n(7905),h=n(2311),p=n(8593),m=n(8927),g=n(7445),y=n(1887),v=n(7351),b=n(4552);function w(t,e,n,l,c,u){const f=[[a.Z,1,i.Ym],[a.Z,5,5*i.Ym],[a.Z,15,15*i.Ym],[a.Z,30,30*i.Ym],[u,1,i.yB],[u,5,5*i.yB],[u,15,15*i.yB],[u,30,30*i.yB],[c,1,i.Y2],[c,3,3*i.Y2],[c,6,6*i.Y2],[c,12,12*i.Y2],[l,1,i.UD],[l,2,2*i.UD],[n,1,i.iM],[e,1,i.jz],[e,3,3*i.jz],[t,1,i.qz]];function d(e,n,a){const l=Math.abs(n-e)/a,c=(0,r.Z)((([,,t])=>t)).right(f,l);if(c===f.length)return t.every((0,o.ly)(e/i.qz,n/i.qz,a));if(0===c)return s.Z.every(Math.max((0,o.ly)(e,n,a),1));const[u,d]=f[l/f[c-1][2]<f[c][2]/l?c-1:c];return u.every(d)}return[function(t,e,n){const r=e<t;r&&([t,e]=[e,t]);const o=n&&"function"==typeof n.range?n:d(t,e,n),i=o?o.range(t,+e+1):[];return r?i.reverse():i},d]}const[_,x]=w(b.Z,v.Z,y.Ox,g.Z,m.Z,p.Z),[k,q]=w(h.Z,d.Z,f.OM,u.Z,c.Z,l.Z)},7445:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s,y:()=>a});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/o.UD}),(function(t){return t.getUTCDate()-1}));const s=i;var a=i.range},8927:(t,e,n)=>{"use strict";n.d(e,{X:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*o.Y2)}),(function(t,e){return(e-t)/o.Y2}),(function(t){return t.getUTCHours()}));const s=i;var a=i.range},8593:(t,e,n)=>{"use strict";n.d(e,{N:()=>a,Z:()=>s});var r=n(3606),o=n(9123),i=(0,r.Z)((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*o.yB)}),(function(t,e){return(e-t)/o.yB}),(function(t){return t.getUTCMinutes()}));const s=i;var a=i.range},7351:(t,e,n)=>{"use strict";n.d(e,{K:()=>i,Z:()=>o});var r=(0,n(3606).Z)((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const o=r;var i=r.range},1887:(t,e,n)=>{"use strict";n.d(e,{$3:()=>p,DK:()=>m,J1:()=>l,Ox:()=>s,QQ:()=>f,Q_:()=>b,SU:()=>h,b3:()=>c,fz:()=>v,g4:()=>d,hB:()=>u,l6:()=>a,uy:()=>g,xj:()=>y});var r=n(3606),o=n(9123);function i(t){return(0,r.Z)((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/o.iM}))}var s=i(0),a=i(1),l=i(2),c=i(3),u=i(4),f=i(5),d=i(6),h=s.range,p=a.range,m=l.range,g=c.range,y=u.range,v=f.range,b=d.range},4552:(t,e,n)=>{"use strict";n.d(e,{D:()=>s,Z:()=>i});var r=n(3606),o=(0,r.Z)((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));o.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const i=o;var s=o.range},6018:(t,e,n)=>{"use strict";n.d(e,{$t:()=>y,EY:()=>d,Ff:()=>b,Ld:()=>g,OM:()=>s,aU:()=>m,b$:()=>v,bJ:()=>p,bL:()=>u,mC:()=>f,sy:()=>l,vm:()=>h,wA:()=>a,zg:()=>c});var r=n(3606),o=n(9123);function i(t){return(0,r.Z)((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*o.yB)/o.iM}))}var s=i(0),a=i(1),l=i(2),c=i(3),u=i(4),f=i(5),d=i(6),h=s.range,p=a.range,m=l.range,g=c.range,y=u.range,v=f.range,b=d.range},2311:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,g:()=>s});var r=n(3606),o=(0,r.Z)((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));o.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const i=o;var s=o.range},3016:(t,e,n)=>{"use strict";n.r(e),n.d(e,{Adder:()=>r.Adder,Delaunay:()=>ti,FormatSpecifier:()=>ta.v,InternMap:()=>r.InternMap,InternSet:()=>r.InternSet,Node:()=>ld.NB,Voronoi:()=>Ho,ZoomTransform:()=>Rv,active:()=>gn,arc:()=>eg,area:()=>cg,areaRadial:()=>vg,ascending:()=>r.ascending,autoType:()=>vi,axisBottom:()=>v,axisLeft:()=>b,axisRight:()=>y,axisTop:()=>g,bin:()=>r.bin,bisect:()=>r.bisect,bisectCenter:()=>r.bisectCenter,bisectLeft:()=>r.bisectLeft,bisectRight:()=>r.bisectRight,bisector:()=>r.bisector,blob:()=>as,blur:()=>r.blur,blur2:()=>r.blur2,blurImage:()=>r.blurImage,brush:()=>Gn,brushSelection:()=>zn,brushX:()=>Un,brushY:()=>Bn,buffer:()=>cs,chord:()=>nr,chordDirected:()=>or,chordTranspose:()=>rr,cluster:()=>ad,color:()=>$e.ZP,contourDensity:()=>xo,contours:()=>go,count:()=>r.count,create:()=>Cm,creator:()=>Nt,cross:()=>r.cross,csv:()=>ps,csvFormat:()=>di,csvFormatBody:()=>hi,csvFormatRow:()=>mi,csvFormatRows:()=>pi,csvFormatValue:()=>gi,csvParse:()=>ui,csvParseRows:()=>fi,cubehelix:()=>no,cumsum:()=>r.cumsum,curveBasis:()=>ly,curveBasisClosed:()=>uy,curveBasisOpen:()=>dy,curveBumpX:()=>xg,curveBumpY:()=>kg,curveBundle:()=>py,curveCardinal:()=>yy,curveCardinalClosed:()=>by,curveCardinalOpen:()=>_y,curveCatmullRom:()=>qy,curveCatmullRomClosed:()=>Sy,curveCatmullRomOpen:()=>My,curveLinear:()=>ig,curveLinearClosed:()=>Cy,curveMonotoneX:()=>Dy,curveMonotoneY:()=>Ly,curveNatural:()=>zy,curveStep:()=>By,curveStepAfter:()=>Jy,curveStepBefore:()=>Gy,descending:()=>r.descending,deviation:()=>r.deviation,difference:()=>r.difference,disjoint:()=>r.disjoint,dispatch:()=>N,drag:()=>ai,dragDisable:()=>Bt,dragEnable:()=>Gt,dsv:()=>hs,dsvFormat:()=>li.Z,easeBack:()=>es,easeBackIn:()=>Qi,easeBackInOut:()=>es,easeBackOut:()=>ts,easeBounce:()=>Yi,easeBounceIn:()=>Vi,easeBounceInOut:()=>Ki,easeBounceOut:()=>Yi,easeCircle:()=>Di,easeCircleIn:()=>Pi,easeCircleInOut:()=>Di,easeCircleOut:()=>Fi,easeCubic:()=>dn,easeCubicIn:()=>un,easeCubicInOut:()=>dn,easeCubicOut:()=>fn,easeElastic:()=>os,easeElasticIn:()=>rs,easeElasticInOut:()=>is,easeElasticOut:()=>os,easeExp:()=>Ri,easeExpIn:()=>Oi,easeExpInOut:()=>Ri,easeExpOut:()=>Ii,easeLinear:()=>wi,easePoly:()=>Si,easePolyIn:()=>qi,easePolyInOut:()=>Si,easePolyOut:()=>Ni,easeQuad:()=>ki,easeQuadIn:()=>_i,easeQuadInOut:()=>ki,easeQuadOut:()=>xi,easeSin:()=>ji,easeSinIn:()=>Ti,easeSinInOut:()=>ji,easeSinOut:()=>Ci,every:()=>r.every,extent:()=>r.extent,fcumsum:()=>r.fcumsum,filter:()=>r.filter,flatGroup:()=>r.flatGroup,flatRollup:()=>r.flatRollup,forceCenter:()=>ks,forceCollide:()=>Ps,forceLink:()=>Ls,forceManyBody:()=>Hs,forceRadial:()=>Vs,forceSimulation:()=>Ws,forceX:()=>Ys,forceY:()=>Ks,format:()=>Xs.WU,formatDefaultLocale:()=>Xs.ZP,formatLocale:()=>Qs.Z,formatPrefix:()=>Xs.jH,formatSpecifier:()=>ta.Z,fsum:()=>r.fsum,geoAlbers:()=>xf,geoAlbersUsa:()=>kf,geoArea:()=>il,geoAzimuthalEqualArea:()=>Af,geoAzimuthalEqualAreaRaw:()=>Sf,geoAzimuthalEquidistant:()=>Tf,geoAzimuthalEquidistantRaw:()=>Mf,geoBounds:()=>$l,geoCentroid:()=>Xl,geoCircle:()=>cc,geoClipAntimeridian:()=>_c,geoClipCircle:()=>xc,geoClipExtent:()=>Cc,geoClipRectangle:()=>Tc,geoConicConformal:()=>Rf,geoConicConformalRaw:()=>If,geoConicEqualArea:()=>_f,geoConicEqualAreaRaw:()=>wf,geoConicEquidistant:()=>Lf,geoConicEquidistantRaw:()=>Df,geoContains:()=>Wc,geoDistance:()=>Dc,geoEqualEarth:()=>Jf,geoEqualEarthRaw:()=>Gf,geoEquirectangular:()=>Ff,geoEquirectangularRaw:()=>Pf,geoGnomonic:()=>Hf,geoGnomonicRaw:()=>Wf,geoGraticule:()=>Kc,geoGraticule10:()=>Xc,geoIdentity:()=>Vf,geoInterpolate:()=>Qc,geoLength:()=>Rc,geoMercator:()=>jf,geoMercatorRaw:()=>Cf,geoNaturalEarth1:()=>Kf,geoNaturalEarth1Raw:()=>Yf,geoOrthographic:()=>Qf,geoOrthographicRaw:()=>Xf,geoPath:()=>nf,geoProjection:()=>yf,geoProjectionMutator:()=>vf,geoRotation:()=>sc,geoStereographic:()=>ed,geoStereographicRaw:()=>td,geoStream:()=>Ra,geoTransform:()=>rf,geoTransverseMercator:()=>rd,geoTransverseMercatorRaw:()=>nd,gray:()=>Pr,greatest:()=>r.greatest,greatestIndex:()=>r.greatestIndex,group:()=>r.group,groupSort:()=>r.groupSort,groups:()=>r.groups,hcl:()=>Gr,hierarchy:()=>ld.ZP,histogram:()=>r.histogram,hsl:()=>$e.Ym,html:()=>_s,image:()=>gs,index:()=>r.index,indexes:()=>r.indexes,interpolate:()=>Jt.Z,interpolateArray:()=>eh.Z,interpolateBasis:()=>nh.Z,interpolateBasisClosed:()=>rh.Z,interpolateBlues:()=>rm,interpolateBrBG:()=>mp,interpolateBuGn:()=>Op,interpolateBuPu:()=>Rp,interpolateCividis:()=>pm,interpolateCool:()=>ym,interpolateCubehelix:()=>_h,interpolateCubehelixDefault:()=>mm,interpolateCubehelixLong:()=>xh,interpolateDate:()=>oh.Z,interpolateDiscrete:()=>ih,interpolateGnBu:()=>Fp,interpolateGreens:()=>im,interpolateGreys:()=>am,interpolateHcl:()=>vh,interpolateHclLong:()=>bh,interpolateHsl:()=>ph,interpolateHslLong:()=>mh,interpolateHue:()=>ah,interpolateInferno:()=>Mm,interpolateLab:()=>gh,interpolateMagma:()=>Am,interpolateNumber:()=>Ce.Z,interpolateNumberArray:()=>lh.Z,interpolateObject:()=>ch.Z,interpolateOrRd:()=>Lp,interpolateOranges:()=>hm,interpolatePRGn:()=>yp,interpolatePiYG:()=>bp,interpolatePlasma:()=>Tm,interpolatePuBu:()=>Up,interpolatePuBuGn:()=>Zp,interpolatePuOr:()=>_p,interpolatePuRd:()=>Gp,interpolatePurples:()=>cm,interpolateRainbow:()=>bm,interpolateRdBu:()=>kp,interpolateRdGy:()=>Np,interpolateRdPu:()=>Wp,interpolateRdYlBu:()=>Ap,interpolateRdYlGn:()=>Tp,interpolateReds:()=>fm,interpolateRgb:()=>Ze.ZP,interpolateRgbBasis:()=>Ze.hD,interpolateRgbBasisClosed:()=>Ze.YD,interpolateRound:()=>uh.Z,interpolateSinebow:()=>km,interpolateSpectral:()=>jp,interpolateString:()=>ze.Z,interpolateTransformCss:()=>Re,interpolateTransformSvg:()=>Pe,interpolateTurbo:()=>qm,interpolateViridis:()=>Sm,interpolateWarm:()=>gm,interpolateYlGn:()=>Kp,interpolateYlGnBu:()=>Vp,interpolateYlOrBr:()=>Qp,interpolateYlOrRd:()=>em,interpolateZoom:()=>dh,interrupt:()=>Me,intersection:()=>r.intersection,interval:()=>Ev,isoFormat:()=>Tv,isoParse:()=>jv,json:()=>vs,lab:()=>Fr,lch:()=>Br,least:()=>r.least,leastIndex:()=>r.leastIndex,line:()=>lg,lineRadial:()=>yg,link:()=>Ag,linkHorizontal:()=>Mg,linkRadial:()=>Cg,linkVertical:()=>Tg,local:()=>Em,map:()=>r.map,matcher:()=>j,max:()=>r.max,maxIndex:()=>r.maxIndex,mean:()=>r.mean,median:()=>r.median,medianIndex:()=>r.medianIndex,merge:()=>r.merge,min:()=>r.min,minIndex:()=>r.minIndex,mode:()=>r.mode,namespace:()=>J,namespaces:()=>G,nice:()=>r.nice,now:()=>se,pack:()=>Ed,packEnclose:()=>gd,packSiblings:()=>Cd,pairs:()=>r.pairs,partition:()=>Dd,path:()=>dr,permute:()=>r.permute,pie:()=>dg,piecewise:()=>kh.Z,pointRadial:()=>bg,pointer:()=>Ht,pointers:()=>Im,polygonArea:()=>Nh,polygonCentroid:()=>Sh,polygonContains:()=>jh,polygonHull:()=>Ch,polygonLength:()=>Eh,precisionFixed:()=>ea.Z,precisionPrefix:()=>na.Z,precisionRound:()=>ra.Z,quadtree:()=>Ms,quantile:()=>r.quantile,quantileIndex:()=>r.quantileIndex,quantileSorted:()=>r.quantileSorted,quantize:()=>qh,quickselect:()=>r.quickselect,radialArea:()=>vg,radialLine:()=>yg,randomBates:()=>Lh,randomBernoulli:()=>zh,randomBeta:()=>Gh,randomBinomial:()=>Jh,randomCauchy:()=>Hh,randomExponential:()=>$h,randomGamma:()=>Bh,randomGeometric:()=>Uh,randomInt:()=>Rh,randomIrwinHall:()=>Dh,randomLcg:()=>tp,randomLogNormal:()=>Fh,randomLogistic:()=>Vh,randomNormal:()=>Ph,randomPareto:()=>Zh,randomPoisson:()=>Yh,randomUniform:()=>Ih,randomWeibull:()=>Wh,range:()=>r.range,rank:()=>r.rank,reduce:()=>r.reduce,reverse:()=>r.reverse,rgb:()=>$e.B8,ribbon:()=>kr,ribbonArrow:()=>qr,rollup:()=>r.rollup,rollups:()=>r.rollups,scaleBand:()=>ep.scaleBand,scaleDiverging:()=>ep.scaleDiverging,scaleDivergingLog:()=>ep.scaleDivergingLog,scaleDivergingPow:()=>ep.scaleDivergingPow,scaleDivergingSqrt:()=>ep.scaleDivergingSqrt,scaleDivergingSymlog:()=>ep.scaleDivergingSymlog,scaleIdentity:()=>ep.scaleIdentity,scaleImplicit:()=>ep.scaleImplicit,scaleLinear:()=>ep.scaleLinear,scaleLog:()=>ep.scaleLog,scaleOrdinal:()=>ep.scaleOrdinal,scalePoint:()=>ep.scalePoint,scalePow:()=>ep.scalePow,scaleQuantile:()=>ep.scaleQuantile,scaleQuantize:()=>ep.scaleQuantize,scaleRadial:()=>ep.scaleRadial,scaleSequential:()=>ep.scaleSequential,scaleSequentialLog:()=>ep.scaleSequentialLog,scaleSequentialPow:()=>ep.scaleSequentialPow,scaleSequentialQuantile:()=>ep.scaleSequentialQuantile,scaleSequentialSqrt:()=>ep.scaleSequentialSqrt,scaleSequentialSymlog:()=>ep.scaleSequentialSymlog,scaleSqrt:()=>ep.scaleSqrt,scaleSymlog:()=>ep.scaleSymlog,scaleThreshold:()=>ep.scaleThreshold,scaleTime:()=>ep.scaleTime,scaleUtc:()=>ep.scaleUtc,scan:()=>r.scan,schemeAccent:()=>op,schemeBlues:()=>nm,schemeBrBG:()=>pp,schemeBuGn:()=>Ep,schemeBuPu:()=>Ip,schemeCategory10:()=>np.Z,schemeDark2:()=>ip,schemeGnBu:()=>Pp,schemeGreens:()=>om,schemeGreys:()=>sm,schemeOrRd:()=>Dp,schemeOranges:()=>dm,schemePRGn:()=>gp,schemePaired:()=>sp,schemePastel1:()=>ap,schemePastel2:()=>lp,schemePiYG:()=>vp,schemePuBu:()=>zp,schemePuBuGn:()=>$p,schemePuOr:()=>wp,schemePuRd:()=>Bp,schemePurples:()=>lm,schemeRdBu:()=>xp,schemeRdGy:()=>qp,schemeRdPu:()=>Jp,schemeRdYlBu:()=>Sp,schemeRdYlGn:()=>Mp,schemeReds:()=>um,schemeSet1:()=>cp,schemeSet2:()=>up,schemeSet3:()=>fp,schemeSpectral:()=>Cp,schemeTableau10:()=>dp,schemeYlGn:()=>Yp,schemeYlGnBu:()=>Hp,schemeYlOrBr:()=>Xp,schemeYlOrRd:()=>tm,select:()=>Lt,selectAll:()=>Rm,selection:()=>Dt,selector:()=>A,selectorAll:()=>C,shuffle:()=>r.shuffle,shuffler:()=>r.shuffler,some:()=>r.some,sort:()=>r.sort,stack:()=>Ky,stackOffsetDiverging:()=>Qy,stackOffsetExpand:()=>Xy,stackOffsetNone:()=>Wy,stackOffsetSilhouette:()=>tv,stackOffsetWiggle:()=>ev,stackOrderAppearance:()=>nv,stackOrderAscending:()=>ov,stackOrderDescending:()=>sv,stackOrderInsideOut:()=>av,stackOrderNone:()=>Hy,stackOrderReverse:()=>lv,stratify:()=>Ld.Z,style:()=>rt,subset:()=>r.subset,sum:()=>r.sum,superset:()=>r.superset,svg:()=>xs,symbol:()=>oy,symbolAsterisk:()=>Eg,symbolCircle:()=>Og,symbolCross:()=>Ig,symbolDiamond:()=>Fg,symbolDiamond2:()=>Dg,symbolPlus:()=>Lg,symbolSquare:()=>$g,symbolSquare2:()=>Zg,symbolStar:()=>Gg,symbolTriangle:()=>Wg,symbolTriangle2:()=>Vg,symbolWye:()=>ty,symbolX:()=>ey,symbols:()=>ny,symbolsFill:()=>ny,symbolsStroke:()=>ry,text:()=>fs,thresholdFreedmanDiaconis:()=>r.thresholdFreedmanDiaconis,thresholdScott:()=>r.thresholdScott,thresholdSturges:()=>r.thresholdSturges,tickFormat:()=>ep.tickFormat,tickIncrement:()=>r.tickIncrement,tickStep:()=>r.tickStep,ticks:()=>r.ticks,timeDay:()=>pv.Z,timeDays:()=>pv.a,timeFormat:()=>Nv.i$,timeFormatDefaultLocale:()=>Nv.ZP,timeFormatLocale:()=>Sv.Z,timeFriday:()=>mv.mC,timeFridays:()=>mv.b$,timeHour:()=>hv.Z,timeHours:()=>hv.i,timeInterval:()=>cv.Z,timeMillisecond:()=>uv.Z,timeMilliseconds:()=>uv.m,timeMinute:()=>dv.Z,timeMinutes:()=>dv.L,timeMonday:()=>mv.wA,timeMondays:()=>mv.bJ,timeMonth:()=>gv.Z,timeMonths:()=>gv.e,timeParse:()=>Nv.Z1,timeSaturday:()=>mv.EY,timeSaturdays:()=>mv.Ff,timeSecond:()=>fv.Z,timeSeconds:()=>fv.m,timeSunday:()=>mv.OM,timeSundays:()=>mv.vm,timeThursday:()=>mv.bL,timeThursdays:()=>mv.$t,timeTickInterval:()=>qv._g,timeTicks:()=>qv.jK,timeTuesday:()=>mv.sy,timeTuesdays:()=>mv.aU,timeWednesday:()=>mv.zg,timeWednesdays:()=>mv.Ld,timeWeek:()=>mv.OM,timeWeeks:()=>mv.vm,timeYear:()=>yv.Z,timeYears:()=>yv.g,timeout:()=>pe,timer:()=>ce,timerFlush:()=>ue,transition:()=>an,transpose:()=>r.transpose,tree:()=>Jd,treemap:()=>Kd,treemapBinary:()=>Xd,treemapDice:()=>Fd,treemapResquarify:()=>th,treemapSlice:()=>Wd,treemapSliceDice:()=>Qd,treemapSquarify:()=>Yd,tsv:()=>ms,tsvFormat:()=>yi.vP,tsvFormatBody:()=>yi.uH,tsvFormatRow:()=>yi.Hf,tsvFormatRows:()=>yi.n5,tsvFormatValue:()=>yi.sS,tsvParse:()=>yi.tJ,tsvParseRows:()=>yi.E0,union:()=>r.union,utcDay:()=>wv.Z,utcDays:()=>wv.y,utcFormat:()=>Nv.g0,utcFriday:()=>_v.QQ,utcFridays:()=>_v.fz,utcHour:()=>bv.Z,utcHours:()=>bv.X,utcMillisecond:()=>uv.Z,utcMilliseconds:()=>uv.m,utcMinute:()=>vv.Z,utcMinutes:()=>vv.N,utcMonday:()=>_v.l6,utcMondays:()=>_v.$3,utcMonth:()=>xv.Z,utcMonths:()=>xv.K,utcParse:()=>Nv.wp,utcSaturday:()=>_v.g4,utcSaturdays:()=>_v.Q_,utcSecond:()=>fv.Z,utcSeconds:()=>fv.m,utcSunday:()=>_v.Ox,utcSundays:()=>_v.SU,utcThursday:()=>_v.hB,utcThursdays:()=>_v.xj,utcTickInterval:()=>qv.jo,utcTicks:()=>qv.WG,utcTuesday:()=>_v.J1,utcTuesdays:()=>_v.DK,utcWednesday:()=>_v.b3,utcWednesdays:()=>_v.uy,utcWeek:()=>_v.Ox,utcWeeks:()=>_v.SU,utcYear:()=>kv.Z,utcYears:()=>kv.D,variance:()=>r.variance,window:()=>Q,xml:()=>ws,zip:()=>r.zip,zoom:()=>Jv,zoomIdentity:()=>Pv,zoomTransform:()=>Fv});var r=n(9060);function o(t){return t}var i=1,s=2,a=3,l=4,c=1e-6;function u(t){return"translate("+t+",0)"}function f(t){return"translate(0,"+t+")"}function d(t){return e=>+t(e)}function h(t,e){return e=Math.max(0,t.bandwidth()-2*e)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function p(){return!this.__axis}function m(t,e){var n=[],r=null,m=null,g=6,y=6,v=3,b="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,w=t===i||t===l?-1:1,_=t===l||t===s?"x":"y",x=t===i||t===a?u:f;function k(u){var f=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,k=null==m?e.tickFormat?e.tickFormat.apply(e,n):o:m,q=Math.max(g,0)+v,N=e.range(),S=+N[0]+b,A=+N[N.length-1]+b,M=(e.bandwidth?h:d)(e.copy(),b),T=u.selection?u.selection():u,C=T.selectAll(".domain").data([null]),j=T.selectAll(".tick").data(f,e).order(),E=j.exit(),O=j.enter().append("g").attr("class","tick"),I=j.select("line"),R=j.select("text");C=C.merge(C.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),j=j.merge(O),I=I.merge(O.append("line").attr("stroke","currentColor").attr(_+"2",w*g)),R=R.merge(O.append("text").attr("fill","currentColor").attr(_,w*q).attr("dy",t===i?"0em":t===a?"0.71em":"0.32em")),u!==T&&(C=C.transition(u),j=j.transition(u),I=I.transition(u),R=R.transition(u),E=E.transition(u).attr("opacity",c).attr("transform",(function(t){return isFinite(t=M(t))?x(t+b):this.getAttribute("transform")})),O.attr("opacity",c).attr("transform",(function(t){var e=this.parentNode.__axis;return x((e&&isFinite(e=e(t))?e:M(t))+b)}))),E.remove(),C.attr("d",t===l||t===s?y?"M"+w*y+","+S+"H"+b+"V"+A+"H"+w*y:"M"+b+","+S+"V"+A:y?"M"+S+","+w*y+"V"+b+"H"+A+"V"+w*y:"M"+S+","+b+"H"+A),j.attr("opacity",1).attr("transform",(function(t){return x(M(t)+b)})),I.attr(_+"2",w*g),R.attr(_,w*q).text(k),T.filter(p).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===s?"start":t===l?"end":"middle"),T.each((function(){this.__axis=M}))}return k.scale=function(t){return arguments.length?(e=t,k):e},k.ticks=function(){return n=Array.from(arguments),k},k.tickArguments=function(t){return arguments.length?(n=null==t?[]:Array.from(t),k):n.slice()},k.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),k):r&&r.slice()},k.tickFormat=function(t){return arguments.length?(m=t,k):m},k.tickSize=function(t){return arguments.length?(g=y=+t,k):g},k.tickSizeInner=function(t){return arguments.length?(g=+t,k):g},k.tickSizeOuter=function(t){return arguments.length?(y=+t,k):y},k.tickPadding=function(t){return arguments.length?(v=+t,k):v},k.offset=function(t){return arguments.length?(b=+t,k):b},k}function g(t){return m(i,t)}function y(t){return m(s,t)}function v(t){return m(a,t)}function b(t){return m(l,t)}var w={value:()=>{}};function _(){for(var t,e=0,n=arguments.length,r={};e<n;++e){if(!(t=arguments[e]+"")||t in r||/[\s.]/.test(t))throw new Error("illegal type: "+t);r[t]=[]}return new x(r)}function x(t){this._=t}function k(t,e){for(var n,r=0,o=t.length;r<o;++r)if((n=t[r]).name===e)return n.value}function q(t,e,n){for(var r=0,o=t.length;r<o;++r)if(t[r].name===e){t[r]=w,t=t.slice(0,r).concat(t.slice(r+1));break}return null!=n&&t.push({name:e,value:n}),t}x.prototype=_.prototype={constructor:x,on:function(t,e){var n,r,o=this._,i=(r=o,(t+"").trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");if(n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))),s=-1,a=i.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++s<a;)if(n=(t=i[s]).type)o[n]=q(o[n],t.name,e);else if(null==e)for(n in o)o[n]=q(o[n],t.name,null);return this}for(;++s<a;)if((n=(t=i[s]).type)&&(n=k(o[n],t.name)))return n},copy:function(){var t={},e=this._;for(var n in e)t[n]=e[n].slice();return new x(t)},call:function(t,e){if((n=arguments.length-2)>0)for(var n,r,o=new Array(n),i=0;i<n;++i)o[i]=arguments[i+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(i=0,n=(r=this._[t]).length;i<n;++i)r[i].value.apply(e,o)},apply:function(t,e,n){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],o=0,i=r.length;o<i;++o)r[o].value.apply(e,n)}};const N=_;function S(){}function A(t){return null==t?S:function(){return this.querySelector(t)}}function M(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function T(){return[]}function C(t){return null==t?T:function(){return this.querySelectorAll(t)}}function j(t){return function(){return this.matches(t)}}function E(t){return function(e){return e.matches(t)}}var O=Array.prototype.find;function I(){return this.firstElementChild}var R=Array.prototype.filter;function P(){return Array.from(this.children)}function F(t){return new Array(t.length)}function D(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}function L(t,e,n,r,o,i){for(var s,a=0,l=e.length,c=i.length;a<c;++a)(s=e[a])?(s.__data__=i[a],r[a]=s):n[a]=new D(t,i[a]);for(;a<l;++a)(s=e[a])&&(o[a]=s)}function $(t,e,n,r,o,i,s){var a,l,c,u=new Map,f=e.length,d=i.length,h=new Array(f);for(a=0;a<f;++a)(l=e[a])&&(h[a]=c=s.call(l,l.__data__,a,e)+"",u.has(c)?o[a]=l:u.set(c,l));for(a=0;a<d;++a)c=s.call(t,i[a],a,i)+"",(l=u.get(c))?(r[a]=l,l.__data__=i[a],u.delete(c)):n[a]=new D(t,i[a]);for(a=0;a<f;++a)(l=e[a])&&u.get(h[a])===l&&(o[a]=l)}function Z(t){return t.__data__}function z(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function U(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}D.prototype={constructor:D,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var B="http://www.w3.org/1999/xhtml";const G={svg:"http://www.w3.org/2000/svg",xhtml:B,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function J(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),G.hasOwnProperty(e)?{space:G[e],local:t}:t}function W(t){return function(){this.removeAttribute(t)}}function H(t){return function(){this.removeAttributeNS(t.space,t.local)}}function V(t,e){return function(){this.setAttribute(t,e)}}function Y(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function K(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function X(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function Q(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function tt(t){return function(){this.style.removeProperty(t)}}function et(t,e,n){return function(){this.style.setProperty(t,e,n)}}function nt(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function rt(t,e){return t.style.getPropertyValue(e)||Q(t).getComputedStyle(t,null).getPropertyValue(e)}function ot(t){return function(){delete this[t]}}function it(t,e){return function(){this[t]=e}}function st(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function at(t){return t.trim().split(/^|\s+/)}function lt(t){return t.classList||new ct(t)}function ct(t){this._node=t,this._names=at(t.getAttribute("class")||"")}function ut(t,e){for(var n=lt(t),r=-1,o=e.length;++r<o;)n.add(e[r])}function ft(t,e){for(var n=lt(t),r=-1,o=e.length;++r<o;)n.remove(e[r])}function dt(t){return function(){ut(this,t)}}function ht(t){return function(){ft(this,t)}}function pt(t,e){return function(){(e.apply(this,arguments)?ut:ft)(this,t)}}function mt(){this.textContent=""}function gt(t){return function(){this.textContent=t}}function yt(t){return function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}}function vt(){this.innerHTML=""}function bt(t){return function(){this.innerHTML=t}}function wt(t){return function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}}function _t(){this.nextSibling&&this.parentNode.appendChild(this)}function xt(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kt(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===B&&e.documentElement.namespaceURI===B?e.createElement(t):e.createElementNS(n,t)}}function qt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Nt(t){var e=J(t);return(e.local?qt:kt)(e)}function St(){return null}function At(){var t=this.parentNode;t&&t.removeChild(this)}function Mt(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Tt(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function Ct(t){return function(){var e=this.__on;if(e){for(var n,r=0,o=-1,i=e.length;r<i;++r)n=e[r],t.type&&n.type!==t.type||n.name!==t.name?e[++o]=n:this.removeEventListener(n.type,n.listener,n.options);++o?e.length=o:delete this.__on}}}function jt(t,e,n){return function(){var r,o=this.__on,i=function(t){return function(e){t.call(this,e,this.__data__)}}(e);if(o)for(var s=0,a=o.length;s<a;++s)if((r=o[s]).type===t.type&&r.name===t.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=i,r.options=n),void(r.value=e);this.addEventListener(t.type,i,n),r={type:t.type,name:t.name,value:e,listener:i,options:n},o?o.push(r):this.__on=[r]}}function Et(t,e,n){var r=Q(t),o=r.CustomEvent;"function"==typeof o?o=new o(e,n):(o=r.document.createEvent("Event"),n?(o.initEvent(e,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(e,!1,!1)),t.dispatchEvent(o)}function Ot(t,e){return function(){return Et(this,t,e)}}function It(t,e){return function(){return Et(this,t,e.apply(this,arguments))}}ct.prototype={add:function(t){this._names.indexOf(t)<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Rt=[null];function Pt(t,e){this._groups=t,this._parents=e}function Ft(){return new Pt([[document.documentElement]],Rt)}Pt.prototype=Ft.prototype={constructor:Pt,select:function(t){"function"!=typeof t&&(t=A(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s,a=e[o],l=a.length,c=r[o]=new Array(l),u=0;u<l;++u)(i=a[u])&&(s=t.call(i,i.__data__,u,a))&&("__data__"in i&&(s.__data__=i.__data__),c[u]=s);return new Pt(r,this._parents)},selectAll:function(t){t="function"==typeof t?function(t){return function(){return M(t.apply(this,arguments))}}(t):C(t);for(var e=this._groups,n=e.length,r=[],o=[],i=0;i<n;++i)for(var s,a=e[i],l=a.length,c=0;c<l;++c)(s=a[c])&&(r.push(t.call(s,s.__data__,c,a)),o.push(s));return new Pt(r,o)},selectChild:function(t){return this.select(null==t?I:function(t){return function(){return O.call(this.children,t)}}("function"==typeof t?t:E(t)))},selectChildren:function(t){return this.selectAll(null==t?P:function(t){return function(){return R.call(this.children,t)}}("function"==typeof t?t:E(t)))},filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s=e[o],a=s.length,l=r[o]=[],c=0;c<a;++c)(i=s[c])&&t.call(i,i.__data__,c,s)&&l.push(i);return new Pt(r,this._parents)},data:function(t,e){if(!arguments.length)return Array.from(this,Z);var n=e?$:L,r=this._parents,o=this._groups;"function"!=typeof t&&(t=function(t){return function(){return t}}(t));for(var i=o.length,s=new Array(i),a=new Array(i),l=new Array(i),c=0;c<i;++c){var u=r[c],f=o[c],d=f.length,h=z(t.call(u,u&&u.__data__,c,r)),p=h.length,m=a[c]=new Array(p),g=s[c]=new Array(p);n(u,f,m,g,l[c]=new Array(d),h,e);for(var y,v,b=0,w=0;b<p;++b)if(y=m[b]){for(b>=w&&(w=b+1);!(v=g[w])&&++w<p;);y._next=v||null}}return(s=new Pt(s,r))._enter=a,s._exit=l,s},enter:function(){return new Pt(this._enter||this._groups.map(F),this._parents)},exit:function(){return new Pt(this._exit||this._groups.map(F),this._parents)},join:function(t,e,n){var r=this.enter(),o=this,i=this.exit();return"function"==typeof t?(r=t(r))&&(r=r.selection()):r=r.append(t+""),null!=e&&(o=e(o))&&(o=o.selection()),null==n?i.remove():n(i),r&&o?r.merge(o).order():o},merge:function(t){for(var e=t.selection?t.selection():t,n=this._groups,r=e._groups,o=n.length,i=r.length,s=Math.min(o,i),a=new Array(o),l=0;l<s;++l)for(var c,u=n[l],f=r[l],d=u.length,h=a[l]=new Array(d),p=0;p<d;++p)(c=u[p]||f[p])&&(h[p]=c);for(;l<o;++l)a[l]=n[l];return new Pt(a,this._parents)},selection:function(){return this},order:function(){for(var t=this._groups,e=-1,n=t.length;++e<n;)for(var r,o=t[e],i=o.length-1,s=o[i];--i>=0;)(r=o[i])&&(s&&4^r.compareDocumentPosition(s)&&s.parentNode.insertBefore(r,s),s=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=U);for(var n=this._groups,r=n.length,o=new Array(r),i=0;i<r;++i){for(var s,a=n[i],l=a.length,c=o[i]=new Array(l),u=0;u<l;++u)(s=a[u])&&(c[u]=s);c.sort(e)}return new Pt(o,this._parents).order()},call:function(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r=t[e],o=0,i=r.length;o<i;++o){var s=r[o];if(s)return s}return null},size:function(){let t=0;for(const e of this)++t;return t},empty:function(){return!this.node()},each:function(t){for(var e=this._groups,n=0,r=e.length;n<r;++n)for(var o,i=e[n],s=0,a=i.length;s<a;++s)(o=i[s])&&t.call(o,o.__data__,s,i);return this},attr:function(t,e){var n=J(t);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==e?n.local?H:W:"function"==typeof e?n.local?X:K:n.local?Y:V)(n,e))},style:function(t,e,n){return arguments.length>1?this.each((null==e?tt:"function"==typeof e?nt:et)(t,e,null==n?"":n)):rt(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?ot:"function"==typeof e?st:it)(t,e)):this.node()[t]},classed:function(t,e){var n=at(t+"");if(arguments.length<2){for(var r=lt(this.node()),o=-1,i=n.length;++o<i;)if(!r.contains(n[o]))return!1;return!0}return this.each(("function"==typeof e?pt:e?dt:ht)(n,e))},text:function(t){return arguments.length?this.each(null==t?mt:("function"==typeof t?yt:gt)(t)):this.node().textContent},html:function(t){return arguments.length?this.each(null==t?vt:("function"==typeof t?wt:bt)(t)):this.node().innerHTML},raise:function(){return this.each(_t)},lower:function(){return this.each(xt)},append:function(t){var e="function"==typeof t?t:Nt(t);return this.select((function(){return this.appendChild(e.apply(this,arguments))}))},insert:function(t,e){var n="function"==typeof t?t:Nt(t),r=null==e?St:"function"==typeof e?e:A(e);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(At)},clone:function(t){return this.select(t?Tt:Mt)},datum:function(t){return arguments.length?this.property("__data__",t):this.node().__data__},on:function(t,e,n){var r,o,i=function(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}(t+""),s=i.length;if(!(arguments.length<2)){for(a=e?jt:Ct,r=0;r<s;++r)this.each(a(i[r],e,n));return this}var a=this.node().__on;if(a)for(var l,c=0,u=a.length;c<u;++c)for(r=0,l=a[c];r<s;++r)if((o=i[r]).type===l.type&&o.name===l.name)return l.value},dispatch:function(t,e){return this.each(("function"==typeof e?It:Ot)(t,e))},[Symbol.iterator]:function*(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r,o=t[e],i=0,s=o.length;i<s;++i)(r=o[i])&&(yield r)}};const Dt=Ft;function Lt(t){return"string"==typeof t?new Pt([[document.querySelector(t)]],[document.documentElement]):new Pt([[t]],Rt)}const $t={passive:!1},Zt={capture:!0,passive:!1};function zt(t){t.stopImmediatePropagation()}function Ut(t){t.preventDefault(),t.stopImmediatePropagation()}function Bt(t){var e=t.document.documentElement,n=Lt(t).on("dragstart.drag",Ut,Zt);"onselectstart"in e?n.on("selectstart.drag",Ut,Zt):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none")}function Gt(t,e){var n=t.document.documentElement,r=Lt(t).on("dragstart.drag",null);e&&(r.on("click.drag",Ut,Zt),setTimeout((function(){r.on("click.drag",null)}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}var Jt=n(2303);function Wt(t){let e;for(;e=t.sourceEvent;)t=e;return t}function Ht(t,e){if(t=Wt(t),void 0===e&&(e=t.currentTarget),e){var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=t.clientX,r.y=t.clientY,[(r=r.matrixTransform(e.getScreenCTM().inverse())).x,r.y]}if(e.getBoundingClientRect){var o=e.getBoundingClientRect();return[t.clientX-o.left-e.clientLeft,t.clientY-o.top-e.clientTop]}}return[t.pageX,t.pageY]}var Vt,Yt,Kt=0,Xt=0,Qt=0,te=1e3,ee=0,ne=0,re=0,oe="object"==typeof performance&&performance.now?performance:Date,ie="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function se(){return ne||(ie(ae),ne=oe.now()+re)}function ae(){ne=0}function le(){this._call=this._time=this._next=null}function ce(t,e,n){var r=new le;return r.restart(t,e,n),r}function ue(){se(),++Kt;for(var t,e=Vt;e;)(t=ne-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kt}function fe(){ne=(ee=oe.now())+re,Kt=Xt=0;try{ue()}finally{Kt=0,function(){var t,e,n=Vt,r=1/0;for(;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Vt=e);Yt=t,he(r)}(),ne=0}}function de(){var t=oe.now(),e=t-ee;e>te&&(re-=e,ee=t)}function he(t){Kt||(Xt&&(Xt=clearTimeout(Xt)),t-ne>24?(t<1/0&&(Xt=setTimeout(fe,t-oe.now()-re)),Qt&&(Qt=clearInterval(Qt))):(Qt||(ee=oe.now(),Qt=setInterval(de,te)),Kt=1,ie(fe)))}function pe(t,e,n){var r=new le;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}le.prototype=ce.prototype={constructor:le,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?se():+n)+(null==e?0:+e),this._next||Yt===this||(Yt?Yt._next=this:Vt=this,Yt=this),this._call=t,this._time=n,he()},stop:function(){this._call&&(this._call=null,this._time=1/0,he())}};var me=N("start","end","cancel","interrupt"),ge=[],ye=0,ve=1,be=2,we=3,_e=4,xe=5,ke=6;function qe(t,e,n,r,o,i){var s=t.__transition;if(s){if(n in s)return}else t.__transition={};!function(t,e,n){var r,o=t.__transition;function i(t){n.state=ve,n.timer.restart(s,n.delay,n.time),n.delay<=t&&s(t-n.delay)}function s(i){var c,u,f,d;if(n.state!==ve)return l();for(c in o)if((d=o[c]).name===n.name){if(d.state===we)return pe(s);d.state===_e?(d.state=ke,d.timer.stop(),d.on.call("interrupt",t,t.__data__,d.index,d.group),delete o[c]):+c<e&&(d.state=ke,d.timer.stop(),d.on.call("cancel",t,t.__data__,d.index,d.group),delete o[c])}if(pe((function(){n.state===we&&(n.state=_e,n.timer.restart(a,n.delay,n.time),a(i))})),n.state=be,n.on.call("start",t,t.__data__,n.index,n.group),n.state===be){for(n.state=we,r=new Array(f=n.tween.length),c=0,u=-1;c<f;++c)(d=n.tween[c].value.call(t,t.__data__,n.index,n.group))&&(r[++u]=d);r.length=u+1}}function a(e){for(var o=e<n.duration?n.ease.call(null,e/n.duration):(n.timer.restart(l),n.state=xe,1),i=-1,s=r.length;++i<s;)r[i].call(t,o);n.state===xe&&(n.on.call("end",t,t.__data__,n.index,n.group),l())}function l(){for(var r in n.state=ke,n.timer.stop(),delete o[e],o)return;delete t.__transition}o[e]=n,n.timer=ce(i,0,n.time)}(t,n,{name:e,index:r,group:o,on:me,tween:ge,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:ye})}function Ne(t,e){var n=Ae(t,e);if(n.state>ye)throw new Error("too late; already scheduled");return n}function Se(t,e){var n=Ae(t,e);if(n.state>we)throw new Error("too late; already running");return n}function Ae(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function Me(t,e){var n,r,o,i=t.__transition,s=!0;if(i){for(o in e=null==e?null:e+"",i)(n=i[o]).name===e?(r=n.state>be&&n.state<xe,n.state=ke,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete i[o]):s=!1;s&&delete t.__transition}}var Te,Ce=n(8403),je=180/Math.PI,Ee={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Oe(t,e,n,r,o,i){var s,a,l;return(s=Math.sqrt(t*t+e*e))&&(t/=s,e/=s),(l=t*n+e*r)&&(n-=t*l,r-=e*l),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,l/=a),t*r<e*n&&(t=-t,e=-e,l=-l,s=-s),{translateX:o,translateY:i,rotate:Math.atan2(e,t)*je,skewX:Math.atan(l)*je,scaleX:s,scaleY:a}}function Ie(t,e,n,r){function o(t){return t.length?t.pop()+" ":""}return function(i,s){var a=[],l=[];return i=t(i),s=t(s),function(t,r,o,i,s,a){if(t!==o||r!==i){var l=s.push("translate(",null,e,null,n);a.push({i:l-4,x:(0,Ce.Z)(t,o)},{i:l-2,x:(0,Ce.Z)(r,i)})}else(o||i)&&s.push("translate("+o+e+i+n)}(i.translateX,i.translateY,s.translateX,s.translateY,a,l),function(t,e,n,i){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),i.push({i:n.push(o(n)+"rotate(",null,r)-2,x:(0,Ce.Z)(t,e)})):e&&n.push(o(n)+"rotate("+e+r)}(i.rotate,s.rotate,a,l),function(t,e,n,i){t!==e?i.push({i:n.push(o(n)+"skewX(",null,r)-2,x:(0,Ce.Z)(t,e)}):e&&n.push(o(n)+"skewX("+e+r)}(i.skewX,s.skewX,a,l),function(t,e,n,r,i,s){if(t!==n||e!==r){var a=i.push(o(i)+"scale(",null,",",null,")");s.push({i:a-4,x:(0,Ce.Z)(t,n)},{i:a-2,x:(0,Ce.Z)(e,r)})}else 1===n&&1===r||i.push(o(i)+"scale("+n+","+r+")")}(i.scaleX,i.scaleY,s.scaleX,s.scaleY,a,l),i=s=null,function(t){for(var e,n=-1,r=l.length;++n<r;)a[(e=l[n]).i]=e.x(t);return a.join("")}}}var Re=Ie((function(t){const e=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?Ee:Oe(e.a,e.b,e.c,e.d,e.e,e.f)}),"px, ","px)","deg)"),Pe=Ie((function(t){return null==t?Ee:(Te||(Te=document.createElementNS("http://www.w3.org/2000/svg","g")),Te.setAttribute("transform",t),(t=Te.transform.baseVal.consolidate())?Oe((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):Ee)}),", ",")",")");function Fe(t,e){var n,r;return function(){var o=Se(this,t),i=o.tween;if(i!==n)for(var s=0,a=(r=n=i).length;s<a;++s)if(r[s].name===e){(r=r.slice()).splice(s,1);break}o.tween=r}}function De(t,e,n){var r,o;if("function"!=typeof n)throw new Error;return function(){var i=Se(this,t),s=i.tween;if(s!==r){o=(r=s).slice();for(var a={name:e,value:n},l=0,c=o.length;l<c;++l)if(o[l].name===e){o[l]=a;break}l===c&&o.push(a)}i.tween=o}}function Le(t,e,n){var r=t._id;return t.each((function(){var t=Se(this,r);(t.value||(t.value={}))[e]=n.apply(this,arguments)})),function(t){return Ae(t,r).value[e]}}var $e=n(1495),Ze=n(490),ze=n(9009);function Ue(t,e){var n;return("number"==typeof e?Ce.Z:e instanceof $e.ZP?Ze.ZP:(n=(0,$e.ZP)(e))?(e=n,Ze.ZP):ze.Z)(t,e)}function Be(t){return function(){this.removeAttribute(t)}}function Ge(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Je(t,e,n){var r,o,i=n+"";return function(){var s=this.getAttribute(t);return s===i?null:s===r?o:o=e(r=s,n)}}function We(t,e,n){var r,o,i=n+"";return function(){var s=this.getAttributeNS(t.space,t.local);return s===i?null:s===r?o:o=e(r=s,n)}}function He(t,e,n){var r,o,i;return function(){var s,a,l=n(this);if(null!=l)return(s=this.getAttribute(t))===(a=l+"")?null:s===r&&a===o?i:(o=a,i=e(r=s,l));this.removeAttribute(t)}}function Ve(t,e,n){var r,o,i;return function(){var s,a,l=n(this);if(null!=l)return(s=this.getAttributeNS(t.space,t.local))===(a=l+"")?null:s===r&&a===o?i:(o=a,i=e(r=s,l));this.removeAttributeNS(t.space,t.local)}}function Ye(t,e){var n,r;function o(){var o=e.apply(this,arguments);return o!==r&&(n=(r=o)&&function(t,e){return function(n){this.setAttributeNS(t.space,t.local,e.call(this,n))}}(t,o)),n}return o._value=e,o}function Ke(t,e){var n,r;function o(){var o=e.apply(this,arguments);return o!==r&&(n=(r=o)&&function(t,e){return function(n){this.setAttribute(t,e.call(this,n))}}(t,o)),n}return o._value=e,o}function Xe(t,e){return function(){Ne(this,t).delay=+e.apply(this,arguments)}}function Qe(t,e){return e=+e,function(){Ne(this,t).delay=e}}function tn(t,e){return function(){Se(this,t).duration=+e.apply(this,arguments)}}function en(t,e){return e=+e,function(){Se(this,t).duration=e}}var nn=Dt.prototype.constructor;function rn(t){return function(){this.style.removeProperty(t)}}var on=0;function sn(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function an(t){return Dt().transition(t)}function ln(){return++on}var cn=Dt.prototype;function un(t){return t*t*t}function fn(t){return--t*t*t+1}function dn(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}sn.prototype=an.prototype={constructor:sn,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=A(t));for(var r=this._groups,o=r.length,i=new Array(o),s=0;s<o;++s)for(var a,l,c=r[s],u=c.length,f=i[s]=new Array(u),d=0;d<u;++d)(a=c[d])&&(l=t.call(a,a.__data__,d,c))&&("__data__"in a&&(l.__data__=a.__data__),f[d]=l,qe(f[d],e,n,d,f,Ae(a,n)));return new sn(i,this._parents,e,n)},selectAll:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=C(t));for(var r=this._groups,o=r.length,i=[],s=[],a=0;a<o;++a)for(var l,c=r[a],u=c.length,f=0;f<u;++f)if(l=c[f]){for(var d,h=t.call(l,l.__data__,f,c),p=Ae(l,n),m=0,g=h.length;m<g;++m)(d=h[m])&&qe(d,e,n,m,h,p);i.push(h),s.push(l)}return new sn(i,s,e,n)},selectChild:cn.selectChild,selectChildren:cn.selectChildren,filter:function(t){"function"!=typeof t&&(t=j(t));for(var e=this._groups,n=e.length,r=new Array(n),o=0;o<n;++o)for(var i,s=e[o],a=s.length,l=r[o]=[],c=0;c<a;++c)(i=s[c])&&t.call(i,i.__data__,c,s)&&l.push(i);return new sn(r,this._parents,this._name,this._id)},merge:function(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,n=t._groups,r=e.length,o=n.length,i=Math.min(r,o),s=new Array(r),a=0;a<i;++a)for(var l,c=e[a],u=n[a],f=c.length,d=s[a]=new Array(f),h=0;h<f;++h)(l=c[h]||u[h])&&(d[h]=l);for(;a<r;++a)s[a]=e[a];return new sn(s,this._parents,this._name,this._id)},selection:function(){return new nn(this._groups,this._parents)},transition:function(){for(var t=this._name,e=this._id,n=ln(),r=this._groups,o=r.length,i=0;i<o;++i)for(var s,a=r[i],l=a.length,c=0;c<l;++c)if(s=a[c]){var u=Ae(s,e);qe(s,t,n,c,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new sn(r,this._parents,t,n)},call:cn.call,nodes:cn.nodes,node:cn.node,size:cn.size,empty:cn.empty,each:cn.each,on:function(t,e){var n=this._id;return arguments.length<2?Ae(this.node(),n).on.on(t):this.each(function(t,e,n){var r,o,i=function(t){return(t+"").trim().split(/^|\s+/).every((function(t){var e=t.indexOf(".");return e>=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?Ne:Se;return function(){var s=i(this,t),a=s.on;a!==r&&(o=(r=a).copy()).on(e,n),s.on=o}}(n,t,e))},attr:function(t,e){var n=J(t),r="transform"===n?Pe:Ue;return this.attrTween(t,"function"==typeof e?(n.local?Ve:He)(n,r,Le(this,"attr."+t,e)):null==e?(n.local?Ge:Be)(n):(n.local?We:Je)(n,r,e))},attrTween:function(t,e){var n="attr."+t;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==e)return this.tween(n,null);if("function"!=typeof e)throw new Error;var r=J(t);return this.tween(n,(r.local?Ye:Ke)(r,e))},style:function(t,e,n){var r="transform"==(t+="")?Re:Ue;return null==e?this.styleTween(t,function(t,e){var n,r,o;return function(){var i=rt(this,t),s=(this.style.removeProperty(t),rt(this,t));return i===s?null:i===n&&s===r?o:o=e(n=i,r=s)}}(t,r)).on("end.style."+t,rn(t)):"function"==typeof e?this.styleTween(t,function(t,e,n){var r,o,i;return function(){var s=rt(this,t),a=n(this),l=a+"";return null==a&&(this.style.removeProperty(t),l=a=rt(this,t)),s===l?null:s===r&&l===o?i:(o=l,i=e(r=s,a))}}(t,r,Le(this,"style."+t,e))).each(function(t,e){var n,r,o,i,s="style."+e,a="end."+s;return function(){var l=Se(this,t),c=l.on,u=null==l.value[s]?i||(i=rn(e)):void 0;c===n&&o===u||(r=(n=c).copy()).on(a,o=u),l.on=r}}(this._id,t)):this.styleTween(t,function(t,e,n){var r,o,i=n+"";return function(){var s=rt(this,t);return s===i?null:s===r?o:o=e(r=s,n)}}(t,r,e),n).on("end.style."+t,null)},styleTween:function(t,e,n){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==e)return this.tween(r,null);if("function"!=typeof e)throw new Error;return this.tween(r,function(t,e,n){var r,o;function i(){var i=e.apply(this,arguments);return i!==o&&(r=(o=i)&&function(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}(t,i,n)),r}return i._value=e,i}(t,e,null==n?"":n))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var e=t(this);this.textContent=null==e?"":e}}(Le(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var e="text";if(arguments.length<1)return(e=this.tween(e))&&e._value;if(null==t)return this.tween(e,null);if("function"!=typeof t)throw new Error;return this.tween(e,function(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&function(t){return function(e){this.textContent=t.call(this,e)}}(r)),e}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var e=this.parentNode;for(var n in this.__transition)if(+n!==t)return;e&&e.removeChild(this)}}(this._id))},tween:function(t,e){var n=this._id;if(t+="",arguments.length<2){for(var r,o=Ae(this.node(),n).tween,i=0,s=o.length;i<s;++i)if((r=o[i]).name===t)return r.value;return null}return this.each((null==e?Fe:De)(n,t,e))},delay:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?Xe:Qe)(e,t)):Ae(this.node(),e).delay},duration:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?tn:en)(e,t)):Ae(this.node(),e).duration},ease:function(t){var e=this._id;return arguments.length?this.each(function(t,e){if("function"!=typeof e)throw new Error;return function(){Se(this,t).ease=e}}(e,t)):Ae(this.node(),e).ease},easeVarying:function(t){if("function"!=typeof t)throw new Error;return this.each(function(t,e){return function(){var n=e.apply(this,arguments);if("function"!=typeof n)throw new Error;Se(this,t).ease=n}}(this._id,t))},end:function(){var t,e,n=this,r=n._id,o=n.size();return new Promise((function(i,s){var a={value:s},l={value:function(){0==--o&&i()}};n.each((function(){var n=Se(this,r),o=n.on;o!==t&&((e=(t=o).copy())._.cancel.push(a),e._.interrupt.push(a),e._.end.push(l)),n.on=e})),0===o&&i()}))},[Symbol.iterator]:cn[Symbol.iterator]};var hn={time:null,delay:0,duration:250,ease:dn};function pn(t,e){for(var n;!(n=t.__transition)||!(n=n[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return n}Dt.prototype.interrupt=function(t){return this.each((function(){Me(this,t)}))},Dt.prototype.transition=function(t){var e,n;t instanceof sn?(e=t._id,t=t._name):(e=ln(),(n=hn).time=se(),t=null==t?null:t+"");for(var r=this._groups,o=r.length,i=0;i<o;++i)for(var s,a=r[i],l=a.length,c=0;c<l;++c)(s=a[c])&&qe(s,t,e,c,a,n||pn(s,e));return new sn(r,this._parents,t,e)};var mn=[null];function gn(t,e){var n,r,o=t.__transition;if(o)for(r in e=null==e?null:e+"",o)if((n=o[r]).state>ve&&n.name===e)return new sn([[t]],mn,e,+r);return null}const yn=t=>()=>t;function vn(t,{sourceEvent:e,target:n,selection:r,mode:o,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:o,enumerable:!0,configurable:!0},_:{value:i}})}function bn(t){t.preventDefault(),t.stopImmediatePropagation()}var wn={name:"drag"},_n={name:"space"},xn={name:"handle"},kn={name:"center"};const{abs:qn,max:Nn,min:Sn}=Math;function An(t){return[+t[0],+t[1]]}function Mn(t){return[An(t[0]),An(t[1])]}var Tn={name:"x",handles:["w","e"].map(Fn),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Cn={name:"y",handles:["n","s"].map(Fn),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},jn={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Fn),input:function(t){return null==t?null:Mn(t)},output:function(t){return t}},En={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},On={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},In={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Rn={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},Pn={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Fn(t){return{type:t}}function Dn(t){return!t.ctrlKey&&!t.button}function Ln(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function $n(){return navigator.maxTouchPoints||"ontouchstart"in this}function Zn(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function zn(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Un(){return Jn(Tn)}function Bn(){return Jn(Cn)}function Gn(){return Jn(jn)}function Jn(t){var e,n=Ln,r=Dn,o=$n,i=!0,s=N("start","brush","end"),a=6;function l(e){var n=e.property("__brush",m).selectAll(".overlay").data([Fn("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",En.overlay).merge(n).each((function(){var t=Zn(this).extent;Lt(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([Fn("selection")]).enter().append("rect").attr("class","selection").attr("cursor",En.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return En[t.type]})),e.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",d).filter(o).on("touchstart.brush",d).on("touchmove.brush",h).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function c(){var t=Lt(this),e=Zn(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-a/2:e[0][0]-a/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-a/2:e[0][1]-a/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+a:a})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+a:a}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function u(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new f(t,e,n):r}function f(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function d(n){if((!e||n.touches)&&r.apply(this,arguments)){var o,s,a,l,f,d,h,p,m,g,y,v=this,b=n.target.__data__.type,w="selection"===(i&&n.metaKey?b="overlay":b)?wn:i&&n.altKey?kn:xn,_=t===Cn?null:Rn[b],x=t===Tn?null:Pn[b],k=Zn(v),q=k.extent,N=k.selection,S=q[0][0],A=q[0][1],M=q[1][0],T=q[1][1],C=0,j=0,E=_&&x&&i&&n.shiftKey,O=Array.from(n.touches||[n],(t=>{const e=t.identifier;return(t=Ht(t,v)).point0=t.slice(),t.identifier=e,t}));Me(v);var I=u(v,arguments,!0).beforestart();if("overlay"===b){N&&(m=!0);const e=[O[0],O[1]||O[0]];k.selection=N=[[o=t===Cn?S:Sn(e[0][0],e[1][0]),a=t===Tn?A:Sn(e[0][1],e[1][1])],[f=t===Cn?M:Nn(e[0][0],e[1][0]),h=t===Tn?T:Nn(e[0][1],e[1][1])]],O.length>1&&L(n)}else o=N[0][0],a=N[0][1],f=N[1][0],h=N[1][1];s=o,l=a,d=f,p=h;var R=Lt(v).attr("pointer-events","none"),P=R.selectAll(".overlay").attr("cursor",En[b]);if(n.touches)I.moved=D,I.ended=$;else{var F=Lt(n.view).on("mousemove.brush",D,!0).on("mouseup.brush",$,!0);i&&F.on("keydown.brush",(function(t){switch(t.keyCode){case 16:E=_&&x;break;case 18:w===xn&&(_&&(f=d-C*_,o=s+C*_),x&&(h=p-j*x,a=l+j*x),w=kn,L(t));break;case 32:w!==xn&&w!==kn||(_<0?f=d-C:_>0&&(o=s-C),x<0?h=p-j:x>0&&(a=l-j),w=_n,P.attr("cursor",En.selection),L(t));break;default:return}bn(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:E&&(g=y=E=!1,L(t));break;case 18:w===kn&&(_<0?f=d:_>0&&(o=s),x<0?h=p:x>0&&(a=l),w=xn,L(t));break;case 32:w===_n&&(t.altKey?(_&&(f=d-C*_,o=s+C*_),x&&(h=p-j*x,a=l+j*x),w=kn):(_<0?f=d:_>0&&(o=s),x<0?h=p:x>0&&(a=l),w=xn),P.attr("cursor",En[b]),L(t));break;default:return}bn(t)}),!0),Bt(n.view)}c.call(v),I.start(n,w.name)}function D(t){for(const e of t.changedTouches||[t])for(const t of O)t.identifier===e.identifier&&(t.cur=Ht(e,v));if(E&&!g&&!y&&1===O.length){const t=O[0];qn(t.cur[0]-t[0])>qn(t.cur[1]-t[1])?y=!0:g=!0}for(const t of O)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);m=!0,bn(t),L(t)}function L(t){const e=O[0],n=e.point0;var r;switch(C=e[0]-n[0],j=e[1]-n[1],w){case _n:case wn:_&&(C=Nn(S-o,Sn(M-f,C)),s=o+C,d=f+C),x&&(j=Nn(A-a,Sn(T-h,j)),l=a+j,p=h+j);break;case xn:O[1]?(_&&(s=Nn(S,Sn(M,O[0][0])),d=Nn(S,Sn(M,O[1][0])),_=1),x&&(l=Nn(A,Sn(T,O[0][1])),p=Nn(A,Sn(T,O[1][1])),x=1)):(_<0?(C=Nn(S-o,Sn(M-o,C)),s=o+C,d=f):_>0&&(C=Nn(S-f,Sn(M-f,C)),s=o,d=f+C),x<0?(j=Nn(A-a,Sn(T-a,j)),l=a+j,p=h):x>0&&(j=Nn(A-h,Sn(T-h,j)),l=a,p=h+j));break;case kn:_&&(s=Nn(S,Sn(M,o-C*_)),d=Nn(S,Sn(M,f+C*_))),x&&(l=Nn(A,Sn(T,a-j*x)),p=Nn(A,Sn(T,h+j*x)))}d<s&&(_*=-1,r=o,o=f,f=r,r=s,s=d,d=r,b in On&&P.attr("cursor",En[b=On[b]])),p<l&&(x*=-1,r=a,a=h,h=r,r=l,l=p,p=r,b in In&&P.attr("cursor",En[b=In[b]])),k.selection&&(N=k.selection),g&&(s=N[0][0],d=N[1][0]),y&&(l=N[0][1],p=N[1][1]),N[0][0]===s&&N[0][1]===l&&N[1][0]===d&&N[1][1]===p||(k.selection=[[s,l],[d,p]],c.call(v),I.brush(t,w.name))}function $(t){if(function(t){t.stopImmediatePropagation()}(t),t.touches){if(t.touches.length)return;e&&clearTimeout(e),e=setTimeout((function(){e=null}),500)}else Gt(t.view,m),F.on("keydown.brush keyup.brush mousemove.brush mouseup.brush",null);R.attr("pointer-events","all"),P.attr("cursor",En.overlay),k.selection&&(N=k.selection),function(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}(N)&&(k.selection=null,c.call(v)),I.end(t,w.name)}}function h(t){u(this,arguments).moved(t)}function p(t){u(this,arguments).ended(t)}function m(){var e=this.__brush||{selection:null};return e.extent=Mn(n.apply(this,arguments)),e.dim=t,e}return l.move=function(e,n,r){e.tween?e.on("start.brush",(function(t){u(this,arguments).beforestart().start(t)})).on("interrupt.brush end.brush",(function(t){u(this,arguments).end(t)})).tween("brush",(function(){var e=this,r=e.__brush,o=u(e,arguments),i=r.selection,s=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),a=(0,Jt.Z)(i,s);function l(t){r.selection=1===t&&null===s?null:a(t),c.call(e),o.brush()}return null!==i&&null!==s?l:l(1)})):e.each((function(){var e=this,o=arguments,i=e.__brush,s=t.input("function"==typeof n?n.apply(e,o):n,i.extent),a=u(e,o).beforestart();Me(e),i.selection=null===s?null:s,c.call(e),a.start(r).brush(r).end(r)}))},l.clear=function(t,e){l.move(t,null,e)},f.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(t,e){return this.starting?(this.starting=!1,this.emit("start",t,e)):this.emit("brush",t),this},brush:function(t,e){return this.emit("brush",t,e),this},end:function(t,e){return 0==--this.active&&(delete this.state.emitter,this.emit("end",t,e)),this},emit:function(e,n,r){var o=Lt(this.that).datum();s.call(e,this.that,new vn(e,{sourceEvent:n,target:l,selection:t.output(this.state.selection),mode:r,dispatch:s}),o)}},l.extent=function(t){return arguments.length?(n="function"==typeof t?t:yn(Mn(t)),l):n},l.filter=function(t){return arguments.length?(r="function"==typeof t?t:yn(!!t),l):r},l.touchable=function(t){return arguments.length?(o="function"==typeof t?t:yn(!!t),l):o},l.handleSize=function(t){return arguments.length?(a=+t,l):a},l.keyModifiers=function(t){return arguments.length?(i=!!t,l):i},l.on=function(){var t=s.on.apply(s,arguments);return t===s?l:t},l}var Wn=Math.abs,Hn=Math.cos,Vn=Math.sin,Yn=Math.PI,Kn=Yn/2,Xn=2*Yn,Qn=Math.max,tr=1e-12;function er(t,e){return Array.from({length:e-t},((e,n)=>t+n))}function nr(){return ir(!1,!1)}function rr(){return ir(!1,!0)}function or(){return ir(!0,!1)}function ir(t,e){var n=0,r=null,o=null,i=null;function s(s){var a,l=s.length,c=new Array(l),u=er(0,l),f=new Array(l*l),d=new Array(l),h=0;s=Float64Array.from({length:l*l},e?(t,e)=>s[e%l][e/l|0]:(t,e)=>s[e/l|0][e%l]);for(let e=0;e<l;++e){let n=0;for(let r=0;r<l;++r)n+=s[e*l+r]+t*s[r*l+e];h+=c[e]=n}a=(h=Qn(0,Xn-n*l)/h)?n:Xn/l;{let e=0;r&&u.sort(((t,e)=>r(c[t],c[e])));for(const n of u){const r=e;if(t){const t=er(1+~l,l).filter((t=>t<0?s[~t*l+n]:s[n*l+t]));o&&t.sort(((t,e)=>o(t<0?-s[~t*l+n]:s[n*l+t],e<0?-s[~e*l+n]:s[n*l+e])));for(const r of t)if(r<0){(f[~r*l+n]||(f[~r*l+n]={source:null,target:null})).target={index:n,startAngle:e,endAngle:e+=s[~r*l+n]*h,value:s[~r*l+n]}}else{(f[n*l+r]||(f[n*l+r]={source:null,target:null})).source={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}else{const t=er(0,l).filter((t=>s[n*l+t]||s[t*l+n]));o&&t.sort(((t,e)=>o(s[n*l+t],s[n*l+e])));for(const r of t){let t;if(n<r?(t=f[n*l+r]||(f[n*l+r]={source:null,target:null}),t.source={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]}):(t=f[r*l+n]||(f[r*l+n]={source:null,target:null}),t.target={index:n,startAngle:e,endAngle:e+=s[n*l+r]*h,value:s[n*l+r]},n===r&&(t.source=t.target)),t.source&&t.target&&t.source.value<t.target.value){const e=t.source;t.source=t.target,t.target=e}}d[n]={index:n,startAngle:r,endAngle:e,value:c[n]}}e+=a}}return(f=Object.values(f)).groups=d,i?f.sort(i):f}return s.padAngle=function(t){return arguments.length?(n=Qn(0,t),s):n},s.sortGroups=function(t){return arguments.length?(r=t,s):r},s.sortSubgroups=function(t){return arguments.length?(o=t,s):o},s.sortChords=function(t){return arguments.length?(null==t?i=null:(e=t,i=function(t,n){return e(t.source.value+t.target.value,n.source.value+n.target.value)})._=t,s):i&&i._;var e},s}const sr=Math.PI,ar=2*sr,lr=1e-6,cr=ar-lr;function ur(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function fr(){return new ur}ur.prototype=fr.prototype={constructor:ur,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r)},bezierCurveTo:function(t,e,n,r,o,i){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+o)+","+(this._y1=+i)},arcTo:function(t,e,n,r,o){t=+t,e=+e,n=+n,r=+r,o=+o;var i=this._x1,s=this._y1,a=n-t,l=r-e,c=i-t,u=s-e,f=c*c+u*u;if(o<0)throw new Error("negative radius: "+o);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(f>lr)if(Math.abs(u*a-l*c)>lr&&o){var d=n-i,h=r-s,p=a*a+l*l,m=d*d+h*h,g=Math.sqrt(p),y=Math.sqrt(f),v=o*Math.tan((sr-Math.acos((p+f-m)/(2*g*y)))/2),b=v/y,w=v/g;Math.abs(b-1)>lr&&(this._+="L"+(t+b*c)+","+(e+b*u)),this._+="A"+o+","+o+",0,0,"+ +(u*d>c*h)+","+(this._x1=t+w*a)+","+(this._y1=e+w*l)}else this._+="L"+(this._x1=t)+","+(this._y1=e);else;},arc:function(t,e,n,r,o,i){t=+t,e=+e,i=!!i;var s=(n=+n)*Math.cos(r),a=n*Math.sin(r),l=t+s,c=e+a,u=1^i,f=i?r-o:o-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+l+","+c:(Math.abs(this._x1-l)>lr||Math.abs(this._y1-c)>lr)&&(this._+="L"+l+","+c),n&&(f<0&&(f=f%ar+ar),f>cr?this._+="A"+n+","+n+",0,1,"+u+","+(t-s)+","+(e-a)+"A"+n+","+n+",0,1,"+u+","+(this._x1=l)+","+(this._y1=c):f>lr&&(this._+="A"+n+","+n+",0,"+ +(f>=sr)+","+u+","+(this._x1=t+n*Math.cos(o))+","+(this._y1=e+n*Math.sin(o))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const dr=fr;var hr=Array.prototype.slice;function pr(t){return function(){return t}}function mr(t){return t.source}function gr(t){return t.target}function yr(t){return t.radius}function vr(t){return t.startAngle}function br(t){return t.endAngle}function wr(){return 0}function _r(){return 10}function xr(t){var e=mr,n=gr,r=yr,o=yr,i=vr,s=br,a=wr,l=null;function c(){var c,u=e.apply(this,arguments),f=n.apply(this,arguments),d=a.apply(this,arguments)/2,h=hr.call(arguments),p=+r.apply(this,(h[0]=u,h)),m=i.apply(this,h)-Kn,g=s.apply(this,h)-Kn,y=+o.apply(this,(h[0]=f,h)),v=i.apply(this,h)-Kn,b=s.apply(this,h)-Kn;if(l||(l=c=dr()),d>tr&&(Wn(g-m)>2*d+tr?g>m?(m+=d,g-=d):(m-=d,g+=d):m=g=(m+g)/2,Wn(b-v)>2*d+tr?b>v?(v+=d,b-=d):(v-=d,b+=d):v=b=(v+b)/2),l.moveTo(p*Hn(m),p*Vn(m)),l.arc(0,0,p,m,g),m!==v||g!==b)if(t){var w=y-+t.apply(this,arguments),_=(v+b)/2;l.quadraticCurveTo(0,0,w*Hn(v),w*Vn(v)),l.lineTo(y*Hn(_),y*Vn(_)),l.lineTo(w*Hn(b),w*Vn(b))}else l.quadraticCurveTo(0,0,y*Hn(v),y*Vn(v)),l.arc(0,0,y,v,b);if(l.quadraticCurveTo(0,0,p*Hn(m),p*Vn(m)),l.closePath(),c)return l=null,c+""||null}return t&&(c.headRadius=function(e){return arguments.length?(t="function"==typeof e?e:pr(+e),c):t}),c.radius=function(t){return arguments.length?(r=o="function"==typeof t?t:pr(+t),c):r},c.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:pr(+t),c):r},c.targetRadius=function(t){return arguments.length?(o="function"==typeof t?t:pr(+t),c):o},c.startAngle=function(t){return arguments.length?(i="function"==typeof t?t:pr(+t),c):i},c.endAngle=function(t){return arguments.length?(s="function"==typeof t?t:pr(+t),c):s},c.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:pr(+t),c):a},c.source=function(t){return arguments.length?(e=t,c):e},c.target=function(t){return arguments.length?(n=t,c):n},c.context=function(t){return arguments.length?(l=null==t?null:t,c):l},c}function kr(){return xr()}function qr(){return xr(_r)}var Nr=n(3456);const Sr=Math.PI/180,Ar=180/Math.PI,Mr=.96422,Tr=1,Cr=.82521,jr=4/29,Er=6/29,Or=3*Er*Er,Ir=Er*Er*Er;function Rr(t){if(t instanceof Dr)return new Dr(t.l,t.a,t.b,t.opacity);if(t instanceof Jr)return Wr(t);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e,n,r=zr(t.r),o=zr(t.g),i=zr(t.b),s=Lr((.2225045*r+.7168786*o+.0606169*i)/Tr);return r===o&&o===i?e=n=s:(e=Lr((.4360747*r+.3850649*o+.1430804*i)/Mr),n=Lr((.0139322*r+.0971045*o+.7141733*i)/Cr)),new Dr(116*s-16,500*(e-s),200*(s-n),t.opacity)}function Pr(t,e){return new Dr(t,0,0,null==e?1:e)}function Fr(t,e,n,r){return 1===arguments.length?Rr(t):new Dr(t,e,n,null==r?1:r)}function Dr(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function Lr(t){return t>Ir?Math.pow(t,1/3):t/Or+jr}function $r(t){return t>Er?t*t*t:Or*(t-jr)}function Zr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function zr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ur(t){if(t instanceof Jr)return new Jr(t.h,t.c,t.l,t.opacity);if(t instanceof Dr||(t=Rr(t)),0===t.a&&0===t.b)return new Jr(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);var e=Math.atan2(t.b,t.a)*Ar;return new Jr(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Br(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(n,e,t,null==r?1:r)}function Gr(t,e,n,r){return 1===arguments.length?Ur(t):new Jr(t,e,n,null==r?1:r)}function Jr(t,e,n,r){this.h=+t,this.c=+e,this.l=+n,this.opacity=+r}function Wr(t){if(isNaN(t.h))return new Dr(t.l,0,0,t.opacity);var e=t.h*Sr;return new Dr(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}(0,Nr.Z)(Dr,Fr,(0,Nr.l)($e.Il,{brighter(t){return new Dr(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker(t){return new Dr(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,n=isNaN(this.b)?t:t-this.b/200;return e=Mr*$r(e),t=Tr*$r(t),n=Cr*$r(n),new $e.Ss(Zr(3.1338561*e-1.6168667*t-.4906146*n),Zr(-.9787684*e+1.9161415*t+.033454*n),Zr(.0719453*e-.2289914*t+1.4052427*n),this.opacity)}})),(0,Nr.Z)(Jr,Gr,(0,Nr.l)($e.Il,{brighter(t){return new Jr(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker(t){return new Jr(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb(){return Wr(this).rgb()}}));var Hr=-.14861,Vr=1.78277,Yr=-.29227,Kr=-.90649,Xr=1.97294,Qr=Xr*Kr,to=Xr*Vr,eo=Vr*Yr-Kr*Hr;function no(t,e,n,r){return 1===arguments.length?function(t){if(t instanceof ro)return new ro(t.h,t.s,t.l,t.opacity);t instanceof $e.Ss||(t=(0,$e.SU)(t));var e=t.r/255,n=t.g/255,r=t.b/255,o=(eo*r+Qr*e-to*n)/(eo+Qr-to),i=r-o,s=(Xr*(n-o)-Yr*i)/Kr,a=Math.sqrt(s*s+i*i)/(Xr*o*(1-o)),l=a?Math.atan2(s,i)*Ar-120:NaN;return new ro(l<0?l+360:l,a,o,t.opacity)}(t):new ro(t,e,n,null==r?1:r)}function ro(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}(0,Nr.Z)(ro,no,(0,Nr.l)($e.Il,{brighter(t){return t=null==t?$e.J5:Math.pow($e.J5,t),new ro(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?$e.xV:Math.pow($e.xV,t),new ro(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=isNaN(this.h)?0:(this.h+120)*Sr,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),o=Math.sin(t);return new $e.Ss(255*(e+n*(Hr*r+Vr*o)),255*(e+n*(Yr*r+Kr*o)),255*(e+n*(Xr*r)),this.opacity)}}));var oo=n(2327),io=n(2038),so=n(6106),ao=Array.prototype.slice;function lo(t,e){return t-e}const co=t=>()=>t;function uo(t,e){for(var n,r=-1,o=e.length;++r<o;)if(n=fo(t,e[r]))return n;return 0}function fo(t,e){for(var n=e[0],r=e[1],o=-1,i=0,s=t.length,a=s-1;i<s;a=i++){var l=t[i],c=l[0],u=l[1],f=t[a],d=f[0],h=f[1];if(ho(l,f,e))return 0;u>r!=h>r&&n<(d-c)*(r-u)/(h-u)+c&&(o=-o)}return o}function ho(t,e,n){var r,o,i,s;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(o=t[r=+(t[0]===e[0])],i=n[r],s=e[r],o<=i&&i<=s||s<=i&&i<=o)}function po(){}var mo=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function go(){var t=1,e=1,n=oo.Z,r=a;function o(t){var e=n(t);if(Array.isArray(e))e=e.slice().sort(lo);else{const n=(0,io.Z)(t),r=(0,so.ly)(n[0],n[1],e);e=(0,so.ZP)(Math.floor(n[0]/r)*r,Math.floor(n[1]/r-1)*r,e)}return e.map((e=>i(t,e)))}function i(n,o){var i=[],a=[];return function(n,r,o){var i,a,l,c,u,f,d=new Array,h=new Array;i=a=-1,c=n[0]>=r,mo[c<<1].forEach(p);for(;++i<t-1;)l=c,c=n[i+1]>=r,mo[l|c<<1].forEach(p);mo[c<<0].forEach(p);for(;++a<e-1;){for(i=-1,c=n[a*t+t]>=r,u=n[a*t]>=r,mo[c<<1|u<<2].forEach(p);++i<t-1;)l=c,c=n[a*t+t+i+1]>=r,f=u,u=n[a*t+i+1]>=r,mo[l|c<<1|u<<2|f<<3].forEach(p);mo[c|u<<3].forEach(p)}i=-1,u=n[a*t]>=r,mo[u<<2].forEach(p);for(;++i<t-1;)f=u,u=n[a*t+i+1]>=r,mo[u<<2|f<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+i,t[0][1]+a],l=[t[1][0]+i,t[1][1]+a],c=s(r),u=s(l);(e=h[c])?(n=d[u])?(delete h[e.end],delete d[n.start],e===n?(e.ring.push(l),o(e.ring)):d[e.start]=h[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[e.end],e.ring.push(l),h[e.end=u]=e):(e=d[u])?(n=h[c])?(delete d[e.start],delete h[n.end],e===n?(e.ring.push(l),o(e.ring)):d[n.start]=h[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[e.start],e.ring.unshift(r),d[e.start=c]=e):d[c]=h[u]={start:c,end:u,ring:[r,l]}}mo[u<<3].forEach(p)}(n,o,(function(t){r(t,n,o),function(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++e<n;)r+=t[e-1][1]*t[e][0]-t[e-1][0]*t[e][1];return r}(t)>0?i.push([t]):a.push(t)})),a.forEach((function(t){for(var e,n=0,r=i.length;n<r;++n)if(-1!==uo((e=i[n])[0],t))return void e.push(t)})),{type:"MultiPolygon",value:o,coordinates:i}}function s(e){return 2*e[0]+e[1]*(t+1)*4}function a(n,r,o){n.forEach((function(n){var i,s=n[0],a=n[1],l=0|s,c=0|a,u=r[c*t+l];s>0&&s<t&&l===s&&(i=r[c*t+l-1],n[0]=s+(o-i)/(u-i)-.5),a>0&&a<e&&c===a&&(i=r[(c-1)*t+l],n[1]=a+(o-i)/(u-i)-.5)}))}return o.contour=i,o.size=function(n){if(!arguments.length)return[t,e];var r=Math.floor(n[0]),i=Math.floor(n[1]);if(!(r>=0&&i>=0))throw new Error("invalid size");return t=r,e=i,o},o.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?co(ao.call(t)):co(t),o):n},o.smooth=function(t){return arguments.length?(r=t?a:po,o):r===a},o}var yo=n(1045),vo=n(8319);function bo(t){return t[0]}function wo(t){return t[1]}function _o(){return 1}function xo(){var t=bo,e=wo,n=_o,r=960,o=500,i=20,s=2,a=3*i,l=r+2*a>>s,c=o+2*a>>s,u=co(20);function f(r){var o=new Float32Array(l*c),u=Math.pow(2,-s),f=-1;for(const i of r){var d=(t(i,++f,r)+a)*u,h=(e(i,f,r)+a)*u,p=+n(i,f,r);if(d>=0&&d<l&&h>=0&&h<c){var m=Math.floor(d),g=Math.floor(h),y=d-m-.5,v=h-g-.5;o[m+g*l]+=(1-y)*(1-v)*p,o[m+1+g*l]+=y*(1-v)*p,o[m+1+(g+1)*l]+=y*v*p,o[m+(g+1)*l]+=(1-y)*v*p}}return(0,yo.u8)({data:o,width:l,height:c},i*u),o}function d(t){var e=f(t),n=u(e),r=Math.pow(2,2*s);return Array.isArray(n)||(n=(0,so.ZP)(Number.MIN_VALUE,(0,vo.Z)(e)/r,n)),go().size([l,c]).thresholds(n.map((t=>t*r)))(e).map(((t,e)=>(t.value=+n[e],h(t))))}function h(t){return t.coordinates.forEach(p),t}function p(t){t.forEach(m)}function m(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,s)-a,t[1]=t[1]*Math.pow(2,s)-a}function y(){return l=r+2*(a=3*i)>>s,c=o+2*a>>s,d}return d.contours=function(t){var e=f(t),n=go().size([l,c]),r=Math.pow(2,2*s),o=t=>{t=+t;var o=h(n.contour(e,t*r));return o.value=t,o};return Object.defineProperty(o,"max",{get:()=>(0,vo.Z)(e)/r}),o},d.x=function(e){return arguments.length?(t="function"==typeof e?e:co(+e),d):t},d.y=function(t){return arguments.length?(e="function"==typeof t?t:co(+t),d):e},d.weight=function(t){return arguments.length?(n="function"==typeof t?t:co(+t),d):n},d.size=function(t){if(!arguments.length)return[r,o];var e=+t[0],n=+t[1];if(!(e>=0&&n>=0))throw new Error("invalid size");return r=e,o=n,y()},d.cellSize=function(t){if(!arguments.length)return 1<<s;if(!((t=+t)>=1))throw new Error("invalid cell size");return s=Math.floor(Math.log(t)/Math.LN2),y()},d.thresholds=function(t){return arguments.length?(u="function"==typeof t?t:Array.isArray(t)?co(ao.call(t)):co(t),d):u},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(i*(i+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return i=(Math.sqrt(4*t*t+1)-1)/2,y()},d}const ko=134217729,qo=33306690738754706e-32;function No(t,e,n,r,o){let i,s,a,l,c=e[0],u=r[0],f=0,d=0;u>c==u>-c?(i=c,c=e[++f]):(i=u,u=r[++d]);let h=0;if(f<t&&d<n)for(u>c==u>-c?(s=c+i,a=i-(s-c),c=e[++f]):(s=u+i,a=i-(s-u),u=r[++d]),i=s,0!==a&&(o[h++]=a);f<t&&d<n;)u>c==u>-c?(s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++f]):(s=i+u,l=s-i,a=i-(s-l)+(u-l),u=r[++d]),i=s,0!==a&&(o[h++]=a);for(;f<t;)s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++f],i=s,0!==a&&(o[h++]=a);for(;d<n;)s=i+u,l=s-i,a=i-(s-l)+(u-l),u=r[++d],i=s,0!==a&&(o[h++]=a);return 0===i&&0!==h||(o[h++]=i),h}function So(t){return new Float64Array(t)}const Ao=22204460492503146e-32,Mo=11093356479670487e-47,To=So(4),Co=So(8),jo=So(12),Eo=So(16),Oo=So(4);function Io(t,e,n,r,o,i){const s=(e-i)*(n-o),a=(t-o)*(r-i),l=s-a;if(0===s||0===a||s>0!=a>0)return l;const c=Math.abs(s+a);return Math.abs(l)>=33306690738754716e-32*c?l:-function(t,e,n,r,o,i,s){let a,l,c,u,f,d,h,p,m,g,y,v,b,w,_,x,k,q;const N=t-o,S=n-o,A=e-i,M=r-i;w=N*M,d=ko*N,h=d-(d-N),p=N-h,d=ko*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=A*S,d=ko*A,h=d-(d-A),p=A-h,d=ko*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,To[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,To[1]=b-(y+f)+(f-x),q=v+y,f=q-v,To[2]=v-(q-f)+(y-f),To[3]=q;let T=function(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}(4,To),C=Ao*s;if(T>=C||-T>=C)return T;if(f=t-N,a=t-(N+f)+(f-o),f=n-S,c=n-(S+f)+(f-o),f=e-A,l=e-(A+f)+(f-i),f=r-M,u=r-(M+f)+(f-i),0===a&&0===l&&0===c&&0===u)return T;if(C=Mo*s+qo*Math.abs(T),T+=N*u+M*a-(A*c+S*l),T>=C||-T>=C)return T;w=a*M,d=ko*a,h=d-(d-a),p=a-h,d=ko*M,m=d-(d-M),g=M-m,_=p*g-(w-h*m-p*m-h*g),x=l*S,d=ko*l,h=d-(d-l),p=l-h,d=ko*S,m=d-(d-S),g=S-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const j=No(4,To,4,Oo,Co);w=N*u,d=ko*N,h=d-(d-N),p=N-h,d=ko*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=A*c,d=ko*A,h=d-(d-A),p=A-h,d=ko*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const E=No(j,Co,4,Oo,jo);w=a*u,d=ko*a,h=d-(d-a),p=a-h,d=ko*u,m=d-(d-u),g=u-m,_=p*g-(w-h*m-p*m-h*g),x=l*c,d=ko*l,h=d-(d-l),p=l-h,d=ko*c,m=d-(d-c),g=c-m,k=p*g-(x-h*m-p*m-h*g),y=_-k,f=_-y,Oo[0]=_-(y+f)+(f-k),v=w+y,f=v-w,b=w-(v-f)+(y-f),y=b-x,f=b-y,Oo[1]=b-(y+f)+(f-x),q=v+y,f=q-v,Oo[2]=v-(q-f)+(y-f),Oo[3]=q;const O=No(E,jo,4,Oo,Eo);return Eo[O-1]}(t,e,n,r,o,i,c)}So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(8),So(8),So(8),So(4),So(8),So(8),So(8),So(12);So(192),So(192);So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(8),So(4),So(4),So(4),So(8),So(16),So(16),So(16),So(32),So(32),So(48),So(64);So(1152),So(1152);So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(4),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(24),So(1152),So(1152),So(1152),So(1152),So(1152),So(2304),So(2304),So(3456),So(5760),So(8),So(8),So(8),So(16),So(24),So(48),So(48),So(96),So(192),So(384),So(384),So(384),So(768);So(96),So(96),So(96),So(1152);const Ro=Math.pow(2,-52),Po=new Uint32Array(512);class Fo{static from(t,e=Uo,n=Bo){const r=t.length,o=new Float64Array(2*r);for(let i=0;i<r;i++){const r=t[i];o[2*i]=e(r),o[2*i+1]=n(r)}return new Fo(o)}constructor(t){const e=t.length>>1;if(e>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const n=Math.max(2*e-5,0);this._triangles=new Uint32Array(3*n),this._halfedges=new Int32Array(3*n),this._hashSize=Math.ceil(Math.sqrt(e)),this._hullPrev=new Uint32Array(e),this._hullNext=new Uint32Array(e),this._hullTri=new Uint32Array(e),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(e),this._dists=new Float64Array(e),this.update()}update(){const{coords:t,_hullPrev:e,_hullNext:n,_hullTri:r,_hullHash:o}=this,i=t.length>>1;let s=1/0,a=1/0,l=-1/0,c=-1/0;for(let e=0;e<i;e++){const n=t[2*e],r=t[2*e+1];n<s&&(s=n),r<a&&(a=r),n>l&&(l=n),r>c&&(c=r),this._ids[e]=e}const u=(s+l)/2,f=(a+c)/2;let d,h,p,m=1/0;for(let e=0;e<i;e++){const n=Do(u,f,t[2*e],t[2*e+1]);n<m&&(d=e,m=n)}const g=t[2*d],y=t[2*d+1];m=1/0;for(let e=0;e<i;e++){if(e===d)continue;const n=Do(g,y,t[2*e],t[2*e+1]);n<m&&n>0&&(h=e,m=n)}let v=t[2*h],b=t[2*h+1],w=1/0;for(let e=0;e<i;e++){if(e===d||e===h)continue;const n=$o(g,y,v,b,t[2*e],t[2*e+1]);n<w&&(p=e,w=n)}let _=t[2*p],x=t[2*p+1];if(w===1/0){for(let e=0;e<i;e++)this._dists[e]=t[2*e]-t[0]||t[2*e+1]-t[1];Zo(this._ids,this._dists,0,i-1);const e=new Uint32Array(i);let n=0;for(let t=0,r=-1/0;t<i;t++){const o=this._ids[t];this._dists[o]>r&&(e[n++]=o,r=this._dists[o])}return this.hull=e.subarray(0,n),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Io(g,y,v,b,_,x)<0){const t=h,e=v,n=b;h=p,v=_,b=x,p=t,_=e,x=n}const k=function(t,e,n,r,o,i){const s=n-t,a=r-e,l=o-t,c=i-e,u=s*s+a*a,f=l*l+c*c,d=.5/(s*c-a*l),h=t+(c*u-a*f)*d,p=e+(s*f-l*u)*d;return{x:h,y:p}}(g,y,v,b,_,x);this._cx=k.x,this._cy=k.y;for(let e=0;e<i;e++)this._dists[e]=Do(t[2*e],t[2*e+1],k.x,k.y);Zo(this._ids,this._dists,0,i-1),this._hullStart=d;let q=3;n[d]=e[p]=h,n[h]=e[d]=p,n[p]=e[h]=d,r[d]=0,r[h]=1,r[p]=2,o.fill(-1),o[this._hashKey(g,y)]=d,o[this._hashKey(v,b)]=h,o[this._hashKey(_,x)]=p,this.trianglesLen=0,this._addTriangle(d,h,p,-1,-1,-1);for(let i,s,a=0;a<this._ids.length;a++){const l=this._ids[a],c=t[2*l],u=t[2*l+1];if(a>0&&Math.abs(c-i)<=Ro&&Math.abs(u-s)<=Ro)continue;if(i=c,s=u,l===d||l===h||l===p)continue;let f=0;for(let t=0,e=this._hashKey(c,u);t<this._hashSize&&(f=o[(e+t)%this._hashSize],-1===f||f===n[f]);t++);f=e[f];let m,g=f;for(;m=n[g],Io(c,u,t[2*g],t[2*g+1],t[2*m],t[2*m+1])>=0;)if(g=m,g===f){g=-1;break}if(-1===g)continue;let y=this._addTriangle(g,l,n[g],-1,-1,r[g]);r[l]=this._legalize(y+2),r[g]=y,q++;let v=n[g];for(;m=n[v],Io(c,u,t[2*v],t[2*v+1],t[2*m],t[2*m+1])<0;)y=this._addTriangle(v,l,m,r[l],-1,r[v]),r[l]=this._legalize(y+2),n[v]=v,q--,v=m;if(g===f)for(;m=e[g],Io(c,u,t[2*m],t[2*m+1],t[2*g],t[2*g+1])<0;)y=this._addTriangle(m,l,g,-1,r[g],r[m]),this._legalize(y+2),r[m]=y,n[g]=g,q--,g=m;this._hullStart=e[l]=g,n[g]=e[v]=l,n[l]=v,o[this._hashKey(c,u)]=l,o[this._hashKey(t[2*g],t[2*g+1])]=g}this.hull=new Uint32Array(q);for(let t=0,e=this._hullStart;t<q;t++)this.hull[t]=e,e=n[e];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(t,e){return Math.floor(function(t,e){const n=t/(Math.abs(t)+Math.abs(e));return(e>0?3-n:1+n)/4}(t-this._cx,e-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:e,_halfedges:n,coords:r}=this;let o=0,i=0;for(;;){const s=n[t],a=t-t%3;if(i=a+(t+2)%3,-1===s){if(0===o)break;t=Po[--o];continue}const l=s-s%3,c=a+(t+1)%3,u=l+(s+2)%3,f=e[i],d=e[t],h=e[c],p=e[u];if(Lo(r[2*f],r[2*f+1],r[2*d],r[2*d+1],r[2*h],r[2*h+1],r[2*p],r[2*p+1])){e[t]=p,e[s]=f;const r=n[u];if(-1===r){let e=this._hullStart;do{if(this._hullTri[e]===u){this._hullTri[e]=t;break}e=this._hullPrev[e]}while(e!==this._hullStart)}this._link(t,r),this._link(s,n[i]),this._link(i,u);const a=l+(s+1)%3;o<Po.length&&(Po[o++]=a)}else{if(0===o)break;t=Po[--o]}}return i}_link(t,e){this._halfedges[t]=e,-1!==e&&(this._halfedges[e]=t)}_addTriangle(t,e,n,r,o,i){const s=this.trianglesLen;return this._triangles[s]=t,this._triangles[s+1]=e,this._triangles[s+2]=n,this._link(s,r),this._link(s+1,o),this._link(s+2,i),this.trianglesLen+=3,s}}function Do(t,e,n,r){const o=t-n,i=e-r;return o*o+i*i}function Lo(t,e,n,r,o,i,s,a){const l=t-s,c=e-a,u=n-s,f=r-a,d=o-s,h=i-a,p=u*u+f*f,m=d*d+h*h;return l*(f*m-p*h)-c*(u*m-p*d)+(l*l+c*c)*(u*h-f*d)<0}function $o(t,e,n,r,o,i){const s=n-t,a=r-e,l=o-t,c=i-e,u=s*s+a*a,f=l*l+c*c,d=.5/(s*c-a*l),h=(c*u-a*f)*d,p=(s*f-l*u)*d;return h*h+p*p}function Zo(t,e,n,r){if(r-n<=20)for(let o=n+1;o<=r;o++){const r=t[o],i=e[r];let s=o-1;for(;s>=n&&e[t[s]]>i;)t[s+1]=t[s--];t[s+1]=r}else{let o=n+1,i=r;zo(t,n+r>>1,o),e[t[n]]>e[t[r]]&&zo(t,n,r),e[t[o]]>e[t[r]]&&zo(t,o,r),e[t[n]]>e[t[o]]&&zo(t,n,o);const s=t[o],a=e[s];for(;;){do{o++}while(e[t[o]]<a);do{i--}while(e[t[i]]>a);if(i<o)break;zo(t,o,i)}t[n+1]=t[i],t[i]=s,r-o+1>=i-n?(Zo(t,e,o,r),Zo(t,e,n,i-1)):(Zo(t,e,n,i-1),Zo(t,e,o,r))}}function zo(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function Uo(t){return t[0]}function Bo(t){return t[1]}const Go=1e-6;class Jo{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,e){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,e){this._+=`L${this._x1=+t},${this._y1=+e}`}arc(t,e,n){const r=(t=+t)+(n=+n),o=e=+e;if(n<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${o}`:(Math.abs(this._x1-r)>Go||Math.abs(this._y1-o)>Go)&&(this._+="L"+r+","+o),n&&(this._+=`A${n},${n},0,1,1,${t-n},${e}A${n},${n},0,1,1,${this._x1=r},${this._y1=o}`)}rect(t,e,n,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${+n}v${+r}h${-n}Z`}value(){return this._||null}}class Wo{constructor(){this._=[]}moveTo(t,e){this._.push([t,e])}closePath(){this._.push(this._[0].slice())}lineTo(t,e){this._.push([t,e])}value(){return this._.length?this._:null}}class Ho{constructor(t,[e,n,r,o]=[0,0,960,500]){if(!((r=+r)>=(e=+e)&&(o=+o)>=(n=+n)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=e,this.ymax=o,this.ymin=n,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:e,triangles:n},vectors:r}=this,o=this.circumcenters=this._circumcenters.subarray(0,n.length/3*2);for(let e,r,i=0,s=0,a=n.length;i<a;i+=3,s+=2){const a=2*n[i],l=2*n[i+1],c=2*n[i+2],u=t[a],f=t[a+1],d=t[l],h=t[l+1],p=t[c],m=t[c+1],g=d-u,y=h-f,v=p-u,b=m-f,w=2*(g*b-y*v);if(Math.abs(w)<1e-9){let o=1e9;const i=2*n[0];o*=Math.sign((t[i]-u)*b-(t[i+1]-f)*v),e=(u+p)/2-o*b,r=(f+m)/2+o*v}else{const t=1/w,n=g*g+y*y,o=v*v+b*b;e=u+(b*n-y*o)*t,r=f+(g*o-v*n)*t}o[s]=e,o[s+1]=r}let i,s,a,l=e[e.length-1],c=4*l,u=t[2*l],f=t[2*l+1];r.fill(0);for(let n=0;n<e.length;++n)l=e[n],i=c,s=u,a=f,c=4*l,u=t[2*l],f=t[2*l+1],r[i+2]=r[c]=a-f,r[i+3]=r[c+1]=u-s}render(t){const e=null==t?t=new Jo:void 0,{delaunay:{halfedges:n,inedges:r,hull:o},circumcenters:i,vectors:s}=this;if(o.length<=1)return null;for(let e=0,r=n.length;e<r;++e){const r=n[e];if(r<e)continue;const o=2*Math.floor(e/3),s=2*Math.floor(r/3),a=i[o],l=i[o+1],c=i[s],u=i[s+1];this._renderSegment(a,l,c,u,t)}let a,l=o[o.length-1];for(let e=0;e<o.length;++e){a=l,l=o[e];const n=2*Math.floor(r[l]/3),c=i[n],u=i[n+1],f=4*a,d=this._project(c,u,s[f+2],s[f+3]);d&&this._renderSegment(c,u,d[0],d[1],t)}return e&&e.value()}renderBounds(t){const e=null==t?t=new Jo:void 0;return t.rect(this.xmin,this.ymin,this.xmax-this.xmin,this.ymax-this.ymin),e&&e.value()}renderCell(t,e){const n=null==e?e=new Jo:void 0,r=this._clip(t);if(null===r||!r.length)return;e.moveTo(r[0],r[1]);let o=r.length;for(;r[0]===r[o-2]&&r[1]===r[o-1]&&o>1;)o-=2;for(let t=2;t<o;t+=2)r[t]===r[t-2]&&r[t+1]===r[t-1]||e.lineTo(r[t],r[t+1]);return e.closePath(),n&&n.value()}*cellPolygons(){const{delaunay:{points:t}}=this;for(let e=0,n=t.length/2;e<n;++e){const t=this.cellPolygon(e);t&&(t.index=e,yield t)}}cellPolygon(t){const e=new Wo;return this.renderCell(t,e),e.value()}_renderSegment(t,e,n,r,o){let i;const s=this._regioncode(t,e),a=this._regioncode(n,r);0===s&&0===a?(o.moveTo(t,e),o.lineTo(n,r)):(i=this._clipSegment(t,e,n,r,s,a))&&(o.moveTo(i[0],i[1]),o.lineTo(i[2],i[3]))}contains(t,e,n){return(e=+e)==e&&(n=+n)==n&&this.delaunay._step(t,e,n)===t}*neighbors(t){const e=this._clip(t);if(e)for(const n of this.delaunay.neighbors(t)){const t=this._clip(n);if(t)t:for(let r=0,o=e.length;r<o;r+=2)for(let i=0,s=t.length;i<s;i+=2)if(e[r]==t[i]&&e[r+1]==t[i+1]&&e[(r+2)%o]==t[(i+s-2)%s]&&e[(r+3)%o]==t[(i+s-1)%s]){yield n;break t}}}_cell(t){const{circumcenters:e,delaunay:{inedges:n,halfedges:r,triangles:o}}=this,i=n[t];if(-1===i)return null;const s=[];let a=i;do{const n=Math.floor(a/3);if(s.push(e[2*n],e[2*n+1]),a=a%3==2?a-2:a+1,o[a]!==t)break;a=r[a]}while(a!==i&&-1!==a);return s}_clip(t){if(0===t&&1===this.delaunay.hull.length)return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];const e=this._cell(t);if(null===e)return null;const{vectors:n}=this,r=4*t;return n[r]||n[r+1]?this._clipInfinite(t,e,n[r],n[r+1],n[r+2],n[r+3]):this._clipFinite(t,e)}_clipFinite(t,e){const n=e.length;let r,o,i,s,a=null,l=e[n-2],c=e[n-1],u=this._regioncode(l,c),f=0;for(let d=0;d<n;d+=2)if(r=l,o=c,l=e[d],c=e[d+1],i=u,u=this._regioncode(l,c),0===i&&0===u)s=f,f=0,a?a.push(l,c):a=[l,c];else{let e,n,d,h,p;if(0===i){if(null===(e=this._clipSegment(r,o,l,c,i,u)))continue;[n,d,h,p]=e}else{if(null===(e=this._clipSegment(l,c,r,o,u,i)))continue;[h,p,n,d]=e,s=f,f=this._edgecode(n,d),s&&f&&this._edge(t,s,f,a,a.length),a?a.push(n,d):a=[n,d]}s=f,f=this._edgecode(h,p),s&&f&&this._edge(t,s,f,a,a.length),a?a.push(h,p):a=[h,p]}if(a)s=f,f=this._edgecode(a[0],a[1]),s&&f&&this._edge(t,s,f,a,a.length);else if(this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2))return[this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];return a}_clipSegment(t,e,n,r,o,i){for(;;){if(0===o&&0===i)return[t,e,n,r];if(o&i)return null;let s,a,l=o||i;8&l?(s=t+(n-t)*(this.ymax-e)/(r-e),a=this.ymax):4&l?(s=t+(n-t)*(this.ymin-e)/(r-e),a=this.ymin):2&l?(a=e+(r-e)*(this.xmax-t)/(n-t),s=this.xmax):(a=e+(r-e)*(this.xmin-t)/(n-t),s=this.xmin),o?(t=s,e=a,o=this._regioncode(t,e)):(n=s,r=a,i=this._regioncode(n,r))}}_clipInfinite(t,e,n,r,o,i){let s,a=Array.from(e);if((s=this._project(a[0],a[1],n,r))&&a.unshift(s[0],s[1]),(s=this._project(a[a.length-2],a[a.length-1],o,i))&&a.push(s[0],s[1]),a=this._clipFinite(t,a))for(let e,n=0,r=a.length,o=this._edgecode(a[r-2],a[r-1]);n<r;n+=2)e=o,o=this._edgecode(a[n],a[n+1]),e&&o&&(n=this._edge(t,e,o,a,n),r=a.length);else this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)&&(a=[this.xmin,this.ymin,this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax]);return a}_edge(t,e,n,r,o){for(;e!==n;){let n,i;switch(e){case 5:e=4;continue;case 4:e=6,n=this.xmax,i=this.ymin;break;case 6:e=2;continue;case 2:e=10,n=this.xmax,i=this.ymax;break;case 10:e=8;continue;case 8:e=9,n=this.xmin,i=this.ymax;break;case 9:e=1;continue;case 1:e=5,n=this.xmin,i=this.ymin}r[o]===n&&r[o+1]===i||!this.contains(t,n,i)||(r.splice(o,0,n,i),o+=2)}if(r.length>4)for(let t=0;t<r.length;t+=2){const e=(t+2)%r.length,n=(t+4)%r.length;(r[t]===r[e]&&r[e]===r[n]||r[t+1]===r[e+1]&&r[e+1]===r[n+1])&&(r.splice(e,2),t-=2)}return o}_project(t,e,n,r){let o,i,s,a=1/0;if(r<0){if(e<=this.ymin)return null;(o=(this.ymin-e)/r)<a&&(s=this.ymin,i=t+(a=o)*n)}else if(r>0){if(e>=this.ymax)return null;(o=(this.ymax-e)/r)<a&&(s=this.ymax,i=t+(a=o)*n)}if(n>0){if(t>=this.xmax)return null;(o=(this.xmax-t)/n)<a&&(i=this.xmax,s=e+(a=o)*r)}else if(n<0){if(t<=this.xmin)return null;(o=(this.xmin-t)/n)<a&&(i=this.xmin,s=e+(a=o)*r)}return[i,s]}_edgecode(t,e){return(t===this.xmin?1:t===this.xmax?2:0)|(e===this.ymin?4:e===this.ymax?8:0)}_regioncode(t,e){return(t<this.xmin?1:t>this.xmax?2:0)|(e<this.ymin?4:e>this.ymax?8:0)}}const Vo=2*Math.PI,Yo=Math.pow;function Ko(t){return t[0]}function Xo(t){return t[1]}function Qo(t,e,n){return[t+Math.sin(t+e)*n,e+Math.cos(t-e)*n]}class ti{static from(t,e=Ko,n=Xo,r){return new ti("length"in t?function(t,e,n,r){const o=t.length,i=new Float64Array(2*o);for(let s=0;s<o;++s){const o=t[s];i[2*s]=e.call(r,o,s,t),i[2*s+1]=n.call(r,o,s,t)}return i}(t,e,n,r):Float64Array.from(function*(t,e,n,r){let o=0;for(const i of t)yield e.call(r,i,o,t),yield n.call(r,i,o,t),++o}(t,e,n,r)))}constructor(t){this._delaunator=new Fo(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init()}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,e=this.points;if(t.hull&&t.hull.length>2&&function(t){const{triangles:e,coords:n}=t;for(let t=0;t<e.length;t+=3){const r=2*e[t],o=2*e[t+1],i=2*e[t+2];if((n[i]-n[r])*(n[o+1]-n[r+1])-(n[o]-n[r])*(n[i+1]-n[r+1])>1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:e.length/2},((t,e)=>e)).sort(((t,n)=>e[2*t]-e[2*n]||e[2*t+1]-e[2*n+1]));const t=this.collinear[0],n=this.collinear[this.collinear.length-1],r=[e[2*t],e[2*t+1],e[2*n],e[2*n+1]],o=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,n=e.length/2;t<n;++t){const n=Qo(e[2*t],e[2*t+1],o);e[2*t]=n[0],e[2*t+1]=n[1]}this._delaunator=new Fo(e)}else delete this.collinear;const n=this.halfedges=this._delaunator.halfedges,r=this.hull=this._delaunator.hull,o=this.triangles=this._delaunator.triangles,i=this.inedges.fill(-1),s=this._hullIndex.fill(-1);for(let t=0,e=n.length;t<e;++t){const e=o[t%3==2?t-2:t+1];-1!==n[t]&&-1!==i[e]||(i[e]=t)}for(let t=0,e=r.length;t<e;++t)s[r[t]]=t;r.length<=2&&r.length>0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],i[r[0]]=1,2===r.length&&(i[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new Ho(this,t)}*neighbors(t){const{inedges:e,hull:n,_hullIndex:r,halfedges:o,triangles:i,collinear:s}=this;if(s){const e=s.indexOf(t);return e>0&&(yield s[e-1]),void(e<s.length-1&&(yield s[e+1]))}const a=e[t];if(-1===a)return;let l=a,c=-1;do{if(yield c=i[l],l=l%3==2?l-2:l+1,i[l]!==t)return;if(l=o[l],-1===l){const e=n[(r[t]+1)%n.length];return void(e!==c&&(yield e))}}while(l!==a)}find(t,e,n=0){if((t=+t)!=t||(e=+e)!=e)return-1;const r=n;let o;for(;(o=this._step(n,t,e))>=0&&o!==n&&o!==r;)n=o;return o}_step(t,e,n){const{inedges:r,hull:o,_hullIndex:i,halfedges:s,triangles:a,points:l}=this;if(-1===r[t]||!l.length)return(t+1)%(l.length>>1);let c=t,u=Yo(e-l[2*t],2)+Yo(n-l[2*t+1],2);const f=r[t];let d=f;do{let r=a[d];const f=Yo(e-l[2*r],2)+Yo(n-l[2*r+1],2);if(f<u&&(u=f,c=r),d=d%3==2?d-2:d+1,a[d]!==t)break;if(d=s[d],-1===d){if(d=o[(i[t]+1)%o.length],d!==r&&Yo(e-l[2*d],2)+Yo(n-l[2*d+1],2)<u)return d;break}}while(d!==f);return c}render(t){const e=null==t?t=new Jo:void 0,{points:n,halfedges:r,triangles:o}=this;for(let e=0,i=r.length;e<i;++e){const i=r[e];if(i<e)continue;const s=2*o[e],a=2*o[i];t.moveTo(n[s],n[s+1]),t.lineTo(n[a],n[a+1])}return this.renderHull(t),e&&e.value()}renderPoints(t,e){void 0!==e||t&&"function"==typeof t.moveTo||(e=t,t=null),e=null==e?2:+e;const n=null==t?t=new Jo:void 0,{points:r}=this;for(let n=0,o=r.length;n<o;n+=2){const o=r[n],i=r[n+1];t.moveTo(o+e,i),t.arc(o,i,e,0,Vo)}return n&&n.value()}renderHull(t){const e=null==t?t=new Jo:void 0,{hull:n,points:r}=this,o=2*n[0],i=n.length;t.moveTo(r[o],r[o+1]);for(let e=1;e<i;++e){const o=2*n[e];t.lineTo(r[o],r[o+1])}return t.closePath(),e&&e.value()}hullPolygon(){const t=new Wo;return this.renderHull(t),t.value()}renderTriangle(t,e){const n=null==e?e=new Jo:void 0,{points:r,triangles:o}=this,i=2*o[t*=3],s=2*o[t+1],a=2*o[t+2];return e.moveTo(r[i],r[i+1]),e.lineTo(r[s],r[s+1]),e.lineTo(r[a],r[a+1]),e.closePath(),n&&n.value()}*trianglePolygons(){const{triangles:t}=this;for(let e=0,n=t.length/3;e<n;++e)yield this.trianglePolygon(e)}trianglePolygon(t){const e=new Wo;return this.renderTriangle(t,e),e.value()}}const ei=t=>()=>t;function ni(t,{sourceEvent:e,subject:n,target:r,identifier:o,active:i,x:s,y:a,dx:l,dy:c,dispatch:u}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:i,enumerable:!0,configurable:!0},x:{value:s,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:u}})}function ri(t){return!t.ctrlKey&&!t.button}function oi(){return this.parentNode}function ii(t,e){return null==e?{x:t.x,y:t.y}:e}function si(){return navigator.maxTouchPoints||"ontouchstart"in this}function ai(){var t,e,n,r,o=ri,i=oi,s=ii,a=si,l={},c=N("start","drag","end"),u=0,f=0;function d(t){t.on("mousedown.drag",h).filter(a).on("touchstart.drag",g).on("touchmove.drag",y,$t).on("touchend.drag touchcancel.drag",v).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(s,a){if(!r&&o.call(this,s,a)){var l=b(this,i.call(this,s,a),s,a,"mouse");l&&(Lt(s.view).on("mousemove.drag",p,Zt).on("mouseup.drag",m,Zt),Bt(s.view),zt(s),n=!1,t=s.clientX,e=s.clientY,l("start",s))}}function p(r){if(Ut(r),!n){var o=r.clientX-t,i=r.clientY-e;n=o*o+i*i>f}l.mouse("drag",r)}function m(t){Lt(t.view).on("mousemove.drag mouseup.drag",null),Gt(t.view,n),Ut(t),l.mouse("end",t)}function g(t,e){if(o.call(this,t,e)){var n,r,s=t.changedTouches,a=i.call(this,t,e),l=s.length;for(n=0;n<l;++n)(r=b(this,a,t,e,s[n].identifier,s[n]))&&(zt(t),r("start",t,s[n]))}}function y(t){var e,n,r=t.changedTouches,o=r.length;for(e=0;e<o;++e)(n=l[r[e].identifier])&&(Ut(t),n("drag",t,r[e]))}function v(t){var e,n,o=t.changedTouches,i=o.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null}),500),e=0;e<i;++e)(n=l[o[e].identifier])&&(zt(t),n("end",t,o[e]))}function b(t,e,n,r,o,i){var a,f,h,p=c.copy(),m=Ht(i||n,e);if(null!=(h=s.call(t,new ni("beforestart",{sourceEvent:n,target:d,identifier:o,active:u,x:m[0],y:m[1],dx:0,dy:0,dispatch:p}),r)))return a=h.x-m[0]||0,f=h.y-m[1]||0,function n(i,s,c){var g,y=m;switch(i){case"start":l[o]=n,g=u++;break;case"end":delete l[o],--u;case"drag":m=Ht(c||s,e),g=u}p.call(i,t,new ni(i,{sourceEvent:s,subject:h,target:d,identifier:o,active:g,x:m[0]+a,y:m[1]+f,dx:m[0]-y[0],dy:m[1]-y[1],dispatch:p}),r)}}return d.filter=function(t){return arguments.length?(o="function"==typeof t?t:ei(!!t),d):o},d.container=function(t){return arguments.length?(i="function"==typeof t?t:ei(t),d):i},d.subject=function(t){return arguments.length?(s="function"==typeof t?t:ei(t),d):s},d.touchable=function(t){return arguments.length?(a="function"==typeof t?t:ei(!!t),d):a},d.on=function(){var t=c.on.apply(c,arguments);return t===c?d:t},d.clickDistance=function(t){return arguments.length?(f=(t=+t)*t,d):Math.sqrt(f)},d}ni.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var li=n(4476),ci=(0,li.Z)(","),ui=ci.parse,fi=ci.parseRows,di=ci.format,hi=ci.formatBody,pi=ci.formatRows,mi=ci.formatRow,gi=ci.formatValue,yi=n(5026);function vi(t){for(var e in t){var n,r,o=t[e].trim();if(o)if("true"===o)o=!0;else if("false"===o)o=!1;else if("NaN"===o)o=NaN;else if(isNaN(n=+o)){if(!(r=o.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;bi&&r[4]&&!r[7]&&(o=o.replace(/-/g,"/").replace(/T/," ")),o=new Date(o)}else o=n;else o=null;t[e]=o}return t}const bi=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours(),wi=t=>+t;function _i(t){return t*t}function xi(t){return t*(2-t)}function ki(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}var qi=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),Ni=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),Si=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3),Ai=Math.PI,Mi=Ai/2;function Ti(t){return 1==+t?1:1-Math.cos(t*Mi)}function Ci(t){return Math.sin(t*Mi)}function ji(t){return(1-Math.cos(Ai*t))/2}function Ei(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function Oi(t){return Ei(1-+t)}function Ii(t){return 1-Ei(t)}function Ri(t){return((t*=2)<=1?Ei(1-t):2-Ei(t-1))/2}function Pi(t){return 1-Math.sqrt(1-t*t)}function Fi(t){return Math.sqrt(1- --t*t)}function Di(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var Li=4/11,$i=6/11,Zi=8/11,zi=3/4,Ui=9/11,Bi=10/11,Gi=15/16,Ji=21/22,Wi=63/64,Hi=1/Li/Li;function Vi(t){return 1-Yi(1-t)}function Yi(t){return(t=+t)<Li?Hi*t*t:t<Zi?Hi*(t-=$i)*t+zi:t<Bi?Hi*(t-=Ui)*t+Gi:Hi*(t-=Ji)*t+Wi}function Ki(t){return((t*=2)<=1?1-Yi(1-t):Yi(t-1)+1)/2}var Xi=1.70158,Qi=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(Xi),ts=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(Xi),es=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(Xi),ns=2*Math.PI,rs=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return e*Ei(- --t)*Math.sin((r-t)/n)}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3),os=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return 1-e*Ei(t=+t)*Math.sin((t+r)/n)}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3),is=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=ns);function o(t){return((t=2*t-1)<0?e*Ei(-t)*Math.sin((r-t)/n):2-e*Ei(t)*Math.sin((r+t)/n))/2}return o.amplitude=function(e){return t(e,n*ns)},o.period=function(n){return t(e,n)},o}(1,.3);function ss(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function as(t,e){return fetch(t,e).then(ss)}function ls(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function cs(t,e){return fetch(t,e).then(ls)}function us(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function fs(t,e){return fetch(t,e).then(us)}function ds(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),fs(e,n).then((function(e){return t(e,r)}))}}function hs(t,e,n,r){3===arguments.length&&"function"==typeof n&&(r=n,n=void 0);var o=(0,li.Z)(t);return fs(e,n).then((function(t){return o.parse(t,r)}))}var ps=ds(ui),ms=ds(yi.tJ);function gs(t,e){return new Promise((function(n,r){var o=new Image;for(var i in e)o[i]=e[i];o.onerror=r,o.onload=function(){n(o)},o.src=t}))}function ys(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function vs(t,e){return fetch(t,e).then(ys)}function bs(t){return(e,n)=>fs(e,n).then((e=>(new DOMParser).parseFromString(e,t)))}const ws=bs("application/xml");var _s=bs("text/html"),xs=bs("image/svg+xml");function ks(t,e){var n,r=1;function o(){var o,i,s=n.length,a=0,l=0;for(o=0;o<s;++o)a+=(i=n[o]).x,l+=i.y;for(a=(a/s-t)*r,l=(l/s-e)*r,o=0;o<s;++o)(i=n[o]).x-=a,i.y-=l}return null==t&&(t=0),null==e&&(e=0),o.initialize=function(t){n=t},o.x=function(e){return arguments.length?(t=+e,o):t},o.y=function(t){return arguments.length?(e=+t,o):e},o.strength=function(t){return arguments.length?(r=+t,o):r},o}function qs(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var o,i,s,a,l,c,u,f,d,h=t._root,p={data:r},m=t._x0,g=t._y0,y=t._x1,v=t._y1;if(!h)return t._root=p,t;for(;h.length;)if((c=e>=(i=(m+y)/2))?m=i:y=i,(u=n>=(s=(g+v)/2))?g=s:v=s,o=h,!(h=h[f=u<<1|c]))return o[f]=p,t;if(a=+t._x.call(null,h.data),l=+t._y.call(null,h.data),e===a&&n===l)return p.next=h,o?o[f]=p:t._root=p,t;do{o=o?o[f]=new Array(4):t._root=new Array(4),(c=e>=(i=(m+y)/2))?m=i:y=i,(u=n>=(s=(g+v)/2))?g=s:v=s}while((f=u<<1|c)==(d=(l>=s)<<1|a>=i));return o[d]=h,o[f]=p,t}function Ns(t,e,n,r,o){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=o}function Ss(t){return t[0]}function As(t){return t[1]}function Ms(t,e,n){var r=new Ts(null==e?Ss:e,null==n?As:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Ts(t,e,n,r,o,i){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=o,this._y1=i,this._root=void 0}function Cs(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var js=Ms.prototype=Ts.prototype;function Es(t){return function(){return t}}function Os(t){return 1e-6*(t()-.5)}function Is(t){return t.x+t.vx}function Rs(t){return t.y+t.vy}function Ps(t){var e,n,r,o=1,i=1;function s(){for(var t,s,l,c,u,f,d,h=e.length,p=0;p<i;++p)for(s=Ms(e,Is,Rs).visitAfter(a),t=0;t<h;++t)l=e[t],f=n[l.index],d=f*f,c=l.x+l.vx,u=l.y+l.vy,s.visit(m);function m(t,e,n,i,s){var a=t.data,h=t.r,p=f+h;if(!a)return e>c+p||i<c-p||n>u+p||s<u-p;if(a.index>l.index){var m=c-a.x-a.vx,g=u-a.y-a.vy,y=m*m+g*g;y<p*p&&(0===m&&(y+=(m=Os(r))*m),0===g&&(y+=(g=Os(r))*g),y=(p-(y=Math.sqrt(y)))/y*o,l.vx+=(m*=y)*(p=(h*=h)/(d+h)),l.vy+=(g*=y)*p,a.vx-=m*(p=1-p),a.vy-=g*p)}}}function a(t){if(t.data)return t.r=n[t.data.index];for(var e=t.r=0;e<4;++e)t[e]&&t[e].r>t.r&&(t.r=t[e].r)}function l(){if(e){var r,o,i=e.length;for(n=new Array(i),r=0;r<i;++r)o=e[r],n[o.index]=+t(o,r,e)}}return"function"!=typeof t&&(t=Es(null==t?1:+t)),s.initialize=function(t,n){e=t,r=n,l()},s.iterations=function(t){return arguments.length?(i=+t,s):i},s.strength=function(t){return arguments.length?(o=+t,s):o},s.radius=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),l(),s):t},s}function Fs(t){return t.index}function Ds(t,e){var n=t.get(e);if(!n)throw new Error("node not found: "+e);return n}function Ls(t){var e,n,r,o,i,s,a=Fs,l=function(t){return 1/Math.min(o[t.source.index],o[t.target.index])},c=Es(30),u=1;function f(r){for(var o=0,a=t.length;o<u;++o)for(var l,c,f,d,h,p,m,g=0;g<a;++g)c=(l=t[g]).source,d=(f=l.target).x+f.vx-c.x-c.vx||Os(s),h=f.y+f.vy-c.y-c.vy||Os(s),d*=p=((p=Math.sqrt(d*d+h*h))-n[g])/p*r*e[g],h*=p,f.vx-=d*(m=i[g]),f.vy-=h*m,c.vx+=d*(m=1-m),c.vy+=h*m}function d(){if(r){var s,l,c=r.length,u=t.length,f=new Map(r.map(((t,e)=>[a(t,e,r),t])));for(s=0,o=new Array(c);s<u;++s)(l=t[s]).index=s,"object"!=typeof l.source&&(l.source=Ds(f,l.source)),"object"!=typeof l.target&&(l.target=Ds(f,l.target)),o[l.source.index]=(o[l.source.index]||0)+1,o[l.target.index]=(o[l.target.index]||0)+1;for(s=0,i=new Array(u);s<u;++s)l=t[s],i[s]=o[l.source.index]/(o[l.source.index]+o[l.target.index]);e=new Array(u),h(),n=new Array(u),p()}}function h(){if(r)for(var n=0,o=t.length;n<o;++n)e[n]=+l(t[n],n,t)}function p(){if(r)for(var e=0,o=t.length;e<o;++e)n[e]=+c(t[e],e,t)}return null==t&&(t=[]),f.initialize=function(t,e){r=t,s=e,d()},f.links=function(e){return arguments.length?(t=e,d(),f):t},f.id=function(t){return arguments.length?(a=t,f):a},f.iterations=function(t){return arguments.length?(u=+t,f):u},f.strength=function(t){return arguments.length?(l="function"==typeof t?t:Es(+t),h(),f):l},f.distance=function(t){return arguments.length?(c="function"==typeof t?t:Es(+t),p(),f):c},f}js.copy=function(){var t,e,n=new Ts(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=Cs(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var o=0;o<4;++o)(e=r.source[o])&&(e.length?t.push({source:e,target:r.target[o]=new Array(4)}):r.target[o]=Cs(e));return n},js.add=function(t){const e=+this._x.call(null,t),n=+this._y.call(null,t);return qs(this.cover(e,n),e,n,t)},js.addAll=function(t){var e,n,r,o,i=t.length,s=new Array(i),a=new Array(i),l=1/0,c=1/0,u=-1/0,f=-1/0;for(n=0;n<i;++n)isNaN(r=+this._x.call(null,e=t[n]))||isNaN(o=+this._y.call(null,e))||(s[n]=r,a[n]=o,r<l&&(l=r),r>u&&(u=r),o<c&&(c=o),o>f&&(f=o));if(l>u||c>f)return this;for(this.cover(l,c).cover(u,f),n=0;n<i;++n)qs(this,s[n],a[n],t[n]);return this},js.cover=function(t,e){if(isNaN(t=+t)||isNaN(e=+e))return this;var n=this._x0,r=this._y0,o=this._x1,i=this._y1;if(isNaN(n))o=(n=Math.floor(t))+1,i=(r=Math.floor(e))+1;else{for(var s,a,l=o-n||1,c=this._root;n>t||t>=o||r>e||e>=i;)switch(a=(e<r)<<1|t<n,(s=new Array(4))[a]=c,c=s,l*=2,a){case 0:o=n+l,i=r+l;break;case 1:n=o-l,i=r+l;break;case 2:o=n+l,r=i-l;break;case 3:n=o-l,r=i-l}this._root&&this._root.length&&(this._root=c)}return this._x0=n,this._y0=r,this._x1=o,this._y1=i,this},js.data=function(){var t=[];return this.visit((function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)})),t},js.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},js.find=function(t,e,n){var r,o,i,s,a,l,c,u=this._x0,f=this._y0,d=this._x1,h=this._y1,p=[],m=this._root;for(m&&p.push(new Ns(m,u,f,d,h)),null==n?n=1/0:(u=t-n,f=e-n,d=t+n,h=e+n,n*=n);l=p.pop();)if(!(!(m=l.node)||(o=l.x0)>d||(i=l.y0)>h||(s=l.x1)<u||(a=l.y1)<f))if(m.length){var g=(o+s)/2,y=(i+a)/2;p.push(new Ns(m[3],g,y,s,a),new Ns(m[2],o,y,g,a),new Ns(m[1],g,i,s,y),new Ns(m[0],o,i,g,y)),(c=(e>=y)<<1|t>=g)&&(l=p[p.length-1],p[p.length-1]=p[p.length-1-c],p[p.length-1-c]=l)}else{var v=t-+this._x.call(null,m.data),b=e-+this._y.call(null,m.data),w=v*v+b*b;if(w<n){var _=Math.sqrt(n=w);u=t-_,f=e-_,d=t+_,h=e+_,r=m.data}}return r},js.remove=function(t){if(isNaN(i=+this._x.call(null,t))||isNaN(s=+this._y.call(null,t)))return this;var e,n,r,o,i,s,a,l,c,u,f,d,h=this._root,p=this._x0,m=this._y0,g=this._x1,y=this._y1;if(!h)return this;if(h.length)for(;;){if((c=i>=(a=(p+g)/2))?p=a:g=a,(u=s>=(l=(m+y)/2))?m=l:y=l,e=h,!(h=h[f=u<<1|c]))return this;if(!h.length)break;(e[f+1&3]||e[f+2&3]||e[f+3&3])&&(n=e,d=f)}for(;h.data!==t;)if(r=h,!(h=h.next))return this;return(o=h.next)&&delete h.next,r?(o?r.next=o:delete r.next,this):e?(o?e[f]=o:delete e[f],(h=e[0]||e[1]||e[2]||e[3])&&h===(e[3]||e[2]||e[1]||e[0])&&!h.length&&(n?n[d]=h:this._root=h),this):(this._root=o,this)},js.removeAll=function(t){for(var e=0,n=t.length;e<n;++e)this.remove(t[e]);return this},js.root=function(){return this._root},js.size=function(){var t=0;return this.visit((function(e){if(!e.length)do{++t}while(e=e.next)})),t},js.visit=function(t){var e,n,r,o,i,s,a=[],l=this._root;for(l&&a.push(new Ns(l,this._x0,this._y0,this._x1,this._y1));e=a.pop();)if(!t(l=e.node,r=e.x0,o=e.y0,i=e.x1,s=e.y1)&&l.length){var c=(r+i)/2,u=(o+s)/2;(n=l[3])&&a.push(new Ns(n,c,u,i,s)),(n=l[2])&&a.push(new Ns(n,r,u,c,s)),(n=l[1])&&a.push(new Ns(n,c,o,i,u)),(n=l[0])&&a.push(new Ns(n,r,o,c,u))}return this},js.visitAfter=function(t){var e,n=[],r=[];for(this._root&&n.push(new Ns(this._root,this._x0,this._y0,this._x1,this._y1));e=n.pop();){var o=e.node;if(o.length){var i,s=e.x0,a=e.y0,l=e.x1,c=e.y1,u=(s+l)/2,f=(a+c)/2;(i=o[0])&&n.push(new Ns(i,s,a,u,f)),(i=o[1])&&n.push(new Ns(i,u,a,l,f)),(i=o[2])&&n.push(new Ns(i,s,f,u,c)),(i=o[3])&&n.push(new Ns(i,u,f,l,c))}r.push(e)}for(;e=r.pop();)t(e.node,e.x0,e.y0,e.x1,e.y1);return this},js.x=function(t){return arguments.length?(this._x=t,this):this._x},js.y=function(t){return arguments.length?(this._y=t,this):this._y};const $s=1664525,Zs=1013904223,zs=4294967296;function Us(t){return t.x}function Bs(t){return t.y}var Gs=10,Js=Math.PI*(3-Math.sqrt(5));function Ws(t){var e,n=1,r=.001,o=1-Math.pow(r,1/300),i=0,s=.6,a=new Map,l=ce(f),c=N("tick","end"),u=function(){let t=1;return()=>(t=($s*t+Zs)%zs)/zs}();function f(){d(),c.call("tick",e),n<r&&(l.stop(),c.call("end",e))}function d(r){var l,c,u=t.length;void 0===r&&(r=1);for(var f=0;f<r;++f)for(n+=(i-n)*o,a.forEach((function(t){t(n)})),l=0;l<u;++l)null==(c=t[l]).fx?c.x+=c.vx*=s:(c.x=c.fx,c.vx=0),null==c.fy?c.y+=c.vy*=s:(c.y=c.fy,c.vy=0);return e}function h(){for(var e,n=0,r=t.length;n<r;++n){if((e=t[n]).index=n,null!=e.fx&&(e.x=e.fx),null!=e.fy&&(e.y=e.fy),isNaN(e.x)||isNaN(e.y)){var o=Gs*Math.sqrt(.5+n),i=n*Js;e.x=o*Math.cos(i),e.y=o*Math.sin(i)}(isNaN(e.vx)||isNaN(e.vy))&&(e.vx=e.vy=0)}}function p(e){return e.initialize&&e.initialize(t,u),e}return null==t&&(t=[]),h(),e={tick:d,restart:function(){return l.restart(f),e},stop:function(){return l.stop(),e},nodes:function(n){return arguments.length?(t=n,h(),a.forEach(p),e):t},alpha:function(t){return arguments.length?(n=+t,e):n},alphaMin:function(t){return arguments.length?(r=+t,e):r},alphaDecay:function(t){return arguments.length?(o=+t,e):+o},alphaTarget:function(t){return arguments.length?(i=+t,e):i},velocityDecay:function(t){return arguments.length?(s=1-t,e):1-s},randomSource:function(t){return arguments.length?(u=t,a.forEach(p),e):u},force:function(t,n){return arguments.length>1?(null==n?a.delete(t):a.set(t,p(n)),e):a.get(t)},find:function(e,n,r){var o,i,s,a,l,c=0,u=t.length;for(null==r?r=1/0:r*=r,c=0;c<u;++c)(s=(o=e-(a=t[c]).x)*o+(i=n-a.y)*i)<r&&(l=a,r=s);return l},on:function(t,n){return arguments.length>1?(c.on(t,n),e):c.on(t)}}}function Hs(){var t,e,n,r,o,i=Es(-30),s=1,a=1/0,l=.81;function c(n){var o,i=t.length,s=Ms(t,Us,Bs).visitAfter(f);for(r=n,o=0;o<i;++o)e=t[o],s.visit(d)}function u(){if(t){var e,n,r=t.length;for(o=new Array(r),e=0;e<r;++e)n=t[e],o[n.index]=+i(n,e,t)}}function f(t){var e,n,r,i,s,a=0,l=0;if(t.length){for(r=i=s=0;s<4;++s)(e=t[s])&&(n=Math.abs(e.value))&&(a+=e.value,l+=n,r+=n*e.x,i+=n*e.y);t.x=r/l,t.y=i/l}else{(e=t).x=e.data.x,e.y=e.data.y;do{a+=o[e.data.index]}while(e=e.next)}t.value=a}function d(t,i,c,u){if(!t.value)return!0;var f=t.x-e.x,d=t.y-e.y,h=u-i,p=f*f+d*d;if(h*h/l<p)return p<a&&(0===f&&(p+=(f=Os(n))*f),0===d&&(p+=(d=Os(n))*d),p<s&&(p=Math.sqrt(s*p)),e.vx+=f*t.value*r/p,e.vy+=d*t.value*r/p),!0;if(!(t.length||p>=a)){(t.data!==e||t.next)&&(0===f&&(p+=(f=Os(n))*f),0===d&&(p+=(d=Os(n))*d),p<s&&(p=Math.sqrt(s*p)));do{t.data!==e&&(h=o[t.data.index]*r/p,e.vx+=f*h,e.vy+=d*h)}while(t=t.next)}}return c.initialize=function(e,r){t=e,n=r,u()},c.strength=function(t){return arguments.length?(i="function"==typeof t?t:Es(+t),u(),c):i},c.distanceMin=function(t){return arguments.length?(s=t*t,c):Math.sqrt(s)},c.distanceMax=function(t){return arguments.length?(a=t*t,c):Math.sqrt(a)},c.theta=function(t){return arguments.length?(l=t*t,c):Math.sqrt(l)},c}function Vs(t,e,n){var r,o,i,s=Es(.1);function a(t){for(var s=0,a=r.length;s<a;++s){var l=r[s],c=l.x-e||1e-6,u=l.y-n||1e-6,f=Math.sqrt(c*c+u*u),d=(i[s]-f)*o[s]*t/f;l.vx+=c*d,l.vy+=u*d}}function l(){if(r){var e,n=r.length;for(o=new Array(n),i=new Array(n),e=0;e<n;++e)i[e]=+t(r[e],e,r),o[e]=isNaN(i[e])?0:+s(r[e],e,r)}}return"function"!=typeof t&&(t=Es(+t)),null==e&&(e=0),null==n&&(n=0),a.initialize=function(t){r=t,l()},a.strength=function(t){return arguments.length?(s="function"==typeof t?t:Es(+t),l(),a):s},a.radius=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),l(),a):t},a.x=function(t){return arguments.length?(e=+t,a):e},a.y=function(t){return arguments.length?(n=+t,a):n},a}function Ys(t){var e,n,r,o=Es(.1);function i(t){for(var o,i=0,s=e.length;i<s;++i)(o=e[i]).vx+=(r[i]-o.x)*n[i]*t}function s(){if(e){var i,s=e.length;for(n=new Array(s),r=new Array(s),i=0;i<s;++i)n[i]=isNaN(r[i]=+t(e[i],i,e))?0:+o(e[i],i,e)}}return"function"!=typeof t&&(t=Es(null==t?0:+t)),i.initialize=function(t){e=t,s()},i.strength=function(t){return arguments.length?(o="function"==typeof t?t:Es(+t),s(),i):o},i.x=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),s(),i):t},i}function Ks(t){var e,n,r,o=Es(.1);function i(t){for(var o,i=0,s=e.length;i<s;++i)(o=e[i]).vy+=(r[i]-o.y)*n[i]*t}function s(){if(e){var i,s=e.length;for(n=new Array(s),r=new Array(s),i=0;i<s;++i)n[i]=isNaN(r[i]=+t(e[i],i,e))?0:+o(e[i],i,e)}}return"function"!=typeof t&&(t=Es(null==t?0:+t)),i.initialize=function(t){e=t,s()},i.strength=function(t){return arguments.length?(o="function"==typeof t?t:Es(+t),s(),i):o},i.y=function(e){return arguments.length?(t="function"==typeof e?e:Es(+e),s(),i):t},i}var Xs=n(2163),Qs=n(2107),ta=n(7259),ea=n(9680),na=n(3150),ra=n(3621),oa=n(9343),ia=1e-6,sa=1e-12,aa=Math.PI,la=aa/2,ca=aa/4,ua=2*aa,fa=180/aa,da=aa/180,ha=Math.abs,pa=Math.atan,ma=Math.atan2,ga=Math.cos,ya=Math.ceil,va=Math.exp,ba=(Math.floor,Math.hypot),wa=Math.log,_a=Math.pow,xa=Math.sin,ka=Math.sign||function(t){return t>0?1:t<0?-1:0},qa=Math.sqrt,Na=Math.tan;function Sa(t){return t>1?0:t<-1?aa:Math.acos(t)}function Aa(t){return t>1?la:t<-1?-la:Math.asin(t)}function Ma(t){return(t=xa(t/2))*t}function Ta(){}function Ca(t,e){t&&Ea.hasOwnProperty(t.type)&&Ea[t.type](t,e)}var ja={Feature:function(t,e){Ca(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,o=n.length;++r<o;)Ca(n[r].geometry,e)}},Ea={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)t=n[r],e.point(t[0],t[1],t[2])},LineString:function(t,e){Oa(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)Oa(n[r],e,0)},Polygon:function(t,e){Ia(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)Ia(n[r],e)},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,o=n.length;++r<o;)Ca(n[r],e)}};function Oa(t,e,n){var r,o=-1,i=t.length-n;for(e.lineStart();++o<i;)r=t[o],e.point(r[0],r[1],r[2]);e.lineEnd()}function Ia(t,e){var n=-1,r=t.length;for(e.polygonStart();++n<r;)Oa(t[n],e,1);e.polygonEnd()}function Ra(t,e){t&&ja.hasOwnProperty(t.type)?ja[t.type](t,e):Ca(t,e)}var Pa,Fa,Da,La,$a,Za,za,Ua,Ba,Ga,Ja,Wa,Ha,Va,Ya,Ka,Xa=new oa.dU,Qa=new oa.dU,tl={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){Xa=new oa.dU,tl.lineStart=el,tl.lineEnd=nl},polygonEnd:function(){var t=+Xa;Qa.add(t<0?ua+t:t),this.lineStart=this.lineEnd=this.point=Ta},sphere:function(){Qa.add(ua)}};function el(){tl.point=rl}function nl(){ol(Pa,Fa)}function rl(t,e){tl.point=ol,Pa=t,Fa=e,Da=t*=da,La=ga(e=(e*=da)/2+ca),$a=xa(e)}function ol(t,e){var n=(t*=da)-Da,r=n>=0?1:-1,o=r*n,i=ga(e=(e*=da)/2+ca),s=xa(e),a=$a*s,l=La*i+a*ga(o),c=a*r*xa(o);Xa.add(ma(c,l)),Da=t,La=i,$a=s}function il(t){return Qa=new oa.dU,Ra(t,tl),2*Qa}function sl(t){return[ma(t[1],t[0]),Aa(t[2])]}function al(t){var e=t[0],n=t[1],r=ga(n);return[r*ga(e),r*xa(e),xa(n)]}function ll(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function cl(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function ul(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function fl(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function dl(t){var e=qa(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var hl,pl,ml,gl,yl,vl,bl,wl,_l,xl,kl,ql,Nl,Sl,Al,Ml,Tl={point:Cl,lineStart:El,lineEnd:Ol,polygonStart:function(){Tl.point=Il,Tl.lineStart=Rl,Tl.lineEnd=Pl,Va=new oa.dU,tl.polygonStart()},polygonEnd:function(){tl.polygonEnd(),Tl.point=Cl,Tl.lineStart=El,Tl.lineEnd=Ol,Xa<0?(Za=-(Ua=180),za=-(Ba=90)):Va>ia?Ba=90:Va<-ia&&(za=-90),Ka[0]=Za,Ka[1]=Ua},sphere:function(){Za=-(Ua=180),za=-(Ba=90)}};function Cl(t,e){Ya.push(Ka=[Za=t,Ua=t]),e<za&&(za=e),e>Ba&&(Ba=e)}function jl(t,e){var n=al([t*da,e*da]);if(Ha){var r=cl(Ha,n),o=cl([r[1],-r[0],0],r);dl(o),o=sl(o);var i,s=t-Ga,a=s>0?1:-1,l=o[0]*fa*a,c=ha(s)>180;c^(a*Ga<l&&l<a*t)?(i=o[1]*fa)>Ba&&(Ba=i):c^(a*Ga<(l=(l+360)%360-180)&&l<a*t)?(i=-o[1]*fa)<za&&(za=i):(e<za&&(za=e),e>Ba&&(Ba=e)),c?t<Ga?Fl(Za,t)>Fl(Za,Ua)&&(Ua=t):Fl(t,Ua)>Fl(Za,Ua)&&(Za=t):Ua>=Za?(t<Za&&(Za=t),t>Ua&&(Ua=t)):t>Ga?Fl(Za,t)>Fl(Za,Ua)&&(Ua=t):Fl(t,Ua)>Fl(Za,Ua)&&(Za=t)}else Ya.push(Ka=[Za=t,Ua=t]);e<za&&(za=e),e>Ba&&(Ba=e),Ha=n,Ga=t}function El(){Tl.point=jl}function Ol(){Ka[0]=Za,Ka[1]=Ua,Tl.point=Cl,Ha=null}function Il(t,e){if(Ha){var n=t-Ga;Va.add(ha(n)>180?n+(n>0?360:-360):n)}else Ja=t,Wa=e;tl.point(t,e),jl(t,e)}function Rl(){tl.lineStart()}function Pl(){Il(Ja,Wa),tl.lineEnd(),ha(Va)>ia&&(Za=-(Ua=180)),Ka[0]=Za,Ka[1]=Ua,Ha=null}function Fl(t,e){return(e-=t)<0?e+360:e}function Dl(t,e){return t[0]-e[0]}function Ll(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}function $l(t){var e,n,r,o,i,s,a;if(Ba=Ua=-(Za=za=1/0),Ya=[],Ra(t,Tl),n=Ya.length){for(Ya.sort(Dl),e=1,i=[r=Ya[0]];e<n;++e)Ll(r,(o=Ya[e])[0])||Ll(r,o[1])?(Fl(r[0],o[1])>Fl(r[0],r[1])&&(r[1]=o[1]),Fl(o[0],r[1])>Fl(r[0],r[1])&&(r[0]=o[0])):i.push(r=o);for(s=-1/0,e=0,r=i[n=i.length-1];e<=n;r=o,++e)o=i[e],(a=Fl(r[1],o[0]))>s&&(s=a,Za=o[0],Ua=r[1])}return Ya=Ka=null,Za===1/0||za===1/0?[[NaN,NaN],[NaN,NaN]]:[[Za,za],[Ua,Ba]]}var Zl={sphere:Ta,point:zl,lineStart:Bl,lineEnd:Wl,polygonStart:function(){Zl.lineStart=Hl,Zl.lineEnd=Vl},polygonEnd:function(){Zl.lineStart=Bl,Zl.lineEnd=Wl}};function zl(t,e){t*=da;var n=ga(e*=da);Ul(n*ga(t),n*xa(t),xa(e))}function Ul(t,e,n){++hl,ml+=(t-ml)/hl,gl+=(e-gl)/hl,yl+=(n-yl)/hl}function Bl(){Zl.point=Gl}function Gl(t,e){t*=da;var n=ga(e*=da);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),Zl.point=Jl,Ul(Sl,Al,Ml)}function Jl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),o=n*xa(t),i=xa(e),s=ma(qa((s=Al*i-Ml*o)*s+(s=Ml*r-Sl*i)*s+(s=Sl*o-Al*r)*s),Sl*r+Al*o+Ml*i);pl+=s,vl+=s*(Sl+(Sl=r)),bl+=s*(Al+(Al=o)),wl+=s*(Ml+(Ml=i)),Ul(Sl,Al,Ml)}function Wl(){Zl.point=zl}function Hl(){Zl.point=Yl}function Vl(){Kl(ql,Nl),Zl.point=zl}function Yl(t,e){ql=t,Nl=e,t*=da,e*=da,Zl.point=Kl;var n=ga(e);Sl=n*ga(t),Al=n*xa(t),Ml=xa(e),Ul(Sl,Al,Ml)}function Kl(t,e){t*=da;var n=ga(e*=da),r=n*ga(t),o=n*xa(t),i=xa(e),s=Al*i-Ml*o,a=Ml*r-Sl*i,l=Sl*o-Al*r,c=ba(s,a,l),u=Aa(c),f=c&&-u/c;_l.add(f*s),xl.add(f*a),kl.add(f*l),pl+=u,vl+=u*(Sl+(Sl=r)),bl+=u*(Al+(Al=o)),wl+=u*(Ml+(Ml=i)),Ul(Sl,Al,Ml)}function Xl(t){hl=pl=ml=gl=yl=vl=bl=wl=0,_l=new oa.dU,xl=new oa.dU,kl=new oa.dU,Ra(t,Zl);var e=+_l,n=+xl,r=+kl,o=ba(e,n,r);return o<sa&&(e=vl,n=bl,r=wl,pl<ia&&(e=ml,n=gl,r=yl),(o=ba(e,n,r))<sa)?[NaN,NaN]:[ma(n,e)*fa,Aa(r/o)*fa]}function Ql(t){return function(){return t}}function tc(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return(n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}function ec(t,e){return[ha(t)>aa?t+Math.round(-t/ua)*ua:t,e]}function nc(t,e,n){return(t%=ua)?e||n?tc(oc(t),ic(e,n)):oc(t):e||n?ic(e,n):ec}function rc(t){return function(e,n){return[(e+=t)>aa?e-ua:e<-aa?e+ua:e,n]}}function oc(t){var e=rc(t);return e.invert=rc(-t),e}function ic(t,e){var n=ga(t),r=xa(t),o=ga(e),i=xa(e);function s(t,e){var s=ga(e),a=ga(t)*s,l=xa(t)*s,c=xa(e),u=c*n+a*r;return[ma(l*o-u*i,a*n-c*r),Aa(u*o+l*i)]}return s.invert=function(t,e){var s=ga(e),a=ga(t)*s,l=xa(t)*s,c=xa(e),u=c*o-l*i;return[ma(l*o+c*i,a*n+u*r),Aa(u*n-a*r)]},s}function sc(t){function e(e){return(e=t(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e}return t=nc(t[0]*da,t[1]*da,t.length>2?t[2]*da:0),e.invert=function(e){return(e=t.invert(e[0]*da,e[1]*da))[0]*=fa,e[1]*=fa,e},e}function ac(t,e,n,r,o,i){if(n){var s=ga(e),a=xa(e),l=r*n;null==o?(o=e+r*ua,i=e-l/2):(o=lc(s,o),i=lc(s,i),(r>0?o<i:o>i)&&(o+=r*ua));for(var c,u=o;r>0?u>i:u<i;u-=l)c=sl([s,-a*ga(u),-a*xa(u)]),t.point(c[0],c[1])}}function lc(t,e){(e=al(e))[0]-=t,dl(e);var n=Sa(-e[1]);return((-e[2]<0?-n:n)+ua-ia)%ua}function cc(){var t,e,n=Ql([0,0]),r=Ql(90),o=Ql(6),i={point:function(n,r){t.push(n=e(n,r)),n[0]*=fa,n[1]*=fa}};function s(){var s=n.apply(this,arguments),a=r.apply(this,arguments)*da,l=o.apply(this,arguments)*da;return t=[],e=nc(-s[0]*da,-s[1]*da,0).invert,ac(i,a,l,1),s={type:"Polygon",coordinates:[t]},t=e=null,s}return s.center=function(t){return arguments.length?(n="function"==typeof t?t:Ql([+t[0],+t[1]]),s):n},s.radius=function(t){return arguments.length?(r="function"==typeof t?t:Ql(+t),s):r},s.precision=function(t){return arguments.length?(o="function"==typeof t?t:Ql(+t),s):o},s}function uc(){var t,e=[];return{point:function(e,n,r){t.push([e,n,r])},lineStart:function(){e.push(t=[])},lineEnd:Ta,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function fc(t,e){return ha(t[0]-e[0])<ia&&ha(t[1]-e[1])<ia}function dc(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function hc(t,e,n,r,o){var i,s,a=[],l=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,r=t[0],s=t[e];if(fc(r,s)){if(!r[2]&&!s[2]){for(o.lineStart(),i=0;i<e;++i)o.point((r=t[i])[0],r[1]);return void o.lineEnd()}s[0]+=2*ia}a.push(n=new dc(r,t,null,!0)),l.push(n.o=new dc(r,null,n,!1)),a.push(n=new dc(s,t,null,!1)),l.push(n.o=new dc(s,null,n,!0))}})),a.length){for(l.sort(e),pc(a),pc(l),i=0,s=l.length;i<s;++i)l[i].e=n=!n;for(var c,u,f=a[0];;){for(var d=f,h=!0;d.v;)if((d=d.n)===f)return;c=d.z,o.lineStart();do{if(d.v=d.o.v=!0,d.e){if(h)for(i=0,s=c.length;i<s;++i)o.point((u=c[i])[0],u[1]);else r(d.x,d.n.x,1,o);d=d.n}else{if(h)for(c=d.p.z,i=c.length-1;i>=0;--i)o.point((u=c[i])[0],u[1]);else r(d.x,d.p.x,-1,o);d=d.p}c=(d=d.o).z,h=!h}while(!d.v);o.lineEnd()}}}function pc(t){if(e=t.length){for(var e,n,r=0,o=t[0];++r<e;)o.n=n=t[r],n.p=o,o=n;o.n=n=t[0],n.p=o}}function mc(t){return ha(t[0])<=aa?t[0]:ka(t[0])*((ha(t[0])+aa)%ua-aa)}function gc(t,e){var n=mc(e),r=e[1],o=xa(r),i=[xa(n),-ga(n),0],s=0,a=0,l=new oa.dU;1===o?r=la+ia:-1===o&&(r=-la-ia);for(var c=0,u=t.length;c<u;++c)if(d=(f=t[c]).length)for(var f,d,h=f[d-1],p=mc(h),m=h[1]/2+ca,g=xa(m),y=ga(m),v=0;v<d;++v,p=w,g=x,y=k,h=b){var b=f[v],w=mc(b),_=b[1]/2+ca,x=xa(_),k=ga(_),q=w-p,N=q>=0?1:-1,S=N*q,A=S>aa,M=g*x;if(l.add(ma(M*N*xa(S),y*k+M*ga(S))),s+=A?q+N*ua:q,A^p>=n^w>=n){var T=cl(al(h),al(b));dl(T);var C=cl(i,T);dl(C);var j=(A^q>=0?-1:1)*Aa(C[2]);(r>j||r===j&&(T[0]||T[1]))&&(a+=A^q>=0?1:-1)}}return(s<-ia||s<ia&&l<-sa)^1&a}ec.invert=ec;var yc=n(1740);function vc(t,e,n,r){return function(o){var i,s,a,l=e(o),c=uc(),u=e(c),f=!1,d={point:h,lineStart:m,lineEnd:g,polygonStart:function(){d.point=y,d.lineStart=v,d.lineEnd=b,s=[],i=[]},polygonEnd:function(){d.point=h,d.lineStart=m,d.lineEnd=g,s=(0,yc.Z)(s);var t=gc(i,r);s.length?(f||(o.polygonStart(),f=!0),hc(s,wc,t,n,o)):t&&(f||(o.polygonStart(),f=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),f&&(o.polygonEnd(),f=!1),s=i=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function h(e,n){t(e,n)&&o.point(e,n)}function p(t,e){l.point(t,e)}function m(){d.point=p,l.lineStart()}function g(){d.point=h,l.lineEnd()}function y(t,e){a.push([t,e]),u.point(t,e)}function v(){u.lineStart(),a=[]}function b(){y(a[0][0],a[0][1]),u.lineEnd();var t,e,n,r,l=u.clean(),d=c.result(),h=d.length;if(a.pop(),i.push(a),a=null,h)if(1&l){if((e=(n=d[0]).length-1)>0){for(f||(o.polygonStart(),f=!0),o.lineStart(),t=0;t<e;++t)o.point((r=n[t])[0],r[1]);o.lineEnd()}}else h>1&&2&l&&d.push(d.pop().concat(d.shift())),s.push(d.filter(bc))}return d}}function bc(t){return t.length>1}function wc(t,e){return((t=t.x)[0]<0?t[1]-la-ia:la-t[1])-((e=e.x)[0]<0?e[1]-la-ia:la-e[1])}const _c=vc((function(){return!0}),(function(t){var e,n=NaN,r=NaN,o=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,s){var a=i>0?aa:-aa,l=ha(i-n);ha(l-aa)<ia?(t.point(n,r=(r+s)/2>0?la:-la),t.point(o,r),t.lineEnd(),t.lineStart(),t.point(a,r),t.point(i,r),e=0):o!==a&&l>=aa&&(ha(n-o)<ia&&(n-=o*ia),ha(i-a)<ia&&(i-=a*ia),r=function(t,e,n,r){var o,i,s=xa(t-n);return ha(s)>ia?pa((xa(e)*(i=ga(r))*xa(n)-xa(r)*(o=ga(e))*xa(t))/(o*i*s)):(e+r)/2}(n,r,i,s),t.point(o,r),t.lineEnd(),t.lineStart(),t.point(a,r),e=0),t.point(n=i,r=s),o=a},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var o;if(null==t)o=n*la,r.point(-aa,o),r.point(0,o),r.point(aa,o),r.point(aa,0),r.point(aa,-o),r.point(0,-o),r.point(-aa,-o),r.point(-aa,0),r.point(-aa,o);else if(ha(t[0]-e[0])>ia){var i=t[0]<e[0]?aa:-aa;o=n*i/2,r.point(-i,o),r.point(0,o),r.point(i,o)}else r.point(e[0],e[1])}),[-aa,-la]);function xc(t){var e=ga(t),n=6*da,r=e>0,o=ha(e)>ia;function i(t,n){return ga(t)*ga(n)>e}function s(t,n,r){var o=[1,0,0],i=cl(al(t),al(n)),s=ll(i,i),a=i[0],l=s-a*a;if(!l)return!r&&t;var c=e*s/l,u=-e*a/l,f=cl(o,i),d=fl(o,c);ul(d,fl(i,u));var h=f,p=ll(d,h),m=ll(h,h),g=p*p-m*(ll(d,d)-1);if(!(g<0)){var y=qa(g),v=fl(h,(-p-y)/m);if(ul(v,d),v=sl(v),!r)return v;var b,w=t[0],_=n[0],x=t[1],k=n[1];_<w&&(b=w,w=_,_=b);var q=_-w,N=ha(q-aa)<ia;if(!N&&k<x&&(b=x,x=k,k=b),N||q<ia?N?x+k>0^v[1]<(ha(v[0]-w)<ia?x:k):x<=v[1]&&v[1]<=k:q>aa^(w<=v[0]&&v[0]<=_)){var S=fl(h,(-p+y)/m);return ul(S,d),[v,sl(S)]}}}function a(e,n){var o=r?t:aa-t,i=0;return e<-o?i|=1:e>o&&(i|=2),n<-o?i|=4:n>o&&(i|=8),i}return vc(i,(function(t){var e,n,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,d){var h,p=[f,d],m=i(f,d),g=r?m?0:a(f,d):m?a(f+(f<0?aa:-aa),d):0;if(!e&&(c=l=m)&&t.lineStart(),m!==l&&(!(h=s(e,p))||fc(e,h)||fc(p,h))&&(p[2]=1),m!==l)u=0,m?(t.lineStart(),h=s(p,e),t.point(h[0],h[1])):(h=s(e,p),t.point(h[0],h[1],2),t.lineEnd()),e=h;else if(o&&e&&r^m){var y;g&n||!(y=s(p,e,!0))||(u=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!m||e&&fc(e,p)||t.point(p[0],p[1]),e=p,l=m,n=g},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return u|(c&&l)<<1}}}),(function(e,r,o,i){ac(i,t,n,o,e,r)}),r?[0,-t]:[-aa,t-aa])}var kc,qc,Nc,Sc,Ac=1e9,Mc=-Ac;function Tc(t,e,n,r){function o(o,i){return t<=o&&o<=n&&e<=i&&i<=r}function i(o,i,a,c){var u=0,f=0;if(null==o||(u=s(o,a))!==(f=s(i,a))||l(o,i)<0^a>0)do{c.point(0===u||3===u?t:n,u>1?r:e)}while((u=(u+a+4)%4)!==f);else c.point(i[0],i[1])}function s(r,o){return ha(r[0]-t)<ia?o>0?0:3:ha(r[0]-n)<ia?o>0?2:1:ha(r[1]-e)<ia?o>0?1:0:o>0?3:2}function a(t,e){return l(t.x,e.x)}function l(t,e){var n=s(t,1),r=s(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){var l,c,u,f,d,h,p,m,g,y,v,b=s,w=uc(),_={point:x,lineStart:function(){_.point=k,c&&c.push(u=[]);y=!0,g=!1,p=m=NaN},lineEnd:function(){l&&(k(f,d),h&&g&&w.rejoin(),l.push(w.result()));_.point=x,g&&b.lineEnd()},polygonStart:function(){b=w,l=[],c=[],v=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,o=c.length;n<o;++n)for(var i,s,a=c[n],l=1,u=a.length,f=a[0],d=f[0],h=f[1];l<u;++l)i=d,s=h,d=(f=a[l])[0],h=f[1],s<=r?h>r&&(d-i)*(r-s)>(h-s)*(t-i)&&++e:h<=r&&(d-i)*(r-s)<(h-s)*(t-i)&&--e;return e}(),n=v&&e,o=(l=(0,yc.Z)(l)).length;(n||o)&&(s.polygonStart(),n&&(s.lineStart(),i(null,null,1,s),s.lineEnd()),o&&hc(l,a,e,i,s),s.polygonEnd());b=s,l=c=u=null}};function x(t,e){o(t,e)&&b.point(t,e)}function k(i,s){var a=o(i,s);if(c&&u.push([i,s]),y)f=i,d=s,h=a,y=!1,a&&(b.lineStart(),b.point(i,s));else if(a&&g)b.point(i,s);else{var l=[p=Math.max(Mc,Math.min(Ac,p)),m=Math.max(Mc,Math.min(Ac,m))],w=[i=Math.max(Mc,Math.min(Ac,i)),s=Math.max(Mc,Math.min(Ac,s))];!function(t,e,n,r,o,i){var s,a=t[0],l=t[1],c=0,u=1,f=e[0]-a,d=e[1]-l;if(s=n-a,f||!(s>0)){if(s/=f,f<0){if(s<c)return;s<u&&(u=s)}else if(f>0){if(s>u)return;s>c&&(c=s)}if(s=o-a,f||!(s<0)){if(s/=f,f<0){if(s>u)return;s>c&&(c=s)}else if(f>0){if(s<c)return;s<u&&(u=s)}if(s=r-l,d||!(s>0)){if(s/=d,d<0){if(s<c)return;s<u&&(u=s)}else if(d>0){if(s>u)return;s>c&&(c=s)}if(s=i-l,d||!(s<0)){if(s/=d,d<0){if(s>u)return;s>c&&(c=s)}else if(d>0){if(s<c)return;s<u&&(u=s)}return c>0&&(t[0]=a+c*f,t[1]=l+c*d),u<1&&(e[0]=a+u*f,e[1]=l+u*d),!0}}}}}(l,w,t,e,n,r)?a&&(b.lineStart(),b.point(i,s),v=!1):(g||(b.lineStart(),b.point(l[0],l[1])),b.point(w[0],w[1]),a||b.lineEnd(),v=!1)}p=i,m=s,g=a}return _}}function Cc(){var t,e,n,r=0,o=0,i=960,s=500;return n={stream:function(n){return t&&e===n?t:t=Tc(r,o,i,s)(e=n)},extent:function(a){return arguments.length?(r=+a[0][0],o=+a[0][1],i=+a[1][0],s=+a[1][1],t=e=null,n):[[r,o],[i,s]]}}}var jc={sphere:Ta,point:Ta,lineStart:function(){jc.point=Oc,jc.lineEnd=Ec},lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta};function Ec(){jc.point=jc.lineEnd=Ta}function Oc(t,e){qc=t*=da,Nc=xa(e*=da),Sc=ga(e),jc.point=Ic}function Ic(t,e){t*=da;var n=xa(e*=da),r=ga(e),o=ha(t-qc),i=ga(o),s=r*xa(o),a=Sc*n-Nc*r*i,l=Nc*n+Sc*r*i;kc.add(ma(qa(s*s+a*a),l)),qc=t,Nc=n,Sc=r}function Rc(t){return kc=new oa.dU,Ra(t,jc),+kc}var Pc=[null,null],Fc={type:"LineString",coordinates:Pc};function Dc(t,e){return Pc[0]=t,Pc[1]=e,Rc(Fc)}var Lc={Feature:function(t,e){return Zc(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,o=n.length;++r<o;)if(Zc(n[r].geometry,e))return!0;return!1}},$c={Sphere:function(){return!0},Point:function(t,e){return zc(t.coordinates,e)},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(zc(n[r],e))return!0;return!1},LineString:function(t,e){return Uc(t.coordinates,e)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(Uc(n[r],e))return!0;return!1},Polygon:function(t,e){return Bc(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,o=n.length;++r<o;)if(Bc(n[r],e))return!0;return!1},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,o=n.length;++r<o;)if(Zc(n[r],e))return!0;return!1}};function Zc(t,e){return!(!t||!$c.hasOwnProperty(t.type))&&$c[t.type](t,e)}function zc(t,e){return 0===Dc(t,e)}function Uc(t,e){for(var n,r,o,i=0,s=t.length;i<s;i++){if(0===(r=Dc(t[i],e)))return!0;if(i>0&&(o=Dc(t[i],t[i-1]))>0&&n<=o&&r<=o&&(n+r-o)*(1-Math.pow((n-r)/o,2))<sa*o)return!0;n=r}return!1}function Bc(t,e){return!!gc(t.map(Gc),Jc(e))}function Gc(t){return(t=t.map(Jc)).pop(),t}function Jc(t){return[t[0]*da,t[1]*da]}function Wc(t,e){return(t&&Lc.hasOwnProperty(t.type)?Lc[t.type]:Zc)(t,e)}var Hc=n(1265);function Vc(t,e,n){var r=(0,Hc.Z)(t,e-ia,n).concat(e);return function(t){return r.map((function(e){return[t,e]}))}}function Yc(t,e,n){var r=(0,Hc.Z)(t,e-ia,n).concat(e);return function(t){return r.map((function(e){return[e,t]}))}}function Kc(){var t,e,n,r,o,i,s,a,l,c,u,f,d=10,h=d,p=90,m=360,g=2.5;function y(){return{type:"MultiLineString",coordinates:v()}}function v(){return(0,Hc.Z)(ya(r/p)*p,n,p).map(u).concat((0,Hc.Z)(ya(a/m)*m,s,m).map(f)).concat((0,Hc.Z)(ya(e/d)*d,t,d).filter((function(t){return ha(t%p)>ia})).map(l)).concat((0,Hc.Z)(ya(i/h)*h,o,h).filter((function(t){return ha(t%m)>ia})).map(c))}return y.lines=function(){return v().map((function(t){return{type:"LineString",coordinates:t}}))},y.outline=function(){return{type:"Polygon",coordinates:[u(r).concat(f(s).slice(1),u(n).reverse().slice(1),f(a).reverse().slice(1))]}},y.extent=function(t){return arguments.length?y.extentMajor(t).extentMinor(t):y.extentMinor()},y.extentMajor=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],a=+t[0][1],s=+t[1][1],r>n&&(t=r,r=n,n=t),a>s&&(t=a,a=s,s=t),y.precision(g)):[[r,a],[n,s]]},y.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],i=+n[0][1],o=+n[1][1],e>t&&(n=e,e=t,t=n),i>o&&(n=i,i=o,o=n),y.precision(g)):[[e,i],[t,o]]},y.step=function(t){return arguments.length?y.stepMajor(t).stepMinor(t):y.stepMinor()},y.stepMajor=function(t){return arguments.length?(p=+t[0],m=+t[1],y):[p,m]},y.stepMinor=function(t){return arguments.length?(d=+t[0],h=+t[1],y):[d,h]},y.precision=function(d){return arguments.length?(g=+d,l=Vc(i,o,90),c=Yc(e,t,g),u=Vc(a,s,90),f=Yc(r,n,g),y):g},y.extentMajor([[-180,-90+ia],[180,90-ia]]).extentMinor([[-180,-80-ia],[180,80+ia]])}function Xc(){return Kc()()}function Qc(t,e){var n=t[0]*da,r=t[1]*da,o=e[0]*da,i=e[1]*da,s=ga(r),a=xa(r),l=ga(i),c=xa(i),u=s*ga(n),f=s*xa(n),d=l*ga(o),h=l*xa(o),p=2*Aa(qa(Ma(i-r)+s*l*Ma(o-n))),m=xa(p),g=p?function(t){var e=xa(t*=p)/m,n=xa(p-t)/m,r=n*u+e*d,o=n*f+e*h,i=n*a+e*c;return[ma(o,r)*fa,ma(i,qa(r*r+o*o))*fa]}:function(){return[n*fa,r*fa]};return g.distance=p,g}const tu=t=>t;var eu,nu,ru,ou,iu=new oa.dU,su=new oa.dU,au={point:Ta,lineStart:Ta,lineEnd:Ta,polygonStart:function(){au.lineStart=lu,au.lineEnd=fu},polygonEnd:function(){au.lineStart=au.lineEnd=au.point=Ta,iu.add(ha(su)),su=new oa.dU},result:function(){var t=iu/2;return iu=new oa.dU,t}};function lu(){au.point=cu}function cu(t,e){au.point=uu,eu=ru=t,nu=ou=e}function uu(t,e){su.add(ou*t-ru*e),ru=t,ou=e}function fu(){uu(eu,nu)}const du=au;var hu=1/0,pu=hu,mu=-hu,gu=mu,yu={point:function(t,e){t<hu&&(hu=t);t>mu&&(mu=t);e<pu&&(pu=e);e>gu&&(gu=e)},lineStart:Ta,lineEnd:Ta,polygonStart:Ta,polygonEnd:Ta,result:function(){var t=[[hu,pu],[mu,gu]];return mu=gu=-(pu=hu=1/0),t}};const vu=yu;var bu,wu,_u,xu,ku=0,qu=0,Nu=0,Su=0,Au=0,Mu=0,Tu=0,Cu=0,ju=0,Eu={point:Ou,lineStart:Iu,lineEnd:Fu,polygonStart:function(){Eu.lineStart=Du,Eu.lineEnd=Lu},polygonEnd:function(){Eu.point=Ou,Eu.lineStart=Iu,Eu.lineEnd=Fu},result:function(){var t=ju?[Tu/ju,Cu/ju]:Mu?[Su/Mu,Au/Mu]:Nu?[ku/Nu,qu/Nu]:[NaN,NaN];return ku=qu=Nu=Su=Au=Mu=Tu=Cu=ju=0,t}};function Ou(t,e){ku+=t,qu+=e,++Nu}function Iu(){Eu.point=Ru}function Ru(t,e){Eu.point=Pu,Ou(_u=t,xu=e)}function Pu(t,e){var n=t-_u,r=e-xu,o=qa(n*n+r*r);Su+=o*(_u+t)/2,Au+=o*(xu+e)/2,Mu+=o,Ou(_u=t,xu=e)}function Fu(){Eu.point=Ou}function Du(){Eu.point=$u}function Lu(){Zu(bu,wu)}function $u(t,e){Eu.point=Zu,Ou(bu=_u=t,wu=xu=e)}function Zu(t,e){var n=t-_u,r=e-xu,o=qa(n*n+r*r);Su+=o*(_u+t)/2,Au+=o*(xu+e)/2,Mu+=o,Tu+=(o=xu*t-_u*e)*(_u+t),Cu+=o*(xu+e),ju+=3*o,Ou(_u=t,xu=e)}const zu=Eu;function Uu(t){this._context=t}Uu.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,ua)}},result:Ta};var Bu,Gu,Ju,Wu,Hu,Vu=new oa.dU,Yu={point:Ta,lineStart:function(){Yu.point=Ku},lineEnd:function(){Bu&&Xu(Gu,Ju),Yu.point=Ta},polygonStart:function(){Bu=!0},polygonEnd:function(){Bu=null},result:function(){var t=+Vu;return Vu=new oa.dU,t}};function Ku(t,e){Yu.point=Xu,Gu=Wu=t,Ju=Hu=e}function Xu(t,e){Wu-=t,Hu-=e,Vu.add(qa(Wu*Wu+Hu*Hu)),Wu=t,Hu=e}const Qu=Yu;function tf(){this._string=[]}function ef(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function nf(t,e){var n,r,o=4.5;function i(t){return t&&("function"==typeof o&&r.pointRadius(+o.apply(this,arguments)),Ra(t,n(r))),r.result()}return i.area=function(t){return Ra(t,n(du)),du.result()},i.measure=function(t){return Ra(t,n(Qu)),Qu.result()},i.bounds=function(t){return Ra(t,n(vu)),vu.result()},i.centroid=function(t){return Ra(t,n(zu)),zu.result()},i.projection=function(e){return arguments.length?(n=null==e?(t=null,tu):(t=e).stream,i):t},i.context=function(t){return arguments.length?(r=null==t?(e=null,new tf):new Uu(e=t),"function"!=typeof o&&r.pointRadius(o),i):e},i.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(r.pointRadius(+t),+t),i):o},i.projection(t).context(e)}function rf(t){return{stream:of(t)}}function of(t){return function(e){var n=new sf;for(var r in t)n[r]=t[r];return n.stream=e,n}}function sf(){}function af(t,e,n){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Ra(n,t.stream(vu)),e(vu.result()),null!=r&&t.clipExtent(r),t}function lf(t,e,n){return af(t,(function(n){var r=e[1][0]-e[0][0],o=e[1][1]-e[0][1],i=Math.min(r/(n[1][0]-n[0][0]),o/(n[1][1]-n[0][1])),s=+e[0][0]+(r-i*(n[1][0]+n[0][0]))/2,a=+e[0][1]+(o-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([s,a])}),n)}function cf(t,e,n){return lf(t,[[0,0],e],n)}function uf(t,e,n){return af(t,(function(n){var r=+e,o=r/(n[1][0]-n[0][0]),i=(r-o*(n[1][0]+n[0][0]))/2,s=-o*n[0][1];t.scale(150*o).translate([i,s])}),n)}function ff(t,e,n){return af(t,(function(n){var r=+e,o=r/(n[1][1]-n[0][1]),i=-o*n[0][0],s=(r-o*(n[1][1]+n[0][1]))/2;t.scale(150*o).translate([i,s])}),n)}tf.prototype={_radius:4.5,_circle:ef(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=ef(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},sf.prototype={constructor:sf,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var df=16,hf=ga(30*da);function pf(t,e){return+e?function(t,e){function n(r,o,i,s,a,l,c,u,f,d,h,p,m,g){var y=c-r,v=u-o,b=y*y+v*v;if(b>4*e&&m--){var w=s+d,_=a+h,x=l+p,k=qa(w*w+_*_+x*x),q=Aa(x/=k),N=ha(ha(x)-1)<ia||ha(i-f)<ia?(i+f)/2:ma(_,w),S=t(N,q),A=S[0],M=S[1],T=A-r,C=M-o,j=v*T-y*C;(j*j/b>e||ha((y*T+v*C)/b-.5)>.3||s*d+a*h+l*p<hf)&&(n(r,o,i,s,a,l,A,M,N,w/=k,_/=k,x,m,g),g.point(A,M),n(A,M,N,w,_,x,c,u,f,d,h,p,m,g))}}return function(e){var r,o,i,s,a,l,c,u,f,d,h,p,m={point:g,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),m.lineStart=w},polygonEnd:function(){e.polygonEnd(),m.lineStart=y}};function g(n,r){n=t(n,r),e.point(n[0],n[1])}function y(){u=NaN,m.point=v,e.lineStart()}function v(r,o){var i=al([r,o]),s=t(r,o);n(u,f,c,d,h,p,u=s[0],f=s[1],c=r,d=i[0],h=i[1],p=i[2],df,e),e.point(u,f)}function b(){m.point=g,e.lineEnd()}function w(){y(),m.point=_,m.lineEnd=x}function _(t,e){v(r=t,e),o=u,i=f,s=d,a=h,l=p,m.point=v}function x(){n(u,f,c,d,h,p,o,i,r,s,a,l,df,e),m.lineEnd=b,b()}return m}}(t,e):function(t){return of({point:function(e,n){e=t(e,n),this.stream.point(e[0],e[1])}})}(t)}var mf=of({point:function(t,e){this.stream.point(t*da,e*da)}});function gf(t,e,n,r,o,i){if(!i)return function(t,e,n,r,o){function i(i,s){return[e+t*(i*=r),n-t*(s*=o)]}return i.invert=function(i,s){return[(i-e)/t*r,(n-s)/t*o]},i}(t,e,n,r,o);var s=ga(i),a=xa(i),l=s*t,c=a*t,u=s/t,f=a/t,d=(a*n-s*e)/t,h=(a*e+s*n)/t;function p(t,i){return[l*(t*=r)-c*(i*=o)+e,n-c*t-l*i]}return p.invert=function(t,e){return[r*(u*t-f*e+d),o*(h-f*t-u*e)]},p}function yf(t){return vf((function(){return t}))()}function vf(t){var e,n,r,o,i,s,a,l,c,u,f=150,d=480,h=250,p=0,m=0,g=0,y=0,v=0,b=0,w=1,_=1,x=null,k=_c,q=null,N=tu,S=.5;function A(t){return l(t[0]*da,t[1]*da)}function M(t){return(t=l.invert(t[0],t[1]))&&[t[0]*fa,t[1]*fa]}function T(){var t=gf(f,0,0,w,_,b).apply(null,e(p,m)),r=gf(f,d-t[0],h-t[1],w,_,b);return n=nc(g,y,v),a=tc(e,r),l=tc(n,a),s=pf(a,S),C()}function C(){return c=u=null,A}return A.stream=function(t){return c&&u===t?c:c=mf(function(t){return of({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(k(s(N(u=t)))))},A.preclip=function(t){return arguments.length?(k=t,x=void 0,C()):k},A.postclip=function(t){return arguments.length?(N=t,q=r=o=i=null,C()):N},A.clipAngle=function(t){return arguments.length?(k=+t?xc(x=t*da):(x=null,_c),C()):x*fa},A.clipExtent=function(t){return arguments.length?(N=null==t?(q=r=o=i=null,tu):Tc(q=+t[0][0],r=+t[0][1],o=+t[1][0],i=+t[1][1]),C()):null==q?null:[[q,r],[o,i]]},A.scale=function(t){return arguments.length?(f=+t,T()):f},A.translate=function(t){return arguments.length?(d=+t[0],h=+t[1],T()):[d,h]},A.center=function(t){return arguments.length?(p=t[0]%360*da,m=t[1]%360*da,T()):[p*fa,m*fa]},A.rotate=function(t){return arguments.length?(g=t[0]%360*da,y=t[1]%360*da,v=t.length>2?t[2]%360*da:0,T()):[g*fa,y*fa,v*fa]},A.angle=function(t){return arguments.length?(b=t%360*da,T()):b*fa},A.reflectX=function(t){return arguments.length?(w=t?-1:1,T()):w<0},A.reflectY=function(t){return arguments.length?(_=t?-1:1,T()):_<0},A.precision=function(t){return arguments.length?(s=pf(a,S=t*t),C()):qa(S)},A.fitExtent=function(t,e){return lf(A,t,e)},A.fitSize=function(t,e){return cf(A,t,e)},A.fitWidth=function(t,e){return uf(A,t,e)},A.fitHeight=function(t,e){return ff(A,t,e)},function(){return e=t.apply(this,arguments),A.invert=e.invert&&M,T()}}function bf(t){var e=0,n=aa/3,r=vf(t),o=r(e,n);return o.parallels=function(t){return arguments.length?r(e=t[0]*da,n=t[1]*da):[e*fa,n*fa]},o}function wf(t,e){var n=xa(t),r=(n+xa(e))/2;if(ha(r)<ia)return function(t){var e=ga(t);function n(t,n){return[t*e,xa(n)/e]}return n.invert=function(t,n){return[t/e,Aa(n*e)]},n}(t);var o=1+n*(2*r-n),i=qa(o)/r;function s(t,e){var n=qa(o-2*r*xa(e))/r;return[n*xa(t*=r),i-n*ga(t)]}return s.invert=function(t,e){var n=i-e,s=ma(t,ha(n))*ka(n);return n*r<0&&(s-=aa*ka(t)*ka(n)),[s/r,Aa((o-(t*t+n*n)*r*r)/(2*r))]},s}function _f(){return bf(wf).scale(155.424).center([0,33.6442])}function xf(){return _f().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function kf(){var t,e,n,r,o,i,s=xf(),a=_f().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=_f().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(t,e){i=[t,e]}};function u(t){var e=t[0],s=t[1];return i=null,n.point(e,s),i||(r.point(e,s),i)||(o.point(e,s),i)}function f(){return t=e=null,u}return u.invert=function(t){var e=s.scale(),n=s.translate(),r=(t[0]-n[0])/e,o=(t[1]-n[1])/e;return(o>=.12&&o<.234&&r>=-.425&&r<-.214?a:o>=.166&&o<.234&&r>=-.214&&r<-.115?l:s).invert(t)},u.stream=function(n){return t&&e===n?t:(r=[s.stream(e=n),a.stream(n),l.stream(n)],o=r.length,t={point:function(t,e){for(var n=-1;++n<o;)r[n].point(t,e)},sphere:function(){for(var t=-1;++t<o;)r[t].sphere()},lineStart:function(){for(var t=-1;++t<o;)r[t].lineStart()},lineEnd:function(){for(var t=-1;++t<o;)r[t].lineEnd()},polygonStart:function(){for(var t=-1;++t<o;)r[t].polygonStart()},polygonEnd:function(){for(var t=-1;++t<o;)r[t].polygonEnd()}});var r,o},u.precision=function(t){return arguments.length?(s.precision(t),a.precision(t),l.precision(t),f()):s.precision()},u.scale=function(t){return arguments.length?(s.scale(t),a.scale(.35*t),l.scale(t),u.translate(s.translate())):s.scale()},u.translate=function(t){if(!arguments.length)return s.translate();var e=s.scale(),i=+t[0],u=+t[1];return n=s.translate(t).clipExtent([[i-.455*e,u-.238*e],[i+.455*e,u+.238*e]]).stream(c),r=a.translate([i-.307*e,u+.201*e]).clipExtent([[i-.425*e+ia,u+.12*e+ia],[i-.214*e-ia,u+.234*e-ia]]).stream(c),o=l.translate([i-.205*e,u+.212*e]).clipExtent([[i-.214*e+ia,u+.166*e+ia],[i-.115*e-ia,u+.234*e-ia]]).stream(c),f()},u.fitExtent=function(t,e){return lf(u,t,e)},u.fitSize=function(t,e){return cf(u,t,e)},u.fitWidth=function(t,e){return uf(u,t,e)},u.fitHeight=function(t,e){return ff(u,t,e)},u.scale(1070)}function qf(t){return function(e,n){var r=ga(e),o=ga(n),i=t(r*o);return i===1/0?[2,0]:[i*o*xa(e),i*xa(n)]}}function Nf(t){return function(e,n){var r=qa(e*e+n*n),o=t(r),i=xa(o),s=ga(o);return[ma(e*i,r*s),Aa(r&&n*i/r)]}}var Sf=qf((function(t){return qa(2/(1+t))}));function Af(){return yf(Sf).scale(124.75).clipAngle(179.999)}Sf.invert=Nf((function(t){return 2*Aa(t/2)}));var Mf=qf((function(t){return(t=Sa(t))&&t/xa(t)}));function Tf(){return yf(Mf).scale(79.4188).clipAngle(179.999)}function Cf(t,e){return[t,wa(Na((la+e)/2))]}function jf(){return Ef(Cf).scale(961/ua)}function Ef(t){var e,n,r,o=yf(t),i=o.center,s=o.scale,a=o.translate,l=o.clipExtent,c=null;function u(){var i=aa*s(),a=o(sc(o.rotate()).invert([0,0]));return l(null==c?[[a[0]-i,a[1]-i],[a[0]+i,a[1]+i]]:t===Cf?[[Math.max(a[0]-i,c),e],[Math.min(a[0]+i,n),r]]:[[c,Math.max(a[1]-i,e)],[n,Math.min(a[1]+i,r)]])}return o.scale=function(t){return arguments.length?(s(t),u()):s()},o.translate=function(t){return arguments.length?(a(t),u()):a()},o.center=function(t){return arguments.length?(i(t),u()):i()},o.clipExtent=function(t){return arguments.length?(null==t?c=e=n=r=null:(c=+t[0][0],e=+t[0][1],n=+t[1][0],r=+t[1][1]),u()):null==c?null:[[c,e],[n,r]]},u()}function Of(t){return Na((la+t)/2)}function If(t,e){var n=ga(t),r=t===e?xa(t):wa(n/ga(e))/wa(Of(e)/Of(t)),o=n*_a(Of(t),r)/r;if(!r)return Cf;function i(t,e){o>0?e<-la+ia&&(e=-la+ia):e>la-ia&&(e=la-ia);var n=o/_a(Of(e),r);return[n*xa(r*t),o-n*ga(r*t)]}return i.invert=function(t,e){var n=o-e,i=ka(r)*qa(t*t+n*n),s=ma(t,ha(n))*ka(n);return n*r<0&&(s-=aa*ka(t)*ka(n)),[s/r,2*pa(_a(o/i,1/r))-la]},i}function Rf(){return bf(If).scale(109.5).parallels([30,30])}function Pf(t,e){return[t,e]}function Ff(){return yf(Pf).scale(152.63)}function Df(t,e){var n=ga(t),r=t===e?xa(t):(n-ga(e))/(e-t),o=n/r+t;if(ha(r)<ia)return Pf;function i(t,e){var n=o-e,i=r*t;return[n*xa(i),o-n*ga(i)]}return i.invert=function(t,e){var n=o-e,i=ma(t,ha(n))*ka(n);return n*r<0&&(i-=aa*ka(t)*ka(n)),[i/r,o-ka(r)*qa(t*t+n*n)]},i}function Lf(){return bf(Df).scale(131.154).center([0,13.9389])}Mf.invert=Nf((function(t){return t})),Cf.invert=function(t,e){return[t,2*pa(va(e))-la]},Pf.invert=Pf;var $f=1.340264,Zf=-.081106,zf=893e-6,Uf=.003796,Bf=qa(3)/2;function Gf(t,e){var n=Aa(Bf*xa(e)),r=n*n,o=r*r*r;return[t*ga(n)/(Bf*($f+3*Zf*r+o*(7*zf+9*Uf*r))),n*($f+Zf*r+o*(zf+Uf*r))]}function Jf(){return yf(Gf).scale(177.158)}function Wf(t,e){var n=ga(e),r=ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function Hf(){return yf(Wf).scale(144.049).clipAngle(60)}function Vf(){var t,e,n,r,o,i,s,a=1,l=0,c=0,u=1,f=1,d=0,h=null,p=1,m=1,g=of({point:function(t,e){var n=b([t,e]);this.stream.point(n[0],n[1])}}),y=tu;function v(){return p=a*u,m=a*f,i=s=null,b}function b(n){var r=n[0]*p,o=n[1]*m;if(d){var i=o*t-r*e;r=r*t+o*e,o=i}return[r+l,o+c]}return b.invert=function(n){var r=n[0]-l,o=n[1]-c;if(d){var i=o*t+r*e;r=r*t-o*e,o=i}return[r/p,o/m]},b.stream=function(t){return i&&s===t?i:i=g(y(s=t))},b.postclip=function(t){return arguments.length?(y=t,h=n=r=o=null,v()):y},b.clipExtent=function(t){return arguments.length?(y=null==t?(h=n=r=o=null,tu):Tc(h=+t[0][0],n=+t[0][1],r=+t[1][0],o=+t[1][1]),v()):null==h?null:[[h,n],[r,o]]},b.scale=function(t){return arguments.length?(a=+t,v()):a},b.translate=function(t){return arguments.length?(l=+t[0],c=+t[1],v()):[l,c]},b.angle=function(n){return arguments.length?(e=xa(d=n%360*da),t=ga(d),v()):d*fa},b.reflectX=function(t){return arguments.length?(u=t?-1:1,v()):u<0},b.reflectY=function(t){return arguments.length?(f=t?-1:1,v()):f<0},b.fitExtent=function(t,e){return lf(b,t,e)},b.fitSize=function(t,e){return cf(b,t,e)},b.fitWidth=function(t,e){return uf(b,t,e)},b.fitHeight=function(t,e){return ff(b,t,e)},b}function Yf(t,e){var n=e*e,r=n*n;return[t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function Kf(){return yf(Yf).scale(175.295)}function Xf(t,e){return[ga(e)*xa(t),xa(e)]}function Qf(){return yf(Xf).scale(249.5).clipAngle(90+ia)}function td(t,e){var n=ga(e),r=1+ga(t)*n;return[n*xa(t)/r,xa(e)/r]}function ed(){return yf(td).scale(250).clipAngle(142)}function nd(t,e){return[wa(Na((la+e)/2)),-t]}function rd(){var t=Ef(nd),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}function od(t,e){return t.parent===e.parent?1:2}function id(t,e){return t+e.x}function sd(t,e){return Math.max(t,e.y)}function ad(){var t=od,e=1,n=1,r=!1;function o(o){var i,s=0;o.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(id,0)/t.length}(n),e.y=function(t){return 1+t.reduce(sd,0)}(n)):(e.x=i?s+=t(e,i):0,e.y=0,i=e)}));var a=function(t){for(var e;e=t.children;)t=e[0];return t}(o),l=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(o),c=a.x-t(a,l)/2,u=l.x+t(l,a)/2;return o.eachAfter(r?function(t){t.x=(t.x-o.x)*e,t.y=(o.y-t.y)*n}:function(t){t.x=(t.x-c)/(u-c)*e,t.y=(1-(o.y?t.y/o.y:1))*n})}return o.separation=function(e){return arguments.length?(t=e,o):t},o.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],o):r?null:[e,n]},o.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],o):r?[e,n]:null},o}Gf.invert=function(t,e){for(var n,r=e,o=r*r,i=o*o*o,s=0;s<12&&(i=(o=(r-=n=(r*($f+Zf*o+i*(zf+Uf*o))-e)/($f+3*Zf*o+i*(7*zf+9*Uf*o)))*r)*o*o,!(ha(n)<sa));++s);return[Bf*t*($f+3*Zf*o+i*(7*zf+9*Uf*o))/ga(r),Aa(xa(r)/Bf)]},Wf.invert=Nf(pa),Yf.invert=function(t,e){var n,r=e,o=25;do{var i=r*r,s=i*i;r-=n=(r*(1.007226+i*(.015085+s*(.028874*i-.044475-.005916*s)))-e)/(1.007226+i*(.045255+s*(.259866*i-.311325-.005916*11*s)))}while(ha(n)>ia&&--o>0);return[t/(.8707+(i=r*r)*(i*(i*i*i*(.003971-.001529*i)-.013791)-.131979)),r]},Xf.invert=Nf(Aa),td.invert=Nf((function(t){return 2*pa(t)})),nd.invert=function(t,e){return[-e,2*pa(va(t))-la]};var ld=n(5220),cd=n(9466);function ud(){return 0}function fd(t){return function(){return t}}const dd=1664525,hd=1013904223,pd=4294967296;function md(){let t=1;return()=>(t=(dd*t+hd)%pd)/pd}function gd(t){return yd(t,md())}function yd(t,e){for(var n,r,o=0,i=(t=function(t,e){let n,r,o=t.length;for(;o;)r=e()*o--|0,n=t[o],t[o]=t[r],t[r]=n;return t}(Array.from(t),e)).length,s=[];o<i;)n=t[o],r&&wd(r,n)?++o:(r=xd(s=vd(s,n)),o=0);return r}function vd(t,e){var n,r;if(_d(e,t))return[e];for(n=0;n<t.length;++n)if(bd(e,t[n])&&_d(kd(t[n],e),t))return[t[n],e];for(n=0;n<t.length-1;++n)for(r=n+1;r<t.length;++r)if(bd(kd(t[n],t[r]),e)&&bd(kd(t[n],e),t[r])&&bd(kd(t[r],e),t[n])&&_d(qd(t[n],t[r],e),t))return[t[n],t[r],e];throw new Error}function bd(t,e){var n=t.r-e.r,r=e.x-t.x,o=e.y-t.y;return n<0||n*n<r*r+o*o}function wd(t,e){var n=t.r-e.r+1e-9*Math.max(t.r,e.r,1),r=e.x-t.x,o=e.y-t.y;return n>0&&n*n>r*r+o*o}function _d(t,e){for(var n=0;n<e.length;++n)if(!wd(t,e[n]))return!1;return!0}function xd(t){switch(t.length){case 1:return function(t){return{x:t.x,y:t.y,r:t.r}}(t[0]);case 2:return kd(t[0],t[1]);case 3:return qd(t[0],t[1],t[2])}}function kd(t,e){var n=t.x,r=t.y,o=t.r,i=e.x,s=e.y,a=e.r,l=i-n,c=s-r,u=a-o,f=Math.sqrt(l*l+c*c);return{x:(n+i+l/f*u)/2,y:(r+s+c/f*u)/2,r:(f+o+a)/2}}function qd(t,e,n){var r=t.x,o=t.y,i=t.r,s=e.x,a=e.y,l=e.r,c=n.x,u=n.y,f=n.r,d=r-s,h=r-c,p=o-a,m=o-u,g=l-i,y=f-i,v=r*r+o*o-i*i,b=v-s*s-a*a+l*l,w=v-c*c-u*u+f*f,_=h*p-d*m,x=(p*w-m*b)/(2*_)-r,k=(m*g-p*y)/_,q=(h*b-d*w)/(2*_)-o,N=(d*y-h*g)/_,S=k*k+N*N-1,A=2*(i+x*k+q*N),M=x*x+q*q-i*i,T=-(Math.abs(S)>1e-6?(A+Math.sqrt(A*A-4*S*M))/(2*S):M/A);return{x:r+x+k*T,y:o+q+N*T,r:T}}function Nd(t,e,n){var r,o,i,s,a=t.x-e.x,l=t.y-e.y,c=a*a+l*l;c?(o=e.r+n.r,o*=o,s=t.r+n.r,o>(s*=s)?(r=(c+s-o)/(2*c),i=Math.sqrt(Math.max(0,s/c-r*r)),n.x=t.x-r*a-i*l,n.y=t.y-r*l+i*a):(r=(c+o-s)/(2*c),i=Math.sqrt(Math.max(0,o/c-r*r)),n.x=e.x+r*a-i*l,n.y=e.y+r*l+i*a)):(n.x=e.x+n.r,n.y=e.y)}function Sd(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,o=e.y-t.y;return n>0&&n*n>r*r+o*o}function Ad(t){var e=t._,n=t.next._,r=e.r+n.r,o=(e.x*n.r+n.x*e.r)/r,i=(e.y*n.r+n.y*e.r)/r;return o*o+i*i}function Md(t){this._=t,this.next=null,this.previous=null}function Td(t,e){if(!(i=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var n,r,o,i,s,a,l,c,u,f,d;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(r=t[1],n.x=-r.r,r.x=n.r,r.y=0,!(i>2))return n.r+r.r;Nd(r,n,o=t[2]),n=new Md(n),r=new Md(r),o=new Md(o),n.next=o.previous=r,r.next=n.previous=o,o.next=r.previous=n;t:for(l=3;l<i;++l){Nd(n._,r._,o=t[l]),o=new Md(o),c=r.next,u=n.previous,f=r._.r,d=n._.r;do{if(f<=d){if(Sd(c._,o._)){r=c,n.next=r,r.previous=n,--l;continue t}f+=c._.r,c=c.next}else{if(Sd(u._,o._)){(n=u).next=r,r.previous=n,--l;continue t}d+=u._.r,u=u.previous}}while(c!==u.next);for(o.previous=n,o.next=r,n.next=r.previous=r=o,s=Ad(n);(o=o.next)!==r;)(a=Ad(o))<s&&(n=o,s=a);r=n.next}for(n=[r._],o=r;(o=o.next)!==r;)n.push(o._);for(o=yd(n,e),l=0;l<i;++l)(n=t[l]).x-=o.x,n.y-=o.y;return o.r}function Cd(t){return Td(t,md()),t}function jd(t){return Math.sqrt(t.value)}function Ed(){var t=null,e=1,n=1,r=ud;function o(o){const i=md();return o.x=e/2,o.y=n/2,t?o.eachBefore(Od(t)).eachAfter(Id(r,.5,i)).eachBefore(Rd(1)):o.eachBefore(Od(jd)).eachAfter(Id(ud,1,i)).eachAfter(Id(r,o.r/Math.min(e,n),i)).eachBefore(Rd(Math.min(e,n)/(2*o.r))),o}return o.radius=function(e){return arguments.length?(t=(0,cd.j)(e),o):t},o.size=function(t){return arguments.length?(e=+t[0],n=+t[1],o):[e,n]},o.padding=function(t){return arguments.length?(r="function"==typeof t?t:fd(+t),o):r},o}function Od(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0))}}function Id(t,e,n){return function(r){if(o=r.children){var o,i,s,a=o.length,l=t(r)*e||0;if(l)for(i=0;i<a;++i)o[i].r+=l;if(s=Td(o,n),l)for(i=0;i<a;++i)o[i].r-=l;r.r=s+l}}}function Rd(t){return function(e){var n=e.parent;e.r*=t,n&&(e.x=n.x+t*e.x,e.y=n.y+t*e.y)}}function Pd(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Fd(t,e,n,r,o){for(var i,s=t.children,a=-1,l=s.length,c=t.value&&(r-e)/t.value;++a<l;)(i=s[a]).y0=n,i.y1=o,i.x0=e,i.x1=e+=i.value*c}function Dd(){var t=1,e=1,n=0,r=!1;function o(o){var i=o.height+1;return o.x0=o.y0=n,o.x1=t,o.y1=e/i,o.eachBefore(function(t,e){return function(r){r.children&&Fd(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var o=r.x0,i=r.y0,s=r.x1-n,a=r.y1-n;s<o&&(o=s=(o+s)/2),a<i&&(i=a=(i+a)/2),r.x0=o,r.y0=i,r.x1=s,r.y1=a}}(e,i)),r&&o.eachBefore(Pd),o}return o.round=function(t){return arguments.length?(r=!!t,o):r},o.size=function(n){return arguments.length?(t=+n[0],e=+n[1],o):[t,e]},o.padding=function(t){return arguments.length?(n=+t,o):n},o}var Ld=n(4766);function $d(t,e){return t.parent===e.parent?1:2}function Zd(t){var e=t.children;return e?e[0]:t.t}function zd(t){var e=t.children;return e?e[e.length-1]:t.t}function Ud(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function Bd(t,e,n){return t.a.parent===e.parent?t.a:n}function Gd(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function Jd(){var t=$d,e=1,n=1,r=null;function o(o){var l=function(t){for(var e,n,r,o,i,s=new Gd(t,0),a=[s];e=a.pop();)if(r=e._.children)for(e.children=new Array(i=r.length),o=i-1;o>=0;--o)a.push(n=e.children[o]=new Gd(r[o],o)),n.parent=e;return(s.parent=new Gd(null,0)).children=[s],s}(o);if(l.eachAfter(i),l.parent.m=-l.z,l.eachBefore(s),r)o.eachBefore(a);else{var c=o,u=o,f=o;o.eachBefore((function(t){t.x<c.x&&(c=t),t.x>u.x&&(u=t),t.depth>f.depth&&(f=t)}));var d=c===u?1:t(c,u)/2,h=d-c.x,p=e/(u.x+d+h),m=n/(f.depth||1);o.eachBefore((function(t){t.x=(t.x+h)*p,t.y=t.depth*m}))}return o}function i(e){var n=e.children,r=e.parent.children,o=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,o=t.children,i=o.length;--i>=0;)(e=o[i]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var i=(n[0].z+n[n.length-1].z)/2;o?(e.z=o.z+t(e._,o._),e.m=e.z-i):e.z=i}else o&&(e.z=o.z+t(e._,o._));e.parent.A=function(e,n,r){if(n){for(var o,i=e,s=e,a=n,l=i.parent.children[0],c=i.m,u=s.m,f=a.m,d=l.m;a=zd(a),i=Zd(i),a&&i;)l=Zd(l),(s=zd(s)).a=e,(o=a.z+f-i.z-c+t(a._,i._))>0&&(Ud(Bd(a,e,r),e,o),c+=o,u+=o),f+=a.m,c+=i.m,d+=l.m,u+=s.m;a&&!zd(s)&&(s.t=a,s.m+=f-u),i&&!Zd(l)&&(l.t=i,l.m+=c-d,r=e)}return r}(e,o,e.parent.A||r[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function a(t){t.x*=e,t.y=t.depth*n}return o.separation=function(e){return arguments.length?(t=e,o):t},o.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],o):r?null:[e,n]},o.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],o):r?[e,n]:null},o}function Wd(t,e,n,r,o){for(var i,s=t.children,a=-1,l=s.length,c=t.value&&(o-n)/t.value;++a<l;)(i=s[a]).x0=e,i.x1=r,i.y0=n,i.y1=n+=i.value*c}Gd.prototype=Object.create(ld.NB.prototype);var Hd=(1+Math.sqrt(5))/2;function Vd(t,e,n,r,o,i){for(var s,a,l,c,u,f,d,h,p,m,g,y=[],v=e.children,b=0,w=0,_=v.length,x=e.value;b<_;){l=o-n,c=i-r;do{u=v[w++].value}while(!u&&w<_);for(f=d=u,g=u*u*(m=Math.max(c/l,l/c)/(x*t)),p=Math.max(d/g,g/f);w<_;++w){if(u+=a=v[w].value,a<f&&(f=a),a>d&&(d=a),g=u*u*m,(h=Math.max(d/g,g/f))>p){u-=a;break}p=h}y.push(s={value:u,dice:l<c,children:v.slice(b,w)}),s.dice?Fd(s,n,r,o,x?r+=c*u/x:i):Wd(s,n,r,x?n+=l*u/x:o,i),x-=u,b=w}return y}const Yd=function t(e){function n(t,n,r,o,i){Vd(e,t,n,r,o,i)}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Hd);function Kd(){var t=Yd,e=!1,n=1,r=1,o=[0],i=ud,s=ud,a=ud,l=ud,c=ud;function u(t){return t.x0=t.y0=0,t.x1=n,t.y1=r,t.eachBefore(f),o=[0],e&&t.eachBefore(Pd),t}function f(e){var n=o[e.depth],r=e.x0+n,u=e.y0+n,f=e.x1-n,d=e.y1-n;f<r&&(r=f=(r+f)/2),d<u&&(u=d=(u+d)/2),e.x0=r,e.y0=u,e.x1=f,e.y1=d,e.children&&(n=o[e.depth+1]=i(e)/2,r+=c(e)-n,u+=s(e)-n,(f-=a(e)-n)<r&&(r=f=(r+f)/2),(d-=l(e)-n)<u&&(u=d=(u+d)/2),t(e,r,u,f,d))}return u.round=function(t){return arguments.length?(e=!!t,u):e},u.size=function(t){return arguments.length?(n=+t[0],r=+t[1],u):[n,r]},u.tile=function(e){return arguments.length?(t=(0,cd.C)(e),u):t},u.padding=function(t){return arguments.length?u.paddingInner(t).paddingOuter(t):u.paddingInner()},u.paddingInner=function(t){return arguments.length?(i="function"==typeof t?t:fd(+t),u):i},u.paddingOuter=function(t){return arguments.length?u.paddingTop(t).paddingRight(t).paddingBottom(t).paddingLeft(t):u.paddingTop()},u.paddingTop=function(t){return arguments.length?(s="function"==typeof t?t:fd(+t),u):s},u.paddingRight=function(t){return arguments.length?(a="function"==typeof t?t:fd(+t),u):a},u.paddingBottom=function(t){return arguments.length?(l="function"==typeof t?t:fd(+t),u):l},u.paddingLeft=function(t){return arguments.length?(c="function"==typeof t?t:fd(+t),u):c},u}function Xd(t,e,n,r,o){var i,s,a=t.children,l=a.length,c=new Array(l+1);for(c[0]=s=i=0;i<l;++i)c[i+1]=s+=a[i].value;!function t(e,n,r,o,i,s,l){if(e>=n-1){var u=a[e];return u.x0=o,u.y0=i,u.x1=s,void(u.y1=l)}var f=c[e],d=r/2+f,h=e+1,p=n-1;for(;h<p;){var m=h+p>>>1;c[m]<d?h=m+1:p=m}d-c[h-1]<c[h]-d&&e+1<h&&--h;var g=c[h]-f,y=r-g;if(s-o>l-i){var v=r?(o*y+s*g)/r:s;t(e,h,g,o,i,v,l),t(h,n,y,v,i,s,l)}else{var b=r?(i*y+l*g)/r:l;t(e,h,g,o,i,s,b),t(h,n,y,o,b,s,l)}}(0,l,t.value,e,n,r,o)}function Qd(t,e,n,r,o){(1&t.depth?Wd:Fd)(t,e,n,r,o)}const th=function t(e){function n(t,n,r,o,i){if((s=t._squarify)&&s.ratio===e)for(var s,a,l,c,u,f=-1,d=s.length,h=t.value;++f<d;){for(l=(a=s[f]).children,c=a.value=0,u=l.length;c<u;++c)a.value+=l[c].value;a.dice?Fd(a,n,r,o,h?r+=(i-r)*a.value/h:i):Wd(a,n,r,h?n+=(o-n)*a.value/h:o,i),h-=a.value}else t._squarify=s=Vd(e,t,n,r,o,i),s.ratio=e}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(Hd);var eh=n(4321),nh=n(5409),rh=n(7855),oh=n(6261);function ih(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}var sh=n(8190);function ah(t,e){var n=(0,sh.wx)(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}var lh=n(5003),ch=n(8765),uh=n(5250);function fh(t){return((t=Math.exp(t))+1/t)/2}const dh=function t(e,n,r){function o(t,o){var i,s,a=t[0],l=t[1],c=t[2],u=o[0],f=o[1],d=o[2],h=u-a,p=f-l,m=h*h+p*p;if(m<1e-12)s=Math.log(d/c)/e,i=function(t){return[a+t*h,l+t*p,c*Math.exp(e*t*s)]};else{var g=Math.sqrt(m),y=(d*d-c*c+r*m)/(2*c*n*g),v=(d*d-c*c-r*m)/(2*d*n*g),b=Math.log(Math.sqrt(y*y+1)-y),w=Math.log(Math.sqrt(v*v+1)-v);s=(w-b)/e,i=function(t){var r=t*s,o=fh(b),i=c/(n*g)*(o*function(t){return((t=Math.exp(2*t))-1)/(t+1)}(e*r+b)-function(t){return((t=Math.exp(t))-1/t)/2}(b));return[a+i*h,l+i*p,c*o/fh(e*r+b)]}}return i.duration=1e3*s*e/Math.SQRT2,i}return o.rho=function(e){var n=Math.max(.001,+e),r=n*n;return t(n,r,r*r)},o}(Math.SQRT2,2,4);function hh(t){return function(e,n){var r=t((e=(0,$e.Ym)(e)).h,(n=(0,$e.Ym)(n)).h),o=(0,sh.ZP)(e.s,n.s),i=(0,sh.ZP)(e.l,n.l),s=(0,sh.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.s=o(t),e.l=i(t),e.opacity=s(t),e+""}}}const ph=hh(sh.wx);var mh=hh(sh.ZP);function gh(t,e){var n=(0,sh.ZP)((t=Fr(t)).l,(e=Fr(e)).l),r=(0,sh.ZP)(t.a,e.a),o=(0,sh.ZP)(t.b,e.b),i=(0,sh.ZP)(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=r(e),t.b=o(e),t.opacity=i(e),t+""}}function yh(t){return function(e,n){var r=t((e=Gr(e)).h,(n=Gr(n)).h),o=(0,sh.ZP)(e.c,n.c),i=(0,sh.ZP)(e.l,n.l),s=(0,sh.ZP)(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=o(t),e.l=i(t),e.opacity=s(t),e+""}}}const vh=yh(sh.wx);var bh=yh(sh.ZP);function wh(t){return function e(n){function r(e,r){var o=t((e=no(e)).h,(r=no(r)).h),i=(0,sh.ZP)(e.s,r.s),s=(0,sh.ZP)(e.l,r.l),a=(0,sh.ZP)(e.opacity,r.opacity);return function(t){return e.h=o(t),e.s=i(t),e.l=s(Math.pow(t,n)),e.opacity=a(t),e+""}}return n=+n,r.gamma=e,r}(1)}const _h=wh(sh.wx);var xh=wh(sh.ZP),kh=n(9444);function qh(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t(r/(e-1));return n}function Nh(t){for(var e,n=-1,r=t.length,o=t[r-1],i=0;++n<r;)e=o,o=t[n],i+=e[1]*o[0]-e[0]*o[1];return i/2}function Sh(t){for(var e,n,r=-1,o=t.length,i=0,s=0,a=t[o-1],l=0;++r<o;)e=a,a=t[r],l+=n=e[0]*a[1]-a[0]*e[1],i+=(e[0]+a[0])*n,s+=(e[1]+a[1])*n;return[i/(l*=3),s/l]}function Ah(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function Mh(t,e){return t[0]-e[0]||t[1]-e[1]}function Th(t){const e=t.length,n=[0,1];let r,o=2;for(r=2;r<e;++r){for(;o>1&&Ah(t[n[o-2]],t[n[o-1]],t[r])<=0;)--o;n[o++]=r}return n.slice(0,o)}function Ch(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),o=new Array(n);for(e=0;e<n;++e)r[e]=[+t[e][0],+t[e][1],e];for(r.sort(Mh),e=0;e<n;++e)o[e]=[r[e][0],-r[e][1]];var i=Th(r),s=Th(o),a=s[0]===i[0],l=s[s.length-1]===i[i.length-1],c=[];for(e=i.length-1;e>=0;--e)c.push(t[r[i[e]][2]]);for(e=+a;e<s.length-l;++e)c.push(t[r[s[e]][2]]);return c}function jh(t,e){for(var n,r,o=t.length,i=t[o-1],s=e[0],a=e[1],l=i[0],c=i[1],u=!1,f=0;f<o;++f)n=(i=t[f])[0],(r=i[1])>a!=c>a&&s<(l-n)*(a-r)/(c-r)+n&&(u=!u),l=n,c=r;return u}function Eh(t){for(var e,n,r=-1,o=t.length,i=t[o-1],s=i[0],a=i[1],l=0;++r<o;)e=s,n=a,e-=s=(i=t[r])[0],n-=a=i[1],l+=Math.hypot(e,n);return l}const Oh=Math.random,Ih=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,1===arguments.length?(n=t,t=0):n-=t,function(){return e()*n+t}}return n.source=t,n}(Oh),Rh=function t(e){function n(t,n){return arguments.length<2&&(n=t,t=0),t=Math.floor(t),n=Math.floor(n)-t,function(){return Math.floor(e()*n+t)}}return n.source=t,n}(Oh),Ph=function t(e){function n(t,n){var r,o;return t=null==t?0:+t,n=null==n?1:+n,function(){var i;if(null!=r)i=r,r=null;else do{r=2*e()-1,i=2*e()-1,o=r*r+i*i}while(!o||o>1);return t+n*i*Math.sqrt(-2*Math.log(o)/o)}}return n.source=t,n}(Oh),Fh=function t(e){var n=Ph.source(e);function r(){var t=n.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Oh),Dh=function t(e){function n(t){return(t=+t)<=0?()=>0:function(){for(var n=0,r=t;r>1;--r)n+=e();return n+r*e()}}return n.source=t,n}(Oh),Lh=function t(e){var n=Dh.source(e);function r(t){if(0==(t=+t))return e;var r=n(t);return function(){return r()/t}}return r.source=t,r}(Oh),$h=function t(e){function n(t){return function(){return-Math.log1p(-e())/t}}return n.source=t,n}(Oh),Zh=function t(e){function n(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-e(),t)}}return n.source=t,n}(Oh),zh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(e()+t)}}return n.source=t,n}(Oh),Uh=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-e())/t)})}return n.source=t,n}(Oh),Bh=function t(e){var n=Ph.source(e)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-e())*r;var o=(t<1?t+1:t)-1/3,i=1/(3*Math.sqrt(o)),s=t<1?()=>Math.pow(e(),1/t):()=>1;return function(){do{do{var t=n(),a=1+i*t}while(a<=0);a*=a*a;var l=1-e()}while(l>=1-.0331*t*t*t*t&&Math.log(l)>=.5*t*t+o*(1-a+Math.log(a)));return o*a*s()*r}}return r.source=t,r}(Oh),Gh=function t(e){var n=Bh.source(e);function r(t,e){var r=n(t),o=n(e);return function(){var t=r();return 0===t?0:t/(t+o())}}return r.source=t,r}(Oh),Jh=function t(e){var n=Uh.source(e),r=Gh.source(e);function o(t,e){return t=+t,(e=+e)>=1?()=>t:e<=0?()=>0:function(){for(var o=0,i=t,s=e;i*s>16&&i*(1-s)>16;){var a=Math.floor((i+1)*s),l=r(a,i-a+1)();l<=s?(o+=a,i-=a,s=(s-l)/(1-l)):(i=a-1,s/=l)}for(var c=s<.5,u=n(c?s:1-s),f=u(),d=0;f<=i;++d)f+=u();return o+(c?d:i-d)}}return o.source=t,o}(Oh),Wh=function t(e){function n(t,n,r){var o;return 0==(t=+t)?o=t=>-Math.log(t):(t=1/t,o=e=>Math.pow(e,t)),n=null==n?0:+n,r=null==r?1:+r,function(){return n+r*o(-Math.log1p(-e()))}}return n.source=t,n}(Oh),Hh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){return t+n*Math.tan(Math.PI*e())}}return n.source=t,n}(Oh),Vh=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){var r=e();return t+n*Math.log(r/(1-r))}}return n.source=t,n}(Oh),Yh=function t(e){var n=Bh.source(e),r=Jh.source(e);function o(t){return function(){for(var o=0,i=t;i>16;){var s=Math.floor(.875*i),a=n(s)();if(a>i)return o+r(s-1,i/a)();o+=s,i-=a}for(var l=-Math.log1p(-e()),c=0;l<=i;++c)l-=Math.log1p(-e());return o+c}}return o.source=t,o}(Oh),Kh=1664525,Xh=1013904223,Qh=1/4294967296;function tp(t=Math.random()){let e=0|(0<=t&&t<1?t/Qh:Math.abs(t));return()=>(e=Kh*e+Xh|0,Qh*(e>>>0))}var ep=n(4635),np=n(7763),rp=n(4090);const op=(0,rp.Z)("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),ip=(0,rp.Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),sp=(0,rp.Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),ap=(0,rp.Z)("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),lp=(0,rp.Z)("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),cp=(0,rp.Z)("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),up=(0,rp.Z)("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),fp=(0,rp.Z)("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),dp=(0,rp.Z)("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),hp=t=>(0,Ze.hD)(t[t.length-1]);var pp=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(rp.Z);const mp=hp(pp);var gp=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(rp.Z);const yp=hp(gp);var vp=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(rp.Z);const bp=hp(vp);var wp=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(rp.Z);const _p=hp(wp);var xp=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(rp.Z);const kp=hp(xp);var qp=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(rp.Z);const Np=hp(qp);var Sp=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(rp.Z);const Ap=hp(Sp);var Mp=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(rp.Z);const Tp=hp(Mp);var Cp=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(rp.Z);const jp=hp(Cp);var Ep=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(rp.Z);const Op=hp(Ep);var Ip=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(rp.Z);const Rp=hp(Ip);var Pp=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(rp.Z);const Fp=hp(Pp);var Dp=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(rp.Z);const Lp=hp(Dp);var $p=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(rp.Z);const Zp=hp($p);var zp=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(rp.Z);const Up=hp(zp);var Bp=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(rp.Z);const Gp=hp(Bp);var Jp=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(rp.Z);const Wp=hp(Jp);var Hp=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(rp.Z);const Vp=hp(Hp);var Yp=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(rp.Z);const Kp=hp(Yp);var Xp=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(rp.Z);const Qp=hp(Xp);var tm=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(rp.Z);const em=hp(tm);var nm=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(rp.Z);const rm=hp(nm);var om=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(rp.Z);const im=hp(om);var sm=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(rp.Z);const am=hp(sm);var lm=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(rp.Z);const cm=hp(lm);var um=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(rp.Z);const fm=hp(um);var dm=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(rp.Z);const hm=hp(dm);function pm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}const mm=xh(no(300,.5,0),no(-240,.5,1));var gm=xh(no(-100,.75,.35),no(80,1.5,.8)),ym=xh(no(260,.75,.35),no(80,1.5,.8)),vm=no();function bm(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return vm.h=360*t-100,vm.s=1.5-1.5*e,vm.l=.8-.9*e,vm+""}var wm=(0,$e.B8)(),_m=Math.PI/3,xm=2*Math.PI/3;function km(t){var e;return t=(.5-t)*Math.PI,wm.r=255*(e=Math.sin(t))*e,wm.g=255*(e=Math.sin(t+_m))*e,wm.b=255*(e=Math.sin(t+xm))*e,wm+""}function qm(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}function Nm(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const Sm=Nm((0,rp.Z)("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Am=Nm((0,rp.Z)("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Mm=Nm((0,rp.Z)("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Tm=Nm((0,rp.Z)("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Cm(t){return Lt(Nt(t).call(document.documentElement))}var jm=0;function Em(){return new Om}function Om(){this._="@"+(++jm).toString(36)}function Im(t,e){return t.target&&(t=Wt(t),void 0===e&&(e=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>Ht(t,e)))}function Rm(t){return"string"==typeof t?new Pt([document.querySelectorAll(t)],[document.documentElement]):new Pt([M(t)],Rt)}function Pm(t){return function(){return t}}Om.prototype=Em.prototype={constructor:Om,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}};const Fm=Math.abs,Dm=Math.atan2,Lm=Math.cos,$m=Math.max,Zm=Math.min,zm=Math.sin,Um=Math.sqrt,Bm=1e-12,Gm=Math.PI,Jm=Gm/2,Wm=2*Gm;function Hm(t){return t>=1?Jm:t<=-1?-Jm:Math.asin(t)}function Vm(t){return t.innerRadius}function Ym(t){return t.outerRadius}function Km(t){return t.startAngle}function Xm(t){return t.endAngle}function Qm(t){return t&&t.padAngle}function tg(t,e,n,r,o,i,s){var a=t-n,l=e-r,c=(s?i:-i)/Um(a*a+l*l),u=c*l,f=-c*a,d=t+u,h=e+f,p=n+u,m=r+f,g=(d+p)/2,y=(h+m)/2,v=p-d,b=m-h,w=v*v+b*b,_=o-i,x=d*m-p*h,k=(b<0?-1:1)*Um($m(0,_*_*w-x*x)),q=(x*b-v*k)/w,N=(-x*v-b*k)/w,S=(x*b+v*k)/w,A=(-x*v+b*k)/w,M=q-g,T=N-y,C=S-g,j=A-y;return M*M+T*T>C*C+j*j&&(q=S,N=A),{cx:q,cy:N,x01:-u,y01:-f,x11:q*(o/_-1),y11:N*(o/_-1)}}function eg(){var t=Vm,e=Ym,n=Pm(0),r=null,o=Km,i=Xm,s=Qm,a=null;function l(){var l,c,u=+t.apply(this,arguments),f=+e.apply(this,arguments),d=o.apply(this,arguments)-Jm,h=i.apply(this,arguments)-Jm,p=Fm(h-d),m=h>d;if(a||(a=l=dr()),f<u&&(c=f,f=u,u=c),f>Bm)if(p>Wm-Bm)a.moveTo(f*Lm(d),f*zm(d)),a.arc(0,0,f,d,h,!m),u>Bm&&(a.moveTo(u*Lm(h),u*zm(h)),a.arc(0,0,u,h,d,m));else{var g,y,v=d,b=h,w=d,_=h,x=p,k=p,q=s.apply(this,arguments)/2,N=q>Bm&&(r?+r.apply(this,arguments):Um(u*u+f*f)),S=Zm(Fm(f-u)/2,+n.apply(this,arguments)),A=S,M=S;if(N>Bm){var T=Hm(N/u*zm(q)),C=Hm(N/f*zm(q));(x-=2*T)>Bm?(w+=T*=m?1:-1,_-=T):(x=0,w=_=(d+h)/2),(k-=2*C)>Bm?(v+=C*=m?1:-1,b-=C):(k=0,v=b=(d+h)/2)}var j=f*Lm(v),E=f*zm(v),O=u*Lm(_),I=u*zm(_);if(S>Bm){var R,P=f*Lm(b),F=f*zm(b),D=u*Lm(w),L=u*zm(w);if(p<Gm&&(R=function(t,e,n,r,o,i,s,a){var l=n-t,c=r-e,u=s-o,f=a-i,d=f*l-u*c;if(!(d*d<Bm))return[t+(d=(u*(e-i)-f*(t-o))/d)*l,e+d*c]}(j,E,D,L,P,F,O,I))){var $=j-R[0],Z=E-R[1],z=P-R[0],U=F-R[1],B=1/zm(function(t){return t>1?0:t<-1?Gm:Math.acos(t)}(($*z+Z*U)/(Um($*$+Z*Z)*Um(z*z+U*U)))/2),G=Um(R[0]*R[0]+R[1]*R[1]);A=Zm(S,(u-G)/(B-1)),M=Zm(S,(f-G)/(B+1))}}k>Bm?M>Bm?(g=tg(D,L,j,E,f,M,m),y=tg(P,F,O,I,f,M,m),a.moveTo(g.cx+g.x01,g.cy+g.y01),M<S?a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,M,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,f,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),!m),a.arc(y.cx,y.cy,M,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):(a.moveTo(j,E),a.arc(0,0,f,v,b,!m)):a.moveTo(j,E),u>Bm&&x>Bm?A>Bm?(g=tg(O,I,P,F,u,-A,m),y=tg(j,E,D,L,u,-A,m),a.lineTo(g.cx+g.x01,g.cy+g.y01),A<S?a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(y.y01,y.x01),!m):(a.arc(g.cx,g.cy,A,Dm(g.y01,g.x01),Dm(g.y11,g.x11),!m),a.arc(0,0,u,Dm(g.cy+g.y11,g.cx+g.x11),Dm(y.cy+y.y11,y.cx+y.x11),m),a.arc(y.cx,y.cy,A,Dm(y.y11,y.x11),Dm(y.y01,y.x01),!m))):a.arc(0,0,u,_,w,m):a.lineTo(O,I)}else a.moveTo(0,0);if(a.closePath(),l)return a=null,l+""||null}return l.centroid=function(){var n=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,r=(+o.apply(this,arguments)+ +i.apply(this,arguments))/2-Gm/2;return[Lm(r)*n,zm(r)*n]},l.innerRadius=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),l):t},l.outerRadius=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),l):e},l.cornerRadius=function(t){return arguments.length?(n="function"==typeof t?t:Pm(+t),l):n},l.padRadius=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Pm(+t),l):r},l.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),l):o},l.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:Pm(+t),l):i},l.padAngle=function(t){return arguments.length?(s="function"==typeof t?t:Pm(+t),l):s},l.context=function(t){return arguments.length?(a=null==t?null:t,l):a},l}var ng=Array.prototype.slice;function rg(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function og(t){this._context=t}function ig(t){return new og(t)}function sg(t){return t[0]}function ag(t){return t[1]}function lg(t,e){var n=Pm(!0),r=null,o=ig,i=null;function s(s){var a,l,c,u=(s=rg(s)).length,f=!1;for(null==r&&(i=o(c=dr())),a=0;a<=u;++a)!(a<u&&n(l=s[a],a,s))===f&&((f=!f)?i.lineStart():i.lineEnd()),f&&i.point(+t(l,a,s),+e(l,a,s));if(c)return i=null,c+""||null}return t="function"==typeof t?t:void 0===t?sg:Pm(t),e="function"==typeof e?e:void 0===e?ag:Pm(e),s.x=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),s):t},s.y=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),s):e},s.defined=function(t){return arguments.length?(n="function"==typeof t?t:Pm(!!t),s):n},s.curve=function(t){return arguments.length?(o=t,null!=r&&(i=o(r)),s):o},s.context=function(t){return arguments.length?(null==t?r=i=null:i=o(r=t),s):r},s}function cg(t,e,n){var r=null,o=Pm(!0),i=null,s=ig,a=null;function l(l){var c,u,f,d,h,p=(l=rg(l)).length,m=!1,g=new Array(p),y=new Array(p);for(null==i&&(a=s(h=dr())),c=0;c<=p;++c){if(!(c<p&&o(d=l[c],c,l))===m)if(m=!m)u=c,a.areaStart(),a.lineStart();else{for(a.lineEnd(),a.lineStart(),f=c-1;f>=u;--f)a.point(g[f],y[f]);a.lineEnd(),a.areaEnd()}m&&(g[c]=+t(d,c,l),y[c]=+e(d,c,l),a.point(r?+r(d,c,l):g[c],n?+n(d,c,l):y[c]))}if(h)return a=null,h+""||null}function c(){return lg().defined(o).curve(s).context(i)}return t="function"==typeof t?t:void 0===t?sg:Pm(+t),e="function"==typeof e?e:Pm(void 0===e?0:+e),n="function"==typeof n?n:void 0===n?ag:Pm(+n),l.x=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),r=null,l):t},l.x0=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),l):t},l.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Pm(+t),l):r},l.y=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),n=null,l):e},l.y0=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),l):e},l.y1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:Pm(+t),l):n},l.lineX0=l.lineY0=function(){return c().x(t).y(e)},l.lineY1=function(){return c().x(t).y(n)},l.lineX1=function(){return c().x(r).y(e)},l.defined=function(t){return arguments.length?(o="function"==typeof t?t:Pm(!!t),l):o},l.curve=function(t){return arguments.length?(s=t,null!=i&&(a=s(i)),l):s},l.context=function(t){return arguments.length?(null==t?i=a=null:a=s(i=t),l):i},l}function ug(t,e){return e<t?-1:e>t?1:e>=t?0:NaN}function fg(t){return t}function dg(){var t=fg,e=ug,n=null,r=Pm(0),o=Pm(Wm),i=Pm(0);function s(s){var a,l,c,u,f,d=(s=rg(s)).length,h=0,p=new Array(d),m=new Array(d),g=+r.apply(this,arguments),y=Math.min(Wm,Math.max(-Wm,o.apply(this,arguments)-g)),v=Math.min(Math.abs(y)/d,i.apply(this,arguments)),b=v*(y<0?-1:1);for(a=0;a<d;++a)(f=m[p[a]=a]=+t(s[a],a,s))>0&&(h+=f);for(null!=e?p.sort((function(t,n){return e(m[t],m[n])})):null!=n&&p.sort((function(t,e){return n(s[t],s[e])})),a=0,c=h?(y-d*b)/h:0;a<d;++a,g=u)l=p[a],u=g+((f=m[l])>0?f*c:0)+b,m[l]={data:s[l],index:a,value:f,startAngle:g,endAngle:u,padAngle:v};return m}return s.value=function(e){return arguments.length?(t="function"==typeof e?e:Pm(+e),s):t},s.sortValues=function(t){return arguments.length?(e=t,n=null,s):e},s.sort=function(t){return arguments.length?(n=t,e=null,s):n},s.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),s):r},s.endAngle=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),s):o},s.padAngle=function(t){return arguments.length?(i="function"==typeof t?t:Pm(+t),s):i},s}og.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}};var hg=mg(ig);function pg(t){this._curve=t}function mg(t){function e(e){return new pg(t(e))}return e._curve=t,e}function gg(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function yg(){return gg(lg().curve(hg))}function vg(){var t=cg().curve(hg),e=t.curve,n=t.lineX0,r=t.lineX1,o=t.lineY0,i=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return gg(n())},delete t.lineX0,t.lineEndAngle=function(){return gg(r())},delete t.lineX1,t.lineInnerRadius=function(){return gg(o())},delete t.lineY0,t.lineOuterRadius=function(){return gg(i())},delete t.lineY1,t.curve=function(t){return arguments.length?e(mg(t)):e()._curve},t}function bg(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}pg.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}};class wg{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e)}this._x0=t,this._y0=e}}class _g{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,e){if(t=+t,e=+e,0==this._point++)this._x0=t,this._y0=e;else{const n=bg(this._x0,this._y0),r=bg(this._x0,this._y0=(this._y0+e)/2),o=bg(t,this._y0),i=bg(t,e);this._context.moveTo(...n),this._context.bezierCurveTo(...r,...o,...i)}}}function xg(t){return new wg(t,!0)}function kg(t){return new wg(t,!1)}function qg(t){return new _g(t)}function Ng(t){return t.source}function Sg(t){return t.target}function Ag(t){let e=Ng,n=Sg,r=sg,o=ag,i=null,s=null;function a(){let a;const l=ng.call(arguments),c=e.apply(this,l),u=n.apply(this,l);if(null==i&&(s=t(a=dr())),s.lineStart(),l[0]=c,s.point(+r.apply(this,l),+o.apply(this,l)),l[0]=u,s.point(+r.apply(this,l),+o.apply(this,l)),s.lineEnd(),a)return s=null,a+""||null}return a.source=function(t){return arguments.length?(e=t,a):e},a.target=function(t){return arguments.length?(n=t,a):n},a.x=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),a):r},a.y=function(t){return arguments.length?(o="function"==typeof t?t:Pm(+t),a):o},a.context=function(e){return arguments.length?(null==e?i=s=null:s=t(i=e),a):i},a}function Mg(){return Ag(xg)}function Tg(){return Ag(kg)}function Cg(){const t=Ag(qg);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}const jg=Um(3),Eg={draw(t,e){const n=.59436*Um(e+Zm(e/28,.75)),r=n/2,o=r*jg;t.moveTo(0,n),t.lineTo(0,-n),t.moveTo(-o,-r),t.lineTo(o,r),t.moveTo(-o,r),t.lineTo(o,-r)}},Og={draw(t,e){const n=Um(e/Gm);t.moveTo(n,0),t.arc(0,0,n,0,Wm)}},Ig={draw(t,e){const n=Um(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},Rg=Um(1/3),Pg=2*Rg,Fg={draw(t,e){const n=Um(e/Pg),r=n*Rg;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},Dg={draw(t,e){const n=.62625*Um(e);t.moveTo(0,-n),t.lineTo(n,0),t.lineTo(0,n),t.lineTo(-n,0),t.closePath()}},Lg={draw(t,e){const n=.87559*Um(e-Zm(e/7,2));t.moveTo(-n,0),t.lineTo(n,0),t.moveTo(0,n),t.lineTo(0,-n)}},$g={draw(t,e){const n=Um(e),r=-n/2;t.rect(r,r,n,n)}},Zg={draw(t,e){const n=.4431*Um(e);t.moveTo(n,n),t.lineTo(n,-n),t.lineTo(-n,-n),t.lineTo(-n,n),t.closePath()}},zg=zm(Gm/10)/zm(7*Gm/10),Ug=zm(Wm/10)*zg,Bg=-Lm(Wm/10)*zg,Gg={draw(t,e){const n=Um(.8908130915292852*e),r=Ug*n,o=Bg*n;t.moveTo(0,-n),t.lineTo(r,o);for(let e=1;e<5;++e){const i=Wm*e/5,s=Lm(i),a=zm(i);t.lineTo(a*n,-s*n),t.lineTo(s*r-a*o,a*r+s*o)}t.closePath()}},Jg=Um(3),Wg={draw(t,e){const n=-Um(e/(3*Jg));t.moveTo(0,2*n),t.lineTo(-Jg*n,-n),t.lineTo(Jg*n,-n),t.closePath()}},Hg=Um(3),Vg={draw(t,e){const n=.6824*Um(e),r=n/2,o=n*Hg/2;t.moveTo(0,-n),t.lineTo(o,r),t.lineTo(-o,r),t.closePath()}},Yg=-.5,Kg=Um(3)/2,Xg=1/Um(12),Qg=3*(Xg/2+1),ty={draw(t,e){const n=Um(e/Qg),r=n/2,o=n*Xg,i=r,s=n*Xg+n,a=-i,l=s;t.moveTo(r,o),t.lineTo(i,s),t.lineTo(a,l),t.lineTo(Yg*r-Kg*o,Kg*r+Yg*o),t.lineTo(Yg*i-Kg*s,Kg*i+Yg*s),t.lineTo(Yg*a-Kg*l,Kg*a+Yg*l),t.lineTo(Yg*r+Kg*o,Yg*o-Kg*r),t.lineTo(Yg*i+Kg*s,Yg*s-Kg*i),t.lineTo(Yg*a+Kg*l,Yg*l-Kg*a),t.closePath()}},ey={draw(t,e){const n=.6189*Um(e-Zm(e/6,1.7));t.moveTo(-n,-n),t.lineTo(n,n),t.moveTo(-n,n),t.lineTo(n,-n)}},ny=[Og,Ig,Fg,$g,Gg,Wg,ty],ry=[Og,Lg,ey,Vg,Eg,Zg,Dg];function oy(t,e){let n=null;function r(){let r;if(n||(n=r=dr()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),r)return n=null,r+""||null}return t="function"==typeof t?t:Pm(t||Og),e="function"==typeof e?e:Pm(void 0===e?64:+e),r.type=function(e){return arguments.length?(t="function"==typeof e?e:Pm(e),r):t},r.size=function(t){return arguments.length?(e="function"==typeof t?t:Pm(+t),r):e},r.context=function(t){return arguments.length?(n=null==t?null:t,r):n},r}function iy(){}function sy(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function ay(t){this._context=t}function ly(t){return new ay(t)}function cy(t){this._context=t}function uy(t){return new cy(t)}function fy(t){this._context=t}function dy(t){return new fy(t)}function hy(t,e){this._basis=new ay(t),this._beta=e}ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:sy(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},cy.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},fy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:sy(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},hy.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,o=t[0],i=e[0],s=t[n]-o,a=e[n]-i,l=-1;++l<=n;)r=l/n,this._basis.point(this._beta*t[l]+(1-this._beta)*(o+r*s),this._beta*e[l]+(1-this._beta)*(i+r*a));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const py=function t(e){function n(t){return 1===e?new ay(t):new hy(t,e)}return n.beta=function(e){return t(+e)},n}(.85);function my(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function gy(t,e){this._context=t,this._k=(1-e)/6}gy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:my(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const yy=function t(e){function n(t){return new gy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function vy(t,e){this._context=t,this._k=(1-e)/6}vy.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const by=function t(e){function n(t){return new vy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function wy(t,e){this._context=t,this._k=(1-e)/6}wy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:my(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const _y=function t(e){function n(t){return new wy(t,e)}return n.tension=function(e){return t(+e)},n}(0);function xy(t,e,n){var r=t._x1,o=t._y1,i=t._x2,s=t._y2;if(t._l01_a>Bm){var a=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,l=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*a-t._x0*t._l12_2a+t._x2*t._l01_2a)/l,o=(o*a-t._y0*t._l12_2a+t._y2*t._l01_2a)/l}if(t._l23_a>Bm){var c=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,u=3*t._l23_a*(t._l23_a+t._l12_a);i=(i*c+t._x1*t._l23_2a-e*t._l12_2a)/u,s=(s*c+t._y1*t._l23_2a-n*t._l12_2a)/u}t._context.bezierCurveTo(r,o,i,s,t._x2,t._y2)}function ky(t,e){this._context=t,this._alpha=e}ky.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const qy=function t(e){function n(t){return e?new ky(t,e):new gy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ny(t,e){this._context=t,this._alpha=e}Ny.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const Sy=function t(e){function n(t){return e?new Ny(t,e):new vy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ay(t,e){this._context=t,this._alpha=e}Ay.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:xy(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const My=function t(e){function n(t){return e?new Ay(t,e):new wy(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Ty(t){this._context=t}function Cy(t){return new Ty(t)}function jy(t){return t<0?-1:1}function Ey(t,e,n){var r=t._x1-t._x0,o=e-t._x1,i=(t._y1-t._y0)/(r||o<0&&-0),s=(n-t._y1)/(o||r<0&&-0),a=(i*o+s*r)/(r+o);return(jy(i)+jy(s))*Math.min(Math.abs(i),Math.abs(s),.5*Math.abs(a))||0}function Oy(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function Iy(t,e,n){var r=t._x0,o=t._y0,i=t._x1,s=t._y1,a=(i-r)/3;t._context.bezierCurveTo(r+a,o+a*e,i-a,s-a*n,i,s)}function Ry(t){this._context=t}function Py(t){this._context=new Fy(t)}function Fy(t){this._context=t}function Dy(t){return new Ry(t)}function Ly(t){return new Py(t)}function $y(t){this._context=t}function Zy(t){var e,n,r=t.length-1,o=new Array(r),i=new Array(r),s=new Array(r);for(o[0]=0,i[0]=2,s[0]=t[0]+2*t[1],e=1;e<r-1;++e)o[e]=1,i[e]=4,s[e]=4*t[e]+2*t[e+1];for(o[r-1]=2,i[r-1]=7,s[r-1]=8*t[r-1]+t[r],e=1;e<r;++e)n=o[e]/i[e-1],i[e]-=n,s[e]-=n*s[e-1];for(o[r-1]=s[r-1]/i[r-1],e=r-2;e>=0;--e)o[e]=(s[e]-o[e+1])/i[e];for(i[r-1]=(t[r]+o[r-1])/2,e=0;e<r-1;++e)i[e]=2*t[e+1]-o[e+1];return[o,i]}function zy(t){return new $y(t)}function Uy(t,e){this._context=t,this._t=e}function By(t){return new Uy(t,.5)}function Gy(t){return new Uy(t,0)}function Jy(t){return new Uy(t,1)}function Wy(t,e){if((o=t.length)>1)for(var n,r,o,i=1,s=t[e[0]],a=s.length;i<o;++i)for(r=s,s=t[e[i]],n=0;n<a;++n)s[n][1]+=s[n][0]=isNaN(r[n][1])?r[n][0]:r[n][1]}function Hy(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function Vy(t,e){return t[e]}function Yy(t){const e=[];return e.key=t,e}function Ky(){var t=Pm([]),e=Hy,n=Wy,r=Vy;function o(o){var i,s,a=Array.from(t.apply(this,arguments),Yy),l=a.length,c=-1;for(const t of o)for(i=0,++c;i<l;++i)(a[i][c]=[0,+r(t,a[i].key,c,o)]).data=t;for(i=0,s=rg(e(a));i<l;++i)a[s[i]].index=i;return n(a,s),a}return o.keys=function(e){return arguments.length?(t="function"==typeof e?e:Pm(Array.from(e)),o):t},o.value=function(t){return arguments.length?(r="function"==typeof t?t:Pm(+t),o):r},o.order=function(t){return arguments.length?(e=null==t?Hy:"function"==typeof t?t:Pm(Array.from(t)),o):e},o.offset=function(t){return arguments.length?(n=null==t?Wy:t,o):n},o}function Xy(t,e){if((r=t.length)>0){for(var n,r,o,i=0,s=t[0].length;i<s;++i){for(o=n=0;n<r;++n)o+=t[n][i][1]||0;if(o)for(n=0;n<r;++n)t[n][i][1]/=o}Wy(t,e)}}function Qy(t,e){if((a=t.length)>0)for(var n,r,o,i,s,a,l=0,c=t[e[0]].length;l<c;++l)for(i=s=0,n=0;n<a;++n)(o=(r=t[e[n]][l])[1]-r[0])>0?(r[0]=i,r[1]=i+=o):o<0?(r[1]=s,r[0]=s+=o):(r[0]=0,r[1]=o)}function tv(t,e){if((n=t.length)>0){for(var n,r=0,o=t[e[0]],i=o.length;r<i;++r){for(var s=0,a=0;s<n;++s)a+=t[s][r][1]||0;o[r][1]+=o[r][0]=-a/2}Wy(t,e)}}function ev(t,e){if((o=t.length)>0&&(r=(n=t[e[0]]).length)>0){for(var n,r,o,i=0,s=1;s<r;++s){for(var a=0,l=0,c=0;a<o;++a){for(var u=t[e[a]],f=u[s][1]||0,d=(f-(u[s-1][1]||0))/2,h=0;h<a;++h){var p=t[e[h]];d+=(p[s][1]||0)-(p[s-1][1]||0)}l+=f,c+=d*f}n[s-1][1]+=n[s-1][0]=i,l&&(i-=c/l)}n[s-1][1]+=n[s-1][0]=i,Wy(t,e)}}function nv(t){var e=t.map(rv);return Hy(t).sort((function(t,n){return e[t]-e[n]}))}function rv(t){for(var e,n=-1,r=0,o=t.length,i=-1/0;++n<o;)(e=+t[n][1])>i&&(i=e,r=n);return r}function ov(t){var e=t.map(iv);return Hy(t).sort((function(t,n){return e[t]-e[n]}))}function iv(t){for(var e,n=0,r=-1,o=t.length;++r<o;)(e=+t[r][1])&&(n+=e);return n}function sv(t){return ov(t).reverse()}function av(t){var e,n,r=t.length,o=t.map(iv),i=nv(t),s=0,a=0,l=[],c=[];for(e=0;e<r;++e)n=i[e],s<a?(s+=o[n],l.push(n)):(a+=o[n],c.push(n));return c.reverse().concat(l)}function lv(t){return Hy(t).reverse()}Ty.prototype={areaStart:iy,areaEnd:iy,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}},Ry.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Iy(this,this._t0,Oy(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,Iy(this,Oy(this,n=Ey(this,t,e)),n);break;default:Iy(this,this._t0,n=Ey(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}},(Py.prototype=Object.create(Ry.prototype)).point=function(t,e){Ry.prototype.point.call(this,e,t)},Fy.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,o,i){this._context.bezierCurveTo(e,t,r,n,i,o)}},$y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=Zy(t),o=Zy(e),i=0,s=1;s<n;++i,++s)this._context.bezierCurveTo(r[0][i],o[0][i],r[1][i],o[1][i],t[s],e[s]);(this._line||0!==this._line&&1===n)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}},Uy.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}};var cv=n(3606),uv=n(8383),fv=n(1343),dv=n(2991),hv=n(6596),pv=n(8467),mv=n(6018),gv=n(7905),yv=n(2311),vv=n(8593),bv=n(8927),wv=n(7445),_v=n(1887),xv=n(7351),kv=n(4552),qv=n(7150),Nv=n(1852),Sv=n(3015),Av="%Y-%m-%dT%H:%M:%S.%LZ";var Mv=Date.prototype.toISOString?function(t){return t.toISOString()}:(0,Nv.g0)(Av);const Tv=Mv;var Cv=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:(0,Nv.wp)(Av);const jv=Cv;function Ev(t,e,n){var r=new le,o=e;return null==e?(r.restart(t,e,n),r):(r._restart=r.restart,r.restart=function(t,e,n){e=+e,n=null==n?se():+n,r._restart((function i(s){s+=o,r._restart(i,o+=e,n),t(s)}),e,n)},r.restart(t,e,n),r)}const Ov=t=>()=>t;function Iv(t,{sourceEvent:e,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function Rv(t,e,n){this.k=t,this.x=e,this.y=n}Rv.prototype={constructor:Rv,scale:function(t){return 1===t?this:new Rv(this.k*t,this.x,this.y)},translate:function(t,e){return 0===t&0===e?this:new Rv(this.k,this.x+this.k*t,this.y+this.k*e)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pv=new Rv(1,0,0);function Fv(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Pv;return t.__zoom}function Dv(t){t.stopImmediatePropagation()}function Lv(t){t.preventDefault(),t.stopImmediatePropagation()}function $v(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function Zv(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function zv(){return this.__zoom||Pv}function Uv(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Bv(){return navigator.maxTouchPoints||"ontouchstart"in this}function Gv(t,e,n){var r=t.invertX(e[0][0])-n[0][0],o=t.invertX(e[1][0])-n[1][0],i=t.invertY(e[0][1])-n[0][1],s=t.invertY(e[1][1])-n[1][1];return t.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),s>i?(i+s)/2:Math.min(0,i)||Math.max(0,s))}function Jv(){var t,e,n,r=$v,o=Zv,i=Gv,s=Uv,a=Bv,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,f=dh,d=N("start","zoom","end"),h=500,p=150,m=0,g=10;function y(t){t.property("__zoom",zv).on("wheel.zoom",q,{passive:!1}).on("mousedown.zoom",S).on("dblclick.zoom",A).filter(a).on("touchstart.zoom",M).on("touchmove.zoom",T).on("touchend.zoom touchcancel.zoom",C).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function v(t,e){return(e=Math.max(l[0],Math.min(l[1],e)))===t.k?t:new Rv(e,t.x,t.y)}function b(t,e,n){var r=e[0]-n[0]*t.k,o=e[1]-n[1]*t.k;return r===t.x&&o===t.y?t:new Rv(t.k,r,o)}function w(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function _(t,e,n,r){t.on("start.zoom",(function(){x(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){x(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,i=arguments,s=x(t,i).event(r),a=o.apply(t,i),l=null==n?w(a):"function"==typeof n?n.apply(t,i):n,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),u=t.__zoom,d="function"==typeof e?e.apply(t,i):e,h=f(u.invert(l).concat(c/u.k),d.invert(l).concat(c/d.k));return function(t){if(1===t)t=d;else{var e=h(t),n=c/e[2];t=new Rv(n,l[0]-e[0]*n,l[1]-e[1]*n)}s.zoom(null,t)}}))}function x(t,e,n){return!n&&t.__zooming||new k(t,e)}function k(t,e){this.that=t,this.args=e,this.active=0,this.sourceEvent=null,this.extent=o.apply(t,e),this.taps=0}function q(t,...e){if(r.apply(this,arguments)){var n=x(this,e).event(t),o=this.__zoom,a=Math.max(l[0],Math.min(l[1],o.k*Math.pow(2,s.apply(this,arguments)))),u=Ht(t);if(n.wheel)n.mouse[0][0]===u[0]&&n.mouse[0][1]===u[1]||(n.mouse[1]=o.invert(n.mouse[0]=u)),clearTimeout(n.wheel);else{if(o.k===a)return;n.mouse=[u,o.invert(u)],Me(this),n.start()}Lv(t),n.wheel=setTimeout((function(){n.wheel=null,n.end()}),p),n.zoom("mouse",i(b(v(o,a),n.mouse[0],n.mouse[1]),n.extent,c))}}function S(t,...e){if(!n&&r.apply(this,arguments)){var o=t.currentTarget,s=x(this,e,!0).event(t),a=Lt(t.view).on("mousemove.zoom",(function(t){if(Lv(t),!s.moved){var e=t.clientX-u,n=t.clientY-f;s.moved=e*e+n*n>m}s.event(t).zoom("mouse",i(b(s.that.__zoom,s.mouse[0]=Ht(t,o),s.mouse[1]),s.extent,c))}),!0).on("mouseup.zoom",(function(t){a.on("mousemove.zoom mouseup.zoom",null),Gt(t.view,s.moved),Lv(t),s.event(t).end()}),!0),l=Ht(t,o),u=t.clientX,f=t.clientY;Bt(t.view),Dv(t),s.mouse=[l,this.__zoom.invert(l)],Me(this),s.start()}}function A(t,...e){if(r.apply(this,arguments)){var n=this.__zoom,s=Ht(t.changedTouches?t.changedTouches[0]:t,this),a=n.invert(s),l=n.k*(t.shiftKey?.5:2),f=i(b(v(n,l),s,a),o.apply(this,e),c);Lv(t),u>0?Lt(this).transition().duration(u).call(_,f,s,t):Lt(this).call(y.transform,f,s,t)}}function M(n,...o){if(r.apply(this,arguments)){var i,s,a,l,c=n.touches,u=c.length,f=x(this,o,n.changedTouches.length===u).event(n);for(Dv(n),s=0;s<u;++s)l=[l=Ht(a=c[s],this),this.__zoom.invert(l),a.identifier],f.touch0?f.touch1||f.touch0[2]===l[2]||(f.touch1=l,f.taps=0):(f.touch0=l,i=!0,f.taps=1+!!t);t&&(t=clearTimeout(t)),i&&(f.taps<2&&(e=l[0],t=setTimeout((function(){t=null}),h)),Me(this),f.start())}}function T(t,...e){if(this.__zooming){var n,r,o,s,a=x(this,e).event(t),l=t.changedTouches,u=l.length;for(Lv(t),n=0;n<u;++n)o=Ht(r=l[n],this),a.touch0&&a.touch0[2]===r.identifier?a.touch0[0]=o:a.touch1&&a.touch1[2]===r.identifier&&(a.touch1[0]=o);if(r=a.that.__zoom,a.touch1){var f=a.touch0[0],d=a.touch0[1],h=a.touch1[0],p=a.touch1[1],m=(m=h[0]-f[0])*m+(m=h[1]-f[1])*m,g=(g=p[0]-d[0])*g+(g=p[1]-d[1])*g;r=v(r,Math.sqrt(m/g)),o=[(f[0]+h[0])/2,(f[1]+h[1])/2],s=[(d[0]+p[0])/2,(d[1]+p[1])/2]}else{if(!a.touch0)return;o=a.touch0[0],s=a.touch0[1]}a.zoom("touch",i(b(r,o,s),a.extent,c))}}function C(t,...r){if(this.__zooming){var o,i,s=x(this,r).event(t),a=t.changedTouches,l=a.length;for(Dv(t),n&&clearTimeout(n),n=setTimeout((function(){n=null}),h),o=0;o<l;++o)i=a[o],s.touch0&&s.touch0[2]===i.identifier?delete s.touch0:s.touch1&&s.touch1[2]===i.identifier&&delete s.touch1;if(s.touch1&&!s.touch0&&(s.touch0=s.touch1,delete s.touch1),s.touch0)s.touch0[1]=this.__zoom.invert(s.touch0[0]);else if(s.end(),2===s.taps&&(i=Ht(i,this),Math.hypot(e[0]-i[0],e[1]-i[1])<g)){var c=Lt(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return y.transform=function(t,e,n,r){var o=t.selection?t.selection():t;o.property("__zoom",zv),t!==o?_(t,e,n,r):o.interrupt().each((function(){x(this,arguments).event(r).start().zoom(null,"function"==typeof e?e.apply(this,arguments):e).end()}))},y.scaleBy=function(t,e,n,r){y.scaleTo(t,(function(){return this.__zoom.k*("function"==typeof e?e.apply(this,arguments):e)}),n,r)},y.scaleTo=function(t,e,n,r){y.transform(t,(function(){var t=o.apply(this,arguments),r=this.__zoom,s=null==n?w(t):"function"==typeof n?n.apply(this,arguments):n,a=r.invert(s),l="function"==typeof e?e.apply(this,arguments):e;return i(b(v(r,l),s,a),t,c)}),n,r)},y.translateBy=function(t,e,n,r){y.transform(t,(function(){return i(this.__zoom.translate("function"==typeof e?e.apply(this,arguments):e,"function"==typeof n?n.apply(this,arguments):n),o.apply(this,arguments),c)}),null,r)},y.translateTo=function(t,e,n,r,s){y.transform(t,(function(){var t=o.apply(this,arguments),s=this.__zoom,a=null==r?w(t):"function"==typeof r?r.apply(this,arguments):r;return i(Pv.translate(a[0],a[1]).scale(s.k).translate("function"==typeof e?-e.apply(this,arguments):-e,"function"==typeof n?-n.apply(this,arguments):-n),t,c)}),r,s)},k.prototype={event:function(t){return t&&(this.sourceEvent=t),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(t,e){return this.mouse&&"mouse"!==t&&(this.mouse[1]=e.invert(this.mouse[0])),this.touch0&&"touch"!==t&&(this.touch0[1]=e.invert(this.touch0[0])),this.touch1&&"touch"!==t&&(this.touch1[1]=e.invert(this.touch1[0])),this.that.__zoom=e,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(t){var e=Lt(this.that).datum();d.call(t,this.that,new Iv(t,{sourceEvent:this.sourceEvent,target:y,type:t,transform:this.that.__zoom,dispatch:d}),e)}},y.wheelDelta=function(t){return arguments.length?(s="function"==typeof t?t:Ov(+t),y):s},y.filter=function(t){return arguments.length?(r="function"==typeof t?t:Ov(!!t),y):r},y.touchable=function(t){return arguments.length?(a="function"==typeof t?t:Ov(!!t),y):a},y.extent=function(t){return arguments.length?(o="function"==typeof t?t:Ov([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),y):o},y.scaleExtent=function(t){return arguments.length?(l[0]=+t[0],l[1]=+t[1],y):[l[0],l[1]]},y.translateExtent=function(t){return arguments.length?(c[0][0]=+t[0][0],c[1][0]=+t[1][0],c[0][1]=+t[0][1],c[1][1]=+t[1][1],y):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},y.constrain=function(t){return arguments.length?(i=t,y):i},y.duration=function(t){return arguments.length?(u=+t,y):u},y.interpolate=function(t){return arguments.length?(f=t,y):f},y.on=function(){var t=d.on.apply(d,arguments);return t===d?y:t},y.clickDistance=function(t){return arguments.length?(m=(t=+t)*t,y):Math.sqrt(m)},y.tapDistance=function(t){return arguments.length?(g=+t,y):g},y}Fv.prototype=Rv.prototype},8828:(t,e,n)=>{"use strict";n.d(e,{H:()=>o,L:()=>r});class r extends Map{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const[e,n]of t)this.set(e,n)}get(t){return super.get(i(this,t))}has(t){return super.has(i(this,t))}set(t,e){return super.set(s(this,t),e)}delete(t){return super.delete(a(this,t))}}class o extends Set{constructor(t,e=l){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const e of t)this.add(e)}has(t){return super.has(i(this,t))}add(t){return super.add(s(this,t))}delete(t){return super.delete(a(this,t))}}function i({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function s({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function a({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function l(t){return null!==t&&"object"==typeof t?t.valueOf():t}}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,n),i.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{"use strict";var t=n(334),e=n.n(t),r=n(141),o=n(7147),i=n.n(o),s=n(1017),a=n.n(s);{const t=i().readdirSync(a().join(e().binpath,"/routes")).filter((t=>t.endsWith(".ts"))).map((t=>{const e=n(126)(`./${t}`);return e.file=t,e}));!function(t,e,n={}){const r=Object.assign({basepath:""},n);for(const n of e){const e=n.api;for(const n in e.methods){const o=e.methods[n];t[n](`${r.basepath}/${e.endpoint}`,o.init(r))}}!function(t,e){if(e.apiJson){const n=JSON.stringify(t.map((t=>t.api))),r=s.dirname(e.apiJson);o.existsSync(r)||o.mkdirSync(r,{recursive:!0}),o.writeFileSync(e.apiJson,n)}if(e.types){const n=function(t,e){const n={};for(const{file:e,route:r}of t){const t=r.api;for(const r in t.methods){const o=t.methods[r];o.alternativeFor||(n[e]||(n[e]=new Set),o.request.typeId&&n[e].add(o.request.typeId),o.response.typeId&&n[e].add(o.response.typeId))}}const r=["import { createValidate } from 'typia'"],o=[];for(const t in n){const i=Array.from(n[t]);r.push(`import { ${i.join(", ")} } from '${e}/${t}'`);for(const t of i)o.push(`export const valid${t} = createValidate<${t}>()`)}return r.join("\n")+"\n\n"+o.join("\n")}(t.map((t=>({file:t.file,route:t}))),e.types.importDir),r=s.dirname(e.types.outputFile);o.existsSync(r)||o.mkdirSync(r,{recursive:!0}),o.writeFileSync(e.types.outputFile,n)}}(e,r)}(r.l2,t,{app:r.l2,genomes:r.g_,basepath:r.LJ,apiJson:a().join(__dirname,"../../public/docs/server-api.json"),types:{importDir:"../types/routes",outputFile:a().join(__dirname,"./shared/checkers-raw/index.ts")}})}(0,r.lE)(e()).then((async()=>{if(console.log(`\n${new Date} ${e().commitHash||""}`),console.log("\nValidation succeeded.\n"),"validate"!=process.argv[2])if("phewas-precompute"!=process.argv[2])await(0,r.OG)();else{const t=process.argv[3],e=process.argv[4],n=r.g_[t];if(!n)throw"invalid genome name: "+t;const o=n.datasets[e];if(!o)throw"invalid dataset: "+e;r.U_.do_precompute(o)}else console.log("You may now run the server.")})).catch((t=>{let n=1;if(!i().existsSync(e().tpmasterdir)){const t=e().maintenance||{};if("start"in t&&"stop"in t&&"tpErrorCode"in t){const e=+new Date(t.start),r=+new Date(t.stop),o=+new Date;e<=o&&o<=r&&(n=t.tpErrorCode)}}t.stack&&console.log(t.stack),n?console.error("\n!!!\n"+t+"\n\n"):console.log("\n!!!\n"+t+"\n\n"),process.exit(n)}))})()})();
|