jbrowse-plugin-graphgenomeviewer 10.23.1 → 10.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunks/{AddTrackWorkflow-UA37WEMP.js → AddTrackWorkflow-4L335D42.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-YFAJJXFU.js → GbzBaseSyntenyAdapter-ITBQ2OVP.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-YFAJJXFU.js.map → GbzBaseSyntenyAdapter-ITBQ2OVP.js.map} +1 -1
- package/dist/chunks/{GfaTabixAdapter-I3LESQD7.js → GfaTabixAdapter-G3KQERSG.js} +2 -2
- package/dist/chunks/{GfaTabixAdapter-I3LESQD7.js.map → GfaTabixAdapter-G3KQERSG.js.map} +1 -1
- package/dist/chunks/{GfaWalksFormsAdapter-KTKTA2FU.js → GfaWalksFormsAdapter-6IHA5V7I.js} +2 -2
- package/dist/chunks/{GfaWalksSyntenyAdapter-EX4UUNKJ.js → GfaWalksSyntenyAdapter-KMWZLUNT.js} +2 -2
- package/dist/chunks/{GraphGenomeView-7CXETNV2.js → GraphGenomeView-HJ6QSGV7.js} +2 -2
- package/dist/chunks/GraphSettingsDialog-EMAFUDUK.js +2 -0
- package/dist/chunks/HighlightColorDialog-EHGGEHGB.js +2 -0
- package/dist/chunks/{HighlightColorDialog-NMK77E2W.js.map → HighlightColorDialog-EHGGEHGB.js.map} +1 -1
- package/dist/chunks/LinearGraphDisplay-456PTWEO.js +2 -0
- package/dist/chunks/{MinigraphBubbleAdapter-XMYKMLGM.js → MinigraphBubbleAdapter-3T3AVWG7.js} +2 -2
- package/dist/chunks/chunk-2VKA7YEW.js +3 -0
- package/dist/chunks/chunk-2VKA7YEW.js.map +7 -0
- package/dist/chunks/{chunk-WVYW7MJI.js → chunk-3LEQAY3J.js} +1 -1
- package/dist/chunks/{chunk-WVYW7MJI.js.map → chunk-3LEQAY3J.js.map} +1 -1
- package/dist/chunks/{chunk-6277RLIJ.js → chunk-3W7WSULH.js} +2 -2
- package/dist/chunks/{chunk-6277RLIJ.js.map → chunk-3W7WSULH.js.map} +1 -1
- package/dist/chunks/{chunk-SDWF4YYT.js → chunk-5DVV2ZHH.js} +2 -2
- package/dist/chunks/{chunk-QBCXKMHG.js → chunk-5URP77TX.js} +2 -2
- package/dist/chunks/{chunk-QBCXKMHG.js.map → chunk-5URP77TX.js.map} +1 -1
- package/dist/chunks/{chunk-DSB72RII.js → chunk-7N53GARW.js} +2 -2
- package/dist/chunks/chunk-AGJAVVWD.js +2 -0
- package/dist/chunks/chunk-AGJAVVWD.js.map +7 -0
- package/dist/chunks/{chunk-Y22J5P7Q.js → chunk-CJJMPOSW.js} +2 -2
- package/dist/chunks/{chunk-E42VJJ6O.js → chunk-FN5OANFE.js} +2 -2
- package/dist/chunks/{chunk-E42VJJ6O.js.map → chunk-FN5OANFE.js.map} +1 -1
- package/dist/chunks/chunk-GNVL442Z.js +5 -0
- package/dist/chunks/chunk-GNVL442Z.js.map +7 -0
- package/dist/chunks/{chunk-3HPP2PB4.js → chunk-IMCJTUCX.js} +1 -1
- package/dist/chunks/{chunk-3HPP2PB4.js.map → chunk-IMCJTUCX.js.map} +1 -1
- package/dist/chunks/chunk-JYU2J2B7.js +2 -0
- package/dist/chunks/chunk-JYU2J2B7.js.map +7 -0
- package/dist/chunks/{chunk-CG7YC4GW.js → chunk-P4XSCP6W.js} +2 -2
- package/dist/chunks/{chunk-HQI4FV6X.js → chunk-RCXMPQKP.js} +2 -2
- package/dist/chunks/{chunk-HQI4FV6X.js.map → chunk-RCXMPQKP.js.map} +1 -1
- package/dist/chunks/{chunk-UJGD5DRM.js → chunk-SCON5NQT.js} +2 -2
- package/dist/chunks/{chunk-R7RKUQNY.js → chunk-SG6G5XK3.js} +2 -2
- package/dist/chunks/chunk-UXUARTLL.js +4 -0
- package/dist/chunks/chunk-UXUARTLL.js.map +7 -0
- package/dist/chunks/{chunk-XTPIB2L7.js → chunk-WZOAYGF5.js} +2 -2
- package/dist/chunks/{chunk-XTPIB2L7.js.map → chunk-WZOAYGF5.js.map} +1 -1
- package/dist/chunks/{chunk-NVER5Z5N.js → chunk-YEY23TBB.js} +2 -2
- package/dist/chunks/{chunk-NVER5Z5N.js.map → chunk-YEY23TBB.js.map} +1 -1
- package/dist/chunks/{chunk-LMWU7WIM.js → chunk-YGIWBVPD.js} +2 -2
- package/dist/chunks/{chunk-LMWU7WIM.js.map → chunk-YGIWBVPD.js.map} +1 -1
- package/dist/chunks/chunk-YIL4545N.js +9 -0
- package/dist/chunks/chunk-YIL4545N.js.map +7 -0
- package/dist/chunks/renderSvg-LCEIAI6F.js +2 -0
- package/dist/chunks/renderSvg-LCEIAI6F.js.map +7 -0
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +3 -3
- package/package.json +5 -2
- package/src/GraphGenomeView/components/GraphCanvas.tsx +28 -3
- package/src/GraphGenomeView/components/HoverLayer.tsx +5 -1
- package/src/GraphGenomeView/components/LegendSwatch.tsx +22 -0
- package/src/GraphGenomeView/components/PaneLayer.tsx +1 -0
- package/src/GraphGenomeView/components/PaneSvg.tsx +18 -3
- package/src/GraphGenomeView/frame.ts +37 -0
- package/src/GraphGenomeView/legendSections.ts +13 -1
- package/src/GraphGenomeView/model.ts +11 -6
- package/src/GraphGenomeView/pane/fitViews.ts +195 -17
- package/src/GraphGenomeView/pane/graphViews.ts +6 -0
- package/src/GraphGenomeView/pane/launchActions.ts +5 -0
- package/src/GraphGenomeView/pane/paneBase.ts +1 -0
- package/src/GraphGenomeView/pane/settingActions.ts +4 -0
- package/src/GraphGenomeView/pane/viewFrame.test.ts +261 -0
- package/src/GraphGenomeView/pane/viewFrame.ts +329 -0
- package/src/GraphGenomeView/viewModel.ts +4 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.config.test.ts +697 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.cut.test.ts +235 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.fold.test.ts +115 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.kept.test.ts +639 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.key.test.ts +404 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.menu.test.ts +512 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.modes.test.ts +239 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.pan.test.ts +151 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.restore.test.ts +219 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.sizing.test.ts +208 -0
- package/src/LinearGraphDisplay/LinearGraphDisplay.zoom.test.ts +159 -0
- package/src/LinearGraphDisplay/configSchema.ts +31 -1
- package/src/LinearGraphDisplay/displayTestSupport.ts +1094 -0
- package/src/LinearGraphDisplay/model.ts +19 -8
- package/src/lineEnds.ts +15 -0
- package/src/version.ts +1 -1
- package/dist/chunks/GraphSettingsDialog-KOWGWFCE.js +0 -2
- package/dist/chunks/HighlightColorDialog-NMK77E2W.js +0 -2
- package/dist/chunks/LinearGraphDisplay-GPNK7CH2.js +0 -2
- package/dist/chunks/chunk-DSOMVUSV.js +0 -3
- package/dist/chunks/chunk-DSOMVUSV.js.map +0 -7
- package/dist/chunks/chunk-JYFYZFOL.js +0 -2
- package/dist/chunks/chunk-JYFYZFOL.js.map +0 -7
- package/dist/chunks/chunk-WB4I42OY.js +0 -4
- package/dist/chunks/chunk-WB4I42OY.js.map +0 -7
- package/dist/chunks/chunk-YMEWYPGD.js +0 -5
- package/dist/chunks/chunk-YMEWYPGD.js.map +0 -7
- package/dist/chunks/chunk-ZFW4M5SM.js +0 -2
- package/dist/chunks/chunk-ZFW4M5SM.js.map +0 -7
- package/dist/chunks/chunk-ZRUIPLSC.js +0 -9
- package/dist/chunks/chunk-ZRUIPLSC.js.map +0 -7
- package/dist/chunks/renderSvg-T2NKTBSC.js +0 -2
- package/dist/chunks/renderSvg-T2NKTBSC.js.map +0 -7
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +0 -4242
- /package/dist/chunks/{AddTrackWorkflow-UA37WEMP.js.map → AddTrackWorkflow-4L335D42.js.map} +0 -0
- /package/dist/chunks/{GfaWalksFormsAdapter-KTKTA2FU.js.map → GfaWalksFormsAdapter-6IHA5V7I.js.map} +0 -0
- /package/dist/chunks/{GfaWalksSyntenyAdapter-EX4UUNKJ.js.map → GfaWalksSyntenyAdapter-KMWZLUNT.js.map} +0 -0
- /package/dist/chunks/{GraphGenomeView-7CXETNV2.js.map → GraphGenomeView-HJ6QSGV7.js.map} +0 -0
- /package/dist/chunks/{GraphSettingsDialog-KOWGWFCE.js.map → GraphSettingsDialog-EMAFUDUK.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-GPNK7CH2.js.map → LinearGraphDisplay-456PTWEO.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-XMYKMLGM.js.map → MinigraphBubbleAdapter-3T3AVWG7.js.map} +0 -0
- /package/dist/chunks/{chunk-SDWF4YYT.js.map → chunk-5DVV2ZHH.js.map} +0 -0
- /package/dist/chunks/{chunk-DSB72RII.js.map → chunk-7N53GARW.js.map} +0 -0
- /package/dist/chunks/{chunk-Y22J5P7Q.js.map → chunk-CJJMPOSW.js.map} +0 -0
- /package/dist/chunks/{chunk-CG7YC4GW.js.map → chunk-P4XSCP6W.js.map} +0 -0
- /package/dist/chunks/{chunk-UJGD5DRM.js.map → chunk-SCON5NQT.js.map} +0 -0
- /package/dist/chunks/{chunk-R7RKUQNY.js.map → chunk-SG6G5XK3.js.map} +0 -0
package/README.md
CHANGED
|
@@ -109,8 +109,8 @@ In reading order:
|
|
|
109
109
|
|
|
110
110
|
- [BandageJS](https://github.com/cmdcolin/BandageJS): standalone page with the
|
|
111
111
|
same layouts
|
|
112
|
-
- [
|
|
113
|
-
|
|
112
|
+
- [haplotubemap](https://github.com/cmdcolin/haplotubemap): our fork of the tube
|
|
113
|
+
map app
|
|
114
114
|
|
|
115
115
|
Supporting utility libraries
|
|
116
116
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as U,c as V,d as X,e as q,f as K,h as Q}from"./chunk-MQS4CLYS.js";import{e as D}from"./chunk-ZCNHZLT2.js";import{c as x,d as P}from"./chunk-HNTK5LBJ.js";import{j as r}from"./chunk-PCP5Y77D.js";import{B as j,C as z,D as J,G as h,a as E,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 G,d as W}from"./chunk-DUU6T2I5.js";import"./chunk-TMM73K4C.js";import{g as H}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=AddTrackWorkflow-
|
|
1
|
+
import{a as U,c as V,d as X,e as q,f as K,h as Q}from"./chunk-MQS4CLYS.js";import{e as D}from"./chunk-ZCNHZLT2.js";import{c as x,d as P}from"./chunk-HNTK5LBJ.js";import{j as r}from"./chunk-PCP5Y77D.js";import{B as j,C as z,D as J,G as h,a as E,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 G,d as W}from"./chunk-DUU6T2I5.js";import"./chunk-TMM73K4C.js";import{g as H}from"./chunk-CJJMPOSW.js";import"./chunk-D6TY2QEG.js";import"./chunk-2MOWWQHO.js";import"./chunk-EGZZ3ADM.js";import"./chunk-IMCJTUCX.js";import{b as A,h as R,j as v,n as M}from"./chunk-5L276I7O.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 H(o,a,s).getHeader({signal:AbortSignal.timeout(U)});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=["GfaTabixAdapter","GfaWalksSyntenyAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],me=W(function({model:a}){let{classes:s}=pe(),p=v(a),u=x(a),[n,$]=r("GfaTabixAdapter"),[l,ee]=r(),[f,F]=r(),[S,te]=r(),g=n==="GbzBaseSyntenyAdapter",c=n==="GfaWalksSyntenyAdapter",[b,ae]=r(""),[T,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}=R(a),[ne,ie]=await Promise.all([n==="GfaTabixAdapter"?V(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();A({model:a,session:p,conf:Q({choice:n,loc:l,indexLoc:f,readsLoc:g?S:void 0,manifest:ne,assembly:a.assembly,sample:b,haplotypes:c?D(T):void 0,walkReference:ie,trackId:M({name:m}),name:m})})}catch(m){k(m)}}return G(j,{className:s.paper,children:[C?t(I,{error:C}):null,G(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:X[e]},e))})]}),t(d,{location:l,name:q[n],rootModel:u,setLocation:ee}),t(d,{location:f,name:K[n],rootModel:u,setLocation:F}),g?t(d,{location:S,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:T,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(E,{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"})]})}),Re=me;export{Re as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-4L335D42.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as In,j as vn,k as Lt,l as Mt}from"./chunk-QBCXKMHG.js";import{a as fe,b as R,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 Ln,u as Cn,v as On}from"./chunk-SDWF4YYT.js";import"./chunk-JM4W4PKP.js";import{a as xs,b as Mn,c as Hn,d as Ht}from"./chunk-CG7YC4GW.js";import"./chunk-IASBT3FL.js";import{a as An}from"./chunk-UJGD5DRM.js";import"./chunk-YBLNN5FU.js";import{j as kn}from"./chunk-6277RLIJ.js";import{_ as En,c as Sn}from"./chunk-LMWU7WIM.js";import{a as Pn}from"./chunk-V55TK2NP.js";import"./chunk-TMM73K4C.js";import{b as _e,e as $n}from"./chunk-Y22J5P7Q.js";import{a as Re}from"./chunk-D6TY2QEG.js";import{j as Nn}from"./chunk-2MOWWQHO.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as $t,g as Ae,h as $e,i as Rt}from"./chunk-3HPP2PB4.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}}},Bn=255,Ss=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<Bn?Math.floor(Ss/this.sigma):0}next(){if(this.sigma>=Bn){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 Fn(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(r.node)===R(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 Is=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 Tn(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+Is[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),$=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+$|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 _n(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 Dn(a){return{name:a.get("pggname"),subgraph:_n(a.get("subgraph"),"subgraph"),translation:_n(a.get("translation"),"translation")}}function zn(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 Gn(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])),zn(t.subgraph,e.subgraph),zn(t.translation,e.translation)),t}function qn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function jn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of qn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of qn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function Un(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)):Tn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Es="_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 ks=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,vs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ps(a){let e=ks.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=vs.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"?Ps(a):a}function Me(a,e){return{sample:a.sample??Es,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ns=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ns?n[1]=t:e.push([t,t])}return e}var As=32768,Wn={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 Qn(a,e,t,n){return a==="forward"?e-n:e+t}function Vn(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 Zn(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:Qn(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)},$=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):Qn(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>As?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=R(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=R(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(R(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 ${R(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),ws=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(ws[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>Wn.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Wn.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 ms=new Set(B.map(g=>`${g.low}:${g.high}`)),ys=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ms.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 $({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},bs=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 $({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 bs(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 ys){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 $({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)&&Vn(C):!C.canonical||Vn(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 $(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 Kn(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 $s(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 Ls(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 Ms(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Yn(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 Hs(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?Ls(c,f):void 0;if(p){c=Ms(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 Cs=32768;function Os(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]<=Cs?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(R(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=R(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(Os(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=R(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(R(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=R(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([R(e),R(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=R(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=R(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=R(n),c=R(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=R(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]),$=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push($),i[y+1]=i[y]+$.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,$)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),$&&($.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,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:$,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 $=i[y],F=i[y+1]-$;for(let T=0;T<F;T++)if(w[$+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 $=i[y],F=i[y+1]-$,T=0;for(let O=0;O<F;O++)w[$+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[$+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 $=n.seqOffset-E;this.refInterval=[$,$+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+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(R(i));for(let o of[...this.records.keys()])r.has(R(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 Zn({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(Kn);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,$;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);$=this.record(G.node).gbwt().lf(G.offset),E=void 0}if($===void 0||$.node===0){I.end="endmarker";break}let F=ve($),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($.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h($,I),O=await d($.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,$=O.gbwt().lf($.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),Yn(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??$s(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=Fs(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:$}=this.editsAgainst(E,t),F=Xn($,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(Ts($,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],Xn(p,[h.len])))}),Hs(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:_s(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(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=R(n),r=`S ${s} ${this.record(n).sequence}
|
|
1
|
+
import{a as In,j as vn,k as Lt,l as Mt}from"./chunk-5URP77TX.js";import{a as fe,b as R,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 Ln,u as Cn,v as On}from"./chunk-5DVV2ZHH.js";import"./chunk-JM4W4PKP.js";import{a as xs,b as Mn,c as Hn,d as Ht}from"./chunk-P4XSCP6W.js";import"./chunk-IASBT3FL.js";import{a as An}from"./chunk-SCON5NQT.js";import"./chunk-YBLNN5FU.js";import{j as kn}from"./chunk-3W7WSULH.js";import{_ as En,c as Sn}from"./chunk-YGIWBVPD.js";import{a as Pn}from"./chunk-V55TK2NP.js";import"./chunk-TMM73K4C.js";import{b as _e,e as $n}from"./chunk-CJJMPOSW.js";import{a as Re}from"./chunk-D6TY2QEG.js";import{j as Nn}from"./chunk-2MOWWQHO.js";import{e as Ke,h as dn,i as fn,j as ln}from"./chunk-EGZZ3ADM.js";import{a as $t,g as Ae,h as $e,i as Rt}from"./chunk-IMCJTUCX.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}}},Bn=255,Ss=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<Bn?Math.floor(Ss/this.sigma):0}next(){if(this.sigma>=Bn){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 Fn(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(r.node)===R(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 Is=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 Tn(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+Is[S]+o[S]|0,E=we(h,2)^we(h,13)^we(h,22),$=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+$|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 _n(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 Dn(a){return{name:a.get("pggname"),subgraph:_n(a.get("subgraph"),"subgraph"),translation:_n(a.get("translation"),"translation")}}function zn(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 Gn(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])),zn(t.subgraph,e.subgraph),zn(t.translation,e.translation)),t}function qn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function jn(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of qn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of qn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function Un(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)):Tn(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Es="_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 ks=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,vs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ps(a){let e=ks.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=vs.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"?Ps(a):a}function Me(a,e){return{sample:a.sample??Es,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var Ns=4096;function Ot(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ns?n[1]=t:e.push([t,t])}return e}var As=32768,Wn={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 Qn(a,e,t,n){return a==="forward"?e-n:e+t}function Vn(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 Zn(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:Qn(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)},$=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):Qn(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>As?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=R(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=R(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(R(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 ${R(be.node)}); it does not match this graph`);let Yt=ue.filter(g=>de(g)<=a.window.start),ws=ue.filter(g=>de(g)>=a.window.end);o.anchors=[de(Yt[Yt.length-1]??ue[0]),de(ws[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>Wn.mostChosenPaths)throw new oe(`${o.chosenPaths} chosen paths pass the anchors, more than ${Wn.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 ms=new Set(B.map(g=>`${g.low}:${g.high}`)),ys=ie.filter(g=>w(g.pathHandle)&&(g.snarl===void 0||ms.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 $({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},bs=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 $({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 bs(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 ys){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 $({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)&&Vn(C):!C.canonical||Vn(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 $(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 Kn(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 $s(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 Ls(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 Ms(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],r=n.edits.map(([d,h])=>[d,h]);Yn(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 Hs(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?Ls(c,f):void 0;if(p){c=Ms(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 Cs=32768;function Os(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]<=Cs?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(R(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=R(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(Os(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=R(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(R(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=R(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([R(e),R(t)]),r=[];for(;n.length>0;){let o=n.pop(),i=R(o);this.hasNode(i)||(await this.addNode(i),r.push(i));for(let c of this.record(o).successors()){let d=R(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=R(n),c=R(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=R(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]),$=E.gbwt().decompressArrays();c[y]=E.sequenceLen,d.push($),i[y+1]=i[y]+$.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,$)=>{let F=[],T=0,D=0,O=-1,H=y,v=E;for(;;){H===u&&v===l&&(O=T),$&&($.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,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:y,offsets:E,len:$,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 $=i[y],F=i[y+1]-$;for(let T=0;T<F;T++)if(w[$+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 $=i[y],F=i[y+1]-$,T=0;for(let O=0;O<F;O++)w[$+O]===0&&(T+=1);let D=(u===void 0||b!==void 0)&&T===I[y];for(let O=0;O<F;O++)if(w[$+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 $=n.seqOffset-E;this.refInterval=[$,$+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+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(R(i));for(let o of[...this.records.keys()])r.has(R(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 Zn({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(Kn);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,$;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);$=this.record(G.node).gbwt().lf(G.offset),E=void 0}if($===void 0||$.node===0){I.end="endmarker";break}let F=ve($),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($.node)&&(I.reentries+=1),this.twinStarts.has(F)&&(I.twinLandings+=1);let D=await h($,I),O=await d($.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,$=O.gbwt().lf($.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),Yn(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??$s(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=Fs(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:$}=this.editsAgainst(E,t),F=Xn($,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(Ts($,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],Xn(p,[h.len])))}),Hs(d,i,c).map(h=>{let{edits:f,identity:p,pieces:w,soloAligned:u,...l}=h,b={...l,cigar:_s(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(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=R(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 Un(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",...jn(Gn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let d of s)V(d)||n.push(`S ${R(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 ${R(d)} ${r(d)} ${R(h)} ${r(h)} 0M`);let o=(d,h,f,p,w)=>{let u=rt(d,h).map(x=>`${V(x)?"<":">"}${R(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
|
`)}
|
|
@@ -8,4 +8,4 @@ import{a as In,j as vn,k as Lt,l as Mt}from"./chunk-QBCXKMHG.js";import{a as fe,
|
|
|
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($t(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 sr(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})}function rr(a){let e=kn(Number.NaN),t=a.indexOf(`
|
|
9
9
|
`),n=t===-1?a.length:t;return a===""?a:a.startsWith("H ")?`${a.slice(0,n)} ${e}${a.slice(n)}`:`H VN:Z:1.1 ${e}
|
|
10
10
|
${a}`}async function or(a,e){let t=await a.paths();return rr(hs(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 sr(a,e,t,n,s);if(r.length===1)return ds(r[0].toCompactSubgraph());let o=await or(a,r);return(o===""?void 0:vn(o))??o}function ar(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=R(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 ir=/^(.*)\[(\d+)-(\d+)\]$/;function ds(a){let e=Array.from(a.nodeIds,String),t=ar(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=ir.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 dr(a){return fn(a)&&It(dn(a))?ln(a,e=>It(e)):void 0}function fr(a){return a instanceof Error&&(/\bHTTP 40[34]\b/.test(a.message)||a.code==="ENOENT")}async function fs(a,e){let t=dr(a);if(!t)return{};try{return await Re(t,e).stat(),{location:t}}catch(n){return fr(n)?{}:{unreadable:String(n)}}}var lr=5e3,pr=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 ur(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 ls=(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>pr)throw new Vt(t);let n=await this.file.readFile({signal:e}),s=new TextDecoder().decode(n[0]===31&&n[1]===139?await Nn(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&&ls(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=>ls(s,e));return{records:ur(n,lr),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 gr(a,e){return`${ce(a)}#${a.contig}@${e.start.node}.${e.start.offset}`}function wr({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=gr(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 mr({pair:a,lane:e,mateLane:t}){return On({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 yr=12e4;function br(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<=yr&&(n=Math.max(n,o))}}return n}function gs(a,e){return a instanceof mt&&(a.message=`Zoom in to about ${hn(a.fitsBp)} to see ${e}`),a}var ps=(a,e,t)=>Cn(gs(St(a,e,t)??a,"lanes"),t),us=a=>({...a,start:Math.floor(a.start),end:Math.ceil(a.end)}),Kt=class extends Ln{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 fs(t,this.pluginManager),r=s.location,o=await Qe.open({source:Re(t,this.pluginManager),haplotypeIndex:r?Re(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:$e(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(Re(t,this.pluginManager),Ke(n)?$n(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=Rt(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:$e(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=>$e(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}=us(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 gs(b,"the graph")});return typeof l=="string"?l:An(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=$e(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=$e(this,n.targetAssemblyName),h=Rt(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 ps(l,w,c-i)})):[]).flatMap(l=>{let b=l.resolved?wr({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 ps(E,w,c-i)}),N=br(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(Hn(n),s.statusCallback,()=>b(p)):[]).flatMap(S=>h.flatMap(({pair:I,featureSide:N,mateSide:y})=>N.flatMap(E=>y.flatMap($=>S.pairAlignments({target:E,query:$,bases:!1}).map(F=>mr({pair:F,lane:I.queryAssemblyName,mateLane:I.targetAssemblyName}))))))}getFeatures(t,n={}){let s=us(t);return Pn(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=Mn(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,xs as PairTargetError,Kt as default,br as widestWalkGap};
|
|
11
|
-
//# sourceMappingURL=GbzBaseSyntenyAdapter-
|
|
11
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-ITBQ2OVP.js.map
|