@vuu-ui/vuu-data-local 0.8.30 → 0.8.31-debug

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/cjs/index.js CHANGED
@@ -1,2 +1,4628 @@
1
- "use strict";var $t=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var Ze=(o,t)=>{for(var e in t)$t(o,e,{get:t[e],enumerable:!0})},qe=(o,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ke(t))!Je.call(o,r)&&r!==e&&$t(o,r,{get:()=>t[r],enumerable:!(s=Ye(t,r))||s.enumerable});return o};var He=o=>qe($t({},"__esModule",{value:!0}),o);var Se=(o,t,e)=>{if(!t.has(o))throw TypeError("Cannot "+e)};var u=(o,t,e)=>(Se(o,t,"read from private field"),e?e.call(o):t.get(o)),P=(o,t,e)=>{if(t.has(o))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(o):t.set(o,e)},m=(o,t,e,s)=>(Se(o,t,"write to private field"),s?s.call(o,e):t.set(o,e),e);var jt=(o,t,e,s)=>({set _(r){m(o,t,r,e)},get _(){return u(o,t,s)}});var Qs={};Ze(Qs,{ArrayDataSource:()=>ge,JsonDataSource:()=>me});module.exports=He(Qs);var ts=0,Rt=class{constructor(t,e){this.from=t,this.to=e}},C=class{constructor(t={}){this.id=ts++,this.perNode=!!t.perNode,this.deserialize=t.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(t){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof t!="function"&&(t=z.match(t)),e=>{let s=t(e);return s===void 0?null:[this,s]}}};C.closedBy=new C({deserialize:o=>o.split(" ")});C.openedBy=new C({deserialize:o=>o.split(" ")});C.group=new C({deserialize:o=>o.split(" ")});C.contextHash=new C({perNode:!0});C.lookAhead=new C({perNode:!0});C.mounted=new C({perNode:!0});var es=Object.create(null),z=class o{constructor(t,e,s,r=0){this.name=t,this.props=e,this.id=s,this.flags=r}static define(t){let e=t.props&&t.props.length?Object.create(null):es,s=(t.top?1:0)|(t.skipped?2:0)|(t.error?4:0)|(t.name==null?8:0),r=new o(t.name||"",e,t.id,s);if(t.props){for(let i of t.props)if(Array.isArray(i)||(i=i(r)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");e[i[0].id]=i[1]}}return r}prop(t){return this.props[t.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(t){if(typeof t=="string"){if(this.name==t)return!0;let e=this.prop(C.group);return e?e.indexOf(t)>-1:!1}return this.id==t}static match(t){let e=Object.create(null);for(let s in t)for(let r of s.split(" "))e[r]=t[s];return s=>{for(let r=s.prop(C.group),i=-1;i<(r?r.length:0);i++){let n=e[i<0?s.name:r[i]];if(n)return n}}}};z.none=new z("",Object.create(null),0,8);var It=class o{constructor(t){this.types=t;for(let e=0;e<t.length;e++)if(t[e].id!=e)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...t){let e=[];for(let s of this.types){let r=null;for(let i of t){let n=i(s);n&&(r||(r=Object.assign({},s.props)),r[n[0].id]=n[1])}e.push(r?new z(s.name,r,s.id,s.flags):s)}return new o(e)}},At=new WeakMap,ye=new WeakMap,T;(function(o){o[o.ExcludeBuffers=1]="ExcludeBuffers",o[o.IncludeAnonymous=2]="IncludeAnonymous",o[o.IgnoreMounts=4]="IgnoreMounts",o[o.IgnoreOverlays=8]="IgnoreOverlays"})(T||(T={}));var E=class o{constructor(t,e,s,r,i){if(this.type=t,this.children=e,this.positions=s,this.length=r,this.props=null,i&&i.length){this.props=Object.create(null);for(let[n,l]of i)this.props[typeof n=="number"?n:n.id]=l}}toString(){let t=this.prop(C.mounted);if(t&&!t.overlay)return t.tree.toString();let e="";for(let s of this.children){let r=s.toString();r&&(e&&(e+=","),e+=r)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(e.length?"("+e+")":""):e}cursor(t=0){return new mt(this.topNode,t)}cursorAt(t,e=0,s=0){let r=At.get(this)||this.topNode,i=new mt(r);return i.moveTo(t,e),At.set(this,i._tree),i}get topNode(){return new ht(this,0,0,null)}resolve(t,e=0){let s=gt(At.get(this)||this.topNode,t,e,!1);return At.set(this,s),s}resolveInner(t,e=0){let s=gt(ye.get(this)||this.topNode,t,e,!0);return ye.set(this,s),s}iterate(t){let{enter:e,leave:s,from:r=0,to:i=this.length}=t,n=t.mode||0,l=(n&T.IncludeAnonymous)>0;for(let h=this.cursor(n|T.IncludeAnonymous);;){let a=!1;if(h.from<=i&&h.to>=r&&(!l&&h.type.isAnonymous||e(h)!==!1)){if(h.firstChild())continue;a=!0}for(;a&&s&&(l||!h.type.isAnonymous)&&s(h),!h.nextSibling();){if(!h.parent())return;a=!0}}}prop(t){return t.perNode?this.props?this.props[t.id]:void 0:this.type.prop(t)}get propValues(){let t=[];if(this.props)for(let e in this.props)t.push([+e,this.props[e]]);return t}balance(t={}){return this.children.length<=8?this:Kt(z.none,this.children,this.positions,0,this.children.length,0,this.length,(e,s,r)=>new o(this.type,e,s,r,this.propValues),t.makeTree||((e,s,r)=>new o(z.none,e,s,r)))}static build(t){return ss(t)}};E.empty=new E(z.none,[],[],0);var Wt=class o{constructor(t,e){this.buffer=t,this.index=e}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new o(this.buffer,this.index)}},lt=class o{constructor(t,e,s){this.buffer=t,this.length=e,this.set=s}get type(){return z.none}toString(){let t=[];for(let e=0;e<this.buffer.length;)t.push(this.childString(e)),e=this.buffer[e+3];return t.join(",")}childString(t){let e=this.buffer[t],s=this.buffer[t+3],r=this.set.types[e],i=r.name;if(/\W/.test(i)&&!r.isError&&(i=JSON.stringify(i)),t+=4,s==t)return i;let n=[];for(;t<s;)n.push(this.childString(t)),t=this.buffer[t+3];return i+"("+n.join(",")+")"}findChild(t,e,s,r,i){let{buffer:n}=this,l=-1;for(let h=t;h!=e&&!(xe(i,r,n[h+1],n[h+2])&&(l=h,s>0));h=n[h+3]);return l}slice(t,e,s){let r=this.buffer,i=new Uint16Array(e-t),n=0;for(let l=t,h=0;l<e;){i[h++]=r[l++],i[h++]=r[l++]-s;let a=i[h++]=r[l++]-s;i[h++]=r[l++]-t,n=Math.max(n,a)}return new o(i,n,this.set)}};function xe(o,t,e,s){switch(o){case-2:return e<t;case-1:return s>=t&&e<t;case 0:return e<t&&s>t;case 1:return e<=t&&s>t;case 2:return s>t;case 4:return!0}}function Ce(o,t){let e=o.childBefore(t);for(;e;){let s=e.lastChild;if(!s||s.to!=e.to)break;s.type.isError&&s.from==s.to?(o=e,e=s.prevSibling):e=s}return o}function gt(o,t,e,s){for(var r;o.from==o.to||(e<1?o.from>=t:o.from>t)||(e>-1?o.to<=t:o.to<t);){let n=!s&&o instanceof ht&&o.index<0?null:o.parent;if(!n)return o;o=n}let i=s?0:T.IgnoreOverlays;if(s)for(let n=o,l=n.parent;l;n=l,l=n.parent)n instanceof ht&&n.index<0&&((r=l.enter(t,e,i))===null||r===void 0?void 0:r.from)!=n.from&&(o=l);for(;;){let n=o.enter(t,e,i);if(!n)return o;o=n}}var ht=class o{constructor(t,e,s,r){this._tree=t,this.from=e,this.index=s,this._parent=r}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,e,s,r,i=0){for(let n=this;;){for(let{children:l,positions:h}=n._tree,a=e>0?l.length:-1;t!=a;t+=e){let f=l[t],c=h[t]+n.from;if(xe(r,s,c,c+f.length)){if(f instanceof lt){if(i&T.ExcludeBuffers)continue;let p=f.findChild(0,f.buffer.length,e,s-c,r);if(p>-1)return new Pt(new Ut(n,f,t,c),null,p)}else if(i&T.IncludeAnonymous||!f.type.isAnonymous||Yt(f)){let p;if(!(i&T.IgnoreMounts)&&f.props&&(p=f.prop(C.mounted))&&!p.overlay)return new o(p.tree,c,t,n);let g=new o(f,c,t,n);return i&T.IncludeAnonymous||!g.type.isAnonymous?g:g.nextChild(e<0?f.children.length-1:0,e,s,r)}}}if(i&T.IncludeAnonymous||!n.type.isAnonymous||(n.index>=0?t=n.index+e:t=e<0?-1:n._parent._tree.children.length,n=n._parent,!n))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(t){return this.nextChild(0,1,t,2)}childBefore(t){return this.nextChild(this._tree.children.length-1,-1,t,-2)}enter(t,e,s=0){let r;if(!(s&T.IgnoreOverlays)&&(r=this._tree.prop(C.mounted))&&r.overlay){let i=t-this.from;for(let{from:n,to:l}of r.overlay)if((e>0?n<=i:n<i)&&(e<0?l>=i:l>i))return new o(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,e,s)}nextSignificantParent(){let t=this;for(;t.type.isAnonymous&&t._parent;)t=t._parent;return t}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(t=0){return new mt(this,t)}get tree(){return this._tree}toTree(){return this._tree}resolve(t,e=0){return gt(this,t,e,!1)}resolveInner(t,e=0){return gt(this,t,e,!0)}enterUnfinishedNodesBefore(t){return Ce(this,t)}getChild(t,e=null,s=null){let r=Nt(this,t,e,s);return r.length?r[0]:null}getChildren(t,e=null,s=null){return Nt(this,t,e,s)}toString(){return this._tree.toString()}get node(){return this}matchContext(t){return Mt(this,t)}};function Nt(o,t,e,s){let r=o.cursor(),i=[];if(!r.firstChild())return i;if(e!=null){for(;!r.type.is(e);)if(!r.nextSibling())return i}for(;;){if(s!=null&&r.type.is(s))return i;if(r.type.is(t)&&i.push(r.node),!r.nextSibling())return s==null?i:[]}}function Mt(o,t,e=t.length-1){for(let s=o.parent;e>=0;s=s.parent){if(!s)return!1;if(!s.type.isAnonymous){if(t[e]&&t[e]!=s.name)return!1;e--}}return!0}var Ut=class{constructor(t,e,s,r){this.parent=t,this.buffer=e,this.index=s,this.start=r}},Pt=class o{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(t,e,s){this.context=t,this._parent=e,this.index=s,this.type=t.buffer.set.types[t.buffer.buffer[s]]}child(t,e,s){let{buffer:r}=this.context,i=r.findChild(this.index+4,r.buffer[this.index+3],t,e-this.context.start,s);return i<0?null:new o(this.context,this,i)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(t){return this.child(1,t,2)}childBefore(t){return this.child(-1,t,-2)}enter(t,e,s=0){if(s&T.ExcludeBuffers)return null;let{buffer:r}=this.context,i=r.findChild(this.index+4,r.buffer[this.index+3],e>0?1:-1,t-this.context.start,e);return i<0?null:new o(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(t){return this._parent?null:this.context.parent.nextChild(this.context.index+t,t,0,4)}get nextSibling(){let{buffer:t}=this.context,e=t.buffer[this.index+3];return e<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new o(this.context,this._parent,e):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,e=this._parent?this._parent.index+4:0;return this.index==e?this.externalSibling(-1):new o(this.context,this._parent,t.findChild(e,this.index,-1,0,4))}cursor(t=0){return new mt(this,t)}get tree(){return null}toTree(){let t=[],e=[],{buffer:s}=this.context,r=this.index+4,i=s.buffer[this.index+3];if(i>r){let n=s.buffer[this.index+1];t.push(s.slice(r,i,n)),e.push(0)}return new E(this.type,t,e,this.to-this.from)}resolve(t,e=0){return gt(this,t,e,!1)}resolveInner(t,e=0){return gt(this,t,e,!0)}enterUnfinishedNodesBefore(t){return Ce(this,t)}toString(){return this.context.buffer.childString(this.index)}getChild(t,e=null,s=null){let r=Nt(this,t,e,s);return r.length?r[0]:null}getChildren(t,e=null,s=null){return Nt(this,t,e,s)}get node(){return this}matchContext(t){return Mt(this,t)}},mt=class{get name(){return this.type.name}constructor(t,e=0){if(this.mode=e,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,t instanceof ht)this.yieldNode(t);else{this._tree=t.context.parent,this.buffer=t.context;for(let s=t._parent;s;s=s._parent)this.stack.unshift(s.index);this.bufferNode=t,this.yieldBuf(t.index)}}yieldNode(t){return t?(this._tree=t,this.type=t.type,this.from=t.from,this.to=t.to,!0):!1}yieldBuf(t,e){this.index=t;let{start:s,buffer:r}=this.buffer;return this.type=e||r.set.types[r.buffer[t]],this.from=s+r.buffer[t+1],this.to=s+r.buffer[t+2],!0}yield(t){return t?t instanceof ht?(this.buffer=null,this.yieldNode(t)):(this.buffer=t.context,this.yieldBuf(t.index,t.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(t,e,s){if(!this.buffer)return this.yield(this._tree.nextChild(t<0?this._tree._tree.children.length-1:0,t,e,s,this.mode));let{buffer:r}=this.buffer,i=r.findChild(this.index+4,r.buffer[this.index+3],t,e-this.buffer.start,s);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(t){return this.enterChild(1,t,2)}childBefore(t){return this.enterChild(-1,t,-2)}enter(t,e,s=this.mode){return this.buffer?s&T.ExcludeBuffers?!1:this.enterChild(1,t,e):this.yield(this._tree.enter(t,e,s))}parent(){if(!this.buffer)return this.yieldNode(this.mode&T.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let t=this.mode&T.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(t)}sibling(t){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+t,t,0,4,this.mode)):!1;let{buffer:e}=this.buffer,s=this.stack.length-1;if(t<0){let r=s<0?0:this.stack[s]+4;if(this.index!=r)return this.yieldBuf(e.findChild(r,this.index,-1,0,4))}else{let r=e.buffer[this.index+3];if(r<(s<0?e.buffer.length:e.buffer[this.stack[s]+3]))return this.yieldBuf(r)}return s<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+t,t,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(t){let e,s,{buffer:r}=this;if(r){if(t>0){if(this.index<r.buffer.buffer.length)return!1}else for(let i=0;i<this.index;i++)if(r.buffer.buffer[i+3]<this.index)return!1;({index:e,parent:s}=r)}else({index:e,_parent:s}=this._tree);for(;s;{index:e,_parent:s}=s)if(e>-1)for(let i=e+t,n=t<0?-1:s._tree.children.length;i!=n;i+=t){let l=s._tree.children[i];if(this.mode&T.IncludeAnonymous||l instanceof lt||!l.type.isAnonymous||Yt(l))return!1}return!0}move(t,e){if(e&&this.enterChild(t,0,4))return!0;for(;;){if(this.sibling(t))return!0;if(this.atLastNode(t)||!this.parent())return!1}}next(t=!0){return this.move(1,t)}prev(t=!0){return this.move(-1,t)}moveTo(t,e=0){for(;(this.from==this.to||(e<1?this.from>=t:this.from>t)||(e>-1?this.to<=t:this.to<t))&&this.parent(););for(;this.enterChild(1,t,e););return this}get node(){if(!this.buffer)return this._tree;let t=this.bufferNode,e=null,s=0;if(t&&t.context==this.buffer)t:for(let r=this.index,i=this.stack.length;i>=0;){for(let n=t;n;n=n._parent)if(n.index==r){if(r==this.index)return n;e=n,s=i+1;break t}r=this.stack[--i]}for(let r=s;r<this.stack.length;r++)e=new Pt(this.buffer,e,this.stack[r]);return this.bufferNode=new Pt(this.buffer,e,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(t,e){for(let s=0;;){let r=!1;if(this.type.isAnonymous||t(this)!==!1){if(this.firstChild()){s++;continue}this.type.isAnonymous||(r=!0)}for(;r&&e&&e(this),r=this.type.isAnonymous,!this.nextSibling();){if(!s)return;this.parent(),s--,r=!0}}}matchContext(t){if(!this.buffer)return Mt(this.node,t);let{buffer:e}=this.buffer,{types:s}=e.set;for(let r=t.length-1,i=this.stack.length-1;r>=0;i--){if(i<0)return Mt(this.node,t,r);let n=s[e.buffer[this.stack[i]]];if(!n.isAnonymous){if(t[r]&&t[r]!=n.name)return!1;r--}}return!0}};function Yt(o){return o.children.some(t=>t instanceof lt||!t.type.isAnonymous||Yt(t))}function ss(o){var t;let{buffer:e,nodeSet:s,maxBufferLength:r=1024,reused:i=[],minRepeatType:n=s.types.length}=o,l=Array.isArray(e)?new Wt(e,e.length):e,h=s.types,a=0,f=0;function c(R,v,b,k,N){let{id:x,start:y,end:D,size:B}=l,$=f;for(;B<0;)if(l.next(),B==-1){let H=i[x];b.push(H),k.push(y-R);return}else if(B==-3){a=x;return}else if(B==-4){f=x;return}else throw new RangeError(`Unrecognized record size: ${B}`);let pt=h[x],q,Y,be=y-R;if(D-y<=r&&(Y=Z(l.pos-v,N))){let H=new Uint16Array(Y.size-Y.skip),j=l.pos-Y.size,K=H.length;for(;l.pos>j;)K=ft(Y.start,H,K);q=new lt(H,D-Y.start,s),be=Y.start-R}else{let H=l.pos-B;l.next();let j=[],K=[],ot=x>=n?x:-1,dt=0,Dt=D;for(;l.pos>H;)ot>=0&&l.id==ot&&l.size>=0?(l.end<=Dt-r&&(g(j,K,y,dt,l.end,Dt,ot,$),dt=j.length,Dt=l.end),l.next()):c(y,H,j,K,ot);if(ot>=0&&dt>0&&dt<j.length&&g(j,K,y,dt,y,Dt,ot,$),j.reverse(),K.reverse(),ot>-1&&dt>0){let we=p(pt);q=Kt(pt,j,K,0,j.length,0,D-y,we,we)}else q=S(pt,j,K,D-y,$-D)}b.push(q),k.push(be)}function p(R){return(v,b,k)=>{let N=0,x=v.length-1,y,D;if(x>=0&&(y=v[x])instanceof E){if(!x&&y.type==R&&y.length==k)return y;(D=y.prop(C.lookAhead))&&(N=b[x]+y.length+D)}return S(R,v,b,k,N)}}function g(R,v,b,k,N,x,y,D){let B=[],$=[];for(;R.length>k;)B.push(R.pop()),$.push(v.pop()+b-N);R.push(S(s.types[y],B,$,x-N,D-x)),v.push(N-b)}function S(R,v,b,k,N=0,x){if(a){let y=[C.contextHash,a];x=x?[y].concat(x):[y]}if(N>25){let y=[C.lookAhead,N];x=x?[y].concat(x):[y]}return new E(R,v,b,k,x)}function Z(R,v){let b=l.fork(),k=0,N=0,x=0,y=b.end-r,D={size:0,start:0,skip:0};t:for(let B=b.pos-R;b.pos>B;){let $=b.size;if(b.id==v&&$>=0){D.size=k,D.start=N,D.skip=x,x+=4,k+=4,b.next();continue}let pt=b.pos-$;if($<0||pt<B||b.start<y)break;let q=b.id>=n?4:0,Y=b.start;for(b.next();b.pos>pt;){if(b.size<0)if(b.size==-3)q+=4;else break t;else b.id>=n&&(q+=4);b.next()}N=Y,k+=$,x+=q}return(v<0||k==R)&&(D.size=k,D.start=N,D.skip=x),D.size>4?D:void 0}function ft(R,v,b){let{id:k,start:N,end:x,size:y}=l;if(l.next(),y>=0&&k<n){let D=b;if(y>4){let B=l.pos-(y-4);for(;l.pos>B;)b=ft(R,v,b)}v[--b]=D,v[--b]=x-R,v[--b]=N-R,v[--b]=k}else y==-3?a=k:y==-4&&(f=k);return b}let nt=[],ct=[];for(;l.pos>0;)c(o.start||0,o.bufferStart||0,nt,ct,-1);let V=(t=o.length)!==null&&t!==void 0?t:nt.length?ct[0]+nt[0].length:0;return new E(h[o.topID],nt.reverse(),ct.reverse(),V)}var ke=new WeakMap;function Tt(o,t){if(!o.isAnonymous||t instanceof lt||t.type!=o)return 1;let e=ke.get(t);if(e==null){e=1;for(let s of t.children){if(s.type!=o||!(s instanceof E)){e=1;break}e+=Tt(o,s)}ke.set(t,e)}return e}function Kt(o,t,e,s,r,i,n,l,h){let a=0;for(let S=s;S<r;S++)a+=Tt(o,t[S]);let f=Math.ceil(a*1.5/8),c=[],p=[];function g(S,Z,ft,nt,ct){for(let V=ft;V<nt;){let R=V,v=Z[V],b=Tt(o,S[V]);for(V++;V<nt;V++){let k=Tt(o,S[V]);if(b+k>=f)break;b+=k}if(V==R+1){if(b>f){let k=S[R];g(k.children,k.positions,0,k.children.length,Z[R]+ct);continue}c.push(S[R])}else{let k=Z[V-1]+S[V-1].length-v;c.push(Kt(o,S,Z,R,V,v,k,null,h))}p.push(v+ct-i)}}return g(t,e,s,r,0),(l||h)(c,p,n)}var Ft=class{startParse(t,e,s){return typeof t=="string"&&(t=new Xt(t)),s=s?s.length?s.map(r=>new Rt(r.from,r.to)):[new Rt(0,0)]:[new Rt(0,t.length)],this.createParse(t,e||[],s)}parse(t,e,s){let r=this.startParse(t,e,s);for(;;){let i=r.advance();if(i)return i}}},Xt=class{constructor(t){this.string=t}get length(){return this.string.length}chunk(t){return this.string.slice(t)}get lineChunks(){return!1}read(t,e){return this.string.slice(t,e)}};var Gs=new C({perNode:!0});var Zt=class o{constructor(t,e,s,r,i,n,l,h,a,f=0,c){this.p=t,this.stack=e,this.state=s,this.reducePos=r,this.pos=i,this.score=n,this.buffer=l,this.bufferBase=h,this.curContext=a,this.lookAhead=f,this.parent=c}toString(){return`[${this.stack.filter((t,e)=>e%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(t,e,s=0){let r=t.parser.context;return new o(t,[],e,s,s,0,[],0,r?new Vt(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(t,e){this.stack.push(this.state,e,this.bufferBase+this.buffer.length),this.state=t}reduce(t){var e;let s=t>>19,r=t&65535,{parser:i}=this.p,n=i.dynamicPrecedence(r);if(n&&(this.score+=n),s==0){this.pushState(i.getGoto(this.state,r,!0),this.reducePos),r<i.minRepeatTerm&&this.storeNode(r,this.reducePos,this.reducePos,4,!0),this.reduceContext(r,this.reducePos);return}let l=this.stack.length-(s-1)*3-(t&262144?6:0),h=l?this.stack[l-2]:this.p.ranges[0].from,a=this.reducePos-h;a>=2e3&&!(!((e=this.p.parser.nodeSet.types[r])===null||e===void 0)&&e.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=a):this.p.lastBigReductionSize<a&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=h,this.p.lastBigReductionSize=a));let f=l?this.stack[l-1]:0,c=this.bufferBase+this.buffer.length-f;if(r<i.minRepeatTerm||t&131072){let p=i.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(r,h,p,c+4,!0)}if(t&262144)this.state=this.stack[l];else{let p=this.stack[l-3];this.state=i.getGoto(p,r,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(r,h)}storeNode(t,e,s,r=4,i=!1){if(t==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let n=this,l=this.buffer.length;if(l==0&&n.parent&&(l=n.bufferBase-n.parent.bufferBase,n=n.parent),l>0&&n.buffer[l-4]==0&&n.buffer[l-1]>-1){if(e==s)return;if(n.buffer[l-2]>=e){n.buffer[l-2]=s;return}}}if(!i||this.pos==s)this.buffer.push(t,e,s,r);else{let n=this.buffer.length;if(n>0&&this.buffer[n-4]!=0)for(;n>0&&this.buffer[n-2]>s;)this.buffer[n]=this.buffer[n-4],this.buffer[n+1]=this.buffer[n-3],this.buffer[n+2]=this.buffer[n-2],this.buffer[n+3]=this.buffer[n-1],n-=4,r>4&&(r-=4);this.buffer[n]=t,this.buffer[n+1]=e,this.buffer[n+2]=s,this.buffer[n+3]=r}}shift(t,e,s){let r=this.pos;if(t&131072)this.pushState(t&65535,this.pos);else if(t&262144)this.pos=s,this.shiftContext(e,r),e<=this.p.parser.maxNode&&this.buffer.push(e,r,s,4);else{let i=t,{parser:n}=this.p;(s>this.pos||e<=n.maxNode)&&(this.pos=s,n.stateFlag(i,1)||(this.reducePos=s)),this.pushState(i,r),this.shiftContext(e,r),e<=n.maxNode&&this.buffer.push(e,r,s,4)}}apply(t,e,s){t&65536?this.reduce(t):this.shift(t,e,s)}useNode(t,e){let s=this.p.reused.length-1;(s<0||this.p.reused[s]!=t)&&(this.p.reused.push(t),s++);let r=this.pos;this.reducePos=this.pos=r+t.length,this.pushState(e,r),this.buffer.push(s,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,t,this,this.p.stream.reset(this.pos-t.length)))}split(){let t=this,e=t.buffer.length;for(;e>0&&t.buffer[e-2]>t.reducePos;)e-=4;let s=t.buffer.slice(e),r=t.bufferBase+e;for(;t&&r==t.bufferBase;)t=t.parent;return new o(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,s,r,this.curContext,this.lookAhead,t)}recoverByDelete(t,e){let s=t<=this.p.parser.maxNode;s&&this.storeNode(t,this.pos,e,4),this.storeNode(0,this.pos,e,s?8:4),this.pos=this.reducePos=e,this.score-=190}canShift(t){for(let e=new qt(this);;){let s=this.p.parser.stateSlot(e.state,4)||this.p.parser.hasAction(e.state,t);if(s==0)return!1;if(!(s&65536))return!0;e.reduce(s)}}recoverByInsert(t){if(this.stack.length>=300)return[];let e=this.p.parser.nextStates(this.state);if(e.length>8||this.stack.length>=120){let r=[];for(let i=0,n;i<e.length;i+=2)(n=e[i+1])!=this.state&&this.p.parser.hasAction(n,t)&&r.push(e[i],n);if(this.stack.length<120)for(let i=0;r.length<8&&i<e.length;i+=2){let n=e[i+1];r.some((l,h)=>h&1&&l==n)||r.push(e[i],n)}e=r}let s=[];for(let r=0;r<e.length&&s.length<4;r+=2){let i=e[r+1];if(i==this.state)continue;let n=this.split();n.pushState(i,this.pos),n.storeNode(0,n.pos,n.pos,4,!0),n.shiftContext(e[r],this.pos),n.score-=200,s.push(n)}return s}forceReduce(){let{parser:t}=this.p,e=t.stateSlot(this.state,5);if(!(e&65536))return!1;if(!t.validAction(this.state,e)){let s=e>>19,r=e&65535,i=this.stack.length-s*3;if(i<0||t.getGoto(this.stack[i],r,!1)<0){let n=this.findForcedReduction();if(n==null)return!1;e=n}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(e),!0}findForcedReduction(){let{parser:t}=this.p,e=[],s=(r,i)=>{if(!e.includes(r))return e.push(r),t.allActions(r,n=>{if(!(n&393216))if(n&65536){let l=(n>>19)-i;if(l>1){let h=n&65535,a=this.stack.length-l*3;if(a>=0&&t.getGoto(this.stack[a],h,!1)>=0)return l<<19|65536|h}}else{let l=s(n,i+1);if(l!=null)return l}})};return s(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:t}=this.p;return t.data[t.stateSlot(this.state,1)]==65535&&!t.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(t){if(this.state!=t.state||this.stack.length!=t.stack.length)return!1;for(let e=0;e<this.stack.length;e+=3)if(this.stack[e]!=t.stack[e])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(t){return this.p.parser.dialect.flags[t]}shiftContext(t,e){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,t,this,this.p.stream.reset(e)))}reduceContext(t,e){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,t,this,this.p.stream.reset(e)))}emitContext(){let t=this.buffer.length-1;(t<0||this.buffer[t]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let t=this.buffer.length-1;(t<0||this.buffer[t]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(t){if(t!=this.curContext.context){let e=new Vt(this.curContext.tracker,t);e.hash!=this.curContext.hash&&this.emitContext(),this.curContext=e}}setLookAhead(t){t>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=t)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},Vt=class{constructor(t,e){this.tracker=t,this.context=e,this.hash=t.strict?t.hash(e):0}},Re;(function(o){o[o.Insert=200]="Insert",o[o.Delete=190]="Delete",o[o.Reduce=100]="Reduce",o[o.MaxNext=4]="MaxNext",o[o.MaxInsertStackDepth=300]="MaxInsertStackDepth",o[o.DampenInsertStackDepth=120]="DampenInsertStackDepth",o[o.MinBigReduction=2e3]="MinBigReduction"})(Re||(Re={}));var qt=class{constructor(t){this.start=t,this.state=t.state,this.stack=t.stack,this.base=this.stack.length}reduce(t){let e=t&65535,s=t>>19;s==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(s-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],e,!0);this.state=r}},Ht=class o{constructor(t,e,s){this.stack=t,this.pos=e,this.index=s,this.buffer=t.buffer,this.index==0&&this.maybeNext()}static create(t,e=t.bufferBase+t.buffer.length){return new o(t,e,e-t.bufferBase)}maybeNext(){let t=this.stack.parent;t!=null&&(this.index=this.stack.bufferBase-t.bufferBase,this.stack=t,this.buffer=t.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new o(this.stack,this.pos,this.index)}};function Ot(o,t=Uint16Array){if(typeof o!="string")return o;let e=null;for(let s=0,r=0;s<o.length;){let i=0;for(;;){let n=o.charCodeAt(s++),l=!1;if(n==126){i=65535;break}n>=92&&n--,n>=34&&n--;let h=n-32;if(h>=46&&(h-=46,l=!0),i+=h,l)break;i*=46}e?e[r++]=i:e=new t(i)}return e}var bt=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},Pe=new bt,te=class{constructor(t,e){this.input=t,this.ranges=e,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Pe,this.rangeIndex=0,this.pos=this.chunkPos=e[0].from,this.range=e[0],this.end=e[e.length-1].to,this.readNext()}resolveOffset(t,e){let s=this.range,r=this.rangeIndex,i=this.pos+t;for(;i<s.from;){if(!r)return null;let n=this.ranges[--r];i-=s.from-n.to,s=n}for(;e<0?i>s.to:i>=s.to;){if(r==this.ranges.length-1)return null;let n=this.ranges[++r];i+=n.from-s.to,s=n}return i}clipPos(t){if(t>=this.range.from&&t<this.range.to)return t;for(let e of this.ranges)if(e.to>t)return Math.max(t,e.from);return this.end}peek(t){let e=this.chunkOff+t,s,r;if(e>=0&&e<this.chunk.length)s=this.pos+t,r=this.chunk.charCodeAt(e);else{let i=this.resolveOffset(t,1);if(i==null)return-1;if(s=i,s>=this.chunk2Pos&&s<this.chunk2Pos+this.chunk2.length)r=this.chunk2.charCodeAt(s-this.chunk2Pos);else{let n=this.rangeIndex,l=this.range;for(;l.to<=s;)l=this.ranges[++n];this.chunk2=this.input.chunk(this.chunk2Pos=s),s+this.chunk2.length>l.to&&(this.chunk2=this.chunk2.slice(0,l.to-s)),r=this.chunk2.charCodeAt(0)}}return s>=this.token.lookAhead&&(this.token.lookAhead=s+1),r}acceptToken(t,e=0){let s=e?this.resolveOffset(e,-1):this.pos;if(s==null||s<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=t,this.token.end=s}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:t,chunkPos:e}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=t,this.chunk2Pos=e,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let t=this.input.chunk(this.pos),e=this.pos+t.length;this.chunk=e>this.range.to?t.slice(0,this.range.to-this.pos):t,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(t=1){for(this.chunkOff+=t;this.pos+t>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();t-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=t,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(t,e){if(e?(this.token=e,e.start=t,e.lookAhead=t+1,e.value=e.extended=-1):this.token=Pe,this.pos!=t){if(this.pos=t,t==this.end)return this.setDone(),this;for(;t<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;t>=this.range.to;)this.range=this.ranges[++this.rangeIndex];t>=this.chunkPos&&t<this.chunkPos+this.chunk.length?this.chunkOff=t-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(t,e){if(t>=this.chunkPos&&e<=this.chunkPos+this.chunk.length)return this.chunk.slice(t-this.chunkPos,e-this.chunkPos);if(t>=this.chunk2Pos&&e<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(t-this.chunk2Pos,e-this.chunk2Pos);if(t>=this.range.from&&e<=this.range.to)return this.input.read(t,e);let s="";for(let r of this.ranges){if(r.from>=e)break;r.to>t&&(s+=this.input.read(Math.max(r.from,t),Math.min(r.to,e)))}return s}},tt=class{constructor(t,e){this.data=t,this.id=e}token(t,e){let{parser:s}=e.p;Ne(this.data,t,e,this.id,s.data,s.tokenPrecTable)}};tt.prototype.contextual=tt.prototype.fallback=tt.prototype.extend=!1;var ee=class{constructor(t,e,s){this.precTable=e,this.elseToken=s,this.data=typeof t=="string"?Ot(t):t}token(t,e){let s=t.pos,r=0;for(;;){let i=t.next<0,n=t.resolveOffset(1,1);if(Ne(this.data,t,e,0,this.data,this.precTable),t.token.value>-1)break;if(this.elseToken==null)return;if(i||r++,n==null)break;t.reset(n,t.token)}r&&(t.reset(s,t.token),t.acceptToken(this.elseToken,r))}};ee.prototype.contextual=tt.prototype.fallback=tt.prototype.extend=!1;function Ne(o,t,e,s,r,i){let n=0,l=1<<s,{dialect:h}=e.p.parser;t:for(;l&o[n];){let a=o[n+1];for(let g=n+3;g<a;g+=2)if((o[g+1]&l)>0){let S=o[g];if(h.allows(S)&&(t.token.value==-1||t.token.value==S||is(S,t.token.value,r,i))){t.acceptToken(S);break}}let f=t.next,c=0,p=o[n+2];if(t.next<0&&p>c&&o[a+p*3-3]==65535&&o[a+p*3-3]==65535){n=o[a+p*3-1];continue t}for(;c<p;){let g=c+p>>1,S=a+g+(g<<1),Z=o[S],ft=o[S+1]||65536;if(f<Z)p=g;else if(f>=ft)c=g+1;else{n=o[S+2],t.advance();continue t}}break}}function Oe(o,t,e){for(let s=t,r;(r=o[s])!=65535;s++)if(r==e)return s-t;return-1}function is(o,t,e,s){let r=Oe(e,s,t);return r<0||Oe(e,s,o)<r}var W=typeof process<"u"&&process.env&&/\bparse\b/.test(process.env.LOG),Jt=null,ve;(function(o){o[o.Margin=25]="Margin"})(ve||(ve={}));function De(o,t,e){let s=o.cursor(T.IncludeAnonymous);for(s.moveTo(t);;)if(!(e<0?s.childBefore(t):s.childAfter(t)))for(;;){if((e<0?s.to<t:s.from>t)&&!s.type.isError)return e<0?Math.max(0,Math.min(s.to-1,t-25)):Math.min(o.length,Math.max(s.from+1,t+25));if(e<0?s.prevSibling():s.nextSibling())break;if(!s.parent())return e<0?0:o.length}}var se=class{constructor(t,e){this.fragments=t,this.nodeSet=e,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let t=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(t){for(this.safeFrom=t.openStart?De(t.tree,t.from+t.offset,1)-t.offset:t.from,this.safeTo=t.openEnd?De(t.tree,t.to+t.offset,-1)-t.offset:t.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(t.tree),this.start.push(-t.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(t){if(t<this.nextStart)return null;for(;this.fragment&&this.safeTo<=t;)this.nextFragment();if(!this.fragment)return null;for(;;){let e=this.trees.length-1;if(e<0)return this.nextFragment(),null;let s=this.trees[e],r=this.index[e];if(r==s.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let i=s.children[r],n=this.start[e]+s.positions[r];if(n>t)return this.nextStart=n,null;if(i instanceof E){if(n==t){if(n<this.safeFrom)return null;let l=n+i.length;if(l<=this.safeTo){let h=i.prop(C.lookAhead);if(!h||l+h<this.fragment.to)return i}}this.index[e]++,n+i.length>=Math.max(this.safeFrom,t)&&(this.trees.push(i),this.start.push(n),this.index.push(0))}else this.index[e]++,this.nextStart=n+i.length}}},re=class{constructor(t,e){this.stream=e,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=t.tokenizers.map(s=>new bt)}getActions(t){let e=0,s=null,{parser:r}=t.p,{tokenizers:i}=r,n=r.stateSlot(t.state,3),l=t.curContext?t.curContext.hash:0,h=0;for(let a=0;a<i.length;a++){if(!(1<<a&n))continue;let f=i[a],c=this.tokens[a];if(!(s&&!f.fallback)&&((f.contextual||c.start!=t.pos||c.mask!=n||c.context!=l)&&(this.updateCachedToken(c,f,t),c.mask=n,c.context=l),c.lookAhead>c.end+25&&(h=Math.max(c.lookAhead,h)),c.value!=0)){let p=e;if(c.extended>-1&&(e=this.addActions(t,c.extended,c.end,e)),e=this.addActions(t,c.value,c.end,e),!f.extend&&(s=c,e>p))break}}for(;this.actions.length>e;)this.actions.pop();return h&&t.setLookAhead(h),!s&&t.pos==this.stream.end&&(s=new bt,s.value=t.p.parser.eofTerm,s.start=s.end=t.pos,e=this.addActions(t,s.value,s.end,e)),this.mainToken=s,this.actions}getMainToken(t){if(this.mainToken)return this.mainToken;let e=new bt,{pos:s,p:r}=t;return e.start=s,e.end=Math.min(s+1,r.stream.end),e.value=s==r.stream.end?r.parser.eofTerm:0,e}updateCachedToken(t,e,s){let r=this.stream.clipPos(s.pos);if(e.token(this.stream.reset(r,t),s),t.value>-1){let{parser:i}=s.p;for(let n=0;n<i.specialized.length;n++)if(i.specialized[n]==t.value){let l=i.specializers[n](this.stream.read(t.start,t.end),s);if(l>=0&&s.p.parser.dialect.allows(l>>1)){l&1?t.extended=l>>1:t.value=l>>1;break}}}else t.value=0,t.end=this.stream.clipPos(r+1)}putAction(t,e,s,r){for(let i=0;i<r;i+=3)if(this.actions[i]==t)return r;return this.actions[r++]=t,this.actions[r++]=e,this.actions[r++]=s,r}addActions(t,e,s,r){let{state:i}=t,{parser:n}=t.p,{data:l}=n;for(let h=0;h<2;h++)for(let a=n.stateSlot(i,h?2:1);;a+=3){if(l[a]==65535)if(l[a+1]==1)a=J(l,a+2);else{r==0&&l[a+1]==2&&(r=this.putAction(J(l,a+2),e,s,r));break}l[a]==e&&(r=this.putAction(J(l,a+1),e,s,r))}return r}},Ae;(function(o){o[o.Distance=5]="Distance",o[o.MaxRemainingPerStep=3]="MaxRemainingPerStep",o[o.MinBufferLengthPrune=500]="MinBufferLengthPrune",o[o.ForceReduceLimit=10]="ForceReduceLimit",o[o.CutDepth=15e3]="CutDepth",o[o.CutTo=9e3]="CutTo",o[o.MaxLeftAssociativeReductionCount=300]="MaxLeftAssociativeReductionCount",o[o.MaxStackCount=12]="MaxStackCount"})(Ae||(Ae={}));var ie=class{constructor(t,e,s,r){this.parser=t,this.input=e,this.ranges=r,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new te(e,r),this.tokens=new re(t,this.stream),this.topTerm=t.top[1];let{from:i}=r[0];this.stacks=[Zt.start(this,t.top[0],i)],this.fragments=s.length&&this.stream.end-i>t.bufferLength*4?new se(s,t.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let t=this.stacks,e=this.minStackPos,s=this.stacks=[],r,i;if(this.bigReductionCount>300&&t.length==1){let[n]=t;for(;n.forceReduce()&&n.stack.length&&n.stack[n.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let n=0;n<t.length;n++){let l=t[n];for(;;){if(this.tokens.mainToken=null,l.pos>e)s.push(l);else{if(this.advanceStack(l,s,t))continue;{r||(r=[],i=[]),r.push(l);let h=this.tokens.getMainToken(l);i.push(h.value,h.end)}}break}}if(!s.length){let n=r&&ns(r);if(n)return this.stackToTree(n);if(this.parser.strict)throw W&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+e);this.recovering||(this.recovering=5)}if(this.recovering&&r){let n=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,i,s);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let n=this.recovering==1?1:this.recovering*3;if(s.length>n)for(s.sort((l,h)=>h.score-l.score);s.length>n;)s.pop();s.some(l=>l.reducePos>e)&&this.recovering--}else if(s.length>1){t:for(let n=0;n<s.length-1;n++){let l=s[n];for(let h=n+1;h<s.length;h++){let a=s[h];if(l.sameState(a)||l.buffer.length>500&&a.buffer.length>500)if((l.score-a.score||l.buffer.length-a.buffer.length)>0)s.splice(h--,1);else{s.splice(n--,1);continue t}}}s.length>12&&s.splice(12,s.length-12)}this.minStackPos=s[0].pos;for(let n=1;n<s.length;n++)s[n].pos<this.minStackPos&&(this.minStackPos=s[n].pos);return null}stopAt(t){if(this.stoppedAt!=null&&this.stoppedAt<t)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=t}advanceStack(t,e,s){let r=t.pos,{parser:i}=this,n=W?this.stackID(t)+" -> ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return t.forceReduce()?t:null;if(this.fragments){let a=t.curContext&&t.curContext.tracker.strict,f=a?t.curContext.hash:0;for(let c=this.fragments.nodeAt(r);c;){let p=this.parser.nodeSet.types[c.type.id]==c.type?i.getGoto(t.state,c.type.id):-1;if(p>-1&&c.length&&(!a||(c.prop(C.contextHash)||0)==f))return t.useNode(c,p),W&&console.log(n+this.stackID(t)+` (via reuse of ${i.getName(c.type.id)})`),!0;if(!(c instanceof E)||c.children.length==0||c.positions[0]>0)break;let g=c.children[0];if(g instanceof E&&c.positions[0]==0)c=g;else break}}let l=i.stateSlot(t.state,4);if(l>0)return t.reduce(l),W&&console.log(n+this.stackID(t)+` (via always-reduce ${i.getName(l&65535)})`),!0;if(t.stack.length>=15e3)for(;t.stack.length>9e3&&t.forceReduce(););let h=this.tokens.getActions(t);for(let a=0;a<h.length;){let f=h[a++],c=h[a++],p=h[a++],g=a==h.length||!s,S=g?t:t.split();if(S.apply(f,c,p),W&&console.log(n+this.stackID(S)+` (via ${f&65536?`reduce of ${i.getName(f&65535)}`:"shift"} for ${i.getName(c)} @ ${r}${S==t?"":", split"})`),g)return!0;S.pos>r?e.push(S):s.push(S)}return!1}advanceFully(t,e){let s=t.pos;for(;;){if(!this.advanceStack(t,null,null))return!1;if(t.pos>s)return Te(t,e),!0}}runRecovery(t,e,s){let r=null,i=!1;for(let n=0;n<t.length;n++){let l=t[n],h=e[n<<1],a=e[(n<<1)+1],f=W?this.stackID(l)+" -> ":"";if(l.deadEnd&&(i||(i=!0,l.restart(),W&&console.log(f+this.stackID(l)+" (restarted)"),this.advanceFully(l,s))))continue;let c=l.split(),p=f;for(let g=0;c.forceReduce()&&g<10&&(W&&console.log(p+this.stackID(c)+" (via force-reduce)"),!this.advanceFully(c,s));g++)W&&(p=this.stackID(c)+" -> ");for(let g of l.recoverByInsert(h))W&&console.log(f+this.stackID(g)+" (via recover-insert)"),this.advanceFully(g,s);this.stream.end>l.pos?(a==l.pos&&(a++,h=0),l.recoverByDelete(h,a),W&&console.log(f+this.stackID(l)+` (via recover-delete ${this.parser.getName(h)})`),Te(l,s)):(!r||r.score<l.score)&&(r=l)}return r}stackToTree(t){return t.close(),E.build({buffer:Ht.create(t),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:t.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(t){let e=(Jt||(Jt=new WeakMap)).get(t);return e||Jt.set(t,e=String.fromCodePoint(this.nextStackID++)),e+t}};function Te(o,t){for(let e=0;e<t.length;e++){let s=t[e];if(s.pos==o.pos&&s.sameState(o)){t[e].score<o.score&&(t[e]=o);return}}t.push(o)}var ne=class{constructor(t,e,s){this.source=t,this.flags=e,this.disabled=s}allows(t){return!this.disabled||this.disabled[t]==0}};var Bt=class o extends Ft{constructor(t){if(super(),this.wrappers=[],t.version!=14)throw new RangeError(`Parser version (${t.version}) doesn't match runtime version (14)`);let e=t.nodeNames.split(" ");this.minRepeatTerm=e.length;for(let l=0;l<t.repeatNodeCount;l++)e.push("");let s=Object.keys(t.topRules).map(l=>t.topRules[l][1]),r=[];for(let l=0;l<e.length;l++)r.push([]);function i(l,h,a){r[l].push([h,h.deserialize(String(a))])}if(t.nodeProps)for(let l of t.nodeProps){let h=l[0];typeof h=="string"&&(h=C[h]);for(let a=1;a<l.length;){let f=l[a++];if(f>=0)i(f,h,l[a++]);else{let c=l[a+-f];for(let p=-f;p>0;p--)i(l[a++],h,c);a++}}}this.nodeSet=new It(e.map((l,h)=>z.define({name:h>=this.minRepeatTerm?void 0:l,id:h,props:r[h],top:s.indexOf(h)>-1,error:h==0,skipped:t.skippedNodes&&t.skippedNodes.indexOf(h)>-1}))),t.propSources&&(this.nodeSet=this.nodeSet.extend(...t.propSources)),this.strict=!1,this.bufferLength=1024;let n=Ot(t.tokenData);this.context=t.context,this.specializerSpecs=t.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;l<this.specializerSpecs.length;l++)this.specialized[l]=this.specializerSpecs[l].term;this.specializers=this.specializerSpecs.map(Ie),this.states=Ot(t.states,Uint32Array),this.data=Ot(t.stateData),this.goto=Ot(t.goto),this.maxTerm=t.maxTerm,this.tokenizers=t.tokenizers.map(l=>typeof l=="number"?new tt(n,l):l),this.topRules=t.topRules,this.dialects=t.dialects||{},this.dynamicPrecedences=t.dynamicPrecedences||null,this.tokenPrecTable=t.tokenPrec,this.termNames=t.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(t,e,s){let r=new ie(this,t,e,s);for(let i of this.wrappers)r=i(r,t,e,s);return r}getGoto(t,e,s=!1){let r=this.goto;if(e>=r[0])return-1;for(let i=r[e+1];;){let n=r[i++],l=n&1,h=r[i++];if(l&&s)return h;for(let a=i+(n>>1);i<a;i++)if(r[i]==t)return h;if(l)return-1}}hasAction(t,e){let s=this.data;for(let r=0;r<2;r++)for(let i=this.stateSlot(t,r?2:1),n;;i+=3){if((n=s[i])==65535)if(s[i+1]==1)n=s[i=J(s,i+2)];else{if(s[i+1]==2)return J(s,i+2);break}if(n==e||n==0)return J(s,i+1)}return 0}stateSlot(t,e){return this.states[t*6+e]}stateFlag(t,e){return(this.stateSlot(t,0)&e)>0}validAction(t,e){return!!this.allActions(t,s=>s==e?!0:null)}allActions(t,e){let s=this.stateSlot(t,4),r=s?e(s):void 0;for(let i=this.stateSlot(t,1);r==null;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=J(this.data,i+2);else break;r=e(J(this.data,i+1))}return r}nextStates(t){let e=[];for(let s=this.stateSlot(t,1);;s+=3){if(this.data[s]==65535)if(this.data[s+1]==1)s=J(this.data,s+2);else break;if(!(this.data[s+2]&1)){let r=this.data[s+1];e.some((i,n)=>n&1&&i==r)||e.push(this.data[s],r)}}return e}configure(t){let e=Object.assign(Object.create(o.prototype),this);if(t.props&&(e.nodeSet=this.nodeSet.extend(...t.props)),t.top){let s=this.topRules[t.top];if(!s)throw new RangeError(`Invalid top rule name ${t.top}`);e.top=s}return t.tokenizers&&(e.tokenizers=this.tokenizers.map(s=>{let r=t.tokenizers.find(i=>i.from==s);return r?r.to:s})),t.specializers&&(e.specializers=this.specializers.slice(),e.specializerSpecs=this.specializerSpecs.map((s,r)=>{let i=t.specializers.find(l=>l.from==s.external);if(!i)return s;let n=Object.assign(Object.assign({},s),{external:i.to});return e.specializers[r]=Ie(n),n})),t.contextTracker&&(e.context=t.contextTracker),t.dialect&&(e.dialect=this.parseDialect(t.dialect)),t.strict!=null&&(e.strict=t.strict),t.wrap&&(e.wrappers=e.wrappers.concat(t.wrap)),t.bufferLength!=null&&(e.bufferLength=t.bufferLength),e}hasWrappers(){return this.wrappers.length>0}getName(t){return this.termNames?this.termNames[t]:String(t<=this.maxNode&&this.nodeSet.types[t].name||t)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(t){let e=this.dynamicPrecedences;return e==null?0:e[t]||0}parseDialect(t){let e=Object.keys(this.dialects),s=e.map(()=>!1);if(t)for(let i of t.split(" ")){let n=e.indexOf(i);n>=0&&(s[n]=!0)}let r=null;for(let i=0;i<e.length;i++)if(!s[i])for(let n=this.dialects[e[i]],l;(l=this.data[n++])!=65535;)(r||(r=new Uint8Array(this.maxTerm+1)))[l]=1;return new ne(t,s,r)}static deserialize(t){return new o(t)}};function J(o,t){return o[t]|o[t+1]<<16}function ns(o){let t=null;for(let e of o){let s=e.p.stoppedAt;(e.pos==e.p.stream.end||s!=null&&e.pos>s)&&e.p.parser.stateFlag(e.state,2)&&(!t||t.score<e.score)&&(t=e)}return t}function Ie(o){if(o.external){let t=o.extend?1:0;return(e,s)=>o.external(e,s)<<1|t}return o.get}var oe=Bt.deserialize({version:14,states:"%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",stateData:"#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",goto:"#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",nodeNames:"\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",maxTerm:39,skippedNodes:[0],repeatNodeCount:1,tokenData:"6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",tokenizers:[0,1],topRules:{Filter:[0,1]},tokenPrec:0});var U=require("@vuu-ui/vuu-utils");var Q,le=class{constructor(){P(this,Q,void 0)}setFilterCombinatorOp(t,e=u(this,Q)){(0,U.isMultiClauseFilter)(e)&&e.op===t||m(this,Q,{op:t,filters:[u(this,Q)]})}add(t){if(u(this,Q)===void 0)m(this,Q,t);else if((0,U.isMultiClauseFilter)(u(this,Q)))u(this,Q).filters.push(t);else throw Error("Invalid filter passed to FilterExpression")}setColumn(t,e=u(this,Q)){if((0,U.isMultiClauseFilter)(e)){let s=e.filters.at(-1);s&&this.setColumn(t,s)}else e&&(e.column=t)}setOp(t,e=u(this,Q)){if((0,U.isMultiClauseFilter)(e)){let s=e.filters.at(-1);s&&this.setOp(t,s)}else e&&(e.op=t)}setValue(t,e=u(this,Q)){var s;if((0,U.isMultiClauseFilter)(e)){let r=e.filters.at(-1);r&&this.setValue(t,r)}else(0,U.isMultiValueFilter)(e)?((s=e.values)!=null||(e.values=[]),e.values.push(t)):(0,U.isSingleValueFilter)(e)&&(e.value=t)}toJSON(t=u(this,Q)){return this.name?{...t,name:this.name}:t}};Q=new WeakMap;var he=(o,t)=>{let e=new le,s=o.cursor();do{let{name:r,from:i,to:n}=s;switch(r){case"ColumnValueExpression":e.add({});break;case"ColumnSetExpression":e.add({op:"in"});break;case"Or":case"And":e.setFilterCombinatorOp(t.substring(i,n));break;case"Column":e.setColumn(t.substring(i,n));break;case"Operator":e.setOp(t.substring(i,n));break;case"String":e.setValue(t.substring(i+1,n-1));break;case"Number":e.setValue(parseFloat(t.substring(i,n)));break;case"True":e.setValue(!0);break;case"False":e.setValue(!1);break;case"FilterName":e.name=t.substring(i,n);break;default:}}while(s.next());return e.toJSON()};var os=oe.configure({strict:!0}),wt=o=>{let t=os.parse(o);return he(t,o)};function Et(o,t){switch(t.op){case"in":return ls(o,t);case"=":return hs(o,t);case">":return as(o,t);case">=":return us(o,t);case"<":return fs(o,t);case"<=":return cs(o,t);case"ends":return ps(o,t);case"starts":return ds(o,t);case"and":return gs(o,t);case"or":return ms(o,t);default:return console.log(`unrecognized filter type ${t.op}`),()=>!0}}var ls=(o,t)=>e=>t.values.indexOf(e[o[t.column]])!==-1,hs=(o,t)=>e=>e[o[t.column]]===t.value,as=(o,t)=>e=>e[o[t.column]]>t.value,us=(o,t)=>e=>e[o[t.column]]>=t.value,fs=(o,t)=>e=>e[o[t.column]]<t.value,cs=(o,t)=>e=>e[o[t.column]]<=t.value,ps=(o,t)=>{let e=t.value;if(typeof e!="string")throw Error("string filter applied to value of wrong type");return s=>{let r=s[o[t.column]];if(typeof r!="string")throw Error("string filter applied to value of wrong type");return r.toLowerCase().endsWith(e.toLowerCase())}},ds=(o,t)=>{let e=t.value;if(typeof e!="string")throw Error("string filter applied to value of wrong type");return s=>{let r=s[o[t.column]];if(typeof r!="string")throw Error("string filter applied to value of wrong type");return r.toLowerCase().startsWith(e.toLowerCase())}},gs=(o,t)=>{let e=t.filters.map(s=>Et(o,s));return s=>e.every(r=>r(s))};function ms(o,t){let e=t.filters.map(s=>Et(o,s));return s=>e.some(r=>r(s))}var d=require("@vuu-ui/vuu-utils");var Me=(o,t,e,s,r,i)=>{let n=o[o.length-1].aggType,l=e.map(h=>r[h]);switch(n){case 1:return Ve(i,s,r,o,t,l);case 2:return bs(i,s,r,o,t,l);case 3:return Fe(i,r,o,t,l);case 4:return Ss(i,s,r,o,t,l);case 5:return ys(i,s,r,o,t,l);case 6:return ws(i,s,r,o,t,l)}};function Fe(o,t,e,s,r){let i={},n=St(t,e);function l(h){if(Array.isArray(h))return h.length;{let a=0;for(let f in h)a+=1+l(h[f]);return a}}for(let h in o){let a=l(o[h]);i[h]=a}for(let h=0;h<s.length;h++)for(let a in i)s[h][r[0]]===a&&(s[h][n]=i[a]);return console.log("!!!! targetData",s),console.log("!!!! counts",i),i}function St(o,t){console.log("!!!! aggregation length",t.length);let e=t[t.length-1].column;return o[e]}function Ve(o,t,e,s,r,i){let n={},l=St(e,s);function h(a,f,c){if(Array.isArray(a)){let p=0;for(let g of a)p+=Number(f[g][c]);return p}else{let p=0;for(let g in a)p+=h(a[g],f,c);return p}}for(let a in o){console.log(a);let f=Number(h(o[a],t,l));n[a]=f}for(let a=0;a<r.length;a++)for(let f in n)r[a][i[0]]===f&&(r[a][l]=n[f]);return console.log("!!!! targetData",r),console.log("!!!! sums",n),n}function bs(o,t,e,s,r,i){let n={},l=St(e,s),h=Fe(o,e,s,r,i),a=Ve(o,t,e,s,r,i);for(let f in h){let c=0;c=a[f]/h[f],n[f]=c}for(let f=0;f<r.length;f++)for(let c in n)r[f][i[0]]===c&&(r[f][l]=n[c]);return console.log("!!!! targetData",r),console.log("!!!! averages",n),n}function Qt(o,t,e){let s=[];if(Array.isArray(o))for(let r of o)s.push(t[r][e]);else for(let r in o)s.push(...Qt(o[r],t,e));return s}function ws(o,t,e,s,r,i){let n={},l=St(e,s);for(let h in o){let a=Qt(o[h],t,l),f=[...new Set(a)];n[h]=f}for(let h=0;h<r.length;h++)for(let a in n)r[h][i[0]]===a&&(r[h][l]=n[a]);return n}function Ss(o,t,e,s,r,i){let n={},l=St(e,s);for(let h in o){let a=Qt(o[h],t,l),f=Math.max(...a);n[h]=f}for(let h=0;h<r.length;h++)for(let a in n)r[h][i[0]]===a&&(r[h][l]=n[a]);return n}function ys(o,t,e,s,r,i){let n={},l=St(e,s);for(let h in o){let a=Qt(o[h],t,l),f=Math.min(...a);n[h]=f}for(let h=0;h<r.length;h++)for(let a in n)r[h][i[0]]===a&&(r[h][l]=n[a]);return n}var at=require("@vuu-ui/vuu-utils"),{RENDER_IDX:ks,SELECTED:xs}=at.metadataKeys,ae=(o,t,e,s)=>{let[r]=o,i;if(s){let{count:n}=at.metadataKeys;i=o.slice(0,n).concat(s.map(l=>o[l]))}else i=o.slice();return i[ks]=t.keyFor(r),i[xs]=(0,at.getSelectionStatus)(e,r),i},Cs=(o,t)=>{if(t){let{count:e}=at.metadataKeys;for(let[s,r]of Object.entries(o)){let i=t[s];if(i===void 0)throw Error(`ArrayDataSource column ${s} is not in underlying data set`);if(i!==r-e)return!0}}return!1},Rs=(o,t)=>{let{count:e}=at.metadataKeys,s=[];return Object.entries(o).forEach(([r])=>{s.push(t[r]+e)}),s},ue=(o,t)=>{if(t&&Cs(o,t))return Rs(o,t)};var Be=require("@vuu-ui/vuu-utils"),{DEPTH:fe,IS_EXPANDED:Ee,KEY:ce}=Be.metadataKeys,Qe=(o,t)=>{let e=[];for(let s=0,r=0,i=!1,n=t.length;s<n;s++){let l=t[s],{[fe]:h,[ce]:a}=l;if(a===o){let f=l.slice();for(f[Ee]=!1,e.push(f),r+=1,i=!0;s<n-1&&t[s+1][fe]>h;)s+=1}else if(i){let f=l.slice();f[0]=r,f[1]=r,e.push(f),r+=1}else e.push(l),r+=1}return e},pe=(o,t,e,s,r,i)=>{let n=e.map(l=>s[l]);return ze(r,n,o,t,void 0,void 0,void 0,i)},ze=(o,t,e,s=[],r="$root",i=1,n=[],l)=>{console.log("dataRowsFromGroups2 1)");let h=Object.keys(o).sort();for(let a of h){let f=n.length,c=`${r}|${a}`,p=[f,f,!1,!1,i,0,c,0];p[t[i-1]]=a,n.push(p),e.includes(c)&&(p[Ee]=!0,Array.isArray(o[a])?Ps(n,o[a],s,c,i+1):ze(o[a],t,e,s,c,i+1,n,l))}console.log("dataRowsFromGroups2 2)");for(let a in n)for(let f in n)if(n[a][2]===!1&&l[f]!=null&&n[a][t[0]]===l[f][t[0]]){n[a]=n[a].splice(0,8).concat(l[f].slice(8,l[f].length));break}return console.log("dataRowsFromGroups2 3)"),n},Ps=(o,t,e,s,r)=>{for(let i of t){let n=o.length,l=e[i].slice();l[0]=n,l[1]=n,l[fe]=r,l[ce]=`${s}|${l[ce]}`,o.push(l)}},Ge=(o,t,e)=>{let s=t.map(n=>e[n]),r=vs(o,s);return[Os(r,s),r]},Os=(o,t)=>{let s=[],r=0,i=Object.keys(o).sort();for(let n of i){let l=[r,r,!1,!1,1,0,`$root|${n}`,0];l[t[0]]=n,s.push(l),r+=1}return s};function vs(o,t){let e={},s=t.length,r=s-1;for(let i=0,n=o.length;i<n;i++){let l=o[i],h=e,a,f;for(let c=0;c<s;c++){let p=t[c];f=l[p].toString(),a=h[f],a&&c===r?a.push(i):a?h=a:!a&&c<r?h=h[f]={}:a||(h[f]=[i])}}return console.log("!! groups",e),e}var Ds=(o,t,[e,s])=>{let r=s==="D"?t[e]:o[e],i=s==="D"?o[e]:t[e];return r===i?0:i===null||r>i?1:-1},As=o=>o.length===1?Ts(o):o.length===2?Is(o):Ns(o),Ts=([[o,t]])=>(e,s)=>{let r=t==="D"?s[o]:e[o],i=t==="D"?e[o]:s[o];return r>i?1:i>r?-1:0},Is=([[o,t],[e,s]])=>(r,i)=>{let n=t==="D"?i[o]:r[o],l=t==="D"?r[o]:i[o],h=s==="D"?i[e]:r[e],a=s==="D"?r[e]:i[e];return n>l?1:l>n?-1:h>a?1:a>h?-1:0},Ns=(o,t=Ds)=>(e,s)=>{for(let r of o){let i=t(e,s,r);if(i!==0)return i}return 0},Le=(o,{sortDefs:t},e)=>{let s=t.map(({column:i,sortType:n})=>[e[i],n]),r=As(s);return o.slice().sort(r)};var{debug:G,info:yt}=(0,d.logger)("ArrayDataSource"),{KEY:_e}=d.metadataKeys,de=o=>(t,e)=>[e,e,!0,!1,1,0,String(t[o]),0,...t],Ms=(o,t)=>({columns:o.map(({name:s,serverDataType:r="string"})=>({name:s,serverDataType:r})),key:t!=null?t:o[0].name,table:{module:"",table:"Array"}}),F,w,A,zt,O,vt,Gt,L,kt,ge=class extends d.EventEmitter{constructor({aggregations:e,columnDescriptors:s,data:r,dataMap:i,filter:n,groupBy:l,keyColumn:h,rangeChangeRowset:a="delta",sort:f,title:c,viewport:p}){super();this.lastRangeServed={from:0,to:0};this.openTreeNodes=[];P(this,F,void 0);P(this,w,d.vanillaConfig);P(this,A,void 0);P(this,zt,void 0);P(this,O,d.NULL_RANGE);P(this,vt,0);P(this,Gt,0);P(this,L,"initialising");P(this,kt,void 0);this.selectedRows=[];this.keys=new d.KeySet(u(this,O));this.processedData=void 0;this.insert=e=>{let s=de(this.key)(e,this.size);u(this,A).push(s);let{from:r,to:i}=u(this,O),[n]=s;n>=r&&n<i&&this.sendRowsToClient()};this.update=(e,s)=>{var h;let r=e[this.key],i=u(this,F)[s],n=(h=this.dataMap)==null?void 0:h[s],l=u(this,A).findIndex(a=>a[_e]===r);if(l!==-1&&n!==void 0){let a=u(this,A)[l];a[i]=e[n];let{from:f,to:c}=u(this,O),[p]=a;p>=f&&p<c&&this.sendRowsToClient(!1,a)}};this.updateRow=e=>{let s=e[this.key],r=u(this,A).findIndex(i=>i[_e]===s);if(r!==-1){let i=de(this.key)(e,r);u(this,A)[r]=i;let{from:n,to:l}=u(this,O);r>=n&&r<l&&this.sendRowsToClient(!1,i)}};if(!r||!s)throw Error("ArrayDataSource constructor called without data or without columnDescriptors");this.columnDescriptors=s,this.dataMap=i,this.key=h?this.columnDescriptors.findIndex(S=>S.name===h):0,this.rangeChangeRowset=a,this.tableSchema=Ms(s,h),this.viewport=p||(0,d.uuid)(),m(this,Gt,r.length),m(this,kt,c);let g=s.map(S=>S.name);m(this,F,(0,d.buildColumnMap)(g)),this.dataIndices=ue(u(this,F),this.dataMap),m(this,A,r.map(de(this.key))),this.config={...u(this,w),aggregations:e||u(this,w).aggregations,columns:g,filter:n||u(this,w).filter,groupBy:l||u(this,w).groupBy,sort:f||u(this,w).sort},G==null||G(`columnMap: ${JSON.stringify(u(this,F))}`)}async subscribe({viewport:e=(f=>(f=this.viewport)!=null?f:(0,d.uuid)())(),columns:s,aggregations:r,range:i,sort:n,groupBy:l,filter:h},a){var g;this.clientCallback=a,this.viewport=e,m(this,L,"subscribed"),this.lastRangeServed={from:0,to:0};let c=u(this,w),p=r||s||h||l||n;p&&(i&&m(this,O,i),c={...c,aggregations:r||u(this,w).aggregations,columns:s||u(this,w).columns,filter:h||u(this,w).filter,groupBy:l||u(this,w).groupBy,sort:n||u(this,w).sort}),(g=this.clientCallback)==null||g.call(this,{...c,type:"subscribed",clientViewportId:this.viewport,range:u(this,O),tableSchema:this.tableSchema}),p?this.config=c:(this.clientCallback({clientViewportId:this.viewport,mode:"size-only",type:"viewport-update",size:u(this,A).length}),i?(this.range=i,this.sendRowsToClient()):u(this,O)!==d.NULL_RANGE&&this.sendRowsToClient())}unsubscribe(){console.log("unsubscribe noop")}suspend(){return console.log(`suspend #${this.viewport}, current status ${u(this,L)}`),yt==null||yt(`suspend #${this.viewport}, current status ${u(this,L)}`),m(this,L,"suspended"),this}resume(){console.log(`resume #${this.viewport}, current status ${u(this,L)}`);let e=u(this,L)==="suspended";return yt==null||yt(`resume #${this.viewport}, current status ${u(this,L)}`),console.log("resume noop"),e&&m(this,L,"subscribed"),this}disable(){return console.log("disable noop"),this}enable(){return console.log("enable noop"),this}select(e){m(this,vt,e.length),G==null||G(`select ${JSON.stringify(e)}`),this.selectedRows=e,this.setRange((0,d.resetRange)(u(this,O)),!0)}openTreeNode(e){this.openTreeNodes.push(e),this.processedData=pe(this.openTreeNodes,u(this,A),u(this,w).groupBy,u(this,F),this.groupMap,this.processedData),this.setRange((0,d.resetRange)(u(this,O)),!0)}closeTreeNode(e){this.openTreeNodes=this.openTreeNodes.filter(s=>s!==e),this.processedData&&(this.processedData=Qe(e,this.processedData),this.setRange((0,d.resetRange)(u(this,O)),!0))}get links(){return u(this,zt)}get menu(){return this._menu}get status(){return u(this,L)}get data(){return u(this,A)}get currentData(){var e;return(e=this.processedData)!=null?e:u(this,A)}get table(){return this.tableSchema.table}get config(){return u(this,w)}set config(e){var r;let s=this.applyConfig(e);if(s){if(e){let i=u(this,w),n=(r=e==null?void 0:e.filter)!=null&&r.filter&&(e==null?void 0:e.filter.filterStruct)===void 0?{...e,filter:{filter:e.filter.filter,filterStruct:wt(e.filter.filter)}}:e;m(this,w,(0,d.withConfigDefaults)(n));let l;if((0,d.hasFilter)(e)){let{filter:h,filterStruct:a=wt(h)}=e.filter;if(a){let f=Et(u(this,F),a);l=u(this,A).filter(f)}else throw Error("filter must include filterStruct")}if((0,d.hasSort)(e)&&(l=Le(l!=null?l:u(this,A),e.sort,u(this,F))),this.openTreeNodes.length>0&&(0,d.isGroupByChanged)(i,e)&&(u(this,w).groupBy.length===0?this.openTreeNodes.length=0:console.log("adjust the openTReeNodes groupBy changed ",{originalGroupBy:i.groupBy,newGroupBy:n.groupBy})),(0,d.hasGroupBy)(e)){let[h,a]=Ge(l!=null?l:u(this,A),e.groupBy,u(this,F));this.groupMap=a,l=h,this.openTreeNodes.length>0&&(l=pe(this.openTreeNodes,u(this,A),u(this,w).groupBy,u(this,F),this.groupMap,l))}this.processedData=l==null?void 0:l.map((h,a)=>{let f=h.slice();return f[0]=a,f[1]=a,f})}this.setRange((0,d.resetRange)(u(this,O)),!0),this.emit("config",u(this,w),void 0,s)}}applyConfig(e){var i;let{noChanges:s,...r}=(0,d.isConfigChanged)(u(this,w),e);if(s!==!0&&e){let n=(i=e==null?void 0:e.filter)!=null&&i.filter&&(e==null?void 0:e.filter.filterStruct)===void 0?{...e,filter:{filter:e.filter.filter,filterStruct:wt(e.filter.filter)}}:e;return m(this,w,(0,d.withConfigDefaults)(n)),r}}get selectedRowsCount(){return u(this,vt)}get size(){var e,s;return(s=(e=this.processedData)==null?void 0:e.length)!=null?s:u(this,A).length}get range(){return u(this,O)}set range(e){this.setRange(e)}delete(e){console.log(`delete row ${e.join(",")}`)}setRange(e,s=!1){if(e.from!==u(this,O).from||e.to!==u(this,O).to){m(this,O,e);let r=this.keys.reset(e);this.sendRowsToClient(s||r)}else s&&this.sendRowsToClient(s)}sendRowsToClient(e=!1,s){var r,i,n;if(s)(r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,mode:"update",rows:[ae(s,this.keys,this.selectedRows,this.dataIndices)],type:"viewport-update"});else{let l=this.rangeChangeRowset==="delta"&&!e?(0,d.rangeNewItems)(this.lastRangeServed,u(this,O)):u(this,O),h=(i=this.processedData)!=null?i:u(this,A),a=h.slice(l.from,l.to).map(f=>ae(f,this.keys,this.selectedRows,this.dataIndices));(n=this.clientCallback)==null||n.call(this,{clientViewportId:this.viewport,mode:"batch",rows:a,size:h.length,type:"viewport-update"}),this.lastRangeServed={from:u(this,O).from,to:Math.min(u(this,O).to,u(this,O).from+a.length)}}}get columns(){return u(this,w).columns}set columns(e){let s=(0,d.getAddedItems)(this.config.columns,e);if(s.length>0){let r=(0,d.getMissingItems)(this.columnDescriptors,s,i=>i.name);console.log("columnsWithoutDescriptors",{columnsWithoutDescriptors:r})}m(this,F,(0,d.buildColumnMap)(e)),this.dataIndices=ue(u(this,F),this.dataMap),this.config={...u(this,w),columns:e}}get aggregations(){return u(this,w).aggregations}set aggregations(e){var i;m(this,w,{...u(this,w),aggregations:e});let s=(i=this.processedData)!=null?i:u(this,A),r=u(this,A);Me(e,s,u(this,w).groupBy,r,u(this,F),this.groupMap),this.setRange((0,d.resetRange)(u(this,O)),!0),this.emit("config",u(this,w))}get sort(){return u(this,w).sort}set sort(e){G==null||G(`sort ${JSON.stringify(e)}`),this.config={...u(this,w),sort:e}}get filter(){return u(this,w).filter}set filter(e){G==null||G(`filter ${JSON.stringify(e)}`),this.config={...u(this,w),filter:e}}get groupBy(){return u(this,w).groupBy}set groupBy(e){this.config={...u(this,w),groupBy:e}}get title(){return u(this,kt)}set title(e){m(this,kt,e)}get _clientCallback(){return this.clientCallback}createLink({parentVpId:e,link:{fromColumn:s,toColumn:r}}){console.log("create link",{parentVpId:e,fromColumn:s,toColumn:r})}removeLink(){console.log("remove link")}findRow(e){let s=u(this,A)[e];if(s)return s;throw`no row found for key ${e}`}applyEdit(e,s,r){return console.log(`ArrayDataSource applyEdit ${e[0]} ${s} ${r}`),Promise.resolve(!0)}async menuRpcCall(e){return new Promise(s=>{let{type:r}=e;switch(r){case"VP_EDIT_CELL_RPC":break;default:s(void 0)}})}};F=new WeakMap,w=new WeakMap,A=new WeakMap,zt=new WeakMap,O=new WeakMap,vt=new WeakMap,Gt=new WeakMap,L=new WeakMap,kt=new WeakMap;var I=require("@vuu-ui/vuu-utils");var Fs={columns:[],key:"",table:{module:"",table:""}},{DEPTH:ut,IDX:$e,IS_EXPANDED:Vs,IS_LEAF:Bs,KEY:Xe,SELECTED:je}=I.metadataKeys,We=(o,t)=>{let[e]=o,s=o.slice();return s[1]=t.keyFor(e),s},et,_,M,st,rt,X,Lt,_t,it,xt,Ct,me=class extends I.EventEmitter{constructor({aggregations:e,data:s,filter:r,groupBy:i,sort:n,title:l,viewport:h}){super();this.expandedRows=new Set;this.visibleRows=[];P(this,et,[]);P(this,_,I.vanillaConfig);P(this,M,void 0);P(this,st,{filter:""});P(this,rt,[]);P(this,X,{from:0,to:0});P(this,Lt,0);P(this,_t,0);P(this,it,{sortDefs:[]});P(this,xt,"initialising");P(this,Ct,void 0);this.keys=new I.KeySet(u(this,X));if(!s)throw Error("JsonDataSource constructor called without data");[this.columnDescriptors,jt(this,M)._]=(0,I.jsonToDataSourceRows)(s),this.visibleRows=u(this,M).filter(a=>a[ut]===0).map((a,f)=>[f,f].concat(a.slice(2))),this.viewport=h||(0,I.uuid)(),e&&m(this,et,e),this.columnDescriptors&&m(this,_,{...u(this,_),columns:this.columnDescriptors.map(a=>a.name)}),r&&m(this,st,r),i&&m(this,rt,i),n&&m(this,it,n),m(this,Ct,l)}async subscribe({viewport:e=(f=>(f=this.viewport)!=null?f:(0,I.uuid)())(),columns:s,aggregations:r,range:i,sort:n,groupBy:l,filter:h},a){var c;this.clientCallback=a,r&&m(this,et,r),s&&m(this,_,{...u(this,_),columns:s}),h&&m(this,st,h),l&&m(this,rt,l),i&&m(this,X,i),n&&m(this,it,n),u(this,xt)==="initialising"&&(this.viewport=e,m(this,xt,"subscribed"),(c=this.clientCallback)==null||c.call(this,{aggregations:u(this,et),type:"subscribed",clientViewportId:this.viewport,columns:u(this,_).columns,filter:u(this,st),groupBy:u(this,rt),range:u(this,X),sort:u(this,it),tableSchema:Fs}),this.clientCallback({clientViewportId:this.viewport,mode:"size-only",type:"viewport-update",size:this.visibleRows.length}))}unsubscribe(){console.log("noop")}suspend(){return console.log("noop"),this}resume(){return console.log("noop"),this}disable(){return console.log("noop"),this}enable(){return console.log("noop"),this}set data(e){console.log("set JsonDataSource data"),[this.columnDescriptors,jt(this,M)._]=(0,I.jsonToDataSourceRows)(e),this.visibleRows=u(this,M).filter(s=>s[ut]===0).map((s,r)=>[r,r].concat(s.slice(2))),requestAnimationFrame(()=>{this.sendRowsToClient()})}select(e){var r;let s=[];for(let i of u(this,M)){let{[$e]:n,[je]:l}=i,h=l===1,a=(0,I.isSelected)(e,n);if(a!==h){let f=i.slice();f[je]=a?1:0,u(this,M)[n]=f,s.push(f)}}s.length>0&&((r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,mode:"update",type:"viewport-update",rows:s}))}openTreeNode(e){var i;this.expandedRows.add(e),this.visibleRows=Ue(u(this,M),this.expandedRows);let{from:s,to:r}=u(this,X);(i=this.clientCallback)==null||i.call(this,{clientViewportId:this.viewport,mode:"batch",rows:this.visibleRows.slice(s,r).map(n=>We(n,this.keys)),size:this.visibleRows.length,type:"viewport-update"})}closeTreeNode(e,s=!1){if(this.expandedRows.delete(e),s)for(let r of this.expandedRows.keys())r.startsWith(e)&&this.expandedRows.delete(r);this.visibleRows=Ue(u(this,M),this.expandedRows),this.sendRowsToClient()}get status(){return u(this,xt)}get config(){return u(this,_)}applyConfig(){return I.NO_CONFIG_CHANGES}get selectedRowsCount(){return u(this,Lt)}get size(){return u(this,_t)}get range(){return u(this,X)}set range(e){m(this,X,e),this.keys.reset(e),requestAnimationFrame(()=>{this.sendRowsToClient()})}sendRowsToClient(){var r;let{from:e,to:s}=u(this,X);(r=this.clientCallback)==null||r.call(this,{clientViewportId:this.viewport,mode:"batch",rows:this.visibleRows.slice(e,s).map(i=>We(i,this.keys)),size:this.visibleRows.length,type:"viewport-update"})}get columns(){return u(this,_).columns}set columns(e){m(this,_,{...u(this,_),columns:e})}get aggregations(){return u(this,et)}set aggregations(e){m(this,et,e)}get sort(){return u(this,it)}set sort(e){m(this,it,e)}get filter(){return u(this,st)}set filter(e){m(this,st,e)}get groupBy(){return u(this,rt)}set groupBy(e){m(this,rt,e)}get title(){return u(this,Ct)}set title(e){m(this,Ct,e)}createLink({parentVpId:e,link:{fromColumn:s,toColumn:r}}){console.log("create link",{parentVpId:e,fromColumn:s,toColumn:r})}removeLink(){console.log("remove link")}async menuRpcCall(e){console.log("rmenuRpcCall",{rpcRequest:e})}applyEdit(e,s,r){return console.log(`ArrayDataSource applyEdit ${e.join(",")} ${s} ${r}`),Promise.resolve(!0)}getChildRows(e){let s=u(this,M).find(r=>r[Xe]===e);if(s){let{[$e]:r,[ut]:i}=s,n=r+1,l=[];do{let{[ut]:h}=u(this,M)[n];if(h===i+1)l.push(u(this,M)[n]);else if(h<=i)break;n+=1}while(n<u(this,M).length);return l}else console.warn(`JsonDataSource getChildRows row not found for key ${e}`);return[]}getRowsAtDepth(e,s=!0){return(s?this.visibleRows:u(this,M)).filter(i=>i[ut]===e)}};et=new WeakMap,_=new WeakMap,M=new WeakMap,st=new WeakMap,rt=new WeakMap,X=new WeakMap,Lt=new WeakMap,_t=new WeakMap,it=new WeakMap,xt=new WeakMap,Ct=new WeakMap;function Ue(o,t){let e=[],s={value:0};for(let r=0;r<o.length;r++){let i=o[r],{[ut]:n,[Xe]:l,[Bs]:h}=i,a=t.has(l);if(e.push(Es(i,s,a)),!h&&!a)do r+=1;while(r<o.length-1&&o[r+1][ut]>n)}return e}var Es=(o,t,e)=>{let s=o.slice();return s[0]=t.value,s[1]=t.value,e&&(s[Vs]=!0),t.value+=1,s};
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __accessCheck = (obj, member, msg) => {
20
+ if (!member.has(obj))
21
+ throw TypeError("Cannot " + msg);
22
+ };
23
+ var __privateGet = (obj, member, getter) => {
24
+ __accessCheck(obj, member, "read from private field");
25
+ return getter ? getter.call(obj) : member.get(obj);
26
+ };
27
+ var __privateAdd = (obj, member, value) => {
28
+ if (member.has(obj))
29
+ throw TypeError("Cannot add the same private member more than once");
30
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
31
+ };
32
+ var __privateSet = (obj, member, value, setter) => {
33
+ __accessCheck(obj, member, "write to private field");
34
+ setter ? setter.call(obj, value) : member.set(obj, value);
35
+ return value;
36
+ };
37
+ var __privateWrapper = (obj, member, setter, getter) => ({
38
+ set _(value) {
39
+ __privateSet(obj, member, value, setter);
40
+ },
41
+ get _() {
42
+ return __privateGet(obj, member, getter);
43
+ }
44
+ });
45
+
46
+ // src/index.ts
47
+ var src_exports = {};
48
+ __export(src_exports, {
49
+ ArrayDataSource: () => ArrayDataSource,
50
+ JsonDataSource: () => JsonDataSource
51
+ });
52
+ module.exports = __toCommonJS(src_exports);
53
+
54
+ // ../../node_modules/@lezer/common/dist/index.js
55
+ var DefaultBufferLength = 1024;
56
+ var nextPropID = 0;
57
+ var Range = class {
58
+ constructor(from, to) {
59
+ this.from = from;
60
+ this.to = to;
61
+ }
62
+ };
63
+ var NodeProp = class {
64
+ /// Create a new node prop type.
65
+ constructor(config = {}) {
66
+ this.id = nextPropID++;
67
+ this.perNode = !!config.perNode;
68
+ this.deserialize = config.deserialize || (() => {
69
+ throw new Error("This node type doesn't define a deserialize function");
70
+ });
71
+ }
72
+ /// This is meant to be used with
73
+ /// [`NodeSet.extend`](#common.NodeSet.extend) or
74
+ /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
75
+ /// prop values for each node type in the set. Takes a [match
76
+ /// object](#common.NodeType^match) or function that returns undefined
77
+ /// if the node type doesn't get this prop, and the prop's value if
78
+ /// it does.
79
+ add(match) {
80
+ if (this.perNode)
81
+ throw new RangeError("Can't add per-node props to node types");
82
+ if (typeof match != "function")
83
+ match = NodeType.match(match);
84
+ return (type) => {
85
+ let result = match(type);
86
+ return result === void 0 ? null : [this, result];
87
+ };
88
+ }
89
+ };
90
+ NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
91
+ NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") });
92
+ NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") });
93
+ NodeProp.contextHash = new NodeProp({ perNode: true });
94
+ NodeProp.lookAhead = new NodeProp({ perNode: true });
95
+ NodeProp.mounted = new NodeProp({ perNode: true });
96
+ var noProps = /* @__PURE__ */ Object.create(null);
97
+ var NodeType = class _NodeType {
98
+ /// @internal
99
+ constructor(name, props, id, flags = 0) {
100
+ this.name = name;
101
+ this.props = props;
102
+ this.id = id;
103
+ this.flags = flags;
104
+ }
105
+ /// Define a node type.
106
+ static define(spec) {
107
+ let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
108
+ let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
109
+ let type = new _NodeType(spec.name || "", props, spec.id, flags);
110
+ if (spec.props)
111
+ for (let src of spec.props) {
112
+ if (!Array.isArray(src))
113
+ src = src(type);
114
+ if (src) {
115
+ if (src[0].perNode)
116
+ throw new RangeError("Can't store a per-node prop on a node type");
117
+ props[src[0].id] = src[1];
118
+ }
119
+ }
120
+ return type;
121
+ }
122
+ /// Retrieves a node prop for this type. Will return `undefined` if
123
+ /// the prop isn't present on this node.
124
+ prop(prop) {
125
+ return this.props[prop.id];
126
+ }
127
+ /// True when this is the top node of a grammar.
128
+ get isTop() {
129
+ return (this.flags & 1) > 0;
130
+ }
131
+ /// True when this node is produced by a skip rule.
132
+ get isSkipped() {
133
+ return (this.flags & 2) > 0;
134
+ }
135
+ /// Indicates whether this is an error node.
136
+ get isError() {
137
+ return (this.flags & 4) > 0;
138
+ }
139
+ /// When true, this node type doesn't correspond to a user-declared
140
+ /// named node, for example because it is used to cache repetition.
141
+ get isAnonymous() {
142
+ return (this.flags & 8) > 0;
143
+ }
144
+ /// Returns true when this node's name or one of its
145
+ /// [groups](#common.NodeProp^group) matches the given string.
146
+ is(name) {
147
+ if (typeof name == "string") {
148
+ if (this.name == name)
149
+ return true;
150
+ let group = this.prop(NodeProp.group);
151
+ return group ? group.indexOf(name) > -1 : false;
152
+ }
153
+ return this.id == name;
154
+ }
155
+ /// Create a function from node types to arbitrary values by
156
+ /// specifying an object whose property names are node or
157
+ /// [group](#common.NodeProp^group) names. Often useful with
158
+ /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
159
+ /// names, separated by spaces, in a single property name to map
160
+ /// multiple node names to a single value.
161
+ static match(map) {
162
+ let direct = /* @__PURE__ */ Object.create(null);
163
+ for (let prop in map)
164
+ for (let name of prop.split(" "))
165
+ direct[name] = map[prop];
166
+ return (node) => {
167
+ for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
168
+ let found = direct[i < 0 ? node.name : groups[i]];
169
+ if (found)
170
+ return found;
171
+ }
172
+ };
173
+ }
174
+ };
175
+ NodeType.none = new NodeType(
176
+ "",
177
+ /* @__PURE__ */ Object.create(null),
178
+ 0,
179
+ 8
180
+ /* NodeFlag.Anonymous */
181
+ );
182
+ var NodeSet = class _NodeSet {
183
+ /// Create a set with the given types. The `id` property of each
184
+ /// type should correspond to its position within the array.
185
+ constructor(types) {
186
+ this.types = types;
187
+ for (let i = 0; i < types.length; i++)
188
+ if (types[i].id != i)
189
+ throw new RangeError("Node type ids should correspond to array positions when creating a node set");
190
+ }
191
+ /// Create a copy of this set with some node properties added. The
192
+ /// arguments to this method can be created with
193
+ /// [`NodeProp.add`](#common.NodeProp.add).
194
+ extend(...props) {
195
+ let newTypes = [];
196
+ for (let type of this.types) {
197
+ let newProps = null;
198
+ for (let source of props) {
199
+ let add = source(type);
200
+ if (add) {
201
+ if (!newProps)
202
+ newProps = Object.assign({}, type.props);
203
+ newProps[add[0].id] = add[1];
204
+ }
205
+ }
206
+ newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
207
+ }
208
+ return new _NodeSet(newTypes);
209
+ }
210
+ };
211
+ var CachedNode = /* @__PURE__ */ new WeakMap();
212
+ var CachedInnerNode = /* @__PURE__ */ new WeakMap();
213
+ var IterMode;
214
+ (function(IterMode2) {
215
+ IterMode2[IterMode2["ExcludeBuffers"] = 1] = "ExcludeBuffers";
216
+ IterMode2[IterMode2["IncludeAnonymous"] = 2] = "IncludeAnonymous";
217
+ IterMode2[IterMode2["IgnoreMounts"] = 4] = "IgnoreMounts";
218
+ IterMode2[IterMode2["IgnoreOverlays"] = 8] = "IgnoreOverlays";
219
+ })(IterMode || (IterMode = {}));
220
+ var Tree = class _Tree {
221
+ /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
222
+ constructor(type, children, positions, length, props) {
223
+ this.type = type;
224
+ this.children = children;
225
+ this.positions = positions;
226
+ this.length = length;
227
+ this.props = null;
228
+ if (props && props.length) {
229
+ this.props = /* @__PURE__ */ Object.create(null);
230
+ for (let [prop, value] of props)
231
+ this.props[typeof prop == "number" ? prop : prop.id] = value;
232
+ }
233
+ }
234
+ /// @internal
235
+ toString() {
236
+ let mounted = this.prop(NodeProp.mounted);
237
+ if (mounted && !mounted.overlay)
238
+ return mounted.tree.toString();
239
+ let children = "";
240
+ for (let ch of this.children) {
241
+ let str = ch.toString();
242
+ if (str) {
243
+ if (children)
244
+ children += ",";
245
+ children += str;
246
+ }
247
+ }
248
+ return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
249
+ }
250
+ /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
251
+ /// the tree. Mode can be used to [control](#common.IterMode) which
252
+ /// nodes the cursor visits.
253
+ cursor(mode = 0) {
254
+ return new TreeCursor(this.topNode, mode);
255
+ }
256
+ /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
257
+ /// at the given position and side (see
258
+ /// [`moveTo`](#common.TreeCursor.moveTo).
259
+ cursorAt(pos, side = 0, mode = 0) {
260
+ let scope = CachedNode.get(this) || this.topNode;
261
+ let cursor = new TreeCursor(scope);
262
+ cursor.moveTo(pos, side);
263
+ CachedNode.set(this, cursor._tree);
264
+ return cursor;
265
+ }
266
+ /// Get a [syntax node](#common.SyntaxNode) object for the top of the
267
+ /// tree.
268
+ get topNode() {
269
+ return new TreeNode(this, 0, 0, null);
270
+ }
271
+ /// Get the [syntax node](#common.SyntaxNode) at the given position.
272
+ /// If `side` is -1, this will move into nodes that end at the
273
+ /// position. If 1, it'll move into nodes that start at the
274
+ /// position. With 0, it'll only enter nodes that cover the position
275
+ /// from both sides.
276
+ ///
277
+ /// Note that this will not enter
278
+ /// [overlays](#common.MountedTree.overlay), and you often want
279
+ /// [`resolveInner`](#common.Tree.resolveInner) instead.
280
+ resolve(pos, side = 0) {
281
+ let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
282
+ CachedNode.set(this, node);
283
+ return node;
284
+ }
285
+ /// Like [`resolve`](#common.Tree.resolve), but will enter
286
+ /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
287
+ /// pointing into the innermost overlaid tree at the given position
288
+ /// (with parent links going through all parent structure, including
289
+ /// the host trees).
290
+ resolveInner(pos, side = 0) {
291
+ let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
292
+ CachedInnerNode.set(this, node);
293
+ return node;
294
+ }
295
+ /// Iterate over the tree and its children, calling `enter` for any
296
+ /// node that touches the `from`/`to` region (if given) before
297
+ /// running over such a node's children, and `leave` (if given) when
298
+ /// leaving the node. When `enter` returns `false`, that node will
299
+ /// not have its children iterated over (or `leave` called).
300
+ iterate(spec) {
301
+ let { enter, leave, from = 0, to = this.length } = spec;
302
+ let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
303
+ for (let c = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
304
+ let entered = false;
305
+ if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
306
+ if (c.firstChild())
307
+ continue;
308
+ entered = true;
309
+ }
310
+ for (; ; ) {
311
+ if (entered && leave && (anon || !c.type.isAnonymous))
312
+ leave(c);
313
+ if (c.nextSibling())
314
+ break;
315
+ if (!c.parent())
316
+ return;
317
+ entered = true;
318
+ }
319
+ }
320
+ }
321
+ /// Get the value of the given [node prop](#common.NodeProp) for this
322
+ /// node. Works with both per-node and per-type props.
323
+ prop(prop) {
324
+ return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
325
+ }
326
+ /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
327
+ /// format that can be passed to the [`Tree`](#common.Tree)
328
+ /// constructor.
329
+ get propValues() {
330
+ let result = [];
331
+ if (this.props)
332
+ for (let id in this.props)
333
+ result.push([+id, this.props[id]]);
334
+ return result;
335
+ }
336
+ /// Balance the direct children of this tree, producing a copy of
337
+ /// which may have children grouped into subtrees with type
338
+ /// [`NodeType.none`](#common.NodeType^none).
339
+ balance(config = {}) {
340
+ return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new _Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new _Tree(NodeType.none, children, positions, length)));
341
+ }
342
+ /// Build a tree from a postfix-ordered buffer of node information,
343
+ /// or a cursor over such a buffer.
344
+ static build(data) {
345
+ return buildTree(data);
346
+ }
347
+ };
348
+ Tree.empty = new Tree(NodeType.none, [], [], 0);
349
+ var FlatBufferCursor = class _FlatBufferCursor {
350
+ constructor(buffer, index) {
351
+ this.buffer = buffer;
352
+ this.index = index;
353
+ }
354
+ get id() {
355
+ return this.buffer[this.index - 4];
356
+ }
357
+ get start() {
358
+ return this.buffer[this.index - 3];
359
+ }
360
+ get end() {
361
+ return this.buffer[this.index - 2];
362
+ }
363
+ get size() {
364
+ return this.buffer[this.index - 1];
365
+ }
366
+ get pos() {
367
+ return this.index;
368
+ }
369
+ next() {
370
+ this.index -= 4;
371
+ }
372
+ fork() {
373
+ return new _FlatBufferCursor(this.buffer, this.index);
374
+ }
375
+ };
376
+ var TreeBuffer = class _TreeBuffer {
377
+ /// Create a tree buffer.
378
+ constructor(buffer, length, set) {
379
+ this.buffer = buffer;
380
+ this.length = length;
381
+ this.set = set;
382
+ }
383
+ /// @internal
384
+ get type() {
385
+ return NodeType.none;
386
+ }
387
+ /// @internal
388
+ toString() {
389
+ let result = [];
390
+ for (let index = 0; index < this.buffer.length; ) {
391
+ result.push(this.childString(index));
392
+ index = this.buffer[index + 3];
393
+ }
394
+ return result.join(",");
395
+ }
396
+ /// @internal
397
+ childString(index) {
398
+ let id = this.buffer[index], endIndex = this.buffer[index + 3];
399
+ let type = this.set.types[id], result = type.name;
400
+ if (/\W/.test(result) && !type.isError)
401
+ result = JSON.stringify(result);
402
+ index += 4;
403
+ if (endIndex == index)
404
+ return result;
405
+ let children = [];
406
+ while (index < endIndex) {
407
+ children.push(this.childString(index));
408
+ index = this.buffer[index + 3];
409
+ }
410
+ return result + "(" + children.join(",") + ")";
411
+ }
412
+ /// @internal
413
+ findChild(startIndex, endIndex, dir, pos, side) {
414
+ let { buffer } = this, pick = -1;
415
+ for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
416
+ if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
417
+ pick = i;
418
+ if (dir > 0)
419
+ break;
420
+ }
421
+ }
422
+ return pick;
423
+ }
424
+ /// @internal
425
+ slice(startI, endI, from) {
426
+ let b = this.buffer;
427
+ let copy = new Uint16Array(endI - startI), len = 0;
428
+ for (let i = startI, j = 0; i < endI; ) {
429
+ copy[j++] = b[i++];
430
+ copy[j++] = b[i++] - from;
431
+ let to = copy[j++] = b[i++] - from;
432
+ copy[j++] = b[i++] - startI;
433
+ len = Math.max(len, to);
434
+ }
435
+ return new _TreeBuffer(copy, len, this.set);
436
+ }
437
+ };
438
+ function checkSide(side, pos, from, to) {
439
+ switch (side) {
440
+ case -2:
441
+ return from < pos;
442
+ case -1:
443
+ return to >= pos && from < pos;
444
+ case 0:
445
+ return from < pos && to > pos;
446
+ case 1:
447
+ return from <= pos && to > pos;
448
+ case 2:
449
+ return to > pos;
450
+ case 4:
451
+ return true;
452
+ }
453
+ }
454
+ function enterUnfinishedNodesBefore(node, pos) {
455
+ let scan = node.childBefore(pos);
456
+ while (scan) {
457
+ let last = scan.lastChild;
458
+ if (!last || last.to != scan.to)
459
+ break;
460
+ if (last.type.isError && last.from == last.to) {
461
+ node = scan;
462
+ scan = last.prevSibling;
463
+ } else {
464
+ scan = last;
465
+ }
466
+ }
467
+ return node;
468
+ }
469
+ function resolveNode(node, pos, side, overlays) {
470
+ var _a;
471
+ while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
472
+ let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
473
+ if (!parent)
474
+ return node;
475
+ node = parent;
476
+ }
477
+ let mode = overlays ? 0 : IterMode.IgnoreOverlays;
478
+ if (overlays)
479
+ for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
480
+ if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
481
+ node = parent;
482
+ }
483
+ for (; ; ) {
484
+ let inner = node.enter(pos, side, mode);
485
+ if (!inner)
486
+ return node;
487
+ node = inner;
488
+ }
489
+ }
490
+ var TreeNode = class _TreeNode {
491
+ constructor(_tree, from, index, _parent) {
492
+ this._tree = _tree;
493
+ this.from = from;
494
+ this.index = index;
495
+ this._parent = _parent;
496
+ }
497
+ get type() {
498
+ return this._tree.type;
499
+ }
500
+ get name() {
501
+ return this._tree.type.name;
502
+ }
503
+ get to() {
504
+ return this.from + this._tree.length;
505
+ }
506
+ nextChild(i, dir, pos, side, mode = 0) {
507
+ for (let parent = this; ; ) {
508
+ for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
509
+ let next = children[i], start = positions[i] + parent.from;
510
+ if (!checkSide(side, pos, start, start + next.length))
511
+ continue;
512
+ if (next instanceof TreeBuffer) {
513
+ if (mode & IterMode.ExcludeBuffers)
514
+ continue;
515
+ let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
516
+ if (index > -1)
517
+ return new BufferNode(new BufferContext(parent, next, i, start), null, index);
518
+ } else if (mode & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) {
519
+ let mounted;
520
+ if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay)
521
+ return new _TreeNode(mounted.tree, start, i, parent);
522
+ let inner = new _TreeNode(next, start, i, parent);
523
+ return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
524
+ }
525
+ }
526
+ if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
527
+ return null;
528
+ if (parent.index >= 0)
529
+ i = parent.index + dir;
530
+ else
531
+ i = dir < 0 ? -1 : parent._parent._tree.children.length;
532
+ parent = parent._parent;
533
+ if (!parent)
534
+ return null;
535
+ }
536
+ }
537
+ get firstChild() {
538
+ return this.nextChild(
539
+ 0,
540
+ 1,
541
+ 0,
542
+ 4
543
+ /* Side.DontCare */
544
+ );
545
+ }
546
+ get lastChild() {
547
+ return this.nextChild(
548
+ this._tree.children.length - 1,
549
+ -1,
550
+ 0,
551
+ 4
552
+ /* Side.DontCare */
553
+ );
554
+ }
555
+ childAfter(pos) {
556
+ return this.nextChild(
557
+ 0,
558
+ 1,
559
+ pos,
560
+ 2
561
+ /* Side.After */
562
+ );
563
+ }
564
+ childBefore(pos) {
565
+ return this.nextChild(
566
+ this._tree.children.length - 1,
567
+ -1,
568
+ pos,
569
+ -2
570
+ /* Side.Before */
571
+ );
572
+ }
573
+ enter(pos, side, mode = 0) {
574
+ let mounted;
575
+ if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
576
+ let rPos = pos - this.from;
577
+ for (let { from, to } of mounted.overlay) {
578
+ if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos))
579
+ return new _TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
580
+ }
581
+ }
582
+ return this.nextChild(0, 1, pos, side, mode);
583
+ }
584
+ nextSignificantParent() {
585
+ let val = this;
586
+ while (val.type.isAnonymous && val._parent)
587
+ val = val._parent;
588
+ return val;
589
+ }
590
+ get parent() {
591
+ return this._parent ? this._parent.nextSignificantParent() : null;
592
+ }
593
+ get nextSibling() {
594
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
595
+ this.index + 1,
596
+ 1,
597
+ 0,
598
+ 4
599
+ /* Side.DontCare */
600
+ ) : null;
601
+ }
602
+ get prevSibling() {
603
+ return this._parent && this.index >= 0 ? this._parent.nextChild(
604
+ this.index - 1,
605
+ -1,
606
+ 0,
607
+ 4
608
+ /* Side.DontCare */
609
+ ) : null;
610
+ }
611
+ cursor(mode = 0) {
612
+ return new TreeCursor(this, mode);
613
+ }
614
+ get tree() {
615
+ return this._tree;
616
+ }
617
+ toTree() {
618
+ return this._tree;
619
+ }
620
+ resolve(pos, side = 0) {
621
+ return resolveNode(this, pos, side, false);
622
+ }
623
+ resolveInner(pos, side = 0) {
624
+ return resolveNode(this, pos, side, true);
625
+ }
626
+ enterUnfinishedNodesBefore(pos) {
627
+ return enterUnfinishedNodesBefore(this, pos);
628
+ }
629
+ getChild(type, before = null, after = null) {
630
+ let r = getChildren(this, type, before, after);
631
+ return r.length ? r[0] : null;
632
+ }
633
+ getChildren(type, before = null, after = null) {
634
+ return getChildren(this, type, before, after);
635
+ }
636
+ /// @internal
637
+ toString() {
638
+ return this._tree.toString();
639
+ }
640
+ get node() {
641
+ return this;
642
+ }
643
+ matchContext(context) {
644
+ return matchNodeContext(this, context);
645
+ }
646
+ };
647
+ function getChildren(node, type, before, after) {
648
+ let cur = node.cursor(), result = [];
649
+ if (!cur.firstChild())
650
+ return result;
651
+ if (before != null) {
652
+ while (!cur.type.is(before))
653
+ if (!cur.nextSibling())
654
+ return result;
655
+ }
656
+ for (; ; ) {
657
+ if (after != null && cur.type.is(after))
658
+ return result;
659
+ if (cur.type.is(type))
660
+ result.push(cur.node);
661
+ if (!cur.nextSibling())
662
+ return after == null ? result : [];
663
+ }
664
+ }
665
+ function matchNodeContext(node, context, i = context.length - 1) {
666
+ for (let p = node.parent; i >= 0; p = p.parent) {
667
+ if (!p)
668
+ return false;
669
+ if (!p.type.isAnonymous) {
670
+ if (context[i] && context[i] != p.name)
671
+ return false;
672
+ i--;
673
+ }
674
+ }
675
+ return true;
676
+ }
677
+ var BufferContext = class {
678
+ constructor(parent, buffer, index, start) {
679
+ this.parent = parent;
680
+ this.buffer = buffer;
681
+ this.index = index;
682
+ this.start = start;
683
+ }
684
+ };
685
+ var BufferNode = class _BufferNode {
686
+ get name() {
687
+ return this.type.name;
688
+ }
689
+ get from() {
690
+ return this.context.start + this.context.buffer.buffer[this.index + 1];
691
+ }
692
+ get to() {
693
+ return this.context.start + this.context.buffer.buffer[this.index + 2];
694
+ }
695
+ constructor(context, _parent, index) {
696
+ this.context = context;
697
+ this._parent = _parent;
698
+ this.index = index;
699
+ this.type = context.buffer.set.types[context.buffer.buffer[index]];
700
+ }
701
+ child(dir, pos, side) {
702
+ let { buffer } = this.context;
703
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
704
+ return index < 0 ? null : new _BufferNode(this.context, this, index);
705
+ }
706
+ get firstChild() {
707
+ return this.child(
708
+ 1,
709
+ 0,
710
+ 4
711
+ /* Side.DontCare */
712
+ );
713
+ }
714
+ get lastChild() {
715
+ return this.child(
716
+ -1,
717
+ 0,
718
+ 4
719
+ /* Side.DontCare */
720
+ );
721
+ }
722
+ childAfter(pos) {
723
+ return this.child(
724
+ 1,
725
+ pos,
726
+ 2
727
+ /* Side.After */
728
+ );
729
+ }
730
+ childBefore(pos) {
731
+ return this.child(
732
+ -1,
733
+ pos,
734
+ -2
735
+ /* Side.Before */
736
+ );
737
+ }
738
+ enter(pos, side, mode = 0) {
739
+ if (mode & IterMode.ExcludeBuffers)
740
+ return null;
741
+ let { buffer } = this.context;
742
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
743
+ return index < 0 ? null : new _BufferNode(this.context, this, index);
744
+ }
745
+ get parent() {
746
+ return this._parent || this.context.parent.nextSignificantParent();
747
+ }
748
+ externalSibling(dir) {
749
+ return this._parent ? null : this.context.parent.nextChild(
750
+ this.context.index + dir,
751
+ dir,
752
+ 0,
753
+ 4
754
+ /* Side.DontCare */
755
+ );
756
+ }
757
+ get nextSibling() {
758
+ let { buffer } = this.context;
759
+ let after = buffer.buffer[this.index + 3];
760
+ if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
761
+ return new _BufferNode(this.context, this._parent, after);
762
+ return this.externalSibling(1);
763
+ }
764
+ get prevSibling() {
765
+ let { buffer } = this.context;
766
+ let parentStart = this._parent ? this._parent.index + 4 : 0;
767
+ if (this.index == parentStart)
768
+ return this.externalSibling(-1);
769
+ return new _BufferNode(this.context, this._parent, buffer.findChild(
770
+ parentStart,
771
+ this.index,
772
+ -1,
773
+ 0,
774
+ 4
775
+ /* Side.DontCare */
776
+ ));
777
+ }
778
+ cursor(mode = 0) {
779
+ return new TreeCursor(this, mode);
780
+ }
781
+ get tree() {
782
+ return null;
783
+ }
784
+ toTree() {
785
+ let children = [], positions = [];
786
+ let { buffer } = this.context;
787
+ let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
788
+ if (endI > startI) {
789
+ let from = buffer.buffer[this.index + 1];
790
+ children.push(buffer.slice(startI, endI, from));
791
+ positions.push(0);
792
+ }
793
+ return new Tree(this.type, children, positions, this.to - this.from);
794
+ }
795
+ resolve(pos, side = 0) {
796
+ return resolveNode(this, pos, side, false);
797
+ }
798
+ resolveInner(pos, side = 0) {
799
+ return resolveNode(this, pos, side, true);
800
+ }
801
+ enterUnfinishedNodesBefore(pos) {
802
+ return enterUnfinishedNodesBefore(this, pos);
803
+ }
804
+ /// @internal
805
+ toString() {
806
+ return this.context.buffer.childString(this.index);
807
+ }
808
+ getChild(type, before = null, after = null) {
809
+ let r = getChildren(this, type, before, after);
810
+ return r.length ? r[0] : null;
811
+ }
812
+ getChildren(type, before = null, after = null) {
813
+ return getChildren(this, type, before, after);
814
+ }
815
+ get node() {
816
+ return this;
817
+ }
818
+ matchContext(context) {
819
+ return matchNodeContext(this, context);
820
+ }
821
+ };
822
+ var TreeCursor = class {
823
+ /// Shorthand for `.type.name`.
824
+ get name() {
825
+ return this.type.name;
826
+ }
827
+ /// @internal
828
+ constructor(node, mode = 0) {
829
+ this.mode = mode;
830
+ this.buffer = null;
831
+ this.stack = [];
832
+ this.index = 0;
833
+ this.bufferNode = null;
834
+ if (node instanceof TreeNode) {
835
+ this.yieldNode(node);
836
+ } else {
837
+ this._tree = node.context.parent;
838
+ this.buffer = node.context;
839
+ for (let n = node._parent; n; n = n._parent)
840
+ this.stack.unshift(n.index);
841
+ this.bufferNode = node;
842
+ this.yieldBuf(node.index);
843
+ }
844
+ }
845
+ yieldNode(node) {
846
+ if (!node)
847
+ return false;
848
+ this._tree = node;
849
+ this.type = node.type;
850
+ this.from = node.from;
851
+ this.to = node.to;
852
+ return true;
853
+ }
854
+ yieldBuf(index, type) {
855
+ this.index = index;
856
+ let { start, buffer } = this.buffer;
857
+ this.type = type || buffer.set.types[buffer.buffer[index]];
858
+ this.from = start + buffer.buffer[index + 1];
859
+ this.to = start + buffer.buffer[index + 2];
860
+ return true;
861
+ }
862
+ yield(node) {
863
+ if (!node)
864
+ return false;
865
+ if (node instanceof TreeNode) {
866
+ this.buffer = null;
867
+ return this.yieldNode(node);
868
+ }
869
+ this.buffer = node.context;
870
+ return this.yieldBuf(node.index, node.type);
871
+ }
872
+ /// @internal
873
+ toString() {
874
+ return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
875
+ }
876
+ /// @internal
877
+ enterChild(dir, pos, side) {
878
+ if (!this.buffer)
879
+ return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
880
+ let { buffer } = this.buffer;
881
+ let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
882
+ if (index < 0)
883
+ return false;
884
+ this.stack.push(this.index);
885
+ return this.yieldBuf(index);
886
+ }
887
+ /// Move the cursor to this node's first child. When this returns
888
+ /// false, the node has no child, and the cursor has not been moved.
889
+ firstChild() {
890
+ return this.enterChild(
891
+ 1,
892
+ 0,
893
+ 4
894
+ /* Side.DontCare */
895
+ );
896
+ }
897
+ /// Move the cursor to this node's last child.
898
+ lastChild() {
899
+ return this.enterChild(
900
+ -1,
901
+ 0,
902
+ 4
903
+ /* Side.DontCare */
904
+ );
905
+ }
906
+ /// Move the cursor to the first child that ends after `pos`.
907
+ childAfter(pos) {
908
+ return this.enterChild(
909
+ 1,
910
+ pos,
911
+ 2
912
+ /* Side.After */
913
+ );
914
+ }
915
+ /// Move to the last child that starts before `pos`.
916
+ childBefore(pos) {
917
+ return this.enterChild(
918
+ -1,
919
+ pos,
920
+ -2
921
+ /* Side.Before */
922
+ );
923
+ }
924
+ /// Move the cursor to the child around `pos`. If side is -1 the
925
+ /// child may end at that position, when 1 it may start there. This
926
+ /// will also enter [overlaid](#common.MountedTree.overlay)
927
+ /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
928
+ /// set to false.
929
+ enter(pos, side, mode = this.mode) {
930
+ if (!this.buffer)
931
+ return this.yield(this._tree.enter(pos, side, mode));
932
+ return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
933
+ }
934
+ /// Move to the node's parent node, if this isn't the top node.
935
+ parent() {
936
+ if (!this.buffer)
937
+ return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
938
+ if (this.stack.length)
939
+ return this.yieldBuf(this.stack.pop());
940
+ let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
941
+ this.buffer = null;
942
+ return this.yieldNode(parent);
943
+ }
944
+ /// @internal
945
+ sibling(dir) {
946
+ if (!this.buffer)
947
+ return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
948
+ let { buffer } = this.buffer, d = this.stack.length - 1;
949
+ if (dir < 0) {
950
+ let parentStart = d < 0 ? 0 : this.stack[d] + 4;
951
+ if (this.index != parentStart)
952
+ return this.yieldBuf(buffer.findChild(
953
+ parentStart,
954
+ this.index,
955
+ -1,
956
+ 0,
957
+ 4
958
+ /* Side.DontCare */
959
+ ));
960
+ } else {
961
+ let after = buffer.buffer[this.index + 3];
962
+ if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
963
+ return this.yieldBuf(after);
964
+ }
965
+ return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
966
+ }
967
+ /// Move to this node's next sibling, if any.
968
+ nextSibling() {
969
+ return this.sibling(1);
970
+ }
971
+ /// Move to this node's previous sibling, if any.
972
+ prevSibling() {
973
+ return this.sibling(-1);
974
+ }
975
+ atLastNode(dir) {
976
+ let index, parent, { buffer } = this;
977
+ if (buffer) {
978
+ if (dir > 0) {
979
+ if (this.index < buffer.buffer.buffer.length)
980
+ return false;
981
+ } else {
982
+ for (let i = 0; i < this.index; i++)
983
+ if (buffer.buffer.buffer[i + 3] < this.index)
984
+ return false;
985
+ }
986
+ ({ index, parent } = buffer);
987
+ } else {
988
+ ({ index, _parent: parent } = this._tree);
989
+ }
990
+ for (; parent; { index, _parent: parent } = parent) {
991
+ if (index > -1)
992
+ for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
993
+ let child = parent._tree.children[i];
994
+ if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
995
+ return false;
996
+ }
997
+ }
998
+ return true;
999
+ }
1000
+ move(dir, enter) {
1001
+ if (enter && this.enterChild(
1002
+ dir,
1003
+ 0,
1004
+ 4
1005
+ /* Side.DontCare */
1006
+ ))
1007
+ return true;
1008
+ for (; ; ) {
1009
+ if (this.sibling(dir))
1010
+ return true;
1011
+ if (this.atLastNode(dir) || !this.parent())
1012
+ return false;
1013
+ }
1014
+ }
1015
+ /// Move to the next node in a
1016
+ /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
1017
+ /// traversal, going from a node to its first child or, if the
1018
+ /// current node is empty or `enter` is false, its next sibling or
1019
+ /// the next sibling of the first parent node that has one.
1020
+ next(enter = true) {
1021
+ return this.move(1, enter);
1022
+ }
1023
+ /// Move to the next node in a last-to-first pre-order traveral. A
1024
+ /// node is followed by its last child or, if it has none, its
1025
+ /// previous sibling or the previous sibling of the first parent
1026
+ /// node that has one.
1027
+ prev(enter = true) {
1028
+ return this.move(-1, enter);
1029
+ }
1030
+ /// Move the cursor to the innermost node that covers `pos`. If
1031
+ /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
1032
+ /// it will enter nodes that start at `pos`.
1033
+ moveTo(pos, side = 0) {
1034
+ while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos))
1035
+ if (!this.parent())
1036
+ break;
1037
+ while (this.enterChild(1, pos, side)) {
1038
+ }
1039
+ return this;
1040
+ }
1041
+ /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
1042
+ /// position.
1043
+ get node() {
1044
+ if (!this.buffer)
1045
+ return this._tree;
1046
+ let cache = this.bufferNode, result = null, depth = 0;
1047
+ if (cache && cache.context == this.buffer) {
1048
+ scan:
1049
+ for (let index = this.index, d = this.stack.length; d >= 0; ) {
1050
+ for (let c = cache; c; c = c._parent)
1051
+ if (c.index == index) {
1052
+ if (index == this.index)
1053
+ return c;
1054
+ result = c;
1055
+ depth = d + 1;
1056
+ break scan;
1057
+ }
1058
+ index = this.stack[--d];
1059
+ }
1060
+ }
1061
+ for (let i = depth; i < this.stack.length; i++)
1062
+ result = new BufferNode(this.buffer, result, this.stack[i]);
1063
+ return this.bufferNode = new BufferNode(this.buffer, result, this.index);
1064
+ }
1065
+ /// Get the [tree](#common.Tree) that represents the current node, if
1066
+ /// any. Will return null when the node is in a [tree
1067
+ /// buffer](#common.TreeBuffer).
1068
+ get tree() {
1069
+ return this.buffer ? null : this._tree._tree;
1070
+ }
1071
+ /// Iterate over the current node and all its descendants, calling
1072
+ /// `enter` when entering a node and `leave`, if given, when leaving
1073
+ /// one. When `enter` returns `false`, any children of that node are
1074
+ /// skipped, and `leave` isn't called for it.
1075
+ iterate(enter, leave) {
1076
+ for (let depth = 0; ; ) {
1077
+ let mustLeave = false;
1078
+ if (this.type.isAnonymous || enter(this) !== false) {
1079
+ if (this.firstChild()) {
1080
+ depth++;
1081
+ continue;
1082
+ }
1083
+ if (!this.type.isAnonymous)
1084
+ mustLeave = true;
1085
+ }
1086
+ for (; ; ) {
1087
+ if (mustLeave && leave)
1088
+ leave(this);
1089
+ mustLeave = this.type.isAnonymous;
1090
+ if (this.nextSibling())
1091
+ break;
1092
+ if (!depth)
1093
+ return;
1094
+ this.parent();
1095
+ depth--;
1096
+ mustLeave = true;
1097
+ }
1098
+ }
1099
+ }
1100
+ /// Test whether the current node matches a given context—a sequence
1101
+ /// of direct parent node names. Empty strings in the context array
1102
+ /// are treated as wildcards.
1103
+ matchContext(context) {
1104
+ if (!this.buffer)
1105
+ return matchNodeContext(this.node, context);
1106
+ let { buffer } = this.buffer, { types } = buffer.set;
1107
+ for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
1108
+ if (d < 0)
1109
+ return matchNodeContext(this.node, context, i);
1110
+ let type = types[buffer.buffer[this.stack[d]]];
1111
+ if (!type.isAnonymous) {
1112
+ if (context[i] && context[i] != type.name)
1113
+ return false;
1114
+ i--;
1115
+ }
1116
+ }
1117
+ return true;
1118
+ }
1119
+ };
1120
+ function hasChild(tree) {
1121
+ return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
1122
+ }
1123
+ function buildTree(data) {
1124
+ var _a;
1125
+ let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
1126
+ let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
1127
+ let types = nodeSet.types;
1128
+ let contextHash = 0, lookAhead = 0;
1129
+ function takeNode(parentStart, minPos, children2, positions2, inRepeat) {
1130
+ let { id, start, end, size } = cursor;
1131
+ let lookAheadAtStart = lookAhead;
1132
+ while (size < 0) {
1133
+ cursor.next();
1134
+ if (size == -1) {
1135
+ let node2 = reused[id];
1136
+ children2.push(node2);
1137
+ positions2.push(start - parentStart);
1138
+ return;
1139
+ } else if (size == -3) {
1140
+ contextHash = id;
1141
+ return;
1142
+ } else if (size == -4) {
1143
+ lookAhead = id;
1144
+ return;
1145
+ } else {
1146
+ throw new RangeError(`Unrecognized record size: ${size}`);
1147
+ }
1148
+ }
1149
+ let type = types[id], node, buffer2;
1150
+ let startPos = start - parentStart;
1151
+ if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
1152
+ let data2 = new Uint16Array(buffer2.size - buffer2.skip);
1153
+ let endPos = cursor.pos - buffer2.size, index = data2.length;
1154
+ while (cursor.pos > endPos)
1155
+ index = copyToBuffer(buffer2.start, data2, index);
1156
+ node = new TreeBuffer(data2, end - buffer2.start, nodeSet);
1157
+ startPos = buffer2.start - parentStart;
1158
+ } else {
1159
+ let endPos = cursor.pos - size;
1160
+ cursor.next();
1161
+ let localChildren = [], localPositions = [];
1162
+ let localInRepeat = id >= minRepeatType ? id : -1;
1163
+ let lastGroup = 0, lastEnd = end;
1164
+ while (cursor.pos > endPos) {
1165
+ if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
1166
+ if (cursor.end <= lastEnd - maxBufferLength) {
1167
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
1168
+ lastGroup = localChildren.length;
1169
+ lastEnd = cursor.end;
1170
+ }
1171
+ cursor.next();
1172
+ } else {
1173
+ takeNode(start, endPos, localChildren, localPositions, localInRepeat);
1174
+ }
1175
+ }
1176
+ if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1177
+ makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
1178
+ localChildren.reverse();
1179
+ localPositions.reverse();
1180
+ if (localInRepeat > -1 && lastGroup > 0) {
1181
+ let make = makeBalanced(type);
1182
+ node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
1183
+ } else {
1184
+ node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
1185
+ }
1186
+ }
1187
+ children2.push(node);
1188
+ positions2.push(startPos);
1189
+ }
1190
+ function makeBalanced(type) {
1191
+ return (children2, positions2, length2) => {
1192
+ let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp;
1193
+ if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) {
1194
+ if (!lastI && last.type == type && last.length == length2)
1195
+ return last;
1196
+ if (lookAheadProp = last.prop(NodeProp.lookAhead))
1197
+ lookAhead2 = positions2[lastI] + last.length + lookAheadProp;
1198
+ }
1199
+ return makeTree(type, children2, positions2, length2, lookAhead2);
1200
+ };
1201
+ }
1202
+ function makeRepeatLeaf(children2, positions2, base, i, from, to, type, lookAhead2) {
1203
+ let localChildren = [], localPositions = [];
1204
+ while (children2.length > i) {
1205
+ localChildren.push(children2.pop());
1206
+ localPositions.push(positions2.pop() + base - from);
1207
+ }
1208
+ children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead2 - to));
1209
+ positions2.push(from - base);
1210
+ }
1211
+ function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) {
1212
+ if (contextHash) {
1213
+ let pair2 = [NodeProp.contextHash, contextHash];
1214
+ props = props ? [pair2].concat(props) : [pair2];
1215
+ }
1216
+ if (lookAhead2 > 25) {
1217
+ let pair2 = [NodeProp.lookAhead, lookAhead2];
1218
+ props = props ? [pair2].concat(props) : [pair2];
1219
+ }
1220
+ return new Tree(type, children2, positions2, length2, props);
1221
+ }
1222
+ function findBufferSize(maxSize, inRepeat) {
1223
+ let fork = cursor.fork();
1224
+ let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
1225
+ let result = { size: 0, start: 0, skip: 0 };
1226
+ scan:
1227
+ for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
1228
+ let nodeSize2 = fork.size;
1229
+ if (fork.id == inRepeat && nodeSize2 >= 0) {
1230
+ result.size = size;
1231
+ result.start = start;
1232
+ result.skip = skip;
1233
+ skip += 4;
1234
+ size += 4;
1235
+ fork.next();
1236
+ continue;
1237
+ }
1238
+ let startPos = fork.pos - nodeSize2;
1239
+ if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart)
1240
+ break;
1241
+ let localSkipped = fork.id >= minRepeatType ? 4 : 0;
1242
+ let nodeStart = fork.start;
1243
+ fork.next();
1244
+ while (fork.pos > startPos) {
1245
+ if (fork.size < 0) {
1246
+ if (fork.size == -3)
1247
+ localSkipped += 4;
1248
+ else
1249
+ break scan;
1250
+ } else if (fork.id >= minRepeatType) {
1251
+ localSkipped += 4;
1252
+ }
1253
+ fork.next();
1254
+ }
1255
+ start = nodeStart;
1256
+ size += nodeSize2;
1257
+ skip += localSkipped;
1258
+ }
1259
+ if (inRepeat < 0 || size == maxSize) {
1260
+ result.size = size;
1261
+ result.start = start;
1262
+ result.skip = skip;
1263
+ }
1264
+ return result.size > 4 ? result : void 0;
1265
+ }
1266
+ function copyToBuffer(bufferStart, buffer2, index) {
1267
+ let { id, start, end, size } = cursor;
1268
+ cursor.next();
1269
+ if (size >= 0 && id < minRepeatType) {
1270
+ let startIndex = index;
1271
+ if (size > 4) {
1272
+ let endPos = cursor.pos - (size - 4);
1273
+ while (cursor.pos > endPos)
1274
+ index = copyToBuffer(bufferStart, buffer2, index);
1275
+ }
1276
+ buffer2[--index] = startIndex;
1277
+ buffer2[--index] = end - bufferStart;
1278
+ buffer2[--index] = start - bufferStart;
1279
+ buffer2[--index] = id;
1280
+ } else if (size == -3) {
1281
+ contextHash = id;
1282
+ } else if (size == -4) {
1283
+ lookAhead = id;
1284
+ }
1285
+ return index;
1286
+ }
1287
+ let children = [], positions = [];
1288
+ while (cursor.pos > 0)
1289
+ takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
1290
+ let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
1291
+ return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
1292
+ }
1293
+ var nodeSizeCache = /* @__PURE__ */ new WeakMap();
1294
+ function nodeSize(balanceType, node) {
1295
+ if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
1296
+ return 1;
1297
+ let size = nodeSizeCache.get(node);
1298
+ if (size == null) {
1299
+ size = 1;
1300
+ for (let child of node.children) {
1301
+ if (child.type != balanceType || !(child instanceof Tree)) {
1302
+ size = 1;
1303
+ break;
1304
+ }
1305
+ size += nodeSize(balanceType, child);
1306
+ }
1307
+ nodeSizeCache.set(node, size);
1308
+ }
1309
+ return size;
1310
+ }
1311
+ function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
1312
+ let total = 0;
1313
+ for (let i = from; i < to; i++)
1314
+ total += nodeSize(balanceType, children[i]);
1315
+ let maxChild = Math.ceil(
1316
+ total * 1.5 / 8
1317
+ /* Balance.BranchFactor */
1318
+ );
1319
+ let localChildren = [], localPositions = [];
1320
+ function divide(children2, positions2, from2, to2, offset) {
1321
+ for (let i = from2; i < to2; ) {
1322
+ let groupFrom = i, groupStart = positions2[i], groupSize = nodeSize(balanceType, children2[i]);
1323
+ i++;
1324
+ for (; i < to2; i++) {
1325
+ let nextSize = nodeSize(balanceType, children2[i]);
1326
+ if (groupSize + nextSize >= maxChild)
1327
+ break;
1328
+ groupSize += nextSize;
1329
+ }
1330
+ if (i == groupFrom + 1) {
1331
+ if (groupSize > maxChild) {
1332
+ let only = children2[groupFrom];
1333
+ divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset);
1334
+ continue;
1335
+ }
1336
+ localChildren.push(children2[groupFrom]);
1337
+ } else {
1338
+ let length2 = positions2[i - 1] + children2[i - 1].length - groupStart;
1339
+ localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i, groupStart, length2, null, mkTree));
1340
+ }
1341
+ localPositions.push(groupStart + offset - start);
1342
+ }
1343
+ }
1344
+ divide(children, positions, from, to, 0);
1345
+ return (mkTop || mkTree)(localChildren, localPositions, length);
1346
+ }
1347
+ var Parser = class {
1348
+ /// Start a parse, returning a [partial parse](#common.PartialParse)
1349
+ /// object. [`fragments`](#common.TreeFragment) can be passed in to
1350
+ /// make the parse incremental.
1351
+ ///
1352
+ /// By default, the entire input is parsed. You can pass `ranges`,
1353
+ /// which should be a sorted array of non-empty, non-overlapping
1354
+ /// ranges, to parse only those ranges. The tree returned in that
1355
+ /// case will start at `ranges[0].from`.
1356
+ startParse(input, fragments, ranges) {
1357
+ if (typeof input == "string")
1358
+ input = new StringInput(input);
1359
+ ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map((r) => new Range(r.from, r.to)) : [new Range(0, 0)];
1360
+ return this.createParse(input, fragments || [], ranges);
1361
+ }
1362
+ /// Run a full parse, returning the resulting tree.
1363
+ parse(input, fragments, ranges) {
1364
+ let parse = this.startParse(input, fragments, ranges);
1365
+ for (; ; ) {
1366
+ let done = parse.advance();
1367
+ if (done)
1368
+ return done;
1369
+ }
1370
+ }
1371
+ };
1372
+ var StringInput = class {
1373
+ constructor(string) {
1374
+ this.string = string;
1375
+ }
1376
+ get length() {
1377
+ return this.string.length;
1378
+ }
1379
+ chunk(from) {
1380
+ return this.string.slice(from);
1381
+ }
1382
+ get lineChunks() {
1383
+ return false;
1384
+ }
1385
+ read(from, to) {
1386
+ return this.string.slice(from, to);
1387
+ }
1388
+ };
1389
+ var stoppedInner = new NodeProp({ perNode: true });
1390
+
1391
+ // ../../node_modules/@lezer/lr/dist/index.js
1392
+ var Stack = class _Stack {
1393
+ /// @internal
1394
+ constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) {
1395
+ this.p = p;
1396
+ this.stack = stack;
1397
+ this.state = state;
1398
+ this.reducePos = reducePos;
1399
+ this.pos = pos;
1400
+ this.score = score;
1401
+ this.buffer = buffer;
1402
+ this.bufferBase = bufferBase;
1403
+ this.curContext = curContext;
1404
+ this.lookAhead = lookAhead;
1405
+ this.parent = parent;
1406
+ }
1407
+ /// @internal
1408
+ toString() {
1409
+ return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
1410
+ }
1411
+ // Start an empty stack
1412
+ /// @internal
1413
+ static start(p, state, pos = 0) {
1414
+ let cx = p.parser.context;
1415
+ return new _Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
1416
+ }
1417
+ /// The stack's current [context](#lr.ContextTracker) value, if
1418
+ /// any. Its type will depend on the context tracker's type
1419
+ /// parameter, or it will be `null` if there is no context
1420
+ /// tracker.
1421
+ get context() {
1422
+ return this.curContext ? this.curContext.context : null;
1423
+ }
1424
+ // Push a state onto the stack, tracking its start position as well
1425
+ // as the buffer base at that point.
1426
+ /// @internal
1427
+ pushState(state, start) {
1428
+ this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
1429
+ this.state = state;
1430
+ }
1431
+ // Apply a reduce action
1432
+ /// @internal
1433
+ reduce(action) {
1434
+ var _a;
1435
+ let depth = action >> 19, type = action & 65535;
1436
+ let { parser: parser2 } = this.p;
1437
+ let dPrec = parser2.dynamicPrecedence(type);
1438
+ if (dPrec)
1439
+ this.score += dPrec;
1440
+ if (depth == 0) {
1441
+ this.pushState(parser2.getGoto(this.state, type, true), this.reducePos);
1442
+ if (type < parser2.minRepeatTerm)
1443
+ this.storeNode(type, this.reducePos, this.reducePos, 4, true);
1444
+ this.reduceContext(type, this.reducePos);
1445
+ return;
1446
+ }
1447
+ let base = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
1448
+ let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
1449
+ if (size >= 2e3 && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
1450
+ if (start == this.p.lastBigReductionStart) {
1451
+ this.p.bigReductionCount++;
1452
+ this.p.lastBigReductionSize = size;
1453
+ } else if (this.p.lastBigReductionSize < size) {
1454
+ this.p.bigReductionCount = 1;
1455
+ this.p.lastBigReductionStart = start;
1456
+ this.p.lastBigReductionSize = size;
1457
+ }
1458
+ }
1459
+ let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
1460
+ if (type < parser2.minRepeatTerm || action & 131072) {
1461
+ let pos = parser2.stateFlag(
1462
+ this.state,
1463
+ 1
1464
+ /* StateFlag.Skipped */
1465
+ ) ? this.pos : this.reducePos;
1466
+ this.storeNode(type, start, pos, count + 4, true);
1467
+ }
1468
+ if (action & 262144) {
1469
+ this.state = this.stack[base];
1470
+ } else {
1471
+ let baseStateID = this.stack[base - 3];
1472
+ this.state = parser2.getGoto(baseStateID, type, true);
1473
+ }
1474
+ while (this.stack.length > base)
1475
+ this.stack.pop();
1476
+ this.reduceContext(type, start);
1477
+ }
1478
+ // Shift a value into the buffer
1479
+ /// @internal
1480
+ storeNode(term, start, end, size = 4, isReduce = false) {
1481
+ if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
1482
+ let cur = this, top = this.buffer.length;
1483
+ if (top == 0 && cur.parent) {
1484
+ top = cur.bufferBase - cur.parent.bufferBase;
1485
+ cur = cur.parent;
1486
+ }
1487
+ if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) {
1488
+ if (start == end)
1489
+ return;
1490
+ if (cur.buffer[top - 2] >= start) {
1491
+ cur.buffer[top - 2] = end;
1492
+ return;
1493
+ }
1494
+ }
1495
+ }
1496
+ if (!isReduce || this.pos == end) {
1497
+ this.buffer.push(term, start, end, size);
1498
+ } else {
1499
+ let index = this.buffer.length;
1500
+ if (index > 0 && this.buffer[index - 4] != 0)
1501
+ while (index > 0 && this.buffer[index - 2] > end) {
1502
+ this.buffer[index] = this.buffer[index - 4];
1503
+ this.buffer[index + 1] = this.buffer[index - 3];
1504
+ this.buffer[index + 2] = this.buffer[index - 2];
1505
+ this.buffer[index + 3] = this.buffer[index - 1];
1506
+ index -= 4;
1507
+ if (size > 4)
1508
+ size -= 4;
1509
+ }
1510
+ this.buffer[index] = term;
1511
+ this.buffer[index + 1] = start;
1512
+ this.buffer[index + 2] = end;
1513
+ this.buffer[index + 3] = size;
1514
+ }
1515
+ }
1516
+ // Apply a shift action
1517
+ /// @internal
1518
+ shift(action, next, nextEnd) {
1519
+ let start = this.pos;
1520
+ if (action & 131072) {
1521
+ this.pushState(action & 65535, this.pos);
1522
+ } else if ((action & 262144) == 0) {
1523
+ let nextState = action, { parser: parser2 } = this.p;
1524
+ if (nextEnd > this.pos || next <= parser2.maxNode) {
1525
+ this.pos = nextEnd;
1526
+ if (!parser2.stateFlag(
1527
+ nextState,
1528
+ 1
1529
+ /* StateFlag.Skipped */
1530
+ ))
1531
+ this.reducePos = nextEnd;
1532
+ }
1533
+ this.pushState(nextState, start);
1534
+ this.shiftContext(next, start);
1535
+ if (next <= parser2.maxNode)
1536
+ this.buffer.push(next, start, nextEnd, 4);
1537
+ } else {
1538
+ this.pos = nextEnd;
1539
+ this.shiftContext(next, start);
1540
+ if (next <= this.p.parser.maxNode)
1541
+ this.buffer.push(next, start, nextEnd, 4);
1542
+ }
1543
+ }
1544
+ // Apply an action
1545
+ /// @internal
1546
+ apply(action, next, nextEnd) {
1547
+ if (action & 65536)
1548
+ this.reduce(action);
1549
+ else
1550
+ this.shift(action, next, nextEnd);
1551
+ }
1552
+ // Add a prebuilt (reused) node into the buffer.
1553
+ /// @internal
1554
+ useNode(value, next) {
1555
+ let index = this.p.reused.length - 1;
1556
+ if (index < 0 || this.p.reused[index] != value) {
1557
+ this.p.reused.push(value);
1558
+ index++;
1559
+ }
1560
+ let start = this.pos;
1561
+ this.reducePos = this.pos = start + value.length;
1562
+ this.pushState(next, start);
1563
+ this.buffer.push(
1564
+ index,
1565
+ start,
1566
+ this.reducePos,
1567
+ -1
1568
+ /* size == -1 means this is a reused value */
1569
+ );
1570
+ if (this.curContext)
1571
+ this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
1572
+ }
1573
+ // Split the stack. Due to the buffer sharing and the fact
1574
+ // that `this.stack` tends to stay quite shallow, this isn't very
1575
+ // expensive.
1576
+ /// @internal
1577
+ split() {
1578
+ let parent = this;
1579
+ let off = parent.buffer.length;
1580
+ while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
1581
+ off -= 4;
1582
+ let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
1583
+ while (parent && base == parent.bufferBase)
1584
+ parent = parent.parent;
1585
+ return new _Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
1586
+ }
1587
+ // Try to recover from an error by 'deleting' (ignoring) one token.
1588
+ /// @internal
1589
+ recoverByDelete(next, nextEnd) {
1590
+ let isNode = next <= this.p.parser.maxNode;
1591
+ if (isNode)
1592
+ this.storeNode(next, this.pos, nextEnd, 4);
1593
+ this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
1594
+ this.pos = this.reducePos = nextEnd;
1595
+ this.score -= 190;
1596
+ }
1597
+ /// Check if the given term would be able to be shifted (optionally
1598
+ /// after some reductions) on this stack. This can be useful for
1599
+ /// external tokenizers that want to make sure they only provide a
1600
+ /// given token when it applies.
1601
+ canShift(term) {
1602
+ for (let sim = new SimulatedStack(this); ; ) {
1603
+ let action = this.p.parser.stateSlot(
1604
+ sim.state,
1605
+ 4
1606
+ /* ParseState.DefaultReduce */
1607
+ ) || this.p.parser.hasAction(sim.state, term);
1608
+ if (action == 0)
1609
+ return false;
1610
+ if ((action & 65536) == 0)
1611
+ return true;
1612
+ sim.reduce(action);
1613
+ }
1614
+ }
1615
+ // Apply up to Recover.MaxNext recovery actions that conceptually
1616
+ // inserts some missing token or rule.
1617
+ /// @internal
1618
+ recoverByInsert(next) {
1619
+ if (this.stack.length >= 300)
1620
+ return [];
1621
+ let nextStates = this.p.parser.nextStates(this.state);
1622
+ if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
1623
+ let best = [];
1624
+ for (let i = 0, s; i < nextStates.length; i += 2) {
1625
+ if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
1626
+ best.push(nextStates[i], s);
1627
+ }
1628
+ if (this.stack.length < 120)
1629
+ for (let i = 0; best.length < 4 << 1 && i < nextStates.length; i += 2) {
1630
+ let s = nextStates[i + 1];
1631
+ if (!best.some((v, i2) => i2 & 1 && v == s))
1632
+ best.push(nextStates[i], s);
1633
+ }
1634
+ nextStates = best;
1635
+ }
1636
+ let result = [];
1637
+ for (let i = 0; i < nextStates.length && result.length < 4; i += 2) {
1638
+ let s = nextStates[i + 1];
1639
+ if (s == this.state)
1640
+ continue;
1641
+ let stack = this.split();
1642
+ stack.pushState(s, this.pos);
1643
+ stack.storeNode(0, stack.pos, stack.pos, 4, true);
1644
+ stack.shiftContext(nextStates[i], this.pos);
1645
+ stack.score -= 200;
1646
+ result.push(stack);
1647
+ }
1648
+ return result;
1649
+ }
1650
+ // Force a reduce, if possible. Return false if that can't
1651
+ // be done.
1652
+ /// @internal
1653
+ forceReduce() {
1654
+ let { parser: parser2 } = this.p;
1655
+ let reduce = parser2.stateSlot(
1656
+ this.state,
1657
+ 5
1658
+ /* ParseState.ForcedReduce */
1659
+ );
1660
+ if ((reduce & 65536) == 0)
1661
+ return false;
1662
+ if (!parser2.validAction(this.state, reduce)) {
1663
+ let depth = reduce >> 19, term = reduce & 65535;
1664
+ let target = this.stack.length - depth * 3;
1665
+ if (target < 0 || parser2.getGoto(this.stack[target], term, false) < 0) {
1666
+ let backup = this.findForcedReduction();
1667
+ if (backup == null)
1668
+ return false;
1669
+ reduce = backup;
1670
+ }
1671
+ this.storeNode(0, this.pos, this.pos, 4, true);
1672
+ this.score -= 100;
1673
+ }
1674
+ this.reducePos = this.pos;
1675
+ this.reduce(reduce);
1676
+ return true;
1677
+ }
1678
+ /// Try to scan through the automaton to find some kind of reduction
1679
+ /// that can be applied. Used when the regular ForcedReduce field
1680
+ /// isn't a valid action. @internal
1681
+ findForcedReduction() {
1682
+ let { parser: parser2 } = this.p, seen = [];
1683
+ let explore = (state, depth) => {
1684
+ if (seen.includes(state))
1685
+ return;
1686
+ seen.push(state);
1687
+ return parser2.allActions(state, (action) => {
1688
+ if (action & (262144 | 131072))
1689
+ ;
1690
+ else if (action & 65536) {
1691
+ let rDepth = (action >> 19) - depth;
1692
+ if (rDepth > 1) {
1693
+ let term = action & 65535, target = this.stack.length - rDepth * 3;
1694
+ if (target >= 0 && parser2.getGoto(this.stack[target], term, false) >= 0)
1695
+ return rDepth << 19 | 65536 | term;
1696
+ }
1697
+ } else {
1698
+ let found = explore(action, depth + 1);
1699
+ if (found != null)
1700
+ return found;
1701
+ }
1702
+ });
1703
+ };
1704
+ return explore(this.state, 0);
1705
+ }
1706
+ /// @internal
1707
+ forceAll() {
1708
+ while (!this.p.parser.stateFlag(
1709
+ this.state,
1710
+ 2
1711
+ /* StateFlag.Accepting */
1712
+ )) {
1713
+ if (!this.forceReduce()) {
1714
+ this.storeNode(0, this.pos, this.pos, 4, true);
1715
+ break;
1716
+ }
1717
+ }
1718
+ return this;
1719
+ }
1720
+ /// Check whether this state has no further actions (assumed to be a direct descendant of the
1721
+ /// top state, since any other states must be able to continue
1722
+ /// somehow). @internal
1723
+ get deadEnd() {
1724
+ if (this.stack.length != 3)
1725
+ return false;
1726
+ let { parser: parser2 } = this.p;
1727
+ return parser2.data[parser2.stateSlot(
1728
+ this.state,
1729
+ 1
1730
+ /* ParseState.Actions */
1731
+ )] == 65535 && !parser2.stateSlot(
1732
+ this.state,
1733
+ 4
1734
+ /* ParseState.DefaultReduce */
1735
+ );
1736
+ }
1737
+ /// Restart the stack (put it back in its start state). Only safe
1738
+ /// when this.stack.length == 3 (state is directly below the top
1739
+ /// state). @internal
1740
+ restart() {
1741
+ this.state = this.stack[0];
1742
+ this.stack.length = 0;
1743
+ }
1744
+ /// @internal
1745
+ sameState(other) {
1746
+ if (this.state != other.state || this.stack.length != other.stack.length)
1747
+ return false;
1748
+ for (let i = 0; i < this.stack.length; i += 3)
1749
+ if (this.stack[i] != other.stack[i])
1750
+ return false;
1751
+ return true;
1752
+ }
1753
+ /// Get the parser used by this stack.
1754
+ get parser() {
1755
+ return this.p.parser;
1756
+ }
1757
+ /// Test whether a given dialect (by numeric ID, as exported from
1758
+ /// the terms file) is enabled.
1759
+ dialectEnabled(dialectID) {
1760
+ return this.p.parser.dialect.flags[dialectID];
1761
+ }
1762
+ shiftContext(term, start) {
1763
+ if (this.curContext)
1764
+ this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
1765
+ }
1766
+ reduceContext(term, start) {
1767
+ if (this.curContext)
1768
+ this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
1769
+ }
1770
+ /// @internal
1771
+ emitContext() {
1772
+ let last = this.buffer.length - 1;
1773
+ if (last < 0 || this.buffer[last] != -3)
1774
+ this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
1775
+ }
1776
+ /// @internal
1777
+ emitLookAhead() {
1778
+ let last = this.buffer.length - 1;
1779
+ if (last < 0 || this.buffer[last] != -4)
1780
+ this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
1781
+ }
1782
+ updateContext(context) {
1783
+ if (context != this.curContext.context) {
1784
+ let newCx = new StackContext(this.curContext.tracker, context);
1785
+ if (newCx.hash != this.curContext.hash)
1786
+ this.emitContext();
1787
+ this.curContext = newCx;
1788
+ }
1789
+ }
1790
+ /// @internal
1791
+ setLookAhead(lookAhead) {
1792
+ if (lookAhead > this.lookAhead) {
1793
+ this.emitLookAhead();
1794
+ this.lookAhead = lookAhead;
1795
+ }
1796
+ }
1797
+ /// @internal
1798
+ close() {
1799
+ if (this.curContext && this.curContext.tracker.strict)
1800
+ this.emitContext();
1801
+ if (this.lookAhead > 0)
1802
+ this.emitLookAhead();
1803
+ }
1804
+ };
1805
+ var StackContext = class {
1806
+ constructor(tracker, context) {
1807
+ this.tracker = tracker;
1808
+ this.context = context;
1809
+ this.hash = tracker.strict ? tracker.hash(context) : 0;
1810
+ }
1811
+ };
1812
+ var Recover;
1813
+ (function(Recover2) {
1814
+ Recover2[Recover2["Insert"] = 200] = "Insert";
1815
+ Recover2[Recover2["Delete"] = 190] = "Delete";
1816
+ Recover2[Recover2["Reduce"] = 100] = "Reduce";
1817
+ Recover2[Recover2["MaxNext"] = 4] = "MaxNext";
1818
+ Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
1819
+ Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
1820
+ Recover2[Recover2["MinBigReduction"] = 2e3] = "MinBigReduction";
1821
+ })(Recover || (Recover = {}));
1822
+ var SimulatedStack = class {
1823
+ constructor(start) {
1824
+ this.start = start;
1825
+ this.state = start.state;
1826
+ this.stack = start.stack;
1827
+ this.base = this.stack.length;
1828
+ }
1829
+ reduce(action) {
1830
+ let term = action & 65535, depth = action >> 19;
1831
+ if (depth == 0) {
1832
+ if (this.stack == this.start.stack)
1833
+ this.stack = this.stack.slice();
1834
+ this.stack.push(this.state, 0, 0);
1835
+ this.base += 3;
1836
+ } else {
1837
+ this.base -= (depth - 1) * 3;
1838
+ }
1839
+ let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
1840
+ this.state = goto;
1841
+ }
1842
+ };
1843
+ var StackBufferCursor = class _StackBufferCursor {
1844
+ constructor(stack, pos, index) {
1845
+ this.stack = stack;
1846
+ this.pos = pos;
1847
+ this.index = index;
1848
+ this.buffer = stack.buffer;
1849
+ if (this.index == 0)
1850
+ this.maybeNext();
1851
+ }
1852
+ static create(stack, pos = stack.bufferBase + stack.buffer.length) {
1853
+ return new _StackBufferCursor(stack, pos, pos - stack.bufferBase);
1854
+ }
1855
+ maybeNext() {
1856
+ let next = this.stack.parent;
1857
+ if (next != null) {
1858
+ this.index = this.stack.bufferBase - next.bufferBase;
1859
+ this.stack = next;
1860
+ this.buffer = next.buffer;
1861
+ }
1862
+ }
1863
+ get id() {
1864
+ return this.buffer[this.index - 4];
1865
+ }
1866
+ get start() {
1867
+ return this.buffer[this.index - 3];
1868
+ }
1869
+ get end() {
1870
+ return this.buffer[this.index - 2];
1871
+ }
1872
+ get size() {
1873
+ return this.buffer[this.index - 1];
1874
+ }
1875
+ next() {
1876
+ this.index -= 4;
1877
+ this.pos -= 4;
1878
+ if (this.index == 0)
1879
+ this.maybeNext();
1880
+ }
1881
+ fork() {
1882
+ return new _StackBufferCursor(this.stack, this.pos, this.index);
1883
+ }
1884
+ };
1885
+ function decodeArray(input, Type = Uint16Array) {
1886
+ if (typeof input != "string")
1887
+ return input;
1888
+ let array = null;
1889
+ for (let pos = 0, out = 0; pos < input.length; ) {
1890
+ let value = 0;
1891
+ for (; ; ) {
1892
+ let next = input.charCodeAt(pos++), stop = false;
1893
+ if (next == 126) {
1894
+ value = 65535;
1895
+ break;
1896
+ }
1897
+ if (next >= 92)
1898
+ next--;
1899
+ if (next >= 34)
1900
+ next--;
1901
+ let digit = next - 32;
1902
+ if (digit >= 46) {
1903
+ digit -= 46;
1904
+ stop = true;
1905
+ }
1906
+ value += digit;
1907
+ if (stop)
1908
+ break;
1909
+ value *= 46;
1910
+ }
1911
+ if (array)
1912
+ array[out++] = value;
1913
+ else
1914
+ array = new Type(value);
1915
+ }
1916
+ return array;
1917
+ }
1918
+ var CachedToken = class {
1919
+ constructor() {
1920
+ this.start = -1;
1921
+ this.value = -1;
1922
+ this.end = -1;
1923
+ this.extended = -1;
1924
+ this.lookAhead = 0;
1925
+ this.mask = 0;
1926
+ this.context = 0;
1927
+ }
1928
+ };
1929
+ var nullToken = new CachedToken();
1930
+ var InputStream = class {
1931
+ /// @internal
1932
+ constructor(input, ranges) {
1933
+ this.input = input;
1934
+ this.ranges = ranges;
1935
+ this.chunk = "";
1936
+ this.chunkOff = 0;
1937
+ this.chunk2 = "";
1938
+ this.chunk2Pos = 0;
1939
+ this.next = -1;
1940
+ this.token = nullToken;
1941
+ this.rangeIndex = 0;
1942
+ this.pos = this.chunkPos = ranges[0].from;
1943
+ this.range = ranges[0];
1944
+ this.end = ranges[ranges.length - 1].to;
1945
+ this.readNext();
1946
+ }
1947
+ /// @internal
1948
+ resolveOffset(offset, assoc) {
1949
+ let range = this.range, index = this.rangeIndex;
1950
+ let pos = this.pos + offset;
1951
+ while (pos < range.from) {
1952
+ if (!index)
1953
+ return null;
1954
+ let next = this.ranges[--index];
1955
+ pos -= range.from - next.to;
1956
+ range = next;
1957
+ }
1958
+ while (assoc < 0 ? pos > range.to : pos >= range.to) {
1959
+ if (index == this.ranges.length - 1)
1960
+ return null;
1961
+ let next = this.ranges[++index];
1962
+ pos += next.from - range.to;
1963
+ range = next;
1964
+ }
1965
+ return pos;
1966
+ }
1967
+ /// @internal
1968
+ clipPos(pos) {
1969
+ if (pos >= this.range.from && pos < this.range.to)
1970
+ return pos;
1971
+ for (let range of this.ranges)
1972
+ if (range.to > pos)
1973
+ return Math.max(pos, range.from);
1974
+ return this.end;
1975
+ }
1976
+ /// Look at a code unit near the stream position. `.peek(0)` equals
1977
+ /// `.next`, `.peek(-1)` gives you the previous character, and so
1978
+ /// on.
1979
+ ///
1980
+ /// Note that looking around during tokenizing creates dependencies
1981
+ /// on potentially far-away content, which may reduce the
1982
+ /// effectiveness incremental parsing—when looking forward—or even
1983
+ /// cause invalid reparses when looking backward more than 25 code
1984
+ /// units, since the library does not track lookbehind.
1985
+ peek(offset) {
1986
+ let idx = this.chunkOff + offset, pos, result;
1987
+ if (idx >= 0 && idx < this.chunk.length) {
1988
+ pos = this.pos + offset;
1989
+ result = this.chunk.charCodeAt(idx);
1990
+ } else {
1991
+ let resolved = this.resolveOffset(offset, 1);
1992
+ if (resolved == null)
1993
+ return -1;
1994
+ pos = resolved;
1995
+ if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
1996
+ result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
1997
+ } else {
1998
+ let i = this.rangeIndex, range = this.range;
1999
+ while (range.to <= pos)
2000
+ range = this.ranges[++i];
2001
+ this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
2002
+ if (pos + this.chunk2.length > range.to)
2003
+ this.chunk2 = this.chunk2.slice(0, range.to - pos);
2004
+ result = this.chunk2.charCodeAt(0);
2005
+ }
2006
+ }
2007
+ if (pos >= this.token.lookAhead)
2008
+ this.token.lookAhead = pos + 1;
2009
+ return result;
2010
+ }
2011
+ /// Accept a token. By default, the end of the token is set to the
2012
+ /// current stream position, but you can pass an offset (relative to
2013
+ /// the stream position) to change that.
2014
+ acceptToken(token, endOffset = 0) {
2015
+ let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
2016
+ if (end == null || end < this.token.start)
2017
+ throw new RangeError("Token end out of bounds");
2018
+ this.token.value = token;
2019
+ this.token.end = end;
2020
+ }
2021
+ getChunk() {
2022
+ if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
2023
+ let { chunk, chunkPos } = this;
2024
+ this.chunk = this.chunk2;
2025
+ this.chunkPos = this.chunk2Pos;
2026
+ this.chunk2 = chunk;
2027
+ this.chunk2Pos = chunkPos;
2028
+ this.chunkOff = this.pos - this.chunkPos;
2029
+ } else {
2030
+ this.chunk2 = this.chunk;
2031
+ this.chunk2Pos = this.chunkPos;
2032
+ let nextChunk = this.input.chunk(this.pos);
2033
+ let end = this.pos + nextChunk.length;
2034
+ this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
2035
+ this.chunkPos = this.pos;
2036
+ this.chunkOff = 0;
2037
+ }
2038
+ }
2039
+ readNext() {
2040
+ if (this.chunkOff >= this.chunk.length) {
2041
+ this.getChunk();
2042
+ if (this.chunkOff == this.chunk.length)
2043
+ return this.next = -1;
2044
+ }
2045
+ return this.next = this.chunk.charCodeAt(this.chunkOff);
2046
+ }
2047
+ /// Move the stream forward N (defaults to 1) code units. Returns
2048
+ /// the new value of [`next`](#lr.InputStream.next).
2049
+ advance(n = 1) {
2050
+ this.chunkOff += n;
2051
+ while (this.pos + n >= this.range.to) {
2052
+ if (this.rangeIndex == this.ranges.length - 1)
2053
+ return this.setDone();
2054
+ n -= this.range.to - this.pos;
2055
+ this.range = this.ranges[++this.rangeIndex];
2056
+ this.pos = this.range.from;
2057
+ }
2058
+ this.pos += n;
2059
+ if (this.pos >= this.token.lookAhead)
2060
+ this.token.lookAhead = this.pos + 1;
2061
+ return this.readNext();
2062
+ }
2063
+ setDone() {
2064
+ this.pos = this.chunkPos = this.end;
2065
+ this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
2066
+ this.chunk = "";
2067
+ return this.next = -1;
2068
+ }
2069
+ /// @internal
2070
+ reset(pos, token) {
2071
+ if (token) {
2072
+ this.token = token;
2073
+ token.start = pos;
2074
+ token.lookAhead = pos + 1;
2075
+ token.value = token.extended = -1;
2076
+ } else {
2077
+ this.token = nullToken;
2078
+ }
2079
+ if (this.pos != pos) {
2080
+ this.pos = pos;
2081
+ if (pos == this.end) {
2082
+ this.setDone();
2083
+ return this;
2084
+ }
2085
+ while (pos < this.range.from)
2086
+ this.range = this.ranges[--this.rangeIndex];
2087
+ while (pos >= this.range.to)
2088
+ this.range = this.ranges[++this.rangeIndex];
2089
+ if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
2090
+ this.chunkOff = pos - this.chunkPos;
2091
+ } else {
2092
+ this.chunk = "";
2093
+ this.chunkOff = 0;
2094
+ }
2095
+ this.readNext();
2096
+ }
2097
+ return this;
2098
+ }
2099
+ /// @internal
2100
+ read(from, to) {
2101
+ if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
2102
+ return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
2103
+ if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
2104
+ return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
2105
+ if (from >= this.range.from && to <= this.range.to)
2106
+ return this.input.read(from, to);
2107
+ let result = "";
2108
+ for (let r of this.ranges) {
2109
+ if (r.from >= to)
2110
+ break;
2111
+ if (r.to > from)
2112
+ result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
2113
+ }
2114
+ return result;
2115
+ }
2116
+ };
2117
+ var TokenGroup = class {
2118
+ constructor(data, id) {
2119
+ this.data = data;
2120
+ this.id = id;
2121
+ }
2122
+ token(input, stack) {
2123
+ let { parser: parser2 } = stack.p;
2124
+ readToken(this.data, input, stack, this.id, parser2.data, parser2.tokenPrecTable);
2125
+ }
2126
+ };
2127
+ TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2128
+ var LocalTokenGroup = class {
2129
+ constructor(data, precTable, elseToken) {
2130
+ this.precTable = precTable;
2131
+ this.elseToken = elseToken;
2132
+ this.data = typeof data == "string" ? decodeArray(data) : data;
2133
+ }
2134
+ token(input, stack) {
2135
+ let start = input.pos, skipped = 0;
2136
+ for (; ; ) {
2137
+ let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
2138
+ readToken(this.data, input, stack, 0, this.data, this.precTable);
2139
+ if (input.token.value > -1)
2140
+ break;
2141
+ if (this.elseToken == null)
2142
+ return;
2143
+ if (!atEof)
2144
+ skipped++;
2145
+ if (nextPos == null)
2146
+ break;
2147
+ input.reset(nextPos, input.token);
2148
+ }
2149
+ if (skipped) {
2150
+ input.reset(start, input.token);
2151
+ input.acceptToken(this.elseToken, skipped);
2152
+ }
2153
+ }
2154
+ };
2155
+ LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
2156
+ function readToken(data, input, stack, group, precTable, precOffset) {
2157
+ let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
2158
+ scan:
2159
+ for (; ; ) {
2160
+ if ((groupMask & data[state]) == 0)
2161
+ break;
2162
+ let accEnd = data[state + 1];
2163
+ for (let i = state + 3; i < accEnd; i += 2)
2164
+ if ((data[i + 1] & groupMask) > 0) {
2165
+ let term = data[i];
2166
+ if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
2167
+ input.acceptToken(term);
2168
+ break;
2169
+ }
2170
+ }
2171
+ let next = input.next, low = 0, high = data[state + 2];
2172
+ if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 && data[accEnd + high * 3 - 3] == 65535) {
2173
+ state = data[accEnd + high * 3 - 1];
2174
+ continue scan;
2175
+ }
2176
+ for (; low < high; ) {
2177
+ let mid = low + high >> 1;
2178
+ let index = accEnd + mid + (mid << 1);
2179
+ let from = data[index], to = data[index + 1] || 65536;
2180
+ if (next < from)
2181
+ high = mid;
2182
+ else if (next >= to)
2183
+ low = mid + 1;
2184
+ else {
2185
+ state = data[index + 2];
2186
+ input.advance();
2187
+ continue scan;
2188
+ }
2189
+ }
2190
+ break;
2191
+ }
2192
+ }
2193
+ function findOffset(data, start, term) {
2194
+ for (let i = start, next; (next = data[i]) != 65535; i++)
2195
+ if (next == term)
2196
+ return i - start;
2197
+ return -1;
2198
+ }
2199
+ function overrides(token, prev, tableData, tableOffset) {
2200
+ let iPrev = findOffset(tableData, tableOffset, prev);
2201
+ return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
2202
+ }
2203
+ var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
2204
+ var stackIDs = null;
2205
+ var Safety;
2206
+ (function(Safety2) {
2207
+ Safety2[Safety2["Margin"] = 25] = "Margin";
2208
+ })(Safety || (Safety = {}));
2209
+ function cutAt(tree, pos, side) {
2210
+ let cursor = tree.cursor(IterMode.IncludeAnonymous);
2211
+ cursor.moveTo(pos);
2212
+ for (; ; ) {
2213
+ if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
2214
+ for (; ; ) {
2215
+ if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
2216
+ return side < 0 ? Math.max(0, Math.min(
2217
+ cursor.to - 1,
2218
+ pos - 25
2219
+ /* Safety.Margin */
2220
+ )) : Math.min(tree.length, Math.max(
2221
+ cursor.from + 1,
2222
+ pos + 25
2223
+ /* Safety.Margin */
2224
+ ));
2225
+ if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
2226
+ break;
2227
+ if (!cursor.parent())
2228
+ return side < 0 ? 0 : tree.length;
2229
+ }
2230
+ }
2231
+ }
2232
+ var FragmentCursor = class {
2233
+ constructor(fragments, nodeSet) {
2234
+ this.fragments = fragments;
2235
+ this.nodeSet = nodeSet;
2236
+ this.i = 0;
2237
+ this.fragment = null;
2238
+ this.safeFrom = -1;
2239
+ this.safeTo = -1;
2240
+ this.trees = [];
2241
+ this.start = [];
2242
+ this.index = [];
2243
+ this.nextFragment();
2244
+ }
2245
+ nextFragment() {
2246
+ let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
2247
+ if (fr) {
2248
+ this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
2249
+ this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
2250
+ while (this.trees.length) {
2251
+ this.trees.pop();
2252
+ this.start.pop();
2253
+ this.index.pop();
2254
+ }
2255
+ this.trees.push(fr.tree);
2256
+ this.start.push(-fr.offset);
2257
+ this.index.push(0);
2258
+ this.nextStart = this.safeFrom;
2259
+ } else {
2260
+ this.nextStart = 1e9;
2261
+ }
2262
+ }
2263
+ // `pos` must be >= any previously given `pos` for this cursor
2264
+ nodeAt(pos) {
2265
+ if (pos < this.nextStart)
2266
+ return null;
2267
+ while (this.fragment && this.safeTo <= pos)
2268
+ this.nextFragment();
2269
+ if (!this.fragment)
2270
+ return null;
2271
+ for (; ; ) {
2272
+ let last = this.trees.length - 1;
2273
+ if (last < 0) {
2274
+ this.nextFragment();
2275
+ return null;
2276
+ }
2277
+ let top = this.trees[last], index = this.index[last];
2278
+ if (index == top.children.length) {
2279
+ this.trees.pop();
2280
+ this.start.pop();
2281
+ this.index.pop();
2282
+ continue;
2283
+ }
2284
+ let next = top.children[index];
2285
+ let start = this.start[last] + top.positions[index];
2286
+ if (start > pos) {
2287
+ this.nextStart = start;
2288
+ return null;
2289
+ }
2290
+ if (next instanceof Tree) {
2291
+ if (start == pos) {
2292
+ if (start < this.safeFrom)
2293
+ return null;
2294
+ let end = start + next.length;
2295
+ if (end <= this.safeTo) {
2296
+ let lookAhead = next.prop(NodeProp.lookAhead);
2297
+ if (!lookAhead || end + lookAhead < this.fragment.to)
2298
+ return next;
2299
+ }
2300
+ }
2301
+ this.index[last]++;
2302
+ if (start + next.length >= Math.max(this.safeFrom, pos)) {
2303
+ this.trees.push(next);
2304
+ this.start.push(start);
2305
+ this.index.push(0);
2306
+ }
2307
+ } else {
2308
+ this.index[last]++;
2309
+ this.nextStart = start + next.length;
2310
+ }
2311
+ }
2312
+ }
2313
+ };
2314
+ var TokenCache = class {
2315
+ constructor(parser2, stream) {
2316
+ this.stream = stream;
2317
+ this.tokens = [];
2318
+ this.mainToken = null;
2319
+ this.actions = [];
2320
+ this.tokens = parser2.tokenizers.map((_) => new CachedToken());
2321
+ }
2322
+ getActions(stack) {
2323
+ let actionIndex = 0;
2324
+ let main = null;
2325
+ let { parser: parser2 } = stack.p, { tokenizers } = parser2;
2326
+ let mask = parser2.stateSlot(
2327
+ stack.state,
2328
+ 3
2329
+ /* ParseState.TokenizerMask */
2330
+ );
2331
+ let context = stack.curContext ? stack.curContext.hash : 0;
2332
+ let lookAhead = 0;
2333
+ for (let i = 0; i < tokenizers.length; i++) {
2334
+ if ((1 << i & mask) == 0)
2335
+ continue;
2336
+ let tokenizer = tokenizers[i], token = this.tokens[i];
2337
+ if (main && !tokenizer.fallback)
2338
+ continue;
2339
+ if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
2340
+ this.updateCachedToken(token, tokenizer, stack);
2341
+ token.mask = mask;
2342
+ token.context = context;
2343
+ }
2344
+ if (token.lookAhead > token.end + 25)
2345
+ lookAhead = Math.max(token.lookAhead, lookAhead);
2346
+ if (token.value != 0) {
2347
+ let startIndex = actionIndex;
2348
+ if (token.extended > -1)
2349
+ actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
2350
+ actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
2351
+ if (!tokenizer.extend) {
2352
+ main = token;
2353
+ if (actionIndex > startIndex)
2354
+ break;
2355
+ }
2356
+ }
2357
+ }
2358
+ while (this.actions.length > actionIndex)
2359
+ this.actions.pop();
2360
+ if (lookAhead)
2361
+ stack.setLookAhead(lookAhead);
2362
+ if (!main && stack.pos == this.stream.end) {
2363
+ main = new CachedToken();
2364
+ main.value = stack.p.parser.eofTerm;
2365
+ main.start = main.end = stack.pos;
2366
+ actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
2367
+ }
2368
+ this.mainToken = main;
2369
+ return this.actions;
2370
+ }
2371
+ getMainToken(stack) {
2372
+ if (this.mainToken)
2373
+ return this.mainToken;
2374
+ let main = new CachedToken(), { pos, p } = stack;
2375
+ main.start = pos;
2376
+ main.end = Math.min(pos + 1, p.stream.end);
2377
+ main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
2378
+ return main;
2379
+ }
2380
+ updateCachedToken(token, tokenizer, stack) {
2381
+ let start = this.stream.clipPos(stack.pos);
2382
+ tokenizer.token(this.stream.reset(start, token), stack);
2383
+ if (token.value > -1) {
2384
+ let { parser: parser2 } = stack.p;
2385
+ for (let i = 0; i < parser2.specialized.length; i++)
2386
+ if (parser2.specialized[i] == token.value) {
2387
+ let result = parser2.specializers[i](this.stream.read(token.start, token.end), stack);
2388
+ if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
2389
+ if ((result & 1) == 0)
2390
+ token.value = result >> 1;
2391
+ else
2392
+ token.extended = result >> 1;
2393
+ break;
2394
+ }
2395
+ }
2396
+ } else {
2397
+ token.value = 0;
2398
+ token.end = this.stream.clipPos(start + 1);
2399
+ }
2400
+ }
2401
+ putAction(action, token, end, index) {
2402
+ for (let i = 0; i < index; i += 3)
2403
+ if (this.actions[i] == action)
2404
+ return index;
2405
+ this.actions[index++] = action;
2406
+ this.actions[index++] = token;
2407
+ this.actions[index++] = end;
2408
+ return index;
2409
+ }
2410
+ addActions(stack, token, end, index) {
2411
+ let { state } = stack, { parser: parser2 } = stack.p, { data } = parser2;
2412
+ for (let set = 0; set < 2; set++) {
2413
+ for (let i = parser2.stateSlot(
2414
+ state,
2415
+ set ? 2 : 1
2416
+ /* ParseState.Actions */
2417
+ ); ; i += 3) {
2418
+ if (data[i] == 65535) {
2419
+ if (data[i + 1] == 1) {
2420
+ i = pair(data, i + 2);
2421
+ } else {
2422
+ if (index == 0 && data[i + 1] == 2)
2423
+ index = this.putAction(pair(data, i + 2), token, end, index);
2424
+ break;
2425
+ }
2426
+ }
2427
+ if (data[i] == token)
2428
+ index = this.putAction(pair(data, i + 1), token, end, index);
2429
+ }
2430
+ }
2431
+ return index;
2432
+ }
2433
+ };
2434
+ var Rec;
2435
+ (function(Rec2) {
2436
+ Rec2[Rec2["Distance"] = 5] = "Distance";
2437
+ Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
2438
+ Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune";
2439
+ Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit";
2440
+ Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth";
2441
+ Rec2[Rec2["CutTo"] = 9e3] = "CutTo";
2442
+ Rec2[Rec2["MaxLeftAssociativeReductionCount"] = 300] = "MaxLeftAssociativeReductionCount";
2443
+ Rec2[Rec2["MaxStackCount"] = 12] = "MaxStackCount";
2444
+ })(Rec || (Rec = {}));
2445
+ var Parse = class {
2446
+ constructor(parser2, input, fragments, ranges) {
2447
+ this.parser = parser2;
2448
+ this.input = input;
2449
+ this.ranges = ranges;
2450
+ this.recovering = 0;
2451
+ this.nextStackID = 9812;
2452
+ this.minStackPos = 0;
2453
+ this.reused = [];
2454
+ this.stoppedAt = null;
2455
+ this.lastBigReductionStart = -1;
2456
+ this.lastBigReductionSize = 0;
2457
+ this.bigReductionCount = 0;
2458
+ this.stream = new InputStream(input, ranges);
2459
+ this.tokens = new TokenCache(parser2, this.stream);
2460
+ this.topTerm = parser2.top[1];
2461
+ let { from } = ranges[0];
2462
+ this.stacks = [Stack.start(this, parser2.top[0], from)];
2463
+ this.fragments = fragments.length && this.stream.end - from > parser2.bufferLength * 4 ? new FragmentCursor(fragments, parser2.nodeSet) : null;
2464
+ }
2465
+ get parsedPos() {
2466
+ return this.minStackPos;
2467
+ }
2468
+ // Move the parser forward. This will process all parse stacks at
2469
+ // `this.pos` and try to advance them to a further position. If no
2470
+ // stack for such a position is found, it'll start error-recovery.
2471
+ //
2472
+ // When the parse is finished, this will return a syntax tree. When
2473
+ // not, it returns `null`.
2474
+ advance() {
2475
+ let stacks = this.stacks, pos = this.minStackPos;
2476
+ let newStacks = this.stacks = [];
2477
+ let stopped, stoppedTokens;
2478
+ if (this.bigReductionCount > 300 && stacks.length == 1) {
2479
+ let [s] = stacks;
2480
+ while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) {
2481
+ }
2482
+ this.bigReductionCount = this.lastBigReductionSize = 0;
2483
+ }
2484
+ for (let i = 0; i < stacks.length; i++) {
2485
+ let stack = stacks[i];
2486
+ for (; ; ) {
2487
+ this.tokens.mainToken = null;
2488
+ if (stack.pos > pos) {
2489
+ newStacks.push(stack);
2490
+ } else if (this.advanceStack(stack, newStacks, stacks)) {
2491
+ continue;
2492
+ } else {
2493
+ if (!stopped) {
2494
+ stopped = [];
2495
+ stoppedTokens = [];
2496
+ }
2497
+ stopped.push(stack);
2498
+ let tok = this.tokens.getMainToken(stack);
2499
+ stoppedTokens.push(tok.value, tok.end);
2500
+ }
2501
+ break;
2502
+ }
2503
+ }
2504
+ if (!newStacks.length) {
2505
+ let finished = stopped && findFinished(stopped);
2506
+ if (finished)
2507
+ return this.stackToTree(finished);
2508
+ if (this.parser.strict) {
2509
+ if (verbose && stopped)
2510
+ console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
2511
+ throw new SyntaxError("No parse at " + pos);
2512
+ }
2513
+ if (!this.recovering)
2514
+ this.recovering = 5;
2515
+ }
2516
+ if (this.recovering && stopped) {
2517
+ let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
2518
+ if (finished)
2519
+ return this.stackToTree(finished.forceAll());
2520
+ }
2521
+ if (this.recovering) {
2522
+ let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
2523
+ if (newStacks.length > maxRemaining) {
2524
+ newStacks.sort((a, b) => b.score - a.score);
2525
+ while (newStacks.length > maxRemaining)
2526
+ newStacks.pop();
2527
+ }
2528
+ if (newStacks.some((s) => s.reducePos > pos))
2529
+ this.recovering--;
2530
+ } else if (newStacks.length > 1) {
2531
+ outer:
2532
+ for (let i = 0; i < newStacks.length - 1; i++) {
2533
+ let stack = newStacks[i];
2534
+ for (let j = i + 1; j < newStacks.length; j++) {
2535
+ let other = newStacks[j];
2536
+ if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
2537
+ if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
2538
+ newStacks.splice(j--, 1);
2539
+ } else {
2540
+ newStacks.splice(i--, 1);
2541
+ continue outer;
2542
+ }
2543
+ }
2544
+ }
2545
+ }
2546
+ if (newStacks.length > 12)
2547
+ newStacks.splice(
2548
+ 12,
2549
+ newStacks.length - 12
2550
+ /* Rec.MaxStackCount */
2551
+ );
2552
+ }
2553
+ this.minStackPos = newStacks[0].pos;
2554
+ for (let i = 1; i < newStacks.length; i++)
2555
+ if (newStacks[i].pos < this.minStackPos)
2556
+ this.minStackPos = newStacks[i].pos;
2557
+ return null;
2558
+ }
2559
+ stopAt(pos) {
2560
+ if (this.stoppedAt != null && this.stoppedAt < pos)
2561
+ throw new RangeError("Can't move stoppedAt forward");
2562
+ this.stoppedAt = pos;
2563
+ }
2564
+ // Returns an updated version of the given stack, or null if the
2565
+ // stack can't advance normally. When `split` and `stacks` are
2566
+ // given, stacks split off by ambiguous operations will be pushed to
2567
+ // `split`, or added to `stacks` if they move `pos` forward.
2568
+ advanceStack(stack, stacks, split) {
2569
+ let start = stack.pos, { parser: parser2 } = this;
2570
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2571
+ if (this.stoppedAt != null && start > this.stoppedAt)
2572
+ return stack.forceReduce() ? stack : null;
2573
+ if (this.fragments) {
2574
+ let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
2575
+ for (let cached = this.fragments.nodeAt(start); cached; ) {
2576
+ let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser2.getGoto(stack.state, cached.type.id) : -1;
2577
+ if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
2578
+ stack.useNode(cached, match);
2579
+ if (verbose)
2580
+ console.log(base + this.stackID(stack) + ` (via reuse of ${parser2.getName(cached.type.id)})`);
2581
+ return true;
2582
+ }
2583
+ if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
2584
+ break;
2585
+ let inner = cached.children[0];
2586
+ if (inner instanceof Tree && cached.positions[0] == 0)
2587
+ cached = inner;
2588
+ else
2589
+ break;
2590
+ }
2591
+ }
2592
+ let defaultReduce = parser2.stateSlot(
2593
+ stack.state,
2594
+ 4
2595
+ /* ParseState.DefaultReduce */
2596
+ );
2597
+ if (defaultReduce > 0) {
2598
+ stack.reduce(defaultReduce);
2599
+ if (verbose)
2600
+ console.log(base + this.stackID(stack) + ` (via always-reduce ${parser2.getName(
2601
+ defaultReduce & 65535
2602
+ /* Action.ValueMask */
2603
+ )})`);
2604
+ return true;
2605
+ }
2606
+ if (stack.stack.length >= 15e3) {
2607
+ while (stack.stack.length > 9e3 && stack.forceReduce()) {
2608
+ }
2609
+ }
2610
+ let actions = this.tokens.getActions(stack);
2611
+ for (let i = 0; i < actions.length; ) {
2612
+ let action = actions[i++], term = actions[i++], end = actions[i++];
2613
+ let last = i == actions.length || !split;
2614
+ let localStack = last ? stack : stack.split();
2615
+ localStack.apply(action, term, end);
2616
+ if (verbose)
2617
+ console.log(base + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser2.getName(
2618
+ action & 65535
2619
+ /* Action.ValueMask */
2620
+ )}`} for ${parser2.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
2621
+ if (last)
2622
+ return true;
2623
+ else if (localStack.pos > start)
2624
+ stacks.push(localStack);
2625
+ else
2626
+ split.push(localStack);
2627
+ }
2628
+ return false;
2629
+ }
2630
+ // Advance a given stack forward as far as it will go. Returns the
2631
+ // (possibly updated) stack if it got stuck, or null if it moved
2632
+ // forward and was given to `pushStackDedup`.
2633
+ advanceFully(stack, newStacks) {
2634
+ let pos = stack.pos;
2635
+ for (; ; ) {
2636
+ if (!this.advanceStack(stack, null, null))
2637
+ return false;
2638
+ if (stack.pos > pos) {
2639
+ pushStackDedup(stack, newStacks);
2640
+ return true;
2641
+ }
2642
+ }
2643
+ }
2644
+ runRecovery(stacks, tokens, newStacks) {
2645
+ let finished = null, restarted = false;
2646
+ for (let i = 0; i < stacks.length; i++) {
2647
+ let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
2648
+ let base = verbose ? this.stackID(stack) + " -> " : "";
2649
+ if (stack.deadEnd) {
2650
+ if (restarted)
2651
+ continue;
2652
+ restarted = true;
2653
+ stack.restart();
2654
+ if (verbose)
2655
+ console.log(base + this.stackID(stack) + " (restarted)");
2656
+ let done = this.advanceFully(stack, newStacks);
2657
+ if (done)
2658
+ continue;
2659
+ }
2660
+ let force = stack.split(), forceBase = base;
2661
+ for (let j = 0; force.forceReduce() && j < 10; j++) {
2662
+ if (verbose)
2663
+ console.log(forceBase + this.stackID(force) + " (via force-reduce)");
2664
+ let done = this.advanceFully(force, newStacks);
2665
+ if (done)
2666
+ break;
2667
+ if (verbose)
2668
+ forceBase = this.stackID(force) + " -> ";
2669
+ }
2670
+ for (let insert of stack.recoverByInsert(token)) {
2671
+ if (verbose)
2672
+ console.log(base + this.stackID(insert) + " (via recover-insert)");
2673
+ this.advanceFully(insert, newStacks);
2674
+ }
2675
+ if (this.stream.end > stack.pos) {
2676
+ if (tokenEnd == stack.pos) {
2677
+ tokenEnd++;
2678
+ token = 0;
2679
+ }
2680
+ stack.recoverByDelete(token, tokenEnd);
2681
+ if (verbose)
2682
+ console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
2683
+ pushStackDedup(stack, newStacks);
2684
+ } else if (!finished || finished.score < stack.score) {
2685
+ finished = stack;
2686
+ }
2687
+ }
2688
+ return finished;
2689
+ }
2690
+ // Convert the stack's buffer to a syntax tree.
2691
+ stackToTree(stack) {
2692
+ stack.close();
2693
+ return Tree.build({
2694
+ buffer: StackBufferCursor.create(stack),
2695
+ nodeSet: this.parser.nodeSet,
2696
+ topID: this.topTerm,
2697
+ maxBufferLength: this.parser.bufferLength,
2698
+ reused: this.reused,
2699
+ start: this.ranges[0].from,
2700
+ length: stack.pos - this.ranges[0].from,
2701
+ minRepeatType: this.parser.minRepeatTerm
2702
+ });
2703
+ }
2704
+ stackID(stack) {
2705
+ let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
2706
+ if (!id)
2707
+ stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
2708
+ return id + stack;
2709
+ }
2710
+ };
2711
+ function pushStackDedup(stack, newStacks) {
2712
+ for (let i = 0; i < newStacks.length; i++) {
2713
+ let other = newStacks[i];
2714
+ if (other.pos == stack.pos && other.sameState(stack)) {
2715
+ if (newStacks[i].score < stack.score)
2716
+ newStacks[i] = stack;
2717
+ return;
2718
+ }
2719
+ }
2720
+ newStacks.push(stack);
2721
+ }
2722
+ var Dialect = class {
2723
+ constructor(source, flags, disabled) {
2724
+ this.source = source;
2725
+ this.flags = flags;
2726
+ this.disabled = disabled;
2727
+ }
2728
+ allows(term) {
2729
+ return !this.disabled || this.disabled[term] == 0;
2730
+ }
2731
+ };
2732
+ var LRParser = class _LRParser extends Parser {
2733
+ /// @internal
2734
+ constructor(spec) {
2735
+ super();
2736
+ this.wrappers = [];
2737
+ if (spec.version != 14)
2738
+ throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
2739
+ let nodeNames = spec.nodeNames.split(" ");
2740
+ this.minRepeatTerm = nodeNames.length;
2741
+ for (let i = 0; i < spec.repeatNodeCount; i++)
2742
+ nodeNames.push("");
2743
+ let topTerms = Object.keys(spec.topRules).map((r) => spec.topRules[r][1]);
2744
+ let nodeProps = [];
2745
+ for (let i = 0; i < nodeNames.length; i++)
2746
+ nodeProps.push([]);
2747
+ function setProp(nodeID, prop, value) {
2748
+ nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
2749
+ }
2750
+ if (spec.nodeProps)
2751
+ for (let propSpec of spec.nodeProps) {
2752
+ let prop = propSpec[0];
2753
+ if (typeof prop == "string")
2754
+ prop = NodeProp[prop];
2755
+ for (let i = 1; i < propSpec.length; ) {
2756
+ let next = propSpec[i++];
2757
+ if (next >= 0) {
2758
+ setProp(next, prop, propSpec[i++]);
2759
+ } else {
2760
+ let value = propSpec[i + -next];
2761
+ for (let j = -next; j > 0; j--)
2762
+ setProp(propSpec[i++], prop, value);
2763
+ i++;
2764
+ }
2765
+ }
2766
+ }
2767
+ this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
2768
+ name: i >= this.minRepeatTerm ? void 0 : name,
2769
+ id: i,
2770
+ props: nodeProps[i],
2771
+ top: topTerms.indexOf(i) > -1,
2772
+ error: i == 0,
2773
+ skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
2774
+ })));
2775
+ if (spec.propSources)
2776
+ this.nodeSet = this.nodeSet.extend(...spec.propSources);
2777
+ this.strict = false;
2778
+ this.bufferLength = DefaultBufferLength;
2779
+ let tokenArray = decodeArray(spec.tokenData);
2780
+ this.context = spec.context;
2781
+ this.specializerSpecs = spec.specialized || [];
2782
+ this.specialized = new Uint16Array(this.specializerSpecs.length);
2783
+ for (let i = 0; i < this.specializerSpecs.length; i++)
2784
+ this.specialized[i] = this.specializerSpecs[i].term;
2785
+ this.specializers = this.specializerSpecs.map(getSpecializer);
2786
+ this.states = decodeArray(spec.states, Uint32Array);
2787
+ this.data = decodeArray(spec.stateData);
2788
+ this.goto = decodeArray(spec.goto);
2789
+ this.maxTerm = spec.maxTerm;
2790
+ this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
2791
+ this.topRules = spec.topRules;
2792
+ this.dialects = spec.dialects || {};
2793
+ this.dynamicPrecedences = spec.dynamicPrecedences || null;
2794
+ this.tokenPrecTable = spec.tokenPrec;
2795
+ this.termNames = spec.termNames || null;
2796
+ this.maxNode = this.nodeSet.types.length - 1;
2797
+ this.dialect = this.parseDialect();
2798
+ this.top = this.topRules[Object.keys(this.topRules)[0]];
2799
+ }
2800
+ createParse(input, fragments, ranges) {
2801
+ let parse = new Parse(this, input, fragments, ranges);
2802
+ for (let w of this.wrappers)
2803
+ parse = w(parse, input, fragments, ranges);
2804
+ return parse;
2805
+ }
2806
+ /// Get a goto table entry @internal
2807
+ getGoto(state, term, loose = false) {
2808
+ let table = this.goto;
2809
+ if (term >= table[0])
2810
+ return -1;
2811
+ for (let pos = table[term + 1]; ; ) {
2812
+ let groupTag = table[pos++], last = groupTag & 1;
2813
+ let target = table[pos++];
2814
+ if (last && loose)
2815
+ return target;
2816
+ for (let end = pos + (groupTag >> 1); pos < end; pos++)
2817
+ if (table[pos] == state)
2818
+ return target;
2819
+ if (last)
2820
+ return -1;
2821
+ }
2822
+ }
2823
+ /// Check if this state has an action for a given terminal @internal
2824
+ hasAction(state, terminal) {
2825
+ let data = this.data;
2826
+ for (let set = 0; set < 2; set++) {
2827
+ for (let i = this.stateSlot(
2828
+ state,
2829
+ set ? 2 : 1
2830
+ /* ParseState.Actions */
2831
+ ), next; ; i += 3) {
2832
+ if ((next = data[i]) == 65535) {
2833
+ if (data[i + 1] == 1)
2834
+ next = data[i = pair(data, i + 2)];
2835
+ else if (data[i + 1] == 2)
2836
+ return pair(data, i + 2);
2837
+ else
2838
+ break;
2839
+ }
2840
+ if (next == terminal || next == 0)
2841
+ return pair(data, i + 1);
2842
+ }
2843
+ }
2844
+ return 0;
2845
+ }
2846
+ /// @internal
2847
+ stateSlot(state, slot) {
2848
+ return this.states[state * 6 + slot];
2849
+ }
2850
+ /// @internal
2851
+ stateFlag(state, flag) {
2852
+ return (this.stateSlot(
2853
+ state,
2854
+ 0
2855
+ /* ParseState.Flags */
2856
+ ) & flag) > 0;
2857
+ }
2858
+ /// @internal
2859
+ validAction(state, action) {
2860
+ return !!this.allActions(state, (a) => a == action ? true : null);
2861
+ }
2862
+ /// @internal
2863
+ allActions(state, action) {
2864
+ let deflt = this.stateSlot(
2865
+ state,
2866
+ 4
2867
+ /* ParseState.DefaultReduce */
2868
+ );
2869
+ let result = deflt ? action(deflt) : void 0;
2870
+ for (let i = this.stateSlot(
2871
+ state,
2872
+ 1
2873
+ /* ParseState.Actions */
2874
+ ); result == null; i += 3) {
2875
+ if (this.data[i] == 65535) {
2876
+ if (this.data[i + 1] == 1)
2877
+ i = pair(this.data, i + 2);
2878
+ else
2879
+ break;
2880
+ }
2881
+ result = action(pair(this.data, i + 1));
2882
+ }
2883
+ return result;
2884
+ }
2885
+ /// Get the states that can follow this one through shift actions or
2886
+ /// goto jumps. @internal
2887
+ nextStates(state) {
2888
+ let result = [];
2889
+ for (let i = this.stateSlot(
2890
+ state,
2891
+ 1
2892
+ /* ParseState.Actions */
2893
+ ); ; i += 3) {
2894
+ if (this.data[i] == 65535) {
2895
+ if (this.data[i + 1] == 1)
2896
+ i = pair(this.data, i + 2);
2897
+ else
2898
+ break;
2899
+ }
2900
+ if ((this.data[i + 2] & 65536 >> 16) == 0) {
2901
+ let value = this.data[i + 1];
2902
+ if (!result.some((v, i2) => i2 & 1 && v == value))
2903
+ result.push(this.data[i], value);
2904
+ }
2905
+ }
2906
+ return result;
2907
+ }
2908
+ /// Configure the parser. Returns a new parser instance that has the
2909
+ /// given settings modified. Settings not provided in `config` are
2910
+ /// kept from the original parser.
2911
+ configure(config) {
2912
+ let copy = Object.assign(Object.create(_LRParser.prototype), this);
2913
+ if (config.props)
2914
+ copy.nodeSet = this.nodeSet.extend(...config.props);
2915
+ if (config.top) {
2916
+ let info2 = this.topRules[config.top];
2917
+ if (!info2)
2918
+ throw new RangeError(`Invalid top rule name ${config.top}`);
2919
+ copy.top = info2;
2920
+ }
2921
+ if (config.tokenizers)
2922
+ copy.tokenizers = this.tokenizers.map((t) => {
2923
+ let found = config.tokenizers.find((r) => r.from == t);
2924
+ return found ? found.to : t;
2925
+ });
2926
+ if (config.specializers) {
2927
+ copy.specializers = this.specializers.slice();
2928
+ copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
2929
+ let found = config.specializers.find((r) => r.from == s.external);
2930
+ if (!found)
2931
+ return s;
2932
+ let spec = Object.assign(Object.assign({}, s), { external: found.to });
2933
+ copy.specializers[i] = getSpecializer(spec);
2934
+ return spec;
2935
+ });
2936
+ }
2937
+ if (config.contextTracker)
2938
+ copy.context = config.contextTracker;
2939
+ if (config.dialect)
2940
+ copy.dialect = this.parseDialect(config.dialect);
2941
+ if (config.strict != null)
2942
+ copy.strict = config.strict;
2943
+ if (config.wrap)
2944
+ copy.wrappers = copy.wrappers.concat(config.wrap);
2945
+ if (config.bufferLength != null)
2946
+ copy.bufferLength = config.bufferLength;
2947
+ return copy;
2948
+ }
2949
+ /// Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
2950
+ /// are registered for this parser.
2951
+ hasWrappers() {
2952
+ return this.wrappers.length > 0;
2953
+ }
2954
+ /// Returns the name associated with a given term. This will only
2955
+ /// work for all terms when the parser was generated with the
2956
+ /// `--names` option. By default, only the names of tagged terms are
2957
+ /// stored.
2958
+ getName(term) {
2959
+ return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
2960
+ }
2961
+ /// The eof term id is always allocated directly after the node
2962
+ /// types. @internal
2963
+ get eofTerm() {
2964
+ return this.maxNode + 1;
2965
+ }
2966
+ /// The type of top node produced by the parser.
2967
+ get topNode() {
2968
+ return this.nodeSet.types[this.top[1]];
2969
+ }
2970
+ /// @internal
2971
+ dynamicPrecedence(term) {
2972
+ let prec = this.dynamicPrecedences;
2973
+ return prec == null ? 0 : prec[term] || 0;
2974
+ }
2975
+ /// @internal
2976
+ parseDialect(dialect) {
2977
+ let values = Object.keys(this.dialects), flags = values.map(() => false);
2978
+ if (dialect)
2979
+ for (let part of dialect.split(" ")) {
2980
+ let id = values.indexOf(part);
2981
+ if (id >= 0)
2982
+ flags[id] = true;
2983
+ }
2984
+ let disabled = null;
2985
+ for (let i = 0; i < values.length; i++)
2986
+ if (!flags[i]) {
2987
+ for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535; )
2988
+ (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
2989
+ }
2990
+ return new Dialect(dialect, flags, disabled);
2991
+ }
2992
+ /// Used by the output of the parser generator. Not available to
2993
+ /// user code. @hide
2994
+ static deserialize(spec) {
2995
+ return new _LRParser(spec);
2996
+ }
2997
+ };
2998
+ function pair(data, off) {
2999
+ return data[off] | data[off + 1] << 16;
3000
+ }
3001
+ function findFinished(stacks) {
3002
+ let best = null;
3003
+ for (let stack of stacks) {
3004
+ let stopped = stack.p.stoppedAt;
3005
+ if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
3006
+ stack.state,
3007
+ 2
3008
+ /* StateFlag.Accepting */
3009
+ ) && (!best || best.score < stack.score))
3010
+ best = stack;
3011
+ }
3012
+ return best;
3013
+ }
3014
+ function getSpecializer(spec) {
3015
+ if (spec.external) {
3016
+ let mask = spec.extend ? 1 : 0;
3017
+ return (value, stack) => spec.external(value, stack) << 1 | mask;
3018
+ }
3019
+ return spec.get;
3020
+ }
3021
+
3022
+ // ../vuu-filter-parser/src/generated/filter-parser.js
3023
+ var parser = LRParser.deserialize({
3024
+ version: 14,
3025
+ states: "%QOVQPOOOOQO'#C_'#C_O_QQO'#C^OOQO'#DO'#DOOvQQO'#C|OOQO'#DR'#DROVQPO'#CuOOQO'#C}'#C}QOQPOOOOQO'#C`'#C`O!UQQO,58xO!dQPO,59VOVQPO,59]OVQPO,59_O!iQPO,59hO!nQQO,59aOOQO'#DQ'#DQOOQO1G.d1G.dO!UQQO1G.qO!yQQO1G.wOOQO1G.y1G.yOOQO'#Cw'#CwOOQO1G/S1G/SOOQO1G.{1G.{O#[QPO'#CnO#dQPO7+$]O!UQQO'#CxO#iQPO,59YOOQO<<Gw<<GwOOQO,59d,59dOOQO-E6v-E6v",
3026
+ stateData: "#q~OoOS~OsPOvUO~OTXOUXOVXOWXOXXOYXO`ZO~Of[Oh]Oj^OmpX~OZ`O[`O]`O^`O~OabO~OseO~Of[Oh]OwgO~Oh]Ofeijeimeiwei~OcjOdbX~OdlO~OcjOdba~O",
3027
+ goto: "#YvPPw}!TPPPPPPPPPPwPP!WPP!ZP!ZP!aP!g!jPPP!p!s!aP#P!aXROU[]XQOU[]RYQRibXTOU[]XVOU[]Rf^QkhRnkRWOQSOQ_UQc[Rd]QaYQhbRmj",
3028
+ nodeNames: "\u26A0 Filter ColumnValueExpression Column Operator Eq NotEq Gt Lt Starts Ends Number String True False ColumnSetExpression In LBrack Values Comma RBrack AndExpression And OrExpression Or ParenthesizedExpression As FilterName",
3029
+ maxTerm: 39,
3030
+ skippedNodes: [0],
3031
+ repeatNodeCount: 1,
3032
+ tokenData: "6p~RnXY#PYZ#P]^#Ppq#Pqr#brs#mxy$eyz$j|}$o!O!P$t!Q![%S!^!_%_!_!`%d!`!a%i!c!}%n!}#O&V#P#Q&[#R#S%n#T#U&a#U#X%n#X#Y(w#Y#Z+]#Z#]%n#]#^.]#^#c%n#c#d/e#d#g%n#g#h0m#h#i4[#i#o%n~#USo~XY#PYZ#P]^#Ppq#P~#eP!_!`#h~#mOU~~#pWOX#mZ]#m^r#mrs$Ys#O#m#P;'S#m;'S;=`$_<%lO#m~$_O[~~$bP;=`<%l#m~$jOv~~$oOw~~$tOc~~$wP!Q![$z~%PPZ~!Q![$z~%XQZ~!O!P$t!Q![%S~%dOW~~%iOT~~%nOV~P%sUsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n~&[Oa~~&aOd~R&fYsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c'U#c#g%n#g#h(^#h#o%nR'ZWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X's#X#o%nR'zUfQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(eUjQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR(|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c)f#c#o%nR)kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#W%n#W#X*T#X#o%nR*YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h*r#h#o%nR*yUYQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR+bVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U+w#U#o%nR+|WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#`%n#`#a,f#a#o%nR,kWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h-T#h#o%nR-YWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y-r#Y#o%nR-yU^QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR.bWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#b%n#b#c.z#c#o%nR/RU`QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR/jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g0S#g#o%nR0ZUhQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR0rWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i1[#i#o%nR1aVsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#U1v#U#o%nR1{WsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g2e#g#o%nR2jWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#h%n#h#i3S#i#o%nR3XWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#g%n#g#h3q#h#o%nR3xUXQsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%nR4aWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#f%n#f#g4y#g#o%nR5OWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#i%n#i#j5h#j#o%nR5mWsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#X%n#X#Y6V#Y#o%nR6^U]QsP}!O%n!O!P%n!Q![%n!c!}%n#R#S%n#T#o%n",
3033
+ tokenizers: [0, 1],
3034
+ topRules: { "Filter": [0, 1] },
3035
+ tokenPrec: 0
3036
+ });
3037
+
3038
+ // ../vuu-filter-parser/src/FilterTreeWalker.ts
3039
+ var import_vuu_utils = require("@vuu-ui/vuu-utils");
3040
+ var _filter;
3041
+ var FilterExpression = class {
3042
+ constructor() {
3043
+ __privateAdd(this, _filter, void 0);
3044
+ }
3045
+ setFilterCombinatorOp(op, filter = __privateGet(this, _filter)) {
3046
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter) && filter.op === op) {
3047
+ return;
3048
+ } else {
3049
+ __privateSet(this, _filter, {
3050
+ op,
3051
+ filters: [__privateGet(this, _filter)]
3052
+ });
3053
+ }
3054
+ }
3055
+ add(filter) {
3056
+ if (__privateGet(this, _filter) === void 0) {
3057
+ __privateSet(this, _filter, filter);
3058
+ } else if ((0, import_vuu_utils.isMultiClauseFilter)(__privateGet(this, _filter))) {
3059
+ __privateGet(this, _filter).filters.push(filter);
3060
+ } else {
3061
+ throw Error(`Invalid filter passed to FilterExpression`);
3062
+ }
3063
+ }
3064
+ setColumn(column, filter = __privateGet(this, _filter)) {
3065
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3066
+ const target = filter.filters.at(-1);
3067
+ if (target) {
3068
+ this.setColumn(column, target);
3069
+ }
3070
+ } else if (filter) {
3071
+ filter.column = column;
3072
+ }
3073
+ }
3074
+ setOp(value, filter = __privateGet(this, _filter)) {
3075
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3076
+ const target = filter.filters.at(-1);
3077
+ if (target) {
3078
+ this.setOp(value, target);
3079
+ }
3080
+ } else if (filter) {
3081
+ filter.op = value;
3082
+ }
3083
+ }
3084
+ setValue(value, filter = __privateGet(this, _filter)) {
3085
+ var _a;
3086
+ if ((0, import_vuu_utils.isMultiClauseFilter)(filter)) {
3087
+ const target = filter.filters.at(-1);
3088
+ if (target) {
3089
+ this.setValue(value, target);
3090
+ }
3091
+ } else if ((0, import_vuu_utils.isMultiValueFilter)(filter)) {
3092
+ (_a = filter.values) != null ? _a : filter.values = [];
3093
+ filter.values.push(value);
3094
+ } else if ((0, import_vuu_utils.isSingleValueFilter)(filter)) {
3095
+ filter.value = value;
3096
+ }
3097
+ }
3098
+ toJSON(filter = __privateGet(this, _filter)) {
3099
+ if (this.name) {
3100
+ return {
3101
+ ...filter,
3102
+ name: this.name
3103
+ };
3104
+ } else {
3105
+ return filter;
3106
+ }
3107
+ }
3108
+ };
3109
+ _filter = new WeakMap();
3110
+ var walkTree = (tree, source) => {
3111
+ const filterExpression = new FilterExpression();
3112
+ const cursor = tree.cursor();
3113
+ do {
3114
+ const { name, from, to } = cursor;
3115
+ switch (name) {
3116
+ case "ColumnValueExpression":
3117
+ filterExpression.add({});
3118
+ break;
3119
+ case "ColumnSetExpression":
3120
+ filterExpression.add({ op: "in" });
3121
+ break;
3122
+ case "Or":
3123
+ case "And":
3124
+ filterExpression.setFilterCombinatorOp(source.substring(from, to));
3125
+ break;
3126
+ case "Column":
3127
+ filterExpression.setColumn(source.substring(from, to));
3128
+ break;
3129
+ case "Operator":
3130
+ filterExpression.setOp(source.substring(from, to));
3131
+ break;
3132
+ case "String":
3133
+ filterExpression.setValue(source.substring(from + 1, to - 1));
3134
+ break;
3135
+ case "Number":
3136
+ filterExpression.setValue(parseFloat(source.substring(from, to)));
3137
+ break;
3138
+ case "True":
3139
+ filterExpression.setValue(true);
3140
+ break;
3141
+ case "False":
3142
+ filterExpression.setValue(false);
3143
+ break;
3144
+ case "FilterName":
3145
+ filterExpression.name = source.substring(from, to);
3146
+ break;
3147
+ default:
3148
+ }
3149
+ } while (cursor.next());
3150
+ return filterExpression.toJSON();
3151
+ };
3152
+
3153
+ // ../vuu-filter-parser/src/FilterParser.ts
3154
+ var strictParser = parser.configure({ strict: true });
3155
+ var parseFilter = (filterQuery) => {
3156
+ const parseTree = strictParser.parse(filterQuery);
3157
+ const filter = walkTree(parseTree, filterQuery);
3158
+ return filter;
3159
+ };
3160
+
3161
+ // ../vuu-filter-parser/src/filter-evaluation-utils.ts
3162
+ function filterPredicate(columnMap, filter) {
3163
+ switch (filter.op) {
3164
+ case "in":
3165
+ return testInclude(columnMap, filter);
3166
+ case "=":
3167
+ return testEQ(columnMap, filter);
3168
+ case ">":
3169
+ return testGT(columnMap, filter);
3170
+ case ">=":
3171
+ return testGE(columnMap, filter);
3172
+ case "<":
3173
+ return testLT(columnMap, filter);
3174
+ case "<=":
3175
+ return testLE(columnMap, filter);
3176
+ case "ends":
3177
+ return testEW(columnMap, filter);
3178
+ case "starts":
3179
+ return testSW(columnMap, filter);
3180
+ case "and":
3181
+ return testAND(columnMap, filter);
3182
+ case "or":
3183
+ return testOR(columnMap, filter);
3184
+ default:
3185
+ console.log(`unrecognized filter type ${filter.op}`);
3186
+ return () => true;
3187
+ }
3188
+ }
3189
+ var testInclude = (columnMap, filter) => {
3190
+ return (row) => filter.values.indexOf(row[columnMap[filter.column]]) !== -1;
3191
+ };
3192
+ var testEQ = (columnMap, filter) => {
3193
+ return (row) => row[columnMap[filter.column]] === filter.value;
3194
+ };
3195
+ var testGT = (columnMap, filter) => {
3196
+ return (row) => row[columnMap[filter.column]] > filter.value;
3197
+ };
3198
+ var testGE = (columnMap, filter) => {
3199
+ return (row) => row[columnMap[filter.column]] >= filter.value;
3200
+ };
3201
+ var testLT = (columnMap, filter) => {
3202
+ return (row) => row[columnMap[filter.column]] < filter.value;
3203
+ };
3204
+ var testLE = (columnMap, filter) => {
3205
+ return (row) => row[columnMap[filter.column]] <= filter.value;
3206
+ };
3207
+ var testEW = (columnMap, filter) => {
3208
+ const filterValue = filter.value;
3209
+ if (typeof filterValue !== "string") {
3210
+ throw Error("string filter applied to value of wrong type");
3211
+ }
3212
+ return (row) => {
3213
+ const rowValue = row[columnMap[filter.column]];
3214
+ if (typeof rowValue !== "string") {
3215
+ throw Error("string filter applied to value of wrong type");
3216
+ }
3217
+ return rowValue.toLowerCase().endsWith(filterValue.toLowerCase());
3218
+ };
3219
+ };
3220
+ var testSW = (columnMap, filter) => {
3221
+ const filterValue = filter.value;
3222
+ if (typeof filterValue !== "string") {
3223
+ throw Error("string filter applied to value of wrong type");
3224
+ }
3225
+ return (row) => {
3226
+ const rowValue = row[columnMap[filter.column]];
3227
+ if (typeof rowValue !== "string") {
3228
+ throw Error("string filter applied to value of wrong type");
3229
+ }
3230
+ return rowValue.toLowerCase().startsWith(filterValue.toLowerCase());
3231
+ };
3232
+ };
3233
+ var testAND = (columnMap, filter) => {
3234
+ const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3235
+ return (row) => filters.every((fn) => fn(row));
3236
+ };
3237
+ function testOR(columnMap, filter) {
3238
+ const filters = filter.filters.map((f1) => filterPredicate(columnMap, f1));
3239
+ return (row) => filters.some((fn) => fn(row));
3240
+ }
3241
+
3242
+ // src/array-data-source/array-data-source.ts
3243
+ var import_vuu_utils4 = require("@vuu-ui/vuu-utils");
3244
+
3245
+ // src/array-data-source/aggregate-utils.ts
3246
+ var aggregateData = (aggregations, targetData, groupBy, leafData, columnMap, groupMap) => {
3247
+ const aggType = aggregations[aggregations.length - 1].aggType;
3248
+ const groupIndices = groupBy.map((column) => columnMap[column]);
3249
+ switch (aggType) {
3250
+ case 1:
3251
+ return aggregateSum(
3252
+ groupMap,
3253
+ leafData,
3254
+ columnMap,
3255
+ aggregations,
3256
+ targetData,
3257
+ groupIndices
3258
+ );
3259
+ case 2:
3260
+ return aggregateAverage(
3261
+ groupMap,
3262
+ leafData,
3263
+ columnMap,
3264
+ aggregations,
3265
+ targetData,
3266
+ groupIndices
3267
+ );
3268
+ case 3:
3269
+ return aggregateCount(
3270
+ groupMap,
3271
+ columnMap,
3272
+ aggregations,
3273
+ targetData,
3274
+ groupIndices
3275
+ );
3276
+ case 4:
3277
+ return aggregateHigh(
3278
+ groupMap,
3279
+ leafData,
3280
+ columnMap,
3281
+ aggregations,
3282
+ targetData,
3283
+ groupIndices
3284
+ );
3285
+ case 5:
3286
+ return aggregateLow(
3287
+ groupMap,
3288
+ leafData,
3289
+ columnMap,
3290
+ aggregations,
3291
+ targetData,
3292
+ groupIndices
3293
+ );
3294
+ case 6:
3295
+ return aggregateDistinct(
3296
+ groupMap,
3297
+ leafData,
3298
+ columnMap,
3299
+ aggregations,
3300
+ targetData,
3301
+ groupIndices
3302
+ );
3303
+ }
3304
+ };
3305
+ function aggregateCount(groupMap, columnMap, aggregations, targetData, groupIndices) {
3306
+ const counts = {};
3307
+ const aggColumn = getAggColumn(columnMap, aggregations);
3308
+ function countRecursive(map) {
3309
+ if (Array.isArray(map)) {
3310
+ return map.length;
3311
+ } else {
3312
+ let count = 0;
3313
+ for (const key in map) {
3314
+ count += 1 + countRecursive(map[key]);
3315
+ }
3316
+ return count;
3317
+ }
3318
+ }
3319
+ for (const key in groupMap) {
3320
+ const count = countRecursive(groupMap[key]);
3321
+ counts[key] = count;
3322
+ }
3323
+ for (let index = 0; index < targetData.length; index++) {
3324
+ for (const key in counts) {
3325
+ if (targetData[index][groupIndices[0]] === key) {
3326
+ targetData[index][aggColumn] = counts[key];
3327
+ }
3328
+ }
3329
+ }
3330
+ console.log("!!!! targetData", targetData);
3331
+ console.log("!!!! counts", counts);
3332
+ return counts;
3333
+ }
3334
+ function getAggColumn(columnMap, aggregations) {
3335
+ console.log("!!!! aggregation length", aggregations.length);
3336
+ const columnName = aggregations[aggregations.length - 1].column;
3337
+ const columnNumber = columnMap[columnName];
3338
+ return columnNumber;
3339
+ }
3340
+ function aggregateSum(groupMap, leafData, columnMap, aggregations, targetData, groupIndices) {
3341
+ const sums = {};
3342
+ const aggColumn = getAggColumn(columnMap, aggregations);
3343
+ function sumRecursive(map, leafData2, aggColumn2) {
3344
+ if (Array.isArray(map)) {
3345
+ let sum = 0;
3346
+ for (const key of map) {
3347
+ sum += Number(leafData2[key][aggColumn2]);
3348
+ }
3349
+ return sum;
3350
+ } else {
3351
+ let sum = 0;
3352
+ for (const key in map) {
3353
+ sum += sumRecursive(map[key], leafData2, aggColumn2);
3354
+ }
3355
+ return sum;
3356
+ }
3357
+ }
3358
+ for (const key in groupMap) {
3359
+ console.log(key);
3360
+ const sum = Number(sumRecursive(groupMap[key], leafData, aggColumn));
3361
+ sums[key] = sum;
3362
+ }
3363
+ for (let index = 0; index < targetData.length; index++) {
3364
+ for (const key in sums) {
3365
+ if (targetData[index][groupIndices[0]] === key) {
3366
+ targetData[index][aggColumn] = sums[key];
3367
+ }
3368
+ }
3369
+ }
3370
+ console.log("!!!! targetData", targetData);
3371
+ console.log("!!!! sums", sums);
3372
+ return sums;
3373
+ }
3374
+ function aggregateAverage(groupMap, leafData, columnMap, aggregations, targetData, groupIndices) {
3375
+ const averages = {};
3376
+ const aggColumn = getAggColumn(columnMap, aggregations);
3377
+ const count = aggregateCount(
3378
+ groupMap,
3379
+ columnMap,
3380
+ aggregations,
3381
+ targetData,
3382
+ groupIndices
3383
+ );
3384
+ const sum = aggregateSum(
3385
+ groupMap,
3386
+ leafData,
3387
+ columnMap,
3388
+ aggregations,
3389
+ targetData,
3390
+ groupIndices
3391
+ );
3392
+ for (const key in count) {
3393
+ let average = 0;
3394
+ average = sum[key] / count[key];
3395
+ averages[key] = average;
3396
+ }
3397
+ for (let index = 0; index < targetData.length; index++) {
3398
+ for (const key in averages) {
3399
+ if (targetData[index][groupIndices[0]] === key) {
3400
+ targetData[index][aggColumn] = averages[key];
3401
+ }
3402
+ }
3403
+ }
3404
+ console.log("!!!! targetData", targetData);
3405
+ console.log("!!!! averages", averages);
3406
+ return averages;
3407
+ }
3408
+ function getLeafColumnData(map, leafData, aggColumn) {
3409
+ const data = [];
3410
+ if (Array.isArray(map)) {
3411
+ for (const key of map) {
3412
+ data.push(leafData[key][aggColumn]);
3413
+ }
3414
+ } else {
3415
+ for (const key in map) {
3416
+ data.push(...getLeafColumnData(map[key], leafData, aggColumn));
3417
+ }
3418
+ }
3419
+ return data;
3420
+ }
3421
+ function aggregateDistinct(groupMap, leafData, columnMap, aggregations, targetData, groupIndices) {
3422
+ const distincts = {};
3423
+ const aggColumn = getAggColumn(columnMap, aggregations);
3424
+ for (const key in groupMap) {
3425
+ const leafColumnData = getLeafColumnData(
3426
+ groupMap[key],
3427
+ leafData,
3428
+ aggColumn
3429
+ );
3430
+ const distinct = [...new Set(leafColumnData)];
3431
+ distincts[key] = distinct;
3432
+ }
3433
+ for (let index = 0; index < targetData.length; index++) {
3434
+ for (const key in distincts) {
3435
+ if (targetData[index][groupIndices[0]] === key) {
3436
+ targetData[index][aggColumn] = distincts[key];
3437
+ }
3438
+ }
3439
+ }
3440
+ return distincts;
3441
+ }
3442
+ function aggregateHigh(groupMap, leafData, columnMap, aggregations, targetData, groupIndices) {
3443
+ const highs = {};
3444
+ const aggColumn = getAggColumn(columnMap, aggregations);
3445
+ for (const key in groupMap) {
3446
+ const leafColumnData = getLeafColumnData(
3447
+ groupMap[key],
3448
+ leafData,
3449
+ aggColumn
3450
+ );
3451
+ const maxNumber = Math.max(...leafColumnData);
3452
+ highs[key] = maxNumber;
3453
+ }
3454
+ for (let index = 0; index < targetData.length; index++) {
3455
+ for (const key in highs) {
3456
+ if (targetData[index][groupIndices[0]] === key) {
3457
+ targetData[index][aggColumn] = highs[key];
3458
+ }
3459
+ }
3460
+ }
3461
+ return highs;
3462
+ }
3463
+ function aggregateLow(groupMap, leafData, columnMap, aggregations, targetData, groupIndices) {
3464
+ const mins = {};
3465
+ const aggColumn = getAggColumn(columnMap, aggregations);
3466
+ for (const key in groupMap) {
3467
+ const leafColumnData = getLeafColumnData(
3468
+ groupMap[key],
3469
+ leafData,
3470
+ aggColumn
3471
+ );
3472
+ const minNumber = Math.min(...leafColumnData);
3473
+ mins[key] = minNumber;
3474
+ }
3475
+ for (let index = 0; index < targetData.length; index++) {
3476
+ for (const key in mins) {
3477
+ if (targetData[index][groupIndices[0]] === key) {
3478
+ targetData[index][aggColumn] = mins[key];
3479
+ }
3480
+ }
3481
+ }
3482
+ return mins;
3483
+ }
3484
+
3485
+ // src/array-data-source/array-data-utils.ts
3486
+ var import_vuu_utils2 = require("@vuu-ui/vuu-utils");
3487
+ var { RENDER_IDX, SELECTED } = import_vuu_utils2.metadataKeys;
3488
+ var toClientRow = (row, keys, selection, dataIndices) => {
3489
+ const [rowIndex] = row;
3490
+ let clientRow;
3491
+ if (dataIndices) {
3492
+ const { count } = import_vuu_utils2.metadataKeys;
3493
+ clientRow = row.slice(0, count).concat(dataIndices.map((idx) => row[idx]));
3494
+ } else {
3495
+ clientRow = row.slice();
3496
+ }
3497
+ clientRow[RENDER_IDX] = keys.keyFor(rowIndex);
3498
+ clientRow[SELECTED] = (0, import_vuu_utils2.getSelectionStatus)(selection, rowIndex);
3499
+ return clientRow;
3500
+ };
3501
+ var divergentMaps = (columnMap, dataMap) => {
3502
+ if (dataMap) {
3503
+ const { count: mapOffset } = import_vuu_utils2.metadataKeys;
3504
+ for (const [columnName, index] of Object.entries(columnMap)) {
3505
+ const dataIdx = dataMap[columnName];
3506
+ if (dataIdx === void 0) {
3507
+ throw Error(
3508
+ `ArrayDataSource column ${columnName} is not in underlying data set`
3509
+ );
3510
+ } else if (dataIdx !== index - mapOffset) {
3511
+ return true;
3512
+ }
3513
+ }
3514
+ }
3515
+ return false;
3516
+ };
3517
+ var getDataIndices = (columnMap, dataMap) => {
3518
+ const { count: mapOffset } = import_vuu_utils2.metadataKeys;
3519
+ const result = [];
3520
+ Object.entries(columnMap).forEach(([columnName]) => {
3521
+ result.push(dataMap[columnName] + mapOffset);
3522
+ });
3523
+ return result;
3524
+ };
3525
+ var buildDataToClientMap = (columnMap, dataMap) => {
3526
+ if (dataMap && divergentMaps(columnMap, dataMap)) {
3527
+ return getDataIndices(columnMap, dataMap);
3528
+ }
3529
+ return void 0;
3530
+ };
3531
+
3532
+ // src/array-data-source/group-utils.ts
3533
+ var import_vuu_utils3 = require("@vuu-ui/vuu-utils");
3534
+ var { DEPTH, IS_EXPANDED, KEY } = import_vuu_utils3.metadataKeys;
3535
+ var collapseGroup = (key, groupedRows) => {
3536
+ const rows = [];
3537
+ for (let i = 0, idx = 0, collapsed = false, len = groupedRows.length; i < len; i++) {
3538
+ const row = groupedRows[i];
3539
+ const { [DEPTH]: depth, [KEY]: rowKey } = row;
3540
+ if (rowKey === key) {
3541
+ const collapsedRow = row.slice();
3542
+ collapsedRow[IS_EXPANDED] = false;
3543
+ rows.push(collapsedRow);
3544
+ idx += 1;
3545
+ collapsed = true;
3546
+ while (i < len - 1 && groupedRows[i + 1][DEPTH] > depth) {
3547
+ i += 1;
3548
+ }
3549
+ } else if (collapsed) {
3550
+ const newRow = row.slice();
3551
+ newRow[0] = idx;
3552
+ newRow[1] = idx;
3553
+ rows.push(newRow);
3554
+ idx += 1;
3555
+ } else {
3556
+ rows.push(row);
3557
+ idx += 1;
3558
+ }
3559
+ }
3560
+ return rows;
3561
+ };
3562
+ var expandGroup = (keys, sourceRows, groupBy, columnMap, groupMap, processedData) => {
3563
+ const groupIndices = groupBy.map((column) => columnMap[column]);
3564
+ return dataRowsFromGroups2(
3565
+ groupMap,
3566
+ groupIndices,
3567
+ keys,
3568
+ sourceRows,
3569
+ void 0,
3570
+ void 0,
3571
+ void 0,
3572
+ processedData
3573
+ );
3574
+ };
3575
+ var dataRowsFromGroups2 = (groupMap, groupIndices, openKeys, sourceRows = [], root = "$root", depth = 1, rows = [], processedData) => {
3576
+ console.log(`dataRowsFromGroups2 1)`);
3577
+ const keys = Object.keys(groupMap).sort();
3578
+ for (const key of keys) {
3579
+ const idx = rows.length;
3580
+ const groupKey = `${root}|${key}`;
3581
+ const row = [idx, idx, false, false, depth, 0, groupKey, 0];
3582
+ row[groupIndices[depth - 1]] = key;
3583
+ rows.push(row);
3584
+ if (openKeys.includes(groupKey)) {
3585
+ row[IS_EXPANDED] = true;
3586
+ if (Array.isArray(groupMap[key])) {
3587
+ pushChildren(
3588
+ rows,
3589
+ groupMap[key],
3590
+ sourceRows,
3591
+ groupKey,
3592
+ depth + 1
3593
+ );
3594
+ } else {
3595
+ dataRowsFromGroups2(
3596
+ groupMap[key],
3597
+ groupIndices,
3598
+ openKeys,
3599
+ sourceRows,
3600
+ groupKey,
3601
+ depth + 1,
3602
+ rows,
3603
+ processedData
3604
+ );
3605
+ }
3606
+ }
3607
+ }
3608
+ console.log(`dataRowsFromGroups2 2)`);
3609
+ for (const key in rows) {
3610
+ for (const index in rows) {
3611
+ if (rows[key][2] === false && processedData[index] != void 0) {
3612
+ if (rows[key][groupIndices[0]] === processedData[index][groupIndices[0]]) {
3613
+ rows[key] = rows[key].splice(0, 8).concat(
3614
+ processedData[index].slice(
3615
+ 8,
3616
+ // groupIndices[0] + 1,
3617
+ processedData[index].length
3618
+ )
3619
+ );
3620
+ break;
3621
+ }
3622
+ }
3623
+ }
3624
+ }
3625
+ console.log(`dataRowsFromGroups2 3)`);
3626
+ return rows;
3627
+ };
3628
+ var pushChildren = (rows, tree, sourceRows, parentKey, depth) => {
3629
+ for (const rowIdx of tree) {
3630
+ const idx = rows.length;
3631
+ const sourceRow = sourceRows[rowIdx].slice();
3632
+ sourceRow[0] = idx;
3633
+ sourceRow[1] = idx;
3634
+ sourceRow[DEPTH] = depth;
3635
+ sourceRow[KEY] = `${parentKey}|${sourceRow[KEY]}`;
3636
+ rows.push(sourceRow);
3637
+ }
3638
+ };
3639
+ var groupRows = (rows, groupBy, columnMap) => {
3640
+ const groupIndices = groupBy.map((column) => columnMap[column]);
3641
+ const groupTree = groupLeafRows(rows, groupIndices);
3642
+ const groupedDataRows = dataRowsFromGroups(groupTree, groupIndices);
3643
+ return [groupedDataRows, groupTree];
3644
+ };
3645
+ var dataRowsFromGroups = (groupTree, groupIndices) => {
3646
+ const depth = 0;
3647
+ const rows = [];
3648
+ let idx = 0;
3649
+ const keys = Object.keys(groupTree).sort();
3650
+ for (const key of keys) {
3651
+ const row = [
3652
+ idx,
3653
+ idx,
3654
+ false,
3655
+ false,
3656
+ 1,
3657
+ 0,
3658
+ `$root|${key}`,
3659
+ 0
3660
+ ];
3661
+ row[groupIndices[depth]] = key;
3662
+ rows.push(row);
3663
+ idx += 1;
3664
+ }
3665
+ return rows;
3666
+ };
3667
+ function groupLeafRows(leafRows, groupby) {
3668
+ const groups = {};
3669
+ const levels = groupby.length;
3670
+ const lastLevel = levels - 1;
3671
+ for (let i = 0, len = leafRows.length; i < len; i++) {
3672
+ const leafRow = leafRows[i];
3673
+ let target = groups;
3674
+ let targetNode;
3675
+ let key;
3676
+ for (let level = 0; level < levels; level++) {
3677
+ const colIdx = groupby[level];
3678
+ key = leafRow[colIdx].toString();
3679
+ targetNode = target[key];
3680
+ if (targetNode && level === lastLevel) {
3681
+ targetNode.push(i);
3682
+ } else if (targetNode) {
3683
+ target = targetNode;
3684
+ } else if (!targetNode && level < lastLevel) {
3685
+ target = target[key] = {};
3686
+ } else if (!targetNode) {
3687
+ target[key] = [i];
3688
+ }
3689
+ }
3690
+ }
3691
+ console.log("!! groups", groups);
3692
+ return groups;
3693
+ }
3694
+
3695
+ // src/array-data-source/sort-utils.ts
3696
+ var defaultSortPredicate = (r1, r2, [i, direction]) => {
3697
+ const val1 = direction === "D" ? r2[i] : r1[i];
3698
+ const val2 = direction === "D" ? r1[i] : r2[i];
3699
+ if (val1 === val2) {
3700
+ return 0;
3701
+ } else if (val2 === null || val1 > val2) {
3702
+ return 1;
3703
+ } else {
3704
+ return -1;
3705
+ }
3706
+ };
3707
+ var sortComparator = (sortDefs) => {
3708
+ if (sortDefs.length === 1) {
3709
+ return singleColComparator(sortDefs);
3710
+ } else if (sortDefs.length === 2) {
3711
+ return twoColComparator(sortDefs);
3712
+ } else {
3713
+ return multiColComparator(sortDefs);
3714
+ }
3715
+ };
3716
+ var singleColComparator = ([[i, direction]]) => (r1, r2) => {
3717
+ const v1 = direction === "D" ? r2[i] : r1[i];
3718
+ const v2 = direction === "D" ? r1[i] : r2[i];
3719
+ return v1 > v2 ? 1 : v2 > v1 ? -1 : 0;
3720
+ };
3721
+ var twoColComparator = ([[idx1, direction1], [idx2, direction2]]) => (r1, r2) => {
3722
+ const v1 = direction1 === "D" ? r2[idx1] : r1[idx1];
3723
+ const v2 = direction1 === "D" ? r1[idx1] : r2[idx1];
3724
+ const v3 = direction2 === "D" ? r2[idx2] : r1[idx2];
3725
+ const v4 = direction2 === "D" ? r1[idx2] : r2[idx2];
3726
+ return v1 > v2 ? 1 : v2 > v1 ? -1 : v3 > v4 ? 1 : v4 > v3 ? -1 : 0;
3727
+ };
3728
+ var multiColComparator = (sortDefs, test = defaultSortPredicate) => (r1, r2) => {
3729
+ for (const sortDef of sortDefs) {
3730
+ const result = test(r1, r2, sortDef);
3731
+ if (result !== 0) {
3732
+ return result;
3733
+ }
3734
+ }
3735
+ return 0;
3736
+ };
3737
+ var sortRows = (rows, { sortDefs }, columnMap) => {
3738
+ const indexedSortDefs = sortDefs.map(({ column, sortType }) => [
3739
+ columnMap[column],
3740
+ sortType
3741
+ ]);
3742
+ const comparator = sortComparator(indexedSortDefs);
3743
+ return rows.slice().sort(comparator);
3744
+ };
3745
+
3746
+ // src/array-data-source/array-data-source.ts
3747
+ var { debug, info } = (0, import_vuu_utils4.logger)("ArrayDataSource");
3748
+ var { KEY: KEY2 } = import_vuu_utils4.metadataKeys;
3749
+ var toDataSourceRow = (key) => (data, index) => {
3750
+ return [index, index, true, false, 1, 0, String(data[key]), 0, ...data];
3751
+ };
3752
+ var buildTableSchema = (columns, keyColumn) => {
3753
+ const schema = {
3754
+ columns: columns.map(({ name, serverDataType = "string" }) => ({
3755
+ name,
3756
+ serverDataType
3757
+ })),
3758
+ key: keyColumn != null ? keyColumn : columns[0].name,
3759
+ table: { module: "", table: "Array" }
3760
+ };
3761
+ return schema;
3762
+ };
3763
+ var _columnMap, _config, _data, _links, _range, _selectedRowsCount, _size, _status, _title;
3764
+ var ArrayDataSource = class extends import_vuu_utils4.EventEmitter {
3765
+ constructor({
3766
+ aggregations,
3767
+ // different from RemoteDataSource
3768
+ columnDescriptors,
3769
+ data,
3770
+ dataMap,
3771
+ filter,
3772
+ groupBy,
3773
+ keyColumn,
3774
+ rangeChangeRowset = "delta",
3775
+ sort,
3776
+ title,
3777
+ viewport
3778
+ }) {
3779
+ super();
3780
+ this.lastRangeServed = { from: 0, to: 0 };
3781
+ this.openTreeNodes = [];
3782
+ /** Map reflecting positions of columns in client data sent to user */
3783
+ __privateAdd(this, _columnMap, void 0);
3784
+ __privateAdd(this, _config, import_vuu_utils4.vanillaConfig);
3785
+ __privateAdd(this, _data, void 0);
3786
+ __privateAdd(this, _links, void 0);
3787
+ __privateAdd(this, _range, import_vuu_utils4.NULL_RANGE);
3788
+ __privateAdd(this, _selectedRowsCount, 0);
3789
+ __privateAdd(this, _size, 0);
3790
+ __privateAdd(this, _status, "initialising");
3791
+ __privateAdd(this, _title, void 0);
3792
+ this.selectedRows = [];
3793
+ this.keys = new import_vuu_utils4.KeySet(__privateGet(this, _range));
3794
+ this.processedData = void 0;
3795
+ this.insert = (row) => {
3796
+ const dataSourceRow = toDataSourceRow(this.key)(row, this.size);
3797
+ __privateGet(this, _data).push(dataSourceRow);
3798
+ const { from, to } = __privateGet(this, _range);
3799
+ const [rowIdx] = dataSourceRow;
3800
+ if (rowIdx >= from && rowIdx < to) {
3801
+ this.sendRowsToClient();
3802
+ }
3803
+ };
3804
+ this.update = (row, columnName) => {
3805
+ var _a;
3806
+ const keyValue = row[this.key];
3807
+ const colIndex = __privateGet(this, _columnMap)[columnName];
3808
+ const dataColIndex = (_a = this.dataMap) == null ? void 0 : _a[columnName];
3809
+ const dataIndex = __privateGet(this, _data).findIndex((row2) => row2[KEY2] === keyValue);
3810
+ if (dataIndex !== -1 && dataColIndex !== void 0) {
3811
+ const dataSourceRow = __privateGet(this, _data)[dataIndex];
3812
+ dataSourceRow[colIndex] = row[dataColIndex];
3813
+ const { from, to } = __privateGet(this, _range);
3814
+ const [rowIdx] = dataSourceRow;
3815
+ if (rowIdx >= from && rowIdx < to) {
3816
+ this.sendRowsToClient(false, dataSourceRow);
3817
+ }
3818
+ }
3819
+ };
3820
+ this.updateRow = (row) => {
3821
+ const keyValue = row[this.key];
3822
+ const dataIndex = __privateGet(this, _data).findIndex((row2) => row2[KEY2] === keyValue);
3823
+ if (dataIndex !== -1) {
3824
+ const dataSourceRow = toDataSourceRow(this.key)(row, dataIndex);
3825
+ __privateGet(this, _data)[dataIndex] = dataSourceRow;
3826
+ const { from, to } = __privateGet(this, _range);
3827
+ if (dataIndex >= from && dataIndex < to) {
3828
+ this.sendRowsToClient(false, dataSourceRow);
3829
+ }
3830
+ }
3831
+ };
3832
+ if (!data || !columnDescriptors) {
3833
+ throw Error(
3834
+ "ArrayDataSource constructor called without data or without columnDescriptors"
3835
+ );
3836
+ }
3837
+ this.columnDescriptors = columnDescriptors;
3838
+ this.dataMap = dataMap;
3839
+ this.key = keyColumn ? this.columnDescriptors.findIndex((col) => col.name === keyColumn) : 0;
3840
+ this.rangeChangeRowset = rangeChangeRowset;
3841
+ this.tableSchema = buildTableSchema(columnDescriptors, keyColumn);
3842
+ this.viewport = viewport || (0, import_vuu_utils4.uuid)();
3843
+ __privateSet(this, _size, data.length);
3844
+ __privateSet(this, _title, title);
3845
+ const columns = columnDescriptors.map((col) => col.name);
3846
+ __privateSet(this, _columnMap, (0, import_vuu_utils4.buildColumnMap)(columns));
3847
+ this.dataIndices = buildDataToClientMap(__privateGet(this, _columnMap), this.dataMap);
3848
+ __privateSet(this, _data, data.map(toDataSourceRow(this.key)));
3849
+ this.config = {
3850
+ ...__privateGet(this, _config),
3851
+ aggregations: aggregations || __privateGet(this, _config).aggregations,
3852
+ columns,
3853
+ filter: filter || __privateGet(this, _config).filter,
3854
+ groupBy: groupBy || __privateGet(this, _config).groupBy,
3855
+ sort: sort || __privateGet(this, _config).sort
3856
+ };
3857
+ debug == null ? void 0 : debug(`columnMap: ${JSON.stringify(__privateGet(this, _columnMap))}`);
3858
+ }
3859
+ async subscribe({
3860
+ viewport = ((_a) => (_a = this.viewport) != null ? _a : (0, import_vuu_utils4.uuid)())(),
3861
+ columns,
3862
+ aggregations,
3863
+ range,
3864
+ sort,
3865
+ groupBy,
3866
+ filter
3867
+ }, callback) {
3868
+ var _a2;
3869
+ this.clientCallback = callback;
3870
+ this.viewport = viewport;
3871
+ __privateSet(this, _status, "subscribed");
3872
+ this.lastRangeServed = { from: 0, to: 0 };
3873
+ let config = __privateGet(this, _config);
3874
+ const hasConfigProps = aggregations || columns || filter || groupBy || sort;
3875
+ if (hasConfigProps) {
3876
+ if (range) {
3877
+ __privateSet(this, _range, range);
3878
+ }
3879
+ config = {
3880
+ ...config,
3881
+ aggregations: aggregations || __privateGet(this, _config).aggregations,
3882
+ columns: columns || __privateGet(this, _config).columns,
3883
+ filter: filter || __privateGet(this, _config).filter,
3884
+ groupBy: groupBy || __privateGet(this, _config).groupBy,
3885
+ sort: sort || __privateGet(this, _config).sort
3886
+ };
3887
+ }
3888
+ (_a2 = this.clientCallback) == null ? void 0 : _a2.call(this, {
3889
+ ...config,
3890
+ type: "subscribed",
3891
+ clientViewportId: this.viewport,
3892
+ range: __privateGet(this, _range),
3893
+ tableSchema: this.tableSchema
3894
+ });
3895
+ if (hasConfigProps) {
3896
+ this.config = config;
3897
+ } else {
3898
+ this.clientCallback({
3899
+ clientViewportId: this.viewport,
3900
+ mode: "size-only",
3901
+ type: "viewport-update",
3902
+ size: __privateGet(this, _data).length
3903
+ });
3904
+ if (range) {
3905
+ this.range = range;
3906
+ this.sendRowsToClient();
3907
+ } else if (__privateGet(this, _range) !== import_vuu_utils4.NULL_RANGE) {
3908
+ this.sendRowsToClient();
3909
+ }
3910
+ }
3911
+ }
3912
+ unsubscribe() {
3913
+ console.log(`unsubscribe noop`);
3914
+ }
3915
+ suspend() {
3916
+ console.log(`suspend #${this.viewport}, current status ${__privateGet(this, _status)}`);
3917
+ info == null ? void 0 : info(`suspend #${this.viewport}, current status ${__privateGet(this, _status)}`);
3918
+ __privateSet(this, _status, "suspended");
3919
+ return this;
3920
+ }
3921
+ resume() {
3922
+ console.log(`resume #${this.viewport}, current status ${__privateGet(this, _status)}`);
3923
+ const isSuspended = __privateGet(this, _status) === "suspended";
3924
+ info == null ? void 0 : info(`resume #${this.viewport}, current status ${__privateGet(this, _status)}`);
3925
+ console.log(`resume noop`);
3926
+ if (isSuspended) {
3927
+ __privateSet(this, _status, "subscribed");
3928
+ }
3929
+ return this;
3930
+ }
3931
+ disable() {
3932
+ console.log(`disable noop`);
3933
+ return this;
3934
+ }
3935
+ enable() {
3936
+ console.log(`enable noop`);
3937
+ return this;
3938
+ }
3939
+ select(selected) {
3940
+ __privateSet(this, _selectedRowsCount, selected.length);
3941
+ debug == null ? void 0 : debug(`select ${JSON.stringify(selected)}`);
3942
+ this.selectedRows = selected;
3943
+ this.setRange((0, import_vuu_utils4.resetRange)(__privateGet(this, _range)), true);
3944
+ }
3945
+ openTreeNode(key) {
3946
+ this.openTreeNodes.push(key);
3947
+ this.processedData = expandGroup(
3948
+ this.openTreeNodes,
3949
+ __privateGet(this, _data),
3950
+ __privateGet(this, _config).groupBy,
3951
+ __privateGet(this, _columnMap),
3952
+ this.groupMap,
3953
+ this.processedData
3954
+ );
3955
+ this.setRange((0, import_vuu_utils4.resetRange)(__privateGet(this, _range)), true);
3956
+ }
3957
+ closeTreeNode(key) {
3958
+ this.openTreeNodes = this.openTreeNodes.filter((value) => value !== key);
3959
+ if (this.processedData) {
3960
+ this.processedData = collapseGroup(key, this.processedData);
3961
+ this.setRange((0, import_vuu_utils4.resetRange)(__privateGet(this, _range)), true);
3962
+ }
3963
+ }
3964
+ get links() {
3965
+ return __privateGet(this, _links);
3966
+ }
3967
+ get menu() {
3968
+ return this._menu;
3969
+ }
3970
+ get status() {
3971
+ return __privateGet(this, _status);
3972
+ }
3973
+ get data() {
3974
+ return __privateGet(this, _data);
3975
+ }
3976
+ // Only used by the UpdateGenerator
3977
+ get currentData() {
3978
+ var _a;
3979
+ return (_a = this.processedData) != null ? _a : __privateGet(this, _data);
3980
+ }
3981
+ get table() {
3982
+ return this.tableSchema.table;
3983
+ }
3984
+ get config() {
3985
+ return __privateGet(this, _config);
3986
+ }
3987
+ set config(config) {
3988
+ var _a;
3989
+ const configChanges = this.applyConfig(config);
3990
+ if (configChanges) {
3991
+ if (config) {
3992
+ const originalConfig = __privateGet(this, _config);
3993
+ const newConfig = ((_a = config == null ? void 0 : config.filter) == null ? void 0 : _a.filter) && (config == null ? void 0 : config.filter.filterStruct) === void 0 ? {
3994
+ ...config,
3995
+ filter: {
3996
+ filter: config.filter.filter,
3997
+ filterStruct: parseFilter(config.filter.filter)
3998
+ }
3999
+ } : config;
4000
+ __privateSet(this, _config, (0, import_vuu_utils4.withConfigDefaults)(newConfig));
4001
+ let processedData;
4002
+ if ((0, import_vuu_utils4.hasFilter)(config)) {
4003
+ const { filter, filterStruct = parseFilter(filter) } = config.filter;
4004
+ if (filterStruct) {
4005
+ const fn = filterPredicate(__privateGet(this, _columnMap), filterStruct);
4006
+ processedData = __privateGet(this, _data).filter(fn);
4007
+ } else {
4008
+ throw Error("filter must include filterStruct");
4009
+ }
4010
+ }
4011
+ if ((0, import_vuu_utils4.hasSort)(config)) {
4012
+ processedData = sortRows(
4013
+ processedData != null ? processedData : __privateGet(this, _data),
4014
+ config.sort,
4015
+ __privateGet(this, _columnMap)
4016
+ );
4017
+ }
4018
+ if (this.openTreeNodes.length > 0 && (0, import_vuu_utils4.isGroupByChanged)(originalConfig, config)) {
4019
+ if (__privateGet(this, _config).groupBy.length === 0) {
4020
+ this.openTreeNodes.length = 0;
4021
+ } else {
4022
+ console.log("adjust the openTReeNodes groupBy changed ", {
4023
+ originalGroupBy: originalConfig.groupBy,
4024
+ newGroupBy: newConfig.groupBy
4025
+ });
4026
+ }
4027
+ }
4028
+ if ((0, import_vuu_utils4.hasGroupBy)(config)) {
4029
+ const [groupedData, groupMap] = groupRows(
4030
+ processedData != null ? processedData : __privateGet(this, _data),
4031
+ config.groupBy,
4032
+ __privateGet(this, _columnMap)
4033
+ );
4034
+ this.groupMap = groupMap;
4035
+ processedData = groupedData;
4036
+ if (this.openTreeNodes.length > 0) {
4037
+ processedData = expandGroup(
4038
+ this.openTreeNodes,
4039
+ __privateGet(this, _data),
4040
+ __privateGet(this, _config).groupBy,
4041
+ __privateGet(this, _columnMap),
4042
+ this.groupMap,
4043
+ processedData
4044
+ );
4045
+ }
4046
+ }
4047
+ this.processedData = processedData == null ? void 0 : processedData.map((row, i) => {
4048
+ const dolly = row.slice();
4049
+ dolly[0] = i;
4050
+ dolly[1] = i;
4051
+ return dolly;
4052
+ });
4053
+ }
4054
+ this.setRange((0, import_vuu_utils4.resetRange)(__privateGet(this, _range)), true);
4055
+ this.emit("config", __privateGet(this, _config), void 0, configChanges);
4056
+ }
4057
+ }
4058
+ applyConfig(config) {
4059
+ var _a;
4060
+ const { noChanges, ...otherChanges } = (0, import_vuu_utils4.isConfigChanged)(
4061
+ __privateGet(this, _config),
4062
+ config
4063
+ );
4064
+ if (noChanges !== true) {
4065
+ if (config) {
4066
+ const newConfig = ((_a = config == null ? void 0 : config.filter) == null ? void 0 : _a.filter) && (config == null ? void 0 : config.filter.filterStruct) === void 0 ? {
4067
+ ...config,
4068
+ filter: {
4069
+ filter: config.filter.filter,
4070
+ filterStruct: parseFilter(config.filter.filter)
4071
+ }
4072
+ } : config;
4073
+ __privateSet(this, _config, (0, import_vuu_utils4.withConfigDefaults)(newConfig));
4074
+ return otherChanges;
4075
+ }
4076
+ }
4077
+ }
4078
+ get selectedRowsCount() {
4079
+ return __privateGet(this, _selectedRowsCount);
4080
+ }
4081
+ get size() {
4082
+ var _a, _b;
4083
+ return (_b = (_a = this.processedData) == null ? void 0 : _a.length) != null ? _b : __privateGet(this, _data).length;
4084
+ }
4085
+ get range() {
4086
+ return __privateGet(this, _range);
4087
+ }
4088
+ set range(range) {
4089
+ this.setRange(range);
4090
+ }
4091
+ delete(row) {
4092
+ console.log(`delete row ${row.join(",")}`);
4093
+ }
4094
+ setRange(range, forceFullRefresh = false) {
4095
+ if (range.from !== __privateGet(this, _range).from || range.to !== __privateGet(this, _range).to) {
4096
+ __privateSet(this, _range, range);
4097
+ const keysResequenced = this.keys.reset(range);
4098
+ this.sendRowsToClient(forceFullRefresh || keysResequenced);
4099
+ } else if (forceFullRefresh) {
4100
+ this.sendRowsToClient(forceFullRefresh);
4101
+ }
4102
+ }
4103
+ sendRowsToClient(forceFullRefresh = false, row) {
4104
+ var _a, _b, _c;
4105
+ if (row) {
4106
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, {
4107
+ clientViewportId: this.viewport,
4108
+ mode: "update",
4109
+ rows: [
4110
+ toClientRow(row, this.keys, this.selectedRows, this.dataIndices)
4111
+ ],
4112
+ type: "viewport-update"
4113
+ });
4114
+ } else {
4115
+ const rowRange = this.rangeChangeRowset === "delta" && !forceFullRefresh ? (0, import_vuu_utils4.rangeNewItems)(this.lastRangeServed, __privateGet(this, _range)) : __privateGet(this, _range);
4116
+ const data = (_b = this.processedData) != null ? _b : __privateGet(this, _data);
4117
+ const rowsWithinViewport = data.slice(rowRange.from, rowRange.to).map(
4118
+ (row2) => toClientRow(row2, this.keys, this.selectedRows, this.dataIndices)
4119
+ );
4120
+ (_c = this.clientCallback) == null ? void 0 : _c.call(this, {
4121
+ clientViewportId: this.viewport,
4122
+ mode: "batch",
4123
+ rows: rowsWithinViewport,
4124
+ size: data.length,
4125
+ type: "viewport-update"
4126
+ });
4127
+ this.lastRangeServed = {
4128
+ from: __privateGet(this, _range).from,
4129
+ to: Math.min(
4130
+ __privateGet(this, _range).to,
4131
+ __privateGet(this, _range).from + rowsWithinViewport.length
4132
+ )
4133
+ };
4134
+ }
4135
+ }
4136
+ get columns() {
4137
+ return __privateGet(this, _config).columns;
4138
+ }
4139
+ set columns(columns) {
4140
+ const addedColumns = (0, import_vuu_utils4.getAddedItems)(this.config.columns, columns);
4141
+ if (addedColumns.length > 0) {
4142
+ const columnsWithoutDescriptors = (0, import_vuu_utils4.getMissingItems)(
4143
+ this.columnDescriptors,
4144
+ addedColumns,
4145
+ (col) => col.name
4146
+ );
4147
+ console.log(`columnsWithoutDescriptors`, {
4148
+ columnsWithoutDescriptors
4149
+ });
4150
+ }
4151
+ __privateSet(this, _columnMap, (0, import_vuu_utils4.buildColumnMap)(columns));
4152
+ this.dataIndices = buildDataToClientMap(__privateGet(this, _columnMap), this.dataMap);
4153
+ this.config = {
4154
+ ...__privateGet(this, _config),
4155
+ columns
4156
+ };
4157
+ }
4158
+ get aggregations() {
4159
+ return __privateGet(this, _config).aggregations;
4160
+ }
4161
+ set aggregations(aggregations) {
4162
+ var _a;
4163
+ __privateSet(this, _config, {
4164
+ ...__privateGet(this, _config),
4165
+ aggregations
4166
+ });
4167
+ const targetData = (_a = this.processedData) != null ? _a : __privateGet(this, _data);
4168
+ const leafData = __privateGet(this, _data);
4169
+ aggregateData(
4170
+ aggregations,
4171
+ targetData,
4172
+ __privateGet(this, _config).groupBy,
4173
+ leafData,
4174
+ __privateGet(this, _columnMap),
4175
+ this.groupMap
4176
+ );
4177
+ this.setRange((0, import_vuu_utils4.resetRange)(__privateGet(this, _range)), true);
4178
+ this.emit("config", __privateGet(this, _config));
4179
+ }
4180
+ get sort() {
4181
+ return __privateGet(this, _config).sort;
4182
+ }
4183
+ set sort(sort) {
4184
+ debug == null ? void 0 : debug(`sort ${JSON.stringify(sort)}`);
4185
+ this.config = {
4186
+ ...__privateGet(this, _config),
4187
+ sort
4188
+ };
4189
+ }
4190
+ get filter() {
4191
+ return __privateGet(this, _config).filter;
4192
+ }
4193
+ set filter(filter) {
4194
+ debug == null ? void 0 : debug(`filter ${JSON.stringify(filter)}`);
4195
+ this.config = {
4196
+ ...__privateGet(this, _config),
4197
+ filter
4198
+ };
4199
+ }
4200
+ get groupBy() {
4201
+ return __privateGet(this, _config).groupBy;
4202
+ }
4203
+ set groupBy(groupBy) {
4204
+ this.config = {
4205
+ ...__privateGet(this, _config),
4206
+ groupBy
4207
+ };
4208
+ }
4209
+ get title() {
4210
+ return __privateGet(this, _title);
4211
+ }
4212
+ set title(title) {
4213
+ __privateSet(this, _title, title);
4214
+ }
4215
+ get _clientCallback() {
4216
+ return this.clientCallback;
4217
+ }
4218
+ createLink({
4219
+ parentVpId,
4220
+ link: { fromColumn, toColumn }
4221
+ }) {
4222
+ console.log("create link", {
4223
+ parentVpId,
4224
+ fromColumn,
4225
+ toColumn
4226
+ });
4227
+ }
4228
+ removeLink() {
4229
+ console.log("remove link");
4230
+ }
4231
+ findRow(rowKey) {
4232
+ const row = __privateGet(this, _data)[rowKey];
4233
+ if (row) {
4234
+ return row;
4235
+ } else {
4236
+ throw `no row found for key ${rowKey}`;
4237
+ }
4238
+ }
4239
+ applyEdit(row, columnName, value) {
4240
+ console.log(`ArrayDataSource applyEdit ${row[0]} ${columnName} ${value}`);
4241
+ return Promise.resolve(true);
4242
+ }
4243
+ async menuRpcCall(rpcRequest) {
4244
+ return new Promise((resolve) => {
4245
+ const { type } = rpcRequest;
4246
+ switch (type) {
4247
+ case "VP_EDIT_CELL_RPC":
4248
+ {
4249
+ }
4250
+ break;
4251
+ default:
4252
+ resolve(void 0);
4253
+ }
4254
+ });
4255
+ }
4256
+ };
4257
+ _columnMap = new WeakMap();
4258
+ _config = new WeakMap();
4259
+ _data = new WeakMap();
4260
+ _links = new WeakMap();
4261
+ _range = new WeakMap();
4262
+ _selectedRowsCount = new WeakMap();
4263
+ _size = new WeakMap();
4264
+ _status = new WeakMap();
4265
+ _title = new WeakMap();
4266
+
4267
+ // src/json-data-source/json-data-source.ts
4268
+ var import_vuu_utils5 = require("@vuu-ui/vuu-utils");
4269
+ var NULL_SCHEMA = { columns: [], key: "", table: { module: "", table: "" } };
4270
+ var { DEPTH: DEPTH2, IDX, IS_EXPANDED: IS_EXPANDED2, IS_LEAF, KEY: KEY3, SELECTED: SELECTED2 } = import_vuu_utils5.metadataKeys;
4271
+ var toClientRow2 = (row, keys) => {
4272
+ const [rowIndex] = row;
4273
+ const clientRow = row.slice();
4274
+ clientRow[1] = keys.keyFor(rowIndex);
4275
+ return clientRow;
4276
+ };
4277
+ var _aggregations, _config2, _data2, _filter2, _groupBy, _range2, _selectedRowsCount2, _size2, _sort, _status2, _title2;
4278
+ var JsonDataSource = class extends import_vuu_utils5.EventEmitter {
4279
+ constructor({
4280
+ aggregations,
4281
+ data,
4282
+ filter,
4283
+ groupBy,
4284
+ sort,
4285
+ title,
4286
+ viewport
4287
+ }) {
4288
+ super();
4289
+ this.expandedRows = /* @__PURE__ */ new Set();
4290
+ this.visibleRows = [];
4291
+ __privateAdd(this, _aggregations, []);
4292
+ __privateAdd(this, _config2, import_vuu_utils5.vanillaConfig);
4293
+ __privateAdd(this, _data2, void 0);
4294
+ __privateAdd(this, _filter2, { filter: "" });
4295
+ __privateAdd(this, _groupBy, []);
4296
+ __privateAdd(this, _range2, { from: 0, to: 0 });
4297
+ __privateAdd(this, _selectedRowsCount2, 0);
4298
+ __privateAdd(this, _size2, 0);
4299
+ __privateAdd(this, _sort, { sortDefs: [] });
4300
+ __privateAdd(this, _status2, "initialising");
4301
+ __privateAdd(this, _title2, void 0);
4302
+ this.keys = new import_vuu_utils5.KeySet(__privateGet(this, _range2));
4303
+ if (!data) {
4304
+ throw Error("JsonDataSource constructor called without data");
4305
+ }
4306
+ [this.columnDescriptors, __privateWrapper(this, _data2)._] = (0, import_vuu_utils5.jsonToDataSourceRows)(data);
4307
+ this.visibleRows = __privateGet(this, _data2).filter((row) => row[DEPTH2] === 0).map(
4308
+ (row, index) => [index, index].concat(row.slice(2))
4309
+ );
4310
+ this.viewport = viewport || (0, import_vuu_utils5.uuid)();
4311
+ if (aggregations) {
4312
+ __privateSet(this, _aggregations, aggregations);
4313
+ }
4314
+ if (this.columnDescriptors) {
4315
+ __privateSet(this, _config2, {
4316
+ ...__privateGet(this, _config2),
4317
+ columns: this.columnDescriptors.map((c) => c.name)
4318
+ });
4319
+ }
4320
+ if (filter) {
4321
+ __privateSet(this, _filter2, filter);
4322
+ }
4323
+ if (groupBy) {
4324
+ __privateSet(this, _groupBy, groupBy);
4325
+ }
4326
+ if (sort) {
4327
+ __privateSet(this, _sort, sort);
4328
+ }
4329
+ __privateSet(this, _title2, title);
4330
+ }
4331
+ async subscribe({
4332
+ viewport = ((_a) => (_a = this.viewport) != null ? _a : (0, import_vuu_utils5.uuid)())(),
4333
+ columns,
4334
+ aggregations,
4335
+ range,
4336
+ sort,
4337
+ groupBy,
4338
+ filter
4339
+ }, callback) {
4340
+ var _a2;
4341
+ this.clientCallback = callback;
4342
+ if (aggregations) {
4343
+ __privateSet(this, _aggregations, aggregations);
4344
+ }
4345
+ if (columns) {
4346
+ __privateSet(this, _config2, {
4347
+ ...__privateGet(this, _config2),
4348
+ columns
4349
+ });
4350
+ }
4351
+ if (filter) {
4352
+ __privateSet(this, _filter2, filter);
4353
+ }
4354
+ if (groupBy) {
4355
+ __privateSet(this, _groupBy, groupBy);
4356
+ }
4357
+ if (range) {
4358
+ __privateSet(this, _range2, range);
4359
+ }
4360
+ if (sort) {
4361
+ __privateSet(this, _sort, sort);
4362
+ }
4363
+ if (__privateGet(this, _status2) !== "initialising") {
4364
+ return;
4365
+ }
4366
+ this.viewport = viewport;
4367
+ __privateSet(this, _status2, "subscribed");
4368
+ (_a2 = this.clientCallback) == null ? void 0 : _a2.call(this, {
4369
+ aggregations: __privateGet(this, _aggregations),
4370
+ type: "subscribed",
4371
+ clientViewportId: this.viewport,
4372
+ columns: __privateGet(this, _config2).columns,
4373
+ filter: __privateGet(this, _filter2),
4374
+ groupBy: __privateGet(this, _groupBy),
4375
+ range: __privateGet(this, _range2),
4376
+ sort: __privateGet(this, _sort),
4377
+ tableSchema: NULL_SCHEMA
4378
+ });
4379
+ this.clientCallback({
4380
+ clientViewportId: this.viewport,
4381
+ mode: "size-only",
4382
+ type: "viewport-update",
4383
+ size: this.visibleRows.length
4384
+ });
4385
+ }
4386
+ unsubscribe() {
4387
+ console.log("noop");
4388
+ }
4389
+ suspend() {
4390
+ console.log("noop");
4391
+ return this;
4392
+ }
4393
+ resume() {
4394
+ console.log("noop");
4395
+ return this;
4396
+ }
4397
+ disable() {
4398
+ console.log("noop");
4399
+ return this;
4400
+ }
4401
+ enable() {
4402
+ console.log("noop");
4403
+ return this;
4404
+ }
4405
+ set data(data) {
4406
+ console.log(`set JsonDataSource data`);
4407
+ [this.columnDescriptors, __privateWrapper(this, _data2)._] = (0, import_vuu_utils5.jsonToDataSourceRows)(data);
4408
+ this.visibleRows = __privateGet(this, _data2).filter((row) => row[DEPTH2] === 0).map(
4409
+ (row, index) => [index, index].concat(row.slice(2))
4410
+ );
4411
+ requestAnimationFrame(() => {
4412
+ this.sendRowsToClient();
4413
+ });
4414
+ }
4415
+ select(selected) {
4416
+ var _a;
4417
+ const updatedRows = [];
4418
+ for (const row of __privateGet(this, _data2)) {
4419
+ const { [IDX]: rowIndex, [SELECTED2]: sel } = row;
4420
+ const wasSelected = sel === 1;
4421
+ const nowSelected = (0, import_vuu_utils5.isSelected)(selected, rowIndex);
4422
+ if (nowSelected !== wasSelected) {
4423
+ const selectedRow = row.slice();
4424
+ selectedRow[SELECTED2] = nowSelected ? 1 : 0;
4425
+ __privateGet(this, _data2)[rowIndex] = selectedRow;
4426
+ updatedRows.push(selectedRow);
4427
+ }
4428
+ }
4429
+ if (updatedRows.length > 0) {
4430
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, {
4431
+ clientViewportId: this.viewport,
4432
+ mode: "update",
4433
+ type: "viewport-update",
4434
+ rows: updatedRows
4435
+ });
4436
+ }
4437
+ }
4438
+ openTreeNode(key) {
4439
+ var _a;
4440
+ this.expandedRows.add(key);
4441
+ this.visibleRows = getVisibleRows(__privateGet(this, _data2), this.expandedRows);
4442
+ const { from, to } = __privateGet(this, _range2);
4443
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, {
4444
+ clientViewportId: this.viewport,
4445
+ mode: "batch",
4446
+ rows: this.visibleRows.slice(from, to).map((row) => toClientRow2(row, this.keys)),
4447
+ size: this.visibleRows.length,
4448
+ type: "viewport-update"
4449
+ });
4450
+ }
4451
+ closeTreeNode(key, cascade = false) {
4452
+ this.expandedRows.delete(key);
4453
+ if (cascade) {
4454
+ for (const rowKey of this.expandedRows.keys()) {
4455
+ if (rowKey.startsWith(key)) {
4456
+ this.expandedRows.delete(rowKey);
4457
+ }
4458
+ }
4459
+ }
4460
+ this.visibleRows = getVisibleRows(__privateGet(this, _data2), this.expandedRows);
4461
+ this.sendRowsToClient();
4462
+ }
4463
+ get status() {
4464
+ return __privateGet(this, _status2);
4465
+ }
4466
+ get config() {
4467
+ return __privateGet(this, _config2);
4468
+ }
4469
+ applyConfig() {
4470
+ return import_vuu_utils5.NO_CONFIG_CHANGES;
4471
+ }
4472
+ get selectedRowsCount() {
4473
+ return __privateGet(this, _selectedRowsCount2);
4474
+ }
4475
+ get size() {
4476
+ return __privateGet(this, _size2);
4477
+ }
4478
+ get range() {
4479
+ return __privateGet(this, _range2);
4480
+ }
4481
+ set range(range) {
4482
+ __privateSet(this, _range2, range);
4483
+ this.keys.reset(range);
4484
+ requestAnimationFrame(() => {
4485
+ this.sendRowsToClient();
4486
+ });
4487
+ }
4488
+ sendRowsToClient() {
4489
+ var _a;
4490
+ const { from, to } = __privateGet(this, _range2);
4491
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, {
4492
+ clientViewportId: this.viewport,
4493
+ mode: "batch",
4494
+ rows: this.visibleRows.slice(from, to).map((row) => toClientRow2(row, this.keys)),
4495
+ size: this.visibleRows.length,
4496
+ type: "viewport-update"
4497
+ });
4498
+ }
4499
+ get columns() {
4500
+ return __privateGet(this, _config2).columns;
4501
+ }
4502
+ set columns(columns) {
4503
+ __privateSet(this, _config2, {
4504
+ ...__privateGet(this, _config2),
4505
+ columns
4506
+ });
4507
+ }
4508
+ get aggregations() {
4509
+ return __privateGet(this, _aggregations);
4510
+ }
4511
+ set aggregations(aggregations) {
4512
+ __privateSet(this, _aggregations, aggregations);
4513
+ }
4514
+ get sort() {
4515
+ return __privateGet(this, _sort);
4516
+ }
4517
+ set sort(sort) {
4518
+ __privateSet(this, _sort, sort);
4519
+ }
4520
+ get filter() {
4521
+ return __privateGet(this, _filter2);
4522
+ }
4523
+ set filter(filter) {
4524
+ __privateSet(this, _filter2, filter);
4525
+ }
4526
+ get groupBy() {
4527
+ return __privateGet(this, _groupBy);
4528
+ }
4529
+ set groupBy(groupBy) {
4530
+ __privateSet(this, _groupBy, groupBy);
4531
+ }
4532
+ get title() {
4533
+ return __privateGet(this, _title2);
4534
+ }
4535
+ set title(title) {
4536
+ __privateSet(this, _title2, title);
4537
+ }
4538
+ createLink({
4539
+ parentVpId,
4540
+ link: { fromColumn, toColumn }
4541
+ }) {
4542
+ console.log("create link", {
4543
+ parentVpId,
4544
+ fromColumn,
4545
+ toColumn
4546
+ });
4547
+ }
4548
+ removeLink() {
4549
+ console.log("remove link");
4550
+ }
4551
+ async menuRpcCall(rpcRequest) {
4552
+ console.log("rmenuRpcCall", {
4553
+ rpcRequest
4554
+ });
4555
+ return void 0;
4556
+ }
4557
+ applyEdit(row, columnName, value) {
4558
+ console.log(
4559
+ `ArrayDataSource applyEdit ${row.join(",")} ${columnName} ${value}`
4560
+ );
4561
+ return Promise.resolve(true);
4562
+ }
4563
+ getChildRows(rowKey) {
4564
+ const parentRow = __privateGet(this, _data2).find((row) => row[KEY3] === rowKey);
4565
+ if (parentRow) {
4566
+ const { [IDX]: parentIdx, [DEPTH2]: parentDepth } = parentRow;
4567
+ let rowIdx = parentIdx + 1;
4568
+ const childRows = [];
4569
+ do {
4570
+ const { [DEPTH2]: depth } = __privateGet(this, _data2)[rowIdx];
4571
+ if (depth === parentDepth + 1) {
4572
+ childRows.push(__privateGet(this, _data2)[rowIdx]);
4573
+ } else if (depth <= parentDepth) {
4574
+ break;
4575
+ }
4576
+ rowIdx += 1;
4577
+ } while (rowIdx < __privateGet(this, _data2).length);
4578
+ return childRows;
4579
+ } else {
4580
+ console.warn(
4581
+ `JsonDataSource getChildRows row not found for key ${rowKey}`
4582
+ );
4583
+ }
4584
+ return [];
4585
+ }
4586
+ getRowsAtDepth(depth, visibleOnly = true) {
4587
+ const rows = visibleOnly ? this.visibleRows : __privateGet(this, _data2);
4588
+ return rows.filter((row) => row[DEPTH2] === depth);
4589
+ }
4590
+ };
4591
+ _aggregations = new WeakMap();
4592
+ _config2 = new WeakMap();
4593
+ _data2 = new WeakMap();
4594
+ _filter2 = new WeakMap();
4595
+ _groupBy = new WeakMap();
4596
+ _range2 = new WeakMap();
4597
+ _selectedRowsCount2 = new WeakMap();
4598
+ _size2 = new WeakMap();
4599
+ _sort = new WeakMap();
4600
+ _status2 = new WeakMap();
4601
+ _title2 = new WeakMap();
4602
+ function getVisibleRows(rows, expandedKeys) {
4603
+ const visibleRows = [];
4604
+ const index = { value: 0 };
4605
+ for (let i = 0; i < rows.length; i++) {
4606
+ const row = rows[i];
4607
+ const { [DEPTH2]: depth, [KEY3]: key, [IS_LEAF]: isLeaf } = row;
4608
+ const isExpanded = expandedKeys.has(key);
4609
+ visibleRows.push(cloneRow(row, index, isExpanded));
4610
+ if (!isLeaf && !isExpanded) {
4611
+ do {
4612
+ i += 1;
4613
+ } while (i < rows.length - 1 && rows[i + 1][DEPTH2] > depth);
4614
+ }
4615
+ }
4616
+ return visibleRows;
4617
+ }
4618
+ var cloneRow = (row, index, isExpanded) => {
4619
+ const dolly = row.slice();
4620
+ dolly[0] = index.value;
4621
+ dolly[1] = index.value;
4622
+ if (isExpanded) {
4623
+ dolly[IS_EXPANDED2] = true;
4624
+ }
4625
+ index.value += 1;
4626
+ return dolly;
4627
+ };
2
4628
  //# sourceMappingURL=index.js.map