jbrowse-plugin-graphgenomeviewer 6.1.0 → 6.1.2
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/dist/chunks/{AddTrackWorkflow-U3UNCVXJ.js → AddTrackWorkflow-F5YBOJ3E.js} +2 -2
- package/dist/chunks/ChooseSamplesDialog-KVTDIA4A.js +2 -0
- package/dist/chunks/ChooseSamplesDialog-KVTDIA4A.js.map +7 -0
- package/dist/chunks/{GbzBaseSyntenyAdapter-2BKLBC4F.js → GbzBaseSyntenyAdapter-Z4NDQGEZ.js} +2 -2
- package/dist/chunks/{GbzBaseSyntenyAdapter-2BKLBC4F.js.map → GbzBaseSyntenyAdapter-Z4NDQGEZ.js.map} +1 -1
- package/dist/chunks/{GraphGenomeView-QC2QC4KU.js → GraphGenomeView-KS7FVZJ5.js} +2 -2
- package/dist/chunks/{GraphTrackSettingsDialog-PPKPBVLS.js → GraphTrackSettingsDialog-PTKKSSBE.js} +2 -2
- package/dist/chunks/{LinearGraphDisplay-OSAPH6XH.js → LinearGraphDisplay-LWHPENRV.js} +2 -2
- package/dist/chunks/{MinigraphBubbleAdapter-3UAIVFCB.js → MinigraphBubbleAdapter-HGW2CBIT.js} +2 -2
- package/dist/chunks/{RgfaTabixAdapter-THL7HZG6.js → RgfaTabixAdapter-H3N36A4S.js} +2 -2
- package/dist/chunks/{bandage-layout-3AR6BCUD-77FHETNY.js → bandage-layout-3AR6BCUD-HF5PAMCE.js} +1 -1
- package/dist/chunks/{bandage-layout-3AR6BCUD-77FHETNY.js.map → bandage-layout-3AR6BCUD-HF5PAMCE.js.map} +1 -1
- package/dist/chunks/{chunk-S2YZT446.js → chunk-6UUUO22M.js} +1 -1
- package/dist/chunks/{chunk-S2YZT446.js.map → chunk-6UUUO22M.js.map} +1 -1
- package/dist/chunks/chunk-7PF6DB6Y.js +2 -0
- package/dist/chunks/chunk-7PF6DB6Y.js.map +7 -0
- package/dist/chunks/{chunk-DKNKJWYF.js → chunk-B2UJRFGO.js} +2 -2
- package/dist/chunks/chunk-EAFQ3OQR.js +2 -0
- package/dist/chunks/chunk-EAFQ3OQR.js.map +7 -0
- package/dist/chunks/{chunk-OPJLYB4S.js → chunk-EYWDKUI6.js} +1 -1
- package/dist/chunks/{chunk-OPJLYB4S.js.map → chunk-EYWDKUI6.js.map} +1 -1
- package/dist/chunks/{chunk-LRBVMAUV.js → chunk-QU4UAKXZ.js} +1 -1
- package/dist/chunks/{chunk-LRBVMAUV.js.map → chunk-QU4UAKXZ.js.map} +1 -1
- package/dist/chunks/chunk-U3XWI3ON.js +3 -0
- package/dist/chunks/chunk-U3XWI3ON.js.map +7 -0
- package/dist/chunks/chunk-WA4J2BQ5.js +2 -0
- package/dist/chunks/{chunk-BD6T6PQA.js.map → chunk-WA4J2BQ5.js.map} +1 -1
- package/dist/chunks/{chunk-IKKD4EOI.js → chunk-WV6GUYH7.js} +2 -2
- package/dist/chunks/{chunk-IKKD4EOI.js.map → chunk-WV6GUYH7.js.map} +1 -1
- package/dist/chunks/{chunk-CNQYRKZ3.js → chunk-YPZ64NPV.js} +1 -1
- package/dist/chunks/{chunk-CNQYRKZ3.js.map → chunk-YPZ64NPV.js.map} +1 -1
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +7 -5
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +4 -4
- package/src/GraphGenomeView/components/ChooseSamplesDialog.tsx +83 -0
- package/src/GraphGenomeView/components/GraphCanvas.tsx +7 -0
- package/src/GraphGenomeView/components/WalkRowContextMenu.tsx +30 -1
- package/src/GraphGenomeView/components/WalkRowsOverlay.tsx +30 -6
- package/src/GraphGenomeView/components/usePaneGestures.ts +8 -0
- package/src/GraphGenomeView/genes/geneFeatures.ts +6 -4
- package/src/GraphGenomeView/genes/genes.test.ts +38 -0
- package/src/GraphGenomeView/model.test.ts +100 -5
- package/src/GraphGenomeView/pane/fitViews.ts +122 -10
- package/src/GraphGenomeView/pane/graphViews.ts +43 -58
- package/src/GraphGenomeView/pane/launchActions.ts +44 -0
- package/src/GraphGenomeView/pane/loadActions.ts +6 -1
- package/src/GraphGenomeView/pane/paneBase.ts +5 -0
- package/src/GraphGenomeView/pane/settingActions.ts +4 -0
- package/src/GraphGenomeView/pane/walkRowViews.ts +0 -22
- package/src/LinearGraphDisplay/LinearGraphDisplay.test.ts +30 -0
- package/src/LinearGraphDisplay/model.ts +59 -7
- package/src/MinigraphBubbleAdapter/configSchema.ts +1 -1
- package/src/RgfaTabixAdapter/bubbleTier.test.ts +1 -1
- package/src/version.ts +1 -1
- package/dist/chunks/chunk-BD6T6PQA.js +0 -2
- package/dist/chunks/chunk-FSGQSCPI.js +0 -2
- package/dist/chunks/chunk-FSGQSCPI.js.map +0 -7
- package/dist/chunks/chunk-JE3RBATE.js +0 -2
- package/dist/chunks/chunk-JE3RBATE.js.map +0 -7
- package/dist/chunks/chunk-XNL7PBQZ.js +0 -3
- package/dist/chunks/chunk-XNL7PBQZ.js.map +0 -7
- /package/dist/chunks/{AddTrackWorkflow-U3UNCVXJ.js.map → AddTrackWorkflow-F5YBOJ3E.js.map} +0 -0
- /package/dist/chunks/{GraphGenomeView-QC2QC4KU.js.map → GraphGenomeView-KS7FVZJ5.js.map} +0 -0
- /package/dist/chunks/{GraphTrackSettingsDialog-PPKPBVLS.js.map → GraphTrackSettingsDialog-PTKKSSBE.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-OSAPH6XH.js.map → LinearGraphDisplay-LWHPENRV.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-3UAIVFCB.js.map → MinigraphBubbleAdapter-HGW2CBIT.js.map} +0 -0
- /package/dist/chunks/{RgfaTabixAdapter-THL7HZG6.js.map → RgfaTabixAdapter-H3N36A4S.js.map} +0 -0
- /package/dist/chunks/{chunk-DKNKJWYF.js.map → chunk-B2UJRFGO.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as F,c as T,i as y}from"./chunk-4T7DPQTR.js";import{a as N}from"./chunk-J4OLMLS5.js";import{a as
|
|
2
|
-
//# sourceMappingURL=AddTrackWorkflow-
|
|
1
|
+
import{a as W}from"./chunk-FCWXYIFC.js";import{b as F,c as T,i as y}from"./chunk-4T7DPQTR.js";import{a as N}from"./chunk-J4OLMLS5.js";import{a as O}from"./chunk-J6KYLXRD.js";import{a as C,b as B,c as H,d as _}from"./chunk-TYJTJGPO.js";import{a as w,b as t}from"./chunk-FY3BTKY4.js";var S=w((q,L)=>{L.exports=JBrowseExports["@jbrowse/core/util/tss-react"]});var s=t(O(),1),i=t(B(),1),l=t(N(),1),A=t(S(),1),R=t(W(),1),e=t(_(),1),x=t(H(),1);var o=t(C(),1),j=(0,A.makeStyles)()(n=>({paper:{margin:n.spacing(),padding:n.spacing()},field:{marginTop:n.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),D=["RgfaTabixAdapter","MinigraphBubbleAdapter"],J=(0,x.observer)(function({model:r}){let{classes:c}=j(),h=(0,l.getSession)(r),b=(0,R.getRoot)(r),[m,G]=(0,s.useState)("RgfaTabixAdapter"),[p,v]=(0,s.useState)(),[g,P]=(0,s.useState)(),[u,I]=(0,s.useState)(""),[d,M]=(0,s.useState)("Pangenome graph"),[f,k]=(0,s.useState)();function E(){if(!(!p||!r.assembly))try{k(void 0);let a=d.trim();(0,l.addTrackFromWidget)({model:r,session:h,conf:y({choice:m,loc:p,indexLoc:g,assembly:r.assembly,sample:u,trackId:(0,l.makeTrackId)({name:a}),name:a})})}catch(a){k(a)}}return(0,o.jsxs)(e.Paper,{className:c.paper,children:[f?(0,o.jsx)(i.ErrorMessage,{error:f}):null,(0,o.jsxs)(e.FormControl,{children:[(0,o.jsx)(e.FormLabel,{children:"File type"}),(0,o.jsx)(e.RadioGroup,{value:m,onChange:a=>{G(a.target.value)},children:D.map(a=>(0,o.jsx)(e.FormControlLabel,{value:a,control:(0,o.jsx)(e.Radio,{}),label:F[a]},a))})]}),(0,o.jsx)(i.FileSelector,{location:p,name:T[m],rootModel:b,setLocation:v}),(0,o.jsx)(i.FileSelector,{location:g,name:"Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)",rootModel:b,setLocation:P}),(0,o.jsx)(e.TextField,{className:c.field,value:u,onChange:a=>{I(a.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:"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}),(0,o.jsx)(e.TextField,{className:c.field,value:d,helperText:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:a=>{M(a.target.value)}}),(0,o.jsx)(i.AssemblySelector,{session:h,helperText:"Select assembly to add track to",selected:r.assembly,onChange:a=>{r.setAssembly(a)},fullWidth:!0}),(0,o.jsx)(e.Button,{variant:"contained",className:c.submit,disabled:!p||!d.trim()||!r.assembly,onClick:E,children:"Submit"})]})}),K=J;export{K as default};
|
|
2
|
+
//# sourceMappingURL=AddTrackWorkflow-F5YBOJ3E.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as C}from"./chunk-J6KYLXRD.js";import{a as r,b as S,c as u,d as w}from"./chunk-TYJTJGPO.js";import{b as a}from"./chunk-FY3BTKY4.js";var c=a(C(),1),m=a(S(),1),e=a(w(),1),h=a(u(),1),o=a(r(),1),y=(0,h.observer)(function({model:t,onClose:i}){let{samples:s}=t.walkRowSampleChoices,[p,d]=(0,c.useState)(()=>(t.walkRowSamples??[]).filter(l=>s.includes(l)));return(0,o.jsxs)(m.Dialog,{open:!0,onClose:i,title:"Choose samples",children:[(0,o.jsxs)(e.DialogContent,{children:[(0,o.jsx)(e.Autocomplete,{multiple:!0,disableCloseOnSelect:!0,"data-testid":"graph-choose-samples",options:s,value:p,onChange:(l,n)=>{d(n)},renderOption:({key:l,...n},k,{selected:g})=>(0,o.jsxs)("li",{...n,children:[(0,o.jsx)(e.Checkbox,{size:"small",checked:g}),k]},l),renderInput:l=>(0,o.jsx)(e.TextField,{...l,autoFocus:!0,label:"Samples",placeholder:"type to search"})}),(0,o.jsxs)(e.Typography,{variant:"caption",color:"text.secondary",children:[s.length.toLocaleString()," samples in this cut. Their walks show in pairs, in the order picked."]})]}),(0,o.jsxs)(e.DialogActions,{children:[(0,o.jsx)(e.Button,{onClick:i,children:"Cancel"}),(0,o.jsx)(e.Button,{variant:"contained",disabled:p.length===0,onClick:()=>{t.setWalkRowSamples(p),i()},children:"Show these samples"})]})]})}),D=y;export{D as default};
|
|
2
|
+
//# sourceMappingURL=ChooseSamplesDialog-KVTDIA4A.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/GraphGenomeView/components/ChooseSamplesDialog.tsx"],
|
|
4
|
+
"sourcesContent": ["import { useState } from 'react'\n\nimport { Dialog } from '@jbrowse/core/ui'\nimport {\n Autocomplete,\n Button,\n Checkbox,\n DialogActions,\n DialogContent,\n TextField,\n Typography,\n} from '@mui/material'\nimport { observer } from 'mobx-react'\n\nimport type { GraphPaneModel } from '../model'\n\ntype SamplePicker = Pick<\n GraphPaneModel,\n 'walkRowSampleChoices' | 'walkRowSamples' | 'setWalkRowSamples'\n>\n\n// Which samples' walks walk rows show, searched by name, in the order picked\nconst ChooseSamplesDialog = observer(function ChooseSamplesDialog({\n model,\n onClose,\n}: {\n model: SamplePicker\n onClose: () => void\n}) {\n const { samples } = model.walkRowSampleChoices\n const [picked, setPicked] = useState(() =>\n (model.walkRowSamples ?? []).filter(s => samples.includes(s)),\n )\n return (\n <Dialog open onClose={onClose} title=\"Choose samples\">\n <DialogContent>\n <Autocomplete\n multiple\n disableCloseOnSelect\n data-testid=\"graph-choose-samples\"\n options={samples}\n value={picked}\n onChange={(_, value) => {\n setPicked(value)\n }}\n renderOption={({ key, ...props }, sample, { selected }) => (\n <li key={key} {...props}>\n <Checkbox size=\"small\" checked={selected} />\n {sample}\n </li>\n )}\n renderInput={params => (\n <TextField\n {...params}\n autoFocus\n label=\"Samples\"\n placeholder=\"type to search\"\n />\n )}\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {samples.length.toLocaleString()} samples in this cut. Their walks\n show in pairs, in the order picked.\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>Cancel</Button>\n <Button\n variant=\"contained\"\n disabled={picked.length === 0}\n onClick={() => {\n model.setWalkRowSamples(picked)\n onClose()\n }}\n >\n Show these samples\n </Button>\n </DialogActions>\n </Dialog>\n )\n})\n\nexport default ChooseSamplesDialog\n"],
|
|
5
|
+
"mappings": "6IAAA,IAAAA,EAAyB,SAEzBC,EAAuB,SACvBC,EAQO,SACPC,EAAyB,SAkCbC,EAAA,SAxBNC,KAAsB,YAAS,SAA6B,CAChE,MAAAC,EACA,QAAAC,CACF,EAGG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIF,EAAM,qBACpB,CAACG,EAAQC,CAAS,KAAI,YAAS,KAClCJ,EAAM,gBAAkB,CAAC,GAAG,OAAOK,GAAKH,EAAQ,SAASG,CAAC,CAAC,CAC9D,EACA,SACE,QAAC,UAAO,KAAI,GAAC,QAASJ,EAAS,MAAM,iBACnC,qBAAC,iBACC,oBAAC,gBACC,SAAQ,GACR,qBAAoB,GACpB,cAAY,uBACZ,QAASC,EACT,MAAOC,EACP,SAAU,CAACG,EAAGC,IAAU,CACtBH,EAAUG,CAAK,CACjB,EACA,aAAc,CAAC,CAAE,IAAAC,EAAK,GAAGC,CAAM,EAAGC,EAAQ,CAAE,SAAAC,CAAS,OACnD,QAAC,MAAc,GAAGF,EAChB,oBAAC,YAAS,KAAK,QAAQ,QAASE,EAAU,EACzCD,IAFMF,CAGT,EAEF,YAAaI,MACX,OAAC,aACE,GAAGA,EACJ,UAAS,GACT,MAAM,UACN,YAAY,iBACd,EAEJ,KACA,QAAC,cAAW,QAAQ,UAAU,MAAM,iBACjC,UAAAV,EAAQ,OAAO,eAAe,EAAE,yEAEnC,GACF,KACA,QAAC,iBACC,oBAAC,UAAO,QAASD,EAAS,kBAAM,KAChC,OAAC,UACC,QAAQ,YACR,SAAUE,EAAO,SAAW,EAC5B,QAAS,IAAM,CACbH,EAAM,kBAAkBG,CAAM,EAC9BF,EAAQ,CACV,EACD,8BAED,GACF,GACF,CAEJ,CAAC,EAEMY,EAAQd",
|
|
6
|
+
"names": ["import_react", "import_ui", "import_material", "import_mobx_react", "import_jsx_runtime", "ChooseSamplesDialog", "model", "onClose", "samples", "picked", "setPicked", "s", "_", "value", "key", "props", "sample", "selected", "params", "ChooseSamplesDialog_default"]
|
|
7
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as Ln,b as qs,c as Gr,d as zr}from"./chunk-DKNKJWYF.js";import{f as Hs,g as _n,h as Ce,i as kn,j as On,k as St,l as Nn,m as vt,o as Tn}from"./chunk-IKKD4EOI.js";import{a as Br}from"./chunk-KWAXLUPQ.js";import"./chunk-E7J6SB5P.js";import{a as Ds,d as Hr,e as qr,f as Dr}from"./chunk-4T7DPQTR.js";import{a as ot}from"./chunk-J4OLMLS5.js";import{a as Fn,b as $n}from"./chunk-S2YZT446.js";import"./chunk-CNQYRKZ3.js";import"./chunk-YBLNN5FU.js";import{e as bt,f as ze,g as Pn}from"./chunk-LRBVMAUV.js";import{a as Bs,b as ce}from"./chunk-FY3BTKY4.js";var Cs=Bs((rd,As)=>{As.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function ye(n,e){return 2*n+(e==="reverse"?1:0)}function O(n){return Math.floor(n/2)}function je(n){return n%2===0?"forward":"reverse"}function z(n){return n%2===1}function re(n){return n%2===0?n+1:n-1}function jr(n){return n==="left"?"right":"left"}function It(n){return n==="forward"?"left":"right"}function Et(n){return n==="forward"?"right":"left"}function Ur(n){return n==="left"?"forward":"reverse"}function Wr(n){return n==="right"?"forward":"reverse"}function Ue(n,e){let t=O(n),r=O(e);return z(n)?r>t||r===t&&!z(e):r>=t}function st(n){return Fe(n[0],n[n.length-1])}function Fe(n,e){return n===void 0||e===void 0?!0:z(n)===z(e)?!z(n):Ue(n,e)}var it=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 r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},Vr=255,Gs=256,At=class{source;sigma;threshold;constructor(e,t){this.source=new it(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Vr?Math.floor(Gs/this.sigma):0}next(){if(this.sigma>=Vr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Qr(n){let e=new it(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var Ct=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new At(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(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:re(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];O(s.node)===O(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var zs=["","A","C","G","T","N"];function Yr(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Kr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=zs[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var js={A:"T",C:"G",G:"C",T:"A",N:"N"};function Rt(n){let e="";for(let t=n.length-1;t>=0;t--)e+=js[n[t]]??"N";return e}var Us=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]),Ie=(n,e)=>n>>>e|n<<32-e;function Xr(n){let e=Math.ceil((n.length+9)/64),t=new Uint8Array(e*64);t.set(n),t[n.length]=128;let r=new DataView(t.buffer),o=n.length*8;r.setUint32(t.length-8,Math.floor(o/2**32)),r.setUint32(t.length-4,o>>>0);let s=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let c=0;c<e;c++){for(let S=0;S<16;S++)i[S]=r.getUint32(c*64+S*4);for(let S=16;S<64;S++){let g=i[S-15],b=i[S-2],x=Ie(g,7)^Ie(g,18)^g>>>3,E=Ie(b,17)^Ie(b,19)^b>>>10;i[S]=i[S-16]+x+i[S-7]+E}let l=s[0],h=s[1],d=s[2],p=s[3],u=s[4],m=s[5],w=s[6],y=s[7];for(let S=0;S<64;S++){let g=Ie(u,6)^Ie(u,11)^Ie(u,25),b=u&m^~u&w,x=y+g+b+Us[S]+i[S]|0,E=Ie(l,2)^Ie(l,13)^Ie(l,22),A=l&h^l&d^h&d;y=w,w=m,m=u,u=p+x|0,p=d,d=h,h=l,l=x+E+A|0}[l,h,d,p,u,m,w,y].forEach((S,g)=>{s[g]=s[g]+S})}let a=new Uint8Array(32),f=new DataView(a.buffer);for(let c=0;c<8;c++)f.setUint32(c*4,s[c]);return a}function Zr(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function to(n){return{name:n.get("pggname"),subgraph:Zr(n.get("subgraph"),"subgraph"),translation:Zr(n.get("translation"),"translation")}}function Jr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function no(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),Jr(t.subgraph,e.subgraph),Jr(t.translation,e.translation)),t}function eo(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function ro(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of eo(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of eo(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function oo(n){let e=n.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e),r=0;for(let i of n)t.set(i,r),r+=i.length;let o=globalThis.crypto?.subtle;return[...o?new Uint8Array(await o.digest("SHA-256",t)):Xr(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var Ws="_gbwt_ref";function me(n){let e=`${n.sample}#${n.haplotype}#${n.contig}`;return n.end===void 0?e:`${e}[${n.fragment}-${n.end}]`}var Vs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ys(n){let e=Vs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Qs.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(n){return typeof n=="string"?Ys(n):n}function Ve(n,e){return{sample:n.sample??Ws,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var Ks=4096;function Hn(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=Ks?r[1]=t:e.push([t,t])}return e}var Xs=32768,so={mostChosenPaths:32},Bn=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},ie=class extends Error{};function Mt(n,e,t,r){return n==="forward"?e+t:e-r}function io(n,e,t,r){return n==="forward"?e-r:e+t}function ao(n){return Fe(re(n.handles[n.handles.length-1]),re(n.handles[0]))}function at(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function fo(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let I=performance.now(),R=I-o;return o=I,R},i={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}},a=(I,R)=>{let k=`${I}: ${R}`;i.walks[k]=(i.walks[k]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async I=>{let R=t.get(I)??c.get(I);if(R)return R;let k=await e.getRecord(I);if(i.graphFetches+=1,!k)throw new Error(`Node record ${I} is missing from the database`);return c.set(I,k),k},h=I=>t.get(I).sequenceLen,d=await e.pathsByHandle(),p=I=>{let R=d.get(I);return R!==void 0&&n.keep(R.name)},u=[],m=new Bn,w=new Map,y=new Set,S=new Set,g=async I=>{let R=(await l(I.node)).gbwt().lf(I.offset);return R===void 0||R.node===0?void 0:R},b=async(I,R)=>{let k=(await l(re(I.node))).gbwt().predecessorAt(I.offset);if(k===void 0||R!==void 0&&!R.has(k))return;let L=(await l(k)).gbwt().offsetTo(I);if(L===void 0)throw new Error(`No offset in ${k} leads to ${I.node}:${I.offset}`);return{node:k,offset:L}},x=(I,R,k,L)=>{let H=k.map(V=>V.pos.node),W=k.map(V=>V.pos.offset),J=0;for(let V of H)J+=h(V);let B=R==="forward"?k[0].left:k[k.length-1].left,F=u.length;u.push({pathHandle:I,orientation:R,handles:H,offsets:W,len:J,hapStart:B,hapEnd:B+J,canonical:Fe(H[0],H[H.length-1]),source:L});for(let V of k)m.set(V.pos,F);let K=w.get(I);return K?K.push(F):w.set(I,[F]),F},E=async(I,R,k,L)=>{let H=[],W=I;for(;;){r?.throwIfAborted();let B=await b(W.pos,t);if(!B)break;W={pos:B,left:io(k,W.left,h(W.pos.node),h(B.node))},H.push(W)}H.reverse();let J=[I];for(W=I;;){r?.throwIfAborted();let B=await g(W.pos);if(!B||!t.has(B.node))break;W={pos:B,left:Mt(k,W.left,h(W.pos.node),h(B.node))},J.push(W)}return x(R,k,[...H,...J],L)},A=async(I,R,k,L)=>u[m.get(I.pos)??await E(I,R,k,L)],_=I=>{let R=I.handles[I.handles.length-1];return{pos:{node:R,offset:I.offsets[I.offsets.length-1]},left:I.orientation==="forward"?I.hapEnd-h(R):I.hapStart}},T=I=>{let R=I.handles[0];return{pos:{node:R,offset:I.offsets[0]},left:I.orientation==="forward"?I.hapStart:I.hapEnd-h(R)}},$=await E({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),C=u[$],N=()=>{if(i.fallback!==void 0)return{reference:C,pieces:[],stats:i};let I=new Map;u.forEach((k,L)=>{L!==$&&I.set(at(k),[...I.get(at(k))??[],k])});let R=[];for(let k of I.values()){let L=new Set;for(let H of k)H.canonical&&!L.has(H.orientation)&&(L.add(H.orientation),R.push(H),i.sources[H.source]+=1)}return i.sources.reference=1,i.pieces=R.length+1,{reference:C,pieces:R,stats:i}},P=async(I,R)=>{let k=R?y:S,L=R?S:y,H=I;for(;;){if(k.has(H))return;k.add(H);let W=u[H],J=R?_(W):T(W),B=0,F;for(;F===void 0;){r?.throwIfAborted();let K=R?await g(J.pos):await b(J.pos);if(!K){F="endmarker";break}let V=(await l(J.pos.node)).sequenceLen,ve=(await l(K.node)).sequenceLen,oe=R?Mt(W.orientation,J.left,V,ve):io(W.orientation,J.left,V,ve);if(t.has(K.node)){let ee=m.get(K);ee===void 0?(H=await E({pos:K,left:oe},W.pathHandle,W.orientation,"chain"),L.add(H),F="landed"):(L.add(ee),F="merge")}else B>Xs?F="bound":(B+=ve,J={pos:K,left:oe})}if(a("chain",F),F!=="landed")return}},U=async I=>{if(n.context>I.context)throw new ie(`the context of ${n.context} bp exceeds the ${I.context} bp the haplotype index's stray rows cover`);let R=i.spacing;if(R===void 0)throw new ie("the haplotype index has no anchors");let{bin:k,bound:L}=I,{fills:H,inserted:W}=n.snarls;if(n.snarls.mode==="overlapping"&&H.length>0)throw new ie("the haplotype index's stray rows cover contained snarls only");for(let v of H){if(v.inserted>0&&v.low===v.high)throw new ie(`the haplotype index's stray rows leave out the snarl bounded by node ${v.low} at both ends`);if(v.inserted>0&&(I.snarlNodes===void 0||v.nodes>I.snarlNodes))throw new ie(I.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${v.nodes} nodes exceeds the ${I.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(n.window.start/k),B=Math.floor((n.window.end-1)/k),F=J*k,K=(B+1)*k,V=new Map,ve=async(v,M)=>{let j=await e.haplotypeAnchorsBetween(n.referenceHandle,v*R,M*R);for(let D of j)V.set(D.anchorOffset/R,D)},oe=Math.max(0,Math.floor((F-L)/R)-1),ee=Math.ceil((K+L)/R)+1,[{listed:xt,strays:fe}]=await Promise.all([e.haplotypeBinData(n.referenceHandle,J,B),ve(oe,ee)]);for(let v of t.keys()){let M=O(v);if(!z(v)&&!xt(M)&&!W.has(M))throw new ie(`the haplotype index lists node ${M} of the subgraph in no bin that the window touches`)}i.scans=Hn([...t.keys()].sort((v,M)=>v-M));let de=Promise.all(i.scans.map(([v,M])=>e.haplotypeSamplesInRange(v,M)));for(de.catch(()=>{});oe>0&&(V.get(oe)?.pathOffset??Number.POSITIVE_INFINITY)>=F-L;)oe-=1,await ve(oe,oe);for(;V.has(ee)&&V.get(ee).pathOffset<=K+L;)ee+=1,await ve(ee,ee);let xe=[...V.keys()].sort((v,M)=>v-M),_e=V.get(xe[0]??-1);if(!_e)throw new ie("the haplotype index has no anchors on this path");let pe=v=>V.get(v).pathOffset,tt=new Map;for(let v of xe){let M=O(V.get(v).node);tt.set(M,[...tt.get(M)??[],v])}let Cn=[...tt.keys()],Rr=Cn.map(v=>V.get(tt.get(v)[0]).visits);if(!Rr[Cn.indexOf(O(_e.node))].some(v=>v.pathHandle===n.referenceHandle&&v.orientation==="forward"&&v.pathOffset===_e.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${_e.pathOffset} (node ${O(_e.node)}); it does not match this graph`);let Mr=xe.filter(v=>pe(v)<=n.window.start),Ts=xe.filter(v=>pe(v)>=n.window.end);i.anchors=[pe(Mr[Mr.length-1]??xe[0]),pe(Ts[0]??xe[xe.length-1])],i.anchorsRead=xe.length;let Rn=new Map,Pr=new Set;if(Cn.forEach((v,M)=>{let j=tt.get(v),D=j.length===1?j[0]:void 0;for(let G of Rr[M])Pr.add(G.pathHandle),G.orientation==="forward"&&p(G.pathHandle)&&Rn.set(G.pathHandle,[...Rn.get(G.pathHandle)??[],{k:D,row:G}])}),i.chosenPaths=[...Pr].filter(p).length,i.chosenPaths>so.mostChosenPaths)throw new ie(`${i.chosenPaths} chosen paths pass the anchors, more than ${so.mostChosenPaths}`);let yt=[],Le=Number.POSITIVE_INFINITY,ke=0;for(let[v,M]of Rn){M.sort((j,D)=>j.row.pathOffset-D.row.pathOffset);for(let j=0;j+1<M.length;j++){let D=M[j],G=M[j+1];if(D.k===void 0||G.k===void 0||Math.abs(D.k-G.k)!==1)continue;let[Z,te]=pe(D.k)<=pe(G.k)?[D,G]:[G,D],ne=pe(Z.k),se=pe(te.k);ne<K&&se>=F?(yt.push({pathHandle:v,from:D.row,to:G.row}),Le=Math.min(Le,ne-L),ke=Math.max(ke,se+L)):ne>=K&&ne-K<=L?(yt.push({pathHandle:v,from:Z.row,to:void 0}),Le=Math.min(Le,ne-L),ke=Math.max(ke,ne+L)):se<F&&F-se<=L&&(yt.push({pathHandle:v,from:te.row,to:void 0}),Le=Math.min(Le,se-L),ke=Math.max(ke,se+L))}}let Ls=new Set(H.map(v=>`${v.low}:${v.high}`)),Fs=fe.filter(v=>p(v.pathHandle)&&(v.snarl===void 0||Ls.has(`${v.snarl[0]}:${v.snarl[1]}`))).sort((v,M)=>v.pathHandle-M.pathHandle||v.pathStart-M.pathStart);i.strays={bins:B-J+1,rows:fe.length,walked:0,outsideBp:0},ke>0&&await n.prefetchReferenceRange(n.referenceHandle,Math.max(0,Le),ke+1),i.ms.scan=s();let _r=8*R+2*(n.window.end-n.window.start),kr=i.strays,nt=0,Or=v=>{if(kr.outsideBp+=v,nt+=v,nt>_r)throw new ie(`a walk of a chosen path near the window went past its cap of ${_r} bp`)},Mn=new Map,Nr=(v,M,j)=>(Mn.get(v)??[]).some(([D,G])=>D<=M&&j<G),Tr=(v,M,j)=>{Mn.set(v,[...Mn.get(v)??[],[M,j]])},Lr=async(v,M,j,D,G)=>{let Z=M,te=j,ne=te;for(;Z&&te<=D;){r?.throwIfAborted();let se;if(t.has(Z.node)){let rt=await A({pos:Z,left:te},v,"forward",G),$r=_(rt);Z=$r.pos,te=$r.left,se=h(Z.node),ne=Math.max(ne,rt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Or(se),ne=Math.max(ne,te+se);Z=await g(Z),te+=se}return ne},$s=async(v,M,j,D)=>{let G={pos:M,left:j},Z=j;for(;G.left>D;){r?.throwIfAborted();let te=await b(G.pos);if(!te)break;let ne=(await l(te.node)).sequenceLen,se=G.left-ne;if(t.has(te.node)){let rt=await A({pos:te,left:se},v,"forward","section");G=T(rt),Z=Math.min(Z,rt.hapStart)}else Or(ne),G={pos:te,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:v,from:M,to:j}of yt){let D=M.pathOffset,G=(j??M).pathOffset+L;if(Nr(v,D-L,G))continue;let Z={node:M.node,offset:M.offset};nt=0;let te=await Lr(v,Z,D,G,"section");nt=0;let ne=await $s(v,Z,D,D-L);Tr(v,Math.min(ne,D-L),Math.max(te,G+1)),a(j?"section":"visit",j?"past the far anchor":"bound")}for(let v of Fs){if(Nr(v.pathHandle,v.pathStart,v.pathEnd))continue;nt=0;let M=await Lr(v.pathHandle,{node:v.node,offset:v.offset},v.pathStart,v.pathEnd,"stray");Tr(v.pathHandle,v.pathStart,Math.max(M,v.pathEnd+1)),kr.walked+=1}i.ms.walks=s();let Fr=[];for(let v of await de)for(let M of v)if(i.scanRows+=1,t.has(M.node)&&p(M.pathHandle)){if(!(w.get(M.pathHandle)??[]).some(j=>{let D=u[j];return D.hapStart<=M.pathOffset&&M.pathOffset<D.hapEnd}))throw new ie(`chosen path ${M.pathHandle} has a sample at ${M.pathOffset} on the window's nodes that no walk reached`);M.orientation==="reverse"&&Fr.push(M)}for(let v of Fr)await A({pos:{node:v.node,offset:v.offset},left:v.pathOffset},v.pathHandle,"reverse","twin");i.ms.check=s()},Y=async()=>{let I=new Map,R=B=>{let F=at(B),K=I.get(F);K?K.add(B.orientation):I.set(F,new Set([B.orientation]))},k=0,L=()=>{for(;k<u.length;k++)R(u[k])};L();let H=B=>(I.get(at(B))?.size??0)>1,W=2*f,J=(B,F)=>F===$?p(n.referenceHandle)&&ao(B):!B.canonical||ao(B);for(let B=0;B<u.length;B++){let F=u[B];if(H(F)||!J(F,B))continue;i.twins.tried+=1;let K=F.orientation==="forward"?"reverse":"forward",V=_(F),ve=0,oe;for(;!oe&&ve<=W;){r?.throwIfAborted();let fe=await g(V.pos);if(!fe)break;let de=(await l(fe.node)).sequenceLen,xe=Mt(F.orientation,V.left,(await l(V.pos.node)).sequenceLen,de),_e=re(fe.node);oe=(await e.haplotypeSamplesInRange(_e,_e)).find(pe=>pe.pathHandle===F.pathHandle&&pe.orientation===K&&pe.pathOffset===xe),ve+=de,V={pos:fe,left:xe}}let ee=oe&&{pos:{node:oe.node,offset:oe.offset},left:oe.pathOffset},xt=0;for(;ee&&!H(F)&&xt<=W+F.len;){if(r?.throwIfAborted(),t.has(ee.pos.node)){let fe=await A(ee,F.pathHandle,K,"twin"),de=u.indexOf(fe);await P(de,!0),await P(de,!1),L(),ee=_(fe)}if(!H(F)){let fe=(await l(ee.pos.node)).sequenceLen;xt+=fe;let de=await g(ee.pos);ee=de?{pos:de,left:Mt(K,ee.left,fe,(await l(de.node)).sequenceLen)}:void 0}}if(L(),!H(F))throw new ie(`piece ${at(F)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let I=await e.haplotypeStrayOptions();if(I===void 0)throw new ie("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await U(I),await Y()}catch(I){if(!(I instanceof ie))throw I;i.fallback=I.message}return N()}function co(n,e){return n.handles[0]-e.handles[0]||n.offsets[0]-e.offsets[0]}function Pt(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var _t=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},qn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Pt(a,o)-Pt(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),h=Pt(c,o),d=Pt(c,s);for(let p=0;p<d-h;p++){let u=r===1?c[d-1-p]-o:s-1-c[h+p],m=i.bestBefore(u),w=(m===-1?0:i.ending[m])+l;if(w>i.ending[u]&&(i.raise(u,w),a)){let y=a.count++;a.row[y]=f,a.column[y]=u,a.previous[y]=m===-1?-1:a.endingMatch[m],a.endingMatch[u]=y}}}}chain(e,t,r,o,s){let i=new _t(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new _t(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let h=0;h<=i;h++){let d=a[h]+f[i-h];d>l&&(l=d,c=h)}return o+c}};function lo(n,e,t){let r=new qn(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Zs=100,zn=4e6,Js=5e3,le=15,ei=64,ti=8,xo=1,jn=-4,ae=-6,Re=-1,Qe=-(2**30),Ot=0,Dn=1,yo=2;function $e(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function kt(n,e,t){return n>=t&&n>=e?Ot:t>=e?yo:Dn}function bo(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Qe),f=new Int32Array(s).fill(Qe),c=new Int32Array(s).fill(Qe);a[0]=0;for(let u=1;u<=o;u++)c[u]=ae+(u-1)*Re,i[u]=(u===1?Ot:yo)<<4;for(let u=1;u<=r;u++){let m=new Int32Array(s).fill(Qe),w=new Int32Array(s).fill(Qe),y=new Int32Array(s).fill(Qe);w[0]=ae+(u-1)*Re,i[u*s]=(u===1?Ot:Dn)<<2;let S=n.charCodeAt(u-1);for(let g=1;g<=o;g++){let b=kt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?xo:jn);let x=kt(a[g]+ae,f[g]+Re,c[g]+ae);w[g]=Math.max(a[g]+ae,f[g]+Re,c[g]+ae);let E=kt(m[g-1]+ae,w[g-1]+ae,y[g-1]+Re);y[g]=Math.max(m[g-1]+ae,w[g-1]+ae,y[g-1]+Re),i[u*s+g]=b|x<<2|E<<4}a=m,f=w,c=y}let l=[],h=r,d=o,p=kt(a[o],f[o],c[o]);for(;h>0||d>0;){let u=i[h*s+d]>>2*p&3;p===Ot?(l.push(n[h-1]===e[d-1]?"=":"X"),h-=1,d-=1):p===Dn?(l.push("I"),h-=1):(l.push("D"),d-=1),p=u}for(let u of l.reverse())$e(t,u,1)}function ni(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-ae-(t-1)*Re,-ae+10*Math.log2(t)))+(Math.min(n,e)>0?-jn:0)}function So(n,e){let t=Math.abs(n-e);return t===0?0:.01*le*t+.5*Math.log2(t)}function ho(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function ri(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=le&&s.push(ho(n,i,a)),i=Math.max(i,f);return r-i>=le&&s.push(ho(n,i,r)),s}function Un(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),h=new Int32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g],x=b.qe-b.qs;for(let E=g-1;E>=Math.max(0,g-Js);E--){if(c[E]+x<=c[g])continue;let A=f[E];if(A.flipped===b.flipped&&A.qs<b.qs&&(b.flipped?b.te<A.te:A.ts<b.ts)){let T=Math.max(0,A.qe-b.qs,b.flipped?b.te-A.ts:A.te-b.ts),$=b.qs+T-A.qe,C=b.flipped?A.ts-(b.te-T):b.ts+T-A.te;if(T<x&&$<=e&&C<=e){let N=c[E]+x-T-r($,C);N>c[g]&&(c[g]=N,l[g]=E,h[g]=T)}}}}let d=new Int32Array(f.length),p=-1;for(let g=0;g<f.length;g++){let b=f[g];d[g]=(d[l[g]]??0)+b.qe-b.qs-h[g],d[g]>=t&&(p<0||c[g]>c[p])&&(p=g)}if(p<0)break;let u=[];for(let g=p;g>=0;g=l[g])u.push({run:f[g],trim:h[g]});u.reverse(),s.push(u);let m=u[0],w=u.at(-1),{flipped:y}=m.run,S=y?a.flipped:a.forward;S.query.push([m.run.qs+m.trim,w.run.qe]),S.target.push(y?[w.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,w.run.te]);for(let{run:g,trim:b}of u)i.query.push([g.qs+b,g.qe]),i.target.push(g.flipped?[g.ts,g.te-b]:[g.ts+b,g.te]);f=f.flatMap(g=>{let b=g.flipped?a.flipped:a.forward;return ri(g,[...i.query,...b.query],[...i.target,...b.target])}).sort((g,b)=>g.qs-b.qs||g.ts-b.ts)}return s}function Gn(n,e){let t=new Map;for(let s=0;s+le<=e.length;s++){let i=e.slice(s,s+le),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+le<=n.length;s++){let i=t.get(n.slice(s,s+le));if(i&&i.length<=ei)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+le,c.te=a+le;else{let l={qs:s,qe:s+le,ts:a,te:a+le,flipped:!1};o.set(f,l),r.push(l)}}}return r}function oi(n,e){return[...Gn(n,e),...Gn(n,Rt(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Nt(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,h=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?Rt(h):h,r,s.qe,c)}$e(r,"=",i.qe-f),s=i}}function Wn(n,e,t){$e(t,"I",n.length),$e(t,"D",e.length)}function vo(n,e,t){n.length*e.length<=zn?bo(n,e,t):Wn(n,e,t)}function Vn(n,e,t,r=0){let[o]=n.length*e.length>zn&&r<ti?Un(Gn(n,e),1/0,le,So,1):[];if(!o){vo(n,e,t);return}let s=(f,c,l)=>{Vn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),Nt(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function si(n,e,t){Vn(n,e,t)}function ii(n,e,t){let r=[];Nt(n,e,t,r,si);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function ai(n,e,t,r){let o=[];if(n.length*e.length<=zn)bo(n,e,t);else{let s=Un(oi(n,e),1/0,Math.max(r,le),So),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>ii(a,n,e)),i){let a=(l,h,d,p,u)=>{o.some(w=>p<w.queryEnd&&w.queryStart<p+l.length||u<w.targetEnd&&w.targetStart<u+h.length)?vo(l,h,d):Vn(l,h,d)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Nt(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Wn(n,e,t)}return o}function Qn(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function po(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Qn(n,(i,a,f,c)=>{let l=e==="query"?f:c,h=d=>{let p=l+o*d;return p>=t&&p<r};if(i==="="||i==="X")for(let d=0;d<a;d++)h(d)&&(s+=i==="="?xo:jn);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)h(d)&&(s+=d===0?ae:Re);else h(0)&&(s+=ae+(a-1)*Re)}),s}function uo(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function fi(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[p,u]of n.shared)f.fill(1,p-n.queryStart,u-n.queryStart);let c=p=>f[p-n.queryStart]===1,l=()=>{$e(r,"I",o),$e(r,"D",s),o=0,s=0};Qn(n,(p,u,m)=>{if(p==="I")o+=u;else if(p==="D")s+=u;else{for(let w=0;w<u;w++)e[i+w]?(o+=1,s+=1,c(t?m-w:m+w)&&(a+=1)):((o>0||s>0)&&l(),$e(r,p,1));i+=u}}),l();let h={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[p,u]=r.shift();h[p]+=u}let d={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[p,u]=r.pop();d[p]+=u}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?d.I:h.I),queryEnd:n.queryEnd-(t?h.I:d.I),targetStart:n.targetStart+h.D,targetEnd:n.targetEnd-d.D,edits:r,sharedBases:n.sharedBases-a}}function ci(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];Qn(c,(h,d,p,u)=>{if(h==="="||h==="X")for(let m=0;m<d;m++)l.push([c.strand==="-"?p-m:p+m,u+m])});for(let[h,d]of l)o.query[h]=Math.min(255,o.query[h]+1),o.target[d]=Math.min(255,o.target[d]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[h,d]of c)for(let[p,u]of[["query",h],["target",d]])if(o[p][u]>1){let m=i[p].get(u);m?m.at(-1)!==l&&m.push(l):i[p].set(u,[l])}});let a=new Map,f=(c,l,h)=>{let d=`${h}:${c}:${l}`,p=a.get(d);if(p===void 0){let[u,m]=uo(n[c],h),[w,y]=uo(n[l],h),S=Math.max(u,w),g=Math.min(m,y),[b,x]=[n[c],n[l]];p=[po(x,h,S,g)-po(b,h,S,g),x.sharedBases-b.sharedBases,c-l].find(A=>A!==0)>0,a.set(d,p)}return p};return n.flatMap((c,l)=>{let h=s[l],d=new Uint8Array(h.length);if(h.forEach(([m,w],y)=>{for(let[S,g]of[["query",m],["target",w]])!d[y]&&i[S].get(g)?.some(b=>b!==l&&f(l,b,S))&&(d[y]=1)}),!d.includes(1))return[c];let p=fi(c,d),u=p?.edits.reduce((m,[w,y])=>m+(w==="="?y:0),0)??0;return p&&u>=r?[p]:[]})}function mo(n,e){return n.map(t=>{let r=e(O(t));return z(t)?Rt(r):r}).join("")}function go(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(O(r)).length);return t}function wo(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function li(n,e,t,r){let o=wo(n),s=wo(e),i=new Map;e.forEach((h,d)=>{s[d]||i.set(O(h),[d])});let a=2*e.length,f=(h,d,p)=>h*a+2*d+(p?1:0),c=new Set;n.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[])c.add(f(d,p,z(h)!==z(e[p])))});let l=[];return n.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[]){let u=z(h)!==z(e[p]),m=u?-1:1,w=p-m;if(!(d>0&&w>=0&&w<e.length&&c.has(f(d-1,w,u)))){let S=d,g=p;for(;S<n.length&&g>=0&&g<e.length&&c.has(f(S,g,u));)S+=1,g+=m;let b=g-m;l.push({qs:t[d],qe:t[S],ts:r[Math.min(p,b)],te:r[Math.max(p,b)+1],flipped:u})}}}),l}function Io(n){let{query:e,target:t,sequenceOf:r}=n,o=mo(e,r),s=mo(t,r),i=li(e,t,go(e,r),go(t,r)),a=n.minMatch??Zs,f=n.bases??!0,c=[];for(let l of Un(i,n.maxGap??1/0,a,ni)){let h=[],d=l[0],p=l.at(-1),{flipped:u}=d.run;Nt(l,o,s,h,f?(w,y,S,g,b)=>{for(let x of ai(w,y,S,a)){let E=b+y.length;c.push({...x,queryStart:g+x.queryStart,queryEnd:g+x.queryEnd,targetStart:u?E-x.targetEnd:b+x.targetStart,targetEnd:u?E-x.targetStart:b+x.targetEnd,strand:u?"+":"-",edits:u?x.edits.reverse():x.edits,shared:[]})}}:Wn),c.push({queryStart:d.run.qs+d.trim,queryEnd:p.run.qe,targetStart:u?p.run.ts:d.run.ts+d.trim,targetEnd:u?d.run.te-d.trim:p.run.te,strand:u?"-":"+",edits:u?h.reverse():h,sharedBases:l.reduce((w,{run:y,trim:S})=>w+y.qe-y.qs-S,0),shared:l.map(({run:w,trim:y})=>[w.qs+y,w.qe])})}return ci(c,o.length,s.length,a).map(({shared:l,...h})=>h).sort((l,h)=>l.queryStart-h.queryStart)}function Eo(n){return n.map(([e,t])=>`${t}${e}`).join("")}var be=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 Yn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var ct=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Yn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Yn(e[s],e[a])&&(a=s),i<e.length&&Yn(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function hi(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function di(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function Be(n){return`${n.node}:${n.offset}`}function ft(n){return n.map(e=>re(e)).reverse()}function pi(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ui(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);Co(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,pieces:[...a.pieces,...f.pieces],soloAligned:[...a.soloAligned,...f.soloAligned],identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function mi(n,e,t){if(n.some(i=>i.weight!==void 0))return n;let r=new Map;n.forEach((i,a)=>{if(i.identity){let f=r.get(i.identity.pathHandle);f?f.push(a):r.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of r.values()){i.sort((l,h)=>n[l].identity.hapStart-n[h].identity.hapStart);let a=i[0],f=n[a],c=[];for(let l of i.slice(1)){let h=n[l],d=c.length===0?pi(f,h):void 0;if(d){f=ui(f,h,d),s.add(l);continue}if(!e(h)){c.push(l);continue}let p=e(f)?t([f,...c.map(u=>n[u]),h]):void 0;if(p){f=p;for(let u of[...c,l])s.add(u)}else o.set(a,f),a=l,f=h;c=[]}o.set(a,f)}return n.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Tt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var gi=32768;function wi(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=gi?o[1]=r:t.push([r,r])}return t}var $t=class n{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 n(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(ye(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 be(this.limit);let t=await this.db.getRecord(ye(e,"forward")),r=await this.db.getRecord(ye(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}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 ${me(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${me(t.name)} at ${t.name.fragment} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`The fragment of ${me(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(O(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`The fragment of ${me(e.name)} at ${e.name.fragment} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=je(e),a=new ct;return a.push(t,o,It(i)),a.push(s.sequenceLen-t-1,o,Et(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords([[Math.min(i,a),Math.max(i,a)+1]])){let c=await this.db.indexedPositionsBetween(e,t,r);await this.db.prefetchRecords(wi(c.map(l=>l.pos.node)).map(([l,h])=>[l,h+2]),!0)}}return o}async aroundInterval(e,t,r){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof be&&o.windowBp===void 0?new be(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new ct;for(;;){let f=O(o.node),c=je(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,It(c));let h=l.sequenceLen-s;if(i<=h){a.push(i===h?0:h-i-1,f,Et(c));break}a.push(0,f,Et(c));let d=l.gbwt().lf(o.offset);if(!d)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=d,s=0,i-=h}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new ct;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let r=new Set,o=new Set;for(let i of this.records.keys())o.add(O(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=jr(f);if(!r.has(`${a}:${l}`)){let p=this.record(ye(a,Ur(f))),u=i+p.sequenceLen-1;u<=t&&e.push(u,a,l)}let h=this.record(ye(a,Wr(f))),d=i+1;if(d<=t)for(let p of h.successors()){let u=O(p),m=It(je(p));r.has(`${u}:${m}`)||e.push(d,u,m)}}for(let i of o)this.records.delete(ye(i,"forward")),this.records.delete(ye(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let r=[e,re(t)],o=new Set([O(e),O(t)]),s=[];for(;r.length>0;){let i=r.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s.push(a));for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(r.push(f,re(f)),o.add(c))}}return{inserted:s,nodes:o.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[r,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(r,o),a=O(r),f=O(o);this.snarlFills.push({low:Math.min(a,f),high:Math.max(a,f),nodes:i,inserted:s.length});for(let c of s)this.snarlNodes.add(c);t+=s.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(re(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(re(l))).successors().length>1},r=async f=>{let c=await e(re(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[re(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=O(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let h of["forward","reverse"])s.push(...(await e(ye(c,h))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((x,E)=>i.set(x,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let x=0;x<s;x++){let E=this.record(o[x]),A=E.gbwt().decompressArrays();f[x]=E.sequenceLen,c.push(A),a[x+1]=a[x]+A.nodes.length}let l=a[s],h=new Int32Array(l),d=new Int32Array(l),p=new Uint8Array(l);for(let x=0;x<s;x++){let E=c[x];h.set(E.nodes,a[x]),d.set(E.offsets,a[x])}c.length=0;for(let x=0;x<l;x++){let E=i.get(h[x]);E===void 0?h[x]=-1:(h[x]=E,p[a[E]+d[x]]=1)}let u=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,w,y=(x,E,A)=>{let _=[],T=0,$=0,C=-1,N=x,P=E;for(;;){N===u&&P===m&&(C=T),A&&(A.push(o[N]),_.push(P)),T+=1,$+=f[N];let U=a[N]+P,Y=h[U];if(Y<0)break;P=d[U],N=Y}return{offsets:_,len:$,refAt:C,last:N}},S=(x,E,A,_)=>{_>=0&&(this.refId=this.paths.length,w=_),this.paths.push({path:x,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let x=0;x<s;x++){let E=o[x];if(!z(E)){let A=a[x],_=a[x+1]-A;for(let T=0;T<_;T++)if(p[A+T]===0){let $=[],{offsets:C,len:N,refAt:P,last:U}=y(x,T,$),Y=o[U];if(P>=0||Fe(E,Y)){if(S($,C,N,P),!z(Y)){let I=i.get(re(Y));g[I]=g[I]+1}}else this.twinStarts.add(Be({node:E,offset:T}))}}}for(let x=0;x<s;x++){let E=o[x];if(z(E)){let A=a[x],_=a[x+1]-A,T=0;for(let C=0;C<_;C++)p[A+C]===0&&(T+=1);let $=(u===void 0||w!==void 0)&&T===g[x];for(let C=0;C<_;C++)if(p[A+C]===0){let N=$?void 0:y(x,C,void 0);if(N&&(N.refAt>=0||Fe(E,o[N.last]))){let P=[],{offsets:U,len:Y,refAt:I}=y(x,C,P);S(P,U,Y,I)}else this.twinStarts.add(Be({node:E,offset:C}))}}}let b=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((x,E)=>x.path[0]-E.path[0]||x.offsets[0]-E.offsets[0]),b&&(this.refId=this.paths.indexOf(b)),r){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let x=this.paths[this.refId],E=r.nodeOffset;for(let _ of x.path.slice(0,w))E+=this.record(_).sequenceLen;let A=r.seqOffset-E;this.refInterval=[A,A+x.len],x.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+x.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],r=t?.path,o=r&&!st(r)?ft(r):void 0,s=c=>o!==void 0&&Kn(c,o)===0||st(ft(c)),i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>Kn(c.path,l.path)||c.len-l.len||(c===t?-1:l===t?1:0));let a=[],f;for(let c of this.paths){let l=a[a.length-1],h=i&&c!==t&&s(c.path);this.twinDeferred||=h,l&&Kn(l.path,c.path)===0&&!h?l.weight=(l.weight??1)+(c.weight??1):(c===t&&(f=a.length),a.push({...c,weight:c.weight??1}))}this.paths=a,this.refId=f}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,r=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(r({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(r(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(r(i.identity)));s.length<this.paths.length&&(this.paths=s,this.refId=e===void 0?void 0:s.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(i=>i.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((i,a)=>a!==this.refId&&i.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 r=this.refId===void 0?void 0:this.paths[this.refId],o=this.paths.filter((i,a)=>a===this.refId||i.identity!==void 0&&e(i.identity.name)),s=new Set;for(let i of o)for(let a of i.path)s.add(O(a));for(let i of[...this.records.keys()])s.has(O(i))||this.records.delete(i);this.paths=o,this.refId=r===void 0?void 0:o.indexOf(r)}async extractChosenPaths(e,t,r,o){this.clearPaths();let s=e.position.seqOffset,i=await fo({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:s-e.position.nodeOffset,window:{start:s,end:s+t},context:o,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:r,signal:this.signal,prefetchReferenceRange:(l,h,d)=>this.prefetchReferenceRange(l,h,d)});if(this.stats.keep=i.stats,i.stats.fallback!==void 0)return!1;let a=await this.db.pathsByHandle(),f=l=>({path:l.handles,offsets:l.offsets,len:l.len,weight:void 0,identity:{pathHandle:l.pathHandle,name:l===i.reference?e.name:a.get(l.pathHandle).name,orientation:l.orientation,hapStart:l.hapStart,hapEnd:l.hapEnd}}),c=[i.reference,...i.pieces].sort(co);return this.paths=c.map(f),this.refId=c.indexOf(i.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[i.reference.hapStart,i.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=Hn(this.sortedHandles());if(t.length===0)return;let r=new Map,o=await Promise.all(t.map(([m,w])=>this.db.haplotypeSamplesInRange(m,w)));for(let m of o.flat())r.set(Be(m),m);let s=m=>{let w=0,y=t.length-1;for(;w<y;){let g=w+y+1>>1;t[g][0]<=m?w=g:y=g-1}let S=t[w];return S[0]<=m&&m<=S[1]},i=new Map;this.paths.forEach((m,w)=>{m.path.length>0&&w!==this.refId&&i.set(Be(Tt(m,0)),w)});let a=this.stats.identification;a.interval=e,a.scans=t,a.windowSamples=r.size,this.paths.forEach((m,w)=>{w!==this.refId&&a.fragmentLengths.push(m.len)});let f=this.recordReader(()=>{this.stats.identificationFetches+=1,a.graphFetches+=1}),c=m=>(a.graphLookups+=1,f(m)),l=async(m,w)=>{if(s(m.node))return r.get(Be(m));this.stats.identificationFetches+=1,a.companionSeeks+=1,w.seeks+=1;let y=await this.db.haplotypeSampleAt(m.node,m.offset);return y||(a.companionMisses+=1),y},h=new Map,d=async m=>{let w=h.get(m);if(!w){let y=await this.db.getPath(m);if(!y)throw new Error(`Path ${m} is missing from the database`);w=y.name,h.set(m,w)}return w},p=(m,w,y)=>m.orientation==="forward"?{pathHandle:m.pathHandle,orientation:"forward",base:m.pathOffset-w}:{pathHandle:m.pathHandle,orientation:"reverse",base:m.pathOffset+w+y},u=(m,w)=>m.orientation==="forward"?{pathHandle:m.pathHandle,orientation:"forward",base:m.hapStart-w}:{pathHandle:m.pathHandle,orientation:"reverse",base:m.hapEnd+w};for(let m=0;m<this.paths.length;m++){let w=this.paths[m];if(m===this.refId||w.identity)continue;let y=[],S=new Set,g={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};a.chains.push(g);let b,x=0,E=m,A;for(;b===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){g.end="cycle";break}S.add(E);let N=this.paths[E];y.push({index:E,startBp:x}),g.fragments+=1;let P=x;for(let Y=0;Y<N.path.length;Y++){let I=Tt(N,Y),R=r.get(Be(I)),k=this.record(I.node).sequenceLen;if(R){b=p(R,P,k);break}P+=k}if(x+=N.len,b){g.end="in-fragment sample";break}let U=Tt(N,N.path.length-1);A=this.record(U.node).gbwt().lf(U.offset),E=void 0}if(A===void 0||A.node===0){g.end="endmarker";break}let _=Be(A),T=i.get(_);if(T!==void 0){let N=this.paths[T].identity;if(N){b=u(N,x),g.end="identified sibling";break}E=T;continue}this.records.has(A.node)&&(g.reentries+=1),this.twinStarts.has(_)&&(g.twinLandings+=1);let $=await l(A,g),C=await c(A.node);if($){b=p($,x,C.sequenceLen),g.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,g.steps+=1,x-y[y.length-1].startBp>4*e+4*C.sequenceLen){g.end="bound";break}x+=C.sequenceLen,A=C.gbwt().lf(A.offset)}if(b){g.pathHandle=b.pathHandle;let _=await d(b.pathHandle);for(let{index:T,startBp:$}of y){let C=this.paths[T];C.identity=b.orientation==="forward"?{pathHandle:b.pathHandle,name:_,orientation:"forward",hapStart:b.base+$,hapEnd:b.base+$+C.len}:{pathHandle:b.pathHandle,name:_,orientation:"reverse",hapStart:b.base-$-C.len,hapEnd:b.base-$}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=di(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),X(r,"M",i),Co(r,o-i-a,s-i-a),X(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??hi(lo(e,t,h=>this.record(h).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(h,d,p,u)=>{h===d?X(s,"D",i[u]-i[p]):p===u?X(s,"I",this.pathLen(e.slice(h,d))):this.align(e.slice(h,d),t.slice(p,u),s)},f=0,c=0,l=0;for(let h=0;h<o.count;h++){let d=o.pathAt[h],p=o.refAt[h];(c!==d||l!==p)&&a(c,d,l,p);let u=this.record(e[d]).sequenceLen;X(s,"M",u),f+=u,c=d+1,l=p+1}return a(c,e.length,l,t.length),{edits:s,matched:f,matches:o}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(st(r)&&(t.identity===void 0||!st(ft(t.path))))o={...this.editsAgainst(t.path,r),flipped:!1};else{let s=ft(t.path),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={...this.editsAgainst(t.path,r),flipped:!1};else if(i===0)o={...this.editsAgainst(s,r),flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,r])=>`${r}${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,r=this.refPrefix(t)[t.length],o=(l,h,d,p)=>{let u=yi(l),m=this.paths[d[0]],w=this.paths[d[d.length-1]],y=m.identity,S=y?.orientation==="forward",[g,b]=S?[m,w]:[w,m];return{strand:h,refStart:e.start+u.leading,refEnd:e.start+r-u.trailing,edits:u.edits,weight:m.weight,path:d.flatMap(x=>this.paths[x].path),start:Tt(m,0),pieces:d,soloAligned:p,identity:y===void 0?void 0:{pathHandle:y.pathHandle,name:y.name,hapStart:y.name.fragment+g.identity.hapStart,hapEnd:y.name.fragment+b.identity.hapEnd,walkForward:S}}},s=l=>l.soloAligned.reduce((h,d)=>h+d,0),i=l=>l.pieces.reduce((h,d)=>h+this.paths[d].len,0),a=l=>2*s(l)>=i(l),f=l=>{let h=l[0],d=l[l.length-1],p=h.identity.walkForward;if(l.some((P,U)=>P.strand!==h.strand||P.identity.walkForward!==p||U>0&&P.identity.hapStart<l[U-1].identity.hapEnd))return;let u=p?l:[...l].reverse(),m=u.flatMap(P=>P.pieces),w=u.flatMap(P=>P.soloAligned),y=h.strand==="+"!==p,S=m.map(P=>this.paths[P]),g=S.slice(1).map((P,U)=>{let Y=S[U].identity;return p?P.identity.hapStart-Y.hapEnd:Y.hapStart-P.identity.hapEnd}),b=y?[...S].reverse():S,x=y?[...g].reverse():g,E=b.flatMap(P=>y?ft(P.path):P.path),{edits:A}=this.editsAgainst(E,t),_=Ao(A,b.map(P=>P.len)),T=new Map((y?[...m].reverse():m).map((P,U)=>[P,_[U]])),$=P=>2*P.pieces.reduce((U,Y)=>U+T.get(Y),0)>=s(P);if(!$(h)||!$(d))return;let C=[],N=0;return b.slice(0,-1).forEach((P,U)=>{N+=P.len,C.push([N,x[U]])}),o(bi(A,C),h.strand,m,w)},c=[];return this.paths.forEach((l,h)=>{if(h===this.refId)return;let{edits:d,flipped:p}=this.alignment(h),u=l.identity,m=u?u.orientation==="forward"!==p:!p;c.push(o(d,m?"+":"-",[h],Ao(d,[l.len])))}),mi(c,a,f).map(l=>{let{edits:h,identity:d,pieces:p,soloAligned:u,...m}=l,w={...m,cigar:Si(h)};return d?{...w,resolved:!0,name:d.name,label:me({...d.name,fragment:d.hapStart,end:d.hapEnd}),pathHandle:d.pathHandle,hapStart:d.hapStart,hapEnd:d.hapEnd}:{...w,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:h}=l;return h?[{name:h.name,start:h.name.fragment+h.hapStart,steps:Ft(l,h)}]:[]}),i=l=>h=>h.sample===l.sample&&h.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(ye(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(h=>f(h.name)).flatMap(h=>Io({...o,query:h.steps,target:l.steps,sequenceOf:c}).map(d=>({query:h.name,queryStart:h.start+d.queryStart,queryEnd:h.start+d.queryEnd,strand:d.strand,target:l.name,targetStart:l.start+d.targetStart,targetEnd:l.start+d.targetEnd,cigar:Eo(d.edits),matches:d.edits.reduce((p,[u,m])=>p+(u==="="?m:0),0),columns:d.edits.reduce((p,[,u])=>p+u,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=ye(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([r==="reverse"?1:0,O(s),z(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!z(r)){let o=O(r),s=`S ${o} ${this.record(r).sequence}
|
|
1
|
+
import{a as Ln,b as qs,c as Gr,d as zr}from"./chunk-B2UJRFGO.js";import{f as Hs,g as _n,h as Ce,i as kn,j as On,k as St,l as Nn,m as vt,o as Tn}from"./chunk-WV6GUYH7.js";import{a as Fn,b as $n}from"./chunk-6UUUO22M.js";import"./chunk-YPZ64NPV.js";import{a as Br}from"./chunk-KWAXLUPQ.js";import"./chunk-YBLNN5FU.js";import{e as bt,f as ze,g as Pn}from"./chunk-QU4UAKXZ.js";import"./chunk-E7J6SB5P.js";import{a as Ds,d as Hr,e as qr,f as Dr}from"./chunk-4T7DPQTR.js";import{a as ot}from"./chunk-J4OLMLS5.js";import{a as Bs,b as ce}from"./chunk-FY3BTKY4.js";var Cs=Bs((rd,As)=>{As.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function ye(n,e){return 2*n+(e==="reverse"?1:0)}function O(n){return Math.floor(n/2)}function je(n){return n%2===0?"forward":"reverse"}function z(n){return n%2===1}function re(n){return n%2===0?n+1:n-1}function jr(n){return n==="left"?"right":"left"}function It(n){return n==="forward"?"left":"right"}function Et(n){return n==="forward"?"right":"left"}function Ur(n){return n==="left"?"forward":"reverse"}function Wr(n){return n==="right"?"forward":"reverse"}function Ue(n,e){let t=O(n),r=O(e);return z(n)?r>t||r===t&&!z(e):r>=t}function st(n){return Fe(n[0],n[n.length-1])}function Fe(n,e){return n===void 0||e===void 0?!0:z(n)===z(e)?!z(n):Ue(n,e)}var it=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 r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},Vr=255,Gs=256,At=class{source;sigma;threshold;constructor(e,t){this.source=new it(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<Vr?Math.floor(Gs/this.sigma):0}next(){if(this.sigma>=Vr){let o=this.source.int(),s=this.source.int();return o===void 0||s===void 0?void 0:{value:o,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let o=this.source.int();if(o===void 0)return;r+=o}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Qr(n){let e=new it(n),t=e.int();if(t===void 0||t===0)return[];let r=[],o=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");o+=i,r.push({node:o,offset:a})}return r}var Ct=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new At(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(o=>o.offset),r=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(r+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[o.value]=i+o.len,r+=o.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let o=t+r>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:r=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(r+=s.len,r>e.offset))return o-(r-e.offset)}predecessorAt(e){let t=this.edges.map(o=>({node:o.node===0?0:re(o.node),count:0}));for(let o of this.runs()){let s=t[o.value];s&&(s.count+=o.len)}for(let o=1;o<t.length;o++){let s=t[o-1],i=t[o];O(s.node)===O(i.node)&&(t[o-1]=i,t[o]=s)}let r=0;for(let o of t)if(r+=o.count,r>e)return o.node===0?void 0:o.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),o=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:o}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let o=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:o.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var zs=["","A","C","G","T","N"];function Yr(n){let e=n[n.length-1];if(e===void 0)return 0;let t=e,r=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),r+=1;return 3*(n.length-1)+r}function Kr(n){let e="";for(let t of n){let r=t;for(let o=0;o<3;o++){let s=zs[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}var js={A:"T",C:"G",G:"C",T:"A",N:"N"};function Rt(n){let e="";for(let t=n.length-1;t>=0;t--)e+=js[n[t]]??"N";return e}var Us=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]),Ie=(n,e)=>n>>>e|n<<32-e;function Xr(n){let e=Math.ceil((n.length+9)/64),t=new Uint8Array(e*64);t.set(n),t[n.length]=128;let r=new DataView(t.buffer),o=n.length*8;r.setUint32(t.length-8,Math.floor(o/2**32)),r.setUint32(t.length-4,o>>>0);let s=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=new Uint32Array(64);for(let c=0;c<e;c++){for(let S=0;S<16;S++)i[S]=r.getUint32(c*64+S*4);for(let S=16;S<64;S++){let g=i[S-15],b=i[S-2],x=Ie(g,7)^Ie(g,18)^g>>>3,E=Ie(b,17)^Ie(b,19)^b>>>10;i[S]=i[S-16]+x+i[S-7]+E}let l=s[0],h=s[1],d=s[2],p=s[3],u=s[4],m=s[5],w=s[6],y=s[7];for(let S=0;S<64;S++){let g=Ie(u,6)^Ie(u,11)^Ie(u,25),b=u&m^~u&w,x=y+g+b+Us[S]+i[S]|0,E=Ie(l,2)^Ie(l,13)^Ie(l,22),A=l&h^l&d^h&d;y=w,w=m,m=u,u=p+x|0,p=d,d=h,h=l,l=x+E+A|0}[l,h,d,p,u,m,w,y].forEach((S,g)=>{s[g]=s[g]+S})}let a=new Uint8Array(32),f=new DataView(a.buffer);for(let c=0;c<8;c++)f.setUint32(c*4,s[c]);return a}function Zr(n,e){let t=new Map;if(n!==void 0)for(let r of n.split(";")){let o=r.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function to(n){return{name:n.get("pggname"),subgraph:Zr(n.get("subgraph"),"subgraph"),translation:Zr(n.get("translation"),"translation")}}function Jr(n,e){for(let[t,r]of e){let o=n.get(t);o||(o=new Set,n.set(t,o));for(let s of r)o.add(s)}}function no(n,e){let t={name:n,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(n,new Set([e.name])),Jr(t.subgraph,e.subgraph),Jr(t.translation,e.translation)),t}function eo(n){return[...n.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function ro(n){let e=[];n.name!==void 0&&e.push(`H NM:Z:${n.name}`);for(let[t,r]of eo(n.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of eo(n.translation))e.push(`H TL:Z:${t},${r}`);return e}async function oo(n){let e=n.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e),r=0;for(let i of n)t.set(i,r),r+=i.length;let o=globalThis.crypto?.subtle;return[...o?new Uint8Array(await o.digest("SHA-256",t)):Xr(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var Ws="_gbwt_ref";function me(n){let e=`${n.sample}#${n.haplotype}#${n.contig}`;return n.end===void 0?e:`${e}[${n.fragment}-${n.end}]`}var Vs=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Ys(n){let e=Vs.exec(n);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Qs.exec(n);if(t)return{contig:t[1]};throw new Error(`"${n}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(n){return typeof n=="string"?Ys(n):n}function Ve(n,e){return{sample:n.sample??Ws,contig:n.contig,haplotype:n.haplotype??0,fragment:e}}var Ks=4096;function Hn(n){let e=[];for(let t of n){let r=e[e.length-1];r&&t-r[1]<=Ks?r[1]=t:e.push([t,t])}return e}var Xs=32768,so={mostChosenPaths:32},Bn=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let r=this.byNode.get(e.node);r||(r=new Map,this.byNode.set(e.node,r)),r.set(e.offset,t)}},ie=class extends Error{};function Mt(n,e,t,r){return n==="forward"?e+t:e-r}function io(n,e,t,r){return n==="forward"?e-r:e+t}function ao(n){return Fe(re(n.handles[n.handles.length-1]),re(n.handles[0]))}function at(n){return`${n.pathHandle}:${n.hapStart}:${n.hapEnd}`}async function fo(n){let{db:e,records:t,signal:r}=n,o=performance.now(),s=()=>{let I=performance.now(),R=I-o;return o=I,R},i={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}},a=(I,R)=>{let k=`${I}: ${R}`;i.walks[k]=(i.walks[k]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async I=>{let R=t.get(I)??c.get(I);if(R)return R;let k=await e.getRecord(I);if(i.graphFetches+=1,!k)throw new Error(`Node record ${I} is missing from the database`);return c.set(I,k),k},h=I=>t.get(I).sequenceLen,d=await e.pathsByHandle(),p=I=>{let R=d.get(I);return R!==void 0&&n.keep(R.name)},u=[],m=new Bn,w=new Map,y=new Set,S=new Set,g=async I=>{let R=(await l(I.node)).gbwt().lf(I.offset);return R===void 0||R.node===0?void 0:R},b=async(I,R)=>{let k=(await l(re(I.node))).gbwt().predecessorAt(I.offset);if(k===void 0||R!==void 0&&!R.has(k))return;let L=(await l(k)).gbwt().offsetTo(I);if(L===void 0)throw new Error(`No offset in ${k} leads to ${I.node}:${I.offset}`);return{node:k,offset:L}},x=(I,R,k,L)=>{let H=k.map(V=>V.pos.node),W=k.map(V=>V.pos.offset),J=0;for(let V of H)J+=h(V);let B=R==="forward"?k[0].left:k[k.length-1].left,F=u.length;u.push({pathHandle:I,orientation:R,handles:H,offsets:W,len:J,hapStart:B,hapEnd:B+J,canonical:Fe(H[0],H[H.length-1]),source:L});for(let V of k)m.set(V.pos,F);let K=w.get(I);return K?K.push(F):w.set(I,[F]),F},E=async(I,R,k,L)=>{let H=[],W=I;for(;;){r?.throwIfAborted();let B=await b(W.pos,t);if(!B)break;W={pos:B,left:io(k,W.left,h(W.pos.node),h(B.node))},H.push(W)}H.reverse();let J=[I];for(W=I;;){r?.throwIfAborted();let B=await g(W.pos);if(!B||!t.has(B.node))break;W={pos:B,left:Mt(k,W.left,h(W.pos.node),h(B.node))},J.push(W)}return x(R,k,[...H,...J],L)},A=async(I,R,k,L)=>u[m.get(I.pos)??await E(I,R,k,L)],_=I=>{let R=I.handles[I.handles.length-1];return{pos:{node:R,offset:I.offsets[I.offsets.length-1]},left:I.orientation==="forward"?I.hapEnd-h(R):I.hapStart}},T=I=>{let R=I.handles[0];return{pos:{node:R,offset:I.offsets[0]},left:I.orientation==="forward"?I.hapStart:I.hapEnd-h(R)}},$=await E({pos:n.referencePos,left:n.referenceLeft},n.referenceHandle,"forward","reference"),C=u[$],N=()=>{if(i.fallback!==void 0)return{reference:C,pieces:[],stats:i};let I=new Map;u.forEach((k,L)=>{L!==$&&I.set(at(k),[...I.get(at(k))??[],k])});let R=[];for(let k of I.values()){let L=new Set;for(let H of k)H.canonical&&!L.has(H.orientation)&&(L.add(H.orientation),R.push(H),i.sources[H.source]+=1)}return i.sources.reference=1,i.pieces=R.length+1,{reference:C,pieces:R,stats:i}},P=async(I,R)=>{let k=R?y:S,L=R?S:y,H=I;for(;;){if(k.has(H))return;k.add(H);let W=u[H],J=R?_(W):T(W),B=0,F;for(;F===void 0;){r?.throwIfAborted();let K=R?await g(J.pos):await b(J.pos);if(!K){F="endmarker";break}let V=(await l(J.pos.node)).sequenceLen,ve=(await l(K.node)).sequenceLen,oe=R?Mt(W.orientation,J.left,V,ve):io(W.orientation,J.left,V,ve);if(t.has(K.node)){let ee=m.get(K);ee===void 0?(H=await E({pos:K,left:oe},W.pathHandle,W.orientation,"chain"),L.add(H),F="landed"):(L.add(ee),F="merge")}else B>Xs?F="bound":(B+=ve,J={pos:K,left:oe})}if(a("chain",F),F!=="landed")return}},U=async I=>{if(n.context>I.context)throw new ie(`the context of ${n.context} bp exceeds the ${I.context} bp the haplotype index's stray rows cover`);let R=i.spacing;if(R===void 0)throw new ie("the haplotype index has no anchors");let{bin:k,bound:L}=I,{fills:H,inserted:W}=n.snarls;if(n.snarls.mode==="overlapping"&&H.length>0)throw new ie("the haplotype index's stray rows cover contained snarls only");for(let v of H){if(v.inserted>0&&v.low===v.high)throw new ie(`the haplotype index's stray rows leave out the snarl bounded by node ${v.low} at both ends`);if(v.inserted>0&&(I.snarlNodes===void 0||v.nodes>I.snarlNodes))throw new ie(I.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${v.nodes} nodes exceeds the ${I.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(n.window.start/k),B=Math.floor((n.window.end-1)/k),F=J*k,K=(B+1)*k,V=new Map,ve=async(v,M)=>{let j=await e.haplotypeAnchorsBetween(n.referenceHandle,v*R,M*R);for(let D of j)V.set(D.anchorOffset/R,D)},oe=Math.max(0,Math.floor((F-L)/R)-1),ee=Math.ceil((K+L)/R)+1,[{listed:xt,strays:fe}]=await Promise.all([e.haplotypeBinData(n.referenceHandle,J,B),ve(oe,ee)]);for(let v of t.keys()){let M=O(v);if(!z(v)&&!xt(M)&&!W.has(M))throw new ie(`the haplotype index lists node ${M} of the subgraph in no bin that the window touches`)}i.scans=Hn([...t.keys()].sort((v,M)=>v-M));let de=Promise.all(i.scans.map(([v,M])=>e.haplotypeSamplesInRange(v,M)));for(de.catch(()=>{});oe>0&&(V.get(oe)?.pathOffset??Number.POSITIVE_INFINITY)>=F-L;)oe-=1,await ve(oe,oe);for(;V.has(ee)&&V.get(ee).pathOffset<=K+L;)ee+=1,await ve(ee,ee);let xe=[...V.keys()].sort((v,M)=>v-M),_e=V.get(xe[0]??-1);if(!_e)throw new ie("the haplotype index has no anchors on this path");let pe=v=>V.get(v).pathOffset,tt=new Map;for(let v of xe){let M=O(V.get(v).node);tt.set(M,[...tt.get(M)??[],v])}let Cn=[...tt.keys()],Rr=Cn.map(v=>V.get(tt.get(v)[0]).visits);if(!Rr[Cn.indexOf(O(_e.node))].some(v=>v.pathHandle===n.referenceHandle&&v.orientation==="forward"&&v.pathOffset===_e.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${n.referenceHandle} at offset ${_e.pathOffset} (node ${O(_e.node)}); it does not match this graph`);let Mr=xe.filter(v=>pe(v)<=n.window.start),Ts=xe.filter(v=>pe(v)>=n.window.end);i.anchors=[pe(Mr[Mr.length-1]??xe[0]),pe(Ts[0]??xe[xe.length-1])],i.anchorsRead=xe.length;let Rn=new Map,Pr=new Set;if(Cn.forEach((v,M)=>{let j=tt.get(v),D=j.length===1?j[0]:void 0;for(let G of Rr[M])Pr.add(G.pathHandle),G.orientation==="forward"&&p(G.pathHandle)&&Rn.set(G.pathHandle,[...Rn.get(G.pathHandle)??[],{k:D,row:G}])}),i.chosenPaths=[...Pr].filter(p).length,i.chosenPaths>so.mostChosenPaths)throw new ie(`${i.chosenPaths} chosen paths pass the anchors, more than ${so.mostChosenPaths}`);let yt=[],Le=Number.POSITIVE_INFINITY,ke=0;for(let[v,M]of Rn){M.sort((j,D)=>j.row.pathOffset-D.row.pathOffset);for(let j=0;j+1<M.length;j++){let D=M[j],G=M[j+1];if(D.k===void 0||G.k===void 0||Math.abs(D.k-G.k)!==1)continue;let[Z,te]=pe(D.k)<=pe(G.k)?[D,G]:[G,D],ne=pe(Z.k),se=pe(te.k);ne<K&&se>=F?(yt.push({pathHandle:v,from:D.row,to:G.row}),Le=Math.min(Le,ne-L),ke=Math.max(ke,se+L)):ne>=K&&ne-K<=L?(yt.push({pathHandle:v,from:Z.row,to:void 0}),Le=Math.min(Le,ne-L),ke=Math.max(ke,ne+L)):se<F&&F-se<=L&&(yt.push({pathHandle:v,from:te.row,to:void 0}),Le=Math.min(Le,se-L),ke=Math.max(ke,se+L))}}let Ls=new Set(H.map(v=>`${v.low}:${v.high}`)),Fs=fe.filter(v=>p(v.pathHandle)&&(v.snarl===void 0||Ls.has(`${v.snarl[0]}:${v.snarl[1]}`))).sort((v,M)=>v.pathHandle-M.pathHandle||v.pathStart-M.pathStart);i.strays={bins:B-J+1,rows:fe.length,walked:0,outsideBp:0},ke>0&&await n.prefetchReferenceRange(n.referenceHandle,Math.max(0,Le),ke+1),i.ms.scan=s();let _r=8*R+2*(n.window.end-n.window.start),kr=i.strays,nt=0,Or=v=>{if(kr.outsideBp+=v,nt+=v,nt>_r)throw new ie(`a walk of a chosen path near the window went past its cap of ${_r} bp`)},Mn=new Map,Nr=(v,M,j)=>(Mn.get(v)??[]).some(([D,G])=>D<=M&&j<G),Tr=(v,M,j)=>{Mn.set(v,[...Mn.get(v)??[],[M,j]])},Lr=async(v,M,j,D,G)=>{let Z=M,te=j,ne=te;for(;Z&&te<=D;){r?.throwIfAborted();let se;if(t.has(Z.node)){let rt=await A({pos:Z,left:te},v,"forward",G),$r=_(rt);Z=$r.pos,te=$r.left,se=h(Z.node),ne=Math.max(ne,rt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Or(se),ne=Math.max(ne,te+se);Z=await g(Z),te+=se}return ne},$s=async(v,M,j,D)=>{let G={pos:M,left:j},Z=j;for(;G.left>D;){r?.throwIfAborted();let te=await b(G.pos);if(!te)break;let ne=(await l(te.node)).sequenceLen,se=G.left-ne;if(t.has(te.node)){let rt=await A({pos:te,left:se},v,"forward","section");G=T(rt),Z=Math.min(Z,rt.hapStart)}else Or(ne),G={pos:te,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:v,from:M,to:j}of yt){let D=M.pathOffset,G=(j??M).pathOffset+L;if(Nr(v,D-L,G))continue;let Z={node:M.node,offset:M.offset};nt=0;let te=await Lr(v,Z,D,G,"section");nt=0;let ne=await $s(v,Z,D,D-L);Tr(v,Math.min(ne,D-L),Math.max(te,G+1)),a(j?"section":"visit",j?"past the far anchor":"bound")}for(let v of Fs){if(Nr(v.pathHandle,v.pathStart,v.pathEnd))continue;nt=0;let M=await Lr(v.pathHandle,{node:v.node,offset:v.offset},v.pathStart,v.pathEnd,"stray");Tr(v.pathHandle,v.pathStart,Math.max(M,v.pathEnd+1)),kr.walked+=1}i.ms.walks=s();let Fr=[];for(let v of await de)for(let M of v)if(i.scanRows+=1,t.has(M.node)&&p(M.pathHandle)){if(!(w.get(M.pathHandle)??[]).some(j=>{let D=u[j];return D.hapStart<=M.pathOffset&&M.pathOffset<D.hapEnd}))throw new ie(`chosen path ${M.pathHandle} has a sample at ${M.pathOffset} on the window's nodes that no walk reached`);M.orientation==="reverse"&&Fr.push(M)}for(let v of Fr)await A({pos:{node:v.node,offset:v.offset},left:v.pathOffset},v.pathHandle,"reverse","twin");i.ms.check=s()},Y=async()=>{let I=new Map,R=B=>{let F=at(B),K=I.get(F);K?K.add(B.orientation):I.set(F,new Set([B.orientation]))},k=0,L=()=>{for(;k<u.length;k++)R(u[k])};L();let H=B=>(I.get(at(B))?.size??0)>1,W=2*f,J=(B,F)=>F===$?p(n.referenceHandle)&&ao(B):!B.canonical||ao(B);for(let B=0;B<u.length;B++){let F=u[B];if(H(F)||!J(F,B))continue;i.twins.tried+=1;let K=F.orientation==="forward"?"reverse":"forward",V=_(F),ve=0,oe;for(;!oe&&ve<=W;){r?.throwIfAborted();let fe=await g(V.pos);if(!fe)break;let de=(await l(fe.node)).sequenceLen,xe=Mt(F.orientation,V.left,(await l(V.pos.node)).sequenceLen,de),_e=re(fe.node);oe=(await e.haplotypeSamplesInRange(_e,_e)).find(pe=>pe.pathHandle===F.pathHandle&&pe.orientation===K&&pe.pathOffset===xe),ve+=de,V={pos:fe,left:xe}}let ee=oe&&{pos:{node:oe.node,offset:oe.offset},left:oe.pathOffset},xt=0;for(;ee&&!H(F)&&xt<=W+F.len;){if(r?.throwIfAborted(),t.has(ee.pos.node)){let fe=await A(ee,F.pathHandle,K,"twin"),de=u.indexOf(fe);await P(de,!0),await P(de,!1),L(),ee=_(fe)}if(!H(F)){let fe=(await l(ee.pos.node)).sequenceLen;xt+=fe;let de=await g(ee.pos);ee=de?{pos:de,left:Mt(K,ee.left,fe,(await l(de.node)).sequenceLen)}:void 0}}if(L(),!H(F))throw new ie(`piece ${at(F)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let I=await e.haplotypeStrayOptions();if(I===void 0)throw new ie("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await U(I),await Y()}catch(I){if(!(I instanceof ie))throw I;i.fallback=I.message}return N()}function co(n,e){return n.handles[0]-e.handles[0]||n.offsets[0]-e.offsets[0]}function Pt(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]<e?t=o+1:r=o}return t}var _t=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let o=this.tree[r];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let o=this.tree[r];(o===-1||t>this.ending[o])&&(this.tree[r]=e)}}},qn=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,r,o){let s=0;for(;e+s<t&&r+s<o&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&o-i>r+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,o-i);for(let a=i;a>0;a--)this.match(t-a,o-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,o){if(e===t||r===o)return;let s=this.matchCount(e,t,r,o);if(s===0)return;if(s<=t-e+(o-r)){this.chain(e,t,r,o,s);return}let i=e+t>>1,a=this.split(e,i,t,r,o);this.solve(e,i,r,a),this.solve(i,t,a,o)}matchCount(e,t,r,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Pt(a,o)-Pt(a,r))}return s}sweep(e,t,r,o,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),h=Pt(c,o),d=Pt(c,s);for(let p=0;p<d-h;p++){let u=r===1?c[d-1-p]-o:s-1-c[h+p],m=i.bestBefore(u),w=(m===-1?0:i.ending[m])+l;if(w>i.ending[u]&&(i.raise(u,w),a)){let y=a.count++;a.row[y]=f,a.column[y]=u,a.previous[y]=m===-1?-1:a.endingMatch[m],a.endingMatch[u]=y}}}}chain(e,t,r,o,s){let i=new _t(o-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-r),count:0};this.sweep(e,t,1,r,o,i,a);let f=i.bestBefore(o-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,o,s){let i=new _t(s-o);this.sweep(e,t,r,o,s,i);let a=new Float64Array(s-o+1);for(let f=0;f<s-o;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(r-1,t-1,-1,o,s),c=0,l=-1;for(let h=0;h<=i;h++){let d=a[h]+f[i-h];d>l&&(l=d,c=h)}return o+c}};function lo(n,e,t){let r=new qn(n,e,t);return r.solve(0,n.length,0,e.length),[r.pairs,r.total]}var Zs=100,zn=4e6,Js=5e3,le=15,ei=64,ti=8,xo=1,jn=-4,ae=-6,Re=-1,Qe=-(2**30),Ot=0,Dn=1,yo=2;function $e(n,e,t){let r=n.at(-1);t>0&&(r?.[0]===e?r[1]+=t:n.push([e,t]))}function kt(n,e,t){return n>=t&&n>=e?Ot:t>=e?yo:Dn}function bo(n,e,t){let r=n.length,o=e.length,s=o+1,i=new Uint8Array((r+1)*s),a=new Int32Array(s).fill(Qe),f=new Int32Array(s).fill(Qe),c=new Int32Array(s).fill(Qe);a[0]=0;for(let u=1;u<=o;u++)c[u]=ae+(u-1)*Re,i[u]=(u===1?Ot:yo)<<4;for(let u=1;u<=r;u++){let m=new Int32Array(s).fill(Qe),w=new Int32Array(s).fill(Qe),y=new Int32Array(s).fill(Qe);w[0]=ae+(u-1)*Re,i[u*s]=(u===1?Ot:Dn)<<2;let S=n.charCodeAt(u-1);for(let g=1;g<=o;g++){let b=kt(a[g-1],f[g-1],c[g-1]);m[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?xo:jn);let x=kt(a[g]+ae,f[g]+Re,c[g]+ae);w[g]=Math.max(a[g]+ae,f[g]+Re,c[g]+ae);let E=kt(m[g-1]+ae,w[g-1]+ae,y[g-1]+Re);y[g]=Math.max(m[g-1]+ae,w[g-1]+ae,y[g-1]+Re),i[u*s+g]=b|x<<2|E<<4}a=m,f=w,c=y}let l=[],h=r,d=o,p=kt(a[o],f[o],c[o]);for(;h>0||d>0;){let u=i[h*s+d]>>2*p&3;p===Ot?(l.push(n[h-1]===e[d-1]?"=":"X"),h-=1,d-=1):p===Dn?(l.push("I"),h-=1):(l.push("D"),d-=1),p=u}for(let u of l.reverse())$e(t,u,1)}function ni(n,e){let t=Math.abs(n-e);return(t===0?0:Math.min(-ae-(t-1)*Re,-ae+10*Math.log2(t)))+(Math.min(n,e)>0?-jn:0)}function So(n,e){let t=Math.abs(n-e);return t===0?0:.01*le*t+.5*Math.log2(t)}function ho(n,e,t){return{qs:n.qs+e,qe:n.qs+t,ts:n.flipped?n.te-t:n.ts+e,te:n.flipped?n.te-e:n.ts+t,flipped:n.flipped}}function ri(n,e,t){let r=n.qe-n.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-n.qs),l=Math.min(r,f-n.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,n.flipped?n.te-f:a-n.ts),l=Math.min(r,n.flipped?n.te-a:f-n.ts);c<l&&o.push([c,l])}if(o.length===0)return[n];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=le&&s.push(ho(n,i,a)),i=Math.max(i,f);return r-i>=le&&s.push(ho(n,i,r)),s}function Un(n,e,t,r,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...n].sort((c,l)=>c.qs-l.qs||c.ts-l.ts);for(;f.length>0&&s.length<o;){let c=f.map(g=>g.qe-g.qs),l=new Int32Array(f.length).fill(-1),h=new Int32Array(f.length);for(let g=0;g<f.length;g++){let b=f[g],x=b.qe-b.qs;for(let E=g-1;E>=Math.max(0,g-Js);E--){if(c[E]+x<=c[g])continue;let A=f[E];if(A.flipped===b.flipped&&A.qs<b.qs&&(b.flipped?b.te<A.te:A.ts<b.ts)){let T=Math.max(0,A.qe-b.qs,b.flipped?b.te-A.ts:A.te-b.ts),$=b.qs+T-A.qe,C=b.flipped?A.ts-(b.te-T):b.ts+T-A.te;if(T<x&&$<=e&&C<=e){let N=c[E]+x-T-r($,C);N>c[g]&&(c[g]=N,l[g]=E,h[g]=T)}}}}let d=new Int32Array(f.length),p=-1;for(let g=0;g<f.length;g++){let b=f[g];d[g]=(d[l[g]]??0)+b.qe-b.qs-h[g],d[g]>=t&&(p<0||c[g]>c[p])&&(p=g)}if(p<0)break;let u=[];for(let g=p;g>=0;g=l[g])u.push({run:f[g],trim:h[g]});u.reverse(),s.push(u);let m=u[0],w=u.at(-1),{flipped:y}=m.run,S=y?a.flipped:a.forward;S.query.push([m.run.qs+m.trim,w.run.qe]),S.target.push(y?[w.run.ts,m.run.te-m.trim]:[m.run.ts+m.trim,w.run.te]);for(let{run:g,trim:b}of u)i.query.push([g.qs+b,g.qe]),i.target.push(g.flipped?[g.ts,g.te-b]:[g.ts+b,g.te]);f=f.flatMap(g=>{let b=g.flipped?a.flipped:a.forward;return ri(g,[...i.query,...b.query],[...i.target,...b.target])}).sort((g,b)=>g.qs-b.qs||g.ts-b.ts)}return s}function Gn(n,e){let t=new Map;for(let s=0;s+le<=e.length;s++){let i=e.slice(s,s+le),a=t.get(i);a?a.push(s):t.set(i,[s])}let r=[],o=new Map;for(let s=0;s+le<=n.length;s++){let i=t.get(n.slice(s,s+le));if(i&&i.length<=ei)for(let a of i){let f=a-s,c=o.get(f);if(c&&s<=c.qe)c.qe=s+le,c.te=a+le;else{let l={qs:s,qe:s+le,ts:a,te:a+le,flipped:!1};o.set(f,l),r.push(l)}}}return r}function oi(n,e){return[...Gn(n,e),...Gn(n,Rt(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Nt(n,e,t,r,o){let s;for(let{run:i,trim:a}of n){let f=i.qs+a;if(s){let c=i.flipped?i.te-a:s.te,l=i.flipped?s.ts:i.ts+a,h=t.slice(c,l);o(e.slice(s.qe,f),i.flipped?Rt(h):h,r,s.qe,c)}$e(r,"=",i.qe-f),s=i}}function Wn(n,e,t){$e(t,"I",n.length),$e(t,"D",e.length)}function vo(n,e,t){n.length*e.length<=zn?bo(n,e,t):Wn(n,e,t)}function Vn(n,e,t,r=0){let[o]=n.length*e.length>zn&&r<ti?Un(Gn(n,e),1/0,le,So,1):[];if(!o){vo(n,e,t);return}let s=(f,c,l)=>{Vn(f,c,l,r+1)},i=o[0].run,a=o.at(-1).run;s(n.slice(0,i.qs),e.slice(0,i.ts),t),Nt(o,n,e,t,s),s(n.slice(a.qe),e.slice(a.te),t)}function si(n,e,t){Vn(n,e,t)}function ii(n,e,t){let r=[];Nt(n,e,t,r,si);let o=n[0],s=n.at(-1),{flipped:i}=o.run;return{queryStart:o.run.qs+o.trim,queryEnd:s.run.qe,targetStart:i?s.run.ts:o.run.ts+o.trim,targetEnd:i?o.run.te-o.trim:s.run.te,strand:i?"-":"+",edits:i?r.reverse():r,sharedBases:0}}function ai(n,e,t,r){let o=[];if(n.length*e.length<=zn)bo(n,e,t);else{let s=Un(oi(n,e),1/0,Math.max(r,le),So),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>ii(a,n,e)),i){let a=(l,h,d,p,u)=>{o.some(w=>p<w.queryEnd&&w.queryStart<p+l.length||u<w.targetEnd&&w.targetStart<u+h.length)?vo(l,h,d):Vn(l,h,d)},f=i[0].run,c=i.at(-1).run;a(n.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Nt(i,n,e,t,a),a(n.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else Wn(n,e,t)}return o}function Qn(n,e){let t=n.strand==="-",r=0,o=0;for(let[s,i]of n.edits)e(s,i,t?n.queryEnd-1-r:n.queryStart+r,n.targetStart+o),s!=="D"&&(r+=i),s!=="I"&&(o+=i)}function po(n,e,t,r){let o=e==="query"&&n.strand==="-"?-1:1,s=0;return Qn(n,(i,a,f,c)=>{let l=e==="query"?f:c,h=d=>{let p=l+o*d;return p>=t&&p<r};if(i==="="||i==="X")for(let d=0;d<a;d++)h(d)&&(s+=i==="="?xo:jn);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)h(d)&&(s+=d===0?ae:Re);else h(0)&&(s+=ae+(a-1)*Re)}),s}function uo(n,e){return e==="query"?[n.queryStart,n.queryEnd]:[n.targetStart,n.targetEnd]}function fi(n,e){let t=n.strand==="-",r=[],o=0,s=0,i=0,a=0,f=new Uint8Array(n.queryEnd-n.queryStart);for(let[p,u]of n.shared)f.fill(1,p-n.queryStart,u-n.queryStart);let c=p=>f[p-n.queryStart]===1,l=()=>{$e(r,"I",o),$e(r,"D",s),o=0,s=0};Qn(n,(p,u,m)=>{if(p==="I")o+=u;else if(p==="D")s+=u;else{for(let w=0;w<u;w++)e[i+w]?(o+=1,s+=1,c(t?m-w:m+w)&&(a+=1)):((o>0||s>0)&&l(),$e(r,p,1));i+=u}}),l();let h={I:0,D:0};for(;r[0]?.[0]==="I"||r[0]?.[0]==="D";){let[p,u]=r.shift();h[p]+=u}let d={I:0,D:0};for(;r.at(-1)?.[0]==="I"||r.at(-1)?.[0]==="D";){let[p,u]=r.pop();d[p]+=u}return r.length===0?void 0:{...n,queryStart:n.queryStart+(t?d.I:h.I),queryEnd:n.queryEnd-(t?h.I:d.I),targetStart:n.targetStart+h.D,targetEnd:n.targetEnd-d.D,edits:r,sharedBases:n.sharedBases-a}}function ci(n,e,t,r){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=n.map(c=>{let l=[];Qn(c,(h,d,p,u)=>{if(h==="="||h==="X")for(let m=0;m<d;m++)l.push([c.strand==="-"?p-m:p+m,u+m])});for(let[h,d]of l)o.query[h]=Math.min(255,o.query[h]+1),o.target[d]=Math.min(255,o.target[d]+1);return l}),i={query:new Map,target:new Map};s.forEach((c,l)=>{for(let[h,d]of c)for(let[p,u]of[["query",h],["target",d]])if(o[p][u]>1){let m=i[p].get(u);m?m.at(-1)!==l&&m.push(l):i[p].set(u,[l])}});let a=new Map,f=(c,l,h)=>{let d=`${h}:${c}:${l}`,p=a.get(d);if(p===void 0){let[u,m]=uo(n[c],h),[w,y]=uo(n[l],h),S=Math.max(u,w),g=Math.min(m,y),[b,x]=[n[c],n[l]];p=[po(x,h,S,g)-po(b,h,S,g),x.sharedBases-b.sharedBases,c-l].find(A=>A!==0)>0,a.set(d,p)}return p};return n.flatMap((c,l)=>{let h=s[l],d=new Uint8Array(h.length);if(h.forEach(([m,w],y)=>{for(let[S,g]of[["query",m],["target",w]])!d[y]&&i[S].get(g)?.some(b=>b!==l&&f(l,b,S))&&(d[y]=1)}),!d.includes(1))return[c];let p=fi(c,d),u=p?.edits.reduce((m,[w,y])=>m+(w==="="?y:0),0)??0;return p&&u>=r?[p]:[]})}function mo(n,e){return n.map(t=>{let r=e(O(t));return z(t)?Rt(r):r}).join("")}function go(n,e){let t=[0];for(let r of n)t.push(t.at(-1)+e(O(r)).length);return t}function wo(n){let e=new Map,t=new Map;n.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let r=new Int32Array(n.length+1);for(let[i,a]of t)r[e.get(i)]+=1,r[a+1]-=1;let o=new Uint8Array(n.length),s=0;for(let i=0;i<n.length;i++)s+=r[i],o[i]=s>0?1:0;return o}function li(n,e,t,r){let o=wo(n),s=wo(e),i=new Map;e.forEach((h,d)=>{s[d]||i.set(O(h),[d])});let a=2*e.length,f=(h,d,p)=>h*a+2*d+(p?1:0),c=new Set;n.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[])c.add(f(d,p,z(h)!==z(e[p])))});let l=[];return n.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[]){let u=z(h)!==z(e[p]),m=u?-1:1,w=p-m;if(!(d>0&&w>=0&&w<e.length&&c.has(f(d-1,w,u)))){let S=d,g=p;for(;S<n.length&&g>=0&&g<e.length&&c.has(f(S,g,u));)S+=1,g+=m;let b=g-m;l.push({qs:t[d],qe:t[S],ts:r[Math.min(p,b)],te:r[Math.max(p,b)+1],flipped:u})}}}),l}function Io(n){let{query:e,target:t,sequenceOf:r}=n,o=mo(e,r),s=mo(t,r),i=li(e,t,go(e,r),go(t,r)),a=n.minMatch??Zs,f=n.bases??!0,c=[];for(let l of Un(i,n.maxGap??1/0,a,ni)){let h=[],d=l[0],p=l.at(-1),{flipped:u}=d.run;Nt(l,o,s,h,f?(w,y,S,g,b)=>{for(let x of ai(w,y,S,a)){let E=b+y.length;c.push({...x,queryStart:g+x.queryStart,queryEnd:g+x.queryEnd,targetStart:u?E-x.targetEnd:b+x.targetStart,targetEnd:u?E-x.targetStart:b+x.targetEnd,strand:u?"+":"-",edits:u?x.edits.reverse():x.edits,shared:[]})}}:Wn),c.push({queryStart:d.run.qs+d.trim,queryEnd:p.run.qe,targetStart:u?p.run.ts:d.run.ts+d.trim,targetEnd:u?d.run.te-d.trim:p.run.te,strand:u?"-":"+",edits:u?h.reverse():h,sharedBases:l.reduce((w,{run:y,trim:S})=>w+y.qe-y.qs-S,0),shared:l.map(({run:w,trim:y})=>[w.qs+y,w.qe])})}return ci(c,o.length,s.length,a).map(({shared:l,...h})=>h).sort((l,h)=>l.queryStart-h.queryStart)}function Eo(n){return n.map(([e,t])=>`${t}${e}`).join("")}var be=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 Yn(n,e){return n[0]<e[0]||n[0]===e[0]&&(n[1]<e[1]||n[1]===e[1]&&n[2]<e[2])}var ct=class{heap=[];push(e,t,r){let o=this.heap;o.push([e,t,r]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Yn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Yn(e[s],e[a])&&(a=s),i<e.length&&Yn(e[i],e[a])&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}}return t}get size(){return this.heap.length}};function hi(n){let e=new Int32Array(n.length),t=new Int32Array(n.length);return n.forEach(([r,o],s)=>{e[s]=r,t[s]=o}),{pathAt:e,refAt:t,count:n.length}}function di(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>1;n[o]>e?r=o:t=o+1}return n[t]}function Be(n){return`${n.node}:${n.offset}`}function ft(n){return n.map(e=>re(e)).reverse()}function pi(n,e){let t=e.identity.hapStart-n.identity.hapEnd,r=n.strand==="+"?e.refStart-n.refEnd:n.refStart-e.refEnd;return n.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function ui(n,e,t){let[r,o]=n.strand==="+"?[n,e]:[e,n],s=r.edits.map(([c,l])=>[c,l]);Co(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=n.identity.walkForward,[a,f]=i?[n,e]:[e,n];return{strand:n.strand,refStart:r.refStart,refEnd:o.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,pieces:[...a.pieces,...f.pieces],soloAligned:[...a.soloAligned,...f.soloAligned],identity:{pathHandle:n.identity.pathHandle,name:n.identity.name,hapStart:n.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function mi(n,e,t){if(n.some(i=>i.weight!==void 0))return n;let r=new Map;n.forEach((i,a)=>{if(i.identity){let f=r.get(i.identity.pathHandle);f?f.push(a):r.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of r.values()){i.sort((l,h)=>n[l].identity.hapStart-n[h].identity.hapStart);let a=i[0],f=n[a],c=[];for(let l of i.slice(1)){let h=n[l],d=c.length===0?pi(f,h):void 0;if(d){f=ui(f,h,d),s.add(l);continue}if(!e(h)){c.push(l);continue}let p=e(f)?t([f,...c.map(u=>n[u]),h]):void 0;if(p){f=p;for(let u of[...c,l])s.add(u)}else o.set(a,f),a=l,f=h;c=[]}o.set(a,f)}return n.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Tt(n,e){return{node:n.path[e],offset:n.offsets[e]}}var gi=32768;function wi(n){let e=[...n].sort((r,o)=>r-o),t=[];for(let r of e){let o=t[t.length-1];o&&r-o[1]<=gi?o[1]=r:t.push([r,r])}return t}var $t=class n{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 n(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(ye(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 be(this.limit);let t=await this.db.getRecord(ye(e,"forward")),r=await this.db.getRecord(ye(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}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 ${me(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${me(t.name)} at ${t.name.fragment} has not been indexed for random access`);let r=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,r);if(!o)throw new Error(`The fragment of ${me(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,r,o.pathOffset,o.pos)}async findPathPosition(e,t,r,o){let s=r,i=o;for(;;){await this.ensureNode(O(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`The fragment of ${me(e.name)} at ${e.name.fragment} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let o=O(e);await this.ensureNode(o);let s=this.record(e),i=je(e),a=new ct;return a.push(t,o,It(i)),a.push(s.sequenceLen-t-1,o,Et(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(o&&s){let i=o.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords([[Math.min(i,a),Math.max(i,a)+1]])){let c=await this.db.indexedPositionsBetween(e,t,r);await this.db.prefetchRecords(wi(c.map(l=>l.pos.node)).map(([l,h])=>[l,h+2]),!0)}}return o}async aroundInterval(e,t,r){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(o){throw o instanceof be&&o.windowBp===void 0?new be(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let o={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new ct;for(;;){let f=O(o.node),c=je(o.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(o.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,It(c));let h=l.sequenceLen-s;if(i<=h){a.push(i===h?0:h-i-1,f,Et(c));break}a.push(0,f,Et(c));let d=l.gbwt().lf(o.offset);if(!d)throw new Error(`No successor for GBWT position (${o.node}, ${o.offset})`);o=d,s=0,i-=h}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new ct;for(let o of e)await this.ensureNode(o),r.push(0,o,"left"),r.push(0,o,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let r=new Set,o=new Set;for(let i of this.records.keys())o.add(O(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=jr(f);if(!r.has(`${a}:${l}`)){let p=this.record(ye(a,Ur(f))),u=i+p.sequenceLen-1;u<=t&&e.push(u,a,l)}let h=this.record(ye(a,Wr(f))),d=i+1;if(d<=t)for(let p of h.successors()){let u=O(p),m=It(je(p));r.has(`${u}:${m}`)||e.push(d,u,m)}}for(let i of o)this.records.delete(ye(i,"forward")),this.records.delete(ye(i,"reverse"));return{inserted:s,removed:o.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let r=[e,re(t)],o=new Set([O(e),O(t)]),s=[];for(;r.length>0;){let i=r.pop(),a=O(i);this.hasNode(a)||(await this.addNode(a),s.push(a));for(let f of this.record(i).successors()){let c=O(f);o.has(c)||(r.push(f,re(f)),o.add(c))}}return{inserted:s,nodes:o.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[r,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(r,o),a=O(r),f=O(o);this.snarlFills.push({low:Math.min(a,f),high:Math.max(a,f),nodes:i,inserted:s.length});for(let c of s)this.snarlNodes.add(c);t+=s.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(o=>this.hasHandle(o));return r===void 0?!1:t.length>1||this.record(re(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let o=this.records.get(r);if(o)return o;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(re(l))).successors().length>1},r=async f=>{let c=await e(re(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[re(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},o=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=O(f);if(!this.hasHandle(f)&&!o.has(c)){o.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let h of["forward","reverse"])s.push(...(await e(ye(c,h))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((x,E)=>i.set(x,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let x=0;x<s;x++){let E=this.record(o[x]),A=E.gbwt().decompressArrays();f[x]=E.sequenceLen,c.push(A),a[x+1]=a[x]+A.nodes.length}let l=a[s],h=new Int32Array(l),d=new Int32Array(l),p=new Uint8Array(l);for(let x=0;x<s;x++){let E=c[x];h.set(E.nodes,a[x]),d.set(E.offsets,a[x])}c.length=0;for(let x=0;x<l;x++){let E=i.get(h[x]);E===void 0?h[x]=-1:(h[x]=E,p[a[E]+d[x]]=1)}let u=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,w,y=(x,E,A)=>{let _=[],T=0,$=0,C=-1,N=x,P=E;for(;;){N===u&&P===m&&(C=T),A&&(A.push(o[N]),_.push(P)),T+=1,$+=f[N];let U=a[N]+P,Y=h[U];if(Y<0)break;P=d[U],N=Y}return{offsets:_,len:$,refAt:C,last:N}},S=(x,E,A,_)=>{_>=0&&(this.refId=this.paths.length,w=_),this.paths.push({path:x,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let x=0;x<s;x++){let E=o[x];if(!z(E)){let A=a[x],_=a[x+1]-A;for(let T=0;T<_;T++)if(p[A+T]===0){let $=[],{offsets:C,len:N,refAt:P,last:U}=y(x,T,$),Y=o[U];if(P>=0||Fe(E,Y)){if(S($,C,N,P),!z(Y)){let I=i.get(re(Y));g[I]=g[I]+1}}else this.twinStarts.add(Be({node:E,offset:T}))}}}for(let x=0;x<s;x++){let E=o[x];if(z(E)){let A=a[x],_=a[x+1]-A,T=0;for(let C=0;C<_;C++)p[A+C]===0&&(T+=1);let $=(u===void 0||w!==void 0)&&T===g[x];for(let C=0;C<_;C++)if(p[A+C]===0){let N=$?void 0:y(x,C,void 0);if(N&&(N.refAt>=0||Fe(E,o[N.last]))){let P=[],{offsets:U,len:Y,refAt:I}=y(x,C,P);S(P,U,Y,I)}else this.twinStarts.add(Be({node:E,offset:C}))}}}let b=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((x,E)=>x.path[0]-E.path[0]||x.offsets[0]-E.offsets[0]),b&&(this.refId=this.paths.indexOf(b)),r){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let x=this.paths[this.refId],E=r.nodeOffset;for(let _ of x.path.slice(0,w))E+=this.record(_).sequenceLen;let A=r.seqOffset-E;this.refInterval=[A,A+x.len],x.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+x.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],r=t?.path,o=r&&!st(r)?ft(r):void 0,s=c=>o!==void 0&&Kn(c,o)===0||st(ft(c)),i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>Kn(c.path,l.path)||c.len-l.len||(c===t?-1:l===t?1:0));let a=[],f;for(let c of this.paths){let l=a[a.length-1],h=i&&c!==t&&s(c.path);this.twinDeferred||=h,l&&Kn(l.path,c.path)===0&&!h?l.weight=(l.weight??1)+(c.weight??1):(c===t&&(f=a.length),a.push({...c,weight:c.weight??1}))}this.paths=a,this.refId=f}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,r=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(r({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(r(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(r(i.identity)));s.length<this.paths.length&&(this.paths=s,this.refId=e===void 0?void 0:s.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(i=>i.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((i,a)=>a!==this.refId&&i.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 r=this.refId===void 0?void 0:this.paths[this.refId],o=this.paths.filter((i,a)=>a===this.refId||i.identity!==void 0&&e(i.identity.name)),s=new Set;for(let i of o)for(let a of i.path)s.add(O(a));for(let i of[...this.records.keys()])s.has(O(i))||this.records.delete(i);this.paths=o,this.refId=r===void 0?void 0:o.indexOf(r)}async extractChosenPaths(e,t,r,o){this.clearPaths();let s=e.position.seqOffset,i=await fo({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:s-e.position.nodeOffset,window:{start:s,end:s+t},context:o,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:r,signal:this.signal,prefetchReferenceRange:(l,h,d)=>this.prefetchReferenceRange(l,h,d)});if(this.stats.keep=i.stats,i.stats.fallback!==void 0)return!1;let a=await this.db.pathsByHandle(),f=l=>({path:l.handles,offsets:l.offsets,len:l.len,weight:void 0,identity:{pathHandle:l.pathHandle,name:l===i.reference?e.name:a.get(l.pathHandle).name,orientation:l.orientation,hapStart:l.hapStart,hapEnd:l.hapEnd}}),c=[i.reference,...i.pieces].sort(co);return this.paths=c.map(f),this.refId=c.indexOf(i.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[i.reference.hapStart,i.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=Hn(this.sortedHandles());if(t.length===0)return;let r=new Map,o=await Promise.all(t.map(([m,w])=>this.db.haplotypeSamplesInRange(m,w)));for(let m of o.flat())r.set(Be(m),m);let s=m=>{let w=0,y=t.length-1;for(;w<y;){let g=w+y+1>>1;t[g][0]<=m?w=g:y=g-1}let S=t[w];return S[0]<=m&&m<=S[1]},i=new Map;this.paths.forEach((m,w)=>{m.path.length>0&&w!==this.refId&&i.set(Be(Tt(m,0)),w)});let a=this.stats.identification;a.interval=e,a.scans=t,a.windowSamples=r.size,this.paths.forEach((m,w)=>{w!==this.refId&&a.fragmentLengths.push(m.len)});let f=this.recordReader(()=>{this.stats.identificationFetches+=1,a.graphFetches+=1}),c=m=>(a.graphLookups+=1,f(m)),l=async(m,w)=>{if(s(m.node))return r.get(Be(m));this.stats.identificationFetches+=1,a.companionSeeks+=1,w.seeks+=1;let y=await this.db.haplotypeSampleAt(m.node,m.offset);return y||(a.companionMisses+=1),y},h=new Map,d=async m=>{let w=h.get(m);if(!w){let y=await this.db.getPath(m);if(!y)throw new Error(`Path ${m} is missing from the database`);w=y.name,h.set(m,w)}return w},p=(m,w,y)=>m.orientation==="forward"?{pathHandle:m.pathHandle,orientation:"forward",base:m.pathOffset-w}:{pathHandle:m.pathHandle,orientation:"reverse",base:m.pathOffset+w+y},u=(m,w)=>m.orientation==="forward"?{pathHandle:m.pathHandle,orientation:"forward",base:m.hapStart-w}:{pathHandle:m.pathHandle,orientation:"reverse",base:m.hapEnd+w};for(let m=0;m<this.paths.length;m++){let w=this.paths[m];if(m===this.refId||w.identity)continue;let y=[],S=new Set,g={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};a.chains.push(g);let b,x=0,E=m,A;for(;b===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){g.end="cycle";break}S.add(E);let N=this.paths[E];y.push({index:E,startBp:x}),g.fragments+=1;let P=x;for(let Y=0;Y<N.path.length;Y++){let I=Tt(N,Y),R=r.get(Be(I)),k=this.record(I.node).sequenceLen;if(R){b=p(R,P,k);break}P+=k}if(x+=N.len,b){g.end="in-fragment sample";break}let U=Tt(N,N.path.length-1);A=this.record(U.node).gbwt().lf(U.offset),E=void 0}if(A===void 0||A.node===0){g.end="endmarker";break}let _=Be(A),T=i.get(_);if(T!==void 0){let N=this.paths[T].identity;if(N){b=u(N,x),g.end="identified sibling";break}E=T;continue}this.records.has(A.node)&&(g.reentries+=1),this.twinStarts.has(_)&&(g.twinLandings+=1);let $=await l(A,g),C=await c(A.node);if($){b=p($,x,C.sequenceLen),g.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,g.steps+=1,x-y[y.length-1].startBp>4*e+4*C.sequenceLen){g.end="bound";break}x+=C.sequenceLen,A=C.gbwt().lf(A.offset)}if(b){g.pathHandle=b.pathHandle;let _=await d(b.pathHandle);for(let{index:T,startBp:$}of y){let C=this.paths[T];C.identity=b.orientation==="forward"?{pathHandle:b.pathHandle,name:_,orientation:"forward",hapStart:b.base+$,hapEnd:b.base+$+C.len}:{pathHandle:b.pathHandle,name:_,orientation:"reverse",hapStart:b.base-$-C.len,hapEnd:b.base-$}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,o)=>{t.push(t[o]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),o=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=di(c,a);if(l===void 0)return;o[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:o,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[o]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,o=0,s=0,i=0,a=0;for(;o<e.length&&s<t.length;){let f=this.record(e[e.length-o-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let o=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>o&&(a=o-i),i+a>s&&(a=s-i),X(r,"M",i),Co(r,o-i-a,s-i-a),X(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),o=0;for(let s of e)r.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=r??hi(lo(e,t,h=>this.record(h).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(h,d,p,u)=>{h===d?X(s,"D",i[u]-i[p]):p===u?X(s,"I",this.pathLen(e.slice(h,d))):this.align(e.slice(h,d),t.slice(p,u),s)},f=0,c=0,l=0;for(let h=0;h<o.count;h++){let d=o.pathAt[h],p=o.refAt[h];(c!==d||l!==p)&&a(c,d,l,p);let u=this.record(e[d]).sequenceLen;X(s,"M",u),f+=u,c=d+1,l=p+1}return a(c,e.length,l,t.length),{edits:s,matched:f,matches:o}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,o;if(st(r)&&(t.identity===void 0||!st(ft(t.path))))o={...this.editsAgainst(t.path,r),flipped:!1};else{let s=ft(t.path),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)o={...this.editsAgainst(t.path,r),flipped:!1};else if(i===0)o={...this.editsAgainst(s,r),flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,r])=>`${r}${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,r=this.refPrefix(t)[t.length],o=(l,h,d,p)=>{let u=yi(l),m=this.paths[d[0]],w=this.paths[d[d.length-1]],y=m.identity,S=y?.orientation==="forward",[g,b]=S?[m,w]:[w,m];return{strand:h,refStart:e.start+u.leading,refEnd:e.start+r-u.trailing,edits:u.edits,weight:m.weight,path:d.flatMap(x=>this.paths[x].path),start:Tt(m,0),pieces:d,soloAligned:p,identity:y===void 0?void 0:{pathHandle:y.pathHandle,name:y.name,hapStart:y.name.fragment+g.identity.hapStart,hapEnd:y.name.fragment+b.identity.hapEnd,walkForward:S}}},s=l=>l.soloAligned.reduce((h,d)=>h+d,0),i=l=>l.pieces.reduce((h,d)=>h+this.paths[d].len,0),a=l=>2*s(l)>=i(l),f=l=>{let h=l[0],d=l[l.length-1],p=h.identity.walkForward;if(l.some((P,U)=>P.strand!==h.strand||P.identity.walkForward!==p||U>0&&P.identity.hapStart<l[U-1].identity.hapEnd))return;let u=p?l:[...l].reverse(),m=u.flatMap(P=>P.pieces),w=u.flatMap(P=>P.soloAligned),y=h.strand==="+"!==p,S=m.map(P=>this.paths[P]),g=S.slice(1).map((P,U)=>{let Y=S[U].identity;return p?P.identity.hapStart-Y.hapEnd:Y.hapStart-P.identity.hapEnd}),b=y?[...S].reverse():S,x=y?[...g].reverse():g,E=b.flatMap(P=>y?ft(P.path):P.path),{edits:A}=this.editsAgainst(E,t),_=Ao(A,b.map(P=>P.len)),T=new Map((y?[...m].reverse():m).map((P,U)=>[P,_[U]])),$=P=>2*P.pieces.reduce((U,Y)=>U+T.get(Y),0)>=s(P);if(!$(h)||!$(d))return;let C=[],N=0;return b.slice(0,-1).forEach((P,U)=>{N+=P.len,C.push([N,x[U]])}),o(bi(A,C),h.strand,m,w)},c=[];return this.paths.forEach((l,h)=>{if(h===this.refId)return;let{edits:d,flipped:p}=this.alignment(h),u=l.identity,m=u?u.orientation==="forward"!==p:!p;c.push(o(d,m?"+":"-",[h],Ao(d,[l.len])))}),mi(c,a,f).map(l=>{let{edits:h,identity:d,pieces:p,soloAligned:u,...m}=l,w={...m,cigar:Si(h)};return d?{...w,resolved:!0,name:d.name,label:me({...d.name,fragment:d.hapStart,end:d.hapEnd}),pathHandle:d.pathHandle,hapStart:d.hapStart,hapEnd:d.hapEnd}:{...w,resolved:!1}})}pairAlignments(e){let{target:t,query:r,...o}=e,s=this.paths.flatMap(l=>{let{identity:h}=l;return h?[{name:h.name,start:h.name.fragment+h.hapStart,steps:Ft(l,h)}]:[]}),i=l=>h=>h.sample===l.sample&&h.haplotype===l.haplotype,a=i(t),f=r?i(r):l=>!a(l),c=l=>this.record(ye(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(h=>f(h.name)).flatMap(h=>Io({...o,query:h.steps,target:l.steps,sequenceOf:c}).map(d=>({query:h.name,queryStart:h.start+d.queryStart,queryEnd:h.start+d.queryEnd,strand:d.strand,target:l.name,targetStart:l.start+d.targetStart,targetEnd:l.start+d.targetEnd,cigar:Eo(d.edits),matches:d.edits.reduce((p,[u,m])=>p+(u==="="?m:0),0),columns:d.edits.reduce((p,[,u])=>p+u,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let o=ye(e,r);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([r==="reverse"?1:0,O(s),z(s)?1:0])}return t.sort((r,o)=>r[0]-o[0]||r[1]-o[1]||r[2]-o[2]),t.filter((r,o)=>o===0||r[0]!==t[o-1][0]||r[1]!==t[o-1][1]||r[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!z(r)){let o=O(r),s=`S ${o} ${this.record(r).sequence}
|
|
2
2
|
`;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(s))}return oo(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,r=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...ro(no(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)z(c)||r.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>z(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Ue(c,l)&&r.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,h,d,p)=>{let u=Ft(c,l).map(y=>`${z(y)?"<":">"}${O(y)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,w=p===void 0?"":` CG:Z:${p}`;return`W ${h.sample} ${h.haplotype} ${h.contig} ${h.fragment} ${d} ${u}${m}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let f=1;return this.paths.forEach((c,l)=>{if(l!==this.refId){let h=e.names!=="anonymous"?c.identity:void 0,d=t?this.alignToRef(l):void 0;r.push(h?i(c,h,{...h.name,fragment:h.name.fragment+h.hapStart},h.name.fragment+h.hapEnd,d):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,d)),f+=1}}),`${r.join(`
|
|
4
4
|
`)}
|
|
5
5
|
`}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,r=[],o=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:me({...i,end:this.refPath.fragment+this.refInterval[1]}),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let f=e.names!=="anonymous"?i.identity:void 0;r.push({info:i,identity:f,name:f?me({...f.name,fragment:f.name.fragment+f.hapStart,end:f.name.fragment+f.hapEnd}):me({sample:"unknown",contig:o,haplotype:s,fragment:0,end:i.len}),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Ue(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!z(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(O(s)),from_is_reverse:z(s),to:String(O(i)),to_is_reverse:z(i)});let o=this.outputPaths(e).map(s=>xi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!z(i)),r=new Int32Array(t.length),o=[];t.forEach((i,a)=>{r[a]=O(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:o,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Ft(i.info,i.identity))}))}}};function Ft(n,e){return e?.orientation==="reverse"?n.path.map(t=>re(t)).reverse():n.path}function xi(n,e,t,r){return{name:t,...n.weight===void 0?{}:{weight:n.weight},...r===void 0?{}:{cigar:r},path:Ft(n,e).map(o=>({id:String(O(o)),is_reverse:z(o)}))}}function Kn(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++){let o=n[r],s=e[r];if(o!==s)return o<s?-1:1}return n.length-e.length}function X(n,e,t){if(t===0)return;let r=n[n.length-1];r?.[0]===e?r[1]+=t:n.push([e,t])}function Lt(n){return n===0?0:6+(n-1)}function Co(n,e,t){if(e===0)X(n,"D",t);else if(t===0)X(n,"I",e);else{let r=Math.min(e,t),o=4*r+Lt(e-r)+Lt(t-r),s=Lt(e)+Lt(t);o<=s?(X(n,"M",r),X(n,"I",e-r),X(n,"D",t-r)):(X(n,"I",e),X(n,"D",t))}}function yi(n){let e=0;for(;e<n.length&&n[e][0]!=="M";)e+=1;if(e===n.length){let a=n.filter(([c])=>c==="I"),f=n.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=n.length;for(;n[t-1][0]!=="M";)t-=1;let r=a=>({inserted:a.reduce((f,[c,l])=>f+(c==="I"?l:0),0),deleted:a.reduce((f,[c,l])=>f+(c==="D"?l:0),0)}),o=r(n.slice(0,e)),s=r(n.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of n.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function Ao(n,e){let t=e.map(()=>0),r=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of n){if(a==="D")continue;let c=f;for(;c>0;){for(;o<r&&i>=s;)o+=1,s+=e[o];let l=o<r?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function bi(n,e){let t=[],r=0,o=0;for(let[s,i]of n){if(s==="D"){X(t,s,i);continue}let a=r;for(;o<e.length&&e[o][0]<r+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,r+i-a),r+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function Si(n){return n.map(([e,t])=>`${t}${e}`).join("")}function Oe(n,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${n} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function Bt(n){return Oe("context",n.context??100)}function Ht(n,e){return e.limit!==void 0&&Oe("limit",e.limit),$t.create(n,e)}async function Ro(n,e){let t=Bt(e),r=Ht(n,e),o=await r.pathPosition(Ve(We(e.path),Oe("offset",e.offset)));return await r.aroundPosition(o.position.handle,o.position.nodeOffset,t),await r.extractSnarls(e.snarls??"none"),r.extractPaths(o,e.haplotypes??"all"),r}async function vi(n,e){let t=Oe("start",e.start),r=Oe("end",e.end),o=Bt(e),s=Ht(n,e);try{let i=await s.pathPosition(Ve(We(e.path),t));return await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,o),await s.extractSnarls(e.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof be&&i.windowBp===void 0?new be(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}}async function Xn(n,e){let{keep:t}=e,r=e.haplotypes??"all",o=r==="all"||r==="distinct";if(t!==void 0&&o&&!n.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await vi(n,e);return t===void 0||!o?(s.extractPaths(i,r),s):(await s.extractChosenPaths(i,e.end-e.start,t,Bt(e))||(s.extractPaths(i,"all"),await s.identifyPaths()),s.keepHaplotypes(t),r==="distinct"&&s.mergeDistinct(),s)}async function Mo(n,e){let t=e.haplotypes??"all",r=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(r==="overlapping"&&new Set(e.nodeIds).size>1)throw new Error("Overlapping snarls cannot be extracted for a node-based query with multiple nodes");let o=Bt(e);for(let i of e.nodeIds)Oe("node id",i,1);let s=Ht(n,e);return await s.aroundNodes(e.nodeIds,o),await s.extractSnarls(r),s.extractPaths(void 0,t),s}async function Po(n,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let r=Ht(n,e);return await r.betweenNodes(Oe("startHandle",e.startHandle,2),Oe("endHandle",e.endHandle,2)),r.extractPaths(void 0,t),r}function Ee(n,e){let t=0;for(let o=0;o<8;o++){let s=n[e+o];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0){if(o===7&&!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+o+1]}}let r=n[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function Ii(n,e,t){switch(t){case 1:return n.getInt8(e);case 2:return n.getInt16(e);case 3:return n.getInt8(e)<<16|n.getUint16(e+1);case 4:return n.getInt32(e);case 6:return n.getInt16(e)*4294967296+n.getUint32(e+2);default:{let r=n.getBigInt64(e);if(r>BigInt(Number.MAX_SAFE_INTEGER)||r<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${r} exceeds the safe integer range`);return Number(r)}}}var Ei=new TextDecoder;function qt(n){let[e,t]=Ee(n,0),r=[],o=t;for(;o<e;){let[a,f]=Ee(n,o);r.push(a),o=f}let s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=Ii(s,i,f);return i+=f,c}if(a===7){let f=s.getFloat64(i);return i+=8,f}if(a===8)return 0;if(a===9)return 1;if(a>=12){let f=a-12>>1,c=n.subarray(i,i+f);return i+=f,a%2===0?c:Ei.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Gt=2,zt=5,_o=10,Dt=13;function ko(n,e){return n[e]*256+n[e+1]}function Ne(n,e){return n[e]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function Ai(n,e){let t=n[e];if(t!==Gt&&t!==zt&&t!==_o&&t!==Dt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===Gt||t===zt;return{type:t,cellCount:ko(n,e+3),rightChild:r?Ne(n,e+8):0,cellPointers:e+(r?12:8)}}function Me(n,e,t){return ko(n,e.cellPointers+2*t)}var Ci=4096,jt=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,o=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=o)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=o?i:s}async payload(e,t,r,o){let s=this.localPayloadSize(r,o);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,f=Ne(e,t+s);for(;f!==0&&a<r;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,f=Ne(c,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Ai(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Dt)return s;if(a.type!==zt)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:Ne(i,Me(i,a,f))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Ee(e,Me(e,t,i)+4);a<r?o=i+1:s=i}return o}async prefetchRowidRanges(e,t,r=!1){if(t.length===0)return!0;let o=await this.tableDepth(e,t[0][0]),s=t.map(()=>[e]);for(let i=0;i<o;i++){s=await Promise.all(s.map((f,c)=>this.childrenInRange(f,...t[c])));let a=s.flat();if(r)this.pager.prefetchLeading(a);else if(!this.pager.prefetch(a))return!1}return!0}async childrenInRange(e,t,r){let o=await Promise.all(e.map(i=>this.pageAt(i))),s=[];return o.forEach(({page:i,header:a},f)=>{let c=f===0?this.childIndexFor(i,a,t):0,l=f===o.length-1?this.childIndexFor(i,a,r):a.cellCount;for(let h=c;h<=l;h++)s.push(h===a.cellCount?a.rightChild:Ne(i,Me(i,a,h)))}),s}async tableRowid(e,t){let r=e;for(;;){let{page:o,header:s}=await this.pageAt(r);if(s.type===Dt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,h=Me(o,s,l),[d,p]=Ee(o,h),[u,m]=Ee(o,p);if(u===t)return qt(await this.payload(o,m,d,!1));u<t?f=l+1:c=l}return}if(s.type!==zt)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let f=i+a>>1,c=Me(o,s,f),[l]=Ee(o,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:Ne(o,Me(o,s,i))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:r,header:o}=await this.pageAt(e);if(o.type===Dt)for(let s=0;s<o.cellCount;s++){let i=Me(r,o,s),[a,f]=Ee(r,i),[c,l]=Ee(r,f);yield{rowid:c,values:qt(await this.payload(r,l,a,!1))}}else{let s=[];for(let i=0;i<o.cellCount;i++)s.push(Ne(r,Me(r,o,i)));s.push(o.rightChild),t===1&&this.pager.prefetchLeading(s);for(let i of s)yield*this.scanPage(i,t-1)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=Ci){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,o){let s=this.decodedCells(e,r),i=s[o];if(!i){let a=Me(t,r,o),f=r.type===Gt,[c,l]=Ee(t,f?a+4:a);i={values:qt(await this.payload(t,l,c,!0)),leftChild:f?Ne(t,a):0},s[o]=i}return i}async lowerBound(e,t,r,o,s,i){let a=s,f=r.cellCount;for(;a<f;){let c=a+f>>1,l=await this.indexCell(e,t,r,c),h=Zn(l.values,o);h<0||i&&h===0?a=c+1:f=c}return a}async*indexScanFrom(e,t,r){let{page:o,header:s}=await this.pageAt(e),i=await this.lowerBound(e,o,s,t,0,!1),a=s.type===Gt;if(a&&r){let f=await this.lowerBound(e,o,s,r,i,!0),c=[];for(let l=i;l<=f;l++)c.push(l===s.cellCount?s.rightChild:(await this.indexCell(e,o,s,l)).leftChild);this.pager.prefetchLeading(c)}for(let f=i;f<s.cellCount;f++){let c=await this.indexCell(e,o,s,f);if(a&&(yield*this.indexScanFrom(c.leftChild,t,r)),r&&Zn(c.values,r)>0)return;yield c.values}a&&(yield*this.indexScanFrom(s.rightChild,t,r))}async indexSeekLE(e,t){let r,o=e;for(;;){let{page:s,header:i}=await this.pageAt(o),a=0,f=i.cellCount,c=0;for(;a<f;){let l=a+f>>1,h=await this.indexCell(o,s,i,l);Zn(h.values,t)<=0?(r=h.values,a=l+1):(c=h.leftChild,f=l)}if(i.type===_o)return r;o=a===i.cellCount?i.rightChild:c}}};function Zn(n,e){for(let t=0;t<e.length;t++){let r=n[t],o=e[t];if(typeof r!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(r!==o)return r<o?-1:1}return 0}function Oo({blockSize:n,maxBlocks:e}){if(n!==void 0&&!(Number.isSafeInteger(n)&&n>0))throw new Error(`blockSize must be a positive integer, not ${n}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var Ut=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,o={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=o.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=o.maxBlocks??256}async read(e,t){let r=await this.readRetrying(e,t);if(this.bytesFetched+=r.length,r.length<e)throw new Error(`the file ends at byte ${t+r.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return r}async readRetrying(e,t){let r=0;for(;;)try{return await this.source.read(e,t)}catch(o){if(r+=1,r>=3)throw o;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){this.follow(e);let t=this.touch(e);if(t)return t;let r=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-r),s=this.read(o,r);return this.fetches+=1,this.store(e,s),this.evict(),s}touch(e){let t=this.blocks.get(e);return t&&(this.blocks.delete(e),this.blocks.set(e,t)),t}blockOf(e){return Math.floor((e-1)*this.pageSize/this.blockSize)}get prefetchBudget(){return Math.max(1,Math.floor(this.maxBlocks/2))}get chunk(){return Math.max(1,Math.floor(this.prefetchBudget/2))}prefetch(e){let t=new Set(e.map(r=>this.blockOf(r)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],r=new Map;for(let o of e){let s=this.blockOf(o);r.has(s)||(r.set(s,t.length),t.push(s))}this.plan={blocks:t,position:r,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let r=t.blocks.slice(t.next,t.next+e);t.next+=r.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(r))}follow(e){let t=this.plan,r=t?.position.get(e);t&&r!==void 0&&r>=t.next-Math.ceil(this.chunk/2)&&this.advance(this.chunk)}fetchBlocks(e){let t=[...e].filter(o=>!this.touch(o)).sort((o,s)=>o-s),r=0;for(;r<t.length;){let o=r+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[r],o-r),r=o}}fetchRun(e,t){let r=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(o,r);this.fetches+=1;for(let i=0;i<t;i++){let a=i*this.blockSize;this.store(e+i,s.then(f=>f.subarray(a,a+this.blockSize)))}this.evict()}store(e,t){this.blocks.set(e,t),t.catch(()=>{this.blocks.get(e)===t&&this.blocks.delete(e)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return r.subarray(o,o+this.pageSize)}};var lt=class n{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){Oo(t);let r=await e.read(Math.max(512,t.blockSize??65536),0),o=r.subarray(0,100);if(new TextDecoder().decode(o.subarray(0,15))!=="SQLite format 3"||o.length<100)throw new Error("Not a SQLite database");let i=new DataView(o.buffer,o.byteOffset,o.byteLength),a=i.getUint16(16),f=a===1?65536:a,c=o[20]??0,l=i.getUint32(56);if(l!==1)throw new Error(`SQLite text encoding ${l} is not UTF-8`);let h=i.getUint32(28);if(h===0||i.getUint32(24)!==i.getUint32(92))throw new Error("SQLite header has no valid database size; the file was written by SQLite older than 3.7.0");let d=h*f,p=new Ut(e,f,d,t);p.seed(0,r),p.fetches+=1,p.bytesFetched+=r.length;let u=new jt(p,c),m=new Map;for await(let{values:w}of u.tableScan(1)){let[y,S,g,b,x]=w;typeof y=="string"&&typeof S=="string"&&typeof g=="string"&&typeof b=="number"&&m.set(S,{type:y,name:S,tableName:g,rootPage:b,sql:typeof x=="string"?x:""})}return new n(p,u,m)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}withoutRowid(e){let t=this.objects.get(e);return t?.type==="table"&&/without\s+rowid/i.test(t.sql)}indexOn(e){let t=[...this.objects.values()].find(r=>r.type==="index"&&r.tableName===e);if(t)return t.rootPage;if(this.withoutRowid(e))return this.rootPage(e);throw new Error(`SQLite table ${e} has no index`)}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,r){return this.btree.indexScanFrom(this.indexOn(e),t,r)}has(e){return this.objects.has(e)}};var nr="GBZ-base version 4",Wt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${me(e)}`),this.path=e}},Vt=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},Qt=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: it has no version tag":`unsupported database schema "${e}"; this reader understands "${nr}"`),this.found=e}};function Ri(n){if(n.length===1)return n[0];let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}var Jn=3,Ye=class{at=0;bytes;constructor(e){this.bytes=e}get done(){return this.at>=this.bytes.length}next(){let e=0,t=1;for(;;){let r=this.bytes[this.at++];if(r===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(r&127)*t,t*=128,(r&128)===0)return e}}};function Mi(n,e){let t=new Ye(n),r=0;for(;!t.done;){let o=r+t.next();r=o+t.next(),e.push([o,r])}}function Pi(n){n.sort((r,o)=>r[0]-o[0]);let e=[],t=[];for(let[r,o]of n){let s=t.length-1;s>=0&&r<=t[s]+1?t[s]=Math.max(t[s],o):(e.push(r),t.push(o))}return r=>{let o=0,s=e.length;for(;o<s;){let i=o+s>>1;e[i]<=r?o=i+1:s=i}return o>0&&r<=t[o-1]}}function _i(n,e,t){let r=new Ye(e);for(;!r.done;){let o=r.next(),s=r.next(),i=r.next(),a=r.next(),f=r.next();t.push({bin:n,pathHandle:o,pathStart:s,pathEnd:i,snarl:f>0?[a,f]:void 0,node:r.next(),offset:r.next()})}}function ki(n,e,t){let r=O(n);for(let o of e){let s=new Ye(o);for(;!s.done;){let i=s.next(),a=i%2;t.push({node:2*r+a,offset:s.next(),pathHandle:(i-a)/2,orientation:"forward",pathOffset:s.next()})}}}var tr=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,o,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=o,this.next=s,this.sequenceLen=Yr(o)}get id(){return O(this.handle)}get orientation(){return je(this.handle)}get sequence(){return this.decoded??=Kr(this.encodedSequence),this.decoded}successors(){return this.edges.filter(e=>e.node!==0).map(e=>e.node)}gbwt(){if(this.edges.length===0)throw new Error(`GBWT record for handle ${this.handle} is empty`);return new Ct(this.edges,this.bwt)}};function Q(n,e){if(typeof n!="number")throw new Error(`${e} is not a number in the database`);return n}function ht(n,e){if(typeof n!="string")throw new Error(`${e} is not text in the database`);return n}function He(n,e){if(!(n instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return n}function No(n,e){return{handle:n,fwStart:{node:Q(e[1],"Paths.fw_node"),offset:Q(e[2],"Paths.fw_offset")},revStart:{node:Q(e[3],"Paths.rev_node"),offset:Q(e[4],"Paths.rev_offset")},name:{sample:ht(e[5],"Paths.sample"),contig:ht(e[6],"Paths.contig"),haplotype:Q(e[7],"Paths.haplotype"),fragment:Q(e[8],"Paths.fragment")},isIndexed:Q(e[9],"Paths.is_indexed")!==0}}function er(n,e){return n.catch(e),n}async function To(n){let e=new Map;for await(let{values:t}of n.scan("Tags"))e.set(ht(t[0],"Tags.key"),ht(t[1],"Tags.value"));return e}var dt=class n{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,r){this.sqlite=e,this.index=t,this.tagMap=r}static async open(e){let{source:t,haplotypeIndex:r}=e,o={blockSize:e.blockSize,maxBlocks:e.maxBlocks},s=await lt.open(t,o),i=s.objects.has("Tags")?await To(s):new Map,a=i.get("version");if(a!==nr)throw new Qt(a);for(let l of["Nodes","Paths","ReferenceIndex"])s.rootPage(l);let f=r?await lt.open(r,o):void 0,c=new n(s,f,i);if(f){for(let m of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!f.objects.has(m))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${m} table`);c.indexTags=await To(f);let l=c.indexTags.get("haplotype_index_paths"),h=await c.tag("paths");if(l!==h)throw new Error(`haplotype index was built for ${l??"an unknown number of"} paths but the graph has ${h}`);let d=c.indexTags.get("haplotype_index_nodes"),p=await c.tag("nodes");if(d!==void 0&&d!==p)throw new Error(`haplotype index was built for a graph with ${d} nodes but this one has ${p}`);if(c.indexTags.get("haplotype_index_orientations")==="forward")throw new Vt;let u=c.indexTags.get("haplotype_index_format");if(Number(u)!==Jn)throw new Error(u===void 0?`the haplotype index predates format ${Jn}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${u}; this version of @gmod/gbz-base reads format ${Jn}`)}return c}async tags(){return this.tagMap}async tag(e){return this.tagMap.get(e)}prefetchRecords(e,t=!1){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new tr(e,Qr(He(t[1],"Nodes.edges")),He(t[2],"Nodes.bwt"),He(t[3],"Nodes.sequence"),typeof r=="number"?r:void 0)}paths(){return this.pathCache??=er(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:r}of this.sqlite.scan("Paths"))e.push(No(t,r));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?No(e,t):void 0}pathsByHandle(){return this.pathMapCache??=er(this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),()=>{this.pathMapCache=void 0}),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,o)=>o.name.fragment-r.name.fragment)[0]}async pathsNamed(e){let t=Ve(We(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,o)=>r.name.fragment-o.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`${i?`The fragment of ${me(i.name)} at ${i.name.fragment}`:`Path ${e}`} has not been indexed for random access`)}let o=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);o+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return o;s=a}}return t}async getPathFragments(e){let{start:t,end:r}=e;if(Number.isNaN(t)||Number.isNaN(r))throw new Error(`The window ${t}..${r} is not a number range`);let o=await this.pathsNamed(e.path);if(o.length===0)throw new Wt(Ve(We(e.path),0));if(r<=t)return[];let s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<r);return(await Promise.all([...s,...i].map(async f=>({path:f,start:f.name.fragment,end:f.name.fragment+await this.pathLength(f.handle)})))).filter(f=>t<f.end)}async subgraphForFragment(e,t){let{sample:r,contig:o,haplotype:s}=e.path.name,i=Math.max(t.start,e.start),a=t.haplotypes??"all";try{let f=await Xn(this,{...t,path:{sample:r,contig:o,haplotype:s},start:i,end:Math.min(t.end,e.end)});return t.keep===void 0&&this.hasHaplotypeIndex&&(a==="all"||a==="distinct")&&await f.identifyPaths(),f}catch(f){throw f instanceof be&&f.walkedBp!==void 0?new be(f.limit,{windowBp:t.end-t.start,walkedBp:i-t.start+f.walkedBp}):f}}async getSubgraphs(e){let t=await this.getPathFragments(e);return(await Promise.allSettled(t.map(o=>this.subgraphForFragment(o,e)))).map(o=>{if(o.status==="rejected")throw o.reason;return o.value})}async getAlignments(e){return(await this.getSubgraphs(e)).flatMap(t=>t.alignments())}subgraphInInterval(e){return Xn(this,e)}subgraphAtOffset(e){return Ro(this,e)}subgraphAroundNodes(e){return Mo(this,e)}subgraphBetween(e){return Po(this,e)}fetchStats(){let e=({pager:t})=>({fetches:t.fetches,bytesFetched:t.bytesFetched});return{graph:e(this.sqlite),haplotypeIndex:this.index?e(this.index):void 0}}async graphName(){let e=new Map;for(let[r,o]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=to(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index!==void 0}get companion(){if(!this.index)throw new Error("no haplotype index was opened with this database");return this.index}async haplotypeSampleInterval(){let e=this.indexTags.get("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeSampleGap(){let e=await this.haplotypeSampleInterval(),t=this.indexTags.get("haplotype_index_reference_interval");return e===void 0?void 0:Math.max(e,t===void 0?0:Number(t))}async haplotypeAnchorSpacing(){let e=this.index?.has("HaplotypeAnchors")?this.indexTags.get("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeStrayOptions(){let e=r=>this.indexTags.get(`haplotype_index_stray_${r}`);if(!this.index?.has("HaplotypeBins")||e("format")!=="2")return;let t=e("snarls")==="modeled"&&e("chain_links")===(await this.tag("chain_links")??"0");return{context:Number(e("context")),bin:Number(e("bin")),bound:Number(e("bound")),snarlNodes:t?Number(e("snarl_nodes")):void 0}}async blobRows(e,t,r){let o=[],s=[];for await(let i of this.companion.indexScanFrom(e,t,r))s.push(Q(i[i.length-1],`${e} rowid`));s.length>1&&await this.companion.prefetchRows(e,[[Math.min(...s),Math.max(...s)+1]],!0);for(let i of s){let a=await this.companion.byRowid(e,i);a&&o.push(a)}return o}async haplotypeBinData(e,t,r){let o=[],s=[];for(let i of await this.blobRows("HaplotypeBins",[e,t],[e,r])){let a=Q(i[1],"HaplotypeBins.bin");Mi(He(i[3],"HaplotypeBins.nodes"),o),_i(a,He(i[4],"HaplotypeBins.strays"),s)}return{listed:Pi(o),strays:s}}async haplotypeAnchorsBetween(e,t,r){let o=[],s=[],i=()=>{let a=o[o.length-1];a&&ki(a.node,s,a.visits),s=[]};for(let a of await this.blobRows("HaplotypeAnchors",[e,t],[e,r])){let f=Q(a[1],"HaplotypeAnchors.anchor_offset");o[o.length-1]?.anchorOffset!==f&&(i(),o.push({anchorOffset:f,node:Q(a[3],"HaplotypeAnchors.node_handle"),pathOffset:Q(a[4],"HaplotypeAnchors.path_offset"),visits:[]})),s.push(He(a[5],"HaplotypeAnchors.visits"))}return i(),o}async haplotypeAnchor(e,t){let[r]=await this.haplotypeAnchorsBetween(e,t,t);return r&&{node:r.node,pathOffset:r.pathOffset}}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:Q(e[0],"HaplotypeSamples.node_handle"),offset:Q(e[1],"HaplotypeSamples.node_offset"),pathHandle:Q(e[2],"HaplotypeSamples.path_handle"),orientation:Q(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:Q(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))r.push(this.sampleFromRow(o));return r}async haplotypeSampleAt(e,t){let r=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return r?.[0]===e&&r[1]===t?this.sampleFromRow(r):void 0}overviewRows(){return this.overviewRowsCache??=er((async()=>{let e=[];for await(let{rowid:t,values:r}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:ht(r[1],"HaplotypeOverviewRows.sample"),haplotype:Q(r[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,r,o,s){let i=new Map;for(let a of await this.blobRows(e,[t,r,o],[t,r,s])){let f=Q(a[2],`${e}.chunk`),c=i.get(f)??[];c.push(He(a[4],`${e} blob`)),i.set(f,c)}return new Map([...i].map(([a,f])=>[a,Ri(f)]))}async haplotypeOverview(e){let t=u=>this.indexTags.get(`haplotype_index_overview_${u}`);if(!this.index?.has("HaplotypeOverviewClasses")||t("format")!=="1")return;let r=Number(t("bin")),o=Number(t("chunk")),s=Number(t("levels")),i=Math.max(0,Math.min(Math.floor(e.level??0)||0,s-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;i+1<s&&r*4**(i+1)<=e.bpPerPixel;)i+=1;let a=r*4**i,[f,c]=await Promise.all([this.getPathFragments(e),this.overviewRows()]),l=Math.ceil(c.length/2),h=[],d=[];for(let u of f){let m=u.end-u.start,w=Math.max(e.start,u.start)-u.start,y=Math.min(e.end,u.end)-u.start,S=Math.floor(w/a),g=Math.floor((y-1)/a),b=Math.floor(S/o),x=Math.floor(g/o),[E,A]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",u.path.handle,i,b,x),this.overviewChunks("HaplotypeOverviewClasses",u.path.handle,i,b,x)]);for(let _=b;_<=x;_++){let T=new Ye(E.get(_)??new Uint8Array),$=A.get(_)??new Uint8Array;for(let C=_*o;!T.done;C++){let N=Array.from({length:7},()=>T.next());if(C<S||C>g)continue;h.push({start:u.start+C*a,end:u.start+Math.min((C+1)*a,m),classes:[N[0],N[1],N[2],N[3]],excursions:N[4],variants:N[5],longestExcursion:N[6]});let P=(C-_*o)*l;d.push($.subarray(P,P+l))}}}if(h.length===0)return;let p=new Uint8Array(h.length*c.length);return d.forEach((u,m)=>{for(let w=0;w<c.length;w++)p[m*c.length+w]=(u[w>>1]??0)>>4*(w%2)&15}),{level:i,bin:a,haplotypes:c,bins:h,cells:p}}async haplotypeLength(e){let t=await this.companion.byRowid("HaplotypeLengths",e);return t?Q(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:Q(t[1],"ReferenceIndex.path_offset"),pos:{node:Q(t[2],"ReferenceIndex.node_handle"),offset:Q(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?Q(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(o!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",[[o,s+1]]);for(let a=o;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var Ir=ce(Ln(),1),wt=ce(ot(),1),En=ce(Br(),1),Ns=ce(qs(),1);function Yt(n){let e=/\.gbz\.db$/i;return e.test(n)?n.replace(e,".haplotype-index.db"):void 0}var Lo=ce(Br(),1);function Oi(n){return qr(n)&&Yt(Hr(n))?Dr(n,e=>Yt(e)):void 0}function Ni(n){return n instanceof Error&&(/\bHTTP 40[34]\b/.test(n.message)||n.code==="ENOENT")}async function Fo(n,e){let t=Oi(n);if(!t)return{};try{return await(0,Lo.openLocation)(t,e).stat(),{location:t}}catch(r){return Ni(r)?{}:{unreadable:String(r)}}}var Bo=ce(Ln(),1),Ti=5e3,Li=50*2**20,rr=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 Fi(n,e){if(n.length<=e)return n;let t=n.length/e;return Array.from({length:e},(r,o)=>n[Math.floor(o*t)])}var $o=(n,e)=>n.path.some(t=>e.has(t.name)),Kt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=(0,Bo.cachedSetup)({setup:async()=>{let{size:e}=await this.file.stat();if(e>Li)throw new rr(e);let t=await this.file.readFile(),r=new TextDecoder().decode(t[0]===31&&t[1]===139?await Gr(t):t);return $n(r)}})}async readIndexed(e,t,r){let o=1/0,s=-1/0;for(let a of t){let f=Number(a);Number.isInteger(f)&&(o=Math.min(o,f),s=Math.max(s,f))}let i=[];return o<=s&&await e.getLines("{node}",o,s+1,{signal:r,lineCallback:a=>{let f=Fn(a);f&&$o(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let r=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>$o(o,e));return{records:Fi(r,Ti),total:r.length}}};var Ps=ce(Ln(),1),_s=ce(ot(),1);var or=function(n,e){return or=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},or(n,e)};function pt(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");or(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ho(n,e,t,r){function o(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{c(r.next(l))}catch(h){i(h)}}function f(l){try{c(r.throw(l))}catch(h){i(h)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((r=r.apply(n,e||[])).next())})}function Xt(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(l){return f([c,l])}}function f(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,o=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(l){c=[6,l],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function qe(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ke(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function Xe(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function De(n){return this instanceof De?(this.v=n,this):new De(n)}function qo(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(p){return function(u){return Promise.resolve(u).then(p,h)}}function a(p,u){r[p]&&(o[p]=function(m){return new Promise(function(w,y){s.push([p,m,w,y])>1||f(p,m)})},u&&(o[p]=u(o[p])))}function f(p,u){try{c(r[p](u))}catch(m){d(s[0][3],m)}}function c(p){p.value instanceof De?Promise.resolve(p.value.v).then(l,h):d(s[0][2],p)}function l(p){f("next",p)}function h(p){f("throw",p)}function d(p,u){p(u),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Do(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof qe=="function"?qe(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(i){return new Promise(function(a,f){i=n[s](i),o(a,f,i.done,i.value)})}}function o(s,i,a,f){Promise.resolve(f).then(function(c){s({value:c,done:a})},i)}}function q(n){return typeof n=="function"}function Go(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Zt=Go(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
6
6
|
`+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
7
7
|
`):"",this.name="UnsubscriptionError",this.errors=t}});function sr(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Jt=(function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=qe(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(q(l))try{l()}catch(m){s=m instanceof Zt?m.errors:[m]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var d=qe(h),p=d.next();!p.done;p=d.next()){var u=p.value;try{zo(u)}catch(m){s=s??[],m instanceof Zt?s=Xe(Xe([],Ke(s)),Ke(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(r)throw r.error}}}if(s)throw new Zt(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)zo(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&sr(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&sr(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=(function(){var e=new n;return e.closed=!0,e})(),n})();var Kf=Jt.EMPTY;function en(n){return n instanceof Jt||n&&"closed"in n&&q(n.remove)&&q(n.add)&&q(n.unsubscribe)}function zo(n){q(n)?n():n.unsubscribe()}var Se={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ze={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var o=Ze.delegate;return o?.setTimeout?o.setTimeout.apply(o,Xe([n,e],Ke(t))):setTimeout.apply(void 0,Xe([n,e],Ke(t)))},clearTimeout:function(n){var e=Ze.delegate;return(e?.clearTimeout||clearTimeout)(n)},delegate:void 0};function tn(n){Ze.setTimeout(function(){var e=Se.onUnhandledError;if(e)e(n);else throw n})}function ir(){}var jo=(function(){return ar("C",void 0,void 0)})();function Uo(n){return ar("E",void 0,n)}function Wo(n){return ar("N",n,void 0)}function ar(n,e,t){return{kind:n,value:e,error:t}}var Ge=null;function Vo(n){if(Se.useDeprecatedSynchronousErrorHandling){var e=!Ge;if(e&&(Ge={errorThrown:!1,error:null}),n(),e){var t=Ge,r=t.errorThrown,o=t.error;if(Ge=null,r)throw o}}else n()}function Qo(n){Se.useDeprecatedSynchronousErrorHandling&&Ge&&(Ge.errorThrown=!0,Ge.error=n)}var ut=(function(n){pt(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,en(t)&&t.add(r)):r.destination=qi,r}return e.create=function(t,r,o){return new rn(t,r,o)},e.prototype.next=function(t){this.isStopped?cr(Wo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?cr(Uo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?cr(jo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Jt);var $i=Function.prototype.bind;function fr(n,e){return $i.call(n,e)}var Bi=(function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){nn(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){nn(r)}else nn(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){nn(t)}},n})(),rn=(function(n){pt(e,n);function e(t,r,o){var s=n.call(this)||this,i;if(q(t)||!t)i={next:t??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&Se.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&fr(t.next,a),error:t.error&&fr(t.error,a),complete:t.complete&&fr(t.complete,a)}):i=t}return s.destination=new Bi(i),s}return e})(ut);function nn(n){Se.useDeprecatedSynchronousErrorHandling?Qo(n):tn(n)}function Hi(n){throw n}function cr(n,e){var t=Se.onStoppedNotification;t&&Ze.setTimeout(function(){return t(n,e)})}var qi={closed:!0,next:ir,error:Hi,complete:ir};var Je=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Yo(n){return n}function Ko(n){return n.length===0?Yo:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var he=(function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,s=Gi(e)?e:new rn(e,t,r);return Vo(function(){var i=o,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?o._subscribe(s):o._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Xo(t),new t(function(o,s){var i=new rn({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Je]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ko(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Xo(e),new e(function(r,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},n.create=function(e){return new n(e)},n})();function Xo(n){var e;return(e=n??Se.Promise)!==null&&e!==void 0?e:Promise}function Di(n){return n&&q(n.next)&&q(n.error)&&q(n.complete)}function Gi(n){return n&&n instanceof ut||Di(n)&&en(n)}function zi(n){return q(n?.lift)}function ge(n){return function(e){if(zi(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Pe(n,e,t,r,o){return new ji(n,e,t,r,o)}var ji=(function(n){pt(e,n);function e(t,r,o,s,i,a){var f=n.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:n.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(ut);var on=(function(n){return n&&typeof n.length=="number"&&typeof n!="function"});function sn(n){return q(n?.then)}function an(n){return q(n[Je])}function fn(n){return Symbol.asyncIterator&&q(n?.[Symbol.asyncIterator])}function cn(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ui(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ln=Ui();function hn(n){return q(n?.[ln])}function dn(n){return qo(this,arguments,function(){var t,r,o,s;return Xt(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,De(t.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,De(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,De(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function pn(n){return q(n?.getReader)}function Ae(n){if(n instanceof he)return n;if(n!=null){if(an(n))return Wi(n);if(on(n))return Vi(n);if(sn(n))return Qi(n);if(fn(n))return Zo(n);if(hn(n))return Yi(n);if(pn(n))return Ki(n)}throw cn(n)}function Wi(n){return new he(function(e){var t=n[Je]();if(q(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vi(n){return new he(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Qi(n){return new he(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,tn)})}function Yi(n){return new he(function(e){var t,r;try{for(var o=qe(n),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.complete()})}function Zo(n){return new he(function(e){Xi(n,e).catch(function(t){return e.error(t)})})}function Ki(n){return Zo(dn(n))}function Xi(n,e){var t,r,o,s;return Ho(this,void 0,void 0,function(){var i,a;return Xt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Do(n),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),o={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function we(n,e,t,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!o)return s}function un(n,e){return e===void 0&&(e=0),ge(function(t,r){t.subscribe(Pe(r,function(o){return we(r,n,function(){return r.next(o)},e)},function(){return we(r,n,function(){return r.complete()},e)},function(o){return we(r,n,function(){return r.error(o)},e)}))})}function mn(n,e){return e===void 0&&(e=0),ge(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function Jo(n,e){return Ae(n).pipe(mn(e),un(e))}function es(n,e){return Ae(n).pipe(mn(e),un(e))}function ts(n,e){return new he(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function ns(n,e){return new he(function(t){var r;return we(t,e,function(){r=n[ln](),we(t,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return q(r?.return)&&r.return()}})}function gn(n,e){if(!n)throw new Error("Iterable cannot be null");return new he(function(t){we(t,e,function(){var r=n[Symbol.asyncIterator]();we(t,e,function(){r.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function rs(n,e){return gn(dn(n),e)}function os(n,e){if(n!=null){if(an(n))return Jo(n,e);if(on(n))return ts(n,e);if(sn(n))return es(n,e);if(fn(n))return gn(n,e);if(hn(n))return ns(n,e);if(pn(n))return rs(n,e)}throw cn(n)}function lr(n,e){return e?os(n,e):Ae(n)}function mt(n,e){return ge(function(t,r){var o=0;t.subscribe(Pe(r,function(s){r.next(n.call(e,s,o++))}))})}function ss(n,e,t,r,o,s,i,a){var f=[],c=0,l=0,h=!1,d=function(){h&&!f.length&&!c&&e.complete()},p=function(m){return c<r?u(m):f.push(m)},u=function(m){s&&e.next(m),c++;var w=!1;Ae(t(m,l++)).subscribe(Pe(e,function(y){o?.(y),s?p(y):e.next(y)},function(){w=!0},void 0,function(){if(w)try{c--;for(var y=function(){var S=f.shift();i?we(e,i,function(){return u(S)}):u(S)};f.length&&c<r;)y();d()}catch(S){e.error(S)}}))};return n.subscribe(Pe(e,p,function(){h=!0,d()})),function(){a?.()}}function et(n,e,t){return t===void 0&&(t=1/0),q(e)?et(function(r,o){return mt(function(s,i){return e(r,s,o,i)})(Ae(n(r,o)))},t):(typeof e=="number"&&(t=e),ge(function(r,o){return ss(r,o,n,t)}))}function is(n,e,t,r,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Pe(i,function(l){var h=c++;f=a?n(f,l,h):(a=!0,l),r&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function as(n,e){return ge(is(n,e,arguments.length>=2,!1,!0))}var Zi=function(n,e){return n.push(e),n};function wn(){return ge(function(n,e){as(Zi,[])(n).subscribe(e)})}function fs(n){let e=[],t=0,r;for(let o=0,s=n.length;o<s;o++){let i=n.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=n[o];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function pr(n){let e="";for(let{own:t,mate:r,op:o}of fs(n))e+=o==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${o==="I"?r:t}${o}`;return e}var hr=2**28-1;function dr(n,e,t){for(let r=e;r>0;r-=hr)n.push((Math.min(r,hr)<<4|t)>>>0)}function Ji(n,e,t){if(e===t)dr(n,e,0);else{let r=Math.ceil(Math.max(e,t)/hr);for(let o=0;o<r;o++){let s=Math.floor(e*(o+1)/r)-Math.floor(e*o/r),i=Math.floor(t*(o+1)/r)-Math.floor(t*o/r);n.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function ur(n){let e=[];for(let{own:t,mate:r,op:o}of fs(n))o==="M"?Ji(e,t,r):o==="I"?dr(e,r,1):dr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function ea(n){return n>=48&&n<=57}function ta(n){return n!==void 0&&/[A-Za-z]/.test(n)}function cs(n,e){let t=e;for(;t<n.length&&ta(n[t]);)t++;return t}function ls(n,e){let t=e,r=0;for(;t<n.length&&ea(n.charCodeAt(t));)r=r*10+(n.charCodeAt(t)-48),t++;return{value:r,next:t}}function ms(n,e){let t=0;for(;t<n.length;){let r=n[t];if(r===":"){let{value:o,next:s}=ls(n,t+1);e(":",o,o,t+1,s),t=s}else if(r==="="){let o=cs(n,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,n.length)),t+=3;else if(r==="+"||r==="-"){let o=cs(n,t+1),s=o-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,o),t=o}else if(r==="~"){let{value:o,next:s}=ls(n,t+3),i=Math.min(s+2,n.length);e("~",o,0,t+1,i),t=i}else t++}}function mr(n,e,t,r){let o=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;ms(n,(a,f,c,l,h)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,n[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let d=n.slice(l,h);e(73,i,c,d,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>o&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function gs(n,e,t,r){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=n.length;f<c;f++){let l=n[f],h=l>>>4,d=l&15;if(d===0||d===7){if(a)for(let p=0;p<h;p++)(e.charCodeAt(s+p)|32)!==(t.charCodeAt(o+p)|32)&&i.push({start:o+p,type:"mismatch",base:e[s+p],altbase:t[o+p],length:1});s+=h,o+=h}else if(d===1)i.push({start:o,type:"insertion",insertlen:h,insertedBases:e?.slice(s,s+h),length:0}),s+=h;else if(d===2)i.push({start:o,type:"deletion",length:h}),o+=h;else if(d===3)i.push({start:o,type:"skip",length:h}),o+=h;else if(d===8){for(let p=0;p<h;p++)i.push({start:o+p,type:"mismatch",base:e?.[s+p]||"X",qual:r?.[s+p],length:1});s+=h,o+=h}else d===5?i.push({start:o,type:"hardclip",cliplen:h,length:1}):d===4&&(i.push({start:o,type:"softclip",cliplen:h,length:1}),s+=h)}return i}function ws(n,e,t,r,o){if(!e)return[];let s=[],i=e.length,a=r.length,f=o!==void 0,c=t.length,l=!1;for(let S=0;S<c;S++)if(t[S].type==="skip"){l=!0;break}let h=0,d=0,p=0,u=0,m=0,w=0,y=n.length;for(;w<y;){let S=n.charCodeAt(w);if(S>=48&&S<=57){let g=0;for(;w<y;){let b=n.charCodeAt(w);if(b>=48&&b<=57)g=g*10+(b-48),w++;else break}h+=g}else if(S===94)for(w++;w<y&&n.charCodeAt(w)>=65;)w++,h++;else if(S>=65){let g=n[w];if(w++,l&&c>0)for(let _=m;_<c;_++){let T=t[_];T.type==="skip"&&h>=T.start&&(h+=T.length,m=_+1)}let b=p,x=u;for(let _=d;_<i&&x<=h;_++,d=_){let T=e[_],$=T>>>4,C=T&15;C===4||C===1?b+=$:C===2||C===6||C===3?x+=$:C!==5&&(b+=$,x+=$)}p=b,u=x;let E=b-(x-h),A=E<a?r[E]:"X";s.push({start:h,base:A,qual:f?o[E]:void 0,altbase:g,length:1,type:"mismatch"}),h++}else w++}return s}var xs={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function ys(n=""){let e=0,t=[];for(let r=0,o=n.length;r<o;r++){let s=n.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=xs[s];t.push(e<<4|i),e=0}}return t}function xr(n=""){let e=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,o=0;for(let s=0,i=n.length;s<i;s++){let a=n.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[o++]=r<<4|xs[a],r=0)}return t}function vn(n,e,t,r,o){let s=ys(n),i=n?gs(s,t,r,o):[];return e&&t?i.concat(ws(e,s,i,t,o)):i}var oa=397,sa=387,ia=385;function bs(n){return(1<<n&oa)!==0}function Ss(n){return(1<<n&sa)!==0}function vs(n){return(1<<n&ia)!==0}function yr(n,e,t,r,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?r:t,l=[],h=1/0,d=-1/0,p=1/0,u=-1/0,m=(w,y)=>{p=Math.min(p,w,y),u=Math.max(u,w,y)};for(let w=0;w<n.length;w++){let y=n[w],S=y>>>4,g=y&15,b=g===9,x=b||bs(g)?S:0,E=b?n[++w]>>>4:Ss(g)?S:0,A=f+x,_=c+E*a,T=f,$=A;if($>=s&&T<=i)if(x>0){let C=Math.max(T,s),N=Math.min($,i);if(N>C)if(h=Math.min(h,C),d=Math.max(d,N),b){let P=E/S,U=N-C,Y=Math.round(U*P),I=Math.round(c+(C-f)*P*a);l.push(U<<4|9,Y<<4|9),m(I,I+Y*a)}else l.push(N-C<<4|g),vs(g)?m(c+(C-f)*a,c+(N-f)*a):m(c,c)}else E>0&&(b?l.push(y,n[w]):l.push(y),h=Math.min(h,f),d=Math.max(d,f),m(c,_));if(f=A,c=_,f>i)break}if(l.length!==0)return{start:h,end:d,mateStart:p,mateEnd:u,cigar:Uint32Array.from(l)}}function aa(n){return n===1||n===2||n===3}function br(n,e,t,r,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?r:t,l,h=!1,d=()=>{l!==void 0&&h&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,h=!1};for(let p=0;p<n.length;p++){let u=n[p],m=u>>>4,w=u&15,y=w===9,S=y?n[++p]:void 0,g=y||bs(w)?m:0,b=S!==void 0?S>>>4:Ss(w)?m:0,x=c+b*i;aa(w)&&m>=s?d():(g>0||b>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+g,l.tLo=Math.min(l.tLo,c,x),l.tHi=Math.max(l.tHi,c,x),l.ops.push(u),S!==void 0&&l.ops.push(S),h=h||y||vs(w)),f+=g,c=x}return d(),a}function Is(n){let e=n.get("CIGAR");return typeof e=="string"?e:void 0}function Es(n){let e=n.get("coarseCigar");return typeof e=="string"?e:void 0}function Sr(n){let e=Is(n),t=e===void 0?Es(n):void 0;return e!==void 0?xr(e):t!==void 0?ur(t):void 0}var fa=ce(ot(),1),ca=ce(Cs(),1);var la=ce(ot(),1);var ha=ce(Ds(),1);var Rs=ce(ot(),1),Te=class extends Rs.SimpleFeature{get(e){return e==="mismatches"?vn(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?pr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),o=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)mr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of vn(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var da=["CIGAR","cs","coarseCigar","cg","cr"];function pa(n){return typeof n=="object"&&n!==null&&"refName"in n&&"start"in n&&"end"in n&&typeof n.refName=="string"&&typeof n.start=="number"&&typeof n.end=="number"}function ua(n){let e=n.get("mate");return pa(e)?e:void 0}function ma(n,e,t,r){let o=Math.max(n.start,r.start),s=Math.min(n.end,r.end),i=(e.end-e.start)/Math.max(n.end-n.start,1),a=l=>t===-1?e.end-(l-n.start)*i:e.start+(l-n.start)*i,f=Math.round(a(o)),c=Math.round(a(s));return s>o?{start:o,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function ga(n,e,t,r,o){let s={start:n.get("start"),end:n.get("end")},i=n.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&r===void 0&&!o?void 0:Sr(n);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ma(s,e,i,t);return c===void 0?[]:[c]}else return(r===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:br(f,s.start,e.start,e.end,i,r)).flatMap(l=>{let h=yr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return h===void 0?[]:[h]})}function wa(n,e,t,r,o,s){let i=`:${r.start}-${r.end}${o}`,a=n.toJSON(),f={...a,uniqueId:`${n.id()}${i}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};a.syntenyId!==void 0&&(f.syntenyId=`${String(a.syntenyId)}${i}`);for(let c of da)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Te(f)}function Ms(n,e,t,r=!1){let o=ua(n);if(o===void 0)return[n];{let s=ga(n,o,e,t,r);return s.map((i,a)=>wa(n,o,i,e,s.length>1?`/${a}`:"",r))}}var In=class extends Ps.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=r,f=o&&this.recordsAreAlignments,c=(0,_s.createStatusFanOut)(a.statusCallback);return lr(t).pipe(et((l,h)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(et(d=>f?Ms(d,d.get("assemblyName")===l.assemblyName?l:{start:d.get("start"),end:d.get("end")},s,i):[d]),wn(),mt(d=>({index:h,features:d})))),wn(),et(l=>l.sort((h,d)=>h.index-d.index).flatMap(h=>h.features)))}};var An=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"}},Er=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}},Ar=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function ks(n,e){let t=Ce(e);return n[t]??n[e.sample]??t}function xa(n,e){return`${Ce(n)}#${n.contig}@${e.start.node}.${e.start.offset}`}function ya({alignment:n,assemblyName:e,refName:t,lane:r}){let{refStart:o,refEnd:s,strand:i,cigar:a}=n;if(!(!n.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=n,h=xa(f,n),d={uniqueId:h,assemblyName:e,refName:t,start:o,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:h,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new Te(d)}}function ba({pair:n,lane:e,mateLane:t}){let r=`${Ce(n.target)}#${n.target.contig}:${n.targetStart}-${n.targetEnd}|${Ce(n.query)}#${n.query.contig}:${n.queryStart}-${n.queryEnd}`;return new Te({uniqueId:r,assemblyName:e,refName:n.target.contig,start:n.targetStart,end:n.targetEnd,type:"match",strand:n.strand==="-"?-1:1,CIGAR:n.cigar,syntenyId:r,identity:n.matches/Math.max(n.columns,1),numMatches:n.matches,blockLen:n.columns,mate:{refName:n.query.contig,start:n.queryStart,end:n.queryEnd,assemblyName:t}})}function Os(n,e){return n instanceof _n&&(n.message=`Zoom in to about ${(0,wt.getBpDisplayStr)(n.fitsBp)} to see ${e}`),n}var vr=n=>!("uri"in n)||n.uri!=="",Cr=class extends In{constructor(){super(...arguments);this.graph=(0,Ir.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),r=this.getConf("haplotypeIndexLocation"),o=vr(r)?{location:r}:await Fo(t,this.pluginManager),s=o.location,i=await dt.open({source:(0,En.openLocation)(t,this.pluginManager),haplotypeIndex:s?(0,En.openLocation)(s,this.pluginManager):void 0}),a=this.getConf("assemblyNames")[0];if(a===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let f=await On(i),c=St({configured:this.getConf("referenceSample"),anchorPrefix:ze(this,a),referenceSamples:f});return{db:i,anchor:a,referenceSample:c,referenceSamples:f,unreadableIndex:o.unreadable}}});this.gaf=(0,Ir.cachedSetup)({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),r=this.getConf(["readsIndex","location"]);return vr(t)?new Kt((0,En.openLocation)(t,this.pluginManager),vr(r)?zr(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,r){let{db:o,referenceSample:s}=await this.graph(r);return Nn(o,s,t)}async getHaplotypes(t={}){let{db:r,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=Ce(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:o.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Pn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:ks(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:ze(this,i),f=(await r.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:bt(Ce(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let o=t===void 0||t.length===0?void 0:t.map(s=>ze(this,s));return o===void 0&&r===void 0?void 0:s=>kn(s,o)&&(r===void 0||bt(Ce(s),r))}async getSubgraph(t,r={}){let{db:o,anchor:s,unreadableIndex:i}=await this.graph(),{assemblyName:a,refName:f,start:c,end:l}=t;if(a!==s)throw new Ar(a,s);let h=await this.referenceQuery(f,{}),d=this.keepPredicate(r.haplotypes);if(d!==void 0&&!o.hasHaplotypeIndex)throw new An(i);return Tn(o,h,c,l,{context:this.getConf("context"),snarls:r.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:r.signal,keep:d}).catch(p=>{throw Os(p,"the graph")})}async getReads(t,r={}){let o=await this.gaf(r);return o?o.readsOver(new Set(t),r):{records:[],total:0}}async laneHaplotypes(t,r){let o=ze(this,t);return(await this.getHaplotypes(r)).filter(s=>bt(s.prefix,o))}async anchorFeatures(t,r){let{db:o}=await this.graph(r),{assemblyName:s,refName:i,start:a,end:f}=t,c=ze(this,r.targetAssemblyName),l=Pn(this),h=this.keepPredicate(r.haplotypes,c),d=await this.referenceQuery(i,r),p=this.getConf("nodeLimit");return(d?await(0,wt.updateStatus)(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,r.statusCallback,()=>o.getAlignments({path:d,start:a,end:f,context:this.getConf("context"),haplotypes:"all",limit:p,signal:r.signal,keep:h}).catch(m=>{throw Os(vt(m,p,f-a)??m,"lanes")})):[]).flatMap(m=>{let w=m.resolved?ya({alignment:m,assemblyName:s,refName:i,lane:ks(l,m.name)}):void 0;return w===void 0?[]:[w]})}async pairFeatures(t,r,o){let{targetAssemblyName:s}=o;if(s===void 0)throw new Er(r);let{db:i}=await this.graph(o),{refName:a,start:f,end:c}=t,l=await this.laneHaplotypes(r,o),h=await this.laneHaplotypes(s,o),d=[...l,...h],p=await this.referenceQuery(a,o),u=this.getConf("nodeLimit"),m=y=>i.getSubgraphs({path:y,start:f,end:c,context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:u,signal:o.signal,keep:S=>d.some(g=>g.sample===S.sample&&g.haplotype===S.haplotype)}).catch(S=>{throw vt(S,u,c-f)??S});return(p&&l.length>0&&h.length>0?await(0,wt.updateStatus)(`Reading ${r} against ${s}`,o.statusCallback,()=>m(p)):[]).flatMap(y=>l.flatMap(S=>h.flatMap(g=>y.pairAlignments({target:S,query:g,bases:!1}).map(b=>ba({pair:b,lane:r,mateLane:s})))))}getFeatures(t,r={}){return(0,Ns.ObservableCreate)(async o=>{let{db:s,anchor:i,unreadableIndex:a}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new An(a);if(t.assemblyName===i){let f=r.queryAssemblyName===void 0?await this.anchorFeatures(t,r):await this.pairFeatures(t,r.queryAssemblyName,r);for(let c of f)o.next(c)}o.complete()},r.signal)}};export{Ar as HaplotypeWindowError,An as NoHaplotypeIndexError,Hs as NoReferenceSampleError,_n as NodeLimitError,Er as PairTargetError,Cr as default,ya as fragmentFeature,Ce as haplotypePrefix,ks as laneAssemblyName,vt as nodeLimitError,ba as pairFeature,St as resolveReferenceSample};
|
|
8
|
-
//# sourceMappingURL=GbzBaseSyntenyAdapter-
|
|
8
|
+
//# sourceMappingURL=GbzBaseSyntenyAdapter-Z4NDQGEZ.js.map
|