jbrowse-plugin-graphgenomeviewer 8.0.2 → 8.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{AddTrackWorkflow-RJSOQZYQ.js → AddTrackWorkflow-7CXTSSMR.js} +2 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-EJIR3HZM.js +2 -0
- package/dist/chunks/GbzBaseSyntenyAdapter-EJIR3HZM.js.map +7 -0
- package/dist/chunks/{GraphGenomeView-667ZUNDI.js → GraphGenomeView-2AKRM74B.js} +2 -2
- package/dist/chunks/{GraphTrackSettingsDialog-7M3Q635V.js → GraphTrackSettingsDialog-7XRZQW6T.js} +2 -2
- package/dist/chunks/{HighlightColorDialog-4F34Q4PY.js → HighlightColorDialog-LCBGD2ZA.js} +2 -2
- package/dist/chunks/LinearGraphDisplay-WWQ73BO5.js +2 -0
- package/dist/chunks/{MinigraphBubbleAdapter-G25V6MZL.js → MinigraphBubbleAdapter-4OOBJ44C.js} +2 -2
- package/dist/chunks/RgfaTabixAdapter-CEGFN2QY.js +2 -0
- package/dist/chunks/RgfaTabixAdapter-CEGFN2QY.js.map +7 -0
- package/dist/chunks/{WalkFormsAdapter-PBN7BJZW.js → WalkFormsAdapter-LTAKACZD.js} +2 -2
- package/dist/chunks/{WalkTabixSyntenyAdapter-27WDE5JF.js → WalkTabixSyntenyAdapter-B6V3YNW7.js} +2 -2
- package/dist/chunks/chunk-5FNGR33G.js +2 -0
- package/dist/chunks/chunk-5FNGR33G.js.map +7 -0
- package/dist/chunks/chunk-6VNDP3UB.js +2 -0
- package/dist/chunks/chunk-6VNDP3UB.js.map +7 -0
- package/dist/chunks/{chunk-CJAV55QB.js → chunk-BJHWGRMP.js} +1 -1
- package/dist/chunks/{chunk-CJAV55QB.js.map → chunk-BJHWGRMP.js.map} +1 -1
- package/dist/chunks/{chunk-IAXUZMOX.js → chunk-CNCYMJ5E.js} +2 -2
- package/dist/chunks/{chunk-IAXUZMOX.js.map → chunk-CNCYMJ5E.js.map} +2 -2
- package/dist/chunks/{chunk-2V75YPTT.js → chunk-CVHKXFVS.js} +2 -2
- package/dist/chunks/{chunk-2V75YPTT.js.map → chunk-CVHKXFVS.js.map} +2 -2
- package/dist/chunks/chunk-CZI7IP5S.js +2 -0
- package/dist/chunks/chunk-CZI7IP5S.js.map +7 -0
- package/dist/chunks/chunk-CZXJXNZN.js +3 -0
- package/dist/chunks/chunk-CZXJXNZN.js.map +7 -0
- package/dist/chunks/chunk-HAAABGE7.js +2 -0
- package/dist/chunks/{chunk-JMRW3IGK.js → chunk-IK3MQ4ZJ.js} +2 -2
- package/dist/chunks/chunk-IK3MQ4ZJ.js.map +7 -0
- package/dist/chunks/{chunk-JOYKGTDE.js → chunk-MCBYBZZJ.js} +2 -2
- package/dist/chunks/chunk-NOXHIOIM.js +2 -0
- package/dist/chunks/chunk-NOXHIOIM.js.map +7 -0
- package/dist/chunks/{chunk-FY7X6253.js → chunk-OGXVDZPS.js} +2 -2
- package/dist/chunks/{chunk-FY7X6253.js.map → chunk-OGXVDZPS.js.map} +2 -2
- package/dist/chunks/{chunk-3EQNVA3F.js → chunk-OLZZDBQJ.js} +2 -2
- package/dist/chunks/{chunk-3EQNVA3F.js.map → chunk-OLZZDBQJ.js.map} +2 -2
- package/dist/chunks/{chunk-I6F25EXY.js → chunk-PTOKTIQG.js} +2 -2
- package/dist/chunks/{chunk-O5FDMVL3.js → chunk-QWG7NASD.js} +2 -2
- package/dist/chunks/chunk-SL4JJJQJ.js +3 -0
- package/dist/chunks/chunk-SL4JJJQJ.js.map +7 -0
- package/dist/chunks/{chunk-XB5KC2EZ.js → chunk-T2VC3EEL.js} +1 -1
- package/dist/chunks/{chunk-XB5KC2EZ.js.map → chunk-T2VC3EEL.js.map} +1 -1
- package/dist/chunks/{chunk-2PNGGCQJ.js → chunk-UECOGSWM.js} +2 -2
- package/dist/chunks/{chunk-2PNGGCQJ.js.map → chunk-UECOGSWM.js.map} +1 -1
- package/dist/chunks/chunk-UHV6XIDG.js +2 -0
- package/dist/chunks/chunk-UHV6XIDG.js.map +7 -0
- package/dist/chunks/{chunk-5RHNR3TH.js → chunk-VKZALU57.js} +1 -1
- package/dist/chunks/{chunk-5RHNR3TH.js.map → chunk-VKZALU57.js.map} +1 -1
- package/dist/chunks/chunk-W7IHIVSE.js +2 -0
- package/dist/chunks/{chunk-XWCLYB5C.js.map → chunk-W7IHIVSE.js.map} +4 -4
- package/dist/chunks/{chunk-NLS74JSZ.js → chunk-WUOXZAGN.js} +2 -2
- package/dist/chunks/{chunk-NLS74JSZ.js.map → chunk-WUOXZAGN.js.map} +1 -1
- package/dist/chunks/{renderSvg-YNA5VK6A.js → renderSvg-E5Q7MLCH.js} +2 -2
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js +5 -5
- package/dist/jbrowse-plugin-graphgenomeviewer.esm.js.map +4 -4
- package/package.json +4 -4
- package/src/GraphAddTrackWorkflow/buildTrackConfig.ts +12 -2
- package/src/GraphAddTrackWorkflow/graphManifest.ts +16 -9
- package/src/GraphGenomeView/components/HoverTooltip.tsx +8 -0
- package/src/GraphGenomeView/pane/paneBase.ts +14 -9
- package/src/RgfaTabixAdapter/RgfaTabixAdapter.ts +94 -41
- package/src/RgfaTabixAdapter/configSchema.ts +35 -4
- package/src/RgfaTabixAdapter/format2.test.ts +128 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f1.links.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f1.links.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f1.segs.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f1.segs.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f2.graph.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/pggb_ecoli_f2.graph.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/test_data/walks5_skip.GRCh38.walks.bed.gz +0 -0
- package/src/RgfaTabixAdapter/test_data/walks5_skip.GRCh38.walks.bed.gz.tbi +0 -0
- package/src/RgfaTabixAdapter/walkFiles.test.ts +21 -0
- package/src/RgfaTabixAdapter/walkReader.ts +20 -15
- package/src/graphTrackDefaults/index.ts +2 -2
- package/src/locationName.ts +2 -0
- package/src/version.ts +1 -1
- package/dist/chunks/GbzBaseSyntenyAdapter-EGNUOKB2.js +0 -2
- package/dist/chunks/GbzBaseSyntenyAdapter-EGNUOKB2.js.map +0 -7
- package/dist/chunks/LinearGraphDisplay-BAEMS5WG.js +0 -2
- package/dist/chunks/RgfaTabixAdapter-JPTUWO2Z.js +0 -2
- package/dist/chunks/RgfaTabixAdapter-JPTUWO2Z.js.map +0 -7
- package/dist/chunks/chunk-AH5UWTAV.js +0 -2
- package/dist/chunks/chunk-AH5UWTAV.js.map +0 -7
- package/dist/chunks/chunk-DG3E6BSX.js +0 -3
- package/dist/chunks/chunk-DG3E6BSX.js.map +0 -7
- package/dist/chunks/chunk-HLAQQI6G.js +0 -2
- package/dist/chunks/chunk-HLAQQI6G.js.map +0 -7
- package/dist/chunks/chunk-IKJZPPOA.js +0 -2
- package/dist/chunks/chunk-IKJZPPOA.js.map +0 -7
- package/dist/chunks/chunk-JMRW3IGK.js.map +0 -7
- package/dist/chunks/chunk-Q7QC2EQU.js +0 -2
- package/dist/chunks/chunk-RHYBJCA4.js +0 -2
- package/dist/chunks/chunk-RHYBJCA4.js.map +0 -7
- package/dist/chunks/chunk-X7YIGIYW.js +0 -2
- package/dist/chunks/chunk-X7YIGIYW.js.map +0 -7
- package/dist/chunks/chunk-XWCLYB5C.js +0 -2
- package/dist/chunks/chunk-ZGTG74GE.js +0 -3
- package/dist/chunks/chunk-ZGTG74GE.js.map +0 -7
- /package/dist/chunks/{AddTrackWorkflow-RJSOQZYQ.js.map → AddTrackWorkflow-7CXTSSMR.js.map} +0 -0
- /package/dist/chunks/{GraphGenomeView-667ZUNDI.js.map → GraphGenomeView-2AKRM74B.js.map} +0 -0
- /package/dist/chunks/{GraphTrackSettingsDialog-7M3Q635V.js.map → GraphTrackSettingsDialog-7XRZQW6T.js.map} +0 -0
- /package/dist/chunks/{HighlightColorDialog-4F34Q4PY.js.map → HighlightColorDialog-LCBGD2ZA.js.map} +0 -0
- /package/dist/chunks/{LinearGraphDisplay-BAEMS5WG.js.map → LinearGraphDisplay-WWQ73BO5.js.map} +0 -0
- /package/dist/chunks/{MinigraphBubbleAdapter-G25V6MZL.js.map → MinigraphBubbleAdapter-4OOBJ44C.js.map} +0 -0
- /package/dist/chunks/{WalkFormsAdapter-PBN7BJZW.js.map → WalkFormsAdapter-LTAKACZD.js.map} +0 -0
- /package/dist/chunks/{WalkTabixSyntenyAdapter-27WDE5JF.js.map → WalkTabixSyntenyAdapter-B6V3YNW7.js.map} +0 -0
- /package/dist/chunks/{chunk-Q7QC2EQU.js.map → chunk-HAAABGE7.js.map} +0 -0
- /package/dist/chunks/{chunk-JOYKGTDE.js.map → chunk-MCBYBZZJ.js.map} +0 -0
- /package/dist/chunks/{chunk-I6F25EXY.js.map → chunk-PTOKTIQG.js.map} +0 -0
- /package/dist/chunks/{chunk-O5FDMVL3.js.map → chunk-QWG7NASD.js.map} +0 -0
- /package/dist/chunks/{renderSvg-YNA5VK6A.js.map → renderSvg-E5Q7MLCH.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as x,b,c as N,d as R,f as c,g as C,h as P,i as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=WalkFormsAdapter-
|
|
1
|
+
import{a as x,b,c as N,d as R,f as c,g as C,h as P,i as T}from"./chunk-PTOKTIQG.js";import{a as k}from"./chunk-KOB7YIMR.js";import{E as $,b as l,d as g,e as w,f as h,g as p,k as y,o as B,s as F,t as S}from"./chunk-CZXJXNZN.js";import"./chunk-YBLNN5FU.js";import"./chunk-ROZPEXN4.js";import"./chunk-VKZALU57.js";import"./chunk-OGQ6OQDN.js";import"./chunk-3WG3GF2A.js";import{a as m,o as u}from"./chunk-J5RMHLFJ.js";var v=r=>`${(r/1e6).toFixed(1)} MB`,O=r=>`${(r/1e6).toFixed(1)} M`;function E(r,f){if(!(r instanceof g))return r;let t=N(f);if(r instanceof F)return new Error(`The pinned window ${t} is too large to read every walk in full for structural forms: its walks take ${O(r.steps)} steps, over the ${O(r.limit)} step budget, and about ${p(r.fitsBp)} of it fits. Pin a narrower window`);let e=`walkByteBudget, ${v(r.limit)}`;return new Error(`The pinned window ${t} is too large to cut for structural forms: ${r.zoomHelps?`about ${p(r.fitsBp)} of it fits in ${e}. Pin a narrower window or raise walkByteBudget`:`its cut fetches ${v(r.bytes??0)}, over ${e}. Raise walkByteBudget`}`)}var L=8,i=new Map;function A(r,f){let t=i.get(r),e=t??f();if(i.delete(r),i.set(r,e),!t){e.catch(()=>{i.get(r)===e&&i.delete(r)});for(let s of i.keys()){if(i.size<=L)break;i.delete(s)}}return e}var d=class extends l{constructor(){super(...arguments);this.reader=new y($(this,["walksLocation"],["walksIndex"]))}static{this.capabilities=["getFeatures","getRefNames"]}async referenceSample(t){let{references:e}=await this.reader.header(t);return e[0]??""}async getRefNames(t={}){let e=await this.reader.referenceSequences(t),s=await this.referenceSample(t),a=e.filter(o=>h(o,s)).map(o=>w(o));return a.length>0?[...new Set(a)]:e}pinned(){let t=x(this.getConf("pinned"));if(!t)throw new Error("WalkFormsAdapter needs `pinned`, the window its forms come from: { refName, start, end }");return t}forms(t){if(!this.formsRead){let e=this.pinned(),s=`${JSON.stringify(this.getConf("walksLocation"))} ${e.refName}:${e.start}-${e.end}`,a=this.getConf("walkByteBudget"),o=A(`${s} ${a}`,()=>u("Cutting walks",t.statusCallback,()=>S(this.reader,e,{byteBudget:a,partial:!1}).catch(n=>{throw E(n,e)}))).then(n=>B(n,{window:e,floorBp:b(this.getConf("floorBp")),exclude:this.getConf("exclude")}));o.catch(()=>{this.formsRead===o&&(this.formsRead=void 0)}),this.formsRead=o}return this.formsRead}maxForms(){return this.getConf("maxForms")}async getSourcesAndWarnings(t={}){let e=await this.forms(t),s=R(this.pinned());return{sources:c(e,this.maxForms()),warnings:C(e,this.maxForms()).map(a=>s+a)}}async getSources(t,e={}){return c(await this.forms(e),this.maxForms())}async onPinnedSequence(t,e){let s=await this.referenceSample(e),[a,o]=await Promise.all([this.reader.sequenceFor(s,t,e),this.reader.sequenceFor(s,this.pinned().refName,e)]);return a!==void 0&&a===o}getFeatures(t,e={}){return k(async s=>{let a=await this.forms(e),o=await this.onPinnedSequence(t.refName,e)?T(a,this.maxForms()).filter(n=>n.start<t.end&&n.end>t.start):[];for(let n of o)s.next(new m({uniqueId:`forms-${a.floorBp}-${n.id}`,refName:t.refName,start:n.start,end:n.end,name:n.name,description:n.description,type:n.type,svType:n.svType,consequence:n.consequence,REF:"N",ALT:[n.alt],INFO:{SVTYPE:[n.svType],SVLEN:[n.mark.delta]},mark:n.mark,genotypes:n.genotypes}));if(o.length===0){let n=Math.floor(t.start);s.next(new m({uniqueId:`forms-reference-${t.refName}-${n}`,refName:t.refName,start:n,end:n+1,REF:"N",ALT:["."],genotypes:P(a,this.maxForms())}))}s.complete()},e.signal)}};export{d as default};
|
|
2
|
+
//# sourceMappingURL=WalkFormsAdapter-LTAKACZD.js.map
|
package/dist/chunks/{WalkTabixSyntenyAdapter-27WDE5JF.js → WalkTabixSyntenyAdapter-B6V3YNW7.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as K}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=WalkTabixSyntenyAdapter-
|
|
1
|
+
import{a as K}from"./chunk-NOXHIOIM.js";import{b as $,d as U,e as X,f as O,g as z,h as G}from"./chunk-QWG7NASD.js";import"./chunk-HAAABGE7.js";import{a as q}from"./chunk-KOB7YIMR.js";import{p as M,q as _,r as T}from"./chunk-M2D7NUOY.js";import"./chunk-YBLNN5FU.js";import"./chunk-CZI7IP5S.js";import"./chunk-IK3MQ4ZJ.js";import{E as D,F as H,i as j}from"./chunk-CZXJXNZN.js";import"./chunk-YBLNN5FU.js";import"./chunk-ROZPEXN4.js";import{a as S,c as I,d as W,g as F,h as w,i as x}from"./chunk-VKZALU57.js";import"./chunk-OTBDKJEA.js";import"./chunk-3VGXCEMQ.js";import"./chunk-OGQ6OQDN.js";import"./chunk-3WG3GF2A.js";import{o as R}from"./chunk-J5RMHLFJ.js";var se=50;function re(r){let i=[];for(let e=0;e<r.length;e++){let[t,a]=r[e],[s,n]=r[e+1]??[];a===n&&a<=se&&(t==="I"&&s==="D"||t==="D"&&s==="I")?(i.push(["X",a]),e++):i.push([t,a])}return i}function E(r){return Array.from(r.ids,(i,e)=>2*i+r.rev[e])}function A(r,i){let e=r.get(i);return e===void 0?0:e.end-e.start}function V(r){let i=new Map,e=s=>{let n=A(r,s),o=i.get(n);return o===void 0&&(o="N".repeat(n),i.set(n,o)),o},t=new Map,a=s=>{let n=t.get(s);return n===void 0&&(n=E(s),t.set(s,n)),n};return(s,n)=>_({query:a(s),target:a(n),sequenceOf:e,bases:!1})}var B=100;function v(r,i,e){let t=r.at(-1);e>0&&(t?.[0]===i?t[1]+=e:r.push([i,e]))}function Z(r){let i=t=>A(r,t>>1),e=t=>{let a=new Float64Array(t.length+1);return t.forEach((s,n)=>{a[n+1]=a[n]+i(s)}),a};return(t,a)=>{let s=E(a),n=E(t),[o,l]=M(n,s,i),[u,f]=M(n.map(g=>g^1).reverse(),s,i),c=f>l,p=c?u:o,N=Math.max(l,f);if(N<B)return[];let h=e(s),d=e(n),y=g=>c?n.length-1-p[g][0]:p[g][0],m=[];p.forEach(([,g],k)=>{if(k>0){let[ee,te]=[y(k-1),y(k)].sort((ae,ne)=>ae-ne);v(m,"I",d[te]-d[ee+1]),v(m,"D",h[g]-h[p[k-1][1]+1])}v(m,"=",i(s[g]))});let[b,P]=[y(0),y(p.length-1)].sort((g,k)=>g-k);return[{queryStart:d[b],queryEnd:d[P+1],targetStart:h[p[0][1]],targetEnd:h[p.at(-1)[1]+1],strand:c?"-":"+",edits:m,sharedBases:N}]}}function oe(r){let i=new Map,e=new Set;r.ids.forEach((t,a)=>{i.has(t)?e.add(t):i.set(t,r.rev[a])});for(let t of e)i.delete(t);return i}function J(r){let i=new Map,e=t=>{let a=i.get(t);return a===void 0&&(a=oe(t),i.set(t,a)),a};return(t,a)=>{let s=e(a),n=0,o=0;for(let[l,u]of e(t)){let f=s.get(l);f===u?n+=A(r,l):f!==void 0&&(o+=A(r,l))}return{same:n,opposite:o}}}function Q(r){let i=Z(r),e=V(r),t=J(r);return(a,s)=>{let{same:n,opposite:o}=t(a,s);return n>=B&&o>=B?e(a,s):i(a,s)}}var ie=1e4;function Y(r){let i=Z(r),e=V(r),t=J(r);return(a,s)=>{let n=i(a,s),o=n[0]?.strand,{same:l,opposite:u}=t(a,s);return o===void 0||Math.min(l,u)<ie?n:[...n,...e(a,s).filter(f=>f.strand!==o)]}}function C({chain:r,target:i,query:e,assemblyName:t,refName:a,mateAssemblyName:s}){let n=re(r.edits);return G({target:{name:i.name,assemblyName:t,refName:a,start:i.hapStart+r.targetStart,end:i.hapStart+r.targetEnd},query:{name:e.name,assemblyName:s,refName:W(e.name),start:e.hapStart+r.queryStart,end:e.hapStart+r.queryEnd},strand:r.strand,cigar:T(n),matches:n.reduce((o,[l,u])=>o+(l==="="?u:0),0),columns:n.reduce((o,[,l])=>o+l,0)})}var me=r=>I(r.name)??r.name,L=class extends ${constructor(){super(...arguments);this.walks=new K(D(this,["walksLocation"],["walksIndex"]),this);this.refNames=new H(this.walks.file,this)}get anchor(){let e=this.getConf("assemblyNames")[0];if(e===void 0)throw new Error("WalkTabixSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");return e}async getHaplotypeNames(e={}){return this.walks.haplotypeNames(e)}async getHeader(e={}){let{haplotypes:t}=await this.walks.reader.header(e),{anchor:a}=this,s=w(this,a),n=x(this);return{hasCoarseTier:!1,anchorAssemblyName:a,lanes:t.filter(o=>o!==s&&S(o)!==s).map(o=>({name:O(n,o),label:o,group:S(o)}))}}async getRefNames(e={}){let{assemblyName:t}=e;return t===void 0||t===this.anchor?this.refNames.assemblyRefNames({...e,assemblyName:this.anchor}):[]}async getSubgraph(e,t={}){let a=await this.refNames.resolveForCut(e,{signal:t.signal});return this.walks.subgraph(a,e,t)}async laneWalks(e,t,a,s,n){let o=j(a,e);return R(n,s.statusCallback,()=>this.walks.reader.cut(e,t,{...this.walks.budgets(),signal:s.signal,keep:o,expand:o,links:!1}).catch(l=>{throw z(l,t.end-t.start)}))}async anchorFeatures(e,t,a){let s=a.haplotypes?.length?a.haplotypes.map(m=>w(this,m)):void 0,n=w(this,a.targetAssemblyName),o=n===void 0?s:s===void 0||s.some(m=>F(n,m)||F(m,n))?[n]:[];if(o?.length===0)return[];let{start:l,end:u}=t,{graph:f,fragments:c}=await this.laneWalks(e,t,o,a,`Reading walks ${t.refName}:${l.toLocaleString()}-${u.toLocaleString()}`),p=Y(f.nodes),N=x(this),h=c.filter(m=>m.name===e),d=m=>o===void 0?0:o.findIndex(b=>F(m.name,b));return c.filter(m=>m.name!==e&&d(m)>=0).sort((m,b)=>d(m)-d(b)).flatMap(m=>h.flatMap(b=>p(m,b).map(P=>C({chain:P,target:b,query:m,assemblyName:t.assemblyName,refName:t.refName,mateAssemblyName:O(N,me(m))}))))}async pairFeatures(e,t,a,s){let n=a.map(c=>({pair:c,featurePrefix:w(this,c.queryAssemblyName),matePrefix:w(this,c.targetAssemblyName)})),{graph:o,fragments:l}=await this.laneWalks(e,t,n.flatMap(c=>[c.featurePrefix,c.matePrefix]),s,X(a)),u=Q(o.nodes),f=c=>l.filter(p=>F(p.name,c));return n.flatMap(({pair:c,featurePrefix:p,matePrefix:N})=>f(p).flatMap(h=>f(N).flatMap(d=>u(d,h).map(y=>C({chain:y,target:h,query:d,assemblyName:c.queryAssemblyName,refName:W(h.name),mateAssemblyName:c.targetAssemblyName})))))}getFeatures(e,t={}){return q(async a=>{let s=e.assemblyName===this.anchor?await this.refNames.resolve(e,t):void 0;if(s!==void 0){let n=U(t),o=n.length>0?await this.pairFeatures(s,e,n,t):await this.anchorFeatures(s,e,t);for(let l of o)a.next(l)}a.complete()},t.signal)}};export{L as default};
|
|
2
|
+
//# sourceMappingURL=WalkTabixSyntenyAdapter-B6V3YNW7.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as m}from"./chunk-3VGXCEMQ.js";import{a as p,b as l,c as h,d as A,h as a,i as g,j as d}from"./chunk-6VNDP3UB.js";import{a as T}from"./chunk-OGQ6OQDN.js";var z=5e3;function G(e){return typeof e=="string"&&/^[\w+-][\w.+-]*$/.test(e)}function x(e){return e==null}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e){return M(e)&&G(e.prefix)&&typeof e.foldBelowBp=="number"&&Number.isFinite(e.foldBelowBp)&&e.foldBelowBp>0}function P(e){let n;try{n=JSON.parse(e)}catch{return}if(!M(n)||n.schema!==1)return;let{reference:i,tier:t,index:r,contig:o,bubbles:s,alleles:f}=n;if((x(i)||typeof i=="string"&&i.trim()!=="")&&(x(t)||L(t))&&[r,o,s,f].every(I=>x(I)||G(I)))return{...typeof i=="string"?{reference:i.trim()}:{},...L(t)?{tier:{prefix:t.prefix,foldBelowBp:t.foldBelowBp}}:{}}}function y(e,n){return d(e,i=>i.replace(/[^/\\]*$/,n))}function R(e){let n=a(e);return[p,l].find(i=>n.endsWith(i))}function N(e){return g(e)&&R(e)!==void 0}function F(e,n){let i=R(e)??p;return d(e,t=>`${t.slice(0,-i.length)}${n}`)}function _(e){return N(e)?F(e,".graph.json"):void 0}async function X(e,n){let i=_(e);if(i)try{let t=await T(i,n).readFile({encoding:"utf8",signal:AbortSignal.timeout(z)});return P(t)}catch{return}}var J={RgfaTabixAdapter:"Indexed GFA (gfa-to-tabix .segs.bed.gz or .graph.bed.gz)",RgfaTabixWalks:"Haplotype walks (.walks.bed.gz)",GbzBaseSyntenyAdapter:"GBZ database (.gbz.db)",MinigraphBubbleAdapter:"Minigraph bubbles (tabix BED)"},K={RgfaTabixAdapter:"Path to segments BED (.segs.bed.gz from gfa-to-tabix; the .links.bed.gz, its index and any .graph.json are read beside it), or format 2's .graph.bed.gz",RgfaTabixWalks:"Path to a walk file (<prefix>.<sample>.walks.bed.gz from gfa-to-tabix --walks, for the sample this assembly is)",GbzBaseSyntenyAdapter:"Path to the .gbz.db written by gbz-base construct",MinigraphBubbleAdapter:"Path to bubbles BED (.bed.gz from gfatools bubble)"},B="Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)",Z={RgfaTabixAdapter:B,RgfaTabixWalks:B,GbzBaseSyntenyAdapter:"Path to the haplotype index (optional; graph.haplotype-index.db beside the database is assumed)",MinigraphBubbleAdapter:B};function b(e,n){return d(e,i=>i+n)}function C(e){if(!a(e).endsWith(p))throw new Error(`Expected a segments BED ending in ${p}, got ${a(e)}`);return F(e,".links.bed.gz")}function u(e,n){return n?{location:n,indexType:m(a(n),"CSI","TBI")}:{location:b(e,".tbi"),indexType:"TBI"}}function k(e,n){return n!==void 0&&m(a(n),"CSI","TBI")==="CSI"?{location:b(e,".csi"),indexType:"CSI"}:{location:b(e,".tbi"),indexType:"TBI"}}function w(e,n){let i=n.trim();return i&&e?{assemblyNameToPanSN:{[e]:i}}:{}}function E(e,n,i){if(!i)return{};let t=y(e,`${i.prefix}${p}`),r=y(e,`${i.prefix}.links.bed.gz`);return{coarse:{foldBelowBp:i.foldBelowBp,segmentsLocation:t,segmentsIndex:k(t,n),linksLocation:r,linksIndex:k(r,n)}}}function S(e,n,i){let t=i===e?void 0:i;return w(e,n.trim()||t||"")}function W(e){return e?{readsLocation:e,...a(e).endsWith(".gz")&&g(e)?{readsIndex:{location:b(e,".tbi")}}:{}}:{}}function q(e){return e.split(/[\s,]+/).filter(n=>n!=="")}function D({choice:e,loc:n,indexLoc:i,readsLoc:t,manifest:r,assembly:o,sample:s,haplotypes:f=[]}){if(e==="RgfaTabixWalks"){if(!a(n).endsWith(h))throw new Error(`Expected a walk file ending in ${h}, got ${a(n)}`);return{type:"RgfaTabixAdapter",walksLocation:n,walksIndex:u(n,i),...S(o,s,A(n)),...f.length>0?{defaultHaplotypes:f}:{}}}if(e==="GbzBaseSyntenyAdapter")return{type:"GbzBaseSyntenyAdapter",gbzDbLocation:n,...i?{haplotypeIndexLocation:i}:{},...W(t),...w(o,s)};if(e==="MinigraphBubbleAdapter")return{type:"MinigraphBubbleAdapter",bubblesLocation:n,index:u(n,i),...w(o,s)};if(a(n).endsWith(l))return{type:"RgfaTabixAdapter",graphLocation:n,graphIndex:u(n,i),...S(o,s,r?.reference),...E(n,i,r?.tier)};let c=C(n);return{type:"RgfaTabixAdapter",segmentsLocation:n,segmentsIndex:u(n,i),linksLocation:c,linksIndex:k(c,i),...S(o,s,r?.reference),...E(n,i,r?.tier)}}function Q(e){let{choice:n,assembly:i,trackId:t,name:r}=e;return{type:n==="MinigraphBubbleAdapter"?"FeatureTrack":"GraphTrack",trackId:t,name:r,assemblyNames:[i],adapter:D(e),...n==="RgfaTabixAdapter"||n==="RgfaTabixWalks"?{displayDefaults:{labels:{name:{show:!1},description:{show:!1}}}}:{}}}export{N as a,X as b,J as c,K as d,Z as e,q as f,D as g,Q as h};
|
|
2
|
+
//# sourceMappingURL=chunk-5FNGR33G.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/GraphAddTrackWorkflow/graphManifest.ts", "../../src/GraphAddTrackWorkflow/buildTrackConfig.ts"],
|
|
4
|
+
"sourcesContent": ["import { openLocation } from '@jbrowse/core/util/io'\n\nimport {\n GRAPH_SUFFIX,\n SEGMENTS_SUFFIX,\n locationName,\n readsSiblings,\n renamed,\n} from '../locationName'\n\nimport type PluginManager from '@jbrowse/core/PluginManager'\nimport type { FileLocation } from '@jbrowse/core/util'\n\n// The part of `<prefix>.graph.json`, written by `gfa-to-tabix build`, that\n// Open track reads\nexport interface GraphManifest {\n reference?: string\n tier?: { prefix: string; foldBelowBp: number }\n}\n\nconst FETCH_TIMEOUT_MS = 5000\n\n// A bare file name beside the manifest: no directory, scheme or leading dot\nfunction isSiblingName(name: unknown): name is string {\n return typeof name === 'string' && /^[\\w+-][\\w.+-]*$/.test(name)\n}\n\nfunction isAbsent(value: unknown) {\n return value === undefined || value === null\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isTier(tier: unknown): tier is NonNullable<GraphManifest['tier']> {\n return (\n isPlainRecord(tier) &&\n isSiblingName(tier.prefix) &&\n typeof tier.foldBelowBp === 'number' &&\n Number.isFinite(tier.foldBelowBp) &&\n tier.foldBelowBp > 0\n )\n}\n\nexport function parseGraphManifest(text: string): GraphManifest | undefined {\n let json: unknown\n try {\n json = JSON.parse(text)\n } catch {\n return undefined\n }\n if (!isPlainRecord(json) || json.schema !== 1) {\n return undefined\n }\n const { reference, tier, index, contig, bubbles, alleles } = json\n const valid =\n (isAbsent(reference) ||\n (typeof reference === 'string' && reference.trim() !== '')) &&\n (isAbsent(tier) || isTier(tier)) &&\n [index, contig, bubbles, alleles].every(\n f => isAbsent(f) || isSiblingName(f),\n )\n if (!valid) {\n return undefined\n }\n return {\n ...(typeof reference === 'string' ? { reference: reference.trim() } : {}),\n ...(isTier(tier)\n ? { tier: { prefix: tier.prefix, foldBelowBp: tier.foldBelowBp } }\n : {}),\n }\n}\n\n// A file the manifest names, in the directory of the segments file opened\nexport function besideSegments(segs: FileLocation, fileName: string) {\n return renamed(segs, name => name.replace(/[^/\\\\]*$/, fileName))\n}\n\n// The suffix of a gfa-to-tabix index file: format 1's segments BED or format\n// 2's graph BED\nfunction indexSuffix(loc: FileLocation) {\n const name = locationName(loc)\n return [SEGMENTS_SUFFIX, GRAPH_SUFFIX].find(suffix => name.endsWith(suffix))\n}\n\n// A segments BED, or format 2's graph BED, the rest of the index and the\n// manifest can be found beside\nexport function isGraphIndexLocation(loc: FileLocation) {\n return readsSiblings(loc) && indexSuffix(loc) !== undefined\n}\n\n// `<prefix><suffix>` beside `<prefix>.segs.bed.gz` or `<prefix>.graph.bed.gz`\nexport function segmentsSibling(segs: FileLocation, suffix: string) {\n const own = indexSuffix(segs) ?? SEGMENTS_SUFFIX\n return renamed(segs, name => `${name.slice(0, -own.length)}${suffix}`)\n}\n\nexport function manifestLocation(segs: FileLocation) {\n return isGraphIndexLocation(segs)\n ? segmentsSibling(segs, '.graph.json')\n : undefined\n}\n\n// Undefined for a manifest that is missing, unreadable or not schema 1, so\n// Open track falls back to the files beside the segments alone\nexport async function readGraphManifest(\n segs: FileLocation,\n pluginManager?: PluginManager,\n) {\n const loc = manifestLocation(segs)\n if (!loc) {\n return undefined\n }\n try {\n const text = await openLocation(loc, pluginManager).readFile({\n encoding: 'utf8',\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n })\n return parseGraphManifest(text)\n } catch {\n return undefined\n }\n}\n", "import { makeIndexType } from '@jbrowse/core/util/tracks'\n\nimport { besideSegments, segmentsSibling } from './graphManifest'\nimport {\n GRAPH_SUFFIX,\n SEGMENTS_SUFFIX,\n WALKS_SUFFIX,\n locationName,\n readsSiblings,\n renamed,\n walkFileSample,\n} from '../locationName'\n\nimport type { GraphManifest } from './graphManifest'\nimport type { FileLocation } from '@jbrowse/core/util'\n\n// 'RgfaTabixWalks' is an RgfaTabixAdapter read from a walk file\nexport type GraphFileChoice =\n | 'RgfaTabixAdapter'\n | 'RgfaTabixWalks'\n | 'GbzBaseSyntenyAdapter'\n | 'MinigraphBubbleAdapter'\n\nexport const GRAPH_FILE_LABELS: Record<GraphFileChoice, string> = {\n RgfaTabixAdapter: 'Indexed GFA (gfa-to-tabix .segs.bed.gz or .graph.bed.gz)',\n RgfaTabixWalks: 'Haplotype walks (.walks.bed.gz)',\n GbzBaseSyntenyAdapter: 'GBZ database (.gbz.db)',\n MinigraphBubbleAdapter: 'Minigraph bubbles (tabix BED)',\n}\n\nexport const GRAPH_FILE_FIELDS: Record<GraphFileChoice, string> = {\n RgfaTabixAdapter:\n \"Path to segments BED (.segs.bed.gz from gfa-to-tabix; the .links.bed.gz, its index and any .graph.json are read beside it), or format 2's .graph.bed.gz\",\n RgfaTabixWalks:\n 'Path to a walk file (<prefix>.<sample>.walks.bed.gz from gfa-to-tabix --walks, for the sample this assembly is)',\n GbzBaseSyntenyAdapter: 'Path to the .gbz.db written by gbz-base construct',\n MinigraphBubbleAdapter: 'Path to bubbles BED (.bed.gz from gfatools bubble)',\n}\n\nconst TABIX_INDEX_FIELD =\n 'Path to tabix index (optional; the sibling .tbi is assumed, a .csi is recognised by name)'\n\nexport const GRAPH_INDEX_FIELDS: Record<GraphFileChoice, string> = {\n RgfaTabixAdapter: TABIX_INDEX_FIELD,\n RgfaTabixWalks: TABIX_INDEX_FIELD,\n GbzBaseSyntenyAdapter:\n 'Path to the haplotype index (optional; graph.haplotype-index.db beside the database is assumed)',\n MinigraphBubbleAdapter: TABIX_INDEX_FIELD,\n}\n\nfunction sibling(loc: FileLocation, suffix: string) {\n return renamed(loc, name => name + suffix)\n}\n\nfunction linksLocation(loc: FileLocation) {\n if (!locationName(loc).endsWith(SEGMENTS_SUFFIX)) {\n throw new Error(\n `Expected a segments BED ending in ${SEGMENTS_SUFFIX}, got ${locationName(loc)}`,\n )\n }\n return segmentsSibling(loc, '.links.bed.gz')\n}\n\nfunction tabixIndex(loc: FileLocation, indexLoc: FileLocation | undefined) {\n return indexLoc\n ? {\n location: indexLoc,\n indexType: makeIndexType(locationName(indexLoc), 'CSI', 'TBI'),\n }\n : { location: sibling(loc, '.tbi'), indexType: 'TBI' }\n}\n\n// The links file's index is assumed beside it, of the kind the segments' is.\nfunction siblingIndex(loc: FileLocation, indexLoc: FileLocation | undefined) {\n const csi =\n indexLoc !== undefined &&\n makeIndexType(locationName(indexLoc), 'CSI', 'TBI') === 'CSI'\n return csi\n ? { location: sibling(loc, '.csi'), indexType: 'CSI' }\n : { location: sibling(loc, '.tbi'), indexType: 'TBI' }\n}\n\n// none for a guessed config, which knows no assembly yet; see withWalkReference\nfunction panSN(assembly: string, sample: string) {\n const name = sample.trim()\n return name && assembly ? { assemblyNameToPanSN: { [assembly]: name } } : {}\n}\n\nfunction coarseTier(\n loc: FileLocation,\n indexLoc: FileLocation | undefined,\n tier: GraphManifest['tier'],\n) {\n if (!tier) {\n return {}\n }\n const segs = besideSegments(loc, `${tier.prefix}${SEGMENTS_SUFFIX}`)\n const links = besideSegments(loc, `${tier.prefix}.links.bed.gz`)\n return {\n coarse: {\n foldBelowBp: tier.foldBelowBp,\n segmentsLocation: segs,\n segmentsIndex: siblingIndex(segs, indexLoc),\n linksLocation: links,\n linksIndex: siblingIndex(links, indexLoc),\n },\n }\n}\n\n// The user's sample wins; the reference the graph's files name (a manifest's,\n// or a walk file's own) stands in when blank\nfunction referencePanSN(\n assembly: string,\n sample: string,\n reference: string | undefined,\n) {\n const fromManifest = reference === assembly ? undefined : reference\n return panSN(assembly, sample.trim() || fromManifest || '')\n}\n\n// a bgzipped GAF is read by its tabix index, a plain one whole\nfunction readsConfig(readsLoc: FileLocation | undefined) {\n return readsLoc\n ? {\n readsLocation: readsLoc,\n ...(locationName(readsLoc).endsWith('.gz') && readsSiblings(readsLoc)\n ? { readsIndex: { location: sibling(readsLoc, '.tbi') } }\n : {}),\n }\n : {}\n}\n\n// Names typed as a list, by comma or space\nexport function parseHaplotypes(text: string) {\n return text.split(/[\\s,]+/).filter(name => name !== '')\n}\n\nexport function buildAdapterConfig({\n choice,\n loc,\n indexLoc,\n readsLoc,\n manifest,\n assembly,\n sample,\n haplotypes = [],\n}: {\n choice: GraphFileChoice\n loc: FileLocation\n indexLoc: FileLocation | undefined\n // a GBZ track's GAF reads, which no other choice takes\n readsLoc?: FileLocation\n // the `.graph.json` beside an rGFA segments file\n manifest?: GraphManifest\n assembly: string\n sample: string\n // a walk file's haplotypes to cut for until the user picks others\n haplotypes?: string[]\n}) {\n if (choice === 'RgfaTabixWalks') {\n if (!locationName(loc).endsWith(WALKS_SUFFIX)) {\n throw new Error(\n `Expected a walk file ending in ${WALKS_SUFFIX}, got ${locationName(loc)}`,\n )\n }\n return {\n type: 'RgfaTabixAdapter',\n walksLocation: loc,\n walksIndex: tabixIndex(loc, indexLoc),\n ...referencePanSN(assembly, sample, walkFileSample(loc)),\n ...(haplotypes.length > 0 ? { defaultHaplotypes: haplotypes } : {}),\n }\n }\n if (choice === 'GbzBaseSyntenyAdapter') {\n return {\n type: 'GbzBaseSyntenyAdapter',\n gbzDbLocation: loc,\n ...(indexLoc ? { haplotypeIndexLocation: indexLoc } : {}),\n ...readsConfig(readsLoc),\n ...panSN(assembly, sample),\n }\n }\n if (choice === 'MinigraphBubbleAdapter') {\n return {\n type: 'MinigraphBubbleAdapter',\n bubblesLocation: loc,\n index: tabixIndex(loc, indexLoc),\n ...panSN(assembly, sample),\n }\n }\n if (locationName(loc).endsWith(GRAPH_SUFFIX)) {\n return {\n type: 'RgfaTabixAdapter',\n graphLocation: loc,\n graphIndex: tabixIndex(loc, indexLoc),\n ...referencePanSN(assembly, sample, manifest?.reference),\n ...coarseTier(loc, indexLoc, manifest?.tier),\n }\n }\n const links = linksLocation(loc)\n return {\n type: 'RgfaTabixAdapter',\n segmentsLocation: loc,\n segmentsIndex: tabixIndex(loc, indexLoc),\n linksLocation: links,\n linksIndex: siblingIndex(links, indexLoc),\n ...referencePanSN(assembly, sample, manifest?.reference),\n ...coarseTier(loc, indexLoc, manifest?.tier),\n }\n}\n\nexport function buildTrackConfig(args: {\n choice: GraphFileChoice\n loc: FileLocation\n indexLoc: FileLocation | undefined\n readsLoc?: FileLocation\n manifest?: GraphManifest\n assembly: string\n sample: string\n haplotypes?: string[]\n trackId: string\n name: string\n}) {\n const { choice, assembly, trackId, name } = args\n return {\n type: choice === 'MinigraphBubbleAdapter' ? 'FeatureTrack' : 'GraphTrack',\n trackId,\n name,\n assemblyNames: [assembly],\n adapter: buildAdapterConfig(args),\n ...(choice === 'RgfaTabixAdapter' || choice === 'RgfaTabixWalks'\n ? {\n displayDefaults: {\n labels: { name: { show: false }, description: { show: false } },\n },\n }\n : {}),\n }\n}\n"],
|
|
5
|
+
"mappings": "kKAoBA,IAAMA,EAAmB,IAGzB,SAASC,EAAcC,EAA+B,CACpD,OAAO,OAAOA,GAAS,UAAY,mBAAmB,KAAKA,CAAI,CACjE,CAEA,SAASC,EAASC,EAAgB,CAChC,OAA8BA,GAAU,IAC1C,CAEA,SAASC,EAAcD,EAAkD,CACvE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAASE,EAAOC,EAA2D,CACzE,OACEF,EAAcE,CAAI,GAClBN,EAAcM,EAAK,MAAM,GACzB,OAAOA,EAAK,aAAgB,UAC5B,OAAO,SAASA,EAAK,WAAW,GAChCA,EAAK,YAAc,CAEvB,CAEO,SAASC,EAAmBC,EAAyC,CAC1E,IAAIC,EACJ,GAAI,CACFA,EAAO,KAAK,MAAMD,CAAI,CACxB,MAAQ,CACN,MACF,CACA,GAAI,CAACJ,EAAcK,CAAI,GAAKA,EAAK,SAAW,EAC1C,OAEF,GAAM,CAAE,UAAAC,EAAW,KAAAJ,EAAM,MAAAK,EAAO,OAAAC,EAAQ,QAAAC,EAAS,QAAAC,CAAQ,EAAIL,EAQ7D,IANGP,EAASQ,CAAS,GAChB,OAAOA,GAAc,UAAYA,EAAU,KAAK,IAAM,MACxDR,EAASI,CAAI,GAAKD,EAAOC,CAAI,IAC9B,CAACK,EAAOC,EAAQC,EAASC,CAAO,EAAE,MAChCC,GAAKb,EAASa,CAAC,GAAKf,EAAce,CAAC,CACrC,EAIF,MAAO,CACL,GAAI,OAAOL,GAAc,SAAW,CAAE,UAAWA,EAAU,KAAK,CAAE,EAAI,CAAC,EACvE,GAAIL,EAAOC,CAAI,EACX,CAAE,KAAM,CAAE,OAAQA,EAAK,OAAQ,YAAaA,EAAK,WAAY,CAAE,EAC/D,CAAC,CACP,CACF,CAGO,SAASU,EAAeC,EAAoBC,EAAkB,CACnE,OAAOC,EAAQF,EAAMhB,GAAQA,EAAK,QAAQ,WAAYiB,CAAQ,CAAC,CACjE,CAIA,SAASE,EAAYC,EAAmB,CACtC,IAAMpB,EAAOqB,EAAaD,CAAG,EAC7B,MAAO,CAACE,EAAiBC,CAAY,EAAE,KAAKC,GAAUxB,EAAK,SAASwB,CAAM,CAAC,CAC7E,CAIO,SAASC,EAAqBL,EAAmB,CACtD,OAAOM,EAAcN,CAAG,GAAKD,EAAYC,CAAG,IAAM,MACpD,CAGO,SAASO,EAAgBX,EAAoBQ,EAAgB,CAClE,IAAMI,EAAMT,EAAYH,CAAI,GAAKM,EACjC,OAAOJ,EAAQF,EAAMhB,GAAQ,GAAGA,EAAK,MAAM,EAAG,CAAC4B,EAAI,MAAM,CAAC,GAAGJ,CAAM,EAAE,CACvE,CAEO,SAASK,EAAiBb,EAAoB,CACnD,OAAOS,EAAqBT,CAAI,EAC5BW,EAAgBX,EAAM,aAAa,EACnC,MACN,CAIA,eAAsBc,EACpBd,EACAe,EACA,CACA,IAAMX,EAAMS,EAAiBb,CAAI,EACjC,GAAKI,EAGL,GAAI,CACF,IAAMb,EAAO,MAAMyB,EAAaZ,EAAKW,CAAa,EAAE,SAAS,CAC3D,SAAU,OACV,OAAQ,YAAY,QAAQjC,CAAgB,CAC9C,CAAC,EACD,OAAOQ,EAAmBC,CAAI,CAChC,MAAQ,CACN,MACF,CACF,CCpGO,IAAM0B,EAAqD,CAChE,iBAAkB,2DAClB,eAAgB,kCAChB,sBAAuB,yBACvB,uBAAwB,+BAC1B,EAEaC,EAAqD,CAChE,iBACE,0JACF,eACE,kHACF,sBAAuB,oDACvB,uBAAwB,oDAC1B,EAEMC,EACJ,4FAEWC,EAAsD,CACjE,iBAAkBD,EAClB,eAAgBA,EAChB,sBACE,kGACF,uBAAwBA,CAC1B,EAEA,SAASE,EAAQC,EAAmBC,EAAgB,CAClD,OAAOC,EAAQF,EAAKG,GAAQA,EAAOF,CAAM,CAC3C,CAEA,SAASG,EAAcJ,EAAmB,CACxC,GAAI,CAACK,EAAaL,CAAG,EAAE,SAASM,CAAe,EAC7C,MAAM,IAAI,MACR,qCAAqCA,CAAe,SAASD,EAAaL,CAAG,CAAC,EAChF,EAEF,OAAOO,EAAgBP,EAAK,eAAe,CAC7C,CAEA,SAASQ,EAAWR,EAAmBS,EAAoC,CACzE,OAAOA,EACH,CACE,SAAUA,EACV,UAAWC,EAAcL,EAAaI,CAAQ,EAAG,MAAO,KAAK,CAC/D,EACA,CAAE,SAAUV,EAAQC,EAAK,MAAM,EAAG,UAAW,KAAM,CACzD,CAGA,SAASW,EAAaX,EAAmBS,EAAoC,CAI3E,OAFEA,IAAa,QACbC,EAAcL,EAAaI,CAAQ,EAAG,MAAO,KAAK,IAAM,MAEtD,CAAE,SAAUV,EAAQC,EAAK,MAAM,EAAG,UAAW,KAAM,EACnD,CAAE,SAAUD,EAAQC,EAAK,MAAM,EAAG,UAAW,KAAM,CACzD,CAGA,SAASY,EAAMC,EAAkBC,EAAgB,CAC/C,IAAMX,EAAOW,EAAO,KAAK,EACzB,OAAOX,GAAQU,EAAW,CAAE,oBAAqB,CAAE,CAACA,CAAQ,EAAGV,CAAK,CAAE,EAAI,CAAC,CAC7E,CAEA,SAASY,EACPf,EACAS,EACAO,EACA,CACA,GAAI,CAACA,EACH,MAAO,CAAC,EAEV,IAAMC,EAAOC,EAAelB,EAAK,GAAGgB,EAAK,MAAM,GAAGV,CAAe,EAAE,EAC7Da,EAAQD,EAAelB,EAAK,GAAGgB,EAAK,MAAM,eAAe,EAC/D,MAAO,CACL,OAAQ,CACN,YAAaA,EAAK,YAClB,iBAAkBC,EAClB,cAAeN,EAAaM,EAAMR,CAAQ,EAC1C,cAAeU,EACf,WAAYR,EAAaQ,EAAOV,CAAQ,CAC1C,CACF,CACF,CAIA,SAASW,EACPP,EACAC,EACAO,EACA,CACA,IAAMC,EAAeD,IAAcR,EAAW,OAAYQ,EAC1D,OAAOT,EAAMC,EAAUC,EAAO,KAAK,GAAKQ,GAAgB,EAAE,CAC5D,CAGA,SAASC,EAAYC,EAAoC,CACvD,OAAOA,EACH,CACE,cAAeA,EACf,GAAInB,EAAamB,CAAQ,EAAE,SAAS,KAAK,GAAKC,EAAcD,CAAQ,EAChE,CAAE,WAAY,CAAE,SAAUzB,EAAQyB,EAAU,MAAM,CAAE,CAAE,EACtD,CAAC,CACP,EACA,CAAC,CACP,CAGO,SAASE,EAAgBC,EAAc,CAC5C,OAAOA,EAAK,MAAM,QAAQ,EAAE,OAAOxB,GAAQA,IAAS,EAAE,CACxD,CAEO,SAASyB,EAAmB,CACjC,OAAAC,EACA,IAAA7B,EACA,SAAAS,EACA,SAAAe,EACA,SAAAM,EACA,SAAAjB,EACA,OAAAC,EACA,WAAAiB,EAAa,CAAC,CAChB,EAYG,CACD,GAAIF,IAAW,iBAAkB,CAC/B,GAAI,CAACxB,EAAaL,CAAG,EAAE,SAASgC,CAAY,EAC1C,MAAM,IAAI,MACR,kCAAkCA,CAAY,SAAS3B,EAAaL,CAAG,CAAC,EAC1E,EAEF,MAAO,CACL,KAAM,mBACN,cAAeA,EACf,WAAYQ,EAAWR,EAAKS,CAAQ,EACpC,GAAGW,EAAeP,EAAUC,EAAQmB,EAAejC,CAAG,CAAC,EACvD,GAAI+B,EAAW,OAAS,EAAI,CAAE,kBAAmBA,CAAW,EAAI,CAAC,CACnE,CACF,CACA,GAAIF,IAAW,wBACb,MAAO,CACL,KAAM,wBACN,cAAe7B,EACf,GAAIS,EAAW,CAAE,uBAAwBA,CAAS,EAAI,CAAC,EACvD,GAAGc,EAAYC,CAAQ,EACvB,GAAGZ,EAAMC,EAAUC,CAAM,CAC3B,EAEF,GAAIe,IAAW,yBACb,MAAO,CACL,KAAM,yBACN,gBAAiB7B,EACjB,MAAOQ,EAAWR,EAAKS,CAAQ,EAC/B,GAAGG,EAAMC,EAAUC,CAAM,CAC3B,EAEF,GAAIT,EAAaL,CAAG,EAAE,SAASkC,CAAY,EACzC,MAAO,CACL,KAAM,mBACN,cAAelC,EACf,WAAYQ,EAAWR,EAAKS,CAAQ,EACpC,GAAGW,EAAeP,EAAUC,EAAQgB,GAAU,SAAS,EACvD,GAAGf,EAAWf,EAAKS,EAAUqB,GAAU,IAAI,CAC7C,EAEF,IAAMX,EAAQf,EAAcJ,CAAG,EAC/B,MAAO,CACL,KAAM,mBACN,iBAAkBA,EAClB,cAAeQ,EAAWR,EAAKS,CAAQ,EACvC,cAAeU,EACf,WAAYR,EAAaQ,EAAOV,CAAQ,EACxC,GAAGW,EAAeP,EAAUC,EAAQgB,GAAU,SAAS,EACvD,GAAGf,EAAWf,EAAKS,EAAUqB,GAAU,IAAI,CAC7C,CACF,CAEO,SAASK,EAAiBC,EAW9B,CACD,GAAM,CAAE,OAAAP,EAAQ,SAAAhB,EAAU,QAAAwB,EAAS,KAAAlC,CAAK,EAAIiC,EAC5C,MAAO,CACL,KAAMP,IAAW,yBAA2B,eAAiB,aAC7D,QAAAQ,EACA,KAAAlC,EACA,cAAe,CAACU,CAAQ,EACxB,QAASe,EAAmBQ,CAAI,EAChC,GAAIP,IAAW,oBAAsBA,IAAW,iBAC5C,CACE,gBAAiB,CACf,OAAQ,CAAE,KAAM,CAAE,KAAM,EAAM,EAAG,YAAa,CAAE,KAAM,EAAM,CAAE,CAChE,CACF,EACA,CAAC,CACP,CACF",
|
|
6
|
+
"names": ["FETCH_TIMEOUT_MS", "isSiblingName", "name", "isAbsent", "value", "isPlainRecord", "isTier", "tier", "parseGraphManifest", "text", "json", "reference", "index", "contig", "bubbles", "alleles", "f", "besideSegments", "segs", "fileName", "renamed", "indexSuffix", "loc", "locationName", "SEGMENTS_SUFFIX", "GRAPH_SUFFIX", "suffix", "isGraphIndexLocation", "readsSiblings", "segmentsSibling", "own", "manifestLocation", "readGraphManifest", "pluginManager", "openLocation", "GRAPH_FILE_LABELS", "GRAPH_FILE_FIELDS", "TABIX_INDEX_FIELD", "GRAPH_INDEX_FIELDS", "sibling", "loc", "suffix", "renamed", "name", "linksLocation", "locationName", "SEGMENTS_SUFFIX", "segmentsSibling", "tabixIndex", "indexLoc", "makeIndexType", "siblingIndex", "panSN", "assembly", "sample", "coarseTier", "tier", "segs", "besideSegments", "links", "referencePanSN", "reference", "fromManifest", "readsConfig", "readsLoc", "readsSiblings", "parseHaplotypes", "text", "buildAdapterConfig", "choice", "manifest", "haplotypes", "WALKS_SUFFIX", "walkFileSample", "GRAPH_SUFFIX", "buildTrackConfig", "args", "trackId"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var s=".segs.bed.gz",u=".graph.bed.gz",r=".walks.bed.gz";function l(e){let n=a(e).replace(/^.*[/\\]/,"");if(!n.endsWith(r))return;let t=n.slice(0,-r.length),i=t.lastIndexOf(".");return i===-1?void 0:t.slice(i+1)||void 0}function c(e){return!("uri"in e)||e.uri!==""}function p(e){return typeof e=="object"&&e!==null&&Object.entries(e).some(([n,t])=>["uri","localPath","blobId"].includes(n)&&typeof t=="string"&&t!=="")}function o(e){let n=e.search(/[?#]/);return n===-1?{name:e,query:""}:{name:e.slice(0,n),query:e.slice(n)}}function a(e){return"uri"in e?o(e.uri).name:"localPath"in e?e.localPath:e.name}function d(e){return"uri"in e||"localPath"in e}function f(e,n){if("uri"in e){let{name:t,query:i}=o(e.uri);return{...e,uri:n(t)+i}}else{if("localPath"in e)return{...e,localPath:n(e.localPath)};throw new Error(`${e.name} was picked in the browser, which reads no file beside it; open it by URL`)}}export{s as a,u as b,r as c,l as d,c as e,p as f,o as g,a as h,d as i,f as j};
|
|
2
|
+
//# sourceMappingURL=chunk-6VNDP3UB.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/locationName.ts"],
|
|
4
|
+
"sourcesContent": ["import type { FileLocation } from '@jbrowse/core/util'\n\nexport const SEGMENTS_SUFFIX = '.segs.bed.gz'\n// gfa-to-tabix's format 2: segments and links in one file\nexport const GRAPH_SUFFIX = '.graph.bed.gz'\nexport const WALKS_SUFFIX = '.walks.bed.gz'\n\n// The reference sample `gfa-to-tabix --walks` names a walk file after:\n// GRCh38 in `chr22.GRCh38.walks.bed.gz`\nexport function walkFileSample(loc: FileLocation) {\n const name = locationName(loc).replace(/^.*[/\\\\]/, '')\n if (!name.endsWith(WALKS_SUFFIX)) {\n return undefined\n }\n const prefix = name.slice(0, -WALKS_SUFFIX.length)\n const dot = prefix.lastIndexOf('.')\n return dot === -1 ? undefined : prefix.slice(dot + 1) || undefined\n}\n\n// A schema's unset file slot defaults to an empty uri\nexport function locationIsSet(loc: FileLocation) {\n return !('uri' in loc) || loc.uri !== ''\n}\n\n// Whether a location as a config snapshot writes it names a file\nexport function snapshotNamesFile(location: unknown) {\n return (\n typeof location === 'object' &&\n location !== null &&\n Object.entries(location).some(\n ([key, value]) =>\n ['uri', 'localPath', 'blobId'].includes(key) &&\n typeof value === 'string' &&\n value !== '',\n )\n )\n}\n\n// A url's query string (a presigned signature, a token) follows the file name\nexport function splitUri(uri: string) {\n const end = uri.search(/[?#]/)\n return end === -1\n ? { name: uri, query: '' }\n : { name: uri.slice(0, end), query: uri.slice(end) }\n}\n\nexport function locationName(loc: FileLocation) {\n return 'uri' in loc\n ? splitUri(loc.uri).name\n : 'localPath' in loc\n ? loc.localPath\n : loc.name\n}\n\n// A file picked in the browser comes without the directory it sat in\nexport function readsSiblings(loc: FileLocation) {\n return 'uri' in loc || 'localPath' in loc\n}\n\nexport function renamed(loc: FileLocation, rename: (name: string) => string) {\n if ('uri' in loc) {\n const { name, query } = splitUri(loc.uri)\n return { ...loc, uri: rename(name) + query }\n } else if ('localPath' in loc) {\n return { ...loc, localPath: rename(loc.localPath) }\n } else {\n throw new Error(\n `${loc.name} was picked in the browser, which reads no file beside it; open it by URL`,\n )\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEO,IAAMA,EAAkB,eAElBC,EAAe,gBACfC,EAAe,gBAIrB,SAASC,EAAeC,EAAmB,CAChD,IAAMC,EAAOC,EAAaF,CAAG,EAAE,QAAQ,WAAY,EAAE,EACrD,GAAI,CAACC,EAAK,SAASH,CAAY,EAC7B,OAEF,IAAMK,EAASF,EAAK,MAAM,EAAG,CAACH,EAAa,MAAM,EAC3CM,EAAMD,EAAO,YAAY,GAAG,EAClC,OAAOC,IAAQ,GAAK,OAAYD,EAAO,MAAMC,EAAM,CAAC,GAAK,MAC3D,CAGO,SAASC,EAAcL,EAAmB,CAC/C,MAAO,EAAE,QAASA,IAAQA,EAAI,MAAQ,EACxC,CAGO,SAASM,EAAkBC,EAAmB,CACnD,OACE,OAAOA,GAAa,UACpBA,IAAa,MACb,OAAO,QAAQA,CAAQ,EAAE,KACvB,CAAC,CAACC,EAAKC,CAAK,IACV,CAAC,MAAO,YAAa,QAAQ,EAAE,SAASD,CAAG,GAC3C,OAAOC,GAAU,UACjBA,IAAU,EACd,CAEJ,CAGO,SAASC,EAASC,EAAa,CACpC,IAAMC,EAAMD,EAAI,OAAO,MAAM,EAC7B,OAAOC,IAAQ,GACX,CAAE,KAAMD,EAAK,MAAO,EAAG,EACvB,CAAE,KAAMA,EAAI,MAAM,EAAGC,CAAG,EAAG,MAAOD,EAAI,MAAMC,CAAG,CAAE,CACvD,CAEO,SAASV,EAAaF,EAAmB,CAC9C,MAAO,QAASA,EACZU,EAASV,EAAI,GAAG,EAAE,KAClB,cAAeA,EACbA,EAAI,UACJA,EAAI,IACZ,CAGO,SAASa,EAAcb,EAAmB,CAC/C,MAAO,QAASA,GAAO,cAAeA,CACxC,CAEO,SAASc,EAAQd,EAAmBe,EAAkC,CAC3E,GAAI,QAASf,EAAK,CAChB,GAAM,CAAE,KAAAC,EAAM,MAAAe,CAAM,EAAIN,EAASV,EAAI,GAAG,EACxC,MAAO,CAAE,GAAGA,EAAK,IAAKe,EAAOd,CAAI,EAAIe,CAAM,CAC7C,KAAO,IAAI,cAAehB,EACxB,MAAO,CAAE,GAAGA,EAAK,UAAWe,EAAOf,EAAI,SAAS,CAAE,EAElD,MAAM,IAAI,MACR,GAAGA,EAAI,IAAI,2EACb,EAEJ",
|
|
6
|
+
"names": ["SEGMENTS_SUFFIX", "GRAPH_SUFFIX", "WALKS_SUFFIX", "walkFileSample", "loc", "name", "locationName", "prefix", "dot", "locationIsSet", "snapshotNamesFile", "location", "key", "value", "splitUri", "uri", "end", "readsSiblings", "renamed", "rename", "query"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function o(t){return t===void 0||t==="*"?void 0:t}function s(t){let e=t.split(" ");return{refName:e[0],start:+e[1],end:+e[2],segmentCount:+e[3],pathCount:+e[4],inversion:e[5]==="1",shortestAlleleLength:+e[6],longestAlleleLength:+e[7],segments:e[11],shortestAllele:o(e[12]),longestAllele:o(e[13])}}function u(t,e){return t.key!==void 0||e.key!==void 0?t.key===e.key:t.refName===e.refName&&t.start===e.start&&t.end===e.end}function i(t){return t.key??`${t.refName}:${t.start}-${t.end}`}function b(t){let{shortestAlleleLength:e,longestAlleleLength:n}=t;return e===n?`${n.toLocaleString()} bp`:`${e.toLocaleString()}-${n.toLocaleString()} bp`}var r=2147483647;function a(t){let{pathCount:e,segmentCount:n,inversion:l}=t;return[`${n} segments`,e===r?"more paths than gfatools counts":`up to ${e.toLocaleString()} paths`,...l?["inversion"]:[]].join(", ")}export{s as a,u as b,i as c,b as d,r as e,a as f};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-BJHWGRMP.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../node_modules/.pnpm/@jbrowse+bandage-core@12.
|
|
3
|
+
"sources": ["../../node_modules/.pnpm/@jbrowse+bandage-core@12.1.1/node_modules/@jbrowse/bandage-core/dist/chunks/chunk-FX4RDMDN.js"],
|
|
4
4
|
"sourcesContent": ["// src/bubbles/bubbleLine.ts\nfunction sequence(field) {\n return field === void 0 || field === \"*\" ? void 0 : field;\n}\nfunction parseBubbleLine(line) {\n const cols = line.split(\"\t\");\n return {\n refName: cols[0],\n start: +cols[1],\n end: +cols[2],\n segmentCount: +cols[3],\n pathCount: +cols[4],\n inversion: cols[5] === \"1\",\n shortestAlleleLength: +cols[6],\n longestAlleleLength: +cols[7],\n segments: cols[11],\n shortestAllele: sequence(cols[12]),\n longestAllele: sequence(cols[13])\n };\n}\nfunction sameBubble(a, b) {\n return a.key !== void 0 || b.key !== void 0 ? a.key === b.key : a.refName === b.refName && a.start === b.start && a.end === b.end;\n}\nfunction bubbleKey(b) {\n return b.key ?? `${b.refName}:${b.start}-${b.end}`;\n}\nfunction bubbleLabel(bubble) {\n const { shortestAlleleLength: min, longestAlleleLength: max } = bubble;\n return min === max ? `${max.toLocaleString()} bp` : `${min.toLocaleString()}-${max.toLocaleString()} bp`;\n}\nvar SATURATED_PATH_COUNT = 2147483647;\nfunction bubbleDescription(bubble) {\n const { pathCount, segmentCount, inversion } = bubble;\n return [\n `${segmentCount} segments`,\n pathCount === SATURATED_PATH_COUNT ? \"more paths than gfatools counts\" : `up to ${pathCount.toLocaleString()} paths`,\n ...inversion ? [\"inversion\"] : []\n ].join(\", \");\n}\n\nexport {\n parseBubbleLine,\n sameBubble,\n bubbleKey,\n bubbleLabel,\n SATURATED_PATH_COUNT,\n bubbleDescription\n};\n"],
|
|
5
5
|
"mappings": "AACA,SAASA,EAASC,EAAO,CACvB,OAAOA,IAAU,QAAUA,IAAU,IAAM,OAASA,CACtD,CACA,SAASC,EAAgBC,EAAM,CAC7B,IAAMC,EAAOD,EAAK,MAAM,GAAG,EAC3B,MAAO,CACL,QAASC,EAAK,CAAC,EACf,MAAO,CAACA,EAAK,CAAC,EACd,IAAK,CAACA,EAAK,CAAC,EACZ,aAAc,CAACA,EAAK,CAAC,EACrB,UAAW,CAACA,EAAK,CAAC,EAClB,UAAWA,EAAK,CAAC,IAAM,IACvB,qBAAsB,CAACA,EAAK,CAAC,EAC7B,oBAAqB,CAACA,EAAK,CAAC,EAC5B,SAAUA,EAAK,EAAE,EACjB,eAAgBJ,EAASI,EAAK,EAAE,CAAC,EACjC,cAAeJ,EAASI,EAAK,EAAE,CAAC,CAClC,CACF,CACA,SAASC,EAAWC,EAAGC,EAAG,CACxB,OAAOD,EAAE,MAAQ,QAAUC,EAAE,MAAQ,OAASD,EAAE,MAAQC,EAAE,IAAMD,EAAE,UAAYC,EAAE,SAAWD,EAAE,QAAUC,EAAE,OAASD,EAAE,MAAQC,EAAE,GAChI,CACA,SAASC,EAAUD,EAAG,CACpB,OAAOA,EAAE,KAAO,GAAGA,EAAE,OAAO,IAAIA,EAAE,KAAK,IAAIA,EAAE,GAAG,EAClD,CACA,SAASE,EAAYC,EAAQ,CAC3B,GAAM,CAAE,qBAAsBC,EAAK,oBAAqBC,CAAI,EAAIF,EAChE,OAAOC,IAAQC,EAAM,GAAGA,EAAI,eAAe,CAAC,MAAQ,GAAGD,EAAI,eAAe,CAAC,IAAIC,EAAI,eAAe,CAAC,KACrG,CACA,IAAIC,EAAuB,WAC3B,SAASC,EAAkBJ,EAAQ,CACjC,GAAM,CAAE,UAAAK,EAAW,aAAAC,EAAc,UAAAC,CAAU,EAAIP,EAC/C,MAAO,CACL,GAAGM,CAAY,YACfD,IAAcF,EAAuB,kCAAoC,SAASE,EAAU,eAAe,CAAC,SAC5G,GAAGE,EAAY,CAAC,WAAW,EAAI,CAAC,CAClC,EAAE,KAAK,IAAI,CACb",
|
|
6
6
|
"names": ["sequence", "field", "parseBubbleLine", "line", "cols", "sameBubble", "a", "b", "bubbleKey", "bubbleLabel", "bubble", "min", "max", "SATURATED_PATH_COUNT", "bubbleDescription", "pathCount", "segmentCount", "inversion"]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j as zt,k as He,l as Oe,m as Pe,n as Dt,o as jt,p as Ut,q as Wt,r as Vt}from"./chunk-M2D7NUOY.js";import{a as _t,g as Tt}from"./chunk-FY7X6253.js";import{c as Ot}from"./chunk-JMRW3IGK.js";import{a as Ct,g as Bt}from"./chunk-5RHNR3TH.js";var Ln=4096;function pt(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ln?n[1]=t:e.push([t,t])}return e}var Hn=32768,Gt={mostChosenPaths:32},lt=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)}},re=class extends Error{};function Ve(a,e,t,n){return a==="forward"?e+t:e-n}function Qt(a,e,t,n){return a==="forward"?e-n:e+t}function Kt(a){return Pe(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function Ce(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Zt(a){let{db:e,records:t,signal:n}=a,s=performance.now(),o=()=>{let w=performance.now(),S=w-s;return s=w,S},r={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(w,S)=>{let A=`${w}: ${S}`;r.walks[A]=(r.walks[A]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let S=t.get(w)??c.get(w);if(S)return S;let A=await e.getRecord(w);if(r.graphFetches+=1,!A)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,A),A},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let S=p.get(w);return S!==void 0&&a.keep(S.name)},g=[],l=new lt,b=new Map,x=new Set,P=new Set,E=async w=>{let S=(await d(w.node)).gbwt().lf(w.offset);return S===void 0||S.node===0?void 0:S},R=async(w,S)=>{let A=(await d(ee(w.node))).gbwt().predecessorAt(w.offset);if(A===void 0||S!==void 0&&!S.has(A))return;let M=(await d(A)).gbwt().offsetTo(w);if(M===void 0)throw new Error(`No offset in ${A} leads to ${w.node}:${w.offset}`);return{node:A,offset:M}},m=(w,S,A,M)=>{let B=A.map(W=>W.pos.node),U=A.map(W=>W.pos.offset),J=0;for(let W of B)J+=f(W);let O=S==="forward"?A[0].left:A[A.length-1].left,L=g.length;g.push({pathHandle:w,orientation:S,handles:B,offsets:U,len:J,hapStart:O,hapEnd:O+J,canonical:Pe(B[0],B[B.length-1]),source:M});for(let W of A)l.set(W.pos,L);let G=b.get(w);return G?G.push(L):b.set(w,[L]),L},I=async(w,S,A,M)=>{let B=[],U=w;for(;;){n?.throwIfAborted();let O=await R(U.pos,t);if(!O)break;U={pos:O,left:Qt(A,U.left,f(U.pos.node),f(O.node))},B.push(U)}B.reverse();let J=[w];for(U=w;;){n?.throwIfAborted();let O=await E(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:Ve(A,U.left,f(U.pos.node),f(O.node))},J.push(U)}return m(S,A,[...B,...J],M)},$=async(w,S,A,M)=>g[l.get(w.pos)??await I(w,S,A,M)],F=w=>{let S=w.handles[w.handles.length-1];return{pos:{node:S,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(S):w.hapStart}},_=w=>{let S=w.handles[0];return{pos:{node:S,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(S)}},D=await I({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),C=g[D],H=()=>{if(r.fallback!==void 0)return{reference:C,pieces:[],stats:r};let w=new Map;g.forEach((A,M)=>{M!==D&&w.set(Ce(A),[...w.get(Ce(A))??[],A])});let S=[];for(let A of w.values()){let M=new Set;for(let B of A)B.canonical&&!M.has(B.orientation)&&(M.add(B.orientation),S.push(B),r.sources[B.source]+=1)}return r.sources.reference=1,r.pieces=S.length+1,{reference:C,pieces:S,stats:r}},k=async(w,S)=>{let A=S?x:P,M=S?P:x,B=w;for(;;){if(A.has(B))return;A.add(B);let U=g[B],J=S?F(U):_(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let G=S?await E(J.pos):await R(J.pos);if(!G){L="endmarker";break}let W=(await d(J.pos.node)).sequenceLen,ue=(await d(G.node)).sequenceLen,se=S?Ve(U.orientation,J.left,W,ue):Qt(U.orientation,J.left,W,ue);if(t.has(G.node)){let Y=l.get(G);Y===void 0?(B=await I({pos:G,left:se},U.pathHandle,U.orientation,"chain"),M.add(B),L="landed"):(M.add(Y),L="merge")}else O>Hn?L="bound":(O+=ue,J={pos:G,left:se})}if(i("chain",L),L!=="landed")return}},j=async w=>{if(a.context>w.context)throw new re(`the context of ${a.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let S=r.spacing;if(S===void 0)throw new re("the haplotype index has no anchors");let{bin:A,bound:M}=w,{fills:B,inserted:U}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new re("the haplotype index's stray rows cover contained snarls only");for(let u of B){if(u.inserted>0&&u.low===u.high)throw new re(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new re(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(a.window.start/A),O=Math.floor((a.window.end-1)/A),L=J*A,G=(O+1)*A,W=new Map,ue=async(u,v)=>{let z=await e.haplotypeAnchorsBetween(a.referenceHandle,u*S,v*S);for(let T of z)W.set(T.anchorOffset/S,T)},se=Math.max(0,Math.floor((L-M)/S)-1),Y=Math.ceil((G+M)/S)+1,[{listed:De,strays:ae}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,J,O),ue(se,Y)]);for(let u of t.keys()){let v=N(u);if(!Q(u)&&!De(v)&&!U.has(v))throw new re(`the haplotype index lists node ${v} of the subgraph in no bin that the window touches`)}r.scans=pt([...t.keys()].sort((u,v)=>u-v));let ie=Promise.all(r.scans.map(([u,v])=>e.haplotypeSamplesInRange(u,v)));for(ie.catch(()=>{});se>0&&(W.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=L-M;)se-=1,await ue(se,se);for(;W.has(Y)&&W.get(Y).pathOffset<=G+M;)Y+=1,await ue(Y,Y);let pe=[...W.keys()].sort((u,v)=>u-v),ye=W.get(pe[0]??-1);if(!ye)throw new re("the haplotype index has no anchors on this path");let he=u=>W.get(u).pathOffset,Ne=new Map;for(let u of pe){let v=N(W.get(u).node);Ne.set(v,[...Ne.get(v)??[],u])}let ct=[...Ne.keys()],Et=ct.map(u=>W.get(Ne.get(u)[0]).visits);if(!Et[ct.indexOf(N(ye.node))].some(u=>u.pathHandle===a.referenceHandle&&u.orientation==="forward"&&u.pathOffset===ye.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${ye.pathOffset} (node ${N(ye.node)}); it does not match this graph`);let kt=pe.filter(u=>he(u)<=a.window.start),$n=pe.filter(u=>he(u)>=a.window.end);r.anchors=[he(kt[kt.length-1]??pe[0]),he($n[0]??pe[pe.length-1])],r.anchorsRead=pe.length;let dt=new Map,vt=new Set;if(ct.forEach((u,v)=>{let z=Ne.get(u),T=z.length===1?z[0]:void 0;for(let q of Et[v])vt.add(q.pathHandle),q.orientation==="forward"&&y(q.pathHandle)&&dt.set(q.pathHandle,[...dt.get(q.pathHandle)??[],{k:T,row:q}])}),r.chosenPaths=[...vt].filter(y).length,r.chosenPaths>Gt.mostChosenPaths)throw new re(`${r.chosenPaths} chosen paths pass the anchors, more than ${Gt.mostChosenPaths}`);let je=[],Ie=Number.POSITIVE_INFINITY,be=0;for(let[u,v]of dt){v.sort((z,T)=>z.row.pathOffset-T.row.pathOffset);for(let z=0;z+1<v.length;z++){let T=v[z],q=v[z+1];if(T.k===void 0||q.k===void 0||Math.abs(T.k-q.k)!==1)continue;let[Z,te]=he(T.k)<=he(q.k)?[T,q]:[q,T],ne=he(Z.k),oe=he(te.k);ne<G&&oe>=L?(je.push({pathHandle:u,from:T.row,to:q.row}),Ie=Math.min(Ie,ne-M),be=Math.max(be,oe+M)):ne>=G&&ne-G<=M?(je.push({pathHandle:u,from:Z.row,to:void 0}),Ie=Math.min(Ie,ne-M),be=Math.max(be,ne+M)):oe<L&&L-oe<=M&&(je.push({pathHandle:u,from:te.row,to:void 0}),Ie=Math.min(Ie,oe-M),be=Math.max(be,oe+M))}}let Rn=new Set(B.map(u=>`${u.low}:${u.high}`)),Nn=ae.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Rn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,v)=>u.pathHandle-v.pathHandle||u.pathStart-v.pathStart);r.strays={bins:O-J+1,rows:ae.length,walked:0,outsideBp:0},be>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ie),be+1),r.ms.scan=o();let Pt=8*S+2*(a.window.end-a.window.start),At=r.strays,Me=0,$t=u=>{if(At.outsideBp+=u,Me+=u,Me>Pt)throw new re(`a walk of a chosen path near the window went past its cap of ${Pt} bp`)},ft=new Map,Rt=(u,v,z)=>(ft.get(u)??[]).some(([T,q])=>T<=v&&z<q),Nt=(u,v,z)=>{ft.set(u,[...ft.get(u)??[],[v,z]])},Mt=async(u,v,z,T,q)=>{let Z=v,te=z,ne=te;for(;Z&&te<=T;){n?.throwIfAborted();let oe;if(t.has(Z.node)){let Le=await $({pos:Z,left:te},u,"forward",q),Ht=F(Le);Z=Ht.pos,te=Ht.left,oe=f(Z.node),ne=Math.max(ne,Le.hapEnd)}else oe=(await d(Z.node)).sequenceLen,$t(oe),ne=Math.max(ne,te+oe);Z=await E(Z),te+=oe}return ne},Mn=async(u,v,z,T)=>{let q={pos:v,left:z},Z=z;for(;q.left>T;){n?.throwIfAborted();let te=await R(q.pos);if(!te)break;let ne=(await d(te.node)).sequenceLen,oe=q.left-ne;if(t.has(te.node)){let Le=await $({pos:te,left:oe},u,"forward","section");q=_(Le),Z=Math.min(Z,Le.hapStart)}else $t(ne),q={pos:te,left:oe},Z=Math.min(Z,oe)}return Z};for(let{pathHandle:u,from:v,to:z}of je){let T=v.pathOffset,q=(z??v).pathOffset+M;if(Rt(u,T-M,q))continue;let Z={node:v.node,offset:v.offset};Me=0;let te=await Mt(u,Z,T,q,"section");Me=0;let ne=await Mn(u,Z,T,T-M);Nt(u,Math.min(ne,T-M),Math.max(te,q+1)),i(z?"section":"visit",z?"past the far anchor":"bound")}for(let u of Nn){if(Rt(u.pathHandle,u.pathStart,u.pathEnd))continue;Me=0;let v=await Mt(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");Nt(u.pathHandle,u.pathStart,Math.max(v,u.pathEnd+1)),At.walked+=1}r.ms.walks=o();let Lt=[];for(let u of await ie)for(let v of u)if(r.scanRows+=1,t.has(v.node)&&y(v.pathHandle)){if(!(b.get(v.pathHandle)??[]).some(z=>{let T=g[z];return T.hapStart<=v.pathOffset&&v.pathOffset<T.hapEnd}))throw new re(`chosen path ${v.pathHandle} has a sample at ${v.pathOffset} on the window's nodes that no walk reached`);v.orientation==="reverse"&&Lt.push(v)}for(let u of Lt)await $({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");r.ms.check=o()},X=async()=>{let w=new Map,S=O=>{let L=Ce(O),G=w.get(L);G?G.add(O.orientation):w.set(L,new Set([O.orientation]))},A=0,M=()=>{for(;A<g.length;A++)S(g[A])};M();let B=O=>(w.get(Ce(O))?.size??0)>1,U=2*h,J=(O,L)=>L===D?y(a.referenceHandle)&&Kt(O):!O.canonical||Kt(O);for(let O=0;O<g.length;O++){let L=g[O];if(B(L)||!J(L,O))continue;r.twins.tried+=1;let G=L.orientation==="forward"?"reverse":"forward",W=F(L),ue=0,se;for(;!se&&ue<=U;){n?.throwIfAborted();let ae=await E(W.pos);if(!ae)break;let ie=(await d(ae.node)).sequenceLen,pe=Ve(L.orientation,W.left,(await d(W.pos.node)).sequenceLen,ie),ye=ee(ae.node);se=(await e.haplotypeSamplesInRange(ye,ye)).find(he=>he.pathHandle===L.pathHandle&&he.orientation===G&&he.pathOffset===pe),ue+=ie,W={pos:ae,left:pe}}let Y=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},De=0;for(;Y&&!B(L)&&De<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ae=await $(Y,L.pathHandle,G,"twin"),ie=g.indexOf(ae);await k(ie,!0),await k(ie,!1),M(),Y=F(ae)}if(!B(L)){let ae=(await d(Y.pos.node)).sequenceLen;De+=ae;let ie=await E(Y.pos);Y=ie?{pos:ie,left:Ve(G,Y.left,ae,(await d(ie.node)).sequenceLen)}:void 0}}if(M(),!B(L))throw new re(`piece ${Ce(L)} was found in one orientation where extractPaths keeps the other`);r.twins.found+=1}r.ms.twins=o()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new re("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await j(w),await X()}catch(w){if(!(w instanceof re))throw w;r.fallback=w.message}return H()}function Xt(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var On=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Jt(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint32Array(64);for(let c=0;c<e;c++){for(let P=0;P<16;P++)r[P]=n.getUint32(c*64+P*4);for(let P=16;P<64;P++){let E=r[P-15],R=r[P-2],m=we(E,7)^we(E,18)^E>>>3,I=we(R,17)^we(R,19)^R>>>10;r[P]=r[P-16]+m+r[P-7]+I}let d=o[0],f=o[1],p=o[2],y=o[3],g=o[4],l=o[5],b=o[6],x=o[7];for(let P=0;P<64;P++){let E=we(g,6)^we(g,11)^we(g,25),R=g&l^~g&b,m=x+E+R+On[P]+r[P]|0,I=we(d,2)^we(d,13)^we(d,22),$=d&f^d&p^f&p;x=b,b=l,l=g,g=y+m|0,y=p,p=f,f=d,d=m+I+$|0}[d,f,p,y,g,l,b,x].forEach((P,E)=>{o[E]=o[E]+P})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,o[c]);return i}function Yt(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[o,r]=s;if(s.length!==2||!o||!r)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(o);i||(i=new Set,t.set(o,i)),i.add(r)}return t}function nn(a){return{name:a.get("pggname"),subgraph:Yt(a.get("subgraph"),"subgraph"),translation:Yt(a.get("translation"),"translation")}}function en(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let o of n)s.add(o)}}function sn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),en(t.subgraph,e.subgraph),en(t.translation,e.translation)),t}function tn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function on(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of tn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of tn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function rn(a){let e=a.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Jt(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}var Cn="_gbwt_ref";function fe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Bn=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,_n=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Tn(a){let e=Bn.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=_n.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Ae(a){return typeof a=="string"?Tn(a):a}function $e(a,e){return{sample:a.sample??Cn,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var le=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 ut(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var _e=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let o=s.length-1;for(;o>0;){let r=o-1>>1;if(ut(s[o],s[r]))[s[o],s[r]]=[s[r],s[o]],o=r;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let o=2*s+1,r=o+1,i=s;if(o<e.length&&ut(e[o],e[i])&&(i=o),r<e.length&&ut(e[r],e[i])&&(i=r),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function Fn(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],o)=>{e[o]=n,t[o]=s}),{pathAt:e,refAt:t,count:a.length}}function qn(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ke(a){return`${a.node}:${a.offset}`}function Be(a){return a.map(e=>ee(e)).reverse()}function zn(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Dn(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],o=n.edits.map(([c,d])=>[c,d]);hn(o,t.insertion,t.deletion);for(let[c,d]of s.edits)K(o,c,d);let r=a.identity.walkForward,[i,h]=r?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:o,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:r}}}function jn(a,e,t){if(a.some(r=>r.weight!==void 0))return a;let n=new Map;a.forEach((r,i)=>{if(r.identity){let h=n.get(r.identity.pathHandle);h?h.push(i):n.set(r.identity.pathHandle,[i])}});let s=new Map,o=new Set;for(let r of n.values()){r.sort((d,f)=>a[d].identity.hapStart-a[f].identity.hapStart);let i=r[0],h=a[i],c=[];for(let d of r.slice(1)){let f=a[d],p=c.length===0?zn(h,f):void 0;if(p){h=Dn(h,f,p),o.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(g=>a[g]),f]):void 0;if(y){h=y;for(let g of[...c,d])o.add(g)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return a.flatMap((r,i)=>o.has(i)?[]:[s.get(i)??r])}function Ge(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Un=32768;function Wn(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Un?s[1]=n:t.push([n,n])}return t}var Te=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(ce(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 le(this.limit);let t=await this.db.getRecord(ce(e,"forward")),n=await this.db.getRecord(ce(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 ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let o=n,r=s;for(;;){await this.ensureNode(N(r.node));let i=this.record(r.node);if(o+i.sequenceLen>t)return{position:{seqOffset:t,handle:r.node,nodeOffset:t-o,gbwtOffset:r.offset},name:e.name,handle:e.handle};o+=i.sequenceLen;let h=i.gbwt().lf(r.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);r=h}}async aroundPosition(e,t,n){let s=N(e);await this.ensureNode(s);let o=this.record(e),r=Ee(e),i=new _e;return i.push(t,s,Ue(r)),i.push(o.sequenceLen-t-1,s,We(r)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,o]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&o){let r=s.pos.node,i=o.pos.node;if(!await this.db.prefetchRecords([[Math.min(r,i),Math.max(r,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Wn(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof le&&s.windowBp===void 0?new le(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},o=e.nodeOffset,r=t,i=new _e;for(;;){let h=N(s.node),c=Ee(s.node);this.walkedBp=t-r,await this.ensureNode(h);let d=this.record(s.node);if(o>=d.sequenceLen)throw new Error(`Offset ${o} in node ${h} of length ${d.sequenceLen}`);i.push(o,h,Ue(c));let f=d.sequenceLen-o;if(r<=f){i.push(r===f?0:f-r-1,h,We(c));break}i.push(0,h,We(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,o=0,r-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new _e;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let r of this.records.keys())s.add(N(r));let o=0;for(;e.size>0;){let[r,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),o+=1);let d=Ft(h);if(!n.has(`${i}:${d}`)){let y=this.record(ce(i,qt(h))),g=r+y.sequenceLen-1;g<=t&&e.push(g,i,d)}let f=this.record(ce(i,zt(h))),p=r+1;if(p<=t)for(let y of f.successors()){let g=N(y),l=Ue(Ee(y));n.has(`${g}:${l}`)||e.push(p,g,l)}}for(let r of s)this.records.delete(ce(r,"forward")),this.records.delete(ce(r,"reverse"));return{inserted:o,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([N(e),N(t)]),o=[];for(;n.length>0;){let r=n.pop(),i=N(r);this.hasNode(i)||(await this.addNode(i),o.push(i));for(let h of this.record(r).successors()){let c=N(h);s.has(c)||(n.push(h,ee(h)),s.add(c))}}return{inserted:o,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:o,nodes:r}=await this.fillBetween(n,s),i=N(n),h=N(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:r,inserted:o.length});for(let c of o)this.snarlNodes.add(c);t+=o.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let o=this.record(s),r=o.next;r!==void 0&&(n=!0,this.hasHandle(r)?He(s,r)&&t.push([s,r]):e==="overlapping"&&this.isSnarlEntryInSubgraph(o)&&t.push([s,r]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let o=t.get(n);if(!o){if(o=await this.db.getRecord(n),e?.(),!o)throw new Error(`Node record ${n} is missing from the database`);t.set(n,o)}return o}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(ee(d))).successors().length>1},n=async h=>{let c=await e(ee(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[ee(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,o=this.sortedHandles().flatMap(h=>this.record(h).successors()),r,i=!1;for(;!i&&o.length>0;){let h=o.shift(),c=N(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")r=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])o.push(...(await e(ce(c,f))).successors())}}return r}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),o=s.length,r=new Map;s.forEach((m,I)=>r.set(m,I));let i=new Int32Array(o+1),h=new Int32Array(o),c=[];for(let m=0;m<o;m++){let I=this.record(s[m]),$=I.gbwt().decompressArrays();h[m]=I.sequenceLen,c.push($),i[m+1]=i[m]+$.nodes.length}let d=i[o],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let m=0;m<o;m++){let I=c[m];f.set(I.nodes,i[m]),p.set(I.offsets,i[m])}c.length=0;for(let m=0;m<d;m++){let I=r.get(f[m]);I===void 0?f[m]=-1:(f[m]=I,y[i[I]+p[m]]=1)}let g=n===void 0?void 0:r.get(n.handle),l=n?.gbwtOffset,b,x=(m,I,$)=>{let F=[],_=0,D=0,C=-1,H=m,k=I;for(;;){H===g&&k===l&&(C=_),$&&($.push(s[H]),F.push(k)),_+=1,D+=h[H];let j=i[H]+k,X=f[j];if(X<0)break;k=p[j],H=X}return{offsets:F,len:D,refAt:C,last:H}},P=(m,I,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:m,offsets:I,len:$,weight:void 0,identity:void 0})},E=new Int32Array(o);for(let m=0;m<o;m++){let I=s[m];if(!Q(I)){let $=i[m],F=i[m+1]-$;for(let _=0;_<F;_++)if(y[$+_]===0){let D=[],{offsets:C,len:H,refAt:k,last:j}=x(m,_,D),X=s[j];if(k>=0||Pe(I,X)){if(P(D,C,H,k),!Q(X)){let w=r.get(ee(X));E[w]=E[w]+1}}else this.twinStarts.add(ke({node:I,offset:_}))}}}for(let m=0;m<o;m++){let I=s[m];if(Q(I)){let $=i[m],F=i[m+1]-$,_=0;for(let C=0;C<F;C++)y[$+C]===0&&(_+=1);let D=(g===void 0||b!==void 0)&&_===E[m];for(let C=0;C<F;C++)if(y[$+C]===0){let H=D?void 0:x(m,C,void 0);if(H&&(H.refAt>=0||Pe(I,s[H.last]))){let k=[],{offsets:j,len:X,refAt:w}=x(m,C,k);P(k,j,X,w)}else this.twinStarts.add(ke({node:I,offset:C}))}}}let R=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((m,I)=>m.path[0]-I.path[0]||m.offsets[0]-I.offsets[0]),R&&(this.refId=this.paths.indexOf(R)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let m=this.paths[this.refId],I=n.nodeOffset;for(let F of m.path.slice(0,b))I+=this.record(F).sequenceLen;let $=n.seqOffset-I;this.refInterval=[$,$+m.len],m.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+m.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Oe(n)?Be(n):void 0,o=c=>s!==void 0&&wt(c,s)===0||Oe(Be(c)),r=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>wt(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=r&&c!==t&&o(c.path);this.twinDeferred||=f,d&&wt(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}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=r=>`${r.pathHandle}:${r.hapStart}-${r.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let r of this.paths)r!==e&&r.identity?.orientation==="forward"&&s.add(n(r.identity));let o=this.paths.filter(r=>r===e||r.identity?.orientation!=="reverse"||!s.has(n(r.identity)));o.length<this.paths.length&&(this.paths=o,this.refId=e===void 0?void 0:o.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(r=>r.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((r,i)=>i!==this.refId&&r.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((r,i)=>i===this.refId||r.identity!==void 0&&e(r.identity.name)),o=new Set;for(let r of s)for(let i of r.path)o.add(N(i));for(let r of[...this.records.keys()])o.has(N(r))||this.records.delete(r);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let o=e.position.seqOffset,r=await Zt({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=r.stats,r.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===r.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[r.reference,...r.pieces].sort(Xt);return this.paths=c.map(h),this.refId=c.indexOf(r.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[r.reference.hapStart,r.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=pt(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let o=l=>{let b=0,x=t.length-1;for(;b<x;){let E=b+x+1>>1;t[E][0]<=l?b=E:x=E-1}let P=t[b];return P[0]<=l&&l<=P[1]},r=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&r.set(ke(Ge(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(o(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},y=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},g=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],P=new Set,E={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(E);let R,m=0,I=l,$;for(;R===void 0;){if(this.signal?.throwIfAborted(),I!==void 0){if(P.has(I)){E.end="cycle";break}P.add(I);let H=this.paths[I];x.push({index:I,startBp:m}),E.fragments+=1;let k=m;for(let X=0;X<H.path.length;X++){let w=Ge(H,X),S=n.get(ke(w)),A=this.record(w.node).sequenceLen;if(S){R=y(S,k,A);break}k+=A}if(m+=H.len,R){E.end="in-fragment sample";break}let j=Ge(H,H.path.length-1);$=this.record(j.node).gbwt().lf(j.offset),I=void 0}if($===void 0||$.node===0){E.end="endmarker";break}let F=ke($),_=r.get(F);if(_!==void 0){let H=this.paths[_].identity;if(H){R=g(H,m),E.end="identified sibling";break}I=_;continue}this.records.has($.node)&&(E.reentries+=1),this.twinStarts.has(F)&&(E.twinLandings+=1);let D=await d($,E),C=await c($.node);if(D){R=y(D,m,C.sequenceLen),E.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,E.steps+=1,m-x[x.length-1].startBp>4*e+4*C.sequenceLen){E.end="bound";break}m+=C.sequenceLen,$=C.gbwt().lf($.offset)}if(R){E.pathHandle=R.pathHandle;let F=await p(R.pathHandle);for(let{index:_,startBp:D}of x){let C=this.paths[_];C.identity=R.orientation==="forward"?{pathHandle:R.pathHandle,name:F,orientation:"forward",hapStart:R.base+D,hapEnd:R.base+D+C.len}:{pathHandle:R.pathHandle,name:F,orientation:"reverse",hapStart:R.base-D-C.len,hapEnd:R.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let o=t.get(n);o?o.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),o=new Int32Array(e.length),r=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=qn(c,i);if(d===void 0)return;s[r]=h,o[r]=d,r+=1,i=d}}return{pathAt:s,refAt:o,count:r}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[o]).sequence;for(;r<h.length&&i<c.length;){if(h[r]!==c[i])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-o-1]).sequence;for(;r<h.length&&i<c.length;){if(h[h.length-r-1]!==c[c.length-i-1])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),o=this.pathLen(t),r=this.prefixMatches(e,t),i=this.suffixMatches(e,t);r+i>s&&(i=s-r),r+i>o&&(i=o-r),K(n,"M",r),hn(n,s-r-i,o-r-i),K(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let o of e)n.has(o)&&(s+=this.record(o).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??Fn(Ut(e,t,f=>this.record(f).sequenceLen)[0]),o=[],r=this.refPrefix(t),i=(f,p,y,g)=>{f===p?K(o,"D",r[g]-r[y]):y===g?K(o,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,g),o)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let g=this.record(e[p]).sequenceLen;K(o,"M",g),h+=g,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:o,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Oe(n)&&(t.identity===void 0||!Oe(Be(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let o=Be(t.path),r=this.sharedWeight(t.path,n);if(this.sharedWeight(o,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(r===0)s={...this.editsAgainst(o,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(o,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let g=Gn(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,P=x?.orientation==="forward",[E,R]=P?[l,b]:[b,l];return{strand:f,refStart:e.start+g.leading,refEnd:e.start+n-g.trailing,edits:g.edits,weight:l.weight,path:p.flatMap(m=>this.paths[m].path),start:Ge(l,0),pieces:p,soloAligned:y,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+E.identity.hapStart,hapEnd:x.name.fragment+R.identity.hapEnd,walkForward:P}}},o=d=>d.soloAligned.reduce((f,p)=>f+p,0),r=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*o(d)>=r(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((k,j)=>k.strand!==f.strand||k.identity.walkForward!==y||j>0&&k.identity.hapStart<d[j-1].identity.hapEnd))return;let g=y?d:[...d].reverse(),l=g.flatMap(k=>k.pieces),b=g.flatMap(k=>k.soloAligned),x=f.strand==="+"!==y,P=l.map(k=>this.paths[k]),E=P.slice(1).map((k,j)=>{let X=P[j].identity;return y?k.identity.hapStart-X.hapEnd:X.hapStart-k.identity.hapEnd}),R=x?[...P].reverse():P,m=x?[...E].reverse():E,I=R.flatMap(k=>x?Be(k.path):k.path),{edits:$}=this.editsAgainst(I,t),F=an($,R.map(k=>k.len)),_=new Map((x?[...l].reverse():l).map((k,j)=>[k,F[j]])),D=k=>2*k.pieces.reduce((j,X)=>j+_.get(X),0)>=o(k);if(!D(f)||!D(p))return;let C=[],H=0;return R.slice(0,-1).forEach((k,j)=>{H+=k.len,C.push([H,m[j]])}),s(Qn($,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),g=d.identity,l=g?g.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],an(p,[d.len])))}),jn(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:g,...l}=d,b={...l,cigar:Kn(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,o=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:Ke(d,f)}]:[]}),r=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=r(t),h=n?r(n):d=>!i(d),c=d=>this.record(ce(d,"forward")).sequence;return o.filter(d=>i(d.name)).flatMap(d=>o.filter(f=>h(f.name)).flatMap(f=>Wt({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:Vt(p.edits),matches:p.edits.reduce((y,[g,l])=>y+(g==="="?l:0),0),columns:p.edits.reduce((y,[,g])=>y+g,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ce(e,n);for(let o of this.record(s).successors())this.hasHandle(o)&&He(s,o)&&t.push([n==="reverse"?1:0,N(o),Q(o)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!Q(n)){let s=N(n),o=`S ${s} ${this.record(n).sequence}
|
|
1
|
+
import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j as zt,k as He,l as Oe,m as Pe,n as Dt,o as jt,p as Ut,q as Wt,r as Vt}from"./chunk-M2D7NUOY.js";import{a as _t,g as Tt}from"./chunk-OGXVDZPS.js";import{c as Ot}from"./chunk-IK3MQ4ZJ.js";import{a as Ct,g as Bt}from"./chunk-VKZALU57.js";var Ln=4096;function pt(a){let e=[];for(let t of a){let n=e[e.length-1];n&&t-n[1]<=Ln?n[1]=t:e.push([t,t])}return e}var Hn=32768,Gt={mostChosenPaths:32},lt=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)}},re=class extends Error{};function Ve(a,e,t,n){return a==="forward"?e+t:e-n}function Qt(a,e,t,n){return a==="forward"?e-n:e+t}function Kt(a){return Pe(ee(a.handles[a.handles.length-1]),ee(a.handles[0]))}function Ce(a){return`${a.pathHandle}:${a.hapStart}:${a.hapEnd}`}async function Zt(a){let{db:e,records:t,signal:n}=a,s=performance.now(),o=()=>{let w=performance.now(),S=w-s;return s=w,S},r={spacing:await e.haplotypeAnchorSpacing(),anchors:void 0,anchorsRead:0,chosenPaths:0,scans:[],scanRows:0,strays:void 0,pieces:0,sources:{reference:0,section:0,stray:0,chain:0,twin:0},walks:{},twins:{tried:0,found:0},graphFetches:0,fallback:void 0,ms:{scan:0,walks:0,check:0,twins:0}},i=(w,S)=>{let A=`${w}: ${S}`;r.walks[A]=(r.walks[A]??0)+1},h=await e.haplotypeSampleInterval()??4096,c=new Map,d=async w=>{let S=t.get(w)??c.get(w);if(S)return S;let A=await e.getRecord(w);if(r.graphFetches+=1,!A)throw new Error(`Node record ${w} is missing from the database`);return c.set(w,A),A},f=w=>t.get(w).sequenceLen,p=await e.pathsByHandle(),y=w=>{let S=p.get(w);return S!==void 0&&a.keep(S.name)},g=[],l=new lt,b=new Map,x=new Set,P=new Set,E=async w=>{let S=(await d(w.node)).gbwt().lf(w.offset);return S===void 0||S.node===0?void 0:S},R=async(w,S)=>{let A=(await d(ee(w.node))).gbwt().predecessorAt(w.offset);if(A===void 0||S!==void 0&&!S.has(A))return;let M=(await d(A)).gbwt().offsetTo(w);if(M===void 0)throw new Error(`No offset in ${A} leads to ${w.node}:${w.offset}`);return{node:A,offset:M}},m=(w,S,A,M)=>{let B=A.map(W=>W.pos.node),U=A.map(W=>W.pos.offset),J=0;for(let W of B)J+=f(W);let O=S==="forward"?A[0].left:A[A.length-1].left,L=g.length;g.push({pathHandle:w,orientation:S,handles:B,offsets:U,len:J,hapStart:O,hapEnd:O+J,canonical:Pe(B[0],B[B.length-1]),source:M});for(let W of A)l.set(W.pos,L);let G=b.get(w);return G?G.push(L):b.set(w,[L]),L},I=async(w,S,A,M)=>{let B=[],U=w;for(;;){n?.throwIfAborted();let O=await R(U.pos,t);if(!O)break;U={pos:O,left:Qt(A,U.left,f(U.pos.node),f(O.node))},B.push(U)}B.reverse();let J=[w];for(U=w;;){n?.throwIfAborted();let O=await E(U.pos);if(!O||!t.has(O.node))break;U={pos:O,left:Ve(A,U.left,f(U.pos.node),f(O.node))},J.push(U)}return m(S,A,[...B,...J],M)},$=async(w,S,A,M)=>g[l.get(w.pos)??await I(w,S,A,M)],F=w=>{let S=w.handles[w.handles.length-1];return{pos:{node:S,offset:w.offsets[w.offsets.length-1]},left:w.orientation==="forward"?w.hapEnd-f(S):w.hapStart}},_=w=>{let S=w.handles[0];return{pos:{node:S,offset:w.offsets[0]},left:w.orientation==="forward"?w.hapStart:w.hapEnd-f(S)}},D=await I({pos:a.referencePos,left:a.referenceLeft},a.referenceHandle,"forward","reference"),C=g[D],H=()=>{if(r.fallback!==void 0)return{reference:C,pieces:[],stats:r};let w=new Map;g.forEach((A,M)=>{M!==D&&w.set(Ce(A),[...w.get(Ce(A))??[],A])});let S=[];for(let A of w.values()){let M=new Set;for(let B of A)B.canonical&&!M.has(B.orientation)&&(M.add(B.orientation),S.push(B),r.sources[B.source]+=1)}return r.sources.reference=1,r.pieces=S.length+1,{reference:C,pieces:S,stats:r}},k=async(w,S)=>{let A=S?x:P,M=S?P:x,B=w;for(;;){if(A.has(B))return;A.add(B);let U=g[B],J=S?F(U):_(U),O=0,L;for(;L===void 0;){n?.throwIfAborted();let G=S?await E(J.pos):await R(J.pos);if(!G){L="endmarker";break}let W=(await d(J.pos.node)).sequenceLen,ue=(await d(G.node)).sequenceLen,se=S?Ve(U.orientation,J.left,W,ue):Qt(U.orientation,J.left,W,ue);if(t.has(G.node)){let Y=l.get(G);Y===void 0?(B=await I({pos:G,left:se},U.pathHandle,U.orientation,"chain"),M.add(B),L="landed"):(M.add(Y),L="merge")}else O>Hn?L="bound":(O+=ue,J={pos:G,left:se})}if(i("chain",L),L!=="landed")return}},j=async w=>{if(a.context>w.context)throw new re(`the context of ${a.context} bp exceeds the ${w.context} bp the haplotype index's stray rows cover`);let S=r.spacing;if(S===void 0)throw new re("the haplotype index has no anchors");let{bin:A,bound:M}=w,{fills:B,inserted:U}=a.snarls;if(a.snarls.mode==="overlapping"&&B.length>0)throw new re("the haplotype index's stray rows cover contained snarls only");for(let u of B){if(u.inserted>0&&u.low===u.high)throw new re(`the haplotype index's stray rows leave out the snarl bounded by node ${u.low} at both ends`);if(u.inserted>0&&(w.snarlNodes===void 0||u.nodes>w.snarlNodes))throw new re(w.snarlNodes===void 0?"the haplotype index's stray rows leave snarls out":`a snarl of ${u.nodes} nodes exceeds the ${w.snarlNodes} the haplotype index's stray rows cover`)}let J=Math.floor(a.window.start/A),O=Math.floor((a.window.end-1)/A),L=J*A,G=(O+1)*A,W=new Map,ue=async(u,v)=>{let z=await e.haplotypeAnchorsBetween(a.referenceHandle,u*S,v*S);for(let T of z)W.set(T.anchorOffset/S,T)},se=Math.max(0,Math.floor((L-M)/S)-1),Y=Math.ceil((G+M)/S)+1,[{listed:De,strays:ae}]=await Promise.all([e.haplotypeBinData(a.referenceHandle,J,O),ue(se,Y)]);for(let u of t.keys()){let v=N(u);if(!Q(u)&&!De(v)&&!U.has(v))throw new re(`the haplotype index lists node ${v} of the subgraph in no bin that the window touches`)}r.scans=pt([...t.keys()].sort((u,v)=>u-v));let ie=Promise.all(r.scans.map(([u,v])=>e.haplotypeSamplesInRange(u,v)));for(ie.catch(()=>{});se>0&&(W.get(se)?.pathOffset??Number.POSITIVE_INFINITY)>=L-M;)se-=1,await ue(se,se);for(;W.has(Y)&&W.get(Y).pathOffset<=G+M;)Y+=1,await ue(Y,Y);let pe=[...W.keys()].sort((u,v)=>u-v),ye=W.get(pe[0]??-1);if(!ye)throw new re("the haplotype index has no anchors on this path");let he=u=>W.get(u).pathOffset,Ne=new Map;for(let u of pe){let v=N(W.get(u).node);Ne.set(v,[...Ne.get(v)??[],u])}let ct=[...Ne.keys()],Et=ct.map(u=>W.get(Ne.get(u)[0]).visits);if(!Et[ct.indexOf(N(ye.node))].some(u=>u.pathHandle===a.referenceHandle&&u.orientation==="forward"&&u.pathOffset===ye.pathOffset))throw new Error(`The haplotype index has no anchor row for the reference path ${a.referenceHandle} at offset ${ye.pathOffset} (node ${N(ye.node)}); it does not match this graph`);let kt=pe.filter(u=>he(u)<=a.window.start),$n=pe.filter(u=>he(u)>=a.window.end);r.anchors=[he(kt[kt.length-1]??pe[0]),he($n[0]??pe[pe.length-1])],r.anchorsRead=pe.length;let dt=new Map,vt=new Set;if(ct.forEach((u,v)=>{let z=Ne.get(u),T=z.length===1?z[0]:void 0;for(let q of Et[v])vt.add(q.pathHandle),q.orientation==="forward"&&y(q.pathHandle)&&dt.set(q.pathHandle,[...dt.get(q.pathHandle)??[],{k:T,row:q}])}),r.chosenPaths=[...vt].filter(y).length,r.chosenPaths>Gt.mostChosenPaths)throw new re(`${r.chosenPaths} chosen paths pass the anchors, more than ${Gt.mostChosenPaths}`);let je=[],Ie=Number.POSITIVE_INFINITY,be=0;for(let[u,v]of dt){v.sort((z,T)=>z.row.pathOffset-T.row.pathOffset);for(let z=0;z+1<v.length;z++){let T=v[z],q=v[z+1];if(T.k===void 0||q.k===void 0||Math.abs(T.k-q.k)!==1)continue;let[Z,te]=he(T.k)<=he(q.k)?[T,q]:[q,T],ne=he(Z.k),oe=he(te.k);ne<G&&oe>=L?(je.push({pathHandle:u,from:T.row,to:q.row}),Ie=Math.min(Ie,ne-M),be=Math.max(be,oe+M)):ne>=G&&ne-G<=M?(je.push({pathHandle:u,from:Z.row,to:void 0}),Ie=Math.min(Ie,ne-M),be=Math.max(be,ne+M)):oe<L&&L-oe<=M&&(je.push({pathHandle:u,from:te.row,to:void 0}),Ie=Math.min(Ie,oe-M),be=Math.max(be,oe+M))}}let Rn=new Set(B.map(u=>`${u.low}:${u.high}`)),Nn=ae.filter(u=>y(u.pathHandle)&&(u.snarl===void 0||Rn.has(`${u.snarl[0]}:${u.snarl[1]}`))).sort((u,v)=>u.pathHandle-v.pathHandle||u.pathStart-v.pathStart);r.strays={bins:O-J+1,rows:ae.length,walked:0,outsideBp:0},be>0&&await a.prefetchReferenceRange(a.referenceHandle,Math.max(0,Ie),be+1),r.ms.scan=o();let Pt=8*S+2*(a.window.end-a.window.start),At=r.strays,Me=0,$t=u=>{if(At.outsideBp+=u,Me+=u,Me>Pt)throw new re(`a walk of a chosen path near the window went past its cap of ${Pt} bp`)},ft=new Map,Rt=(u,v,z)=>(ft.get(u)??[]).some(([T,q])=>T<=v&&z<q),Nt=(u,v,z)=>{ft.set(u,[...ft.get(u)??[],[v,z]])},Mt=async(u,v,z,T,q)=>{let Z=v,te=z,ne=te;for(;Z&&te<=T;){n?.throwIfAborted();let oe;if(t.has(Z.node)){let Le=await $({pos:Z,left:te},u,"forward",q),Ht=F(Le);Z=Ht.pos,te=Ht.left,oe=f(Z.node),ne=Math.max(ne,Le.hapEnd)}else oe=(await d(Z.node)).sequenceLen,$t(oe),ne=Math.max(ne,te+oe);Z=await E(Z),te+=oe}return ne},Mn=async(u,v,z,T)=>{let q={pos:v,left:z},Z=z;for(;q.left>T;){n?.throwIfAborted();let te=await R(q.pos);if(!te)break;let ne=(await d(te.node)).sequenceLen,oe=q.left-ne;if(t.has(te.node)){let Le=await $({pos:te,left:oe},u,"forward","section");q=_(Le),Z=Math.min(Z,Le.hapStart)}else $t(ne),q={pos:te,left:oe},Z=Math.min(Z,oe)}return Z};for(let{pathHandle:u,from:v,to:z}of je){let T=v.pathOffset,q=(z??v).pathOffset+M;if(Rt(u,T-M,q))continue;let Z={node:v.node,offset:v.offset};Me=0;let te=await Mt(u,Z,T,q,"section");Me=0;let ne=await Mn(u,Z,T,T-M);Nt(u,Math.min(ne,T-M),Math.max(te,q+1)),i(z?"section":"visit",z?"past the far anchor":"bound")}for(let u of Nn){if(Rt(u.pathHandle,u.pathStart,u.pathEnd))continue;Me=0;let v=await Mt(u.pathHandle,{node:u.node,offset:u.offset},u.pathStart,u.pathEnd,"stray");Nt(u.pathHandle,u.pathStart,Math.max(v,u.pathEnd+1)),At.walked+=1}r.ms.walks=o();let Lt=[];for(let u of await ie)for(let v of u)if(r.scanRows+=1,t.has(v.node)&&y(v.pathHandle)){if(!(b.get(v.pathHandle)??[]).some(z=>{let T=g[z];return T.hapStart<=v.pathOffset&&v.pathOffset<T.hapEnd}))throw new re(`chosen path ${v.pathHandle} has a sample at ${v.pathOffset} on the window's nodes that no walk reached`);v.orientation==="reverse"&&Lt.push(v)}for(let u of Lt)await $({pos:{node:u.node,offset:u.offset},left:u.pathOffset},u.pathHandle,"reverse","twin");r.ms.check=o()},X=async()=>{let w=new Map,S=O=>{let L=Ce(O),G=w.get(L);G?G.add(O.orientation):w.set(L,new Set([O.orientation]))},A=0,M=()=>{for(;A<g.length;A++)S(g[A])};M();let B=O=>(w.get(Ce(O))?.size??0)>1,U=2*h,J=(O,L)=>L===D?y(a.referenceHandle)&&Kt(O):!O.canonical||Kt(O);for(let O=0;O<g.length;O++){let L=g[O];if(B(L)||!J(L,O))continue;r.twins.tried+=1;let G=L.orientation==="forward"?"reverse":"forward",W=F(L),ue=0,se;for(;!se&&ue<=U;){n?.throwIfAborted();let ae=await E(W.pos);if(!ae)break;let ie=(await d(ae.node)).sequenceLen,pe=Ve(L.orientation,W.left,(await d(W.pos.node)).sequenceLen,ie),ye=ee(ae.node);se=(await e.haplotypeSamplesInRange(ye,ye)).find(he=>he.pathHandle===L.pathHandle&&he.orientation===G&&he.pathOffset===pe),ue+=ie,W={pos:ae,left:pe}}let Y=se&&{pos:{node:se.node,offset:se.offset},left:se.pathOffset},De=0;for(;Y&&!B(L)&&De<=U+L.len;){if(n?.throwIfAborted(),t.has(Y.pos.node)){let ae=await $(Y,L.pathHandle,G,"twin"),ie=g.indexOf(ae);await k(ie,!0),await k(ie,!1),M(),Y=F(ae)}if(!B(L)){let ae=(await d(Y.pos.node)).sequenceLen;De+=ae;let ie=await E(Y.pos);Y=ie?{pos:ie,left:Ve(G,Y.left,ae,(await d(ie.node)).sequenceLen)}:void 0}}if(M(),!B(L))throw new re(`piece ${Ce(L)} was found in one orientation where extractPaths keeps the other`);r.twins.found+=1}r.ms.twins=o()};try{let w=await e.haplotypeStrayOptions();if(w===void 0)throw new re("the haplotype index has no stray rows; gbz-haplotype-index 0.2.0 writes them");await j(w),await X()}catch(w){if(!(w instanceof re))throw w;r.fallback=w.message}return H()}function Xt(a,e){return a.handles[0]-e.handles[0]||a.offsets[0]-e.offsets[0]}var On=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),we=(a,e)=>a>>>e|a<<32-e;function Jt(a){let e=Math.ceil((a.length+9)/64),t=new Uint8Array(e*64);t.set(a),t[a.length]=128;let n=new DataView(t.buffer),s=a.length*8;n.setUint32(t.length-8,Math.floor(s/2**32)),n.setUint32(t.length-4,s>>>0);let o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),r=new Uint32Array(64);for(let c=0;c<e;c++){for(let P=0;P<16;P++)r[P]=n.getUint32(c*64+P*4);for(let P=16;P<64;P++){let E=r[P-15],R=r[P-2],m=we(E,7)^we(E,18)^E>>>3,I=we(R,17)^we(R,19)^R>>>10;r[P]=r[P-16]+m+r[P-7]+I}let d=o[0],f=o[1],p=o[2],y=o[3],g=o[4],l=o[5],b=o[6],x=o[7];for(let P=0;P<64;P++){let E=we(g,6)^we(g,11)^we(g,25),R=g&l^~g&b,m=x+E+R+On[P]+r[P]|0,I=we(d,2)^we(d,13)^we(d,22),$=d&f^d&p^f&p;x=b,b=l,l=g,g=y+m|0,y=p,p=f,f=d,d=m+I+$|0}[d,f,p,y,g,l,b,x].forEach((P,E)=>{o[E]=o[E]+P})}let i=new Uint8Array(32),h=new DataView(i.buffer);for(let c=0;c<8;c++)h.setUint32(c*4,o[c]);return i}function Yt(a,e){let t=new Map;if(a!==void 0)for(let n of a.split(";")){let s=n.split(","),[o,r]=s;if(s.length!==2||!o||!r)throw new Error(`Invalid ${e} relationship: ${n}`);let i=t.get(o);i||(i=new Set,t.set(o,i)),i.add(r)}return t}function nn(a){return{name:a.get("pggname"),subgraph:Yt(a.get("subgraph"),"subgraph"),translation:Yt(a.get("translation"),"translation")}}function en(a,e){for(let[t,n]of e){let s=a.get(t);s||(s=new Set,a.set(t,s));for(let o of n)s.add(o)}}function sn(a,e){let t={name:a,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(a,new Set([e.name])),en(t.subgraph,e.subgraph),en(t.translation,e.translation)),t}function tn(a){return[...a.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(n=>[e,n]))}function on(a){let e=[];a.name!==void 0&&e.push(`H NM:Z:${a.name}`);for(let[t,n]of tn(a.subgraph))e.push(`H SG:Z:${t},${n}`);for(let[t,n]of tn(a.translation))e.push(`H TL:Z:${t},${n}`);return e}async function rn(a){let e=a.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),n=0;for(let r of a)t.set(r,n),n+=r.length;let s=globalThis.crypto?.subtle;return[...s?new Uint8Array(await s.digest("SHA-256",t)):Jt(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}var Cn="_gbwt_ref";function fe(a){let e=`${a.sample}#${a.haplotype}#${a.contig}`;return a.end===void 0?e:`${e}[${a.fragment}-${a.end}]`}var Bn=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,_n=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Tn(a){let e=Bn.exec(a);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=_n.exec(a);if(t)return{contig:t[1]};throw new Error(`"${a}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function Ae(a){return typeof a=="string"?Tn(a):a}function $e(a,e){return{sample:a.sample??Cn,contig:a.contig,haplotype:a.haplotype??0,fragment:e}}var le=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 ut(a,e){return a[0]<e[0]||a[0]===e[0]&&(a[1]<e[1]||a[1]===e[1]&&a[2]<e[2])}var _e=class{heap=[];push(e,t,n){let s=this.heap;s.push([e,t,n]);let o=s.length-1;for(;o>0;){let r=o-1>>1;if(ut(s[o],s[r]))[s[o],s[r]]=[s[r],s[o]],o=r;else break}}pop(){let e=this.heap,t=e[0],n=e.pop();if(e.length>0&&n!==void 0){e[0]=n;let s=0;for(;;){let o=2*s+1,r=o+1,i=s;if(o<e.length&&ut(e[o],e[i])&&(i=o),r<e.length&&ut(e[r],e[i])&&(i=r),i===s)break;[e[s],e[i]]=[e[i],e[s]],s=i}}return t}get size(){return this.heap.length}};function Fn(a){let e=new Int32Array(a.length),t=new Int32Array(a.length);return a.forEach(([n,s],o)=>{e[o]=n,t[o]=s}),{pathAt:e,refAt:t,count:a.length}}function qn(a,e){let t=0,n=a.length;for(;t<n;){let s=t+n>>1;a[s]>e?n=s:t=s+1}return a[t]}function ke(a){return`${a.node}:${a.offset}`}function Be(a){return a.map(e=>ee(e)).reverse()}function zn(a,e){let t=e.identity.hapStart-a.identity.hapEnd,n=a.strand==="+"?e.refStart-a.refEnd:a.refStart-e.refEnd;return a.strand===e.strand&&t>=0&&n>=0?{insertion:t,deletion:n}:void 0}function Dn(a,e,t){let[n,s]=a.strand==="+"?[a,e]:[e,a],o=n.edits.map(([c,d])=>[c,d]);hn(o,t.insertion,t.deletion);for(let[c,d]of s.edits)K(o,c,d);let r=a.identity.walkForward,[i,h]=r?[a,e]:[e,a];return{strand:a.strand,refStart:n.refStart,refEnd:s.refEnd,edits:o,weight:void 0,path:[...i.path,...h.path],start:i.start,pieces:[...i.pieces,...h.pieces],soloAligned:[...i.soloAligned,...h.soloAligned],identity:{pathHandle:a.identity.pathHandle,name:a.identity.name,hapStart:a.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:r}}}function jn(a,e,t){if(a.some(r=>r.weight!==void 0))return a;let n=new Map;a.forEach((r,i)=>{if(r.identity){let h=n.get(r.identity.pathHandle);h?h.push(i):n.set(r.identity.pathHandle,[i])}});let s=new Map,o=new Set;for(let r of n.values()){r.sort((d,f)=>a[d].identity.hapStart-a[f].identity.hapStart);let i=r[0],h=a[i],c=[];for(let d of r.slice(1)){let f=a[d],p=c.length===0?zn(h,f):void 0;if(p){h=Dn(h,f,p),o.add(d);continue}if(!e(f)){c.push(d);continue}let y=e(h)?t([h,...c.map(g=>a[g]),f]):void 0;if(y){h=y;for(let g of[...c,d])o.add(g)}else s.set(i,h),i=d,h=f;c=[]}s.set(i,h)}return a.flatMap((r,i)=>o.has(i)?[]:[s.get(i)??r])}function Ge(a,e){return{node:a.path[e],offset:a.offsets[e]}}var Un=32768;function Wn(a){let e=[...a].sort((n,s)=>n-s),t=[];for(let n of e){let s=t[t.length-1];s&&n-s[1]<=Un?s[1]=n:t.push([n,n])}return t}var Te=class a{records=new Map;paths=[];twinStarts=new Set;twinDeferred=!1;unsettled;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;snarlMode="none";snarlFills=[];snarlNodes=new Set;stats={orderedAlignments:0,lcsAlignments:0,snarls:{fills:0,inserted:0},identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},keep:void 0};db;limit;signal;constructor(e,t){this.db=e,this.limit=t.limit,this.signal=t.signal}static create(e,t={}){return new a(e,t)}get nodeCount(){return this.records.size/2}get pathCount(){return this.settleDeferred(),this.paths.length}get referenceInterval(){return this.refInterval&&this.refPath?{name:this.refPath,start:this.refPath.fragment+this.refInterval[0],end:this.refPath.fragment+this.refInterval[1]}:void 0}hasNode(e){return this.records.has(ce(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 le(this.limit);let t=await this.db.getRecord(ce(e,"forward")),n=await this.db.getRecord(ce(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 ${fe(e)}`);if(!t.isIndexed)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);let n=e.fragment-t.name.fragment,s=await this.db.indexedPosition(t.handle,n);if(!s)throw new Error(`The fragment of ${fe(t.name)} at ${t.name.fragment} has not been indexed for random access`);return this.findPathPosition(t,n,s.pathOffset,s.pos)}async findPathPosition(e,t,n,s){let o=n,r=s;for(;;){await this.ensureNode(N(r.node));let i=this.record(r.node);if(o+i.sequenceLen>t)return{position:{seqOffset:t,handle:r.node,nodeOffset:t-o,gbwtOffset:r.offset},name:e.name,handle:e.handle};o+=i.sequenceLen;let h=i.gbwt().lf(r.offset);if(!h)throw new Error(`The fragment of ${fe(e.name)} at ${e.name.fragment} does not contain offset ${t}`);r=h}}async aroundPosition(e,t,n){let s=N(e);await this.ensureNode(s);let o=this.record(e),r=Ee(e),i=new _e;return i.push(t,s,Ue(r)),i.push(o.sequenceLen-t-1,s,We(r)),this.insertContext(i,n)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,n){let[s,o]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,n)]);if(s&&o){let r=s.pos.node,i=o.pos.node;if(!await this.db.prefetchRecords([[Math.min(r,i),Math.max(r,i)+1]])){let c=await this.db.indexedPositionsBetween(e,t,n);await this.db.prefetchRecords(Wn(c.map(d=>d.pos.node)).map(([d,f])=>[d,f+2]),!0)}}return s}async aroundInterval(e,t,n){if(!(t>0))throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,n)}catch(s){throw s instanceof le&&s.windowBp===void 0?new le(s.limit,{windowBp:t,walkedBp:this.walkedBp}):s}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,n){let s={node:e.handle,offset:e.gbwtOffset},o=e.nodeOffset,r=t,i=new _e;for(;;){let h=N(s.node),c=Ee(s.node);this.walkedBp=t-r,await this.ensureNode(h);let d=this.record(s.node);if(o>=d.sequenceLen)throw new Error(`Offset ${o} in node ${h} of length ${d.sequenceLen}`);i.push(o,h,Ue(c));let f=d.sequenceLen-o;if(r<=f){i.push(r===f?0:f-r-1,h,We(c));break}i.push(0,h,We(c));let p=d.gbwt().lf(s.offset);if(!p)throw new Error(`No successor for GBWT position (${s.node}, ${s.offset})`);s=p,o=0,r-=f}return this.walkedBp=t,this.insertContext(i,n)}async aroundNodes(e,t){let n=new _e;for(let s of e)await this.ensureNode(s),n.push(0,s,"left"),n.push(0,s,"right");return this.insertContext(n,t)}async insertContext(e,t){this.clearPaths(),this.snarlMode="none",this.snarlFills=[],this.snarlNodes.clear(),this.stats.snarls={fills:0,inserted:0};let n=new Set,s=new Set;for(let r of this.records.keys())s.add(N(r));let o=0;for(;e.size>0;){let[r,i,h]=e.pop(),c=`${i}:${h}`;if(n.has(c))continue;n.add(c),s.delete(i),this.hasNode(i)||(await this.addNode(i),o+=1);let d=Ft(h);if(!n.has(`${i}:${d}`)){let y=this.record(ce(i,qt(h))),g=r+y.sequenceLen-1;g<=t&&e.push(g,i,d)}let f=this.record(ce(i,zt(h))),p=r+1;if(p<=t)for(let y of f.successors()){let g=N(y),l=Ue(Ee(y));n.has(`${g}:${l}`)||e.push(p,g,l)}}for(let r of s)this.records.delete(ce(r,"forward")),this.records.delete(ce(r,"reverse"));return{inserted:o,removed:s.size}}async betweenNodes(e,t){return(await this.fillBetween(e,t)).inserted.length}async fillBetween(e,t){this.clearPaths();let n=[e,ee(t)],s=new Set([N(e),N(t)]),o=[];for(;n.length>0;){let r=n.pop(),i=N(r);this.hasNode(i)||(await this.addNode(i),o.push(i));for(let h of this.record(r).successors()){let c=N(h);s.has(c)||(n.push(h,ee(h)),s.add(c))}}return{inserted:o,nodes:s.size-2}}async extractSnarls(e){let t=0;this.snarlMode=e;for(let[n,s]of await this.overlappingSnarls(e)){let{inserted:o,nodes:r}=await this.fillBetween(n,s),i=N(n),h=N(s);this.snarlFills.push({low:Math.min(i,h),high:Math.max(i,h),nodes:r,inserted:o.length});for(let c of o)this.snarlNodes.add(c);t+=o.length}return this.stats.snarls={fills:this.snarlFills.length,inserted:this.snarlNodes.size},t}async overlappingSnarls(e){let t=[];if(e!=="none"){let n=!1;for(let s of this.sortedHandles()){let o=this.record(s),r=o.next;r!==void 0&&(n=!0,this.hasHandle(r)?He(s,r)&&t.push([s,r]):e==="overlapping"&&this.isSnarlEntryInSubgraph(o)&&t.push([s,r]))}if(!n&&e==="overlapping"&&await this.db.hasChainLinks()){let s=await this.findCoveringSnarl();s&&t.push(s)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),n=t.find(s=>this.hasHandle(s));return n===void 0?!1:t.length>1||this.record(ee(n)).successors().length>1}recordReader(e){let t=new Map;return async n=>{let s=this.records.get(n);if(s)return s;let o=t.get(n);if(!o){if(o=await this.db.getRecord(n),e?.(),!o)throw new Error(`Node record ${n} is missing from the database`);t.set(n,o)}return o}}async findCoveringSnarl(){let e=this.recordReader(),t=async h=>{let c=h.successors(),d=c[0];return d===void 0?!1:c.length>1||(await e(ee(d))).successors().length>1},n=async h=>{let c=await e(ee(h));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[ee(h),c.next]}:{kind:"chain"}:(await e(h)).next!==void 0?{kind:"chain"}:{kind:"regular"}},s=new Set,o=this.sortedHandles().flatMap(h=>this.record(h).successors()),r,i=!1;for(;!i&&o.length>0;){let h=o.shift(),c=N(h);if(!this.hasHandle(h)&&!s.has(c)){s.add(c);let d=await n(h);if(d.kind==="snarl-exit")r=d.snarl,i=!0;else if(d.kind==="chain")i=!0;else for(let f of["forward","reverse"])o.push(...(await e(ce(c,f))).successors())}}return r}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let n=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let s=this.sortedHandles(),o=s.length,r=new Map;s.forEach((m,I)=>r.set(m,I));let i=new Int32Array(o+1),h=new Int32Array(o),c=[];for(let m=0;m<o;m++){let I=this.record(s[m]),$=I.gbwt().decompressArrays();h[m]=I.sequenceLen,c.push($),i[m+1]=i[m]+$.nodes.length}let d=i[o],f=new Int32Array(d),p=new Int32Array(d),y=new Uint8Array(d);for(let m=0;m<o;m++){let I=c[m];f.set(I.nodes,i[m]),p.set(I.offsets,i[m])}c.length=0;for(let m=0;m<d;m++){let I=r.get(f[m]);I===void 0?f[m]=-1:(f[m]=I,y[i[I]+p[m]]=1)}let g=n===void 0?void 0:r.get(n.handle),l=n?.gbwtOffset,b,x=(m,I,$)=>{let F=[],_=0,D=0,C=-1,H=m,k=I;for(;;){H===g&&k===l&&(C=_),$&&($.push(s[H]),F.push(k)),_+=1,D+=h[H];let j=i[H]+k,X=f[j];if(X<0)break;k=p[j],H=X}return{offsets:F,len:D,refAt:C,last:H}},P=(m,I,$,F)=>{F>=0&&(this.refId=this.paths.length,b=F),this.paths.push({path:m,offsets:I,len:$,weight:void 0,identity:void 0})},E=new Int32Array(o);for(let m=0;m<o;m++){let I=s[m];if(!Q(I)){let $=i[m],F=i[m+1]-$;for(let _=0;_<F;_++)if(y[$+_]===0){let D=[],{offsets:C,len:H,refAt:k,last:j}=x(m,_,D),X=s[j];if(k>=0||Pe(I,X)){if(P(D,C,H,k),!Q(X)){let w=r.get(ee(X));E[w]=E[w]+1}}else this.twinStarts.add(ke({node:I,offset:_}))}}}for(let m=0;m<o;m++){let I=s[m];if(Q(I)){let $=i[m],F=i[m+1]-$,_=0;for(let C=0;C<F;C++)y[$+C]===0&&(_+=1);let D=(g===void 0||b!==void 0)&&_===E[m];for(let C=0;C<F;C++)if(y[$+C]===0){let H=D?void 0:x(m,C,void 0);if(H&&(H.refAt>=0||Pe(I,s[H.last]))){let k=[],{offsets:j,len:X,refAt:w}=x(m,C,k);P(k,j,X,w)}else this.twinStarts.add(ke({node:I,offset:C}))}}}let R=this.refId===void 0?void 0:this.paths[this.refId];if(this.paths.sort((m,I)=>m.path[0]-I.path[0]||m.offsets[0]-I.offsets[0]),R&&(this.refId=this.paths.indexOf(R)),n){if(b===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let m=this.paths[this.refId],I=n.nodeOffset;for(let F of m.path.slice(0,b))I+=this.record(F).sequenceLen;let $=n.seqOffset-I;this.refInterval=[$,$+m.len],m.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:$,hapEnd:$+m.len}}if(t==="distinct")this.distinctPaths(!0);else if(t==="reference-only"){if(this.refId===void 0)throw new Error("Reference path is required for reference-only output");this.paths=[this.paths[this.refId]],this.refId=0}}distinctPaths(e){let t=this.refId===void 0?void 0:this.paths[this.refId],n=t?.path,s=n&&!Oe(n)?Be(n):void 0,o=c=>s!==void 0&&wt(c,s)===0||Oe(Be(c)),r=e&&this.db.hasHaplotypeIndex;this.twinDeferred=!1,this.paths.sort((c,d)=>wt(c.path,d.path)||c.len-d.len||(c===t?-1:d===t?1:0));let i=[],h;for(let c of this.paths){let d=i[i.length-1],f=r&&c!==t&&o(c.path);this.twinDeferred||=f,d&&wt(d.path,c.path)===0&&!f?d.weight=(d.weight??1)+(c.weight??1):(c===t&&(h=i.length),i.push({...c,weight:c.weight??1}))}this.paths=i,this.refId=h}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=r=>`${r.pathHandle}:${r.hapStart}-${r.hapEnd}`,s=new Set;e?.identity&&t&&s.add(n({...e.identity,hapStart:t[0],hapEnd:t[1]}));for(let r of this.paths)r!==e&&r.identity?.orientation==="forward"&&s.add(n(r.identity));let o=this.paths.filter(r=>r===e||r.identity?.orientation!=="reverse"||!s.has(n(r.identity)));o.length<this.paths.length&&(this.paths=o,this.refId=e===void 0?void 0:o.indexOf(e)),this.twinDeferred&&this.distinctPaths(!1)}keepHaplotypes(e){if(this.paths.some(r=>r.weight!==void 0))throw new Error("keepHaplotypes needs one walk per haplotype: extract with haplotypes 'all', then call mergeDistinct()");let t=this.paths.filter((r,i)=>i!==this.refId&&r.identity===void 0).length;if(t>0)throw new Error(`${t} of the window's ${this.paths.length} walks have no name, so the haplotypes to keep cannot be told from the rest; call identifyPaths() first, and check that the haplotype index was built for this graph`);let n=this.refId===void 0?void 0:this.paths[this.refId],s=this.paths.filter((r,i)=>i===this.refId||r.identity!==void 0&&e(r.identity.name)),o=new Set;for(let r of s)for(let i of r.path)o.add(N(i));for(let r of[...this.records.keys()])o.has(N(r))||this.records.delete(r);this.paths=s,this.refId=n===void 0?void 0:s.indexOf(n)}async extractChosenPaths(e,t,n,s){this.clearPaths();let o=e.position.seqOffset,r=await Zt({db:this.db,records:this.records,referenceHandle:e.handle,referencePos:{node:e.position.handle,offset:e.position.gbwtOffset},referenceLeft:o-e.position.nodeOffset,window:{start:o,end:o+t},context:s,snarls:{mode:this.snarlMode,fills:this.snarlFills,inserted:this.snarlNodes},keep:n,signal:this.signal,prefetchReferenceRange:(d,f,p)=>this.prefetchReferenceRange(d,f,p)});if(this.stats.keep=r.stats,r.stats.fallback!==void 0)return!1;let i=await this.db.pathsByHandle(),h=d=>({path:d.handles,offsets:d.offsets,len:d.len,weight:void 0,identity:{pathHandle:d.pathHandle,name:d===r.reference?e.name:i.get(d.pathHandle).name,orientation:d.orientation,hapStart:d.hapStart,hapEnd:d.hapEnd}}),c=[r.reference,...r.pieces].sort(Xt);return this.paths=c.map(h),this.refId=c.indexOf(r.reference),this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[r.reference.hapStart,r.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=pt(this.sortedHandles());if(t.length===0)return;let n=new Map,s=await Promise.all(t.map(([l,b])=>this.db.haplotypeSamplesInRange(l,b)));for(let l of s.flat())n.set(ke(l),l);let o=l=>{let b=0,x=t.length-1;for(;b<x;){let E=b+x+1>>1;t[E][0]<=l?b=E:x=E-1}let P=t[b];return P[0]<=l&&l<=P[1]},r=new Map;this.paths.forEach((l,b)=>{l.path.length>0&&b!==this.refId&&r.set(ke(Ge(l,0)),b)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=n.size,this.paths.forEach((l,b)=>{b!==this.refId&&i.fragmentLengths.push(l.len)});let h=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),c=l=>(i.graphLookups+=1,h(l)),d=async(l,b)=>{if(o(l.node))return n.get(ke(l));this.stats.identificationFetches+=1,i.companionSeeks+=1,b.seeks+=1;let x=await this.db.haplotypeSampleAt(l.node,l.offset);return x||(i.companionMisses+=1),x},f=new Map,p=async l=>{let b=f.get(l);if(!b){let x=await this.db.getPath(l);if(!x)throw new Error(`Path ${l} is missing from the database`);b=x.name,f.set(l,b)}return b},y=(l,b,x)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.pathOffset-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.pathOffset+b+x},g=(l,b)=>l.orientation==="forward"?{pathHandle:l.pathHandle,orientation:"forward",base:l.hapStart-b}:{pathHandle:l.pathHandle,orientation:"reverse",base:l.hapEnd+b};for(let l=0;l<this.paths.length;l++){let b=this.paths[l];if(l===this.refId||b.identity)continue;let x=[],P=new Set,E={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(E);let R,m=0,I=l,$;for(;R===void 0;){if(this.signal?.throwIfAborted(),I!==void 0){if(P.has(I)){E.end="cycle";break}P.add(I);let H=this.paths[I];x.push({index:I,startBp:m}),E.fragments+=1;let k=m;for(let X=0;X<H.path.length;X++){let w=Ge(H,X),S=n.get(ke(w)),A=this.record(w.node).sequenceLen;if(S){R=y(S,k,A);break}k+=A}if(m+=H.len,R){E.end="in-fragment sample";break}let j=Ge(H,H.path.length-1);$=this.record(j.node).gbwt().lf(j.offset),I=void 0}if($===void 0||$.node===0){E.end="endmarker";break}let F=ke($),_=r.get(F);if(_!==void 0){let H=this.paths[_].identity;if(H){R=g(H,m),E.end="identified sibling";break}I=_;continue}this.records.has($.node)&&(E.reentries+=1),this.twinStarts.has(F)&&(E.twinLandings+=1);let D=await d($,E),C=await c($.node);if(D){R=y(D,m,C.sequenceLen),E.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,E.steps+=1,m-x[x.length-1].startBp>4*e+4*C.sequenceLen){E.end="bound";break}m+=C.sequenceLen,$=C.gbwt().lf($.offset)}if(R){E.pathHandle=R.pathHandle;let F=await p(R.pathHandle);for(let{index:_,startBp:D}of x){let C=this.paths[_];C.identity=R.orientation==="forward"?{pathHandle:R.pathHandle,name:F,orientation:"forward",hapStart:R.base+D,hapEnd:R.base+D+C.len}:{pathHandle:R.pathHandle,name:F,orientation:"reverse",hapStart:R.base-D-C.len,hapEnd:R.base-D}}}}this.dropTwins()}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((n,s)=>{let o=t.get(n);o?o.push(s):t.set(n,[s])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((n,s)=>{t.push(t[s]+this.record(n).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let n=this.refIndex(t),s=new Int32Array(e.length),o=new Int32Array(e.length),r=0,i=-1;for(let h=0;h<e.length;h++){let c=n.get(e[h]);if(c){let d=qn(c,i);if(d===void 0)return;s[r]=h,o[r]=d,r+=1,i=d}}return{pathAt:s,refAt:o,count:r}}pathLen(e){let t=0;for(let n of e)t+=this.record(n).sequenceLen;return t}prefixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[s]).sequence,c=this.record(t[o]).sequence;for(;r<h.length&&i<c.length;){if(h[r]!==c[i])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}suffixMatches(e,t){let n=0,s=0,o=0,r=0,i=0;for(;s<e.length&&o<t.length;){let h=this.record(e[e.length-s-1]).sequence,c=this.record(t[t.length-o-1]).sequence;for(;r<h.length&&i<c.length;){if(h[h.length-r-1]!==c[c.length-i-1])return n;r+=1,i+=1,n+=1}r===h.length&&(s+=1,r=0),i===c.length&&(o+=1,i=0)}return n}align(e,t,n){let s=this.pathLen(e),o=this.pathLen(t),r=this.prefixMatches(e,t),i=this.suffixMatches(e,t);r+i>s&&(i=s-r),r+i>o&&(i=o-r),K(n,"M",r),hn(n,s-r-i,o-r-i),K(n,"M",i)}sharedWeight(e,t){let n=this.refIndex(t),s=0;for(let o of e)n.has(o)&&(s+=this.record(o).sequenceLen);return s}editsAgainst(e,t){let n=this.orderedMatches(e,t);n?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let s=n??Fn(Ut(e,t,f=>this.record(f).sequenceLen)[0]),o=[],r=this.refPrefix(t),i=(f,p,y,g)=>{f===p?K(o,"D",r[g]-r[y]):y===g?K(o,"I",this.pathLen(e.slice(f,p))):this.align(e.slice(f,p),t.slice(y,g),o)},h=0,c=0,d=0;for(let f=0;f<s.count;f++){let p=s.pathAt[f],y=s.refAt[f];(c!==p||d!==y)&&i(c,p,d,y);let g=this.record(e[p]).sequenceLen;K(o,"M",g),h+=g,c=p+1,d=y+1}return i(c,e.length,d,t.length),{edits:o,matched:h,matches:s}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let n=this.paths[this.refId].path,s;if(Oe(n)&&(t.identity===void 0||!Oe(Be(t.path))))s={...this.editsAgainst(t.path,n),flipped:!1};else{let o=Be(t.path),r=this.sharedWeight(t.path,n);if(this.sharedWeight(o,n)===0)s={...this.editsAgainst(t.path,n),flipped:!1};else if(r===0)s={...this.editsAgainst(o,n),flipped:!0};else{let h=this.editsAgainst(t.path,n),c=this.editsAgainst(o,n);s=c.matched>h.matched?{...c,flipped:!0}:{...h,flipped:!1}}}return s}alignToRef(e){return this.settleDeferred(),this.alignment(e)?.edits.map(([t,n])=>`${n}${t}`).join("")}alignments(){this.settleDeferred();let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,n=this.refPrefix(t)[t.length],s=(d,f,p,y)=>{let g=Gn(d),l=this.paths[p[0]],b=this.paths[p[p.length-1]],x=l.identity,P=x?.orientation==="forward",[E,R]=P?[l,b]:[b,l];return{strand:f,refStart:e.start+g.leading,refEnd:e.start+n-g.trailing,edits:g.edits,weight:l.weight,path:p.flatMap(m=>this.paths[m].path),start:Ge(l,0),pieces:p,soloAligned:y,identity:x===void 0?void 0:{pathHandle:x.pathHandle,name:x.name,hapStart:x.name.fragment+E.identity.hapStart,hapEnd:x.name.fragment+R.identity.hapEnd,walkForward:P}}},o=d=>d.soloAligned.reduce((f,p)=>f+p,0),r=d=>d.pieces.reduce((f,p)=>f+this.paths[p].len,0),i=d=>2*o(d)>=r(d),h=d=>{let f=d[0],p=d[d.length-1],y=f.identity.walkForward;if(d.some((k,j)=>k.strand!==f.strand||k.identity.walkForward!==y||j>0&&k.identity.hapStart<d[j-1].identity.hapEnd))return;let g=y?d:[...d].reverse(),l=g.flatMap(k=>k.pieces),b=g.flatMap(k=>k.soloAligned),x=f.strand==="+"!==y,P=l.map(k=>this.paths[k]),E=P.slice(1).map((k,j)=>{let X=P[j].identity;return y?k.identity.hapStart-X.hapEnd:X.hapStart-k.identity.hapEnd}),R=x?[...P].reverse():P,m=x?[...E].reverse():E,I=R.flatMap(k=>x?Be(k.path):k.path),{edits:$}=this.editsAgainst(I,t),F=an($,R.map(k=>k.len)),_=new Map((x?[...l].reverse():l).map((k,j)=>[k,F[j]])),D=k=>2*k.pieces.reduce((j,X)=>j+_.get(X),0)>=o(k);if(!D(f)||!D(p))return;let C=[],H=0;return R.slice(0,-1).forEach((k,j)=>{H+=k.len,C.push([H,m[j]])}),s(Qn($,C),f.strand,l,b)},c=[];return this.paths.forEach((d,f)=>{if(f===this.refId)return;let{edits:p,flipped:y}=this.alignment(f),g=d.identity,l=g?g.orientation==="forward"!==y:!y;c.push(s(p,l?"+":"-",[f],an(p,[d.len])))}),jn(c,i,h).map(d=>{let{edits:f,identity:p,pieces:y,soloAligned:g,...l}=d,b={...l,cigar:Kn(f)};return p?{...b,resolved:!0,name:p.name,label:fe({...p.name,fragment:p.hapStart,end:p.hapEnd}),pathHandle:p.pathHandle,hapStart:p.hapStart,hapEnd:p.hapEnd}:{...b,resolved:!1}})}pairAlignments(e){let{target:t,query:n,...s}=e,o=this.paths.flatMap(d=>{let{identity:f}=d;return f?[{name:f.name,start:f.name.fragment+f.hapStart,steps:Ke(d,f)}]:[]}),r=d=>f=>f.sample===d.sample&&f.haplotype===d.haplotype,i=r(t),h=n?r(n):d=>!i(d),c=d=>this.record(ce(d,"forward")).sequence;return o.filter(d=>i(d.name)).flatMap(d=>o.filter(f=>h(f.name)).flatMap(f=>Wt({...s,query:f.steps,target:d.steps,sequenceOf:c}).map(p=>({query:f.name,queryStart:f.start+p.queryStart,queryEnd:f.start+p.queryEnd,strand:p.strand,target:d.name,targetStart:d.start+p.targetStart,targetEnd:d.start+p.targetEnd,cigar:Vt(p.edits),matches:p.edits.reduce((y,[g,l])=>y+(g==="="?l:0),0),columns:p.edits.reduce((y,[,g])=>y+g,0),sharedBases:p.sharedBases}))))}canonicalEdges(e){let t=[];for(let n of["forward","reverse"]){let s=ce(e,n);for(let o of this.record(s).successors())this.hasHandle(o)&&He(s,o)&&t.push([n==="reverse"?1:0,N(o),Q(o)?1:0])}return t.sort((n,s)=>n[0]-s[0]||n[1]-s[1]||n[2]-s[2]),t.filter((n,s)=>s===0||n[0]!==t[s-1][0]||n[1]!==t[s-1][1]||n[2]!==t[s-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let n of this.sortedHandles())if(!Q(n)){let s=N(n),o=`S ${s} ${this.record(n).sequence}
|
|
2
2
|
`;for(let[r,i,h]of this.canonicalEdges(s))o+=`L ${s} ${r?"-":"+"} ${i} ${h?"-":"+"}
|
|
3
3
|
`;t.push(e.encode(o))}return rn(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",...on(sn(await this.stableName(),await this.db.graphName()))],s=this.sortedHandles();for(let c of s)Q(c)||n.push(`S ${N(c)} ${this.record(c).sequence}`);let o=c=>Q(c)?"-":"+";for(let c of s)for(let d of this.record(c).successors())this.hasHandle(d)&&He(c,d)&&n.push(`L ${N(c)} ${o(c)} ${N(d)} ${o(d)} 0M`);let r=(c,d,f,p,y)=>{let g=Ke(c,d).map(x=>`${Q(x)?"<":">"}${N(x)}`).join(""),l=c.weight===void 0?"":` WT:i:${c.weight}`,b=y===void 0?"":` CG:Z:${y}`;return`W ${f.sample} ${f.haplotype} ${f.contig} ${f.fragment} ${p} ${g}${l}${b}`},i=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&n.push(r(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let h=1;return this.paths.forEach((c,d)=>{if(d!==this.refId){let f=e.names!=="anonymous"?c.identity:void 0,p=t?this.alignToRef(d):void 0;n.push(f?r(c,f,{...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd,p):r(c,void 0,{sample:"unknown",contig:i,haplotype:h,fragment:0},c.len,p)),h+=1}}),`${n.join(`
|
|
4
4
|
`)}
|
|
@@ -6,4 +6,4 @@ import{a as ce,b as N,c as Ee,d as Q,e as ee,f as Ft,g as Ue,h as We,i as qt,j a
|
|
|
6
6
|
`).filter(p=>p!=="")),n=(f,p)=>f.filter(y=>y.startsWith(`${p} `)),s=cs(t.flat()),o=0,r=t.map(f=>{let p=n(f,"W").map(hs),y=o;for(let g of p.filter(l=>l.fields[1]===is)){let l=+g.fields[2]+y;g.fields[2]=String(l),g.name=g.fields.slice(1,4).join(" "),o=Math.max(o,l)}return p}),h=[...Ot([...r.flatMap(f=>f.slice(0,1)),...r.flatMap(f=>f.slice(1))],f=>f.name).values()].flatMap(f=>fs(f,s,e)),c=new Set(t.flatMap(f=>n(f,"L")));for(let f of h)for(let p of ls(f))!c.has(p.forward)&&!c.has(p.reverse)&&c.add(p.forward);return`${[...new Set([...n(t[0],"H"),...t.flatMap(f=>n(f,"S")),...c,...h.map(f=>f.fields.join(" "))])].join(`
|
|
7
7
|
`)}
|
|
8
8
|
`}var In=class extends Error{constructor(a,e){super(e.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${a}" maps to none; set referenceSample`:`the anchor "${a}" is none of the graph's reference samples (${e.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`),this.name="NoReferenceSampleError"}},En=class extends Error{constructor(a,e,t){super(`this ${e.toLocaleString()} bp window reads more than nodeLimit (${a.toLocaleString()}) graph nodes; zoom in to about ${t.toLocaleString()} bp or raise nodeLimit`),this.fitsBp=t,this.name="NodeLimitError",this.regionTooLarge=!0}};function kn(a){return`${a.sample}#${a.haplotype}`}function ps(a,e){let t=kn(a);return e===void 0||e.some(n=>Bt(t,n))}async function us(a){return(await a.tag("gbwt_reference_samples")??"").split(/\s+/).filter(e=>e!=="")}function vn(a,e){let t=a.toLowerCase(),n=_t(a)?.toLowerCase();return e.find(s=>s===a)??e.find(s=>s.toLowerCase()===t)??e.find(s=>s.toLowerCase()===n)}function ws({configured:a,anchorPrefix:e,referenceSamples:t}){if(a!=="")return a;let n=vn(Ct(e),t)??(t.length===1?t[0]:void 0);if(n===void 0)throw new In(e,t);return n}async function gs(a,e,t){let n=(await a.paths()).find(s=>s.isIndexed&&s.name.sample===e&&s.name.contig===t);return n?{sample:n.name.sample,contig:t,haplotype:n.name.haplotype}:void 0}function Pn(a,e,t){if(a instanceof Error&&(a.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(a.message))){let s=a.walkedBp,o=typeof s=="number"&&s>0?Math.floor(s*.8):Math.floor(t/2);return new En(e,t,Math.max(o,1))}else return}var ms={context:1e3,snarls:"contained",limit:1e5};async function ys(a,e,t,n,s){return a.getSubgraphs({...s,path:e,start:t,end:n,haplotypes:"all"}).catch(o=>{throw Pn(o,s.limit,n-t)??o})}async function bs(a,e){let t=await a.paths();return Sn(await Promise.all(e.map(n=>n.toGFA())),(n,s,o,r)=>t.some(({name:i})=>i.sample===n&&i.haplotype===s&&i.contig===o&&i.fragment===r))}async function xs(a,e,t,n,s){if(!e)return"";let o=await ys(a,e,t,n,s);if(o.length===1)return An(o[0].toCompactSubgraph());let r=await bs(a,o);return r&&Tt(r)||r}function Ss(a,e){let t=1/0,n=-1/0;for(let i of a)t=Math.min(t,i),n=Math.max(n,i);let s=n-t+1,o=a.length>0&&s<=16*a.length?new Int32Array(s).fill(-1):void 0,r=new Map;return a.forEach((i,h)=>{o?o[i-t]=h:r.set(i,h)}),i=>{let h=N(i),c=o!==void 0&&h>=t&&h<=n,d=c?o[h-t]:r.get(h)??-1;return d>=0?d:(c?o[h-t]=e.length:r.set(h,e.length),e.push(String(h)),e.length-1)}}var Is=/^(.*)\[(\d+)-(\d+)\]$/;function An(a){let e=Array.from(a.nodeIds,String),t=Ss(a.nodeIds,e),n=a.nodeIds.length,s=a.edges.length/2,o=new Int32Array(s),r=new Int32Array(s),i=new Uint8Array(s);for(let l=0;l<s;l++){let b=a.edges[2*l],x=a.edges[2*l+1];o[l]=t(b),r[l]=t(x),i[l]=(Q(b)?1:0)|(Q(x)?2:0)}let h=a.paths.filter(l=>l.steps.length>0),c=new Int32Array(h.length+1);h.forEach((l,b)=>{c[b+1]=c[b]+l.steps.length});let d=new Int32Array(c[h.length]),f=new Uint8Array(d.length),p=new Float64Array(h.length),y=new Float64Array(h.length),g=h.map((l,b)=>{let x=Is.exec(l.name);p[b]=x?+x[2]:0,y[b]=x?+x[3]:-1;let P=c[b];for(let E of l.steps)d[P]=t(E),f[P++]=Q(E)?1:0;return x?x[1]:l.name});return{nodes:{names:e,lengths:Int32Array.from(a.nodeSequences,l=>l.length),refs:new Int32Array(n).fill(-1),starts:new Float64Array(n),ranks:new Int32Array(n),refNames:[]},links:{from:o,to:r,strands:i},walks:{names:g,starts:p,ends:y,offsets:c,steps:d,reversed:f}}}export{le as a,St as b,En as c,kn as d,ps as e,us as f,ws as g,gs as h,Pn as i,ms as j,xs as k};
|
|
9
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
//# sourceMappingURL=chunk-CNCYMJ5E.js.map
|