jbrowse-plugin-graphgenomeviewer 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +0,0 @@
1
- import"./chunk-LGKM2PZH.js";import{a as Pn}from"./chunk-D7XFR2IV.js";import{a as er,b as _n}from"./chunk-TN6FK5UD.js";import{a as Rn}from"./chunk-KWAXLUPQ.js";import{a as we}from"./chunk-J4OLMLS5.js";import{a as tr,d as Oe,e as ye,f as It}from"./chunk-F4C3BEPV.js";import{a as Cn,b as U}from"./chunk-FY3BTKY4.js";var mn=Cn((Ff,un)=>{un.exports=JBrowseExports["@jbrowse/core/util/installClearHoverOnSurfaceMove"]});function Y(o,e){return 2*o+(e==="reverse"?1:0)}function A(o){return Math.floor(o/2)}function ce(o){return o%2===0?"forward":"reverse"}function M(o){return o%2===1}function G(o){return o%2===0?o+1:o-1}function rr(o){return o==="left"?"right":"left"}function Le(o){return o==="forward"?"left":"right"}function Te(o){return o==="forward"?"right":"left"}function nr(o){return o==="left"?"forward":"reverse"}function or(o){return o==="right"?"forward":"reverse"}function le(o,e){let t=A(o),r=A(e);return M(o)?r>t||r===t&&!M(e):r>=t}function sr(o){return Me(o[0],o[o.length-1])}function Me(o,e){return o===void 0||e===void 0?!0:M(o)===M(e)?!M(o):le(o,e)}var be=class{offset=0;bytes;constructor(e){this.bytes=e}get done(){return this.offset>=this.bytes.length}byte(){let e=this.bytes[this.offset];if(e!==void 0)return this.offset+=1,e}int(){let e=1,t=0;for(;this.offset<this.bytes.length;){let r=this.bytes[this.offset];if(this.offset+=1,t+=(r&127)*e,e*=128,(r&128)===0)return t}}},ir=255,On=256,Ne=class{source;sigma;threshold;constructor(e,t){this.source=new be(e),this.sigma=t===0?Number.MAX_SAFE_INTEGER:t,this.threshold=this.sigma<ir?Math.floor(On/this.sigma):0}next(){if(this.sigma>=ir){let n=this.source.int(),s=this.source.int();return n===void 0||s===void 0?void 0:{value:n,len:s+1}}let e=this.source.byte();if(e===void 0)return;let t=e%this.sigma,r=Math.floor(e/this.sigma)+1;if(r===this.threshold){let n=this.source.int();if(n===void 0)return;r+=n}return{value:t,len:r}}*[Symbol.iterator](){for(let e=this.next();e!==void 0;e=this.next())yield e}};function ar(o){let e=new be(o),t=e.int();if(t===void 0||t===0)return[];let r=[],n=0;for(let s=0;s<t;s++){let i=e.int(),a=e.int();if(i===void 0||a===void 0)throw new Error("GBWT edge list ends early");n+=i,r.push({node:n,offset:a})}return r}var Fe=class{edges;bwt;constructor(e,t){this.edges=e,this.bwt=t}runs(){return new Ne(this.bwt,this.edges.length)}edge(e){let t=this.edges[e];if(t===void 0)throw new Error(`GBWT run refers to edge rank ${e} of ${this.edges.length}`);return t}lf(e){let t=this.edges.map(n=>n.offset),r=0;for(let n of this.runs()){let s=this.edge(n.value),i=t[n.value];if(r+n.len>e)return s.node===0?void 0:{node:s.node,offset:i+(e-r)};t[n.value]=i+n.len,r+=n.len}}edgeTo(e){let t=0,r=this.edges.length;for(;t<r;){let n=t+r>>1,s=this.edges[n];if(s.node===e)return n;s.node<e?t=n+1:r=n}}offsetTo(e){if(e.node===0)return;let t=this.edgeTo(e.node);if(t===void 0)return;let r=this.edges[t].offset;if(r>e.offset)return;let n=0;for(let s of this.runs())if(n+=s.len,s.value===t&&(r+=s.len,r>e.offset))return n-(r-e.offset)}predecessorAt(e){let t=this.edges.map(n=>({node:n.node===0?0:G(n.node),count:0}));for(let n of this.runs()){let s=t[n.value];s&&(s.count+=n.len)}for(let n=1;n<t.length;n++){let s=t[n-1],i=t[n];A(s.node)===A(i.node)&&(t[n-1]=i,t[n]=s)}let r=0;for(let n of t)if(r+=n.count,r>e)return n.node===0?void 0:n.node}decompressArrays(){let e=this.edges.map(i=>i.offset),t=0;for(let i of this.runs())t+=i.len;let r=new Int32Array(t),n=new Int32Array(t),s=0;for(let i of this.runs()){let a=this.edge(i.value),f=e[i.value];for(let c=0;c<i.len;c++)r[s]=a.node,n[s]=f,f+=1,s+=1;e[i.value]=f}return{nodes:r,offsets:n}}decompress(){let e=this.edges.map(r=>r.offset),t=[];for(let r of this.runs()){let n=this.edge(r.value);for(let s=0;s<r.len;s++)t.push({node:n.node,offset:e[r.value]}),e[r.value]=e[r.value]+1}return t}};var Ln=["","A","C","G","T","N"];function fr(o){let e=o[o.length-1];if(e===void 0)return 0;let t=e,r=0;for(let n=0;n<3&&t%6!==0;n++)t=Math.floor(t/6),r+=1;return 3*(o.length-1)+r}function cr(o){let e="";for(let t of o){let r=t;for(let n=0;n<3;n++){let s=Ln[r%6];if(s==="")return e;r=Math.floor(r/6),e+=s}}return e}function lr(o,e){let t=new Map;if(o!==void 0)for(let r of o.split(";")){let n=r.split(","),[s,i]=n;if(n.length!==2||!s||!i)throw new Error(`Invalid ${e} relationship: ${r}`);let a=t.get(s);a||(a=new Set,t.set(s,a)),a.add(i)}return t}function dr(o){return{name:o.get("pggname"),subgraph:lr(o.get("subgraph"),"subgraph"),translation:lr(o.get("translation"),"translation")}}function pr(o,e){for(let[t,r]of e){let n=o.get(t);n||(n=new Set,o.set(t,n));for(let s of r)n.add(s)}}function ur(o,e){let t={name:o,subgraph:new Map,translation:new Map};return e.name!==void 0&&(t.subgraph.set(o,new Set([e.name])),pr(t.subgraph,e.subgraph),pr(t.translation,e.translation)),t}function hr(o){return[...o.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0).flatMap(([e,t])=>[...t].sort().map(r=>[e,r]))}function mr(o){let e=[];o.name!==void 0&&e.push(`H NM:Z:${o.name}`);for(let[t,r]of hr(o.subgraph))e.push(`H SG:Z:${t},${r}`);for(let[t,r]of hr(o.translation))e.push(`H TL:Z:${t},${r}`);return e}async function gr(o){let e=o.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of o)t.set(s,r),r+=s.length;let n=await globalThis.crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")}var Tn="_gbwt_ref";function $(o,e){return`${o.sample}#${o.haplotype}#${o.contig}[${o.fragment}-${e}]`}var Mn=/^([^#]+)#(\d+)#([^#]+?)(?:\[\d+-\d+\])?$/,Nn=/^([^#]+?)(?:\[\d+-\d+\])?$/;function Fn(o){let e=Mn.exec(o);if(e)return{sample:e[1],haplotype:Number(e[2]),contig:e[3]};let t=Nn.exec(o);if(t)return{contig:t[1]};throw new Error(`"${o}" is not a path name; expected "sample#haplotype#contig" or a bare contig`)}function xr(o){return typeof o=="string"?Fn(o):o}function Se(o,e){return{sample:o.sample??Tn,contig:o.contig,haplotype:o.haplotype??0,fragment:e}}function He(o,e){let t=0,r=o.length;for(;t<r;){let n=t+r>>1;o[n]<e?t=n+1:r=n}return t}var $e=class{ending;tree;constructor(e){this.ending=new Float64Array(e),this.tree=new Int32Array(e+1).fill(-1)}bestBefore(e){let t=-1;for(let r=e;r>0;r-=r&-r){let n=this.tree[r];n!==-1&&(t===-1||this.ending[n]>this.ending[t])&&(t=n)}return t}raise(e,t){this.ending[e]=t;for(let r=e+1;r<this.tree.length;r+=r&-r){let n=this.tree[r];(n===-1||t>this.ending[n])&&(this.tree[r]=e)}}},At=class{pairs=[];total=0;a;b;weight;occurrences=new Map;constructor(e,t,r){this.a=e,this.b=t,this.weight=r,t.forEach((n,s)=>{let i=this.occurrences.get(n);i?i.push(s):this.occurrences.set(n,[s])})}solve(e,t,r,n){let s=0;for(;e+s<t&&r+s<n&&this.a[e+s]===this.b[r+s];)this.match(e+s,r+s),s+=1;let i=0;for(;t-i>e+s&&n-i>r+s&&this.a[t-i-1]===this.b[n-i-1];)i+=1;this.solveMiddle(e+s,t-i,r+s,n-i);for(let a=i;a>0;a--)this.match(t-a,n-a)}match(e,t){this.pairs.push([e,t]),this.total+=this.weight(this.a[e])}solveMiddle(e,t,r,n){if(e===t||r===n)return;let s=this.matchCount(e,t,r,n);if(s===0)return;if(s<=t-e+(n-r)){this.chain(e,t,r,n,s);return}let i=e+t>>1,a=this.split(e,i,t,r,n);this.solve(e,i,r,a),this.solve(i,t,a,n)}matchCount(e,t,r,n){let s=0;for(let i=e;i<t;i++){let a=this.occurrences.get(this.a[i]);a&&(s+=He(a,n)-He(a,r))}return s}sweep(e,t,r,n,s,i,a){for(let f=e;f!==t;f+=r){let c=this.occurrences.get(this.a[f]);if(!c)continue;let l=this.weight(this.a[f]),p=He(c,n),u=He(c,s);for(let h=0;h<u-p;h++){let d=r===1?c[u-1-h]-n:s-1-c[p+h],m=i.bestBefore(d),x=(m===-1?0:i.ending[m])+l;if(x>i.ending[d]&&(i.raise(d,x),a)){let w=a.count++;a.row[w]=f,a.column[w]=d,a.previous[w]=m===-1?-1:a.endingMatch[m],a.endingMatch[d]=w}}}}chain(e,t,r,n,s){let i=new $e(n-r),a={row:new Int32Array(s),column:new Int32Array(s),previous:new Int32Array(s),endingMatch:new Int32Array(n-r),count:0};this.sweep(e,t,1,r,n,i,a);let f=i.bestBefore(n-r);if(f===-1)return;this.total+=i.ending[f];let c=[];for(let l=a.endingMatch[f];l!==-1;l=a.previous[l])c.push([a.row[l],r+a.column[l]]);for(let l=c.length-1;l>=0;l--)this.pairs.push(c[l])}frontier(e,t,r,n,s){let i=new $e(s-n);this.sweep(e,t,r,n,s,i);let a=new Float64Array(s-n+1);for(let f=0;f<s-n;f++)a[f+1]=Math.max(a[f],i.ending[f]);return a}split(e,t,r,n,s){let i=s-n,a=this.frontier(e,t,1,n,s),f=this.frontier(r-1,t-1,-1,n,s),c=0,l=-1;for(let p=0;p<=i;p++){let u=a[p]+f[i-p];u>l&&(l=u,c=p)}return n+c}};function wr(o,e,t){let r=new At(o,e,t);return r.solve(0,o.length,0,e.length),[r.pairs,r.total]}var V=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 Et(o,e){return o[0]<e[0]||o[0]===e[0]&&(o[1]<e[1]||o[1]===e[1]&&o[2]<e[2])}var ve=class{heap=[];push(e,t,r){let n=this.heap;n.push([e,t,r]);let s=n.length-1;for(;s>0;){let i=s-1>>1;if(Et(n[s],n[i]))[n[s],n[i]]=[n[i],n[s]],s=i;else break}}pop(){let e=this.heap,t=e[0],r=e.pop();if(e.length>0&&r!==void 0){e[0]=r;let n=0;for(;;){let s=2*n+1,i=s+1,a=n;if(s<e.length&&Et(e[s],e[a])&&(a=s),i<e.length&&Et(e[i],e[a])&&(a=i),a===n)break;[e[n],e[a]]=[e[a],e[n]],n=a}}return t}get size(){return this.heap.length}};function Hn(o){let e=new Int32Array(o.length),t=new Int32Array(o.length);return o.forEach(([r,n],s)=>{e[s]=r,t[s]=n}),{pathAt:e,refAt:t,count:o.length}}function $n(o,e){let t=0,r=o.length;for(;t<r;){let n=t+r>>1;o[n]>e?r=n:t=n+1}return o[t]}function re(o){return`${o.node}:${o.offset}`}function Bn(o,e){let t=e.identity.hapStart-o.identity.hapEnd,r=o.strand==="+"?e.refStart-o.refEnd:o.refStart-e.refEnd;return o.strand===e.strand&&t>=0&&r>=0?{insertion:t,deletion:r}:void 0}function Gn(o,e,t){let[r,n]=o.strand==="+"?[o,e]:[e,o],s=r.edits.map(([c,l])=>[c,l]);br(s,t.insertion,t.deletion);for(let[c,l]of n.edits)D(s,c,l);let i=o.identity.walkForward,[a,f]=i?[o,e]:[e,o];return{strand:o.strand,refStart:r.refStart,refEnd:n.refEnd,edits:s,weight:void 0,path:[...a.path,...f.path],start:a.start,identity:{pathHandle:o.identity.pathHandle,name:o.identity.name,hapStart:o.identity.hapStart,hapEnd:e.identity.hapEnd,walkForward:i}}}function Dn(o){if(o.some(n=>n.weight!==void 0))return o;let e=new Map;o.forEach((n,s)=>{if(n.identity){let i=e.get(n.identity.pathHandle);i?i.push(s):e.set(n.identity.pathHandle,[s])}});let t=new Map,r=new Set;for(let n of e.values()){n.sort((a,f)=>o[a].identity.hapStart-o[f].identity.hapStart);let s=n[0],i=o[s];for(let a of n.slice(1)){let f=o[a],c=Bn(i,f);c?(i=Gn(i,f,c),r.add(a)):(t.set(s,i),s=a,i=f)}t.set(s,i)}return o.flatMap((n,s)=>r.has(s)?[]:[t.get(s)??n])}function Be(o,e){return{node:o.path[e],offset:o.offsets[e]}}var zn=4096;function yr(o){let e=[];for(let t of o){let r=e[e.length-1];r&&t-r[1]<=zn?r[1]=t:e.push([t,t])}return e}var jn=32768,qn=65536;function Wn(o){let e=[...o].sort((r,n)=>r-n),t=[];for(let r of e){let n=t[t.length-1];n&&r-n[1]<=jn?n[1]=r:t.push([r,r])}return t}var Ie=class{records=new Map;paths=[];twinStarts=new Set;refId;refPath;refHandle;refInterval;refIndexCache;refPrefixCache;walkedBp;stats={orderedAlignments:0,lcsAlignments:0,identificationSteps:0,identificationFetches:0,identification:{interval:0,scans:[],windowSamples:0,fragmentLengths:[],companionSeeks:0,companionMisses:0,graphLookups:0,graphFetches:0,chains:[]},anchorWalk:void 0};db;limit;signal;constructor(e,t={}){this.db=e,this.limit=t.limit,this.signal=t.signal}get nodeCount(){return this.records.size/2}get pathCount(){return 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(Y(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 V(this.limit);let t=await this.db.getRecord(Y(e,"forward")),r=await this.db.getRecord(Y(e,"reverse"));if(!t||!r)throw new Error(`Node ${e} does not exist in the graph`);this.records.set(t.handle,t),this.records.set(r.handle,r)}async ensureNode(e){this.hasNode(e)||await this.addNode(e)}clearPaths(){this.paths=[],this.twinStarts.clear(),this.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 ${$(e,e.fragment)}`);if(!t.isIndexed)throw new Error(`Path ${$(t.name,t.name.fragment)} has not been indexed for random access`);let r=e.fragment-t.name.fragment,n=await this.db.indexedPosition(t.handle,r);if(!n)throw new Error(`Path ${$(t.name,t.name.fragment)} has not been indexed for random access`);return this.findPathPosition(t,r,n.pathOffset,n.pos)}async findPathPosition(e,t,r,n){let s=r,i=n;for(;;){await this.ensureNode(A(i.node));let a=this.record(i.node);if(s+a.sequenceLen>t)return{position:{seqOffset:t,handle:i.node,nodeOffset:t-s,gbwtOffset:i.offset},name:e.name,handle:e.handle};s+=a.sequenceLen;let f=a.gbwt().lf(i.offset);if(!f)throw new Error(`Path ${$(e.name,e.name.fragment)} does not contain offset ${t}`);i=f}}async aroundPosition(e,t,r){let n=A(e);await this.ensureNode(n);let s=this.record(e),i=ce(e),a=new ve;return a.push(t,n,Le(i)),a.push(s.sequenceLen-t-1,n,Te(i)),this.insertContext(a,r)}prefetchReferenceWalk(e,t){return this.prefetchReferenceRange(e.handle,e.position.seqOffset,e.position.seqOffset+t)}async prefetchReferenceRange(e,t,r){let[n,s]=await Promise.all([this.db.indexedPosition(e,t),this.db.indexedPosition(e,r)]);if(n&&s){let i=n.pos.node,a=s.pos.node;if(!await this.db.prefetchRecords(Math.min(i,a),Math.max(i,a)+1)){let c=await this.db.indexedPositionsBetween(e,t,r),l=Wn(c.map(p=>p.pos.node));await Promise.all(l.map(([p,u])=>this.db.prefetchRecords(p,u+2)))}}return n}async aroundInterval(e,t,r){if(t===0)throw new Error("Interval length must be greater than 0");this.walkedBp=0;try{return await this.walkInterval(e,t,r)}catch(n){throw n instanceof V&&n.windowBp===void 0?new V(n.limit,{windowBp:t,walkedBp:this.walkedBp}):n}}get referenceWalkedBp(){return this.walkedBp}async walkInterval(e,t,r){let n={node:e.handle,offset:e.gbwtOffset},s=e.nodeOffset,i=t,a=new ve;for(;;){let f=A(n.node),c=ce(n.node);this.walkedBp=t-i,await this.ensureNode(f);let l=this.record(n.node);if(s>=l.sequenceLen)throw new Error(`Offset ${s} in node ${f} of length ${l.sequenceLen}`);a.push(s,f,Le(c));let p=l.sequenceLen-s;if(i<=p){a.push(i===p?0:p-i-1,f,Te(c));break}a.push(0,f,Te(c));let u=l.gbwt().lf(n.offset);if(!u)throw new Error(`No successor for GBWT position (${n.node}, ${n.offset})`);n=u,s=0,i-=p}return this.walkedBp=t,this.insertContext(a,r)}async aroundNodes(e,t){let r=new ve;for(let n of e)await this.ensureNode(n),r.push(0,n,"left"),r.push(0,n,"right");return this.insertContext(r,t)}async insertContext(e,t){this.clearPaths();let r=new Set,n=new Set;for(let i of this.records.keys())n.add(A(i));let s=0;for(;e.size>0;){let[i,a,f]=e.pop(),c=`${a}:${f}`;if(r.has(c))continue;r.add(c),n.delete(a),this.hasNode(a)||(await this.addNode(a),s+=1);let l=rr(f);if(!r.has(`${a}:${l}`)){let h=this.record(Y(a,nr(f))),d=i+h.sequenceLen-1;d<=t&&e.push(d,a,l)}let p=this.record(Y(a,or(f))),u=i+1;if(u<=t)for(let h of p.successors()){let d=A(h),m=Le(ce(h));r.has(`${d}:${m}`)||e.push(u,d,m)}}for(let i of n)this.records.delete(Y(i,"forward")),this.records.delete(Y(i,"reverse"));return{inserted:s,removed:n.size}}async betweenNodes(e,t){this.clearPaths();let r=[e,G(t)],n=new Set([A(e),A(t)]),s=0;for(;r.length>0;){let i=r.pop(),a=A(i);this.hasNode(a)||(await this.addNode(a),s+=1);for(let f of this.record(i).successors()){let c=A(f);n.has(c)||(r.push(f,G(f)),n.add(c))}}return s}async extractSnarls(e){let t=0;for(let[r,n]of await this.overlappingSnarls(e))t+=await this.betweenNodes(r,n);return t}async overlappingSnarls(e){let t=[];if(e!=="none"){let r=!1;for(let n of this.sortedHandles()){let s=this.record(n),i=s.next;i!==void 0&&(r=!0,this.hasHandle(i)?le(n,i)&&t.push([n,i]):e==="overlapping"&&this.isSnarlEntryInSubgraph(s)&&t.push([n,i]))}if(!r&&e==="overlapping"&&await this.db.hasChainLinks()){let n=await this.findCoveringSnarl();n&&t.push(n)}}return t}isSnarlEntryInSubgraph(e){let t=e.successors(),r=t.find(n=>this.hasHandle(n));return r===void 0?!1:t.length>1||this.record(G(r)).successors().length>1}recordReader(e){let t=new Map;return async r=>{let n=this.records.get(r);if(n)return n;let s=t.get(r);if(!s){if(s=await this.db.getRecord(r),e?.(),!s)throw new Error(`Node record ${r} is missing from the database`);t.set(r,s)}return s}}async findCoveringSnarl(){let e=this.recordReader(),t=async f=>{let c=f.successors(),l=c[0];return l===void 0?!1:c.length>1||(await e(G(l))).successors().length>1},r=async f=>{let c=await e(G(f));return c.next!==void 0?await t(c)?{kind:"snarl-exit",snarl:[G(f),c.next]}:{kind:"chain"}:(await e(f)).next!==void 0?{kind:"chain"}:{kind:"regular"}},n=new Set,s=this.sortedHandles().flatMap(f=>this.record(f).successors()),i,a=!1;for(;!a&&s.length>0;){let f=s.shift(),c=A(f);if(!this.hasHandle(f)&&!n.has(c)){n.add(c);let l=await r(f);if(l.kind==="snarl-exit")i=l.snarl,a=!0;else if(l.kind==="chain")a=!0;else for(let p of["forward","reverse"])s.push(...(await e(Y(c,p))).successors())}}return i}extractPaths(e,t){if(this.clearPaths(),t==="none")return;let r=e?.position;this.refPath=e?.name,this.refHandle=e?.handle;let n=this.sortedHandles(),s=n.length,i=new Map;n.forEach((g,b)=>i.set(g,b));let a=new Int32Array(s+1),f=new Int32Array(s),c=[];for(let g=0;g<s;g++){let b=this.record(n[g]),E=b.gbwt().decompressArrays();f[g]=b.sequenceLen,c.push(E),a[g+1]=a[g]+E.nodes.length}let l=a[s],p=new Int32Array(l),u=new Int32Array(l),h=new Uint8Array(l);for(let g=0;g<s;g++){let b=c[g];p.set(b.nodes,a[g]),u.set(b.offsets,a[g])}c.length=0;for(let g=0;g<l;g++){let b=i.get(p[g]);b===void 0?p[g]=-1:(p[g]=b,h[a[b]+u[g]]=1)}let d=r===void 0?void 0:i.get(r.handle),m=r?.gbwtOffset,x,w=(g,b,E)=>{let I=[],C=0,_=0,v=-1,O=g,L=b;for(;;){O===d&&L===m&&(v=C),E&&(E.push(n[O]),I.push(L)),C+=1,_+=f[O];let N=a[O]+L,F=p[N];if(F<0)break;L=u[N],O=F}return{offsets:I,len:_,refAt:v,last:O}},y=(g,b,E,I)=>{I>=0&&(this.refId=this.paths.length,x=I),this.paths.push({path:g,offsets:b,len:E,weight:void 0,identity:void 0})},S=new Int32Array(s),R=d!==void 0&&M(n[d]);for(let g=0;g<s;g++){let b=n[g];if(!M(b)){let E=a[g],I=a[g+1]-E;for(let C=0;C<I;C++)if(h[E+C]===0){let _=[],{offsets:v,len:O,refAt:L,last:N}=w(g,C,_),F=n[N];if(L>=0||Me(b,F)){if(y(_,v,O,L),!M(F)){let H=i.get(G(F));S[H]=S[H]+1}}else this.twinStarts.add(re({node:b,offset:C}))}}}for(let g=0;g<s;g++){let b=n[g];if(M(b)){let E=a[g],I=a[g+1]-E,C=0;for(let v=0;v<I;v++)h[E+v]===0&&(C+=1);let _=!R&&C===S[g];for(let v=0;v<I;v++)if(h[E+v]===0){let O=_?void 0:w(g,v,void 0);if(O&&(O.refAt>=0||Me(b,n[O.last]))){let L=[],{offsets:N,len:F,refAt:H}=w(g,v,L);y(L,N,F,H)}else this.twinStarts.add(re({node:b,offset:v}))}}}if(r){if(x===void 0||this.refId===void 0)throw this.clearPaths(),new Error("Could not find the reference path");let g=this.paths[this.refId],b=r.nodeOffset;for(let I of g.path.slice(0,x))b+=this.record(I).sequenceLen;let E=r.seqOffset-b;this.refInterval=[E,E+g.len],g.identity={pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:E,hapEnd:E+g.len}}if(t==="distinct")this.distinctPaths();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(){let e=this.refId===void 0?void 0:this.paths[this.refId].path;this.paths.sort((n,s)=>Ct(n.path,s.path)||n.len-s.len);let t=[],r;for(let n of this.paths){let s=t[t.length-1];s&&Ct(s.path,n.path)===0?s.weight=(s.weight??0)+1:(e&&Ct(n.path,e)===0&&(r=t.length),t.push({...n,weight:1}))}this.paths=t,this.refId=r}keepHaplotypes(e){let t=this.refId===void 0?void 0:this.paths[this.refId],r=this.paths.filter((s,i)=>i===this.refId||s.identity!==void 0&&e(s.identity.name)),n=new Set;for(let s of r)for(let i of s.path)n.add(A(i));for(let s of[...this.records.keys()])n.has(A(s))||this.records.delete(s);this.paths=r,this.refId=t===void 0?void 0:r.indexOf(t)}async walkHaplotypesFromAnchor(e,t,r,n,s){let i=e.position.seqOffset,a=i+t,f=Math.floor(i/r)*r,c=Math.min(r,qn),l=4*(r+t)+c,p={spacing:r,anchorOffset:f,anchorNodeOffset:-1,anchorHandle:-1,referenceSteps:0,rows:0,walks:[],graphFetches:0,scans:[],scanRows:0,fallback:void 0,ms:{reference:0,rows:0,walks:0,scan:0,sampled:0}};this.stats.anchorWalk=p;let u=performance.now(),h=()=>{let k=performance.now(),j=k-u;return u=k,j};this.clearPaths(),this.records.clear();let d=this.recordReader(()=>{p.graphFetches+=1}),m=await this.db.haplotypeAnchor(e.handle,f);if(m===void 0)throw new Error(`The haplotype index names no anchor for ${$(e.name,e.name.fragment)} at offset ${f}; it was not built with anchors at ${r} bp for this graph`);p.anchorNodeOffset=m.pathOffset;let x=await this.prefetchReferenceRange(e.handle,m.pathOffset,a+c);if(!x)throw new Error(`Path ${$(e.name,e.name.fragment)} has not been indexed for random access`);let w=await this.walkReference(d,x,m,i,a,a+c),{anchor:y,refOffsetOf:S,refHandles:R,windowSteps:g}=w;p.anchorHandle=y.pos.node,p.referenceSteps=w.steps,this.walkedBp=t;let b=[],E=[],I=0;for(let k of g)await this.ensureNode(A(k.pos.node)),b.push(k.pos.node),E.push(k.pos.offset),I+=this.record(k.pos.node).sequenceLen;let C=g[0];if(C===void 0)throw new Error("The reference walk has no node in the window");this.refPath=e.name,this.refHandle=e.handle,this.refInterval=[C.refOffset,C.refOffset+I],this.refId=0,this.paths.push({path:b,offsets:E,len:I,weight:void 0,identity:{pathHandle:e.handle,name:e.name,orientation:"forward",hapStart:C.refOffset,hapEnd:C.refOffset+I}}),p.ms.reference=h();let _=await this.db.haplotypeSamplesAtNode(y.pos.node);p.rows=_.length,p.ms.rows=h();let v=_.find(k=>k.offset===y.pos.offset&&k.pathHandle===e.handle&&k.pathOffset===y.offset);if(v===void 0)throw new Error(`The haplotype index has no anchor row for ${$(e.name,e.name.fragment)} at offset ${y.offset} (node ${A(y.pos.node)}); it was not built with anchors at ${r} bp for this graph`);let O=await this.db.pathsByHandle(),L=k=>{let j=O.get(k);if(!j)throw new Error(`Path ${k} is missing from the database`);return j.name},N=new Set([e.handle]),F=new Map;for(let k of _)if(k!==v&&n(L(k.pathHandle))){let j=F.get(k.pathHandle);j?j.push(k):F.set(k.pathHandle,[k])}let H;for(let[k,j]of F)if(H===void 0){let ae=te=>Math.abs(te.offset-v.offset);j.sort((te,En)=>ae(te)-ae(En));let fe;for(let te of j)N.has(k)||(fe=await this.walkAndKeep(d,te,"anchor",L(k),S,a,l,s,N,p));N.has(k)||(H=fe)}p.ms.walks=h();let xe=H===void 0?await this.samplesOfUnwalkedContigs(b,S,R,n,N,L,p):new Map;if(p.ms.scan=h(),xe.size>0){await this.mapReferenceBefore(d,e.handle,Math.max(0,m.pathOffset-2*r),m.pathOffset,S,R);for(let[k,j]of xe)if(H===void 0){let ae=L(k),fe;for(let te of j)fe??=await this.entryBefore(d,te,S,R,this.refInterval[0],l);H=fe===void 0?`no sample of ${$(ae,ae.fragment)} on the window's nodes runs with the reference`:await this.walkAndKeep(d,fe,"sample",ae,S,a,l,s,N,p)}p.ms.sampled=h()}return p.fallback=H,H}async walkAndKeep(e,t,r,n,s,i,a,f,c,l){let p=await this.walkFromRow(e,t,n,s,this.refInterval[0],i,a,f);l.walks.push({pathHandle:t.pathHandle,from:r,steps:p.steps,pieces:p.infos.length,end:p.end});let u;return p.end==="bound"?u=`${$(n,t.pathOffset)} walked ${p.steps} steps from its ${r} without reaching the window's end (${p.end})`:(c.add(t.pathHandle),this.paths.push(...p.infos)),u}async mapReferenceBefore(e,t,r,n,s,i){let a=await this.prefetchReferenceRange(t,r,n),f=a?.pos,c=a?.pathOffset??n;for(;f!==void 0&&f.node!==0&&c<n;){this.signal?.throwIfAborted();let l=await e(f.node),p=A(f.node);s.has(p)||(s.set(p,c),i.add(f.node)),c+=l.sequenceLen,f=l.gbwt().lf(f.offset)}}async runsWithReference(e,t,r,n,s){let i={node:t.node,offset:t.offset},a=0,f;for(;f===void 0;)if(this.signal?.throwIfAborted(),i===void 0||i.node===0||a>s)f=!1;else if(r.has(A(i.node)))f=n.has(i.node);else{let c=await e(i.node);a+=c.sequenceLen,i=c.gbwt().lf(i.offset)}return f}async entryBefore(e,t,r,n,s,i){let a=(await e(t.node)).sequenceLen,f=async(h,d)=>{let m=(await e(h.node)).sequenceLen;return{node:h.node,offset:h.offset,pathHandle:t.pathHandle,orientation:t.orientation,pathOffset:t.orientation==="forward"?t.pathOffset-d:t.pathOffset+a+d-m}},c={node:t.node,offset:t.offset},l=0,p,u=!await this.runsWithReference(e,t,r,n,i);for(;!u;){this.signal?.throwIfAborted();let h=r.get(A(c.node));if(h!==void 0&&h<s)p=await f(c,l),u=!0;else if(l>i)p={...t},u=!0;else{let m=(await e(G(c.node))).gbwt().predecessorAt(c.offset);if(m===void 0)p=await f(c,l),u=!0;else{let x=await e(m),w=x.gbwt().offsetTo(c);if(w===void 0)throw new Error(`No offset in ${m} leads to ${c.node}:${c.offset}`);c={node:m,offset:w},l+=x.sequenceLen}}}return p}async walkReference(e,t,r,n,s,i){let a=new Map,f=new Set,c=[],l,p=t.pos,u=t.pathOffset,h=0;for(;p!==void 0&&p.node!==0&&u<i;){this.signal?.throwIfAborted();let d=await e(p.node),m=u+d.sequenceLen;if(l===void 0&&u===r.pathOffset){if(p.node!==r.node)throw new Error(`The reference walk reaches node ${A(p.node)} at offset ${u} where the haplotype index names node ${A(r.node)} as the anchor`);l={pos:p,offset:u}}if(l!==void 0){h+=1;let x=A(p.node);a.has(x)||(a.set(x,u),f.add(p.node)),u<s&&m>n&&c.push({pos:p,refOffset:u})}u=m,p=d.gbwt().lf(p.offset)}if(l===void 0)throw new Error(`The reference walk from offset ${t.pathOffset} never starts a node at the anchor offset ${r.pathOffset}`);return{anchor:l,refOffsetOf:a,refHandles:f,windowSteps:c,steps:h}}async walkFromRow(e,t,r,n,s,i,a,f){let c=(await e(t.node)).sequenceLen,l=t.orientation==="forward"?t.pathOffset:t.pathOffset+c,p=[],u=[],h=[],d=0,m=0,x=0,w,y,S={node:t.node,offset:t.offset};for(;y===void 0;)if(this.signal?.throwIfAborted(),S===void 0||S.node===0)y=w===void 0?"before the window":"ended in the window";else if(m>a)y="bound";else{let g=n.get(A(S.node)),b=w!==void 0;if(g!==void 0&&g>=i)y=b?"through the window":"past the window";else{!b&&g!==void 0&&g>=s&&(w=m);let E=await e(S.node);if(w!==void 0){let I={pos:S,at:m,len:E.sequenceLen};g===void 0?(h.push(I),d+=I.len):(d>f&&g<s?(p.push(u),u=[]):u.push(...h),h=[],d=0,u.push(I))}x+=1,m+=E.sequenceLen,S=E.gbwt().lf(S.offset)}}p.push(u);let R=[];for(let g of p){let b=g[0],E=g[g.length-1];if(b!==void 0&&E!==void 0){let I=[],C=[],_=0;for(let L of g)await this.ensureNode(A(L.pos.node)),I.push(L.pos.node),C.push(L.pos.offset),_+=L.len;let v=b.at,O=E.at+E.len;R.push({path:I,offsets:C,len:_,weight:void 0,identity:t.orientation==="forward"?{pathHandle:t.pathHandle,name:r,orientation:"forward",hapStart:l+v,hapEnd:l+O}:{pathHandle:t.pathHandle,name:r,orientation:"reverse",hapStart:l-O,hapEnd:l-v}})}}return{steps:x,end:y,infos:R}}async samplesOfUnwalkedContigs(e,t,r,n,s,i,a){let f=yr([...e].sort((l,p)=>l-p));a.scans=f;let c=new Map;for(let[l,p]of f){let u=await this.db.haplotypeSamplesInRange(l,p);a.scanRows+=u.length;for(let h of u){let d=t.has(A(h.node));if(!s.has(h.pathHandle)&&(!d||r.has(h.node))&&n(i(h.pathHandle))){let m=c.get(h.pathHandle)??[];d?m.unshift(h):m.push(h),c.set(h.pathHandle,m)}}}return c}async identifyPaths(){if(!this.db.hasHaplotypeIndex)throw new Error("The database has no HaplotypeSamples table; run gbz-haplotype-index on it");let e=await this.db.haplotypeSampleInterval()??4096,t=yr(this.sortedHandles());if(t.length===0)return;let r=new Map;for(let[d,m]of t)for(let x of await this.db.haplotypeSamplesInRange(d,m))r.set(re(x),x);let n=d=>{let m=0,x=t.length-1;for(;m<x;){let y=m+x+1>>1;t[y][0]<=d?m=y:x=y-1}let w=t[m];return w[0]<=d&&d<=w[1]},s=new Map;this.paths.forEach((d,m)=>{d.path.length>0&&m!==this.refId&&s.set(re(Be(d,0)),m)});let i=this.stats.identification;i.interval=e,i.scans=t,i.windowSamples=r.size,this.paths.forEach((d,m)=>{m!==this.refId&&i.fragmentLengths.push(d.len)});let a=this.recordReader(()=>{this.stats.identificationFetches+=1,i.graphFetches+=1}),f=d=>(i.graphLookups+=1,a(d)),c=async(d,m)=>{if(n(d.node))return r.get(re(d));this.stats.identificationFetches+=1,i.companionSeeks+=1,m.seeks+=1;let x=await this.db.haplotypeSampleAt(d.node,d.offset);return x||(i.companionMisses+=1),x},l=new Map,p=async d=>{let m=l.get(d);if(!m){let x=await this.db.getPath(d);if(!x)throw new Error(`Path ${d} is missing from the database`);m=x.name,l.set(d,m)}return m},u=(d,m,x)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.pathOffset-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.pathOffset+m+x},h=(d,m)=>d.orientation==="forward"?{pathHandle:d.pathHandle,orientation:"forward",base:d.hapStart-m}:{pathHandle:d.pathHandle,orientation:"reverse",base:d.hapEnd+m};for(let d=0;d<this.paths.length;d++){let m=this.paths[d];if(d===this.refId||m.identity)continue;let x=[],w=new Set,y={fragments:0,steps:0,seeks:0,reentries:0,twinLandings:0,end:"endmarker",pathHandle:void 0};i.chains.push(y);let S,R=0,g=d,b;for(;S===void 0;){if(this.signal?.throwIfAborted(),g!==void 0){if(w.has(g)){y.end="cycle";break}w.add(g);let v=this.paths[g];x.push({index:g,startBp:R}),y.fragments+=1;let O=R;for(let N=0;N<v.path.length;N++){let F=Be(v,N),H=r.get(re(F)),xe=this.record(F.node).sequenceLen;if(H){S=u(H,O,xe);break}O+=xe}if(R+=v.len,S){y.end="in-fragment sample";break}let L=Be(v,v.path.length-1);b=this.record(L.node).gbwt().lf(L.offset),g=void 0}if(b===void 0||b.node===0){y.end="endmarker";break}let E=re(b),I=s.get(E);if(I!==void 0){let v=this.paths[I].identity;if(v){S=h(v,R),y.end="identified sibling";break}g=I;continue}this.records.has(b.node)&&(y.reentries+=1),this.twinStarts.has(E)&&(y.twinLandings+=1);let C=await c(b,y),_=await f(b.node);if(C){S=u(C,R,_.sequenceLen),y.end="out-of-window sample";break}if(this.stats.identificationSteps+=1,y.steps+=1,R-x[x.length-1].startBp>4*e+4*_.sequenceLen){y.end="bound";break}R+=_.sequenceLen,b=_.gbwt().lf(b.offset)}if(S){y.pathHandle=S.pathHandle;let E=await p(S.pathHandle);for(let{index:I,startBp:C}of x){let _=this.paths[I];_.identity=S.orientation==="forward"?{pathHandle:S.pathHandle,name:E,orientation:"forward",hapStart:S.base+C,hapEnd:S.base+C+_.len}:{pathHandle:S.pathHandle,name:E,orientation:"reverse",hapStart:S.base-C-_.len,hapEnd:S.base-C}}}}}refIndex(e){if(this.refIndexCache===void 0){let t=new Map;e.forEach((r,n)=>{let s=t.get(r);s?s.push(n):t.set(r,[n])}),this.refIndexCache=t}return this.refIndexCache}refPrefix(e){if(this.refPrefixCache===void 0){let t=[0];e.forEach((r,n)=>{t.push(t[n]+this.record(r).sequenceLen)}),this.refPrefixCache=t}return this.refPrefixCache}orderedMatches(e,t){let r=this.refIndex(t),n=new Int32Array(e.length),s=new Int32Array(e.length),i=0,a=-1;for(let f=0;f<e.length;f++){let c=r.get(e[f]);if(c){let l=$n(c,a);if(l===void 0)return;n[i]=f,s[i]=l,i+=1,a=l}}return{pathAt:n,refAt:s,count:i}}pathLen(e){let t=0;for(let r of e)t+=this.record(r).sequenceLen;return t}prefixMatches(e,t){let r=0,n=0,s=0,i=0,a=0;for(;n<e.length&&s<t.length;){let f=this.record(e[n]).sequence,c=this.record(t[s]).sequence;for(;i<f.length&&a<c.length;){if(f[i]!==c[a])return r;i+=1,a+=1,r+=1}i===f.length&&(n+=1,i=0),a===c.length&&(s+=1,a=0)}return r}suffixMatches(e,t){let r=0,n=0,s=0,i=0,a=0;for(;n<e.length&&s<t.length;){let f=this.record(e[e.length-n-1]).sequence,c=this.record(t[t.length-s-1]).sequence;for(;i<f.length&&a<c.length;){if(f[f.length-i-1]!==c[c.length-a-1])return r;i+=1,a+=1,r+=1}i===f.length&&(n+=1,i=0),a===c.length&&(s+=1,a=0)}return r}align(e,t,r){let n=this.pathLen(e),s=this.pathLen(t),i=this.prefixMatches(e,t),a=this.suffixMatches(e,t);i+a>n&&(a=n-i),i+a>s&&(a=s-i),D(r,"M",i),br(r,n-i-a,s-i-a),D(r,"M",a)}sharedWeight(e,t){let r=this.refIndex(t),n=0;for(let s of e)r.has(s)&&(n+=this.record(s).sequenceLen);return n}editsAgainst(e,t){let r=this.orderedMatches(e,t);r?this.stats.orderedAlignments+=1:this.stats.lcsAlignments+=1;let n=r??Hn(wr(e,t,p=>this.record(p).sequenceLen)[0]),s=[],i=this.refPrefix(t),a=(p,u,h,d)=>{p===u?D(s,"D",i[d]-i[h]):h===d?D(s,"I",this.pathLen(e.slice(p,u))):this.align(e.slice(p,u),t.slice(h,d),s)},f=0,c=0,l=0;for(let p=0;p<n.count;p++){let u=n.pathAt[p],h=n.refAt[p];(c!==u||l!==h)&&a(c,u,l,h);let d=this.record(e[u]).sequenceLen;D(s,"M",d),f+=d,c=u+1,l=h+1}return a(c,e.length,l,t.length),{edits:s,matched:f}}alignment(e){let t=this.paths[e];if(this.refId===void 0||e===this.refId||!t)return;let r=this.paths[this.refId].path,n;if(sr(r))n={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else{let s=t.path.map(f=>G(f)).reverse(),i=this.sharedWeight(t.path,r);if(this.sharedWeight(s,r)===0)n={edits:this.editsAgainst(t.path,r).edits,flipped:!1};else if(i===0)n={edits:this.editsAgainst(s,r).edits,flipped:!0};else{let f=this.editsAgainst(t.path,r),c=this.editsAgainst(s,r);n=c.matched>f.matched?{edits:c.edits,flipped:!0}:{edits:f.edits,flipped:!1}}}return n}alignToRef(e){return this.alignment(e)?.edits.map(([t,r])=>`${r}${t}`).join("")}alignments(){let e=this.referenceInterval;if(this.refId===void 0||!e)throw new Error("Alignments need a reference path");let t=this.paths[this.refId].path,r=this.refPrefix(t)[t.length],n=[];return this.paths.forEach((s,i)=>{if(i===this.refId)return;let{edits:a,flipped:f}=this.alignment(i),c=0,l=0;for(;c<a.length&&a[c][0]==="D";)l+=a[c][1],c+=1;let p=a.length,u=0;for(;p>c&&a[p-1][0]==="D";)u+=a[p-1][1],p-=1;let h=s.identity,d=h?h.orientation==="forward"!==f:!f;n.push({strand:d?"+":"-",refStart:e.start+l,refEnd:e.start+r-u,edits:a.slice(c,p),weight:s.weight,path:s.path,start:Be(s,0),identity:h===void 0?void 0:{pathHandle:h.pathHandle,name:h.name,hapStart:h.name.fragment+h.hapStart,hapEnd:h.name.fragment+h.hapEnd,walkForward:h.orientation==="forward"}})}),Dn(n).map(s=>{let{edits:i,identity:a,...f}=s,c={...f,cigar:Qn(i)};return a?{...c,resolved:!0,name:a.name,label:$({...a.name,fragment:a.hapStart},a.hapEnd),pathHandle:a.pathHandle,hapStart:a.hapStart,hapEnd:a.hapEnd}:{...c,resolved:!1}})}canonicalEdges(e){let t=[];for(let r of["forward","reverse"]){let n=Y(e,r);for(let s of this.record(n).successors())this.hasHandle(s)&&le(n,s)&&t.push([r==="reverse"?1:0,A(s),M(s)?1:0])}return t.sort((r,n)=>r[0]-n[0]||r[1]-n[1]||r[2]-n[2]),t.filter((r,n)=>n===0||r[0]!==t[n-1][0]||r[1]!==t[n-1][1]||r[2]!==t[n-1][2])}async stableName(){let e=new TextEncoder,t=[];for(let r of this.sortedHandles())if(!M(r)){let n=A(r),s=`S ${n} ${this.record(r).sequence}
2
- `;for(let[i,a,f]of this.canonicalEdges(n))s+=`L ${n} ${i?"-":"+"} ${a} ${f?"-":"+"}
3
- `;t.push(e.encode(s))}return gr(t)}async toGFA(e={}){let t=e.cigar??!1,r=[this.refPath?`H VN:Z:1.1 RS:Z:${this.refPath.sample}`:"H VN:Z:1.1",...mr(ur(await this.stableName(),await this.db.graphName()))],n=this.sortedHandles();for(let c of n)M(c)||r.push(`S ${A(c)} ${this.record(c).sequence}`);let s=c=>M(c)?"-":"+";for(let c of n)for(let l of this.record(c).successors())this.hasHandle(l)&&le(c,l)&&r.push(`L ${A(c)} ${s(c)} ${A(l)} ${s(l)} 0M`);let i=(c,l,p,u,h)=>{let d=Rt(c,l).map(w=>`${M(w)?"<":">"}${A(w)}`).join(""),m=c.weight===void 0?"":` WT:i:${c.weight}`,x=h===void 0?"":` CG:Z:${h}`;return`W ${p.sample} ${p.haplotype} ${p.contig} ${p.fragment} ${u} ${d}${m}${x}`},a=this.refPath?.contig??"unknown";this.refId!==void 0&&this.refPath&&this.refInterval&&r.push(i(this.paths[this.refId],void 0,{...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]},this.refPath.fragment+this.refInterval[1],void 0));let f=1;return this.paths.forEach((c,l)=>{if(l!==this.refId){let p=e.names==="resolved"?c.identity:void 0,u=t?this.alignToRef(l):void 0;r.push(p?i(c,p,{...p.name,fragment:p.name.fragment+p.hapStart},p.name.fragment+p.hapEnd,u):i(c,void 0,{sample:"unknown",contig:a,haplotype:f,fragment:0},c.len,u)),f+=1}}),`${r.join(`
4
- `)}
5
- `}outputPaths(e){let t=e.cigar??!1,r=[],n=this.refPath?.contig??"unknown";if(this.refId!==void 0&&this.refPath&&this.refInterval){let i={...this.refPath,fragment:this.refPath.fragment+this.refInterval[0]};r.push({info:this.paths[this.refId],identity:void 0,name:$(i,this.refPath.fragment+this.refInterval[1]),cigar:void 0})}let s=1;return this.paths.forEach((i,a)=>{if(a===this.refId)return;let f=e.names==="resolved"?i.identity:void 0;r.push({info:i,identity:f,name:f?$({...f.name,fragment:f.name.fragment+f.hapStart},f.name.fragment+f.hapEnd):$({sample:"unknown",contig:n,haplotype:s,fragment:0},i.len),cigar:t?this.alignToRef(a):void 0}),s+=1}),r}*outputEdges(){for(let e of this.sortedHandles())for(let t of this.record(e).successors())this.hasHandle(t)&&le(e,t)&&(yield[e,t])}toSubgraphJson(e={}){let t=this.sortedHandles().filter(s=>!M(s)).map(s=>({id:String(A(s)),sequence:this.record(s).sequence})),r=[];for(let[s,i]of this.outputEdges())r.push({from:String(A(s)),from_is_reverse:M(s),to:String(A(i)),to_is_reverse:M(i)});let n=this.outputPaths(e).map(s=>Un(s.info,s.identity,s.name,s.cigar));return{nodes:t,edges:r,paths:n}}toCompactSubgraph(e={}){let t=this.sortedHandles().filter(i=>!M(i)),r=new Int32Array(t.length),n=[];t.forEach((i,a)=>{r[a]=A(i),n.push(this.record(i).sequence)});let s=[];for(let[i,a]of this.outputEdges())s.push(i,a);return{nodeIds:r,nodeSequences:n,edges:Int32Array.from(s),paths:this.outputPaths(e).map(i=>({name:i.name,weight:i.info.weight,cigar:i.cigar,steps:Int32Array.from(Rt(i.info,i.identity))}))}}};function Rt(o,e){return e?.orientation==="reverse"?o.path.map(t=>G(t)).reverse():o.path}function Un(o,e,t,r){return{name:t,...o.weight===void 0?{}:{weight:o.weight},...r===void 0?{}:{cigar:r},path:Rt(o,e).map(n=>({id:String(A(n)),is_reverse:M(n)}))}}function Ct(o,e){let t=Math.min(o.length,e.length);for(let r=0;r<t;r++){let n=o[r],s=e[r];if(n!==s)return n<s?-1:1}return o.length-e.length}function D(o,e,t){if(t===0)return;let r=o[o.length-1];r?.[0]===e?r[1]+=t:o.push([e,t])}function Ge(o){return o===0?0:6+(o-1)}function br(o,e,t){if(e===0)D(o,"D",t);else if(t===0)D(o,"I",e);else{let r=Math.min(e,t),n=4*r+Ge(e-r)+Ge(t-r),s=Ge(e)+Ge(t);n<=s?(D(o,"M",r),D(o,"I",e-r),D(o,"D",t-r)):(D(o,"I",e),D(o,"D",t))}}function Qn(o){return o.map(([e,t])=>`${t}${e}`).join("")}async function De(o,e,t,r,n={}){let s=new Ie(o,n);try{let i=await s.pathPosition(Se(e,t));await s.prefetchReferenceWalk(i,r-t),await s.aroundInterval(i.position,r-t,n.context??100),await s.extractSnarls(n.snarls??"none"),s.extractPaths(i,n.haplotypes??"all")}catch(i){throw i instanceof V&&i.windowBp===void 0?new V(i.limit,{windowBp:r-t,walkedBp:s.referenceWalkedBp??0}):i}return s}async function Sr(o,e,t,r,n){if(!o.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let s=await o.haplotypeAnchorSpacing(),i,a;if(s!==void 0&&(n.haplotypes??"all")==="all"){let f=new Ie(o,n);try{let c=await f.pathPosition(Se(e,t));a=await f.walkHaplotypesFromAnchor(c,r-t,s,n.keep,n.context??100)}catch(c){throw c instanceof V&&c.windowBp===void 0?new V(c.limit,{windowBp:r-t,walkedBp:f.referenceWalkedBp??0}):c}if(a===void 0)i=f;else{a=`${a}; identified from the per-path samples instead`;let c=await De(o,e,t,r,n);await c.identifyPaths(),c.keepHaplotypes(n.keep),c.stats.anchorWalk=f.stats.anchorWalk,c.stats.anchorWalk&&(c.stats.anchorWalk.fallback=a),i=c}}else i=await De(o,e,t,r,n),await i.identifyPaths(),i.keepHaplotypes(n.keep);return i}function K(o,e){let t=0;for(let n=0;n<8;n++){let s=o[e+n];if(s===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*128+(s&127),(s&128)===0)return[t,e+n+1]}let r=o[e+8];if(r===void 0)throw new Error("SQLite varint runs past the end of the buffer");if(t=t*256+r,!Number.isSafeInteger(t))throw new Error("SQLite varint exceeds the safe integer range");return[t,e+9]}function Yn(o,e,t){switch(t){case 1:return o.getInt8(e);case 2:return o.getInt16(e);case 3:return o.getInt8(e)<<16|o.getUint16(e+1);case 4:return o.getInt32(e);case 6:return o.getInt16(e)*4294967296+o.getUint32(e+2);default:{let r=o.getBigInt64(e);if(r>BigInt(Number.MAX_SAFE_INTEGER)||r<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`SQLite integer ${r} exceeds the safe integer range`);return Number(r)}}}var Vn=new TextDecoder;function ze(o){let[e,t]=K(o,0),r=[],n=t;for(;n<e;){let[a,f]=K(o,n);r.push(a),n=f}let s=new DataView(o.buffer,o.byteOffset,o.byteLength),i=e;return r.map(a=>{if(a===0)return null;if(a>=1&&a<=6){let f=a<=4?a:a===5?6:8,c=Yn(s,i,f);return i+=f,c}if(a===7){let f=s.getFloat64(i);return i+=8,f}if(a===8)return 0;if(a===9)return 1;if(a>=12){let f=a-12>>1,c=o.subarray(i,i+f);return i+=f,a%2===0?c:Vn.decode(c)}throw new Error(`SQLite serial type ${a} is reserved`)})}var Ae=2,qe=5,Ir=10,je=13;function Ar(o,e){return o[e]*256+o[e+1]}function ee(o,e){return o[e]*16777216+o[e+1]*65536+o[e+2]*256+o[e+3]}function Kn(o,e){let t=o[e];if(t!==Ae&&t!==qe&&t!==Ir&&t!==je)throw new Error(`SQLite page has unknown b-tree type ${t}`);let r=t===Ae||t===qe;return{type:t,cellCount:Ar(o,e+3),rightChild:r?ee(o,e+8):0,cellPointers:e+(r?12:8)}}function Z(o,e,t){return Ar(o,e.cellPointers+2*t)}var Xn=4096,Zn=4096,We=class{usable;pager;decodedIndexPages=new Map;tableDepths=new Map;constructor(e,t){this.pager=e,this.usable=e.pageSize-t}localPayloadSize(e,t){let r=this.usable,n=t?Math.floor((r-12)*64/255)-23:r-35;if(e<=n)return e;let s=Math.floor((r-12)*32/255)-23,i=s+(e-s)%(r-4);return i<=n?i:s}async payload(e,t,r,n){let s=this.localPayloadSize(r,n);if(s===r)return e.subarray(t,t+r);let i=new Uint8Array(r);i.set(e.subarray(t,t+s),0);let a=s,f=ee(e,t+s);for(;f!==0&&a<r;){let c=await this.pager.page(f),l=c.subarray(4,4+Math.min(this.usable-4,r-a));i.set(l,a),a+=l.length,f=ee(c,0)}if(a!==r)throw new Error("SQLite overflow chain ended before the payload was complete");return i}async pageAt(e){let t=await this.pager.page(e);return{page:t,header:Kn(t,e===1?100:0)}}tableDepth(e,t){let r=this.tableDepths.get(e);return r||(r=(async()=>{let n=e;for(let s=0;;s++){let{page:i,header:a}=await this.pageAt(n);if(a.type===je)return s;if(a.type!==qe)throw new Error("SQLite table b-tree contains an index page");let f=this.childIndexFor(i,a,t);n=f===a.cellCount?a.rightChild:ee(i,Z(i,a,f))}})(),this.tableDepths.set(e,r),r.catch(()=>this.tableDepths.delete(e))),r}childIndexFor(e,t,r){let n=0,s=t.cellCount;for(;n<s;){let i=n+s>>1,[a]=K(e,Z(e,t,i)+4);a<r?n=i+1:s=i}return n}async prefetchRowidRange(e,t,r){let n=await this.tableDepth(e,t),s=[e];for(let i=0;i<n;i++){let a=await Promise.all(s.map(c=>this.pageAt(c))),f=[];if(a.forEach(({page:c,header:l},p)=>{let u=p===0?this.childIndexFor(c,l,t):0,h=p===a.length-1?this.childIndexFor(c,l,r):l.cellCount;for(let d=u;d<=h;d++)f.push(d===l.cellCount?l.rightChild:ee(c,Z(c,l,d)))}),f.length>Zn)return!1;this.pager.prefetch(f),s=f}return!0}async tableRowid(e,t){let r=e;for(;;){let{page:n,header:s}=await this.pageAt(r);if(s.type===je){let f=0,c=s.cellCount;for(;f<c;){let l=f+c>>1,p=Z(n,s,l),[u,h]=K(n,p),[d,m]=K(n,h);if(d===t)return ze(await this.payload(n,m,u,!1));d<t?f=l+1:c=l}return}if(s.type!==qe)throw new Error("SQLite table b-tree contains an index page");let i=0,a=s.cellCount;for(;i<a;){let f=i+a>>1,c=Z(n,s,f),[l]=K(n,c+4);l<t?i=f+1:a=f}r=i===s.cellCount?s.rightChild:ee(n,Z(n,s,i))}}async*tableScan(e){let{page:t,header:r}=await this.pageAt(e);if(r.type===je)for(let n=0;n<r.cellCount;n++){let s=Z(t,r,n),[i,a]=K(t,s),[f,c]=K(t,a);yield{rowid:f,values:ze(await this.payload(t,c,i,!1))}}else{let n=[];for(let s=0;s<r.cellCount;s++)n.push(ee(t,Z(t,r,s)));n.push(r.rightChild),this.pager.prefetch(n);for(let s of n)yield*this.tableScan(s)}}decodedCells(e,t){let r=this.decodedIndexPages.get(e);if(r)this.decodedIndexPages.delete(e);else if(r=new Array(t.cellCount),this.decodedIndexPages.size>=Xn){let n=this.decodedIndexPages.keys().next().value;n!==void 0&&this.decodedIndexPages.delete(n)}return this.decodedIndexPages.set(e,r),r}async indexCell(e,t,r,n){let s=this.decodedCells(e,r),i=s[n];if(!i){let a=Z(t,r,n),f=r.type===Ae,[c,l]=K(t,f?a+4:a);i={values:ze(await this.payload(t,l,c,!0)),leftChild:f?ee(t,a):0},s[n]=i}return i}async*indexScanFrom(e,t){let{page:r,header:n}=await this.pageAt(e),s=0,i=n.cellCount;for(;s<i;){let a=s+i>>1,f=await this.indexCell(e,r,n,a);vr(f.values,t)<0?s=a+1:i=a}for(let a=s;a<n.cellCount;a++){let f=await this.indexCell(e,r,n,a);n.type===Ae&&(yield*this.indexScanFrom(f.leftChild,t)),yield f.values}n.type===Ae&&(yield*this.indexScanFrom(n.rightChild,t))}async indexSeekLE(e,t){let r,n=e;for(;;){let{page:s,header:i}=await this.pageAt(n),a=0,f=i.cellCount,c=0;for(;a<f;){let l=a+f>>1,p=await this.indexCell(n,s,i,l);vr(p.values,t)<=0?(r=p.values,a=l+1):(c=p.leftChild,f=l)}if(i.type===Ir)return r;n=a===i.cellCount?i.rightChild:c}}};function vr(o,e){for(let t=0;t<e.length;t++){let r=o[t],n=e[t];if(typeof r!="number"||n===void 0)throw new Error("SQLite index key is not numeric");if(r!==n)return r<n?-1:1}return 0}var Ue=class{blocks=new Map;blockSize;maxBlocks;bytesFetched=0;fetches=0;source;pageSize;fileSize;constructor(e,t,r,n={}){this.source=e,this.pageSize=t,this.fileSize=r;let s=n.blockSize??65536;this.blockSize=Math.max(t,Math.ceil(s/t)*t),this.maxBlocks=n.maxBlocks??256}async read(e,t){let r=0;for(;;)try{let n=await this.source.read(e,t);return this.bytesFetched+=n.length,n}catch(n){if(r+=1,r>=3)throw n;await new Promise(s=>setTimeout(s,200*r))}}seed(e,t){t.length===Math.min(this.blockSize,this.fileSize-e*this.blockSize)&&this.blocks.set(e,Promise.resolve(t))}block(e){let t=this.blocks.get(e);if(t)return this.blocks.delete(e),this.blocks.set(e,t),t;let r=e*this.blockSize,n=Math.min(this.blockSize,this.fileSize-r),s=this.read(n,r);return this.fetches+=1,this.blocks.set(e,s),this.forgetOnFailure(s,[e]),this.evict(),s}prefetch(e){let t=[...new Set(e.map(n=>Math.floor((n-1)*this.pageSize/this.blockSize)))].filter(n=>!this.blocks.has(n)).sort((n,s)=>n-s),r=0;for(;r<t.length;){let n=r+1;for(;n<t.length&&t[n]===t[n-1]+1;)n+=1;this.fetchRun(t[r],n-r),r=n}}fetchRun(e,t){let r=e*this.blockSize,n=Math.min(t*this.blockSize,this.fileSize-r),s=this.read(n,r);this.fetches+=1;let i=[];for(let a=0;a<t;a++){let f=a*this.blockSize;i.push(e+a),this.blocks.set(e+a,s.then(c=>c.subarray(f,f+this.blockSize)))}this.forgetOnFailure(s,i),this.evict()}forgetOnFailure(e,t){e.catch(()=>{for(let r of t)this.blocks.delete(r)})}evict(){for(;this.blocks.size>this.maxBlocks;){let e=this.blocks.keys().next().value;if(e===void 0)break;this.blocks.delete(e)}}async page(e){let t=(e-1)*this.pageSize;if(e<1||t+this.pageSize>this.fileSize)throw new Error(`SQLite page ${e} is outside the file`);let r=await this.block(Math.floor(t/this.blockSize)),n=t%this.blockSize;return r.subarray(n,n+this.pageSize)}};var Ee=class o{pager;btree;objects;constructor(e,t,r){this.pager=e,this.btree=t,this.objects=r}static async open(e,t={}){let{size:r}=await e.stat(),n=await e.read(Math.min(t.blockSize??65536,r),0),s=n.subarray(0,100);if(new TextDecoder().decode(s.subarray(0,15))!=="SQLite format 3")throw new Error("Not a SQLite database");let a=new DataView(s.buffer,s.byteOffset,s.byteLength),f=a.getUint16(16),c=f===1?65536:f,l=s[20]??0,p=a.getUint32(56);if(p!==1)throw new Error(`SQLite text encoding ${p} is not UTF-8`);let u=new Ue(e,c,r,t);u.seed(0,n),u.fetches+=1,u.bytesFetched+=n.length;let h=new We(u,l),d=new Map;for await(let{values:m}of h.tableScan(1)){let[x,w,y,S,R]=m;typeof x=="string"&&typeof w=="string"&&typeof y=="string"&&typeof S=="number"&&d.set(w,{type:x,name:w,tableName:y,rootPage:S,sql:typeof R=="string"?R:""})}return new o(u,h,d)}rootPage(e){let t=this.objects.get(e);if(!t)throw new Error(`SQLite database has no object named ${e}`);return t.rootPage}indexOn(e){let t=[...this.objects.values()].find(r=>r.type==="index"&&r.tableName===e);if(!t)throw new Error(`SQLite table ${e} has no index`);return t.rootPage}byRowid(e,t){return this.btree.tableRowid(this.rootPage(e),t)}prefetchRows(e,t,r){return this.btree.prefetchRowidRange(this.rootPage(e),t,r)}scan(e){return this.btree.tableScan(this.rootPage(e))}indexSeekLE(e,t){return this.btree.indexSeekLE(this.indexOn(e),t)}indexScanFrom(e,t){return this.btree.indexScanFrom(this.indexOn(e),t)}has(e){return this.objects.has(e)}};var Pt="GBZ-base version 4",Qe=class extends Error{name="ForwardOnlyIndexError";constructor(){super("the haplotype index was written with --forward-only, which cannot name the walks stored against their reference (about half of them); rebuild it with gbz-haplotype-index without --forward-only")}},Ye=class extends Error{name="SchemaVersionError";found;constructor(e){super(e===void 0?"not a gbz-base database: its Tags table has no version":`unsupported database schema "${e}"; this reader understands "${Pt}"`),this.found=e}},Ve=class{sequenceLen;handle;edges;bwt;encodedSequence;next;decoded;constructor(e,t,r,n,s){this.handle=e,this.edges=t,this.bwt=r,this.encodedSequence=n,this.next=s,this.sequenceLen=fr(n)}get id(){return A(this.handle)}get orientation(){return ce(this.handle)}get sequence(){return this.decoded??=cr(this.encodedSequence),this.decoded}successors(){return this.edges.filter(e=>e.node!==0).map(e=>e.node)}gbwt(){if(this.edges.length===0)throw new Error(`GBWT record for handle ${this.handle} is empty`);return new Fe(this.edges,this.bwt)}};function T(o,e){if(typeof o!="number")throw new Error(`${e} is not a number in the database`);return o}function Ke(o,e){if(typeof o!="string")throw new Error(`${e} is not text in the database`);return o}function _t(o,e){if(!(o instanceof Uint8Array))throw new Error(`${e} is not a blob in the database`);return o}function Er(o,e){return{handle:o,fwStart:{node:T(e[1],"Paths.fw_node"),offset:T(e[2],"Paths.fw_offset")},revStart:{node:T(e[3],"Paths.rev_node"),offset:T(e[4],"Paths.rev_offset")},name:{sample:Ke(e[5],"Paths.sample"),contig:Ke(e[6],"Paths.contig"),haplotype:T(e[7],"Paths.haplotype"),fragment:T(e[8],"Paths.fragment")},isIndexed:T(e[9],"Paths.is_indexed")!==0}}async function Cr(o){let e=new Map;for await(let{values:t}of o.scan("Tags"))e.set(Ke(t[0],"Tags.key"),Ke(t[1],"Tags.value"));return e}var Ce=class o{tagCache;pathCache;pathMapCache;indexTags;sqlite;index;constructor(e,t){this.sqlite=e,this.index=t}static async open(e,t={}){let{haplotypeIndex:r,...n}=t,s=await Ee.open(e,n);for(let c of["Tags","Nodes","Paths","ReferenceIndex"])s.rootPage(c);let i=r?await Ee.open(r,n):s,a=new o(s,i),f=await a.tag("version");if(f!==Pt)throw new Ye(f);if(r){for(let h of["Tags","HaplotypeSamples","HaplotypeLengths"])i.rootPage(h);a.indexTags=await Cr(i);let c=a.indexTags.get("haplotype_index_paths"),l=await a.tag("paths");if(c!==l)throw new Error(`haplotype index was built for ${c??"an unknown number of"} paths but the graph has ${l}`);let p=a.indexTags.get("haplotype_index_nodes"),u=await a.tag("nodes");if(p!==void 0&&p!==u)throw new Error(`haplotype index was built for a graph with ${p} nodes but this one has ${u}`)}if(a.hasHaplotypeIndex&&await a.haplotypeIndexTag("haplotype_index_orientations")==="forward")throw new Qe;return a}tags(){return this.tagCache??=Cr(this.sqlite),this.tagCache}async tag(e){return(await this.tags()).get(e)}prefetchRecords(e,t){return this.sqlite.prefetchRows("Nodes",e,t)}async getRecord(e){let t=await this.sqlite.byRowid("Nodes",e);if(!t)return;let r=t[4];return new Ve(e,ar(_t(t[1],"Nodes.edges")),_t(t[2],"Nodes.bwt"),_t(t[3],"Nodes.sequence"),typeof r=="number"?r:void 0)}paths(){return this.pathCache??=(async()=>{let e=[];for await(let{rowid:t,values:r}of this.sqlite.scan("Paths"))e.push(Er(t,r));return e})(),this.pathCache}async getPath(e){let t=await this.sqlite.byRowid("Paths",e);return t?Er(e,t):void 0}pathsByHandle(){return this.pathMapCache??=this.paths().then(e=>new Map(e.map(t=>[t.handle,t]))),this.pathMapCache}async findPath(e){return(await this.paths()).filter(r=>r.name.sample===e.sample&&r.name.contig===e.contig&&r.name.haplotype===e.haplotype&&r.name.fragment<=e.fragment).sort((r,n)=>n.name.fragment-r.name.fragment)[0]}async pathsForSample(e){return(await this.paths()).filter(t=>t.name.sample===e)}async pathsNamed(e){let t=Se(xr(e),0);return(await this.paths()).filter(r=>r.name.sample===t.sample&&r.name.contig===t.contig&&r.name.haplotype===t.haplotype).sort((r,n)=>r.name.fragment-n.name.fragment)}async hasPath(e){return(await this.pathsNamed(e)).length>0}pathLengths=new Map;pathLength(e){let t=this.pathLengths.get(e);return t||(t=this.walkPathLength(e),this.pathLengths.set(e,t),t.catch(()=>this.pathLengths.delete(e))),t}async walkPathLength(e){let t=this.hasHaplotypeIndex?await this.haplotypeLength(e):void 0;if(t===void 0){let r=await this.indexedPosition(e,Number.MAX_SAFE_INTEGER);if(!r){let i=await this.getPath(e);throw new Error(`Path ${i?$(i.name,i.name.fragment):e} has not been indexed for random access`)}let n=r.pathOffset,s=r.pos;for(;;){let i=await this.getRecord(s.node);if(!i)throw new Error(`Node ${s.node} does not exist in the graph`);n+=i.sequenceLen;let a=i.gbwt().lf(s.offset);if(!a||a.node===0)return n;s=a}}return t}async pathFragmentsForRange(e,t,r){if(r<=t)return[];let n=await this.pathsNamed(e),s=n.filter(f=>f.name.fragment<=t).slice(-1),i=n.filter(f=>f.name.fragment>t&&f.name.fragment<r);return(await Promise.all([...s,...i].map(async f=>({path:f,start:f.name.fragment,end:f.name.fragment+await this.pathLength(f.handle)})))).filter(f=>t<f.end)}async subgraphForFragment(e,t,r,n){let{keep:s,...i}=n;if(s!==void 0&&!this.hasHaplotypeIndex)throw new Error("keep needs the haplotype index: this database cannot name its walks");let{sample:a,contig:f,haplotype:c}=e.path.name,l={sample:a,contig:f,haplotype:c},p=Math.max(t,e.start),u=Math.min(r,e.end),h=n.haplotypes??"all",d=h==="all"||h==="distinct",m;return s!==void 0&&h==="all"?m=await Sr(this,l,p,u,{...i,keep:s}):(m=await De(this,l,p,u,i),this.hasHaplotypeIndex&&d&&(await m.identifyPaths(),s!==void 0&&m.keepHaplotypes(s))),m}async getSubgraphForRange(e,t,r,n={}){let[s]=await this.pathFragmentsForRange(e,t,r);return s?this.subgraphForFragment(s,t,r,n):void 0}async getAlignmentsForRange(e,t,r,n={}){let s=[];for(let i of await this.pathFragmentsForRange(e,t,r)){let a=await this.subgraphForFragment(i,t,r,n);s.push(...a.alignments())}return s}async graphName(){let e=new Map;for(let[r,n]of await this.tags())r.startsWith("gbz_")&&e.set(r.slice(4),n);let t={name:void 0,subgraph:new Map,translation:new Map};try{t=dr(e)}catch{}return t}async hasChainLinks(){let e=await this.tag("chain_links");return e!==void 0&&Number(e)>0}get hasHaplotypeIndex(){return this.index.has("HaplotypeSamples")&&this.index.has("HaplotypeLengths")}async haplotypeIndexTag(e){return this.indexTags?this.indexTags.get(e):await this.tag(e)}async haplotypeSampleInterval(){let e=await this.haplotypeIndexTag("haplotype_index_interval");return e===void 0?void 0:Number(e)}async haplotypeAnchorSpacing(){let e=this.hasHaplotypeIndex&&this.index.has("HaplotypeAnchors")?await this.haplotypeIndexTag("haplotype_index_anchor_spacing"):void 0;return e===void 0?void 0:Number(e)}async haplotypeAnchor(e,t){let r=await this.index.indexSeekLE("HaplotypeAnchors",[e,t]),n=r?.[0]===e&&r[1]===t?await this.index.byRowid("HaplotypeAnchors",T(r[2],"HaplotypeAnchors rowid")):void 0;return n?{node:T(n[2],"HaplotypeAnchors.node_handle"),pathOffset:T(n[3],"HaplotypeAnchors.path_offset")}:void 0}haplotypeSamplesAtNode(e){return this.haplotypeSamplesInRange(e,e)}sampleFromRow(e){return{node:T(e[0],"HaplotypeSamples.node_handle"),offset:T(e[1],"HaplotypeSamples.node_offset"),pathHandle:T(e[2],"HaplotypeSamples.path_handle"),orientation:T(e[3],"HaplotypeSamples.orientation")===0?"forward":"reverse",pathOffset:T(e[4],"HaplotypeSamples.path_offset")}}async haplotypeSamplesInRange(e,t){let r=[];for await(let n of this.index.indexScanFrom("HaplotypeSamples",[e,0])){if(T(n[0],"HaplotypeSamples.node_handle")>t)break;let i=await this.index.byRowid("HaplotypeSamples",T(n[2],"HaplotypeSamples rowid"));i&&r.push(this.sampleFromRow(i))}return r}async haplotypeSampleAt(e,t){let r=await this.index.indexSeekLE("HaplotypeSamples",[e,t]);if(r?.[0]!==e||r[1]!==t)return;let n=await this.index.byRowid("HaplotypeSamples",T(r[2],"HaplotypeSamples rowid"));return n?this.sampleFromRow(n):void 0}async haplotypeLength(e){let t=await this.index.byRowid("HaplotypeLengths",e);return t?T(t[1],"HaplotypeLengths.length"):void 0}async indexedRow(e){let t=await this.sqlite.byRowid("ReferenceIndex",e);if(!t)throw new Error("ReferenceIndex row referenced by its index is missing");return{pathOffset:T(t[1],"ReferenceIndex.path_offset"),pos:{node:T(t[2],"ReferenceIndex.node_handle"),offset:T(t[3],"ReferenceIndex.node_offset")}}}async indexedRowid(e,t){let r=await this.sqlite.indexSeekLE("ReferenceIndex",[e,t]);return r?.[0]===e?T(r[2],"ReferenceIndex rowid"):void 0}async indexedPosition(e,t){let r=await this.indexedRowid(e,t);return r===void 0?void 0:this.indexedRow(r)}async indexedPositionsBetween(e,t,r){let[n,s]=await Promise.all([this.indexedRowid(e,t),this.indexedRowid(e,r)]),i=[];if(n!==void 0&&s!==void 0){await this.sqlite.prefetchRows("ReferenceIndex",n,s+1);for(let a=n;a<=s;a++)i.push(await this.indexedRow(a))}return i}};var vn=U(er(),1),In=U(we(),1),Yt=U(Rn(),1),An=U(_n(),1);var wn=U(er(),1),yn=U(we(),1);var kt=function(o,e){return kt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])},kt(o,e)};function Re(o,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");kt(o,e);function t(){this.constructor=o}o.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Rr(o,e,t,r){function n(s){return s instanceof t?s:new t(function(i){i(s)})}return new(t||(t=Promise))(function(s,i){function a(l){try{c(r.next(l))}catch(p){i(p)}}function f(l){try{c(r.throw(l))}catch(p){i(p)}}function c(l){l.done?s(l.value):n(l.value).then(a,f)}c((r=r.apply(o,e||[])).next())})}function Xe(o,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,n,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(l){return f([c,l])}}function f(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(t=0)),t;)try{if(r=1,n&&(s=c[0]&2?n.return:c[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,c[1])).done)return s;switch(n=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(o,t)}catch(l){c=[6,l],n=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ne(o){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&o[e],r=0;if(t)return t.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&r>=o.length&&(o=void 0),{value:o&&o[r++],done:!o}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pe(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var r=t.call(o),n,s=[],i;try{for(;(e===void 0||e-- >0)&&!(n=r.next()).done;)s.push(n.value)}catch(a){i={error:a}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return s}function he(o,e,t){if(t||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return o.concat(s||Array.prototype.slice.call(e))}function oe(o){return this instanceof oe?(this.v=o,this):new oe(o)}function _r(o,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(o,e||[]),n,s=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),n[Symbol.asyncIterator]=function(){return this},n;function i(h){return function(d){return Promise.resolve(d).then(h,p)}}function a(h,d){r[h]&&(n[h]=function(m){return new Promise(function(x,w){s.push([h,m,x,w])>1||f(h,m)})},d&&(n[h]=d(n[h])))}function f(h,d){try{c(r[h](d))}catch(m){u(s[0][3],m)}}function c(h){h.value instanceof oe?Promise.resolve(h.value.v).then(l,p):u(s[0][2],h)}function l(h){f("next",h)}function p(h){f("throw",h)}function u(h,d){h(d),s.shift(),s.length&&f(s[0][0],s[0][1])}}function Pr(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=o[Symbol.asyncIterator],t;return e?e.call(o):(o=typeof ne=="function"?ne(o):o[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=o[s]&&function(i){return new Promise(function(a,f){i=o[s](i),n(a,f,i.done,i.value)})}}function n(s,i,a,f){Promise.resolve(f).then(function(c){s({value:c,done:a})},i)}}function P(o){return typeof o=="function"}function kr(o){var e=function(r){Error.call(r),r.stack=new Error().stack},t=o(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Ze=kr(function(o){return function(t){o(this),this.message=t?t.length+` errors occurred during unsubscription:
6
- `+t.map(function(r,n){return n+1+") "+r.toString()}).join(`
7
- `):"",this.name="UnsubscriptionError",this.errors=t}});function Ot(o,e){if(o){var t=o.indexOf(e);0<=t&&o.splice(t,1)}}var Je=(function(){function o(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return o.prototype.unsubscribe=function(){var e,t,r,n,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=ne(i),f=a.next();!f.done;f=a.next()){var c=f.value;c.remove(this)}}catch(m){e={error:m}}finally{try{f&&!f.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var l=this.initialTeardown;if(P(l))try{l()}catch(m){s=m instanceof Ze?m.errors:[m]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var u=ne(p),h=u.next();!h.done;h=u.next()){var d=h.value;try{Or(d)}catch(m){s=s??[],m instanceof Ze?s=he(he([],pe(s)),pe(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{h&&!h.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}if(s)throw new Ze(s)}},o.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Or(e);else{if(e instanceof o){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},o.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},o.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},o.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Ot(t,e)},o.prototype.remove=function(e){var t=this._finalizers;t&&Ot(t,e),e instanceof o&&e._removeParent(this)},o.EMPTY=(function(){var e=new o;return e.closed=!0,e})(),o})();var _s=Je.EMPTY;function et(o){return o instanceof Je||o&&"closed"in o&&P(o.remove)&&P(o.add)&&P(o.unsubscribe)}function Or(o){P(o)?o():o.unsubscribe()}var Q={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var de={setTimeout:function(o,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var n=de.delegate;return n?.setTimeout?n.setTimeout.apply(n,he([o,e],pe(t))):setTimeout.apply(void 0,he([o,e],pe(t)))},clearTimeout:function(o){var e=de.delegate;return(e?.clearTimeout||clearTimeout)(o)},delegate:void 0};function tt(o){de.setTimeout(function(){var e=Q.onUnhandledError;if(e)e(o);else throw o})}function Lt(){}var Lr=(function(){return Tt("C",void 0,void 0)})();function Tr(o){return Tt("E",void 0,o)}function Mr(o){return Tt("N",o,void 0)}function Tt(o,e,t){return{kind:o,value:e,error:t}}var se=null;function Nr(o){if(Q.useDeprecatedSynchronousErrorHandling){var e=!se;if(e&&(se={errorThrown:!1,error:null}),o(),e){var t=se,r=t.errorThrown,n=t.error;if(se=null,r)throw n}}else o()}function Fr(o){Q.useDeprecatedSynchronousErrorHandling&&se&&(se.errorThrown=!0,se.error=o)}var _e=(function(o){Re(e,o);function e(t){var r=o.call(this)||this;return r.isStopped=!1,t?(r.destination=t,et(t)&&t.add(r)):r.destination=ro,r}return e.create=function(t,r,n){return new nt(t,r,n)},e.prototype.next=function(t){this.isStopped?Nt(Mr(t),this):this._next(t)},e.prototype.error=function(t){this.isStopped?Nt(Tr(t),this):(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped?Nt(Lr,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,o.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(Je);var Jn=Function.prototype.bind;function Mt(o,e){return Jn.call(o,e)}var eo=(function(){function o(e){this.partialObserver=e}return o.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){rt(r)}},o.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){rt(r)}else rt(e)},o.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){rt(t)}},o})(),nt=(function(o){Re(e,o);function e(t,r,n){var s=o.call(this)||this,i;if(P(t)||!t)i={next:t??void 0,error:r??void 0,complete:n??void 0};else{var a;s&&Q.useDeprecatedNextContext?(a=Object.create(t),a.unsubscribe=function(){return s.unsubscribe()},i={next:t.next&&Mt(t.next,a),error:t.error&&Mt(t.error,a),complete:t.complete&&Mt(t.complete,a)}):i=t}return s.destination=new eo(i),s}return e})(_e);function rt(o){Q.useDeprecatedSynchronousErrorHandling?Fr(o):tt(o)}function to(o){throw o}function Nt(o,e){var t=Q.onStoppedNotification;t&&de.setTimeout(function(){return t(o,e)})}var ro={closed:!0,next:Lt,error:to,complete:Lt};var ue=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Hr(o){return o}function $r(o){return o.length===0?Hr:o.length===1?o[0]:function(t){return o.reduce(function(r,n){return n(r)},t)}}var z=(function(){function o(e){e&&(this._subscribe=e)}return o.prototype.lift=function(e){var t=new o;return t.source=this,t.operator=e,t},o.prototype.subscribe=function(e,t,r){var n=this,s=oo(e)?e:new nt(e,t,r);return Nr(function(){var i=n,a=i.operator,f=i.source;s.add(a?a.call(s,f):f?n._subscribe(s):n._trySubscribe(s))}),s},o.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},o.prototype.forEach=function(e,t){var r=this;return t=Br(t),new t(function(n,s){var i=new nt({next:function(a){try{e(a)}catch(f){s(f),i.unsubscribe()}},error:s,complete:n});r.subscribe(i)})},o.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},o.prototype[ue]=function(){return this},o.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return $r(e)(this)},o.prototype.toPromise=function(e){var t=this;return e=Br(e),new e(function(r,n){var s;t.subscribe(function(i){return s=i},function(i){return n(i)},function(){return r(s)})})},o.create=function(e){return new o(e)},o})();function Br(o){var e;return(e=o??Q.Promise)!==null&&e!==void 0?e:Promise}function no(o){return o&&P(o.next)&&P(o.error)&&P(o.complete)}function oo(o){return o&&o instanceof _e||no(o)&&et(o)}function so(o){return P(o?.lift)}function q(o){return function(e){if(so(e))return e.lift(function(t){try{return o(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function J(o,e,t,r,n){return new io(o,e,t,r,n)}var io=(function(o){Re(e,o);function e(t,r,n,s,i,a){var f=o.call(this,t)||this;return f.onFinalize=i,f.shouldUnsubscribe=a,f._next=r?function(c){try{r(c)}catch(l){t.error(l)}}:o.prototype._next,f._error=s?function(c){try{s(c)}catch(l){t.error(l)}finally{this.unsubscribe()}}:o.prototype._error,f._complete=n?function(){try{n()}catch(c){t.error(c)}finally{this.unsubscribe()}}:o.prototype._complete,f}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;o.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e})(_e);var ot=(function(o){return o&&typeof o.length=="number"&&typeof o!="function"});function st(o){return P(o?.then)}function it(o){return P(o[ue])}function at(o){return Symbol.asyncIterator&&P(o?.[Symbol.asyncIterator])}function ft(o){return new TypeError("You provided "+(o!==null&&typeof o=="object"?"an invalid object":"'"+o+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ao(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ct=ao();function lt(o){return P(o?.[ct])}function pt(o){return _r(this,arguments,function(){var t,r,n,s;return Xe(this,function(i){switch(i.label){case 0:t=o.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,oe(t.read())];case 3:return r=i.sent(),n=r.value,s=r.done,s?[4,oe(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,oe(n)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function ht(o){return P(o?.getReader)}function X(o){if(o instanceof z)return o;if(o!=null){if(it(o))return fo(o);if(ot(o))return co(o);if(st(o))return lo(o);if(at(o))return Gr(o);if(lt(o))return po(o);if(ht(o))return ho(o)}throw ft(o)}function fo(o){return new z(function(e){var t=o[ue]();if(P(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function co(o){return new z(function(e){for(var t=0;t<o.length&&!e.closed;t++)e.next(o[t]);e.complete()})}function lo(o){return new z(function(e){o.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,tt)})}function po(o){return new z(function(e){var t,r;try{for(var n=ne(o),s=n.next();!s.done;s=n.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}e.complete()})}function Gr(o){return new z(function(e){uo(o,e).catch(function(t){return e.error(t)})})}function ho(o){return Gr(pt(o))}function uo(o,e){var t,r,n,s;return Rr(this,void 0,void 0,function(){var i,a;return Xe(this,function(f){switch(f.label){case 0:f.trys.push([0,5,6,11]),t=Pr(o),f.label=1;case 1:return[4,t.next()];case 2:if(r=f.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];f.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=f.sent(),n={error:a},[3,11];case 6:return f.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:f.sent(),f.label=8;case 8:return[3,10];case 9:if(n)throw n.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function W(o,e,t,r,n){r===void 0&&(r=0),n===void 0&&(n=!1);var s=e.schedule(function(){t(),n?o.add(this.schedule(null,r)):this.unsubscribe()},r);if(o.add(s),!n)return s}function dt(o,e){return e===void 0&&(e=0),q(function(t,r){t.subscribe(J(r,function(n){return W(r,o,function(){return r.next(n)},e)},function(){return W(r,o,function(){return r.complete()},e)},function(n){return W(r,o,function(){return r.error(n)},e)}))})}function ut(o,e){return e===void 0&&(e=0),q(function(t,r){r.add(o.schedule(function(){return t.subscribe(r)},e))})}function Dr(o,e){return X(o).pipe(ut(e),dt(e))}function zr(o,e){return X(o).pipe(ut(e),dt(e))}function jr(o,e){return new z(function(t){var r=0;return e.schedule(function(){r===o.length?t.complete():(t.next(o[r++]),t.closed||this.schedule())})})}function qr(o,e){return new z(function(t){var r;return W(t,e,function(){r=o[ct](),W(t,e,function(){var n,s,i;try{n=r.next(),s=n.value,i=n.done}catch(a){t.error(a);return}i?t.complete():t.next(s)},0,!0)}),function(){return P(r?.return)&&r.return()}})}function mt(o,e){if(!o)throw new Error("Iterable cannot be null");return new z(function(t){W(t,e,function(){var r=o[Symbol.asyncIterator]();W(t,e,function(){r.next().then(function(n){n.done?t.complete():t.next(n.value)})},0,!0)})})}function Wr(o,e){return mt(pt(o),e)}function Ur(o,e){if(o!=null){if(it(o))return Dr(o,e);if(ot(o))return jr(o,e);if(st(o))return zr(o,e);if(at(o))return mt(o,e);if(lt(o))return qr(o,e);if(ht(o))return Wr(o,e)}throw ft(o)}function Ft(o,e){return e?Ur(o,e):X(o)}function Pe(o,e){return q(function(t,r){var n=0;t.subscribe(J(r,function(s){r.next(o.call(e,s,n++))}))})}function Qr(o,e,t,r,n,s,i,a){var f=[],c=0,l=0,p=!1,u=function(){p&&!f.length&&!c&&e.complete()},h=function(m){return c<r?d(m):f.push(m)},d=function(m){s&&e.next(m),c++;var x=!1;X(t(m,l++)).subscribe(J(e,function(w){n?.(w),s?h(w):e.next(w)},function(){x=!0},void 0,function(){if(x)try{c--;for(var w=function(){var y=f.shift();i?W(e,i,function(){return d(y)}):d(y)};f.length&&c<r;)w();u()}catch(y){e.error(y)}}))};return o.subscribe(J(e,h,function(){p=!0,u()})),function(){a?.()}}function me(o,e,t){return t===void 0&&(t=1/0),P(e)?me(function(r,n){return Pe(function(s,i){return e(r,s,n,i)})(X(o(r,n)))},t):(typeof e=="number"&&(t=e),q(function(r,n){return Qr(r,n,o,t)}))}function Yr(o,e,t,r,n){return function(s,i){var a=t,f=e,c=0;s.subscribe(J(i,function(l){var p=c++;f=a?o(f,l,p):(a=!0,l),r&&i.next(f)},n&&(function(){a&&i.next(f),i.complete()})))}}function Vr(o,e){return q(Yr(o,e,arguments.length>=2,!1,!0))}var mo=function(o,e){return o.push(e),o};function gt(){return q(function(o,e){Vr(mo,[])(o).subscribe(e)})}function Kr(o){let e=[],t=0,r;for(let n=0,s=o.length;n<s;n++){let i=o.charCodeAt(n);if(i>=48&&i<=57)t=t*10+i-48;else if(i===58)r=t,t=0;else{let a=o[n];a==="M"||a==="="||a==="X"?e.push({own:r===void 0?t:r,mate:t,op:"M"}):a==="I"?e.push({own:0,mate:t,op:a}):(a==="D"||a==="N")&&e.push({own:t,mate:0,op:a}),r=void 0,t=0}}return e}function Bt(o){let e="";for(let{own:t,mate:r,op:n}of Kr(o))e+=n==="M"?t===0?`${r}I`:r===0?`${t}D`:`${t}M`:`${n==="I"?r:t}${n}`;return e}var Ht=2**28-1;function $t(o,e,t){for(let r=e;r>0;r-=Ht)o.push((Math.min(r,Ht)<<4|t)>>>0)}function go(o,e,t){if(e===t)$t(o,e,0);else{let r=Math.ceil(Math.max(e,t)/Ht);for(let n=0;n<r;n++){let s=Math.floor(e*(n+1)/r)-Math.floor(e*n/r),i=Math.floor(t*(n+1)/r)-Math.floor(t*n/r);o.push((s<<4|9)>>>0,(i<<4|9)>>>0)}}}function Gt(o){let e=[];for(let{own:t,mate:r,op:n}of Kr(o))n==="M"?go(e,t,r):n==="I"?$t(e,r,1):$t(e,t,n==="N"?3:2);return Uint32Array.from(e)}function xo(o){return o>=48&&o<=57}function wo(o){return o!==void 0&&/[A-Za-z]/.test(o)}function Xr(o,e){let t=e;for(;t<o.length&&wo(o[t]);)t++;return t}function Zr(o,e){let t=e,r=0;for(;t<o.length&&xo(o.charCodeAt(t));)r=r*10+(o.charCodeAt(t)-48),t++;return{value:r,next:t}}function nn(o,e){let t=0;for(;t<o.length;){let r=o[t];if(r===":"){let{value:n,next:s}=Zr(o,t+1);e(":",n,n,t+1,s),t=s}else if(r==="="){let n=Xr(o,t+1),s=n-t-1;e("=",s,s,t+1,n),t=n}else if(r==="*")e("*",1,1,t+1,Math.min(t+3,o.length)),t+=3;else if(r==="+"||r==="-"){let n=Xr(o,t+1),s=n-t-1;e(r,r==="-"?s:0,r==="+"?s:0,t+1,n),t=n}else if(r==="~"){let{value:n,next:s}=Zr(o,t+3),i=Math.min(s+2,o.length);e("~",n,0,t+1,i),t=i}else t++}}function Dt(o,e,t,r){let n=t??Number.NEGATIVE_INFINITY,s=r??Number.POSITIVE_INFINITY,i=0;nn(o,(a,f,c,l,p)=>{if(a==="*")i>=n&&i<s&&e(88,i,1,o[l+1]??"",-1,0,0);else if(a==="+"){if(i>=n&&i<=s){let u=o.slice(l,p);e(73,i,c,u,-1,0,c)}}else(a==="-"||a==="~")&&i<s&&i+f>n&&e(a==="-"?68:78,i,f,"",-1,0,0);i+=f})}function on(o,e,t,r){let n=0,s=0,i=[],a=t&&e;for(let f=0,c=o.length;f<c;f++){let l=o[f],p=l>>>4,u=l&15;if(u===0||u===7){if(a)for(let h=0;h<p;h++)(e.charCodeAt(s+h)|32)!==(t.charCodeAt(n+h)|32)&&i.push({start:n+h,type:"mismatch",base:e[s+h],altbase:t[n+h],length:1});s+=p,n+=p}else if(u===1)i.push({start:n,type:"insertion",insertlen:p,insertedBases:e?.slice(s,s+p),length:0}),s+=p;else if(u===2)i.push({start:n,type:"deletion",length:p}),n+=p;else if(u===3)i.push({start:n,type:"skip",length:p}),n+=p;else if(u===8){for(let h=0;h<p;h++)i.push({start:n+h,type:"mismatch",base:e?.[s+h]||"X",qual:r?.[s+h],length:1});s+=p,n+=p}else u===5?i.push({start:n,type:"hardclip",cliplen:p,length:1}):u===4&&(i.push({start:n,type:"softclip",cliplen:p,length:1}),s+=p)}return i}function sn(o,e,t,r,n){if(!e)return[];let s=[],i=e.length,a=r.length,f=n!==void 0,c=t.length,l=!1;for(let y=0;y<c;y++)if(t[y].type==="skip"){l=!0;break}let p=0,u=0,h=0,d=0,m=0,x=0,w=o.length;for(;x<w;){let y=o.charCodeAt(x);if(y>=48&&y<=57){let S=0;for(;x<w;){let R=o.charCodeAt(x);if(R>=48&&R<=57)S=S*10+(R-48),x++;else break}p+=S}else if(y===94)for(x++;x<w&&o.charCodeAt(x)>=65;)x++,p++;else if(y>=65){let S=o[x];if(x++,l&&c>0)for(let I=m;I<c;I++){let C=t[I];C.type==="skip"&&p>=C.start&&(p+=C.length,m=I+1)}let R=h,g=d;for(let I=u;I<i&&g<=p;I++,u=I){let C=e[I],_=C>>>4,v=C&15;v===4||v===1?R+=_:v===2||v===6||v===3?g+=_:v!==5&&(R+=_,g+=_)}h=R,d=g;let b=R-(g-p),E=b<a?r[b]:"X";s.push({start:p,base:E,qual:f?n[b]:void 0,altbase:S,length:1,type:"mismatch"}),p++}else x++}return s}var an={77:0,73:1,68:2,78:3,83:4,72:5,80:6,61:7,88:8};function fn(o=""){let e=0,t=[];for(let r=0,n=o.length;r<n;r++){let s=o.charCodeAt(r);if(s>=48&&s<=57)e=e*10+(s-48);else{let i=an[s];t.push(e<<4|i),e=0}}return t}function qt(o=""){let e=0;for(let s=0,i=o.length;s<i;s++){let a=o.charCodeAt(s);(a<48||a>57)&&e++}let t=new Uint32Array(e),r=0,n=0;for(let s=0,i=o.length;s<i;s++){let a=o.charCodeAt(s);a>=48&&a<=57?r=r*10+(a-48):(t[n++]=r<<4|an[a],r=0)}return t}function St(o,e,t,r,n){let s=fn(o),i=o?on(s,t,r,n):[];return e&&t?i.concat(sn(e,s,i,t,n)):i}var So=397,vo=387,Io=385;function cn(o){return(1<<o&So)!==0}function ln(o){return(1<<o&vo)!==0}function pn(o){return(1<<o&Io)!==0}function Wt(o,e,t,r,n,s,i){let a=n===-1?-1:1,f=e,c=n===-1?r:t,l=[],p=1/0,u=-1/0,h=1/0,d=-1/0,m=(x,w)=>{h=Math.min(h,x,w),d=Math.max(d,x,w)};for(let x=0;x<o.length;x++){let w=o[x],y=w>>>4,S=w&15,R=S===9,g=R||cn(S)?y:0,b=R?o[++x]>>>4:ln(S)?y:0,E=f+g,I=c+b*a,C=f,_=E;if(_>=s&&C<=i)if(g>0){let v=Math.max(C,s),O=Math.min(_,i);if(O>v)if(p=Math.min(p,v),u=Math.max(u,O),R){let L=b/y,N=O-v,F=Math.round(N*L),H=Math.round(c+(v-f)*L*a);l.push(N<<4|9,F<<4|9),m(H,H+F*a)}else l.push(O-v<<4|S),pn(S)?m(c+(v-f)*a,c+(O-f)*a):m(c,c)}else b>0&&(R?l.push(w,o[x]):l.push(w),p=Math.min(p,f),u=Math.max(u,f),m(c,I));if(f=E,c=I,f>i)break}if(l.length!==0)return{start:p,end:u,mateStart:h,mateEnd:d,cigar:Uint32Array.from(l)}}function Ao(o){return o===1||o===2||o===3}function Ut(o,e,t,r,n,s){let i=n===-1?-1:1,a=[],f=e,c=n===-1?r:t,l,p=!1,u=()=>{l!==void 0&&p&&l.qHi>l.qLo&&a.push({start:l.qLo,end:l.qHi,mateStart:l.tLo,mateEnd:l.tHi,cigar:Uint32Array.from(l.ops)}),l=void 0,p=!1};for(let h=0;h<o.length;h++){let d=o[h],m=d>>>4,x=d&15,w=x===9,y=w?o[++h]:void 0,S=w||cn(x)?m:0,R=y!==void 0?y>>>4:ln(x)?m:0,g=c+R*i;Ao(x)&&m>=s?u():(S>0||R>0)&&(l===void 0&&(l={qLo:f,qHi:f,tLo:c,tHi:c,ops:[]}),l.qHi=f+S,l.tLo=Math.min(l.tLo,c,g),l.tHi=Math.max(l.tHi,c,g),l.ops.push(d),y!==void 0&&l.ops.push(y),p=p||w||pn(x)),f+=S,c=g}return u(),a}function hn(o){let e=o.get("CIGAR");return typeof e=="string"?e:void 0}function dn(o){let e=o.get("coarseCigar");return typeof e=="string"?e:void 0}function Qt(o){let e=hn(o),t=e===void 0?dn(o):void 0;return e!==void 0?qt(e):t!==void 0?Gt(t):void 0}var Eo=U(we(),1),Co=U(mn(),1);var Ro=U(we(),1);var _o=U(Pn(),1);var gn=U(we(),1),ie=class extends gn.SimpleFeature{get(e){return e==="mismatches"?St(this.walkableCigar):e==="clipLengthAtStartOfRead"?this.clipLengthAtStartOfRead:e==="name"?super.get("name")??this.mate?.refName:super.get(e)}get mate(){return super.get("mate")}get walkableCigar(){let e=super.get("CIGAR"),t=super.get("coarseCigar");return typeof e=="string"?e:typeof t=="string"?Bt(t):void 0}get clipLengthAtStartOfRead(){return this.mate?.start??0}forEachMismatch(e,t){let r=this.get("start"),n=t?.start===void 0?void 0:t.start-r,s=t?.end===void 0?void 0:t.end-r,i=this.get("cs");if(i)Dt(i,e,n,s);else{let a=n??Number.NEGATIVE_INFINITY,f=s??Number.POSITIVE_INFINITY;for(let c of St(this.walkableCigar))(c.type==="deletion"||c.type==="skip"?c.start<f&&c.start+c.length>a:c.start>=a&&c.start<=f)&&(c.type==="mismatch"?e(88,c.start,c.length,c.base,c.qual??-1,0,0):c.type==="insertion"?e(73,c.start,c.length,c.insertedBases??"",-1,0,c.insertlen):c.type==="deletion"?e(68,c.start,c.length,"",-1,0,0):c.type==="skip"&&e(78,c.start,c.length,"",-1,0,0))}}};var Po=["CIGAR","cs","coarseCigar","cg","cr"];function ko(o){return typeof o=="object"&&o!==null&&"refName"in o&&"start"in o&&"end"in o&&typeof o.refName=="string"&&typeof o.start=="number"&&typeof o.end=="number"}function Oo(o){let e=o.get("mate");return ko(e)?e:void 0}function Lo(o,e,t,r){let n=Math.max(o.start,r.start),s=Math.min(o.end,r.end),i=(e.end-e.start)/Math.max(o.end-o.start,1),a=l=>t===-1?e.end-(l-o.start)*i:e.start+(l-o.start)*i,f=Math.round(a(n)),c=Math.round(a(s));return s>n?{start:n,end:s,mateStart:Math.min(f,c),mateEnd:Math.max(f,c)}:void 0}function To(o,e,t,r){let n={start:o.get("start"),end:o.get("end")},s=o.get("strand")===-1?-1:1,i=n.start>=t.start&&n.end<=t.end,a=i&&r===void 0?void 0:Qt(o);if(a===void 0){let f=i?{...n,mateStart:e.start,mateEnd:e.end}:Lo(n,e,s,t);return f===void 0?[]:[f]}else return(r===void 0?[{...n,mateStart:e.start,mateEnd:e.end,cigar:a}]:Ut(a,n.start,e.start,e.end,s,r)).flatMap(c=>{let l=Wt(c.cigar,c.start,c.mateStart,c.mateEnd,s,t.start,t.end);return l===void 0?[]:[l]})}function Mo(o,e,t,r,n){let s=`:${r.start}-${r.end}${n}`,i=o.toJSON(),a={...i,uniqueId:`${o.id()}${s}`,start:t.start,end:t.end,mate:{...e,start:t.mateStart,end:t.mateEnd}};i.syntenyId!==void 0&&(a.syntenyId=`${String(i.syntenyId)}${s}`);for(let f of Po)delete a[f];return new ie(a)}function xn(o,e,t){let r=Oo(o);if(r===void 0)return[o];{let n=To(o,r,e,t);return n.map((s,i)=>Mo(o,r,s,e,n.length>1?`/${i}`:""))}}var vt=class extends wn.BaseFeatureDataAdapter{constructor(){super(...arguments);this.recordsAreAlignments=!0}static{this.capabilities=["getFeatures","getRefNames"]}async hasDataForRefName(){return!0}getFeaturesInMultipleRegions(t,r={}){let{clipToRegion:n,splitAtGapBp:s,...i}=r,a=n&&this.recordsAreAlignments,f=(0,yn.createStatusFanOut)(i.statusCallback);return Ft(t).pipe(me((c,l)=>this.getFeatures(c,{...i,statusCallback:f()}).pipe(me(p=>a?xn(p,c,s):[p]),gt(),Pe(p=>({index:l,features:p})))),gt(),me(c=>c.sort((l,p)=>l.index-p.index).flatMap(l=>l.features)))}};var Vt=class extends Error{constructor(){super("this .gbz.db has no HaplotypeSamples/HaplotypeLengths tables, so its walks cannot be named; run gbz-haplotype-index (from @gmod/gbz-base) over it first");this.name="NoHaplotypeIndexError"}},Kt=class extends Error{constructor(t,r){super(r.length===0?`the graph names no reference sample (gbwt_reference_samples) and the anchor "${t}" maps to none; set referenceSample`:`the anchor "${t}" is none of the graph's reference samples (${r.join(", ")}); set referenceSample or map it through assemblyNameToPanSN`);this.name="NoReferenceSampleError"}};function ge(o){return`${o.sample}#${o.haplotype}`}function No(o,e){let t=ge(o);return e===void 0||e.some(r=>Oe(t,r))}var Xt=class extends Error{constructor(t,r){super(`the graph is cut on its reference, ${r}; a window on ${t} has no reference coordinates to cut at. Open the graph from a ${r} view, and find this haplotype's lane there`);this.name="HaplotypeWindowError"}},Zt=class extends Error{constructor(t,r,n){super(`this ${r.toLocaleString()} bp window reads more than nodeLimit (${t.toLocaleString()}) graph nodes; zoom in to about ${n.toLocaleString()} bp or raise nodeLimit`);this.name="NodeLimitError"}};function bn(o,e,t){if(o instanceof Error&&(o.name==="SubgraphLimitError"||/^Subgraph size limit of \d+ nodes exceeded/.test(o.message))){let n=o.walkedBp,s=typeof n=="number"&&n>0?Math.floor(n*.8):Math.floor(t/2);return new Zt(e,t,Math.max(s,1))}else return}function Sn(o,e){let t=ge(e);return o[t]??o[e.sample]??t}function Fo({configured:o,anchorPrefix:e,referenceSamples:t}){let r=tr(e);if(o!=="")return o;if(t.includes(r))return r;if(t.length===1)return t[0];throw new Kt(e,t)}function Ho(o,e){return`${ge(o)}#${o.contig}@${e.start.node}.${e.start.offset}`}function $o({alignment:o,assemblyName:e,refName:t,lane:r}){let{refStart:n,refEnd:s,strand:i,cigar:a}=o;if(!(!o.resolved||s<=n)){let{name:f,hapStart:c,hapEnd:l}=o,p=Ho(f,o),u={uniqueId:p,assemblyName:e,refName:t,start:n,end:s,type:"match",strand:i==="-"?-1:1,CIGAR:a,syntenyId:p,mate:{refName:f.contig,start:c,end:l,assemblyName:r}};return new ie(u)}}var Jt=class extends vt{constructor(){super(...arguments);this.graph=(0,vn.cachedSetup)({label:"Opening pangenome database",setup:async()=>{let t=this.getConf("haplotypeIndexLocation"),r=!("uri"in t)||t.uri!=="",n=await Ce.open((0,Yt.openLocation)(this.getConf("gbzDbLocation"),this.pluginManager),r?{haplotypeIndex:(0,Yt.openLocation)(t,this.pluginManager)}:{}),s=this.getConf("assemblyNames")[0];if(s===void 0)throw new Error("GbzBaseSyntenyAdapter needs assemblyNames: its first entry is the assembly the reference sample is loaded as");let i=(await n.tag("gbwt_reference_samples")??"").split(/\s+/).filter(f=>f!==""),a=Fo({configured:this.getConf("referenceSample"),anchorPrefix:ye(this,s),referenceSamples:i});return{db:n,anchor:s,referenceSample:a,referenceSamples:i}}})}async referenceQuery(t,r){let{db:n,referenceSample:s}=await this.graph(r),i=(await n.paths()).find(a=>a.isIndexed&&a.name.sample===s&&a.name.contig===t);return i?{sample:i.name.sample,contig:t,haplotype:i.name.haplotype}:void 0}async getHaplotypes(t={}){let{db:r,referenceSamples:n}=await this.graph(t),s=new Map;for(let i of await r.paths()){let a=ge(i.name),f=s.get(a);f?f.contigs.includes(i.name.contig)||f.contigs.push(i.name.contig):s.set(a,{prefix:a,sample:i.name.sample,haplotype:i.name.haplotype,contigs:[i.name.contig],isReference:n.includes(i.name.sample)})}return[...s.values()]}async getHeader(t={}){let{anchor:r,referenceSample:n,referenceSamples:s}=await this.graph(t),i=It(this),a=[];for(let f of await this.getHaplotypes(t))f.sample!==n&&a.push({name:Sn(i,f),label:f.prefix,group:f.sample});return{hasCoarseTier:!1,anchorAssemblyName:r,referenceSample:n,referenceSamples:s,lanes:a}}async getRefNames(t={}){let{db:r,anchor:n,referenceSample:s}=await this.graph(t),{assemblyName:i}=t,a=i===n?void 0:ye(this,i),f=(await r.paths()).filter(c=>i===n?c.isIndexed&&c.name.sample===s:Oe(ge(c.name),a)).map(c=>c.name.contig);return[...new Set(f)]}keepPredicate(t,r){let n=t===void 0||t.length===0?void 0:t.map(s=>ye(this,s));return n===void 0&&r===void 0?void 0:s=>No(s,n)&&(r===void 0||Oe(ge(s),r))}async getSubgraph(t,r={}){let{db:n,anchor:s}=await this.graph(),{assemblyName:i,refName:a,start:f,end:c}=t;if(i!==s)throw new Xt(i,s);let l=await this.referenceQuery(a,{}),p=this.getConf("nodeLimit"),u=this.keepPredicate(r.haplotypes),h=l?await n.getSubgraphForRange(l,f,c,{context:this.getConf("context"),snarls:this.getConf("subgraphSnarls"),haplotypes:"all",limit:p,signal:r.signal,...u===void 0?{}:{keep:u}}).catch(d=>{throw bn(d,p,c-f)??d}):void 0;return h?h.toGFA({names:"resolved"}):""}getFeatures(t,r={}){return(0,An.ObservableCreate)(async n=>{let{db:s,anchor:i}=await this.graph(r);if(!s.hasHaplotypeIndex)throw new Vt;let{assemblyName:a,refName:f,start:c,end:l}=t;if(a===i){let p=ye(this,r.targetAssemblyName),u=It(this),h=this.keepPredicate(r.haplotypes,p),d=await this.referenceQuery(f,r),m=this.getConf("nodeLimit"),x=d?await(0,In.updateStatus)(`Reading graph ${f}:${c.toLocaleString()}-${l.toLocaleString()}`,r.statusCallback,()=>s.getAlignmentsForRange(d,c,l,{context:this.getConf("context"),haplotypes:"all",limit:m,signal:r.signal,...h===void 0?{}:{keep:h}}).catch(w=>{throw bn(w,m,l-c)??w})):[];for(let w of x)if(w.resolved){let y=$o({alignment:w,assemblyName:a,refName:f,lane:Sn(u,w.name)});y!==void 0&&n.next(y)}}n.complete()},r.signal)}};export{Xt as HaplotypeWindowError,Vt as NoHaplotypeIndexError,Kt as NoReferenceSampleError,Zt as NodeLimitError,Jt as default,$o as fragmentFeature,ge as haplotypePrefix,Sn as laneAssemblyName,bn as nodeLimitError,Fo as resolveReferenceSample};
8
- //# sourceMappingURL=GbzBaseSyntenyAdapter-EFIOI2SN.js.map