jbrowse-plugin-graphgenomeviewer 10.0.3 → 10.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/chunks/{AddTrackWorkflow-W7XIQ5F3.js → AddTrackWorkflow-47H3VBK4.js} +2 -2
  2. package/dist/chunks/{GbzBaseSyntenyAdapter-JMYDJODG.js → GbzBaseSyntenyAdapter-X6AW5IYW.js} +2 -2
  3. package/dist/chunks/{GraphGenomeView-7KODXFCZ.js → GraphGenomeView-ZTZEYNUY.js} +2 -2
  4. package/dist/chunks/{LinearGraphDisplay-ZAIMEATG.js → LinearGraphDisplay-QWJZ5PSO.js} +2 -2
  5. package/dist/chunks/{MinigraphBubbleAdapter-N5BOXD7U.js → MinigraphBubbleAdapter-WUTIBCFA.js} +2 -2
  6. package/dist/chunks/{RgfaTabixAdapter-FZZ7W2HN.js → RgfaTabixAdapter-VT7TYMNE.js} +2 -2
  7. package/dist/chunks/{WalkFormsAdapter-TZW5UBRI.js → WalkFormsAdapter-VRJ4FYQB.js} +2 -2
  8. package/dist/chunks/{WalkTabixSyntenyAdapter-XM7HBNJA.js → WalkTabixSyntenyAdapter-ZYWYXAC7.js} +2 -2
  9. package/dist/chunks/{WalkTabixSyntenyAdapter-XM7HBNJA.js.map → WalkTabixSyntenyAdapter-ZYWYXAC7.js.map} +2 -2
  10. package/dist/chunks/{chunk-NLHJYXCS.js → chunk-5FMNLEED.js} +2 -2
  11. package/dist/chunks/{chunk-TMF6JHCE.js → chunk-MQ43JVZM.js} +2 -2
  12. package/dist/chunks/{chunk-D7BAG2VJ.js → chunk-P7V5S3V3.js} +2 -2
  13. package/dist/chunks/{chunk-D7BAG2VJ.js.map → chunk-P7V5S3V3.js.map} +2 -2
  14. package/dist/chunks/chunk-TDHUAADJ.js +6 -0
  15. package/dist/chunks/chunk-TDHUAADJ.js.map +7 -0
  16. package/dist/chunks/{chunk-JLIDLLZG.js → chunk-UPSA4KVF.js} +2 -2
  17. package/dist/chunks/{chunk-HTVBMX7V.js → chunk-UXBGMTAO.js} +2 -2
  18. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -1
  19. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +1 -1
  20. package/package.json +2 -2
  21. package/src/RgfaTabixAdapter/walkReader.ts +4 -2
  22. package/src/WalkTabixSyntenyAdapter/WalkTabixSyntenyAdapter.ts +1 -1
  23. package/src/version.ts +1 -1
  24. package/dist/chunks/chunk-CTQBRAQH.js +0 -6
  25. package/dist/chunks/chunk-CTQBRAQH.js.map +0 -7
  26. /package/dist/chunks/{AddTrackWorkflow-W7XIQ5F3.js.map → AddTrackWorkflow-47H3VBK4.js.map} +0 -0
  27. /package/dist/chunks/{GbzBaseSyntenyAdapter-JMYDJODG.js.map → GbzBaseSyntenyAdapter-X6AW5IYW.js.map} +0 -0
  28. /package/dist/chunks/{GraphGenomeView-7KODXFCZ.js.map → GraphGenomeView-ZTZEYNUY.js.map} +0 -0
  29. /package/dist/chunks/{LinearGraphDisplay-ZAIMEATG.js.map → LinearGraphDisplay-QWJZ5PSO.js.map} +0 -0
  30. /package/dist/chunks/{MinigraphBubbleAdapter-N5BOXD7U.js.map → MinigraphBubbleAdapter-WUTIBCFA.js.map} +0 -0
  31. /package/dist/chunks/{RgfaTabixAdapter-FZZ7W2HN.js.map → RgfaTabixAdapter-VT7TYMNE.js.map} +0 -0
  32. /package/dist/chunks/{WalkFormsAdapter-TZW5UBRI.js.map → WalkFormsAdapter-VRJ4FYQB.js.map} +0 -0
  33. /package/dist/chunks/{chunk-NLHJYXCS.js.map → chunk-5FMNLEED.js.map} +0 -0
  34. /package/dist/chunks/{chunk-TMF6JHCE.js.map → chunk-MQ43JVZM.js.map} +0 -0
  35. /package/dist/chunks/{chunk-JLIDLLZG.js.map → chunk-UPSA4KVF.js.map} +0 -0
  36. /package/dist/chunks/{chunk-HTVBMX7V.js.map → chunk-UXBGMTAO.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{a as D,c as U,d as V,e as X,f as q,h as K}from"./chunk-YROUE32O.js";import{d as Q}from"./chunk-D3QZGLZ3.js";import{c as M,d as P}from"./chunk-WKD7ALOU.js";import{f as E}from"./chunk-HTVBMX7V.js";import"./chunk-CTQBRAQH.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{b as R,h as A,j as v,n as x}from"./chunk-5L276I7O.js";import{i as r}from"./chunk-J2PN6CG3.js";import{B as j,C as z,D as J,G as h,a as H,f as I,g as d,o as B,t as N,u as _,v as O}from"./chunk-H42TSPVA.js";import{b as t,c as T,d as W}from"./chunk-DUU6T2I5.js";var i=JBrowseExports["@jbrowse/core/util/tss-react"],le=o=>i!=null&&o in Object(i)?i[o]:Object.assign(function(){throw new Error("This JBrowse does not provide '"+o+"' from '@jbrowse/core/util/tss-react' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse")},{jbrowseHostMissing:o});var Y=le("makeStyles"),de=i&&i.__esModule?i.default:i;async function Z(o,a,s){try{let{references:p}=await E(o,a,s).header({signal:AbortSignal.timeout(D)});return p[0]}catch{return}}var pe=Y()(o=>({paper:{margin:o.spacing(),padding:o.spacing()},field:{marginTop:o.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),ce=["RgfaTabixAdapter","WalkTabixSyntenyAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],me=W(function({model:a}){let{classes:s}=pe(),p=v(a),u=M(a),[n,$]=r("RgfaTabixAdapter"),[l,ee]=r(),[f,F]=r(),[G,te]=r(),g=n==="GbzBaseSyntenyAdapter",c=n==="WalkTabixSyntenyAdapter",[b,ae]=r(""),[S,oe]=r(""),[y,re]=r("Pangenome graph"),[C,k]=r(),[w,L]=r(!1);async function se(){if(!l||!a.assembly)return;k(void 0),L(!0);let{pluginManager:e}=A(a),[ne,ie]=await Promise.all([n==="RgfaTabixAdapter"?U(l,e):void 0,c&&!b.trim()?Z(l,f,e):void 0]);if(L(!1),!(!P(a)||!a.assembly))try{let m=y.trim();R({model:a,session:p,conf:K({choice:n,loc:l,indexLoc:f,readsLoc:g?G:void 0,manifest:ne,assembly:a.assembly,sample:b,haplotypes:c?Q(S):void 0,walkReference:ie,trackId:x({name:m}),name:m})})}catch(m){k(m)}}return T(j,{className:s.paper,children:[C?t(I,{error:C}):null,T(N,{children:[t(O,{children:"File type"}),t(J,{value:n,onChange:e=>{$(e.target.value),F(void 0),k(void 0)},children:ce.map(e=>t(_,{value:e,control:t(z,{}),label:V[e]},e))})]}),t(d,{location:l,name:X[n],rootModel:u,setLocation:ee}),t(d,{location:f,name:q[n],rootModel:u,setLocation:F}),g?t(d,{location:G,name:"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)",rootModel:u,setLocation:te}):null,t(h,{className:s.field,value:b,onChange:e=>{ae(e.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:g?"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample":c?"Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz":"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare",placeholder:"GRCh38",fullWidth:!0}),c?t(h,{className:s.field,value:S,onChange:e=>{oe(e.target.value)},label:"Haplotypes",slotProps:{htmlInput:{"data-testid":"graph-haplotypes-input"}},helperText:"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file",placeholder:"HG002, HG00733",fullWidth:!0}):null,t(h,{className:s.field,value:y,label:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:e=>{re(e.target.value)}}),t(H,{session:p,helperText:"Select assembly to add track to",selected:a.assembly,onChange:e=>{a.setAssembly(e)},fullWidth:!0}),t(B,{variant:"contained",className:s.submit,disabled:!l||!y.trim()||!a.assembly||w,onClick:()=>{se()},children:w?"Reading\u2026":"Submit"})]})}),Ae=me;export{Ae as default};
2
- //# sourceMappingURL=AddTrackWorkflow-W7XIQ5F3.js.map
1
+ import{a as D,c as U,d as V,e as X,f as q,h as K}from"./chunk-YROUE32O.js";import{d as Q}from"./chunk-D3QZGLZ3.js";import{c as M,d as P}from"./chunk-WKD7ALOU.js";import{f as E}from"./chunk-UXBGMTAO.js";import"./chunk-TDHUAADJ.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{b as R,h as A,j as v,n as x}from"./chunk-5L276I7O.js";import{i as r}from"./chunk-J2PN6CG3.js";import{B as j,C as z,D as J,G as h,a as H,f as I,g as d,o as B,t as N,u as _,v as O}from"./chunk-H42TSPVA.js";import{b as t,c as T,d as W}from"./chunk-DUU6T2I5.js";var i=JBrowseExports["@jbrowse/core/util/tss-react"],le=o=>i!=null&&o in Object(i)?i[o]:Object.assign(function(){throw new Error("This JBrowse does not provide '"+o+"' from '@jbrowse/core/util/tss-react' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse")},{jbrowseHostMissing:o});var Y=le("makeStyles"),de=i&&i.__esModule?i.default:i;async function Z(o,a,s){try{let{references:p}=await E(o,a,s).header({signal:AbortSignal.timeout(D)});return p[0]}catch{return}}var pe=Y()(o=>({paper:{margin:o.spacing(),padding:o.spacing()},field:{marginTop:o.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),ce=["RgfaTabixAdapter","WalkTabixSyntenyAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],me=W(function({model:a}){let{classes:s}=pe(),p=v(a),u=M(a),[n,$]=r("RgfaTabixAdapter"),[l,ee]=r(),[f,F]=r(),[G,te]=r(),g=n==="GbzBaseSyntenyAdapter",c=n==="WalkTabixSyntenyAdapter",[b,ae]=r(""),[S,oe]=r(""),[y,re]=r("Pangenome graph"),[C,k]=r(),[w,L]=r(!1);async function se(){if(!l||!a.assembly)return;k(void 0),L(!0);let{pluginManager:e}=A(a),[ne,ie]=await Promise.all([n==="RgfaTabixAdapter"?U(l,e):void 0,c&&!b.trim()?Z(l,f,e):void 0]);if(L(!1),!(!P(a)||!a.assembly))try{let m=y.trim();R({model:a,session:p,conf:K({choice:n,loc:l,indexLoc:f,readsLoc:g?G:void 0,manifest:ne,assembly:a.assembly,sample:b,haplotypes:c?Q(S):void 0,walkReference:ie,trackId:x({name:m}),name:m})})}catch(m){k(m)}}return T(j,{className:s.paper,children:[C?t(I,{error:C}):null,T(N,{children:[t(O,{children:"File type"}),t(J,{value:n,onChange:e=>{$(e.target.value),F(void 0),k(void 0)},children:ce.map(e=>t(_,{value:e,control:t(z,{}),label:V[e]},e))})]}),t(d,{location:l,name:X[n],rootModel:u,setLocation:ee}),t(d,{location:f,name:q[n],rootModel:u,setLocation:F}),g?t(d,{location:G,name:"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)",rootModel:u,setLocation:te}):null,t(h,{className:s.field,value:b,onChange:e=>{ae(e.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:g?"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample":c?"Optional. The PanSN sample this assembly is in the graph; blank takes it from the file name, GRCh38 in chr22.GRCh38.walks.gz":"Optional. The PanSN prefix the graph gives this assembly, e.g. GRCh38 for HPRC's GRCh38#0#chr1; leave blank when the graph's stable names are bare",placeholder:"GRCh38",fullWidth:!0}),c?t(h,{className:s.field,value:S,onChange:e=>{oe(e.target.value)},label:"Haplotypes",slotProps:{htmlInput:{"data-testid":"graph-haplotypes-input"}},helperText:"Optional. The haplotypes the track cuts for until you pick others in its menu, as PanSN names separated by commas (HG002#1, or HG002 for both); blank is every haplotype in the file",placeholder:"HG002, HG00733",fullWidth:!0}):null,t(h,{className:s.field,value:y,label:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:e=>{re(e.target.value)}}),t(H,{session:p,helperText:"Select assembly to add track to",selected:a.assembly,onChange:e=>{a.setAssembly(e)},fullWidth:!0}),t(B,{variant:"contained",className:s.submit,disabled:!l||!y.trim()||!a.assembly||w,onClick:()=>{se()},children:w?"Reading\u2026":"Submit"})]})}),Ae=me;export{Ae as default};
2
+ //# sourceMappingURL=AddTrackWorkflow-47H3VBK4.js.map
@@ -1,4 +1,4 @@
1
- import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j as gn,k as Fe,l as Te,m as Ne,n as wn,o as mn,p as yn,q as bn,r as xn,s as Rn,t as $n,u as Hn,v as Cn}from"./chunk-NLHJYXCS.js";import{a as Nn}from"./chunk-JLIDLLZG.js";import{a as vn}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{a as bs,b as Ln,c as Mn,d as Ht}from"./chunk-3GK5ZBUB.js";import{a as In,g as kn,h as Lt,i as Mt}from"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import{T as En,c as Sn}from"./chunk-RQSCKHNS.js";import"./chunk-FQI75MV6.js";import{b as _e,d as An}from"./chunk-HTVBMX7V.js";import{k as Pn}from"./chunk-CTQBRAQH.js";import"./chunk-TMM73K4C.js";import{a as $e}from"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as Rt,g as Ae,h as Re,i as $t}from"./chunk-H5PFNYKH.js";import{e as hn,q as At}from"./chunk-5L276I7O.js";var ze=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},On=255,xs=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new ze(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<On?Math.floor(xs/this.sigma):0}next(){if(this.sigma>=On){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Bn(a){let e=new ze(a),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let o=e.int(),i=e.int();if(o===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=o,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),o=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:o+(e-n)};t[s.value]=o+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:ee(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],o=t[s];$(r.node)===$(o.node)&&(t[s-1]=o,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(o=>o.offset),t=0;for(let o of this.runs())t+=o.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let o of this.runs()){let i=this.edge(o.value),c=e[o.value];for(let d=0;d<o.len;d++)n[r]=i.node,s[r]=c,c+=1,r+=1;e[o.value]=c}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Ss=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Fn(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<e;d++){for(let S=0;S<16;S++)o[S]=n.getUint32(d*64+S*4);for(let S=16;S<64;S++){let I=o[S-15],N=o[S-2],y=we(I,7)^we(I,18)^I>>>3,E=we(N,17)^we(N,19)^N>>>10;o[S]=o[S-16]+y+o[S-7]+E}let h=r[0],f=r[1],p=r[2],w=r[3],u=r[4],l=r[5],b=r[6],x=r[7];for(let S=0;S<64;S++){let I=we(u,6)^we(u,11)^we(u,25),N=u&l^~u&b,y=x+I+N+Ss[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),R=h&f^h&p^f&p;x=b,b=l,l=u,u=w+y|0,w=p,p=f,f=h,h=y+E+R|0}[h,f,p,w,u,l,b,x].forEach((S,I)=>{r[I]=r[I]+S})}let i=new Uint8Array(32),c=new DataView(i.buffer);for(let d=0;d<8;d++)c.setUint32(d*4,r[d]);return i}function Tn(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[r,o]=s;if(s.length!==2||!r||!o)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(o)}return t}function qn(a){return{name:a.get("pggname"),subgraph:Tn(a.get("subgraph"),"subgraph"),translation:Tn(a.get("translation"),"translation")}}function _n(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let r of n)s.add(r)}}function Dn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),_n(t.subgraph,e.subgraph),_n(t.translation,e.translation)),t}function zn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Gn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of zn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of zn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function jn(a){let e=a.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of a)t.set(o,n),n+=o.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Fn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Is="_gbwt_ref";function pe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Es=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,ks=/^([^#]+?)(?:\[\d+-\d+\])?$/;function vs(a){let e=Es.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=ks.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Le(a){return typeof a=="string"?vs(a):a}function Me(a,e){return{sample:a.sample??Is,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ps=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ps?n[1]=t:e.push([t,t])}return e}var Ns=32768,Un={mostChosenPaths:32},Ct=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},oe=class extends Error{};function tt(a,e,t,n){return a==="forward"?e+t:e-n}function Wn(a,e,t,n){return a==="forward"?e-n:e+t}function Qn(a){return Ne(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function qe(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Vn(a){let{db:e,records:t,signal:n}=a,s=performance.now(),r=()=>{let m=performance.now(),k=m-s;return s=m,k},o={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(m,k)=>{let A=`${m}: ${k}`;o.walks[A]=(o.walks[A]??0)+1},c=await e.haplotypeSampleInterval()??4096,d=new Map,h=async m=>{let k=t.get(m)??d.get(m);if(k)return k;let A=await e.getRecord(m);if(o.graphFetches+=1,!A)throw new Error(`Node record ${m} is missing from the database`);return d.set(m,A),A},f=m=>t.get(m).sequenceLen,p=await e.pathsByHandle(),w=m=>{let k=p.get(m);return k!==void 0&&a.keep(k.name)},u=[],l=new Ct,b=new Map,x=new Set,S=new Set,I=async m=>{let k=(await h(m.node)).gbwt().lf(m.offset);return k===void 0||k.node===0?void 0:k},N=async(m,k)=>{let A=(await h(ee(m.node))).gbwt().predecessorAt(m.offset);if(A===void 0||k!==void 0&&!k.has(A))return;let L=(await h(A)).gbwt().offsetTo(m);if(L===void 0)throw new Error(`No offset in ${A} leads to ${m.node}:${m.offset}`);return{node:A,offset:L}},y=(m,k,A,L)=>{let B=A.map(U=>U.pos.node),j=A.map(U=>U.pos.offset),Y=0;for(let U of B)Y+=f(U);let C=k==="forward"?A[0].left:A[A.length-1].left,M=u.length;u.push({pathHandle:m,orientation:k,handles:B,offsets:j,len:Y,hapStart:C,hapEnd:C+Y,canonical:Ne(B[0],B[B.length-1]),source:L});for(let U of A)l.set(U.pos,M);let Q=b.get(m);return Q?Q.push(M):b.set(m,[M]),M},E=async(m,k,A,L)=>{let B=[],j=m;for(;;){n?.throwIfAborted();let C=await N(j.pos,t);if(!C)break;j={pos:C,left:Wn(A,j.left,f(j.pos.node),f(C.node))},B.push(j)}B.reverse();let Y=[m];for(j=m;;){n?.throwIfAborted();let C=await I(j.pos);if(!C||!t.has(C.node))break;j={pos:C,left:tt(A,j.left,f(j.pos.node),f(C.node))},Y.push(j)}return y(k,A,[...B,...Y],L)},R=async(m,k,A,L)=>u[l.get(m.pos)??await E(m,k,A,L)],F=m=>{let k=m.handles[m.handles.length-1];return{pos:{node:k,offset:m.offsets[m.offsets.length-1]},left:m.orientation==="forward"?m.hapEnd-f(k):m.hapStart}},T=m=>{let k=m.handles[0];return{pos:{node:k,offset:m.offsets[0]},left:m.orientation==="forward"?m.hapStart:m.hapEnd-f(k)}},D=await E({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),O=u[D],H=()=>{if(o.fallback!==void 0)return{reference:O,pieces:[],stats:o};let m=new Map;u.forEach((A,L)=>{L!==D&&m.set(qe(A),[...m.get(qe(A))??[],A])});let k=[];for(let A of m.values()){let L=new Set;for(let B of A)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),k.push(B),o.sources[B.source]+=1)}return o.sources.reference=1,o.pieces=k.length+1,{reference:O,pieces:k,stats:o}},v=async(m,k)=>{let A=k?x:S,L=k?S:x,B=m;for(;;){if(A.has(B))return;A.add(B);let j=u[B],Y=k?F(j):T(j),C=0,M;for(;M===void 0;){n?.throwIfAborted();let Q=k?await I(Y.pos):await N(Y.pos);if(!Q){M="endmarker";break}let U=(await h(Y.pos.node)).sequenceLen,ge=(await h(Q.node)).sequenceLen,se=k?tt(j.orientation,Y.left,U,ge):Wn(j.orientation,Y.left,U,ge);if(t.has(Q.node)){let J=l.get(Q);J===void 0?(B=await E({pos:Q,left:se},j.pathHandle,j.orientation,"chain"),L.add(B),M="landed"):(L.add(J),M="merge")}else C>Ns?M="bound":(C+=ge,Y={pos:Q,left:se})}if(i("chain",M),M!=="landed")return}},G=async m=>{if(a.context>m.context)throw new oe(`the context of ${a.context} bp exceeds the ${m.context} bp the haplotype index's stray rows cover`);let k=o.spacing;if(k===void 0)throw new oe("the haplotype index has no anchors");let{bin:A,bound:L}=m,{fills:B,inserted:j}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new oe("the haplotype index's stray rows cover contained snarls only");for(let g of B){if(g.inserted>0&&g.low===g.high)throw new oe(`the haplotype index's stray rows leave out the snarl bounded by node ${g.low} at both ends`);if(g.inserted>0&&(m.snarlNodes===void 0||g.nodes>m.snarlNodes))throw new oe(m.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${g.nodes} nodes exceeds the ${m.snarlNodes} the haplotype index's stray rows cover`)}let Y=Math.floor(a.window.start/A),C=Math.floor((a.window.end-1)/A),M=Y*A,Q=(C+1)*A,U=new Map,ge=async(g,P)=>{let q=await e.haplotypeAnchorsBetween(a.referenceHandle,g*k,P*k);for(let _ of q)U.set(_.anchorOffset/k,_)},se=Math.max(0,Math.floor((M-L)/k)-1),J=Math.ceil((Q+L)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,Y,C),ge(se,J)]);for(let g of t.keys()){let P=$(g);if(!V(g)&&!Ve(P)&&!j.has(P))throw new oe(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}o.scans=Ot([...t.keys()].sort((g,P)=>g-P));let he=Promise.all(o.scans.map(([g,P])=>e.haplotypeSamplesInRange(g,P)));for(he.catch(()=>{});se>0&&(U.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=M-L;)se-=1,await ge(se,se);for(;U.has(J)&&U.get(J).pathOffset<=Q+L;)J+=1,await ge(J,J);let ue=[...U.keys()].sort((g,P)=>g-P),be=U.get(ue[0]??-1);if(!be)throw new oe("the haplotype index has no anchors on this path");let de=g=>U.get(g).pathOffset,Ce=new Map;for(let g of ue){let P=$(U.get(g).node);Ce.set(P,[...Ce.get(P)??[],g])}let vt=[...Ce.keys()],Xt=vt.map(g=>U.get(Ce.get(g)[0]).visits);if(!Xt[vt.indexOf($(be.node))].some(g=>g.pathHandle===a.referenceHandle&&g.orientation==="forward"&&g.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${be.pathOffset} (node ${$(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),gs=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(gs[0]??ue[ue.length-1])],o.anchorsRead=ue.length;let Pt=new Map,Jt=new Set;if(vt.forEach((g,P)=>{let q=Ce.get(g),_=q.length===1?q[0]:void 0;for(let z of Xt[P])Jt.add(z.pathHandle),z.orientation==="forward"&&w(z.pathHandle)&&Pt.set(z.pathHandle,[...Pt.get(z.pathHandle)??[],{k:_,row:z}])}),o.chosenPaths=[...Jt].filter(w).length,o.chosenPaths>Un.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Un.mostChosenPaths}`);let Ze=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[g,P]of Pt){P.sort((q,_)=>q.row.pathOffset-_.row.pathOffset);for(let q=0;q+1<P.length;q++){let _=P[q],z=P[q+1];if(_.k===void 0||z.k===void 0||Math.abs(_.k-z.k)!==1)continue;let[K,te]=de(_.k)<=de(z.k)?[_,z]:[z,_],ne=de(K.k),re=de(te.k);ne<Q&&re>=M?(Ze.push({pathHandle:g,from:_.row,to:z.row}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,re+L)):ne>=Q&&ne-Q<=L?(Ze.push({pathHandle:g,from:K.row,to:void 0}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,ne+L)):re<M&&M-re<=L&&(Ze.push({pathHandle:g,from:te.row,to:void 0}),Ee=Math.min(Ee,re-L),xe=Math.max(xe,re+L))}}let ws=new Set(B.map(g=>`${g.low}:${g.high}`)),ms=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ws.has(`${g.snarl[0]}:${g.snarl[1]}`))).sort((g,P)=>g.pathHandle-P.pathHandle||g.pathStart-P.pathStart);o.strays={bins:C-Y+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ee),xe+1),o.ms.scan=r();let en=8*k+2*(a.window.end-a.window.start),tn=o.strays,Oe=0,nn=g=>{if(tn.outsideBp+=g,Oe+=g,Oe>en)throw new oe(`a walk of a chosen path near the window went past its cap of ${en} bp`)},Nt=new Map,sn=(g,P,q)=>(Nt.get(g)??[]).some(([_,z])=>_<=P&&q<z),rn=(g,P,q)=>{Nt.set(g,[...Nt.get(g)??[],[P,q]])},on=async(g,P,q,_,z)=>{let K=P,te=q,ne=te;for(;K&&te<=_;){n?.throwIfAborted();let re;if(t.has(K.node)){let Be=await R({pos:K,left:te},g,"forward",z),cn=F(Be);K=cn.pos,te=cn.left,re=f(K.node),ne=Math.max(ne,Be.hapEnd)}else re=(await h(K.node)).sequenceLen,nn(re),ne=Math.max(ne,te+re);K=await I(K),te+=re}return ne},ys=async(g,P,q,_)=>{let z={pos:P,left:q},K=q;for(;z.left>_;){n?.throwIfAborted();let te=await N(z.pos);if(!te)break;let ne=(await h(te.node)).sequenceLen,re=z.left-ne;if(t.has(te.node)){let Be=await R({pos:te,left:re},g,"forward","section");z=T(Be),K=Math.min(K,Be.hapStart)}else nn(ne),z={pos:te,left:re},K=Math.min(K,re)}return K};for(let{pathHandle:g,from:P,to:q}of Ze){let _=P.pathOffset,z=(q??P).pathOffset+L;if(sn(g,_-L,z))continue;let K={node:P.node,offset:P.offset};Oe=0;let te=await on(g,K,_,z,"section");Oe=0;let ne=await ys(g,K,_,_-L);rn(g,Math.min(ne,_-L),Math.max(te,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let g of ms){if(sn(g.pathHandle,g.pathStart,g.pathEnd))continue;Oe=0;let P=await on(g.pathHandle,{node:g.node,offset:g.offset},g.pathStart,g.pathEnd,"stray");rn(g.pathHandle,g.pathStart,Math.max(P,g.pathEnd+1)),tn.walked+=1}o.ms.walks=r();let an=[];for(let g of await he)for(let P of g)if(o.scanRows+=1,t.has(P.node)&&w(P.pathHandle)){if(!(b.get(P.pathHandle)??[]).some(q=>{let _=u[q];return _.hapStart<=P.pathOffset&&P.pathOffset<_.hapEnd}))throw new oe(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&an.push(P)}for(let g of an)await R({pos:{node:g.node,offset:g.offset},left:g.pathOffset},g.pathHandle,"reverse","twin");o.ms.check=r()},X=async()=>{let m=new Map,k=C=>{let M=qe(C),Q=m.get(M);Q?Q.add(C.orientation):m.set(M,new Set([C.orientation]))},A=0,L=()=>{for(;A<u.length;A++)k(u[A])};L();let B=C=>(m.get(qe(C))?.size??0)>1,j=2*c,Y=(C,M)=>M===D?w(a.referenceHandle)&&Qn(C):!C.canonical||Qn(C);for(let C=0;C<u.length;C++){let M=u[C];if(B(M)||!Y(M,C))continue;o.twins.tried+=1;let Q=M.orientation==="forward"?"reverse":"forward",U=F(M),ge=0,se;for(;!se&&ge<=j;){n?.throwIfAborted();let ie=await I(U.pos);if(!ie)break;let he=(await h(ie.node)).sequenceLen,ue=tt(M.orientation,U.left,(await h(U.pos.node)).sequenceLen,he),be=ee(ie.node);se=(await e.haplotypeSamplesInRange(be,be)).find(de=>de.pathHandle===M.pathHandle&&de.orientation===Q&&de.pathOffset===ue),ge+=he,U={pos:ie,left:ue}}let J=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},Ve=0;for(;J&&!B(M)&&Ve<=j+M.len;){if(n?.throwIfAborted(),t.has(J.pos.node)){let ie=await R(J,M.pathHandle,Q,"twin"),he=u.indexOf(ie);await v(he,!0),await v(he,!1),L(),J=F(ie)}if(!B(M)){let ie=(await h(J.pos.node)).sequenceLen;Ve+=ie;let he=await I(J.pos);J=he?{pos:he,left:tt(Q,J.left,ie,(await h(he.node)).sequenceLen)}:void 0}}if(L(),!B(M))throw new oe(`piece ${qe(M)} was found in one orientation where extractPaths keeps the other`);o.twins.found+=1}o.ms.twins=r()};try{let m=await e.haplotypeStrayOptions();if(m===void 0)throw new oe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(m),await X()}catch(m){if(!(m instanceof oe))throw m;o.fallback=m.message}return H()}function Zn(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var ae=class extends Error{name="SubgraphLimitError";limit;windowBp;walkedBp;constructor(e,t){super(t===void 0?`Subgraph size limit of ${e} nodes exceeded`:`Subgraph size limit of ${e} nodes exceeded ${t.walkedBp} bp into a ${t.windowBp} bp window`),this.limit=e,this.windowBp=t?.windowBp,this.walkedBp=t?.walkedBp}};function Bt(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var Ge=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let o=r-1>>1;if(Bt(s[r],s[o]))[s[r],s[o]]=[s[o],s[r]],r=o;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,o=r+1,i=s;if(r<e.length&&Bt(e[r],e[i])&&(i=r),o<e.length&&Bt(e[o],e[i])&&(i=o),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function As(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:a.length}}function Rs(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ve(a){return`${a.node}:${a.offset}`}function De(a){return a.map(e=>ee(e)).reverse()}function $s(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Ls(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Xn(r,t.insertion,t.deletion);for(let[d,h]of s.edits)Z(r,d,h);let o=a.identity.walkForward,[i,c]=o?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...c.path],start:i.start,pieces:[...i.pieces,...c.pieces],soloAligned:[...i.soloAligned,...c.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:o}}}function Ms(a,e,t){if(a.some(o=>o.weight!==void 0))return a;let n=new Map;a.forEach((o,i)=>{if(o.identity){let c=n.get(o.identity.pathHandle);c?c.push(i):n.set(o.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let o of n.values()){o.sort((h,f)=>a[h].identity.hapStart-a[f].identity.hapStart);let i=o[0],c=a[i],d=[];for(let h of o.slice(1)){let f=a[h],p=d.length===0?$s(c,f):void 0;if(p){c=Ls(c,f,p),r.add(h);continue}if(!e(f)){d.push(h);continue}let w=e(c)?t([c,...d.map(u=>a[u]),f]):void 0;if(w){c=w;for(let u of[...d,h])r.add(u)}else s.set(i,c),i=h,c=f;d=[]}s.set(i,c)}return a.flatMap((o,i)=>r.has(i)?[]:[s.get(i)??o])}function nt(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Hs=32768;function Cs(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Hs?s[1]=n:t.push([n,n])}return t}var je=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(fe(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new ae(this.limit);let t=await this.db.getRecord(fe(e,"forward")),n=await this.db.getRecord(fe(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${pe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,o=s;for(;;){await this.ensureNode($(o.node));let i=this.record(o.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:o.node,nodeOffset:t-r,gbwtOffset:o.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let c=i.gbwt().lf(o.offset);if(!c)throw new Error(`The fragment of ${pe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);o=c}}async aroundPosition(e,t,n){let s=$(e);await this.ensureNode(s);let r=this.record(e),o=ke(e),i=new Ge;return i.push(t,s,Xe(o)),i.push(r.sequenceLen-t-1,s,Ye(o)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let o=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(o,i),Math.max(o,i)+1]])){let d=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Cs(d.map(h=>h.pos.node)).map(([h,f])=>[h,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof ae&&s.windowBp===void 0?new ae(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,o=t,i=new Ge;for(;;){let c=$(s.node),d=ke(s.node);this.walkedBp=t-o,await this.ensureNode(c);let h=this.record(s.node);if(r>=h.sequenceLen)throw new Error(`Offset ${r} in node ${c} of length ${h.sequenceLen}`);i.push(r,c,Xe(d));let f=h.sequenceLen-r;if(o<=f){i.push(o===f?0:f-o-1,c,Ye(d));break}i.push(0,c,Ye(d));let p=h.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,o-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new Ge;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let o of this.records.keys())s.add($(o));let r=0;for(;e.size>0;){let[o,i,c]=e.pop(),d=`${i}:${c}`;if(n.has(d))continue;n.add(d),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let h=pn(c);if(!n.has(`${i}:${h}`)){let w=this.record(fe(i,un(c))),u=o+w.sequenceLen-1;u<=t&&e.push(u,i,h)}let f=this.record(fe(i,gn(c))),p=o+1;if(p<=t)for(let w of f.successors()){let u=$(w),l=Xe(ke(w));n.has(`${u}:${l}`)||e.push(p,u,l)}}for(let o of s)this.records.delete(fe(o,"forward")),this.records.delete(fe(o,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([$(e),$(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=$(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=$(c);s.has(d)||(n.push(c,ee(c)),s.add(d))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:o}=await this.fillBetween(n,s),i=$(n),c=$(s);this.snarlFills.push({low:Math.min(i,c),high:Math.max(i,c),nodes:o,inserted:r.length});for(let d of r)this.snarlNodes.add(d);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),o=r.next;o!==void 0&&(n=!0,this.hasHandle(o)?Fe(s,o)&&t.push([s,o]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,o]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let d=c.successors(),h=d[0];return h===void 0?!1:d.length>1||(await e(ee(h))).successors().length>1},n=async c=>{let d=await e(ee(c));return d.next!==void 0?await t(d)?{kind:"snarl-exit",snarl:[ee(c),d.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(c=>this.record(c).successors()),o,i=!1;for(;!i&&r.length>0;){let c=r.shift(),d=$(c);if(!this.hasHandle(c)&&!s.has(d)){s.add(d);let h=await n(c);if(h.kind==="snarl-exit")o=h.snarl,i=!0;else if(h.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(fe(d,f))).successors())}}return o}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,o=new Map;s.forEach((y,E)=>o.set(y,E));let i=new Int32Array(r+1),c=new Int32Array(r),d=[];for(let y=0;y<r;y++){let E=this.record(s[y]),R=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push(R),i[y+1]=i[y]+R.nodes.length}let h=i[r],f=new Int32Array(h),p=new Int32Array(h),w=new Uint8Array(h);for(let y=0;y<r;y++){let E=d[y];f.set(E.nodes,i[y]),p.set(E.offsets,i[y])}d.length=0;for(let y=0;y<h;y++){let E=o.get(f[y]);E===void 0?f[y]=-1:(f[y]=E,w[i[E]+p[y]]=1)}let u=n===void 0?void 0:o.get(n.handle),l=n?.gbwtOffset,b,x=(y,E,R)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),R&&(R.push(s[H]),F.push(v)),T+=1,D+=c[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:F,len:D,refAt:O,last:H}},S=(y,E,R,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:R,weight:void 0,identity:void 0})},I=new Int32Array(r);for(let y=0;y<r;y++){let E=s[y];if(!V(E)){let R=i[y],F=i[y+1]-R;for(let T=0;T<F;T++)if(w[R+T]===0){let D=[],{offsets:O,len:H,refAt:v,last:G}=x(y,T,D),X=s[G];if(v>=0||Ne(E,X)){if(S(D,O,H,v),!V(X)){let m=o.get(ee(X));I[m]=I[m]+1}}else this.twinStarts.add(ve({node:E,offset:T}))}}}for(let y=0;y<r;y++){let E=s[y];if(V(E)){let R=i[y],F=i[y+1]-R,T=0;for(let O=0;O<F;O++)w[R+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[R+O]===0){let H=D?void 0:x(y,O,void 0);if(H&&(H.refAt>=0||Ne(E,s[H.last]))){let v=[],{offsets:G,len:X,refAt:m}=x(y,O,v);S(v,G,X,m)}else this.twinStarts.add(ve({node:E,offset:O}))}}}let N=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),N&&(this.refId=this.paths.indexOf(N)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let F of y.path.slice(0,b))E+=this.record(F).sequenceLen;let R=n.seqOffset-E;this.refInterval=[R,R+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:R,hapEnd:R+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Te(n)?De(n):void 0,r=d=>s!==void 0&&Ft(d,s)===0||Te(De(d)),o=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((d,h)=>Ft(d.path,h.path)||d.len-h.len||(d===t?-1:h===t?1:0));let i=[],c;for(let d of this.paths){let h=i[i.length-1],f=o&&d!==t&&r(d.path);this.twinDeferred||=f,h&&Ft(h.path,d.path)===0&&!f?h.weight=(h.weight??1)+(d.weight??1):(d===t&&(c=i.length),i.push({...d,weight:d.weight??1}))}this.paths=i,this.refId=c}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=o=>`${o.pathHandle}:${o.hapStart}-${o.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let o of this.paths)o!==e&&o.identity?.orientation==="forward"&&s.add(n(o.identity));let r=this.paths.filter(o=>o===e||o.identity?.orientation!=="reverse"||!s.has(n(o.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(o=>o.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((o,i)=>i!==this.refId&&o.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((o,i)=>i===this.refId||o.identity!==void 0&&e(o.identity.name)),r=new Set;for(let o of s)for(let i of o.path)r.add($(i));for(let o of[...this.records.keys()])r.has($(o))||this.records.delete(o);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,o=await Vn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(h,f,p)=>this.prefetchReferenceRange(h,f,p)});if(this.stats.keep=o.stats,o.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),c=h=>({path:h.handles,offsets:h.offsets,len:h.len,weight:void 0,identity:{pathHandle:h.pathHandle,name:h===o.reference?e.name:i.get(h.pathHandle).name,orientation:h.orientation,hapStart:h.hapStart,hapEnd:h.hapEnd}}),d=[o.reference,...o.pieces].sort(Zn);return this.paths=d.map(c),this.refId=d.indexOf(o.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[o.reference.hapStart,o.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ot(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ve(l),l);let r=l=>{let b=0,x=t.length-1;for(;b<x;){let I=b+x+1>>1;t[I][0]<=l?b=I:x=I-1}let S=t[b];return S[0]<=l&&l<=S[1]},o=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&o.set(ve(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let c=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),d=l=>(i.graphLookups+=1,c(l)),h=async(l,b)=>{if(r(l.node))return n.get(ve(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},w=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},u=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let N,y=0,E=l,R;for(;N===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){I.end="cycle";break}S.add(E);let H=this.paths[E];x.push({index:E,startBp:y}),I.fragments+=1;let v=y;for(let X=0;X<H.path.length;X++){let m=nt(H,X),k=n.get(ve(m)),A=this.record(m.node).sequenceLen;if(k){N=w(k,v,A);break}v+=A}if(y+=H.len,N){I.end="in-fragment sample";break}let G=nt(H,H.path.length-1);R=this.record(G.node).gbwt().lf(G.offset),E=void 0}if(R===void 0||R.node===0){I.end="endmarker";break}let F=ve(R),T=o.get(F);if(T!==void 0){let H=this.paths[T].identity;if(H){N=u(H,y),I.end="identified sibling";break}E=T;continue}this.records.has(R.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h(R,I),O=await d(R.node);if(D){N=w(D,y,O.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,y-x[x.length-1].startBp>4*e+4*O.sequenceLen){I.end="bound";break}y+=O.sequenceLen,R=O.gbwt().lf(R.offset)}if(N){I.pathHandle=N.pathHandle;let F=await p(N.pathHandle);for(let{index:T,startBp:D}of x){let O=this.paths[T];O.identity=N.orientation==="forward"?{pathHandle:N.pathHandle,name:F,orientation:"forward",hapStart:N.base+D,hapEnd:N.base+D+O.len}:{pathHandle:N.pathHandle,name:F,orientation:"reverse",hapStart:N.base-D-O.len,hapEnd:N.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),o=0,i=-1;for(let c=0;c<e.length;c++){let d=n.get(e[c]);if(d){let h=Rs(d,i);if(h===void 0)return;s[o]=c,r[o]=h,o+=1,i=h}}return{pathAt:s,refAt:r,count:o}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[s]).sequence,d=this.record(t[r]).sequence;for(;o<c.length&&i<d.length;){if(c[o]!==d[i])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[e.length-s-1]).sequence,d=this.record(t[t.length-r-1]).sequence;for(;o<c.length&&i<d.length;){if(c[c.length-o-1]!==d[d.length-i-1])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),o=this.prefixMatches(e,t),i=this.suffixMatches(e,t);o+i>s&&(i=s-o),o+i>r&&(i=r-o),Z(n,"M",o),Xn(n,s-o-i,r-o-i),Z(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??As(yn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],o=this.refPrefix(t),i=(f,p,w,u)=>{f===p?Z(r,"D",o[u]-o[w]):w===u?Z(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(w,u),r)},c=0,d=0,h=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],w=s.refAt[f];(d!==p||h!==w)&&i(d,p,h,w);let u=this.record(e[p]).sequenceLen;Z(r,"M",u),c+=u,d=p+1,h=w+1}return i(d,e.length,h,t.length),{edits:r,matched:c,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Te(n)&&(t.identity===void 0||!Te(De(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=De(t.path),o=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(o===0)s={...this.editsAgainst(r,n),flipped:!0};else{let c=this.editsAgainst(t.path,n),d=this.editsAgainst(r,n);s=d.matched>c.matched?{...d,flipped:!0}:{...c,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(h,f,p,w)=>{let u=Bs(h),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,S=x?.orientation==="forward",[I,N]=S?[l,b]:[b,l];return{strand:f,refStart:e.start+u.leading,refEnd:e.start+n-u.trailing,edits:u.edits,weight:l.weight,path:p.flatMap(y=>this.paths[y].path),start:nt(l,0),pieces:p,soloAligned:w,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+I.identity.hapStart,hapEnd:x.name.fragment+N.identity.hapEnd,walkForward:S}}},r=h=>h.soloAligned.reduce((f,p)=>f+p,0),o=h=>h.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=h=>2*r(h)>=o(h),c=h=>{let f=h[0],p=h[h.length-1],w=f.identity.walkForward;if(h.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==w||G>0&&v.identity.hapStart<h[G-1].identity.hapEnd))return;let u=w?h:[...h].reverse(),l=u.flatMap(v=>v.pieces),b=u.flatMap(v=>v.soloAligned),x=f.strand==="+"!==w,S=l.map(v=>this.paths[v]),I=S.slice(1).map((v,G)=>{let X=S[G].identity;return w?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),N=x?[...S].reverse():S,y=x?[...I].reverse():I,E=N.flatMap(v=>x?De(v.path):v.path),{edits:R}=this.editsAgainst(E,t),F=Kn(R,N.map(v=>v.len)),T=new Map((x?[...l].reverse():l).map((v,G)=>[v,F[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+T.get(X),0)>=r(v);if(!D(f)||!D(p))return;let O=[],H=0;return N.slice(0,-1).forEach((v,G)=>{H+=v.len,O.push([H,y[G]])}),s(Fs(R,O),f.strand,l,b)},d=[];return this.paths.forEach((h,f)=>{if(f===this.refId)return;let{edits:p,flipped:w}=this.alignment(f),u=h.identity,l=u?u.orientation==="forward"!==w:!w;d.push(s(p,l?"+":"-",[f],Kn(p,[h.len])))}),Ms(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:Ts(f)};return p?{...b,resolved:!0,name:p.name,label:pe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(h=>{let{identity:f}=h;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(h,f)}]:[]}),o=h=>f=>f.sample===h.sample&&f.haplotype===h.haplotype,i=o(t),c=n?o(n):h=>!i(h),d=h=>this.record(fe(h,"forward")).sequence;return r.filter(h=>i(h.name)).flatMap(h=>r.filter(f=>c(f.name)).flatMap(f=>bn({...s,query:f.steps,target:h.steps,sequenceOf:d}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:h.name,targetStart:h.start+p.targetStart,targetEnd:h.start+p.targetEnd,cigar:xn(p.edits),matches:p.edits.reduce((w,[u,l])=>w+(u==="="?l:0),0),columns:p.edits.reduce((w,[,u])=>w+u,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=fe(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Fe(s,r)&&t.push([n==="reverse"?1:0,$(r),V(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!V(n)){let s=$(n),r=`S ${s} ${this.record(n).sequence}
1
+ import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j as gn,k as Fe,l as Te,m as Ne,n as wn,o as mn,p as yn,q as bn,r as xn,s as Rn,t as $n,u as Hn,v as Cn}from"./chunk-5FMNLEED.js";import{a as Nn}from"./chunk-UPSA4KVF.js";import{a as vn}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{a as bs,b as Ln,c as Mn,d as Ht}from"./chunk-3GK5ZBUB.js";import{a as In,g as kn,h as Lt,i as Mt}from"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import{T as En,c as Sn}from"./chunk-RQSCKHNS.js";import"./chunk-FQI75MV6.js";import{b as _e,d as An}from"./chunk-UXBGMTAO.js";import{k as Pn}from"./chunk-TDHUAADJ.js";import"./chunk-TMM73K4C.js";import{a as $e}from"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as Rt,g as Ae,h as Re,i as $t}from"./chunk-H5PFNYKH.js";import{e as hn,q as At}from"./chunk-5L276I7O.js";var ze=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},On=255,xs=256,Je=class{source;sigma;threshold;constructor(e,t){this.source=new ze(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<On?Math.floor(xs/this.sigma):0}next(){if(this.sigma>=On){let s=this.source.int(),r=this.source.int();return s===void 0||r===void 0?void 0:{value:s,len:r+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let s=this.source.int();if(s===void 0)return;n+=s}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Bn(a){let e=new ze(a),t=e.int();if(t===void 0||t===0)return[];let n=[],s=0;for(let r=0;r<t;r++){let o=e.int(),i=e.int();if(o===void 0||i===void 0)throw new Error("GBWT edge list ends early");s+=o,n.push({node:s,offset:i})}return n}var et=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Je(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(s=>s.offset),n=0;for(let s of this.runs()){let r=this.edge(s.value),o=t[s.value];if(n+s.len>e)return r.node===0?void 0:{node:r.node,offset:o+(e-n)};t[s.value]=o+s.len,n+=s.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let s=t+n>>1,r=this.edges[s];if(r.node===e)return s;r.node<e?t=s+1:n=s}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let s=0;for(let r of this.runs())if(s+=r.len,r.value===t&&(n+=r.len,n>e.offset))return s-(n-e.offset)}predecessorAt(e){let t=this.edges.map(s=>({node:s.node===0?0:ee(s.node),count:0}));for(let s of this.runs()){let r=t[s.value];r&&(r.count+=s.len)}for(let s=1;s<t.length;s++){let r=t[s-1],o=t[s];$(r.node)===$(o.node)&&(t[s-1]=o,t[s]=r)}let n=0;for(let s of t)if(n+=s.count,n>e)return s.node===0?void 0:s.node}decompressArrays(){let e=this.edges.map(o=>o.offset),t=0;for(let o of this.runs())t+=o.len;let n=new Int32Array(t),s=new Int32Array(t),r=0;for(let o of this.runs()){let i=this.edge(o.value),c=e[o.value];for(let d=0;d<o.len;d++)n[r]=i.node,s[r]=c,c+=1,r+=1;e[o.value]=c}return{nodes:n,offsets:s}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let s=this.edge(n.value);for(let r=0;r<n.len;r++)t.push({node:s.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Ss=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Fn(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let d=0;d<e;d++){for(let S=0;S<16;S++)o[S]=n.getUint32(d*64+S*4);for(let S=16;S<64;S++){let I=o[S-15],N=o[S-2],y=we(I,7)^we(I,18)^I>>>3,E=we(N,17)^we(N,19)^N>>>10;o[S]=o[S-16]+y+o[S-7]+E}let h=r[0],f=r[1],p=r[2],w=r[3],u=r[4],l=r[5],b=r[6],x=r[7];for(let S=0;S<64;S++){let I=we(u,6)^we(u,11)^we(u,25),N=u&l^~u&b,y=x+I+N+Ss[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),R=h&f^h&p^f&p;x=b,b=l,l=u,u=w+y|0,w=p,p=f,f=h,h=y+E+R|0}[h,f,p,w,u,l,b,x].forEach((S,I)=>{r[I]=r[I]+S})}let i=new Uint8Array(32),c=new DataView(i.buffer);for(let d=0;d<8;d++)c.setUint32(d*4,r[d]);return i}function Tn(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[r,o]=s;if(s.length!==2||!r||!o)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(r);i||(i=new Set,t.set(r,i)),i.add(o)}return t}function qn(a){return{name:a.get("pggname"),subgraph:Tn(a.get("subgraph"),"subgraph"),translation:Tn(a.get("translation"),"translation")}}function _n(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let r of n)s.add(r)}}function Dn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),_n(t.subgraph,e.subgraph),_n(t.translation,e.translation)),t}function zn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function Gn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of zn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of zn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function jn(a){let e=a.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of a)t.set(o,n),n+=o.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Fn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Is="_gbwt_ref";function pe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Es=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,ks=/^([^#]+?)(?:\[\d+-\d+\])?$/;function vs(a){let e=Es.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=ks.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Le(a){return typeof a=="string"?vs(a):a}function Me(a,e){return{sample:a.sample??Is,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ps=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ps?n[1]=t:e.push([t,t])}return e}var Ns=32768,Un={mostChosenPaths:32},Ct=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},oe=class extends Error{};function tt(a,e,t,n){return a==="forward"?e+t:e-n}function Wn(a,e,t,n){return a==="forward"?e-n:e+t}function Qn(a){return Ne(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function qe(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Vn(a){let{db:e,records:t,signal:n}=a,s=performance.now(),r=()=>{let m=performance.now(),k=m-s;return s=m,k},o={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(m,k)=>{let A=`${m}: ${k}`;o.walks[A]=(o.walks[A]??0)+1},c=await e.haplotypeSampleInterval()??4096,d=new Map,h=async m=>{let k=t.get(m)??d.get(m);if(k)return k;let A=await e.getRecord(m);if(o.graphFetches+=1,!A)throw new Error(`Node record ${m} is missing from the database`);return d.set(m,A),A},f=m=>t.get(m).sequenceLen,p=await e.pathsByHandle(),w=m=>{let k=p.get(m);return k!==void 0&&a.keep(k.name)},u=[],l=new Ct,b=new Map,x=new Set,S=new Set,I=async m=>{let k=(await h(m.node)).gbwt().lf(m.offset);return k===void 0||k.node===0?void 0:k},N=async(m,k)=>{let A=(await h(ee(m.node))).gbwt().predecessorAt(m.offset);if(A===void 0||k!==void 0&&!k.has(A))return;let L=(await h(A)).gbwt().offsetTo(m);if(L===void 0)throw new Error(`No offset in ${A} leads to ${m.node}:${m.offset}`);return{node:A,offset:L}},y=(m,k,A,L)=>{let B=A.map(U=>U.pos.node),j=A.map(U=>U.pos.offset),Y=0;for(let U of B)Y+=f(U);let C=k==="forward"?A[0].left:A[A.length-1].left,M=u.length;u.push({pathHandle:m,orientation:k,handles:B,offsets:j,len:Y,hapStart:C,hapEnd:C+Y,canonical:Ne(B[0],B[B.length-1]),source:L});for(let U of A)l.set(U.pos,M);let Q=b.get(m);return Q?Q.push(M):b.set(m,[M]),M},E=async(m,k,A,L)=>{let B=[],j=m;for(;;){n?.throwIfAborted();let C=await N(j.pos,t);if(!C)break;j={pos:C,left:Wn(A,j.left,f(j.pos.node),f(C.node))},B.push(j)}B.reverse();let Y=[m];for(j=m;;){n?.throwIfAborted();let C=await I(j.pos);if(!C||!t.has(C.node))break;j={pos:C,left:tt(A,j.left,f(j.pos.node),f(C.node))},Y.push(j)}return y(k,A,[...B,...Y],L)},R=async(m,k,A,L)=>u[l.get(m.pos)??await E(m,k,A,L)],F=m=>{let k=m.handles[m.handles.length-1];return{pos:{node:k,offset:m.offsets[m.offsets.length-1]},left:m.orientation==="forward"?m.hapEnd-f(k):m.hapStart}},T=m=>{let k=m.handles[0];return{pos:{node:k,offset:m.offsets[0]},left:m.orientation==="forward"?m.hapStart:m.hapEnd-f(k)}},D=await E({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),O=u[D],H=()=>{if(o.fallback!==void 0)return{reference:O,pieces:[],stats:o};let m=new Map;u.forEach((A,L)=>{L!==D&&m.set(qe(A),[...m.get(qe(A))??[],A])});let k=[];for(let A of m.values()){let L=new Set;for(let B of A)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),k.push(B),o.sources[B.source]+=1)}return o.sources.reference=1,o.pieces=k.length+1,{reference:O,pieces:k,stats:o}},v=async(m,k)=>{let A=k?x:S,L=k?S:x,B=m;for(;;){if(A.has(B))return;A.add(B);let j=u[B],Y=k?F(j):T(j),C=0,M;for(;M===void 0;){n?.throwIfAborted();let Q=k?await I(Y.pos):await N(Y.pos);if(!Q){M="endmarker";break}let U=(await h(Y.pos.node)).sequenceLen,ge=(await h(Q.node)).sequenceLen,se=k?tt(j.orientation,Y.left,U,ge):Wn(j.orientation,Y.left,U,ge);if(t.has(Q.node)){let J=l.get(Q);J===void 0?(B=await E({pos:Q,left:se},j.pathHandle,j.orientation,"chain"),L.add(B),M="landed"):(L.add(J),M="merge")}else C>Ns?M="bound":(C+=ge,Y={pos:Q,left:se})}if(i("chain",M),M!=="landed")return}},G=async m=>{if(a.context>m.context)throw new oe(`the context of ${a.context} bp exceeds the ${m.context} bp the haplotype index's stray rows cover`);let k=o.spacing;if(k===void 0)throw new oe("the haplotype index has no anchors");let{bin:A,bound:L}=m,{fills:B,inserted:j}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new oe("the haplotype index's stray rows cover contained snarls only");for(let g of B){if(g.inserted>0&&g.low===g.high)throw new oe(`the haplotype index's stray rows leave out the snarl bounded by node ${g.low} at both ends`);if(g.inserted>0&&(m.snarlNodes===void 0||g.nodes>m.snarlNodes))throw new oe(m.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${g.nodes} nodes exceeds the ${m.snarlNodes} the haplotype index's stray rows cover`)}let Y=Math.floor(a.window.start/A),C=Math.floor((a.window.end-1)/A),M=Y*A,Q=(C+1)*A,U=new Map,ge=async(g,P)=>{let q=await e.haplotypeAnchorsBetween(a.referenceHandle,g*k,P*k);for(let _ of q)U.set(_.anchorOffset/k,_)},se=Math.max(0,Math.floor((M-L)/k)-1),J=Math.ceil((Q+L)/k)+1,[{listed:Ve,strays:ie}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,Y,C),ge(se,J)]);for(let g of t.keys()){let P=$(g);if(!V(g)&&!Ve(P)&&!j.has(P))throw new oe(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}o.scans=Ot([...t.keys()].sort((g,P)=>g-P));let he=Promise.all(o.scans.map(([g,P])=>e.haplotypeSamplesInRange(g,P)));for(he.catch(()=>{});se>0&&(U.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=M-L;)se-=1,await ge(se,se);for(;U.has(J)&&U.get(J).pathOffset<=Q+L;)J+=1,await ge(J,J);let ue=[...U.keys()].sort((g,P)=>g-P),be=U.get(ue[0]??-1);if(!be)throw new oe("the haplotype index has no anchors on this path");let de=g=>U.get(g).pathOffset,Ce=new Map;for(let g of ue){let P=$(U.get(g).node);Ce.set(P,[...Ce.get(P)??[],g])}let vt=[...Ce.keys()],Xt=vt.map(g=>U.get(Ce.get(g)[0]).visits);if(!Xt[vt.indexOf($(be.node))].some(g=>g.pathHandle===a.referenceHandle&&g.orientation==="forward"&&g.pathOffset===be.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${be.pathOffset} (node ${$(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),gs=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(gs[0]??ue[ue.length-1])],o.anchorsRead=ue.length;let Pt=new Map,Jt=new Set;if(vt.forEach((g,P)=>{let q=Ce.get(g),_=q.length===1?q[0]:void 0;for(let z of Xt[P])Jt.add(z.pathHandle),z.orientation==="forward"&&w(z.pathHandle)&&Pt.set(z.pathHandle,[...Pt.get(z.pathHandle)??[],{k:_,row:z}])}),o.chosenPaths=[...Jt].filter(w).length,o.chosenPaths>Un.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Un.mostChosenPaths}`);let Ze=[],Ee=Number.POSITIVE_INFINITY,xe=0;for(let[g,P]of Pt){P.sort((q,_)=>q.row.pathOffset-_.row.pathOffset);for(let q=0;q+1<P.length;q++){let _=P[q],z=P[q+1];if(_.k===void 0||z.k===void 0||Math.abs(_.k-z.k)!==1)continue;let[K,te]=de(_.k)<=de(z.k)?[_,z]:[z,_],ne=de(K.k),re=de(te.k);ne<Q&&re>=M?(Ze.push({pathHandle:g,from:_.row,to:z.row}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,re+L)):ne>=Q&&ne-Q<=L?(Ze.push({pathHandle:g,from:K.row,to:void 0}),Ee=Math.min(Ee,ne-L),xe=Math.max(xe,ne+L)):re<M&&M-re<=L&&(Ze.push({pathHandle:g,from:te.row,to:void 0}),Ee=Math.min(Ee,re-L),xe=Math.max(xe,re+L))}}let ws=new Set(B.map(g=>`${g.low}:${g.high}`)),ms=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ws.has(`${g.snarl[0]}:${g.snarl[1]}`))).sort((g,P)=>g.pathHandle-P.pathHandle||g.pathStart-P.pathStart);o.strays={bins:C-Y+1,rows:ie.length,walked:0,outsideBp:0},xe>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ee),xe+1),o.ms.scan=r();let en=8*k+2*(a.window.end-a.window.start),tn=o.strays,Oe=0,nn=g=>{if(tn.outsideBp+=g,Oe+=g,Oe>en)throw new oe(`a walk of a chosen path near the window went past its cap of ${en} bp`)},Nt=new Map,sn=(g,P,q)=>(Nt.get(g)??[]).some(([_,z])=>_<=P&&q<z),rn=(g,P,q)=>{Nt.set(g,[...Nt.get(g)??[],[P,q]])},on=async(g,P,q,_,z)=>{let K=P,te=q,ne=te;for(;K&&te<=_;){n?.throwIfAborted();let re;if(t.has(K.node)){let Be=await R({pos:K,left:te},g,"forward",z),cn=F(Be);K=cn.pos,te=cn.left,re=f(K.node),ne=Math.max(ne,Be.hapEnd)}else re=(await h(K.node)).sequenceLen,nn(re),ne=Math.max(ne,te+re);K=await I(K),te+=re}return ne},ys=async(g,P,q,_)=>{let z={pos:P,left:q},K=q;for(;z.left>_;){n?.throwIfAborted();let te=await N(z.pos);if(!te)break;let ne=(await h(te.node)).sequenceLen,re=z.left-ne;if(t.has(te.node)){let Be=await R({pos:te,left:re},g,"forward","section");z=T(Be),K=Math.min(K,Be.hapStart)}else nn(ne),z={pos:te,left:re},K=Math.min(K,re)}return K};for(let{pathHandle:g,from:P,to:q}of Ze){let _=P.pathOffset,z=(q??P).pathOffset+L;if(sn(g,_-L,z))continue;let K={node:P.node,offset:P.offset};Oe=0;let te=await on(g,K,_,z,"section");Oe=0;let ne=await ys(g,K,_,_-L);rn(g,Math.min(ne,_-L),Math.max(te,z+1)),i(q?"section":"visit",q?"past the far anchor":"bound")}for(let g of ms){if(sn(g.pathHandle,g.pathStart,g.pathEnd))continue;Oe=0;let P=await on(g.pathHandle,{node:g.node,offset:g.offset},g.pathStart,g.pathEnd,"stray");rn(g.pathHandle,g.pathStart,Math.max(P,g.pathEnd+1)),tn.walked+=1}o.ms.walks=r();let an=[];for(let g of await he)for(let P of g)if(o.scanRows+=1,t.has(P.node)&&w(P.pathHandle)){if(!(b.get(P.pathHandle)??[]).some(q=>{let _=u[q];return _.hapStart<=P.pathOffset&&P.pathOffset<_.hapEnd}))throw new oe(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&an.push(P)}for(let g of an)await R({pos:{node:g.node,offset:g.offset},left:g.pathOffset},g.pathHandle,"reverse","twin");o.ms.check=r()},X=async()=>{let m=new Map,k=C=>{let M=qe(C),Q=m.get(M);Q?Q.add(C.orientation):m.set(M,new Set([C.orientation]))},A=0,L=()=>{for(;A<u.length;A++)k(u[A])};L();let B=C=>(m.get(qe(C))?.size??0)>1,j=2*c,Y=(C,M)=>M===D?w(a.referenceHandle)&&Qn(C):!C.canonical||Qn(C);for(let C=0;C<u.length;C++){let M=u[C];if(B(M)||!Y(M,C))continue;o.twins.tried+=1;let Q=M.orientation==="forward"?"reverse":"forward",U=F(M),ge=0,se;for(;!se&&ge<=j;){n?.throwIfAborted();let ie=await I(U.pos);if(!ie)break;let he=(await h(ie.node)).sequenceLen,ue=tt(M.orientation,U.left,(await h(U.pos.node)).sequenceLen,he),be=ee(ie.node);se=(await e.haplotypeSamplesInRange(be,be)).find(de=>de.pathHandle===M.pathHandle&&de.orientation===Q&&de.pathOffset===ue),ge+=he,U={pos:ie,left:ue}}let J=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},Ve=0;for(;J&&!B(M)&&Ve<=j+M.len;){if(n?.throwIfAborted(),t.has(J.pos.node)){let ie=await R(J,M.pathHandle,Q,"twin"),he=u.indexOf(ie);await v(he,!0),await v(he,!1),L(),J=F(ie)}if(!B(M)){let ie=(await h(J.pos.node)).sequenceLen;Ve+=ie;let he=await I(J.pos);J=he?{pos:he,left:tt(Q,J.left,ie,(await h(he.node)).sequenceLen)}:void 0}}if(L(),!B(M))throw new oe(`piece ${qe(M)} was found in one orientation where extractPaths keeps the other`);o.twins.found+=1}o.ms.twins=r()};try{let m=await e.haplotypeStrayOptions();if(m===void 0)throw new oe("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await G(m),await X()}catch(m){if(!(m instanceof oe))throw m;o.fallback=m.message}return H()}function Zn(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var ae=class extends Error{name="SubgraphLimitError";limit;windowBp;walkedBp;constructor(e,t){super(t===void 0?`Subgraph size limit of ${e} nodes exceeded`:`Subgraph size limit of ${e} nodes exceeded ${t.walkedBp} bp into a ${t.windowBp} bp window`),this.limit=e,this.windowBp=t?.windowBp,this.walkedBp=t?.walkedBp}};function Bt(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var Ge=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let r=s.length-1;for(;r>0;){let o=r-1>>1;if(Bt(s[r],s[o]))[s[r],s[o]]=[s[o],s[r]],r=o;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let r=2*s+1,o=r+1,i=s;if(r<e.length&&Bt(e[r],e[i])&&(i=r),o<e.length&&Bt(e[o],e[i])&&(i=o),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function As(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],r)=>{e[r]=n,t[r]=s}),{pathAt:e,refAt:t,count:a.length}}function Rs(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ve(a){return`${a.node}:${a.offset}`}function De(a){return a.map(e=>ee(e)).reverse()}function $s(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Ls(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Xn(r,t.insertion,t.deletion);for(let[d,h]of s.edits)Z(r,d,h);let o=a.identity.walkForward,[i,c]=o?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:r,weight:void 0,path:[...i.path,...c.path],start:i.start,pieces:[...i.pieces,...c.pieces],soloAligned:[...i.soloAligned,...c.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:o}}}function Ms(a,e,t){if(a.some(o=>o.weight!==void 0))return a;let n=new Map;a.forEach((o,i)=>{if(o.identity){let c=n.get(o.identity.pathHandle);c?c.push(i):n.set(o.identity.pathHandle,[i])}});let s=new Map,r=new Set;for(let o of n.values()){o.sort((h,f)=>a[h].identity.hapStart-a[f].identity.hapStart);let i=o[0],c=a[i],d=[];for(let h of o.slice(1)){let f=a[h],p=d.length===0?$s(c,f):void 0;if(p){c=Ls(c,f,p),r.add(h);continue}if(!e(f)){d.push(h);continue}let w=e(c)?t([c,...d.map(u=>a[u]),f]):void 0;if(w){c=w;for(let u of[...d,h])r.add(u)}else s.set(i,c),i=h,c=f;d=[]}s.set(i,c)}return a.flatMap((o,i)=>r.has(i)?[]:[s.get(i)??o])}function nt(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Hs=32768;function Cs(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Hs?s[1]=n:t.push([n,n])}return t}var je=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(fe(e,"forward"))}hasHandle(e){return this.records.has(e)}record(e){let t=this.records.get(e);if(!t)throw new Error(`Subgraph has no record for handle ${e}`);return t}sortedHandles(){return[...this.records.keys()].sort((e,t)=>e-t)}async addNode(e){if(this.signal?.throwIfAborted(),this.limit!==void 0&&this.nodeCount>=this.limit)throw new ae(this.limit);let t=await this.db.getRecord(fe(e,"forward")),n=await this.db.getRecord(fe(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${pe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${pe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let r=n,o=s;for(;;){await this.ensureNode($(o.node));let i=this.record(o.node);if(r+i.sequenceLen>t)return{position:{seqOffset:t,handle:o.node,nodeOffset:t-r,gbwtOffset:o.offset},name:e.name,handle:e.handle};r+=i.sequenceLen;let c=i.gbwt().lf(o.offset);if(!c)throw new Error(`The fragment of ${pe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);o=c}}async aroundPosition(e,t,n){let s=$(e);await this.ensureNode(s);let r=this.record(e),o=ke(e),i=new Ge;return i.push(t,s,Xe(o)),i.push(r.sequenceLen-t-1,s,Ye(o)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,r]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&r){let o=s.pos.node,i=r.pos.node;if(!await this.db.prefetchRecords([[Math.min(o,i),Math.max(o,i)+1]])){let d=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Cs(d.map(h=>h.pos.node)).map(([h,f])=>[h,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof ae&&s.windowBp===void 0?new ae(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},r=e.nodeOffset,o=t,i=new Ge;for(;;){let c=$(s.node),d=ke(s.node);this.walkedBp=t-o,await this.ensureNode(c);let h=this.record(s.node);if(r>=h.sequenceLen)throw new Error(`Offset ${r} in node ${c} of length ${h.sequenceLen}`);i.push(r,c,Xe(d));let f=h.sequenceLen-r;if(o<=f){i.push(o===f?0:f-o-1,c,Ye(d));break}i.push(0,c,Ye(d));let p=h.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,r=0,o-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new Ge;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let o of this.records.keys())s.add($(o));let r=0;for(;e.size>0;){let[o,i,c]=e.pop(),d=`${i}:${c}`;if(n.has(d))continue;n.add(d),s.delete(i),this.hasNode(i)||(await this.addNode(i),r+=1);let h=pn(c);if(!n.has(`${i}:${h}`)){let w=this.record(fe(i,un(c))),u=o+w.sequenceLen-1;u<=t&&e.push(u,i,h)}let f=this.record(fe(i,gn(c))),p=o+1;if(p<=t)for(let w of f.successors()){let u=$(w),l=Xe(ke(w));n.has(`${u}:${l}`)||e.push(p,u,l)}}for(let o of s)this.records.delete(fe(o,"forward")),this.records.delete(fe(o,"reverse"));return{inserted:r,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([$(e),$(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=$(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=$(c);s.has(d)||(n.push(c,ee(c)),s.add(d))}}return{inserted:r,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:r,nodes:o}=await this.fillBetween(n,s),i=$(n),c=$(s);this.snarlFills.push({low:Math.min(i,c),high:Math.max(i,c),nodes:o,inserted:r.length});for(let d of r)this.snarlNodes.add(d);t+=r.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let r=this.record(s),o=r.next;o!==void 0&&(n=!0,this.hasHandle(o)?Fe(s,o)&&t.push([s,o]):e==="overlapping"&&this.isSnarlEntryInSubgraph(r)&&t.push([s,o]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let r=t.get(n);if(!r){if(r=await this.db.getRecord(n),e?.(),!r)throw new Error(`Node record ${n} is missing from the database`);t.set(n,r)}return r}}async findCoveringSnarl(){let e=this.recordReader(),t=async c=>{let d=c.successors(),h=d[0];return h===void 0?!1:d.length>1||(await e(ee(h))).successors().length>1},n=async c=>{let d=await e(ee(c));return d.next!==void 0?await t(d)?{kind:"snarl-exit",snarl:[ee(c),d.next]}:{kind:"chain"}:(await e(c)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,r=this.sortedHandles().flatMap(c=>this.record(c).successors()),o,i=!1;for(;!i&&r.length>0;){let c=r.shift(),d=$(c);if(!this.hasHandle(c)&&!s.has(d)){s.add(d);let h=await n(c);if(h.kind==="snarl-exit")o=h.snarl,i=!0;else if(h.kind==="chain")i=!0;else for(let f of["forward","reverse"])r.push(...(await e(fe(d,f))).successors())}}return o}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),r=s.length,o=new Map;s.forEach((y,E)=>o.set(y,E));let i=new Int32Array(r+1),c=new Int32Array(r),d=[];for(let y=0;y<r;y++){let E=this.record(s[y]),R=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push(R),i[y+1]=i[y]+R.nodes.length}let h=i[r],f=new Int32Array(h),p=new Int32Array(h),w=new Uint8Array(h);for(let y=0;y<r;y++){let E=d[y];f.set(E.nodes,i[y]),p.set(E.offsets,i[y])}d.length=0;for(let y=0;y<h;y++){let E=o.get(f[y]);E===void 0?f[y]=-1:(f[y]=E,w[i[E]+p[y]]=1)}let u=n===void 0?void 0:o.get(n.handle),l=n?.gbwtOffset,b,x=(y,E,R)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),R&&(R.push(s[H]),F.push(v)),T+=1,D+=c[H];let G=i[H]+v,X=f[G];if(X<0)break;v=p[G],H=X}return{offsets:F,len:D,refAt:O,last:H}},S=(y,E,R,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:R,weight:void 0,identity:void 0})},I=new Int32Array(r);for(let y=0;y<r;y++){let E=s[y];if(!V(E)){let R=i[y],F=i[y+1]-R;for(let T=0;T<F;T++)if(w[R+T]===0){let D=[],{offsets:O,len:H,refAt:v,last:G}=x(y,T,D),X=s[G];if(v>=0||Ne(E,X)){if(S(D,O,H,v),!V(X)){let m=o.get(ee(X));I[m]=I[m]+1}}else this.twinStarts.add(ve({node:E,offset:T}))}}}for(let y=0;y<r;y++){let E=s[y];if(V(E)){let R=i[y],F=i[y+1]-R,T=0;for(let O=0;O<F;O++)w[R+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[R+O]===0){let H=D?void 0:x(y,O,void 0);if(H&&(H.refAt>=0||Ne(E,s[H.last]))){let v=[],{offsets:G,len:X,refAt:m}=x(y,O,v);S(v,G,X,m)}else this.twinStarts.add(ve({node:E,offset:O}))}}}let N=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),N&&(this.refId=this.paths.indexOf(N)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let F of y.path.slice(0,b))E+=this.record(F).sequenceLen;let R=n.seqOffset-E;this.refInterval=[R,R+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:R,hapEnd:R+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Te(n)?De(n):void 0,r=d=>s!==void 0&&Ft(d,s)===0||Te(De(d)),o=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((d,h)=>Ft(d.path,h.path)||d.len-h.len||(d===t?-1:h===t?1:0));let i=[],c;for(let d of this.paths){let h=i[i.length-1],f=o&&d!==t&&r(d.path);this.twinDeferred||=f,h&&Ft(h.path,d.path)===0&&!f?h.weight=(h.weight??1)+(d.weight??1):(d===t&&(c=i.length),i.push({...d,weight:d.weight??1}))}this.paths=i,this.refId=c}mergeDistinct(){this.twinDeferred?this.settleDeferred():this.distinctPaths(!1)}settleDeferred(){this.twinDeferred&&(this.unsettled={paths:[...this.paths],refId:this.refId},this.distinctPaths(!1))}dropTwins(){let e=this.refId===void 0?void 0:this.paths[this.refId],t=this.refInterval,n=o=>`${o.pathHandle}:${o.hapStart}-${o.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let o of this.paths)o!==e&&o.identity?.orientation==="forward"&&s.add(n(o.identity));let r=this.paths.filter(o=>o===e||o.identity?.orientation!=="reverse"||!s.has(n(o.identity)));r.length<this.paths.length&&(this.paths=r,this.refId=e===void 0?void 0:r.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(o=>o.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((o,i)=>i!==this.refId&&o.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((o,i)=>i===this.refId||o.identity!==void 0&&e(o.identity.name)),r=new Set;for(let o of s)for(let i of o.path)r.add($(i));for(let o of[...this.records.keys()])r.has($(o))||this.records.delete(o);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let r=e.position.seqOffset,o=await Vn({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:r-e.position.nodeOffset,window:{start:r,end:r+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(h,f,p)=>this.prefetchReferenceRange(h,f,p)});if(this.stats.keep=o.stats,o.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),c=h=>({path:h.handles,offsets:h.offsets,len:h.len,weight:void 0,identity:{pathHandle:h.pathHandle,name:h===o.reference?e.name:i.get(h.pathHandle).name,orientation:h.orientation,hapStart:h.hapStart,hapEnd:h.hapEnd}}),d=[o.reference,...o.pieces].sort(Zn);return this.paths=d.map(c),this.refId=d.indexOf(o.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[o.reference.hapStart,o.reference.hapEnd],this.dropTwins(),!0}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");this.unsettled&&({paths:this.paths,refId:this.refId}=this.unsettled,this.unsettled=void 0,this.twinDeferred=!0);let e=await this.db.haplotypeSampleGap()??4096,t=Ot(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ve(l),l);let r=l=>{let b=0,x=t.length-1;for(;b<x;){let I=b+x+1>>1;t[I][0]<=l?b=I:x=I-1}let S=t[b];return S[0]<=l&&l<=S[1]},o=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&o.set(ve(nt(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let c=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),d=l=>(i.graphLookups+=1,c(l)),h=async(l,b)=>{if(r(l.node))return n.get(ve(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},w=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},u=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],S=new Set,I={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(I);let N,y=0,E=l,R;for(;N===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){I.end="cycle";break}S.add(E);let H=this.paths[E];x.push({index:E,startBp:y}),I.fragments+=1;let v=y;for(let X=0;X<H.path.length;X++){let m=nt(H,X),k=n.get(ve(m)),A=this.record(m.node).sequenceLen;if(k){N=w(k,v,A);break}v+=A}if(y+=H.len,N){I.end="in-fragment sample";break}let G=nt(H,H.path.length-1);R=this.record(G.node).gbwt().lf(G.offset),E=void 0}if(R===void 0||R.node===0){I.end="endmarker";break}let F=ve(R),T=o.get(F);if(T!==void 0){let H=this.paths[T].identity;if(H){N=u(H,y),I.end="identified sibling";break}E=T;continue}this.records.has(R.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h(R,I),O=await d(R.node);if(D){N=w(D,y,O.sequenceLen),I.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,I.steps+=1,y-x[x.length-1].startBp>4*e+4*O.sequenceLen){I.end="bound";break}y+=O.sequenceLen,R=O.gbwt().lf(R.offset)}if(N){I.pathHandle=N.pathHandle;let F=await p(N.pathHandle);for(let{index:T,startBp:D}of x){let O=this.paths[T];O.identity=N.orientation==="forward"?{pathHandle:N.pathHandle,name:F,orientation:"forward",hapStart:N.base+D,hapEnd:N.base+D+O.len}:{pathHandle:N.pathHandle,name:F,orientation:"reverse",hapStart:N.base-D-O.len,hapEnd:N.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let r=t.get(n);r?r.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),r=new Int32Array(e.length),o=0,i=-1;for(let c=0;c<e.length;c++){let d=n.get(e[c]);if(d){let h=Rs(d,i);if(h===void 0)return;s[o]=c,r[o]=h,o+=1,i=h}}return{pathAt:s,refAt:r,count:o}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[s]).sequence,d=this.record(t[r]).sequence;for(;o<c.length&&i<d.length;){if(c[o]!==d[i])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,r=0,o=0,i=0;for(;s<e.length&&r<t.length;){let c=this.record(e[e.length-s-1]).sequence,d=this.record(t[t.length-r-1]).sequence;for(;o<c.length&&i<d.length;){if(c[c.length-o-1]!==d[d.length-i-1])return n;o+=1,i+=1,n+=1}o===c.length&&(s+=1,o=0),i===d.length&&(r+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),r=this.pathLen(t),o=this.prefixMatches(e,t),i=this.suffixMatches(e,t);o+i>s&&(i=s-o),o+i>r&&(i=r-o),Z(n,"M",o),Xn(n,s-o-i,r-o-i),Z(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let r of e)n.has(r)&&(s+=this.record(r).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??As(yn(e,t,f=>this.record(f).sequenceLen)[0]),r=[],o=this.refPrefix(t),i=(f,p,w,u)=>{f===p?Z(r,"D",o[u]-o[w]):w===u?Z(r,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(w,u),r)},c=0,d=0,h=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],w=s.refAt[f];(d!==p||h!==w)&&i(d,p,h,w);let u=this.record(e[p]).sequenceLen;Z(r,"M",u),c+=u,d=p+1,h=w+1}return i(d,e.length,h,t.length),{edits:r,matched:c,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Te(n)&&(t.identity===void 0||!Te(De(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let r=De(t.path),o=this.sharedWeight(t.path,n);if(this.sharedWeight(r,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(o===0)s={...this.editsAgainst(r,n),flipped:!0};else{let c=this.editsAgainst(t.path,n),d=this.editsAgainst(r,n);s=d.matched>c.matched?{...d,flipped:!0}:{...c,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(h,f,p,w)=>{let u=Bs(h),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,S=x?.orientation==="forward",[I,N]=S?[l,b]:[b,l];return{strand:f,refStart:e.start+u.leading,refEnd:e.start+n-u.trailing,edits:u.edits,weight:l.weight,path:p.flatMap(y=>this.paths[y].path),start:nt(l,0),pieces:p,soloAligned:w,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+I.identity.hapStart,hapEnd:x.name.fragment+N.identity.hapEnd,walkForward:S}}},r=h=>h.soloAligned.reduce((f,p)=>f+p,0),o=h=>h.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=h=>2*r(h)>=o(h),c=h=>{let f=h[0],p=h[h.length-1],w=f.identity.walkForward;if(h.some((v,G)=>v.strand!==f.strand||v.identity.walkForward!==w||G>0&&v.identity.hapStart<h[G-1].identity.hapEnd))return;let u=w?h:[...h].reverse(),l=u.flatMap(v=>v.pieces),b=u.flatMap(v=>v.soloAligned),x=f.strand==="+"!==w,S=l.map(v=>this.paths[v]),I=S.slice(1).map((v,G)=>{let X=S[G].identity;return w?v.identity.hapStart-X.hapEnd:X.hapStart-v.identity.hapEnd}),N=x?[...S].reverse():S,y=x?[...I].reverse():I,E=N.flatMap(v=>x?De(v.path):v.path),{edits:R}=this.editsAgainst(E,t),F=Kn(R,N.map(v=>v.len)),T=new Map((x?[...l].reverse():l).map((v,G)=>[v,F[G]])),D=v=>2*v.pieces.reduce((G,X)=>G+T.get(X),0)>=r(v);if(!D(f)||!D(p))return;let O=[],H=0;return N.slice(0,-1).forEach((v,G)=>{H+=v.len,O.push([H,y[G]])}),s(Fs(R,O),f.strand,l,b)},d=[];return this.paths.forEach((h,f)=>{if(f===this.refId)return;let{edits:p,flipped:w}=this.alignment(f),u=h.identity,l=u?u.orientation==="forward"!==w:!w;d.push(s(p,l?"+":"-",[f],Kn(p,[h.len])))}),Ms(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:Ts(f)};return p?{...b,resolved:!0,name:p.name,label:pe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,r=this.paths.flatMap(h=>{let{identity:f}=h;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:rt(h,f)}]:[]}),o=h=>f=>f.sample===h.sample&&f.haplotype===h.haplotype,i=o(t),c=n?o(n):h=>!i(h),d=h=>this.record(fe(h,"forward")).sequence;return r.filter(h=>i(h.name)).flatMap(h=>r.filter(f=>c(f.name)).flatMap(f=>bn({...s,query:f.steps,target:h.steps,sequenceOf:d}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:h.name,targetStart:h.start+p.targetStart,targetEnd:h.start+p.targetEnd,cigar:xn(p.edits),matches:p.edits.reduce((w,[u,l])=>w+(u==="="?l:0),0),columns:p.edits.reduce((w,[,u])=>w+u,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=fe(e,n);for(let r of this.record(s).successors())this.hasHandle(r)&&Fe(s,r)&&t.push([n==="reverse"?1:0,$(r),V(r)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!V(n)){let s=$(n),r=`S ${s} ${this.record(n).sequence}
2
2
  `;for(let[o,i,c]of this.canonicalEdges(s))r+=`L ${s} ${o?"-":"+"} ${i} ${c?"-":"+"}
3
3
  `;t.push(e.encode(r))}return jn(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...Gn(Dn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let d of s)V(d)||n.push(`S ${$(d)} ${this.record(d).sequence}`);let r=d=>V(d)?"-":"+";for(let d of s)for(let h of this.record(d).successors())this.hasHandle(h)&&Fe(d,h)&&n.push(`L ${$(d)} ${r(d)} ${$(h)} ${r(h)} 0M`);let o=(d,h,f,p,w)=>{let u=rt(d,h).map(x=>`${V(x)?"<":">"}${$(x)}`).join(""),l=d.weight===void 0?"":` WT:i:${d.weight}`,b=w===void 0?"":` CG:Z:${w}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${u}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(o(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let c=1;return this.paths.forEach((d,h)=>{if(h!==this.refId){let f=e.names!=="anonymous"?d.identity:void 0,p=t?this.alignToRef(h):void 0;n.push(f?o(d,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):o(d,void 0,{sample:"unknown",contig:i,haplotype:c,fragment:0},d.len,p)),c+=1}}),`${n.join(`
4
4
  `)}
@@ -6,4 +6,4 @@ import{a as fe,b as $,c as ke,d as V,e as ee,f as pn,g as Xe,h as Ye,i as un,j a
6
6
  `).filter(f=>f!=="")),n=Xs(t.flat()),s=0,r=t.map(h=>{let f=wt(h,"W").map(Ks),p=s;for(let w of f.filter(u=>u.fields[1]===Zs)){let u=+w.fields[2]+p;w.fields[2]=String(u),w.name=w.fields.slice(1,4).join(" "),s=Math.max(s,u)}return f}),i=[...Sn([...r.flatMap(h=>h.slice(0,1)),...r.flatMap(h=>h.slice(1))],h=>h.name).values()].flatMap(h=>Js(h,n,e)),c=new Set(t.flatMap(h=>wt(h,"L")));for(let h of i)for(let f of er(h))!c.has(f.forward)&&!c.has(f.reverse)&&c.add(f.forward);return`${[...new Set([...wt(t[0],"H"),...t.flatMap(h=>wt(h,"S")),...c,...i.map(h=>h.fields.join(" "))])].join(`
7
7
  `)}
8
8
  `}var jt=class extends Error{constructor(a,e){super(e.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${a}" maps to none; set referenceSample`:`the anchor "${a}" is none of the graph's reference samples (${e.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`),this.name="NoReferenceSampleError"}},mt=class extends Error{constructor(a,e,t){super(`this ${e.toLocaleString()} bp window reads more than nodeLimit (${a.toLocaleString()}) graph nodes; zoom in to about ${t.toLocaleString()} bp or raise nodeLimit`),this.fitsBp=t,this.name="NodeLimitError",this.regionTooLarge=!0}};function ce(a){return`${a.sample}#${a.haplotype}`}function yt(a,e){let t=ce(a);return e===void 0||e.some(n=>Ae(t,n))}async function bt(a){return(await a.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function Ut(a,e){let t=a.toLowerCase(),n=In(a)?.toLowerCase();return e.find(s=>s===a)??e.find(s=>s.toLowerCase()===t)??e.find(s=>s.toLowerCase()===n)}function Wt({configured:a,anchorPrefix:e,referenceSamples:t}){if(a!=="")return a;let n=Ut(Rt(e),t)??(t.length===1?t[0]:void 0);if(n===void 0)throw new jt(e,t);return n}async function xt(a,e,t){let n=(await a.paths()).find(s=>s.isIndexed&&s.name.sample===e&&s.name.contig===t);return n?{sample:n.name.sample,contig:t,haplotype:n.name.haplotype}:void 0}function St(a,e,t){if(a instanceof Error&&(a.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(a.message))){let s="walkedBp"in a?a.walkedBp:void 0,r=typeof s=="number"&&s>0?Math.floor(s*.8):Math.floor(t/2);return new mt(e,t,Math.max(r,1))}else return}async function tr(a,e,t,n,s){return a.getSubgraphs({...s,path:e,start:t,end:n,haplotypes:"all"}).catch(r=>{throw St(r,s.limit,n-t)??r})}async function nr(a,e){let t=await a.paths();return cs(await Promise.all(e.map(n=>n.toGFA())),(n,s,r,o)=>t.some(({name:i})=>i.sample===n&&i.haplotype===s&&i.contig===r&&i.fragment===o))}async function Qt(a,e,t,n,s){if(!e)return"";let r=await tr(a,e,t,n,s);if(r.length===1)return hs(r[0].toCompactSubgraph());let o=await nr(a,r),i=o===""?void 0:kn(o);return i?{...i,revisited:Number.NaN}:o}function sr(a,e){let t=1/0,n=-1/0;for(let i of a)t=Math.min(t,i),n=Math.max(n,i);let s=n-t+1,r=a.length>0&&s<=16*a.length?new Int32Array(s).fill(-1):void 0,o=new Map;return a.forEach((i,c)=>{r?r[i-t]=c:o.set(i,c)}),i=>{let c=$(i),d=r!==void 0&&c>=t&&c<=n,h=d?r[c-t]:o.get(c)??-1;return h>=0?h:(d?r[c-t]=e.length:o.set(c,e.length),e.push(String(c)),e.length-1)}}var rr=/^(.*)\[(\d+)-(\d+)\]$/;function hs(a){let e=Array.from(a.nodeIds,String),t=sr(a.nodeIds,e),n=a.nodeIds.length,s=a.edges.length/2,r=new Int32Array(s),o=new Int32Array(s),i=new Uint8Array(s);for(let l=0;l<s;l++){let b=a.edges[2*l],x=a.edges[2*l+1];r[l]=t(b),o[l]=t(x),i[l]=(V(b)?1:0)|(V(x)?2:0)}let c=a.paths.filter(l=>l.steps.length>0),d=new Int32Array(c.length+1);c.forEach((l,b)=>{d[b+1]=d[b]+l.steps.length});let h=new Int32Array(d[c.length]),f=new Uint8Array(h.length),p=new Float64Array(c.length),w=new Float64Array(c.length),u=c.map((l,b)=>{let x=rr.exec(l.name);p[b]=x?+x[2]:0,w[b]=x?+x[3]:-1;let S=d[b];for(let I of l.steps)h[S]=t(I),f[S++]=V(I)?1:0;return x?x[1]:l.name});return{nodes:{names:e,lengths:Int32Array.from(a.nodeSequences,l=>l.length),refs:new Int32Array(n).fill(-1),starts:new Float64Array(n),ranks:new Int32Array(n),refNames:[]},links:{from:r,to:o,strands:i},walks:{names:u,starts:p,ends:w,offsets:d,steps:h,reversed:f},departures:En(),revisited:Number.NaN}}function It(a){let e=/\.gbz\.db$/i;return e.test(a)?a.replace(e,".haplotype-index.db"):void 0}function ir(a){return fn(a)&&It(dn(a))?ln(a,e=>It(e)):void 0}function cr(a){return a instanceof Error&&(/\bHTTP 40[34]\b/.test(a.message)||a.code==="ENOENT")}async function ds(a,e){let t=ir(a);if(!t)return{};try{return await $e(t,e).stat(),{location:t}}catch(n){return cr(n)?{}:{unreadable:String(n)}}}var hr=5e3,dr=50*2**20,Vt=class extends Error{constructor(t){super(`this GAF is ${(t/2**20).toFixed(0)} MB without an index; bgzip it and index it with tabix -p gaf`);this.name="UnindexedGafTooLargeError"}};function fr(a,e){if(a.length<=e)return a;let t=a.length/e;return Array.from({length:e},(n,s)=>a[Math.floor(s*t)])}var fs=(a,e)=>a.path.some(t=>e.has(t.name)),Et=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=_e({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>dr)throw new Vt(t);let n=await this.file.readFile({signal:e}),s=new TextDecoder().decode(n[0]===31&&n[1]===139?await Pn(n):n);return Mt(s)}})}async readIndexed(e,t,n){let s=1/0,r=-1/0;for(let i of t){let c=Number(i);Number.isInteger(c)&&(s=Math.min(s,c),r=Math.max(r,c))}let o=[];return s<=r&&await e.getLines("{node}",s,r+1,{signal:n,lineCallback:i=>{let c=Lt(i);c&&fs(c,t)&&o.push(c)}}),o}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(s=>fs(s,e));return{records:fr(n,hr),total:n.length}}};var kt=class extends Error{constructor(t){super(t===void 0?"no haplotype index is set, so the walks cannot be named; build one with gbz-haplotype-index (cargo install gbz-haplotype-index) and set it as haplotypeIndexLocation":`the haplotype index beside the graph database could not be checked (${t}), so the walks cannot be named; if it is there, reload to try again, or set haplotypeIndexLocation`);this.name="NoHaplotypeIndexError"}},Zt=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function lr(a,e){return`${ce(a)}#${a.contig}@${e.start.node}.${e.start.offset}`}function pr({alignment:a,assemblyName:e,refName:t,lane:n}){let{refStart:s,refEnd:r,strand:o,cigar:i}=a;if(!(r<=s)){let{name:c,hapStart:d,hapEnd:h}=a,f=lr(c,a),p={uniqueId:f,assemblyName:e,refName:t,start:s,end:r,type:"match",strand:o==="-"?-1:1,CIGAR:i,syntenyId:f,mate:{refName:c.contig,start:d,end:h,assemblyName:n}};return new Rn(p)}}function ur({pair:a,lane:e,mateLane:t}){return Cn({target:{name:`${ce(a.target)}#${a.target.contig}`,assemblyName:e,refName:a.target.contig,start:a.targetStart,end:a.targetEnd},query:{name:`${ce(a.query)}#${a.query.contig}`,assemblyName:t,refName:a.query.contig,start:a.queryStart,end:a.queryEnd},strand:a.strand,cigar:a.cigar,matches:a.matches,columns:a.columns})}var gr=12e4;function wr(a,e){let t=new Map;for(let s of a)for(let{name:r,start:o,end:i}of s.walkSpans()){let c=ce(r);if(e.has(c)){let d=`${c}#${r.contig}`,h=t.get(d);h?h.push([o,i]):t.set(d,[[o,i]])}}let n=0;for(let s of t.values()){s.sort((r,o)=>r[0]-o[0]);for(let r=1;r<s.length;r++){let o=s[r][0]-s[r-1][1];o>0&&o<=gr&&(n=Math.max(n,o))}}return n}function us(a,e){return a instanceof mt&&(a.message=`Zoom in to about ${hn(a.fitsBp)} to see ${e}`),a}var ls=(a,e,t)=>Hn(us(St(a,e,t)??a,"lanes"),t),ps=a=>({...a,start:Math.floor(a.start),end:Math.ceil(a.end)}),Kt=class extends $n{constructor(){super(...arguments);this.graph=_e({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),s=Ke(n)?{location:n}:await ds(t,this.pluginManager),r=s.location,o=await Qe.open({source:$e(t,this.pluginManager),haplotypeIndex:r?$e(r,this.pluginManager):void 0}),i=this.getConf("assemblyNames")[0];if(i===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let c=await bt(o),d=Wt({configured:this.getConf("referenceSample"),anchorPrefix:Re(this,i),referenceSamples:c});return{db:o,anchor:i,referenceSample:d,referenceSamples:c,unreadableIndex:s.unreadable}}});this.gaf=_e({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return Ke(t)?new Et($e(t,this.pluginManager),Ke(n)?An(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:s,referenceSample:r}=await this.graph(n);return xt(s,r,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:s}=await this.graph(t),r=new Map;for(let o of await n.paths()){let i=ce(o.name),c=r.get(i);c?c.contigs.includes(o.name.contig)||c.contigs.push(o.name.contig):r.set(i,{prefix:i,sample:o.name.sample,haplotype:o.name.haplotype,contigs:[o.name.contig],isReference:s.includes(o.name.sample)})}return[...r.values()]}async getHeader(t={}){let{anchor:n,referenceSample:s}=await this.graph(t),r=$t(this),o=[];for(let i of await this.getHaplotypes(t))i.sample!==s&&o.push({name:Ht(r,i.prefix),label:i.prefix,group:i.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,lanes:o}}async getRefNames(t={}){let{db:n,anchor:s,referenceSample:r}=await this.graph(t),{assemblyName:o}=t,i=o===s?void 0:Re(this,o),c=(await n.paths()).filter(d=>o===s?d.isIndexed&&d.name.sample===r:Ae(ce(d.name),i)).map(d=>d.name.contig);return[...new Set(c)]}keepPredicate(t,n){let s=t===void 0||t.length===0?void 0:t.map(r=>Re(this,r));return s===void 0&&n===void 0?void 0:r=>yt(r,s)&&(n===void 0||Ae(ce(r),n))}async getSubgraph(t,n={}){let{signal:s}=n,{db:r,anchor:o,referenceSample:i,unreadableIndex:c}=await this.graph({signal:s}),{assemblyName:d,refName:h,start:f,end:p}=ps(t);if(d!==o)throw new Zt(d,o);let w=await this.referenceQuery(h,{signal:s});if(!w)throw new Error(`${i} has no indexed path ${h} in this graph`);let u=this.keepPredicate(n.haplotypes);if(u!==void 0&&!r.hasHaplotypeIndex)throw new kt(c);let l=await Qt(r,w,f,p,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:u}).catch(b=>{throw us(b,"the graph")});return typeof l=="string"?l:Nn(l,{start:f,end:p},n.walkRows)}async getReads(t,n={}){let s=await this.gaf(n);return s?s.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let s=Re(this,t);return(await this.getHaplotypes(n)).filter(r=>Ae(r.prefix,s))}async anchorFeatures(t,n){let{db:s}=await this.graph(n),{assemblyName:r,refName:o,start:i,end:c}=t,d=Re(this,n.targetAssemblyName),h=$t(this),f=this.keepPredicate(n.haplotypes,d),p=await this.referenceQuery(o,n),w=this.getConf("nodeLimit");return(p?await At(`Reading graph ${o}:${i.toLocaleString()}-${c.toLocaleString()}`,n.statusCallback,()=>s.getAlignments({path:p,start:i,end:c,context:this.getConf("context"),haplotypes:"all",limit:w,signal:n.signal,keep:f}).catch(l=>{throw ls(l,w,c-i)})):[]).flatMap(l=>{let b=l.resolved?pr({alignment:l,assemblyName:r,refName:o,lane:Ht(h,ce(l.name))}):void 0;return b===void 0?[]:[b]})}async pairFeatures(t,n,s){let{db:r}=await this.graph(s),{refName:o,start:i,end:c}=t,h=(await Promise.all(n.map(async S=>({pair:S,featureSide:await this.laneHaplotypes(S.queryAssemblyName,s),mateSide:await this.laneHaplotypes(S.targetAssemblyName,s)})))).filter(({featureSide:S,mateSide:I})=>S.length>0&&I.length>0),f=new Set(h.flatMap(({featureSide:S,mateSide:I})=>[...S,...I].map(ce))),p=await this.referenceQuery(o,s),w=this.getConf("nodeLimit"),u=this.getConf("context"),l=(S,I)=>r.getSubgraphs({path:S,start:i,end:c,context:I,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:w,signal:s.signal,keep:N=>f.has(ce(N))}),b=async S=>{let I=await l(S,u).catch(E=>{throw ls(E,w,c-i)}),N=wr(I,f),y=Math.ceil(N/2)+2e3;return N>0&&y>u?l(S,y).catch(E=>{if(E instanceof ae)return I;throw E}):I};return(p&&h.length>0?await At(Mn(n),s.statusCallback,()=>b(p)):[]).flatMap(S=>h.flatMap(({pair:I,featureSide:N,mateSide:y})=>N.flatMap(E=>y.flatMap(R=>S.pairAlignments({target:E,query:R,bases:!1}).map(F=>ur({pair:F,lane:I.queryAssemblyName,mateLane:I.targetAssemblyName}))))))}getFeatures(t,n={}){let s=ps(t);return vn(async r=>{let{db:o,anchor:i,unreadableIndex:c}=await this.graph(n);if(!o.hasHaplotypeIndex)throw new kt(c);if(s.assemblyName===i){let d=Ln(n),h=d.length>0?await this.pairFeatures(s,d,n):await this.anchorFeatures(s,n);for(let f of h)r.next(f)}r.complete()},n.signal)}};export{kt as NoHaplotypeIndexError,bs as PairTargetError,Kt as default,wr as widestWalkGap};
9
- //# sourceMappingURL=GbzBaseSyntenyAdapter-JMYDJODG.js.map
9
+ //# sourceMappingURL=GbzBaseSyntenyAdapter-X6AW5IYW.js.map
@@ -1,4 +1,4 @@
1
- import{b as $}from"./chunk-TMF6JHCE.js";import"./chunk-OIGMGVI6.js";import"./chunk-JJ2TPWSH.js";import{g as R,h as U}from"./chunk-VV5LVNCP.js";import"./chunk-IK5G3JHR.js";import{a as V}from"./chunk-4MTS65XF.js";import"./chunk-G6DZANDH.js";import{q as v}from"./chunk-OP2PTYDR.js";import"./chunk-TP6OXTXD.js";import"./chunk-JWIFJIPZ.js";import"./chunk-MYJVR2OX.js";import"./chunk-4RZCYOCW.js";import"./chunk-NTXLYTF6.js";import"./chunk-JM4W4PKP.js";import"./chunk-3GK5ZBUB.js";import"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-D3QZGLZ3.js";import"./chunk-WKD7ALOU.js";import"./chunk-CTQBRAQH.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{j as A,o as F}from"./chunk-5L276I7O.js";import{e as O,i as c}from"./chunk-J2PN6CG3.js";import{B as y,G as x,I as p,e as N,j as B,m as E,n as D,o as l,s as P,y as z}from"./chunk-H42TSPVA.js";import{a as L,b as e,c as n,d}from"./chunk-DUU6T2I5.js";var K=v()({paper:{padding:16,margin:8,maxWidth:560,marginInline:"auto",display:"flex",flexDirection:"column",gap:12},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},actions:{display:"flex",justifyContent:"flex-end",gap:8}}),_=d(function({model:t}){return e(l,{size:"small","data-testid":"graph-genome-choose-another",onClick:()=>{t.clearGraph()},children:"Choose another graph"})}),X=d(function({model:t}){let{classes:r}=K();return!t.error&&!t.loadCanceled?n(y,{className:r.paper,"data-testid":"graph-genome-loading",children:[n("div",{className:r.row,children:[e(B,{variant:"h6",message:t.statusMessage||void 0}),t.canCancelLoad?e(l,{size:"small","data-testid":"graph-genome-cancel",onClick:()=>{t.cancelLoad()},children:"Cancel"}):null]}),e(z,{variant:"indeterminate"})]}):t.error?n(y,{className:r.paper,children:[e(N,{error:t.error,onReset:()=>{t.retryLoad()}}),e("div",{className:r.actions,children:e(_,{model:t})})]}):e(y,{className:r.paper,"data-testid":"graph-genome-load-canceled",children:n("div",{className:r.row,children:[e(p,{variant:"h6",children:"Loading canceled"}),n("div",{className:r.actions,children:[e(_,{model:t}),e(l,{variant:"contained",size:"small","data-testid":"graph-genome-retry",onClick:()=>{t.retryLoad()},children:"Retry"})]})]})})}),I=X;var q=V(e("path",{d:"M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7m2.85 11.1-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1"}),"LightbulbOutlined");var Z=v()({column:{display:"flex",flexDirection:"column",gap:12},actions:{display:"flex",justifyContent:"flex-end"}}),J=d(function({model:t,choices:r}){let{classes:T}=Z(),f=A(t),{assemblyManager:g}=f,[S,G]=c(r[0]?.trackId),[w,k]=c(),[C,h]=c(),a=r.find(o=>o.trackId===S)??r[0],i=a?.assembly,M=(i?g.get(i):void 0)?.regions?.[0],b=w??(a?R(f.views,a.assembly)??(M?U(a,M):""):"");O(()=>{i&&g.waitForAssembly(i).catch(()=>{})},[g,i]);async function W(){if(a)try{let o=await g.waitForAssembly(a.assembly),s=o?F(b,u=>o.isValidRefName(u)):void 0;!o||!s||!o.isValidRefName(s.refName)?h(`No sequence ${s?.refName??b} in ${a.assembly}`):t.showTrackInLinearView(a.trackId,a.assembly,b)}catch(o){h(String(o instanceof Error?o.message:o))}}return n("form",{className:T.column,"data-testid":"graph-track-picker",onSubmit:o=>{o.preventDefault(),W()},children:[e(D,{options:r,value:a??null,getOptionLabel:o=>o.name,isOptionEqualToValue:(o,s)=>o.trackId===s.trackId,onChange:(o,s)=>{s&&(G(s.trackId),k(void 0),h(void 0))},renderOption:({key:o,...s},u)=>e("li",{...s,children:n("div",{children:[e(p,{variant:"body2",children:u.name}),n(p,{variant:"caption",color:"text.secondary",children:[u.assembly," \xB7 ",u.reach]})]})},u.trackId),renderInput:o=>e(x,{...o,size:"small",label:"Graph track",helperText:a?`${a.assembly} \xB7 ${a.reach}`:""})}),e(x,{size:"small",label:"Region",name:"region",value:b,placeholder:"chr1:1,000,001-1,020,000",error:C!==void 0,helperText:C??"A sequence name, or name:start-end",onChange:o=>{k(o.target.value),h(void 0)}}),e("div",{className:T.actions,children:e(l,{type:"submit",variant:"contained","data-testid":"graph-track-show",disabled:!a||!b.trim(),children:"Show in linear genome view"})})]})}),H=J;var Q=`H VN:Z:1.0
1
+ import{b as $}from"./chunk-MQ43JVZM.js";import"./chunk-OIGMGVI6.js";import"./chunk-JJ2TPWSH.js";import{g as R,h as U}from"./chunk-VV5LVNCP.js";import"./chunk-IK5G3JHR.js";import{a as V}from"./chunk-4MTS65XF.js";import"./chunk-G6DZANDH.js";import{q as v}from"./chunk-OP2PTYDR.js";import"./chunk-TP6OXTXD.js";import"./chunk-JWIFJIPZ.js";import"./chunk-MYJVR2OX.js";import"./chunk-4RZCYOCW.js";import"./chunk-NTXLYTF6.js";import"./chunk-JM4W4PKP.js";import"./chunk-3GK5ZBUB.js";import"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-D3QZGLZ3.js";import"./chunk-WKD7ALOU.js";import"./chunk-TDHUAADJ.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{j as A,o as F}from"./chunk-5L276I7O.js";import{e as O,i as c}from"./chunk-J2PN6CG3.js";import{B as y,G as x,I as p,e as N,j as B,m as E,n as D,o as l,s as P,y as z}from"./chunk-H42TSPVA.js";import{a as L,b as e,c as n,d}from"./chunk-DUU6T2I5.js";var K=v()({paper:{padding:16,margin:8,maxWidth:560,marginInline:"auto",display:"flex",flexDirection:"column",gap:12},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},actions:{display:"flex",justifyContent:"flex-end",gap:8}}),_=d(function({model:t}){return e(l,{size:"small","data-testid":"graph-genome-choose-another",onClick:()=>{t.clearGraph()},children:"Choose another graph"})}),X=d(function({model:t}){let{classes:r}=K();return!t.error&&!t.loadCanceled?n(y,{className:r.paper,"data-testid":"graph-genome-loading",children:[n("div",{className:r.row,children:[e(B,{variant:"h6",message:t.statusMessage||void 0}),t.canCancelLoad?e(l,{size:"small","data-testid":"graph-genome-cancel",onClick:()=>{t.cancelLoad()},children:"Cancel"}):null]}),e(z,{variant:"indeterminate"})]}):t.error?n(y,{className:r.paper,children:[e(N,{error:t.error,onReset:()=>{t.retryLoad()}}),e("div",{className:r.actions,children:e(_,{model:t})})]}):e(y,{className:r.paper,"data-testid":"graph-genome-load-canceled",children:n("div",{className:r.row,children:[e(p,{variant:"h6",children:"Loading canceled"}),n("div",{className:r.actions,children:[e(_,{model:t}),e(l,{variant:"contained",size:"small","data-testid":"graph-genome-retry",onClick:()=>{t.retryLoad()},children:"Retry"})]})]})})}),I=X;var q=V(e("path",{d:"M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7m2.85 11.1-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1"}),"LightbulbOutlined");var Z=v()({column:{display:"flex",flexDirection:"column",gap:12},actions:{display:"flex",justifyContent:"flex-end"}}),J=d(function({model:t,choices:r}){let{classes:T}=Z(),f=A(t),{assemblyManager:g}=f,[S,G]=c(r[0]?.trackId),[w,k]=c(),[C,h]=c(),a=r.find(o=>o.trackId===S)??r[0],i=a?.assembly,M=(i?g.get(i):void 0)?.regions?.[0],b=w??(a?R(f.views,a.assembly)??(M?U(a,M):""):"");O(()=>{i&&g.waitForAssembly(i).catch(()=>{})},[g,i]);async function W(){if(a)try{let o=await g.waitForAssembly(a.assembly),s=o?F(b,u=>o.isValidRefName(u)):void 0;!o||!s||!o.isValidRefName(s.refName)?h(`No sequence ${s?.refName??b} in ${a.assembly}`):t.showTrackInLinearView(a.trackId,a.assembly,b)}catch(o){h(String(o instanceof Error?o.message:o))}}return n("form",{className:T.column,"data-testid":"graph-track-picker",onSubmit:o=>{o.preventDefault(),W()},children:[e(D,{options:r,value:a??null,getOptionLabel:o=>o.name,isOptionEqualToValue:(o,s)=>o.trackId===s.trackId,onChange:(o,s)=>{s&&(G(s.trackId),k(void 0),h(void 0))},renderOption:({key:o,...s},u)=>e("li",{...s,children:n("div",{children:[e(p,{variant:"body2",children:u.name}),n(p,{variant:"caption",color:"text.secondary",children:[u.assembly," \xB7 ",u.reach]})]})},u.trackId),renderInput:o=>e(x,{...o,size:"small",label:"Graph track",helperText:a?`${a.assembly} \xB7 ${a.reach}`:""})}),e(x,{size:"small",label:"Region",name:"region",value:b,placeholder:"chr1:1,000,001-1,020,000",error:C!==void 0,helperText:C??"A sequence name, or name:start-end",onChange:o=>{k(o.target.value),h(void 0)}}),e("div",{className:T.actions,children:e(l,{type:"submit",variant:"contained","data-testid":"graph-track-show",disabled:!a||!b.trim(),children:"Show in linear genome view"})})]})}),H=J;var Q=`H VN:Z:1.0
2
2
  S 1 ACGT
3
3
  S 2 GGCC
4
4
  S 3 TTAA
@@ -7,4 +7,4 @@ L 1 + 2 + 0M
7
7
  L 1 + 3 + 0M
8
8
  L 2 + 4 + 0M
9
9
  L 3 + 4 + 0M`,Y=v()(m=>({column:{display:"flex",flexDirection:"column",gap:8},rowEnd:{display:"flex",gap:8,alignItems:"flex-end"},rowCenter:{display:"flex",gap:8,alignItems:"center"},flex1:{flex:1},paper:{padding:16,margin:8,maxWidth:560,marginInline:"auto"},header:{marginBottom:12},tip:{marginBottom:16},divider:{marginBlock:16},footer:{marginTop:12,display:"flex",justifyContent:"flex-end"},dragging:{outline:`2px dashed ${m.palette.primary.main}`,outlineOffset:-4}})),ee=d(function({model:t}){let{classes:r,cx:T}=Y(),[f,g]=c(""),[S,G]=c(!1),{graphTracks:w}=t;function k(){let a=f.trim();a&&t.openGfaLocation({uri:a,locationType:"UriLocation"})}function C(a){let i=a.target.files?.[0];a.target.value="",i&&t.loadGFAFile(i,i.name)}function h(a){a.preventDefault(),G(!1);let i=a.dataTransfer.files[0];i&&t.loadGFAFile(i,i.name)}return n(y,{className:T(r.paper,S&&r.dragging),"data-testid":"graph-import-form",onDragOver:a=>{a.preventDefault(),G(a.dataTransfer.types.includes("Files"))},onDragLeave:a=>{(!(a.relatedTarget instanceof Node)||!a.currentTarget.contains(a.relatedTarget))&&G(!1)},onDrop:a=>{h(a)},children:[n(E,{severity:"info",icon:e(q,{fontSize:"inherit"}),className:r.tip,"data-testid":"graph-import-tip",children:["A pangenome graph usually reads best as a track in a linear genome view, which redraws it as you pan and zoom."," ",w.length>0?"Pick a graph track and a region below.":"Index it with gfa-to-tabix and open it with File \u2192 Open track."]}),w.length>0?n(L,{children:[e("div",{className:r.header,children:e(p,{variant:"h6",children:"Show a graph track"})}),e(H,{model:t,choices:w}),e(P,{className:r.divider}),e("div",{className:r.header,children:e(p,{variant:"subtitle1",children:"Or open a small GFA file"})})]}):e("div",{className:r.header,children:e(p,{variant:"h6",children:"Open a small GFA file"})}),n("div",{className:r.column,children:[n("div",{className:r.rowCenter,children:[n(l,{variant:"outlined",component:"label",size:"small",children:["Choose file",e("input",{type:"file",accept:".gfa,.gfa1,.gfa2,.gz",hidden:!0,onChange:a=>{C(a)}})]}),e(p,{variant:"caption",color:"text.secondary",children:"Or drop one here. The whole file is drawn at once."})]}),n("div",{className:r.rowEnd,children:[e(x,{size:"small",label:"URL",placeholder:"https://example.com/graph.gfa",value:f,onChange:a=>{g(a.target.value)},onKeyDown:a=>{a.key==="Enter"&&k()},className:r.flex1}),e(l,{variant:"contained",onClick:()=>{k()},disabled:!f.trim(),children:"Open"})]})]}),e("div",{className:r.footer,children:e(l,{size:"small",onClick:()=>{t.loadGFA(Q,"Example graph")},children:"Load 4-node example"})}),t.error?e(N,{error:t.error}):null]})}),j=ee;var ae=d(function({model:t}){return t.hasGraph?e($,{model:t}):t.canRetryLoad?e(I,{model:t}):n(L,{children:[t.isLoading?e(I,{model:t}):null,e("div",{hidden:t.isLoading,children:e(j,{model:t})})]})}),Ve=ae;export{Ve as default};
10
- //# sourceMappingURL=GraphGenomeView-7KODXFCZ.js.map
10
+ //# sourceMappingURL=GraphGenomeView-ZTZEYNUY.js.map
@@ -1,2 +1,2 @@
1
- import{a,b as i}from"./chunk-TMF6JHCE.js";import"./chunk-OIGMGVI6.js";import"./chunk-JJ2TPWSH.js";import"./chunk-4MTS65XF.js";import"./chunk-G6DZANDH.js";import"./chunk-OP2PTYDR.js";import"./chunk-TP6OXTXD.js";import"./chunk-JWIFJIPZ.js";import"./chunk-MYJVR2OX.js";import"./chunk-4RZCYOCW.js";import"./chunk-NTXLYTF6.js";import"./chunk-3GK5ZBUB.js";import"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-D3QZGLZ3.js";import"./chunk-WKD7ALOU.js";import"./chunk-CTQBRAQH.js";import"./chunk-TMM73K4C.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import"./chunk-5L276I7O.js";import"./chunk-J2PN6CG3.js";import"./chunk-H42TSPVA.js";import{b as o,d as t}from"./chunk-DUU6T2I5.js";var e=JBrowseExports["@jbrowse/display-kit/DisplayChrome"];var s=e&&e.__esModule?e.default:e;var p=t(function({model:r}){return o(s,{model:r,factory:a,testid:"linear-graph-display","data-layout":r.chosenLayoutMode,"data-cut-tier":r.cutTier,"data-recuts":r.recuts,"data-node-count":r.hasGraph?r.nodeCount:void 0,"data-loading":r.isLoading?"":void 0,style:{width:r.paneWidth,height:r.height,overflow:"hidden"},children:n=>o(i,{model:r,handle:n})})}),c=p;export{c as default};
2
- //# sourceMappingURL=LinearGraphDisplay-ZAIMEATG.js.map
1
+ import{a,b as i}from"./chunk-MQ43JVZM.js";import"./chunk-OIGMGVI6.js";import"./chunk-JJ2TPWSH.js";import"./chunk-4MTS65XF.js";import"./chunk-G6DZANDH.js";import"./chunk-OP2PTYDR.js";import"./chunk-TP6OXTXD.js";import"./chunk-JWIFJIPZ.js";import"./chunk-MYJVR2OX.js";import"./chunk-4RZCYOCW.js";import"./chunk-NTXLYTF6.js";import"./chunk-3GK5ZBUB.js";import"./chunk-LRBNBP2K.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-D3QZGLZ3.js";import"./chunk-WKD7ALOU.js";import"./chunk-TDHUAADJ.js";import"./chunk-TMM73K4C.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import"./chunk-5L276I7O.js";import"./chunk-J2PN6CG3.js";import"./chunk-H42TSPVA.js";import{b as o,d as t}from"./chunk-DUU6T2I5.js";var e=JBrowseExports["@jbrowse/display-kit/DisplayChrome"];var s=e&&e.__esModule?e.default:e;var p=t(function({model:r}){return o(s,{model:r,factory:a,testid:"linear-graph-display","data-layout":r.chosenLayoutMode,"data-cut-tier":r.cutTier,"data-recuts":r.recuts,"data-node-count":r.hasGraph?r.nodeCount:void 0,"data-loading":r.isLoading?"":void 0,style:{width:r.paneWidth,height:r.height,overflow:"hidden"},children:n=>o(i,{model:r,handle:n})})}),c=p;export{c as default};
2
+ //# sourceMappingURL=LinearGraphDisplay-QWJZ5PSO.js.map
@@ -1,2 +1,2 @@
1
- import{a as c,d,f as h}from"./chunk-NTXLYTF6.js";import{a as m}from"./chunk-V55TK2NP.js";import{a as b,c as p,d as u,g as f,h as g}from"./chunk-HTVBMX7V.js";import"./chunk-CTQBRAQH.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as i,q as l}from"./chunk-5L276I7O.js";var a=class extends b{constructor(){super(...arguments);this.bubbles=u(this,["bubblesLocation"],["index"]);this.refNames=new g(f(this.bubbles),this)}static{this.capabilities=["getFeatures","getRefNames"]}async getRefNames(t={}){return this.refNames.assemblyRefNames(t)}async getRegionByteSize(t,s={}){return this.refNames.regionBytes(t,s)}async hasDataForRefName(){return!0}getFeatures(t,s={}){let{signal:n,statusCallback:N}=s;return m(async r=>{let o=await this.refNames.resolveMapped(t,s);o!==void 0&&await l("Downloading bubbles",N,()=>p(this.bubbles,o,t.start,t.end,{signal:n,lineCallback:(y,R)=>{let e=c(y);r.next(new i({uniqueId:`bubble-${R}`,refName:t.refName,start:e.start,end:e.end,name:d(e),description:h(e),type:"bubble",score:e.segmentCount,segmentCount:e.segmentCount,pathCount:e.pathCount,inversion:e.inversion,shortestAlleleLength:e.shortestAlleleLength,longestAlleleLength:e.longestAlleleLength,segments:e.segments,shortestAllele:e.shortestAllele,longestAllele:e.longestAllele}))}})),r.complete()},n)}};export{a as default};
2
- //# sourceMappingURL=MinigraphBubbleAdapter-N5BOXD7U.js.map
1
+ import{a as c,d,f as h}from"./chunk-NTXLYTF6.js";import{a as m}from"./chunk-V55TK2NP.js";import{a as b,c as p,d as u,g as f,h as g}from"./chunk-UXBGMTAO.js";import"./chunk-TDHUAADJ.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as i,q as l}from"./chunk-5L276I7O.js";var a=class extends b{constructor(){super(...arguments);this.bubbles=u(this,["bubblesLocation"],["index"]);this.refNames=new g(f(this.bubbles),this)}static{this.capabilities=["getFeatures","getRefNames"]}async getRefNames(t={}){return this.refNames.assemblyRefNames(t)}async getRegionByteSize(t,s={}){return this.refNames.regionBytes(t,s)}async hasDataForRefName(){return!0}getFeatures(t,s={}){let{signal:n,statusCallback:N}=s;return m(async r=>{let o=await this.refNames.resolveMapped(t,s);o!==void 0&&await l("Downloading bubbles",N,()=>p(this.bubbles,o,t.start,t.end,{signal:n,lineCallback:(y,R)=>{let e=c(y);r.next(new i({uniqueId:`bubble-${R}`,refName:t.refName,start:e.start,end:e.end,name:d(e),description:h(e),type:"bubble",score:e.segmentCount,segmentCount:e.segmentCount,pathCount:e.pathCount,inversion:e.inversion,shortestAlleleLength:e.shortestAlleleLength,longestAlleleLength:e.longestAlleleLength,segments:e.segments,shortestAllele:e.shortestAllele,longestAllele:e.longestAllele}))}})),r.complete()},n)}};export{a as default};
2
+ //# sourceMappingURL=MinigraphBubbleAdapter-WUTIBCFA.js.map
@@ -1,2 +1,2 @@
1
- import{a as y}from"./chunk-D7BAG2VJ.js";import"./chunk-JLIDLLZG.js";import{a as w}from"./chunk-V55TK2NP.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import{a as u,c as f,d as p,e as F,g as c,h as d}from"./chunk-HTVBMX7V.js";import{A as R,w as b,x as k,y as x,z as N}from"./chunk-CTQBRAQH.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as g}from"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as m,q as l}from"./chunk-5L276I7O.js";var h=class extends u{constructor(){super(...arguments);this.fine=this.openIndex([])}static{this.capabilities=["getFeatures","getRefNames"]}openIndex(e){let t=this.getConf("walksLocation"),n=e.length===0&&g(t)?new y(F(this),this):void 0,r=e.length===0?this.getConf("graphLocation"):this.getConf(["coarse","graphLocation"]);if(g(r)){let s=p(this,[...e,"graphLocation"],[...e,"graphIndex"]);return{graph:s,walks:n,refNames:new d(n?.source??c(s),this)}}let a=p(this,[...e,"segmentsLocation"],[...e,"segmentsIndex"]),i=p(this,[...e,"linksLocation"],[...e,"linksIndex"]);return{segments:a,links:i,walks:n,refNames:new d(n?.source??c(a),this)}}async getHaplotypeNames(e={}){return this.fine.walks?.haplotypeNames(e)}index(e="fine"){return e==="fine"?this.fine:(this.coarse??=this.openIndex(["coarse"]),this.coarse)}async getRefNames(e={}){return this.fine.refNames.assemblyRefNames(e)}async getRegionByteSize(e,t={}){return this.fine.refNames.regionBytes(e,t)}async hasDataForRefName(){return!0}getFeatures(e,t={}){return w(async n=>{let r=await this.fine.refNames.resolveMapped(e,t);if(r!==void 0){let{walks:a}=this.fine,i=s=>{n.next(s)};await(a?this.walkFeatures(a,r,e,t,i):this.segmentFeatures(r,e,t,i))}n.complete()},t.signal)}async walkFeatures(e,t,n,r,a){let i=await l("Downloading walks",r.statusCallback,()=>e.referenceNodes(t,n,r));for(let s of i){let o=String(s.id);a(new m({uniqueId:o,refName:n.refName,start:s.start,end:s.end,name:o,type:"segment",rank:0,stableName:s.refName}))}}async segmentRows(e,t,n,r){let a=this.fine;if("graph"in a){let i=x(await a.graph.getHeaderLines({signal:n.signal}));return f(a.graph,e,t.start,t.end,{signal:n.signal,lineCallback:s=>{let o=N(s,i);o?.kind==="N"&&r(o.segment,i.anchored)}})}return f(a.segments,e,t.start,t.end,{signal:n.signal,lineCallback:i=>{let{segment:s,anchored:o}=b(i);r(s,o)}})}async segmentFeatures(e,t,n,r){await l("Downloading segments",n.statusCallback,()=>this.segmentRows(e,t,n,(a,i)=>{if(i&&a.refName!==e)return;let s=k(a);r(new m({uniqueId:a.id,refName:t.refName,start:a.start,end:a.end,name:a.id,type:"segment",rank:a.rank,stableName:a.refName,...s&&{samples:s,sampleCount:s.length}}))}))}async getSubgraph(e,t={}){let{hops:n,signal:r,tier:a}=t,i=this.index(a),s=await i.refNames.resolveForCut(e,{signal:r});return i.walks?i.walks.subgraph(s,e,t):R(i,{refName:s,start:e.start,end:e.end},{hops:n,signal:r})}};export{h as default};
2
- //# sourceMappingURL=RgfaTabixAdapter-FZZ7W2HN.js.map
1
+ import{a as y}from"./chunk-P7V5S3V3.js";import"./chunk-UPSA4KVF.js";import{a as w}from"./chunk-V55TK2NP.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import{a as u,c as f,d as p,e as F,g as c,h as d}from"./chunk-UXBGMTAO.js";import{A as R,w as b,x as k,y as x,z as N}from"./chunk-TDHUAADJ.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as g}from"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as m,q as l}from"./chunk-5L276I7O.js";var h=class extends u{constructor(){super(...arguments);this.fine=this.openIndex([])}static{this.capabilities=["getFeatures","getRefNames"]}openIndex(e){let t=this.getConf("walksLocation"),n=e.length===0&&g(t)?new y(F(this),this):void 0,r=e.length===0?this.getConf("graphLocation"):this.getConf(["coarse","graphLocation"]);if(g(r)){let s=p(this,[...e,"graphLocation"],[...e,"graphIndex"]);return{graph:s,walks:n,refNames:new d(n?.source??c(s),this)}}let a=p(this,[...e,"segmentsLocation"],[...e,"segmentsIndex"]),i=p(this,[...e,"linksLocation"],[...e,"linksIndex"]);return{segments:a,links:i,walks:n,refNames:new d(n?.source??c(a),this)}}async getHaplotypeNames(e={}){return this.fine.walks?.haplotypeNames(e)}index(e="fine"){return e==="fine"?this.fine:(this.coarse??=this.openIndex(["coarse"]),this.coarse)}async getRefNames(e={}){return this.fine.refNames.assemblyRefNames(e)}async getRegionByteSize(e,t={}){return this.fine.refNames.regionBytes(e,t)}async hasDataForRefName(){return!0}getFeatures(e,t={}){return w(async n=>{let r=await this.fine.refNames.resolveMapped(e,t);if(r!==void 0){let{walks:a}=this.fine,i=s=>{n.next(s)};await(a?this.walkFeatures(a,r,e,t,i):this.segmentFeatures(r,e,t,i))}n.complete()},t.signal)}async walkFeatures(e,t,n,r,a){let i=await l("Downloading walks",r.statusCallback,()=>e.referenceNodes(t,n,r));for(let s of i){let o=String(s.id);a(new m({uniqueId:o,refName:n.refName,start:s.start,end:s.end,name:o,type:"segment",rank:0,stableName:s.refName}))}}async segmentRows(e,t,n,r){let a=this.fine;if("graph"in a){let i=x(await a.graph.getHeaderLines({signal:n.signal}));return f(a.graph,e,t.start,t.end,{signal:n.signal,lineCallback:s=>{let o=N(s,i);o?.kind==="N"&&r(o.segment,i.anchored)}})}return f(a.segments,e,t.start,t.end,{signal:n.signal,lineCallback:i=>{let{segment:s,anchored:o}=b(i);r(s,o)}})}async segmentFeatures(e,t,n,r){await l("Downloading segments",n.statusCallback,()=>this.segmentRows(e,t,n,(a,i)=>{if(i&&a.refName!==e)return;let s=k(a);r(new m({uniqueId:a.id,refName:t.refName,start:a.start,end:a.end,name:a.id,type:"segment",rank:a.rank,stableName:a.refName,...s&&{samples:s,sampleCount:s.length}}))}))}async getSubgraph(e,t={}){let{hops:n,signal:r,tier:a}=t,i=this.index(a),s=await i.refNames.resolveForCut(e,{signal:r});return i.walks?i.walks.subgraph(s,e,t):R(i,{refName:s,start:e.start,end:e.end},{hops:n,signal:r})}};export{h as default};
2
+ //# sourceMappingURL=RgfaTabixAdapter-VT7TYMNE.js.map
@@ -1,2 +1,2 @@
1
- import{c as d,d as A,e as D,f as L,g as V}from"./chunk-ZVMXECJA.js";import{a as $}from"./chunk-V55TK2NP.js";import{a as k,e as _}from"./chunk-HTVBMX7V.js";import{a as b,b as C,c as N,d as T,o as E,p as R,q as x,r as O,s as B,t as M,u as q,v as P}from"./chunk-CTQBRAQH.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as F,q as v}from"./chunk-5L276I7O.js";var I={deletion:{svType:"DEL",type:"deletion",alt:"<DEL>"},insertion:{svType:"INS",type:"insertion",alt:"<INS>"},duplication:{svType:"DUP",type:"tandem_duplication",alt:"<DUP:TANDEM>"},replacement:{svType:"CPX",type:"complex_substitution",alt:"<CPX>"},inversion:{svType:"INV",type:"inversion",alt:"<INV>",consequence:"inversion"},shift:{svType:"CPX",type:"complex_structural_alteration",alt:"<CPX>",consequence:"shift"}},Q=e=>e.lopsided??(e.delta<0?"deletion":"insertion"),J=e=>I[e.kind].consequence??(Q(e)==="deletion"?"loss":"gain"),U=e=>`F${e+1}`,Y="other";function W(e,o){let t=100*e/o;return t>0&&t<1?"<1%":`${Math.round(t)}%`}var g=({forms:e},o)=>e.length>o+1?Math.max(0,o):e.length,l=e=>e.reduce((o,t)=>o+t.members.length,0);function w(e,o=d){let t=g(e,o),n=e.forms.slice(t);return[...e.forms.slice(0,t).map((s,a)=>({name:U(a),label:`${W(s.members.length,e.placed)} \xB7 ${q(s,e)}`,haplotypes:s.members.length,forms:1})),...n.length>0?[{name:Y,label:`other forms \xB7 ${W(l(n),e.placed)}`,haplotypes:l(n),forms:n.length}]:[]]}var j=5;function G(e){let o=e.slice(0,j).join(", "),t=e.length-j;return t>0?`${o} and ${t} more`:o}var h=e=>`${e} haplotype${e===1?"":"s"}`;function H(e,o=d){let{unplaced:t,forms:n}=e,s=g(e,o),a=n.slice(s);return[...a.length>0?[`${a.length} smaller forms, ${h(l(a))}, share the empty "other forms" row; maxForms sets how many forms get a row of their own`]:[],...t.length>0?[`${h(t.length)} ${t.length===1?"has":"have"} no walk over the pinned window, so no form: ${G(t)}`]:[]]}function Z({copied:e,refStart:o,refEnd:t}){let[n,s]=e??[o,t];return{start:n,end:Math.max(s,n+1)}}var ee=(e,o)=>e===o?"1":e===R||e===x?".":"0";function X(e,o=d){let{sites:t,forms:n,placed:s}=e,a=g(e,o);return t.flatMap((r,m)=>r.edge?[]:r.states.flatMap(p=>{if(p.key===E)return[];let u=n.map(i=>M(e,i,m)),S=Object.fromEntries(u.slice(0,a).map((i,f)=>[U(f),ee(i,p.key)])),z=l(n.filter((i,f)=>u[f]===p.key));return Object.values(S).includes("1")?p.marks.map((i,f)=>({id:`${m}:${p.key}:${f}`,...Z(i),name:B(i),description:`${z} of ${h(s)}`,...I[i.kind],consequence:J(i),mark:i,genotypes:S})):[]}))}var K=e=>`${(e/1e6).toFixed(1)} MB`;function te(e,o){if(!(e instanceof b))return e;let t=L(o),n=`walkByteBudget, ${K(e.limit)}`;return new Error(`The pinned window ${t} is too large to cut for structural forms: ${e.zoomHelps?`about ${T(e.fitsBp)} of it fits in ${n}. Pin a narrower window or raise walkByteBudget`:`its cut fetches ${K(e.bytes??0)}, over ${n}. Raise walkByteBudget`}`)}var ne=8,c=new Map;function re(e,o){let t=c.get(e),n=t??o();if(c.delete(e),c.set(e,n),!t){n.catch(()=>{c.get(e)===n&&c.delete(e)});for(let s of c.keys()){if(c.size<=ne)break;c.delete(s)}}return n}var y=class extends k{constructor(){super(...arguments);this.reader=_(this);this.variants=new WeakMap}static{this.capabilities=["getFeatures","getRefNames"]}async referenceSample(t){let{references:n}=await this.reader.header(t);return n[0]??""}async getRefNames(t={}){let n=await this.reader.referenceSequences(t),s=await this.referenceSample(t),a=n.filter(r=>N(r,s)).map(r=>C(r));return a.length>0?[...new Set(a)]:n}pinned(){let t=A(this.getConf("pinned"));if(!t)throw new Error("WalkFormsAdapter needs `pinned`, the window its forms come from: { refName, start, end }");return t}async pinnedSequence(t){let n=await this.referenceSample(t),s=[this.pinned().refName,...this.getConf("pinnedAliases")];return(await Promise.all(s.map(r=>this.reader.sequenceFor(n,r,t)))).find(r=>r!==void 0)}forms(t){if(!this.formsRead){let n=this.pinned(),s=this.getConf("walkByteBudget"),a=this.pinnedSequence({}).then(r=>{let m={...n,refName:r??n.refName},p=`${JSON.stringify(this.getConf("walksLocation"))} ${m.refName}:${m.start}-${m.end} ${s}`;return re(p,()=>v("Cutting walks",t.statusCallback,()=>P(this.reader,m,{byteBudget:s}).catch(u=>{throw te(u,n)})))}).then(r=>O(r,{window:n,floorBp:D(this.getConf("floorBp")),exclude:this.getConf("exclude")}));a.catch(()=>{this.formsRead===a&&(this.formsRead=void 0)}),this.formsRead=a}return this.formsRead}variantsOf(t){let n=this.variants.get(t),s=n??X(t,this.maxForms());return n||this.variants.set(t,s),s}maxForms(){return this.getConf("maxForms")}async getSourcesAndWarnings(t={}){let n=await this.forms(t),s=V(this.pinned());return{sources:w(n,this.maxForms()),warnings:H(n,this.maxForms()).map(a=>s+a)}}async getSources(t,n={}){return w(await this.forms(n),this.maxForms())}async onPinnedSequence(t,n){let s=await this.referenceSample(n),[a,r]=await Promise.all([this.reader.sequenceFor(s,t,n),this.pinnedSequence(n)]);return a!==void 0&&a===r}getFeatures(t,n={}){return $(async s=>{if(await this.onPinnedSequence(t.refName,n)){let a=await this.forms(n);for(let r of this.variantsOf(a))r.start<t.end&&r.end>t.start&&s.next(new F({uniqueId:`forms-${a.floorBp}-${r.id}`,refName:t.refName,start:r.start,end:r.end,name:r.name,description:r.description,type:r.type,svType:r.svType,consequence:r.consequence,REF:"N",ALT:[r.alt],INFO:{SVTYPE:[r.svType],SVLEN:[r.mark.delta]},mark:r.mark,genotypes:r.genotypes}))}s.complete()},n.signal)}};export{y as default};
2
- //# sourceMappingURL=WalkFormsAdapter-TZW5UBRI.js.map
1
+ import{c as d,d as A,e as D,f as L,g as V}from"./chunk-ZVMXECJA.js";import{a as $}from"./chunk-V55TK2NP.js";import{a as k,e as _}from"./chunk-UXBGMTAO.js";import{a as b,b as C,c as N,d as T,o as E,p as R,q as x,r as O,s as B,t as M,u as q,v as P}from"./chunk-TDHUAADJ.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import"./chunk-EGZZ3ADM.js";import"./chunk-H5PFNYKH.js";import{a as F,q as v}from"./chunk-5L276I7O.js";var I={deletion:{svType:"DEL",type:"deletion",alt:"<DEL>"},insertion:{svType:"INS",type:"insertion",alt:"<INS>"},duplication:{svType:"DUP",type:"tandem_duplication",alt:"<DUP:TANDEM>"},replacement:{svType:"CPX",type:"complex_substitution",alt:"<CPX>"},inversion:{svType:"INV",type:"inversion",alt:"<INV>",consequence:"inversion"},shift:{svType:"CPX",type:"complex_structural_alteration",alt:"<CPX>",consequence:"shift"}},Q=e=>e.lopsided??(e.delta<0?"deletion":"insertion"),J=e=>I[e.kind].consequence??(Q(e)==="deletion"?"loss":"gain"),U=e=>`F${e+1}`,Y="other";function W(e,o){let t=100*e/o;return t>0&&t<1?"<1%":`${Math.round(t)}%`}var g=({forms:e},o)=>e.length>o+1?Math.max(0,o):e.length,l=e=>e.reduce((o,t)=>o+t.members.length,0);function w(e,o=d){let t=g(e,o),n=e.forms.slice(t);return[...e.forms.slice(0,t).map((s,a)=>({name:U(a),label:`${W(s.members.length,e.placed)} \xB7 ${q(s,e)}`,haplotypes:s.members.length,forms:1})),...n.length>0?[{name:Y,label:`other forms \xB7 ${W(l(n),e.placed)}`,haplotypes:l(n),forms:n.length}]:[]]}var j=5;function G(e){let o=e.slice(0,j).join(", "),t=e.length-j;return t>0?`${o} and ${t} more`:o}var h=e=>`${e} haplotype${e===1?"":"s"}`;function H(e,o=d){let{unplaced:t,forms:n}=e,s=g(e,o),a=n.slice(s);return[...a.length>0?[`${a.length} smaller forms, ${h(l(a))}, share the empty "other forms" row; maxForms sets how many forms get a row of their own`]:[],...t.length>0?[`${h(t.length)} ${t.length===1?"has":"have"} no walk over the pinned window, so no form: ${G(t)}`]:[]]}function Z({copied:e,refStart:o,refEnd:t}){let[n,s]=e??[o,t];return{start:n,end:Math.max(s,n+1)}}var ee=(e,o)=>e===o?"1":e===R||e===x?".":"0";function X(e,o=d){let{sites:t,forms:n,placed:s}=e,a=g(e,o);return t.flatMap((r,m)=>r.edge?[]:r.states.flatMap(p=>{if(p.key===E)return[];let u=n.map(i=>M(e,i,m)),S=Object.fromEntries(u.slice(0,a).map((i,f)=>[U(f),ee(i,p.key)])),z=l(n.filter((i,f)=>u[f]===p.key));return Object.values(S).includes("1")?p.marks.map((i,f)=>({id:`${m}:${p.key}:${f}`,...Z(i),name:B(i),description:`${z} of ${h(s)}`,...I[i.kind],consequence:J(i),mark:i,genotypes:S})):[]}))}var K=e=>`${(e/1e6).toFixed(1)} MB`;function te(e,o){if(!(e instanceof b))return e;let t=L(o),n=`walkByteBudget, ${K(e.limit)}`;return new Error(`The pinned window ${t} is too large to cut for structural forms: ${e.zoomHelps?`about ${T(e.fitsBp)} of it fits in ${n}. Pin a narrower window or raise walkByteBudget`:`its cut fetches ${K(e.bytes??0)}, over ${n}. Raise walkByteBudget`}`)}var ne=8,c=new Map;function re(e,o){let t=c.get(e),n=t??o();if(c.delete(e),c.set(e,n),!t){n.catch(()=>{c.get(e)===n&&c.delete(e)});for(let s of c.keys()){if(c.size<=ne)break;c.delete(s)}}return n}var y=class extends k{constructor(){super(...arguments);this.reader=_(this);this.variants=new WeakMap}static{this.capabilities=["getFeatures","getRefNames"]}async referenceSample(t){let{references:n}=await this.reader.header(t);return n[0]??""}async getRefNames(t={}){let n=await this.reader.referenceSequences(t),s=await this.referenceSample(t),a=n.filter(r=>N(r,s)).map(r=>C(r));return a.length>0?[...new Set(a)]:n}pinned(){let t=A(this.getConf("pinned"));if(!t)throw new Error("WalkFormsAdapter needs `pinned`, the window its forms come from: { refName, start, end }");return t}async pinnedSequence(t){let n=await this.referenceSample(t),s=[this.pinned().refName,...this.getConf("pinnedAliases")];return(await Promise.all(s.map(r=>this.reader.sequenceFor(n,r,t)))).find(r=>r!==void 0)}forms(t){if(!this.formsRead){let n=this.pinned(),s=this.getConf("walkByteBudget"),a=this.pinnedSequence({}).then(r=>{let m={...n,refName:r??n.refName},p=`${JSON.stringify(this.getConf("walksLocation"))} ${m.refName}:${m.start}-${m.end} ${s}`;return re(p,()=>v("Cutting walks",t.statusCallback,()=>P(this.reader,m,{byteBudget:s}).catch(u=>{throw te(u,n)})))}).then(r=>O(r,{window:n,floorBp:D(this.getConf("floorBp")),exclude:this.getConf("exclude")}));a.catch(()=>{this.formsRead===a&&(this.formsRead=void 0)}),this.formsRead=a}return this.formsRead}variantsOf(t){let n=this.variants.get(t),s=n??X(t,this.maxForms());return n||this.variants.set(t,s),s}maxForms(){return this.getConf("maxForms")}async getSourcesAndWarnings(t={}){let n=await this.forms(t),s=V(this.pinned());return{sources:w(n,this.maxForms()),warnings:H(n,this.maxForms()).map(a=>s+a)}}async getSources(t,n={}){return w(await this.forms(n),this.maxForms())}async onPinnedSequence(t,n){let s=await this.referenceSample(n),[a,r]=await Promise.all([this.reader.sequenceFor(s,t,n),this.pinnedSequence(n)]);return a!==void 0&&a===r}getFeatures(t,n={}){return $(async s=>{if(await this.onPinnedSequence(t.refName,n)){let a=await this.forms(n);for(let r of this.variantsOf(a))r.start<t.end&&r.end>t.start&&s.next(new F({uniqueId:`forms-${a.floorBp}-${r.id}`,refName:t.refName,start:r.start,end:r.end,name:r.name,description:r.description,type:r.type,svType:r.svType,consequence:r.consequence,REF:"N",ALT:[r.alt],INFO:{SVTYPE:[r.svType],SVLEN:[r.mark.delta]},mark:r.mark,genotypes:r.genotypes}))}s.complete()},n.signal)}};export{y as default};
2
+ //# sourceMappingURL=WalkFormsAdapter-VRJ4FYQB.js.map
@@ -1,2 +1,2 @@
1
- import{a as ae}from"./chunk-D7BAG2VJ.js";import{a as ee}from"./chunk-IK5G3JHR.js";import{a as te}from"./chunk-G6DZANDH.js";import"./chunk-JWIFJIPZ.js";import"./chunk-4RZCYOCW.js";import{p as v,q as j,r as H,s as K,t as V,u as Q,v as Y}from"./chunk-NLHJYXCS.js";import"./chunk-JLIDLLZG.js";import{a as U}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{b as Z,c as J,d as B}from"./chunk-3GK5ZBUB.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-FQI75MV6.js";import{e as z,h as G}from"./chunk-HTVBMX7V.js";import{e as X}from"./chunk-CTQBRAQH.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as $}from"./chunk-EGZZ3ADM.js";import{a as C,c as q,d as F,g as S,h as w,i as A}from"./chunk-H5PFNYKH.js";import{q as T}from"./chunk-5L276I7O.js";var ue=50;function fe(s){let o=[];for(let e=0;e<s.length;e++){let[t,a]=s[e],[n,r]=s[e+1]??[];a===r&&a<=ue&&(t==="I"&&n==="D"||t==="D"&&n==="I")?(o.push(["X",a]),e++):o.push([t,a])}return o}function L(s){return Array.from(s.ids,(o,e)=>2*o+s.rev[e])}function P(s,o){let e=s.get(o);return e===void 0?0:e.end-e.start}function ne(s){let o=new Map,e=n=>{let r=P(s,n),i=o.get(r);return i===void 0&&(i="N".repeat(r),o.set(r,i)),i},t=new Map,a=n=>{let r=t.get(n);return r===void 0&&(r=L(n),t.set(n,r)),r};return(n,r)=>j({query:a(n),target:a(r),sequenceOf:e,bases:!1})}var I=100;function E(s,o,e){let t=s.at(-1);e>0&&(t?.[0]===o?t[1]+=e:s.push([o,e]))}function re(s){let o=t=>P(s,t>>1),e=t=>{let a=new Float64Array(t.length+1);return t.forEach((n,r)=>{a[r+1]=a[r]+o(n)}),a};return(t,a)=>{let n=L(a),r=L(t),[i,l]=v(r,n,o),[u,c]=v(r.map(h=>h^1).reverse(),n,o),p=c>l,f=p?u:i,W=Math.max(l,c);if(W<I)return[];let d=e(n),b=e(r),y=h=>p?r.length-1-f[h][0]:f[h][0],k=[];f.forEach(([,h],N)=>{if(N>0){let[m,g]=[y(N-1),y(N)].sort((O,pe)=>O-pe);E(k,"I",b[g]-b[m+1]),E(k,"D",d[h]-d[f[N-1][1]+1])}E(k,"=",o(n[h]))});let[M,x]=[y(0),y(f.length-1)].sort((h,N)=>h-N);return[{queryStart:b[M],queryEnd:b[x+1],targetStart:d[f[0][1]],targetEnd:d[f.at(-1)[1]+1],strand:p?"-":"+",edits:k,sharedBases:W}]}}function de(s){let o=new Map,e=new Set;s.ids.forEach((t,a)=>{o.has(t)?e.add(t):o.set(t,s.rev[a])});for(let t of e)o.delete(t);return o}function se(s){let o=new Map,e=t=>{let a=o.get(t);return a===void 0&&(a=de(t),o.set(t,a)),a};return(t,a)=>{let n=e(a),r=0,i=0;for(let[l,u]of e(t)){let c=n.get(l);c===u?r+=P(s,l):c!==void 0&&(i+=P(s,l))}return{same:r,opposite:i}}}function oe(s){let o=re(s),e=ne(s),t=se(s);return(a,n)=>{let{same:r,opposite:i}=t(a,n);return r>=I&&i>=I?e(a,n):o(a,n)}}var he=1e4;function ie(s){let o=re(s),e=ne(s),t=se(s);return(a,n)=>{let r=o(a,n),i=r[0]?.strand,{same:l,opposite:u}=t(a,n);return i===void 0||Math.min(l,u)<he?r:[...r,...e(a,n).filter(c=>c.strand!==i)]}}function R({chain:s,target:o,query:e,assemblyName:t,refName:a,mateAssemblyName:n}){let r=fe(s.edits);return Y({target:{name:o.name,assemblyName:t,refName:a,start:o.hapStart+s.targetStart,end:o.hapStart+s.targetEnd},query:{name:e.name,assemblyName:n,refName:F(e.name),start:e.hapStart+s.queryStart,end:e.hapStart+s.queryEnd},strand:s.strand,cigar:H(r),matches:r.reduce((i,[l,u])=>i+(l==="="?u:0),0),columns:r.reduce((i,[,l])=>i+l,0)})}function me(s,o,e,t){return Array.from(s.ids).some(a=>{let n=o.get(a);return n?.rank===0&&n.refName===e&&n.start<t.end&&n.end>t.start})}function le({leavePos:s,rejoinPos:o},e){return Math.min(s,o)<=e.start&&Math.max(s,o)>=e.end}function ce({departure:s,refName:o,assemblyName:e,mateAssemblyName:t}){let{name:a,hapStart:n,ownBp:r,leavePos:i,rejoinPos:l,rejoinReversed:u}=s,c=`${a}:${n}:${i}:departure`;return new K({uniqueId:c,assemblyName:e,refName:o,start:Math.min(i,l),end:Math.max(i,l),type:"departure",strand:u?-1:1,syntenyId:c,spansWindow:!0,mate:{refName:F(a),start:n,end:n+r,assemblyName:t}})}var _=({name:s})=>q(s)??s,D=class extends V{constructor(){super(...arguments);this.walks=new ae(z(this),this);this.refNames=new G(this.walks.source,this)}get anchor(){let e=this.getConf("assemblyNames")[0];if(e===void 0)throw new Error("WalkTabixSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");return e}async getHaplotypeNames(e={}){return this.walks.haplotypeNames(e)}async getHeader(e={}){let[{haplotypes:t},a]=await Promise.all([this.walks.reader.header(e),this.sheetColors(e)]),{anchor:n}=this,r=w(this,n),i=A(this),l=c=>c===r||C(c)===r,u=a?.(t.find(l)??r);return{hasCoarseTier:!1,anchorAssemblyName:n,...u===void 0?{}:{anchorColor:u},lanes:t.filter(c=>!l(c)).map(c=>{let p=a?.(c);return{name:B(i,c),label:c,group:C(c),...p===void 0?{}:{color:p}}})}}async sheetColors(e){let t=this.getConf("samplesTsvLocation");return $(t)?ee({location:t,names:void 0,namesLabel:"the walk file",pluginManager:this.pluginManager,opts:e}).then(({sources:a})=>te(a,A(this)),()=>{}):void 0}async getRefNames(e={}){let{assemblyName:t}=e;return t===void 0||t===this.anchor?this.refNames.assemblyRefNames({...e,assemblyName:this.anchor}):[]}async getSubgraph(e,t={}){let a=await this.refNames.resolveForCut(e,{signal:t.signal});return this.walks.subgraph(a,e,t)}async laneWalks(e,t,a,n,r){let i=X(a,e);return T(r,n.statusCallback,()=>this.walks.reader.cut(e,t,{...this.walks.cutOptions(),signal:n.signal,keep:i,expand:i,links:!1}).catch(l=>{throw Q(l,t.end-t.start)}))}async anchorFeatures(e,t,a){let n=a.haplotypes?.length?a.haplotypes.map(m=>w(this,m)):void 0,r=w(this,a.targetAssemblyName),i=r===void 0?n:n===void 0||n.some(m=>S(r,m)||S(m,r))?[r]:[];if(i?.length===0)return[];let{start:l,end:u}=t,c=`Reading walks ${t.refName}:${l.toLocaleString()}-${u.toLocaleString()}`,{graph:p,fragments:f,departures:W}=await this.laneWalks(e,t,i,a,c),d=({name:m})=>i===void 0?0:i.findIndex(g=>S(m,g)),b=ie(p.nodes),y=A(this),k=m=>B(y,_(m)),M=f.filter(m=>m.name===e),x=f.filter(m=>m.name!==e&&d(m)>=0).map(m=>({rank:d(m),features:M.flatMap(g=>b(m,g).map(O=>R({chain:O,target:g,query:m,assemblyName:t.assemblyName,refName:t.refName,mateAssemblyName:k(m)})))})),h=new Set(f.filter(m=>me(m,p.nodes,e,t)).map(_)),N=W.filter(m=>d(m)>=0&&!h.has(_(m))&&le(m,t)).sort((m,g)=>m.name.localeCompare(g.name)).map(m=>({rank:d(m),features:[ce({departure:m,refName:t.refName,assemblyName:t.assemblyName,mateAssemblyName:k(m)})]}));return[...x,...N].sort((m,g)=>m.rank-g.rank).flatMap(m=>m.features)}async pairFeatures(e,t,a,n){let r=a.map(p=>({pair:p,featurePrefix:w(this,p.queryAssemblyName),matePrefix:w(this,p.targetAssemblyName)})),{graph:i,fragments:l}=await this.laneWalks(e,t,r.flatMap(p=>[p.featurePrefix,p.matePrefix]),n,J(a)),u=oe(i.nodes),c=p=>l.filter(f=>S(f.name,p));return r.flatMap(({pair:p,featurePrefix:f,matePrefix:W})=>c(f).flatMap(d=>c(W).flatMap(b=>u(b,d).map(y=>R({chain:y,target:d,query:b,assemblyName:p.queryAssemblyName,refName:F(d.name),mateAssemblyName:p.targetAssemblyName})))))}getFeatures(e,t={}){return U(async a=>{let n=e.assemblyName===this.anchor?await this.refNames.resolveMapped(e,t):void 0;if(n!==void 0){let r=Z(t),i=r.length>0?await this.pairFeatures(n,e,r,t):await this.anchorFeatures(n,e,t);for(let l of i)a.next(l)}a.complete()},t.signal)}};export{D as default};
2
- //# sourceMappingURL=WalkTabixSyntenyAdapter-XM7HBNJA.js.map
1
+ import{a as ae}from"./chunk-P7V5S3V3.js";import{a as ee}from"./chunk-IK5G3JHR.js";import{a as te}from"./chunk-G6DZANDH.js";import"./chunk-JWIFJIPZ.js";import"./chunk-4RZCYOCW.js";import{p as v,q as j,r as H,s as K,t as V,u as Q,v as Y}from"./chunk-5FMNLEED.js";import"./chunk-UPSA4KVF.js";import{a as U}from"./chunk-V55TK2NP.js";import"./chunk-JM4W4PKP.js";import{b as Z,c as J,d as B}from"./chunk-3GK5ZBUB.js";import"./chunk-YBLNN5FU.js";import"./chunk-ZLQEXXMV.js";import"./chunk-6TXZQA6S.js";import"./chunk-RQSCKHNS.js";import"./chunk-FQI75MV6.js";import{e as z,h as G}from"./chunk-UXBGMTAO.js";import{e as X}from"./chunk-TDHUAADJ.js";import"./chunk-TMM73K4C.js";import"./chunk-D6TY2QEG.js";import"./chunk-YBLNN5FU.js";import{e as $}from"./chunk-EGZZ3ADM.js";import{a as C,c as q,d as F,g as S,h as w,i as A}from"./chunk-H5PFNYKH.js";import{q as T}from"./chunk-5L276I7O.js";var ue=50;function fe(s){let o=[];for(let e=0;e<s.length;e++){let[t,a]=s[e],[n,r]=s[e+1]??[];a===r&&a<=ue&&(t==="I"&&n==="D"||t==="D"&&n==="I")?(o.push(["X",a]),e++):o.push([t,a])}return o}function L(s){return Array.from(s.ids,(o,e)=>2*o+s.rev[e])}function P(s,o){let e=s.get(o);return e===void 0?0:e.end-e.start}function ne(s){let o=new Map,e=n=>{let r=P(s,n),i=o.get(r);return i===void 0&&(i="N".repeat(r),o.set(r,i)),i},t=new Map,a=n=>{let r=t.get(n);return r===void 0&&(r=L(n),t.set(n,r)),r};return(n,r)=>j({query:a(n),target:a(r),sequenceOf:e,bases:!1})}var I=100;function E(s,o,e){let t=s.at(-1);e>0&&(t?.[0]===o?t[1]+=e:s.push([o,e]))}function re(s){let o=t=>P(s,t>>1),e=t=>{let a=new Float64Array(t.length+1);return t.forEach((n,r)=>{a[r+1]=a[r]+o(n)}),a};return(t,a)=>{let n=L(a),r=L(t),[i,l]=v(r,n,o),[u,c]=v(r.map(h=>h^1).reverse(),n,o),p=c>l,f=p?u:i,W=Math.max(l,c);if(W<I)return[];let d=e(n),b=e(r),y=h=>p?r.length-1-f[h][0]:f[h][0],k=[];f.forEach(([,h],N)=>{if(N>0){let[m,g]=[y(N-1),y(N)].sort((O,pe)=>O-pe);E(k,"I",b[g]-b[m+1]),E(k,"D",d[h]-d[f[N-1][1]+1])}E(k,"=",o(n[h]))});let[M,x]=[y(0),y(f.length-1)].sort((h,N)=>h-N);return[{queryStart:b[M],queryEnd:b[x+1],targetStart:d[f[0][1]],targetEnd:d[f.at(-1)[1]+1],strand:p?"-":"+",edits:k,sharedBases:W}]}}function de(s){let o=new Map,e=new Set;s.ids.forEach((t,a)=>{o.has(t)?e.add(t):o.set(t,s.rev[a])});for(let t of e)o.delete(t);return o}function se(s){let o=new Map,e=t=>{let a=o.get(t);return a===void 0&&(a=de(t),o.set(t,a)),a};return(t,a)=>{let n=e(a),r=0,i=0;for(let[l,u]of e(t)){let c=n.get(l);c===u?r+=P(s,l):c!==void 0&&(i+=P(s,l))}return{same:r,opposite:i}}}function oe(s){let o=re(s),e=ne(s),t=se(s);return(a,n)=>{let{same:r,opposite:i}=t(a,n);return r>=I&&i>=I?e(a,n):o(a,n)}}var he=1e4;function ie(s){let o=re(s),e=ne(s),t=se(s);return(a,n)=>{let r=o(a,n),i=r[0]?.strand,{same:l,opposite:u}=t(a,n);return i===void 0||Math.min(l,u)<he?r:[...r,...e(a,n).filter(c=>c.strand!==i)]}}function R({chain:s,target:o,query:e,assemblyName:t,refName:a,mateAssemblyName:n}){let r=fe(s.edits);return Y({target:{name:o.name,assemblyName:t,refName:a,start:o.hapStart+s.targetStart,end:o.hapStart+s.targetEnd},query:{name:e.name,assemblyName:n,refName:F(e.name),start:e.hapStart+s.queryStart,end:e.hapStart+s.queryEnd},strand:s.strand,cigar:H(r),matches:r.reduce((i,[l,u])=>i+(l==="="?u:0),0),columns:r.reduce((i,[,l])=>i+l,0)})}function me(s,o,e,t){return Array.from(s.ids).some(a=>{let n=o.get(a);return n?.rank===0&&n.refName===e&&n.start<t.end&&n.end>t.start})}function le({leavePos:s,rejoinPos:o},e){return Math.min(s,o)<=e.start&&Math.max(s,o)>=e.end}function ce({departure:s,refName:o,assemblyName:e,mateAssemblyName:t}){let{name:a,hapStart:n,ownBp:r,leavePos:i,rejoinPos:l,rejoinReversed:u}=s,c=`${a}:${n}:${i}:departure`;return new K({uniqueId:c,assemblyName:e,refName:o,start:Math.min(i,l),end:Math.max(i,l),type:"departure",strand:u?-1:1,syntenyId:c,spansWindow:!0,mate:{refName:F(a),start:n,end:n+r,assemblyName:t}})}var _=({name:s})=>q(s)??s,D=class extends V{constructor(){super(...arguments);this.walks=new ae(z(this),this);this.refNames=new G(this.walks.source,this)}get anchor(){let e=this.getConf("assemblyNames")[0];if(e===void 0)throw new Error("WalkTabixSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");return e}async getHaplotypeNames(e={}){return this.walks.haplotypeNames(e)}async getHeader(e={}){let[{haplotypes:t},a]=await Promise.all([this.walks.reader.header(e),this.sheetColors(e)]),{anchor:n}=this,r=w(this,n),i=A(this),l=c=>c===r||C(c)===r,u=a?.(t.find(l)??r);return{hasCoarseTier:!1,anchorAssemblyName:n,...u===void 0?{}:{anchorColor:u},lanes:t.filter(c=>!l(c)).map(c=>{let p=a?.(c);return{name:B(i,c),label:c,group:C(c),...p===void 0?{}:{color:p}}})}}async sheetColors(e){let t=this.getConf("samplesTsvLocation");return $(t)?ee({location:t,names:void 0,namesLabel:"the walk file",pluginManager:this.pluginManager,opts:e}).then(({sources:a})=>te(a,A(this)),()=>{}):void 0}async getRefNames(e={}){let{assemblyName:t}=e;return t===void 0||t===this.anchor?this.refNames.assemblyRefNames({...e,assemblyName:this.anchor}):[]}async getSubgraph(e,t={}){let a=await this.refNames.resolveForCut(e,{signal:t.signal});return this.walks.subgraph(a,e,t)}async laneWalks(e,t,a,n,r){let i=X(a,e);return T(r,n.statusCallback,()=>this.walks.reader.cut(e,t,{...this.walks.cutOptions(),signal:n.signal,keep:i,expand:i,links:"none"}).catch(l=>{throw Q(l,t.end-t.start)}))}async anchorFeatures(e,t,a){let n=a.haplotypes?.length?a.haplotypes.map(m=>w(this,m)):void 0,r=w(this,a.targetAssemblyName),i=r===void 0?n:n===void 0||n.some(m=>S(r,m)||S(m,r))?[r]:[];if(i?.length===0)return[];let{start:l,end:u}=t,c=`Reading walks ${t.refName}:${l.toLocaleString()}-${u.toLocaleString()}`,{graph:p,fragments:f,departures:W}=await this.laneWalks(e,t,i,a,c),d=({name:m})=>i===void 0?0:i.findIndex(g=>S(m,g)),b=ie(p.nodes),y=A(this),k=m=>B(y,_(m)),M=f.filter(m=>m.name===e),x=f.filter(m=>m.name!==e&&d(m)>=0).map(m=>({rank:d(m),features:M.flatMap(g=>b(m,g).map(O=>R({chain:O,target:g,query:m,assemblyName:t.assemblyName,refName:t.refName,mateAssemblyName:k(m)})))})),h=new Set(f.filter(m=>me(m,p.nodes,e,t)).map(_)),N=W.filter(m=>d(m)>=0&&!h.has(_(m))&&le(m,t)).sort((m,g)=>m.name.localeCompare(g.name)).map(m=>({rank:d(m),features:[ce({departure:m,refName:t.refName,assemblyName:t.assemblyName,mateAssemblyName:k(m)})]}));return[...x,...N].sort((m,g)=>m.rank-g.rank).flatMap(m=>m.features)}async pairFeatures(e,t,a,n){let r=a.map(p=>({pair:p,featurePrefix:w(this,p.queryAssemblyName),matePrefix:w(this,p.targetAssemblyName)})),{graph:i,fragments:l}=await this.laneWalks(e,t,r.flatMap(p=>[p.featurePrefix,p.matePrefix]),n,J(a)),u=oe(i.nodes),c=p=>l.filter(f=>S(f.name,p));return r.flatMap(({pair:p,featurePrefix:f,matePrefix:W})=>c(f).flatMap(d=>c(W).flatMap(b=>u(b,d).map(y=>R({chain:y,target:d,query:b,assemblyName:p.queryAssemblyName,refName:F(d.name),mateAssemblyName:p.targetAssemblyName})))))}getFeatures(e,t={}){return U(async a=>{let n=e.assemblyName===this.anchor?await this.refNames.resolveMapped(e,t):void 0;if(n!==void 0){let r=Z(t),i=r.length>0?await this.pairFeatures(n,e,r,t):await this.anchorFeatures(n,e,t);for(let l of i)a.next(l)}a.complete()},t.signal)}};export{D as default};
2
+ //# sourceMappingURL=WalkTabixSyntenyAdapter-ZYWYXAC7.js.map