@dbml/parse 3.13.9-alpha.0 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var jn=typeof global=="object"&&global&&global.Object===Object&&global,Wr=typeof self=="object"&&self&&self.Object===Object&&self,be=jn||Wr||Function("return this")(),pe=be.Symbol,Xn=Object.prototype,Hr=Xn.hasOwnProperty,zr=Xn.toString,He=pe?pe.toStringTag:void 0;function qr(e){var t=Hr.call(e,He),n=e[He];try{e[He]=void 0;var r=!0}catch{}var s=zr.call(e);return r&&(t?e[He]=n:delete e[He]),s}var Yr=Object.prototype,Qr=Yr.toString;function Kr(e){return Qr.call(e)}var Jr="[object Null]",Zr="[object Undefined]",nn=pe?pe.toStringTag:void 0;function $e(e){return e==null?e===void 0?Zr:Jr:nn&&nn in Object(e)?qr(e):Kr(e)}function Se(e){return e!=null&&typeof e=="object"}var es="[object Symbol]";function pt(e){return typeof e=="symbol"||Se(e)&&$e(e)==es}function Wn(e,t){for(var n=-1,r=e==null?0:e.length,s=Array(r);++n<r;)s[n]=t(e[n],n,e);return s}var ce=Array.isArray,rn=pe?pe.prototype:void 0,sn=rn?rn.toString:void 0;function Hn(e){if(typeof e=="string")return e;if(ce(e))return Wn(e,Hn)+"";if(pt(e))return sn?sn.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var ts=/\s/;function ns(e){for(var t=e.length;t--&&ts.test(e.charAt(t)););return t}var rs=/^\s+/;function ss(e){return e&&e.slice(0,ns(e)+1).replace(rs,"")}function Ve(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var an=NaN,is=/^[-+]0x[0-9a-f]+$/i,as=/^0b[01]+$/i,os=/^0o[0-7]+$/i,ls=parseInt;function cs(e){if(typeof e=="number")return e;if(pt(e))return an;if(Ve(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Ve(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=ss(e);var n=as.test(e);return n||os.test(e)?ls(e.slice(2),n?2:8):is.test(e)?an:+e}var us=1/0,hs=17976931348623157e292;function fs(e){if(!e)return e===0?e:0;if(e=cs(e),e===us||e===-1/0){var t=e<0?-1:1;return t*hs}return e===e?e:0}function ps(e){var t=fs(e),n=t%1;return t===t?n?t-n:t:0}function dt(e){return e}var ds="[object AsyncFunction]",Es="[object Function]",Ns="[object GeneratorFunction]",Ts="[object Proxy]";function zn(e){if(!Ve(e))return!1;var t=$e(e);return t==Es||t==Ns||t==ds||t==Ts}var vt=be["__core-js_shared__"],on=function(){var e=/[^.]+$/.exec(vt&&vt.keys&&vt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function bs(e){return!!on&&on in e}var ms=Function.prototype,Is=ms.toString;function Ue(e){if(e!=null){try{return Is.call(e)}catch{}try{return e+""}catch{}}return""}var gs=/[\\^$.*+?()[\]{}|]/g,_s=/^\[object .+?Constructor\]$/,As=Function.prototype,Ls=Object.prototype,vs=As.toString,ys=Ls.hasOwnProperty,ws=RegExp("^"+vs.call(ys).replace(gs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ps(e){if(!Ve(e)||bs(e))return!1;var t=zn(e)?ws:_s;return t.test(Ue(e))}function Ss(e,t){return e==null?void 0:e[t]}function Me(e,t){var n=Ss(e,t);return Ps(n)?n:void 0}var Pt=Me(be,"WeakMap");function Os(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}var xs=800,Ds=16,Rs=Date.now;function ks(e){var t=0,n=0;return function(){var r=Rs(),s=Ds-(r-n);if(n=r,s>0){if(++t>=xs)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function Us(e){return function(){return e}}var ln=function(){try{var e=Me(Object,"defineProperty");return e({},"",{}),e}catch{}}(),Ms=ln?function(e,t){return ln(e,"toString",{configurable:!0,enumerable:!1,value:Us(t),writable:!0})}:dt,Fs=ks(Ms);function Bs(e,t,n,r){e.length;for(var s=n+1;s--;)if(t(e[s],s,e))return s;return-1}var Gs=9007199254740991,Vs=/^(?:0|[1-9]\d*)$/;function qn(e,t){var n=typeof e;return t=t??Gs,!!t&&(n=="number"||n!="symbol"&&Vs.test(e))&&e>-1&&e%1==0&&e<t}function Yn(e,t){return e===t||e!==e&&t!==t}var cn=Math.max;function Cs(e,t,n){return t=cn(t===void 0?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=cn(r.length-t,0),a=Array(i);++s<i;)a[s]=r[t+s];s=-1;for(var o=Array(t+1);++s<t;)o[s]=r[s];return o[t]=n(a),Os(e,this,o)}}function $s(e,t){return Fs(Cs(e,t,dt),e+"")}var js=9007199254740991;function Ft(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=js}function Et(e){return e!=null&&Ft(e.length)&&!zn(e)}var Xs=Object.prototype;function Qn(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||Xs;return e===n}function Kn(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var Ws="[object Arguments]";function un(e){return Se(e)&&$e(e)==Ws}var Jn=Object.prototype,Hs=Jn.hasOwnProperty,zs=Jn.propertyIsEnumerable,Bt=un(function(){return arguments}())?un:function(e){return Se(e)&&Hs.call(e,"callee")&&!zs.call(e,"callee")};function qs(){return!1}var Zn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=Zn&&typeof module=="object"&&module&&!module.nodeType&&module,Ys=hn&&hn.exports===Zn,fn=Ys?be.Buffer:void 0,Qs=fn?fn.isBuffer:void 0,St=Qs||qs,Ks="[object Arguments]",Js="[object Array]",Zs="[object Boolean]",ei="[object Date]",ti="[object Error]",ni="[object Function]",ri="[object Map]",si="[object Number]",ii="[object Object]",ai="[object RegExp]",oi="[object Set]",li="[object String]",ci="[object WeakMap]",ui="[object ArrayBuffer]",hi="[object DataView]",fi="[object Float32Array]",pi="[object Float64Array]",di="[object Int8Array]",Ei="[object Int16Array]",Ni="[object Int32Array]",Ti="[object Uint8Array]",bi="[object Uint8ClampedArray]",mi="[object Uint16Array]",Ii="[object Uint32Array]",O={};O[fi]=O[pi]=O[di]=O[Ei]=O[Ni]=O[Ti]=O[bi]=O[mi]=O[Ii]=!0;O[Ks]=O[Js]=O[ui]=O[Zs]=O[hi]=O[ei]=O[ti]=O[ni]=O[ri]=O[si]=O[ii]=O[ai]=O[oi]=O[li]=O[ci]=!1;function gi(e){return Se(e)&&Ft(e.length)&&!!O[$e(e)]}function _i(e){return function(t){return e(t)}}var er=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ze=er&&typeof module=="object"&&module&&!module.nodeType&&module,Ai=ze&&ze.exports===er,yt=Ai&&jn.process,pn=function(){try{var e=ze&&ze.require&&ze.require("util").types;return e||yt&&yt.binding&&yt.binding("util")}catch{}}(),dn=pn&&pn.isTypedArray,tr=dn?_i(dn):gi,Li=Object.prototype,vi=Li.hasOwnProperty;function nr(e,t){var n=ce(e),r=!n&&Bt(e),s=!n&&!r&&St(e),i=!n&&!r&&!s&&tr(e),a=n||r||s||i,o=a?Kn(e.length,String):[],u=o.length;for(var p in e)(t||vi.call(e,p))&&!(a&&(p=="length"||s&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||qn(p,u)))&&o.push(p);return o}function yi(e,t){return function(n){return e(t(n))}}var wi=yi(Object.keys,Object),Pi=Object.prototype,Si=Pi.hasOwnProperty;function Oi(e){if(!Qn(e))return wi(e);var t=[];for(var n in Object(e))Si.call(e,n)&&n!="constructor"&&t.push(n);return t}function Gt(e){return Et(e)?nr(e):Oi(e)}function xi(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var Di=Object.prototype,Ri=Di.hasOwnProperty;function ki(e){if(!Ve(e))return xi(e);var t=Qn(e),n=[];for(var r in e)r=="constructor"&&(t||!Ri.call(e,r))||n.push(r);return n}function Ui(e){return Et(e)?nr(e,!0):ki(e)}var Mi=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fi=/^\w*$/;function Vt(e,t){if(ce(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||pt(e)?!0:Fi.test(e)||!Mi.test(e)||t!=null&&e in Object(t)}var Ye=Me(Object,"create");function Bi(){this.__data__=Ye?Ye(null):{},this.size=0}function Gi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Vi="__lodash_hash_undefined__",Ci=Object.prototype,$i=Ci.hasOwnProperty;function ji(e){var t=this.__data__;if(Ye){var n=t[e];return n===Vi?void 0:n}return $i.call(t,e)?t[e]:void 0}var Xi=Object.prototype,Wi=Xi.hasOwnProperty;function Hi(e){var t=this.__data__;return Ye?t[e]!==void 0:Wi.call(t,e)}var zi="__lodash_hash_undefined__";function qi(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ye&&t===void 0?zi:t,this}function Oe(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Oe.prototype.clear=Bi;Oe.prototype.delete=Gi;Oe.prototype.get=ji;Oe.prototype.has=Hi;Oe.prototype.set=qi;function Yi(){this.__data__=[],this.size=0}function Nt(e,t){for(var n=e.length;n--;)if(Yn(e[n][0],t))return n;return-1}var Qi=Array.prototype,Ki=Qi.splice;function Ji(e){var t=this.__data__,n=Nt(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Ki.call(t,n,1),--this.size,!0}function Zi(e){var t=this.__data__,n=Nt(t,e);return n<0?void 0:t[n][1]}function ea(e){return Nt(this.__data__,e)>-1}function ta(e,t){var n=this.__data__,r=Nt(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function me(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}me.prototype.clear=Yi;me.prototype.delete=Ji;me.prototype.get=Zi;me.prototype.has=ea;me.prototype.set=ta;var Qe=Me(be,"Map");function na(){this.size=0,this.__data__={hash:new Oe,map:new(Qe||me),string:new Oe}}function ra(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Tt(e,t){var n=e.__data__;return ra(t)?n[typeof t=="string"?"string":"hash"]:n.map}function sa(e){var t=Tt(this,e).delete(e);return this.size-=t?1:0,t}function ia(e){return Tt(this,e).get(e)}function aa(e){return Tt(this,e).has(e)}function oa(e,t){var n=Tt(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function Ie(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Ie.prototype.clear=na;Ie.prototype.delete=sa;Ie.prototype.get=ia;Ie.prototype.has=aa;Ie.prototype.set=oa;var la="Expected a function";function Ct(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(la);var n=function(){var r=arguments,s=t?t.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var a=e.apply(this,r);return n.cache=i.set(s,a)||i,a};return n.cache=new(Ct.Cache||Ie),n}Ct.Cache=Ie;var ca=500;function ua(e){var t=Ct(e,function(r){return n.size===ca&&n.clear(),r}),n=t.cache;return t}var ha=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fa=/\\(\\)?/g,pa=ua(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(ha,function(n,r,s,i){t.push(s?i.replace(fa,"$1"):r||n)}),t});function da(e){return e==null?"":Hn(e)}function rr(e,t){return ce(e)?e:Vt(e,t)?[e]:pa(da(e))}function bt(e){if(typeof e=="string"||pt(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}function sr(e,t){t=rr(t,e);for(var n=0,r=t.length;e!=null&&n<r;)e=e[bt(t[n++])];return n&&n==r?e:void 0}function ir(e,t,n){var r=e==null?void 0:sr(e,t);return r===void 0?n:r}function ar(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}var En=pe?pe.isConcatSpreadable:void 0;function Ea(e){return ce(e)||Bt(e)||!!(En&&e&&e[En])}function Na(e,t,n,r,s){var i=-1,a=e.length;for(n||(n=Ea),s||(s=[]);++i<a;){var o=e[i];n(o)?ar(s,o):s[s.length]=o}return s}function Nn(e){var t=e==null?0:e.length;return t?Na(e):[]}function Ta(){this.__data__=new me,this.size=0}function ba(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function ma(e){return this.__data__.get(e)}function Ia(e){return this.__data__.has(e)}var ga=200;function _a(e,t){var n=this.__data__;if(n instanceof me){var r=n.__data__;if(!Qe||r.length<ga-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Ie(r)}return n.set(e,t),this.size=n.size,this}function Ne(e){var t=this.__data__=new me(e);this.size=t.size}Ne.prototype.clear=Ta;Ne.prototype.delete=ba;Ne.prototype.get=ma;Ne.prototype.has=Ia;Ne.prototype.set=_a;function or(e,t){for(var n=-1,r=e==null?0:e.length,s=0,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[s++]=a)}return i}function Aa(){return[]}var La=Object.prototype,va=La.propertyIsEnumerable,Tn=Object.getOwnPropertySymbols,ya=Tn?function(e){return e==null?[]:(e=Object(e),or(Tn(e),function(t){return va.call(e,t)}))}:Aa;function wa(e,t,n){var r=t(e);return ce(e)?r:ar(r,n(e))}function bn(e){return wa(e,Gt,ya)}var Ot=Me(be,"DataView"),xt=Me(be,"Promise"),Dt=Me(be,"Set"),mn="[object Map]",Pa="[object Object]",In="[object Promise]",gn="[object Set]",_n="[object WeakMap]",An="[object DataView]",Sa=Ue(Ot),Oa=Ue(Qe),xa=Ue(xt),Da=Ue(Dt),Ra=Ue(Pt),ve=$e;(Ot&&ve(new Ot(new ArrayBuffer(1)))!=An||Qe&&ve(new Qe)!=mn||xt&&ve(xt.resolve())!=In||Dt&&ve(new Dt)!=gn||Pt&&ve(new Pt)!=_n)&&(ve=function(e){var t=$e(e),n=t==Pa?e.constructor:void 0,r=n?Ue(n):"";if(r)switch(r){case Sa:return An;case Oa:return mn;case xa:return In;case Da:return gn;case Ra:return _n}return t});var Ln=be.Uint8Array,ka="__lodash_hash_undefined__";function Ua(e){return this.__data__.set(e,ka),this}function Ma(e){return this.__data__.has(e)}function at(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new Ie;++t<n;)this.add(e[t])}at.prototype.add=at.prototype.push=Ua;at.prototype.has=Ma;function Fa(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function Ba(e,t){return e.has(t)}var Ga=1,Va=2;function lr(e,t,n,r,s,i){var a=n&Ga,o=e.length,u=t.length;if(o!=u&&!(a&&u>o))return!1;var p=i.get(e),h=i.get(t);if(p&&h)return p==t&&h==e;var d=-1,E=!0,b=n&Va?new at:void 0;for(i.set(e,t),i.set(t,e);++d<o;){var A=e[d],I=t[d];if(r)var v=a?r(I,A,d,t,e,i):r(A,I,d,e,t,i);if(v!==void 0){if(v)continue;E=!1;break}if(b){if(!Fa(t,function(W,y){if(!Ba(b,y)&&(A===W||s(A,W,n,r,i)))return b.push(y)})){E=!1;break}}else if(!(A===I||s(A,I,n,r,i))){E=!1;break}}return i.delete(e),i.delete(t),E}function Ca(e){var t=-1,n=Array(e.size);return e.forEach(function(r,s){n[++t]=[s,r]}),n}function $a(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var ja=1,Xa=2,Wa="[object Boolean]",Ha="[object Date]",za="[object Error]",qa="[object Map]",Ya="[object Number]",Qa="[object RegExp]",Ka="[object Set]",Ja="[object String]",Za="[object Symbol]",eo="[object ArrayBuffer]",to="[object DataView]",vn=pe?pe.prototype:void 0,wt=vn?vn.valueOf:void 0;function no(e,t,n,r,s,i,a){switch(n){case to:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case eo:return!(e.byteLength!=t.byteLength||!i(new Ln(e),new Ln(t)));case Wa:case Ha:case Ya:return Yn(+e,+t);case za:return e.name==t.name&&e.message==t.message;case Qa:case Ja:return e==t+"";case qa:var o=Ca;case Ka:var u=r&ja;if(o||(o=$a),e.size!=t.size&&!u)return!1;var p=a.get(e);if(p)return p==t;r|=Xa,a.set(e,t);var h=lr(o(e),o(t),r,s,i,a);return a.delete(e),h;case Za:if(wt)return wt.call(e)==wt.call(t)}return!1}var ro=1,so=Object.prototype,io=so.hasOwnProperty;function ao(e,t,n,r,s,i){var a=n&ro,o=bn(e),u=o.length,p=bn(t),h=p.length;if(u!=h&&!a)return!1;for(var d=u;d--;){var E=o[d];if(!(a?E in t:io.call(t,E)))return!1}var b=i.get(e),A=i.get(t);if(b&&A)return b==t&&A==e;var I=!0;i.set(e,t),i.set(t,e);for(var v=a;++d<u;){E=o[d];var W=e[E],y=t[E];if(r)var we=a?r(y,W,E,t,e,i):r(W,y,E,e,t,i);if(!(we===void 0?W===y||s(W,y,n,r,i):we)){I=!1;break}v||(v=E=="constructor")}if(I&&!v){var Q=e.constructor,R=t.constructor;Q!=R&&"constructor"in e&&"constructor"in t&&!(typeof Q=="function"&&Q instanceof Q&&typeof R=="function"&&R instanceof R)&&(I=!1)}return i.delete(e),i.delete(t),I}var oo=1,yn="[object Arguments]",wn="[object Array]",nt="[object Object]",lo=Object.prototype,Pn=lo.hasOwnProperty;function co(e,t,n,r,s,i){var a=ce(e),o=ce(t),u=a?wn:ve(e),p=o?wn:ve(t);u=u==yn?nt:u,p=p==yn?nt:p;var h=u==nt,d=p==nt,E=u==p;if(E&&St(e)){if(!St(t))return!1;a=!0,h=!1}if(E&&!h)return i||(i=new Ne),a||tr(e)?lr(e,t,n,r,s,i):no(e,t,u,n,r,s,i);if(!(n&oo)){var b=h&&Pn.call(e,"__wrapped__"),A=d&&Pn.call(t,"__wrapped__");if(b||A){var I=b?e.value():e,v=A?t.value():t;return i||(i=new Ne),s(I,v,n,r,i)}}return E?(i||(i=new Ne),ao(e,t,n,r,s,i)):!1}function $t(e,t,n,r,s){return e===t?!0:e==null||t==null||!Se(e)&&!Se(t)?e!==e&&t!==t:co(e,t,n,r,$t,s)}var uo=1,ho=2;function fo(e,t,n,r){var s=n.length,i=s;if(e==null)return!i;for(e=Object(e);s--;){var a=n[s];if(a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++s<i;){a=n[s];var o=a[0],u=e[o],p=a[1];if(a[2]){if(u===void 0&&!(o in e))return!1}else{var h=new Ne,d;if(!(d===void 0?$t(p,u,uo|ho,r,h):d))return!1}}return!0}function cr(e){return e===e&&!Ve(e)}function po(e){for(var t=Gt(e),n=t.length;n--;){var r=t[n],s=e[r];t[n]=[r,s,cr(s)]}return t}function ur(e,t){return function(n){return n==null?!1:n[e]===t&&(t!==void 0||e in Object(n))}}function Eo(e){var t=po(e);return t.length==1&&t[0][2]?ur(t[0][0],t[0][1]):function(n){return n===e||fo(n,e,t)}}function No(e,t){return e!=null&&t in Object(e)}function To(e,t,n){t=rr(t,e);for(var r=-1,s=t.length,i=!1;++r<s;){var a=bt(t[r]);if(!(i=e!=null&&n(e,a)))break;e=e[a]}return i||++r!=s?i:(s=e==null?0:e.length,!!s&&Ft(s)&&qn(a,s)&&(ce(e)||Bt(e)))}function bo(e,t){return e!=null&&To(e,t,No)}var mo=1,Io=2;function go(e,t){return Vt(e)&&cr(t)?ur(bt(e),t):function(n){var r=ir(n,e);return r===void 0&&r===t?bo(n,e):$t(t,r,mo|Io)}}function hr(e){return function(t){return t==null?void 0:t[e]}}function _o(e){return function(t){return sr(t,e)}}function Ao(e){return Vt(e)?hr(bt(e)):_o(e)}function fr(e){return typeof e=="function"?e:e==null?dt:typeof e=="object"?ce(e)?go(e[0],e[1]):Eo(e):Ao(e)}function Lo(e,t,n,r){for(var s=-1,i=e==null?0:e.length;++s<i;){var a=e[s];t(r,a,n(a),e)}return r}function vo(e){return function(t,n,r){for(var s=-1,i=Object(t),a=r(t),o=a.length;o--;){var u=a[++s];if(n(i[u],u,i)===!1)break}return t}}var pr=vo();function yo(e,t){return e&&pr(e,t,Gt)}function wo(e,t){return function(n,r){if(n==null)return n;if(!Et(n))return e(n,r);for(var s=n.length,i=-1,a=Object(n);++i<s&&r(a[i],i,a)!==!1;);return n}}var Po=wo(yo);function So(e,t,n,r){return Po(e,function(s,i,a){t(r,s,n(s),a)}),r}function Oo(e,t){return function(n,r){var s=ce(n)?Lo:So,i=t?t():{};return s(n,e,fr(r),i)}}function xo(e){return Se(e)&&Et(e)}function F(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}function Do(e){return typeof e=="function"?e:dt}var Ro=Math.max,ko=Math.min;function Uo(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var s=r-1;return n!==void 0&&(s=ps(n),s=n<0?Ro(r+s,0):ko(s,r-1)),Bs(e,fr(t),s)}function Mo(e){return e&&e.length?e[0]:void 0}function Ke(e,t){return e==null?e:pr(e,Do(t),Ui)}var he=Oo(function(e,t,n){e[n?0:1].push(t)},function(){return[[],[]]}),Fo=Math.max;function Bo(e){if(!(e&&e.length))return[];var t=0;return e=or(e,function(n){if(xo(n))return t=Fo(n.length,t),!0}),Kn(t,function(n){return Wn(e,hr(n))})}var Rt=$s(Bo),f=(e=>(e.SPACE="<space>",e.TAB="<tab>",e.NEWLINE="<newline>",e.COMMA="<comma>",e.LPAREN="<lparen>",e.RPAREN="<rparen>",e.LBRACE="<lbrace>",e.RBRACE="<rbrace>",e.LBRACKET="<lbracket>",e.RBRACKET="<rbracket>",e.LANGLE="<langle>",e.RANGLE="<rangle>",e.OP="<op>",e.EOF="<eof>",e.NUMERIC_LITERAL="<number>",e.STRING_LITERAL="<string>",e.COLOR_LITERAL="<color>",e.FUNCTION_EXPRESSION="<function-expression>",e.QUOTED_STRING="<variable>",e.IDENTIFIER="<identifier>",e.SEMICOLON="<semicolon>",e.COLON="<colon>",e.TILDE="<tilde>",e.SINGLE_LINE_COMMENT="<single-line-comment>",e.MULTILINE_COMMENT="<multiline-comment>",e))(f||{});function Go(e){switch(e.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function Vo(e){if(!e)return!1;switch(e){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function Sn(e){return e!==void 0&&e.kind==="<op>"}class Z{constructor(t,n,r,s,i){this.kind=t,this.startPos=n,this.endPos=r,this.value=s,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=i,this.start=n.offset,this.end=r.offset}static create(t,n,r,s,i){return new Z(t,n,r,s,i)}}function dr(e){return e.trailingTrivia.find(({kind:t})=>t===f.NEWLINE)!==void 0}function On(e,t){return t.leadingTrivia.find(({kind:r})=>r===f.NEWLINE)!==void 0||dr(e)}function kt(e){return e.trailingTrivia.find(({kind:t})=>[f.SPACE,f.TAB].includes(t))!==void 0}function Er(e){return e.trailingTrivia.length===0?e.end:Er(F(e.trailingTrivia))}function Nr(e){return e.leadingTrivia.length===0?e.start:Nr(e.leadingTrivia[0])}function Co(e){return[f.SINGLE_LINE_COMMENT,f.MULTILINE_COMMENT].includes(e.kind)}class $o{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class D{constructor(t,n,r){this.id=t,this.kind=n;const s=r.find(a=>a!==void 0&&!Number.isNaN(a.start));s?(this.startPos=s.startPos,this.fullStart=s instanceof Z?Nr(s):s.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const i=[...r].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));i?(this.endPos=i.endPos,this.fullEnd=i instanceof Z?Er(i):i.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var Pe=(e=>(e.PROGRAM="<program>",e.ELEMENT_DECLARATION="<element-declaration>",e.ATTRIBUTE="<attribute>",e.IDENTIFIER_STREAM="<identifer-stream>",e.LITERAL="<literal>",e.VARIABLE="<variable>",e.PREFIX_EXPRESSION="<prefix-expression>",e.INFIX_EXPRESSION="<infix-expression>",e.POSTFIX_EXPRESSION="<postfix-expression>",e.FUNCTION_EXPRESSION="<function-expression>",e.FUNCTION_APPLICATION="<function-application>",e.BLOCK_EXPRESSION="<block-expression>",e.LIST_EXPRESSION="<list-expression>",e.TUPLE_EXPRESSION="<tuple-expression>",e.CALL_EXPRESSION="<call-expression>",e.PRIMARY_EXPRESSION="<primary-expression>",e.GROUP_EXPRESSION="<group-expression>",e.DUMMY="<dummy>",e.ARRAY="<array>",e.PARTIAL_INJECTION="<partial-injection>",e))(Pe||{});class te extends D{constructor({body:t=[],eof:n},r){super(r,"<program>",[...t,n]),this.body=t,this.eof=n}}class P extends D{constructor({type:t,name:n,as:r,alias:s,attributeList:i,bodyColon:a,body:o},u){if(super(u,"<element-declaration>",[t,n,r,s,i,a,o]),o&&a&&!(o instanceof w||o instanceof P))throw new Error("If an element has a simple body, it must be a function application node");this.type=t,this.name=n,this.as=r,this.alias=s,this.attributeList=i,this.bodyColon=a,this.body=o}}class ie extends D{constructor({identifiers:t=[]},n){super(n,"<identifer-stream>",t||[]),this.identifiers=t}}class ae extends D{constructor({name:t,colon:n,value:r},s){super(s,"<attribute>",[t,n,r]),this.name=t,this.value=r,this.colon=n}}class ne extends D{constructor({op:t,expression:n},r){super(r,"<prefix-expression>",[t,n]),this.op=t,this.expression=n}}class de extends D{constructor({op:t,leftExpression:n,rightExpression:r},s){super(s,"<infix-expression>",[n,t,r]),this.op=t,this.leftExpression=n,this.rightExpression=r}}class mt extends D{constructor({op:t,expression:n},r){super(r,"<postfix-expression>",[n,t]),this.op=t,this.expression=n}}class Te extends D{constructor({value:t},n){super(n,"<function-expression>",[t]),this.value=t}}class w extends D{constructor({callee:t,args:n=[]},r){super(r,"<function-application>",[t,...n]),this.callee=t,this.args=n}}class fe extends D{constructor({blockOpenBrace:t,body:n=[],blockCloseBrace:r},s){super(s,"<block-expression>",[t,...n,r]),this.blockOpenBrace=t,this.body=n,this.blockCloseBrace=r}}class xe extends D{constructor({op:t,partial:n},r){super(r,"<partial-injection>",[t,n]),this.partial=n}}class B extends D{constructor({listOpenBracket:t,elementList:n=[],commaList:r=[],listCloseBracket:s},i){super(i,"<list-expression>",[t,...Tr(n,r),s]),this.listOpenBracket=t,this.elementList=n,this.commaList=r,this.listCloseBracket=s}}class Ee extends D{constructor({tupleOpenParen:t,elementList:n=[],commaList:r=[],tupleCloseParen:s},i){super(i,"<tuple-expression>",[t,...Tr(n,r),s]),this.tupleOpenParen=t,this.elementList=n,this.commaList=r,this.tupleCloseParen=s}}class jt extends Ee{constructor({groupOpenParen:t,expression:n,groupCloseParen:r},s){super({tupleOpenParen:t,elementList:n&&[n],commaList:[],tupleCloseParen:r},s),this.kind="<group-expression>"}}class re extends D{constructor({callee:t,argumentList:n},r){super(r,"<call-expression>",[t,n]),this.callee=t,this.argumentList=n}}class je extends D{constructor({literal:t},n){super(n,"<literal>",[t]),this.literal=t}}class ue extends D{constructor({variable:t},n){super(n,"<variable>",[t]),this.variable=t}}class H extends D{constructor({expression:t},n){super(n,"<primary-expression>",[t]),this.expression=t}}class rt extends D{constructor({pre:t},n){const r=Z.create(f.SPACE,t.endPos,t.endPos," ",!1);super(n,"<dummy>",[r])}}class De extends D{constructor({expression:t,indexer:n},r){super(r,"<array>",[t,n]),this.array=t,this.indexer=n}}function Tr(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e||[];const[n]=e,[r]=t;return(n.start<r.start?Nn(Rt(e,t)):Nn(Rt(t,e))).filter(s=>s!==null)}function jo(e,t=!1){return JSON.stringify(e,function(n,r){var s;return!(this instanceof te)&&n==="symbol"?r==null?void 0:r.id:n==="symbol"?{symbolTable:r==null?void 0:r.symbolTable,id:r==null?void 0:r.id,references:r==null?void 0:r.references.map(i=>i.id),declaration:(s=r==null?void 0:r.declaration)==null?void 0:s.id}:n==="referee"||n==="parent"||n==="declaration"?r==null?void 0:r.id:n==="symbolTable"?Object.fromEntries(r.table):r},t?2:0)}class M{constructor(t){this.value=t}unwrap(){return this.value}unwrap_or(t){return this.value}and_then(t){return t(this.value)}map(t){return new M(t(this.value))}isOk(){return!0}}class x{constructor(){this.value=void 0}unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(t){return t}and_then(t){return new x}map(t){return new x}isOk(){return!1}}var m=(e=>(e.Schema="Schema",e.Table="Table",e.Column="Column",e.TableGroup="TableGroup",e.TableGroupField="TableGroup field",e.Enum="Enum",e.EnumField="Enum field",e.Note="Note",e.TablePartial="TablePartial",e.TablePartialInjection="TablePartialInjection",e))(m||{});function Xt(e){return`Schema:${e}`}function ot(e){return`Table:${e}`}function It(e){return`Column:${e}`}function Wt(e){return`Enum:${e}`}function Ht(e){return`Enum field:${e}`}function zt(e){return`TableGroup:${e}`}function qt(e){return`TableGroup field:${e}`}function Xo(e){return`Note:${e}`}function Yt(e){return`TablePartial:${e}`}function br(e){return`TablePartialInjection:${e}`}function st(e,t){switch(t){case"Column":return It(e);case"Enum":return Wt(e);case"Enum field":return Ht(e);case"Schema":return Xt(e);case"Table":return ot(e);case"TableGroup":return zt(e);case"TableGroup field":return qt(e);case"TablePartial":return Yt(e);default:throw new Error("Unreachable")}}function oe(e){const[t,n]=e.split(":");return Object.values(m).includes(t)?new M({name:n,kind:t}):new x}function Wo(e){const t=oe(e).unwrap_or(void 0);if(!t)return!1;const{kind:n,name:r}=t;return n==="Schema"&&r==="public"}function Ho(e){const t=oe(e).unwrap_or(void 0);if(!t)return!1;const{kind:n}=t;return n==="TablePartialInjection"}function zo(e){const t=oe(e).unwrap_or(void 0);if(!t)return null;const{kind:n,name:r}=t;return n==="TablePartialInjection"?st(r,"TablePartial"):null}class qo{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class mr{constructor({symbolTable:t},n){this.references=[],this.id=n,this.symbolTable=t}}class Yo{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Qo{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Ir{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Qt{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Ko{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Jo{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Zo{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class el{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class tl{constructor({injectorFieldSymbol:t,injectorDeclaration:n},r){this.references=[],this.id=r,this.injectorDeclaration=n,this.injectorFieldSymbol=t}}function nl(e){return[Xt,ot,Wt,zt,It,Ht,qt,Yt,br].map(t=>t(e))}function rl(e){return e instanceof Qt?tl:null}function gt(e){return!!e.match(new RegExp("(\\p{L}|_|\\p{M})","gu"))}function lt(e){const[t]=e;return t>="0"&&t<="9"}function sl(e){const[t]=e;return lt(t)||gt(t)&&t.toLowerCase()>="a"&&t.toLowerCase()<="f"}function Ge(e){return gt(e)||lt(e)}function xn(e,t){const n=[],r=Math.min(e.length,t.length);for(let s=0;s<r;s+=1)n.push(e[s],t[s]);return n.push(...e.slice(r),...t.slice(r)),n}function qe(e,t){return e>=t.start&&e<t.end}function gr(e){var t;return e instanceof ne?`${(t=e.op)==null?void 0:t.value}${gr(e.expression)}`:e.expression.literal.value}function Ut(e){var t;return e instanceof ne?((t=e.op)==null?void 0:t.value)==="-"?-Ut(e.expression):Ut(e.expression):Number.parseFloat(e.expression.literal.value)}var l=(e=>(e[e.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",e[e.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",e[e.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",e[e.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",e[e.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",e[e.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",e[e.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",e[e.MISSING_SPACES=1007]="MISSING_SPACES",e[e.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",e[e.INVALID_OPERAND=1009]="INVALID_OPERAND",e[e.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",e[e.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",e[e.INVALID_NAME=3e3]="INVALID_NAME",e[e.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",e[e.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",e[e.DUPLICATE_NAME=3003]="DUPLICATE_NAME",e[e.INVALID_ALIAS=3004]="INVALID_ALIAS",e[e.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",e[e.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",e[e.INVALID_SETTINGS=3007]="INVALID_SETTINGS",e[e.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",e[e.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",e[e.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",e[e.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",e[e.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",e[e.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",e[e.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",e[e.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",e[e.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",e[e.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",e[e.EMPTY_TABLE=3018]="EMPTY_TABLE",e[e.INVALID_COLUMN=3019]="INVALID_COLUMN",e[e.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",e[e.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",e[e.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",e[e.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",e[e.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",e[e.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",e[e.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",e[e.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",e[e.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",e[e.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",e[e.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",e[e.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",e[e.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",e[e.EMPTY_ENUM=3033]="EMPTY_ENUM",e[e.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",e[e.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",e[e.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",e[e.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",e[e.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",e[e.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",e[e.EMPTY_REF=3040]="EMPTY_REF",e[e.REF_REDEFINED=3041]="REF_REDEFINED",e[e.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",e[e.INVALID_NOTE=3043]="INVALID_NOTE",e[e.NOTE_REDEFINED=3044]="NOTE_REDEFINED",e[e.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",e[e.EMPTY_NOTE=3046]="EMPTY_NOTE",e[e.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",e[e.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",e[e.INVALID_INDEX=3049]="INVALID_INDEX",e[e.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",e[e.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",e[e.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",e[e.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",e[e.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",e[e.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",e[e.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",e[e.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",e[e.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",e[e.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",e[e.INVALID_TABLE_PARTIAL_CONTEXT=3060]="INVALID_TABLE_PARTIAL_CONTEXT",e[e.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3061]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",e[e.INVALID_TABLE_PARTIAL_SETTING=3062]="INVALID_TABLE_PARTIAL_SETTING",e[e.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3063]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",e[e.DUPLICATE_TABLE_PARTIAL_SETTING=3064]="DUPLICATE_TABLE_PARTIAL_SETTING",e[e.INVALID_TABLE_PARTIAL_INJECTION=3065]="INVALID_TABLE_PARTIAL_INJECTION",e[e.INVALID_TABLE_PARTIAL_INJECTION_OP=3066]="INVALID_TABLE_PARTIAL_INJECTION_OP",e[e.INVALID_TABLE_PARTIAL_INJECTION_NAME=3067]="INVALID_TABLE_PARTIAL_INJECTION_NAME",e[e.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3068]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",e[e.BINDING_ERROR=4e3]="BINDING_ERROR",e[e.UNSUPPORTED=5e3]="UNSUPPORTED",e[e.CIRCULAR_REF=5001]="CIRCULAR_REF",e[e.SAME_ENDPOINT=5002]="SAME_ENDPOINT",e[e.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",e[e.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",e[e.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",e))(l||{});class c extends Error{constructor(t,n,r){super(n),this.code=t,this.diagnostic=n,this.nodeOrToken=r,this.start=r.start,this.end=r.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class ee{constructor(t,n){this.value=t,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(t){const n=t(this.value),r=[...this.errors,...n.errors];return new ee(n.value,r)}map(t){return new ee(t(this.value),this.errors)}}function il(e,t,n){if(!e||!ye(e)||t.length===0)return new x;const r=[...t],s=Dn(e).unwrap(),i=r.pop();if(!(i instanceof fe))return new x;const a=F(r)instanceof B?r.pop():void 0;if(r.length===3){const o=Dn(r[1]).value;return!o||!Mt(o)?new x:new M(n.create(P,{type:s,name:r[0],as:o,alias:r[2],attributeList:a,body:i}))}return r.length===1?new M(n.create(P,{type:s,name:r[0],attributeList:a,body:i})):r.length===0?new M(n.create(P,{type:s,attributeList:a,body:i})):new x}function Mt(e){return e.kind===f.IDENTIFIER&&e.value==="as"}function g(e){e&&(e instanceof Z?al(e):ol(e))}function al(e){e.kind!==f.EOF&&(e.isInvalid=!0)}function ol(e){if(e instanceof P)g(e.type),g(e.name),g(e.as),g(e.alias),g(e.bodyColon),g(e.attributeList),g(e.body);else if(e instanceof ie)e.identifiers.forEach(g);else if(e instanceof ae)g(e.name),g(e.colon),g(e.value);else if(e instanceof ne)g(e.op),g(e.expression);else if(e instanceof de)g(e.leftExpression),g(e.op),g(e.rightExpression);else if(e instanceof mt)g(e.op),g(e.expression);else if(e instanceof fe)g(e.blockOpenBrace),e.body.forEach(g),g(e.blockCloseBrace);else if(e instanceof B)g(e.listOpenBracket),e.commaList.forEach(g),e.elementList.forEach(g),g(e.listCloseBracket);else if(e instanceof Ee)g(e.tupleOpenParen),e.commaList.forEach(g),e.elementList.forEach(g),g(e.tupleCloseParen);else if(e instanceof re)g(e.callee),g(e.argumentList);else if(e instanceof w)g(e.callee),e.args.forEach(g);else if(e instanceof H)g(e.expression);else if(e instanceof Te)g(e.value);else if(e instanceof ue)g(e.variable);else if(e instanceof je)g(e.literal);else throw e instanceof jt?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function _r(e){return!!(e!=null&&e.isInvalid)}function $(...e){return e.filter(t=>t!==void 0)}function ll(e){if(e instanceof te)return $(...e.body,e.eof);if(e instanceof P)return $(e.type,e.name,e.as,e.alias,e.attributeList,e.bodyColon,e.body);if(e instanceof ae)return $(e.name,e.colon,e.value);if(e instanceof ie)return e.identifiers;if(e instanceof je)return e.literal?[e.literal]:[];if(e instanceof ue)return $(e.variable);if(e instanceof ne)return $(e.op,e.expression);if(e instanceof de)return $(e.leftExpression,e.op,e.rightExpression);if(e instanceof mt)return $(e.expression,e.op);if(e instanceof Te)return $(e.value);if(e instanceof w)return $(e.callee,...e.args);if(e instanceof fe)return $(e.blockOpenBrace,...e.body,e.blockCloseBrace);if(e instanceof B)return $(e.listOpenBracket,...xn(e.elementList,e.commaList),e.listCloseBracket);if(e instanceof Ee)return $(e.tupleOpenParen,...xn(e.elementList,e.commaList),e.tupleCloseParen);if(e instanceof re)return $(e.callee,e.argumentList);if(e instanceof H)return $(e.expression);if(e instanceof De)return $(e.array,e.indexer);if(e instanceof xe)return $(e.partial);throw e instanceof jt?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Dn(e){return X(e)?new M(e.expression.variable):new x}function q(e){var t;return e instanceof H&&(e.expression instanceof ue&&e.expression.variable instanceof Z&&e.expression.variable.kind===f.QUOTED_STRING||e.expression instanceof je&&((t=e.expression.literal)==null?void 0:t.kind)===f.STRING_LITERAL)}function X(e){return e instanceof H&&e.expression instanceof ue&&e.expression.variable instanceof Z}function ye(e){var t;return e instanceof H&&e.expression instanceof ue&&((t=e.expression.variable)==null?void 0:t.kind)===f.IDENTIFIER}function Kt(e){var t;return e instanceof de&&e.leftExpression instanceof D&&e.rightExpression instanceof D&&((t=e.op)==null?void 0:t.value)==="."}function Ce(e){if(e===void 0)return new x;const t=e.identifiers.map(n=>n.value).join(" ");return t===""?new x:new M(t)}class cl{constructor(t){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=t}isAtEnd(){return this.current.offset>=this.text.length}advance(){const t=this.peek();return this.current={...this.current},t===`
2
- `?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,t}peek(t=0){if(!(this.current.offset+t>=this.text.length))return this.text[this.current.offset+t]}check(t){for(let n=0;n<t.length;n+=1)if(t[n]!==this.peek(n))return!1;return!0}match(t){return this.check(t)?(t.split("").forEach(()=>this.advance()),!0):!1}addToken(t,n=!1){this.tokens.push(this.createToken(t,n))}createToken(t,n=!1){return Z.create(t,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(Z.create(f.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new ee(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const t=this.advance();switch(t){case" ":this.addToken(f.SPACE);break;case"\r":break;case`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var jn=typeof global=="object"&&global&&global.Object===Object&&global,Wr=typeof self=="object"&&self&&self.Object===Object&&self,be=jn||Wr||Function("return this")(),pe=be.Symbol,Xn=Object.prototype,Hr=Xn.hasOwnProperty,zr=Xn.toString,He=pe?pe.toStringTag:void 0;function qr(e){var t=Hr.call(e,He),n=e[He];try{e[He]=void 0;var r=!0}catch{}var s=zr.call(e);return r&&(t?e[He]=n:delete e[He]),s}var Yr=Object.prototype,Kr=Yr.toString;function Qr(e){return Kr.call(e)}var Jr="[object Null]",Zr="[object Undefined]",nn=pe?pe.toStringTag:void 0;function $e(e){return e==null?e===void 0?Zr:Jr:nn&&nn in Object(e)?qr(e):Qr(e)}function Se(e){return e!=null&&typeof e=="object"}var es="[object Symbol]";function pt(e){return typeof e=="symbol"||Se(e)&&$e(e)==es}function Wn(e,t){for(var n=-1,r=e==null?0:e.length,s=Array(r);++n<r;)s[n]=t(e[n],n,e);return s}var ce=Array.isArray,rn=pe?pe.prototype:void 0,sn=rn?rn.toString:void 0;function Hn(e){if(typeof e=="string")return e;if(ce(e))return Wn(e,Hn)+"";if(pt(e))return sn?sn.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var ts=/\s/;function ns(e){for(var t=e.length;t--&&ts.test(e.charAt(t)););return t}var rs=/^\s+/;function ss(e){return e&&e.slice(0,ns(e)+1).replace(rs,"")}function Ve(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var an=NaN,is=/^[-+]0x[0-9a-f]+$/i,as=/^0b[01]+$/i,os=/^0o[0-7]+$/i,ls=parseInt;function cs(e){if(typeof e=="number")return e;if(pt(e))return an;if(Ve(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Ve(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=ss(e);var n=as.test(e);return n||os.test(e)?ls(e.slice(2),n?2:8):is.test(e)?an:+e}var us=1/0,hs=17976931348623157e292;function fs(e){if(!e)return e===0?e:0;if(e=cs(e),e===us||e===-1/0){var t=e<0?-1:1;return t*hs}return e===e?e:0}function ps(e){var t=fs(e),n=t%1;return t===t?n?t-n:t:0}function dt(e){return e}var ds="[object AsyncFunction]",Es="[object Function]",Ns="[object GeneratorFunction]",Ts="[object Proxy]";function zn(e){if(!Ve(e))return!1;var t=$e(e);return t==Es||t==Ns||t==ds||t==Ts}var vt=be["__core-js_shared__"],on=function(){var e=/[^.]+$/.exec(vt&&vt.keys&&vt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function bs(e){return!!on&&on in e}var ms=Function.prototype,Is=ms.toString;function Ue(e){if(e!=null){try{return Is.call(e)}catch{}try{return e+""}catch{}}return""}var gs=/[\\^$.*+?()[\]{}|]/g,_s=/^\[object .+?Constructor\]$/,As=Function.prototype,Ls=Object.prototype,vs=As.toString,ys=Ls.hasOwnProperty,ws=RegExp("^"+vs.call(ys).replace(gs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ps(e){if(!Ve(e)||bs(e))return!1;var t=zn(e)?ws:_s;return t.test(Ue(e))}function Ss(e,t){return e==null?void 0:e[t]}function Me(e,t){var n=Ss(e,t);return Ps(n)?n:void 0}var Pt=Me(be,"WeakMap");function Os(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}var xs=800,Ds=16,Rs=Date.now;function ks(e){var t=0,n=0;return function(){var r=Rs(),s=Ds-(r-n);if(n=r,s>0){if(++t>=xs)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function Us(e){return function(){return e}}var ln=function(){try{var e=Me(Object,"defineProperty");return e({},"",{}),e}catch{}}(),Ms=ln?function(e,t){return ln(e,"toString",{configurable:!0,enumerable:!1,value:Us(t),writable:!0})}:dt,Fs=ks(Ms);function Bs(e,t,n,r){e.length;for(var s=n+1;s--;)if(t(e[s],s,e))return s;return-1}var Gs=9007199254740991,Vs=/^(?:0|[1-9]\d*)$/;function qn(e,t){var n=typeof e;return t=t??Gs,!!t&&(n=="number"||n!="symbol"&&Vs.test(e))&&e>-1&&e%1==0&&e<t}function Yn(e,t){return e===t||e!==e&&t!==t}var cn=Math.max;function Cs(e,t,n){return t=cn(t===void 0?e.length-1:t,0),function(){for(var r=arguments,s=-1,i=cn(r.length-t,0),a=Array(i);++s<i;)a[s]=r[t+s];s=-1;for(var o=Array(t+1);++s<t;)o[s]=r[s];return o[t]=n(a),Os(e,this,o)}}function $s(e,t){return Fs(Cs(e,t,dt),e+"")}var js=9007199254740991;function Ft(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=js}function Et(e){return e!=null&&Ft(e.length)&&!zn(e)}var Xs=Object.prototype;function Kn(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||Xs;return e===n}function Qn(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var Ws="[object Arguments]";function un(e){return Se(e)&&$e(e)==Ws}var Jn=Object.prototype,Hs=Jn.hasOwnProperty,zs=Jn.propertyIsEnumerable,Bt=un(function(){return arguments}())?un:function(e){return Se(e)&&Hs.call(e,"callee")&&!zs.call(e,"callee")};function qs(){return!1}var Zn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=Zn&&typeof module=="object"&&module&&!module.nodeType&&module,Ys=hn&&hn.exports===Zn,fn=Ys?be.Buffer:void 0,Ks=fn?fn.isBuffer:void 0,St=Ks||qs,Qs="[object Arguments]",Js="[object Array]",Zs="[object Boolean]",ei="[object Date]",ti="[object Error]",ni="[object Function]",ri="[object Map]",si="[object Number]",ii="[object Object]",ai="[object RegExp]",oi="[object Set]",li="[object String]",ci="[object WeakMap]",ui="[object ArrayBuffer]",hi="[object DataView]",fi="[object Float32Array]",pi="[object Float64Array]",di="[object Int8Array]",Ei="[object Int16Array]",Ni="[object Int32Array]",Ti="[object Uint8Array]",bi="[object Uint8ClampedArray]",mi="[object Uint16Array]",Ii="[object Uint32Array]",O={};O[fi]=O[pi]=O[di]=O[Ei]=O[Ni]=O[Ti]=O[bi]=O[mi]=O[Ii]=!0;O[Qs]=O[Js]=O[ui]=O[Zs]=O[hi]=O[ei]=O[ti]=O[ni]=O[ri]=O[si]=O[ii]=O[ai]=O[oi]=O[li]=O[ci]=!1;function gi(e){return Se(e)&&Ft(e.length)&&!!O[$e(e)]}function _i(e){return function(t){return e(t)}}var er=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ze=er&&typeof module=="object"&&module&&!module.nodeType&&module,Ai=ze&&ze.exports===er,yt=Ai&&jn.process,pn=function(){try{var e=ze&&ze.require&&ze.require("util").types;return e||yt&&yt.binding&&yt.binding("util")}catch{}}(),dn=pn&&pn.isTypedArray,tr=dn?_i(dn):gi,Li=Object.prototype,vi=Li.hasOwnProperty;function nr(e,t){var n=ce(e),r=!n&&Bt(e),s=!n&&!r&&St(e),i=!n&&!r&&!s&&tr(e),a=n||r||s||i,o=a?Qn(e.length,String):[],u=o.length;for(var p in e)(t||vi.call(e,p))&&!(a&&(p=="length"||s&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||qn(p,u)))&&o.push(p);return o}function yi(e,t){return function(n){return e(t(n))}}var wi=yi(Object.keys,Object),Pi=Object.prototype,Si=Pi.hasOwnProperty;function Oi(e){if(!Kn(e))return wi(e);var t=[];for(var n in Object(e))Si.call(e,n)&&n!="constructor"&&t.push(n);return t}function Gt(e){return Et(e)?nr(e):Oi(e)}function xi(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}var Di=Object.prototype,Ri=Di.hasOwnProperty;function ki(e){if(!Ve(e))return xi(e);var t=Kn(e),n=[];for(var r in e)r=="constructor"&&(t||!Ri.call(e,r))||n.push(r);return n}function Ui(e){return Et(e)?nr(e,!0):ki(e)}var Mi=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fi=/^\w*$/;function Vt(e,t){if(ce(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||pt(e)?!0:Fi.test(e)||!Mi.test(e)||t!=null&&e in Object(t)}var Ye=Me(Object,"create");function Bi(){this.__data__=Ye?Ye(null):{},this.size=0}function Gi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Vi="__lodash_hash_undefined__",Ci=Object.prototype,$i=Ci.hasOwnProperty;function ji(e){var t=this.__data__;if(Ye){var n=t[e];return n===Vi?void 0:n}return $i.call(t,e)?t[e]:void 0}var Xi=Object.prototype,Wi=Xi.hasOwnProperty;function Hi(e){var t=this.__data__;return Ye?t[e]!==void 0:Wi.call(t,e)}var zi="__lodash_hash_undefined__";function qi(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ye&&t===void 0?zi:t,this}function Oe(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Oe.prototype.clear=Bi;Oe.prototype.delete=Gi;Oe.prototype.get=ji;Oe.prototype.has=Hi;Oe.prototype.set=qi;function Yi(){this.__data__=[],this.size=0}function Nt(e,t){for(var n=e.length;n--;)if(Yn(e[n][0],t))return n;return-1}var Ki=Array.prototype,Qi=Ki.splice;function Ji(e){var t=this.__data__,n=Nt(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Qi.call(t,n,1),--this.size,!0}function Zi(e){var t=this.__data__,n=Nt(t,e);return n<0?void 0:t[n][1]}function ea(e){return Nt(this.__data__,e)>-1}function ta(e,t){var n=this.__data__,r=Nt(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function me(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}me.prototype.clear=Yi;me.prototype.delete=Ji;me.prototype.get=Zi;me.prototype.has=ea;me.prototype.set=ta;var Ke=Me(be,"Map");function na(){this.size=0,this.__data__={hash:new Oe,map:new(Ke||me),string:new Oe}}function ra(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Tt(e,t){var n=e.__data__;return ra(t)?n[typeof t=="string"?"string":"hash"]:n.map}function sa(e){var t=Tt(this,e).delete(e);return this.size-=t?1:0,t}function ia(e){return Tt(this,e).get(e)}function aa(e){return Tt(this,e).has(e)}function oa(e,t){var n=Tt(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function Ie(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Ie.prototype.clear=na;Ie.prototype.delete=sa;Ie.prototype.get=ia;Ie.prototype.has=aa;Ie.prototype.set=oa;var la="Expected a function";function Ct(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(la);var n=function(){var r=arguments,s=t?t.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var a=e.apply(this,r);return n.cache=i.set(s,a)||i,a};return n.cache=new(Ct.Cache||Ie),n}Ct.Cache=Ie;var ca=500;function ua(e){var t=Ct(e,function(r){return n.size===ca&&n.clear(),r}),n=t.cache;return t}var ha=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fa=/\\(\\)?/g,pa=ua(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(ha,function(n,r,s,i){t.push(s?i.replace(fa,"$1"):r||n)}),t});function da(e){return e==null?"":Hn(e)}function rr(e,t){return ce(e)?e:Vt(e,t)?[e]:pa(da(e))}function bt(e){if(typeof e=="string"||pt(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}function sr(e,t){t=rr(t,e);for(var n=0,r=t.length;e!=null&&n<r;)e=e[bt(t[n++])];return n&&n==r?e:void 0}function ir(e,t,n){var r=e==null?void 0:sr(e,t);return r===void 0?n:r}function ar(e,t){for(var n=-1,r=t.length,s=e.length;++n<r;)e[s+n]=t[n];return e}var En=pe?pe.isConcatSpreadable:void 0;function Ea(e){return ce(e)||Bt(e)||!!(En&&e&&e[En])}function Na(e,t,n,r,s){var i=-1,a=e.length;for(n||(n=Ea),s||(s=[]);++i<a;){var o=e[i];n(o)?ar(s,o):s[s.length]=o}return s}function Nn(e){var t=e==null?0:e.length;return t?Na(e):[]}function Ta(){this.__data__=new me,this.size=0}function ba(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function ma(e){return this.__data__.get(e)}function Ia(e){return this.__data__.has(e)}var ga=200;function _a(e,t){var n=this.__data__;if(n instanceof me){var r=n.__data__;if(!Ke||r.length<ga-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Ie(r)}return n.set(e,t),this.size=n.size,this}function Ne(e){var t=this.__data__=new me(e);this.size=t.size}Ne.prototype.clear=Ta;Ne.prototype.delete=ba;Ne.prototype.get=ma;Ne.prototype.has=Ia;Ne.prototype.set=_a;function or(e,t){for(var n=-1,r=e==null?0:e.length,s=0,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[s++]=a)}return i}function Aa(){return[]}var La=Object.prototype,va=La.propertyIsEnumerable,Tn=Object.getOwnPropertySymbols,ya=Tn?function(e){return e==null?[]:(e=Object(e),or(Tn(e),function(t){return va.call(e,t)}))}:Aa;function wa(e,t,n){var r=t(e);return ce(e)?r:ar(r,n(e))}function bn(e){return wa(e,Gt,ya)}var Ot=Me(be,"DataView"),xt=Me(be,"Promise"),Dt=Me(be,"Set"),mn="[object Map]",Pa="[object Object]",In="[object Promise]",gn="[object Set]",_n="[object WeakMap]",An="[object DataView]",Sa=Ue(Ot),Oa=Ue(Ke),xa=Ue(xt),Da=Ue(Dt),Ra=Ue(Pt),ve=$e;(Ot&&ve(new Ot(new ArrayBuffer(1)))!=An||Ke&&ve(new Ke)!=mn||xt&&ve(xt.resolve())!=In||Dt&&ve(new Dt)!=gn||Pt&&ve(new Pt)!=_n)&&(ve=function(e){var t=$e(e),n=t==Pa?e.constructor:void 0,r=n?Ue(n):"";if(r)switch(r){case Sa:return An;case Oa:return mn;case xa:return In;case Da:return gn;case Ra:return _n}return t});var Ln=be.Uint8Array,ka="__lodash_hash_undefined__";function Ua(e){return this.__data__.set(e,ka),this}function Ma(e){return this.__data__.has(e)}function at(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new Ie;++t<n;)this.add(e[t])}at.prototype.add=at.prototype.push=Ua;at.prototype.has=Ma;function Fa(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function Ba(e,t){return e.has(t)}var Ga=1,Va=2;function lr(e,t,n,r,s,i){var a=n&Ga,o=e.length,u=t.length;if(o!=u&&!(a&&u>o))return!1;var p=i.get(e),h=i.get(t);if(p&&h)return p==t&&h==e;var d=-1,E=!0,b=n&Va?new at:void 0;for(i.set(e,t),i.set(t,e);++d<o;){var A=e[d],I=t[d];if(r)var v=a?r(I,A,d,t,e,i):r(A,I,d,e,t,i);if(v!==void 0){if(v)continue;E=!1;break}if(b){if(!Fa(t,function(W,y){if(!Ba(b,y)&&(A===W||s(A,W,n,r,i)))return b.push(y)})){E=!1;break}}else if(!(A===I||s(A,I,n,r,i))){E=!1;break}}return i.delete(e),i.delete(t),E}function Ca(e){var t=-1,n=Array(e.size);return e.forEach(function(r,s){n[++t]=[s,r]}),n}function $a(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}var ja=1,Xa=2,Wa="[object Boolean]",Ha="[object Date]",za="[object Error]",qa="[object Map]",Ya="[object Number]",Ka="[object RegExp]",Qa="[object Set]",Ja="[object String]",Za="[object Symbol]",eo="[object ArrayBuffer]",to="[object DataView]",vn=pe?pe.prototype:void 0,wt=vn?vn.valueOf:void 0;function no(e,t,n,r,s,i,a){switch(n){case to:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case eo:return!(e.byteLength!=t.byteLength||!i(new Ln(e),new Ln(t)));case Wa:case Ha:case Ya:return Yn(+e,+t);case za:return e.name==t.name&&e.message==t.message;case Ka:case Ja:return e==t+"";case qa:var o=Ca;case Qa:var u=r&ja;if(o||(o=$a),e.size!=t.size&&!u)return!1;var p=a.get(e);if(p)return p==t;r|=Xa,a.set(e,t);var h=lr(o(e),o(t),r,s,i,a);return a.delete(e),h;case Za:if(wt)return wt.call(e)==wt.call(t)}return!1}var ro=1,so=Object.prototype,io=so.hasOwnProperty;function ao(e,t,n,r,s,i){var a=n&ro,o=bn(e),u=o.length,p=bn(t),h=p.length;if(u!=h&&!a)return!1;for(var d=u;d--;){var E=o[d];if(!(a?E in t:io.call(t,E)))return!1}var b=i.get(e),A=i.get(t);if(b&&A)return b==t&&A==e;var I=!0;i.set(e,t),i.set(t,e);for(var v=a;++d<u;){E=o[d];var W=e[E],y=t[E];if(r)var Pe=a?r(y,W,E,t,e,i):r(W,y,E,e,t,i);if(!(Pe===void 0?W===y||s(W,y,n,r,i):Pe)){I=!1;break}v||(v=E=="constructor")}if(I&&!v){var Q=e.constructor,k=t.constructor;Q!=k&&"constructor"in e&&"constructor"in t&&!(typeof Q=="function"&&Q instanceof Q&&typeof k=="function"&&k instanceof k)&&(I=!1)}return i.delete(e),i.delete(t),I}var oo=1,yn="[object Arguments]",wn="[object Array]",nt="[object Object]",lo=Object.prototype,Pn=lo.hasOwnProperty;function co(e,t,n,r,s,i){var a=ce(e),o=ce(t),u=a?wn:ve(e),p=o?wn:ve(t);u=u==yn?nt:u,p=p==yn?nt:p;var h=u==nt,d=p==nt,E=u==p;if(E&&St(e)){if(!St(t))return!1;a=!0,h=!1}if(E&&!h)return i||(i=new Ne),a||tr(e)?lr(e,t,n,r,s,i):no(e,t,u,n,r,s,i);if(!(n&oo)){var b=h&&Pn.call(e,"__wrapped__"),A=d&&Pn.call(t,"__wrapped__");if(b||A){var I=b?e.value():e,v=A?t.value():t;return i||(i=new Ne),s(I,v,n,r,i)}}return E?(i||(i=new Ne),ao(e,t,n,r,s,i)):!1}function $t(e,t,n,r,s){return e===t?!0:e==null||t==null||!Se(e)&&!Se(t)?e!==e&&t!==t:co(e,t,n,r,$t,s)}var uo=1,ho=2;function fo(e,t,n,r){var s=n.length,i=s;if(e==null)return!i;for(e=Object(e);s--;){var a=n[s];if(a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++s<i;){a=n[s];var o=a[0],u=e[o],p=a[1];if(a[2]){if(u===void 0&&!(o in e))return!1}else{var h=new Ne,d;if(!(d===void 0?$t(p,u,uo|ho,r,h):d))return!1}}return!0}function cr(e){return e===e&&!Ve(e)}function po(e){for(var t=Gt(e),n=t.length;n--;){var r=t[n],s=e[r];t[n]=[r,s,cr(s)]}return t}function ur(e,t){return function(n){return n==null?!1:n[e]===t&&(t!==void 0||e in Object(n))}}function Eo(e){var t=po(e);return t.length==1&&t[0][2]?ur(t[0][0],t[0][1]):function(n){return n===e||fo(n,e,t)}}function No(e,t){return e!=null&&t in Object(e)}function To(e,t,n){t=rr(t,e);for(var r=-1,s=t.length,i=!1;++r<s;){var a=bt(t[r]);if(!(i=e!=null&&n(e,a)))break;e=e[a]}return i||++r!=s?i:(s=e==null?0:e.length,!!s&&Ft(s)&&qn(a,s)&&(ce(e)||Bt(e)))}function bo(e,t){return e!=null&&To(e,t,No)}var mo=1,Io=2;function go(e,t){return Vt(e)&&cr(t)?ur(bt(e),t):function(n){var r=ir(n,e);return r===void 0&&r===t?bo(n,e):$t(t,r,mo|Io)}}function hr(e){return function(t){return t==null?void 0:t[e]}}function _o(e){return function(t){return sr(t,e)}}function Ao(e){return Vt(e)?hr(bt(e)):_o(e)}function fr(e){return typeof e=="function"?e:e==null?dt:typeof e=="object"?ce(e)?go(e[0],e[1]):Eo(e):Ao(e)}function Lo(e,t,n,r){for(var s=-1,i=e==null?0:e.length;++s<i;){var a=e[s];t(r,a,n(a),e)}return r}function vo(e){return function(t,n,r){for(var s=-1,i=Object(t),a=r(t),o=a.length;o--;){var u=a[++s];if(n(i[u],u,i)===!1)break}return t}}var pr=vo();function yo(e,t){return e&&pr(e,t,Gt)}function wo(e,t){return function(n,r){if(n==null)return n;if(!Et(n))return e(n,r);for(var s=n.length,i=-1,a=Object(n);++i<s&&r(a[i],i,a)!==!1;);return n}}var Po=wo(yo);function So(e,t,n,r){return Po(e,function(s,i,a){t(r,s,n(s),a)}),r}function Oo(e,t){return function(n,r){var s=ce(n)?Lo:So,i=t?t():{};return s(n,e,fr(r),i)}}function xo(e){return Se(e)&&Et(e)}function F(e){var t=e==null?0:e.length;return t?e[t-1]:void 0}function Do(e){return typeof e=="function"?e:dt}var Ro=Math.max,ko=Math.min;function Uo(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var s=r-1;return n!==void 0&&(s=ps(n),s=n<0?Ro(r+s,0):ko(s,r-1)),Bs(e,fr(t),s)}function Mo(e){return e&&e.length?e[0]:void 0}function Qe(e,t){return e==null?e:pr(e,Do(t),Ui)}var he=Oo(function(e,t,n){e[n?0:1].push(t)},function(){return[[],[]]}),Fo=Math.max;function Bo(e){if(!(e&&e.length))return[];var t=0;return e=or(e,function(n){if(xo(n))return t=Fo(n.length,t),!0}),Qn(t,function(n){return Wn(e,hr(n))})}var Rt=$s(Bo),f=(e=>(e.SPACE="<space>",e.TAB="<tab>",e.NEWLINE="<newline>",e.COMMA="<comma>",e.LPAREN="<lparen>",e.RPAREN="<rparen>",e.LBRACE="<lbrace>",e.RBRACE="<rbrace>",e.LBRACKET="<lbracket>",e.RBRACKET="<rbracket>",e.LANGLE="<langle>",e.RANGLE="<rangle>",e.OP="<op>",e.EOF="<eof>",e.NUMERIC_LITERAL="<number>",e.STRING_LITERAL="<string>",e.COLOR_LITERAL="<color>",e.FUNCTION_EXPRESSION="<function-expression>",e.QUOTED_STRING="<variable>",e.IDENTIFIER="<identifier>",e.SEMICOLON="<semicolon>",e.COLON="<colon>",e.TILDE="<tilde>",e.SINGLE_LINE_COMMENT="<single-line-comment>",e.MULTILINE_COMMENT="<multiline-comment>",e))(f||{});function Go(e){switch(e.kind){case"<newline>":case"<space>":case"<tab>":case"<single-line-comment>":case"<multiline-comment>":return!0;default:return!1}}function Vo(e){if(!e)return!1;switch(e){case"+":case"-":case"*":case"/":case"%":case"<":case">":case"=":case"!":case".":case"&":case"|":return!0;default:return!1}}function Sn(e){return e!==void 0&&e.kind==="<op>"}class z{constructor(t,n,r,s,i){this.kind=t,this.startPos=n,this.endPos=r,this.value=s,this.leadingTrivia=[],this.trailingTrivia=[],this.leadingInvalid=[],this.trailingInvalid=[],this.isInvalid=i,this.start=n.offset,this.end=r.offset}static create(t,n,r,s,i){return new z(t,n,r,s,i)}}function dr(e){return e.trailingTrivia.find(({kind:t})=>t===f.NEWLINE)!==void 0}function On(e,t){return t.leadingTrivia.find(({kind:r})=>r===f.NEWLINE)!==void 0||dr(e)}function kt(e){return e.trailingTrivia.find(({kind:t})=>[f.SPACE,f.TAB].includes(t))!==void 0}function Er(e){return e.trailingTrivia.length===0?e.end:Er(F(e.trailingTrivia))}function Nr(e){return e.leadingTrivia.length===0?e.start:Nr(e.leadingTrivia[0])}function Co(e){return[f.SINGLE_LINE_COMMENT,f.MULTILINE_COMMENT].includes(e.kind)}class $o{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class D{constructor(t,n,r){this.id=t,this.kind=n;const s=r.find(a=>a!==void 0&&!Number.isNaN(a.start));s?(this.startPos=s.startPos,this.fullStart=s instanceof z?Nr(s):s.fullStart):(this.startPos={offset:NaN,column:NaN,line:NaN},this.fullStart=NaN);const i=[...r].reverse().find(a=>a!==void 0&&!Number.isNaN(a.end));i?(this.endPos=i.endPos,this.fullEnd=i instanceof z?Er(i):i.fullEnd):(this.endPos={offset:NaN,column:NaN,line:NaN},this.fullEnd=NaN),this.start=this.startPos.offset,this.end=this.endPos.offset}}var ye=(e=>(e.PROGRAM="<program>",e.ELEMENT_DECLARATION="<element-declaration>",e.ATTRIBUTE="<attribute>",e.IDENTIFIER_STREAM="<identifer-stream>",e.LITERAL="<literal>",e.VARIABLE="<variable>",e.PREFIX_EXPRESSION="<prefix-expression>",e.INFIX_EXPRESSION="<infix-expression>",e.POSTFIX_EXPRESSION="<postfix-expression>",e.FUNCTION_EXPRESSION="<function-expression>",e.FUNCTION_APPLICATION="<function-application>",e.BLOCK_EXPRESSION="<block-expression>",e.LIST_EXPRESSION="<list-expression>",e.TUPLE_EXPRESSION="<tuple-expression>",e.CALL_EXPRESSION="<call-expression>",e.PRIMARY_EXPRESSION="<primary-expression>",e.GROUP_EXPRESSION="<group-expression>",e.DUMMY="<dummy>",e.ARRAY="<array>",e.PARTIAL_INJECTION="<partial-injection>",e))(ye||{});class ee extends D{constructor({body:t=[],eof:n},r){super(r,"<program>",[...t,n]),this.body=t,this.eof=n}}class P extends D{constructor({type:t,name:n,as:r,alias:s,attributeList:i,bodyColon:a,body:o},u){if(super(u,"<element-declaration>",[t,n,r,s,i,a,o]),o&&a&&!(o instanceof w||o instanceof P))throw new Error("If an element has a simple body, it must be a function application node");this.type=t,this.name=n,this.as=r,this.alias=s,this.attributeList=i,this.bodyColon=a,this.body=o}}class ie extends D{constructor({identifiers:t=[]},n){super(n,"<identifer-stream>",t||[]),this.identifiers=t}}class ae extends D{constructor({name:t,colon:n,value:r},s){super(s,"<attribute>",[t,n,r]),this.name=t,this.value=r,this.colon=n}}class ne extends D{constructor({op:t,expression:n},r){super(r,"<prefix-expression>",[t,n]),this.op=t,this.expression=n}}class de extends D{constructor({op:t,leftExpression:n,rightExpression:r},s){super(s,"<infix-expression>",[n,t,r]),this.op=t,this.leftExpression=n,this.rightExpression=r}}class mt extends D{constructor({op:t,expression:n},r){super(r,"<postfix-expression>",[n,t]),this.op=t,this.expression=n}}class Te extends D{constructor({value:t},n){super(n,"<function-expression>",[t]),this.value=t}}class w extends D{constructor({callee:t,args:n=[]},r){super(r,"<function-application>",[t,...n]),this.callee=t,this.args=n}}class fe extends D{constructor({blockOpenBrace:t,body:n=[],blockCloseBrace:r},s){super(s,"<block-expression>",[t,...n,r]),this.blockOpenBrace=t,this.body=n,this.blockCloseBrace=r}}class xe extends D{constructor({op:t,partial:n},r){super(r,"<partial-injection>",[t,n]),this.partial=n}}class B extends D{constructor({listOpenBracket:t,elementList:n=[],commaList:r=[],listCloseBracket:s},i){super(i,"<list-expression>",[t,...Tr(n,r),s]),this.listOpenBracket=t,this.elementList=n,this.commaList=r,this.listCloseBracket=s}}class Ee extends D{constructor({tupleOpenParen:t,elementList:n=[],commaList:r=[],tupleCloseParen:s},i){super(i,"<tuple-expression>",[t,...Tr(n,r),s]),this.tupleOpenParen=t,this.elementList=n,this.commaList=r,this.tupleCloseParen=s}}class jt extends Ee{constructor({groupOpenParen:t,expression:n,groupCloseParen:r},s){super({tupleOpenParen:t,elementList:n&&[n],commaList:[],tupleCloseParen:r},s),this.kind="<group-expression>"}}class re extends D{constructor({callee:t,argumentList:n},r){super(r,"<call-expression>",[t,n]),this.callee=t,this.argumentList=n}}class je extends D{constructor({literal:t},n){super(n,"<literal>",[t]),this.literal=t}}class ue extends D{constructor({variable:t},n){super(n,"<variable>",[t]),this.variable=t}}class H extends D{constructor({expression:t},n){super(n,"<primary-expression>",[t]),this.expression=t}}class rt extends D{constructor({pre:t},n){const r=z.create(f.SPACE,t.endPos,t.endPos," ",!1);super(n,"<dummy>",[r])}}class De extends D{constructor({expression:t,indexer:n},r){super(r,"<array>",[t,n]),this.array=t,this.indexer=n}}function Tr(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e||[];const[n]=e,[r]=t;return(n.start<r.start?Nn(Rt(e,t)):Nn(Rt(t,e))).filter(s=>s!==null)}function jo(e,t=!1){return JSON.stringify(e,function(n,r){var s;return!(this instanceof ee)&&n==="symbol"?r==null?void 0:r.id:n==="symbol"?{symbolTable:r==null?void 0:r.symbolTable,id:r==null?void 0:r.id,references:r==null?void 0:r.references.map(i=>i.id),declaration:(s=r==null?void 0:r.declaration)==null?void 0:s.id}:n==="referee"||n==="parent"||n==="declaration"?r==null?void 0:r.id:n==="symbolTable"?Object.fromEntries(r.table):r},t?2:0)}class M{constructor(t){this.value=t}unwrap(){return this.value}unwrap_or(t){return this.value}and_then(t){return t(this.value)}map(t){return new M(t(this.value))}isOk(){return!0}}class x{constructor(){this.value=void 0}unwrap(){throw new Error("Trying to unwrap a None value")}unwrap_or(t){return t}and_then(t){return new x}map(t){return new x}isOk(){return!1}}var m=(e=>(e.Schema="Schema",e.Table="Table",e.Column="Column",e.TableGroup="TableGroup",e.TableGroupField="TableGroup field",e.Enum="Enum",e.EnumField="Enum field",e.Note="Note",e.TablePartial="TablePartial",e.TablePartialInjection="TablePartialInjection",e))(m||{});function Xt(e){return`Schema:${e}`}function ot(e){return`Table:${e}`}function It(e){return`Column:${e}`}function Wt(e){return`Enum:${e}`}function Ht(e){return`Enum field:${e}`}function zt(e){return`TableGroup:${e}`}function qt(e){return`TableGroup field:${e}`}function Xo(e){return`Note:${e}`}function Yt(e){return`TablePartial:${e}`}function br(e){return`TablePartialInjection:${e}`}function st(e,t){switch(t){case"Column":return It(e);case"Enum":return Wt(e);case"Enum field":return Ht(e);case"Schema":return Xt(e);case"Table":return ot(e);case"TableGroup":return zt(e);case"TableGroup field":return qt(e);case"TablePartial":return Yt(e);default:throw new Error("Unreachable")}}function oe(e){const[t,n]=e.split(":");return Object.values(m).includes(t)?new M({name:n,kind:t}):new x}function Wo(e){const t=oe(e).unwrap_or(void 0);if(!t)return!1;const{kind:n,name:r}=t;return n==="Schema"&&r==="public"}function Ho(e){const t=oe(e).unwrap_or(void 0);if(!t)return!1;const{kind:n}=t;return n==="TablePartialInjection"}function zo(e){const t=oe(e).unwrap_or(void 0);if(!t)return null;const{kind:n,name:r}=t;return n==="TablePartialInjection"?st(r,"TablePartial"):null}class qo{constructor(){this.id=0}reset(){this.id=0}nextId(){return this.id++}}class mr{constructor({symbolTable:t},n){this.references=[],this.id=n,this.symbolTable=t}}class Yo{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Ko{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Ir{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Kt{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Qo{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class Jo{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class Zo{constructor({symbolTable:t,declaration:n},r){this.references=[],this.id=r,this.symbolTable=t,this.declaration=n}}class el{constructor({declaration:t},n){this.references=[],this.id=n,this.declaration=t}}class tl{constructor({injectorFieldSymbol:t,injectorDeclaration:n},r){this.references=[],this.id=r,this.injectorDeclaration=n,this.injectorFieldSymbol=t}}function nl(e){return[Xt,ot,Wt,zt,It,Ht,qt,Yt,br].map(t=>t(e))}function rl(e){return e instanceof Kt?tl:null}function gt(e){return!!e.match(new RegExp("(\\p{L}|_|\\p{M})","gu"))}function lt(e){const[t]=e;return t>="0"&&t<="9"}function sl(e){const[t]=e;return lt(t)||gt(t)&&t.toLowerCase()>="a"&&t.toLowerCase()<="f"}function Ge(e){return gt(e)||lt(e)}function xn(e,t){const n=[],r=Math.min(e.length,t.length);for(let s=0;s<r;s+=1)n.push(e[s],t[s]);return n.push(...e.slice(r),...t.slice(r)),n}function qe(e,t){return e>=t.start&&e<t.end}function gr(e){var t;return e instanceof ne?`${(t=e.op)==null?void 0:t.value}${gr(e.expression)}`:e.expression.literal.value}function Ut(e){var t;return e instanceof ne?((t=e.op)==null?void 0:t.value)==="-"?-Ut(e.expression):Ut(e.expression):Number.parseFloat(e.expression.literal.value)}var l=(e=>(e[e.UNKNOWN_SYMBOL=1e3]="UNKNOWN_SYMBOL",e[e.UNEXPECTED_SYMBOL=1001]="UNEXPECTED_SYMBOL",e[e.UNEXPECTED_EOF=1002]="UNEXPECTED_EOF",e[e.UNEXPECTED_NEWLINE=1003]="UNEXPECTED_NEWLINE",e[e.UNKNOWN_TOKEN=1004]="UNKNOWN_TOKEN",e[e.UNEXPECTED_TOKEN=1005]="UNEXPECTED_TOKEN",e[e.UNEXPECTED_ELEMENT_DECLARATION=1006]="UNEXPECTED_ELEMENT_DECLARATION",e[e.MISSING_SPACES=1007]="MISSING_SPACES",e[e.UNKNOWN_PREFIX_OP=1008]="UNKNOWN_PREFIX_OP",e[e.INVALID_OPERAND=1009]="INVALID_OPERAND",e[e.EMPTY_ATTRIBUTE_NAME=1010]="EMPTY_ATTRIBUTE_NAME",e[e.INVALID_ESCAPE_SEQUENCE=1011]="INVALID_ESCAPE_SEQUENCE",e[e.INVALID_NAME=3e3]="INVALID_NAME",e[e.UNEXPECTED_NAME=3001]="UNEXPECTED_NAME",e[e.NAME_NOT_FOUND=3002]="NAME_NOT_FOUND",e[e.DUPLICATE_NAME=3003]="DUPLICATE_NAME",e[e.INVALID_ALIAS=3004]="INVALID_ALIAS",e[e.UNEXPECTED_ALIAS=3005]="UNEXPECTED_ALIAS",e[e.UNEXPECTED_SETTINGS=3006]="UNEXPECTED_SETTINGS",e[e.INVALID_SETTINGS=3007]="INVALID_SETTINGS",e[e.UNEXPECTED_SIMPLE_BODY=3008]="UNEXPECTED_SIMPLE_BODY",e[e.UNEXPECTED_COMPLEX_BODY=3009]="UNEXPECTED_COMPLEX_BODY",e[e.INVALID_TABLE_CONTEXT=3010]="INVALID_TABLE_CONTEXT",e[e.INVALID_TABLE_SETTING=3011]="INVALID_TABLE_SETTING",e[e.DUPLICATE_TABLE_SETTING=3012]="DUPLICATE_TABLE_SETTING",e[e.INVALID_TABLEGROUP_CONTEXT=3013]="INVALID_TABLEGROUP_CONTEXT",e[e.INVALID_TABLEGROUP_ELEMENT_NAME=3014]="INVALID_TABLEGROUP_ELEMENT_NAME",e[e.DUPLICATE_TABLEGROUP_ELEMENT_NAME=3015]="DUPLICATE_TABLEGROUP_ELEMENT_NAME",e[e.DUPLICATE_TABLEGROUP_FIELD_NAME=3016]="DUPLICATE_TABLEGROUP_FIELD_NAME",e[e.INVALID_TABLEGROUP_FIELD=3017]="INVALID_TABLEGROUP_FIELD",e[e.EMPTY_TABLE=3018]="EMPTY_TABLE",e[e.INVALID_COLUMN=3019]="INVALID_COLUMN",e[e.INVALID_COLUMN_NAME=3020]="INVALID_COLUMN_NAME",e[e.UNKNOWN_COLUMN_SETTING=3021]="UNKNOWN_COLUMN_SETTING",e[e.INVALID_COLUMN_TYPE=3022]="INVALID_COLUMN_TYPE",e[e.DUPLICATE_COLUMN_NAME=3023]="DUPLICATE_COLUMN_NAME",e[e.DUPLICATE_COLUMN_SETTING=3024]="DUPLICATE_COLUMN_SETTING",e[e.INVALID_COLUMN_SETTING_VALUE=3025]="INVALID_COLUMN_SETTING_VALUE",e[e.INVALID_ENUM_CONTEXT=3026]="INVALID_ENUM_CONTEXT",e[e.INVALID_ENUM_ELEMENT_NAME=3027]="INVALID_ENUM_ELEMENT_NAME",e[e.INVALID_ENUM_ELEMENT=3028]="INVALID_ENUM_ELEMENT",e[e.DUPLICATE_ENUM_ELEMENT_NAME=3029]="DUPLICATE_ENUM_ELEMENT_NAME",e[e.UNKNOWN_ENUM_ELEMENT_SETTING=3030]="UNKNOWN_ENUM_ELEMENT_SETTING",e[e.DUPLICATE_ENUM_ELEMENT_SETTING=3031]="DUPLICATE_ENUM_ELEMENT_SETTING",e[e.INVALID_ENUM_ELEMENT_SETTING=3032]="INVALID_ENUM_ELEMENT_SETTING",e[e.EMPTY_ENUM=3033]="EMPTY_ENUM",e[e.INVALID_REF_CONTEXT=3034]="INVALID_REF_CONTEXT",e[e.UNKNOWN_REF_SETTING=3035]="UNKNOWN_REF_SETTING",e[e.DUPLICATE_REF_SETTING=3036]="DUPLICATE_REF_SETTING",e[e.INVALID_REF_SETTING_VALUE=3037]="INVALID_REF_SETTING_VALUE",e[e.INVALID_REF_RELATIONSHIP=3038]="INVALID_REF_RELATIONSHIP",e[e.INVALID_REF_FIELD=3039]="INVALID_REF_FIELD",e[e.EMPTY_REF=3040]="EMPTY_REF",e[e.REF_REDEFINED=3041]="REF_REDEFINED",e[e.INVALID_NOTE_CONTEXT=3042]="INVALID_NOTE_CONTEXT",e[e.INVALID_NOTE=3043]="INVALID_NOTE",e[e.NOTE_REDEFINED=3044]="NOTE_REDEFINED",e[e.NOTE_CONTENT_REDEFINED=3045]="NOTE_CONTENT_REDEFINED",e[e.EMPTY_NOTE=3046]="EMPTY_NOTE",e[e.INVALID_INDEXES_CONTEXT=3047]="INVALID_INDEXES_CONTEXT",e[e.INVALID_INDEXES_FIELD=3048]="INVALID_INDEXES_FIELD",e[e.INVALID_INDEX=3049]="INVALID_INDEX",e[e.UNKNOWN_INDEX_SETTING=3050]="UNKNOWN_INDEX_SETTING",e[e.DUPLICATE_INDEX_SETTING=3051]="DUPLICATE_INDEX_SETTING",e[e.UNEXPECTED_INDEX_SETTING_VALUE=3052]="UNEXPECTED_INDEX_SETTING_VALUE",e[e.INVALID_INDEX_SETTING_VALUE=3053]="INVALID_INDEX_SETTING_VALUE",e[e.INVALID_PROJECT_CONTEXT=3054]="INVALID_PROJECT_CONTEXT",e[e.PROJECT_REDEFINED=3055]="PROJECT_REDEFINED",e[e.INVALID_PROJECT_FIELD=3056]="INVALID_PROJECT_FIELD",e[e.INVALID_CUSTOM_CONTEXT=3057]="INVALID_CUSTOM_CONTEXT",e[e.INVALID_CUSTOM_ELEMENT_VALUE=3058]="INVALID_CUSTOM_ELEMENT_VALUE",e[e.INVALID_ELEMENT_IN_SIMPLE_BODY=3059]="INVALID_ELEMENT_IN_SIMPLE_BODY",e[e.INVALID_TABLE_PARTIAL_CONTEXT=3060]="INVALID_TABLE_PARTIAL_CONTEXT",e[e.INVALID_TABLE_PARTIAL_ELEMENT_NAME=3061]="INVALID_TABLE_PARTIAL_ELEMENT_NAME",e[e.INVALID_TABLE_PARTIAL_SETTING=3062]="INVALID_TABLE_PARTIAL_SETTING",e[e.DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME=3063]="DUPLICATE_TABLE_PARTIAL_ELEMENT_NAME",e[e.DUPLICATE_TABLE_PARTIAL_SETTING=3064]="DUPLICATE_TABLE_PARTIAL_SETTING",e[e.INVALID_TABLE_PARTIAL_INJECTION=3065]="INVALID_TABLE_PARTIAL_INJECTION",e[e.INVALID_TABLE_PARTIAL_INJECTION_OP=3066]="INVALID_TABLE_PARTIAL_INJECTION_OP",e[e.INVALID_TABLE_PARTIAL_INJECTION_NAME=3067]="INVALID_TABLE_PARTIAL_INJECTION_NAME",e[e.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME=3068]="DUPLICATE_TABLE_PARTIAL_INJECTION_NAME",e[e.BINDING_ERROR=4e3]="BINDING_ERROR",e[e.UNSUPPORTED=5e3]="UNSUPPORTED",e[e.CIRCULAR_REF=5001]="CIRCULAR_REF",e[e.SAME_ENDPOINT=5002]="SAME_ENDPOINT",e[e.UNEQUAL_FIELDS_BINARY_REF=5003]="UNEQUAL_FIELDS_BINARY_REF",e[e.CONFLICTING_SETTING=5004]="CONFLICTING_SETTING",e[e.TABLE_REAPPEAR_IN_TABLEGROUP=5005]="TABLE_REAPPEAR_IN_TABLEGROUP",e))(l||{});class c extends Error{constructor(t,n,r){super(n),this.code=t,this.diagnostic=n,this.nodeOrToken=r,this.start=r.start,this.end=r.end,this.name=this.constructor.name,Object.setPrototypeOf(this,c.prototype)}}class te{constructor(t,n){this.value=t,this.errors=n===void 0?[]:n}getValue(){return this.value}getErrors(){return this.errors}chain(t){const n=t(this.value),r=[...this.errors,...n.errors];return new te(n.value,r)}map(t){return new te(t(this.value),this.errors)}}function il(e,t,n){if(!e||!we(e)||t.length===0)return new x;const r=[...t],s=Dn(e).unwrap(),i=r.pop();if(!(i instanceof fe))return new x;const a=F(r)instanceof B?r.pop():void 0;if(r.length===3){const o=Dn(r[1]).value;return!o||!Mt(o)?new x:new M(n.create(P,{type:s,name:r[0],as:o,alias:r[2],attributeList:a,body:i}))}return r.length===1?new M(n.create(P,{type:s,name:r[0],attributeList:a,body:i})):r.length===0?new M(n.create(P,{type:s,attributeList:a,body:i})):new x}function Mt(e){return e.kind===f.IDENTIFIER&&e.value==="as"}function g(e){e&&(e instanceof z?al(e):ol(e))}function al(e){e.kind!==f.EOF&&(e.isInvalid=!0)}function ol(e){if(e instanceof P)g(e.type),g(e.name),g(e.as),g(e.alias),g(e.bodyColon),g(e.attributeList),g(e.body);else if(e instanceof ie)e.identifiers.forEach(g);else if(e instanceof ae)g(e.name),g(e.colon),g(e.value);else if(e instanceof ne)g(e.op),g(e.expression);else if(e instanceof de)g(e.leftExpression),g(e.op),g(e.rightExpression);else if(e instanceof mt)g(e.op),g(e.expression);else if(e instanceof fe)g(e.blockOpenBrace),e.body.forEach(g),g(e.blockCloseBrace);else if(e instanceof B)g(e.listOpenBracket),e.commaList.forEach(g),e.elementList.forEach(g),g(e.listCloseBracket);else if(e instanceof Ee)g(e.tupleOpenParen),e.commaList.forEach(g),e.elementList.forEach(g),g(e.tupleCloseParen);else if(e instanceof re)g(e.callee),g(e.argumentList);else if(e instanceof w)g(e.callee),e.args.forEach(g);else if(e instanceof H)g(e.expression);else if(e instanceof Te)g(e.value);else if(e instanceof ue)g(e.variable);else if(e instanceof je)g(e.literal);else throw e instanceof jt?new Error("This case is handled by the TupleExpressionNode case"):new Error("Unreachable case in markInvalidNode")}function _r(e){return!!(e!=null&&e.isInvalid)}function $(...e){return e.filter(t=>t!==void 0)}function ll(e){if(e instanceof ee)return $(...e.body,e.eof);if(e instanceof P)return $(e.type,e.name,e.as,e.alias,e.attributeList,e.bodyColon,e.body);if(e instanceof ae)return $(e.name,e.colon,e.value);if(e instanceof ie)return e.identifiers;if(e instanceof je)return e.literal?[e.literal]:[];if(e instanceof ue)return $(e.variable);if(e instanceof ne)return $(e.op,e.expression);if(e instanceof de)return $(e.leftExpression,e.op,e.rightExpression);if(e instanceof mt)return $(e.expression,e.op);if(e instanceof Te)return $(e.value);if(e instanceof w)return $(e.callee,...e.args);if(e instanceof fe)return $(e.blockOpenBrace,...e.body,e.blockCloseBrace);if(e instanceof B)return $(e.listOpenBracket,...xn(e.elementList,e.commaList),e.listCloseBracket);if(e instanceof Ee)return $(e.tupleOpenParen,...xn(e.elementList,e.commaList),e.tupleCloseParen);if(e instanceof re)return $(e.callee,e.argumentList);if(e instanceof H)return $(e.expression);if(e instanceof De)return $(e.array,e.indexer);if(e instanceof xe)return $(e.partial);throw e instanceof jt?new Error("This case is already handled by TupleExpressionNode"):new Error("Unreachable - no other possible cases")}function Dn(e){return X(e)?new M(e.expression.variable):new x}function Y(e){var t;return e instanceof H&&(e.expression instanceof ue&&e.expression.variable instanceof z&&e.expression.variable.kind===f.QUOTED_STRING||e.expression instanceof je&&((t=e.expression.literal)==null?void 0:t.kind)===f.STRING_LITERAL)}function X(e){return e instanceof H&&e.expression instanceof ue&&e.expression.variable instanceof z}function we(e){var t;return e instanceof H&&e.expression instanceof ue&&((t=e.expression.variable)==null?void 0:t.kind)===f.IDENTIFIER}function Qt(e){var t;return e instanceof de&&e.leftExpression instanceof D&&e.rightExpression instanceof D&&((t=e.op)==null?void 0:t.value)==="."}function Ce(e){if(e===void 0)return new x;const t=e.identifiers.map(n=>n.value).join(" ");return t===""?new x:new M(t)}class cl{constructor(t){this.start={offset:0,line:0,column:0},this.current={offset:0,line:0,column:0},this.tokens=[],this.errors=[],this.text=t}isAtEnd(){return this.current.offset>=this.text.length}advance(){const t=this.peek();return this.current={...this.current},t===`
2
+ `?(this.current.line+=1,this.current.column=0):this.current.column+=1,this.current.offset+=1,t}peek(t=0){if(!(this.current.offset+t>=this.text.length))return this.text[this.current.offset+t]}check(t){for(let n=0;n<t.length;n+=1)if(t[n]!==this.peek(n))return!1;return!0}match(t){return this.check(t)?(t.split("").forEach(()=>this.advance()),!0):!1}addToken(t,n=!1){this.tokens.push(this.createToken(t,n))}createToken(t,n=!1){return z.create(t,this.start,this.current,this.text.substring(this.start.offset,this.current.offset),n)}lex(){return this.scanTokens(),this.tokens.push(z.create(f.EOF,this.start,this.current,"",!1)),this.gatherTrivia(),this.gatherInvalid(),new te(this.tokens,this.errors)}scanTokens(){for(;!this.isAtEnd();){const t=this.advance();switch(t){case" ":this.addToken(f.SPACE);break;case"\r":break;case`
3
3
  `:this.addToken(f.NEWLINE);break;case" ":this.addToken(f.TAB);break;case",":this.addToken(f.COMMA);break;case"(":this.addToken(f.LPAREN);break;case")":this.addToken(f.RPAREN);break;case"[":this.addToken(f.LBRACKET);break;case"]":this.addToken(f.RBRACKET);break;case"{":this.addToken(f.LBRACE);break;case"}":this.addToken(f.RBRACE);break;case";":this.addToken(f.SEMICOLON);break;case":":this.addToken(f.COLON);break;case"~":this.addToken(f.TILDE);break;case"'":this.match("''")?this.multilineStringLiteral():this.singleLineStringLiteral();break;case'"':this.quotedVariable();break;case"`":this.functionExpression();break;case"#":this.colorLiteral();break;case"/":this.match("/")?this.singleLineComment():this.match("*")?this.multilineComment():this.operator(t);break;default:if(Vo(t)){this.operator(t);break}if(gt(t)){this.identifier();break}if(lt(t)){this.numericLiteralOrIdentifier();break}this.addToken(f.OP,!0),this.errors.push(new c(l.UNKNOWN_SYMBOL,`Unexpected token '${t}'`,this.createToken(f.OP,!0)));break}this.start={...this.current}}}gatherTrivia(){let t=!0,n=[],r;const s=[];for(const i of this.tokens)Go(i)?(n.push(i),i.kind===f.NEWLINE&&r&&(r.trailingTrivia=n,t=!0,r=void 0,n=[])):(t?i.leadingTrivia=n:r.trailingTrivia=n,s.push(i),n=[],r=i,t=!1);this.tokens=s}gatherInvalid(){let t;const n=[],r=[];for(t=0;t<this.tokens.length&&_r(this.tokens[t]);t+=1)r.push(this.tokens[t]);let s=this.tokens[t];for(s.leadingInvalid=[...r,...s.leadingInvalid];t<this.tokens.length;t+=1){const i=this.tokens[t];i.isInvalid?s.trailingInvalid.push(i):(s=i,n.push(i))}this.tokens=n}consumeUntil(t,n,{allowNewline:r,allowEof:s,raw:i,consumeStopSequence:a=!0}){let o="";for(;!this.isAtEnd()&&(r||!this.check(`
4
4
  `))&&!this.check(n);)this.peek()==="\\"&&!i?(this.advance(),o+=this.escapedString()):o+=this.advance();if(this.isAtEnd()&&!s){const u=this.createToken(t,!0);this.tokens.push(u),this.errors.push(new c(l.UNEXPECTED_EOF,"EOF reached while parsing",u));return}if(this.check(`
5
- `)&&!r){const u=this.createToken(t,!0);this.tokens.push(u),this.errors.push(new c(l.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",u));return}a&&this.match(n),this.tokens.push(Z.create(t,this.start,this.current,o,!1))}singleLineStringLiteral(){this.consumeUntil(f.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(f.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(f.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(f.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(f.SINGLE_LINE_COMMENT,`
5
+ `)&&!r){const u=this.createToken(t,!0);this.tokens.push(u),this.errors.push(new c(l.UNEXPECTED_NEWLINE,"Invalid newline encountered while parsing",u));return}a&&this.match(n),this.tokens.push(z.create(t,this.start,this.current,o,!1))}singleLineStringLiteral(){this.consumeUntil(f.STRING_LITERAL,"'",{allowNewline:!1,allowEof:!1,raw:!1})}multilineStringLiteral(){this.consumeUntil(f.STRING_LITERAL,"'''",{allowNewline:!0,allowEof:!1,raw:!1})}functionExpression(){this.consumeUntil(f.FUNCTION_EXPRESSION,"`",{allowNewline:!1,allowEof:!1,raw:!0})}quotedVariable(){this.consumeUntil(f.QUOTED_STRING,'"',{allowNewline:!1,allowEof:!1,raw:!1})}singleLineComment(){this.consumeUntil(f.SINGLE_LINE_COMMENT,`
6
6
  `,{allowNewline:!0,allowEof:!0,raw:!0,consumeStopSequence:!1})}multilineComment(){this.consumeUntil(f.MULTILINE_COMMENT,"*/",{allowNewline:!0,allowEof:!1,raw:!0})}identifier(){for(;!this.isAtEnd()&&Ge(this.peek());)this.advance();this.addToken(f.IDENTIFIER)}operator(t){switch(t){case"<":[">","="].includes(this.peek())&&this.advance();break;case">":this.peek()==="="&&this.advance();break;case"=":this.peek()==="="&&this.advance();break;case"!":this.peek()==="="&&this.advance();break}this.addToken(f.OP)}numericLiteralOrIdentifier(){let t=0;if(this.isAtEnd())return this.addToken(f.NUMERIC_LITERAL);for(;!this.isAtEnd();){const n=this.check(".");if(t+=n?1:0,t>1)break;if(!n&&this.current.offset===this.text.length-1)return this.advance(),this.addToken(f.NUMERIC_LITERAL);if(!n&&!Ge(this.peek()))return this.addToken(f.NUMERIC_LITERAL);if(!n&&!lt(this.peek()))break;this.advance()}if(t>0){for(;!this.isAtEnd()&&(this.check(".")||Ge(this.peek()));)this.advance();const n=this.createToken(f.NUMERIC_LITERAL,!0);this.tokens.push(n),this.errors.push(new c(l.UNKNOWN_TOKEN,"Invalid number",n))}else{for(;!this.isAtEnd()&&Ge(this.peek());)this.advance();const n=this.createToken(f.IDENTIFIER,!1);this.tokens.push(n)}}colorLiteral(){for(;!this.isAtEnd()&&Ge(this.peek());)this.advance();this.addToken(f.COLOR_LITERAL)}escapedString(){const t={column:this.current.column-1,offset:this.current.offset-1,line:this.current.line};if(this.isAtEnd())return"\\";switch(this.advance()){case"\r":return this.check(`
7
7
  `)&&this.advance(),"";case`
8
8
  `:return"";case"t":return" ";case"n":return`
9
- `;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case" ":return"\\ ";case"u":{let n="";for(let r=0;r<=3;r+=1){if(this.isAtEnd()||!Ge(this.peek()))return this.errors.push(new c(l.INVALID_ESCAPE_SEQUENCE,`Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`,Z.create(f.STRING_LITERAL,t,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var it=(e=>(e[e.ListExpression=0]="ListExpression",e[e.GroupExpression=1]="GroupExpression",e[e.BlockExpression=2]="BlockExpression",e))(it||{});class ul{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(t){this.stack.push(t),t===0&&(this.numberOfNestedLBrackets+=1),t===1&&(this.numberOfNestedLParens+=1),t===2&&(this.numberOfNestedLBraces+=1)}pop(){const t=this.stack.pop();return t===0&&(this.numberOfNestedLBrackets-=1),t===1&&(this.numberOfNestedLParens-=1),t===2&&(this.numberOfNestedLBraces-=1),t}top(){return F(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(t,n){return()=>{this.push(t);try{return n()}finally{this.pop()}}}findHandlerContext(t,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let r=n;r<t.length-1;r+=1)switch(t[r].kind){case f.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(i=>[1,0].includes(i));break;case f.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case f.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case f.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class hl{constructor(t){this.generator=t}create(t,n){return new t(n,this.generator.nextId())}}class T{constructor(t,n,r){this.token=t,this.partialNode=n,this.handlerContext=r}}class fl{constructor(t,n){this.current=0,this.errors=[],this.contextStack=new ul,this.synchronizeProgram=()=>{const r=this.peek();r.kind!==f.EOF?g(this.advance()):(g(this.peek()),this.logError(r,l.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const r=this.peek();if(Mt(r)||this.check(f.COLON,f.LBRACE,f.LBRACKET))break;g(r),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COLON,f.LBRACE,f.LBRACKET))break;g(r),this.advance()}},this.blockExpression=this.contextStack.withContextDo(it.BlockExpression,()=>{const r={body:[]},s=()=>this.nodeFactory.create(fe,r);try{this.consume("Expect an opening brace '{'",f.LBRACE),r.blockOpenBrace=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.blockOpenBrace=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(f.RBRACE);)try{if(this.match(f.TILDE)){const i=this.previous(),a=this.variable(),o=this.nodeFactory.create(xe,{op:i,partial:a});r.body.push(o)}else r.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(i){if(!(i instanceof T))throw i;if(r.body.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",f.RBRACE),r.blockCloseBrace=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.blockCloseBrace=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}return s()}),this.synchronizeBlock=()=>{if(!this.check(f.RBRACE))for(g(this.advance());!this.isAtEnd();){const r=this.peek();if(this.check(f.RBRACE)||On(this.previous(),r))break;g(r),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(it.GroupExpression,()=>{const r={elementList:[],commaList:[]},s=()=>this.nodeFactory.create(jt,{groupOpenParen:r.tupleOpenParen,groupCloseParen:r.tupleCloseParen,expression:r.elementList[0]}),i=()=>this.nodeFactory.create(Ee,r);try{this.consume("Expect an opening parenthesis '('",f.LPAREN),r.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof T))throw a;if(r.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(f.RPAREN))try{r.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof T))throw a;if(r.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,s(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(f.RPAREN);)try{this.consume("Expect a comma ','",f.COMMA),r.commaList.push(this.previous()),r.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof T))throw a;if(a.partialNode instanceof D&&r.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",f.RPAREN),r.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof T))throw a;if(r.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}return r.elementList.length===1?s():i()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.RPAREN,f.COMMA))break;g(r),this.advance()}},this.listExpression=this.contextStack.withContextDo(it.ListExpression,()=>{const r={elementList:[],commaList:[]},s=()=>this.nodeFactory.create(B,r);try{this.consume("Expect an opening bracket '['",f.LBRACKET),r.listOpenBracket=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.listOpenBracket=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(f.RBRACKET))try{r.elementList.push(this.attribute())}catch(i){if(!(i instanceof T))throw i;if(r.elementList.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(f.RBRACKET);)try{this.consume("Expect a comma ','",f.COMMA),r.commaList.push(this.previous()),r.elementList.push(this.attribute())}catch(i){if(!(i instanceof T))throw i;if(i.partialNode instanceof D&&r.elementList.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",f.RBRACKET),r.listCloseBracket=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.listCloseBracket=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}return s()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET))break;g(r),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET,f.COLON))break;g(r),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET))break;g(r),this.advance()}},this.tokens=t,this.nodeFactory=new hl(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===f.EOF}advance(){return this.isAtEnd()?F(this.tokens):this.tokens[this.current++]}peek(t=0){return t+this.current>=this.tokens.length?F(this.tokens):this.tokens[this.current+t]}match(...t){const n=this.check(...t);return n&&this.advance(),n}check(...t){const n=this.peek();return t.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(t){return t.handlerContext===void 0||t.handlerContext===this.contextStack.top()}consume(t,...n){if(!this.match(...n))throw this.logError(this.peek(),l.UNEXPECTED_TOKEN,t),new T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(t,...n){if(this.isAtEnd()||!this.check(...n)){for(g(this.peek()),this.logError(this.advance(),l.UNEXPECTED_TOKEN,t);!this.isAtEnd()&&!this.check(...n);)g(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const t=[],n=[];let r,s=0;for(;s<this.tokens.length&&this.tokens[s].isInvalid;s+=1)n.push(this.tokens[s]);for(r=this.tokens[s],r.leadingInvalid=n,t.push(r),s+=1;s<this.tokens.length;s+=1){const i=this.tokens[s];i.isInvalid?r.trailingInvalid.push(i):(r=i,t.push(r))}this.tokens=t}parse(){const t=this.program(),n=this.advance(),r=this.nodeFactory.create(te,{body:t,eof:n});return this.gatherInvalid(),new ee({ast:r,tokens:this.tokens},this.errors)}program(){const t=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();t.push(n)}catch(n){if(!(n instanceof T))throw n;t.push(n.partialNode),this.synchronizeProgram()}return t}elementDeclaration(){const t={},n=()=>this.nodeFactory.create(P,t);try{this.consume("Expect an identifier",f.IDENTIFIER),t.type=this.previous()}catch(r){throw r instanceof T?(t.type=r.partialNode,new T(r.token,n(),r.handlerContext)):r}if(!this.check(f.COLON,f.LBRACE,f.LBRACKET))try{t.name=this.normalExpression()}catch(r){if(!(r instanceof T))throw r;if(t.name=r.partialNode,!this.canHandle(r))throw new T(r.token,n(),r.handlerContext);this.synchronizeElementDeclarationName()}if(Mt(this.peek()))if(t.as=this.advance(),this.check(f.COLON,f.LBRACE,f.LBRACKET))this.logError(this.peek(),l.UNEXPECTED_TOKEN,"Expect an alias");else try{t.alias=this.normalExpression()}catch(r){if(!(r instanceof T))throw r;if(t.alias=r.partialNode,!this.canHandle(r))throw new T(r.token,n(),r.handlerContext);this.synchronizeElementDeclarationAlias()}try{t.attributeList=this.check(f.LBRACKET)?this.listExpression():void 0}catch(r){throw r instanceof T?(t.attributeList=r.partialNode,new T(r.token,n(),r.handlerContext)):r}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",f.LBRACE,f.COLON))return n();try{if(this.match(f.COLON)){t.bodyColon=this.previous();const r=this.expression();r instanceof P?(g(r),this.logError(r,l.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):t.body=r}else t.body=this.blockExpression()}catch(r){throw r instanceof T?(t.body=r.partialNode,new T(r.token,n(),r.handlerContext)):r}return this.nodeFactory.create(P,t)}fieldDeclaration(){const t={},n=()=>this.nodeFactory.create(P,t);try{this.consume("Expect an identifier",f.IDENTIFIER),t.type=this.previous()}catch(r){throw r instanceof T?(t.type=r.partialNode,new T(r.token,n(),r.handlerContext)):r}try{this.consume("Expect a colon ':'",f.COLON),t.bodyColon=this.previous()}catch(r){throw r instanceof T?(t.bodyColon=r.partialNode,new T(r.token,n(),r.handlerContext)):r}try{const r=this.expression();r instanceof P?this.errors.push(new c(l.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",r)):t.body=r}catch(r){throw r instanceof T?(t.body=r.partialNode,new T(r.token,n(),r.handlerContext)):r}return this.nodeFactory.create(P,t)}expression(){const t={args:[]},n=()=>il(t.callee,t.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,t));try{t.callee=this.normalExpression()}catch(s){throw s instanceof T?(t.callee=s.partialNode,new T(s.token,n(),s.handlerContext)):s}if(this.shouldStopExpression())return n();let r=t.callee;for(;!this.shouldStopExpression();){kt(this.previous())||this.logError(r,l.MISSING_SPACES,"Expect a following space");try{r=this.normalExpression(),t.args.push(r)}catch(s){throw s instanceof T?(r=s.partialNode,t.args.push(r),new T(s.token,n(),s.handlerContext)):s}}return n()}shouldStopExpression(){if(this.isAtEnd()||dr(this.previous()))return!0;const t=this.peek().kind;return t===f.RBRACE||t===f.RBRACKET||t===f.RPAREN||t===f.COMMA||t===f.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(t){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const r=this.peek();if(r.kind===f.LPAREN){const{left:s}=Rn(r);if(s<t||On(this.previous(),r)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(re,{callee:n,argumentList:this.tupleExpression()})}catch(i){throw i instanceof T?(n=this.nodeFactory.create(re,{callee:n,argumentList:i.partialNode}),new T(i.token,n,i.handlerContext)):i}}else if(r.kind===f.LBRACKET){if(kt(this.previous()))break;try{n=this.nodeFactory.create(De,{expression:n,indexer:this.listExpression()})}catch(s){throw s instanceof T?(n=this.nodeFactory.create(De,{expression:n,indexer:s.partialNode}),new T(s.token,n,s.handlerContext)):s}}else if(Sn(r)){const s=r,i=Rn(s);if(i.left!==null){if(i.left<=t)break;this.advance(),n=this.nodeFactory.create(mt,{expression:n,op:s})}else{const a=dl(s);if(a.left===null||a.left<=t)break;this.advance();try{n=this.nodeFactory.create(de,{leftExpression:n,op:s,rightExpression:s.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(o){throw o instanceof T?(n=this.nodeFactory.create(de,{leftExpression:n,op:s,rightExpression:o.partialNode}),new T(o.token,n,o.handlerContext)):o}}}else break}return n}leftExpression_bp(){let t;if(Sn(this.peek())){const n={};n.op=this.peek();const r=Nl(n.op);if(r.right===null)throw this.logError(n.op,l.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new T(n.op,this.nodeFactory.create(rt,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(r.right)}catch(s){throw s instanceof T?(n.expression=s.partialNode,new T(s.token,this.nodeFactory.create(ne,n),s.handlerContext)):s}t=this.nodeFactory.create(ne,n)}else if(t=this.extractOperand(),t instanceof rt)throw new T(this.peek(),this.nodeFactory.create(rt,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return t}extractOperand(){return this.check(f.NUMERIC_LITERAL,f.STRING_LITERAL,f.COLOR_LITERAL,f.QUOTED_STRING,f.IDENTIFIER)?this.primaryExpression():this.check(f.FUNCTION_EXPRESSION)?this.functionExpression():this.check(f.LBRACKET)?this.listExpression():this.check(f.LBRACE)?this.blockExpression():this.check(f.LPAREN)?this.tupleExpression():(this.peek().kind===f.EOF?this.logError(this.peek(),l.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),l.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(rt,{pre:this.previous()}))}functionExpression(){const t={};try{this.consume("Expect a function expression",f.FUNCTION_EXPRESSION),t.value=this.previous()}catch(n){throw n instanceof T?(t.value=n.partialNode,new T(n.token,this.nodeFactory.create(Te,t),n.handlerContext)):n}return this.nodeFactory.create(Te,t)}variable(){this.consume("Expect a variable",f.IDENTIFIER);const t=this.previous();return this.nodeFactory.create(ue,{variable:t})}canBeField(){return this.peek().kind===f.IDENTIFIER&&this.peek(1).kind===f.COLON}primaryExpression(){if(this.match(f.COLOR_LITERAL,f.STRING_LITERAL,f.NUMERIC_LITERAL))return this.nodeFactory.create(H,{expression:this.nodeFactory.create(je,{literal:this.previous()})});if(this.match(f.QUOTED_STRING,f.IDENTIFIER))return this.nodeFactory.create(H,{expression:this.nodeFactory.create(ue,{variable:this.previous()})});throw this.logError(this.peek(),l.UNEXPECTED_TOKEN,"Expect a variable or literal"),new T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const t={};if(this.check(f.COLON,f.RBRACKET,f.COMMA)){const n=this.peek();this.logError(n,l.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),t.name=this.nodeFactory.create(ie,{identifiers:[]})}else try{t.name=this.attributeName()}catch(n){if(!(n instanceof T))throw n;if(t.name=n.partialNode,!this.canHandle(n))throw new T(n.token,this.nodeFactory.create(ae,t),n.handlerContext);this.synchronizeAttributeName()}return this.match(f.COLON)&&(t.colon=this.previous(),t.value=this.attributeValue()),this.nodeFactory.create(ae,t)}attributeValue(){let t;try{t=this.peek().kind===f.IDENTIFIER&&this.peek(1).kind===f.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof T)||!this.canHandle(n))throw n;t=n.partialNode,this.synchronizeAttributeValue()}return t}attributeName(){const t=[];if(this.peek().kind!==f.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(f.COLON,f.COMMA,f.RBRACKET);)try{this.consume("Expect an identifier",f.IDENTIFIER),t.push(this.previous())}catch(n){throw n instanceof T?new T(n.token,this.nodeFactory.create(ie,{identifiers:t}),n.handlerContext):n}return this.nodeFactory.create(ie,{identifiers:t})}logError(t,n,r){this.errors.push(new c(n,r,t))}}const pl={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function dl(e){return pl[e.value]||{left:null,right:null}}const El={"+":{left:null,right:15},"-":{left:null,right:15},"<":{left:null,right:15},">":{left:null,right:15},"<>":{left:null,right:15},"!":{left:null,right:15}};function Nl(e){return El[e.value]||{left:null,right:null}}const Tl={"(":{left:14,right:null}};function Rn(e){return Tl[e.value]||{left:null,right:null}}var _=(e=>(e.Table="table",e.Enum="enum",e.Ref="ref",e.Note="note",e.Project="project",e.Indexes="indexes",e.TableGroup="tablegroup",e.TablePartial="tablepartial",e))(_||{}),N=(e=>(e.Color="color",e.HeaderColor="headercolor",e.Note="note",e.PK="pk",e.PKey="primary key",e.Unique="unique",e.Ref="ref",e.NotNull="not null",e.Null="null",e.Increment="increment",e.Default="default",e.Name="name",e.Type="type",e.Update="update",e.Delete="delete",e))(N||{});function Re(e){var n;const t=(n=e==null?void 0:e.type)==null?void 0:n.value.toLowerCase();switch(t){case _.Enum:case _.Table:case _.Indexes:case _.Note:case _.Project:case _.Ref:case _.TableGroup:case _.TablePartial:return new M(t);default:return new x}}function Fe(e){if(!Kt(e))return new M([e]);const t=Fe(e.leftExpression).unwrap_or(void 0);return t?(t.push(e.rightExpression),new M(t)):new x}function Y(e){if(e===void 0)return new x;const t=Fe(e).unwrap_or(void 0);if(!t)return new x;const n=[];for(const r of t){const s=z(r).unwrap_or(void 0);if(!s)return new x;n.push(s)}return new M(n)}function Je(e){if(e===void 0)return new x;const t=Fe(e).unwrap_or(void 0);if(!t||t.length===0)return new x;const n=[];let r;if(!X(F(t))){const s=t.pop();if(wr(s))r=s.elementList.map(i=>j(i).unwrap());else return new x}for(const s of t){const i=z(s).unwrap_or(void 0);if(!i)return new x;n.push(i)}return new M({variables:n,tupleElements:r})}function z(e){return X(e)?new M(e.expression.variable.value):new x}function ct(e){if(kn(e))return e instanceof Te?new M({functional:[e],nonFunctional:[]}):new M({functional:[],nonFunctional:[e]});if(e instanceof Ee&&e.elementList.every(kn)){const t=e.elementList.filter(r=>r instanceof Te),n=e.elementList.filter(X);return new M({functional:t,nonFunctional:n})}return new x}function j(e){var n;const t=(n=e==null?void 0:e.expression.variable)==null?void 0:n.value;return t===void 0?new x:new M(t)}function bl(e){var n,r;const t=(r=(n=e==null?void 0:e.partial)==null?void 0:n.variable)==null?void 0:r.value;return t===void 0?new x:new M(t)}function V(e){return q(e)?e.expression instanceof ue?new M(e.expression.variable.value):new M(e.expression.literal.value):new x}function ml(e){var t;return!(e instanceof de)||!Lr((t=e.op)==null?void 0:t.value)?!1:Je(e.leftExpression).and_then(()=>Je(e.rightExpression)).unwrap_or(void 0)!==void 0}function Il(e){const t=Je(e.leftExpression),n=Je(e.rightExpression);if(!t.isOk()||!n.isOk())return!1;const{tupleElements:r}=t.unwrap(),{tupleElements:s}=n.unwrap();return(r==null?void 0:r.length)===(s==null?void 0:s.length)}function kn(e){return e instanceof H&&e.expression instanceof ue||e instanceof Te}function Un(e,t){var s,i,a,o;let n=t;const r=Wo(e);for(;n;){if((i=(s=n.symbol)==null?void 0:s.symbolTable)!=null&&i.has(e))return(a=n.symbol.symbolTable)==null?void 0:a.get(e);if(((o=n.symbol)==null?void 0:o.declaration)instanceof te&&r)return n.symbol;if(n instanceof te)return;n=n.parent}}class gl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof te||Re(this.declarationNode.parent).unwrap_or(void 0)!==_.Project?[new c(l.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(t){return t?[new c(l.UNEXPECTED_NAME,"A Custom element shouldn't have a name",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof fe)return[new c(l.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",t)];const n=[];return q(t.callee)||n.push(new c(l.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",t)),t.args.length>0&&n.push(...t.args.map(r=>new c(l.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",r))),n}}class Xe{constructor(){this.table=new Map}has(t){return this.table.has(t)}set(t,n){this.table.set(t,n)}get(t,n){return this.table.get(t)||n!==void 0&&this.set(t,n)||n}entries(){return this.table.entries()}forEach(t){return this.table.forEach(t)}}class _l{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(t){return t?Ar(t)?[]:[new c(l.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",t)]:[new c(l.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}registerElement(){const t=[];this.declarationNode.symbol=this.symbolFactory.create(Yo,{declaration:this.declarationNode,symbolTable:new Xe});const{name:n}=this.declarationNode,r=Y(n);if(r.isOk()){const s=r.unwrap(),i=s.pop(),a=_t(s,this.publicSymbolTable,this.symbolFactory),o=Wt(i);a.has(o)&&t.push(new c(l.DUPLICATE_NAME,`Enum name ${i} already exists in schema '${s.join(".")||"public"}'`,n)),a.set(o,this.declarationNode.symbol)}return t}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.length===0?[new c(l.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:t.flatMap(n=>{const r=[];n.callee&&!X(n.callee)&&r.push(new c(l.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const s=[...n.args];return F(s)instanceof B?(r.push(...this.validateFieldSettings(F(s))),s.pop()):s[0]instanceof B&&(r.push(...this.validateFieldSettings(s[0])),s.shift()),s.length>0&&r.push(...s.map(i=>new c(l.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",i))),r.push(...this.registerField(n)),r})}validateFieldSettings(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"note":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",o))),a.forEach(o=>{q(o.value)||r.push(new c(l.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=Ht(n),s=this.symbolFactory.create(Qo,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}i.set(r,s)}return[]}}class Al{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){const t=new c(l.INVALID_INDEXES_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode);if(this.declarationNode.parent instanceof te)return[t];const n=Re(this.declarationNode.parent).unwrap_or(void 0);return n&&[_.Table,_.TablePartial].includes(n)?[]:[t]}validateName(t){return t?[new c(l.UNEXPECTED_NAME,"An Indexes shouldn't have a name",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[],s=[n.callee,...n.args];return F(s)instanceof B&&r.push(...this.validateFieldSetting(s.pop())),s.forEach(i=>{for(;i instanceof re;)i.argumentList&&!ct(i.argumentList).isOk()&&r.push(new c(l.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",i.argumentList)),i=i.callee;ct(i).isOk()||r.push(new c(l.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",i))}),r})}validateFieldSetting(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"note":case"name":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{q(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'${i}' must be a string`,o))});break;case"unique":case"pk":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{J(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'${i}' must not have a value`,o))});break;case"type":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,"'type' can only appear once",o))),a.forEach(o=>{X(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_INDEX_SETTING,`Unknown index setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Ll{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof te)&&![_.Table,_.TableGroup,_.TablePartial,_.Project].includes(Re(this.declarationNode.parent).unwrap_or(void 0))?[new c(l.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a TableGroup, a TablePartial or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(t){if(!(this.declarationNode.parent instanceof te))return t?[new c(l.UNEXPECTED_NAME,"A Note shouldn't have a name",t)]:[];if(!t)return[new c(l.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=Y(t);if(!n.isOk())return[new c(l.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const s=n.unwrap().join("."),i=Xo(s);return this.publicSymbolTable.has(i)?[new c(l.DUPLICATE_NAME,`Sticky note "${s}" has already been defined`,t)]:(this.publicSymbolTable.set(i,this.declarationNode.symbol),[])}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){const n=[];return t.length===0?[new c(l.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(t.length>1&&t.slice(1).forEach(r=>n.push(new c(l.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",r))),q(t[0].callee)||n.push(new c(l.INVALID_NOTE,"A Note content must be a quoted string",t[0])),t[0].args.length>0&&n.push(...t[0].args.map(r=>new c(l.INVALID_NOTE,"A Note can only contain one quoted string",r))),n)}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...n.map(s=>new c(l.INVALID_PROJECT_FIELD,"A Project can not have inline fields",s)),...this.validateSubElements(r)]}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class yl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof te?[]:[new c(l.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){if(t.length===0)return[new c(l.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return t.length>1&&n.push(...t.slice(1).map(r=>new c(l.REF_REDEFINED,"A Ref can only contain one binary relationship",r))),t.forEach(r=>{r.callee&&!ml(r.callee)&&n.push(new c(l.INVALID_REF_FIELD,"A Ref field must be a binary relationship",r.callee)),r.callee&&!Il(r.callee)&&n.push(new c(l.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",r.callee));const s=[...r.args];if(F(s)instanceof B){const i=this.validateFieldSettings(F(s));n.push(...i),s.pop()}else s[0]instanceof B&&(n.push(...this.validateFieldSettings(s[0])),s.shift());s.length>0&&n.push(...s.map(i=>new c(l.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",i)))}),n}validateFieldSettings(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"delete":case"update":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_REF_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{wl(o.value)||r.push(new c(l.INVALID_REF_SETTING_VALUE,`'${i}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,o))});break;case"color":a.length>1&&r.push(...a.map(o=>new c(l.DUPLICATE_REF_SETTING,"'color' can only appear once",o))),a.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_REF_SETTING_VALUE,"'color' must be a color literal",o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_REF_SETTING,`Unknown ref setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function wl(e){if(!(X(e)&&e.expression.variable.kind!==f.QUOTED_STRING)&&!(e instanceof ie))return!1;let t;if(e instanceof ie?t=Ce(e).unwrap_or(""):t=e.expression.variable.value,t)switch(t.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class Pl{constructor(t,n,r){this.declarationNode=t,this.symbolFactory=r,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(t){return t?t instanceof De?[new c(l.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",t)]:Ar(t)?[]:[new c(l.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",t)]:[new c(l.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(t){return t?Rl(t)?[]:[new c(l.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",t)]:[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Ke(s,(i,a)=>{switch(a){case N.HeaderColor:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",o.value||o.name))});break;case N.Note:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'note' can only appear once",o))),i.forEach(o=>{q(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'note' must be a string literal",o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)))}}),r}registerElement(){const t=[];this.declarationNode.symbol=this.symbolFactory.create(Ir,{declaration:this.declarationNode,symbolTable:new Xe});const{name:n,alias:r}=this.declarationNode,s=Y(n);if(s.isOk()){const i=[...s.unwrap()],a=i.pop(),o=_t(i,this.publicSymbolTable,this.symbolFactory),u=ot(a);o.has(u)&&t.push(new c(l.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${i.join(".")||"public"}'`,n)),o.set(u,this.declarationNode.symbol)}if(r&&We(r)&&!Sl(r.expression.variable.value,s.unwrap_or([]))){const i=j(r).unwrap(),a=ot(i);this.publicSymbolTable.has(a)&&t.push(new c(l.DUPLICATE_NAME,`Table name '${i}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return t}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",t)];const[n,r,s]=t.body.reduce((i,a)=>(a instanceof w?i[0].push(a):a instanceof xe?i[1].push(a):a instanceof P&&i[2].push(a),i),[[],[],[]]);return[...this.validateFields(n),...this.validateInjections(r),...this.validateSubElements(s)]}validateInjections(t){return t.flatMap(n=>this.registerInjection(n))}registerInjection(t){var o,u,p;if(!((u=(o=t.partial)==null?void 0:o.variable)!=null&&u.value))return[];const n=(p=t.partial.variable)==null?void 0:p.value,r=br(n),s=this.symbolFactory.create(el,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable,a=i.get(r);return a?[new c(l.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,t),new c(l.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,a.declaration)]:(i.set(r,s),[])}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[];n.args.length===0&&r.push(new c(l.INVALID_COLUMN,"A column must have a type",n.callee)),X(n.callee)||r.push(new c(l.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Pr(n.args[0])&&r.push(new c(l.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const s=n.args.slice(1);return r.push(...this.validateFieldSetting(s)),r.push(...this.registerField(n)),r})}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=It(n),s=this.symbolFactory.create(Qt,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}i.set(r,s)}return[]}validateFieldSetting(t){if(!t.slice(0,-1).every(ye)||!t.slice(-1).every(u=>ye(u)||u instanceof B))return[...t.map(u=>new c(l.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",u))];if(t.length===0)return[];let n;F(t)instanceof B&&(n=t.pop());const r=G(n),s=r.getErrors(),i=r.getValue();t.forEach(u=>{const p=j(u).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){s.push(new c(l.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",u));return}i[p]===void 0?i[p]=[u]:i[p].push(u)});const a=i[N.PK]||[],o=i[N.PKey]||[];return a.length>=1&&o.length>=1&&s.push(...[...a,...o].map(u=>new c(l.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",u))),Ke(i,(u,p)=>{switch(p){case N.Note:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"note can only appear once",h))),u.forEach(h=>{q(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",h.value||h.name))});break;case N.Ref:u.forEach(h=>{yr(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",h.value||h.name))});break;case N.PKey:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",h))),u.forEach(h=>{J(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",h.value||h.name))});break;case N.PK:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!J(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",h.value||h.name))});break;case N.NotNull:{u.length>1&&s.push(...u.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",d)));const h=i[N.Null]||[];u.length>=1&&h.length>=1&&s.push(...[...u,...h].map(d=>new c(l.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",d))),u.forEach(d=>{J(d.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",d.value||d.name))});break}case N.Null:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",h))),u.forEach(h=>{J(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",h.value||h.name))});break;case N.Unique:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!J(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",h.value||h.name))});break;case N.Increment:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!J(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",h.value||h.name))});break;case N.Default:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_TABLE_SETTING,"'default' can only appear once",h))),u.forEach(h=>{vr(h.value)||s.push(new c(l.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",h.value||h.name))});break;default:u.forEach(h=>s.push(new c(l.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,h)))}}),s}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())==="note"});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}}function Sl(e,t){return t.length===1&&e===t[0]}class Ol{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A TableGroup name must be a single identifier",t)]:[new c(l.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",t)]:[]}registerElement(){const{name:t}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Ko,{declaration:this.declarationNode,symbolTable:new Xe});const n=Y(t);if(n.isOk()){const r=n.unwrap(),s=r.pop(),i=_t(r,this.publicSymbolTable,this.symbolFactory),a=zt(s);if(i.has(a))return[new c(l.DUPLICATE_NAME,`TableGroup name '${s}' already exists`,t)];i.set(a,this.declarationNode.symbol)}return[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Ke(s,(i,a)=>{switch(a){case"color":i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'color' can only appear once",o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'color' must be a color literal",o.value||o.name))});break;case"note":i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'note' can only appear once",o))),i.filter(o=>!q(o.value)).forEach(o=>{r.push(new c(l.INVALID_TABLE_SETTING,"'note' must be a string literal",o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)));break}}),r}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{const r=[];return n.callee&&!Y(n.callee).isOk()&&r.push(new c(l.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&r.push(...n.args.map(s=>new c(l.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",s))),r})}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())==="note"});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=qt(n),s=this.symbolFactory.create(Jo,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,t),new c(l.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}i.set(r,s)}return[]}}const xl=["-","+"];class Dl{constructor(t,n,r){this.declarationNode=t,this.symbolFactory=r,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLE_PARTIAL_CONTEXT,"TablePartial must appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A TablePartial name must be an identifier or a quoted identifer",t)]:[new c(l.NAME_NOT_FOUND,"A TablePartial must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A TablePartial shouldn't have an alias",t)]:[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Ke(s,(i,a)=>{switch(a){case N.HeaderColor:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_PARTIAL_SETTING,`'${a}' can only appear once`,o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_PARTIAL_SETTING,`'${a}' must be a color literal`,o.value||o.name))});break;case N.Note:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_PARTIAL_SETTING,`'${a}' can only appear once`,o))),i.forEach(o=>{q(o.value)||r.push(new c(l.INVALID_TABLE_PARTIAL_SETTING,`'${a}' must be a string literal`,o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)))}}),r}registerElement(){const{name:t}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Zo,{declaration:this.declarationNode,symbolTable:new Xe});const n=Y(t);if(!n.isOk())return[];const r=n.unwrap(),s=r.pop(),i=_t(r,this.publicSymbolTable,this.symbolFactory),a=Yt(s);return i.has(a)?[new c(l.DUPLICATE_NAME,`TablePartial name '${s}' already exists`,t)]:(i.set(a,this.declarationNode.symbol),[])}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A TablePartial's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[];n.args.length===0&&r.push(new c(l.INVALID_COLUMN,"A column must have a type",n.callee)),X(n.callee)||r.push(new c(l.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Pr(n.args[0])&&r.push(new c(l.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const s=n.args.slice(1);return r.push(...this.validateFieldSetting(s),...this.registerField(n)),r})}registerField(t){if(!t.callee||!X(t.callee))return[];const n=j(t.callee).unwrap(),r=It(n),s=this.symbolFactory.create(Qt,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}return i.set(r,s),[]}validateFieldSetting(t){const n=F(t);if(!t.slice(0,-1).every(ye)||!(ye(n)||n instanceof B))return[...t.map(p=>new c(l.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(t.length===0)return[];let r;F(t)instanceof B&&(r=t.pop());const s=G(r),i=s.getErrors(),a=s.getValue();t.forEach(p=>{const h=j(p).unwrap_or("").toLowerCase();if(h!==N.PK&&h!==N.Unique){i.push(new c(l.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));return}a[h]===void 0?a[h]=[p]:a[h].push(p)});const o=a[N.PK]||[],u=a[N.PKey]||[];return o.length>=1&&u.length>=1&&i.push(...[...o,...u].map(p=>new c(l.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p))),Ke(a,(p,h)=>{switch(h){case N.Note:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{q(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a quoted string`,d.value||d.name))});break;case N.Ref:p.forEach(d=>{yr(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a valid unary relationship`,d.value||d.name))});break;case N.PKey:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{J(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.PK:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!J(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.NotNull:{p.length>1&&i.push(...p.map(E=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,E)));const d=a[N.Null]||[];p.length>=1&&d.length>=1&&i.push(...[...p,...d].map(E=>new c(l.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",E))),p.forEach(E=>{J(E.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,E.value||E.name))});break}case N.Null:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{J(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Unique:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!J(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Increment:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!J(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Default:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{vr(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a string literal, number literal, function expression, true, false or null`,d.value||d.name))});break;default:p.forEach(d=>i.push(new c(l.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${h}'`,d)))}}),i}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())===_.Note});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}}function ge(e){switch(e.type.value.toLowerCase()){case _.Enum:return _l;case _.Table:return Pl;case _.TableGroup:return Ol;case _.Project:return vl;case _.Ref:return yl;case _.Note:return Ll;case _.Indexes:return Al;case _.TablePartial:return Dl;default:return gl}}function Ar(e){return!!Y(e).unwrap_or(!1)}function Rl(e){return We(e)}function We(e){return e instanceof H&&e.expression instanceof ue}function _t(e,t,n){var s;e[0]==="public"&&(e=e.slice(1));let r=t;for(const i of e){let a;const o=Xt(i);if(r.has(o)){if(a=(s=r.get(o))==null?void 0:s.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new Xe;const u=n.create(mr,{symbolTable:a});r.set(o,u)}r=a}return r}function Lr(e){return e==="-"||e==="<>"||e===">"||e==="<"}function At(e){var n;if(!(e instanceof H)||!(e.expression instanceof je)||((n=e.expression.literal)==null?void 0:n.kind)!==f.COLOR_LITERAL)return!1;const t=e.expression.literal.value;if(t.length!==4&&t.length!==7||t[0]!=="#")return!1;for(let r=1;r<t.length;r+=1)if(!sl(t[r]))return!1;return!0}function J(e){return e===void 0}function vr(e){var t;return!!(q(e)||ke(e)||ye(e)&&["true","false","null"].includes(e.expression.variable.value.toLowerCase())||e instanceof ne&&xl.includes((t=e.op)==null?void 0:t.value)&&ke(e.expression)||e instanceof Te)}function ke(e){var t,n,r;return e instanceof ne?((t=e.op)==null?void 0:t.value)!=="-"&&((n=e.op)==null?void 0:n.value)!=="+"?!1:ke(e.expression):e instanceof H&&e.expression instanceof je&&((r=e.expression.literal)==null?void 0:r.kind)===f.NUMERIC_LITERAL}function yr(e){var n;if(!(e instanceof ne)||!Lr((n=e.op)==null?void 0:n.value))return!1;const t=Y(e.expression).unwrap_or(void 0);return t!==void 0&&t.length>0}function wr(e){return e instanceof Ee&&e.elementList.every(X)}function Pr(e){if(!(e instanceof re||Kt(e)||e instanceof H||e instanceof De))return!1;if(e instanceof re){if(e.callee===void 0||e.argumentList===void 0||!e.argumentList.elementList.every(n=>ke(n)||q(n)||ye(n)))return!1;e=e.callee}for(;e instanceof De;){if(e.array===void 0||e.indexer===void 0||!e.indexer.elementList.every(n=>!n.colon&&!n.value&&ke(n.name)))return!1;e=e.array}const t=Y(e).unwrap_or(void 0);return t!==void 0&&t.length>0}function G(e){var r;const t={},n=[];if(!e)return new ee({});for(const s of e.elementList){if(!s.name)continue;if(s.name instanceof H){n.push(new c(l.INVALID_SETTINGS,"A setting name must be a stream of identifiers",s.name));continue}const i=(r=Ce(s.name).unwrap_or(void 0))==null?void 0:r.toLowerCase();i&&(t[i]===void 0?t[i]=[s]:t[i].push(s))}return new ee(t,n)}class Mn{constructor(t,n){this.ast=t,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(mr,{symbolTable:new Xe}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const t=[];this.ast.body.forEach(r=>{if(r.parent=this.ast,r.type===void 0)return;const s=ge(r),i=new s(r,this.publicSchemaSymbol.symbolTable,this.symbolFactory);t.push(...i.validate())});const n=this.ast.body.filter(r=>Re(r).unwrap_or(void 0)===_.Project);return n.length>1&&n.forEach(r=>t.push(new c(l.PROJECT_REDEFINED,"Only one project can exist",r))),new ee(this.ast,t)}}class _e{constructor(t,n){this.declarationNode=t,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(t,n){t&&t.elementList.forEach(r=>{if(r.name instanceof H)return;const s=Ce(r.name).unwrap_or(void 0);if(!s)return;const i=n[s.toLowerCase()];i!=null&&i.shouldBind&&this.scanAndBind(r.value,i)})}bindBody(){const t=this.declarationNode;if(!t.body)return;const{body:n}=t;n instanceof fe?n.body.forEach(r=>{if(r instanceof P){if(!r.type||Re(this.declarationNode).unwrap_or(null)===_.TablePartial&&Re(r).unwrap_or(null)===_.Indexes)return;const s=Sr(r);new s(r,this.errors).bind()}else r instanceof w?this.bindSubfield(r):this.bindPartialInjection(r)}):this.bindSubfield(n)}bindSubfield(t){const n=[t.callee,...t.args],r=F(n);r instanceof B&&(n.pop(),this.bindSettingList(r,this.subfield.settingList));const{argBinderRules:s}=this.subfield.arg;for(let i=0;i<Math.min(n.length,s.length);i+=1)s[i].shouldBind&&this.scanAndBind(n[i],s[i])}bindPartialInjection(t){var n;(n=this.injectionBinderRule)!=null&&n.shouldBind&&this.scanAndBind(t,this.injectionBinderRule)}scanAndBind(t,n){var r,s;if(t)if(t instanceof H){if(t.expression instanceof ue&&((s=n.keywords)!=null&&s.includes((r=t.expression.variable)==null?void 0:r.value.toLowerCase())))return;this.bindFragments([t],n)}else t instanceof de?Kt(t)?this.bindFragments(Fe(t).unwrap_or([]),n):(this.scanAndBind(t.leftExpression,n),this.scanAndBind(t.rightExpression,n)):t instanceof ne?this.scanAndBind(t.expression,n):t instanceof mt?this.scanAndBind(t.expression,n):t instanceof Ee?t.elementList.forEach(i=>this.scanAndBind(i,n)):t instanceof xe&&this.bindFragments([t],n)}bindFragments(t,n){if(t.length===0)return;const r=t.length===1&&t[0]instanceof xe,s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,a=r?-1:t.findIndex(E=>!X(E)),u=a!==-1&&wr(t[a])?t[a]:void 0,p=a>=0?s.pop():void 0,h=t.slice(0,a===-1?void 0:a);if(h.length===0)return;const d=[];for(;s.length&&h.length;){const E=s.pop(),b=h.pop(),A=j(b).unwrap();d.unshift({index:st(A,E),referrer:b})}for(;h.length;){const E=h.pop(),b=r?bl(E).unwrap():j(E).unwrap();d.unshift({index:st(b,i),referrer:E})}return u?u.elementList.forEach(E=>this.resolveIndexStack([...d,{index:st(j(E).unwrap(),p),referrer:E}],n.ignoreNameNotFound)):this.resolveIndexStack(d,n.ignoreNameNotFound)}resolveIndexStack(t,n){if(t.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[r,...s]=t,i=Un(r.index,this.declarationNode);if(i===void 0){const{kind:p,name:h}=oe(r.index).unwrap();this.logError(r.referrer,`Can not find ${p} '${h}'`,n);return}i.references.push(r.referrer),r.referrer.referee=i;let a=i.symbolTable,{kind:o,name:u}=oe(r.index).unwrap();for(const p of s){const{kind:h,name:d}=oe(p.index).unwrap(),E=a.get(p.index);if(!E){this.logError(p.referrer,`${o} '${u}' does not have ${h} '${d}'`,n);return}if(o=h,u=d,p.referrer.referee=E,E.references.push(p.referrer),!E.symbolTable)break;a=E.symbolTable}}logError(t,n,r){r||this.errors.push(new c(l.BINDING_ERROR,n,t))}resolveInjections(t){var s;const n=(s=this.declarationNode.symbol)==null?void 0:s.symbolTable;if(!n)return;const r=new Map;n.forEach((i,a)=>{var p,h;if(!Ho(a))return;const o=Un(zo(a),this.declarationNode),u=(h=(p=o==null?void 0:o.declaration)==null?void 0:p.symbol)==null?void 0:h.symbolTable;u&&u.forEach((d,E)=>{n.has(E)||r.set(E,{injectorFieldSymbol:d,injectorDeclaration:i.declaration})})}),r.forEach((i,a)=>{const o=rl(i.injectorFieldSymbol);if(!o)return;const u=t.create(o,i);n.set(a,u)})}}class kl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Ul extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Ml extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Fl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Gl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={},this.injectionBinderRule={shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}}}class Cl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class $l extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}function Sr(e){switch(e.type.value.toLowerCase()){case _.Enum:return Ul;case _.Table:return Vl;case _.TableGroup:return Cl;case _.Project:return Bl;case _.Ref:return Gl;case _.Note:return Fl;case _.Indexes:return Ml;case _.TablePartial:return $l;default:return kl}}class jl{constructor(t){this.ast=t,this.errors=[]}resolve(t){return this.ast.body.map(n=>{if(!n.type)return null;const r=Sr(n),s=new r(n,this.errors);return s.resolveInjections(t),s}).forEach(n=>n==null?void 0:n.bind()),new ee(this.ast,this.errors)}}class Xl{constructor(t){this.generator=t}create(t,n){return new t(n,this.generator.nextId())}}class Wl{constructor(t,n){this.ast=t,this.symbolFactory=new Xl(n)}analyze(){return new Mn(this.ast,this.symbolFactory).validate().chain(n=>new jl(n).resolve(this.symbolFactory))}validate(){return new Mn(this.ast,this.symbolFactory).validate().chain(n=>new ee(n,[]))}}function Fn(e,t){const{variables:n,tupleElements:r}=Je(e).unwrap();return r?n.length===0?{schemaName:t.schemaName,tableName:t.name,fieldNames:r}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:r}:n.length===1?{schemaName:t.schemaName,tableName:t.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function Or(e){switch(e){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"];default:throw new Error("Invalid relation op")}}function L(e){return{start:{offset:e.startPos.offset,line:e.startPos.line+1,column:e.startPos.column+1},end:{offset:e.endPos.offset,line:e.endPos.line+1,column:e.endPos.column+1}}}function ut(e){var n;const t=(n=Fe(e).unwrap_or(void 0))==null?void 0:n.pop();return t instanceof Ee?t.elementList.map(r=>r.referee):[t.referee]}function Be(e){const t=Y(e).unwrap();return{name:t.pop(),schemaName:t}}function et(e){return e.expression.literal.value}function xr(e,t){if(Array.isArray(e)){const s=e.map(({id:a})=>a).sort().join(","),i=t.map(({id:a})=>a).sort().join(",");return s<i?`${s}-${i}`:`${i}-${s}`}const n=e.id.toString(),r=t.id.toString();return n<r?`${n}-${r}`:`${r}-${n}`}function Jt(e,t){if(Array.isArray(e)){const s=e.map(({id:a})=>a).sort(),i=t.map(({id:a})=>a).sort();return Rt(s,i).every(([a,o])=>a===o)}const n=e.id,r=t.id;return n===r}function le(e){const t=e.split(`
9
+ `;case"\\":return"\\";case"r":return"\r";case"'":return"'";case'"':return'"';case"0":return"\0";case"b":return"\b";case"v":return"\v";case"f":return"\f";case" ":return"\\ ";case"u":{let n="";for(let r=0;r<=3;r+=1){if(this.isAtEnd()||!Ge(this.peek()))return this.errors.push(new c(l.INVALID_ESCAPE_SEQUENCE,`Invalid unicode escape sequence '\\u${n}', only unicode escape sequences of the form '\\uHHHH' where H is a hexadecimal number are allowed`,z.create(f.STRING_LITERAL,t,this.current,`\\u${n}`,!0))),`\\u${n}`;n+=this.advance()}return String.fromCharCode(parseInt(n,16))}default:return this.text[this.current.offset-1]}}}var it=(e=>(e[e.ListExpression=0]="ListExpression",e[e.GroupExpression=1]="GroupExpression",e[e.BlockExpression=2]="BlockExpression",e))(it||{});class ul{constructor(){this.stack=[],this.numberOfNestedLParens=0,this.numberOfNestedLBrackets=0,this.numberOfNestedLBraces=0}push(t){this.stack.push(t),t===0&&(this.numberOfNestedLBrackets+=1),t===1&&(this.numberOfNestedLParens+=1),t===2&&(this.numberOfNestedLBraces+=1)}pop(){const t=this.stack.pop();return t===0&&(this.numberOfNestedLBrackets-=1),t===1&&(this.numberOfNestedLParens-=1),t===2&&(this.numberOfNestedLBraces-=1),t}top(){return F(this.stack)}isWithinGroupExpressionContext(){return this.numberOfNestedLParens>0}isWithinListExpressionContext(){return this.numberOfNestedLBrackets>0}isWithinBlockExpressionContext(){return this.numberOfNestedLBraces>0}withContextDo(t,n){return()=>{this.push(t);try{return n()}finally{this.pop()}}}findHandlerContext(t,n){if(!(this.numberOfNestedLBraces<=0&&this.numberOfNestedLBrackets<=0&&this.numberOfNestedLParens<=0))for(let r=n;r<t.length-1;r+=1)switch(t[r].kind){case f.COMMA:if(this.isWithinGroupExpressionContext()||this.isWithinListExpressionContext())return[...this.stack].reverse().find(i=>[1,0].includes(i));break;case f.RPAREN:if(this.isWithinGroupExpressionContext())return 1;break;case f.RBRACE:if(this.isWithinBlockExpressionContext())return 2;break;case f.RBRACKET:if(this.isWithinListExpressionContext())return 0;break}}}class hl{constructor(t){this.generator=t}create(t,n){return new t(n,this.generator.nextId())}}class T{constructor(t,n,r){this.token=t,this.partialNode=n,this.handlerContext=r}}class fl{constructor(t,n){this.current=0,this.errors=[],this.contextStack=new ul,this.synchronizeProgram=()=>{const r=this.peek();r.kind!==f.EOF?g(this.advance()):(g(this.peek()),this.logError(r,l.UNEXPECTED_EOF,"Unexpected EOF"))},this.synchronizeElementDeclarationName=()=>{for(;!this.isAtEnd();){const r=this.peek();if(Mt(r)||this.check(f.COLON,f.LBRACE,f.LBRACKET))break;g(r),this.advance()}},this.synchronizeElementDeclarationAlias=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COLON,f.LBRACE,f.LBRACKET))break;g(r),this.advance()}},this.blockExpression=this.contextStack.withContextDo(it.BlockExpression,()=>{const r={body:[]},s=()=>this.nodeFactory.create(fe,r);try{this.consume("Expect an opening brace '{'",f.LBRACE),r.blockOpenBrace=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.blockOpenBrace=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}for(;!this.isAtEnd()&&!this.check(f.RBRACE);)try{if(this.match(f.TILDE)){const i=this.previous(),a=this.variable(),o=this.nodeFactory.create(xe,{op:i,partial:a});r.body.push(o)}else r.body.push(this.canBeField()?this.fieldDeclaration():this.expression())}catch(i){if(!(i instanceof T))throw i;if(r.body.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}try{this.consume("Expect a closing brace '}'",f.RBRACE),r.blockCloseBrace=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.blockCloseBrace=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeBlock()}return s()}),this.synchronizeBlock=()=>{if(!this.check(f.RBRACE))for(g(this.advance());!this.isAtEnd();){const r=this.peek();if(this.check(f.RBRACE)||On(this.previous(),r))break;g(r),this.advance()}},this.tupleExpression=this.contextStack.withContextDo(it.GroupExpression,()=>{const r={elementList:[],commaList:[]},s=()=>this.nodeFactory.create(jt,{groupOpenParen:r.tupleOpenParen,groupCloseParen:r.tupleCloseParen,expression:r.elementList[0]}),i=()=>this.nodeFactory.create(Ee,r);try{this.consume("Expect an opening parenthesis '('",f.LPAREN),r.tupleOpenParen=this.previous()}catch(a){if(!(a instanceof T))throw a;if(r.tupleOpenParen=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}if(!this.isAtEnd()&&!this.check(f.RPAREN))try{r.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof T))throw a;if(r.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,s(),a.handlerContext);this.synchronizeTuple()}for(;!this.isAtEnd()&&!this.check(f.RPAREN);)try{this.consume("Expect a comma ','",f.COMMA),r.commaList.push(this.previous()),r.elementList.push(this.normalExpression())}catch(a){if(!(a instanceof T))throw a;if(a.partialNode instanceof D&&r.elementList.push(a.partialNode),!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}try{this.consume("Expect a closing parenthesis ')'",f.RPAREN),r.tupleCloseParen=this.previous()}catch(a){if(!(a instanceof T))throw a;if(r.tupleCloseParen=a.partialNode,!this.canHandle(a))throw new T(a.token,i(),a.handlerContext);this.synchronizeTuple()}return r.elementList.length===1?s():i()}),this.synchronizeTuple=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.RPAREN,f.COMMA))break;g(r),this.advance()}},this.listExpression=this.contextStack.withContextDo(it.ListExpression,()=>{const r={elementList:[],commaList:[]},s=()=>this.nodeFactory.create(B,r);try{this.consume("Expect an opening bracket '['",f.LBRACKET),r.listOpenBracket=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.listOpenBracket=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}if(!this.isAtEnd()&&!this.check(f.RBRACKET))try{r.elementList.push(this.attribute())}catch(i){if(!(i instanceof T))throw i;if(r.elementList.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}for(;!this.isAtEnd()&&!this.check(f.RBRACKET);)try{this.consume("Expect a comma ','",f.COMMA),r.commaList.push(this.previous()),r.elementList.push(this.attribute())}catch(i){if(!(i instanceof T))throw i;if(i.partialNode instanceof D&&r.elementList.push(i.partialNode),!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}try{this.consume("Expect a closing bracket ']'",f.RBRACKET),r.listCloseBracket=this.previous()}catch(i){if(!(i instanceof T))throw i;if(r.listCloseBracket=i.partialNode,!this.canHandle(i))throw new T(i.token,s(),i.handlerContext);this.synchronizeList()}return s()}),this.synchronizeList=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET))break;g(r),this.advance()}},this.synchronizeAttributeName=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET,f.COLON))break;g(r),this.advance()}},this.synchronizeAttributeValue=()=>{for(;!this.isAtEnd();){const r=this.peek();if(this.check(f.COMMA,f.RBRACKET))break;g(r),this.advance()}},this.tokens=t,this.nodeFactory=new hl(n)}isAtEnd(){return this.current>=this.tokens.length||this.tokens[this.current].kind===f.EOF}advance(){return this.isAtEnd()?F(this.tokens):this.tokens[this.current++]}peek(t=0){return t+this.current>=this.tokens.length?F(this.tokens):this.tokens[this.current+t]}match(...t){const n=this.check(...t);return n&&this.advance(),n}check(...t){const n=this.peek();return t.includes(n.kind)}previous(){return this.tokens[this.current-1]}canHandle(t){return t.handlerContext===void 0||t.handlerContext===this.contextStack.top()}consume(t,...n){if(!this.match(...n))throw this.logError(this.peek(),l.UNEXPECTED_TOKEN,t),new T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}discardUntil(t,...n){if(this.isAtEnd()||!this.check(...n)){for(g(this.peek()),this.logError(this.advance(),l.UNEXPECTED_TOKEN,t);!this.isAtEnd()&&!this.check(...n);)g(this.advance());return!this.isAtEnd()}return!0}gatherInvalid(){const t=[],n=[];let r,s=0;for(;s<this.tokens.length&&this.tokens[s].isInvalid;s+=1)n.push(this.tokens[s]);for(r=this.tokens[s],r.leadingInvalid=n,t.push(r),s+=1;s<this.tokens.length;s+=1){const i=this.tokens[s];i.isInvalid?r.trailingInvalid.push(i):(r=i,t.push(r))}this.tokens=t}parse(){const t=this.program(),n=this.advance(),r=this.nodeFactory.create(ee,{body:t,eof:n});return this.gatherInvalid(),new te({ast:r,tokens:this.tokens},this.errors)}program(){const t=[];for(;!this.isAtEnd();)try{const n=this.elementDeclaration();t.push(n)}catch(n){if(!(n instanceof T))throw n;t.push(n.partialNode),this.synchronizeProgram()}return t}elementDeclaration(){const t={},n=()=>this.nodeFactory.create(P,t);try{this.consume("Expect an identifier",f.IDENTIFIER),t.type=this.previous()}catch(r){throw r instanceof T?(t.type=r.partialNode,new T(r.token,n(),r.handlerContext)):r}if(!this.check(f.COLON,f.LBRACE,f.LBRACKET))try{t.name=this.normalExpression()}catch(r){if(!(r instanceof T))throw r;if(t.name=r.partialNode,!this.canHandle(r))throw new T(r.token,n(),r.handlerContext);this.synchronizeElementDeclarationName()}if(Mt(this.peek()))if(t.as=this.advance(),this.check(f.COLON,f.LBRACE,f.LBRACKET))this.logError(this.peek(),l.UNEXPECTED_TOKEN,"Expect an alias");else try{t.alias=this.normalExpression()}catch(r){if(!(r instanceof T))throw r;if(t.alias=r.partialNode,!this.canHandle(r))throw new T(r.token,n(),r.handlerContext);this.synchronizeElementDeclarationAlias()}try{t.attributeList=this.check(f.LBRACKET)?this.listExpression():void 0}catch(r){throw r instanceof T?(t.attributeList=r.partialNode,new T(r.token,n(),r.handlerContext)):r}if(!this.discardUntil("Expect an opening brace '{' or a colon ':'",f.LBRACE,f.COLON))return n();try{if(this.match(f.COLON)){t.bodyColon=this.previous();const r=this.expression();r instanceof P?(g(r),this.logError(r,l.UNEXPECTED_ELEMENT_DECLARATION,"An element's simple body must not be an element declaration")):t.body=r}else t.body=this.blockExpression()}catch(r){throw r instanceof T?(t.body=r.partialNode,new T(r.token,n(),r.handlerContext)):r}return this.nodeFactory.create(P,t)}fieldDeclaration(){const t={},n=()=>this.nodeFactory.create(P,t);try{this.consume("Expect an identifier",f.IDENTIFIER),t.type=this.previous()}catch(r){throw r instanceof T?(t.type=r.partialNode,new T(r.token,n(),r.handlerContext)):r}try{this.consume("Expect a colon ':'",f.COLON),t.bodyColon=this.previous()}catch(r){throw r instanceof T?(t.bodyColon=r.partialNode,new T(r.token,n(),r.handlerContext)):r}try{const r=this.expression();r instanceof P?this.errors.push(new c(l.INVALID_ELEMENT_IN_SIMPLE_BODY,"Simple body cannot be an element declaration",r)):t.body=r}catch(r){throw r instanceof T?(t.body=r.partialNode,new T(r.token,n(),r.handlerContext)):r}return this.nodeFactory.create(P,t)}expression(){const t={args:[]},n=()=>il(t.callee,t.args,this.nodeFactory).unwrap_or(this.nodeFactory.create(w,t));try{t.callee=this.normalExpression()}catch(s){throw s instanceof T?(t.callee=s.partialNode,new T(s.token,n(),s.handlerContext)):s}if(this.shouldStopExpression())return n();let r=t.callee;for(;!this.shouldStopExpression();){kt(this.previous())||this.logError(r,l.MISSING_SPACES,"Expect a following space");try{r=this.normalExpression(),t.args.push(r)}catch(s){throw s instanceof T?(r=s.partialNode,t.args.push(r),new T(s.token,n(),s.handlerContext)):s}}return n()}shouldStopExpression(){if(this.isAtEnd()||dr(this.previous()))return!0;const t=this.peek().kind;return t===f.RBRACE||t===f.RBRACKET||t===f.RPAREN||t===f.COMMA||t===f.COLON}normalExpression(){return this.expression_bp(0)}expression_bp(t){let n=this.leftExpression_bp();for(;!this.isAtEnd();){const r=this.peek();if(r.kind===f.LPAREN){const{left:s}=Rn(r);if(s<t||On(this.previous(),r)&&!this.contextStack.isWithinGroupExpressionContext()&&!this.contextStack.isWithinListExpressionContext())break;try{n=this.nodeFactory.create(re,{callee:n,argumentList:this.tupleExpression()})}catch(i){throw i instanceof T?(n=this.nodeFactory.create(re,{callee:n,argumentList:i.partialNode}),new T(i.token,n,i.handlerContext)):i}}else if(r.kind===f.LBRACKET){if(kt(this.previous()))break;try{n=this.nodeFactory.create(De,{expression:n,indexer:this.listExpression()})}catch(s){throw s instanceof T?(n=this.nodeFactory.create(De,{expression:n,indexer:s.partialNode}),new T(s.token,n,s.handlerContext)):s}}else if(Sn(r)){const s=r,i=Rn(s);if(i.left!==null){if(i.left<=t)break;this.advance(),n=this.nodeFactory.create(mt,{expression:n,op:s})}else{const a=dl(s);if(a.left===null||a.left<=t)break;this.advance();try{n=this.nodeFactory.create(de,{leftExpression:n,op:s,rightExpression:s.value==="."?this.extractOperand():this.expression_bp(a.right)})}catch(o){throw o instanceof T?(n=this.nodeFactory.create(de,{leftExpression:n,op:s,rightExpression:o.partialNode}),new T(o.token,n,o.handlerContext)):o}}}else break}return n}leftExpression_bp(){let t;if(Sn(this.peek())){const n={};n.op=this.peek();const r=Nl(n.op);if(r.right===null)throw this.logError(n.op,l.UNKNOWN_PREFIX_OP,`Unexpected '${n.op.value}' in an expression`),new T(n.op,this.nodeFactory.create(rt,{pre:n.op}),this.contextStack.findHandlerContext(this.tokens,this.current));this.advance();try{n.expression=this.expression_bp(r.right)}catch(s){throw s instanceof T?(n.expression=s.partialNode,new T(s.token,this.nodeFactory.create(ne,n),s.handlerContext)):s}t=this.nodeFactory.create(ne,n)}else if(t=this.extractOperand(),t instanceof rt)throw new T(this.peek(),this.nodeFactory.create(rt,{pre:this.peek()}),this.contextStack.findHandlerContext(this.tokens,this.current));return t}extractOperand(){return this.check(f.NUMERIC_LITERAL,f.STRING_LITERAL,f.COLOR_LITERAL,f.QUOTED_STRING,f.IDENTIFIER)?this.primaryExpression():this.check(f.FUNCTION_EXPRESSION)?this.functionExpression():this.check(f.LBRACKET)?this.listExpression():this.check(f.LBRACE)?this.blockExpression():this.check(f.LPAREN)?this.tupleExpression():(this.peek().kind===f.EOF?this.logError(this.peek(),l.UNEXPECTED_EOF,"Unexpected EOF"):this.logError(this.peek(),l.INVALID_OPERAND,`Invalid start of operand "${this.peek().value}"`),this.nodeFactory.create(rt,{pre:this.previous()}))}functionExpression(){const t={};try{this.consume("Expect a function expression",f.FUNCTION_EXPRESSION),t.value=this.previous()}catch(n){throw n instanceof T?(t.value=n.partialNode,new T(n.token,this.nodeFactory.create(Te,t),n.handlerContext)):n}return this.nodeFactory.create(Te,t)}variable(){this.consume("Expect a variable",f.IDENTIFIER);const t=this.previous();return this.nodeFactory.create(ue,{variable:t})}canBeField(){return this.peek().kind===f.IDENTIFIER&&this.peek(1).kind===f.COLON}primaryExpression(){if(this.match(f.COLOR_LITERAL,f.STRING_LITERAL,f.NUMERIC_LITERAL))return this.nodeFactory.create(H,{expression:this.nodeFactory.create(je,{literal:this.previous()})});if(this.match(f.QUOTED_STRING,f.IDENTIFIER))return this.nodeFactory.create(H,{expression:this.nodeFactory.create(ue,{variable:this.previous()})});throw this.logError(this.peek(),l.UNEXPECTED_TOKEN,"Expect a variable or literal"),new T(this.peek(),void 0,this.contextStack.findHandlerContext(this.tokens,this.current))}attribute(){const t={};if(this.check(f.COLON,f.RBRACKET,f.COMMA)){const n=this.peek();this.logError(n,l.EMPTY_ATTRIBUTE_NAME,"Expect a non-empty attribute name"),t.name=this.nodeFactory.create(ie,{identifiers:[]})}else try{t.name=this.attributeName()}catch(n){if(!(n instanceof T))throw n;if(t.name=n.partialNode,!this.canHandle(n))throw new T(n.token,this.nodeFactory.create(ae,t),n.handlerContext);this.synchronizeAttributeName()}return this.match(f.COLON)&&(t.colon=this.previous(),t.value=this.attributeValue()),this.nodeFactory.create(ae,t)}attributeValue(){let t;try{t=this.peek().kind===f.IDENTIFIER&&this.peek(1).kind===f.IDENTIFIER?this.attributeName():this.normalExpression()}catch(n){if(!(n instanceof T)||!this.canHandle(n))throw n;t=n.partialNode,this.synchronizeAttributeValue()}return t}attributeName(){const t=[];if(this.peek().kind!==f.IDENTIFIER)return this.primaryExpression();for(;!this.isAtEnd()&&!this.check(f.COLON,f.COMMA,f.RBRACKET);)try{this.consume("Expect an identifier",f.IDENTIFIER),t.push(this.previous())}catch(n){throw n instanceof T?new T(n.token,this.nodeFactory.create(ie,{identifiers:t}),n.handlerContext):n}return this.nodeFactory.create(ie,{identifiers:t})}logError(t,n,r){this.errors.push(new c(n,r,t))}}const pl={"+":{left:9,right:10},"*":{left:11,right:12},"-":{left:9,right:10},"/":{left:11,right:12},"%":{left:11,right:12},"<":{left:7,right:8},"<=":{left:7,right:8},">":{left:7,right:8},">=":{left:7,right:8},"<>":{left:7,right:8},"=":{left:2,right:3},"==":{left:4,right:5},"!=":{left:4,right:5},".":{left:16,right:17}};function dl(e){return pl[e.value]||{left:null,right:null}}const El={"+":{left:null,right:15},"-":{left:null,right:15},"<":{left:null,right:15},">":{left:null,right:15},"<>":{left:null,right:15},"!":{left:null,right:15}};function Nl(e){return El[e.value]||{left:null,right:null}}const Tl={"(":{left:14,right:null}};function Rn(e){return Tl[e.value]||{left:null,right:null}}var _=(e=>(e.Table="table",e.Enum="enum",e.Ref="ref",e.Note="note",e.Project="project",e.Indexes="indexes",e.TableGroup="tablegroup",e.TablePartial="tablepartial",e))(_||{}),N=(e=>(e.Color="color",e.HeaderColor="headercolor",e.Note="note",e.PK="pk",e.PKey="primary key",e.Unique="unique",e.Ref="ref",e.NotNull="not null",e.Null="null",e.Increment="increment",e.Default="default",e.Name="name",e.Type="type",e.Update="update",e.Delete="delete",e))(N||{});function Re(e){var n;const t=(n=e==null?void 0:e.type)==null?void 0:n.value.toLowerCase();switch(t){case _.Enum:case _.Table:case _.Indexes:case _.Note:case _.Project:case _.Ref:case _.TableGroup:case _.TablePartial:return new M(t);default:return new x}}function Fe(e){if(!Qt(e))return new M([e]);const t=Fe(e.leftExpression).unwrap_or(void 0);return t?(t.push(e.rightExpression),new M(t)):new x}function K(e){if(e===void 0)return new x;const t=Fe(e).unwrap_or(void 0);if(!t)return new x;const n=[];for(const r of t){const s=q(r).unwrap_or(void 0);if(!s)return new x;n.push(s)}return new M(n)}function Je(e){if(e===void 0)return new x;const t=Fe(e).unwrap_or(void 0);if(!t||t.length===0)return new x;const n=[];let r;if(!X(F(t))){const s=t.pop();if(wr(s))r=s.elementList.map(i=>j(i).unwrap());else return new x}for(const s of t){const i=q(s).unwrap_or(void 0);if(!i)return new x;n.push(i)}return new M({variables:n,tupleElements:r})}function q(e){return X(e)?new M(e.expression.variable.value):new x}function ct(e){if(kn(e))return e instanceof Te?new M({functional:[e],nonFunctional:[]}):new M({functional:[],nonFunctional:[e]});if(e instanceof Ee&&e.elementList.every(kn)){const t=e.elementList.filter(r=>r instanceof Te),n=e.elementList.filter(X);return new M({functional:t,nonFunctional:n})}return new x}function j(e){var n;const t=(n=e==null?void 0:e.expression.variable)==null?void 0:n.value;return t===void 0?new x:new M(t)}function bl(e){var n,r;const t=(r=(n=e==null?void 0:e.partial)==null?void 0:n.variable)==null?void 0:r.value;return t===void 0?new x:new M(t)}function V(e){return Y(e)?e.expression instanceof ue?new M(e.expression.variable.value):new M(e.expression.literal.value):new x}function ml(e){var t;return!(e instanceof de)||!Lr((t=e.op)==null?void 0:t.value)?!1:Je(e.leftExpression).and_then(()=>Je(e.rightExpression)).unwrap_or(void 0)!==void 0}function Il(e){const t=Je(e.leftExpression),n=Je(e.rightExpression);if(!t.isOk()||!n.isOk())return!1;const{tupleElements:r}=t.unwrap(),{tupleElements:s}=n.unwrap();return(r==null?void 0:r.length)===(s==null?void 0:s.length)}function kn(e){return e instanceof H&&e.expression instanceof ue||e instanceof Te}function Un(e,t){var s,i,a,o;let n=t;const r=Wo(e);for(;n;){if((i=(s=n.symbol)==null?void 0:s.symbolTable)!=null&&i.has(e))return(a=n.symbol.symbolTable)==null?void 0:a.get(e);if(((o=n.symbol)==null?void 0:o.declaration)instanceof ee&&r)return n.symbol;if(n instanceof ee)return;n=n.parent}}class gl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof ee||Re(this.declarationNode.parent).unwrap_or(void 0)!==_.Project?[new c(l.INVALID_CUSTOM_CONTEXT,"A custom element can only appear in a Project",this.declarationNode)]:[]}validateName(t){return t?[new c(l.UNEXPECTED_NAME,"A Custom element shouldn't have a name",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_NAME,"A Custom element shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Custom element shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof fe)return[new c(l.UNEXPECTED_COMPLEX_BODY,"A Custom element can only have an inline field",t)];const n=[];return Y(t.callee)||n.push(new c(l.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",t)),t.args.length>0&&n.push(...t.args.map(r=>new c(l.INVALID_CUSTOM_ELEMENT_VALUE,"A Custom element value can only be a string",r))),n}}class Xe{constructor(){this.table=new Map}has(t){return this.table.has(t)}set(t,n){this.table.set(t,n)}get(t,n){return this.table.get(t)||n!==void 0&&this.set(t,n)||n}entries(){return this.table.entries()}forEach(t){return this.table.forEach(t)}}class _l{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_PROJECT_CONTEXT,"An Enum can only appear top-level",this.declarationNode)]:[]}validateName(t){return t?Ar(t)?[]:[new c(l.INVALID_NAME,"An Enum name must be of the form <enum> or <schema>.<enum>",t)]:[new c(l.NAME_NOT_FOUND,"An Enum must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}registerElement(){const t=[];this.declarationNode.symbol=this.symbolFactory.create(Yo,{declaration:this.declarationNode,symbolTable:new Xe});const{name:n}=this.declarationNode,r=K(n);if(r.isOk()){const s=r.unwrap(),i=s.pop(),a=_t(s,this.publicSymbolTable,this.symbolFactory),o=Wt(i);a.has(o)&&t.push(new c(l.DUPLICATE_NAME,`Enum name ${i} already exists in schema '${s.join(".")||"public"}'`,n)),a.set(o,this.declarationNode.symbol)}return t}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"An Enum shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.length===0?[new c(l.EMPTY_ENUM,"An Enum must have at least one element",this.declarationNode)]:t.flatMap(n=>{const r=[];n.callee&&!X(n.callee)&&r.push(new c(l.INVALID_ENUM_ELEMENT_NAME,"An enum field must be an identifier or a quoted identifier",n.callee));const s=[...n.args];return F(s)instanceof B?(r.push(...this.validateFieldSettings(F(s))),s.pop()):s[0]instanceof B&&(r.push(...this.validateFieldSettings(s[0])),s.shift()),s.length>0&&r.push(...s.map(i=>new c(l.INVALID_ENUM_ELEMENT,"An Enum must have only a field and optionally a setting list",i))),r.push(...this.registerField(n)),r})}validateFieldSettings(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"note":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_ENUM_ELEMENT_SETTING,"'note' can only appear once",o))),a.forEach(o=>{Y(o.value)||r.push(new c(l.INVALID_ENUM_ELEMENT_SETTING,"'note' must be a string",o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_ENUM_ELEMENT_SETTING,`Unknown enum field setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=Ht(n),s=this.symbolFactory.create(Ko,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate enum field ${n}`,a.declaration)]}i.set(r,s)}return[]}}class Al{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){const t=new c(l.INVALID_INDEXES_CONTEXT,"An Indexes can only appear inside a Table or a TablePartial",this.declarationNode);if(this.declarationNode.parent instanceof ee)return[t];const n=Re(this.declarationNode.parent).unwrap_or(void 0);return n&&[_.Table,_.TablePartial].includes(n)?[]:[t]}validateName(t){return t?[new c(l.UNEXPECTED_NAME,"An Indexes shouldn't have a name",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"An Indexes shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"An Indexes shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"An Indexes must have a complex body",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[],s=[n.callee,...n.args];return F(s)instanceof B&&r.push(...this.validateFieldSetting(s.pop())),s.forEach(i=>{for(;i instanceof re;)i.argumentList&&!ct(i.argumentList).isOk()&&r.push(new c(l.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",i.argumentList)),i=i.callee;ct(i).isOk()||r.push(new c(l.INVALID_INDEXES_FIELD,"An index field must be an identifier, a quoted identifier, a functional expression or a tuple of such",i))}),r})}validateFieldSetting(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"note":case"name":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{Y(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'${i}' must be a string`,o))});break;case"unique":case"pk":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{Z(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'${i}' must not have a value`,o))});break;case"type":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_INDEX_SETTING,"'type' can only appear once",o))),a.forEach(o=>{X(o.value)||r.push(new c(l.INVALID_INDEX_SETTING_VALUE,`'type' must be "btree" or "hash"`,o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_INDEX_SETTING,`Unknown index setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class Ll{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return!(this.declarationNode.parent instanceof ee)&&![_.Table,_.TableGroup,_.TablePartial,_.Project].includes(Re(this.declarationNode.parent).unwrap_or(void 0))?[new c(l.INVALID_NOTE_CONTEXT,"A Note can only appear inside a Table, a TableGroup, a TablePartial or a Project. Sticky note can only appear at the global scope.",this.declarationNode)]:[]}validateName(t){if(!(this.declarationNode.parent instanceof ee))return t?[new c(l.UNEXPECTED_NAME,"A Note shouldn't have a name",t)]:[];if(!t)return[new c(l.INVALID_NAME,"Sticky note must have a name",this.declarationNode)];const n=K(t);if(!n.isOk())return[new c(l.INVALID_NAME,"Invalid name for sticky note ",this.declarationNode)];const s=n.unwrap().join("."),i=Xo(s);return this.publicSymbolTable.has(i)?[new c(l.DUPLICATE_NAME,`Sticky note "${s}" has already been defined`,t)]:(this.publicSymbolTable.set(i,this.declarationNode.symbol),[])}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Note shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){const n=[];return t.length===0?[new c(l.EMPTY_NOTE,"A Note must have a content",this.declarationNode)]:(t.length>1&&t.slice(1).forEach(r=>n.push(new c(l.NOTE_CONTENT_REDEFINED,"A Note can only contain one string",r))),Y(t[0].callee)||n.push(new c(l.INVALID_NOTE,"A Note content must be a quoted string",t[0])),t[0].args.length>0&&n.push(...t[0].args.map(r=>new c(l.INVALID_NOTE,"A Note can only contain one quoted string",r))),n)}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class vl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_PROJECT_CONTEXT,"A Project can only appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A Project's name is optional or must be an identifier or a quoted identifer",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Project shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Project shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A Project's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...n.map(s=>new c(l.INVALID_PROJECT_FIELD,"A Project can not have inline fields",s)),...this.validateSubElements(r)]}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}class yl{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof ee?[]:[new c(l.INVALID_REF_CONTEXT,"A Ref must appear top-level",this.declarationNode)]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A Ref's name is optional or must be an identifier or a quoted identifer",t)]:[]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A Ref shouldn't have an alias",t)]:[]}validateSettingList(t){return t?[new c(l.UNEXPECTED_SETTINGS,"A Ref shouldn't have a setting list",t)]:[]}validateBody(t){if(!t)return[];if(t instanceof w)return this.validateFields([t]);const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){if(t.length===0)return[new c(l.EMPTY_REF,"A Ref must have at least one field",this.declarationNode)];const n=[];return t.length>1&&n.push(...t.slice(1).map(r=>new c(l.REF_REDEFINED,"A Ref can only contain one binary relationship",r))),t.forEach(r=>{r.callee&&!ml(r.callee)&&n.push(new c(l.INVALID_REF_FIELD,"A Ref field must be a binary relationship",r.callee)),r.callee&&!Il(r.callee)&&n.push(new c(l.UNEQUAL_FIELDS_BINARY_REF,"Unequal fields in ref endpoints",r.callee));const s=[...r.args];if(F(s)instanceof B){const i=this.validateFieldSettings(F(s));n.push(...i),s.pop()}else s[0]instanceof B&&(n.push(...this.validateFieldSettings(s[0])),s.shift());s.length>0&&n.push(...s.map(i=>new c(l.INVALID_REF_FIELD,"A Ref field should only have a single binary relationship",i)))}),n}validateFieldSettings(t){const n=G(t),r=n.getErrors(),s=n.getValue();for(const i in s){const a=s[i];switch(i){case"delete":case"update":a.length>1&&a.forEach(o=>r.push(new c(l.DUPLICATE_REF_SETTING,`'${i}' can only appear once`,o))),a.forEach(o=>{wl(o.value)||r.push(new c(l.INVALID_REF_SETTING_VALUE,`'${i}' can only have values "cascade", "no action", "set null", "set default" or "restrict"`,o))});break;case"color":a.length>1&&r.push(...a.map(o=>new c(l.DUPLICATE_REF_SETTING,"'color' can only appear once",o))),a.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_REF_SETTING_VALUE,"'color' must be a color literal",o))});break;default:a.forEach(o=>r.push(new c(l.UNKNOWN_REF_SETTING,`Unknown ref setting '${i}'`,o)))}}return r}validateSubElements(t){return t.flatMap(n=>{if(n.parent=this.declarationNode,!n.type)return[];const r=ge(n);return new r(n,this.publicSymbolTable,this.symbolFactory).validate()})}}function wl(e){if(!(X(e)&&e.expression.variable.kind!==f.QUOTED_STRING)&&!(e instanceof ie))return!1;let t;if(e instanceof ie?t=Ce(e).unwrap_or(""):t=e.expression.variable.value,t)switch(t.toLowerCase()){case"cascade":case"no action":case"set null":case"set default":case"restrict":return!0;default:return!1}return!1}class Pl{constructor(t,n,r){this.declarationNode=t,this.symbolFactory=r,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLE_CONTEXT,"Table must appear top-level",this.declarationNode)]:[]}validateName(t){return t?t instanceof De?[new c(l.INVALID_NAME,"Invalid array as Table name, maybe you forget to add a space between the name and the setting list?",t)]:Ar(t)?[]:[new c(l.INVALID_NAME,"A Table name must be of the form <table> or <schema>.<table>",t)]:[new c(l.NAME_NOT_FOUND,"A Table must have a name",this.declarationNode)]}validateAlias(t){return t?Rl(t)?[]:[new c(l.INVALID_ALIAS,"Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes",t)]:[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Qe(s,(i,a)=>{switch(a){case N.HeaderColor:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'headercolor' can only appear once",o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'headercolor' must be a color literal",o.value||o.name))});break;case N.Note:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'note' can only appear once",o))),i.forEach(o=>{Y(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'note' must be a string literal",o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)))}}),r}registerElement(){const t=[];this.declarationNode.symbol=this.symbolFactory.create(Ir,{declaration:this.declarationNode,symbolTable:new Xe});const{name:n,alias:r}=this.declarationNode,s=K(n);if(s.isOk()){const i=[...s.unwrap()],a=i.pop(),o=_t(i,this.publicSymbolTable,this.symbolFactory),u=ot(a);o.has(u)&&t.push(new c(l.DUPLICATE_NAME,`Table name '${a}' already exists in schema '${i.join(".")||"public"}'`,n)),o.set(u,this.declarationNode.symbol)}if(r&&We(r)&&!Sl(r.expression.variable.value,s.unwrap_or([]))){const i=j(r).unwrap(),a=ot(i);this.publicSymbolTable.has(a)&&t.push(new c(l.DUPLICATE_NAME,`Table name '${i}' already exists`,n)),this.publicSymbolTable.set(a,this.declarationNode.symbol)}return t}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A Table's body must be a block",t)];const[n,r,s]=t.body.reduce((i,a)=>(a instanceof w?i[0].push(a):a instanceof xe?i[1].push(a):a instanceof P&&i[2].push(a),i),[[],[],[]]);return[...this.validateFields(n),...this.validateInjections(r),...this.validateSubElements(s)]}validateInjections(t){return t.flatMap(n=>this.registerInjection(n))}registerInjection(t){var o,u,p;if(!((u=(o=t.partial)==null?void 0:o.variable)!=null&&u.value))return[];const n=(p=t.partial.variable)==null?void 0:p.value,r=br(n),s=this.symbolFactory.create(el,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable,a=i.get(r);return a?[new c(l.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,t),new c(l.DUPLICATE_TABLE_PARTIAL_INJECTION_NAME,`Duplicate injection ${n}`,a.declaration)]:(i.set(r,s),[])}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[];n.args.length===0&&r.push(new c(l.INVALID_COLUMN,"A column must have a type",n.callee)),X(n.callee)||r.push(new c(l.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Pr(n.args[0])&&r.push(new c(l.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const s=n.args.slice(1);return r.push(...this.validateFieldSetting(s)),r.push(...this.registerField(n)),r})}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=It(n),s=this.symbolFactory.create(Kt,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}i.set(r,s)}return[]}validateFieldSetting(t){if(!t.slice(0,-1).every(we)||!t.slice(-1).every(u=>we(u)||u instanceof B))return[...t.map(u=>new c(l.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",u))];if(t.length===0)return[];let n;F(t)instanceof B&&(n=t.pop());const r=G(n),s=r.getErrors(),i=r.getValue();t.forEach(u=>{const p=j(u).unwrap_or("").toLowerCase();if(p!=="pk"&&p!=="unique"){s.push(new c(l.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",u));return}i[p]===void 0?i[p]=[u]:i[p].push(u)});const a=i[N.PK]||[],o=i[N.PKey]||[];return a.length>=1&&o.length>=1&&s.push(...[...a,...o].map(u=>new c(l.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",u))),Qe(i,(u,p)=>{switch(p){case N.Note:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"note can only appear once",h))),u.forEach(h=>{Y(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'note' must be a quoted string",h.value||h.name))});break;case N.Ref:u.forEach(h=>{yr(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'ref' must be a valid unary relationship",h.value||h.name))});break;case N.PKey:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"primary key can only appear once",h))),u.forEach(h=>{Z(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'primary key' must not have a value",h.value||h.name))});break;case N.PK:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'pk' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!Z(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'pk' must not have a value",h.value||h.name))});break;case N.NotNull:{u.length>1&&s.push(...u.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,"'not null' can only appear once",d)));const h=i[N.Null]||[];u.length>=1&&h.length>=1&&s.push(...[...u,...h].map(d=>new c(l.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",d))),u.forEach(d=>{Z(d.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'not null' must not have a value",d.value||d.name))});break}case N.Null:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'null' can only appear once",h))),u.forEach(h=>{Z(h.value)||s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'null' must not have a value",h.value||h.name))});break;case N.Unique:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'unique' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!Z(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'unique' must not have a value",h.value||h.name))});break;case N.Increment:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_COLUMN_SETTING,"'increment' can only appear once",h))),u.forEach(h=>{h instanceof ae&&!Z(h.value)&&s.push(new c(l.INVALID_COLUMN_SETTING_VALUE,"'increment' must not have a value",h.value||h.name))});break;case N.Default:u.length>1&&s.push(...u.map(h=>new c(l.DUPLICATE_TABLE_SETTING,"'default' can only appear once",h))),u.forEach(h=>{vr(h.value)||s.push(new c(l.INVALID_TABLE_SETTING,"'default' must be a string literal, number literal, function expression, true, false or null",h.value||h.name))});break;default:u.forEach(h=>s.push(new c(l.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${p}'`,h)))}}),s}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())==="note"});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}}function Sl(e,t){return t.length===1&&e===t[0]}class Ol{constructor(t,n,r){this.declarationNode=t,this.publicSymbolTable=n,this.symbolFactory=r}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLEGROUP_CONTEXT,"TableGroup must appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A TableGroup name must be a single identifier",t)]:[new c(l.NAME_NOT_FOUND,"A TableGroup must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A TableGroup shouldn't have an alias",t)]:[]}registerElement(){const{name:t}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Qo,{declaration:this.declarationNode,symbolTable:new Xe});const n=K(t);if(n.isOk()){const r=n.unwrap(),s=r.pop(),i=_t(r,this.publicSymbolTable,this.symbolFactory),a=zt(s);if(i.has(a))return[new c(l.DUPLICATE_NAME,`TableGroup name '${s}' already exists`,t)];i.set(a,this.declarationNode.symbol)}return[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Qe(s,(i,a)=>{switch(a){case"color":i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'color' can only appear once",o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_SETTING,"'color' must be a color literal",o.value||o.name))});break;case"note":i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_SETTING,"'note' can only appear once",o))),i.filter(o=>!Y(o.value)).forEach(o=>{r.push(new c(l.INVALID_TABLE_SETTING,"'note' must be a string literal",o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)));break}}),r}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A TableGroup's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{const r=[];return n.callee&&!K(n.callee).isOk()&&r.push(new c(l.INVALID_TABLEGROUP_FIELD,"A TableGroup field must be of the form <table> or <schema>.<table>",n.callee)),this.registerField(n),n.args.length>0&&r.push(...n.args.map(s=>new c(l.INVALID_TABLEGROUP_FIELD,"A TableGroup field should only have a single Table name",s))),r})}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())==="note"});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}registerField(t){if(t.callee&&X(t.callee)){const n=j(t.callee).unwrap(),r=qt(n),s=this.symbolFactory.create(Jo,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,t),new c(l.DUPLICATE_TABLEGROUP_FIELD_NAME,`${n} already exists in the group`,a.declaration)]}i.set(r,s)}return[]}}const xl=["-","+"];class Dl{constructor(t,n,r){this.declarationNode=t,this.symbolFactory=r,this.publicSymbolTable=n}validate(){return[...this.validateContext(),...this.validateName(this.declarationNode.name),...this.validateAlias(this.declarationNode.alias),...this.validateSettingList(this.declarationNode.attributeList),...this.registerElement(),...this.validateBody(this.declarationNode.body)]}validateContext(){return this.declarationNode.parent instanceof P?[new c(l.INVALID_TABLE_PARTIAL_CONTEXT,"TablePartial must appear top-level",this.declarationNode)]:[]}validateName(t){return t?We(t)?[]:[new c(l.INVALID_NAME,"A TablePartial name must be an identifier or a quoted identifer",t)]:[new c(l.NAME_NOT_FOUND,"A TablePartial must have a name",this.declarationNode)]}validateAlias(t){return t?[new c(l.UNEXPECTED_ALIAS,"A TablePartial shouldn't have an alias",t)]:[]}validateSettingList(t){const n=G(t),r=n.getErrors(),s=n.getValue();return Qe(s,(i,a)=>{switch(a){case N.HeaderColor:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_PARTIAL_SETTING,`'${a}' can only appear once`,o))),i.forEach(o=>{At(o.value)||r.push(new c(l.INVALID_TABLE_PARTIAL_SETTING,`'${a}' must be a color literal`,o.value||o.name))});break;case N.Note:i.length>1&&r.push(...i.map(o=>new c(l.DUPLICATE_TABLE_PARTIAL_SETTING,`'${a}' can only appear once`,o))),i.forEach(o=>{Y(o.value)||r.push(new c(l.INVALID_TABLE_PARTIAL_SETTING,`'${a}' must be a string literal`,o.value||o.name))});break;default:r.push(...i.map(o=>new c(l.INVALID_TABLE_SETTING,`Unknown '${a}' setting`,o)))}}),r}registerElement(){const{name:t}=this.declarationNode;this.declarationNode.symbol=this.symbolFactory.create(Zo,{declaration:this.declarationNode,symbolTable:new Xe});const n=K(t);if(!n.isOk())return[];const r=n.unwrap(),s=r.pop(),i=_t(r,this.publicSymbolTable,this.symbolFactory),a=Yt(s);return i.has(a)?[new c(l.DUPLICATE_NAME,`TablePartial name '${s}' already exists`,t)]:(i.set(a,this.declarationNode.symbol),[])}validateBody(t){if(!t)return[];if(t instanceof w)return[new c(l.UNEXPECTED_SIMPLE_BODY,"A TablePartial's body must be a block",t)];const[n,r]=he(t.body,s=>s instanceof w);return[...this.validateFields(n),...this.validateSubElements(r)]}validateFields(t){return t.flatMap(n=>{if(!n.callee)return[];const r=[];n.args.length===0&&r.push(new c(l.INVALID_COLUMN,"A column must have a type",n.callee)),X(n.callee)||r.push(new c(l.INVALID_COLUMN_NAME,"A column name must be an identifier or a quoted identifier",n.callee)),n.args[0]&&!Pr(n.args[0])&&r.push(new c(l.INVALID_COLUMN_TYPE,"Invalid column type",n.args[0]));const s=n.args.slice(1);return r.push(...this.validateFieldSetting(s),...this.registerField(n)),r})}registerField(t){if(!t.callee||!X(t.callee))return[];const n=j(t.callee).unwrap(),r=It(n),s=this.symbolFactory.create(Kt,{declaration:t});t.symbol=s;const i=this.declarationNode.symbol.symbolTable;if(i.has(r)){const a=i.get(r);return[new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,t),new c(l.DUPLICATE_COLUMN_NAME,`Duplicate column ${n}`,a.declaration)]}return i.set(r,s),[]}validateFieldSetting(t){const n=F(t);if(!t.slice(0,-1).every(we)||!(we(n)||n instanceof B))return[...t.map(p=>new c(l.INVALID_COLUMN,"These fields must be some inline settings optionally ended with a setting list",p))];if(t.length===0)return[];let r;F(t)instanceof B&&(r=t.pop());const s=G(r),i=s.getErrors(),a=s.getValue();t.forEach(p=>{const h=j(p).unwrap_or("").toLowerCase();if(h!==N.PK&&h!==N.Unique){i.push(new c(l.INVALID_SETTINGS,"Inline column settings can only be `pk` or `unique`",p));return}a[h]===void 0?a[h]=[p]:a[h].push(p)});const o=a[N.PK]||[],u=a[N.PKey]||[];return o.length>=1&&u.length>=1&&i.push(...[...o,...u].map(p=>new c(l.DUPLICATE_COLUMN_SETTING,"Either one of 'primary key' and 'pk' can appear",p))),Qe(a,(p,h)=>{switch(h){case N.Note:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{Y(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a quoted string`,d.value||d.name))});break;case N.Ref:p.forEach(d=>{yr(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a valid unary relationship`,d.value||d.name))});break;case N.PKey:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{Z(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.PK:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!Z(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.NotNull:{p.length>1&&i.push(...p.map(E=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,E)));const d=a[N.Null]||[];p.length>=1&&d.length>=1&&i.push(...[...p,...d].map(E=>new c(l.CONFLICTING_SETTING,"'not null' and 'null' can not be set at the same time",E))),p.forEach(E=>{Z(E.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,E.value||E.name))});break}case N.Null:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{Z(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Unique:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!Z(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Increment:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{d instanceof ae&&!Z(d.value)&&i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must not have a value`,d.value||d.name))});break;case N.Default:p.length>1&&i.push(...p.map(d=>new c(l.DUPLICATE_COLUMN_SETTING,`'${h}' can only appear once`,d))),p.forEach(d=>{vr(d.value)||i.push(new c(l.INVALID_COLUMN_SETTING_VALUE,`'${h}' must be a string literal, number literal, function expression, true, false or null`,d.value||d.name))});break;default:p.forEach(d=>i.push(new c(l.UNKNOWN_COLUMN_SETTING,`Unknown column setting '${h}'`,d)))}}),i}validateSubElements(t){const n=t.flatMap(s=>{if(s.parent=this.declarationNode,!s.type)return[];const i=ge(s);return new i(s,this.publicSymbolTable,this.symbolFactory).validate()}),r=t.filter(s=>{var i;return((i=s.type)==null?void 0:i.value.toLowerCase())===_.Note});return r.length>1&&n.push(...r.map(s=>new c(l.NOTE_REDEFINED,"Duplicate notes are defined",s))),n}}function ge(e){switch(e.type.value.toLowerCase()){case _.Enum:return _l;case _.Table:return Pl;case _.TableGroup:return Ol;case _.Project:return vl;case _.Ref:return yl;case _.Note:return Ll;case _.Indexes:return Al;case _.TablePartial:return Dl;default:return gl}}function Ar(e){return!!K(e).unwrap_or(!1)}function Rl(e){return We(e)}function We(e){return e instanceof H&&e.expression instanceof ue}function _t(e,t,n){var s;e[0]==="public"&&(e=e.slice(1));let r=t;for(const i of e){let a;const o=Xt(i);if(r.has(o)){if(a=(s=r.get(o))==null?void 0:s.symbolTable,!a)throw new Error("Expect a symbol table in a schema symbol")}else{a=new Xe;const u=n.create(mr,{symbolTable:a});r.set(o,u)}r=a}return r}function Lr(e){return e==="-"||e==="<>"||e===">"||e==="<"}function At(e){var n;if(!(e instanceof H)||!(e.expression instanceof je)||((n=e.expression.literal)==null?void 0:n.kind)!==f.COLOR_LITERAL)return!1;const t=e.expression.literal.value;if(t.length!==4&&t.length!==7||t[0]!=="#")return!1;for(let r=1;r<t.length;r+=1)if(!sl(t[r]))return!1;return!0}function Z(e){return e===void 0}function vr(e){var t;return!!(Y(e)||ke(e)||we(e)&&["true","false","null"].includes(e.expression.variable.value.toLowerCase())||e instanceof ne&&xl.includes((t=e.op)==null?void 0:t.value)&&ke(e.expression)||e instanceof Te)}function ke(e){var t,n,r;return e instanceof ne?((t=e.op)==null?void 0:t.value)!=="-"&&((n=e.op)==null?void 0:n.value)!=="+"?!1:ke(e.expression):e instanceof H&&e.expression instanceof je&&((r=e.expression.literal)==null?void 0:r.kind)===f.NUMERIC_LITERAL}function yr(e){var n;if(!(e instanceof ne)||!Lr((n=e.op)==null?void 0:n.value))return!1;const t=K(e.expression).unwrap_or(void 0);return t!==void 0&&t.length>0}function wr(e){return e instanceof Ee&&e.elementList.every(X)}function Pr(e){if(!(e instanceof re||Qt(e)||e instanceof H||e instanceof De))return!1;if(e instanceof re){if(e.callee===void 0||e.argumentList===void 0||!e.argumentList.elementList.every(n=>ke(n)||Y(n)||we(n)))return!1;e=e.callee}for(;e instanceof De;){if(e.array===void 0||e.indexer===void 0||!e.indexer.elementList.every(n=>!n.colon&&!n.value&&ke(n.name)))return!1;e=e.array}const t=K(e).unwrap_or(void 0);return t!==void 0&&t.length>0}function G(e){var r;const t={},n=[];if(!e)return new te({});for(const s of e.elementList){if(!s.name)continue;if(s.name instanceof H){n.push(new c(l.INVALID_SETTINGS,"A setting name must be a stream of identifiers",s.name));continue}const i=(r=Ce(s.name).unwrap_or(void 0))==null?void 0:r.toLowerCase();i&&(t[i]===void 0?t[i]=[s]:t[i].push(s))}return new te(t,n)}class Mn{constructor(t,n){this.ast=t,this.symbolFactory=n,this.publicSchemaSymbol=this.symbolFactory.create(mr,{symbolTable:new Xe}),this.ast.symbol=this.publicSchemaSymbol,this.ast.symbol.declaration=this.ast}validate(){const t=[];this.ast.body.forEach(r=>{if(r.parent=this.ast,r.type===void 0)return;const s=ge(r),i=new s(r,this.publicSchemaSymbol.symbolTable,this.symbolFactory);t.push(...i.validate())});const n=this.ast.body.filter(r=>Re(r).unwrap_or(void 0)===_.Project);return n.length>1&&n.forEach(r=>t.push(new c(l.PROJECT_REDEFINED,"Only one project can exist",r))),new te(this.ast,t)}}class _e{constructor(t,n){this.declarationNode=t,this.errors=n}bind(){this.bindSettingList(this.declarationNode.attributeList,this.settingList),this.bindBody()}bindSettingList(t,n){t&&t.elementList.forEach(r=>{if(r.name instanceof H)return;const s=Ce(r.name).unwrap_or(void 0);if(!s)return;const i=n[s.toLowerCase()];i!=null&&i.shouldBind&&this.scanAndBind(r.value,i)})}bindBody(){const t=this.declarationNode;if(!t.body)return;const{body:n}=t;n instanceof fe?n.body.forEach(r=>{if(r instanceof P){if(!r.type||Re(this.declarationNode).unwrap_or(null)===_.TablePartial&&Re(r).unwrap_or(null)===_.Indexes)return;const s=Sr(r);new s(r,this.errors).bind()}else r instanceof w?this.bindSubfield(r):this.bindPartialInjection(r)}):this.bindSubfield(n)}bindSubfield(t){const n=[t.callee,...t.args],r=F(n);r instanceof B&&(n.pop(),this.bindSettingList(r,this.subfield.settingList));const{argBinderRules:s}=this.subfield.arg;for(let i=0;i<Math.min(n.length,s.length);i+=1)s[i].shouldBind&&this.scanAndBind(n[i],s[i])}bindPartialInjection(t){var n;(n=this.injectionBinderRule)!=null&&n.shouldBind&&this.scanAndBind(t,this.injectionBinderRule)}scanAndBind(t,n){var r,s;if(t)if(t instanceof H){if(t.expression instanceof ue&&((s=n.keywords)!=null&&s.includes((r=t.expression.variable)==null?void 0:r.value.toLowerCase())))return;this.bindFragments([t],n)}else t instanceof de?Qt(t)?this.bindFragments(Fe(t).unwrap_or([]),n):(this.scanAndBind(t.leftExpression,n),this.scanAndBind(t.rightExpression,n)):t instanceof ne?this.scanAndBind(t.expression,n):t instanceof mt?this.scanAndBind(t.expression,n):t instanceof Ee?t.elementList.forEach(i=>this.scanAndBind(i,n)):t instanceof xe&&this.bindFragments([t],n)}bindFragments(t,n){if(t.length===0)return;const r=t.length===1&&t[0]instanceof xe,s=[...n.topSubnamesSymbolKind],{remainingSubnamesSymbolKind:i}=n,a=r?-1:t.findIndex(E=>!X(E)),u=a!==-1&&wr(t[a])?t[a]:void 0,p=a>=0?s.pop():void 0,h=t.slice(0,a===-1?void 0:a);if(h.length===0)return;const d=[];for(;s.length&&h.length;){const E=s.pop(),b=h.pop(),A=j(b).unwrap();d.unshift({index:st(A,E),referrer:b})}for(;h.length;){const E=h.pop(),b=r?bl(E).unwrap():j(E).unwrap();d.unshift({index:st(b,i),referrer:E})}return u?u.elementList.forEach(E=>this.resolveIndexStack([...d,{index:st(j(E).unwrap(),p),referrer:E}],n.ignoreNameNotFound)):this.resolveIndexStack(d,n.ignoreNameNotFound)}resolveIndexStack(t,n){if(t.length===0)throw new Error("Unreachable - An unresolved name must have at least one name component");const[r,...s]=t,i=Un(r.index,this.declarationNode);if(i===void 0){const{kind:p,name:h}=oe(r.index).unwrap();this.logError(r.referrer,`Can not find ${p} '${h}'`,n);return}i.references.push(r.referrer),r.referrer.referee=i;let a=i.symbolTable,{kind:o,name:u}=oe(r.index).unwrap();for(const p of s){const{kind:h,name:d}=oe(p.index).unwrap(),E=a.get(p.index);if(!E){this.logError(p.referrer,`${o} '${u}' does not have ${h} '${d}'`,n);return}if(o=h,u=d,p.referrer.referee=E,E.references.push(p.referrer),!E.symbolTable)break;a=E.symbolTable}}logError(t,n,r){r||this.errors.push(new c(l.BINDING_ERROR,n,t))}resolveInjections(t){var s;const n=(s=this.declarationNode.symbol)==null?void 0:s.symbolTable;if(!n)return;const r=new Map;n.forEach((i,a)=>{var p,h;if(!Ho(a))return;const o=Un(zo(a),this.declarationNode),u=(h=(p=o==null?void 0:o.declaration)==null?void 0:p.symbol)==null?void 0:h.symbolTable;u&&u.forEach((d,E)=>{n.has(E)||r.set(E,{injectorFieldSymbol:d,injectorDeclaration:i.declaration})})}),r.forEach((i,a)=>{const o=rl(i.injectorFieldSymbol);if(!o)return;const u=t.create(o,i);n.set(a,u)})}}class kl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Ul extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Ml extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Fl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1}]},settingList:{}},this.settingList={}}}class Bl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[]},settingList:{}},this.settingList={}}}class Gl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class Vl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={},this.injectionBinderRule={shouldBind:!0,topSubnamesSymbolKind:[],remainingSubnamesSymbolKind:m.TablePartial,ignoreNameNotFound:!1}}}class Cl extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!0,topSubnamesSymbolKind:[m.Table],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1}]},settingList:{}},this.settingList={}}}class $l extends _e{constructor(){super(...arguments),this.subfield={arg:{argBinderRules:[{shouldBind:!1},{shouldBind:!0,topSubnamesSymbolKind:[m.Enum],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!0}]},settingList:{ref:{shouldBind:!0,topSubnamesSymbolKind:[m.Table,m.Column],remainingSubnamesSymbolKind:m.Schema,ignoreNameNotFound:!1},default:{shouldBind:!1}}},this.settingList={}}}function Sr(e){switch(e.type.value.toLowerCase()){case _.Enum:return Ul;case _.Table:return Vl;case _.TableGroup:return Cl;case _.Project:return Bl;case _.Ref:return Gl;case _.Note:return Fl;case _.Indexes:return Ml;case _.TablePartial:return $l;default:return kl}}class jl{constructor(t){this.ast=t,this.errors=[]}resolve(t){return this.ast.body.map(n=>{if(!n.type)return null;const r=Sr(n),s=new r(n,this.errors);return s.resolveInjections(t),s}).forEach(n=>n==null?void 0:n.bind()),new te(this.ast,this.errors)}}class Xl{constructor(t){this.generator=t}create(t,n){return new t(n,this.generator.nextId())}}class Wl{constructor(t,n){this.ast=t,this.symbolFactory=new Xl(n)}analyze(){return new Mn(this.ast,this.symbolFactory).validate().chain(n=>new jl(n).resolve(this.symbolFactory))}validate(){return new Mn(this.ast,this.symbolFactory).validate().chain(n=>new te(n,[]))}}function Fn(e,t){const{variables:n,tupleElements:r}=Je(e).unwrap();return r?n.length===0?{schemaName:t.schemaName,tableName:t.name,fieldNames:r}:{tableName:n.pop(),schemaName:n.pop()||null,fieldNames:r}:n.length===1?{schemaName:t.schemaName,tableName:t.name,fieldNames:[n[0]]}:{fieldNames:[n.pop()],tableName:n.pop(),schemaName:n.pop()||null}}function Or(e){switch(e){case"<":return["1","*"];case"<>":return["*","*"];case">":return["*","1"];case"-":return["1","1"];default:throw new Error("Invalid relation op")}}function L(e){return{start:{offset:e.startPos.offset,line:e.startPos.line+1,column:e.startPos.column+1},end:{offset:e.endPos.offset,line:e.endPos.line+1,column:e.endPos.column+1}}}function ut(e){var n;const t=(n=Fe(e).unwrap_or(void 0))==null?void 0:n.pop();return t instanceof Ee?t.elementList.map(r=>r.referee):[t.referee]}function Be(e){const t=K(e).unwrap();return{name:t.pop(),schemaName:t}}function et(e){return e.expression.literal.value}function xr(e,t){if(Array.isArray(e)){const s=e.map(({id:a})=>a).sort().join(","),i=t.map(({id:a})=>a).sort().join(",");return s<i?`${s}-${i}`:`${i}-${s}`}const n=e.id.toString(),r=t.id.toString();return n<r?`${n}-${r}`:`${r}-${n}`}function Jt(e,t){if(Array.isArray(e)){const s=e.map(({id:a})=>a).sort(),i=t.map(({id:a})=>a).sort();return Rt(s,i).every(([a,o])=>a===o)}const n=e.id,r=t.id;return n===r}function le(e){const t=e.split(`
10
10
  `),n=t.slice(t.findIndex(i=>i.trimStart()!=="")),r=n.filter(i=>i.trimStart()),s=Math.min(...r.map(i=>i.length-i.trimStart().length));return n.map(i=>i.slice(s)).join(`
11
- `)}function Dr(e){if(e){if(q(e))return{value:V(e).unwrap(),type:"string"};if(ke(e))return{type:"number",value:Ut(e)};if(ye(e))return{value:e.expression.variable.value.toLowerCase(),type:"boolean"};if(e instanceof Te&&e.value)return{value:e.value.value,type:"expression"};throw new Error("Unreachable")}}function Rr(e){let t=null;e instanceof re&&(t=e.argumentList.elementList.map(i=>ke(i)?gr(i):q(i)?V(i).unwrap():z(i).unwrap()).join(","),e=e.callee);let n="";for(;e instanceof De;)n=`[${e.indexer.elementList.map(i=>i.name.expression.literal.value).join(",")}]${n}`,e=e.array;const{name:r,schemaName:s}=Be(e);return s.length>1?new ee({schemaName:s.length===0?null:s[0],type_name:`${r}${n}${t?`(${t})`:""}`,args:t},[new c(l.UNSUPPORTED,"Nested schema is not supported",e)]):new ee({schemaName:s.length===0?null:s[0],type_name:`${r}${n}${t?`(${t})`:""}`,args:t})}class kr{constructor(t,n){this.declarationNode=t,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[],partials:[]},this.pkColumns=[]}interpret(){this.table.token=L(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const t=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n,token:r})=>({value:n,type:"column",token:r})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>{n.pk=!1})),t}interpretName(t){const{name:n,schemaName:r}=Be(t);return r.length>1?(this.table.name=n,this.table.schemaName=r.join("."),[new c(l.UNSUPPORTED,"Nested schema is not supported",t)]):(this.table.name=n,this.table.schemaName=r.length?r[0]:null,[])}interpretAlias(t){if(!t)return[];const n=j(t).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(t){var s,i,a;const n=G(t).getValue();this.table.headerColor=(s=n[N.HeaderColor])!=null&&s.length?et((a=(i=n[N.HeaderColor])==null?void 0:i.at(0))==null?void 0:a.value):void 0;const[r]=n[N.Note]||[];return this.table.note=r&&{value:V(r==null?void 0:r.value).map(le).unwrap(),token:L(r)},[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w||s instanceof xe);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case _.Note:return this.table.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)},[];case _.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretInjection(t,n){const r={order:n,token:L(t)};return r.name=t.partial.variable.value,this.table.partials.push(r),[]}interpretFields(t){var a;const s=((a=this.declarationNode.symbol)!=null&&a.symbolTable?[...this.declarationNode.symbol.symbolTable.entries()]:[]).filter(([o])=>{const u=oe(o).unwrap_or(null);return(u==null?void 0:u.kind)===m.Column}).length?[]:[new c(l.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)],i=t.flatMap((o,u)=>o instanceof w?this.interpretColumn(o):this.interpretInjection(o,u));return[...s,...i]}interpretColumn(t){var a,o,u,p,h,d,E,b,A;const n=[],r={};r.name=j(t.callee).unwrap();const s=Rr(t.args[0]);r.type=s.getValue(),n.push(...s.getErrors()),r.token=L(t),r.inline_refs=[];const i=t.args.slice(1);if(F(i)instanceof B){const I=G(i.pop()).getValue();r.pk=!!((a=I[N.PK])!=null&&a.length)||!!((o=I[N.PKey])!=null&&o.length),r.increment=!!((u=I[N.Increment])!=null&&u.length),r.unique=!!((p=I[N.Unique])!=null&&p.length),r.not_null=(h=I[N.NotNull])!=null&&h.length?!0:(d=I[N.Null])!=null&&d.length?!1:void 0,r.dbdefault=Dr((b=(E=I[N.Default])==null?void 0:E.at(0))==null?void 0:b.value);const v=(A=I[N.Note])==null?void 0:A.at(0);r.note=v&&{value:V(v.value).map(le).unwrap(),token:L(v)};const W=I[N.Ref]||[];r.inline_refs=W.flatMap(y=>{const[we]=ut(y.value.expression);if(Jt(we,t.symbol))return n.push(new c(l.SAME_ENDPOINT,"Two endpoints are the same",y)),[];const Q=y.value.op,R=Y(y.value.expression).unwrap();let se;if(R.length===1){const[K]=R;se={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[K],relation:Q.value,token:L(y)}}else if(R.length===2){const[K,Le]=R;se={schemaName:null,tableName:K,fieldNames:[Le],relation:Q.value,token:L(y)}}else if(R.length===3){const[K,Le,tn]=R;se={schemaName:K,tableName:Le,fieldNames:[tn],relation:Q.value,token:L(y)}}else{n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",y));const K=R.pop(),Le=R.pop();se={schemaName:R.join("."),tableName:Le,fieldNames:[K],relation:Q.value,token:L(y)}}const Ae=this.registerInlineRefToEnv(t,we,se,y);return n.push(...Ae),Ae.length===0?se:[]})}return r.pk||(r.pk=i.some(I=>z(I).unwrap().toLowerCase()==="pk")),r.unique||(r.unique=i.some(I=>z(I).unwrap().toLowerCase()==="unique")),this.table.fields.push(r),r.pk&&this.pkColumns.push(r),n}interpretIndexes(t){return this.table.indexes.push(...t.body.body.map(n=>{var a,o,u,p,h,d,E;const r={columns:[]},s=n;r.token=L(s);const i=[s.callee,...s.args];if(F(i)instanceof B){const b=G(i.pop()).getValue();r.pk=!!((a=b[N.PK])!=null&&a.length),r.unique=!!((o=b[N.Unique])!=null&&o.length),r.name=V((p=(u=b[N.Name])==null?void 0:u.at(0))==null?void 0:p.value).unwrap_or(void 0);const A=(h=b[N.Note])==null?void 0:h.at(0);r.note=A&&{value:V(A.value).unwrap(),token:L(A)},r.type=z((E=(d=b[N.Type])==null?void 0:d.at(0))==null?void 0:E.value).unwrap_or(void 0)}return i.flatMap(b=>{if(!(b instanceof re))return b;const A=[];for(;b instanceof re;)A.push(b.argumentList),b=b.callee;return A.push(b),A}).forEach(b=>{const{functional:A,nonFunctional:I}=ct(b).unwrap();r.columns.push(...A.map(v=>({value:v.value.value,type:"expression",token:L(v)})),...I.map(v=>({value:j(v).unwrap(),type:"column",token:L(v)})))}),r})),[]}registerInlineRefToEnv(t,n,r,s){const i=xr(t.symbol,n);if(this.env.refIds[i])return[new c(l.CIRCULAR_REF,"References with same endpoints exist",s),new c(l.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[i])];const a=Or(r.relation);return this.env.refIds[i]=s,this.env.ref.set(s,{name:null,schemaName:null,token:r.token,endpoints:[{...r,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[z(t.callee).unwrap()],token:L(t),relation:a[0]}]}),[]}}class Hl{constructor(t,n){this.declarationNode=t,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=L(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const{name:n}=Be(t);return this.note.name=n,[]}interpretSettingList(t){var r,s,i;const n=G(t).getValue();return this.note.headerColor=(r=n.headercolor)!=null&&r.length?et((i=(s=n.headercolor)==null?void 0:s.at(0))==null?void 0:i.value):void 0,[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return n.length!==1||r.length>0?[new c(l.INVALID_NOTE,"Invalid note syntax",t)]:[...this.interpretNote(n[0])]}interpretNote(t){const n=ir(t,"callee.expression.literal.value","");return this.note.content=le(n),[]}}class Ur{constructor(t,n){this.declarationNode=t,this.env=n,this.container=this.declarationNode.parent instanceof P?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=L(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const n=[],r=Y(this.declarationNode.name).unwrap_or([]);return this.ref.name=r.pop()||null,r.length>1&&n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=r.join(".")||null,n}interpretBody(t){return t instanceof w?this.interpretField(t):this.interpretField(t.body[0])}interpretField(t){var p,h,d,E,b,A,I;const n=t.callee.op.value,{leftExpression:r,rightExpression:s}=t.callee,i=ut(r),a=ut(s);if(Jt(i,a))return[new c(l.SAME_ENDPOINT,"Two endpoints are the same",t)];const o=xr(i,a);if(this.env.refIds[o])return[new c(l.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(l.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[o])];if(t.args[0]){const v=G(t.args[0]).getValue(),W=(h=(p=v.delete)==null?void 0:p.at(0))==null?void 0:h.value;this.ref.onDelete=W instanceof ie?Ce(W).unwrap_or(void 0):z(W).unwrap_or(void 0);const y=(E=(d=v.update)==null?void 0:d.at(0))==null?void 0:E.value;this.ref.onUpdate=y instanceof ie?Ce(y).unwrap_or(void 0):z(y).unwrap_or(void 0),this.ref.color=(b=v.color)!=null&&b.length?et((I=(A=v.color)==null?void 0:A.at(0))==null?void 0:I.value):void 0}const u=Or(n);return this.ref.endpoints=[{...Fn(r,this.container),relation:u[0],token:L(r)},{...Fn(s,this.container),relation:u[1],token:L(s)}],this.env.refIds[o]=this.declarationNode,[]}}class Mr{constructor(t,n){this.declarationNode=t,this.env=n,this.tableGroup={tables:[]}}interpret(){const t=[];return this.tableGroup.token=L(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),t.push(...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)),t}interpretName(t){const n=[],{name:r,schemaName:s}=Be(t);return s.length>=2&&(this.tableGroup.name=r,this.tableGroup.schemaName=s.join("."),n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=r,this.tableGroup.schemaName=s[0]||null,n}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case"note":this.tableGroup.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)};break}return[]})}interpretFields(t){const n=[];return this.tableGroup.tables=t.map(r=>{const s=Y(r.callee).unwrap();s.length>2&&n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",r));const i=Fe(r.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[i]){const a=this.env.groupOfTable[i],{schemaName:o,name:u}=this.env.tableGroups.get(a),p=o?`${o}.${u}`:u;n.push(new c(l.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${s.join(".")}" already appears in group "${p}"`,r))}else this.env.groupOfTable[i]=this.declarationNode;return{name:s.pop(),schemaName:s.join(".")}}),n}interpretSettingList(t){var s,i,a;const n=G(t).getValue();this.tableGroup.color=(s=n.color)!=null&&s.length?et((a=(i=n.color)==null?void 0:i.at(0))==null?void 0:a.value):void 0;const[r]=n.note||[];return this.tableGroup.note=r&&{value:V(r==null?void 0:r.value).map(le).unwrap(),token:L(r)},[]}}class Fr{constructor(t,n){this.declarationNode=t,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=L(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const{name:n,schemaName:r}=Be(t);return r.length>1?(this.enum.name=n,this.enum.schemaName=r.join("."),[new c(l.UNSUPPORTED,"Nested schema is not supported",t)]):(this.enum.name=n,this.enum.schemaName=r.length?r[0]:null,[])}interpretBody(t){return t.body.flatMap(n=>{var o;const r=n,s={};s.token=L(r),s.name=z(r.callee).unwrap();const a=(o=G(r.args[0]).getValue().note)==null?void 0:o.at(0);return s.note=a&&{value:V(a.value).map(le).unwrap(),token:L(a)},this.enum.values.push(s),[]})}}class Br{constructor(t,n){this.declarationNode=t,this.env=n,this.tablePartial={name:void 0,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.tablePartial.token=L(this.declarationNode),this.env.tablePartials.set(this.declarationNode,this.tablePartial);const t=[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.tablePartial.indexes.push({columns:this.pkColumns.map(({name:n,token:r})=>({value:n,type:"column",token:r})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>{n.pk=!1})),t}interpretName(t){const{name:n}=Be(t);return this.tablePartial.name=n,[]}interpretSettingList(t){const n=G(t).getValue(),r=Mo(n[N.HeaderColor]);this.tablePartial.headerColor=r?et(r.value):void 0;const[s]=n[N.Note]||[];return this.tablePartial.note=s&&{value:V(s==null?void 0:s.value).map(le).unwrap(),token:L(s)},[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case _.Note:return this.tablePartial.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)},[];case _.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretFields(t){return t.flatMap(n=>this.interpretColumn(n))}interpretColumn(t){var a,o,u,p,h,d,E,b,A;const n=[],r={};r.name=j(t.callee).unwrap();const s=Rr(t.args[0]);r.type=s.getValue(),n.push(...s.getErrors()),r.token=L(t),r.inline_refs=[];const i=t.args.slice(1);if(F(i)instanceof B){const I=G(i.pop()).getValue();r.pk=!!((a=I[N.PK])!=null&&a.length)||!!((o=I[N.PKey])!=null&&o.length),r.increment=!!((u=I[N.Increment])!=null&&u.length),r.unique=!!((p=I[N.Unique])!=null&&p.length),r.not_null=(h=I[N.NotNull])!=null&&h.length?!0:(d=I[N.Null])!=null&&d.length?!1:void 0,r.dbdefault=Dr((b=(E=I[N.Default])==null?void 0:E.at(0))==null?void 0:b.value);const v=(A=I[N.Note])==null?void 0:A.at(0);r.note=v&&{value:V(v.value).map(le).unwrap(),token:L(v)};const W=I[N.Ref]||[];r.inline_refs=W.flatMap(y=>{const[we]=ut(y.value.expression);if(Jt(we,t.symbol))return n.push(new c(l.SAME_ENDPOINT,"Two endpoints are the same",y)),[];const Q=y.value.op,R=Y(y.value.expression).unwrap();let se;if(R.length===2){const[Ae,K]=R;se={schemaName:null,tableName:Ae,fieldNames:[K],relation:Q.value,token:L(y)}}else if(R.length===3){const[Ae,K,Le]=R;se={schemaName:Ae,tableName:K,fieldNames:[Le],relation:Q.value,token:L(y)}}else{n.push(new c(l.UNSUPPORTED,"Unsupported",y));const Ae=R.pop(),K=R.pop();se={schemaName:R.join("."),tableName:K,fieldNames:[Ae],relation:Q.value,token:L(y)}}return se})}return r.pk||(r.pk=i.some(I=>z(I).unwrap().toLowerCase()==="pk")),r.unique||(r.unique=i.some(I=>z(I).unwrap().toLowerCase()==="unique")),this.tablePartial.fields.push(r),r.pk&&this.pkColumns.push(r),n}interpretIndexes(t){return this.tablePartial.indexes.push(...t.body.body.map(n=>{var a,o,u,p,h,d,E;const r={columns:[]},s=n;r.token=L(s);const i=[s.callee,...s.args];if(F(i)instanceof B){const b=G(i.pop()).getValue();r.pk=!!((a=b[N.PK])!=null&&a.length),r.unique=!!((o=b[N.Unique])!=null&&o.length),r.name=V((p=(u=b[N.Name])==null?void 0:u.at(0))==null?void 0:p.value).unwrap_or(void 0);const A=(h=b[N.Note])==null?void 0:h.at(0);r.note=A&&{value:V(A.value).unwrap(),token:L(A)},r.type=z((E=(d=b[N.Type])==null?void 0:d.at(0))==null?void 0:E.value).unwrap_or(void 0)}return i.flatMap(b=>{if(!(b instanceof re))return b;const A=[];let I=b;for(;I instanceof re;)A.push(I.argumentList),I=I.callee;return A.push(I),A}).forEach(b=>{const{functional:A,nonFunctional:I}=ct(b).unwrap();r.columns.push(...A.map(v=>({value:v.value.value,type:"expression",token:L(v)})),...I.map(v=>({value:j(v).unwrap(),type:"column",token:L(v)})))}),r})),[]}}class zl{constructor(t,n){this.declarationNode=t,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[],tablePartials:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),this.project.token=L(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){if(!t)return this.project.name=null,[];const{name:n}=Be(t);return this.project.name=n,[]}interpretBody(t){return t.body.flatMap(n=>{var s;const r=n;switch((s=r.type)==null?void 0:s.value.toLowerCase()){case"table":{const i=new kr(r,this.env).interpret();return this.project.tables.push(this.env.tables.get(r)),i}case"ref":{const i=new Ur(r,this.env).interpret();return this.project.refs.push(this.env.ref.get(r)),i}case"tablegroup":{const i=new Mr(r,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(r)),i}case"enum":{const i=new Fr(r,this.env).interpret();return this.project.enums.push(this.env.enums.get(r)),i}case"note":return this.project.note={value:V(r.body instanceof fe?r.body.body[0].callee:r.body.callee).map(le).unwrap(),token:L(r)},[];case"tablepartial":{const i=new Br(r,this.env).interpret();return this.project.tablePartials.push(this.env.tablePartials.get(r)),i}default:return this.project[r.type.value.toLowerCase()]=V(r.body.callee).unwrap(),[]}})}}function ql(e){return{schemas:[],tables:Array.from(e.tables.values()),notes:Array.from(e.notes.values()),refs:Array.from(e.ref.values()),enums:Array.from(e.enums.values()),tableGroups:Array.from(e.tableGroups.values()),aliases:e.aliases,project:Array.from(e.project.values())[0]||{},tablePartials:Array.from(e.tablePartials.values())}}class Yl{constructor(t){this.ast=t,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map,tablePartials:new Map}}interpret(){const t=this.ast.body.flatMap(n=>{switch(Re(n).unwrap_or(void 0)){case _.Table:return new kr(n,this.env).interpret();case _.Note:return new Hl(n,this.env).interpret();case _.Ref:return new Ur(n,this.env).interpret();case _.TableGroup:return new Mr(n,this.env).interpret();case _.TablePartial:return new Br(n,this.env).interpret();case _.Enum:return new Fr(n,this.env).interpret();case _.Project:return new zl(n,this.env).interpret();default:return[]}});return new ee(ql(this.env),t)}}var S=(e=>(e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.User=25]="User",e[e.Issue=26]="Issue",e[e.Snippet=27]="Snippet",e))(S||{}),U=(e=>(e[e.None=0]="None",e[e.KeepWhitespace=1]="KeepWhitespace",e[e.InsertAsSnippet=4]="InsertAsSnippet",e))(U||{});function Ze(e){switch(e){case m.Schema:return S.Module;case m.Table:case m.TablePartial:return S.Class;case m.Column:case m.TableGroupField:return S.Field;case m.Enum:return S.Enum;case m.EnumField:return S.EnumMember;case m.TableGroup:return S.Struct;default:return S.Text}}function ht(e,t){if(!e||kt(e))return!1;for(const n of e.trailingTrivia){if(n.start>t)break;if(n.kind===f.NEWLINE&&n.end<=t)return!1}return!0}function C(){return{suggestions:[]}}function ft(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:` ${t.insertText}`}))}}function Lt(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:t.insertText.split("").every(gt)?t.insertText:`"${t.insertText}"`}))}}function Zt(e,t){return e.getOffsetAt(t)}class Gr{constructor(t,n=[]){this.compiler=t,this.triggerCharacters=n}provideCompletionItems(t,n){var h,d;const r=Zt(t,n),s=this.compiler.token.flatStream(),{token:i,index:a}=this.compiler.container.token(r),o=a===void 0?s[0]:s[a+1];if([...(i==null?void 0:i.trailingTrivia)||[],...(i==null?void 0:i.leadingTrivia)||[],...(o==null?void 0:o.leadingTrivia)||[]].find(E=>Co(E)&&qe(r,E)))return C();if(a===void 0)return $n();if([f.STRING_LITERAL,f.QUOTED_STRING].includes(i.kind)&&qe(r,i))return C();const u=this.compiler.container.element(r);if(this.compiler.container.scopeKind(r)===k.TOPLEVEL||u instanceof P&&u.type&&u.type.start<=r&&u.type.end>=r)return $n();const p=[...this.compiler.container.stack(r)].reverse();for(const E of p)if(E instanceof ne)switch((h=E.op)==null?void 0:h.value){case">":case"<":case"<>":case"-":return Bn(this.compiler,r,E)}else if(E instanceof de)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return Bn(this.compiler,r,E);case".":return Vr(this.compiler,r,E)}else{if(E instanceof ae)return Gn(this.compiler,r,E);if(E instanceof B)return Gn(this.compiler,r,E);if(E instanceof Ee)return Kl(this.compiler,r);if(E instanceof xe)return Ql(this.compiler,r);if(E instanceof w)return Cn(this.compiler,r,E);if(E instanceof P&&(E.bodyColon&&r>=E.bodyColon.end||E.body&&qe(r,E.body)))return Cn(this.compiler,r,void 0)}return C()}}function Ql(e,t){const n=e.container.element(t);return tt(e,t,n,[m.TablePartial])}function Bn(e,t,n){const r=e.container.scopeKind(t);if([k.REF,k.TABLE,k.TABLEPARTIAL].includes(r)){const s=tt(e,t,e.container.element(t),[m.Table,m.Schema,m.Column]);return ht(n.op,t)?ft(s):s}return C()}function tt(e,t,n,r){var a;if(n===void 0)return C();let s=n;const i={suggestions:[]};for(;s;){if((a=s==null?void 0:s.symbol)!=null&&a.symbolTable){const{symbol:o}=s;i.suggestions.push(...e.symbol.members(o).filter(({kind:u})=>r.includes(u)).map(({name:u,kind:p})=>({label:u,insertText:u,insertTextRules:U.KeepWhitespace,kind:Ze(p),sortText:Ze(p).toString().padStart(2,"0"),range:void 0})))}s=s instanceof P?s.parent:void 0}return Lt(i)}function Kl(e,t){var r;switch(e.container.scopeKind(t)){case k.INDEXES:return $r(e,t);case k.REF:{const s=[...e.container.stack(t)];for(;s.length>0;){const i=s.pop();if(i instanceof de&&((r=i.op)==null?void 0:r.value)===".")return Vr(e,t,i)}}return Cr(e,t)}return C()}function Gn(e,t,n){const{token:r}=e.container.token(t);if([f.COMMA,f.LBRACKET].includes(r==null?void 0:r.kind)){const s=Vn(e,t);return(r==null?void 0:r.kind)===f.COMMA&&ht(r,t)?ft(s):s}if(n.name&&n.name.start<=t&&n.name.end>=t)return Vn(e,t);if(n.name instanceof ie){const s=Jl(e,t,Ce(n.name).unwrap_or(""));return(r==null?void 0:r.kind)===f.COLON&&ht(r,t)?ft(s):s}return C()}function Vn(e,t){const n=e.container.element(t);if(n instanceof te)return C();const r=e.container.scopeKind(t);if(n.body&&!qe(t,n.body)){let s;switch(r){case k.TABLE:case k.TABLEPARTIAL:s=[N.HeaderColor,N.Note];break;case k.TABLEGROUP:s=[N.Color,N.Note];break;default:s=[]}return{suggestions:s.map(i=>({label:i,insertText:`${i}: `,kind:S.Field,insertTextRules:U.KeepWhitespace,range:void 0}))}}switch(r){case k.TABLE:case k.TABLEPARTIAL:return{suggestions:[...[N.PK,N.PKey,N.Null,N.NotNull,N.Increment,N.Unique].map(s=>({label:s,insertText:s,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0})),...[N.Ref,N.Default,N.Note].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case k.ENUM:return{suggestions:[...[N.Note].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case k.INDEXES:return{suggestions:[...[N.Unique,N.PK].map(s=>({label:s,insertText:s,insertTextRules:U.KeepWhitespace,kind:S.Property,range:void 0})),...[N.Note,N.Name,N.Type].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case k.REF:return{suggestions:[N.Update,N.Delete,N.Color].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))}}return C()}function Jl(e,t,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(r=>({label:r,insertText:r,kind:S.Value,insertTextRules:U.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(r=>({label:r,insertText:`${r}`,kind:S.Value,insertTextRules:U.KeepWhitespace,range:void 0}))}}return C()}function Vr(e,t,n){const r=Fe(n).unwrap_or([]);if(r.pop(),r.some(i=>!X(i)))return C();const s=r.map(i=>z(i).unwrap());return Lt({suggestions:e.symbol.ofName({nameStack:s,owner:e.container.element(t)}).flatMap(({symbol:i})=>e.symbol.members(i)).map(({kind:i,name:a})=>({label:a,insertText:a,kind:Ze(i),range:void 0}))})}function Cn(e,t,n){var s;switch(e.container.scopeKind(t)){case k.TABLE:case k.TABLEPARTIAL:return ec(e,t,n);case k.PROJECT:return tc(e,t,n);case k.INDEXES:return rc(e,t);case k.ENUM:return Zl(e,t,n);case k.REF:{const i=Cr(e,t);return((s=e.container.token(t).token)==null?void 0:s.kind)===f.COLON&&ht(e.container.token(t).token,t)?ft(i):i}case k.TABLEGROUP:return nc(e);default:return C()}}function $n(){return{suggestions:["Table","TableGroup","Enum","Project","Ref","TablePartial"].map(e=>({label:e,insertText:e,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}}function Zl(e,t,n){return n!=null&&n.callee&&en(t,n)===1?tt(e,t,e.container.element(t),[m.Schema,m.Table,m.Column]):C()}function ec(e,t,n){const r=["Note","indexes"];if(!(n!=null&&n.callee))return{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))};const s=en(t,n);return s===0?{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}:s===1?sc(e,t):C()}function tc(e,t,n){const r=["Table","TableGroup","Enum","Note","Ref","TablePartial"];return n!=null&&n.callee?en(t,n)===0?{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}:C():{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}}function Cr(e,t){return tt(e,t,e.container.element(t),[m.Schema,m.Table,m.Column])}function nc(e){return{suggestions:[...Lt({suggestions:[...e.parse.publicSymbolTable().entries()].flatMap(([t])=>{const n=oe(t).unwrap_or(void 0);if(n===void 0)return[];const{kind:r,name:s}=n;return r!==m.Table&&r!==m.Schema?[]:{label:s,insertText:s,insertTextRules:U.KeepWhitespace,kind:Ze(r),range:void 0}})}).suggestions,...["Note"].map(t=>({label:t,insertText:t,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))]}}function rc(e,t){return $r(e,t)}function sc(e,t){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:U.KeepWhitespace,kind:S.TypeParameter,sortText:S.TypeParameter.toString().padStart(2,"0"),range:void 0})),...tt(e,t,e.container.element(t),[m.Enum,m.Schema]).suggestions]}}function $r(e,t){const n=e.container.element(t),r=n==null?void 0:n.parent;if(!((r==null?void 0:r.symbol)instanceof Ir))return C();const{symbolTable:s}=r.symbol;return Lt({suggestions:[...s.entries()].flatMap(([i])=>{const a=oe(i).unwrap_or(void 0);if(a===void 0)return[];const{name:o}=a;return{label:o,insertText:o,insertTextRules:U.KeepWhitespace,kind:Ze(m.Column),range:void 0}})})}function en(e,t){if(!t.callee)return-1;const n=[t.callee,...t.args],r=n.findIndex(s=>e<=s.end);return r===-1?n.length:r}class jr{constructor(t){this.compiler=t}provideDefinition(t,n){var a,o;const{uri:r}=t,s=Zt(t,n),i=[...this.compiler.container.stack(s)];for(;i.length!==0;){const u=i.pop();if(!(u!=null&&u.referee))continue;let p;if((a=u.referee)!=null&&a.declaration&&[Pe.PRIMARY_EXPRESSION,Pe.VARIABLE,Pe.PARTIAL_INJECTION].includes(u==null?void 0:u.kind)?{declaration:p}=u.referee:(o=u.referee)!=null&&o.injectorDeclaration&&(p=u.referee.injectorDeclaration),p){const{startPos:h,endPos:d}=p;return[{range:{startColumn:h.column+1,startLineNumber:h.line+1,endColumn:d.column+1,endLineNumber:d.line+1},uri:r}]}}return[]}}class Xr{constructor(t){this.compiler=t}provideReferences(t,n){const{uri:r}=t,s=Zt(t,n),i=[...this.compiler.container.stack(s)];for(;i.length!==0;){const a=i.pop();if(a&&[Pe.ELEMENT_DECLARATION,Pe.FUNCTION_APPLICATION,Pe.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:o}=a;if(o!=null&&o.references.length)return o.references.map(({startPos:u,endPos:p})=>({range:{startColumn:u.column+1,startLineNumber:u.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:r}))}}return[]}}const ic=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:U,CompletionItemKind:S,DBMLCompletionItemProvider:Gr,DBMLDefinitionProvider:jr,DBMLReferencesProvider:Xr},Symbol.toStringTag,{value:"Module"}));var k=(e=>(e[e.TABLE=0]="TABLE",e[e.ENUM=1]="ENUM",e[e.TABLEGROUP=2]="TABLEGROUP",e[e.INDEXES=3]="INDEXES",e[e.NOTE=4]="NOTE",e[e.REF=5]="REF",e[e.PROJECT=6]="PROJECT",e[e.CUSTOM=7]="CUSTOM",e[e.TOPLEVEL=8]="TOPLEVEL",e[e.TABLEPARTIAL=9]="TABLEPARTIAL",e))(k||{});class ac{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new $o,this.symbolIdGenerator=new qo,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(_r)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(t=>[...t.leadingInvalid,t,...t.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const t=new cl(this.source).lex().chain(n=>new fl(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:r})=>new Wl(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:r})));return t.getErrors().length>0?t:t.chain(({ast:n,tokens:r})=>new Yl(n).interpret().map(i=>({ast:n,tokens:r,rawDb:i})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,t=>{const n=this.token.flatStream(),{index:r,token:s}=this.container.token(t),i=r===void 0?-1:Uo(n,p=>!p.isInvalid,r);if(i===-1)return[this.parse.ast()];const a=n[i].start;let o=this.parse.ast();const u=[o];for(;;){const h=ll(o).find(d=>qe(a,d));if(h===void 0||h instanceof Z)break;u.push(h),o=h}if((s==null?void 0:s.kind)===f.COLON)return u;for(;u.length>0;){let p=!1;const h=F(u);if(h instanceof w){const d=this.parse.source();for(let E=h.end;E<t;E+=1)d[E]===`
12
- `&&(u.pop(),p=!0)}else h instanceof ne||h instanceof de?this.container.token(t).token!==h.op&&(u.pop(),p=!0):h instanceof B?h.listCloseBracket&&h.end<=t&&(u.pop(),p=!0):h instanceof Ee?h.tupleCloseParen&&h.end<=t&&(u.pop(),p=!0):h instanceof fe?h.blockCloseBrace&&h.end<=t&&(u.pop(),p=!0):h instanceof ie||h.end<t&&(u.pop(),p=!0);if(p){const d=F(u);d instanceof P&&d.end<=t&&u.pop()}if(!p)break}return u}),token:this.createQuery(11,t=>{const n=this.token.flatStream().findIndex(r=>r.start>=t);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,t=>{const n=this.container.stack(t);for(let r=n.length-1;r>=0;r-=1)if(n[r]instanceof P)return n[r];return this.parse.ast()}),scope:this.createQuery(14,t=>{var n,r;return(r=(n=this.container.element(t))==null?void 0:n.symbol)==null?void 0:r.symbolTable}),scopeKind:this.createQuery(15,t=>{var r;if(this.container.element(t)instanceof te)return 8;switch((r=this.container.element(t).type)==null?void 0:r.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;case"tablepartial":return 9;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:t,owner:n=this.parse.ast()})=>{var s;if(t.length===0)return[];const r=[];for(let i=n;i;i=i instanceof P?i.parent:void 0){if(!((s=i.symbol)!=null&&s.symbolTable))continue;const{symbolTable:a}=i.symbol;let o=[a],u=[];for(const p of t)u=o.flatMap(h=>nl(p).flatMap(d=>{const E=h.get(d),b=oe(d).unwrap_or(void 0);return!E||!b?[]:{...b,symbol:E}})),o=u.flatMap(h=>h.symbol.symbolTable?h.symbol.symbolTable:[]);r.push(...u)}return r},({nameStack:t,owner:n})=>`${t.join(".")}@${n.id}`),members:this.createQuery(9,t=>t.symbolTable?[...t.symbolTable.entries()].map(([n,r])=>({...oe(n).unwrap(),symbol:r})):[])}}createQuery(t,n,r){return s=>{const i=this.cache[t],a=s&&r?r(s):s;if(i!==null){if(!(i instanceof Map))return i;if(i.has(a))return i.get(a)}const o=n(s);return s!==void 0?i instanceof Map?i.set(a,o):(this.cache[t]=new Map,this.cache[t].set(a,o)):this.cache[t]=o,o}}setSource(t){this.source=t,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new jr(this),referenceProvider:new Xr(this),autocompletionProvider:new Gr(this)}}}exports.Compiler=ac;exports.serialize=jo;exports.services=ic;
11
+ `)}function Dr(e){if(e){if(Y(e))return{value:V(e).unwrap(),type:"string"};if(ke(e))return{type:"number",value:Ut(e)};if(we(e))return{value:e.expression.variable.value.toLowerCase(),type:"boolean"};if(e instanceof Te&&e.value)return{value:e.value.value,type:"expression"};throw new Error("Unreachable")}}function Rr(e){let t=null;e instanceof re&&(t=e.argumentList.elementList.map(i=>ke(i)?gr(i):Y(i)?V(i).unwrap():q(i).unwrap()).join(","),e=e.callee);let n="";for(;e instanceof De;)n=`[${e.indexer.elementList.map(i=>i.name.expression.literal.value).join(",")}]${n}`,e=e.array;const{name:r,schemaName:s}=Be(e);return s.length>1?new te({schemaName:s.length===0?null:s[0],type_name:`${r}${n}${t?`(${t})`:""}`,args:t},[new c(l.UNSUPPORTED,"Nested schema is not supported",e)]):new te({schemaName:s.length===0?null:s[0],type_name:`${r}${n}${t?`(${t})`:""}`,args:t})}class kr{constructor(t,n){this.declarationNode=t,this.env=n,this.table={name:void 0,schemaName:void 0,alias:null,fields:[],token:void 0,indexes:[],partials:[]},this.pkColumns=[]}interpret(){this.table.token=L(this.declarationNode),this.env.tables.set(this.declarationNode,this.table);const t=[...this.interpretName(this.declarationNode.name),...this.interpretAlias(this.declarationNode.alias),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.table.indexes.push({columns:this.pkColumns.map(({name:n,token:r})=>({value:n,type:"column",token:r})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>{n.pk=!1})),t}interpretName(t){const{name:n,schemaName:r}=Be(t);return r.length>1?(this.table.name=n,this.table.schemaName=r.join("."),[new c(l.UNSUPPORTED,"Nested schema is not supported",t)]):(this.table.name=n,this.table.schemaName=r.length?r[0]:null,[])}interpretAlias(t){if(!t)return[];const n=j(t).unwrap_or(null);return n&&(this.env.aliases.push({name:n,kind:"table",value:{tableName:this.table.name,schemaName:this.table.schemaName}}),this.table.alias=n),[]}interpretSettingList(t){var s,i,a;const n=G(t).getValue();this.table.headerColor=(s=n[N.HeaderColor])!=null&&s.length?et((a=(i=n[N.HeaderColor])==null?void 0:i.at(0))==null?void 0:a.value):void 0;const[r]=n[N.Note]||[];return this.table.note=r&&{value:V(r==null?void 0:r.value).map(le).unwrap(),token:L(r)},[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w||s instanceof xe);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case _.Note:return this.table.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)},[];case _.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretInjection(t,n){const r={order:n,token:L(t)};return r.name=t.partial.variable.value,this.table.partials.push(r),[]}interpretFields(t){var a;const s=((a=this.declarationNode.symbol)!=null&&a.symbolTable?[...this.declarationNode.symbol.symbolTable.entries()]:[]).filter(([o])=>{const u=oe(o).unwrap_or(null);return(u==null?void 0:u.kind)===m.Column}).length?[]:[new c(l.EMPTY_TABLE,"A Table must have at least one column",this.declarationNode)],i=t.flatMap((o,u)=>o instanceof w?this.interpretColumn(o):this.interpretInjection(o,u));return[...s,...i]}interpretColumn(t){var a,o,u,p,h,d,E,b,A;const n=[],r={};r.name=j(t.callee).unwrap();const s=Rr(t.args[0]);r.type=s.getValue(),n.push(...s.getErrors()),r.token=L(t),r.inline_refs=[];const i=t.args.slice(1);if(F(i)instanceof B){const I=G(i.pop()).getValue();r.pk=!!((a=I[N.PK])!=null&&a.length)||!!((o=I[N.PKey])!=null&&o.length),r.increment=!!((u=I[N.Increment])!=null&&u.length),r.unique=!!((p=I[N.Unique])!=null&&p.length),r.not_null=(h=I[N.NotNull])!=null&&h.length?!0:(d=I[N.Null])!=null&&d.length?!1:void 0,r.dbdefault=Dr((b=(E=I[N.Default])==null?void 0:E.at(0))==null?void 0:b.value);const v=(A=I[N.Note])==null?void 0:A.at(0);r.note=v&&{value:V(v.value).map(le).unwrap(),token:L(v)};const W=I[N.Ref]||[];r.inline_refs=W.flatMap(y=>{const[Pe]=ut(y.value.expression);if(Jt(Pe,t.symbol))return n.push(new c(l.SAME_ENDPOINT,"Two endpoints are the same",y)),[];const Q=y.value.op,k=K(y.value.expression).unwrap();let se;if(k.length===1){const[J]=k;se={schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[J],relation:Q.value,token:L(y)}}else if(k.length===2){const[J,Le]=k;se={schemaName:null,tableName:J,fieldNames:[Le],relation:Q.value,token:L(y)}}else if(k.length===3){const[J,Le,tn]=k;se={schemaName:J,tableName:Le,fieldNames:[tn],relation:Q.value,token:L(y)}}else{n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",y));const J=k.pop(),Le=k.pop();se={schemaName:k.join("."),tableName:Le,fieldNames:[J],relation:Q.value,token:L(y)}}const Ae=this.registerInlineRefToEnv(t,Pe,se,y);return n.push(...Ae),Ae.length===0?se:[]})}return r.pk||(r.pk=i.some(I=>q(I).unwrap().toLowerCase()==="pk")),r.unique||(r.unique=i.some(I=>q(I).unwrap().toLowerCase()==="unique")),this.table.fields.push(r),r.pk&&this.pkColumns.push(r),n}interpretIndexes(t){return this.table.indexes.push(...t.body.body.map(n=>{var a,o,u,p,h,d,E;const r={columns:[]},s=n;r.token=L(s);const i=[s.callee,...s.args];if(F(i)instanceof B){const b=G(i.pop()).getValue();r.pk=!!((a=b[N.PK])!=null&&a.length),r.unique=!!((o=b[N.Unique])!=null&&o.length),r.name=V((p=(u=b[N.Name])==null?void 0:u.at(0))==null?void 0:p.value).unwrap_or(void 0);const A=(h=b[N.Note])==null?void 0:h.at(0);r.note=A&&{value:V(A.value).unwrap(),token:L(A)},r.type=q((E=(d=b[N.Type])==null?void 0:d.at(0))==null?void 0:E.value).unwrap_or(void 0)}return i.flatMap(b=>{if(!(b instanceof re))return b;const A=[];for(;b instanceof re;)A.push(b.argumentList),b=b.callee;return A.push(b),A}).forEach(b=>{const{functional:A,nonFunctional:I}=ct(b).unwrap();r.columns.push(...A.map(v=>({value:v.value.value,type:"expression",token:L(v)})),...I.map(v=>({value:j(v).unwrap(),type:"column",token:L(v)})))}),r})),[]}registerInlineRefToEnv(t,n,r,s){const i=xr(t.symbol,n);if(this.env.refIds[i])return[new c(l.CIRCULAR_REF,"References with same endpoints exist",s),new c(l.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[i])];const a=Or(r.relation);return this.env.refIds[i]=s,this.env.ref.set(s,{name:null,schemaName:null,token:r.token,endpoints:[{...r,relation:a[1]},{schemaName:this.table.schemaName,tableName:this.table.name,fieldNames:[q(t.callee).unwrap()],token:L(t),relation:a[0]}]}),[]}}class Hl{constructor(t,n){this.declarationNode=t,this.env=n,this.note={name:void 0,content:void 0,token:void 0}}interpret(){return this.note.token=L(this.declarationNode),this.env.notes.set(this.declarationNode,this.note),[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const{name:n}=Be(t);return this.note.name=n,[]}interpretSettingList(t){var r,s,i;const n=G(t).getValue();return this.note.headerColor=(r=n.headercolor)!=null&&r.length?et((i=(s=n.headercolor)==null?void 0:s.at(0))==null?void 0:i.value):void 0,[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return n.length!==1||r.length>0?[new c(l.INVALID_NOTE,"Invalid note syntax",t)]:[...this.interpretNote(n[0])]}interpretNote(t){const n=ir(t,"callee.expression.literal.value","");return this.note.content=le(n),[]}}class Ur{constructor(t,n){this.declarationNode=t,this.env=n,this.container=this.declarationNode.parent instanceof P?this.env.tables.get(this.declarationNode.parent):void 0,this.ref={}}interpret(){return this.ref.token=L(this.declarationNode),this.env.ref.set(this.declarationNode,this.ref),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const n=[],r=K(this.declarationNode.name).unwrap_or([]);return this.ref.name=r.pop()||null,r.length>1&&n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name)),this.ref.schemaName=r.join(".")||null,n}interpretBody(t){return t instanceof w?this.interpretField(t):this.interpretField(t.body[0])}interpretField(t){var p,h,d,E,b,A,I;const n=t.callee.op.value,{leftExpression:r,rightExpression:s}=t.callee,i=ut(r),a=ut(s);if(Jt(i,a))return[new c(l.SAME_ENDPOINT,"Two endpoints are the same",t)];const o=xr(i,a);if(this.env.refIds[o])return[new c(l.CIRCULAR_REF,"References with same endpoints exist",this.declarationNode),new c(l.CIRCULAR_REF,"References with same endpoints exist",this.env.refIds[o])];if(t.args[0]){const v=G(t.args[0]).getValue(),W=(h=(p=v.delete)==null?void 0:p.at(0))==null?void 0:h.value;this.ref.onDelete=W instanceof ie?Ce(W).unwrap_or(void 0):q(W).unwrap_or(void 0);const y=(E=(d=v.update)==null?void 0:d.at(0))==null?void 0:E.value;this.ref.onUpdate=y instanceof ie?Ce(y).unwrap_or(void 0):q(y).unwrap_or(void 0),this.ref.color=(b=v.color)!=null&&b.length?et((I=(A=v.color)==null?void 0:A.at(0))==null?void 0:I.value):void 0}const u=Or(n);return this.ref.endpoints=[{...Fn(r,this.container),relation:u[0],token:L(r)},{...Fn(s,this.container),relation:u[1],token:L(s)}],this.env.refIds[o]=this.declarationNode,[]}}class Mr{constructor(t,n){this.declarationNode=t,this.env=n,this.tableGroup={tables:[]}}interpret(){const t=[];return this.tableGroup.token=L(this.declarationNode),this.env.tableGroups.set(this.declarationNode,this.tableGroup),t.push(...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)),t}interpretName(t){const n=[],{name:r,schemaName:s}=Be(t);return s.length>=2&&(this.tableGroup.name=r,this.tableGroup.schemaName=s.join("."),n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",this.declarationNode.name))),this.tableGroup.name=r,this.tableGroup.schemaName=s[0]||null,n}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case"note":this.tableGroup.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)};break}return[]})}interpretFields(t){const n=[];return this.tableGroup.tables=t.map(r=>{const s=K(r.callee).unwrap();s.length>2&&n.push(new c(l.UNSUPPORTED,"Nested schema is not supported",r));const i=Fe(r.callee).unwrap().pop().referee.id;if(this.env.groupOfTable[i]){const a=this.env.groupOfTable[i],{schemaName:o,name:u}=this.env.tableGroups.get(a),p=o?`${o}.${u}`:u;n.push(new c(l.TABLE_REAPPEAR_IN_TABLEGROUP,`Table "${s.join(".")}" already appears in group "${p}"`,r))}else this.env.groupOfTable[i]=this.declarationNode;return{name:s.pop(),schemaName:s.join(".")}}),n}interpretSettingList(t){var s,i,a;const n=G(t).getValue();this.tableGroup.color=(s=n.color)!=null&&s.length?et((a=(i=n.color)==null?void 0:i.at(0))==null?void 0:a.value):void 0;const[r]=n.note||[];return this.tableGroup.note=r&&{value:V(r==null?void 0:r.value).map(le).unwrap(),token:L(r)},[]}}class Fr{constructor(t,n){this.declarationNode=t,this.env=n,this.enum={values:[]}}interpret(){return this.enum.token=L(this.declarationNode),this.env.enums.set(this.declarationNode,this.enum),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){const{name:n,schemaName:r}=Be(t);return r.length>1?(this.enum.name=n,this.enum.schemaName=r.join("."),[new c(l.UNSUPPORTED,"Nested schema is not supported",t)]):(this.enum.name=n,this.enum.schemaName=r.length?r[0]:null,[])}interpretBody(t){return t.body.flatMap(n=>{var o;const r=n,s={};s.token=L(r),s.name=q(r.callee).unwrap();const a=(o=G(r.args[0]).getValue().note)==null?void 0:o.at(0);return s.note=a&&{value:V(a.value).map(le).unwrap(),token:L(a)},this.enum.values.push(s),[]})}}class Br{constructor(t,n){this.declarationNode=t,this.env=n,this.tablePartial={name:void 0,fields:[],token:void 0,indexes:[]},this.pkColumns=[]}interpret(){this.tablePartial.token=L(this.declarationNode),this.env.tablePartials.set(this.declarationNode,this.tablePartial);const t=[...this.interpretName(this.declarationNode.name),...this.interpretSettingList(this.declarationNode.attributeList),...this.interpretBody(this.declarationNode.body)];return this.pkColumns.length>=2&&(this.tablePartial.indexes.push({columns:this.pkColumns.map(({name:n,token:r})=>({value:n,type:"column",token:r})),token:{start:{offset:-1,line:-1,column:-1},end:{offset:-1,line:-1,column:-1}},pk:!0}),this.pkColumns.forEach(n=>{n.pk=!1})),t}interpretName(t){const{name:n}=Be(t);return this.tablePartial.name=n,[]}interpretSettingList(t){const n=G(t).getValue(),r=Mo(n[N.HeaderColor]);this.tablePartial.headerColor=r?et(r.value):void 0;const[s]=n[N.Note]||[];return this.tablePartial.note=s&&{value:V(s==null?void 0:s.value).map(le).unwrap(),token:L(s)},[]}interpretBody(t){const[n,r]=he(t.body,s=>s instanceof w);return[...this.interpretFields(n),...this.interpretSubElements(r)]}interpretSubElements(t){return t.flatMap(n=>{var r;switch((r=n.type)==null?void 0:r.value.toLowerCase()){case _.Note:return this.tablePartial.note={value:V(n.body instanceof fe?n.body.body[0].callee:n.body.callee).map(le).unwrap(),token:L(n)},[];case _.Indexes:return this.interpretIndexes(n);default:return[]}})}interpretFields(t){return t.flatMap(n=>this.interpretColumn(n))}interpretColumn(t){var a,o,u,p,h,d,E,b,A;const n=[],r={};r.name=j(t.callee).unwrap();const s=Rr(t.args[0]);r.type=s.getValue(),n.push(...s.getErrors()),r.token=L(t),r.inline_refs=[];const i=t.args.slice(1);if(F(i)instanceof B){const I=G(i.pop()).getValue();r.pk=!!((a=I[N.PK])!=null&&a.length)||!!((o=I[N.PKey])!=null&&o.length),r.increment=!!((u=I[N.Increment])!=null&&u.length),r.unique=!!((p=I[N.Unique])!=null&&p.length),r.not_null=(h=I[N.NotNull])!=null&&h.length?!0:(d=I[N.Null])!=null&&d.length?!1:void 0,r.dbdefault=Dr((b=(E=I[N.Default])==null?void 0:E.at(0))==null?void 0:b.value);const v=(A=I[N.Note])==null?void 0:A.at(0);r.note=v&&{value:V(v.value).map(le).unwrap(),token:L(v)};const W=I[N.Ref]||[];r.inline_refs=W.flatMap(y=>{const[Pe]=ut(y.value.expression);if(Jt(Pe,t.symbol))return n.push(new c(l.SAME_ENDPOINT,"Two endpoints are the same",y)),[];const Q=y.value.op,k=K(y.value.expression).unwrap();let se;if(k.length===2){const[Ae,J]=k;se={schemaName:null,tableName:Ae,fieldNames:[J],relation:Q.value,token:L(y)}}else if(k.length===3){const[Ae,J,Le]=k;se={schemaName:Ae,tableName:J,fieldNames:[Le],relation:Q.value,token:L(y)}}else{n.push(new c(l.UNSUPPORTED,"Unsupported",y));const Ae=k.pop(),J=k.pop();se={schemaName:k.join("."),tableName:J,fieldNames:[Ae],relation:Q.value,token:L(y)}}return se})}return r.pk||(r.pk=i.some(I=>q(I).unwrap().toLowerCase()==="pk")),r.unique||(r.unique=i.some(I=>q(I).unwrap().toLowerCase()==="unique")),this.tablePartial.fields.push(r),r.pk&&this.pkColumns.push(r),n}interpretIndexes(t){return this.tablePartial.indexes.push(...t.body.body.map(n=>{var a,o,u,p,h,d,E;const r={columns:[]},s=n;r.token=L(s);const i=[s.callee,...s.args];if(F(i)instanceof B){const b=G(i.pop()).getValue();r.pk=!!((a=b[N.PK])!=null&&a.length),r.unique=!!((o=b[N.Unique])!=null&&o.length),r.name=V((p=(u=b[N.Name])==null?void 0:u.at(0))==null?void 0:p.value).unwrap_or(void 0);const A=(h=b[N.Note])==null?void 0:h.at(0);r.note=A&&{value:V(A.value).unwrap(),token:L(A)},r.type=q((E=(d=b[N.Type])==null?void 0:d.at(0))==null?void 0:E.value).unwrap_or(void 0)}return i.flatMap(b=>{if(!(b instanceof re))return b;const A=[];let I=b;for(;I instanceof re;)A.push(I.argumentList),I=I.callee;return A.push(I),A}).forEach(b=>{const{functional:A,nonFunctional:I}=ct(b).unwrap();r.columns.push(...A.map(v=>({value:v.value.value,type:"expression",token:L(v)})),...I.map(v=>({value:j(v).unwrap(),type:"column",token:L(v)})))}),r})),[]}}class zl{constructor(t,n){this.declarationNode=t,this.env=n,this.project={enums:[],refs:[],tableGroups:[],tables:[],tablePartials:[]}}interpret(){return this.env.project.set(this.declarationNode,this.project),this.project.token=L(this.declarationNode),[...this.interpretName(this.declarationNode.name),...this.interpretBody(this.declarationNode.body)]}interpretName(t){if(!t)return this.project.name=null,[];const{name:n}=Be(t);return this.project.name=n,[]}interpretBody(t){return t.body.flatMap(n=>{var s;const r=n;switch((s=r.type)==null?void 0:s.value.toLowerCase()){case"table":{const i=new kr(r,this.env).interpret();return this.project.tables.push(this.env.tables.get(r)),i}case"ref":{const i=new Ur(r,this.env).interpret();return this.project.refs.push(this.env.ref.get(r)),i}case"tablegroup":{const i=new Mr(r,this.env).interpret();return this.project.tableGroups.push(this.env.tableGroups.get(r)),i}case"enum":{const i=new Fr(r,this.env).interpret();return this.project.enums.push(this.env.enums.get(r)),i}case"note":return this.project.note={value:V(r.body instanceof fe?r.body.body[0].callee:r.body.callee).map(le).unwrap(),token:L(r)},[];case"tablepartial":{const i=new Br(r,this.env).interpret();return this.project.tablePartials.push(this.env.tablePartials.get(r)),i}default:return this.project[r.type.value.toLowerCase()]=V(r.body.callee).unwrap(),[]}})}}function ql(e){return{schemas:[],tables:Array.from(e.tables.values()),notes:Array.from(e.notes.values()),refs:Array.from(e.ref.values()),enums:Array.from(e.enums.values()),tableGroups:Array.from(e.tableGroups.values()),aliases:e.aliases,project:Array.from(e.project.values())[0]||{},tablePartials:Array.from(e.tablePartials.values())}}class Yl{constructor(t){this.ast=t,this.env={schema:[],tables:new Map,notes:new Map,refIds:{},ref:new Map,enums:new Map,tableGroups:new Map,groupOfTable:{},aliases:[],project:new Map,tablePartials:new Map}}interpret(){const t=this.ast.body.flatMap(n=>{switch(Re(n).unwrap_or(void 0)){case _.Table:return new kr(n,this.env).interpret();case _.Note:return new Hl(n,this.env).interpret();case _.Ref:return new Ur(n,this.env).interpret();case _.TableGroup:return new Mr(n,this.env).interpret();case _.TablePartial:return new Br(n,this.env).interpret();case _.Enum:return new Fr(n,this.env).interpret();case _.Project:return new zl(n,this.env).interpret();default:return[]}});return new te(ql(this.env),t)}}var S=(e=>(e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.User=25]="User",e[e.Issue=26]="Issue",e[e.Snippet=27]="Snippet",e))(S||{}),U=(e=>(e[e.None=0]="None",e[e.KeepWhitespace=1]="KeepWhitespace",e[e.InsertAsSnippet=4]="InsertAsSnippet",e))(U||{});function Ze(e){switch(e){case m.Schema:return S.Module;case m.Table:case m.TablePartial:return S.Class;case m.Column:case m.TableGroupField:return S.Field;case m.Enum:return S.Enum;case m.EnumField:return S.EnumMember;case m.TableGroup:return S.Struct;default:return S.Text}}function ht(e,t){if(!e||kt(e))return!1;for(const n of e.trailingTrivia){if(n.start>t)break;if(n.kind===f.NEWLINE&&n.end<=t)return!1}return!0}function C(){return{suggestions:[]}}function ft(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:` ${t.insertText}`}))}}function Lt(e){return{...e,suggestions:e.suggestions.map(t=>({...t,insertText:t.insertText.split("").every(gt)?t.insertText:`"${t.insertText}"`}))}}function Zt(e,t){return e.getOffsetAt(t)}class Gr{constructor(t,n=[]){this.compiler=t,this.triggerCharacters=n}provideCompletionItems(t,n){var h,d;const r=Zt(t,n),s=this.compiler.token.flatStream(),{token:i,index:a}=this.compiler.container.token(r),o=a===void 0?s[0]:s[a+1];if([...(i==null?void 0:i.trailingTrivia)||[],...(i==null?void 0:i.leadingTrivia)||[],...(o==null?void 0:o.leadingTrivia)||[]].find(E=>Co(E)&&qe(r,E)))return C();if(a===void 0)return $n();if([f.STRING_LITERAL,f.QUOTED_STRING].includes(i.kind)&&qe(r,i))return C();const u=this.compiler.container.element(r);if(this.compiler.container.scopeKind(r)===R.TOPLEVEL||u instanceof P&&u.type&&u.type.start<=r&&u.type.end>=r)return $n();const p=[...this.compiler.container.stack(r)].reverse();for(const E of p)if(E instanceof ne)switch((h=E.op)==null?void 0:h.value){case">":case"<":case"<>":case"-":return Bn(this.compiler,r,E)}else if(E instanceof de)switch((d=E.op)==null?void 0:d.value){case">":case"<":case"<>":case"-":return Bn(this.compiler,r,E);case".":return Vr(this.compiler,r,E)}else{if(E instanceof ae)return Gn(this.compiler,r,E);if(E instanceof B)return Gn(this.compiler,r,E);if(E instanceof Ee)return Ql(this.compiler,r);if(E instanceof xe)return Kl(this.compiler,r);if(E instanceof w)return Cn(this.compiler,r,E);if(E instanceof P&&(E.bodyColon&&r>=E.bodyColon.end||E.body&&qe(r,E.body)))return Cn(this.compiler,r,void 0)}return C()}}function Kl(e,t){const n=e.container.element(t);return tt(e,t,n,[m.TablePartial])}function Bn(e,t,n){const r=e.container.scopeKind(t);if([R.REF,R.TABLE,R.TABLEPARTIAL].includes(r)){const s=tt(e,t,e.container.element(t),[m.Table,m.Schema,m.Column]);return ht(n.op,t)?ft(s):s}return C()}function tt(e,t,n,r){var a;if(n===void 0)return C();let s=n;const i={suggestions:[]};for(;s;){if((a=s==null?void 0:s.symbol)!=null&&a.symbolTable){const{symbol:o}=s;i.suggestions.push(...e.symbol.members(o).filter(({kind:u})=>r.includes(u)).map(({name:u,kind:p})=>({label:u,insertText:u,insertTextRules:U.KeepWhitespace,kind:Ze(p),sortText:Ze(p).toString().padStart(2,"0"),range:void 0})))}s=s instanceof P?s.parent:void 0}return Lt(i)}function Ql(e,t){var r;switch(e.container.scopeKind(t)){case R.INDEXES:return $r(e,t);case R.REF:{const s=[...e.container.stack(t)];for(;s.length>0;){const i=s.pop();if(i instanceof de&&((r=i.op)==null?void 0:r.value)===".")return Vr(e,t,i)}}return Cr(e,t)}return C()}function Gn(e,t,n){const{token:r}=e.container.token(t);if([f.COMMA,f.LBRACKET].includes(r==null?void 0:r.kind)){const s=Vn(e,t);return(r==null?void 0:r.kind)===f.COMMA&&ht(r,t)?ft(s):s}if(n.name&&n.name.start<=t&&n.name.end>=t)return Vn(e,t);if(n.name instanceof ie){const s=Jl(e,t,Ce(n.name).unwrap_or(""));return(r==null?void 0:r.kind)===f.COLON&&ht(r,t)?ft(s):s}return C()}function Vn(e,t){const n=e.container.element(t);if(n instanceof ee)return C();const r=e.container.scopeKind(t);if(n.body&&!qe(t,n.body)){let s;switch(r){case R.TABLE:case R.TABLEPARTIAL:s=[N.HeaderColor,N.Note];break;case R.TABLEGROUP:s=[N.Color,N.Note];break;default:s=[]}return{suggestions:s.map(i=>({label:i,insertText:`${i}: `,kind:S.Field,insertTextRules:U.KeepWhitespace,range:void 0}))}}switch(r){case R.TABLE:case R.TABLEPARTIAL:return{suggestions:[...[N.PK,N.PKey,N.Null,N.NotNull,N.Increment,N.Unique].map(s=>({label:s,insertText:s,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0})),...[N.Ref,N.Default,N.Note].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case R.ENUM:return{suggestions:[...[N.Note].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case R.INDEXES:return{suggestions:[...[N.Unique,N.PK].map(s=>({label:s,insertText:s,insertTextRules:U.KeepWhitespace,kind:S.Property,range:void 0})),...[N.Note,N.Name,N.Type].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))]};case R.REF:return{suggestions:[N.Update,N.Delete,N.Color].map(s=>({label:s,insertText:`${s}: `,kind:S.Property,insertTextRules:U.KeepWhitespace,range:void 0}))}}return C()}function Jl(e,t,n){switch(n==null?void 0:n.toLowerCase()){case"update":case"delete":return{suggestions:["cascade","set default","set null","restrict"].map(r=>({label:r,insertText:r,kind:S.Value,insertTextRules:U.KeepWhitespace,range:void 0}))};case"type":return{suggestions:["btree","hash"].map(r=>({label:r,insertText:`${r}`,kind:S.Value,insertTextRules:U.KeepWhitespace,range:void 0}))}}return C()}function Vr(e,t,n){const r=Fe(n).unwrap_or([]);if(r.pop(),r.some(i=>!X(i)))return C();const s=r.map(i=>q(i).unwrap());return Lt({suggestions:e.symbol.ofName({nameStack:s,owner:e.container.element(t)}).flatMap(({symbol:i})=>e.symbol.members(i)).map(({kind:i,name:a})=>({label:a,insertText:a,kind:Ze(i),range:void 0}))})}function Cn(e,t,n){var s;switch(e.container.scopeKind(t)){case R.TABLE:case R.TABLEPARTIAL:return ec(e,t,n);case R.PROJECT:return tc(e,t,n);case R.INDEXES:return rc(e,t);case R.ENUM:return Zl(e,t,n);case R.REF:{const i=Cr(e,t);return((s=e.container.token(t).token)==null?void 0:s.kind)===f.COLON&&ht(e.container.token(t).token,t)?ft(i):i}case R.TABLEGROUP:return nc(e);default:return C()}}function $n(){return{suggestions:["Table","TableGroup","Enum","Project","Ref","TablePartial"].map(e=>({label:e,insertText:e,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}}function Zl(e,t,n){return n!=null&&n.callee&&en(t,n)===1?tt(e,t,e.container.element(t),[m.Schema,m.Table,m.Column]):C()}function ec(e,t,n){const r=["Note","indexes"];if(!(n!=null&&n.callee))return{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))};const s=en(t,n);return s===0?{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}:s===1?sc(e,t):C()}function tc(e,t,n){const r=["Table","TableGroup","Enum","Note","Ref","TablePartial"];return n!=null&&n.callee?en(t,n)===0?{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}:C():{suggestions:r.map(i=>({label:i,insertText:i,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))}}function Cr(e,t){return tt(e,t,e.container.element(t),[m.Schema,m.Table,m.Column])}function nc(e){return{suggestions:[...Lt({suggestions:[...e.parse.publicSymbolTable().entries()].flatMap(([t])=>{const n=oe(t).unwrap_or(void 0);if(n===void 0)return[];const{kind:r,name:s}=n;return r!==m.Table&&r!==m.Schema?[]:{label:s,insertText:s,insertTextRules:U.KeepWhitespace,kind:Ze(r),range:void 0}})}).suggestions,...["Note"].map(t=>({label:t,insertText:t,insertTextRules:U.KeepWhitespace,kind:S.Keyword,range:void 0}))]}}function rc(e,t){return $r(e,t)}function sc(e,t){return{suggestions:[...["integer","int","tinyint","smallint","mediumint","bigint","bit","bool","binary","varbinary","logical","char","nchar","varchar","varchar2","nvarchar","nvarchar2","binary_float","binary_double","float","double","decimal","dec","real","money","smallmoney","enum","tinyblob","tinytext","blob","text","mediumblob","mediumtext","longblob","longtext","ntext","set","inet6","uuid","image","date","time","datetime","datetime2","timestamp","year","smalldatetime","datetimeoffset","XML","sql_variant","uniqueidentifier","CURSOR","BFILE","CLOB","NCLOB","RAW"].map(n=>({label:n,insertText:n,insertTextRules:U.KeepWhitespace,kind:S.TypeParameter,sortText:S.TypeParameter.toString().padStart(2,"0"),range:void 0})),...tt(e,t,e.container.element(t),[m.Enum,m.Schema]).suggestions]}}function $r(e,t){const n=e.container.element(t),r=n==null?void 0:n.parent;if(!((r==null?void 0:r.symbol)instanceof Ir))return C();const{symbolTable:s}=r.symbol;return Lt({suggestions:[...s.entries()].flatMap(([i])=>{const a=oe(i).unwrap_or(void 0);if(a===void 0)return[];const{name:o}=a;return{label:o,insertText:o,insertTextRules:U.KeepWhitespace,kind:Ze(m.Column),range:void 0}})})}function en(e,t){if(!t.callee)return-1;const n=[t.callee,...t.args],r=n.findIndex(s=>e<=s.end);return r===-1?n.length:r}class jr{constructor(t){this.compiler=t}provideDefinition(t,n){var a,o;const{uri:r}=t,s=Zt(t,n),i=[...this.compiler.container.stack(s)];for(;i.length!==0;){const u=i.pop();if(!(u!=null&&u.referee))continue;let p;if((a=u.referee)!=null&&a.declaration&&[ye.PRIMARY_EXPRESSION,ye.VARIABLE,ye.PARTIAL_INJECTION].includes(u==null?void 0:u.kind)?{declaration:p}=u.referee:(o=u.referee)!=null&&o.injectorDeclaration&&(p=u.referee.injectorDeclaration),p){const{startPos:h,endPos:d}=p;return[{range:{startColumn:h.column+1,startLineNumber:h.line+1,endColumn:d.column+1,endLineNumber:d.line+1},uri:r}]}}return[]}}class Xr{constructor(t){this.compiler=t}provideReferences(t,n){const{uri:r}=t,s=Zt(t,n),i=[...this.compiler.container.stack(s)];for(;i.length!==0;){const a=i.pop();if(a&&[ye.ELEMENT_DECLARATION,ye.FUNCTION_APPLICATION,ye.PRIMARY_EXPRESSION].includes(a==null?void 0:a.kind)){const{symbol:o}=a;if(o!=null&&o.references.length)return o.references.map(({startPos:u,endPos:p})=>({range:{startColumn:u.column+1,startLineNumber:u.line+1,endColumn:p.column+1,endLineNumber:p.line+1},uri:r}))}}return[]}}const ic=Object.freeze(Object.defineProperty({__proto__:null,CompletionItemInsertTextRule:U,CompletionItemKind:S,DBMLCompletionItemProvider:Gr,DBMLDefinitionProvider:jr,DBMLReferencesProvider:Xr},Symbol.toStringTag,{value:"Module"}));var R=(e=>(e[e.TABLE=0]="TABLE",e[e.ENUM=1]="ENUM",e[e.TABLEGROUP=2]="TABLEGROUP",e[e.INDEXES=3]="INDEXES",e[e.NOTE=4]="NOTE",e[e.REF=5]="REF",e[e.PROJECT=6]="PROJECT",e[e.CUSTOM=7]="CUSTOM",e[e.TOPLEVEL=8]="TOPLEVEL",e[e.TABLEPARTIAL=9]="TABLEPARTIAL",e))(R||{});class ac{constructor(){this.source="",this.cache=new Array(16).fill(null),this.nodeIdGenerator=new $o,this.symbolIdGenerator=new qo,this.token={invalidStream:this.createQuery(6,()=>this.parse.tokens().filter(_r)),flatStream:this.createQuery(7,()=>this.parse.tokens().flatMap(t=>[...t.leadingInvalid,t,...t.trailingInvalid]))},this.parse={source:()=>this.source,_:this.createQuery(0,()=>{const t=new cl(this.source).lex().chain(n=>new fl(n,this.nodeIdGenerator).parse()).chain(({ast:n,tokens:r})=>new Wl(n,this.symbolIdGenerator).analyze().map(()=>({ast:n,tokens:r})));return t.getErrors().length>0?t:t.chain(({ast:n,tokens:r})=>new Yl(n).interpret().map(i=>({ast:n,tokens:r,rawDb:i})))}),ast:this.createQuery(1,()=>this.parse._().getValue().ast),errors:this.createQuery(2,()=>this.parse._().getErrors()),tokens:this.createQuery(4,()=>this.parse._().getValue().tokens),rawDb:this.createQuery(3,()=>this.parse._().getValue().rawDb),publicSymbolTable:this.createQuery(5,()=>this.parse._().getValue().ast.symbol.symbolTable)},this.container={stack:this.createQuery(10,t=>{const n=this.token.flatStream(),{index:r,token:s}=this.container.token(t),i=r===void 0?-1:Uo(n,p=>!p.isInvalid,r);if(i===-1)return[this.parse.ast()];const a=n[i].start;let o=this.parse.ast();const u=[o];for(;;){const h=ll(o).find(d=>qe(a,d));if(h===void 0||h instanceof z)break;u.push(h),o=h}if((s==null?void 0:s.kind)===f.COLON)return u;for(;u.length>0;){let p=!1;const h=F(u);if(h instanceof w){const d=this.parse.source();for(let E=h.end;E<t;E+=1)d[E]===`
12
+ `&&(u.pop(),p=!0)}else h instanceof ne||h instanceof de?this.container.token(t).token!==h.op&&(u.pop(),p=!0):h instanceof B?h.listCloseBracket&&h.end<=t&&(u.pop(),p=!0):h instanceof Ee?h.tupleCloseParen&&h.end<=t&&(u.pop(),p=!0):h instanceof fe?h.blockCloseBrace&&h.end<=t&&(u.pop(),p=!0):h instanceof ie||h.end<t&&(u.pop(),p=!0);if(p){const d=F(u);d instanceof P&&d.end<=t&&u.pop()}if(!p)break}return u}),token:this.createQuery(11,t=>{const n=this.token.flatStream().findIndex(r=>r.start>=t);return n===void 0?{token:void 0,index:void 0}:n<=0?{token:void 0,index:void 0}:{token:this.token.flatStream()[n-1],index:n-1}}),element:this.createQuery(12,t=>{const n=this.container.stack(t);for(let r=n.length-1;r>=0;r-=1)if(n[r]instanceof P)return n[r];return this.parse.ast()}),scope:this.createQuery(14,t=>{var n,r;return(r=(n=this.container.element(t))==null?void 0:n.symbol)==null?void 0:r.symbolTable}),scopeKind:this.createQuery(15,t=>{var r;if(this.container.element(t)instanceof ee)return 8;switch((r=this.container.element(t).type)==null?void 0:r.value.toLowerCase()){case"table":return 0;case"enum":return 1;case"ref":return 5;case"tablegroup":return 2;case"indexes":return 3;case"note":return 4;case"project":return 6;case"tablepartial":return 9;default:return 7}})},this.symbol={ofName:this.createQuery(8,({nameStack:t,owner:n=this.parse.ast()})=>{var s;if(t.length===0)return[];const r=[];for(let i=n;i;i=i instanceof P?i.parent:void 0){if(!((s=i.symbol)!=null&&s.symbolTable))continue;const{symbolTable:a}=i.symbol;let o=[a],u=[];for(const p of t)u=o.flatMap(h=>nl(p).flatMap(d=>{const E=h.get(d),b=oe(d).unwrap_or(void 0);return!E||!b?[]:{...b,symbol:E}})),o=u.flatMap(h=>h.symbol.symbolTable?h.symbol.symbolTable:[]);r.push(...u)}return r},({nameStack:t,owner:n})=>`${t.join(".")}@${n.id}`),members:this.createQuery(9,t=>t.symbolTable?[...t.symbolTable.entries()].map(([n,r])=>({...oe(n).unwrap(),symbol:r})):[])}}createQuery(t,n,r){return s=>{const i=this.cache[t],a=s&&r?r(s):s;if(i!==null){if(!(i instanceof Map))return i;if(i.has(a))return i.get(a)}const o=n(s);return s!==void 0?i instanceof Map?i.set(a,o):(this.cache[t]=new Map,this.cache[t].set(a,o)):this.cache[t]=o,o}}setSource(t){this.source=t,this.cache=new Array(16).fill(null),this.nodeIdGenerator.reset(),this.symbolIdGenerator.reset()}initMonacoServices(){return{definitionProvider:new jr(this),referenceProvider:new Xr(this),autocompletionProvider:new Gr(this)}}}exports.CompileError=c;exports.CompileErrorCode=l;exports.Compiler=ac;exports.ElementDeclarationNode=P;exports.ElementKind=_;exports.ProgramNode=ee;exports.ScopeKind=R;exports.SyntaxNode=D;exports.SyntaxNodeKind=ye;exports.SyntaxToken=z;exports.SyntaxTokenKind=f;exports.serialize=jo;exports.services=ic;
@@ -5896,7 +5896,17 @@ class ac {
5896
5896
  }
5897
5897
  }
5898
5898
  export {
5899
+ c as CompileError,
5900
+ l as CompileErrorCode,
5899
5901
  ac as Compiler,
5902
+ P as ElementDeclarationNode,
5903
+ _ as ElementKind,
5904
+ te as ProgramNode,
5905
+ k as ScopeKind,
5906
+ D as SyntaxNode,
5907
+ Pe as SyntaxNodeKind,
5908
+ Z as SyntaxToken,
5909
+ f as SyntaxTokenKind,
5900
5910
  sc as serialize,
5901
5911
  ic as services
5902
5912
  };
@@ -1,4 +1,11 @@
1
1
  import { serialize } from './lib/serialization/serialize';
2
2
  import { default as Compiler } from './compiler';
3
3
  import * as services from './services/index';
4
+ export { ElementKind, } from './lib/analyzer/types';
5
+ export { SyntaxNode, ElementDeclarationNode, ProgramNode, SyntaxNodeKind, type SyntaxNodeId, } from './lib/parser/nodes';
6
+ export { SyntaxToken, SyntaxTokenKind, } from './lib/lexer/tokens';
7
+ export { CompileError, CompileErrorCode, } from './lib/errors';
8
+ export { type Position, } from './lib/types';
9
+ export { ScopeKind, } from './compiler';
10
+ export { type Database, type Table, type Column, type Enum, type Ref, type Project, type TableGroup, type TablePartial, } from './lib/interpreter/types';
4
11
  export { serialize, Compiler, services };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dbml/parse",
3
- "version": "3.13.9-alpha.0",
3
+ "version": "3.14.0",
4
4
  "description": "> TODO: description",
5
5
  "author": "Holistics <dev@holistics.io>",
6
6
  "license": "Apache-2.0",
@@ -48,5 +48,5 @@
48
48
  "engines": {
49
49
  "node": ">=18"
50
50
  },
51
- "gitHead": "330b32307bc949fbcd948455af53995eeb70e17c"
51
+ "gitHead": "a3be772822c217e0b8afa975e90fa54b81d38276"
52
52
  }