jbrowse-plugin-graphgenomeviewer 6.9.2 → 6.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/dist/chunks/AddTrackWorkflow-OBRE3QJE.js +2 -0
  2. package/dist/chunks/AddTrackWorkflow-OBRE3QJE.js.map +7 -0
  3. package/dist/chunks/ChooseSamplesDialog-75F3KRRG.js +2 -0
  4. package/dist/chunks/{ChooseSamplesDialog-GWMJ7B5D.js.map → ChooseSamplesDialog-75F3KRRG.js.map} +2 -2
  5. package/dist/chunks/ChooseWalksDialog-L23LYMKI.js +2 -0
  6. package/dist/chunks/{ChooseWalksDialog-6HVVZMFD.js.map → ChooseWalksDialog-L23LYMKI.js.map} +2 -2
  7. package/dist/chunks/GbzBaseSyntenyAdapter-WPRJGI7E.js +8 -0
  8. package/dist/chunks/GbzBaseSyntenyAdapter-WPRJGI7E.js.map +7 -0
  9. package/dist/chunks/GraphGenomeView-BSJYTSFN.js +10 -0
  10. package/dist/chunks/{GraphGenomeView-WPF4JRXE.js.map → GraphGenomeView-BSJYTSFN.js.map} +4 -4
  11. package/dist/chunks/GraphTrackSettingsDialog-F3YNSD54.js +6 -0
  12. package/dist/chunks/{GraphTrackSettingsDialog-H4QX5DAF.js.map → GraphTrackSettingsDialog-F3YNSD54.js.map} +2 -2
  13. package/dist/chunks/HighlightColorDialog-CU5FQLRJ.js +2 -0
  14. package/dist/chunks/{HighlightColorDialog-4BYDGOLH.js.map → HighlightColorDialog-CU5FQLRJ.js.map} +2 -2
  15. package/dist/chunks/LinearGraphDisplay-VW7DGOVT.js +2 -0
  16. package/dist/chunks/LinearGraphDisplay-VW7DGOVT.js.map +7 -0
  17. package/dist/chunks/MinigraphBubbleAdapter-GCHP5TFS.js +2 -0
  18. package/dist/chunks/{MinigraphBubbleAdapter-PP3LVTLY.js.map → MinigraphBubbleAdapter-GCHP5TFS.js.map} +2 -2
  19. package/dist/chunks/RgfaTabixAdapter-YH726UKU.js +3 -0
  20. package/dist/chunks/RgfaTabixAdapter-YH726UKU.js.map +7 -0
  21. package/dist/chunks/TrackWarningsDialog-XBUQM2ZH.js +2 -0
  22. package/dist/chunks/{TrackWarningsDialog-YL2UP35Z.js.map → TrackWarningsDialog-XBUQM2ZH.js.map} +2 -2
  23. package/dist/chunks/{bandage-layout-3AR6BCUD-4WVXWYHQ.js → bandage-layout-3AR6BCUD-2BIG5R3E.js} +2 -2
  24. package/dist/chunks/{bandage-layout-3AR6BCUD-4WVXWYHQ.js.map → bandage-layout-3AR6BCUD-2BIG5R3E.js.map} +2 -2
  25. package/dist/chunks/chunk-5JXGPUTF.js +2 -0
  26. package/dist/chunks/{chunk-TGP6EJGQ.js.map → chunk-5JXGPUTF.js.map} +2 -2
  27. package/dist/chunks/chunk-6AYSOQOK.js +2 -0
  28. package/dist/chunks/chunk-6AYSOQOK.js.map +7 -0
  29. package/dist/chunks/chunk-6OPB7FOJ.js +2 -0
  30. package/dist/chunks/chunk-6OPB7FOJ.js.map +7 -0
  31. package/dist/chunks/{chunk-2GJ5G3SR.js → chunk-AB2XVNNS.js} +2 -2
  32. package/dist/chunks/{chunk-2GJ5G3SR.js.map → chunk-AB2XVNNS.js.map} +4 -4
  33. package/dist/chunks/{chunk-PJBJA467.js → chunk-BXZLLHYP.js} +2 -2
  34. package/dist/chunks/{chunk-PJBJA467.js.map → chunk-BXZLLHYP.js.map} +1 -1
  35. package/dist/chunks/chunk-D7FMSRTU.js +2 -0
  36. package/dist/chunks/chunk-D7FMSRTU.js.map +7 -0
  37. package/dist/chunks/chunk-DOLO4I5J.js +2 -0
  38. package/dist/chunks/chunk-DOLO4I5J.js.map +7 -0
  39. package/dist/chunks/chunk-ECD5B2ZM.js +2 -0
  40. package/dist/chunks/chunk-ECD5B2ZM.js.map +7 -0
  41. package/dist/chunks/chunk-ELLLNUKS.js +2 -0
  42. package/dist/chunks/chunk-ELLLNUKS.js.map +7 -0
  43. package/dist/chunks/{chunk-2XEEHEDF.js → chunk-FSCO2SM4.js} +1 -1
  44. package/dist/chunks/{chunk-2XEEHEDF.js.map → chunk-FSCO2SM4.js.map} +1 -1
  45. package/dist/chunks/{chunk-TEEA6NQI.js → chunk-I2YWIO5M.js} +1 -1
  46. package/dist/chunks/{chunk-TEEA6NQI.js.map → chunk-I2YWIO5M.js.map} +1 -1
  47. package/dist/chunks/chunk-I574RVHG.js +2 -0
  48. package/dist/chunks/chunk-I574RVHG.js.map +7 -0
  49. package/dist/chunks/chunk-JMBDTNUR.js +2 -0
  50. package/dist/chunks/chunk-JMBDTNUR.js.map +7 -0
  51. package/dist/chunks/chunk-LEWWQ7ZK.js +2 -0
  52. package/dist/chunks/chunk-LEWWQ7ZK.js.map +7 -0
  53. package/dist/chunks/chunk-MDRNFKXW.js +3 -0
  54. package/dist/chunks/chunk-MDRNFKXW.js.map +7 -0
  55. package/dist/chunks/{chunk-IOEK2X7F.js → chunk-NU53CDGF.js} +1 -1
  56. package/dist/chunks/{chunk-IOEK2X7F.js.map → chunk-NU53CDGF.js.map} +1 -1
  57. package/dist/chunks/chunk-OGQ6OQDN.js +2 -0
  58. package/dist/chunks/chunk-OGQ6OQDN.js.map +7 -0
  59. package/dist/chunks/{chunk-6AWRYNB2.js → chunk-PR5YUSXN.js} +1 -1
  60. package/dist/chunks/{chunk-6AWRYNB2.js.map → chunk-PR5YUSXN.js.map} +1 -1
  61. package/dist/chunks/{chunk-OEU2V7TV.js → chunk-R4DSKZ5P.js} +2 -2
  62. package/dist/chunks/{chunk-OEU2V7TV.js.map → chunk-R4DSKZ5P.js.map} +1 -1
  63. package/dist/chunks/chunk-SS5WD35T.js +2 -0
  64. package/dist/chunks/{chunk-TAE3AVU7.js.map → chunk-SS5WD35T.js.map} +2 -2
  65. package/dist/chunks/chunk-TENPGIPX.js +2 -0
  66. package/dist/chunks/chunk-TENPGIPX.js.map +7 -0
  67. package/dist/chunks/chunk-UQT5WHCD.js +3 -0
  68. package/dist/chunks/{chunk-NN5YTZ36.js.map → chunk-UQT5WHCD.js.map} +4 -4
  69. package/dist/chunks/chunk-X4NNWAXW.js +2 -0
  70. package/dist/chunks/chunk-X4NNWAXW.js.map +7 -0
  71. package/dist/chunks/{chunk-7QEJLDYY.js → chunk-XKN5LH2Z.js} +1 -1
  72. package/dist/chunks/{chunk-7QEJLDYY.js.map → chunk-XKN5LH2Z.js.map} +1 -1
  73. package/dist/chunks/chunk-YBIU6GD5.js +2 -0
  74. package/dist/chunks/chunk-YBIU6GD5.js.map +7 -0
  75. package/dist/chunks/executeDiagonalize-JKESYBXN.js +2 -0
  76. package/dist/chunks/executeDiagonalize-JKESYBXN.js.map +7 -0
  77. package/dist/chunks/renderSvg-QXWTNVPN.js +2 -0
  78. package/dist/chunks/renderSvg-QXWTNVPN.js.map +7 -0
  79. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -5
  80. package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
  81. package/package.json +4 -4
  82. package/src/GetSubgraph.test.ts +23 -0
  83. package/src/GetSubgraph.ts +12 -3
  84. package/src/GraphGenomeView/pane/loadActions.ts +7 -6
  85. package/src/RgfaTabixAdapter/RgfaTabixAdapter.ts +8 -3
  86. package/src/RgfaTabixAdapter/walkFiles.test.ts +42 -22
  87. package/src/RgfaTabixAdapter/walkRows.test.ts +8 -8
  88. package/src/RgfaTabixAdapter/walkRows.ts +86 -33
  89. package/src/version.ts +1 -1
  90. package/dist/chunks/AddTrackWorkflow-YGKG57NL.js +0 -2
  91. package/dist/chunks/AddTrackWorkflow-YGKG57NL.js.map +0 -7
  92. package/dist/chunks/ChooseSamplesDialog-GWMJ7B5D.js +0 -2
  93. package/dist/chunks/ChooseWalksDialog-6HVVZMFD.js +0 -2
  94. package/dist/chunks/GbzBaseSyntenyAdapter-56NJEBAK.js +0 -8
  95. package/dist/chunks/GbzBaseSyntenyAdapter-56NJEBAK.js.map +0 -7
  96. package/dist/chunks/GraphGenomeView-WPF4JRXE.js +0 -10
  97. package/dist/chunks/GraphTrackSettingsDialog-H4QX5DAF.js +0 -6
  98. package/dist/chunks/HighlightColorDialog-4BYDGOLH.js +0 -2
  99. package/dist/chunks/LinearGraphDisplay-ZJNR2KCT.js +0 -2
  100. package/dist/chunks/LinearGraphDisplay-ZJNR2KCT.js.map +0 -7
  101. package/dist/chunks/MinigraphBubbleAdapter-PP3LVTLY.js +0 -2
  102. package/dist/chunks/RgfaTabixAdapter-KOIMYOR3.js +0 -4
  103. package/dist/chunks/RgfaTabixAdapter-KOIMYOR3.js.map +0 -7
  104. package/dist/chunks/TrackWarningsDialog-YL2UP35Z.js +0 -2
  105. package/dist/chunks/chunk-3RFIGNJ2.js +0 -2
  106. package/dist/chunks/chunk-3RFIGNJ2.js.map +0 -7
  107. package/dist/chunks/chunk-5KPFOT6O.js +0 -2
  108. package/dist/chunks/chunk-5KPFOT6O.js.map +0 -7
  109. package/dist/chunks/chunk-64LZZURD.js +0 -2
  110. package/dist/chunks/chunk-64LZZURD.js.map +0 -7
  111. package/dist/chunks/chunk-BFBKRNH4.js +0 -2
  112. package/dist/chunks/chunk-BFBKRNH4.js.map +0 -7
  113. package/dist/chunks/chunk-DTU5H2PS.js +0 -2
  114. package/dist/chunks/chunk-DTU5H2PS.js.map +0 -7
  115. package/dist/chunks/chunk-EMN4WZDQ.js +0 -3
  116. package/dist/chunks/chunk-EMN4WZDQ.js.map +0 -7
  117. package/dist/chunks/chunk-FCWXYIFC.js +0 -2
  118. package/dist/chunks/chunk-FCWXYIFC.js.map +0 -7
  119. package/dist/chunks/chunk-FY3BTKY4.js +0 -2
  120. package/dist/chunks/chunk-FY3BTKY4.js.map +0 -7
  121. package/dist/chunks/chunk-J4OLMLS5.js +0 -2
  122. package/dist/chunks/chunk-J4OLMLS5.js.map +0 -7
  123. package/dist/chunks/chunk-J6KYLXRD.js +0 -2
  124. package/dist/chunks/chunk-J6KYLXRD.js.map +0 -7
  125. package/dist/chunks/chunk-K33IZSO2.js +0 -2
  126. package/dist/chunks/chunk-K33IZSO2.js.map +0 -7
  127. package/dist/chunks/chunk-KWAXLUPQ.js +0 -2
  128. package/dist/chunks/chunk-KWAXLUPQ.js.map +0 -7
  129. package/dist/chunks/chunk-NN5YTZ36.js +0 -3
  130. package/dist/chunks/chunk-NXZT63HN.js +0 -2
  131. package/dist/chunks/chunk-NXZT63HN.js.map +0 -7
  132. package/dist/chunks/chunk-OHRUB7O6.js +0 -2
  133. package/dist/chunks/chunk-OHRUB7O6.js.map +0 -7
  134. package/dist/chunks/chunk-TAE3AVU7.js +0 -2
  135. package/dist/chunks/chunk-TGP6EJGQ.js +0 -2
  136. package/dist/chunks/chunk-VOJMYHOU.js +0 -2
  137. package/dist/chunks/chunk-VOJMYHOU.js.map +0 -7
  138. package/dist/chunks/executeDiagonalize-DTKT5PPY.js +0 -2
  139. package/dist/chunks/executeDiagonalize-DTKT5PPY.js.map +0 -7
  140. package/dist/chunks/renderSvg-35VDH2K7.js +0 -2
  141. package/dist/chunks/renderSvg-35VDH2K7.js.map +0 -7
@@ -0,0 +1,2 @@
1
+ import{a as P,b as N,c as _,f as W}from"./chunk-SS5WD35T.js";import{d as G}from"./chunk-ELLLNUKS.js";import"./chunk-D7FMSRTU.js";import{b as F,j as L,m as T}from"./chunk-TENPGIPX.js";import{g as r}from"./chunk-6OPB7FOJ.js";import{A as E,B as I,E as u,a as S,e as w,f as c,n as R,r as x,s as v,t as M,z as B}from"./chunk-ECD5B2ZM.js";import{b as o,c as b,d as A}from"./chunk-JMBDTNUR.js";var s=JBrowseExports["@jbrowse/core/util/tss-react"],q=t=>s!=null&&t in Object(s)?s[t]:Object.assign(function(){throw new Error("This JBrowse does not provide '"+t+"' from '@jbrowse/core/util/tss-react' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse")},{jbrowseHostMissing:t});var H=q("makeStyles"),Y=s&&s.__esModule?s.default:s;var K=H()(t=>({paper:{margin:t.spacing(),padding:t.spacing()},field:{marginTop:t.spacing(2)},submit:{marginTop:25,marginBottom:100,display:"block"}})),Q=["RgfaTabixAdapter","GbzBaseSyntenyAdapter","MinigraphBubbleAdapter"],U=A(function({model:a}){let{classes:i}=K(),g=L(a),p=G(a),[n,j]=r("RgfaTabixAdapter"),[l,O]=r(),[f,z]=r(),[y,J]=r(),d=n==="GbzBaseSyntenyAdapter",[k,D]=r(""),[m,V]=r("Pangenome graph"),[C,h]=r();function X(){if(!(!l||!a.assembly))try{h(void 0);let e=m.trim();F({model:a,session:g,conf:W({choice:n,loc:l,indexLoc:f,readsLoc:d?y:void 0,assembly:a.assembly,sample:k,trackId:T({name:e}),name:e})})}catch(e){h(e)}}return b(B,{className:i.paper,children:[C?o(w,{error:C}):null,b(x,{children:[o(M,{children:"File type"}),o(I,{value:n,onChange:e=>{j(e.target.value),h(void 0)},children:Q.map(e=>o(v,{value:e,control:o(E,{}),label:P[e]},e))})]}),o(c,{location:l,name:N[n],rootModel:p,setLocation:O}),o(c,{location:f,name:_[n],rootModel:p,setLocation:z}),d?o(c,{location:y,name:"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)",rootModel:p,setLocation:J}):null,o(u,{className:i.field,value:k,onChange:e=>{D(e.target.value)},label:"Sample name in the graph",slotProps:{htmlInput:{"data-testid":"graph-sample-input"}},helperText:d?"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample":"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}),o(u,{className:i.field,value:m,helperText:"Track name",slotProps:{htmlInput:{"data-testid":"graph-track-name-input"}},onChange:e=>{V(e.target.value)}}),o(S,{session:g,helperText:"Select assembly to add track to",selected:a.assembly,onChange:e=>{a.setAssembly(e)},fullWidth:!0}),o(R,{variant:"contained",className:i.submit,disabled:!l||!m.trim()||!a.assembly,onClick:X,children:"Submit"})]})}),ie=U;export{ie as default};
2
+ //# sourceMappingURL=AddTrackWorkflow-OBRE3QJE.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["host:@jbrowse/core/util/tss-react", "../../src/GraphAddTrackWorkflow/AddTrackWorkflow.tsx"],
4
+ "sourcesContent": ["const host = JBrowseExports[\"@jbrowse/core/util/tss-react\"]\nconst read = name =>\n host != null && name in Object(host)\n ? host[name]\n : Object.assign(\n function () {\n throw new Error(\n \"This JBrowse does not provide '\" + name + \"' from '\" + \"@jbrowse/core/util/tss-react\" + \"' to plugins: GraphGenomeView was built for a different JBrowse version, so update the plugin or JBrowse\",\n )\n },\n { jbrowseHostMissing: name },\n )\nexport const cx = /* @__PURE__ */ read(\"cx\")\nexport const keyframes = /* @__PURE__ */ read(\"keyframes\")\nexport const makeStyles = /* @__PURE__ */ read(\"makeStyles\")\nexport default host && host.__esModule ? host.default : host", "import { useState } from 'react'\n\nimport { AssemblySelector, ErrorMessage, FileSelector } from '@jbrowse/core/ui'\nimport { addTrackFromWidget, getSession, makeTrackId } from '@jbrowse/core/util'\nimport { makeStyles } from '@jbrowse/core/util/tss-react'\nimport { getRoot } from '@jbrowse/mobx-state-tree'\nimport {\n Button,\n FormControl,\n FormControlLabel,\n FormLabel,\n Paper,\n Radio,\n RadioGroup,\n TextField,\n} from '@mui/material'\nimport { observer } from 'mobx-react'\n\nimport {\n GRAPH_FILE_FIELDS,\n GRAPH_FILE_LABELS,\n GRAPH_INDEX_FIELDS,\n buildTrackConfig,\n} from './buildTrackConfig'\n\nimport type { GraphFileChoice } from './buildTrackConfig'\nimport type {\n AbstractRootModel,\n AddTrackWorkflowModel,\n FileLocation,\n} from '@jbrowse/core/util'\n\nconst useStyles = makeStyles()(theme => ({\n paper: {\n margin: theme.spacing(),\n padding: theme.spacing(),\n },\n field: {\n marginTop: theme.spacing(2),\n },\n submit: {\n marginTop: 25,\n marginBottom: 100,\n display: 'block',\n },\n}))\n\nconst CHOICES: GraphFileChoice[] = [\n 'RgfaTabixAdapter',\n 'GbzBaseSyntenyAdapter',\n 'MinigraphBubbleAdapter',\n]\n\nconst GraphAddTrackWidget = observer(function GraphAddTrackWidget({\n model,\n}: {\n model: AddTrackWorkflowModel\n}) {\n const { classes } = useStyles()\n const session = getSession(model)\n const rootModel = getRoot<AbstractRootModel>(model)\n const [choice, setChoice] = useState<GraphFileChoice>('RgfaTabixAdapter')\n const [loc, setLoc] = useState<FileLocation>()\n const [indexLoc, setIndexLoc] = useState<FileLocation>()\n const [readsLoc, setReadsLoc] = useState<FileLocation>()\n const gbz = choice === 'GbzBaseSyntenyAdapter'\n const [sample, setSample] = useState('')\n const [trackName, setTrackName] = useState('Pangenome graph')\n const [error, setError] = useState<unknown>()\n\n function handleSubmit() {\n if (!loc || !model.assembly) {\n return\n }\n try {\n setError(undefined)\n const name = trackName.trim()\n addTrackFromWidget({\n model,\n session,\n conf: buildTrackConfig({\n choice,\n loc,\n indexLoc,\n readsLoc: gbz ? readsLoc : undefined,\n assembly: model.assembly,\n sample,\n trackId: makeTrackId({ name }),\n name,\n }),\n })\n } catch (e) {\n setError(e)\n }\n }\n\n return (\n <Paper className={classes.paper}>\n {error ? <ErrorMessage error={error} /> : null}\n <FormControl>\n <FormLabel>File type</FormLabel>\n <RadioGroup\n value={choice}\n onChange={event => {\n setChoice(event.target.value as GraphFileChoice)\n setError(undefined)\n }}\n >\n {CHOICES.map(option => (\n <FormControlLabel\n key={option}\n value={option}\n control={<Radio />}\n label={GRAPH_FILE_LABELS[option]}\n />\n ))}\n </RadioGroup>\n </FormControl>\n <FileSelector\n location={loc}\n name={GRAPH_FILE_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setLoc}\n />\n <FileSelector\n location={indexLoc}\n name={GRAPH_INDEX_FIELDS[choice]}\n rootModel={rootModel}\n setLocation={setIndexLoc}\n />\n {gbz ? (\n <FileSelector\n location={readsLoc}\n name=\"Path to reads aligned to the graph as GAF (optional; a .gz is read by the .tbi beside it)\"\n rootModel={rootModel}\n setLocation={setReadsLoc}\n />\n ) : null}\n <TextField\n className={classes.field}\n value={sample}\n onChange={event => {\n setSample(event.target.value)\n }}\n label=\"Sample name in the graph\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-sample-input' } }}\n helperText={\n gbz\n ? \"Optional. The graph's sample for this assembly, e.g. GRCh38 where the assembly is hg38; leave blank when they share a name or the graph has one reference sample\"\n : \"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\"\n }\n placeholder=\"GRCh38\"\n fullWidth\n />\n <TextField\n className={classes.field}\n value={trackName}\n helperText=\"Track name\"\n slotProps={{ htmlInput: { 'data-testid': 'graph-track-name-input' } }}\n onChange={event => {\n setTrackName(event.target.value)\n }}\n />\n <AssemblySelector\n session={session}\n helperText=\"Select assembly to add track to\"\n selected={model.assembly}\n onChange={arg => {\n model.setAssembly(arg)\n }}\n fullWidth\n />\n <Button\n variant=\"contained\"\n className={classes.submit}\n disabled={!loc || !trackName.trim() || !model.assembly}\n onClick={handleSubmit}\n >\n Submit\n </Button>\n </Paper>\n )\n})\n\nexport default GraphAddTrackWidget\n"],
5
+ "mappings": "mYAAA,IAAMA,EAAO,eAAe,8BAA8B,EACpDC,EAAOC,GACXF,GAAQ,MAAQE,KAAQ,OAAOF,CAAI,EAC/BA,EAAKE,CAAI,EACT,OAAO,OACL,UAAY,CACV,MAAM,IAAI,MACR,kCAAoCA,EAAO,8IAC7C,CACF,EACA,CAAE,mBAAoBA,CAAK,CAC7B,EAGC,IAAMC,EAA6BC,EAAK,YAAY,EACpDC,EAAQC,GAAQA,EAAK,WAAaA,EAAK,QAAUA,ECiBxD,IAAMC,EAAYC,EAAW,EAAEC,IAAU,CACvC,MAAO,CACL,OAAQA,EAAM,QAAQ,EACtB,QAASA,EAAM,QAAQ,CACzB,EACA,MAAO,CACL,UAAWA,EAAM,QAAQ,CAAC,CAC5B,EACA,OAAQ,CACN,UAAW,GACX,aAAc,IACd,QAAS,OACX,CACF,EAAE,EAEIC,EAA6B,CACjC,mBACA,wBACA,wBACF,EAEMC,EAAsBC,EAAS,SAA6B,CAChE,MAAAC,CACF,EAEG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIP,EAAU,EACxBQ,EAAUC,EAAWH,CAAK,EAC1BI,EAAYC,EAA2BL,CAAK,EAC5C,CAACM,EAAQC,CAAS,EAAIC,EAA0B,kBAAkB,EAClE,CAACC,EAAKC,CAAM,EAAIF,EAAuB,EACvC,CAACG,EAAUC,CAAW,EAAIJ,EAAuB,EACjD,CAACK,EAAUC,CAAW,EAAIN,EAAuB,EACjDO,EAAMT,IAAW,wBACjB,CAACU,EAAQC,CAAS,EAAIT,EAAS,EAAE,EACjC,CAACU,EAAWC,CAAY,EAAIX,EAAS,iBAAiB,EACtD,CAACY,EAAOC,CAAQ,EAAIb,EAAkB,EAE5C,SAASc,GAAe,CACtB,GAAI,GAACb,GAAO,CAACT,EAAM,UAGnB,GAAI,CACFqB,EAAS,MAAS,EAClB,IAAME,EAAOL,EAAU,KAAK,EAC5BM,EAAmB,CACjB,MAAAxB,EACA,QAAAE,EACA,KAAMuB,EAAiB,CACrB,OAAAnB,EACA,IAAAG,EACA,SAAAE,EACA,SAAUI,EAAMF,EAAW,OAC3B,SAAUb,EAAM,SAChB,OAAAgB,EACA,QAASU,EAAY,CAAE,KAAAH,CAAK,CAAC,EAC7B,KAAAA,CACF,CAAC,CACH,CAAC,CACH,OAAS,EAAG,CACVF,EAAS,CAAC,CACZ,CACF,CAEA,OACEM,EAACC,EAAA,CAAM,UAAW3B,EAAQ,MACvB,UAAAmB,EAAQS,EAACC,EAAA,CAAa,MAAOV,EAAO,EAAK,KAC1CO,EAACI,EAAA,CACC,UAAAF,EAACG,EAAA,CAAU,qBAAS,EACpBH,EAACI,EAAA,CACC,MAAO3B,EACP,SAAU4B,GAAS,CACjB3B,EAAU2B,EAAM,OAAO,KAAwB,EAC/Cb,EAAS,MAAS,CACpB,EAEC,SAAAxB,EAAQ,IAAIsC,GACXN,EAACO,EAAA,CAEC,MAAOD,EACP,QAASN,EAACQ,EAAA,EAAM,EAChB,MAAOC,EAAkBH,CAAM,GAH1BA,CAIP,CACD,EACH,GACF,EACAN,EAACU,EAAA,CACC,SAAU9B,EACV,KAAM+B,EAAkBlC,CAAM,EAC9B,UAAWF,EACX,YAAaM,EACf,EACAmB,EAACU,EAAA,CACC,SAAU5B,EACV,KAAM8B,EAAmBnC,CAAM,EAC/B,UAAWF,EACX,YAAaQ,EACf,EACCG,EACCc,EAACU,EAAA,CACC,SAAU1B,EACV,KAAK,4FACL,UAAWT,EACX,YAAaU,EACf,EACE,KACJe,EAACa,EAAA,CACC,UAAWzC,EAAQ,MACnB,MAAOe,EACP,SAAUkB,GAAS,CACjBjB,EAAUiB,EAAM,OAAO,KAAK,CAC9B,EACA,MAAM,2BACN,UAAW,CAAE,UAAW,CAAE,cAAe,oBAAqB,CAAE,EAChE,WACEnB,EACI,mKACA,qJAEN,YAAY,SACZ,UAAS,GACX,EACAc,EAACa,EAAA,CACC,UAAWzC,EAAQ,MACnB,MAAOiB,EACP,WAAW,aACX,UAAW,CAAE,UAAW,CAAE,cAAe,wBAAyB,CAAE,EACpE,SAAUgB,GAAS,CACjBf,EAAae,EAAM,OAAO,KAAK,CACjC,EACF,EACAL,EAACc,EAAA,CACC,QAASzC,EACT,WAAW,kCACX,SAAUF,EAAM,SAChB,SAAU4C,GAAO,CACf5C,EAAM,YAAY4C,CAAG,CACvB,EACA,UAAS,GACX,EACAf,EAACgB,EAAA,CACC,QAAQ,YACR,UAAW5C,EAAQ,OACnB,SAAU,CAACQ,GAAO,CAACS,EAAU,KAAK,GAAK,CAAClB,EAAM,SAC9C,QAASsB,EACV,kBAED,GACF,CAEJ,CAAC,EAEMwB,GAAQhD",
6
+ "names": ["host", "read", "name", "makeStyles", "read", "tss_react_default", "host", "useStyles", "makeStyles", "theme", "CHOICES", "GraphAddTrackWidget", "observer", "model", "classes", "session", "getSession", "rootModel", "getRoot", "choice", "setChoice", "useState", "loc", "setLoc", "indexLoc", "setIndexLoc", "readsLoc", "setReadsLoc", "gbz", "sample", "setSample", "trackName", "setTrackName", "error", "setError", "handleSubmit", "name", "addTrackFromWidget", "buildTrackConfig", "makeTrackId", "jsxs", "Paper", "jsx", "ErrorMessage", "FormControl", "FormLabel", "RadioGroup", "event", "option", "FormControlLabel", "Radio", "GRAPH_FILE_LABELS", "FileSelector", "GRAPH_FILE_FIELDS", "GRAPH_INDEX_FIELDS", "TextField", "AssemblySelector", "arg", "Button", "AddTrackWorkflow_default"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as i}from"./chunk-5JXGPUTF.js";import"./chunk-6OPB7FOJ.js";import"./chunk-ECD5B2ZM.js";import{b as a,d as s}from"./chunk-JMBDTNUR.js";var t=s(function({model:o,onClose:p}){let{samples:l}=o.walkRowSampleChoices;return a(i,{title:"Choose samples",label:"Samples",testId:"graph-choose-samples",caption:`${l.length.toLocaleString()} samples in this cut. Their walks show in pairs, in the order picked.`,options:l,initial:o.walkRowSamples??[],confirmLabel:e=>e.length>0?"Show these samples":"Show every sample",onPick:e=>{o.setWalkRowSamples(e.length>0?e:void 0)},onClose:p})}),h=t;export{h as default};
2
+ //# sourceMappingURL=ChooseSamplesDialog-75F3KRRG.js.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/GraphGenomeView/components/ChooseSamplesDialog.tsx"],
4
4
  "sourcesContent": ["import { observer } from 'mobx-react'\n\nimport PickNamesDialog from './PickNamesDialog'\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\nconst ChooseSamplesDialog = observer(function ChooseSamplesDialog({\n model,\n onClose,\n}: {\n model: SamplePicker\n onClose: () => void\n}) {\n const { samples } = model.walkRowSampleChoices\n return (\n <PickNamesDialog\n title=\"Choose samples\"\n label=\"Samples\"\n testId=\"graph-choose-samples\"\n caption={`${samples.length.toLocaleString()} samples in this cut. Their walks show in pairs, in the order picked.`}\n options={samples}\n initial={model.walkRowSamples ?? []}\n confirmLabel={picked =>\n picked.length > 0 ? 'Show these samples' : 'Show every sample'\n }\n onPick={picked => {\n model.setWalkRowSamples(picked.length > 0 ? picked : undefined)\n }}\n onClose={onClose}\n />\n )\n})\n\nexport default ChooseSamplesDialog\n"],
5
- "mappings": "uLAAA,IAAAA,EAAyB,SAqBrB,IAAAC,EAAA,SATEC,KAAsB,YAAS,SAA6B,CAChE,MAAAC,EACA,QAAAC,CACF,EAGG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIF,EAAM,qBAC1B,SACE,OAACG,EAAA,CACC,MAAM,iBACN,MAAM,UACN,OAAO,uBACP,QAAS,GAAGD,EAAQ,OAAO,eAAe,CAAC,wEAC3C,QAASA,EACT,QAASF,EAAM,gBAAkB,CAAC,EAClC,aAAcI,GACZA,EAAO,OAAS,EAAI,qBAAuB,oBAE7C,OAAQA,GAAU,CAChBJ,EAAM,kBAAkBI,EAAO,OAAS,EAAIA,EAAS,MAAS,CAChE,EACA,QAASH,EACX,CAEJ,CAAC,EAEMI,EAAQN",
6
- "names": ["import_mobx_react", "import_jsx_runtime", "ChooseSamplesDialog", "model", "onClose", "samples", "PickNamesDialog", "picked", "ChooseSamplesDialog_default"]
5
+ "mappings": "+IAYA,IAAMA,EAAsBC,EAAS,SAA6B,CAChE,MAAAC,EACA,QAAAC,CACF,EAGG,CACD,GAAM,CAAE,QAAAC,CAAQ,EAAIF,EAAM,qBAC1B,OACEG,EAACC,EAAA,CACC,MAAM,iBACN,MAAM,UACN,OAAO,uBACP,QAAS,GAAGF,EAAQ,OAAO,eAAe,CAAC,wEAC3C,QAASA,EACT,QAASF,EAAM,gBAAkB,CAAC,EAClC,aAAcK,GACZA,EAAO,OAAS,EAAI,qBAAuB,oBAE7C,OAAQA,GAAU,CAChBL,EAAM,kBAAkBK,EAAO,OAAS,EAAIA,EAAS,MAAS,CAChE,EACA,QAASJ,EACX,CAEJ,CAAC,EAEMK,EAAQR",
6
+ "names": ["ChooseSamplesDialog", "observer", "model", "onClose", "samples", "jsx", "PickNamesDialog", "picked", "ChooseSamplesDialog_default"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ import{a as t}from"./chunk-5JXGPUTF.js";import"./chunk-6OPB7FOJ.js";import"./chunk-ECD5B2ZM.js";import{b as l,d as i}from"./chunk-JMBDTNUR.js";var h=i(function({model:o,onClose:s}){let{walkChoices:a}=o;return l(t,{title:"Choose haplotypes",label:"Haplotypes",testId:"graph-choose-walks",caption:`${a.length.toLocaleString()} haplotypes in this cut. The ones picked are highlighted in this order, and the rest fades.`,options:a.map(e=>e.name),initial:o.walkLayers.map(e=>e.walk),optionLabel:e=>o.walkLabel(e),confirmLabel:e=>e.length>0?"Highlight these":"Clear highlights",onPick:e=>{o.liftWalks(e)},onClose:s})}),k=h;export{k as default};
2
+ //# sourceMappingURL=ChooseWalksDialog-L23LYMKI.js.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/GraphGenomeView/components/ChooseWalksDialog.tsx"],
4
4
  "sourcesContent": ["import { observer } from 'mobx-react'\n\nimport PickNamesDialog from './PickNamesDialog'\n\nimport type { GraphPaneModel } from '../model'\n\ntype WalkPicker = Pick<\n GraphPaneModel,\n 'walkChoices' | 'walkLayers' | 'walkLabel' | 'liftWalks'\n>\n\n// Which haplotypes to highlight, for a graph with more walks than a menu can\n// list\nconst ChooseWalksDialog = observer(function ChooseWalksDialog({\n model,\n onClose,\n}: {\n model: WalkPicker\n onClose: () => void\n}) {\n const { walkChoices } = model\n return (\n <PickNamesDialog\n title=\"Choose haplotypes\"\n label=\"Haplotypes\"\n testId=\"graph-choose-walks\"\n caption={`${walkChoices.length.toLocaleString()} haplotypes in this cut. The ones picked are highlighted in this order, and the rest fades.`}\n options={walkChoices.map(c => c.name)}\n initial={model.walkLayers.map(l => l.walk)}\n optionLabel={name => model.walkLabel(name)}\n confirmLabel={picked =>\n picked.length > 0 ? 'Highlight these' : 'Clear highlights'\n }\n onPick={picked => {\n model.liftWalks(picked)\n }}\n onClose={onClose}\n />\n )\n})\n\nexport default ChooseWalksDialog\n"],
5
- "mappings": "uLAAA,IAAAA,EAAyB,SAsBrB,IAAAC,EAAA,SATEC,KAAoB,YAAS,SAA2B,CAC5D,MAAAC,EACA,QAAAC,CACF,EAGG,CACD,GAAM,CAAE,YAAAC,CAAY,EAAIF,EACxB,SACE,OAACG,EAAA,CACC,MAAM,oBACN,MAAM,aACN,OAAO,qBACP,QAAS,GAAGD,EAAY,OAAO,eAAe,CAAC,8FAC/C,QAASA,EAAY,IAAIE,GAAKA,EAAE,IAAI,EACpC,QAASJ,EAAM,WAAW,IAAIK,GAAKA,EAAE,IAAI,EACzC,YAAaC,GAAQN,EAAM,UAAUM,CAAI,EACzC,aAAcC,GACZA,EAAO,OAAS,EAAI,kBAAoB,mBAE1C,OAAQA,GAAU,CAChBP,EAAM,UAAUO,CAAM,CACxB,EACA,QAASN,EACX,CAEJ,CAAC,EAEMO,EAAQT",
6
- "names": ["import_mobx_react", "import_jsx_runtime", "ChooseWalksDialog", "model", "onClose", "walkChoices", "PickNamesDialog", "c", "l", "name", "picked", "ChooseWalksDialog_default"]
5
+ "mappings": "+IAaA,IAAMA,EAAoBC,EAAS,SAA2B,CAC5D,MAAAC,EACA,QAAAC,CACF,EAGG,CACD,GAAM,CAAE,YAAAC,CAAY,EAAIF,EACxB,OACEG,EAACC,EAAA,CACC,MAAM,oBACN,MAAM,aACN,OAAO,qBACP,QAAS,GAAGF,EAAY,OAAO,eAAe,CAAC,8FAC/C,QAASA,EAAY,IAAIG,GAAKA,EAAE,IAAI,EACpC,QAASL,EAAM,WAAW,IAAIM,GAAKA,EAAE,IAAI,EACzC,YAAaC,GAAQP,EAAM,UAAUO,CAAI,EACzC,aAAcC,GACZA,EAAO,OAAS,EAAI,kBAAoB,mBAE1C,OAAQA,GAAU,CAChBR,EAAM,UAAUQ,CAAM,CACxB,EACA,QAASP,EACX,CAEJ,CAAC,EAEMQ,EAAQX",
6
+ "names": ["ChooseWalksDialog", "observer", "model", "onClose", "walkChoices", "jsx", "PickNamesDialog", "c", "l", "name", "picked", "ChooseWalksDialog_default"]
7
7
  }
@@ -0,0 +1,8 @@
1
+ import{a as Gr,b as ot,c as zr,d as jr,e as Ur}from"./chunk-X4NNWAXW.js";import{a as Nn,b as Tn}from"./chunk-NU53CDGF.js";import{f as _s,g as qr,h as ye,i as Mn,j as Pn,k as St,l as kn,m as _n,o as On}from"./chunk-R4DSKZ5P.js";import"./chunk-PR5YUSXN.js";import{a as ze}from"./chunk-OGQ6OQDN.js";import"./chunk-YBLNN5FU.js";import{e as bt,f as Ge,g as Rn}from"./chunk-XKN5LH2Z.js";import"./chunk-E7J6SB5P.js";import{b as Br,c as Hr,d as Dr}from"./chunk-D7FMSRTU.js";import{a as Lr,c as Fr,e as $r,o as Cn}from"./chunk-TENPGIPX.js";function be(r,e){return 2*r+(e==="reverse"?1:0)}function O(r){return Math.floor(r/2)}function je(r){return r%2===0?"forward":"reverse"}function j(r){return r%2===1}function re(r){return r%2===0?r+1:r-1}function Wr(r){return r==="left"?"right":"left"}function It(r){return r==="forward"?"left":"right"}function vt(r){return r==="forward"?"right":"left"}function Vr(r){return r==="left"?"forward":"reverse"}function Qr(r){return r==="right"?"forward":"reverse"}function Ue(r,e){let t=O(r),n=O(e);return j(r)?n>t||n===t&&!j(e):n>=t}function st(r){return Le(r[0],r[r.length-1])}function Le(r,e){return r===void 0||e===void 0?!0:j(r)===j(e)?!j(r):Ue(r,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 n=this.bytes[this.offset];if(this.offset+=1,t+=(n&127)*e,e*=128,(n&128)===0)return t}}},Yr=255,Os=256,Et=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<Yr?Math.floor(Os/this.sigma):0}next(){if(this.sigma>=Yr){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,n=Math.floor(e/this.sigma)+1;if(n===this.threshold){let o=this.source.int();if(o===void 0)return;n+=o}return{value:t,len:n}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function Kr(r){let e=new it(r),t=e.int();if(t===void 0||t===0)return[];let n=[],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,n.push({node:o,offset:a})}return n}var At=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Et(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),n=0;for(let o of this.runs()){let s=this.edge(o.value),i=t[o.value];if(n+o.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-n)};t[o.value]=i+o.len,n+=o.len}}edgeTo(e){let t=0,n=this.edges.length;for(;t<n;){let o=t+n>>1,s=this.edges[o];if(s.node===e)return o;s.node<e?t=o+1:n=o}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let n=this.edges[t].offset;if(n>e.offset)return;let o=0;for(let s of this.runs())if(o+=s.len,s.value===t&&(n+=s.len,n>e.offset))return o-(n-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 n=0;for(let o of t)if(n+=o.count,n>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 n=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++)n[s]=a.node,o[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:n,offsets:o}}decompress(){let e=this.edges.map(n=>n.offset),t=[];for(let n of this.runs()){let o=this.edge(n.value);for(let s=0;s<n.len;s++)t.push({node:o.node,offset:e[n.value]}),e[n.value]=e[n.value]+1}return t}};var Ns=["","A","C","G","T","N"];function Xr(r){let e=r[r.length-1];if(e===void 0)return 0;let t=e,n=0;for(let o=0;o<3&&t%6!==0;o++)t=Math.floor(t/6),n+=1;return 3*(r.length-1)+n}function Zr(r){let e="";for(let t of r){let n=t;for(let o=0;o<3;o++){let s=Ns[n%6];if(s==="")return e;n=Math.floor(n/6),e+=s}}return e}var Ts={A:"T",C:"G",G:"C",T:"A",N:"N"};function Ct(r){let e="";for(let t=r.length-1;t>=0;t--)e+=Ts[r[t]]??"N";return e}var Ls=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]),ve=(r,e)=>r>>>e|r<<32-e;function Jr(r){let e=Math.ceil((r.length+9)/64),t=new Uint8Array(e*64);t.set(r),t[r.length]=128;let n=new DataView(t.buffer),o=r.length*8;n.setUint32(t.length-8,Math.floor(o/2**32)),n.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]=n.getUint32(c*64+S*4);for(let S=16;S<64;S++){let g=i[S-15],x=i[S-2],y=ve(g,7)^ve(g,18)^g>>>3,E=ve(x,17)^ve(x,19)^x>>>10;i[S]=i[S-16]+y+i[S-7]+E}let l=s[0],h=s[1],d=s[2],p=s[3],m=s[4],u=s[5],w=s[6],b=s[7];for(let S=0;S<64;S++){let g=ve(m,6)^ve(m,11)^ve(m,25),x=m&u^~m&w,y=b+g+x+Ls[S]+i[S]|0,E=ve(l,2)^ve(l,13)^ve(l,22),A=l&h^l&d^h&d;b=w,w=u,u=m,m=p+y|0,p=d,d=h,h=l,l=y+E+A|0}[l,h,d,p,m,u,w,b].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 eo(r,e){let t=new Map;if(r!==void 0)for(let n of r.split(";")){let o=n.split(","),[s,i]=o;if(o.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${n}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function ro(r){return{name:r.get("pggname"),subgraph:eo(r.get("subgraph"),"subgraph"),translation:eo(r.get("translation"),"translation")}}function to(r,e){for(let[t,n]of e){let o=r.get(t);o||(o=new Set,r.set(t,o));for(let s of n)o.add(s)}}function oo(r,e){let t={name:r,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(r,new Set([e.name])),to(t.subgraph,e.subgraph),to(t.translation,e.translation)),t}function no(r){return[...r.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function so(r){let e=[];r.name!==void 0&&e.push(`H NM:Z:${r.name}`);for(let[t,n]of no(r.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of no(r.translation))e.push(`H TL:Z:${t},${n}`);return e}async function io(r){let e=r.reduce((i,a)=>i+a.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;let o=globalThis.crypto?.subtle;return[...o?new Uint8Array(await o.digest("SHA-256",t)):Jr(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var Fs="_gbwt_ref";function me(r){let e=`${r.sample}#${r.haplotype}#${r.contig}`;return r.end===void 0?e:`${e}[${r.fragment}-${r.end}]`}var $s=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,qs=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Bs(r){let e=$s.exec(r);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=qs.exec(r);if(t)return{contig:t[1]};throw new Error(`"${r}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function We(r){return typeof r=="string"?Bs(r):r}function Ve(r,e){return{sample:r.sample??Fs,contig:r.contig,haplotype:r.haplotype??0,fragment:e}}var Hs=4096;function Fn(r){let e=[];for(let t of r){let n=e[e.length-1];n&&t-n[1]<=Hs?n[1]=t:e.push([t,t])}return e}var Ds=32768,ao={mostChosenPaths:32},Ln=class{byNode=new Map;get(e){return this.byNode.get(e.node)?.get(e.offset)}set(e,t){let n=this.byNode.get(e.node);n||(n=new Map,this.byNode.set(e.node,n)),n.set(e.offset,t)}},ie=class extends Error{};function Rt(r,e,t,n){return r==="forward"?e+t:e-n}function fo(r,e,t,n){return r==="forward"?e-n:e+t}function co(r){return Le(re(r.handles[r.handles.length-1]),re(r.handles[0]))}function at(r){return`${r.pathHandle}:${r.hapStart}:${r.hapEnd}`}async function lo(r){let{db:e,records:t,signal:n}=r,o=performance.now(),s=()=>{let v=performance.now(),R=v-o;return o=v,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=(v,R)=>{let _=`${v}: ${R}`;i.walks[_]=(i.walks[_]??0)+1},f=await e.haplotypeSampleInterval()??4096,c=new Map,l=async v=>{let R=t.get(v)??c.get(v);if(R)return R;let _=await e.getRecord(v);if(i.graphFetches+=1,!_)throw new Error(`Node record ${v} is missing from the database`);return c.set(v,_),_},h=v=>t.get(v).sequenceLen,d=await e.pathsByHandle(),p=v=>{let R=d.get(v);return R!==void 0&&r.keep(R.name)},m=[],u=new Ln,w=new Map,b=new Set,S=new Set,g=async v=>{let R=(await l(v.node)).gbwt().lf(v.offset);return R===void 0||R.node===0?void 0:R},x=async(v,R)=>{let _=(await l(re(v.node))).gbwt().predecessorAt(v.offset);if(_===void 0||R!==void 0&&!R.has(_))return;let L=(await l(_)).gbwt().offsetTo(v);if(L===void 0)throw new Error(`No offset in ${_} leads to ${v.node}:${v.offset}`);return{node:_,offset:L}},y=(v,R,_,L)=>{let B=_.map(V=>V.pos.node),W=_.map(V=>V.pos.offset),J=0;for(let V of B)J+=h(V);let q=R==="forward"?_[0].left:_[_.length-1].left,$=m.length;m.push({pathHandle:v,orientation:R,handles:B,offsets:W,len:J,hapStart:q,hapEnd:q+J,canonical:Le(B[0],B[B.length-1]),source:L});for(let V of _)u.set(V.pos,$);let K=w.get(v);return K?K.push($):w.set(v,[$]),$},E=async(v,R,_,L)=>{let B=[],W=v;for(;;){n?.throwIfAborted();let q=await x(W.pos,t);if(!q)break;W={pos:q,left:fo(_,W.left,h(W.pos.node),h(q.node))},B.push(W)}B.reverse();let J=[v];for(W=v;;){n?.throwIfAborted();let q=await g(W.pos);if(!q||!t.has(q.node))break;W={pos:q,left:Rt(_,W.left,h(W.pos.node),h(q.node))},J.push(W)}return y(R,_,[...B,...J],L)},A=async(v,R,_,L)=>m[u.get(v.pos)??await E(v,R,_,L)],N=v=>{let R=v.handles[v.handles.length-1];return{pos:{node:R,offset:v.offsets[v.offsets.length-1]},left:v.orientation==="forward"?v.hapEnd-h(R):v.hapStart}},k=v=>{let R=v.handles[0];return{pos:{node:R,offset:v.offsets[0]},left:v.orientation==="forward"?v.hapStart:v.hapEnd-h(R)}},F=await E({pos:r.referencePos,left:r.referenceLeft},r.referenceHandle,"forward","reference"),M=m[F],T=()=>{if(i.fallback!==void 0)return{reference:M,pieces:[],stats:i};let v=new Map;m.forEach((_,L)=>{L!==F&&v.set(at(_),[...v.get(at(_))??[],_])});let R=[];for(let _ of v.values()){let L=new Set;for(let B of _)B.canonical&&!L.has(B.orientation)&&(L.add(B.orientation),R.push(B),i.sources[B.source]+=1)}return i.sources.reference=1,i.pieces=R.length+1,{reference:M,pieces:R,stats:i}},C=async(v,R)=>{let _=R?b:S,L=R?S:b,B=v;for(;;){if(_.has(B))return;_.add(B);let W=m[B],J=R?N(W):k(W),q=0,$;for(;$===void 0;){n?.throwIfAborted();let K=R?await g(J.pos):await x(J.pos);if(!K){$="endmarker";break}let V=(await l(J.pos.node)).sequenceLen,Ie=(await l(K.node)).sequenceLen,oe=R?Rt(W.orientation,J.left,V,Ie):fo(W.orientation,J.left,V,Ie);if(t.has(K.node)){let ee=u.get(K);ee===void 0?(B=await E({pos:K,left:oe},W.pathHandle,W.orientation,"chain"),L.add(B),$="landed"):(L.add(ee),$="merge")}else q>Ds?$="bound":(q+=Ie,J={pos:K,left:oe})}if(a("chain",$),$!=="landed")return}},D=async v=>{if(r.context>v.context)throw new ie(`the context of ${r.context} bp exceeds the ${v.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:_,bound:L}=v,{fills:B,inserted:W}=r.snarls;if(r.snarls.mode==="overlapping"&&B.length>0)throw new ie("the haplotype index's stray rows cover contained snarls only");for(let I of B){if(I.inserted>0&&I.low===I.high)throw new ie(`the haplotype index's stray rows leave out the snarl bounded by node ${I.low} at both ends`);if(I.inserted>0&&(v.snarlNodes===void 0||I.nodes>v.snarlNodes))throw new ie(v.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${I.nodes} nodes exceeds the ${v.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(r.window.start/_),q=Math.floor((r.window.end-1)/_),$=J*_,K=(q+1)*_,V=new Map,Ie=async(I,P)=>{let U=await e.haplotypeAnchorsBetween(r.referenceHandle,I*R,P*R);for(let G of U)V.set(G.anchorOffset/R,G)},oe=Math.max(0,Math.floor(($-L)/R)-1),ee=Math.ceil((K+L)/R)+1,[{listed:xt,strays:ce}]=await Promise.all([e.haplotypeBinData(r.referenceHandle,J,q),Ie(oe,ee)]);for(let I of t.keys()){let P=O(I);if(!j(I)&&!xt(P)&&!W.has(P))throw new ie(`the haplotype index lists node ${P} of the subgraph in no bin that the window touches`)}i.scans=Fn([...t.keys()].sort((I,P)=>I-P));let de=Promise.all(i.scans.map(([I,P])=>e.haplotypeSamplesInRange(I,P)));for(de.catch(()=>{});oe>0&&(V.get(oe)?.pathOffset??Number.POSITIVE_INFINITY)>=$-L;)oe-=1,await Ie(oe,oe);for(;V.has(ee)&&V.get(ee).pathOffset<=K+L;)ee+=1,await Ie(ee,ee);let xe=[...V.keys()].sort((I,P)=>I-P),Pe=V.get(xe[0]??-1);if(!Pe)throw new ie("the haplotype index has no anchors on this path");let pe=I=>V.get(I).pathOffset,tt=new Map;for(let I of xe){let P=O(V.get(I).node);tt.set(P,[...tt.get(P)??[],I])}let vn=[...tt.keys()],Er=vn.map(I=>V.get(tt.get(I)[0]).visits);if(!Er[vn.indexOf(O(Pe.node))].some(I=>I.pathHandle===r.referenceHandle&&I.orientation==="forward"&&I.pathOffset===Pe.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${r.referenceHandle} at offset ${Pe.pathOffset} (node ${O(Pe.node)}); it does not match this graph`);let Ar=xe.filter(I=>pe(I)<=r.window.start),Rs=xe.filter(I=>pe(I)>=r.window.end);i.anchors=[pe(Ar[Ar.length-1]??xe[0]),pe(Rs[0]??xe[xe.length-1])],i.anchorsRead=xe.length;let En=new Map,Cr=new Set;if(vn.forEach((I,P)=>{let U=tt.get(I),G=U.length===1?U[0]:void 0;for(let z of Er[P])Cr.add(z.pathHandle),z.orientation==="forward"&&p(z.pathHandle)&&En.set(z.pathHandle,[...En.get(z.pathHandle)??[],{k:G,row:z}])}),i.chosenPaths=[...Cr].filter(p).length,i.chosenPaths>ao.mostChosenPaths)throw new ie(`${i.chosenPaths} chosen paths pass the anchors, more than ${ao.mostChosenPaths}`);let yt=[],Te=Number.POSITIVE_INFINITY,ke=0;for(let[I,P]of En){P.sort((U,G)=>U.row.pathOffset-G.row.pathOffset);for(let U=0;U+1<P.length;U++){let G=P[U],z=P[U+1];if(G.k===void 0||z.k===void 0||Math.abs(G.k-z.k)!==1)continue;let[Z,te]=pe(G.k)<=pe(z.k)?[G,z]:[z,G],ne=pe(Z.k),se=pe(te.k);ne<K&&se>=$?(yt.push({pathHandle:I,from:G.row,to:z.row}),Te=Math.min(Te,ne-L),ke=Math.max(ke,se+L)):ne>=K&&ne-K<=L?(yt.push({pathHandle:I,from:Z.row,to:void 0}),Te=Math.min(Te,ne-L),ke=Math.max(ke,ne+L)):se<$&&$-se<=L&&(yt.push({pathHandle:I,from:te.row,to:void 0}),Te=Math.min(Te,se-L),ke=Math.max(ke,se+L))}}let Ms=new Set(B.map(I=>`${I.low}:${I.high}`)),Ps=ce.filter(I=>p(I.pathHandle)&&(I.snarl===void 0||Ms.has(`${I.snarl[0]}:${I.snarl[1]}`))).sort((I,P)=>I.pathHandle-P.pathHandle||I.pathStart-P.pathStart);i.strays={bins:q-J+1,rows:ce.length,walked:0,outsideBp:0},ke>0&&await r.prefetchReferenceRange(r.referenceHandle,Math.max(0,Te),ke+1),i.ms.scan=s();let Rr=8*R+2*(r.window.end-r.window.start),Mr=i.strays,nt=0,Pr=I=>{if(Mr.outsideBp+=I,nt+=I,nt>Rr)throw new ie(`a walk of a chosen path near the window went past its cap of ${Rr} bp`)},An=new Map,kr=(I,P,U)=>(An.get(I)??[]).some(([G,z])=>G<=P&&U<z),_r=(I,P,U)=>{An.set(I,[...An.get(I)??[],[P,U]])},Or=async(I,P,U,G,z)=>{let Z=P,te=U,ne=te;for(;Z&&te<=G;){n?.throwIfAborted();let se;if(t.has(Z.node)){let rt=await A({pos:Z,left:te},I,"forward",z),Tr=N(rt);Z=Tr.pos,te=Tr.left,se=h(Z.node),ne=Math.max(ne,rt.hapEnd)}else se=(await l(Z.node)).sequenceLen,Pr(se),ne=Math.max(ne,te+se);Z=await g(Z),te+=se}return ne},ks=async(I,P,U,G)=>{let z={pos:P,left:U},Z=U;for(;z.left>G;){n?.throwIfAborted();let te=await x(z.pos);if(!te)break;let ne=(await l(te.node)).sequenceLen,se=z.left-ne;if(t.has(te.node)){let rt=await A({pos:te,left:se},I,"forward","section");z=k(rt),Z=Math.min(Z,rt.hapStart)}else Pr(ne),z={pos:te,left:se},Z=Math.min(Z,se)}return Z};for(let{pathHandle:I,from:P,to:U}of yt){let G=P.pathOffset,z=(U??P).pathOffset+L;if(kr(I,G-L,z))continue;let Z={node:P.node,offset:P.offset};nt=0;let te=await Or(I,Z,G,z,"section");nt=0;let ne=await ks(I,Z,G,G-L);_r(I,Math.min(ne,G-L),Math.max(te,z+1)),a(U?"section":"visit",U?"past the far anchor":"bound")}for(let I of Ps){if(kr(I.pathHandle,I.pathStart,I.pathEnd))continue;nt=0;let P=await Or(I.pathHandle,{node:I.node,offset:I.offset},I.pathStart,I.pathEnd,"stray");_r(I.pathHandle,I.pathStart,Math.max(P,I.pathEnd+1)),Mr.walked+=1}i.ms.walks=s();let Nr=[];for(let I of await de)for(let P of I)if(i.scanRows+=1,t.has(P.node)&&p(P.pathHandle)){if(!(w.get(P.pathHandle)??[]).some(U=>{let G=m[U];return G.hapStart<=P.pathOffset&&P.pathOffset<G.hapEnd}))throw new ie(`chosen path ${P.pathHandle} has a sample at ${P.pathOffset} on the window's nodes that no walk reached`);P.orientation==="reverse"&&Nr.push(P)}for(let I of Nr)await A({pos:{node:I.node,offset:I.offset},left:I.pathOffset},I.pathHandle,"reverse","twin");i.ms.check=s()},Y=async()=>{let v=new Map,R=q=>{let $=at(q),K=v.get($);K?K.add(q.orientation):v.set($,new Set([q.orientation]))},_=0,L=()=>{for(;_<m.length;_++)R(m[_])};L();let B=q=>(v.get(at(q))?.size??0)>1,W=2*f,J=(q,$)=>$===F?p(r.referenceHandle)&&co(q):!q.canonical||co(q);for(let q=0;q<m.length;q++){let $=m[q];if(B($)||!J($,q))continue;i.twins.tried+=1;let K=$.orientation==="forward"?"reverse":"forward",V=N($),Ie=0,oe;for(;!oe&&Ie<=W;){n?.throwIfAborted();let ce=await g(V.pos);if(!ce)break;let de=(await l(ce.node)).sequenceLen,xe=Rt($.orientation,V.left,(await l(V.pos.node)).sequenceLen,de),Pe=re(ce.node);oe=(await e.haplotypeSamplesInRange(Pe,Pe)).find(pe=>pe.pathHandle===$.pathHandle&&pe.orientation===K&&pe.pathOffset===xe),Ie+=de,V={pos:ce,left:xe}}let ee=oe&&{pos:{node:oe.node,offset:oe.offset},left:oe.pathOffset},xt=0;for(;ee&&!B($)&&xt<=W+$.len;){if(n?.throwIfAborted(),t.has(ee.pos.node)){let ce=await A(ee,$.pathHandle,K,"twin"),de=m.indexOf(ce);await C(de,!0),await C(de,!1),L(),ee=N(ce)}if(!B($)){let ce=(await l(ee.pos.node)).sequenceLen;xt+=ce;let de=await g(ee.pos);ee=de?{pos:de,left:Rt(K,ee.left,ce,(await l(de.node)).sequenceLen)}:void 0}}if(L(),!B($))throw new ie(`piece ${at($)} was found in one orientation where extractPaths keeps the other`);i.twins.found+=1}i.ms.twins=s()};try{let v=await e.haplotypeStrayOptions();if(v===void 0)throw new ie("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await D(v),await Y()}catch(v){if(!(v instanceof ie))throw v;i.fallback=v.message}return T()}function ho(r,e){return r.handles[0]-e.handles[0]||r.offsets[0]-e.offsets[0]}function Mt(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]<e?t=o+1:n=o}return t}var Pt=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 n=e;n>0;n-=n&-n){let o=this.tree[n];o!==-1&&(t===-1||this.ending[o]>this.ending[t])&&(t=o)}return t}raise(e,t){this.ending[e]=t;for(let n=e+1;n<this.tree.length;n+=n&-n){let o=this.tree[n];(o===-1||t>this.ending[o])&&(this.tree[n]=e)}}},$n=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,n){this.a=e,this.b=t,this.weight=n,t.forEach((o,s)=>{let i=this.occurrences.get(o);i?i.push(s):this.occurrences.set(o,[s])})}solve(e,t,n,o){let s=0;for(;e+s<t&&n+s<o&&this.a[e+s]===this.b[n+s];)this.match(e+s,n+s),s+=1;let i=0;for(;t-i>e+s&&o-i>n+s&&this.a[t-i-1]===this.b[o-i-1];)i+=1;this.solveMiddle(e+s,t-i,n+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,n,o){if(e===t||n===o)return;let s=this.matchCount(e,t,n,o);if(s===0)return;if(s<=t-e+(o-n)){this.chain(e,t,n,o,s);return}let i=e+t>>1,a=this.split(e,i,t,n,o);this.solve(e,i,n,a),this.solve(i,t,a,o)}matchCount(e,t,n,o){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=Mt(a,o)-Mt(a,n))}return s}sweep(e,t,n,o,s,i,a){for(let f=e;f!==t;f+=n){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),h=Mt(c,o),d=Mt(c,s);for(let p=0;p<d-h;p++){let m=n===1?c[d-1-p]-o:s-1-c[h+p],u=i.bestBefore(m),w=(u===-1?0:i.ending[u])+l;if(w>i.ending[m]&&(i.raise(m,w),a)){let b=a.count++;a.row[b]=f,a.column[b]=m,a.previous[b]=u===-1?-1:a.endingMatch[u],a.endingMatch[m]=b}}}}chain(e,t,n,o,s){let i=new Pt(o-n),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(o-n),count:0};this.sweep(e,t,1,n,o,i,a);let f=i.bestBefore(o-n);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],n+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,n,o,s){let i=new Pt(s-o);this.sweep(e,t,n,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,n,o,s){let i=s-o,a=this.frontier(e,t,1,o,s),f=this.frontier(n-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 po(r,e,t){let n=new $n(r,e,t);return n.solve(0,r.length,0,e.length),[n.pairs,n.total]}var Gs=100,Hn=4e6,zs=5e3,le=15,js=64,Us=8,bo=1,Dn=-4,ae=-6,Ce=-1,Qe=-(2**30),_t=0,qn=1,So=2;function Fe(r,e,t){let n=r.at(-1);t>0&&(n?.[0]===e?n[1]+=t:r.push([e,t]))}function kt(r,e,t){return r>=t&&r>=e?_t:t>=e?So:qn}function Io(r,e,t){let n=r.length,o=e.length,s=o+1,i=new Uint8Array((n+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 m=1;m<=o;m++)c[m]=ae+(m-1)*Ce,i[m]=(m===1?_t:So)<<4;for(let m=1;m<=n;m++){let u=new Int32Array(s).fill(Qe),w=new Int32Array(s).fill(Qe),b=new Int32Array(s).fill(Qe);w[0]=ae+(m-1)*Ce,i[m*s]=(m===1?_t:qn)<<2;let S=r.charCodeAt(m-1);for(let g=1;g<=o;g++){let x=kt(a[g-1],f[g-1],c[g-1]);u[g]=Math.max(a[g-1],f[g-1],c[g-1])+(S===e.charCodeAt(g-1)?bo:Dn);let y=kt(a[g]+ae,f[g]+Ce,c[g]+ae);w[g]=Math.max(a[g]+ae,f[g]+Ce,c[g]+ae);let E=kt(u[g-1]+ae,w[g-1]+ae,b[g-1]+Ce);b[g]=Math.max(u[g-1]+ae,w[g-1]+ae,b[g-1]+Ce),i[m*s+g]=x|y<<2|E<<4}a=u,f=w,c=b}let l=[],h=n,d=o,p=kt(a[o],f[o],c[o]);for(;h>0||d>0;){let m=i[h*s+d]>>2*p&3;p===_t?(l.push(r[h-1]===e[d-1]?"=":"X"),h-=1,d-=1):p===qn?(l.push("I"),h-=1):(l.push("D"),d-=1),p=m}for(let m of l.reverse())Fe(t,m,1)}function Ws(r,e){let t=Math.abs(r-e);return(t===0?0:Math.min(-ae-(t-1)*Ce,-ae+10*Math.log2(t)))+(Math.min(r,e)>0?-Dn:0)}function vo(r,e){let t=Math.abs(r-e);return t===0?0:.01*le*t+.5*Math.log2(t)}function uo(r,e,t){return{qs:r.qs+e,qe:r.qs+t,ts:r.flipped?r.te-t:r.ts+e,te:r.flipped?r.te-e:r.ts+t,flipped:r.flipped}}function Vs(r,e,t){let n=r.qe-r.qs,o=[];for(let[a,f]of e){let c=Math.max(0,a-r.qs),l=Math.min(n,f-r.qs);c<l&&o.push([c,l])}for(let[a,f]of t){let c=Math.max(0,r.flipped?r.te-f:a-r.ts),l=Math.min(n,r.flipped?r.te-a:f-r.ts);c<l&&o.push([c,l])}if(o.length===0)return[r];o.sort((a,f)=>a[0]-f[0]);let s=[],i=0;for(let[a,f]of o)a-i>=le&&s.push(uo(r,i,a)),i=Math.max(i,f);return n-i>=le&&s.push(uo(r,i,n)),s}function Gn(r,e,t,n,o=1/0){let s=[],i={query:[],target:[]},a={forward:{query:[],target:[]},flipped:{query:[],target:[]}},f=[...r].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 x=f[g],y=x.qe-x.qs;for(let E=g-1;E>=Math.max(0,g-zs);E--){if(c[E]+y<=c[g])continue;let A=f[E];if(A.flipped===x.flipped&&A.qs<x.qs&&(x.flipped?x.te<A.te:A.ts<x.ts)){let k=Math.max(0,A.qe-x.qs,x.flipped?x.te-A.ts:A.te-x.ts),F=x.qs+k-A.qe,M=x.flipped?A.ts-(x.te-k):x.ts+k-A.te;if(k<y&&F<=e&&M<=e){let T=c[E]+y-k-n(F,M);T>c[g]&&(c[g]=T,l[g]=E,h[g]=k)}}}}let d=new Int32Array(f.length),p=-1;for(let g=0;g<f.length;g++){let x=f[g];d[g]=(d[l[g]]??0)+x.qe-x.qs-h[g],d[g]>=t&&(p<0||c[g]>c[p])&&(p=g)}if(p<0)break;let m=[];for(let g=p;g>=0;g=l[g])m.push({run:f[g],trim:h[g]});m.reverse(),s.push(m);let u=m[0],w=m.at(-1),{flipped:b}=u.run,S=b?a.flipped:a.forward;S.query.push([u.run.qs+u.trim,w.run.qe]),S.target.push(b?[w.run.ts,u.run.te-u.trim]:[u.run.ts+u.trim,w.run.te]);for(let{run:g,trim:x}of m)i.query.push([g.qs+x,g.qe]),i.target.push(g.flipped?[g.ts,g.te-x]:[g.ts+x,g.te]);f=f.flatMap(g=>{let x=g.flipped?a.flipped:a.forward;return Vs(g,[...i.query,...x.query],[...i.target,...x.target])}).sort((g,x)=>g.qs-x.qs||g.ts-x.ts)}return s}function Bn(r,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 n=[],o=new Map;for(let s=0;s+le<=r.length;s++){let i=t.get(r.slice(s,s+le));if(i&&i.length<=js)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),n.push(l)}}}return n}function Qs(r,e){return[...Bn(r,e),...Bn(r,Ct(e)).map(t=>({...t,ts:e.length-t.te,te:e.length-t.ts,flipped:!0}))]}function Ot(r,e,t,n,o){let s;for(let{run:i,trim:a}of r){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?Ct(h):h,n,s.qe,c)}Fe(n,"=",i.qe-f),s=i}}function zn(r,e,t){Fe(t,"I",r.length),Fe(t,"D",e.length)}function Eo(r,e,t){r.length*e.length<=Hn?Io(r,e,t):zn(r,e,t)}function jn(r,e,t,n=0){let[o]=r.length*e.length>Hn&&n<Us?Gn(Bn(r,e),1/0,le,vo,1):[];if(!o){Eo(r,e,t);return}let s=(f,c,l)=>{jn(f,c,l,n+1)},i=o[0].run,a=o.at(-1).run;s(r.slice(0,i.qs),e.slice(0,i.ts),t),Ot(o,r,e,t,s),s(r.slice(a.qe),e.slice(a.te),t)}function Ys(r,e,t){jn(r,e,t)}function Ks(r,e,t){let n=[];Ot(r,e,t,n,Ys);let o=r[0],s=r.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?n.reverse():n,sharedBases:0}}function Xs(r,e,t,n){let o=[];if(r.length*e.length<=Hn)Io(r,e,t);else{let s=Gn(Qs(r,e),1/0,Math.max(n,le),vo),i=s.find(a=>!a[0].run.flipped);if(o=s.filter(a=>a[0].run.flipped).map(a=>Ks(a,r,e)),i){let a=(l,h,d,p,m)=>{o.some(w=>p<w.queryEnd&&w.queryStart<p+l.length||m<w.targetEnd&&w.targetStart<m+h.length)?Eo(l,h,d):jn(l,h,d)},f=i[0].run,c=i.at(-1).run;a(r.slice(0,f.qs),e.slice(0,f.ts),t,0,0),Ot(i,r,e,t,a),a(r.slice(c.qe),e.slice(c.te),t,c.qe,c.te)}else zn(r,e,t)}return o}function Un(r,e){let t=r.strand==="-",n=0,o=0;for(let[s,i]of r.edits)e(s,i,t?r.queryEnd-1-n:r.queryStart+n,r.targetStart+o),s!=="D"&&(n+=i),s!=="I"&&(o+=i)}function mo(r,e,t,n){let o=e==="query"&&r.strand==="-"?-1:1,s=0;return Un(r,(i,a,f,c)=>{let l=e==="query"?f:c,h=d=>{let p=l+o*d;return p>=t&&p<n};if(i==="="||i==="X")for(let d=0;d<a;d++)h(d)&&(s+=i==="="?bo:Dn);else if(i==="I"==(e==="query"))for(let d=0;d<a;d++)h(d)&&(s+=d===0?ae:Ce);else h(0)&&(s+=ae+(a-1)*Ce)}),s}function go(r,e){return e==="query"?[r.queryStart,r.queryEnd]:[r.targetStart,r.targetEnd]}function Zs(r,e){let t=r.strand==="-",n=[],o=0,s=0,i=0,a=0,f=new Uint8Array(r.queryEnd-r.queryStart);for(let[p,m]of r.shared)f.fill(1,p-r.queryStart,m-r.queryStart);let c=p=>f[p-r.queryStart]===1,l=()=>{Fe(n,"I",o),Fe(n,"D",s),o=0,s=0};Un(r,(p,m,u)=>{if(p==="I")o+=m;else if(p==="D")s+=m;else{for(let w=0;w<m;w++)e[i+w]?(o+=1,s+=1,c(t?u-w:u+w)&&(a+=1)):((o>0||s>0)&&l(),Fe(n,p,1));i+=m}}),l();let h={I:0,D:0};for(;n[0]?.[0]==="I"||n[0]?.[0]==="D";){let[p,m]=n.shift();h[p]+=m}let d={I:0,D:0};for(;n.at(-1)?.[0]==="I"||n.at(-1)?.[0]==="D";){let[p,m]=n.pop();d[p]+=m}return n.length===0?void 0:{...r,queryStart:r.queryStart+(t?d.I:h.I),queryEnd:r.queryEnd-(t?h.I:d.I),targetStart:r.targetStart+h.D,targetEnd:r.targetEnd-d.D,edits:n,sharedBases:r.sharedBases-a}}function Js(r,e,t,n){let o={query:new Uint8Array(e),target:new Uint8Array(t)},s=r.map(c=>{let l=[];Un(c,(h,d,p,m)=>{if(h==="="||h==="X")for(let u=0;u<d;u++)l.push([c.strand==="-"?p-u:p+u,m+u])});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,m]of[["query",h],["target",d]])if(o[p][m]>1){let u=i[p].get(m);u?u.at(-1)!==l&&u.push(l):i[p].set(m,[l])}});let a=new Map,f=(c,l,h)=>{let d=`${h}:${c}:${l}`,p=a.get(d);if(p===void 0){let[m,u]=go(r[c],h),[w,b]=go(r[l],h),S=Math.max(m,w),g=Math.min(u,b),[x,y]=[r[c],r[l]];p=[mo(y,h,S,g)-mo(x,h,S,g),y.sharedBases-x.sharedBases,c-l].find(A=>A!==0)>0,a.set(d,p)}return p};return r.flatMap((c,l)=>{let h=s[l],d=new Uint8Array(h.length);if(h.forEach(([u,w],b)=>{for(let[S,g]of[["query",u],["target",w]])!d[b]&&i[S].get(g)?.some(x=>x!==l&&f(l,x,S))&&(d[b]=1)}),!d.includes(1))return[c];let p=Zs(c,d),m=p?.edits.reduce((u,[w,b])=>u+(w==="="?b:0),0)??0;return p&&m>=n?[p]:[]})}function wo(r,e){return r.map(t=>{let n=e(O(t));return j(t)?Ct(n):n}).join("")}function xo(r,e){let t=[0];for(let n of r)t.push(t.at(-1)+e(O(n)).length);return t}function yo(r){let e=new Map,t=new Map;r.forEach((i,a)=>{let f=O(i);e.has(f)?t.set(f,a):e.set(f,a)});let n=new Int32Array(r.length+1);for(let[i,a]of t)n[e.get(i)]+=1,n[a+1]-=1;let o=new Uint8Array(r.length),s=0;for(let i=0;i<r.length;i++)s+=n[i],o[i]=s>0?1:0;return o}function ei(r,e,t,n){let o=yo(r),s=yo(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;r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[])c.add(f(d,p,j(h)!==j(e[p])))});let l=[];return r.forEach((h,d)=>{for(let p of o[d]?[]:i.get(O(h))??[]){let m=j(h)!==j(e[p]),u=m?-1:1,w=p-u;if(!(d>0&&w>=0&&w<e.length&&c.has(f(d-1,w,m)))){let S=d,g=p;for(;S<r.length&&g>=0&&g<e.length&&c.has(f(S,g,m));)S+=1,g+=u;let x=g-u;l.push({qs:t[d],qe:t[S],ts:n[Math.min(p,x)],te:n[Math.max(p,x)+1],flipped:m})}}}),l}function Ao(r){let{query:e,target:t,sequenceOf:n}=r,o=wo(e,n),s=wo(t,n),i=ei(e,t,xo(e,n),xo(t,n)),a=r.minMatch??Gs,f=r.bases??!0,c=[];for(let l of Gn(i,r.maxGap??1/0,a,Ws)){let h=[],d=l[0],p=l.at(-1),{flipped:m}=d.run;Ot(l,o,s,h,f?(w,b,S,g,x)=>{for(let y of Xs(w,b,S,a)){let E=x+b.length;c.push({...y,queryStart:g+y.queryStart,queryEnd:g+y.queryEnd,targetStart:m?E-y.targetEnd:x+y.targetStart,targetEnd:m?E-y.targetStart:x+y.targetEnd,strand:m?"+":"-",edits:m?y.edits.reverse():y.edits,shared:[]})}}:zn),c.push({queryStart:d.run.qs+d.trim,queryEnd:p.run.qe,targetStart:m?p.run.ts:d.run.ts+d.trim,targetEnd:m?d.run.te-d.trim:p.run.te,strand:m?"-":"+",edits:m?h.reverse():h,sharedBases:l.reduce((w,{run:b,trim:S})=>w+b.qe-b.qs-S,0),shared:l.map(({run:w,trim:b})=>[w.qs+b,w.qe])})}return Js(c,o.length,s.length,a).map(({shared:l,...h})=>h).sort((l,h)=>l.queryStart-h.queryStart)}function Co(r){return r.map(([e,t])=>`${t}${e}`).join("")}var fe=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 Wn(r,e){return r[0]<e[0]||r[0]===e[0]&&(r[1]<e[1]||r[1]===e[1]&&r[2]<e[2])}var ct=class{heap=[];push(e,t,n){let o=this.heap;o.push([e,t,n]);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(Wn(o[s],o[i]))[o[s],o[i]]=[o[i],o[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&Wn(e[s],e[a])&&(a=s),i<e.length&&Wn(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 ti(r){let e=new Int32Array(r.length),t=new Int32Array(r.length);return r.forEach(([n,o],s)=>{e[s]=n,t[s]=o}),{pathAt:e,refAt:t,count:r.length}}function ni(r,e){let t=0,n=r.length;for(;t<n;){let o=t+n>>1;r[o]>e?n=o:t=o+1}return r[t]}function $e(r){return`${r.node}:${r.offset}`}function ft(r){return r.map(e=>re(e)).reverse()}function ri(r,e){let t=e.identity.hapStart-r.identity.hapEnd,n=r.strand==="+"?e.refStart-r.refEnd:r.refStart-e.refEnd;return r.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function oi(r,e,t){let[n,o]=r.strand==="+"?[r,e]:[e,r],s=n.edits.map(([c,l])=>[c,l]);Mo(s,t.insertion,t.deletion);for(let[c,l]of o.edits)X(s,c,l);let i=r.identity.walkForward,[a,f]=i?[r,e]:[e,r];return{strand:r.strand,refStart:n.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:r.identity.pathHandle,name:r.identity.name,hapStart:r.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function si(r,e,t){if(r.some(i=>i.weight!==void 0))return r;let n=new Map;r.forEach((i,a)=>{if(i.identity){let f=n.get(i.identity.pathHandle);f?f.push(a):n.set(i.identity.pathHandle,[a])}});let o=new Map,s=new Set;for(let i of n.values()){i.sort((l,h)=>r[l].identity.hapStart-r[h].identity.hapStart);let a=i[0],f=r[a],c=[];for(let l of i.slice(1)){let h=r[l],d=c.length===0?ri(f,h):void 0;if(d){f=oi(f,h,d),s.add(l);continue}if(!e(h)){c.push(l);continue}let p=e(f)?t([f,...c.map(m=>r[m]),h]):void 0;if(p){f=p;for(let m of[...c,l])s.add(m)}else o.set(a,f),a=l,f=h;c=[]}o.set(a,f)}return r.flatMap((i,a)=>s.has(a)?[]:[o.get(a)??i])}function Nt(r,e){return{node:r.path[e],offset:r.offsets[e]}}var ii=32768;function ai(r){let e=[...r].sort((n,o)=>n-o),t=[];for(let n of e){let o=t[t.length-1];o&&n-o[1]<=ii?o[1]=n:t.push([n,n])}return t}var lt=class r{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 r(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(be(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 fe(this.limit);let t=await this.db.getRecord(be(e,"forward")),n=await this.db.getRecord(be(e,"reverse"));if(!t||!n)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(n.handle,n)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.twinDeferred=!1,this.unsettled=void 0,this.refId=void 0,this.refPath=void 0,this.refHandle=void 0,this.refInterval=void 0,this.refIndexCache=void 0,this.refPrefixCache=void 0}async pathPosition(e){let t=await this.db.findPath(e);if(!t)throw new Error(`Cannot find a path covering offset ${e.fragment} of ${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 n=e.fragment-t.name.fragment,o=await this.db.indexedPosition(t.handle,n);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,n,o.pathOffset,o.pos)}async findPathPosition(e,t,n,o){let s=n,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,n){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,vt(i)),this.insertContext(a,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[o,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);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,n);await this.db.prefetchRecords(ai(c.map(l=>l.pos.node)).map(([l,h])=>[l,h+2]),!0)}}return o}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(o){throw o instanceof fe&&o.windowBp===void 0?new fe(o.limit,{windowBp:t,walkedBp:this.walkedBp}):o}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){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,vt(c));break}a.push(0,f,vt(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,n)}async aroundNodes(e,t){let n=new ct;for(let o of e)await this.ensureNode(o),n.push(0,o,"left"),n.push(0,o,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,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(n.has(c))continue;n.add(c),o.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=Wr(f);if(!n.has(`${a}:${l}`)){let p=this.record(be(a,Vr(f))),m=i+p.sequenceLen-1;m<=t&&e.push(m,a,l)}let h=this.record(be(a,Qr(f))),d=i+1;if(d<=t)for(let p of h.successors()){let m=O(p),u=It(je(p));n.has(`${m}:${u}`)||e.push(d,m,u)}}for(let i of o)this.records.delete(be(i,"forward")),this.records.delete(be(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 n=[e,re(t)],o=new Set([O(e),O(t)]),s=[];for(;n.length>0;){let i=n.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)||(n.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[n,o]of await this.overlappingSnarls(e)){let{inserted:s,nodes:i}=await this.fillBetween(n,o),a=O(n),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 n=!1;for(let o of this.sortedHandles()){let s=this.record(o),i=s.next;i!==void 0&&(n=!0,this.hasHandle(i)?Ue(o,i)&&t.push([o,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([o,i]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let o=await this.findCoveringSnarl();o&&t.push(o)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(o=>this.hasHandle(o));return n===void 0?!1:t.length>1||this.record(re(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let o=this.records.get(n);if(o)return o;let s=t.get(n);if(!s){if(s=await this.db.getRecord(n),e?.(),!s)throw new Error(`Node record ${n} is missing from the database`);t.set(n,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},n=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 n(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(be(c,h))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let o=this.sortedHandles(),s=o.length,i=new Map;o.forEach((y,E)=>i.set(y,E));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let y=0;y<s;y++){let E=this.record(o[y]),A=E.gbwt().decompressArrays();f[y]=E.sequenceLen,c.push(A),a[y+1]=a[y]+A.nodes.length}let l=a[s],h=new Int32Array(l),d=new Int32Array(l),p=new Uint8Array(l);for(let y=0;y<s;y++){let E=c[y];h.set(E.nodes,a[y]),d.set(E.offsets,a[y])}c.length=0;for(let y=0;y<l;y++){let E=i.get(h[y]);E===void 0?h[y]=-1:(h[y]=E,p[a[E]+d[y]]=1)}let m=n===void 0?void 0:i.get(n.handle),u=n?.gbwtOffset,w,b=(y,E,A)=>{let N=[],k=0,F=0,M=-1,T=y,C=E;for(;;){T===m&&C===u&&(M=k),A&&(A.push(o[T]),N.push(C)),k+=1,F+=f[T];let D=a[T]+C,Y=h[D];if(Y<0)break;C=d[D],T=Y}return{offsets:N,len:F,refAt:M,last:T}},S=(y,E,A,N)=>{N>=0&&(this.refId=this.paths.length,w=N),this.paths.push({path:y,offsets:E,len:A,weight:void 0,identity:void 0})},g=new Int32Array(s);for(let y=0;y<s;y++){let E=o[y];if(!j(E)){let A=a[y],N=a[y+1]-A;for(let k=0;k<N;k++)if(p[A+k]===0){let F=[],{offsets:M,len:T,refAt:C,last:D}=b(y,k,F),Y=o[D];if(C>=0||Le(E,Y)){if(S(F,M,T,C),!j(Y)){let v=i.get(re(Y));g[v]=g[v]+1}}else this.twinStarts.add($e({node:E,offset:k}))}}}for(let y=0;y<s;y++){let E=o[y];if(j(E)){let A=a[y],N=a[y+1]-A,k=0;for(let M=0;M<N;M++)p[A+M]===0&&(k+=1);let F=(m===void 0||w!==void 0)&&k===g[y];for(let M=0;M<N;M++)if(p[A+M]===0){let T=F?void 0:b(y,M,void 0);if(T&&(T.refAt>=0||Le(E,o[T.last]))){let C=[],{offsets:D,len:Y,refAt:v}=b(y,M,C);S(C,D,Y,v)}else this.twinStarts.add($e({node:E,offset:M}))}}}let x=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((y,E)=>y.path[0]-E.path[0]||y.offsets[0]-E.offsets[0]),x&&(this.refId=this.paths.indexOf(x)),n){if(w===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let y=this.paths[this.refId],E=n.nodeOffset;for(let N of y.path.slice(0,w))E+=this.record(N).sequenceLen;let A=n.seqOffset-E;this.refInterval=[A,A+y.len],y.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:A,hapEnd:A+y.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,o=n&&!st(n)?ft(n):void 0,s=c=>o!==void 0&&Vn(c,o)===0||st(ft(c)),i=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,l)=>Vn(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&&Vn(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,n=i=>`${i.pathHandle}:${i.hapStart}-${i.hapEnd}`,o=new Set;e?.identity&&t&&o.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let i of this.paths)i!==e&&i.identity?.orientation==="forward"&&o.add(n(i.identity));let s=this.paths.filter(i=>i===e||i.identity?.orientation!=="reverse"||!o.has(n(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 n=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=n===void 0?void 0:o.indexOf(n)}async extractChosenPaths(e,t,n,o){this.clearPaths();let s=e.position.seqOffset,i=await lo({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:n,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(ho);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=Fn(this.sortedHandles());if(t.length===0)return;let n=new Map,o=await Promise.all(t.map(([u,w])=>this.db.haplotypeSamplesInRange(u,w)));for(let u of o.flat())n.set($e(u),u);let s=u=>{let w=0,b=t.length-1;for(;w<b;){let g=w+b+1>>1;t[g][0]<=u?w=g:b=g-1}let S=t[w];return S[0]<=u&&u<=S[1]},i=new Map;this.paths.forEach((u,w)=>{u.path.length>0&&w!==this.refId&&i.set($e(Nt(u,0)),w)});let a=this.stats.identification;a.interval=e,a.scans=t,a.windowSamples=n.size,this.paths.forEach((u,w)=>{w!==this.refId&&a.fragmentLengths.push(u.len)});let f=this.recordReader(()=>{this.stats.identificationFetches+=1,a.graphFetches+=1}),c=u=>(a.graphLookups+=1,f(u)),l=async(u,w)=>{if(s(u.node))return n.get($e(u));this.stats.identificationFetches+=1,a.companionSeeks+=1,w.seeks+=1;let b=await this.db.haplotypeSampleAt(u.node,u.offset);return b||(a.companionMisses+=1),b},h=new Map,d=async u=>{let w=h.get(u);if(!w){let b=await this.db.getPath(u);if(!b)throw new Error(`Path ${u} is missing from the database`);w=b.name,h.set(u,w)}return w},p=(u,w,b)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.pathOffset-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.pathOffset+w+b},m=(u,w)=>u.orientation==="forward"?{pathHandle:u.pathHandle,orientation:"forward",base:u.hapStart-w}:{pathHandle:u.pathHandle,orientation:"reverse",base:u.hapEnd+w};for(let u=0;u<this.paths.length;u++){let w=this.paths[u];if(u===this.refId||w.identity)continue;let b=[],S=new Set,g={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};a.chains.push(g);let x,y=0,E=u,A;for(;x===void 0;){if(this.signal?.throwIfAborted(),E!==void 0){if(S.has(E)){g.end="cycle";break}S.add(E);let T=this.paths[E];b.push({index:E,startBp:y}),g.fragments+=1;let C=y;for(let Y=0;Y<T.path.length;Y++){let v=Nt(T,Y),R=n.get($e(v)),_=this.record(v.node).sequenceLen;if(R){x=p(R,C,_);break}C+=_}if(y+=T.len,x){g.end="in-fragment sample";break}let D=Nt(T,T.path.length-1);A=this.record(D.node).gbwt().lf(D.offset),E=void 0}if(A===void 0||A.node===0){g.end="endmarker";break}let N=$e(A),k=i.get(N);if(k!==void 0){let T=this.paths[k].identity;if(T){x=m(T,y),g.end="identified sibling";break}E=k;continue}this.records.has(A.node)&&(g.reentries+=1),this.twinStarts.has(N)&&(g.twinLandings+=1);let F=await l(A,g),M=await c(A.node);if(F){x=p(F,y,M.sequenceLen),g.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,g.steps+=1,y-b[b.length-1].startBp>4*e+4*M.sequenceLen){g.end="bound";break}y+=M.sequenceLen,A=M.gbwt().lf(A.offset)}if(x){g.pathHandle=x.pathHandle;let N=await d(x.pathHandle);for(let{index:k,startBp:F}of b){let M=this.paths[k];M.identity=x.orientation==="forward"?{pathHandle:x.pathHandle,name:N,orientation:"forward",hapStart:x.base+F,hapEnd:x.base+F+M.len}:{pathHandle:x.pathHandle,name:N,orientation:"reverse",hapStart:x.base-F-M.len,hapEnd:x.base-F}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,o)=>{let s=t.get(n);s?s.push(o):t.set(n,[o])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,o)=>{t.push(t[o]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=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=n.get(e[f]);if(c){let l=ni(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 n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}suffixMatches(e,t){let n=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 n;i+=1,a+=1,n+=1}i===f.length&&(o+=1,i=0),a===c.length&&(s+=1,a=0)}return n}align(e,t,n){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(n,"M",i),Mo(n,o-i-a,s-i-a),X(n,"M",a)}sharedWeight(e,t){let n=this.refIndex(t),o=0;for(let s of e)n.has(s)&&(o+=this.record(s).sequenceLen);return o}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let o=n??ti(po(e,t,h=>this.record(h).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(h,d,p,m)=>{h===d?X(s,"D",i[m]-i[p]):p===m?X(s,"I",this.pathLen(e.slice(h,d))):this.align(e.slice(h,d),t.slice(p,m),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 m=this.record(e[d]).sequenceLen;X(s,"M",m),f+=m,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 n=this.paths[this.refId].path,o;if(st(n)&&(t.identity===void 0||!st(ft(t.path))))o={...this.editsAgainst(t.path,n),flipped:!1};else{let s=ft(t.path),i=this.sharedWeight(t.path,n);if(this.sharedWeight(s,n)===0)o={...this.editsAgainst(t.path,n),flipped:!1};else if(i===0)o={...this.editsAgainst(s,n),flipped:!0};else{let f=this.editsAgainst(t.path,n),c=this.editsAgainst(s,n);o=c.matched>f.matched?{...c,flipped:!0}:{...f,flipped:!1}}}return o}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],o=(l,h,d,p)=>{let m=ci(l),u=this.paths[d[0]],w=this.paths[d[d.length-1]],b=u.identity,S=b?.orientation==="forward",[g,x]=S?[u,w]:[w,u];return{strand:h,refStart:e.start+m.leading,refEnd:e.start+n-m.trailing,edits:m.edits,weight:u.weight,path:d.flatMap(y=>this.paths[y].path),start:Nt(u,0),pieces:d,soloAligned:p,identity:b===void 0?void 0:{pathHandle:b.pathHandle,name:b.name,hapStart:b.name.fragment+g.identity.hapStart,hapEnd:b.name.fragment+x.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((C,D)=>C.strand!==h.strand||C.identity.walkForward!==p||D>0&&C.identity.hapStart<l[D-1].identity.hapEnd))return;let m=p?l:[...l].reverse(),u=m.flatMap(C=>C.pieces),w=m.flatMap(C=>C.soloAligned),b=h.strand==="+"!==p,S=u.map(C=>this.paths[C]),g=S.slice(1).map((C,D)=>{let Y=S[D].identity;return p?C.identity.hapStart-Y.hapEnd:Y.hapStart-C.identity.hapEnd}),x=b?[...S].reverse():S,y=b?[...g].reverse():g,E=x.flatMap(C=>b?ft(C.path):C.path),{edits:A}=this.editsAgainst(E,t),N=Ro(A,x.map(C=>C.len)),k=new Map((b?[...u].reverse():u).map((C,D)=>[C,N[D]])),F=C=>2*C.pieces.reduce((D,Y)=>D+k.get(Y),0)>=s(C);if(!F(h)||!F(d))return;let M=[],T=0;return x.slice(0,-1).forEach((C,D)=>{T+=C.len,M.push([T,y[D]])}),o(li(A,M),h.strand,u,w)},c=[];return this.paths.forEach((l,h)=>{if(h===this.refId)return;let{edits:d,flipped:p}=this.alignment(h),m=l.identity,u=m?m.orientation==="forward"!==p:!p;c.push(o(d,u?"+":"-",[h],Ro(d,[l.len])))}),si(c,a,f).map(l=>{let{edits:h,identity:d,pieces:p,soloAligned:m,...u}=l,w={...u,cigar:hi(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:n,...o}=e,s=this.paths.flatMap(l=>{let{identity:h}=l;return h?[{name:h.name,start:h.name.fragment+h.hapStart,steps:Lt(l,h)}]:[]}),i=l=>h=>h.sample===l.sample&&h.haplotype===l.haplotype,a=i(t),f=n?i(n):l=>!a(l),c=l=>this.record(be(l,"forward")).sequence;return s.filter(l=>a(l.name)).flatMap(l=>s.filter(h=>f(h.name)).flatMap(h=>Ao({...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:Co(d.edits),matches:d.edits.reduce((p,[m,u])=>p+(m==="="?u:0),0),columns:d.edits.reduce((p,[,m])=>p+m,0),sharedBases:d.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let o=be(e,n);for(let s of this.record(o).successors())this.hasHandle(s)&&Ue(o,s)&&t.push([n==="reverse"?1:0,O(s),j(s)?1:0])}return t.sort((n,o)=>n[0]-o[0]||n[1]-o[1]||n[2]-o[2]),t.filter((n,o)=>o===0||n[0]!==t[o-1][0]||n[1]!==t[o-1][1]||n[2]!==t[o-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!j(n)){let o=O(n),s=`S ${o} ${this.record(n).sequence}
2
+ `;for(let[i,a,f]of this.canonicalEdges(o))s+=`L ${o} ${i?"-":"+"} ${a} ${f?"-":"+"}
3
+ `;t.push(e.encode(s))}return io(t)}async toGFA(e={}){this.settleDeferred();let t=e.cigar??!1,n=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...so(oo(await this.stableName(),await this.db.graphName()))],o=this.sortedHandles();for(let c of o)j(c)||n.push(`S ${O(c)} ${this.record(c).sequence}`);let s=c=>j(c)?"-":"+";for(let c of o)for(let l of this.record(c).successors())this.hasHandle(l)&&Ue(c,l)&&n.push(`L ${O(c)} ${s(c)} ${O(l)} ${s(l)} 0M`);let i=(c,l,h,d,p)=>{let m=Lt(c,l).map(b=>`${j(b)?"<":">"}${O(b)}`).join(""),u=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} ${m}${u}${w}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.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;n.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}}),`${n.join(`
4
+ `)}
5
+ `}outputPaths(e){this.settleDeferred();let t=e.cigar??!1,n=[],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]};n.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;n.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}),n}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&Ue(e,t)&&(yield[e,t])}walkSpans(){return this.settleDeferred(),this.paths.flatMap((e,t)=>{let n=t===this.refId?void 0:e.identity;return n?[{name:n.name,start:n.name.fragment+n.hapStart,end:n.name.fragment+n.hapEnd}]:[]})}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!j(s)).map(s=>({id:String(O(s)),sequence:this.record(s).sequence})),n=[];for(let[s,i]of this.outputEdges())n.push({from:String(O(s)),from_is_reverse:j(s),to:String(O(i)),to_is_reverse:j(i)});let o=this.outputPaths(e).map(s=>fi(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:n,paths:o}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!j(i)),n=new Int32Array(t.length),o=[];t.forEach((i,a)=>{n[a]=O(i),o.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:n,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(Lt(i.info,i.identity))}))}}};function Lt(r,e){return e?.orientation==="reverse"?r.path.map(t=>re(t)).reverse():r.path}function fi(r,e,t,n){return{name:t,...r.weight===void 0?{}:{weight:r.weight},...n===void 0?{}:{cigar:n},path:Lt(r,e).map(o=>({id:String(O(o)),is_reverse:j(o)}))}}function Vn(r,e){let t=Math.min(r.length,e.length);for(let n=0;n<t;n++){let o=r[n],s=e[n];if(o!==s)return o<s?-1:1}return r.length-e.length}function X(r,e,t){if(t===0)return;let n=r[r.length-1];n?.[0]===e?n[1]+=t:r.push([e,t])}function Tt(r){return r===0?0:6+(r-1)}function Mo(r,e,t){if(e===0)X(r,"D",t);else if(t===0)X(r,"I",e);else{let n=Math.min(e,t),o=4*n+Tt(e-n)+Tt(t-n),s=Tt(e)+Tt(t);o<=s?(X(r,"M",n),X(r,"I",e-n),X(r,"D",t-n)):(X(r,"I",e),X(r,"D",t))}}function ci(r){let e=0;for(;e<r.length&&r[e][0]!=="M";)e+=1;if(e===r.length){let a=r.filter(([c])=>c==="I"),f=r.filter(([c])=>c==="D").reduce((c,[,l])=>c+l,0);return{edits:a.map(([c,l])=>[c,l]),leading:0,trailing:f}}let t=r.length;for(;r[t-1][0]!=="M";)t-=1;let n=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=n(r.slice(0,e)),s=n(r.slice(t)),i=[];X(i,"I",o.inserted);for(let[a,f]of r.slice(e,t))X(i,a,f);return X(i,"I",s.inserted),{edits:i,leading:o.deleted,trailing:s.deleted}}function Ro(r,e){let t=e.map(()=>0),n=e.length-1,o=0,s=e[0],i=0;for(let[a,f]of r){if(a==="D")continue;let c=f;for(;c>0;){for(;o<n&&i>=s;)o+=1,s+=e[o];let l=o<n?Math.min(c,s-i):c;a==="M"&&(t[o]+=l),i+=l,c-=l}}return t}function li(r,e){let t=[],n=0,o=0;for(let[s,i]of r){if(s==="D"){X(t,s,i);continue}let a=n;for(;o<e.length&&e[o][0]<n+i;){let[f,c]=e[o];X(t,s,f-a),X(t,"I",c),a=f,o+=1}X(t,s,n+i-a),n+=i}for(;o<e.length;o++)X(t,"I",e[o][1]);return t}function hi(r){return r.map(([e,t])=>`${t}${e}`).join("")}function _e(r,e,t=0){if(!Number.isSafeInteger(e)||e<t)throw new Error(`${r} must be a whole number${t>0?` of at least ${t}`:""}, not ${e}`);return e}function Ft(r){return _e("context",r.context??100)}function $t(r,e){return e.limit!==void 0&&_e("limit",e.limit),lt.create(r,e)}async function Po(r,e){let t=Ft(e),n=$t(r,e),o=await n.pathPosition(Ve(We(e.path),_e("offset",e.offset)));return await n.aroundPosition(o.position.handle,o.position.nodeOffset,t),await n.extractSnarls(e.snarls??"none"),n.extractPaths(o,e.haplotypes??"all"),n}async function di(r,e){let t=_e("start",e.start),n=_e("end",e.end),o=Ft(e),s=$t(r,e);try{let i=await s.pathPosition(Ve(We(e.path),t));return await s.prefetchReferenceWalk(i,n-t),await s.aroundInterval(i.position,n-t,o),await s.extractSnarls(e.snarls??"none"),{subgraph:s,reference:i}}catch(i){throw i instanceof fe&&i.windowBp===void 0?new fe(i.limit,{windowBp:n-t,walkedBp:s.referenceWalkedBp??0}):i}}async function Qn(r,e){let{keep:t}=e,n=e.haplotypes??"all",o=n==="all"||n==="distinct";if(t!==void 0&&o&&!r.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{subgraph:s,reference:i}=await di(r,e);return t===void 0||!o?(s.extractPaths(i,n),s):(await s.extractChosenPaths(i,e.end-e.start,t,Ft(e))||(s.extractPaths(i,"all"),await s.identifyPaths()),s.keepHaplotypes(t),n==="distinct"&&s.mergeDistinct(),s)}async function ko(r,e){let t=e.haplotypes??"all",n=e.snarls??"none";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");if(n==="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=Ft(e);for(let i of e.nodeIds)_e("node id",i,1);let s=$t(r,e);return await s.aroundNodes(e.nodeIds,o),await s.extractSnarls(n),s.extractPaths(void 0,t),s}async function _o(r,e){let t=e.haplotypes??"all";if(t==="reference-only")throw new Error("Cannot output a reference path in a node-based query");let n=$t(r,e);return await n.betweenNodes(_e("startHandle",e.startHandle,2),_e("endHandle",e.endHandle,2)),n.extractPaths(void 0,t),n}function Ee(r,e){let t=0;for(let o=0;o<8;o++){let s=r[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 n=r[e+8];if(n===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+n,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function pi(r,e,t){switch(t){case 1:return r.getInt8(e);case 2:return r.getInt16(e);case 3:return r.getInt8(e)<<16|r.getUint16(e+1);case 4:return r.getInt32(e);case 6:return r.getInt16(e)*4294967296+r.getUint32(e+2);default:{let n=r.getBigInt64(e);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${n} exceeds the safe integer range`);return Number(n)}}}var ui=new TextDecoder;function qt(r){let[e,t]=Ee(r,0),n=[],o=t;for(;o<e;){let[a,f]=Ee(r,o);n.push(a),o=f}let s=new DataView(r.buffer,r.byteOffset,r.byteLength),i=e;return n.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=pi(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=r.subarray(i,i+f);return i+=f,a%2===0?c:ui.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Ht=2,Dt=5,Oo=10,Bt=13;function No(r,e){return r[e]*256+r[e+1]}function Oe(r,e){return r[e]*16777216+r[e+1]*65536+r[e+2]*256+r[e+3]}function mi(r,e){let t=r[e];if(t!==Ht&&t!==Dt&&t!==Oo&&t!==Bt)throw new Error(`SQLite page has unknown b-tree type ${t}`);let n=t===Ht||t===Dt;return{type:t,cellCount:No(r,e+3),rightChild:n?Oe(r,e+8):0,cellPointers:e+(n?12:8)}}function Re(r,e,t){return No(r,e.cellPointers+2*t)}var gi=4096,Gt=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let n=this.usable,o=t?Math.floor((n-12)*64/255)-23:n-35;if(e<=o)return e;let s=Math.floor((n-12)*32/255)-23,i=s+(e-s)%(n-4);return i<=o?i:s}async payload(e,t,n,o){let s=this.localPayloadSize(n,o);if(s===n)return e.subarray(t,t+n);let i=new Uint8Array(n);i.set(e.subarray(t,t+s),0);let a=s,f=Oe(e,t+s);for(;f!==0&&a<n;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,n-a));i.set(l,a),a+=l.length,f=Oe(c,0)}if(a!==n)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:mi(t,e===1?100:0)}}tableDepth(e,t){let n=this.tableDepths.get(e);return n||(n=(async()=>{let o=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(o);if(a.type===Bt)return s;if(a.type!==Dt)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);o=f===a.cellCount?a.rightChild:Oe(i,Re(i,a,f))}})(),this.tableDepths.set(e,n),n.catch(()=>this.tableDepths.delete(e))),n}childIndexFor(e,t,n){let o=0,s=t.cellCount;for(;o<s;){let i=o+s>>1,[a]=Ee(e,Re(e,t,i)+4);a<n?o=i+1:s=i}return o}async prefetchRowidRanges(e,t,n=!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(n)this.pager.prefetchLeading(a);else if(!this.pager.prefetch(a))return!1}return!0}async childrenInRange(e,t,n){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,n):a.cellCount;for(let h=c;h<=l;h++)s.push(h===a.cellCount?a.rightChild:Oe(i,Re(i,a,h)))}),s}async tableRowid(e,t){let n=e;for(;;){let{page:o,header:s}=await this.pageAt(n);if(s.type===Bt){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,h=Re(o,s,l),[d,p]=Ee(o,h),[m,u]=Ee(o,p);if(m===t)return qt(await this.payload(o,u,d,!1));m<t?f=l+1:c=l}return}if(s.type!==Dt)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=Re(o,s,f),[l]=Ee(o,c+4);l<t?i=f+1:a=f}n=i===s.cellCount?s.rightChild:Oe(o,Re(o,s,i))}}async*tableScan(e){yield*this.scanPage(e,await this.tableDepth(e,0))}async*scanPage(e,t){let{page:n,header:o}=await this.pageAt(e);if(o.type===Bt)for(let s=0;s<o.cellCount;s++){let i=Re(n,o,s),[a,f]=Ee(n,i),[c,l]=Ee(n,f);yield{rowid:c,values:qt(await this.payload(n,l,a,!1))}}else{let s=[];for(let i=0;i<o.cellCount;i++)s.push(Oe(n,Re(n,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 n=this.decodedIndexPages.get(e);if(n)this.decodedIndexPages.delete(e);else if(n=new Array(t.cellCount),this.decodedIndexPages.size>=gi){let o=this.decodedIndexPages.keys().next().value;o!==void 0&&this.decodedIndexPages.delete(o)}return this.decodedIndexPages.set(e,n),n}async indexCell(e,t,n,o){let s=this.decodedCells(e,n),i=s[o];if(!i){let a=Re(t,n,o),f=n.type===Ht,[c,l]=Ee(t,f?a+4:a);i={values:qt(await this.payload(t,l,c,!0)),leftChild:f?Oe(t,a):0},s[o]=i}return i}async lowerBound(e,t,n,o,s,i){let a=s,f=n.cellCount;for(;a<f;){let c=a+f>>1,l=await this.indexCell(e,t,n,c),h=Yn(l.values,o);h<0||i&&h===0?a=c+1:f=c}return a}async*indexScanFrom(e,t,n){let{page:o,header:s}=await this.pageAt(e),i=await this.lowerBound(e,o,s,t,0,!1),a=s.type===Ht;if(a&&n){let f=await this.lowerBound(e,o,s,n,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,n)),n&&Yn(c.values,n)>0)return;yield c.values}a&&(yield*this.indexScanFrom(s.rightChild,t,n))}async indexSeekLE(e,t){let n,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);Yn(h.values,t)<=0?(n=h.values,a=l+1):(c=h.leftChild,f=l)}if(i.type===Oo)return n;o=a===i.cellCount?i.rightChild:c}}};function Yn(r,e){for(let t=0;t<e.length;t++){let n=r[t],o=e[t];if(typeof n!="number"||o===void 0)throw new Error("SQLite index key is not numeric");if(n!==o)return n<o?-1:1}return 0}function To({blockSize:r,maxBlocks:e}){if(r!==void 0&&!(Number.isSafeInteger(r)&&r>0))throw new Error(`blockSize must be a positive integer, not ${r}`);if(e!==void 0&&!(Number.isSafeInteger(e)&&e>0))throw new Error(`maxBlocks must be a positive integer, not ${e}`)}var zt=class{blocks=new Map;blockSize;maxBlocks;plan;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,n,o={}){this.source=e,this.pageSize=t,this.fileSize=n;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 n=await this.readRetrying(e,t);if(this.bytesFetched+=n.length,n.length<e)throw new Error(`the file ends at byte ${t+n.length}, short of the ${this.fileSize} bytes its SQLite header gives`);return n}async readRetrying(e,t){let n=0;for(;;)try{return await this.source.read(e,t)}catch(o){if(n+=1,n>=3)throw o;await new Promise(s=>setTimeout(s,200*n))}}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 n=e*this.blockSize,o=Math.min(this.blockSize,this.fileSize-n),s=this.read(o,n);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(n=>this.blockOf(n)));return t.size>this.prefetchBudget?!1:(this.fetchBlocks(t),!0)}prefetchLeading(e){let t=[],n=new Map;for(let o of e){let s=this.blockOf(o);n.has(s)||(n.set(s,t.length),t.push(s))}this.plan={blocks:t,position:n,next:0},this.advance(this.prefetchBudget)}advance(e){let t=this.plan;if(!t)return;let n=t.blocks.slice(t.next,t.next+e);t.next+=n.length,t.next>=t.blocks.length&&(this.plan=void 0),this.fetchBlocks(new Set(n))}follow(e){let t=this.plan,n=t?.position.get(e);t&&n!==void 0&&n>=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),n=0;for(;n<t.length;){let o=n+1;for(;o<t.length&&t[o]===t[o-1]+1;)o+=1;this.fetchRun(t[n],o-n),n=o}}fetchRun(e,t){let n=e*this.blockSize,o=Math.min(t*this.blockSize,this.fileSize-n),s=this.read(o,n);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 n=await this.block(Math.floor(t/this.blockSize)),o=t%this.blockSize;return n.subarray(o,o+this.pageSize)}};var ht=class r{pager;btree;objects;constructor(e,t,n){this.pager=e,this.btree=t,this.objects=n}static async open(e,t={}){To(t);let n=await e.read(Math.max(512,t.blockSize??65536),0),o=n.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 zt(e,f,d,t);p.seed(0,n),p.fetches+=1,p.bytesFetched+=n.length;let m=new Gt(p,c),u=new Map;for await(let{values:w}of m.tableScan(1)){let[b,S,g,x,y]=w;typeof b=="string"&&typeof S=="string"&&typeof g=="string"&&typeof x=="number"&&u.set(S,{type:b,name:S,tableName:g,rootPage:x,sql:typeof y=="string"?y:""})}return new r(p,m,u)}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(n=>n.type==="index"&&n.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,n=!1){return this.btree.prefetchRowidRanges(this.rootPage(e),t,n)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t,n){return this.btree.indexScanFrom(this.indexOn(e),t,n)}has(e){return this.objects.has(e)}};var Jn="GBZ-base version 4",jt=class extends Error{name="UnknownPathError";path;constructor(e){super(`the graph has no path named ${me(e)}`),this.path=e}},Ut=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")}},Wt=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 "${Jn}"`),this.found=e}};function wi(r){if(r.length===1)return r[0];let e=new Uint8Array(r.reduce((n,o)=>n+o.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}var Kn=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 n=this.bytes[this.at++];if(n===void 0)throw new Error("a haplotype index blob ends inside a number");if(e+=(n&127)*t,t*=128,(n&128)===0)return e}}};function xi(r,e){let t=new Ye(r),n=0;for(;!t.done;){let o=n+t.next();n=o+t.next(),e.push([o,n])}}function yi(r){r.sort((n,o)=>n[0]-o[0]);let e=[],t=[];for(let[n,o]of r){let s=t.length-1;s>=0&&n<=t[s]+1?t[s]=Math.max(t[s],o):(e.push(n),t.push(o))}return n=>{let o=0,s=e.length;for(;o<s;){let i=o+s>>1;e[i]<=n?o=i+1:s=i}return o>0&&n<=t[o-1]}}function bi(r,e,t){let n=new Ye(e);for(;!n.done;){let o=n.next(),s=n.next(),i=n.next(),a=n.next(),f=n.next();t.push({bin:r,pathHandle:o,pathStart:s,pathEnd:i,snarl:f>0?[a,f]:void 0,node:n.next(),offset:n.next()})}}function Si(r,e,t){let n=O(r);for(let o of e){let s=new Ye(o);for(;!s.done;){let i=s.next(),a=i%2;t.push({node:2*n+a,offset:s.next(),pathHandle:(i-a)/2,orientation:"forward",pathOffset:s.next()})}}}var Zn=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,n,o,s){this.handle=e,this.edges=t,this.bwt=n,this.encodedSequence=o,this.next=s,this.sequenceLen=Xr(o)}get id(){return O(this.handle)}get orientation(){return je(this.handle)}get sequence(){return this.decoded??=Zr(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 At(this.edges,this.bwt)}};function Q(r,e){if(typeof r!="number")throw new Error(`${e} is not a number in the database`);return r}function dt(r,e){if(typeof r!="string")throw new Error(`${e} is not text in the database`);return r}function qe(r,e){if(!(r instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return r}function Lo(r,e){return{handle:r,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:dt(e[5],"Paths.sample"),contig:dt(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 Xn(r,e){return r.catch(e),r}async function Fo(r){let e=new Map;for await(let{values:t}of r.scan("Tags"))e.set(dt(t[0],"Tags.key"),dt(t[1],"Tags.value"));return e}var pt=class r{pathCache;pathMapCache;indexTags=new Map;overviewRowsCache;sqlite;index;tagMap;constructor(e,t,n){this.sqlite=e,this.index=t,this.tagMap=n}static async open(e){let{source:t,haplotypeIndex:n}=e,o={blockSize:e.blockSize,maxBlocks:e.maxBlocks},s=await ht.open(t,o),i=s.objects.has("Tags")?await Fo(s):new Map,a=i.get("version");if(a!==Jn)throw new Wt(a);for(let l of["Nodes","Paths","ReferenceIndex"])s.rootPage(l);let f=n?await ht.open(n,o):void 0,c=new r(s,f,i);if(f){for(let u of["Tags","HaplotypeSamples","HaplotypeLengths"])if(!f.objects.has(u))throw new Error(`haplotypeIndex is not a gbz-base haplotype index: it has no ${u} table`);c.indexTags=await Fo(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 Ut;let m=c.indexTags.get("haplotype_index_format");if(Number(m)!==Kn)throw new Error(m===void 0?`the haplotype index predates format ${Kn}; rebuild it with gbz-haplotype-index 0.3`:`the haplotype index has format ${m}; this version of @gmod/gbz-base reads format ${Kn}`)}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 n=t[4];return new Zn(e,Kr(qe(t[1],"Nodes.edges")),qe(t[2],"Nodes.bwt"),qe(t[3],"Nodes.sequence"),typeof n=="number"?n:void 0)}paths(){return this.pathCache??=Xn(this.scanPaths(),()=>{this.pathCache=void 0}),this.pathCache}async scanPaths(){let e=[];for await(let{rowid:t,values:n}of this.sqlite.scan("Paths"))e.push(Lo(t,n));return e}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?Lo(e,t):void 0}pathsByHandle(){return this.pathMapCache??=Xn(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(n=>n.name.sample===e.sample&&n.name.contig===e.contig&&n.name.haplotype===e.haplotype&&n.name.fragment<=e.fragment).sort((n,o)=>o.name.fragment-n.name.fragment)[0]}async pathsNamed(e){let t=Ve(We(e),0);return(await this.paths()).filter(n=>n.name.sample===t.sample&&n.name.contig===t.contig&&n.name.haplotype===t.haplotype).sort((n,o)=>n.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 n=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!n){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=n.pathOffset,s=n.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:n}=e;if(Number.isNaN(t)||Number.isNaN(n))throw new Error(`The window ${t}..${n} is not a number range`);let o=await this.pathsNamed(e.path);if(o.length===0)throw new jt(Ve(We(e.path),0));if(n<=t)return[];let s=o.filter(f=>f.name.fragment<=t).slice(-1),i=o.filter(f=>f.name.fragment>t&&f.name.fragment<n);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:n,contig:o,haplotype:s}=e.path.name,i=Math.max(t.start,e.start),a=t.haplotypes??"all";try{let f=await Qn(this,{...t,path:{sample:n,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 fe&&f.walkedBp!==void 0?new fe(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 Qn(this,e)}subgraphAtOffset(e){return Po(this,e)}subgraphAroundNodes(e){return ko(this,e)}subgraphBetween(e){return _o(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[n,o]of await this.tags())n.startsWith("gbz_")&&e.set(n.slice(4),o);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=ro(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=n=>this.indexTags.get(`haplotype_index_stray_${n}`);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,n){let o=[],s=[];for await(let i of this.companion.indexScanFrom(e,t,n))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,n){let o=[],s=[];for(let i of await this.blobRows("HaplotypeBins",[e,t],[e,n])){let a=Q(i[1],"HaplotypeBins.bin");xi(qe(i[3],"HaplotypeBins.nodes"),o),bi(a,qe(i[4],"HaplotypeBins.strays"),s)}return{listed:yi(o),strays:s}}async haplotypeAnchorsBetween(e,t,n){let o=[],s=[],i=()=>{let a=o[o.length-1];a&&Si(a.node,s,a.visits),s=[]};for(let a of await this.blobRows("HaplotypeAnchors",[e,t],[e,n])){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(qe(a[5],"HaplotypeAnchors.visits"))}return i(),o}async haplotypeAnchor(e,t){let[n]=await this.haplotypeAnchorsBetween(e,t,t);return n&&{node:n.node,pathOffset:n.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 n=[];for await(let o of this.companion.indexScanFrom("HaplotypeSamples",[e,0],[t,Number.MAX_SAFE_INTEGER]))n.push(this.sampleFromRow(o));return n}async haplotypeSampleAt(e,t){let n=await this.companion.indexSeekLE("HaplotypeSamples",[e,t]);return n?.[0]===e&&n[1]===t?this.sampleFromRow(n):void 0}overviewRows(){return this.overviewRowsCache??=Xn((async()=>{let e=[];for await(let{rowid:t,values:n}of this.companion.scan("HaplotypeOverviewRows"))e[t]={sample:dt(n[1],"HaplotypeOverviewRows.sample"),haplotype:Q(n[2],"HaplotypeOverviewRows.haplotype")};return e})(),()=>{this.overviewRowsCache=void 0}),this.overviewRowsCache}async overviewChunks(e,t,n,o,s){let i=new Map;for(let a of await this.blobRows(e,[t,n,o],[t,n,s])){let f=Q(a[2],`${e}.chunk`),c=i.get(f)??[];c.push(qe(a[4],`${e} blob`)),i.set(f,c)}return new Map([...i].map(([a,f])=>[a,wi(f)]))}async haplotypeOverview(e){let{signal:t}=e;t?.throwIfAborted();let n=u=>this.indexTags.get(`haplotype_index_overview_${u}`);if(!this.index?.has("HaplotypeOverviewClasses")||n("format")!=="1")return;let o=Number(n("bin")),s=Number(n("chunk")),i=Number(n("levels")),a=Math.max(0,Math.min(Math.floor(e.level??0)||0,i-1));if(e.level===void 0&&e.bpPerPixel!==void 0)for(;a+1<i&&o*4**(a+1)<=e.bpPerPixel;)a+=1;let f=o*4**a,[c,l]=await Promise.all([this.getPathFragments(e),this.overviewRows()]);t?.throwIfAborted();let h=Math.ceil(l.length/2),d=[],p=[];for(let u of c){let w=u.end-u.start,b=Math.max(e.start,u.start)-u.start,S=Math.min(e.end,u.end)-u.start,g=Math.floor(b/f),x=Math.floor((S-1)/f),y=Math.floor(g/s),E=Math.floor(x/s),[A,N]=await Promise.all([this.overviewChunks("HaplotypeOverviewBins",u.path.handle,a,y,E),this.overviewChunks("HaplotypeOverviewClasses",u.path.handle,a,y,E)]);t?.throwIfAborted();for(let k=y;k<=E;k++){let F=new Ye(A.get(k)??new Uint8Array),M=N.get(k)??new Uint8Array;for(let T=k*s;!F.done;T++){let C=Array.from({length:7},()=>F.next());if(T<g||T>x)continue;d.push({start:u.start+T*f,end:u.start+Math.min((T+1)*f,w),classes:[C[0],C[1],C[2],C[3]],excursions:C[4],variants:C[5],longestExcursion:C[6]});let D=(T-k*s)*h;p.push(M.subarray(D,D+h))}}}if(d.length===0)return;let m=new Uint8Array(d.length*l.length);return p.forEach((u,w)=>{for(let b=0;b<l.length;b++)m[w*l.length+b]=(u[b>>1]??0)>>4*(b%2)&15}),{level:a,bin:f,haplotypes:l,bins:d,cells:m}}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 n=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return n?.[0]===e?Q(n[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let n=await this.indexedRowid(e,t);return n===void 0?void 0:this.indexedRow(n)}async indexedPositionsBetween(e,t,n){let[o,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,n)]),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}};function Vt(r){let e=/\.gbz\.db$/i;return e.test(r)?r.replace(e,".haplotype-index.db"):void 0}function Ii(r){return Hr(r)&&Vt(Br(r))?Dr(r,e=>Vt(e)):void 0}function vi(r){return r instanceof Error&&(/\bHTTP 40[34]\b/.test(r.message)||r.code==="ENOENT")}async function $o(r,e){let t=Ii(r);if(!t)return{};try{return await ze(t,e).stat(),{location:t}}catch(n){return vi(n)?{}:{unreadable:String(n)}}}var Ei=5e3,Ai=50*2**20,er=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 Ci(r,e){if(r.length<=e)return r;let t=r.length/e;return Array.from({length:e},(n,o)=>r[Math.floor(o*t)])}var qo=(r,e)=>r.path.some(t=>e.has(t.name)),Qt=class{constructor(e,t){this.file=e;this.tabix=t;this.whole=ot({setup:async({signal:e})=>{let{size:t}=await this.file.stat();if(t>Ai)throw new er(t);let n=await this.file.readFile({signal:e}),o=new TextDecoder().decode(n[0]===31&&n[1]===139?await jr(n):n);return Tn(o)}})}async readIndexed(e,t,n){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:n,lineCallback:a=>{let f=Nn(a);f&&qo(f,t)&&i.push(f)}}),i}async readsOver(e,{signal:t}={}){let n=this.tabix?await this.readIndexed(this.tabix,e,t):(await this.whole({signal:t})).filter(o=>qo(o,e));return{records:Ci(n,Ei),total:n.length}}};var tr=function(r,e){return tr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},tr(r,e)};function ut(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");tr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Bo(r,e,t,n){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(n.next(l))}catch(h){i(h)}}function f(l){try{c(n.throw(l))}catch(h){i(h)}}function c(l){l.done?s(l.value):o(l.value).then(a,f)}c((n=n.apply(r,e||[])).next())})}function Yt(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,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(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(n=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(r,t)}catch(l){c=[6,l],o=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Be(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ke(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return s}function Xe(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))}function He(r){return this instanceof He?(this.v=r,this):new He(r)}function Ho(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,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(m){return Promise.resolve(m).then(p,h)}}function a(p,m){n[p]&&(o[p]=function(u){return new Promise(function(w,b){s.push([p,u,w,b])>1||f(p,u)})},m&&(o[p]=m(o[p])))}function f(p,m){try{c(n[p](m))}catch(u){d(s[0][3],u)}}function c(p){p.value instanceof He?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,m){p(m),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Do(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Be=="function"?Be(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(i){return new Promise(function(a,f){i=r[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 H(r){return typeof r=="function"}function Go(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Kt=Go(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
6
+ `+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
7
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function nr(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var Xt=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,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=Be(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(u){e={error:u}}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(H(l))try{l()}catch(u){s=u instanceof Kt?u.errors:[u]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var d=Be(h),p=d.next();!p.done;p=d.next()){var m=p.value;try{zo(m)}catch(u){s=s??[],u instanceof Kt?s=Xe(Xe([],Ke(s)),Ke(u.errors)):s.push(u)}}}catch(u){n={error:u}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(n)throw n.error}}}if(s)throw new Kt(s)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)zo(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&nr(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&nr(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var zf=Xt.EMPTY;function Zt(r){return r instanceof Xt||r&&"closed"in r&&H(r.remove)&&H(r.add)&&H(r.unsubscribe)}function zo(r){H(r)?r():r.unsubscribe()}var Se={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ze={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];var o=Ze.delegate;return o?.setTimeout?o.setTimeout.apply(o,Xe([r,e],Ke(t))):setTimeout.apply(void 0,Xe([r,e],Ke(t)))},clearTimeout:function(r){var e=Ze.delegate;return(e?.clearTimeout||clearTimeout)(r)},delegate:void 0};function Jt(r){Ze.setTimeout(function(){var e=Se.onUnhandledError;if(e)e(r);else throw r})}function rr(){}var jo=(function(){return or("C",void 0,void 0)})();function Uo(r){return or("E",void 0,r)}function Wo(r){return or("N",r,void 0)}function or(r,e,t){return{kind:r,value:e,error:t}}var De=null;function Vo(r){if(Se.useDeprecatedSynchronousErrorHandling){var e=!De;if(e&&(De={errorThrown:!1,error:null}),r(),e){var t=De,n=t.errorThrown,o=t.error;if(De=null,n)throw o}}else r()}function Qo(r){Se.useDeprecatedSynchronousErrorHandling&&De&&(De.errorThrown=!0,De.error=r)}var mt=(function(r){ut(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Zt(t)&&t.add(n)):n.destination=ki,n}return e.create=function(t,n,o){return new tn(t,n,o)},e.prototype.next=function(t){this.isStopped?ir(Wo(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?ir(Uo(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?ir(jo,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.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})(Xt);var Ri=Function.prototype.bind;function sr(r,e){return Ri.call(r,e)}var Mi=(function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){en(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){en(n)}else en(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){en(t)}},r})(),tn=(function(r){ut(e,r);function e(t,n,o){var s=r.call(this)||this,i;if(H(t)||!t)i={next:t??void 0,error:n??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&&sr(t.next,a),error:t.error&&sr(t.error,a),complete:t.complete&&sr(t.complete,a)}):i=t}return s.destination=new Mi(i),s}return e})(mt);function en(r){Se.useDeprecatedSynchronousErrorHandling?Qo(r):Jt(r)}function Pi(r){throw r}function ir(r,e){var t=Se.onStoppedNotification;t&&Ze.setTimeout(function(){return t(r,e)})}var ki={closed:!0,next:rr,error:Pi,complete:rr};var Je=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Yo(r){return r}function Ko(r){return r.length===0?Yo:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var he=(function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,s=Oi(e)?e:new tn(e,t,n);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},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Xo(t),new t(function(o,s){var i=new tn({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:o});n.subscribe(i)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[Je]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ko(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Xo(e),new e(function(n,o){var s;t.subscribe(function(i){return s=i},function(i){return o(i)},function(){return n(s)})})},r.create=function(e){return new r(e)},r})();function Xo(r){var e;return(e=r??Se.Promise)!==null&&e!==void 0?e:Promise}function _i(r){return r&&H(r.next)&&H(r.error)&&H(r.complete)}function Oi(r){return r&&r instanceof mt||_i(r)&&Zt(r)}function Ni(r){return H(r?.lift)}function ge(r){return function(e){if(Ni(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function Me(r,e,t,n,o){return new Ti(r,e,t,n,o)}var Ti=(function(r){ut(e,r);function e(t,n,o,s,i,a){var f=r.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=n?function(c){try{n(c)}catch(l){t.error(l)}}:r.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._error,f._complete=o?function(){try{o()}catch(c){t.error(c)}finally{this.unsubscribe()}}:r.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(mt);var nn=(function(r){return r&&typeof r.length=="number"&&typeof r!="function"});function rn(r){return H(r?.then)}function on(r){return H(r[Je])}function sn(r){return Symbol.asyncIterator&&H(r?.[Symbol.asyncIterator])}function an(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Li(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fn=Li();function cn(r){return H(r?.[fn])}function ln(r){return Ho(this,arguments,function(){var t,n,o,s;return Yt(this,function(i){switch(i.label){case 0:t=r.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,He(t.read())];case 3:return n=i.sent(),o=n.value,s=n.done,s?[4,He(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,He(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 hn(r){return H(r?.getReader)}function Ae(r){if(r instanceof he)return r;if(r!=null){if(on(r))return Fi(r);if(nn(r))return $i(r);if(rn(r))return qi(r);if(sn(r))return Zo(r);if(cn(r))return Bi(r);if(hn(r))return Hi(r)}throw an(r)}function Fi(r){return new he(function(e){var t=r[Je]();if(H(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function $i(r){return new he(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function qi(r){return new he(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Jt)})}function Bi(r){return new he(function(e){var t,n;try{for(var o=Be(r),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&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}e.complete()})}function Zo(r){return new he(function(e){Di(r,e).catch(function(t){return e.error(t)})})}function Hi(r){return Zo(ln(r))}function Di(r,e){var t,n,o,s;return Bo(this,void 0,void 0,function(){var i,a;return Yt(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Do(r),f.label=1;case 1:return[4,t.next()];case 2:if(n=f.sent(),!!n.done)return[3,4];if(i=n.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]),n&&!n.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(r,e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var s=e.schedule(function(){t(),o?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(s),!o)return s}function dn(r,e){return e===void 0&&(e=0),ge(function(t,n){t.subscribe(Me(n,function(o){return we(n,r,function(){return n.next(o)},e)},function(){return we(n,r,function(){return n.complete()},e)},function(o){return we(n,r,function(){return n.error(o)},e)}))})}function pn(r,e){return e===void 0&&(e=0),ge(function(t,n){n.add(r.schedule(function(){return t.subscribe(n)},e))})}function Jo(r,e){return Ae(r).pipe(pn(e),dn(e))}function es(r,e){return Ae(r).pipe(pn(e),dn(e))}function ts(r,e){return new he(function(t){var n=0;return e.schedule(function(){n===r.length?t.complete():(t.next(r[n++]),t.closed||this.schedule())})})}function ns(r,e){return new he(function(t){var n;return we(t,e,function(){n=r[fn](),we(t,e,function(){var o,s,i;try{o=n.next(),s=o.value,i=o.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return H(n?.return)&&n.return()}})}function un(r,e){if(!r)throw new Error("Iterable cannot be null");return new he(function(t){we(t,e,function(){var n=r[Symbol.asyncIterator]();we(t,e,function(){n.next().then(function(o){o.done?t.complete():t.next(o.value)})},0,!0)})})}function rs(r,e){return un(ln(r),e)}function os(r,e){if(r!=null){if(on(r))return Jo(r,e);if(nn(r))return ts(r,e);if(rn(r))return es(r,e);if(sn(r))return un(r,e);if(cn(r))return ns(r,e);if(hn(r))return rs(r,e)}throw an(r)}function ar(r,e){return e?os(r,e):Ae(r)}function gt(r,e){return ge(function(t,n){var o=0;t.subscribe(Me(n,function(s){n.next(r.call(e,s,o++))}))})}function ss(r,e,t,n,o,s,i,a){var f=[],c=0,l=0,h=!1,d=function(){h&&!f.length&&!c&&e.complete()},p=function(u){return c<n?m(u):f.push(u)},m=function(u){s&&e.next(u),c++;var w=!1;Ae(t(u,l++)).subscribe(Me(e,function(b){o?.(b),s?p(b):e.next(b)},function(){w=!0},void 0,function(){if(w)try{c--;for(var b=function(){var S=f.shift();i?we(e,i,function(){return m(S)}):m(S)};f.length&&c<n;)b();d()}catch(S){e.error(S)}}))};return r.subscribe(Me(e,p,function(){h=!0,d()})),function(){a?.()}}function et(r,e,t){return t===void 0&&(t=1/0),H(e)?et(function(n,o){return gt(function(s,i){return e(n,s,o,i)})(Ae(r(n,o)))},t):(typeof e=="number"&&(t=e),ge(function(n,o){return ss(n,o,r,t)}))}function is(r,e,t,n,o){return function(s,i){var a=t,f=e,c=0;s.subscribe(Me(i,function(l){var h=c++;f=a?r(f,l,h):(a=!0,l),n&&i.next(f)},o&&(function(){a&&i.next(f),i.complete()})))}}function as(r,e){return ge(is(r,e,arguments.length>=2,!1,!0))}var Gi=function(r,e){return r.push(e),r};function mn(){return ge(function(r,e){as(Gi,[])(r).subscribe(e)})}function fs(r){let e=[],t=0,n;for(let o=0,s=r.length;o<s;o++){let i=r.charCodeAt(o);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)n=t,t=0;else{let a=r[o];a==="M"||a==="="||a==="X"?e.push({own:n===void 0?t:n,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}),n=void 0,t=0}}return e}function lr(r){let e="";for(let{own:t,mate:n,op:o}of fs(r))e+=o==="M"?t===0?`${n}I`:n===0?`${t}D`:`${t}M`:`${o==="I"?n:t}${o}`;return e}var fr=2**28-1;function cr(r,e,t){for(let n=e;n>0;n-=fr)r.push((Math.min(n,fr)<<4|t)>>>0)}function zi(r,e,t){if(e===t)cr(r,e,0);else{let n=Math.ceil(Math.max(e,t)/fr);for(let o=0;o<n;o++){let s=Math.floor(e*(o+1)/n)-Math.floor(e*o/n),i=Math.floor(t*(o+1)/n)-Math.floor(t*o/n);r.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function hr(r){let e=[];for(let{own:t,mate:n,op:o}of fs(r))o==="M"?zi(e,t,n):o==="I"?cr(e,n,1):cr(e,t,o==="N"?3:2);return Uint32Array.from(e)}function ji(r){return r>=48&&r<=57}function Ui(r){return r!==void 0&&/[A-Za-z]/.test(r)}function cs(r,e){let t=e;for(;t<r.length&&Ui(r[t]);)t++;return t}function ls(r,e){let t=e,n=0;for(;t<r.length&&ji(r.charCodeAt(t));)n=n*10+(r.charCodeAt(t)-48),t++;return{value:n,next:t}}function ms(r,e){let t=0;for(;t<r.length;){let n=r[t];if(n===":"){let{value:o,next:s}=ls(r,t+1);e(":",o,o,t+1,s),t=s}else if(n==="="){let o=cs(r,t+1),s=o-t-1;e("=",s,s,t+1,o),t=o}else if(n==="*")e("*",1,1,t+1,Math.min(t+3,r.length)),t+=3;else if(n==="+"||n==="-"){let o=cs(r,t+1),s=o-t-1;e(n,n==="-"?s:0,n==="+"?s:0,t+1,o),t=o}else if(n==="~"){let{value:o,next:s}=ls(r,t+3),i=Math.min(s+2,r.length);e("~",o,0,t+1,i),t=i}else t++}}function dr(r,e,t,n){let o=t??Number.NEGATIVE_INFINITY,s=n??Number.POSITIVE_INFINITY,i=0;ms(r,(a,f,c,l,h)=>{if(a==="*")i>=o&&i<s&&e(88,i,1,r[l+1]??"",-1,0,0);else if(a==="+"){if(i>=o&&i<=s){let d=r.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(r,e,t,n){let o=0,s=0,i=[],a=t&&e;for(let f=0,c=r.length;f<c;f++){let l=r[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:n?.[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(r,e,t,n,o){if(!e)return[];let s=[],i=e.length,a=n.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,m=0,u=0,w=0,b=r.length;for(;w<b;){let S=r.charCodeAt(w);if(S>=48&&S<=57){let g=0;for(;w<b;){let x=r.charCodeAt(w);if(x>=48&&x<=57)g=g*10+(x-48),w++;else break}h+=g}else if(S===94)for(w++;w<b&&r.charCodeAt(w)>=65;)w++,h++;else if(S>=65){let g=r[w];if(w++,l&&c>0)for(let N=u;N<c;N++){let k=t[N];k.type==="skip"&&h>=k.start&&(h+=k.length,u=N+1)}let x=p,y=m;for(let N=d;N<i&&y<=h;N++,d=N){let k=e[N],F=k>>>4,M=k&15;M===4||M===1?x+=F:M===2||M===6||M===3?y+=F:M!==5&&(x+=F,y+=F)}p=x,m=y;let E=x-(y-h),A=E<a?n[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(r=""){let e=0,t=[];for(let n=0,o=r.length;n<o;n++){let s=r.charCodeAt(n);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 mr(r=""){let e=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),n=0,o=0;for(let s=0,i=r.length;s<i;s++){let a=r.charCodeAt(s);a>=48&&a<=57?n=n*10+(a-48):(t[o++]=n<<4|xs[a],n=0)}return t}function bn(r,e,t,n,o){let s=ys(r),i=r?gs(s,t,n,o):[];return e&&t?i.concat(ws(e,s,i,t,o)):i}var Qi=397,Yi=387,Ki=385;function bs(r){return(1<<r&Qi)!==0}function Ss(r){return(1<<r&Yi)!==0}function Is(r){return(1<<r&Ki)!==0}function gr(r,e,t,n,o,s,i){let a=o===-1?-1:1,f=e,c=o===-1?n:t,l=[],h=1/0,d=-1/0,p=1/0,m=-1/0,u=(w,b)=>{p=Math.min(p,w,b),m=Math.max(m,w,b)};for(let w=0;w<r.length;w++){let b=r[w],S=b>>>4,g=b&15,x=g===9,y=x||bs(g)?S:0,E=x?r[++w]>>>4:Ss(g)?S:0,A=f+y,N=c+E*a,k=f,F=A;if(F>=s&&k<=i)if(y>0){let M=Math.max(k,s),T=Math.min(F,i);if(T>M)if(h=Math.min(h,M),d=Math.max(d,T),x){let C=E/S,D=T-M,Y=Math.round(D*C),v=Math.round(c+(M-f)*C*a);l.push(D<<4|9,Y<<4|9),u(v,v+Y*a)}else l.push(T-M<<4|g),Is(g)?u(c+(M-f)*a,c+(T-f)*a):u(c,c)}else E>0&&(x?l.push(b,r[w]):l.push(b),h=Math.min(h,f),d=Math.max(d,f),u(c,N));if(f=A,c=N,f>i)break}if(l.length!==0)return{start:h,end:d,mateStart:p,mateEnd:m,cigar:Uint32Array.from(l)}}function Xi(r){return r===1||r===2||r===3}function wr(r,e,t,n,o,s){let i=o===-1?-1:1,a=[],f=e,c=o===-1?n: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<r.length;p++){let m=r[p],u=m>>>4,w=m&15,b=w===9,S=b?r[++p]:void 0,g=b||bs(w)?u:0,x=S!==void 0?S>>>4:Ss(w)?u:0,y=c+x*i;Xi(w)&&u>=s?d():(g>0||x>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,y),l.tHi=Math.max(l.tHi,c,y),l.ops.push(m),S!==void 0&&l.ops.push(S),h=h||b||Is(w)),f+=g,c=y}return d(),a}function vs(r){let e=r.get("CIGAR");return typeof e=="string"?e:void 0}function Es(r){let e=r.get("coarseCigar");return typeof e=="string"?e:void 0}function xr(r){let e=vs(r),t=e===void 0?Es(r):void 0;return e!==void 0?mr(e):t!==void 0?hr(t):void 0}var Ne=class extends Lr{get(e){return e==="mismatches"?bn(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"?lr(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let n=this.get("start"),o=t?.start===void 0?void 0:t.start-n,s=t?.end===void 0?void 0:t.end-n,i=this.get("cs");if(i)dr(i,e,o,s);else{let a=o??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of bn(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 Zi=["CIGAR","cs","coarseCigar","cg","cr"];function Ji(r){return typeof r=="object"&&r!==null&&"refName"in r&&"start"in r&&"end"in r&&typeof r.refName=="string"&&typeof r.start=="number"&&typeof r.end=="number"}function ea(r){let e=r.get("mate");return Ji(e)?e:void 0}function ta(r,e,t,n){let o=Math.max(r.start,n.start),s=Math.min(r.end,n.end),i=(e.end-e.start)/Math.max(r.end-r.start,1),a=l=>t===-1?e.end-(l-r.start)*i:e.start+(l-r.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 na(r,e,t,n,o){let s={start:r.get("start"),end:r.get("end")},i=r.get("strand")===-1?-1:1,a=s.start>=t.start&&s.end<=t.end,f=a&&n===void 0&&!o?void 0:xr(r);if(f===void 0){let c=a?{...s,mateStart:e.start,mateEnd:e.end}:ta(s,e,i,t);return c===void 0?[]:[c]}else return(n===void 0?[{...s,mateStart:e.start,mateEnd:e.end,cigar:f}]:wr(f,s.start,e.start,e.end,i,n)).flatMap(l=>{let h=gr(l.cigar,l.start,l.mateStart,l.mateEnd,i,t.start,t.end);return h===void 0?[]:[h]})}function ra(r,e,t,n,o,s){let i=`:${n.start}-${n.end}${o}`,a=r.toJSON(),f={...a,uniqueId:`${r.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 Zi)delete f[c];return s&&t.cigar&&(f.alignmentOps=t.cigar),new Ne(f)}function As(r,e,t,n=!1){let o=ea(r);if(o===void 0)return[r];{let s=na(r,o,e,t,n);return s.map((i,a)=>ra(r,o,i,e,s.length>1?`/${a}`:"",n))}}var Sn=class extends Gr{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,n={}){let{clipToRegion:o,splitAtGapBp:s,keepAlignment:i,...a}=n,f=o&&this.recordsAreAlignments,c=Fr(a.statusCallback);return ar(t).pipe(et((l,h)=>this.getFeatures(l,{...a,statusCallback:c()}).pipe(et(d=>f?As(d,d.get("assemblyName")===l.assemblyName?l:{start:d.get("start"),end:d.get("end")},s,i):[d]),mn(),gt(d=>({index:h,features:d})))),mn(),et(l=>l.sort((h,d)=>h.index-d.index).flatMap(h=>h.features)))}};var In=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"}},Sr=class extends Error{constructor(t){super(`a pair query names both lanes: queryAssemblyName ${t} came without a targetAssemblyName`);this.name="PairTargetError"}};function oa(r,e){if(e===void 0)throw new Sr(r);return{queryAssemblyName:r,targetAssemblyName:e}}var Ir=class extends Error{constructor(t,n){super(`the graph is cut on its reference, ${n}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${n} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}};function Cs(r,e){let t=ye(e);return r[t]??r[e.sample]??t}function sa(r,e){return`${ye(r)}#${r.contig}@${e.start.node}.${e.start.offset}`}function ia({alignment:r,assemblyName:e,refName:t,lane:n}){let{refStart:o,refEnd:s,strand:i,cigar:a}=r;if(!(!r.resolved||s<=o)){let{name:f,hapStart:c,hapEnd:l}=r,h=sa(f,r),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:n}};return new Ne(d)}}function aa({pair:r,lane:e,mateLane:t}){let n=`${ye(r.target)}#${r.target.contig}:${r.targetStart}-${r.targetEnd}|${ye(r.query)}#${r.query.contig}:${r.queryStart}-${r.queryEnd}`;return new Ne({uniqueId:n,assemblyName:e,refName:r.target.contig,start:r.targetStart,end:r.targetEnd,type:"match",strand:r.strand==="-"?-1:1,CIGAR:r.cigar,syntenyId:n,identity:r.matches/Math.max(r.columns,1),numMatches:r.matches,blockLen:r.columns,mate:{refName:r.query.contig,start:r.queryStart,end:r.queryEnd,assemblyName:t}})}var fa=12e4;function ca(r,e){let t=new Map;for(let o of r)for(let{name:s,start:i,end:a}of o.walkSpans()){let f=ye(s);if(e.has(f)){let c=`${f}#${s.contig}`;t.set(c,[...t.get(c)??[],[i,a]])}}let n=0;for(let o of t.values()){o.sort((s,i)=>s[0]-i[0]);for(let s=1;s<o.length;s++){let i=o[s][0]-o[s-1][1];i>0&&i<=fa&&(n=Math.max(n,i))}}return n}function yr(r,e){return r instanceof qr&&(r.message=`Zoom in to about ${$r(r.fitsBp)} to see ${e}`),r}var br=r=>!("uri"in r)||r.uri!=="",vr=class extends Sn{constructor(){super(...arguments);this.graph=ot({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("gbzDbLocation"),n=this.getConf("haplotypeIndexLocation"),o=br(n)?{location:n}:await $o(t,this.pluginManager),s=o.location,i=await pt.open({source:ze(t,this.pluginManager),haplotypeIndex:s?ze(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 Pn(i),c=St({configured:this.getConf("referenceSample"),anchorPrefix:Ge(this,a),referenceSamples:f});return{db:i,anchor:a,referenceSample:c,referenceSamples:f,unreadableIndex:o.unreadable}}});this.gaf=ot({label:"Opening reads",setup:async()=>{let t=this.getConf("readsLocation"),n=this.getConf(["readsIndex","location"]);return br(t)?new Qt(ze(t,this.pluginManager),br(n)?Ur(this,["readsLocation"],["readsIndex"]):void 0):void 0}})}async referenceQuery(t,n){let{db:o,referenceSample:s}=await this.graph(n);return kn(o,s,t)}async getHaplotypes(t={}){let{db:n,referenceSamples:o}=await this.graph(t),s=new Map;for(let i of await n.paths()){let a=ye(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:n,referenceSample:o,referenceSamples:s}=await this.graph(t),i=Rn(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==o&&a.push({name:Cs(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:n,referenceSample:o,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:n,anchor:o,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===o?void 0:Ge(this,i),f=(await n.paths()).filter(c=>i===o?c.isIndexed&&c.name.sample===s:bt(ye(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,n){let o=t===void 0||t.length===0?void 0:t.map(s=>Ge(this,s));return o===void 0&&n===void 0?void 0:s=>Mn(s,o)&&(n===void 0||bt(ye(s),n))}async getSubgraph(t,n={}){let{signal:o}=n,{db:s,anchor:i,referenceSample:a,unreadableIndex:f}=await this.graph({signal:o}),{assemblyName:c,refName:l,start:h,end:d}=t;if(c!==i)throw new Ir(c,i);let p=await this.referenceQuery(l,{signal:o});if(!p)throw new Error(`${a} has no indexed path ${l} in this graph`);let m=this.keepPredicate(n.haplotypes);if(m!==void 0&&!s.hasHaplotypeIndex)throw new In(f);return On(s,p,h,d,{context:this.getConf("context"),snarls:n.snarls??this.getConf("subgraphSnarls"),limit:this.getConf("nodeLimit"),signal:n.signal,keep:m}).catch(u=>{throw yr(u,"the graph")})}async getReads(t,n={}){let o=await this.gaf(n);return o?o.readsOver(new Set(t),n):{records:[],total:0}}async laneHaplotypes(t,n){let o=Ge(this,t);return(await this.getHaplotypes(n)).filter(s=>bt(s.prefix,o))}async anchorFeatures(t,n){let{db:o}=await this.graph(n),{assemblyName:s,refName:i,start:a,end:f}=t,c=Ge(this,n.targetAssemblyName),l=Rn(this),h=this.keepPredicate(n.haplotypes,c),d=await this.referenceQuery(i,n),p=this.getConf("nodeLimit");return(d?await Cn(`Reading graph ${i}:${a.toLocaleString()}-${f.toLocaleString()}`,n.statusCallback,()=>o.getAlignments({path:d,start:a,end:f,context:this.getConf("context"),haplotypes:"all",limit:p,signal:n.signal,keep:h}).catch(u=>{throw yr(_n(u,p,f-a)??u,"lanes")})):[]).flatMap(u=>{let w=u.resolved?ia({alignment:u,assemblyName:s,refName:i,lane:Cs(l,u.name)}):void 0;return w===void 0?[]:[w]})}async pairFeatures(t,n,o){let{db:s}=await this.graph(o),{refName:i,start:a,end:f}=t,l=(await Promise.all(n.map(async g=>({pair:g,featureSide:await this.laneHaplotypes(g.queryAssemblyName,o),mateSide:await this.laneHaplotypes(g.targetAssemblyName,o)})))).filter(({featureSide:g,mateSide:x})=>g.length>0&&x.length>0),h=new Set(l.flatMap(({featureSide:g,mateSide:x})=>[...g,...x].map(ye))),d=await this.referenceQuery(i,o),p=this.getConf("nodeLimit"),m=this.getConf("context"),[u]=n,w=(g,x)=>s.getSubgraphs({path:g,start:a,end:f,context:x,snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:o.signal,keep:y=>h.has(ye(y))}),b=async g=>{let x=await w(g,m).catch(A=>{throw yr(_n(A,p,f-a)??A,"lanes")}),y=ca(x,h),E=Math.ceil(y/2)+2e3;return y>0&&E>m?w(g,E).catch(A=>{if(A instanceof fe)return x;throw A}):x};return(d&&u&&l.length>0?await Cn(n.length===1?`Reading ${u.queryAssemblyName} against ${u.targetAssemblyName}`:`Reading ${n.length} lane pairs`,o.statusCallback,()=>b(d)):[]).flatMap(g=>l.flatMap(({pair:x,featureSide:y,mateSide:E})=>y.flatMap(A=>E.flatMap(N=>g.pairAlignments({target:A,query:N,bases:!1}).map(k=>aa({pair:k,lane:x.queryAssemblyName,mateLane:x.targetAssemblyName}))))))}getFeatures(t,n={}){return zr(async o=>{let{db:s,anchor:i,unreadableIndex:a}=await this.graph(n);if(!s.hasHaplotypeIndex)throw new In(a);if(t.assemblyName===i){let f=n.lanePairs?.length?await this.pairFeatures(t,n.lanePairs,n):n.queryAssemblyName===void 0?await this.anchorFeatures(t,n):await this.pairFeatures(t,[oa(n.queryAssemblyName,n.targetAssemblyName)],n);for(let c of f)o.next(c)}o.complete()},n.signal)}};export{Ir as HaplotypeWindowError,In as NoHaplotypeIndexError,_s as NoReferenceSampleError,Sr as PairTargetError,vr as default,ia as fragmentFeature,Cs as laneAssemblyName,aa as pairFeature,St as resolveReferenceSample,ca as widestWalkGap};
8
+ //# sourceMappingURL=GbzBaseSyntenyAdapter-WPRJGI7E.js.map