@jaepil/uqa 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/uqa.umd.js CHANGED
@@ -1,16 +1,16 @@
1
- (function($,K){typeof exports=="object"&&typeof module<"u"?K(exports,require("bayesian-bm25"),require("libpg-query")):typeof define=="function"&&define.amd?define(["exports","bayesian-bm25","libpg-query"],K):($=typeof globalThis<"u"?globalThis:$||self,K($.uqa={},$.BayesianBM25,$.libpgQuery))})(this,(function($,K,rt){"use strict";var Ai=Object.defineProperty;var ki=($,K,rt)=>K in $?Ai($,K,{enumerable:!0,configurable:!0,writable:!0,value:rt}):$[K]=rt;var b=($,K,rt)=>ki($,typeof K!="symbol"?K+"":K,rt);function on(c,e){const t=Math.min(c.length,e.length);for(let n=0;n<t;n++){if(c[n]<e[n])return-1;if(c[n]>e[n])return 1}return c.length-e.length}function os(c,e){if(c.length!==e.length)return!1;for(let t=0;t<c.length;t++)if(c[t]!==e[t])return!1;return!0}function Gn(c){return c.join("\0")}class D{constructor(e){b(this,"_entries");b(this,"_docIdsCache",null);if(e&&e.length>0){const t=e.slice().sort((s,o)=>s.docId-o.docId),n=[t[0]],r=new Set([t[0].docId]);for(let s=1;s<t.length;s++){const o=t[s];r.has(o.docId)||(r.add(o.docId),n.push(o))}this._entries=n}else this._entries=[]}static fromSorted(e){const t=Object.create(D.prototype);return t._entries=e,t._docIdsCache=null,t}union(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o];i.docId===a.docId?(r.push({docId:i.docId,payload:D.mergePayloads(i.payload,a.payload)}),s++,o++):i.docId<a.docId?(r.push(i),s++):(r.push(a),o++)}for(;s<t.length;)r.push(t[s]),s++;for(;o<n.length;)r.push(n[o]),o++;return D.fromSorted(r)}intersect(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o];i.docId===a.docId?(r.push({docId:i.docId,payload:D.mergePayloads(i.payload,a.payload)}),s++,o++):i.docId<a.docId?s++:o++}return D.fromSorted(r)}difference(e){const t=e.docIds,n=this._entries.filter(r=>!t.has(r.docId));return D.fromSorted(n)}complement(e){return e.difference(this)}static mergePayloads(e,t){const r=[...new Set([...e.positions,...t.positions])].sort((i,a)=>i-a),s=e.score+t.score,o={...e.fields,...t.fields};return{positions:r,score:s,fields:o}}get docIds(){return this._docIdsCache===null&&(this._docIdsCache=new Set(this._entries.map(e=>e.docId))),this._docIdsCache}get entries(){return this._entries}getEntry(e){let t=0,n=this._entries.length-1;for(;t<=n;){const r=t+n>>>1,s=this._entries[r].docId;if(s===e)return this._entries[r];s<e?t=r+1:n=r-1}return null}topK(e){if(e>=this._entries.length)return D.fromSorted(this._entries.slice());const n=this._entries.slice().sort((r,s)=>s.payload.score-r.payload.score).slice(0,e);return new D(n)}withScores(e){const t=[];for(const n of this._entries){const r=e(n);t.push({docId:n.docId,payload:{positions:n.payload.positions,score:r,fields:n.payload.fields}})}return D.fromSorted(t)}get length(){return this._entries.length}[Symbol.iterator](){return this._entries[Symbol.iterator]()}equals(e){if(this._entries.length!==e._entries.length)return!1;for(let t=0;t<this._entries.length;t++)if(this._entries[t].docId!==e._entries[t].docId)return!1;return!0}toString(){return`PostingList([${this._entries.map(t=>String(t.docId)).join(", ")}])`}and(e){return this.intersect(e)}or(e){return this.union(e)}sub(e){return this.difference(e)}}class we{constructor(e){b(this,"_entries");this._entries=(e??[]).slice().sort((t,n)=>on(t.docIds,n.docIds))}static fromSorted(e){const t=Object.create(we.prototype);return t._entries=e,t}get entries(){return this._entries.slice()}get length(){return this._entries.length}[Symbol.iterator](){return this._entries[Symbol.iterator]()}union(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o],l=on(i.docIds,a.docIds);l===0?(r.push(i),s++,o++):l<0?(r.push(i),s++):(r.push(a),o++)}for(;s<t.length;)r.push(t[s]),s++;for(;o<n.length;)r.push(n[o]),o++;return we.fromSorted(r)}intersect(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o],l=on(i.docIds,a.docIds);l===0?(r.push(i),s++,o++):l<0?s++:o++}return we.fromSorted(r)}difference(e){const t=e.docIdsSet,n=this._entries.filter(r=>!t.has(Gn(r.docIds)));return we.fromSorted(n)}complement(e){return e.difference(this)}get docIdsSet(){return new Set(this._entries.map(e=>Gn(e.docIds)))}equals(e){if(this._entries.length!==e._entries.length)return!1;for(let t=0;t<this._entries.length;t++)if(!os(this._entries[t].docIds,e._entries[t].docIds))return!1;return!0}toString(){return`GeneralizedPostingList([${this._entries.map(t=>`(${t.docIds.join(", ")})`).join(", ")}])`}and(e){return this.intersect(e)}or(e){return this.union(e)}sub(e){return this.difference(e)}}function U(c){return{positions:(c==null?void 0:c.positions)??[],score:(c==null?void 0:c.score)??0,fields:(c==null?void 0:c.fields)??{}}}function ce(c,e){return{docId:c,payload:U(e)}}function an(c,e,t){return{vertexId:c,label:e,properties:t??{}}}function gt(c,e,t,n,r){return{edgeId:c,sourceId:e,targetId:t,label:n,properties:r??{}}}class Bn{constructor(e=0,t=0,n=0){b(this,"totalDocs");b(this,"avgDocLength");b(this,"dimensions");b(this,"_docFreqs");this.totalDocs=e,this.avgDocLength=t,this.dimensions=n,this._docFreqs=new Map}docFreq(e,t){return this._docFreqs.get(`${e}\0${t}`)??0}setDocFreq(e,t,n){this._docFreqs.set(`${e}\0${t}`,n)}}class ge{}class ln extends ge{constructor(e){super(),this.target=e}evaluate(e){return e===this.target}}class Un extends ge{constructor(e){super(),this.target=e}evaluate(e){return e!==this.target}}class Wn extends ge{constructor(e){super(),this.target=e}evaluate(e){return e>this.target}}class Hn extends ge{constructor(e){super(),this.target=e}evaluate(e){return e>=this.target}}class Kn extends ge{constructor(e){super(),this.target=e}evaluate(e){return e<this.target}}class Jn extends ge{constructor(e){super(),this.target=e}evaluate(e){return e<=this.target}}class cn extends ge{constructor(t){super();b(this,"_values");this._values=new Set(t)}get values(){return this._values}evaluate(t){return this._values.has(t)}}class un extends ge{constructor(e,t){super(),this.low=e,this.high=t}evaluate(e){const t=e;return t>=this.low&&t<=this.high}}class hn extends ge{evaluate(e){return e==null}}class fn extends ge{evaluate(e){return e!=null}}const mt=new Map;function Yn(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function is(c,e){const t=`${e?"s":"i"}:${c}`,n=mt.get(t);if(n!==void 0)return n;if(mt.size>=256){const i=mt.keys().next().value;mt.delete(i)}let r="^";for(let i=0;i<c.length;i++){const a=c[i];a==="%"?r+=".*":a==="_"?r+=".":a==="\\"&&i+1<c.length?(i++,r+=Yn(c[i])):r+=Yn(a)}r+="$";const s=e?"s":"is",o=new RegExp(r,s);return mt.set(t,o),o}function Dt(c,e,t){return is(e,t).test(c)}class Xn extends ge{constructor(e){super(),this.pattern=e}evaluate(e){return Dt(String(e),this.pattern,!0)}}class as extends ge{constructor(e){super(),this.pattern=e}evaluate(e){return!Dt(String(e),this.pattern,!0)}}class Qn extends ge{constructor(e){super(),this.pattern=e}evaluate(e){return Dt(String(e),this.pattern,!1)}}class ls extends ge{constructor(e){super(),this.pattern=e}evaluate(e){return!Dt(String(e),this.pattern,!1)}}function Zn(c){return c instanceof hn||c instanceof fn}class cs{constructor(e,t){b(this,"docId");b(this,"data");this.docId=e,this.data=t}evalPath(e){let t=this.data;for(const n of e){if(t==null)return;if(typeof n=="number"){if(!Array.isArray(t))return;t=t[n]}else if(Array.isArray(t))t=t.map(r=>r[n]);else if(typeof t=="object")t=t[n];else return}return t}}class Lt{static fromDict(e){const t=e.type;switch(t){case"html_strip":return dn._fromDict(e);case"mapping":return pn._fromDict(e);case"pattern_replace":return gn._fromDict(e);default:throw new Error(`Unknown CharFilter type: ${t}`)}}}const us=/<[^>]+>/g,hs={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" "};class dn extends Lt{filter(e){let t=e.replace(us," ");for(const[n,r]of Object.entries(hs))t=t.replaceAll(n,r);return t}toDict(){return{type:"html_strip"}}static _fromDict(e){return new dn}}class pn extends Lt{constructor(t){super();b(this,"_mapping");this._mapping=Object.entries(t).sort((n,r)=>r[0].length-n[0].length)}filter(t){let n=t;for(const[r,s]of this._mapping)n=n.replaceAll(r,s);return n}toDict(){const t={};for(const[n,r]of this._mapping)t[n]=r;return{type:"mapping",mapping:t}}static _fromDict(t){return new pn(t.mapping)}}class gn extends Lt{constructor(t,n=""){super();b(this,"_pattern");b(this,"_replacement");b(this,"_re");this._pattern=t,this._replacement=n,this._re=new RegExp(t,"g")}filter(t){return t.replace(this._re,this._replacement)}toDict(){return{type:"pattern_replace",pattern:this._pattern,replacement:this._replacement}}static _fromDict(t){return new gn(t.pattern,t.replacement??"")}}class Fe{static fromDict(e){const t=e.type;switch(t){case"lowercase":return st._fromDict(e);case"stop":return _t._fromDict(e);case"porter_stem":return yt._fromDict(e);case"ascii_folding":return ot._fromDict(e);case"synonym":return _n._fromDict(e);case"ngram":return jt._fromDict(e);case"edge_ngram":return yn._fromDict(e);case"length":return bn._fromDict(e);default:throw new Error(`Unknown TokenFilter type: ${t}`)}}}class st extends Fe{filter(e){return e.map(t=>t.toLowerCase())}toDict(){return{type:"lowercase"}}static _fromDict(e){return new st}}const fs={english:new Set(["a","an","and","are","as","at","be","but","by","can","could","did","do","does","for","had","has","have","he","her","him","his","how","i","if","in","into","is","it","its","may","me","my","no","nor","not","of","on","or","our","own","she","should","so","some","such","than","that","the","their","then","there","these","they","this","to","too","us","very","was","we","were","what","when","which","who","whom","why","will","with","would","you","your"])};class _t extends Fe{constructor(t="english",n){super();b(this,"_language");b(this,"_customWords");b(this,"_words");this._language=t,this._customWords=n??new Set;const r=fs[t]??new Set;this._words=new Set([...r,...this._customWords])}filter(t){return t.filter(n=>!this._words.has(n))}toDict(){const t={type:"stop",language:this._language};return this._customWords.size>0&&(t.custom_words=[...this._customWords].sort()),t}static _fromDict(t){const n=t.custom_words?new Set(t.custom_words):null;return new _t(t.language??"english",n)}}function Pe(c,e){const t=c[e];return t==="a"||t==="e"||t==="i"||t==="o"||t==="u"?!1:t==="y"?e===0||!Pe(c,e-1):!0}function We(c,e){let t=0,n=0;for(;n<=e&&Pe(c,n);)n++;for(;n<=e;){for(;n<=e&&!Pe(c,n);)n++;for(t++;n<=e&&Pe(c,n);)n++}return t}function mn(c,e){for(let t=0;t<=e;t++)if(!Pe(c,t))return!0;return!1}function er(c,e){return e<1?!1:c[e]===c[e-1]&&Pe(c,e)}function tr(c,e){if(e<2||!Pe(c,e-2)||Pe(c,e-1)||!Pe(c,e))return!1;const t=c[e];return t!=="w"&&t!=="x"&&t!=="y"}function ds(c){if(c.length<=2)return c;let e=c;if(e.endsWith("sses")||e.endsWith("ies")?e=e.slice(0,-2):!e.endsWith("ss")&&e.endsWith("s")&&(e=e.slice(0,-1)),e.endsWith("eed")){const s=e.slice(0,-3);We(e,s.length-1)>0&&(e=e.slice(0,-1))}else{let s=!1,o=0;e.endsWith("ed")?(o=e.length-2,s=mn(e,o-1)):e.endsWith("ing")&&(o=e.length-3,s=mn(e,o-1)),s&&(e=e.slice(0,o),e.endsWith("at")||e.endsWith("bl")||e.endsWith("iz")?e=e+"e":er(e,e.length-1)&&e[e.length-1]!=="l"&&e[e.length-1]!=="s"&&e[e.length-1]!=="z"?e=e.slice(0,-1):We(e,e.length-1)===1&&tr(e,e.length-1)&&(e=e+"e"))}e.endsWith("y")&&mn(e,e.length-2)&&(e=e.slice(0,-1)+"i");const t=[["ational","ate"],["tional","tion"],["enci","ence"],["anci","ance"],["izer","ize"],["abli","able"],["alli","al"],["entli","ent"],["eli","e"],["ousli","ous"],["ization","ize"],["ation","ate"],["ator","ate"],["alism","al"],["iveness","ive"],["fulness","ful"],["ousness","ous"],["aliti","al"],["iviti","ive"],["biliti","ble"]];for(const[s,o]of t)if(e.endsWith(s)){const i=e.slice(0,-s.length);We(e,i.length-1)>0&&(e=i+o);break}const n=[["icate","ic"],["ative",""],["alize","al"],["iciti","ic"],["ical","ic"],["ful",""],["ness",""]];for(const[s,o]of n)if(e.endsWith(s)){const i=e.slice(0,-s.length);We(e,i.length-1)>0&&(e=i+o);break}const r=["al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","ion","ou","ism","ate","iti","ous","ive","ize"];for(const s of r)if(e.endsWith(s)){const o=e.slice(0,-s.length);if(We(e,o.length-1)>1)if(s==="ion"){const i=o[o.length-1];(i==="s"||i==="t")&&(e=o)}else e=o;break}if(e.endsWith("e")){const s=e.slice(0,-1),o=We(e,s.length-1);(o>1||o===1&&!tr(e,s.length-1))&&(e=s)}return We(e,e.length-1)>1&&er(e,e.length-1)&&e[e.length-1]==="l"&&(e=e.slice(0,-1)),e}class yt extends Fe{filter(e){return e.map(t=>ds(t))}toDict(){return{type:"porter_stem"}}static _fromDict(e){return new yt}}function ps(c){for(let e=0;e<c.length;e++)if(c.charCodeAt(e)>127)return!1;return!0}function gs(c){if(c.charCodeAt(0)<=127)return c;const e=c.normalize("NFKD");let t="";for(let n=0;n<e.length;n++)e.charCodeAt(n)<=127&&(t+=e.charAt(n));return t.length>0?t:c}class ot extends Fe{filter(e){return e.map(t=>ot._fold(t))}static _fold(e){if(ps(e))return e;let t="";for(let n=0;n<e.length;n++)t+=gs(e[n]);return t}toDict(){return{type:"ascii_folding"}}static _fromDict(e){return new ot}}class _n extends Fe{constructor(t){super();b(this,"_synonyms");this._synonyms=t}filter(t){const n=[];for(const r of t){n.push(r);const s=this._synonyms[r];s&&n.push(...s)}return n}toDict(){return{type:"synonym",synonyms:this._synonyms}}static _fromDict(t){return new _n(t.synonyms)}}class jt extends Fe{constructor(t=2,n=3,r=!1){super();b(this,"_minGram");b(this,"_maxGram");b(this,"_keepShort");if(t<1)throw new Error("minGram must be >= 1");if(n<t)throw new Error("maxGram must be >= minGram");this._minGram=t,this._maxGram=n,this._keepShort=r}filter(t){const n=[];for(const r of t){if(r.length<this._minGram){this._keepShort&&n.push(r);continue}for(let s=this._minGram;s<=this._maxGram;s++)for(let o=0;o<=r.length-s;o++)n.push(r.substring(o,o+s))}return n}toDict(){const t={type:"ngram",min_gram:this._minGram,max_gram:this._maxGram};return this._keepShort&&(t.keep_short=!0),t}static _fromDict(t){return new jt(t.min_gram,t.max_gram,t.keep_short??!1)}}class yn extends Fe{constructor(t=1,n=20){super();b(this,"_minGram");b(this,"_maxGram");this._minGram=t,this._maxGram=n}filter(t){const n=[];for(const r of t){const s=Math.min(this._maxGram,r.length);for(let o=this._minGram;o<=s;o++)n.push(r.substring(0,o))}return n}toDict(){return{type:"edge_ngram",min_gram:this._minGram,max_gram:this._maxGram}}static _fromDict(t){return new yn(t.min_gram,t.max_gram)}}class bn extends Fe{constructor(t=0,n=0){super();b(this,"_minLength");b(this,"_maxLength");this._minLength=t,this._maxLength=n}filter(t){return t.filter(n=>!(n.length<this._minLength||this._maxLength>0&&n.length>this._maxLength))}toDict(){return{type:"length",min_length:this._minLength,max_length:this._maxLength}}static _fromDict(t){return new bn(t.min_length,t.max_length)}}class He{static fromDict(e){const t=e.type;switch(t){case"whitespace":return bt._fromDict(e);case"standard":return vt._fromDict(e);case"letter":return vn._fromDict(e);case"ngram":return wn._fromDict(e);case"pattern":return xn._fromDict(e);case"keyword":return Vt._fromDict(e);default:throw new Error(`Unknown Tokenizer type: ${t}`)}}}class bt extends He{tokenize(e){return e.split(/\s+/).filter(t=>t.length>0)}toDict(){return{type:"whitespace"}}static _fromDict(e){return new bt}}const ms=/\w+/gu;class vt extends He{tokenize(e){return[...e.matchAll(ms)].map(t=>t[0])}toDict(){return{type:"standard"}}static _fromDict(e){return new vt}}const _s=/[a-zA-Z]+/g;class vn extends He{tokenize(e){return[...e.matchAll(_s)].map(t=>t[0])}toDict(){return{type:"letter"}}static _fromDict(e){return new vn}}class wn extends He{constructor(t=1,n=2){super();b(this,"_minGram");b(this,"_maxGram");if(t<1)throw new Error("minGram must be >= 1");if(n<t)throw new Error("maxGram must be >= minGram");this._minGram=t,this._maxGram=n}tokenize(t){const n=t.split(/\s+/).filter(s=>s.length>0),r=[];for(const s of n)for(let o=this._minGram;o<=this._maxGram;o++)for(let i=0;i<=s.length-o;i++)r.push(s.substring(i,i+o));return r}toDict(){return{type:"ngram",min_gram:this._minGram,max_gram:this._maxGram}}static _fromDict(t){return new wn(t.min_gram,t.max_gram)}}class xn extends He{constructor(t="\\W+"){super();b(this,"_pattern");b(this,"_re");this._pattern=t,this._re=new RegExp(t)}tokenize(t){return t.split(this._re).filter(n=>n.length>0)}toDict(){return{type:"pattern",pattern:this._pattern}}static _fromDict(t){return new xn(t.pattern)}}class Vt extends He{tokenize(e){return e.length>0?[e]:[]}toDict(){return{type:"keyword"}}static _fromDict(e){return new Vt}}class De{constructor(e,t,n){b(this,"_tokenizer");b(this,"_tokenFilters");b(this,"_charFilters");this._tokenizer=e??new bt,this._tokenFilters=t??[],this._charFilters=n??[]}get tokenizer(){return this._tokenizer}get tokenFilters(){return this._tokenFilters}get charFilters(){return this._charFilters}analyze(e){let t=e;for(const r of this._charFilters)t=r.filter(t);let n=this._tokenizer.tokenize(t);for(const r of this._tokenFilters)n=r.filter(n);return n}toDict(){return{tokenizer:this._tokenizer.toDict(),token_filters:this._tokenFilters.map(e=>e.toDict()),char_filters:this._charFilters.map(e=>e.toDict())}}toJSON(){return JSON.stringify(this.toDict())}static fromDict(e){const t=He.fromDict(e.tokenizer),n=e.token_filters.map(s=>Fe.fromDict(s)),r=e.char_filters?e.char_filters.map(s=>Lt.fromDict(s)):[];return new De(t,n,r)}static fromJSON(e){return De.fromDict(JSON.parse(e))}}function nr(){return new De(new bt,[new st])}function Sn(c="english"){return new De(new vt,[new st,new ot,new _t(c),new yt])}function ys(c="english"){return new De(new vt,[new st,new ot,new _t(c),new yt,new jt(2,3,!0)])}function rr(){return new De(new Vt,[])}const sr=Sn(),$t={whitespace:nr(),standard:Sn(),standard_cjk:ys(),keyword:rr()},wt=new Map;function bs(c,e){if(c in $t)throw new Error(`Cannot override built-in analyzer: ${c}`);wt.set(c,e)}function vs(c){const e=wt.get(c);if(e)return e;const t=$t[c];if(t)return t;throw new Error(`Unknown analyzer: ${c}`)}function ws(c){if(c in $t)throw new Error(`Cannot drop built-in analyzer: ${c}`);if(!wt.has(c))throw new Error(`Analyzer not found: ${c}`);wt.delete(c)}function xs(){return[...Object.keys($t),...wt.keys()].sort()}class Ss{*iterAll(){const e=[...this.docIds].sort((t,n)=>t-n);for(const t of e){const n=this.get(t);n!==null&&(yield[t,n])}}}function Es(c,e){let t=c;for(const n of e){if(t==null)return;if(typeof n=="number"){if(!Array.isArray(t))return;t=t[n]}else if(Array.isArray(t))t=t.map(r=>r[n]);else if(typeof t=="object")t=t[n];else return}return t}class or extends Ss{constructor(){super();b(this,"_documents");this._documents=new Map}put(t,n){this._documents.set(t,n)}get(t){return this._documents.get(t)??null}delete(t){this._documents.delete(t)}clear(){this._documents.clear()}getField(t,n){const r=this._documents.get(t);if(r!==void 0)return r[n]}getFieldsBulk(t,n){const r=new Map;for(const s of t){const o=this._documents.get(s);r.set(s,o!==void 0?o[n]:void 0)}return r}hasValue(t,n){for(const r of this._documents.values())if(r[t]===n)return!0;return!1}evalPath(t,n){const r=this._documents.get(t);if(r!==void 0)return Es(r,n)}get docIds(){return new Set(this._documents.keys())}get length(){return this._documents.size}maxDocId(){let t=-1;for(const n of this._documents.keys())n>t&&(t=n);return t}putBulk(t){for(const[n,r]of t)this._documents.set(n,r)}deleteBulk(t){for(const n of t)this._documents.delete(n)}}class Is{}const Ns={analyze(c){return c.toLowerCase().split(/\s+/).filter(e=>e.length>0)}};class ir extends Is{constructor(t,n){super();b(this,"_analyzer");b(this,"_indexFieldAnalyzers");b(this,"_searchFieldAnalyzers");b(this,"_index");b(this,"_docTerms");b(this,"_docLengths");b(this,"_docCount");b(this,"_totalLength");b(this,"_cachedStats");b(this,"_termToKeys");if(this._analyzer=t??Ns,this._indexFieldAnalyzers=new Map,this._searchFieldAnalyzers=new Map,n)for(const[r,s]of Object.entries(n))this._indexFieldAnalyzers.set(r,s);this._index=new Map,this._docTerms=new Map,this._docLengths=new Map,this._docCount=0,this._totalLength=new Map,this._cachedStats=null,this._termToKeys=new Map}_key(t,n){return`${t}\0${n}`}_parseKey(t){const n=t.indexOf("\0");return[t.substring(0,n),t.substring(n+1)]}get analyzer(){return this._analyzer}get fieldAnalyzers(){const t={};for(const[n,r]of this._indexFieldAnalyzers)t[n]=r;return t}setFieldAnalyzer(t,n,r="both"){(r==="index"||r==="both")&&this._indexFieldAnalyzers.set(t,n),(r==="search"||r==="both")&&this._searchFieldAnalyzers.set(t,n)}getFieldAnalyzer(t){return this._indexFieldAnalyzers.get(t)??this._analyzer}getSearchAnalyzer(t){return this._searchFieldAnalyzers.get(t)??this._indexFieldAnalyzers.get(t)??this._analyzer}addDocument(t,n){this._cachedStats=null,this._docCount++,this._docLengths.set(t,new Map);let r=this._docTerms.get(t);r||(r=new Set,this._docTerms.set(t,r));const s={},o=new Map;for(const[i,a]of Object.entries(n)){const u=this.getFieldAnalyzer(i).analyze(a);this._docLengths.get(t).set(i,u.length),s[i]=u.length;const f=this._totalLength.get(i)??0;this._totalLength.set(i,f+u.length);const d=new Map;for(let p=0;p<u.length;p++){const m=u[p];let _=d.get(m);_||(_=[],d.set(m,_)),_.push(p)}for(const[p,m]of d){const _=this._key(i,p);let y=this._index.get(_);if(!y){y=new Map,this._index.set(_,y);let v=this._termToKeys.get(p);v||(v=[],this._termToKeys.set(p,v)),v.push(_)}const x={docId:t,payload:U({positions:m,score:0})};y.set(t,x),r.add(_),o.set(_,m)}}return{fieldLengths:s,postings:o}}addPosting(t,n,r){this._cachedStats=null;const s=this._key(t,n);let o=this._index.get(s);if(!o){o=new Map,this._index.set(s,o);let a=this._termToKeys.get(n);a||(a=[],this._termToKeys.set(n,a)),a.push(s)}o.set(r.docId,r);let i=this._docTerms.get(r.docId);i||(i=new Set,this._docTerms.set(r.docId,i)),i.add(s)}setDocLength(t,n){const r=new Map;for(const[s,o]of Object.entries(n))r.set(s,o);this._docLengths.set(t,r)}setDocCount(t){this._cachedStats=null,this._docCount=t}addTotalLength(t,n){this._cachedStats=null;const r=this._totalLength.get(t)??0;this._totalLength.set(t,r+n)}removeDocument(t){this._cachedStats=null;const n=this._docTerms.get(t);if(!n)return;for(const s of n){const o=this._index.get(s);if(o&&(o.delete(t),o.size===0)){this._index.delete(s);const[,i]=this._parseKey(s),a=this._termToKeys.get(i);if(a){const l=a.indexOf(s);l!==-1&&a.splice(l,1),a.length===0&&this._termToKeys.delete(i)}}}this._docTerms.delete(t);const r=this._docLengths.get(t);if(r){for(const[s,o]of r){const i=this._totalLength.get(s)??0;this._totalLength.set(s,i-o)}this._docLengths.delete(t),this._docCount--}}clear(){this._index.clear(),this._docTerms.clear(),this._docLengths.clear(),this._termToKeys.clear(),this._cachedStats=null,this._docCount=0,this._totalLength.clear()}getPostingList(t,n){const r=this._index.get(this._key(t,n));if(!r)return new D;const s=[...r.values()].sort((o,i)=>o.docId-i.docId);return D.fromSorted(s)}getPostingListAnyField(t){const n=this._termToKeys.get(t);if(!n||n.length===0)return new D;const r=new Set,s=[];for(const o of n){const i=this._index.get(o);if(i)for(const[a,l]of i)r.has(a)||(r.add(a),s.push(l))}return s.sort((o,i)=>o.docId-i.docId),D.fromSorted(s)}docFreq(t,n){const r=this._index.get(this._key(t,n));return r?r.size:0}docFreqAnyField(t){const n=this._termToKeys.get(t);if(!n||n.length===0)return 0;const r=new Set;for(const s of n){const o=this._index.get(s);if(o)for(const i of o.keys())r.add(i)}return r.size}getDocLength(t,n){const r=this._docLengths.get(t);return r?r.get(n)??0:0}getDocLengthsBulk(t,n){const r=new Map;for(const s of t)r.set(s,this.getDocLength(s,n));return r}getTotalDocLength(t){const n=this._docLengths.get(t);if(!n)return 0;let r=0;for(const s of n.values())r+=s;return r}getTermFreq(t,n,r){const s=this._index.get(this._key(n,r));if(!s)return 0;const o=s.get(t);return o?o.payload.positions.length:0}getTermFreqsBulk(t,n,r){const s=this._index.get(this._key(n,r)),o=new Map;for(const i of t)if(s){const a=s.get(i);o.set(i,a?a.payload.positions.length:0)}else o.set(i,0);return o}getTotalTermFreq(t,n){const r=this._termToKeys.get(n);if(!r)return 0;let s=0;for(const o of r){const i=this._index.get(o);if(i){const a=i.get(t);a&&(s+=a.payload.positions.length)}}return s}addDocuments(t){for(const[n,r]of t)this.addDocument(n,r)}removeDocuments(t){for(const n of t)this.removeDocument(n)}*terms(t){const n=this._key(t,"");for(const r of this._index.keys())if(r.startsWith(n)){const[,s]=this._parseKey(r);yield s}}*allTerms(){for(const t of this._index.keys())yield this._parseKey(t)}*fieldNames(){const t=new Set;for(const n of this._index.keys()){const[r]=this._parseKey(n);t.has(r)||(t.add(r),yield r)}}hasTerm(t,n){return this._index.has(this._key(t,n))}hasDoc(t){return this._docTerms.has(t)}avgDocLength(t){return this._docCount===0?0:(this._totalLength.get(t)??0)/this._docCount}totalDocCount(){return this._docCount}totalFieldLength(t){return this._totalLength.get(t)??0}getPositions(t,n,r){const s=this._index.get(this._key(n,r));if(!s)return[];const o=s.get(t);return o?o.payload.positions:[]}get stats(){if(this._cachedStats!==null)return this._cachedStats;let t=0;for(const s of this._totalLength.values())t+=s;const n=this._docCount>0?t/this._docCount:0,r=new Bn(this._docCount,n);for(const[s,o]of this._index){const[i,a]=this._parseKey(s);r.setDocFreq(i,a,o.size)}return this._cachedStats=r,r}}function ar(c,e){if(c.length!==e.length)throw new Error(`dot: length mismatch (${String(c.length)} vs ${String(e.length)})`);let t=0;for(let n=0;n<c.length;n++)t+=c[n]*e[n];return t}function it(c){return Math.sqrt(ar(c,c))}function at(c,e){const t=it(c),n=it(e);return t===0||n===0?0:ar(c,e)/(t*n)}function As(c){if(c.length===0)return new Float64Array(0);let e=c[0];for(let r=1;r<c.length;r++)c[r]>e&&(e=c[r]);const t=new Float64Array(c.length);let n=0;for(let r=0;r<c.length;r++)t[r]=Math.exp(c[r]-e),n+=t[r];for(let r=0;r<t.length;r++)t[r]=t[r]/n;return t}function ks(c,e,t,n){const[r,s]=e,[o,i]=n;if(s!==o)throw new Error(`matmul: inner dimension mismatch (${String(s)} vs ${String(o)})`);if(c.length!==r*s)throw new Error(`matmul: array a length (${String(c.length)}) does not match shape [${String(r)}, ${String(s)}]`);if(t.length!==o*i)throw new Error(`matmul: array b length (${String(t.length)}) does not match shape [${String(o)}, ${String(i)}]`);const a=new Float64Array(r*i);for(let l=0;l<r;l++)for(let u=0;u<s;u++){const h=c[l*s+u];for(let f=0;f<i;f++)a[l*i+f]=a[l*i+f]+h*t[u*i+f]}return{data:a,shape:[r,i]}}function Ms(c,e,t){if(c.length!==e*t)throw new Error(`transpose: array length (${String(c.length)}) does not match shape [${String(e)}, ${String(t)}]`);const n=new Float64Array(c.length);for(let r=0;r<e;r++)for(let s=0;s<t;s++)n[s*e+r]=c[r*t+s];return n}class Os{}class lr extends Os{constructor(t){super();b(this,"dimensions");b(this,"_vectors");this.dimensions=t,this._vectors=new Map}add(t,n){if(n.length!==this.dimensions)throw new Error(`Vector dimension mismatch: expected ${String(this.dimensions)}, got ${String(n.length)}`);this._vectors.set(t,n)}delete(t){this._vectors.delete(t)}clear(){this._vectors.clear()}searchKnn(t,n){if(this._vectors.size===0)return new D;const r=[];for(const[i,a]of this._vectors){const l=at(t,a);r.push({docId:i,score:l})}r.sort((i,a)=>a.score-i.score);const o=r.slice(0,n).map(i=>({docId:i.docId,payload:U({score:i.score})}));return new D(o)}searchThreshold(t,n){const r=[];for(const[s,o]of this._vectors){const i=at(t,o);i>=n&&r.push({docId:s,payload:U({score:i})})}return new D(r)}count(){return this._vectors.size}}class Cs{}class Ts{constructor(){b(this,"vertexIds",new Set);b(this,"edgeIds",new Set);b(this,"adjOut",new Map);b(this,"adjIn",new Map);b(this,"labelIndex",new Map);b(this,"vertexLabelIndex",new Map)}addVertex(e,t){this.vertexIds.add(e),this.adjOut.has(e)||this.adjOut.set(e,new Set),this.adjIn.has(e)||this.adjIn.set(e,new Set);let n=this.vertexLabelIndex.get(t);n||(n=new Set,this.vertexLabelIndex.set(t,n)),n.add(e)}removeVertex(e,t){this.vertexIds.delete(e),this.adjOut.delete(e),this.adjIn.delete(e);for(const[,r]of this.adjOut)r.delete(e);for(const[,r]of this.adjIn)r.delete(e);const n=this.vertexLabelIndex.get(t);n&&(n.delete(e),n.size===0&&this.vertexLabelIndex.delete(t))}addEdge(e,t,n,r){this.edgeIds.add(e);let s=this.adjOut.get(t);s||(s=new Set,this.adjOut.set(t,s)),s.add(e);let o=this.adjIn.get(n);o||(o=new Set,this.adjIn.set(n,o)),o.add(e);let i=this.labelIndex.get(r);i||(i=new Set,this.labelIndex.set(r,i)),i.add(e)}removeEdge(e,t,n,r){this.edgeIds.delete(e);const s=this.adjOut.get(t);s&&s.delete(e);const o=this.adjIn.get(n);o&&o.delete(e);const i=this.labelIndex.get(r);i&&(i.delete(e),i.size===0&&this.labelIndex.delete(r))}neighbors(e,t,n,r){const s=[];if(r==="out"){const o=this.adjOut.get(e);if(o)for(const i of o){const a=t.get(i);a&&(n===null||a.label===n)&&s.push(a.targetId)}}else{const o=this.adjIn.get(e);if(o)for(const i of o){const a=t.get(i);a&&(n===null||a.label===n)&&s.push(a.sourceId)}}return s}verticesByLabel(e){return this.vertexLabelIndex.get(e)??new Set}}class cr extends Cs{constructor(){super(...arguments);b(this,"_vertices",new Map);b(this,"_edges",new Map);b(this,"_graphs",new Map);b(this,"_vertexMembership",new Map);b(this,"_edgeMembership",new Map);b(this,"_nextVertexId",0);b(this,"_nextEdgeId",0)}createGraph(t){this._graphs.has(t)||this._graphs.set(t,new Ts)}dropGraph(t){const n=this._graphs.get(t);if(n){for(const r of n.vertexIds){const s=this._vertexMembership.get(r);s&&(s.delete(t),s.size===0&&this._vertexMembership.delete(r))}for(const r of n.edgeIds){const s=this._edgeMembership.get(r);s&&(s.delete(t),s.size===0&&this._edgeMembership.delete(r))}this._graphs.delete(t)}}graphNames(){return[...this._graphs.keys()]}hasGraph(t){return this._graphs.has(t)}unionGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(s){for(const i of s.vertexIds){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of s.edgeIds){const a=this._edges.get(i);a&&this.addEdge(a,r)}}if(o){for(const i of o.vertexIds){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of o.edgeIds){const a=this._edges.get(i);a&&this.addEdge(a,r)}}}intersectGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(!(!s||!o)){for(const i of s.vertexIds)if(o.vertexIds.has(i)){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of s.edgeIds)if(o.edgeIds.has(i)){const a=this._edges.get(i);a&&this.addEdge(a,r)}}}differenceGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(!s)return;const i=o?o.vertexIds:new Set,a=o?o.edgeIds:new Set;for(const l of s.vertexIds)if(!i.has(l)){const u=this._vertices.get(l);u&&this.addVertex(u,r)}for(const l of s.edgeIds)if(!a.has(l)){const u=this._edges.get(l);u&&this.addEdge(u,r)}}copyGraph(t,n){this.createGraph(n);const r=this._graphs.get(t);if(r){for(const s of r.vertexIds){const o=this._vertices.get(s);o&&this.addVertex(o,n)}for(const s of r.edgeIds){const o=this._edges.get(s);o&&this.addEdge(o,n)}}}addVertex(t,n){this._vertices.set(t.vertexId,t),t.vertexId>=this._nextVertexId&&(this._nextVertexId=t.vertexId+1);const r=this._graphs.get(n);r&&r.addVertex(t.vertexId,t.label);let s=this._vertexMembership.get(t.vertexId);s||(s=new Set,this._vertexMembership.set(t.vertexId,s)),s.add(n)}addEdge(t,n){this._edges.set(t.edgeId,t),t.edgeId>=this._nextEdgeId&&(this._nextEdgeId=t.edgeId+1);const r=this._graphs.get(n);r&&r.addEdge(t.edgeId,t.sourceId,t.targetId,t.label);let s=this._edgeMembership.get(t.edgeId);s||(s=new Set,this._edgeMembership.set(t.edgeId,s)),s.add(n)}removeVertex(t,n){const r=this._vertices.get(t);if(!r)return;const s=this._graphs.get(n);if(s){const i=[],a=s.adjOut.get(t);if(a)for(const u of a)i.push(u);const l=s.adjIn.get(t);if(l)for(const u of l)i.push(u);for(const u of i)this.removeEdge(u,n);s.removeVertex(t,r.label)}const o=this._vertexMembership.get(t);o&&(o.delete(n),o.size===0&&(this._vertexMembership.delete(t),this._vertices.delete(t)))}removeEdge(t,n){const r=this._edges.get(t);if(!r)return;const s=this._graphs.get(n);s&&s.removeEdge(t,r.sourceId,r.targetId,r.label);const o=this._edgeMembership.get(t);o&&(o.delete(n),o.size===0&&(this._edgeMembership.delete(t),this._edges.delete(t)))}neighbors(t,n,r,s){const o=this._graphs.get(n);return o?o.neighbors(t,this._edges,r??null,s??"out"):[]}verticesByLabel(t,n){const r=this._graphs.get(n);if(!r)return[];const s=r.verticesByLabel(t),o=[];for(const i of s){const a=this._vertices.get(i);a&&o.push(a)}return o}verticesInGraph(t){const n=this._graphs.get(t);if(!n)return[];const r=[];for(const s of n.vertexIds){const o=this._vertices.get(s);o&&r.push(o)}return r}edgesInGraph(t){const n=this._graphs.get(t);if(!n)return[];const r=[];for(const s of n.edgeIds){const o=this._edges.get(s);o&&r.push(o)}return r}vertexGraphs(t){return this._vertexMembership.get(t)??new Set}outEdgeIds(t,n){const r=this._graphs.get(n);return r?r.adjOut.get(t)??new Set:new Set}inEdgeIds(t,n){const r=this._graphs.get(n);return r?r.adjIn.get(t)??new Set:new Set}edgeIdsByLabel(t,n){const r=this._graphs.get(n);return r?r.labelIndex.get(t)??new Set:new Set}vertexIdsInGraph(t){const n=this._graphs.get(t);return n?new Set(n.vertexIds):new Set}degreeDistribution(t){const n=this._graphs.get(t);if(!n)return new Map;const r=new Map;for(const s of n.vertexIds){const o=n.adjOut.get(s),i=n.adjIn.get(s),a=(o?o.size:0)+(i?i.size:0);r.set(a,(r.get(a)??0)+1)}return r}labelDegree(t,n){const r=this._graphs.get(n);if(!r)return 0;const s=r.labelIndex.get(t);return s?s.size:0}vertexLabelCounts(t){const n=this._graphs.get(t);if(!n)return new Map;const r=new Map;for(const[s,o]of n.vertexLabelIndex)r.set(s,o.size);return r}getVertex(t){return this._vertices.get(t)??null}getEdge(t){return this._edges.get(t)??null}nextVertexId(){return this._nextVertexId++}nextEdgeId(){return this._nextEdgeId++}clear(){this._vertices.clear(),this._edges.clear(),this._graphs.clear(),this._vertexMembership.clear(),this._edgeMembership.clear(),this._nextVertexId=0,this._nextEdgeId=0}get vertices(){return this._vertices}get edges(){return this._edges}get vertexCount(){return this._vertices.size}get edgeCount(){return this._edges.size}addVertices(t,n){for(const r of t)this.addVertex(r,n)}addEdges(t,n){for(const r of t)this.addEdge(r,n)}vertexProperty(t,n){const r=this._vertices.get(t);if(r!==void 0)return r.properties[n]}setVertexProperty(t,n,r){const s=this._vertices.get(t);if(s===void 0)throw new Error(`Vertex ${String(t)} not found`);s.properties[n]=r}edgeProperty(t,n){const r=this._edges.get(t);if(r!==void 0)return r.properties[n]}setEdgeProperty(t,n,r){const s=this._edges.get(t);if(s===void 0)throw new Error(`Edge ${String(t)} not found`);s.properties[n]=r}edgesByLabel(t,n){const r=[];if(!this._graphs.get(n))return r;for(const[o,i]of this._edges)if(i.label===t){const a=this._edgeMembership.get(o);a&&a.has(n)&&r.push(i)}return r}vertexLabels(t){const n=new Set;for(const r of this.verticesInGraph(t))r.label&&n.add(r.label);return n}edgeLabels(t){const n=new Set;for(const r of this.edgesInGraph(t))n.add(r.label);return n}outDegree(t,n){return this.outEdgeIds(t,n).size}inDegree(t,n){return this.inEdgeIds(t,n).size}edgesBetween(t,n,r,s){const o=[],i=this.outEdgeIds(t,r);for(const a of i){const l=this._edges.get(a);l&&l.targetId===n&&(s==null||l.label===s)&&o.push(l)}return o}subgraph(t,n,r){this._graphs.has(r)||this.createGraph(r);for(const s of t){const o=this._vertices.get(s);o&&this.addVertex(o,r)}for(const[s,o]of this._edges){const i=this._edgeMembership.get(s);i&&i.has(n)&&t.has(o.sourceId)&&t.has(o.targetId)&&this.addEdge(o,r)}}minTimestamp(t){let n=null;for(const r of this.edgesInGraph(t)){const s=r.properties.timestamp;typeof s=="number"&&(n===null||s<n)&&(n=s)}return n}maxTimestamp(t){let n=null;for(const r of this.edgesInGraph(t)){const s=r.properties.timestamp;typeof s=="number"&&(n===null||s>n)&&(n=s)}return n}edgesInTimeRange(t,n,r){const s=[];for(const o of this.edgesInGraph(t)){const i=o.properties.timestamp;typeof i=="number"&&i>=n&&i<=r&&s.push(o)}return s}}function qt(c){return{k1:(c==null?void 0:c.k1)??1.2,b:(c==null?void 0:c.b)??.75,boost:(c==null?void 0:c.boost)??1}}class xt{constructor(e,t){b(this,"_params");b(this,"_totalDocs");b(this,"_avgDocLength");this._params=e,this._totalDocs=t.totalDocs,this._avgDocLength=t.avgDocLength}get params(){return this._params}idf(e){const t=this._totalDocs;return Math.log((t-e+.5)/(e+.5)+1)}score(e,t,n){return this.scoreWithIdf(e,t,this.idf(n))}scoreWithIdf(e,t,n){const{k1:r,b:s,boost:o}=this._params,i=o*n,a=this._avgDocLength>0?this._avgDocLength:1,l=1/(r*(1-s+s*t/a));return i-i/(1+e*l)}combineScores(e){let t=0;for(const n of e)t+=n;return t}upperBound(e){return this._params.boost*this.idf(e)}}function Ke(c){return{bm25:(c==null?void 0:c.bm25)??qt(),alpha:(c==null?void 0:c.alpha)??1,beta:(c==null?void 0:c.beta)??0,baseRate:(c==null?void 0:c.baseRate)??.5}}class lt{constructor(e,t){b(this,"_bm25");b(this,"_transform");this._bm25=new xt(e.bm25,t),this._transform=new K.BayesianProbabilityTransform(e.alpha,e.beta,e.baseRate===.5?null:e.baseRate)}get bm25(){return this._bm25}idf(e){return this._bm25.idf(e)}score(e,t,n){return this.scoreWithIdf(e,t,this._bm25.idf(n))}scoreWithIdf(e,t,n){const r=this._bm25.scoreWithIdf(e,t,n),s=this._bm25.params.k1>0?t:1,o=s>0?t/s:1;return this._transform.scoreToProbability(r,e,o)}combineScores(e){return e.length===0?.5:e.length===1?e[0]:K.logOddsConjunction(e,0)}upperBound(e){const t=this._bm25.upperBound(e);return this._transform.wandUpperBound(t)}}class q{compose(e){return new Je([this,e])}costEstimate(e){return e.totalDocs}}class Je extends q{constructor(t){super();b(this,"operators");this.operators=t}execute(t){let n=null;for(const r of this.operators)n=r.execute(t);return n===null?new D:n}costEstimate(t){let n=0;for(const r of this.operators)n+=r.costEstimate(t);return n}}const ur=6371e3,Rs=111320;function St(c){return c*Math.PI/180}function Fs(c){return c*180/Math.PI}function hr(c,e,t,n){const r=St(c),s=St(t),o=St(t-c),i=St(n-e),a=Math.sin(o/2)**2+Math.cos(r)*Math.cos(s)*Math.sin(i/2)**2;return 2*ur*Math.asin(Math.sqrt(a))}class Ps{constructor(e,t){b(this,"_tableName");b(this,"_fieldName");b(this,"_points");this._tableName=e,this._fieldName=t,this._points=new Map}get tableName(){return this._tableName}get fieldName(){return this._fieldName}add(e,t,n){this._points.set(e,{x:t,y:n})}delete(e){this._points.delete(e)}clear(){this._points.clear()}searchWithin(e,t,n){if(n<=0)return new D;const r=n/Rs,s=n/ur,o=Math.cos(St(t));let i;if(o<1e-10||s>=Math.PI)i=180;else{const d=Math.sin(s)/o;d>=1?i=180:i=Fs(Math.asin(d))}const a=e-i,l=e+i,u=t-r,h=t+r,f=[];for(const[d,p]of this._points){if(p.x<a||p.x>l||p.y<u||p.y>h)continue;const m=hr(t,e,p.y,p.x);if(m<=n){const _=1-m/n;f.push({docId:d,payload:U({score:_})})}}return f.sort((d,p)=>d.docId-p.docId),D.fromSorted(f)}count(){return this._points.size}close(){this._points.clear()}}function Ds(c,e,t,n){const r=c.documentStore;if(!r)return new D;if(it(t)===0)return new D;const o=[];for(const a of r.docIds){const l=r.getField(a,e);if(!l||!(l instanceof Float64Array)||it(l)===0)continue;const h=at(t,l);o.push({docId:a,score:h})}o.sort((a,l)=>l.score-a.score);const i=o.slice(0,n);return new D(i.map(a=>({docId:a.docId,payload:U({score:a.score})})))}function Ls(c,e,t,n){const r=c.documentStore;if(!r)return new D;if(it(t)===0)return new D;const o=[];for(const i of r.docIds){const a=r.getField(i,e);if(!a||!(a instanceof Float64Array)||it(a)===0)continue;const u=at(t,a);u>=n&&o.push({docId:i,payload:U({score:u})})}return new D(o)}class me extends q{constructor(t,n){super();b(this,"term");b(this,"field");this.term=t,this.field=n??null}execute(t){const n=t.invertedIndex;if(!n)return new D;const s=(this.field?n.getSearchAnalyzer(this.field):n.analyzer).analyze(this.term);if(s.length===0)return new D;const o=s.map(a=>this.field?n.getPostingList(this.field,a):n.getPostingListAnyField(a));let i=o[0];for(let a=1;a<o.length;a++)i=i.union(o[a]);return i}costEstimate(t){return this.field?t.docFreq(this.field,this.term):t.totalDocs}}class xe extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"threshold");b(this,"field");this.queryVector=t,this.threshold=n,this.field=r}execute(t){var r;const n=(r=t.vectorIndexes)==null?void 0:r[this.field];return n?n.searchThreshold(this.queryVector,this.threshold):Ls(t,this.field,this.queryVector,this.threshold)}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}class Le extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"k");b(this,"field");this.queryVector=t,this.k=n,this.field=r}execute(t){var r;const n=(r=t.vectorIndexes)==null?void 0:r[this.field];return n?n.searchKnn(this.queryVector,this.k):Ds(t,this.field,this.queryVector,this.k)}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}class js extends q{constructor(t,n,r,s){super();b(this,"field");b(this,"centerX");b(this,"centerY");b(this,"distance");this.field=t,this.centerX=n,this.centerY=r,this.distance=s}execute(t){var r;const n=(r=t.spatialIndexes)==null?void 0:r[this.field];return n?n.searchWithin(this.centerX,this.centerY,this.distance):this._bruteForceScan(t)}_bruteForceScan(t){const n=t.documentStore;if(!n)return new D;const r=[],s=[...n.docIds].sort((o,i)=>o-i);for(const o of s){const i=n.getField(o,this.field);if(!i)continue;const a=hr(this.centerY,this.centerX,i[1],i[0]);if(a<=this.distance){const l=this.distance>0?1-a/this.distance:1;r.push({docId:o,payload:U({score:l})})}}return D.fromSorted(r)}costEstimate(t){return Math.log2(t.totalDocs+1)}}class G extends q{constructor(t,n,r){super();b(this,"field");b(this,"predicate");b(this,"source");this.field=t,this.predicate=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;const r=Zn(this.predicate),s=typeof n.getFieldsBulk=="function";if(this.source){const l=[...this.source.execute(t)];if(s&&l.length>1){const h=l.map(p=>p.docId),f=n.getFieldsBulk(h,this.field),d=[];for(const p of l){const m=f.get(p.docId);(r?this.predicate.evaluate(m):m!=null&&this.predicate.evaluate(m))&&d.push(p)}return D.fromSorted(d)}const u=[];for(const h of l){const f=n.getField(h.docId,this.field);(r?this.predicate.evaluate(f):f!=null&&this.predicate.evaluate(f))&&u.push(h)}return D.fromSorted(u)}const o=[...n.docIds].sort((a,l)=>a-l);if(s&&o.length>1){const a=n.getFieldsBulk(o,this.field),l=[];for(const u of o){const h=a.get(u);(r?this.predicate.evaluate(h):h!=null&&this.predicate.evaluate(h))&&l.push({docId:u,payload:U({score:0})})}return D.fromSorted(l)}const i=[];for(const a of o){const l=n.getField(a,this.field);!r&&l==null||this.predicate.evaluate(l)&&i.push({docId:a,payload:U({score:0})})}return D.fromSorted(i)}costEstimate(t){return t.totalDocs}}class Vs extends q{constructor(t,n){super();b(this,"field");b(this,"source");this.field=t,this.source=n??null}execute(t){const n=t.documentStore;if(!n)return new D;let r;this.source?r=this.source.execute(t).entries.map(l=>l.docId):r=[...n.docIds].sort((a,l)=>a-l);const s=new Map;for(const a of r){const l=n.getField(a,this.field);if(l!=null){const u=String(l);s.set(u,(s.get(u)??0)+1)}}const i=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0])).map(([a,l],u)=>({docId:u,payload:U({score:l,fields:{_facet_field:this.field,_facet_value:a,_facet_count:l}})}));return D.fromSorted(i)}costEstimate(t){return t.totalDocs}}class de extends q{constructor(t,n,r,s){super();b(this,"scorer");b(this,"source");b(this,"queryTerms");b(this,"field");this.scorer=t,this.source=n,this.queryTerms=r,this.field=s??null}execute(t){const n=this.source.execute(t),r=t.invertedIndex;if(!r)return n;const s=typeof this.scorer.idf=="function"&&typeof this.scorer.scoreWithIdf=="function",o=typeof this.scorer.combineScores=="function",i=[];if(s)for(const p of this.queryTerms){const m=this.field?r.docFreq(this.field,p):r.docFreqAnyField(p);i.push(this.scorer.idf(m))}const a=n.entries,l=a.map(p=>p.docId),u=typeof r.getDocLengthsBulk=="function";let h=null;u&&this.field!==null&&(h=r.getDocLengthsBulk(l,this.field));const f=[];if(u&&this.field!==null)for(const p of this.queryTerms)f.push(r.getTermFreqsBulk(l,this.field,p));const d=[];for(const p of a){const m=[];let _;h!==null?_=h.get(p.docId)??0:this.field!==null?_=r.getDocLength(p.docId,this.field):_=r.getTotalDocLength(p.docId);for(let x=0;x<this.queryTerms.length;x++){const v=this.queryTerms[x];let E;if(f.length>0?E=f[x].get(p.docId)??0:this.field!==null?E=r.getTermFreq(p.docId,this.field,v):E=r.getTotalTermFreq(p.docId,v),s)m.push(this.scorer.scoreWithIdf(E,_,i[x]));else{const I=this.field?r.docFreq(this.field,v):r.docFreqAnyField(v);m.push(this.scorer.score(E,_,I))}}const y=o?this.scorer.combineScores(m):m.reduce((x,v)=>x+v,0);d.push({docId:p.docId,payload:U({positions:p.payload.positions,score:y,fields:p.payload.fields})})}return D.fromSorted(d)}}class zt extends q{constructor(t,n,r){super();b(this,"index");b(this,"field");b(this,"predicate");this.index=t,this.field=n,this.predicate=r}execute(t){return this.index.scan(this.predicate)}costEstimate(t){return this.index.scanCost(this.predicate)}}class re extends q{constructor(t){super();b(this,"operands");this.operands=t}execute(t){const n=this.operands.map(s=>s.execute(t));let r=new D;for(const s of n)r=r.union(s);return r}costEstimate(t){let n=0;for(const r of this.operands)n+=r.costEstimate(t);return n}}class H extends q{constructor(t){super();b(this,"operands");this.operands=t}execute(t){if(this.operands.length===0)return new D;let n=this.operands[0].execute(t);for(let r=1;r<this.operands.length;r++){if(n.length===0)return n;n=n.intersect(this.operands[r].execute(t))}return n}costEstimate(t){if(this.operands.length===0)return 0;let n=1/0;for(const r of this.operands){const s=r.costEstimate(t);s<n&&(n=s)}return n}}class fe extends q{constructor(t){super();b(this,"operand");this.operand=t}execute(t){const n=this.operand.execute(t),r=t.documentStore;if(!r)return new D;const s=D.fromSorted([...r.docIds].sort((o,i)=>o-i).map(o=>({docId:o,payload:U({score:0})})));return n.complement(s)}costEstimate(t){return t.totalDocs}}function $s(c,e,t=1){return e<=0?1:Math.pow(c/e,t)}function qs(c,e=.5){const t=c.length;if(t===0)return{calibrate(i){return i.map(()=>e)}};let n=0;for(let i=0;i<t;i++)n+=c[i];const r=n/t;let s=0;for(let i=0;i<t;i++){const a=c[i]-r;s+=a*a}const o=Math.max(Math.sqrt(s/t),1e-10);return{calibrate(i,a){const l=(a==null?void 0:a.bandwidthFactor)??1,u=(a==null?void 0:a.densityPrior)??null,h=1.06*o*Math.pow(t,-.2)*l;return i.map((f,d)=>{const p=(f-r)/Math.max(h,1e-10),m=Math.exp(-.5*p*p)/(Math.sqrt(2*Math.PI)*h),_=m*2;let y=e;u!==null&&d<u.length&&(y=Math.min(Math.max(u[d]*e,.01),.99));const x=_*y,v=x+m*(1-y);return v<=0?y:Math.min(Math.max(x/v,.001),.999)})}}}function zs(c,e,t,n){const r=c.length,s=new Array(r).fill(.01),o=e.invertedIndex;if(o==null||t===null)return s;const i=n??"",a=new lt(Ke(),o.stats),l=t.toLowerCase().split(/\s+/).filter(p=>p.length>0);if(l.length===0)return s;const u=new me(t,i||null),f=new de(a,u,l,i||null).execute(e),d=new Map;for(const p of f)d.set(p.docId,p.payload.score);for(let p=0;p<c.length;p++){const m=d.get(c[p].docId)??.01;s[p]=Math.min(Math.max(m,.01),.99)}return s}class fr extends q{constructor(t,n,r="embedding",s="kde",o=.5,i="density_prior",a,l,u=1,h=1){super();b(this,"queryVector");b(this,"k");b(this,"field");b(this,"estimationMethod");b(this,"baseRate");b(this,"weightSource");b(this,"bm25Query");b(this,"bm25Field");b(this,"densityGamma");b(this,"bandwidthScale");this.queryVector=t,this.k=n,this.field=r,this.estimationMethod=s,this.baseRate=o,this.weightSource=i,this.bm25Query=a??null,this.bm25Field=l??null,this.densityGamma=u,this.bandwidthScale=h}execute(t){var x;const n=(x=t.vectorIndexes)==null?void 0:x[this.field];if(n===void 0)return new D;const r=n.searchKnn(this.queryVector,this.k);if(r.length===0)return r;const s=[],o=[],i=[];for(const v of r)s.push(v),o.push(v.docId),i.push(v.payload.score);const a=i.map(v=>1-v);let l=null,u=null;const h=n;if(typeof h.probedDistances=="function"){l=h;const v=h.probedDistances(this.queryVector);v!==null&&v.length>0&&(u=Array.isArray(v)?v:Array.from(v))}if((u===null||u.length===0)&&h.backgroundSamples!==null&&h.backgroundSamples!==void 0){l=h;const v=h.backgroundSamples;v.length>0&&(u=Array.isArray(v)?v:Array.from(v))}if(u===null||u.length===0)return r;const f=qs(u,this.baseRate),{weights:d,densityPrior:p,method:m}=this._resolveWeightsAndMethod(s,l,a,t),_=f.calibrate(a,{weights:d,method:m,bandwidthFactor:this.bandwidthScale,densityPrior:p}),y=o.map((v,E)=>({docId:v,payload:U({score:_[E],fields:{_raw_similarity:i[E],...s[E].payload.fields}})}));return new D(y)}_resolveWeightsAndMethod(t,n,r,s){if(this.weightSource==="bayesian_bm25")return{weights:zs(t,s,this.bm25Query,this.bm25Field),densityPrior:null,method:this.estimationMethod};if(this.weightSource==="density_prior"&&n!==null&&typeof n.cellPopulations=="function"){const o=n.cellPopulations(),i=(n.totalVectors??0)/Math.max(n.nlist??1,1);return{weights:null,densityPrior:t.map(l=>{const u=l.payload.fields._centroid_id??-1,h=o.get(u)??1;return $s(h,i,this.densityGamma)}),method:this.estimationMethod}}return this.weightSource==="distance_gap"?{weights:null,densityPrior:null,method:"auto"}:{weights:null,densityPrior:null,method:this.estimationMethod}}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}function Gs(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function Bs(c){const e=Math.max(1e-10,Math.min(.9999999999,c));return Math.log(e/(1-e))}function Us(c,e){if(e<=0)return .5;const t=c/e;return Gs(Bs(.5)-.5*t)}class dr{constructor(e,t,n=.5,r=10,s){b(this,"_signalPostingLists");b(this,"_signalUpperBounds");b(this,"_alpha");b(this,"_k");b(this,"_gating");this._signalPostingLists=e,this._signalUpperBounds=t,this._alpha=n,this._k=r,this._gating=s??null}_computeFusedUpperBound(e){return K.logOddsConjunction(e,this._alpha,void 0,this._gating??"none")}scoreTopK(){const e=this._signalPostingLists.length,t=[],n=new Set;let r=0;for(let l=0;l<e;l++){const u=new Map;for(const h of this._signalPostingLists[l])u.set(h.docId,h.payload.score),n.add(h.docId);t.push(u),r=Math.max(r,u.size)}const s=t.map(l=>Us(l.size,r)),o=[];let i=0;for(const l of n){const u=[];for(let p=0;p<e;p++)t[p].has(l)?u.push(this._signalUpperBounds[p]):u.push(s[p]);const h=this._computeFusedUpperBound(u);if(o.length>=this._k&&h<=i)continue;const f=[];for(let p=0;p<e;p++)f.push(t[p].get(l)??s[p]);const d=K.logOddsConjunction(f,this._alpha,void 0,this._gating??"none");o.length<this._k?(o.push([d,l]),Ws(o,o.length-1),o.length===this._k&&(i=o[0][0])):d>i&&(o[0]=[d,l],Hs(o),i=o[0][0])}const a=o.map(([l,u])=>({docId:u,payload:U({score:l})}));return new D(a)}}function Ws(c,e){for(;e>0;){const t=e-1>>>1;if(c[t][0]<=c[e][0])break;[c[t],c[e]]=[c[e],c[t]],e=t}}function Hs(c){const e=c.length;let t=0;for(;;){let n=t;const r=2*t+1,s=2*t+2;if(r<e&&c[r][0]<c[n][0]&&(n=r),s<e&&c[s][0]<c[n][0]&&(n=s),n===t)break;[c[t],c[n]]=[c[n],c[t]],t=n}}function ct(c,e,t=.01){if(e<=0)return .5;const n=c/e;return .5*(1-n)+t*n}class Ks extends q{constructor(t,n,r){super();b(this,"_termOp");b(this,"_vectorOp");this._termOp=new me(t),this._vectorOp=new xe(n,r)}execute(t){const n=this._termOp.execute(t),r=this._vectorOp.execute(t);return n.intersect(r)}costEstimate(t){return Math.min(this._termOp.costEstimate(t),this._vectorOp.costEstimate(t))}}class Js extends q{constructor(t,n,r){super();b(this,"source");b(this,"_vectorOp");this.source=t,this._vectorOp=new xe(n,r)}execute(t){const n=this.source.execute(t),r=this._vectorOp.execute(t);return n.intersect(r)}costEstimate(t){return Math.min(this.source.costEstimate(t),this._vectorOp.costEstimate(t))}}class Ae extends q{constructor(t,n=.5,r,s,o){super();b(this,"signals");b(this,"alpha");b(this,"topK");b(this,"gating");b(this,"gatingBeta");this.signals=t,this.alpha=n,this.topK=r??null,this.gating=s??null,this.gatingBeta=o??null}execute(t){const n=this.signals.map(f=>f.execute(t));if(this.topK!==null){const f=n.map(p=>{let m=0;for(const _ of p)_.payload.score>m&&(m=_.payload.score);return Math.max(m,.5)});return new dr(n,f,this.alpha,this.topK,this.gating).scoreTopK()}const r=[],s=new Set;for(const f of n){const d=new Map;for(const p of f)d.set(p.docId,p.payload.score),s.add(p.docId);r.push(d)}const o=[...s].sort((f,d)=>f-d),i=o.length,a=r.length;if(i===0)return new D;const l=r.map(f=>ct(f.size,i)),u=[],h=this.alpha;for(const f of o){const d=[];for(let m=0;m<a;m++)d.push(r[m].get(f)??l[m]);let p;a===1?p=d[0]:p=K.logOddsConjunction(d,h,void 0,this.gating??"none",this.gatingBeta??void 0),u.push({docId:f,payload:U({score:p})})}return D.fromSorted(u)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class je extends q{constructor(t,n="and"){super();b(this,"signals");b(this,"mode");this.signals=t,this.mode=n}execute(t){const n=this.signals.map(u=>u.execute(t)),r=[],s=new Set;for(const u of n){const h=new Map;for(const f of u)h.set(f.docId,f.payload.score),s.add(f.docId);r.push(h)}const o=[...s].sort((u,h)=>u-h),i=o.length,a=r.map(u=>ct(u.size,i)),l=[];for(const u of o){const h=[];for(let d=0;d<r.length;d++)h.push(r[d].get(u)??a[d]);const f=this.mode==="and"?K.probAnd(h):K.probOr(h);l.push({docId:u,payload:U({score:f})})}return D.fromSorted(l)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class En extends q{constructor(t,n,r,s="embedding"){super();b(this,"positive");b(this,"_negativeOp");this.positive=t,this._negativeOp=new xe(n,r,s)}execute(t){const n=this.positive.execute(t),r=this._negativeOp.execute(t),s=new Set;for(const i of r)s.add(i.docId);const o=[...n].filter(i=>!s.has(i.docId));return D.fromSorted(o)}costEstimate(t){return this.positive.costEstimate(t)+this._negativeOp.costEstimate(t)}}class pr extends q{constructor(t,n,r,s){super();b(this,"facetField");b(this,"_vectorOp");b(this,"source");this.facetField=t,this._vectorOp=new xe(n,r),this.source=s??null}execute(t){const n=this._vectorOp.execute(t),r=new Set;for(const l of n)r.add(l.docId);let s;this.source!==null?s=[...this.source.execute(t)].filter(u=>r.has(u.docId)).map(u=>u.docId):s=[...r].sort((l,u)=>l-u);const o=t.documentStore;if(!o)return new D;const i=new Map;for(const l of s){const u=o.getField(l,this.facetField);if(u!=null){const h=String(u);i.set(h,(i.get(h)??0)+1)}}const a=[...i.entries()].sort((l,u)=>l[0].localeCompare(u[0]));return D.fromSorted(a.map(([l,u],h)=>({docId:h,payload:U({score:u,fields:{_facet_field:this.facetField,_facet_value:l,_facet_count:u}})})))}costEstimate(t){let n=this._vectorOp.costEstimate(t);return this.source!==null&&(n+=this.source.costEstimate(t)),n}}class Gt extends q{constructor(t,n=.01){super();b(this,"signal");b(this,"defaultProb");this.signal=t,this.defaultProb=n}execute(t){const n=this.signal.execute(t),r=t.documentStore,s=new Map;for(const l of n)s.set(l.docId,l.payload.score);const o=new Set(s.keys());if(r)for(const l of r.docIds)o.add(l);const i=[...o].sort((l,u)=>l-u),a=[];for(const l of i){const h=1-(s.get(l)??this.defaultProb);a.push({docId:l,payload:U({score:h})})}return D.fromSorted(a)}costEstimate(t){return this.signal.costEstimate(t)}}class Ys extends q{constructor(t,n=.5,r){super();b(this,"signals");b(this,"baseAlpha");b(this,"gating");this.signals=t,this.baseAlpha=n,this.gating=r??null}execute(t){const n=this.signals.map(h=>h.execute(t)),r=new Set,s=[];for(const h of n){const f=new Map;for(const d of h)f.set(d.docId,d.payload.score),r.add(d.docId);s.push(f)}const o=[...r].sort((h,f)=>h-f),i=o.length;if(i===0)return new D;const a=[];for(const h of s){const f=i>0?h.size/i:0,d=[...h.values()];let p=0;if(d.length>1){let y=0;for(const v of d)y+=v;y/=d.length;let x=0;for(const v of d)x+=(v-y)*(v-y);p=x/d.length}let m=.5;if(d.length>0){let y=0;for(const x of d)y+=x;m=y/d.length}const _=Math.abs(m-.5);a.push({coverageRatio:f,scoreVariance:p,calibrationError:_})}const l=s.map(h=>ct(h.size,i)),u=[];for(const h of o){const f=[];for(let _=0;_<s.length;_++)f.push(s[_].get(h)??l[_]);const d=[];for(const _ of a){const y=_.coverageRatio*(1-_.calibrationError);d.push(this.baseAlpha*(.5+y))}let p=this.baseAlpha;if(d.length>0){let _=0;for(const y of d)_+=y;p=_/d.length}const m=K.logOddsConjunction(f,p,void 0,this.gating??"none");u.push({docId:h,payload:U({score:m})})}return D.fromSorted(u)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}function gr(c){return c===" "||c===" "||c===`
2
- `||c==="\r"}function mr(c){return!gr(c)&&c!=="("&&c!==")"&&c!==":"&&c!=='"'&&c!=="["&&c!=="]"}const Xs={and:"AND",or:"OR",not:"NOT"};function Qs(c){const e=[];let t=0;const n=c.length;for(;t<n;){const r=c[t];if(gr(r)){t++;continue}if(r==="("){e.push({type:"LPAREN",value:"(",pos:t}),t++;continue}if(r===")"){e.push({type:"RPAREN",value:")",pos:t}),t++;continue}if(r===":"){e.push({type:"COLON",value:":",pos:t}),t++;continue}if(r==='"'){const s=t;t++;let o="";for(;t<n&&c[t]!=='"';)o+=c[t],t++;if(t>=n)throw new Error(`Unterminated quoted phrase starting at position ${String(s)}`);e.push({type:"PHRASE",value:o,pos:s}),t++;continue}if(r==="["){const s=t;t++;let o="";for(;t<n&&c[t]!=="]";)o+=c[t],t++;if(t>=n)throw new Error(`Unterminated vector literal starting at position ${String(s)}`);e.push({type:"VECTOR",value:o.trim(),pos:s}),t++;continue}if(mr(r)){const s=t;let o="";for(;t<n&&mr(c[t]);)o+=c[t],t++;const i=Xs[o.toLowerCase()];i!==void 0?e.push({type:i,value:o,pos:s}):e.push({type:"TERM",value:o,pos:s});continue}throw new Error(`Unexpected character '${r}' at position ${String(t)}`)}return e.push({type:"EOF",value:"",pos:n}),e}class Zs{constructor(e){b(this,"_tokens");b(this,"_pos");this._tokens=e,this._pos=0}parse(){if(this._peek().type==="EOF")throw new Error("Empty query");const e=this._orExpr();if(this._peek().type!=="EOF"){const t=this._peek();throw new Error(`Unexpected token '${t.value}' at position ${String(t.pos)}`)}return e}_peek(){return this._tokens[this._pos]??{type:"EOF",value:"",pos:-1}}_advance(){const e=this._peek();return e.type!=="EOF"&&this._pos++,e}_expect(e){const t=this._advance();if(t.type!==e)throw new Error(`Expected ${e}, got ${t.type} ('${t.value}') at position ${String(t.pos)}`);return t}_orExpr(){let e=this._andExpr();for(;this._peek().type==="OR";){this._advance();const t=this._andExpr();e={type:"or",left:e,right:t}}return e}_andExpr(){let e=this._unary();for(;;){const t=this._peek();if(t.type==="AND"){this._advance();const n=this._unary();e={type:"and",left:e,right:n}}else if(t.type==="TERM"||t.type==="PHRASE"||t.type==="VECTOR"||t.type==="LPAREN"||t.type==="NOT"){const n=this._unary();e={type:"and",left:e,right:n}}else break}return e}_unary(){return this._peek().type==="NOT"?(this._advance(),{type:"not",operand:this._unary()}):this._primary()}_primary(){const e=this._peek();if(e.type==="LPAREN"){this._advance();const t=this._orExpr();return this._expect("RPAREN"),t}if(e.type==="PHRASE")return this._advance(),{type:"phrase",field:null,phrase:e.value};if(e.type==="VECTOR")return this._advance(),{type:"vector",field:null,values:_r(e.value)};if(e.type==="TERM"){if(this._advance(),this._peek().type==="COLON"){this._advance();const t=this._peek();if(t.type==="PHRASE")return this._advance(),{type:"phrase",field:e.value,phrase:t.value};if(t.type==="VECTOR")return this._advance(),{type:"vector",field:e.value,values:_r(t.value)};if(t.type==="TERM")return this._advance(),{type:"term",field:e.value,term:t.value};throw new Error(`Expected term, phrase, or vector after ':', got ${t.type} at position ${String(t.pos)}`)}return{type:"term",field:null,term:e.value}}throw new Error(`Unexpected token ${e.type} ('${e.value}') at position ${String(e.pos)}`)}}function _r(c){const e=c.trim();if(e.length===0)throw new Error("Empty vector literal");return e.split(",").map(t=>{const n=Number(t.trim());if(Number.isNaN(n))throw new Error(`Malformed vector literal: invalid number '${t.trim()}'`);return n})}function ut(c,e){switch(e.type){case"term":return c.includes(e.term.toLowerCase());case"phrase":return c.includes(e.phrase.toLowerCase());case"and":return ut(c,e.left)&&ut(c,e.right);case"or":return ut(c,e.left)||ut(c,e.right);case"not":return!ut(c,e.operand);case"vector":return!1;default:return!1}}function yr(c,e){try{const t=Qs(e),n=new Zs(t).parse();return ut(c.toLowerCase(),n)}catch{const t=e.toLowerCase().split(/\s+/).filter(n=>n.length>0);return t.length===0?!1:t.every(n=>c.toLowerCase().includes(n))}}function M(c){return typeof c=="string"?c:c==null?"":typeof c=="number"?c.toString(10):typeof c=="boolean"?c?"true":"false":typeof c=="bigint"?c.toString(10):JSON.stringify(c)}function eo(c){const e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],t=[];for(let p=0;p<64;p++)t.push(Math.floor(Math.abs(Math.sin(p+1))*4294967296));const r=new TextEncoder().encode(c),s=r.length*8,o=r.length%64<56?56-r.length%64:120-r.length%64,i=new Uint8Array(r.length+o+8);i.set(r),i[r.length]=128;const a=new DataView(i.buffer);a.setUint32(i.length-8,s>>>0,!0),a.setUint32(i.length-4,Math.floor(s/4294967296),!0);let l=1732584193,u=4023233417,h=2562383102,f=271733878;for(let p=0;p<i.length;p+=64){const m=[];for(let E=0;E<16;E++)m.push(a.getUint32(p+E*4,!0));let _=l,y=u,x=h,v=f;for(let E=0;E<64;E++){let I,S;E<16?(I=y&x|~y&v,S=E):E<32?(I=v&y|~v&x,S=(5*E+1)%16):E<48?(I=y^x^v,S=(3*E+5)%16):(I=x^(y|~v),S=7*E%16),I=I+_+t[E]+m[S]>>>0,_=v,v=x,x=y,y=y+(I<<e[E]|I>>>32-e[E])>>>0}l=l+_>>>0,u=u+y>>>0,h=h+x>>>0,f=f+v>>>0}function d(p){let m="";for(let _=0;_<4;_++){const y=p>>>_*8&255;m+=(y<16?"0":"")+y.toString(16)}return m}return d(l)+d(u)+d(h)+d(f)}function br(c){if(c.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(c))return new Date(c);const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?)?$/.exec(c);if(e){const t=parseInt(e[1],10),n=parseInt(e[2],10)-1,r=parseInt(e[3],10),s=e[4]!==void 0?parseInt(e[4],10):0,o=e[5]!==void 0?parseInt(e[5],10):0,i=e[6]!==void 0?parseInt(e[6],10):0,a=e[7]!==void 0?parseInt(e[7].padEnd(3,"0").slice(0,3),10):0;return new Date(t,n,r,s,o,i,a)}return new Date(c)}function vr(c){const e=String(c.getFullYear()).padStart(4,"0"),t=String(c.getMonth()+1).padStart(2,"0"),n=String(c.getDate()).padStart(2,"0"),r=String(c.getHours()).padStart(2,"0"),s=String(c.getMinutes()).padStart(2,"0"),o=String(c.getSeconds()).padStart(2,"0"),i=String(c.getMilliseconds()).padStart(3,"0");return`${e}-${t}-${n}T${r}:${s}:${o}.${i}`}function In(c,e){var t;switch(c){case"upper":return e[0]===null?null:M(e[0]).toUpperCase();case"lower":return e[0]===null?null:M(e[0]).toLowerCase();case"length":case"char_length":case"character_length":return e[0]===null?null:M(e[0]).length;case"octet_length":return e[0]===null?null:new TextEncoder().encode(M(e[0])).length;case"trim":case"btrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=0,o=r.length;for(;s<o&&n.includes(r[s]);)s++;for(;o>s&&n.includes(r[o-1]);)o--;return r.slice(s,o)}return M(e[0]).trim();case"ltrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=0;for(;s<r.length&&n.includes(r[s]);)s++;return r.slice(s)}return M(e[0]).replace(/^\s+/,"");case"rtrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=r.length;for(;s>0&&n.includes(r[s-1]);)s--;return r.slice(0,s)}return M(e[0]).replace(/\s+$/,"");case"replace":return e[0]===null?null:M(e[0]).split(M(e[1])).join(M(e[2]));case"substring":case"substr":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1])-1;if(e.length>=3){const s=Number(e[2]);return n.slice(r,r+s)}return n.slice(r)}case"concat":return e.map(n=>n===null?"":M(n)).join("");case"concat_ws":{if(e[0]===null||e[0]===void 0)return null;const n=M(e[0]);return e.slice(1).filter(r=>r!=null).map(r=>M(r)).join(n)}case"left":return e[0]===null?null:M(e[0]).slice(0,Number(e[1]));case"right":return e[0]===null?null:M(e[0]).slice(-Number(e[1]));case"lpad":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1]),s=e.length>=3?M(e[2]):" ";return n.length>=r?n.slice(0,r):s.repeat(Math.ceil((r-n.length)/s.length)).slice(0,r-n.length)+n}case"rpad":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1]),s=e.length>=3?M(e[2]):" ";return n.length>=r?n.slice(0,r):n+s.repeat(Math.ceil((r-n.length)/s.length)).slice(0,r-n.length)}case"repeat":return e[0]===null?null:M(e[0]).repeat(Number(e[1]));case"reverse":return e[0]===null?null:Array.from(M(e[0])).reverse().join("");case"position":case"strpos":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).indexOf(M(e[1]));return n===-1?0:n+1}case"initcap":return e[0]===null?null:M(e[0]).replace(/\b\w/g,n=>n.toUpperCase());case"md5":return e[0]===null?null:eo(M(e[0]));case"encode":if(e[0]===null)return null;if(M(e[1]).toLowerCase()==="base64"&&typeof btoa=="function")return btoa(M(e[0]));throw new Error(`encode() format not supported: ${M(e[1])}`);case"decode":if(e[0]===null)return null;if(M(e[1]).toLowerCase()==="base64"&&typeof atob=="function")return atob(M(e[0]));throw new Error(`decode() format not supported: ${M(e[1])}`);case"abs":return e[0]===null?null:Math.abs(Number(e[0]));case"round":{if(e[0]===null)return null;const n=Number(e[0]);if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const s=10**Number(e[1]);return Math.round(n*s)/s}return Math.round(n)}case"ceil":case"ceiling":return e[0]===null?null:Math.ceil(Number(e[0]));case"floor":return e[0]===null?null:Math.floor(Number(e[0]));case"trunc":case"truncate":{if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const r=10**Number(e[1]);return Math.trunc(Number(e[0])*r)/r}return Math.trunc(Number(e[0]))}case"power":case"pow":return e[0]===null||e[1]===null?null:Math.pow(Number(e[0]),Number(e[1]));case"sqrt":return e[0]===null?null:Math.sqrt(Number(e[0]));case"cbrt":return e[0]===null?null:Math.cbrt(Number(e[0]));case"exp":return e[0]===null?null:Math.exp(Number(e[0]));case"ln":return e[0]===null?null:Math.log(Number(e[0]));case"log":return e[0]===null?null:e.length>=2&&e[1]!==null?Math.log(Number(e[1]))/Math.log(Number(e[0])):Math.log10(Number(e[0]));case"log10":case"log2":return e[0]===null?null:c==="log10"?Math.log10(Number(e[0])):Math.log2(Number(e[0]));case"mod":return e[0]===null||e[1]===null?null:Number(e[0])%Number(e[1]);case"sign":return e[0]===null?null:Math.sign(Number(e[0]));case"pi":return Math.PI;case"random":return Math.random();case"degrees":return e[0]===null?null:Number(e[0])*180/Math.PI;case"radians":return e[0]===null?null:Number(e[0])*Math.PI/180;case"sin":return e[0]===null?null:Math.sin(Number(e[0]));case"cos":return e[0]===null?null:Math.cos(Number(e[0]));case"tan":return e[0]===null?null:Math.tan(Number(e[0]));case"asin":return e[0]===null?null:Math.asin(Number(e[0]));case"acos":return e[0]===null?null:Math.acos(Number(e[0]));case"atan":return e[0]===null?null:Math.atan(Number(e[0]));case"atan2":return e[0]===null||e[1]===null?null:Math.atan2(Number(e[0]),Number(e[1]));case"div":return e[0]===null||e[1]===null||Number(e[1])===0?null:Math.trunc(Number(e[0])/Number(e[1]));case"gcd":{if(e[0]===null||e[1]===null)return null;let n=Math.abs(Math.trunc(Number(e[0]))),r=Math.abs(Math.trunc(Number(e[1])));for(;r;){const s=r;r=n%r,n=s}return n}case"lcm":{if(e[0]===null||e[1]===null)return null;const n=Math.abs(Math.trunc(Number(e[0]))),r=Math.abs(Math.trunc(Number(e[1])));if(n===0||r===0)return 0;let s=n,o=r;for(;o;){const i=o;o=s%o,s=i}return Math.abs(n*r)/s}case"width_bucket":{if(e.length<4||e.some(i=>i===null))return null;const n=Number(e[0]),r=Number(e[1]),s=Number(e[2]),o=Math.trunc(Number(e[3]));return s===r||o<=0?null:n<r?0:n>=s?o+1:Math.trunc((n-r)/((s-r)/o))+1}case"min_scale":{if(e[0]===null)return null;const n=String(e[0]),r=n.indexOf(".");if(r===-1)return 0;let s=n.length;for(;s>r+1&&n[s-1]==="0";)s--;return s-r-1}case"trim_scale":{if(e[0]===null)return null;const n=Number(e[0]);return Number.isInteger(n),n}case"translate":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]),r=M(e[1]),s=M(e[2]);let o="";for(const i of n){const a=r.indexOf(i);a===-1?o+=i:a<s.length&&(o+=s[a])}return o}case"ascii":return e[0]===null?null:M(e[0]).length>0?M(e[0]).charCodeAt(0):0;case"chr":return e[0]===null?null:String.fromCharCode(Math.trunc(Number(e[0])));case"starts_with":return e[0]===null||e[1]===null?null:M(e[0]).startsWith(M(e[1]));case"split_part":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]).split(M(e[1])),r=Math.trunc(Number(e[2]));return r>=1&&r<=n.length?n[r-1]:""}case"format":{if(e[0]===null)return null;let n=M(e[0]);n=n.replace(/%I/g,"%s").replace(/%L/g,"'%s'");let r=1;return n.replace(/%s/g,()=>r<e.length?M(e[r++]):"")}case"overlay":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]),r=M(e[1]),s=Math.trunc(Number(e[2]))-1,o=e.length>3&&e[3]!=null?Math.trunc(Number(e[3])):r.length;return n.slice(0,s)+r+n.slice(s+o)}case"regexp_match":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).match(new RegExp(M(e[1])));if(n===null)return null;const r=n.slice(1);return r.length>0?r:[n[0]]}case"regexp_matches":{if(e[0]===null||e[1]===null)return null;const n=e.length>2&&e[2]!=null?M(e[2]):"";let r="";if(n.includes("i")&&(r+="i"),n.includes("g")){const o=new RegExp(M(e[1]),r+"g"),i=[];let a;for(;(a=o.exec(M(e[0])))!==null;)i.push(a.slice(1).length>0?[...a.slice(1)]:[a[0]]);return i}const s=M(e[0]).match(new RegExp(M(e[1]),r));return s===null?null:[s.slice(1).length>0?[...s.slice(1)]:[s[0]]]}case"regexp_replace":{if(e[0]===null||e[1]===null)return null;const n=e.length>2&&e[2]!=null?M(e[2]):"",r=e.length>3&&e[3]!=null?M(e[3]):"";let s="";return r.includes("i")&&(s+="i"),r.includes("g")?s+="g":s.includes("g"),M(e[0]).replace(new RegExp(M(e[1]),s||void 0),n)}case"regexp_split_to_array":{if(e[0]===null||e[1]===null)return null;let n="";return e.length>2&&e[2]!=null&&M(e[2]).includes("i")&&(n="i"),M(e[0]).split(new RegExp(M(e[1]),n))}case"regexp_count":{if(e[0]===null||e[1]===null)return 0;let n="";e.length>2&&e[2]!=null&&(n=M(e[2]));const r=new RegExp(M(e[1]),"g"+(n.includes("i")?"i":"")),s=M(e[0]).match(r);return s!==null?s.length:0}case"string_to_array":{if(e[0]===null)return null;const n=e.length>1&&e[1]!=null?M(e[1]):",",r=e.length>2&&e[2]!=null?M(e[2]):null,s=M(e[0]).split(n);return r!==null?s.map(o=>o===r?null:o):s}case"array_to_string":{if(e[0]===null||!Array.isArray(e[0]))return null;const n=e.length>1&&e[1]!=null?M(e[1]):",",r=e.length>2&&e[2]!=null?M(e[2]):"";return e[0].map(s=>s==null?r:M(s)).join(n)}case"array_position":{if(e[0]===null||e[1]===null||!Array.isArray(e[0]))return null;const n=e[0].indexOf(e[1]);return n===-1?null:n+1}case"array_positions":{if(e[0]===null||e[1]===null||!Array.isArray(e[0]))return null;const n=[];for(let r=0;r<e[0].length;r++)e[0][r]===e[1]&&n.push(r+1);return n}case"array_replace":return e[0]===null||!Array.isArray(e[0])?null:e[0].map(n=>n===e[1]?e[2]:n);case"array_dims":return e[0]===null||!Array.isArray(e[0])?null:`[1:${String(e[0].length)}]`;case"array_fill":{if(e.length<2||e[1]===null)return null;const n=e[0],s=(Array.isArray(e[1])?e[1]:[Number(e[1])])[0]??0;return new Array(s).fill(n)}case"generate_series":{if(e.length<2||e[0]===null||e[1]===null)return[];const n=Number(e[0]),r=Number(e[1]),s=e.length>2&&e[2]!=null?Number(e[2]):1;if(s===0)return[];const o=[];if(s>0)for(let i=n;i<=r;i+=s)o.push(i);else for(let i=n;i>=r;i+=s)o.push(i);return o}case"generate_subscripts":{if(e[0]===null)return[];if(!Array.isArray(e[0]))return[];const n=e[0];return Array.from({length:n.length},(r,s)=>s+1)}case"hashtext":{if(e[0]===null)return null;let n=2166136261;const r=M(e[0]);for(let s=0;s<r.length;s++)n^=r.charCodeAt(s),n=Math.imul(n,16777619);return n>>>0}case"quote_ident":return e[0]===null?null:`"${M(e[0]).replace(/"/g,'""')}"`;case"quote_literal":return e[0]===null?"NULL":`'${M(e[0]).replace(/'/g,"''")}'`;case"quote_nullable":return e[0]===null?"NULL":`'${M(e[0]).replace(/'/g,"''")}'`;case"string_agg":return e[0]===null?null:M(e[0]);case"to_hex":{if(e[0]===null)return null;const n=Math.trunc(Number(e[0]));return n>=0?n.toString(16):(n>>>0).toString(16)}case"to_ascii":return e[0]===null?null:M(e[0]).replace(/[^\x00-\x7F]/g,"?");case"date_trunc":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).toLowerCase(),r=br(M(e[1]));return n==="year"?(r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0)):n==="month"?(r.setDate(1),r.setHours(0,0,0,0)):n==="day"?r.setHours(0,0,0,0):n==="hour"?r.setMinutes(0,0,0):n==="minute"?r.setSeconds(0,0):n==="second"&&r.setMilliseconds(0),vr(r)}case"make_timestamp":{if(e.length<6||e.some(r=>r===null))return null;const n=new Date(Number(e[0]),Number(e[1])-1,Number(e[2]),Number(e[3]),Number(e[4]),Math.trunc(Number(e[5])));return vr(n)}case"make_interval":{const n=e.length>0&&e[0]!=null?Number(e[0]):0,r=e.length>1&&e[1]!=null?Number(e[1]):0,s=e.length>2&&e[2]!=null?Number(e[2]):0,o=e.length>3&&e[3]!=null?Number(e[3]):0,i=e.length>4&&e[4]!=null?Number(e[4]):0,a=e.length>5&&e[5]!=null?Number(e[5]):0,l=e.length>6&&e[6]!=null?Number(e[6]):0,u=n*365+r*30+s*7+o,h=[];return n>0&&h.push(`${String(n)} year${n>1?"s":""}`),r>0&&h.push(`${String(r)} mon${r>1?"s":""}`),u>0&&h.push(`${String(u)} day${u!==1?"s":""}`),h.push(`${String(i).padStart(2,"0")}:${String(a).padStart(2,"0")}:${String(l).padStart(2,"0")}`),h.join(" ")}case"make_date":{if(e.length<3||e.some(o=>o===null))return null;const n=String(Number(e[0])).padStart(4,"0"),r=String(Number(e[1])).padStart(2,"0"),s=String(Number(e[2])).padStart(2,"0");return`${n}-${r}-${s}`}case"clock_timestamp":return new Date().toISOString();case"timeofday":return new Date().toUTCString();case"isfinite":return e[0]===null?null:!["infinity","-infinity"].includes(M(e[0]).trim().toLowerCase());case"overlaps":{if(e.length<4||e.some(i=>i===null))return null;const n=new Date(M(e[0])).getTime(),r=new Date(M(e[1])).getTime(),s=new Date(M(e[2])).getTime(),o=new Date(M(e[3])).getTime();return Math.min(n,r)<Math.max(s,o)&&Math.min(s,o)<Math.max(n,r)}case"typeof":case"pg_typeof":return e[0]===null?"null":typeof e[0]=="number"?Number.isInteger(e[0])?"integer":"real":typeof e[0]=="string"?"text":typeof e[0]=="boolean"?"boolean":"unknown";case"gen_random_uuid":return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)});case"array_remove":return e[0]===null?null:Array.isArray(e[0])?e[0].filter(n=>n!==e[1]):null;case"array_upper":return e[0]===null?null:Array.isArray(e[0])&&e[0].length>0?e[0].length:null;case"array_lower":return e[0]===null?null:Array.isArray(e[0])&&e[0].length>0?1:null;case"cardinality":return e[0]===null?null:Array.isArray(e[0])?e[0].length:null;case"json_extract_path":case"jsonb_extract_path":case"json_extract_path_text":case"jsonb_extract_path_text":{if(e[0]===null)return null;let n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];for(let r=1;r<e.length;r++){if(e[r]===null||n===null||n===void 0)return null;if(typeof n=="object"&&!Array.isArray(n))n=n[M(e[r])];else if(Array.isArray(n))n=n[Number(e[r])];else return null}return c.endsWith("_text")?n==null?null:typeof n=="object"?JSON.stringify(n):M(n):n??null}case"jsonb_set":case"jsonb_insert":{if(e.length<3||e[0]===null)return null;let n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];n=JSON.parse(JSON.stringify(n));const s=M(e[1]).replace(/^\{/,"").replace(/\}$/,"").split(",").map(l=>l.trim()),o=e[2];let i=n;for(let l=0;l<s.length-1;l++)if(typeof i=="object"&&i!==null&&!Array.isArray(i))i=i[s[l]];else if(Array.isArray(i))i=i[Number(s[l])];else return n;const a=s[s.length-1];return typeof i=="object"&&i!==null&&!Array.isArray(i)?i[a]=o:Array.isArray(i)&&(i[Number(a)]=o),n}case"json_each":case"jsonb_each":case"json_each_text":case"jsonb_each_text":{if(e[0]===null)return[];const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];if(typeof n!="object"||Array.isArray(n)||n===null)return[];const r=c.endsWith("_text");return Object.entries(n).map(([s,o])=>({key:s,value:r?typeof o=="object"&&o!==null?JSON.stringify(o):o!=null?M(o):null:o}))}case"json_array_elements":case"jsonb_array_elements":case"json_array_elements_text":case"jsonb_array_elements_text":{if(e[0]===null)return[];const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return Array.isArray(n)?c.endsWith("_text")?n.map(r=>typeof r=="object"&&r!==null?JSON.stringify(r):r!=null?M(r):null):n:[]}case"json_object_keys":case"jsonb_object_keys":{if(e[0]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return typeof n!="object"||Array.isArray(n)||n===null?null:Object.keys(n)}case"jsonb_strip_nulls":case"json_strip_nulls":{let n=function(s){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const o={};for(const[i,a]of Object.entries(s))a!==null&&(o[i]=n(a));return o}return s};if(e[0]===null)return null;const r=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return n(r)}case"json_build_array":case"jsonb_build_array":return[...e];case"point":if(e.length!==2)throw new Error("POINT() requires exactly 2 arguments");return[Number(e[0]),Number(e[1])];case"st_distance":{if(e.length!==2||e[0]===null||e[1]===null)return null;const n=e[0],r=e[1];if(!Array.isArray(n)||!Array.isArray(r))return null;const s=6371e3,o=n[1]*Math.PI/180,i=r[1]*Math.PI/180,a=(r[1]-n[1])*Math.PI/180,l=(r[0]-n[0])*Math.PI/180,u=Math.sin(a/2)**2+Math.cos(o)*Math.cos(i)*Math.sin(l/2)**2;return s*2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))}case"st_within":case"st_dwithin":{if(e.length!==3||e[0]===null||e[1]===null)return null;const n=In("st_distance",[e[0],e[1]]);return n===null?null:n<=Number(e[2])}case"coalesce":for(const n of e)if(n!=null)return n;return null;case"nullif":return e[0]===e[1]?null:e[0];case"greatest":{let n=null;for(const r of e)r!==null&&(n===null||r>n)&&(n=r);return n}case"least":{let n=null;for(const r of e)r!==null&&(n===null||r<n)&&(n=r);return n}case"current_date":case"current_timestamp":case"now":return new Date().toISOString();case"date_part":case"extract":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).toLowerCase(),r=br(M(e[1]));switch(n){case"year":return r.getFullYear();case"month":return r.getMonth()+1;case"day":return r.getDate();case"hour":return r.getHours();case"minute":return r.getMinutes();case"second":return r.getSeconds();case"dow":case"dayofweek":return r.getDay();case"doy":case"dayofyear":{const s=new Date(r.getFullYear(),0,0),o=r.getTime()-s.getTime();return Math.floor(o/864e5)}case"epoch":return Math.floor(r.getTime()/1e3);case"quarter":return Math.ceil((r.getMonth()+1)/3);case"week":{const s=new Date(r.getFullYear(),0,1),o=Math.floor((r.getTime()-s.getTime())/864e5)+1,i=s.getDay()||7;return Math.ceil((o+i-1)/7)}case"millisecond":case"milliseconds":return r.getSeconds()*1e3+r.getMilliseconds();case"microsecond":case"microseconds":return r.getSeconds()*1e6+r.getMilliseconds()*1e3;default:throw new Error(`Unknown date part: "${n}"`)}}case"age":{if(e[0]===null)return null;const n=new Date(M(e[0])),s=(e.length>=2&&e[1]!==null?new Date(M(e[1])):new Date).getTime()-n.getTime();return`${String(Math.floor(s/864e5))} days`}case"date_add":case"dateadd":{if(e.length<3||e.some(o=>o===null))return null;const n=M(e[0]).toLowerCase(),r=Number(e[1]),s=new Date(M(e[2]));return n==="year"?s.setFullYear(s.getFullYear()+r):n==="month"?s.setMonth(s.getMonth()+r):n==="day"?s.setDate(s.getDate()+r):n==="hour"?s.setHours(s.getHours()+r):n==="minute"?s.setMinutes(s.getMinutes()+r):n==="second"&&s.setSeconds(s.getSeconds()+r),s.toISOString()}case"date_subtract":case"datesub":{if(e.length<3||e.some(o=>o===null))return null;const n=M(e[0]).toLowerCase(),r=Number(e[1]),s=new Date(M(e[2]));return n==="year"?s.setFullYear(s.getFullYear()-r):n==="month"?s.setMonth(s.getMonth()-r):n==="day"?s.setDate(s.getDate()-r):n==="hour"?s.setHours(s.getHours()-r):n==="minute"?s.setMinutes(s.getMinutes()-r):n==="second"&&s.setSeconds(s.getSeconds()-r),s.toISOString()}case"date_diff":case"datediff":{if(e.length<3||e.some(i=>i===null))return null;const n=M(e[0]).toLowerCase(),r=new Date(M(e[1])),s=new Date(M(e[2])),o=s.getTime()-r.getTime();return n==="day"?Math.trunc(o/864e5):n==="hour"?Math.trunc(o/36e5):n==="minute"?Math.trunc(o/6e4):n==="second"?Math.trunc(o/1e3):n==="year"?s.getFullYear()-r.getFullYear():n==="month"?(s.getFullYear()-r.getFullYear())*12+(s.getMonth()-r.getMonth()):Math.trunc(o/1e3)}case"justify_days":return e[0]===null?null:e[0];case"justify_hours":return e[0]===null?null:e[0];case"justify_interval":return e[0]===null?null:e[0];case"statement_timestamp":case"transaction_timestamp":return new Date().toISOString();case"to_char":{if(e[0]===null)return null;if(e.length>=2&&e[1]!=null){const n=e[0],r=M(e[1]);if(typeof n=="number"){if(r.includes("FM"))return String(n);if(r.includes("9")||r.includes("0")){const s=(((t=r.match(/\.([09]+)/))==null?void 0:t[1])??"").length;return n.toFixed(s)}}if(typeof n=="string"||n instanceof Date){const s=new Date(M(n));let o=r;return o=o.replace(/YYYY/g,String(s.getFullYear())),o=o.replace(/MM/g,String(s.getMonth()+1).padStart(2,"0")),o=o.replace(/DD/g,String(s.getDate()).padStart(2,"0")),o=o.replace(/HH24/g,String(s.getHours()).padStart(2,"0")),o=o.replace(/HH/g,String(s.getHours()%12||12).padStart(2,"0")),o=o.replace(/MI/g,String(s.getMinutes()).padStart(2,"0")),o=o.replace(/SS/g,String(s.getSeconds()).padStart(2,"0")),o}}return M(e[0])}case"to_number":{if(e[0]===null)return null;const n=M(e[0]).replace(/[^0-9eE.+-]/g,"");return Number(n)}case"to_date":case"to_timestamp":return e[0]===null?null:new Date(M(e[0])).toISOString();case"array_length":return e[0]===null?null:Array.isArray(e[0])?e[0].length:null;case"unnest":return e[0];case"array_agg":return e;case"array_cat":return e[0]===null||e[1]===null?null:[...e[0],...e[1]];case"array_append":return e[0]===null?null:[...e[0],e[1]];case"array_prepend":return e[1]===null?null:[e[0],...e[1]];case"json_build_object":case"jsonb_build_object":{const n={};for(let r=0;r+1<e.length;r+=2)n[M(e[r])]=e[r+1]??null;return n}case"json_array_length":case"jsonb_array_length":if(e[0]===null)return null;if(Array.isArray(e[0]))return e[0].length;if(typeof e[0]=="string"){const n=JSON.parse(e[0]);return Array.isArray(n)?n.length:null}return null;case"json_typeof":case"jsonb_typeof":return e[0]===null?"null":Array.isArray(e[0])?"array":typeof e[0]=="object"?"object":typeof e[0];case"row_to_json":return e[0];case"to_json":case"to_jsonb":return e[0];case"jsonb_pretty":{if(e[0]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return JSON.stringify(n,null,2)}case"jsonb_agg":case"json_agg":return e;case"jsonb_object_agg":case"json_object_agg":if(e.length>=2){const n={};return n[M(e[0])]=e[1],n}return{};case"jsonb_concat":{if(e[0]===null||e[1]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0],r=typeof e[1]=="string"?JSON.parse(e[1]):e[1];return Array.isArray(n)&&Array.isArray(r)?[...n,...r]:typeof n=="object"&&typeof r=="object"&&!Array.isArray(n)&&!Array.isArray(r)?{...n,...r}:n}case"jsonb_delete_path":{if(e[0]===null||e[1]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):JSON.parse(JSON.stringify(e[0])),r=Array.isArray(e[1])?e[1]:M(e[1]).replace(/^\{/,"").replace(/\}$/,"").split(",").map(i=>i.trim());if(r.length===0)return n;let s=n;for(let i=0;i<r.length-1;i++)if(typeof s=="object"&&s!==null&&!Array.isArray(s))s=s[r[i]];else if(Array.isArray(s))s=s[Number(r[i])];else return n;const o=r[r.length-1];return typeof s=="object"&&s!==null&&!Array.isArray(s)?delete s[o]:Array.isArray(s)&&s.splice(Number(o),1),n}case"current_schema":case"current_schemas":return"public";case"current_database":return"uqa";case"current_user":case"session_user":return"uqa_user";case"version":return"UQA 1.0";case"has_table_privilege":case"has_schema_privilege":case"has_column_privilege":return!0;case"txid_current":return 1;case"text_match":case"bayesian_match":{if(e.length<2)return!1;const n=e[0],r=e[1];return n===null||r===null?!1:yr(String(n),String(r))}default:throw new Error(`Unknown SQL function: ${c}`)}}function L(c,e){return c[e]??null}function Z(c,e){const t=c[e];return t==null?"":M(t)}function Mi(c){return c}function se(c){return Array.isArray(c)?c:[]}function Bt(c,e){if(e==null)return!0;if(c==null)return!1;if(typeof e!="object")return c===e;if(Array.isArray(e)){if(!Array.isArray(c))return!1;for(const t of e)if(!c.some(n=>Bt(n,t)))return!1;return!0}if(typeof c!="object"||Array.isArray(c))return!1;for(const[t,n]of Object.entries(e))if(!(t in c)||!Bt(c[t],n))return!1;return!0}function Et(c,e){let t="^";for(let n=0;n<c.length;n++){const r=c[n];r==="%"?t+=".*":r==="_"?t+=".":r==="\\"&&n+1<c.length?(n++,t+=c[n].replace(/[.*+?^${}()|[\]\\]/g,"\\$&")):t+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}return t+="$",new RegExp(t,e?"is":"s")}function to(c,e){if(c===null)return null;const t=e.toLowerCase();if(t==="integer"||t==="int"||t==="int4"||t==="bigint"||t==="int8"||t==="smallint"||t==="int2")return Math.trunc(Number(c));if(t==="float"||t==="float4"||t==="float8"||t==="double precision"||t==="real"||t==="numeric"||t==="decimal")return Number(c);if(t==="text"||t==="varchar"||t==="char"||t==="character varying")return M(c);if(t==="boolean"||t==="bool"){if(typeof c=="string"){const n=c.toLowerCase();return n==="true"||n==="t"||n==="1"||n==="yes"}return!!c}return t==="json"||t==="jsonb"?typeof c=="string"?JSON.parse(c):c:t==="date"||t==="timestamp"||t==="timestamptz"?new Date(M(c)).toISOString():c}class oe{constructor(e){b(this,"_params");b(this,"_sequences");b(this,"_outerRow");b(this,"_subqueryExecutor");this._params=(e==null?void 0:e.params)??[],this._sequences=(e==null?void 0:e.sequences)??null,this._outerRow=(e==null?void 0:e.outerRow)??null,this._subqueryExecutor=(e==null?void 0:e.subqueryExecutor)??null}evaluate(e,t){const n=Object.keys(e);if(n.length===0)return null;const r=n[0],s=e[r];switch(r){case"ColumnRef":return this._evalColumnRef(s,t);case"A_Const":return this._evalConst(s);case"A_Expr":return this._evalAExpr(s,t);case"BoolExpr":return this._evalBoolExpr(s,t);case"FuncCall":return this._evalFuncCall(s,t);case"NullTest":return this._evalNullTest(s,t);case"CaseExpr":return this._evalCaseExpr(s,t);case"NamedArgExpr":{const o=L(s,"arg");return o!=null?this.evaluate(o,t):null}case"TypeCast":return this._evalTypeCast(s,t);case"ParamRef":return this._evalParamRef(s);case"SubLink":return this._evalSubLink(s,t);case"CoalesceExpr":return this._evalCoalesceExpr(s,t);case"MinMaxExpr":return this._evalMinMaxExpr(s,t);case"BooleanTest":return this._evalBooleanTest(s,t);case"SQLValueFunction":return this._evalSQLValueFunction(s);case"A_ArrayExpr":return se(L(s,"elements")).map(o=>this.evaluate(o,t));case"List":return se(L(s,"items")).map(o=>this.evaluate(o,t));case"String":case"str":return Z(s,"sval")||Z(s,"str");case"Integer":return L(s,"ival")??0;case"Float":return Number(Z(s,"fval")||Z(s,"str"));default:return"ival"in e?e.ival:"fval"in e?Number(e.fval):"sval"in e?e.sval:"boolval"in e?e.boolval:"bsval"in e?e.bsval:e}}_evalColumnRef(e,t){const n=se(L(e,"fields"));if(n.length===0)return null;const r=[];for(const s of n){const o=L(s,"String")??L(s,"str");if(o!==null&&typeof o=="object"){const i=Z(o,"sval")||Z(o,"str");i&&r.push(i)}else if(typeof o=="string")r.push(o);else if(typeof s=="object"){const i=Z(s,"sval")||Z(s,"str");i&&r.push(i)}}if(r.length===1){const s=r[0];return s in t?t[s]:this._outerRow!==null&&s in this._outerRow?this._outerRow[s]:null}if(r.length===2){const s=`${r[0]}.${r[1]}`;if(s in t)return t[s];if(this._outerRow!==null&&s in this._outerRow)return this._outerRow[s];const o=r[1];return o in t?t[o]:this._outerRow!==null&&o in this._outerRow?this._outerRow[o]:null}return null}_evalConst(e){if(L(e,"isnull")===!0)return null;const t=L(e,"ival");if(t!=null){if(typeof t=="object"){const h=L(t,"ival");return h??(typeof t=="object"&&Object.keys(t).length===0?0:t)}return t}const n=L(e,"fval");if(n!=null)return Number(typeof n=="object"?L(n,"fval")??n:n);const r=L(e,"sval");if(r!=null)return typeof r=="object"?L(r,"sval")??r:r;const s=L(e,"boolval");if(s!=null)return typeof s=="object"?L(s,"boolval")??s:s;const o=L(e,"bsval");if(o!=null)return typeof o=="object"?L(o,"bsval")??o:o;const i=L(e,"Integer");if(i!=null)return L(i,"ival")??0;const a=L(e,"Float");if(a!=null)return Number(Z(a,"fval")||Z(a,"str"));const l=L(e,"String");if(l!=null)return Z(l,"sval")||Z(l,"str");const u=L(e,"Null");return u!=null,null}_evalAExpr(e,t){const n=L(e,"kind");let r;typeof n=="number"?r=n:typeof n=="string"?r={AEXPR_OP:0,AEXPR_OP_ANY:1,AEXPR_OP_ALL:2,AEXPR_DISTINCT:3,AEXPR_NOT_DISTINCT:4,AEXPR_NULLIF:5,AEXPR_IN:6,AEXPR_LIKE:7,AEXPR_ILIKE:8,AEXPR_SIMILAR:9,AEXPR_BETWEEN:10,AEXPR_NOT_BETWEEN:11,AEXPR_BETWEEN_SYM:12,AEXPR_NOT_BETWEEN_SYM:13,AEXPR_PAREN:14}[n]??0:r=0;const s=se(L(e,"name"));let o="";for(const h of s){const f=L(h,"String")??L(h,"str");if(f!==null&&typeof f=="object")o=Z(f,"sval")||Z(f,"str");else if(typeof f=="string")o=f;else{const d=Z(h,"sval")||Z(h,"str");d&&(o=d)}}const i=L(e,"lexpr"),a=L(e,"rexpr");if(r===10||r===11){const h=this.evaluate(i,t),f=a,d=L(f,"List"),p=L(d!==null?d:f,"items"),m=se(p??a);if(m.length>=2){const _=this.evaluate(m[0],t),y=this.evaluate(m[1],t);if(h===null||_===null||y===null)return null;const x=h>=_&&h<=y;return r===11?!x:x}return null}if(r===7||r===8){const h=this.evaluate(i,t),f=this.evaluate(a,t);if(h===null||f===null)return null;const p=Et(M(f),r===8).test(M(h));return o==="!~~"||o==="!~~*"?!p:p}if(r===9){const h=this.evaluate(i,t),f=this.evaluate(a,t);if(h===null||f===null)return null;let d=M(f);return d=d.replace(/%/g,".*").replace(/_/g,"."),new RegExp("^"+d+"$").test(M(h))}if(r===12||r===13){const h=this.evaluate(i,t),f=a,d=L(f,"List"),p=L(d!==null?d:f,"items"),m=se(p??a);if(m.length>=2){const _=this.evaluate(m[0],t),y=this.evaluate(m[1],t);if(h===null||_===null||y===null)return null;const x=_<y?_:y,v=_>=y?_:y,E=h>=x&&h<=v;return r===13?!E:E}return null}if(r===1){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null||f===null?null:(Array.isArray(f)?f:[f]).some(p=>this._applyOp(o,h,p)===!0)}if(r===2){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null||f===null?null:(Array.isArray(f)?f:[f]).every(p=>this._applyOp(o,h,p)===!0)}if(r===3){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null&&f===null?!1:h===null||f===null?!0:h!==f}if(r===4){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null&&f===null?!0:h===null||f===null?!1:h===f}if(r===5){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===f?null:h}if(r===6){const h=this.evaluate(i,t);if(h===null)return null;const f=a,d=L(f,"List"),p=se(d!==null?L(d,"items"):a);let m;if(p.length>0)m=p.map(_=>this.evaluate(_,t));else{const _=this.evaluate(f,t);m=Array.isArray(_)?_:[_]}return m.some(_=>_==h)}const l=i!==null?this.evaluate(i,t):null,u=a!==null?this.evaluate(a,t):null;return this._applyOp(o,l,u)}_applyOp(e,t,n){if(e==="+")return t===null||n===null?null:typeof t=="string"||typeof n=="string"?M(t)+M(n):t+n;if(e==="-")return t===null||n===null?null:t-n;if(e==="*")return t===null||n===null?null:t*n;if(e==="/"){if(t===null||n===null)return null;const r=n;if(r===0)throw new Error("Division by zero");return t/r}if(e==="%")return t===null||n===null?null:t%n;if(e==="^")return t===null||n===null?null:Math.pow(t,n);if(e==="=")return t===null||n===null?null:t===n;if(e==="<>"||e==="!=")return t===null||n===null?null:t!==n;if(e==="<")return t===null||n===null?null:t<n;if(e===">")return t===null||n===null?null:t>n;if(e==="<=")return t===null||n===null?null:t<=n;if(e===">=")return t===null||n===null?null:t>=n;if(e==="||")return t===null||n===null?null:M(t)+M(n);if(e==="~~")return t===null||n===null?null:Et(M(n),!1).test(M(t));if(e==="!~~")return t===null||n===null?null:!Et(M(n),!1).test(M(t));if(e==="~~*")return t===null||n===null?null:Et(M(n),!0).test(M(t));if(e==="!~~*")return t===null||n===null?null:!Et(M(n),!0).test(M(t));if(e==="~")return t===null||n===null?null:new RegExp(M(n)).test(M(t));if(e==="~*")return t===null||n===null?null:new RegExp(M(n),"i").test(M(t));if(e==="!~")return t===null||n===null?null:!new RegExp(M(n)).test(M(t));if(e==="!~*")return t===null||n===null?null:!new RegExp(M(n),"i").test(M(t));if(e==="&")return t===null||n===null?null:t&n;if(e==="|")return t===null||n===null?null:t|n;if(e==="#")return t===null||n===null?null:t^n;if(e==="<<")return t===null||n===null?null:t<<n;if(e===">>")return t===null||n===null?null:t>>n;if(e==="->"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;return typeof n=="number"&&Array.isArray(r)?r[n]??null:typeof r=="object"&&r!==null&&!Array.isArray(r)?r[M(n)]??null:null}if(e==="->>"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;if(typeof n=="number"&&Array.isArray(r)){const s=r[n];return s==null?null:typeof s=="object"?JSON.stringify(s):M(s)}if(typeof r=="object"&&r!==null&&!Array.isArray(r)){const s=r[M(n)];return s==null?null:typeof s=="object"?JSON.stringify(s):M(s)}return null}if(e==="#>"){if(t===null||n===null)return null;let r=typeof t=="string"?JSON.parse(t):t;const s=Array.isArray(n)?n:M(n).replace(/^\{/,"").replace(/\}$/,"").split(",").map(o=>o.trim());for(const o of s){if(r==null)return null;if(Array.isArray(r))r=r[Number(o)];else if(typeof r=="object")r=r[M(o)];else return null}return r??null}if(e==="#>>"){if(t===null||n===null)return null;const r=this._applyOp("#>",t,n);return r==null?null:typeof r=="object"?JSON.stringify(r):M(r)}if(e==="@>"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=typeof n=="string"?JSON.parse(n):n;return Bt(r,s)}if(e==="<@"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=typeof n=="string"?JSON.parse(n):n;return Bt(s,r)}if(e==="?"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;return typeof r=="object"&&r!==null&&!Array.isArray(r)?M(n)in r:Array.isArray(r)?r.includes(M(n)):!1}if(e==="?|"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=Array.isArray(n)?n:[M(n)];return typeof r=="object"&&r!==null&&!Array.isArray(r)?s.some(o=>o in r):!1}if(e==="?&"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=Array.isArray(n)?n:[M(n)];return typeof r=="object"&&r!==null&&!Array.isArray(r)?s.every(o=>o in r):!1}if(e==="&&"){if(t===null||n===null)return null;if(Array.isArray(t)&&Array.isArray(n)){const r=new Set(n);return t.some(s=>r.has(s))}return!1}if(e==="@@"){if(t===null||n===null)return!1;const r=String(t).toLowerCase(),s=String(n);return yr(r,s)}throw new Error(`Unsupported operator: "${e}"`)}_evalBoolExpr(e,t){const n=L(e,"boolop"),r=se(L(e,"args"));if(n===0||n==="BOOL_AND"||n==="AND_EXPR"){let s=!0;for(const o of r){const i=this.evaluate(o,t);if(i===!1)return!1;i===null&&(s=null)}return s}if(n===1||n==="BOOL_OR"||n==="OR_EXPR"){let s=!1;for(const o of r){const i=this.evaluate(o,t);if(i===!0)return!0;i===null&&(s=null)}return s}if(n===2||n==="BOOL_NOT"||n==="NOT_EXPR"){const s=this.evaluate(r[0],t);return s===null?null:!s}throw new Error(`Unknown BoolExpr boolop: ${M(n)}`)}_evalFuncCall(e,t){const n=se(L(e,"funcname")),r=[];for(const l of n){const u=L(l,"String")??L(l,"str");if(u!==null&&typeof u=="object"){const h=Z(u,"sval")||Z(u,"str");h&&r.push(h)}else if(typeof u=="string")r.push(u);else{const h=Z(l,"sval")||Z(l,"str");h&&r.push(h)}}let s=r.join(".").toLowerCase();if(s.startsWith("pg_catalog.")&&(s=s.slice(11)),new Set(["count","sum","avg","min","max","string_agg","array_agg","bool_and","bool_or","stddev","stddev_pop","stddev_samp","variance","var_pop","var_samp","corr","covar_pop","covar_samp","regr_slope","regr_intercept","regr_r2","regr_count","regr_avgx","regr_avgy","regr_sxx","regr_syy","regr_sxy"]).has(s)){const l=L(e,"agg_star")===!0,u=se(L(e,"args"));let h;if(l||u.length===0)h=`${s}(*)`;else try{const d=L(u[0],"ColumnRef");if(d){const p=se(L(d,"fields")),m=[];for(const _ of p){const y=Z(_,"sval")||Z(_,"str");y&&m.push(y)}h=`${s}(${m.join(".")})`}else h=s}catch{h=s}if(h in t)return t[h];const f=`__having_agg_${JSON.stringify({FuncCall:e})}`;if(f in t)return t[f]}if(s==="nextval"&&this._sequences!==null){const l=se(L(e,"args")),u=l.length>0?M(this.evaluate(l[0],t)):"",h=this._sequences.get(u);if(h)return h.current+=h.increment,h.current;throw new Error(`Sequence not found: "${u}"`)}if(s==="currval"&&this._sequences!==null){const l=se(L(e,"args")),u=l.length>0?M(this.evaluate(l[0],t)):"",h=this._sequences.get(u);if(h)return h.current;throw new Error(`Sequence not found: "${u}"`)}if(s==="setval"&&this._sequences!==null){const l=se(L(e,"args"));if(l.length<2)throw new Error("setval() requires at least 2 arguments");const u=M(this.evaluate(l[0],t)),h=Number(this.evaluate(l[1],t)),f=this._sequences.get(u);if(f){const d=l.length>=3?!!this.evaluate(l[2],t):!0;return f.current=d?h:h-f.increment,h}throw new Error(`Sequence not found: "${u}"`)}if(s==="lastval"&&this._sequences!==null){let l=null;for(const u of this._sequences.values())(l===null||u.current>l)&&(l=u.current);if(l===null)throw new Error("lastval is not yet defined in this session");return l}if(L(e,"agg_star")===!0)return 1;const i=se(L(e,"args"));if(s==="make_interval"&&i.some(u=>L(u,"NamedArgExpr")!==null&&L(u,"NamedArgExpr")!==void 0)){const u={years:0,months:0,weeks:0,days:0,hours:0,mins:0,secs:0};for(const h of i){const f=L(h,"NamedArgExpr");if(f!=null){const d=f,p=(Z(d,"name")||"").toLowerCase(),m=L(d,"arg"),_=m!==null?Number(this.evaluate(m,t)):0;p in u&&(u[p]=_)}}return In(s,[u.years,u.months,u.weeks,u.days,u.hours,u.mins,u.secs])}const a=i.map(l=>this.evaluate(l,t));return In(s,a)}_evalNullTest(e,t){const n=L(e,"arg"),r=L(e,"nulltesttype"),s=this.evaluate(n,t);return r===0||r==="IS_NULL"?s==null:s!=null}_evalSQLValueFunction(e){const t=L(e,"op"),n=typeof t=="string"?t:"";if(n==="SVFOP_CURRENT_DATE"){const r=new Date,s=String(r.getFullYear()),o=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");return`${s}-${o}-${i}`}if(n==="SVFOP_CURRENT_TIMESTAMP"||n==="SVFOP_CURRENT_TIMESTAMP_N")return new Date().toISOString();if(n==="SVFOP_CURRENT_TIME"||n==="SVFOP_CURRENT_TIME_N"){const r=new Date,s=String(r.getHours()).padStart(2,"0"),o=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${s}:${o}:${i}`}if(n==="SVFOP_LOCALTIME"||n==="SVFOP_LOCALTIME_N"){const r=new Date,s=String(r.getHours()).padStart(2,"0"),o=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${s}:${o}:${i}`}if(n==="SVFOP_LOCALTIMESTAMP"||n==="SVFOP_LOCALTIMESTAMP_N")return new Date().toISOString();if(n==="SVFOP_CURRENT_ROLE"||n==="SVFOP_CURRENT_USER")return"current_user";if(n==="SVFOP_SESSION_USER")return"session_user";if(n==="SVFOP_USER")return"current_user";if(n==="SVFOP_CURRENT_CATALOG")return"uqa";if(n==="SVFOP_CURRENT_SCHEMA")return"public";throw new Error(`Unsupported SQLValueFunction op: ${n}`)}_evalCaseExpr(e,t){const n=L(e,"arg"),r=n!=null?this.evaluate(n,t):null,s=se(L(e,"args"));for(const i of s){const a=L(i,"CaseWhen")??i,l=L(a,"expr"),u=L(a,"result");if(r!==null){const h=this.evaluate(l,t);if(r===h)return this.evaluate(u,t)}else if(this.evaluate(l,t)===!0)return this.evaluate(u,t)}const o=L(e,"defresult");return o!=null?this.evaluate(o,t):null}_evalTypeCast(e,t){const n=L(e,"arg"),r=L(e,"typeName"),s=this.evaluate(n,t),o=r,i=se(L(o,"names"));let a="";for(const l of i){const u=L(l,"String")??L(l,"str");if(u!==null&&typeof u=="object"){const h=Z(u,"sval")||Z(u,"str");h&&h!=="pg_catalog"&&(a=h)}else if(typeof u=="string"&&u!=="pg_catalog")a=u;else{const h=Z(l,"sval")||Z(l,"str");h&&h!=="pg_catalog"&&(a=h)}}return a?to(s,a):s}_evalParamRef(e){const t=L(e,"number"),n=typeof t=="number"?t:0;if(n>0&&n<=this._params.length)return this._params[n-1];if(n>0&&n>this._params.length)throw new Error(`No value supplied for parameter $${String(n)}`);return null}_evalSubLink(e,t){if(this._subqueryExecutor===null)throw new Error("SubLink (subquery) evaluation requires a subqueryExecutor callback");const n=L(e,"subLinkType"),r=L(e,"subselect"),s=L(r,"SelectStmt")??r,o=this._subqueryExecutor(s,t);if(n===0||n==="EXISTS_SUBLINK")return o.rows.length>0;if(n===1||n==="ALL_SUBLINK"){const i=L(e,"testexpr"),a=this.evaluate(i,t),l=this._extractSubLinkOperator(e),u=o.columns[0];for(const h of o.rows){const f=h[u];if(!this._compareValues(a,l,f))return!1}return!0}if(n===2||n==="ANY_SUBLINK"){const i=L(e,"testexpr"),a=this.evaluate(i,t);if(o.columns.length===0)return!1;const l=o.columns[0],u=this._extractSubLinkOperator(e);for(const h of o.rows){const f=h[l];if(this._compareValues(a,u,f))return!0}return!1}if(n===4||n==="EXPR_SUBLINK"){if(o.rows.length===0)return null;const i=o.columns[0];return o.rows[0][i]??null}throw new Error(`Unsupported SubLink type: ${String(n)}`)}_extractSubLinkOperator(e){const t=se(L(e,"operName"));if(t.length>0){const n=t[0],r=L(n,"str");if(r!=null)return String(r);const s=L(L(n,"String")??n,"sval");if(s!=null)return String(s)}return"="}_compareValues(e,t,n){switch(t){case"=":return e==n;case"<>":case"!=":return e!=n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return e===n}}_evalCoalesceExpr(e,t){const n=se(L(e,"args"));for(const r of n){const s=this.evaluate(r,t);if(s!=null)return s}return null}_evalMinMaxExpr(e,t){const n=L(e,"op"),s=se(L(e,"args")).map(o=>this.evaluate(o,t)).filter(o=>o!=null);return s.length===0?null:n===0||n==="IS_GREATEST"?s.reduce((o,i)=>o>i?o:i):s.reduce((o,i)=>o<i?o:i)}_evalBooleanTest(e,t){const n=L(e,"arg"),r=L(e,"booltesttype"),s=this.evaluate(n,t);switch(r){case 0:case"IS_TRUE":return s===!0;case 1:case"IS_NOT_TRUE":return s!==!0;case 2:case"IS_FALSE":return s===!1;case 3:case"IS_NOT_FALSE":return s!==!1;case 4:case"IS_UNKNOWN":return s==null;case 5:case"IS_NOT_UNKNOWN":return s!=null;default:throw new Error(`Unknown BooleanTest type: ${M(r)}`)}}}function Se(c,e,t){return{name:c,typeName:e,pythonType:(t==null?void 0:t.pythonType)??"string",primaryKey:(t==null?void 0:t.primaryKey)??!1,notNull:(t==null?void 0:t.notNull)??!1,autoIncrement:(t==null?void 0:t.autoIncrement)??!1,defaultValue:(t==null?void 0:t.defaultValue)??null,vectorDimensions:(t==null?void 0:t.vectorDimensions)??null,unique:(t==null?void 0:t.unique)??!1,numericPrecision:(t==null?void 0:t.numericPrecision)??null,numericScale:(t==null?void 0:t.numericScale)??null}}const wr=new Map([["INT",["integer","number"]],["INTEGER",["integer","number"]],["SERIAL",["integer","number"]],["BIGINT",["integer","number"]],["BIGSERIAL",["integer","number"]],["SMALLINT",["integer","number"]],["SMALLSERIAL",["integer","number"]],["INT2",["integer","number"]],["INT4",["integer","number"]],["INT8",["integer","number"]],["FLOAT",["float","number"]],["FLOAT4",["float","number"]],["FLOAT8",["float","number"]],["DOUBLE",["float","number"]],["DOUBLE PRECISION",["float","number"]],["REAL",["float","number"]],["NUMERIC",["float","number"]],["DECIMAL",["float","number"]],["TEXT",["text","string"]],["VARCHAR",["text","string"]],["CHAR",["text","string"]],["CHARACTER",["text","string"]],["CHARACTER VARYING",["text","string"]],["NAME",["text","string"]],["BOOLEAN",["boolean","boolean"]],["BOOL",["boolean","boolean"]],["DATE",["date","string"]],["TIME",["time","string"]],["TIMESTAMP",["timestamp","string"]],["TIMESTAMPTZ",["timestamp","string"]],["TIMESTAMP WITH TIME ZONE",["timestamp","string"]],["TIMESTAMP WITHOUT TIME ZONE",["timestamp","string"]],["INTERVAL",["interval","string"]],["VECTOR",["vector","object"]],["POINT",["point","object"]],["JSON",["json","object"]],["JSONB",["json","object"]],["BYTEA",["bytea","object"]],["ARRAY",["array","array"]],["UUID",["text","string"]]]);function xr(c,e){const t=c[c.length-1].toLowerCase();if(t==="vector")return["vector","object"];if(t==="point")return["point","object"];const n=c.map(o=>o.toUpperCase()).join(" "),r=wr.get(n);if(r)return[r[0],r[1]];const s=c[0];if(s!==void 0){const o=wr.get(s.toUpperCase());if(o)return[o[0],o[1]]}return["text","string"]}function no(c){return typeof c=="object"&&c!==null?c:typeof c=="string"?JSON.parse(c):c}function ro(c){return c instanceof Uint8Array?c:typeof c=="string"?new TextEncoder().encode(c):new TextEncoder().encode(String(c))}function so(c){return Array.isArray(c)?c:typeof c=="string"?JSON.parse(c):[c]}function oo(c,e){const t=typeof c=="number"?c:Number(c),n=Math.pow(10,e);return Math.round(t*n)/n}const io=100,ao=10;class Ut{constructor(e,t,n){b(this,"name");b(this,"columns");b(this,"primaryKey");b(this,"checkConstraints");b(this,"foreignKeys");b(this,"fkInsertValidators");b(this,"fkDeleteValidators");b(this,"fkUpdateValidators");b(this,"documentStore");b(this,"invertedIndex");b(this,"vectorIndexes");b(this,"spatialIndexes");b(this,"_stats");b(this,"_nextDocId");b(this,"_uniqueIndexes");b(this,"_uniqueIndexesBuilt");this.name=e,this.columns=new Map,this.checkConstraints=[],this.foreignKeys=[],this.fkInsertValidators=[],this.fkDeleteValidators=[],this.fkUpdateValidators=[],this._stats=new Map,this._nextDocId=1,this.vectorIndexes=new Map,this.spatialIndexes=new Map,this._uniqueIndexes=new Map,this._uniqueIndexesBuilt=!1;let r=null;for(const s of t)this.columns.set(s.name,s),s.primaryKey&&(r=s.name);this.primaryKey=r,this.documentStore=new or,this.invertedIndex=new ir;for(const s of t)s.typeName==="vector"&&s.vectorDimensions!==null&&this.vectorIndexes.set(s.name,new lr(s.vectorDimensions)),s.typeName==="point"&&this.spatialIndexes.set(s.name,new Ps(this.name,s.name))}get columnNames(){return[...this.columns.keys()]}get rowCount(){return this.documentStore.length}insert(e){let t;if(this.primaryKey!==null)if(this.columns.get(this.primaryKey).autoIncrement)(!(this.primaryKey in e)||e[this.primaryKey]===null||e[this.primaryKey]===void 0)&&(e[this.primaryKey]=this._nextDocId),t=e[this.primaryKey],this._nextDocId=Math.max(this._nextDocId,t+1);else{if(!(this.primaryKey in e)||e[this.primaryKey]===null||e[this.primaryKey]===void 0)throw new Error(`Missing primary key '${this.primaryKey}' for table '${this.name}'`);const l=e[this.primaryKey];typeof l=="number"?(t=l,this._nextDocId=Math.max(this._nextDocId,t+1)):(t=this._nextDocId,this._nextDocId++)}else t=this._nextDocId,this._nextDocId++;for(const[a,l]of this.columns)if(l.notNull&&!l.autoIncrement){const u=e[a];if(u==null)if(l.defaultValue!==null&&l.defaultValue!==void 0)e[a]=l.defaultValue;else throw new Error(`NOT NULL constraint violated: column '${a}' in table '${this.name}'`)}this._buildUniqueIndexes();for(const[a,l]of this.columns){if(!(l.unique||l.primaryKey)||l.autoIncrement)continue;const u=e[a];if(u==null)continue;const h=this._uniqueIndexes.get(a);if(h!==void 0&&h.has(u))throw new Error(`UNIQUE constraint violated: duplicate value '${String(u)}' for column '${a}' in table '${this.name}'`)}for(const[a,l]of this.checkConstraints)if(!l(e))throw new Error(`CHECK constraint '${a}' violated in table '${this.name}'`);for(const a of this.fkInsertValidators)a(e);for(const a of Object.keys(e))if(!this.columns.has(a))throw new Error(`Unknown column '${a}' for table '${this.name}'`);const n={},r={},s={};for(const[a,l]of this.columns){const u=e[a];if(u!=null)if(l.vectorDimensions!==null){const h=u instanceof Float64Array?u:new Float64Array(u);n[a]=Array.from(h),r[a]=h}else if(l.typeName==="point"){const h=u;let f,d;if(Array.isArray(h))f=h[0],d=h[1];else if(typeof h=="object"&&"x"in h)f=h.x,d=h.y;else throw new Error(`POINT column '${a}' requires [x, y] (2 elements), got ${JSON.stringify(h)}`);n[a]=[f,d],s[a]=[f,d]}else l.typeName==="json"||l.typeName==="jsonb"?n[a]=no(u):l.typeName.endsWith("[]")?n[a]=so(u):l.typeName==="bytea"?n[a]=ro(u):l.numericScale!==null?n[a]=oo(u,l.numericScale):l.pythonType==="number"?n[a]=Number(u):l.pythonType==="boolean"?n[a]=!!u:l.pythonType==="string"?n[a]=String(u):n[a]=u;else l.defaultValue!==null&&l.defaultValue!==void 0&&(n[a]=l.defaultValue)}this.documentStore.put(t,n);let o=null;const i={};for(const[a,l]of Object.entries(n))typeof l=="string"&&(i[a]=l);Object.keys(i).length>0&&(o=this.invertedIndex.addDocument(t,i));for(const[a,l]of Object.entries(r)){const u=this.vectorIndexes.get(a);u!==void 0&&u.add(t,l)}for(const[a,[l,u]]of Object.entries(s)){const h=this.spatialIndexes.get(a);h!==void 0&&h.add(t,l,u)}for(const[a,l]of this._uniqueIndexes){const u=n[a];u!=null&&l.set(u,t)}return[t,o]}_buildUniqueIndexes(){if(this._uniqueIndexesBuilt)return;this._uniqueIndexesBuilt=!0;const e=[];for(const[t,n]of this.columns)(n.unique||n.primaryKey)&&!n.autoIncrement&&(e.push(t),this._uniqueIndexes.set(t,new Map));if(e.length!==0)for(const t of this.documentStore.docIds)for(const n of e){const r=this.documentStore.getField(t,n);r!=null&&this._uniqueIndexes.get(n).set(r,t)}}removeFromUniqueIndexes(e){for(const[t,n]of this._uniqueIndexes){const r=this.documentStore.getField(e,t);r!=null&&n.delete(r)}}analyze(){const e=[...this.documentStore.docIds].sort((i,a)=>i-a),t=e.length,n=[...this.columns.keys()],r=new Map,s=new Map;for(const i of n)r.set(i,[]),s.set(i,0);for(const i of e){const a=this.documentStore.get(i);for(const l of n){const u=a!==null?a[l]??null:null;u===null?s.set(l,(s.get(l)??0)+1):r.get(l).push(u)}}const o=new Map;for(const i of n){const a=r.get(i),l=s.get(i),u=new Set(a.map(y=>typeof y=="object"?JSON.stringify(y):String(y))).size,h=a.filter(y=>typeof y=="number"||typeof y=="string");let f=null,d=null;h.length>0&&(f=h.reduce((y,x)=>y<x?y:x),d=h.reduce((y,x)=>y>x?y:x));const p=lo(h),[m,_]=co(a,t);o.set(i,{distinctCount:u,nullCount:l,minValue:f,maxValue:d,rowCount:t,histogram:p,mcvValues:m,mcvFrequencies:_})}return this._stats=o,new Map(o)}getColumnStats(e){return this._stats.get(e)??null}}function lo(c){if(c.length===0)return[];try{const e=[...c].sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:String(s).localeCompare(String(o))),t=e.length,n=Math.min(io,t);if(n<=1)return[e[0],e[t-1]];const r=[e[0]];for(let s=1;s<n;s++){const o=Math.floor(s*t/n),i=e[o];i!==r[r.length-1]&&r.push(i)}return r[r.length-1]!==e[t-1]&&r.push(e[t-1]),r}catch{return[]}}function co(c,e){if(c.length===0||e<=0)return[[],[]];const t=new Map;for(const i of c){const a=typeof i=="object"?JSON.stringify(i):String(i),l=t.get(a);l!==void 0?l.count++:t.set(a,{value:i,count:1})}const n=t.size;if(n<=0)return[[],[]];const r=1/n,o=[...t.values()].sort((i,a)=>a.count-i.count).slice(0,ao).filter(i=>i.count/e>r);return o.length===0?[[],[]]:[o.map(i=>i.value),o.map(i=>i.count/e)]}function ne(c){return{subgraphVertices:(c==null?void 0:c.subgraphVertices)??new Set,subgraphEdges:(c==null?void 0:c.subgraphEdges)??new Set,score:(c==null?void 0:c.score)??0,graphName:(c==null?void 0:c.graphName)??""}}class W extends D{constructor(t,n){super(t);b(this,"_graphPayloads");this._graphPayloads=new Map(n??[])}setGraphPayload(t,n){this._graphPayloads.set(t,n)}getGraphPayload(t){return this._graphPayloads.get(t)??null}get graphPayloads(){return this._graphPayloads}toPostingList(){const t=[];for(const n of this){const r=this._graphPayloads.get(n.docId),s={...n.payload.fields};r&&(s._subgraph_vertices=[...r.subgraphVertices],s._subgraph_edges=[...r.subgraphEdges],s._graph_score=r.score,s._graph_name=r.graphName),t.push({docId:n.docId,payload:U({positions:n.payload.positions,score:r?r.score:n.payload.score,fields:s})})}return new D(t)}static fromPostingList(t){const n=[],r=new Map;for(const s of t){n.push(s);const o=s.payload.fields,i=o._subgraph_vertices,a=o._subgraph_edges,l=o._graph_score,u=o._graph_name;(i!==void 0||a!==void 0)&&r.set(s.docId,ne({subgraphVertices:new Set(Array.isArray(i)?i:[]),subgraphEdges:new Set(Array.isArray(a)?a:[]),score:typeof l=="number"?l:s.payload.score,graphName:typeof u=="string"?u:""}))}return new W(n,r)}}function ht(c){return{kind:"literal",value:c}}function Sr(c){return{kind:"identifier",name:c}}function Er(c,e){return{kind:"property_access",object:c,property:e}}function uo(c){return{kind:"parameter",name:c}}function ft(c,e,t){return{kind:"binary_op",op:c,left:e,right:t}}function Ir(c,e){return{kind:"unary_op",op:c,operand:e}}function ho(c,e){return{kind:"function_call",name:c,args:e}}function Nr(c,e,t){return{variable:c,labels:e??[],properties:t??new Map}}function Ar(c){return{variable:(c==null?void 0:c.variable)??null,types:(c==null?void 0:c.types)??[],properties:(c==null?void 0:c.properties)??new Map,direction:(c==null?void 0:c.direction)??"out",minHops:(c==null?void 0:c.minHops)??null,maxHops:(c==null?void 0:c.maxHops)??null}}function fo(c){return{elements:c}}function po(c){return{clauses:c}}var k=(c=>(c.MATCH="MATCH",c.OPTIONAL="OPTIONAL",c.WHERE="WHERE",c.RETURN="RETURN",c.WITH="WITH",c.CREATE="CREATE",c.DELETE="DELETE",c.DETACH="DETACH",c.SET="SET",c.REMOVE="REMOVE",c.MERGE="MERGE",c.ON="ON",c.ORDER="ORDER",c.BY="BY",c.ASC="ASC",c.DESC="DESC",c.SKIP="SKIP",c.LIMIT="LIMIT",c.DISTINCT="DISTINCT",c.AS="AS",c.AND="AND",c.OR="OR",c.XOR="XOR",c.NOT="NOT",c.IN="IN",c.IS="IS",c.NULL="NULL",c.TRUE="TRUE",c.FALSE="FALSE",c.CASE="CASE",c.WHEN="WHEN",c.THEN="THEN",c.ELSE="ELSE",c.END="END",c.EXISTS="EXISTS",c.UNWIND="UNWIND",c.CALL="CALL",c.YIELD="YIELD",c.INTEGER="INTEGER",c.FLOAT="FLOAT",c.STRING="STRING",c.IDENTIFIER="IDENTIFIER",c.PARAMETER="PARAMETER",c.EQ="EQ",c.NEQ="NEQ",c.LT="LT",c.GT="GT",c.LTE="LTE",c.GTE="GTE",c.PLUS="PLUS",c.PLUS_EQ="PLUS_EQ",c.MINUS="MINUS",c.STAR="STAR",c.SLASH="SLASH",c.PERCENT="PERCENT",c.STARTS_WITH="STARTS_WITH",c.ENDS_WITH="ENDS_WITH",c.CONTAINS="CONTAINS",c.LPAREN="LPAREN",c.RPAREN="RPAREN",c.LBRACKET="LBRACKET",c.RBRACKET="RBRACKET",c.LBRACE="LBRACE",c.RBRACE="RBRACE",c.COMMA="COMMA",c.DOT="DOT",c.COLON="COLON",c.PIPE="PIPE",c.DOTDOT="DOTDOT",c.DASH="DASH",c.ARROW_RIGHT="ARROW_RIGHT",c.ARROW_LEFT="ARROW_LEFT",c.EOF="EOF",c))(k||{});const go=new Map([["match","MATCH"],["optional","OPTIONAL"],["where","WHERE"],["return","RETURN"],["with","WITH"],["create","CREATE"],["delete","DELETE"],["detach","DETACH"],["set","SET"],["remove","REMOVE"],["merge","MERGE"],["on","ON"],["order","ORDER"],["by","BY"],["asc","ASC"],["ascending","ASC"],["desc","DESC"],["descending","DESC"],["skip","SKIP"],["limit","LIMIT"],["distinct","DISTINCT"],["as","AS"],["and","AND"],["or","OR"],["xor","XOR"],["not","NOT"],["in","IN"],["is","IS"],["null","NULL"],["true","TRUE"],["false","FALSE"],["case","CASE"],["when","WHEN"],["then","THEN"],["else","ELSE"],["end","END"],["exists","EXISTS"],["unwind","UNWIND"],["call","CALL"],["yield","YIELD"],["starts","STARTS_WITH"],["ends","ENDS_WITH"],["contains","CONTAINS"]]);function mo(c){const e=[];let t=0;for(;t<c.length;){const n=c[t];if(n===" "||n===" "||n===`
1
+ (function($,K){typeof exports=="object"&&typeof module<"u"?K(exports,require("bayesian-bm25"),require("libpg-query")):typeof define=="function"&&define.amd?define(["exports","bayesian-bm25","libpg-query"],K):($=typeof globalThis<"u"?globalThis:$||self,K($.uqa={},$.BayesianBM25,$.libpgQuery))})(this,(function($,K,st){"use strict";var Ai=Object.defineProperty;var ki=($,K,st)=>K in $?Ai($,K,{enumerable:!0,configurable:!0,writable:!0,value:st}):$[K]=st;var b=($,K,st)=>ki($,typeof K!="symbol"?K+"":K,st);function on(c,e){const t=Math.min(c.length,e.length);for(let n=0;n<t;n++){if(c[n]<e[n])return-1;if(c[n]>e[n])return 1}return c.length-e.length}function os(c,e){if(c.length!==e.length)return!1;for(let t=0;t<c.length;t++)if(c[t]!==e[t])return!1;return!0}function Gn(c){return c.join("\0")}class D{constructor(e){b(this,"_entries");b(this,"_docIdsCache",null);if(e&&e.length>0){const t=e.slice().sort((s,o)=>s.docId-o.docId),n=[t[0]],r=new Set([t[0].docId]);for(let s=1;s<t.length;s++){const o=t[s];r.has(o.docId)||(r.add(o.docId),n.push(o))}this._entries=n}else this._entries=[]}static fromSorted(e){const t=Object.create(D.prototype);return t._entries=e,t._docIdsCache=null,t}union(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o];i.docId===a.docId?(r.push({docId:i.docId,payload:D.mergePayloads(i.payload,a.payload)}),s++,o++):i.docId<a.docId?(r.push(i),s++):(r.push(a),o++)}for(;s<t.length;)r.push(t[s]),s++;for(;o<n.length;)r.push(n[o]),o++;return D.fromSorted(r)}intersect(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o];i.docId===a.docId?(r.push({docId:i.docId,payload:D.mergePayloads(i.payload,a.payload)}),s++,o++):i.docId<a.docId?s++:o++}return D.fromSorted(r)}difference(e){const t=e.docIds,n=this._entries.filter(r=>!t.has(r.docId));return D.fromSorted(n)}complement(e){return e.difference(this)}static mergePayloads(e,t){const r=[...new Set([...e.positions,...t.positions])].sort((i,a)=>i-a),s=e.score+t.score,o={...e.fields,...t.fields};return{positions:r,score:s,fields:o}}get docIds(){return this._docIdsCache===null&&(this._docIdsCache=new Set(this._entries.map(e=>e.docId))),this._docIdsCache}get entries(){return this._entries}getEntry(e){let t=0,n=this._entries.length-1;for(;t<=n;){const r=t+n>>>1,s=this._entries[r].docId;if(s===e)return this._entries[r];s<e?t=r+1:n=r-1}return null}topK(e){if(e>=this._entries.length)return D.fromSorted(this._entries.slice());const n=this._entries.slice().sort((r,s)=>s.payload.score-r.payload.score).slice(0,e);return new D(n)}withScores(e){const t=[];for(const n of this._entries){const r=e(n);t.push({docId:n.docId,payload:{positions:n.payload.positions,score:r,fields:n.payload.fields}})}return D.fromSorted(t)}get length(){return this._entries.length}[Symbol.iterator](){return this._entries[Symbol.iterator]()}equals(e){if(this._entries.length!==e._entries.length)return!1;for(let t=0;t<this._entries.length;t++)if(this._entries[t].docId!==e._entries[t].docId)return!1;return!0}toString(){return`PostingList([${this._entries.map(t=>String(t.docId)).join(", ")}])`}and(e){return this.intersect(e)}or(e){return this.union(e)}sub(e){return this.difference(e)}}class Se{constructor(e){b(this,"_entries");this._entries=(e??[]).slice().sort((t,n)=>on(t.docIds,n.docIds))}static fromSorted(e){const t=Object.create(Se.prototype);return t._entries=e,t}get entries(){return this._entries.slice()}get length(){return this._entries.length}[Symbol.iterator](){return this._entries[Symbol.iterator]()}union(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o],l=on(i.docIds,a.docIds);l===0?(r.push(i),s++,o++):l<0?(r.push(i),s++):(r.push(a),o++)}for(;s<t.length;)r.push(t[s]),s++;for(;o<n.length;)r.push(n[o]),o++;return Se.fromSorted(r)}intersect(e){const t=this._entries,n=e._entries,r=[];let s=0,o=0;for(;s<t.length&&o<n.length;){const i=t[s],a=n[o],l=on(i.docIds,a.docIds);l===0?(r.push(i),s++,o++):l<0?s++:o++}return Se.fromSorted(r)}difference(e){const t=e.docIdsSet,n=this._entries.filter(r=>!t.has(Gn(r.docIds)));return Se.fromSorted(n)}complement(e){return e.difference(this)}get docIdsSet(){return new Set(this._entries.map(e=>Gn(e.docIds)))}equals(e){if(this._entries.length!==e._entries.length)return!1;for(let t=0;t<this._entries.length;t++)if(!os(this._entries[t].docIds,e._entries[t].docIds))return!1;return!0}toString(){return`GeneralizedPostingList([${this._entries.map(t=>`(${t.docIds.join(", ")})`).join(", ")}])`}and(e){return this.intersect(e)}or(e){return this.union(e)}sub(e){return this.difference(e)}}function U(c){return{positions:(c==null?void 0:c.positions)??[],score:(c==null?void 0:c.score)??0,fields:(c==null?void 0:c.fields)??{}}}function he(c,e){return{docId:c,payload:U(e)}}function an(c,e,t){return{vertexId:c,label:e,properties:t??{}}}function gt(c,e,t,n,r){return{edgeId:c,sourceId:e,targetId:t,label:n,properties:r??{}}}class Bn{constructor(e=0,t=0,n=0){b(this,"totalDocs");b(this,"avgDocLength");b(this,"dimensions");b(this,"_docFreqs");this.totalDocs=e,this.avgDocLength=t,this.dimensions=n,this._docFreqs=new Map}docFreq(e,t){return this._docFreqs.get(`${e}\0${t}`)??0}setDocFreq(e,t,n){this._docFreqs.set(`${e}\0${t}`,n)}}class me{}class ln extends me{constructor(e){super(),this.target=e}evaluate(e){return e===this.target}}class Un extends me{constructor(e){super(),this.target=e}evaluate(e){return e!==this.target}}class Wn extends me{constructor(e){super(),this.target=e}evaluate(e){return e>this.target}}class Hn extends me{constructor(e){super(),this.target=e}evaluate(e){return e>=this.target}}class Kn extends me{constructor(e){super(),this.target=e}evaluate(e){return e<this.target}}class Jn extends me{constructor(e){super(),this.target=e}evaluate(e){return e<=this.target}}class cn extends me{constructor(t){super();b(this,"_values");this._values=new Set(t)}get values(){return this._values}evaluate(t){return this._values.has(t)}}class un extends me{constructor(e,t){super(),this.low=e,this.high=t}evaluate(e){const t=e;return t>=this.low&&t<=this.high}}class hn extends me{evaluate(e){return e==null}}class fn extends me{evaluate(e){return e!=null}}const mt=new Map;function Yn(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function is(c,e){const t=`${e?"s":"i"}:${c}`,n=mt.get(t);if(n!==void 0)return n;if(mt.size>=256){const i=mt.keys().next().value;mt.delete(i)}let r="^";for(let i=0;i<c.length;i++){const a=c[i];a==="%"?r+=".*":a==="_"?r+=".":a==="\\"&&i+1<c.length?(i++,r+=Yn(c[i])):r+=Yn(a)}r+="$";const s=e?"s":"is",o=new RegExp(r,s);return mt.set(t,o),o}function Dt(c,e,t){return is(e,t).test(c)}class Xn extends me{constructor(e){super(),this.pattern=e}evaluate(e){return Dt(String(e),this.pattern,!0)}}class as extends me{constructor(e){super(),this.pattern=e}evaluate(e){return!Dt(String(e),this.pattern,!0)}}class Qn extends me{constructor(e){super(),this.pattern=e}evaluate(e){return Dt(String(e),this.pattern,!1)}}class ls extends me{constructor(e){super(),this.pattern=e}evaluate(e){return!Dt(String(e),this.pattern,!1)}}function Zn(c){return c instanceof hn||c instanceof fn}class cs{constructor(e,t){b(this,"docId");b(this,"data");this.docId=e,this.data=t}evalPath(e){let t=this.data;for(const n of e){if(t==null)return;if(typeof n=="number"){if(!Array.isArray(t))return;t=t[n]}else if(Array.isArray(t))t=t.map(r=>r[n]);else if(typeof t=="object")t=t[n];else return}return t}}class Lt{static fromDict(e){const t=e.type;switch(t){case"html_strip":return dn._fromDict(e);case"mapping":return pn._fromDict(e);case"pattern_replace":return gn._fromDict(e);default:throw new Error(`Unknown CharFilter type: ${t}`)}}}const us=/<[^>]+>/g,hs={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" "};class dn extends Lt{filter(e){let t=e.replace(us," ");for(const[n,r]of Object.entries(hs))t=t.replaceAll(n,r);return t}toDict(){return{type:"html_strip"}}static _fromDict(e){return new dn}}class pn extends Lt{constructor(t){super();b(this,"_mapping");this._mapping=Object.entries(t).sort((n,r)=>r[0].length-n[0].length)}filter(t){let n=t;for(const[r,s]of this._mapping)n=n.replaceAll(r,s);return n}toDict(){const t={};for(const[n,r]of this._mapping)t[n]=r;return{type:"mapping",mapping:t}}static _fromDict(t){return new pn(t.mapping)}}class gn extends Lt{constructor(t,n=""){super();b(this,"_pattern");b(this,"_replacement");b(this,"_re");this._pattern=t,this._replacement=n,this._re=new RegExp(t,"g")}filter(t){return t.replace(this._re,this._replacement)}toDict(){return{type:"pattern_replace",pattern:this._pattern,replacement:this._replacement}}static _fromDict(t){return new gn(t.pattern,t.replacement??"")}}class Pe{static fromDict(e){const t=e.type;switch(t){case"lowercase":return ot._fromDict(e);case"stop":return _t._fromDict(e);case"porter_stem":return yt._fromDict(e);case"ascii_folding":return it._fromDict(e);case"synonym":return _n._fromDict(e);case"ngram":return jt._fromDict(e);case"edge_ngram":return yn._fromDict(e);case"length":return bn._fromDict(e);default:throw new Error(`Unknown TokenFilter type: ${t}`)}}}class ot extends Pe{filter(e){return e.map(t=>t.toLowerCase())}toDict(){return{type:"lowercase"}}static _fromDict(e){return new ot}}const fs={english:new Set(["a","an","and","are","as","at","be","but","by","can","could","did","do","does","for","had","has","have","he","her","him","his","how","i","if","in","into","is","it","its","may","me","my","no","nor","not","of","on","or","our","own","she","should","so","some","such","than","that","the","their","then","there","these","they","this","to","too","us","very","was","we","were","what","when","which","who","whom","why","will","with","would","you","your"])};class _t extends Pe{constructor(t="english",n){super();b(this,"_language");b(this,"_customWords");b(this,"_words");this._language=t,this._customWords=n??new Set;const r=fs[t]??new Set;this._words=new Set([...r,...this._customWords])}filter(t){return t.filter(n=>!this._words.has(n))}toDict(){const t={type:"stop",language:this._language};return this._customWords.size>0&&(t.custom_words=[...this._customWords].sort()),t}static _fromDict(t){const n=t.custom_words?new Set(t.custom_words):null;return new _t(t.language??"english",n)}}function De(c,e){const t=c[e];return t==="a"||t==="e"||t==="i"||t==="o"||t==="u"?!1:t==="y"?e===0||!De(c,e-1):!0}function He(c,e){let t=0,n=0;for(;n<=e&&De(c,n);)n++;for(;n<=e;){for(;n<=e&&!De(c,n);)n++;for(t++;n<=e&&De(c,n);)n++}return t}function mn(c,e){for(let t=0;t<=e;t++)if(!De(c,t))return!0;return!1}function er(c,e){return e<1?!1:c[e]===c[e-1]&&De(c,e)}function tr(c,e){if(e<2||!De(c,e-2)||De(c,e-1)||!De(c,e))return!1;const t=c[e];return t!=="w"&&t!=="x"&&t!=="y"}function ds(c){if(c.length<=2)return c;let e=c;if(e.endsWith("sses")||e.endsWith("ies")?e=e.slice(0,-2):!e.endsWith("ss")&&e.endsWith("s")&&(e=e.slice(0,-1)),e.endsWith("eed")){const s=e.slice(0,-3);He(e,s.length-1)>0&&(e=e.slice(0,-1))}else{let s=!1,o=0;e.endsWith("ed")?(o=e.length-2,s=mn(e,o-1)):e.endsWith("ing")&&(o=e.length-3,s=mn(e,o-1)),s&&(e=e.slice(0,o),e.endsWith("at")||e.endsWith("bl")||e.endsWith("iz")?e=e+"e":er(e,e.length-1)&&e[e.length-1]!=="l"&&e[e.length-1]!=="s"&&e[e.length-1]!=="z"?e=e.slice(0,-1):He(e,e.length-1)===1&&tr(e,e.length-1)&&(e=e+"e"))}e.endsWith("y")&&mn(e,e.length-2)&&(e=e.slice(0,-1)+"i");const t=[["ational","ate"],["tional","tion"],["enci","ence"],["anci","ance"],["izer","ize"],["abli","able"],["alli","al"],["entli","ent"],["eli","e"],["ousli","ous"],["ization","ize"],["ation","ate"],["ator","ate"],["alism","al"],["iveness","ive"],["fulness","ful"],["ousness","ous"],["aliti","al"],["iviti","ive"],["biliti","ble"]];for(const[s,o]of t)if(e.endsWith(s)){const i=e.slice(0,-s.length);He(e,i.length-1)>0&&(e=i+o);break}const n=[["icate","ic"],["ative",""],["alize","al"],["iciti","ic"],["ical","ic"],["ful",""],["ness",""]];for(const[s,o]of n)if(e.endsWith(s)){const i=e.slice(0,-s.length);He(e,i.length-1)>0&&(e=i+o);break}const r=["al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","ion","ou","ism","ate","iti","ous","ive","ize"];for(const s of r)if(e.endsWith(s)){const o=e.slice(0,-s.length);if(He(e,o.length-1)>1)if(s==="ion"){const i=o[o.length-1];(i==="s"||i==="t")&&(e=o)}else e=o;break}if(e.endsWith("e")){const s=e.slice(0,-1),o=He(e,s.length-1);(o>1||o===1&&!tr(e,s.length-1))&&(e=s)}return He(e,e.length-1)>1&&er(e,e.length-1)&&e[e.length-1]==="l"&&(e=e.slice(0,-1)),e}class yt extends Pe{filter(e){return e.map(t=>ds(t))}toDict(){return{type:"porter_stem"}}static _fromDict(e){return new yt}}function ps(c){for(let e=0;e<c.length;e++)if(c.charCodeAt(e)>127)return!1;return!0}function gs(c){if(c.charCodeAt(0)<=127)return c;const e=c.normalize("NFKD");let t="";for(let n=0;n<e.length;n++)e.charCodeAt(n)<=127&&(t+=e.charAt(n));return t.length>0?t:c}class it extends Pe{filter(e){return e.map(t=>it._fold(t))}static _fold(e){if(ps(e))return e;let t="";for(let n=0;n<e.length;n++)t+=gs(e[n]);return t}toDict(){return{type:"ascii_folding"}}static _fromDict(e){return new it}}class _n extends Pe{constructor(t){super();b(this,"_synonyms");this._synonyms=t}filter(t){const n=[];for(const r of t){n.push(r);const s=this._synonyms[r];s&&n.push(...s)}return n}toDict(){return{type:"synonym",synonyms:this._synonyms}}static _fromDict(t){return new _n(t.synonyms)}}class jt extends Pe{constructor(t=2,n=3,r=!1){super();b(this,"_minGram");b(this,"_maxGram");b(this,"_keepShort");if(t<1)throw new Error("minGram must be >= 1");if(n<t)throw new Error("maxGram must be >= minGram");this._minGram=t,this._maxGram=n,this._keepShort=r}filter(t){const n=[];for(const r of t){if(r.length<this._minGram){this._keepShort&&n.push(r);continue}for(let s=this._minGram;s<=this._maxGram;s++)for(let o=0;o<=r.length-s;o++)n.push(r.substring(o,o+s))}return n}toDict(){const t={type:"ngram",min_gram:this._minGram,max_gram:this._maxGram};return this._keepShort&&(t.keep_short=!0),t}static _fromDict(t){return new jt(t.min_gram,t.max_gram,t.keep_short??!1)}}class yn extends Pe{constructor(t=1,n=20){super();b(this,"_minGram");b(this,"_maxGram");this._minGram=t,this._maxGram=n}filter(t){const n=[];for(const r of t){const s=Math.min(this._maxGram,r.length);for(let o=this._minGram;o<=s;o++)n.push(r.substring(0,o))}return n}toDict(){return{type:"edge_ngram",min_gram:this._minGram,max_gram:this._maxGram}}static _fromDict(t){return new yn(t.min_gram,t.max_gram)}}class bn extends Pe{constructor(t=0,n=0){super();b(this,"_minLength");b(this,"_maxLength");this._minLength=t,this._maxLength=n}filter(t){return t.filter(n=>!(n.length<this._minLength||this._maxLength>0&&n.length>this._maxLength))}toDict(){return{type:"length",min_length:this._minLength,max_length:this._maxLength}}static _fromDict(t){return new bn(t.min_length,t.max_length)}}class Ke{static fromDict(e){const t=e.type;switch(t){case"whitespace":return bt._fromDict(e);case"standard":return vt._fromDict(e);case"letter":return vn._fromDict(e);case"ngram":return wn._fromDict(e);case"pattern":return xn._fromDict(e);case"keyword":return Vt._fromDict(e);default:throw new Error(`Unknown Tokenizer type: ${t}`)}}}class bt extends Ke{tokenize(e){return e.split(/\s+/).filter(t=>t.length>0)}toDict(){return{type:"whitespace"}}static _fromDict(e){return new bt}}const ms=/\w+/gu;class vt extends Ke{tokenize(e){return[...e.matchAll(ms)].map(t=>t[0])}toDict(){return{type:"standard"}}static _fromDict(e){return new vt}}const _s=/[a-zA-Z]+/g;class vn extends Ke{tokenize(e){return[...e.matchAll(_s)].map(t=>t[0])}toDict(){return{type:"letter"}}static _fromDict(e){return new vn}}class wn extends Ke{constructor(t=1,n=2){super();b(this,"_minGram");b(this,"_maxGram");if(t<1)throw new Error("minGram must be >= 1");if(n<t)throw new Error("maxGram must be >= minGram");this._minGram=t,this._maxGram=n}tokenize(t){const n=t.split(/\s+/).filter(s=>s.length>0),r=[];for(const s of n)for(let o=this._minGram;o<=this._maxGram;o++)for(let i=0;i<=s.length-o;i++)r.push(s.substring(i,i+o));return r}toDict(){return{type:"ngram",min_gram:this._minGram,max_gram:this._maxGram}}static _fromDict(t){return new wn(t.min_gram,t.max_gram)}}class xn extends Ke{constructor(t="\\W+"){super();b(this,"_pattern");b(this,"_re");this._pattern=t,this._re=new RegExp(t)}tokenize(t){return t.split(this._re).filter(n=>n.length>0)}toDict(){return{type:"pattern",pattern:this._pattern}}static _fromDict(t){return new xn(t.pattern)}}class Vt extends Ke{tokenize(e){return e.length>0?[e]:[]}toDict(){return{type:"keyword"}}static _fromDict(e){return new Vt}}class Le{constructor(e,t,n){b(this,"_tokenizer");b(this,"_tokenFilters");b(this,"_charFilters");this._tokenizer=e??new bt,this._tokenFilters=t??[],this._charFilters=n??[]}get tokenizer(){return this._tokenizer}get tokenFilters(){return this._tokenFilters}get charFilters(){return this._charFilters}analyze(e){let t=e;for(const r of this._charFilters)t=r.filter(t);let n=this._tokenizer.tokenize(t);for(const r of this._tokenFilters)n=r.filter(n);return n}toDict(){return{tokenizer:this._tokenizer.toDict(),token_filters:this._tokenFilters.map(e=>e.toDict()),char_filters:this._charFilters.map(e=>e.toDict())}}toJSON(){return JSON.stringify(this.toDict())}static fromDict(e){const t=Ke.fromDict(e.tokenizer),n=e.token_filters.map(s=>Pe.fromDict(s)),r=e.char_filters?e.char_filters.map(s=>Lt.fromDict(s)):[];return new Le(t,n,r)}static fromJSON(e){return Le.fromDict(JSON.parse(e))}}function nr(){return new Le(new bt,[new ot])}function Sn(c="english"){return new Le(new vt,[new ot,new it,new _t(c),new yt])}function ys(c="english"){return new Le(new vt,[new ot,new it,new _t(c),new yt,new jt(2,3,!0)])}function rr(){return new Le(new Vt,[])}const sr=Sn(),$t={whitespace:nr(),standard:Sn(),standard_cjk:ys(),keyword:rr()},wt=new Map;function bs(c,e){if(c in $t)throw new Error(`Cannot override built-in analyzer: ${c}`);wt.set(c,e)}function vs(c){const e=wt.get(c);if(e)return e;const t=$t[c];if(t)return t;throw new Error(`Unknown analyzer: ${c}`)}function ws(c){if(c in $t)throw new Error(`Cannot drop built-in analyzer: ${c}`);if(!wt.has(c))throw new Error(`Analyzer not found: ${c}`);wt.delete(c)}function xs(){return[...Object.keys($t),...wt.keys()].sort()}class Ss{*iterAll(){const e=[...this.docIds].sort((t,n)=>t-n);for(const t of e){const n=this.get(t);n!==null&&(yield[t,n])}}}function Es(c,e){let t=c;for(const n of e){if(t==null)return;if(typeof n=="number"){if(!Array.isArray(t))return;t=t[n]}else if(Array.isArray(t))t=t.map(r=>r[n]);else if(typeof t=="object")t=t[n];else return}return t}class or extends Ss{constructor(){super();b(this,"_documents");this._documents=new Map}put(t,n){this._documents.set(t,n)}get(t){return this._documents.get(t)??null}delete(t){this._documents.delete(t)}clear(){this._documents.clear()}getField(t,n){const r=this._documents.get(t);if(r!==void 0)return r[n]}getFieldsBulk(t,n){const r=new Map;for(const s of t){const o=this._documents.get(s);r.set(s,o!==void 0?o[n]:void 0)}return r}hasValue(t,n){for(const r of this._documents.values())if(r[t]===n)return!0;return!1}evalPath(t,n){const r=this._documents.get(t);if(r!==void 0)return Es(r,n)}get docIds(){return new Set(this._documents.keys())}get length(){return this._documents.size}maxDocId(){let t=-1;for(const n of this._documents.keys())n>t&&(t=n);return t}putBulk(t){for(const[n,r]of t)this._documents.set(n,r)}deleteBulk(t){for(const n of t)this._documents.delete(n)}}class Is{}const Ns={analyze(c){return c.toLowerCase().split(/\s+/).filter(e=>e.length>0)}};class ir extends Is{constructor(t,n){super();b(this,"_analyzer");b(this,"_indexFieldAnalyzers");b(this,"_searchFieldAnalyzers");b(this,"_index");b(this,"_docTerms");b(this,"_docLengths");b(this,"_docCount");b(this,"_totalLength");b(this,"_cachedStats");b(this,"_termToKeys");if(this._analyzer=t??Ns,this._indexFieldAnalyzers=new Map,this._searchFieldAnalyzers=new Map,n)for(const[r,s]of Object.entries(n))this._indexFieldAnalyzers.set(r,s);this._index=new Map,this._docTerms=new Map,this._docLengths=new Map,this._docCount=0,this._totalLength=new Map,this._cachedStats=null,this._termToKeys=new Map}_key(t,n){return`${t}\0${n}`}_parseKey(t){const n=t.indexOf("\0");return[t.substring(0,n),t.substring(n+1)]}get analyzer(){return this._analyzer}get fieldAnalyzers(){const t={};for(const[n,r]of this._indexFieldAnalyzers)t[n]=r;return t}setFieldAnalyzer(t,n,r="both"){(r==="index"||r==="both")&&this._indexFieldAnalyzers.set(t,n),(r==="search"||r==="both")&&this._searchFieldAnalyzers.set(t,n)}getFieldAnalyzer(t){return this._indexFieldAnalyzers.get(t)??this._analyzer}getSearchAnalyzer(t){return this._searchFieldAnalyzers.get(t)??this._indexFieldAnalyzers.get(t)??this._analyzer}addDocument(t,n){this._cachedStats=null,this._docCount++,this._docLengths.set(t,new Map);let r=this._docTerms.get(t);r||(r=new Set,this._docTerms.set(t,r));const s={},o=new Map;for(const[i,a]of Object.entries(n)){const u=this.getFieldAnalyzer(i).analyze(a);this._docLengths.get(t).set(i,u.length),s[i]=u.length;const f=this._totalLength.get(i)??0;this._totalLength.set(i,f+u.length);const d=new Map;for(let p=0;p<u.length;p++){const m=u[p];let _=d.get(m);_||(_=[],d.set(m,_)),_.push(p)}for(const[p,m]of d){const _=this._key(i,p);let y=this._index.get(_);if(!y){y=new Map,this._index.set(_,y);let v=this._termToKeys.get(p);v||(v=[],this._termToKeys.set(p,v)),v.push(_)}const x={docId:t,payload:U({positions:m,score:0})};y.set(t,x),r.add(_),o.set(_,m)}}return{fieldLengths:s,postings:o}}addPosting(t,n,r){this._cachedStats=null;const s=this._key(t,n);let o=this._index.get(s);if(!o){o=new Map,this._index.set(s,o);let a=this._termToKeys.get(n);a||(a=[],this._termToKeys.set(n,a)),a.push(s)}o.set(r.docId,r);let i=this._docTerms.get(r.docId);i||(i=new Set,this._docTerms.set(r.docId,i)),i.add(s)}setDocLength(t,n){const r=new Map;for(const[s,o]of Object.entries(n))r.set(s,o);this._docLengths.set(t,r)}setDocCount(t){this._cachedStats=null,this._docCount=t}addTotalLength(t,n){this._cachedStats=null;const r=this._totalLength.get(t)??0;this._totalLength.set(t,r+n)}removeDocument(t){this._cachedStats=null;const n=this._docTerms.get(t);if(!n)return;for(const s of n){const o=this._index.get(s);if(o&&(o.delete(t),o.size===0)){this._index.delete(s);const[,i]=this._parseKey(s),a=this._termToKeys.get(i);if(a){const l=a.indexOf(s);l!==-1&&a.splice(l,1),a.length===0&&this._termToKeys.delete(i)}}}this._docTerms.delete(t);const r=this._docLengths.get(t);if(r){for(const[s,o]of r){const i=this._totalLength.get(s)??0;this._totalLength.set(s,i-o)}this._docLengths.delete(t),this._docCount--}}clear(){this._index.clear(),this._docTerms.clear(),this._docLengths.clear(),this._termToKeys.clear(),this._cachedStats=null,this._docCount=0,this._totalLength.clear()}getPostingList(t,n){const r=this._index.get(this._key(t,n));if(!r)return new D;const s=[...r.values()].sort((o,i)=>o.docId-i.docId);return D.fromSorted(s)}getPostingListAnyField(t){const n=this._termToKeys.get(t);if(!n||n.length===0)return new D;const r=new Set,s=[];for(const o of n){const i=this._index.get(o);if(i)for(const[a,l]of i)r.has(a)||(r.add(a),s.push(l))}return s.sort((o,i)=>o.docId-i.docId),D.fromSorted(s)}docFreq(t,n){const r=this._index.get(this._key(t,n));return r?r.size:0}docFreqAnyField(t){const n=this._termToKeys.get(t);if(!n||n.length===0)return 0;const r=new Set;for(const s of n){const o=this._index.get(s);if(o)for(const i of o.keys())r.add(i)}return r.size}getDocLength(t,n){const r=this._docLengths.get(t);return r?r.get(n)??0:0}getDocLengthsBulk(t,n){const r=new Map;for(const s of t)r.set(s,this.getDocLength(s,n));return r}getTotalDocLength(t){const n=this._docLengths.get(t);if(!n)return 0;let r=0;for(const s of n.values())r+=s;return r}getTermFreq(t,n,r){const s=this._index.get(this._key(n,r));if(!s)return 0;const o=s.get(t);return o?o.payload.positions.length:0}getTermFreqsBulk(t,n,r){const s=this._index.get(this._key(n,r)),o=new Map;for(const i of t)if(s){const a=s.get(i);o.set(i,a?a.payload.positions.length:0)}else o.set(i,0);return o}getTotalTermFreq(t,n){const r=this._termToKeys.get(n);if(!r)return 0;let s=0;for(const o of r){const i=this._index.get(o);if(i){const a=i.get(t);a&&(s+=a.payload.positions.length)}}return s}addDocuments(t){for(const[n,r]of t)this.addDocument(n,r)}removeDocuments(t){for(const n of t)this.removeDocument(n)}*terms(t){const n=this._key(t,"");for(const r of this._index.keys())if(r.startsWith(n)){const[,s]=this._parseKey(r);yield s}}*allTerms(){for(const t of this._index.keys())yield this._parseKey(t)}*fieldNames(){const t=new Set;for(const n of this._index.keys()){const[r]=this._parseKey(n);t.has(r)||(t.add(r),yield r)}}hasTerm(t,n){return this._index.has(this._key(t,n))}hasDoc(t){return this._docTerms.has(t)}avgDocLength(t){return this._docCount===0?0:(this._totalLength.get(t)??0)/this._docCount}totalDocCount(){return this._docCount}totalFieldLength(t){return this._totalLength.get(t)??0}getPositions(t,n,r){const s=this._index.get(this._key(n,r));if(!s)return[];const o=s.get(t);return o?o.payload.positions:[]}get stats(){if(this._cachedStats!==null)return this._cachedStats;let t=0;for(const s of this._totalLength.values())t+=s;const n=this._docCount>0?t/this._docCount:0,r=new Bn(this._docCount,n);for(const[s,o]of this._index){const[i,a]=this._parseKey(s);r.setDocFreq(i,a,o.size)}return this._cachedStats=r,r}}function ar(c,e){if(c.length!==e.length)throw new Error(`dot: length mismatch (${String(c.length)} vs ${String(e.length)})`);let t=0;for(let n=0;n<c.length;n++)t+=c[n]*e[n];return t}function at(c){return Math.sqrt(ar(c,c))}function lt(c,e){const t=at(c),n=at(e);return t===0||n===0?0:ar(c,e)/(t*n)}function As(c){if(c.length===0)return new Float64Array(0);let e=c[0];for(let r=1;r<c.length;r++)c[r]>e&&(e=c[r]);const t=new Float64Array(c.length);let n=0;for(let r=0;r<c.length;r++)t[r]=Math.exp(c[r]-e),n+=t[r];for(let r=0;r<t.length;r++)t[r]=t[r]/n;return t}function ks(c,e,t,n){const[r,s]=e,[o,i]=n;if(s!==o)throw new Error(`matmul: inner dimension mismatch (${String(s)} vs ${String(o)})`);if(c.length!==r*s)throw new Error(`matmul: array a length (${String(c.length)}) does not match shape [${String(r)}, ${String(s)}]`);if(t.length!==o*i)throw new Error(`matmul: array b length (${String(t.length)}) does not match shape [${String(o)}, ${String(i)}]`);const a=new Float64Array(r*i);for(let l=0;l<r;l++)for(let u=0;u<s;u++){const h=c[l*s+u];for(let f=0;f<i;f++)a[l*i+f]=a[l*i+f]+h*t[u*i+f]}return{data:a,shape:[r,i]}}function Ms(c,e,t){if(c.length!==e*t)throw new Error(`transpose: array length (${String(c.length)}) does not match shape [${String(e)}, ${String(t)}]`);const n=new Float64Array(c.length);for(let r=0;r<e;r++)for(let s=0;s<t;s++)n[s*e+r]=c[r*t+s];return n}class Os{}class lr extends Os{constructor(t){super();b(this,"dimensions");b(this,"_vectors");this.dimensions=t,this._vectors=new Map}add(t,n){if(n.length!==this.dimensions)throw new Error(`Vector dimension mismatch: expected ${String(this.dimensions)}, got ${String(n.length)}`);this._vectors.set(t,n)}delete(t){this._vectors.delete(t)}clear(){this._vectors.clear()}searchKnn(t,n){if(this._vectors.size===0)return new D;const r=[];for(const[i,a]of this._vectors){const l=lt(t,a);r.push({docId:i,score:l})}r.sort((i,a)=>a.score-i.score);const o=r.slice(0,n).map(i=>({docId:i.docId,payload:U({score:i.score})}));return new D(o)}searchThreshold(t,n){const r=[];for(const[s,o]of this._vectors){const i=lt(t,o);i>=n&&r.push({docId:s,payload:U({score:i})})}return new D(r)}count(){return this._vectors.size}}class Cs{}class Ts{constructor(){b(this,"vertexIds",new Set);b(this,"edgeIds",new Set);b(this,"adjOut",new Map);b(this,"adjIn",new Map);b(this,"labelIndex",new Map);b(this,"vertexLabelIndex",new Map)}addVertex(e,t){this.vertexIds.add(e),this.adjOut.has(e)||this.adjOut.set(e,new Set),this.adjIn.has(e)||this.adjIn.set(e,new Set);let n=this.vertexLabelIndex.get(t);n||(n=new Set,this.vertexLabelIndex.set(t,n)),n.add(e)}removeVertex(e,t){this.vertexIds.delete(e),this.adjOut.delete(e),this.adjIn.delete(e);for(const[,r]of this.adjOut)r.delete(e);for(const[,r]of this.adjIn)r.delete(e);const n=this.vertexLabelIndex.get(t);n&&(n.delete(e),n.size===0&&this.vertexLabelIndex.delete(t))}addEdge(e,t,n,r){this.edgeIds.add(e);let s=this.adjOut.get(t);s||(s=new Set,this.adjOut.set(t,s)),s.add(e);let o=this.adjIn.get(n);o||(o=new Set,this.adjIn.set(n,o)),o.add(e);let i=this.labelIndex.get(r);i||(i=new Set,this.labelIndex.set(r,i)),i.add(e)}removeEdge(e,t,n,r){this.edgeIds.delete(e);const s=this.adjOut.get(t);s&&s.delete(e);const o=this.adjIn.get(n);o&&o.delete(e);const i=this.labelIndex.get(r);i&&(i.delete(e),i.size===0&&this.labelIndex.delete(r))}neighbors(e,t,n,r){const s=[];if(r==="out"){const o=this.adjOut.get(e);if(o)for(const i of o){const a=t.get(i);a&&(n===null||a.label===n)&&s.push(a.targetId)}}else{const o=this.adjIn.get(e);if(o)for(const i of o){const a=t.get(i);a&&(n===null||a.label===n)&&s.push(a.sourceId)}}return s}verticesByLabel(e){return this.vertexLabelIndex.get(e)??new Set}}class cr extends Cs{constructor(){super(...arguments);b(this,"_vertices",new Map);b(this,"_edges",new Map);b(this,"_graphs",new Map);b(this,"_vertexMembership",new Map);b(this,"_edgeMembership",new Map);b(this,"_nextVertexId",0);b(this,"_nextEdgeId",0)}createGraph(t){this._graphs.has(t)||this._graphs.set(t,new Ts)}dropGraph(t){const n=this._graphs.get(t);if(n){for(const r of n.vertexIds){const s=this._vertexMembership.get(r);s&&(s.delete(t),s.size===0&&this._vertexMembership.delete(r))}for(const r of n.edgeIds){const s=this._edgeMembership.get(r);s&&(s.delete(t),s.size===0&&this._edgeMembership.delete(r))}this._graphs.delete(t)}}graphNames(){return[...this._graphs.keys()]}hasGraph(t){return this._graphs.has(t)}unionGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(s){for(const i of s.vertexIds){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of s.edgeIds){const a=this._edges.get(i);a&&this.addEdge(a,r)}}if(o){for(const i of o.vertexIds){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of o.edgeIds){const a=this._edges.get(i);a&&this.addEdge(a,r)}}}intersectGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(!(!s||!o)){for(const i of s.vertexIds)if(o.vertexIds.has(i)){const a=this._vertices.get(i);a&&this.addVertex(a,r)}for(const i of s.edgeIds)if(o.edgeIds.has(i)){const a=this._edges.get(i);a&&this.addEdge(a,r)}}}differenceGraphs(t,n,r){this.createGraph(r);const s=this._graphs.get(t),o=this._graphs.get(n);if(!s)return;const i=o?o.vertexIds:new Set,a=o?o.edgeIds:new Set;for(const l of s.vertexIds)if(!i.has(l)){const u=this._vertices.get(l);u&&this.addVertex(u,r)}for(const l of s.edgeIds)if(!a.has(l)){const u=this._edges.get(l);u&&this.addEdge(u,r)}}copyGraph(t,n){this.createGraph(n);const r=this._graphs.get(t);if(r){for(const s of r.vertexIds){const o=this._vertices.get(s);o&&this.addVertex(o,n)}for(const s of r.edgeIds){const o=this._edges.get(s);o&&this.addEdge(o,n)}}}addVertex(t,n){this._vertices.set(t.vertexId,t),t.vertexId>=this._nextVertexId&&(this._nextVertexId=t.vertexId+1);const r=this._graphs.get(n);r&&r.addVertex(t.vertexId,t.label);let s=this._vertexMembership.get(t.vertexId);s||(s=new Set,this._vertexMembership.set(t.vertexId,s)),s.add(n)}addEdge(t,n){this._edges.set(t.edgeId,t),t.edgeId>=this._nextEdgeId&&(this._nextEdgeId=t.edgeId+1);const r=this._graphs.get(n);r&&r.addEdge(t.edgeId,t.sourceId,t.targetId,t.label);let s=this._edgeMembership.get(t.edgeId);s||(s=new Set,this._edgeMembership.set(t.edgeId,s)),s.add(n)}removeVertex(t,n){const r=this._vertices.get(t);if(!r)return;const s=this._graphs.get(n);if(s){const i=[],a=s.adjOut.get(t);if(a)for(const u of a)i.push(u);const l=s.adjIn.get(t);if(l)for(const u of l)i.push(u);for(const u of i)this.removeEdge(u,n);s.removeVertex(t,r.label)}const o=this._vertexMembership.get(t);o&&(o.delete(n),o.size===0&&(this._vertexMembership.delete(t),this._vertices.delete(t)))}removeEdge(t,n){const r=this._edges.get(t);if(!r)return;const s=this._graphs.get(n);s&&s.removeEdge(t,r.sourceId,r.targetId,r.label);const o=this._edgeMembership.get(t);o&&(o.delete(n),o.size===0&&(this._edgeMembership.delete(t),this._edges.delete(t)))}neighbors(t,n,r,s){const o=this._graphs.get(n);return o?o.neighbors(t,this._edges,r??null,s??"out"):[]}verticesByLabel(t,n){const r=this._graphs.get(n);if(!r)return[];const s=r.verticesByLabel(t),o=[];for(const i of s){const a=this._vertices.get(i);a&&o.push(a)}return o}verticesInGraph(t){const n=this._graphs.get(t);if(!n)return[];const r=[];for(const s of n.vertexIds){const o=this._vertices.get(s);o&&r.push(o)}return r}edgesInGraph(t){const n=this._graphs.get(t);if(!n)return[];const r=[];for(const s of n.edgeIds){const o=this._edges.get(s);o&&r.push(o)}return r}vertexGraphs(t){return this._vertexMembership.get(t)??new Set}outEdgeIds(t,n){const r=this._graphs.get(n);return r?r.adjOut.get(t)??new Set:new Set}inEdgeIds(t,n){const r=this._graphs.get(n);return r?r.adjIn.get(t)??new Set:new Set}edgeIdsByLabel(t,n){const r=this._graphs.get(n);return r?r.labelIndex.get(t)??new Set:new Set}vertexIdsInGraph(t){const n=this._graphs.get(t);return n?new Set(n.vertexIds):new Set}degreeDistribution(t){const n=this._graphs.get(t);if(!n)return new Map;const r=new Map;for(const s of n.vertexIds){const o=n.adjOut.get(s),i=n.adjIn.get(s),a=(o?o.size:0)+(i?i.size:0);r.set(a,(r.get(a)??0)+1)}return r}labelDegree(t,n){const r=this._graphs.get(n);if(!r)return 0;const s=r.labelIndex.get(t);return s?s.size:0}vertexLabelCounts(t){const n=this._graphs.get(t);if(!n)return new Map;const r=new Map;for(const[s,o]of n.vertexLabelIndex)r.set(s,o.size);return r}getVertex(t){return this._vertices.get(t)??null}getEdge(t){return this._edges.get(t)??null}nextVertexId(){return this._nextVertexId++}nextEdgeId(){return this._nextEdgeId++}clear(){this._vertices.clear(),this._edges.clear(),this._graphs.clear(),this._vertexMembership.clear(),this._edgeMembership.clear(),this._nextVertexId=0,this._nextEdgeId=0}get vertices(){return this._vertices}get edges(){return this._edges}get vertexCount(){return this._vertices.size}get edgeCount(){return this._edges.size}addVertices(t,n){for(const r of t)this.addVertex(r,n)}addEdges(t,n){for(const r of t)this.addEdge(r,n)}vertexProperty(t,n){const r=this._vertices.get(t);if(r!==void 0)return r.properties[n]}setVertexProperty(t,n,r){const s=this._vertices.get(t);if(s===void 0)throw new Error(`Vertex ${String(t)} not found`);s.properties[n]=r}edgeProperty(t,n){const r=this._edges.get(t);if(r!==void 0)return r.properties[n]}setEdgeProperty(t,n,r){const s=this._edges.get(t);if(s===void 0)throw new Error(`Edge ${String(t)} not found`);s.properties[n]=r}edgesByLabel(t,n){const r=[];if(!this._graphs.get(n))return r;for(const[o,i]of this._edges)if(i.label===t){const a=this._edgeMembership.get(o);a&&a.has(n)&&r.push(i)}return r}vertexLabels(t){const n=new Set;for(const r of this.verticesInGraph(t))r.label&&n.add(r.label);return n}edgeLabels(t){const n=new Set;for(const r of this.edgesInGraph(t))n.add(r.label);return n}outDegree(t,n){return this.outEdgeIds(t,n).size}inDegree(t,n){return this.inEdgeIds(t,n).size}edgesBetween(t,n,r,s){const o=[],i=this.outEdgeIds(t,r);for(const a of i){const l=this._edges.get(a);l&&l.targetId===n&&(s==null||l.label===s)&&o.push(l)}return o}subgraph(t,n,r){this._graphs.has(r)||this.createGraph(r);for(const s of t){const o=this._vertices.get(s);o&&this.addVertex(o,r)}for(const[s,o]of this._edges){const i=this._edgeMembership.get(s);i&&i.has(n)&&t.has(o.sourceId)&&t.has(o.targetId)&&this.addEdge(o,r)}}minTimestamp(t){let n=null;for(const r of this.edgesInGraph(t)){const s=r.properties.timestamp;typeof s=="number"&&(n===null||s<n)&&(n=s)}return n}maxTimestamp(t){let n=null;for(const r of this.edgesInGraph(t)){const s=r.properties.timestamp;typeof s=="number"&&(n===null||s>n)&&(n=s)}return n}edgesInTimeRange(t,n,r){const s=[];for(const o of this.edgesInGraph(t)){const i=o.properties.timestamp;typeof i=="number"&&i>=n&&i<=r&&s.push(o)}return s}}function qt(c){return{k1:(c==null?void 0:c.k1)??1.2,b:(c==null?void 0:c.b)??.75,boost:(c==null?void 0:c.boost)??1}}class xt{constructor(e,t){b(this,"_params");b(this,"_totalDocs");b(this,"_avgDocLength");this._params=e,this._totalDocs=t.totalDocs,this._avgDocLength=t.avgDocLength}get params(){return this._params}idf(e){const t=this._totalDocs;return Math.log((t-e+.5)/(e+.5)+1)}score(e,t,n){return this.scoreWithIdf(e,t,this.idf(n))}scoreWithIdf(e,t,n){const{k1:r,b:s,boost:o}=this._params,i=o*n,a=this._avgDocLength>0?this._avgDocLength:1,l=1/(r*(1-s+s*t/a));return i-i/(1+e*l)}combineScores(e){let t=0;for(const n of e)t+=n;return t}upperBound(e){return this._params.boost*this.idf(e)}}function Je(c){return{bm25:(c==null?void 0:c.bm25)??qt(),alpha:(c==null?void 0:c.alpha)??1,beta:(c==null?void 0:c.beta)??0,baseRate:(c==null?void 0:c.baseRate)??.5}}class ct{constructor(e,t){b(this,"_bm25");b(this,"_transform");this._bm25=new xt(e.bm25,t),this._transform=new K.BayesianProbabilityTransform(e.alpha,e.beta,e.baseRate===.5?null:e.baseRate)}get bm25(){return this._bm25}idf(e){return this._bm25.idf(e)}score(e,t,n){return this.scoreWithIdf(e,t,this._bm25.idf(n))}scoreWithIdf(e,t,n){const r=this._bm25.scoreWithIdf(e,t,n),s=this._bm25.params.k1>0?t:1,o=s>0?t/s:1;return this._transform.scoreToProbability(r,e,o)}combineScores(e){return e.length===0?.5:e.length===1?e[0]:K.logOddsConjunction(e,0)}upperBound(e){const t=this._bm25.upperBound(e);return this._transform.wandUpperBound(t)}}class q{compose(e){return new Ye([this,e])}costEstimate(e){return e.totalDocs}}class Ye extends q{constructor(t){super();b(this,"operators");this.operators=t}execute(t){let n=null;for(const r of this.operators)n=r.execute(t);return n===null?new D:n}costEstimate(t){let n=0;for(const r of this.operators)n+=r.costEstimate(t);return n}}const ur=6371e3,Rs=111320;function St(c){return c*Math.PI/180}function Fs(c){return c*180/Math.PI}function hr(c,e,t,n){const r=St(c),s=St(t),o=St(t-c),i=St(n-e),a=Math.sin(o/2)**2+Math.cos(r)*Math.cos(s)*Math.sin(i/2)**2;return 2*ur*Math.asin(Math.sqrt(a))}class Ps{constructor(e,t){b(this,"_tableName");b(this,"_fieldName");b(this,"_points");this._tableName=e,this._fieldName=t,this._points=new Map}get tableName(){return this._tableName}get fieldName(){return this._fieldName}add(e,t,n){this._points.set(e,{x:t,y:n})}delete(e){this._points.delete(e)}clear(){this._points.clear()}searchWithin(e,t,n){if(n<=0)return new D;const r=n/Rs,s=n/ur,o=Math.cos(St(t));let i;if(o<1e-10||s>=Math.PI)i=180;else{const d=Math.sin(s)/o;d>=1?i=180:i=Fs(Math.asin(d))}const a=e-i,l=e+i,u=t-r,h=t+r,f=[];for(const[d,p]of this._points){if(p.x<a||p.x>l||p.y<u||p.y>h)continue;const m=hr(t,e,p.y,p.x);if(m<=n){const _=1-m/n;f.push({docId:d,payload:U({score:_})})}}return f.sort((d,p)=>d.docId-p.docId),D.fromSorted(f)}count(){return this._points.size}close(){this._points.clear()}}function Ds(c,e,t,n){const r=c.documentStore;if(!r)return new D;if(at(t)===0)return new D;const o=[];for(const a of r.docIds){const l=r.getField(a,e);if(!l||!(l instanceof Float64Array)||at(l)===0)continue;const h=lt(t,l);o.push({docId:a,score:h})}o.sort((a,l)=>l.score-a.score);const i=o.slice(0,n);return new D(i.map(a=>({docId:a.docId,payload:U({score:a.score})})))}function Ls(c,e,t,n){const r=c.documentStore;if(!r)return new D;if(at(t)===0)return new D;const o=[];for(const i of r.docIds){const a=r.getField(i,e);if(!a||!(a instanceof Float64Array)||at(a)===0)continue;const u=lt(t,a);u>=n&&o.push({docId:i,payload:U({score:u})})}return new D(o)}class _e extends q{constructor(t,n){super();b(this,"term");b(this,"field");this.term=t,this.field=n??null}execute(t){const n=t.invertedIndex;if(!n)return new D;const s=(this.field?n.getSearchAnalyzer(this.field):n.analyzer).analyze(this.term);if(s.length===0)return new D;const o=s.map(a=>this.field?n.getPostingList(this.field,a):n.getPostingListAnyField(a));let i=o[0];for(let a=1;a<o.length;a++)i=i.union(o[a]);return i}costEstimate(t){return this.field?t.docFreq(this.field,this.term):t.totalDocs}}class Ee extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"threshold");b(this,"field");this.queryVector=t,this.threshold=n,this.field=r}execute(t){var r;const n=(r=t.vectorIndexes)==null?void 0:r[this.field];return n?n.searchThreshold(this.queryVector,this.threshold):Ls(t,this.field,this.queryVector,this.threshold)}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}class je extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"k");b(this,"field");this.queryVector=t,this.k=n,this.field=r}execute(t){var r;const n=(r=t.vectorIndexes)==null?void 0:r[this.field];return n?n.searchKnn(this.queryVector,this.k):Ds(t,this.field,this.queryVector,this.k)}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}class js extends q{constructor(t,n,r,s){super();b(this,"field");b(this,"centerX");b(this,"centerY");b(this,"distance");this.field=t,this.centerX=n,this.centerY=r,this.distance=s}execute(t){var r;const n=(r=t.spatialIndexes)==null?void 0:r[this.field];return n?n.searchWithin(this.centerX,this.centerY,this.distance):this._bruteForceScan(t)}_bruteForceScan(t){const n=t.documentStore;if(!n)return new D;const r=[],s=[...n.docIds].sort((o,i)=>o-i);for(const o of s){const i=n.getField(o,this.field);if(!i)continue;const a=hr(this.centerY,this.centerX,i[1],i[0]);if(a<=this.distance){const l=this.distance>0?1-a/this.distance:1;r.push({docId:o,payload:U({score:l})})}}return D.fromSorted(r)}costEstimate(t){return Math.log2(t.totalDocs+1)}}class G extends q{constructor(t,n,r){super();b(this,"field");b(this,"predicate");b(this,"source");this.field=t,this.predicate=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;const r=Zn(this.predicate),s=typeof n.getFieldsBulk=="function";if(this.source){const l=[...this.source.execute(t)];if(s&&l.length>1){const h=l.map(p=>p.docId),f=n.getFieldsBulk(h,this.field),d=[];for(const p of l){const m=f.get(p.docId);(r?this.predicate.evaluate(m):m!=null&&this.predicate.evaluate(m))&&d.push(p)}return D.fromSorted(d)}const u=[];for(const h of l){const f=n.getField(h.docId,this.field);(r?this.predicate.evaluate(f):f!=null&&this.predicate.evaluate(f))&&u.push(h)}return D.fromSorted(u)}const o=[...n.docIds].sort((a,l)=>a-l);if(s&&o.length>1){const a=n.getFieldsBulk(o,this.field),l=[];for(const u of o){const h=a.get(u);(r?this.predicate.evaluate(h):h!=null&&this.predicate.evaluate(h))&&l.push({docId:u,payload:U({score:0})})}return D.fromSorted(l)}const i=[];for(const a of o){const l=n.getField(a,this.field);!r&&l==null||this.predicate.evaluate(l)&&i.push({docId:a,payload:U({score:0})})}return D.fromSorted(i)}costEstimate(t){return t.totalDocs}}class Vs extends q{constructor(t,n){super();b(this,"field");b(this,"source");this.field=t,this.source=n??null}execute(t){const n=t.documentStore;if(!n)return new D;let r;this.source?r=this.source.execute(t).entries.map(l=>l.docId):r=[...n.docIds].sort((a,l)=>a-l);const s=new Map;for(const a of r){const l=n.getField(a,this.field);if(l!=null){const u=String(l);s.set(u,(s.get(u)??0)+1)}}const i=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0])).map(([a,l],u)=>({docId:u,payload:U({score:l,fields:{_facet_field:this.field,_facet_value:a,_facet_count:l}})}));return D.fromSorted(i)}costEstimate(t){return t.totalDocs}}class pe extends q{constructor(t,n,r,s){super();b(this,"scorer");b(this,"source");b(this,"queryTerms");b(this,"field");this.scorer=t,this.source=n,this.queryTerms=r,this.field=s??null}execute(t){const n=this.source.execute(t),r=t.invertedIndex;if(!r)return n;const s=typeof this.scorer.idf=="function"&&typeof this.scorer.scoreWithIdf=="function",o=typeof this.scorer.combineScores=="function",i=[];if(s)for(const p of this.queryTerms){const m=this.field?r.docFreq(this.field,p):r.docFreqAnyField(p);i.push(this.scorer.idf(m))}const a=n.entries,l=a.map(p=>p.docId),u=typeof r.getDocLengthsBulk=="function";let h=null;u&&this.field!==null&&(h=r.getDocLengthsBulk(l,this.field));const f=[];if(u&&this.field!==null)for(const p of this.queryTerms)f.push(r.getTermFreqsBulk(l,this.field,p));const d=[];for(const p of a){const m=[];let _;h!==null?_=h.get(p.docId)??0:this.field!==null?_=r.getDocLength(p.docId,this.field):_=r.getTotalDocLength(p.docId);for(let x=0;x<this.queryTerms.length;x++){const v=this.queryTerms[x];let E;if(f.length>0?E=f[x].get(p.docId)??0:this.field!==null?E=r.getTermFreq(p.docId,this.field,v):E=r.getTotalTermFreq(p.docId,v),s)m.push(this.scorer.scoreWithIdf(E,_,i[x]));else{const I=this.field?r.docFreq(this.field,v):r.docFreqAnyField(v);m.push(this.scorer.score(E,_,I))}}const y=o?this.scorer.combineScores(m):m.reduce((x,v)=>x+v,0);d.push({docId:p.docId,payload:U({positions:p.payload.positions,score:y,fields:p.payload.fields})})}return D.fromSorted(d)}}class zt extends q{constructor(t,n,r){super();b(this,"index");b(this,"field");b(this,"predicate");this.index=t,this.field=n,this.predicate=r}execute(t){return this.index.scan(this.predicate)}costEstimate(t){return this.index.scanCost(this.predicate)}}class re extends q{constructor(t){super();b(this,"operands");this.operands=t}execute(t){const n=this.operands.map(s=>s.execute(t));let r=new D;for(const s of n)r=r.union(s);return r}costEstimate(t){let n=0;for(const r of this.operands)n+=r.costEstimate(t);return n}}class H extends q{constructor(t){super();b(this,"operands");this.operands=t}execute(t){if(this.operands.length===0)return new D;let n=this.operands[0].execute(t);for(let r=1;r<this.operands.length;r++){if(n.length===0)return n;n=n.intersect(this.operands[r].execute(t))}return n}costEstimate(t){if(this.operands.length===0)return 0;let n=1/0;for(const r of this.operands){const s=r.costEstimate(t);s<n&&(n=s)}return n}}class de extends q{constructor(t){super();b(this,"operand");this.operand=t}execute(t){const n=this.operand.execute(t),r=t.documentStore;if(!r)return new D;const s=D.fromSorted([...r.docIds].sort((o,i)=>o-i).map(o=>({docId:o,payload:U({score:0})})));return n.complement(s)}costEstimate(t){return t.totalDocs}}function $s(c,e,t=1){return e<=0?1:Math.pow(c/e,t)}function qs(c,e=.5){const t=c.length;if(t===0)return{calibrate(i){return i.map(()=>e)}};let n=0;for(let i=0;i<t;i++)n+=c[i];const r=n/t;let s=0;for(let i=0;i<t;i++){const a=c[i]-r;s+=a*a}const o=Math.max(Math.sqrt(s/t),1e-10);return{calibrate(i,a){const l=(a==null?void 0:a.bandwidthFactor)??1,u=(a==null?void 0:a.densityPrior)??null,h=1.06*o*Math.pow(t,-.2)*l;return i.map((f,d)=>{const p=(f-r)/Math.max(h,1e-10),m=Math.exp(-.5*p*p)/(Math.sqrt(2*Math.PI)*h),_=m*2;let y=e;u!==null&&d<u.length&&(y=Math.min(Math.max(u[d]*e,.01),.99));const x=_*y,v=x+m*(1-y);return v<=0?y:Math.min(Math.max(x/v,.001),.999)})}}}function zs(c,e,t,n){const r=c.length,s=new Array(r).fill(.01),o=e.invertedIndex;if(o==null||t===null)return s;const i=n??"",a=new ct(Je(),o.stats),l=t.toLowerCase().split(/\s+/).filter(p=>p.length>0);if(l.length===0)return s;const u=new _e(t,i||null),f=new pe(a,u,l,i||null).execute(e),d=new Map;for(const p of f)d.set(p.docId,p.payload.score);for(let p=0;p<c.length;p++){const m=d.get(c[p].docId)??.01;s[p]=Math.min(Math.max(m,.01),.99)}return s}class fr extends q{constructor(t,n,r="embedding",s="kde",o=.5,i="density_prior",a,l,u=1,h=1){super();b(this,"queryVector");b(this,"k");b(this,"field");b(this,"estimationMethod");b(this,"baseRate");b(this,"weightSource");b(this,"bm25Query");b(this,"bm25Field");b(this,"densityGamma");b(this,"bandwidthScale");this.queryVector=t,this.k=n,this.field=r,this.estimationMethod=s,this.baseRate=o,this.weightSource=i,this.bm25Query=a??null,this.bm25Field=l??null,this.densityGamma=u,this.bandwidthScale=h}execute(t){var x;const n=(x=t.vectorIndexes)==null?void 0:x[this.field];if(n===void 0)return new D;const r=n.searchKnn(this.queryVector,this.k);if(r.length===0)return r;const s=[],o=[],i=[];for(const v of r)s.push(v),o.push(v.docId),i.push(v.payload.score);const a=i.map(v=>1-v);let l=null,u=null;const h=n;if(typeof h.probedDistances=="function"){l=h;const v=h.probedDistances(this.queryVector);v!==null&&v.length>0&&(u=Array.isArray(v)?v:Array.from(v))}if((u===null||u.length===0)&&h.backgroundSamples!==null&&h.backgroundSamples!==void 0){l=h;const v=h.backgroundSamples;v.length>0&&(u=Array.isArray(v)?v:Array.from(v))}if(u===null||u.length===0)return r;const f=qs(u,this.baseRate),{weights:d,densityPrior:p,method:m}=this._resolveWeightsAndMethod(s,l,a,t),_=f.calibrate(a,{weights:d,method:m,bandwidthFactor:this.bandwidthScale,densityPrior:p}),y=o.map((v,E)=>({docId:v,payload:U({score:_[E],fields:{_raw_similarity:i[E],...s[E].payload.fields}})}));return new D(y)}_resolveWeightsAndMethod(t,n,r,s){if(this.weightSource==="bayesian_bm25")return{weights:zs(t,s,this.bm25Query,this.bm25Field),densityPrior:null,method:this.estimationMethod};if(this.weightSource==="density_prior"&&n!==null&&typeof n.cellPopulations=="function"){const o=n.cellPopulations(),i=(n.totalVectors??0)/Math.max(n.nlist??1,1);return{weights:null,densityPrior:t.map(l=>{const u=l.payload.fields._centroid_id??-1,h=o.get(u)??1;return $s(h,i,this.densityGamma)}),method:this.estimationMethod}}return this.weightSource==="distance_gap"?{weights:null,densityPrior:null,method:"auto"}:{weights:null,densityPrior:null,method:this.estimationMethod}}costEstimate(t){return t.dimensions*Math.log2(t.totalDocs+1)}}function Gs(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function Bs(c){const e=Math.max(1e-10,Math.min(.9999999999,c));return Math.log(e/(1-e))}function Us(c,e){if(e<=0)return .5;const t=c/e;return Gs(Bs(.5)-.5*t)}class dr{constructor(e,t,n=.5,r=10,s){b(this,"_signalPostingLists");b(this,"_signalUpperBounds");b(this,"_alpha");b(this,"_k");b(this,"_gating");this._signalPostingLists=e,this._signalUpperBounds=t,this._alpha=n,this._k=r,this._gating=s??null}_computeFusedUpperBound(e){return K.logOddsConjunction(e,this._alpha,void 0,this._gating??"none")}scoreTopK(){const e=this._signalPostingLists.length,t=[],n=new Set;let r=0;for(let l=0;l<e;l++){const u=new Map;for(const h of this._signalPostingLists[l])u.set(h.docId,h.payload.score),n.add(h.docId);t.push(u),r=Math.max(r,u.size)}const s=t.map(l=>Us(l.size,r)),o=[];let i=0;for(const l of n){const u=[];for(let p=0;p<e;p++)t[p].has(l)?u.push(this._signalUpperBounds[p]):u.push(s[p]);const h=this._computeFusedUpperBound(u);if(o.length>=this._k&&h<=i)continue;const f=[];for(let p=0;p<e;p++)f.push(t[p].get(l)??s[p]);const d=K.logOddsConjunction(f,this._alpha,void 0,this._gating??"none");o.length<this._k?(o.push([d,l]),Ws(o,o.length-1),o.length===this._k&&(i=o[0][0])):d>i&&(o[0]=[d,l],Hs(o),i=o[0][0])}const a=o.map(([l,u])=>({docId:u,payload:U({score:l})}));return new D(a)}}function Ws(c,e){for(;e>0;){const t=e-1>>>1;if(c[t][0]<=c[e][0])break;[c[t],c[e]]=[c[e],c[t]],e=t}}function Hs(c){const e=c.length;let t=0;for(;;){let n=t;const r=2*t+1,s=2*t+2;if(r<e&&c[r][0]<c[n][0]&&(n=r),s<e&&c[s][0]<c[n][0]&&(n=s),n===t)break;[c[t],c[n]]=[c[n],c[t]],t=n}}function ut(c,e,t=.01){if(e<=0)return .5;const n=c/e;return .5*(1-n)+t*n}class Ks extends q{constructor(t,n,r){super();b(this,"_termOp");b(this,"_vectorOp");this._termOp=new _e(t),this._vectorOp=new Ee(n,r)}execute(t){const n=this._termOp.execute(t),r=this._vectorOp.execute(t);return n.intersect(r)}costEstimate(t){return Math.min(this._termOp.costEstimate(t),this._vectorOp.costEstimate(t))}}class Js extends q{constructor(t,n,r){super();b(this,"source");b(this,"_vectorOp");this.source=t,this._vectorOp=new Ee(n,r)}execute(t){const n=this.source.execute(t),r=this._vectorOp.execute(t);return n.intersect(r)}costEstimate(t){return Math.min(this.source.costEstimate(t),this._vectorOp.costEstimate(t))}}class ke extends q{constructor(t,n=.5,r,s,o){super();b(this,"signals");b(this,"alpha");b(this,"topK");b(this,"gating");b(this,"gatingBeta");this.signals=t,this.alpha=n,this.topK=r??null,this.gating=s??null,this.gatingBeta=o??null}execute(t){const n=this.signals.map(f=>f.execute(t));if(this.topK!==null){const f=n.map(p=>{let m=0;for(const _ of p)_.payload.score>m&&(m=_.payload.score);return Math.max(m,.5)});return new dr(n,f,this.alpha,this.topK,this.gating).scoreTopK()}const r=[],s=new Set;for(const f of n){const d=new Map;for(const p of f)d.set(p.docId,p.payload.score),s.add(p.docId);r.push(d)}const o=[...s].sort((f,d)=>f-d),i=o.length,a=r.length;if(i===0)return new D;const l=r.map(f=>ut(f.size,i)),u=[],h=this.alpha;for(const f of o){const d=[];for(let m=0;m<a;m++)d.push(r[m].get(f)??l[m]);let p;a===1?p=d[0]:p=K.logOddsConjunction(d,h,void 0,this.gating??"none",this.gatingBeta??void 0),u.push({docId:f,payload:U({score:p})})}return D.fromSorted(u)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class Ve extends q{constructor(t,n="and"){super();b(this,"signals");b(this,"mode");this.signals=t,this.mode=n}execute(t){const n=this.signals.map(u=>u.execute(t)),r=[],s=new Set;for(const u of n){const h=new Map;for(const f of u)h.set(f.docId,f.payload.score),s.add(f.docId);r.push(h)}const o=[...s].sort((u,h)=>u-h),i=o.length,a=r.map(u=>ut(u.size,i)),l=[];for(const u of o){const h=[];for(let d=0;d<r.length;d++)h.push(r[d].get(u)??a[d]);const f=this.mode==="and"?K.probAnd(h):K.probOr(h);l.push({docId:u,payload:U({score:f})})}return D.fromSorted(l)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class En extends q{constructor(t,n,r,s="embedding"){super();b(this,"positive");b(this,"_negativeOp");this.positive=t,this._negativeOp=new Ee(n,r,s)}execute(t){const n=this.positive.execute(t),r=this._negativeOp.execute(t),s=new Set;for(const i of r)s.add(i.docId);const o=[...n].filter(i=>!s.has(i.docId));return D.fromSorted(o)}costEstimate(t){return this.positive.costEstimate(t)+this._negativeOp.costEstimate(t)}}class pr extends q{constructor(t,n,r,s){super();b(this,"facetField");b(this,"_vectorOp");b(this,"source");this.facetField=t,this._vectorOp=new Ee(n,r),this.source=s??null}execute(t){const n=this._vectorOp.execute(t),r=new Set;for(const l of n)r.add(l.docId);let s;this.source!==null?s=[...this.source.execute(t)].filter(u=>r.has(u.docId)).map(u=>u.docId):s=[...r].sort((l,u)=>l-u);const o=t.documentStore;if(!o)return new D;const i=new Map;for(const l of s){const u=o.getField(l,this.facetField);if(u!=null){const h=String(u);i.set(h,(i.get(h)??0)+1)}}const a=[...i.entries()].sort((l,u)=>l[0].localeCompare(u[0]));return D.fromSorted(a.map(([l,u],h)=>({docId:h,payload:U({score:u,fields:{_facet_field:this.facetField,_facet_value:l,_facet_count:u}})})))}costEstimate(t){let n=this._vectorOp.costEstimate(t);return this.source!==null&&(n+=this.source.costEstimate(t)),n}}class Gt extends q{constructor(t,n=.01){super();b(this,"signal");b(this,"defaultProb");this.signal=t,this.defaultProb=n}execute(t){const n=this.signal.execute(t),r=t.documentStore,s=new Map;for(const l of n)s.set(l.docId,l.payload.score);const o=new Set(s.keys());if(r)for(const l of r.docIds)o.add(l);const i=[...o].sort((l,u)=>l-u),a=[];for(const l of i){const h=1-(s.get(l)??this.defaultProb);a.push({docId:l,payload:U({score:h})})}return D.fromSorted(a)}costEstimate(t){return this.signal.costEstimate(t)}}class Ys extends q{constructor(t,n=.5,r){super();b(this,"signals");b(this,"baseAlpha");b(this,"gating");this.signals=t,this.baseAlpha=n,this.gating=r??null}execute(t){const n=this.signals.map(h=>h.execute(t)),r=new Set,s=[];for(const h of n){const f=new Map;for(const d of h)f.set(d.docId,d.payload.score),r.add(d.docId);s.push(f)}const o=[...r].sort((h,f)=>h-f),i=o.length;if(i===0)return new D;const a=[];for(const h of s){const f=i>0?h.size/i:0,d=[...h.values()];let p=0;if(d.length>1){let y=0;for(const v of d)y+=v;y/=d.length;let x=0;for(const v of d)x+=(v-y)*(v-y);p=x/d.length}let m=.5;if(d.length>0){let y=0;for(const x of d)y+=x;m=y/d.length}const _=Math.abs(m-.5);a.push({coverageRatio:f,scoreVariance:p,calibrationError:_})}const l=s.map(h=>ut(h.size,i)),u=[];for(const h of o){const f=[];for(let _=0;_<s.length;_++)f.push(s[_].get(h)??l[_]);const d=[];for(const _ of a){const y=_.coverageRatio*(1-_.calibrationError);d.push(this.baseAlpha*(.5+y))}let p=this.baseAlpha;if(d.length>0){let _=0;for(const y of d)_+=y;p=_/d.length}const m=K.logOddsConjunction(f,p,void 0,this.gating??"none");u.push({docId:h,payload:U({score:m})})}return D.fromSorted(u)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}function gr(c){return c===" "||c===" "||c===`
2
+ `||c==="\r"}function mr(c){return!gr(c)&&c!=="("&&c!==")"&&c!==":"&&c!=='"'&&c!=="["&&c!=="]"}const Xs={and:"AND",or:"OR",not:"NOT"};function Qs(c){const e=[];let t=0;const n=c.length;for(;t<n;){const r=c[t];if(gr(r)){t++;continue}if(r==="("){e.push({type:"LPAREN",value:"(",pos:t}),t++;continue}if(r===")"){e.push({type:"RPAREN",value:")",pos:t}),t++;continue}if(r===":"){e.push({type:"COLON",value:":",pos:t}),t++;continue}if(r==='"'){const s=t;t++;let o="";for(;t<n&&c[t]!=='"';)o+=c[t],t++;if(t>=n)throw new Error(`Unterminated quoted phrase starting at position ${String(s)}`);e.push({type:"PHRASE",value:o,pos:s}),t++;continue}if(r==="["){const s=t;t++;let o="";for(;t<n&&c[t]!=="]";)o+=c[t],t++;if(t>=n)throw new Error(`Unterminated vector literal starting at position ${String(s)}`);e.push({type:"VECTOR",value:o.trim(),pos:s}),t++;continue}if(mr(r)){const s=t;let o="";for(;t<n&&mr(c[t]);)o+=c[t],t++;const i=Xs[o.toLowerCase()];i!==void 0?e.push({type:i,value:o,pos:s}):e.push({type:"TERM",value:o,pos:s});continue}throw new Error(`Unexpected character '${r}' at position ${String(t)}`)}return e.push({type:"EOF",value:"",pos:n}),e}class Zs{constructor(e){b(this,"_tokens");b(this,"_pos");this._tokens=e,this._pos=0}parse(){if(this._peek().type==="EOF")throw new Error("Empty query");const e=this._orExpr();if(this._peek().type!=="EOF"){const t=this._peek();throw new Error(`Unexpected token '${t.value}' at position ${String(t.pos)}`)}return e}_peek(){return this._tokens[this._pos]??{type:"EOF",value:"",pos:-1}}_advance(){const e=this._peek();return e.type!=="EOF"&&this._pos++,e}_expect(e){const t=this._advance();if(t.type!==e)throw new Error(`Expected ${e}, got ${t.type} ('${t.value}') at position ${String(t.pos)}`);return t}_orExpr(){let e=this._andExpr();for(;this._peek().type==="OR";){this._advance();const t=this._andExpr();e={type:"or",left:e,right:t}}return e}_andExpr(){let e=this._unary();for(;;){const t=this._peek();if(t.type==="AND"){this._advance();const n=this._unary();e={type:"and",left:e,right:n}}else if(t.type==="TERM"||t.type==="PHRASE"||t.type==="VECTOR"||t.type==="LPAREN"||t.type==="NOT"){const n=this._unary();e={type:"and",left:e,right:n}}else break}return e}_unary(){return this._peek().type==="NOT"?(this._advance(),{type:"not",operand:this._unary()}):this._primary()}_primary(){const e=this._peek();if(e.type==="LPAREN"){this._advance();const t=this._orExpr();return this._expect("RPAREN"),t}if(e.type==="PHRASE")return this._advance(),{type:"phrase",field:null,phrase:e.value};if(e.type==="VECTOR")return this._advance(),{type:"vector",field:null,values:_r(e.value)};if(e.type==="TERM"){if(this._advance(),this._peek().type==="COLON"){this._advance();const t=this._peek();if(t.type==="PHRASE")return this._advance(),{type:"phrase",field:e.value,phrase:t.value};if(t.type==="VECTOR")return this._advance(),{type:"vector",field:e.value,values:_r(t.value)};if(t.type==="TERM")return this._advance(),{type:"term",field:e.value,term:t.value};throw new Error(`Expected term, phrase, or vector after ':', got ${t.type} at position ${String(t.pos)}`)}return{type:"term",field:null,term:e.value}}throw new Error(`Unexpected token ${e.type} ('${e.value}') at position ${String(e.pos)}`)}}function _r(c){const e=c.trim();if(e.length===0)throw new Error("Empty vector literal");return e.split(",").map(t=>{const n=Number(t.trim());if(Number.isNaN(n))throw new Error(`Malformed vector literal: invalid number '${t.trim()}'`);return n})}function ht(c,e){switch(e.type){case"term":return c.includes(e.term.toLowerCase());case"phrase":return c.includes(e.phrase.toLowerCase());case"and":return ht(c,e.left)&&ht(c,e.right);case"or":return ht(c,e.left)||ht(c,e.right);case"not":return!ht(c,e.operand);case"vector":return!1;default:return!1}}function yr(c,e){try{const t=Qs(e),n=new Zs(t).parse();return ht(c.toLowerCase(),n)}catch{const t=e.toLowerCase().split(/\s+/).filter(n=>n.length>0);return t.length===0?!1:t.every(n=>c.toLowerCase().includes(n))}}function M(c){return typeof c=="string"?c:c==null?"":typeof c=="number"?c.toString(10):typeof c=="boolean"?c?"true":"false":typeof c=="bigint"?c.toString(10):JSON.stringify(c)}function eo(c){const e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],t=[];for(let p=0;p<64;p++)t.push(Math.floor(Math.abs(Math.sin(p+1))*4294967296));const r=new TextEncoder().encode(c),s=r.length*8,o=r.length%64<56?56-r.length%64:120-r.length%64,i=new Uint8Array(r.length+o+8);i.set(r),i[r.length]=128;const a=new DataView(i.buffer);a.setUint32(i.length-8,s>>>0,!0),a.setUint32(i.length-4,Math.floor(s/4294967296),!0);let l=1732584193,u=4023233417,h=2562383102,f=271733878;for(let p=0;p<i.length;p+=64){const m=[];for(let E=0;E<16;E++)m.push(a.getUint32(p+E*4,!0));let _=l,y=u,x=h,v=f;for(let E=0;E<64;E++){let I,S;E<16?(I=y&x|~y&v,S=E):E<32?(I=v&y|~v&x,S=(5*E+1)%16):E<48?(I=y^x^v,S=(3*E+5)%16):(I=x^(y|~v),S=7*E%16),I=I+_+t[E]+m[S]>>>0,_=v,v=x,x=y,y=y+(I<<e[E]|I>>>32-e[E])>>>0}l=l+_>>>0,u=u+y>>>0,h=h+x>>>0,f=f+v>>>0}function d(p){let m="";for(let _=0;_<4;_++){const y=p>>>_*8&255;m+=(y<16?"0":"")+y.toString(16)}return m}return d(l)+d(u)+d(h)+d(f)}function br(c){if(c.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(c))return new Date(c);const e=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?)?$/.exec(c);if(e){const t=parseInt(e[1],10),n=parseInt(e[2],10)-1,r=parseInt(e[3],10),s=e[4]!==void 0?parseInt(e[4],10):0,o=e[5]!==void 0?parseInt(e[5],10):0,i=e[6]!==void 0?parseInt(e[6],10):0,a=e[7]!==void 0?parseInt(e[7].padEnd(3,"0").slice(0,3),10):0;return new Date(t,n,r,s,o,i,a)}return new Date(c)}function vr(c){const e=String(c.getFullYear()).padStart(4,"0"),t=String(c.getMonth()+1).padStart(2,"0"),n=String(c.getDate()).padStart(2,"0"),r=String(c.getHours()).padStart(2,"0"),s=String(c.getMinutes()).padStart(2,"0"),o=String(c.getSeconds()).padStart(2,"0"),i=String(c.getMilliseconds()).padStart(3,"0");return`${e}-${t}-${n}T${r}:${s}:${o}.${i}`}function In(c,e){var t;switch(c){case"upper":return e[0]===null?null:M(e[0]).toUpperCase();case"lower":return e[0]===null?null:M(e[0]).toLowerCase();case"length":case"char_length":case"character_length":return e[0]===null?null:M(e[0]).length;case"octet_length":return e[0]===null?null:new TextEncoder().encode(M(e[0])).length;case"trim":case"btrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=0,o=r.length;for(;s<o&&n.includes(r[s]);)s++;for(;o>s&&n.includes(r[o-1]);)o--;return r.slice(s,o)}return M(e[0]).trim();case"ltrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=0;for(;s<r.length&&n.includes(r[s]);)s++;return r.slice(s)}return M(e[0]).replace(/^\s+/,"");case"rtrim":if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const n=M(e[1]),r=M(e[0]);let s=r.length;for(;s>0&&n.includes(r[s-1]);)s--;return r.slice(0,s)}return M(e[0]).replace(/\s+$/,"");case"replace":return e[0]===null?null:M(e[0]).split(M(e[1])).join(M(e[2]));case"substring":case"substr":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1])-1;if(e.length>=3){const s=Number(e[2]);return n.slice(r,r+s)}return n.slice(r)}case"concat":return e.map(n=>n===null?"":M(n)).join("");case"concat_ws":{if(e[0]===null||e[0]===void 0)return null;const n=M(e[0]);return e.slice(1).filter(r=>r!=null).map(r=>M(r)).join(n)}case"left":return e[0]===null?null:M(e[0]).slice(0,Number(e[1]));case"right":return e[0]===null?null:M(e[0]).slice(-Number(e[1]));case"lpad":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1]),s=e.length>=3?M(e[2]):" ";return n.length>=r?n.slice(0,r):s.repeat(Math.ceil((r-n.length)/s.length)).slice(0,r-n.length)+n}case"rpad":{if(e[0]===null)return null;const n=M(e[0]),r=Number(e[1]),s=e.length>=3?M(e[2]):" ";return n.length>=r?n.slice(0,r):n+s.repeat(Math.ceil((r-n.length)/s.length)).slice(0,r-n.length)}case"repeat":return e[0]===null?null:M(e[0]).repeat(Number(e[1]));case"reverse":return e[0]===null?null:Array.from(M(e[0])).reverse().join("");case"position":case"strpos":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).indexOf(M(e[1]));return n===-1?0:n+1}case"initcap":return e[0]===null?null:M(e[0]).replace(/\b\w/g,n=>n.toUpperCase());case"md5":return e[0]===null?null:eo(M(e[0]));case"encode":if(e[0]===null)return null;if(M(e[1]).toLowerCase()==="base64"&&typeof btoa=="function")return btoa(M(e[0]));throw new Error(`encode() format not supported: ${M(e[1])}`);case"decode":if(e[0]===null)return null;if(M(e[1]).toLowerCase()==="base64"&&typeof atob=="function")return atob(M(e[0]));throw new Error(`decode() format not supported: ${M(e[1])}`);case"abs":return e[0]===null?null:Math.abs(Number(e[0]));case"round":{if(e[0]===null)return null;const n=Number(e[0]);if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const s=10**Number(e[1]);return Math.round(n*s)/s}return Math.round(n)}case"ceil":case"ceiling":return e[0]===null?null:Math.ceil(Number(e[0]));case"floor":return e[0]===null?null:Math.floor(Number(e[0]));case"trunc":case"truncate":{if(e[0]===null)return null;if(e.length>=2&&e[1]!==null&&e[1]!==void 0){const r=10**Number(e[1]);return Math.trunc(Number(e[0])*r)/r}return Math.trunc(Number(e[0]))}case"power":case"pow":return e[0]===null||e[1]===null?null:Math.pow(Number(e[0]),Number(e[1]));case"sqrt":return e[0]===null?null:Math.sqrt(Number(e[0]));case"cbrt":return e[0]===null?null:Math.cbrt(Number(e[0]));case"exp":return e[0]===null?null:Math.exp(Number(e[0]));case"ln":return e[0]===null?null:Math.log(Number(e[0]));case"log":return e[0]===null?null:e.length>=2&&e[1]!==null?Math.log(Number(e[1]))/Math.log(Number(e[0])):Math.log10(Number(e[0]));case"log10":case"log2":return e[0]===null?null:c==="log10"?Math.log10(Number(e[0])):Math.log2(Number(e[0]));case"mod":return e[0]===null||e[1]===null?null:Number(e[0])%Number(e[1]);case"sign":return e[0]===null?null:Math.sign(Number(e[0]));case"pi":return Math.PI;case"random":return Math.random();case"degrees":return e[0]===null?null:Number(e[0])*180/Math.PI;case"radians":return e[0]===null?null:Number(e[0])*Math.PI/180;case"sin":return e[0]===null?null:Math.sin(Number(e[0]));case"cos":return e[0]===null?null:Math.cos(Number(e[0]));case"tan":return e[0]===null?null:Math.tan(Number(e[0]));case"asin":return e[0]===null?null:Math.asin(Number(e[0]));case"acos":return e[0]===null?null:Math.acos(Number(e[0]));case"atan":return e[0]===null?null:Math.atan(Number(e[0]));case"atan2":return e[0]===null||e[1]===null?null:Math.atan2(Number(e[0]),Number(e[1]));case"div":return e[0]===null||e[1]===null||Number(e[1])===0?null:Math.trunc(Number(e[0])/Number(e[1]));case"gcd":{if(e[0]===null||e[1]===null)return null;let n=Math.abs(Math.trunc(Number(e[0]))),r=Math.abs(Math.trunc(Number(e[1])));for(;r;){const s=r;r=n%r,n=s}return n}case"lcm":{if(e[0]===null||e[1]===null)return null;const n=Math.abs(Math.trunc(Number(e[0]))),r=Math.abs(Math.trunc(Number(e[1])));if(n===0||r===0)return 0;let s=n,o=r;for(;o;){const i=o;o=s%o,s=i}return Math.abs(n*r)/s}case"width_bucket":{if(e.length<4||e.some(i=>i===null))return null;const n=Number(e[0]),r=Number(e[1]),s=Number(e[2]),o=Math.trunc(Number(e[3]));return s===r||o<=0?null:n<r?0:n>=s?o+1:Math.trunc((n-r)/((s-r)/o))+1}case"min_scale":{if(e[0]===null)return null;const n=String(e[0]),r=n.indexOf(".");if(r===-1)return 0;let s=n.length;for(;s>r+1&&n[s-1]==="0";)s--;return s-r-1}case"trim_scale":{if(e[0]===null)return null;const n=Number(e[0]);return Number.isInteger(n),n}case"translate":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]),r=M(e[1]),s=M(e[2]);let o="";for(const i of n){const a=r.indexOf(i);a===-1?o+=i:a<s.length&&(o+=s[a])}return o}case"ascii":return e[0]===null?null:M(e[0]).length>0?M(e[0]).charCodeAt(0):0;case"chr":return e[0]===null?null:String.fromCharCode(Math.trunc(Number(e[0])));case"starts_with":return e[0]===null||e[1]===null?null:M(e[0]).startsWith(M(e[1]));case"split_part":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]).split(M(e[1])),r=Math.trunc(Number(e[2]));return r>=1&&r<=n.length?n[r-1]:""}case"format":{if(e[0]===null)return null;let n=M(e[0]);n=n.replace(/%I/g,"%s").replace(/%L/g,"'%s'");let r=1;return n.replace(/%s/g,()=>r<e.length?M(e[r++]):"")}case"overlay":{if(e[0]===null||e[1]===null||e[2]===null)return null;const n=M(e[0]),r=M(e[1]),s=Math.trunc(Number(e[2]))-1,o=e.length>3&&e[3]!=null?Math.trunc(Number(e[3])):r.length;return n.slice(0,s)+r+n.slice(s+o)}case"regexp_match":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).match(new RegExp(M(e[1])));if(n===null)return null;const r=n.slice(1);return r.length>0?r:[n[0]]}case"regexp_matches":{if(e[0]===null||e[1]===null)return null;const n=e.length>2&&e[2]!=null?M(e[2]):"";let r="";if(n.includes("i")&&(r+="i"),n.includes("g")){const o=new RegExp(M(e[1]),r+"g"),i=[];let a;for(;(a=o.exec(M(e[0])))!==null;)i.push(a.slice(1).length>0?[...a.slice(1)]:[a[0]]);return i}const s=M(e[0]).match(new RegExp(M(e[1]),r));return s===null?null:[s.slice(1).length>0?[...s.slice(1)]:[s[0]]]}case"regexp_replace":{if(e[0]===null||e[1]===null)return null;const n=e.length>2&&e[2]!=null?M(e[2]):"",r=e.length>3&&e[3]!=null?M(e[3]):"";let s="";return r.includes("i")&&(s+="i"),r.includes("g")?s+="g":s.includes("g"),M(e[0]).replace(new RegExp(M(e[1]),s||void 0),n)}case"regexp_split_to_array":{if(e[0]===null||e[1]===null)return null;let n="";return e.length>2&&e[2]!=null&&M(e[2]).includes("i")&&(n="i"),M(e[0]).split(new RegExp(M(e[1]),n))}case"regexp_count":{if(e[0]===null||e[1]===null)return 0;let n="";e.length>2&&e[2]!=null&&(n=M(e[2]));const r=new RegExp(M(e[1]),"g"+(n.includes("i")?"i":"")),s=M(e[0]).match(r);return s!==null?s.length:0}case"string_to_array":{if(e[0]===null)return null;const n=e.length>1&&e[1]!=null?M(e[1]):",",r=e.length>2&&e[2]!=null?M(e[2]):null,s=M(e[0]).split(n);return r!==null?s.map(o=>o===r?null:o):s}case"array_to_string":{if(e[0]===null||!Array.isArray(e[0]))return null;const n=e.length>1&&e[1]!=null?M(e[1]):",",r=e.length>2&&e[2]!=null?M(e[2]):"";return e[0].map(s=>s==null?r:M(s)).join(n)}case"array_position":{if(e[0]===null||e[1]===null||!Array.isArray(e[0]))return null;const n=e[0].indexOf(e[1]);return n===-1?null:n+1}case"array_positions":{if(e[0]===null||e[1]===null||!Array.isArray(e[0]))return null;const n=[];for(let r=0;r<e[0].length;r++)e[0][r]===e[1]&&n.push(r+1);return n}case"array_replace":return e[0]===null||!Array.isArray(e[0])?null:e[0].map(n=>n===e[1]?e[2]:n);case"array_dims":return e[0]===null||!Array.isArray(e[0])?null:`[1:${String(e[0].length)}]`;case"array_fill":{if(e.length<2||e[1]===null)return null;const n=e[0],s=(Array.isArray(e[1])?e[1]:[Number(e[1])])[0]??0;return new Array(s).fill(n)}case"generate_series":{if(e.length<2||e[0]===null||e[1]===null)return[];const n=Number(e[0]),r=Number(e[1]),s=e.length>2&&e[2]!=null?Number(e[2]):1;if(s===0)return[];const o=[];if(s>0)for(let i=n;i<=r;i+=s)o.push(i);else for(let i=n;i>=r;i+=s)o.push(i);return o}case"generate_subscripts":{if(e[0]===null)return[];if(!Array.isArray(e[0]))return[];const n=e[0];return Array.from({length:n.length},(r,s)=>s+1)}case"hashtext":{if(e[0]===null)return null;let n=2166136261;const r=M(e[0]);for(let s=0;s<r.length;s++)n^=r.charCodeAt(s),n=Math.imul(n,16777619);return n>>>0}case"quote_ident":return e[0]===null?null:`"${M(e[0]).replace(/"/g,'""')}"`;case"quote_literal":return e[0]===null?"NULL":`'${M(e[0]).replace(/'/g,"''")}'`;case"quote_nullable":return e[0]===null?"NULL":`'${M(e[0]).replace(/'/g,"''")}'`;case"string_agg":return e[0]===null?null:M(e[0]);case"to_hex":{if(e[0]===null)return null;const n=Math.trunc(Number(e[0]));return n>=0?n.toString(16):(n>>>0).toString(16)}case"to_ascii":return e[0]===null?null:M(e[0]).replace(/[^\x00-\x7F]/g,"?");case"date_trunc":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).toLowerCase(),r=br(M(e[1]));return n==="year"?(r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0)):n==="month"?(r.setDate(1),r.setHours(0,0,0,0)):n==="day"?r.setHours(0,0,0,0):n==="hour"?r.setMinutes(0,0,0):n==="minute"?r.setSeconds(0,0):n==="second"&&r.setMilliseconds(0),vr(r)}case"make_timestamp":{if(e.length<6||e.some(r=>r===null))return null;const n=new Date(Number(e[0]),Number(e[1])-1,Number(e[2]),Number(e[3]),Number(e[4]),Math.trunc(Number(e[5])));return vr(n)}case"make_interval":{const n=e.length>0&&e[0]!=null?Number(e[0]):0,r=e.length>1&&e[1]!=null?Number(e[1]):0,s=e.length>2&&e[2]!=null?Number(e[2]):0,o=e.length>3&&e[3]!=null?Number(e[3]):0,i=e.length>4&&e[4]!=null?Number(e[4]):0,a=e.length>5&&e[5]!=null?Number(e[5]):0,l=e.length>6&&e[6]!=null?Number(e[6]):0,u=n*365+r*30+s*7+o,h=[];return n>0&&h.push(`${String(n)} year${n>1?"s":""}`),r>0&&h.push(`${String(r)} mon${r>1?"s":""}`),u>0&&h.push(`${String(u)} day${u!==1?"s":""}`),h.push(`${String(i).padStart(2,"0")}:${String(a).padStart(2,"0")}:${String(l).padStart(2,"0")}`),h.join(" ")}case"make_date":{if(e.length<3||e.some(o=>o===null))return null;const n=String(Number(e[0])).padStart(4,"0"),r=String(Number(e[1])).padStart(2,"0"),s=String(Number(e[2])).padStart(2,"0");return`${n}-${r}-${s}`}case"clock_timestamp":return new Date().toISOString();case"timeofday":return new Date().toUTCString();case"isfinite":return e[0]===null?null:!["infinity","-infinity"].includes(M(e[0]).trim().toLowerCase());case"overlaps":{if(e.length<4||e.some(i=>i===null))return null;const n=new Date(M(e[0])).getTime(),r=new Date(M(e[1])).getTime(),s=new Date(M(e[2])).getTime(),o=new Date(M(e[3])).getTime();return Math.min(n,r)<Math.max(s,o)&&Math.min(s,o)<Math.max(n,r)}case"typeof":case"pg_typeof":return e[0]===null?"null":typeof e[0]=="number"?Number.isInteger(e[0])?"integer":"real":typeof e[0]=="string"?"text":typeof e[0]=="boolean"?"boolean":"unknown";case"gen_random_uuid":return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)});case"array_remove":return e[0]===null?null:Array.isArray(e[0])?e[0].filter(n=>n!==e[1]):null;case"array_upper":return e[0]===null?null:Array.isArray(e[0])&&e[0].length>0?e[0].length:null;case"array_lower":return e[0]===null?null:Array.isArray(e[0])&&e[0].length>0?1:null;case"cardinality":return e[0]===null?null:Array.isArray(e[0])?e[0].length:null;case"json_extract_path":case"jsonb_extract_path":case"json_extract_path_text":case"jsonb_extract_path_text":{if(e[0]===null)return null;let n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];for(let r=1;r<e.length;r++){if(e[r]===null||n===null||n===void 0)return null;if(typeof n=="object"&&!Array.isArray(n))n=n[M(e[r])];else if(Array.isArray(n))n=n[Number(e[r])];else return null}return c.endsWith("_text")?n==null?null:typeof n=="object"?JSON.stringify(n):M(n):n??null}case"jsonb_set":case"jsonb_insert":{if(e.length<3||e[0]===null)return null;let n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];n=JSON.parse(JSON.stringify(n));const s=M(e[1]).replace(/^\{/,"").replace(/\}$/,"").split(",").map(l=>l.trim()),o=e[2];let i=n;for(let l=0;l<s.length-1;l++)if(typeof i=="object"&&i!==null&&!Array.isArray(i))i=i[s[l]];else if(Array.isArray(i))i=i[Number(s[l])];else return n;const a=s[s.length-1];return typeof i=="object"&&i!==null&&!Array.isArray(i)?i[a]=o:Array.isArray(i)&&(i[Number(a)]=o),n}case"json_each":case"jsonb_each":case"json_each_text":case"jsonb_each_text":{if(e[0]===null)return[];const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];if(typeof n!="object"||Array.isArray(n)||n===null)return[];const r=c.endsWith("_text");return Object.entries(n).map(([s,o])=>({key:s,value:r?typeof o=="object"&&o!==null?JSON.stringify(o):o!=null?M(o):null:o}))}case"json_array_elements":case"jsonb_array_elements":case"json_array_elements_text":case"jsonb_array_elements_text":{if(e[0]===null)return[];const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return Array.isArray(n)?c.endsWith("_text")?n.map(r=>typeof r=="object"&&r!==null?JSON.stringify(r):r!=null?M(r):null):n:[]}case"json_object_keys":case"jsonb_object_keys":{if(e[0]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return typeof n!="object"||Array.isArray(n)||n===null?null:Object.keys(n)}case"jsonb_strip_nulls":case"json_strip_nulls":{let n=function(s){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const o={};for(const[i,a]of Object.entries(s))a!==null&&(o[i]=n(a));return o}return s};if(e[0]===null)return null;const r=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return n(r)}case"json_build_array":case"jsonb_build_array":return[...e];case"point":if(e.length!==2)throw new Error("POINT() requires exactly 2 arguments");return[Number(e[0]),Number(e[1])];case"st_distance":{if(e.length!==2||e[0]===null||e[1]===null)return null;const n=e[0],r=e[1];if(!Array.isArray(n)||!Array.isArray(r))return null;const s=6371e3,o=n[1]*Math.PI/180,i=r[1]*Math.PI/180,a=(r[1]-n[1])*Math.PI/180,l=(r[0]-n[0])*Math.PI/180,u=Math.sin(a/2)**2+Math.cos(o)*Math.cos(i)*Math.sin(l/2)**2;return s*2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))}case"st_within":case"st_dwithin":{if(e.length!==3||e[0]===null||e[1]===null)return null;const n=In("st_distance",[e[0],e[1]]);return n===null?null:n<=Number(e[2])}case"coalesce":for(const n of e)if(n!=null)return n;return null;case"nullif":return e[0]===e[1]?null:e[0];case"greatest":{let n=null;for(const r of e)r!==null&&(n===null||r>n)&&(n=r);return n}case"least":{let n=null;for(const r of e)r!==null&&(n===null||r<n)&&(n=r);return n}case"current_date":case"current_timestamp":case"now":return new Date().toISOString();case"date_part":case"extract":{if(e[0]===null||e[1]===null)return null;const n=M(e[0]).toLowerCase(),r=br(M(e[1]));switch(n){case"year":return r.getFullYear();case"month":return r.getMonth()+1;case"day":return r.getDate();case"hour":return r.getHours();case"minute":return r.getMinutes();case"second":return r.getSeconds();case"dow":case"dayofweek":return r.getDay();case"doy":case"dayofyear":{const s=new Date(r.getFullYear(),0,0),o=r.getTime()-s.getTime();return Math.floor(o/864e5)}case"epoch":return Math.floor(r.getTime()/1e3);case"quarter":return Math.ceil((r.getMonth()+1)/3);case"week":{const s=new Date(r.getFullYear(),0,1),o=Math.floor((r.getTime()-s.getTime())/864e5)+1,i=s.getDay()||7;return Math.ceil((o+i-1)/7)}case"millisecond":case"milliseconds":return r.getSeconds()*1e3+r.getMilliseconds();case"microsecond":case"microseconds":return r.getSeconds()*1e6+r.getMilliseconds()*1e3;default:throw new Error(`Unknown date part: "${n}"`)}}case"age":{if(e[0]===null)return null;const n=new Date(M(e[0])),s=(e.length>=2&&e[1]!==null?new Date(M(e[1])):new Date).getTime()-n.getTime();return`${String(Math.floor(s/864e5))} days`}case"date_add":case"dateadd":{if(e.length<3||e.some(o=>o===null))return null;const n=M(e[0]).toLowerCase(),r=Number(e[1]),s=new Date(M(e[2]));return n==="year"?s.setFullYear(s.getFullYear()+r):n==="month"?s.setMonth(s.getMonth()+r):n==="day"?s.setDate(s.getDate()+r):n==="hour"?s.setHours(s.getHours()+r):n==="minute"?s.setMinutes(s.getMinutes()+r):n==="second"&&s.setSeconds(s.getSeconds()+r),s.toISOString()}case"date_subtract":case"datesub":{if(e.length<3||e.some(o=>o===null))return null;const n=M(e[0]).toLowerCase(),r=Number(e[1]),s=new Date(M(e[2]));return n==="year"?s.setFullYear(s.getFullYear()-r):n==="month"?s.setMonth(s.getMonth()-r):n==="day"?s.setDate(s.getDate()-r):n==="hour"?s.setHours(s.getHours()-r):n==="minute"?s.setMinutes(s.getMinutes()-r):n==="second"&&s.setSeconds(s.getSeconds()-r),s.toISOString()}case"date_diff":case"datediff":{if(e.length<3||e.some(i=>i===null))return null;const n=M(e[0]).toLowerCase(),r=new Date(M(e[1])),s=new Date(M(e[2])),o=s.getTime()-r.getTime();return n==="day"?Math.trunc(o/864e5):n==="hour"?Math.trunc(o/36e5):n==="minute"?Math.trunc(o/6e4):n==="second"?Math.trunc(o/1e3):n==="year"?s.getFullYear()-r.getFullYear():n==="month"?(s.getFullYear()-r.getFullYear())*12+(s.getMonth()-r.getMonth()):Math.trunc(o/1e3)}case"justify_days":return e[0]===null?null:e[0];case"justify_hours":return e[0]===null?null:e[0];case"justify_interval":return e[0]===null?null:e[0];case"statement_timestamp":case"transaction_timestamp":return new Date().toISOString();case"to_char":{if(e[0]===null)return null;if(e.length>=2&&e[1]!=null){const n=e[0],r=M(e[1]);if(typeof n=="number"){if(r.includes("FM"))return String(n);if(r.includes("9")||r.includes("0")){const s=(((t=r.match(/\.([09]+)/))==null?void 0:t[1])??"").length;return n.toFixed(s)}}if(typeof n=="string"||n instanceof Date){const s=new Date(M(n));let o=r;return o=o.replace(/YYYY/g,String(s.getFullYear())),o=o.replace(/MM/g,String(s.getMonth()+1).padStart(2,"0")),o=o.replace(/DD/g,String(s.getDate()).padStart(2,"0")),o=o.replace(/HH24/g,String(s.getHours()).padStart(2,"0")),o=o.replace(/HH/g,String(s.getHours()%12||12).padStart(2,"0")),o=o.replace(/MI/g,String(s.getMinutes()).padStart(2,"0")),o=o.replace(/SS/g,String(s.getSeconds()).padStart(2,"0")),o}}return M(e[0])}case"to_number":{if(e[0]===null)return null;const n=M(e[0]).replace(/[^0-9eE.+-]/g,"");return Number(n)}case"to_date":case"to_timestamp":return e[0]===null?null:new Date(M(e[0])).toISOString();case"array_length":return e[0]===null?null:Array.isArray(e[0])?e[0].length:null;case"unnest":return e[0];case"array_agg":return e;case"array_cat":return e[0]===null||e[1]===null?null:[...e[0],...e[1]];case"array_append":return e[0]===null?null:[...e[0],e[1]];case"array_prepend":return e[1]===null?null:[e[0],...e[1]];case"json_build_object":case"jsonb_build_object":{const n={};for(let r=0;r+1<e.length;r+=2)n[M(e[r])]=e[r+1]??null;return n}case"json_array_length":case"jsonb_array_length":if(e[0]===null)return null;if(Array.isArray(e[0]))return e[0].length;if(typeof e[0]=="string"){const n=JSON.parse(e[0]);return Array.isArray(n)?n.length:null}return null;case"json_typeof":case"jsonb_typeof":return e[0]===null?"null":Array.isArray(e[0])?"array":typeof e[0]=="object"?"object":typeof e[0];case"row_to_json":return e[0];case"to_json":case"to_jsonb":return e[0];case"jsonb_pretty":{if(e[0]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0];return JSON.stringify(n,null,2)}case"jsonb_agg":case"json_agg":return e;case"jsonb_object_agg":case"json_object_agg":if(e.length>=2){const n={};return n[M(e[0])]=e[1],n}return{};case"jsonb_concat":{if(e[0]===null||e[1]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):e[0],r=typeof e[1]=="string"?JSON.parse(e[1]):e[1];return Array.isArray(n)&&Array.isArray(r)?[...n,...r]:typeof n=="object"&&typeof r=="object"&&!Array.isArray(n)&&!Array.isArray(r)?{...n,...r}:n}case"jsonb_delete_path":{if(e[0]===null||e[1]===null)return null;const n=typeof e[0]=="string"?JSON.parse(e[0]):JSON.parse(JSON.stringify(e[0])),r=Array.isArray(e[1])?e[1]:M(e[1]).replace(/^\{/,"").replace(/\}$/,"").split(",").map(i=>i.trim());if(r.length===0)return n;let s=n;for(let i=0;i<r.length-1;i++)if(typeof s=="object"&&s!==null&&!Array.isArray(s))s=s[r[i]];else if(Array.isArray(s))s=s[Number(r[i])];else return n;const o=r[r.length-1];return typeof s=="object"&&s!==null&&!Array.isArray(s)?delete s[o]:Array.isArray(s)&&s.splice(Number(o),1),n}case"current_schema":case"current_schemas":return"public";case"current_database":return"uqa";case"current_user":case"session_user":return"uqa_user";case"version":return"UQA 1.0";case"has_table_privilege":case"has_schema_privilege":case"has_column_privilege":return!0;case"txid_current":return 1;case"text_match":case"bayesian_match":{if(e.length<2)return!1;const n=e[0],r=e[1];return n===null||r===null?!1:yr(String(n),String(r))}default:throw new Error(`Unknown SQL function: ${c}`)}}function L(c,e){return c[e]??null}function Z(c,e){const t=c[e];return t==null?"":M(t)}function Mi(c){return c}function se(c){return Array.isArray(c)?c:[]}function Bt(c,e){if(e==null)return!0;if(c==null)return!1;if(typeof e!="object")return c===e;if(Array.isArray(e)){if(!Array.isArray(c))return!1;for(const t of e)if(!c.some(n=>Bt(n,t)))return!1;return!0}if(typeof c!="object"||Array.isArray(c))return!1;for(const[t,n]of Object.entries(e))if(!(t in c)||!Bt(c[t],n))return!1;return!0}function Et(c,e){let t="^";for(let n=0;n<c.length;n++){const r=c[n];r==="%"?t+=".*":r==="_"?t+=".":r==="\\"&&n+1<c.length?(n++,t+=c[n].replace(/[.*+?^${}()|[\]\\]/g,"\\$&")):t+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}return t+="$",new RegExp(t,e?"is":"s")}function to(c,e){if(c===null)return null;const t=e.toLowerCase();if(t==="integer"||t==="int"||t==="int4"||t==="bigint"||t==="int8"||t==="smallint"||t==="int2")return Math.trunc(Number(c));if(t==="float"||t==="float4"||t==="float8"||t==="double precision"||t==="real"||t==="numeric"||t==="decimal")return Number(c);if(t==="text"||t==="varchar"||t==="char"||t==="character varying")return M(c);if(t==="boolean"||t==="bool"){if(typeof c=="string"){const n=c.toLowerCase();return n==="true"||n==="t"||n==="1"||n==="yes"}return!!c}return t==="json"||t==="jsonb"?typeof c=="string"?JSON.parse(c):c:t==="date"||t==="timestamp"||t==="timestamptz"?new Date(M(c)).toISOString():c}class ie{constructor(e){b(this,"_params");b(this,"_sequences");b(this,"_outerRow");b(this,"_subqueryExecutor");this._params=(e==null?void 0:e.params)??[],this._sequences=(e==null?void 0:e.sequences)??null,this._outerRow=(e==null?void 0:e.outerRow)??null,this._subqueryExecutor=(e==null?void 0:e.subqueryExecutor)??null}evaluate(e,t){const n=Object.keys(e);if(n.length===0)return null;const r=n[0],s=e[r];switch(r){case"ColumnRef":return this._evalColumnRef(s,t);case"A_Const":return this._evalConst(s);case"A_Expr":return this._evalAExpr(s,t);case"BoolExpr":return this._evalBoolExpr(s,t);case"FuncCall":return this._evalFuncCall(s,t);case"NullTest":return this._evalNullTest(s,t);case"CaseExpr":return this._evalCaseExpr(s,t);case"NamedArgExpr":{const o=L(s,"arg");return o!=null?this.evaluate(o,t):null}case"TypeCast":return this._evalTypeCast(s,t);case"ParamRef":return this._evalParamRef(s);case"SubLink":return this._evalSubLink(s,t);case"CoalesceExpr":return this._evalCoalesceExpr(s,t);case"MinMaxExpr":return this._evalMinMaxExpr(s,t);case"BooleanTest":return this._evalBooleanTest(s,t);case"SQLValueFunction":return this._evalSQLValueFunction(s);case"A_ArrayExpr":return se(L(s,"elements")).map(o=>this.evaluate(o,t));case"List":return se(L(s,"items")).map(o=>this.evaluate(o,t));case"String":case"str":return Z(s,"sval")||Z(s,"str");case"Integer":return L(s,"ival")??0;case"Float":return Number(Z(s,"fval")||Z(s,"str"));default:return"ival"in e?e.ival:"fval"in e?Number(e.fval):"sval"in e?e.sval:"boolval"in e?e.boolval:"bsval"in e?e.bsval:e}}_evalColumnRef(e,t){const n=se(L(e,"fields"));if(n.length===0)return null;const r=[];for(const s of n){const o=L(s,"String")??L(s,"str");if(o!==null&&typeof o=="object"){const i=Z(o,"sval")||Z(o,"str");i&&r.push(i)}else if(typeof o=="string")r.push(o);else if(typeof s=="object"){const i=Z(s,"sval")||Z(s,"str");i&&r.push(i)}}if(r.length===1){const s=r[0];return s in t?t[s]:this._outerRow!==null&&s in this._outerRow?this._outerRow[s]:null}if(r.length===2){const s=`${r[0]}.${r[1]}`;if(s in t)return t[s];if(this._outerRow!==null&&s in this._outerRow)return this._outerRow[s];const o=r[1];return o in t?t[o]:this._outerRow!==null&&o in this._outerRow?this._outerRow[o]:null}return null}_evalConst(e){if(L(e,"isnull")===!0)return null;const t=L(e,"ival");if(t!=null){if(typeof t=="object"){const h=L(t,"ival");return h??(typeof t=="object"&&Object.keys(t).length===0?0:t)}return t}const n=L(e,"fval");if(n!=null)return Number(typeof n=="object"?L(n,"fval")??n:n);const r=L(e,"sval");if(r!=null)return typeof r=="object"?L(r,"sval")??r:r;const s=L(e,"boolval");if(s!=null)return typeof s=="object"?L(s,"boolval")??s:s;const o=L(e,"bsval");if(o!=null)return typeof o=="object"?L(o,"bsval")??o:o;const i=L(e,"Integer");if(i!=null)return L(i,"ival")??0;const a=L(e,"Float");if(a!=null)return Number(Z(a,"fval")||Z(a,"str"));const l=L(e,"String");if(l!=null)return Z(l,"sval")||Z(l,"str");const u=L(e,"Null");return u!=null,null}_evalAExpr(e,t){const n=L(e,"kind");let r;typeof n=="number"?r=n:typeof n=="string"?r={AEXPR_OP:0,AEXPR_OP_ANY:1,AEXPR_OP_ALL:2,AEXPR_DISTINCT:3,AEXPR_NOT_DISTINCT:4,AEXPR_NULLIF:5,AEXPR_IN:6,AEXPR_LIKE:7,AEXPR_ILIKE:8,AEXPR_SIMILAR:9,AEXPR_BETWEEN:10,AEXPR_NOT_BETWEEN:11,AEXPR_BETWEEN_SYM:12,AEXPR_NOT_BETWEEN_SYM:13,AEXPR_PAREN:14}[n]??0:r=0;const s=se(L(e,"name"));let o="";for(const h of s){const f=L(h,"String")??L(h,"str");if(f!==null&&typeof f=="object")o=Z(f,"sval")||Z(f,"str");else if(typeof f=="string")o=f;else{const d=Z(h,"sval")||Z(h,"str");d&&(o=d)}}const i=L(e,"lexpr"),a=L(e,"rexpr");if(r===10||r===11){const h=this.evaluate(i,t),f=a,d=L(f,"List"),p=L(d!==null?d:f,"items"),m=se(p??a);if(m.length>=2){const _=this.evaluate(m[0],t),y=this.evaluate(m[1],t);if(h===null||_===null||y===null)return null;const x=h>=_&&h<=y;return r===11?!x:x}return null}if(r===7||r===8){const h=this.evaluate(i,t),f=this.evaluate(a,t);if(h===null||f===null)return null;const p=Et(M(f),r===8).test(M(h));return o==="!~~"||o==="!~~*"?!p:p}if(r===9){const h=this.evaluate(i,t),f=this.evaluate(a,t);if(h===null||f===null)return null;let d=M(f);return d=d.replace(/%/g,".*").replace(/_/g,"."),new RegExp("^"+d+"$").test(M(h))}if(r===12||r===13){const h=this.evaluate(i,t),f=a,d=L(f,"List"),p=L(d!==null?d:f,"items"),m=se(p??a);if(m.length>=2){const _=this.evaluate(m[0],t),y=this.evaluate(m[1],t);if(h===null||_===null||y===null)return null;const x=_<y?_:y,v=_>=y?_:y,E=h>=x&&h<=v;return r===13?!E:E}return null}if(r===1){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null||f===null?null:(Array.isArray(f)?f:[f]).some(p=>this._applyOp(o,h,p)===!0)}if(r===2){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null||f===null?null:(Array.isArray(f)?f:[f]).every(p=>this._applyOp(o,h,p)===!0)}if(r===3){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null&&f===null?!1:h===null||f===null?!0:h!==f}if(r===4){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===null&&f===null?!0:h===null||f===null?!1:h===f}if(r===5){const h=this.evaluate(i,t),f=this.evaluate(a,t);return h===f?null:h}if(r===6){const h=this.evaluate(i,t);if(h===null)return null;const f=a,d=L(f,"List"),p=se(d!==null?L(d,"items"):a);let m;if(p.length>0)m=p.map(_=>this.evaluate(_,t));else{const _=this.evaluate(f,t);m=Array.isArray(_)?_:[_]}return m.some(_=>_==h)}const l=i!==null?this.evaluate(i,t):null,u=a!==null?this.evaluate(a,t):null;return this._applyOp(o,l,u)}_applyOp(e,t,n){if(e==="+")return t===null||n===null?null:typeof t=="string"||typeof n=="string"?M(t)+M(n):t+n;if(e==="-")return t===null||n===null?null:t-n;if(e==="*")return t===null||n===null?null:t*n;if(e==="/"){if(t===null||n===null)return null;const r=n;if(r===0)throw new Error("Division by zero");return t/r}if(e==="%")return t===null||n===null?null:t%n;if(e==="^")return t===null||n===null?null:Math.pow(t,n);if(e==="=")return t===null||n===null?null:t===n;if(e==="<>"||e==="!=")return t===null||n===null?null:t!==n;if(e==="<")return t===null||n===null?null:t<n;if(e===">")return t===null||n===null?null:t>n;if(e==="<=")return t===null||n===null?null:t<=n;if(e===">=")return t===null||n===null?null:t>=n;if(e==="||")return t===null||n===null?null:M(t)+M(n);if(e==="~~")return t===null||n===null?null:Et(M(n),!1).test(M(t));if(e==="!~~")return t===null||n===null?null:!Et(M(n),!1).test(M(t));if(e==="~~*")return t===null||n===null?null:Et(M(n),!0).test(M(t));if(e==="!~~*")return t===null||n===null?null:!Et(M(n),!0).test(M(t));if(e==="~")return t===null||n===null?null:new RegExp(M(n)).test(M(t));if(e==="~*")return t===null||n===null?null:new RegExp(M(n),"i").test(M(t));if(e==="!~")return t===null||n===null?null:!new RegExp(M(n)).test(M(t));if(e==="!~*")return t===null||n===null?null:!new RegExp(M(n),"i").test(M(t));if(e==="&")return t===null||n===null?null:t&n;if(e==="|")return t===null||n===null?null:t|n;if(e==="#")return t===null||n===null?null:t^n;if(e==="<<")return t===null||n===null?null:t<<n;if(e===">>")return t===null||n===null?null:t>>n;if(e==="->"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;return typeof n=="number"&&Array.isArray(r)?r[n]??null:typeof r=="object"&&r!==null&&!Array.isArray(r)?r[M(n)]??null:null}if(e==="->>"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;if(typeof n=="number"&&Array.isArray(r)){const s=r[n];return s==null?null:typeof s=="object"?JSON.stringify(s):M(s)}if(typeof r=="object"&&r!==null&&!Array.isArray(r)){const s=r[M(n)];return s==null?null:typeof s=="object"?JSON.stringify(s):M(s)}return null}if(e==="#>"){if(t===null||n===null)return null;let r=typeof t=="string"?JSON.parse(t):t;const s=Array.isArray(n)?n:M(n).replace(/^\{/,"").replace(/\}$/,"").split(",").map(o=>o.trim());for(const o of s){if(r==null)return null;if(Array.isArray(r))r=r[Number(o)];else if(typeof r=="object")r=r[M(o)];else return null}return r??null}if(e==="#>>"){if(t===null||n===null)return null;const r=this._applyOp("#>",t,n);return r==null?null:typeof r=="object"?JSON.stringify(r):M(r)}if(e==="@>"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=typeof n=="string"?JSON.parse(n):n;return Bt(r,s)}if(e==="<@"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=typeof n=="string"?JSON.parse(n):n;return Bt(s,r)}if(e==="?"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t;return typeof r=="object"&&r!==null&&!Array.isArray(r)?M(n)in r:Array.isArray(r)?r.includes(M(n)):!1}if(e==="?|"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=Array.isArray(n)?n:[M(n)];return typeof r=="object"&&r!==null&&!Array.isArray(r)?s.some(o=>o in r):!1}if(e==="?&"){if(t===null||n===null)return null;const r=typeof t=="string"?JSON.parse(t):t,s=Array.isArray(n)?n:[M(n)];return typeof r=="object"&&r!==null&&!Array.isArray(r)?s.every(o=>o in r):!1}if(e==="&&"){if(t===null||n===null)return null;if(Array.isArray(t)&&Array.isArray(n)){const r=new Set(n);return t.some(s=>r.has(s))}return!1}if(e==="@@"){if(t===null||n===null)return!1;const r=String(t).toLowerCase(),s=String(n);return yr(r,s)}throw new Error(`Unsupported operator: "${e}"`)}_evalBoolExpr(e,t){const n=L(e,"boolop"),r=se(L(e,"args"));if(n===0||n==="BOOL_AND"||n==="AND_EXPR"){let s=!0;for(const o of r){const i=this.evaluate(o,t);if(i===!1)return!1;i===null&&(s=null)}return s}if(n===1||n==="BOOL_OR"||n==="OR_EXPR"){let s=!1;for(const o of r){const i=this.evaluate(o,t);if(i===!0)return!0;i===null&&(s=null)}return s}if(n===2||n==="BOOL_NOT"||n==="NOT_EXPR"){const s=this.evaluate(r[0],t);return s===null?null:!s}throw new Error(`Unknown BoolExpr boolop: ${M(n)}`)}_evalFuncCall(e,t){const n=se(L(e,"funcname")),r=[];for(const l of n){const u=L(l,"String")??L(l,"str");if(u!==null&&typeof u=="object"){const h=Z(u,"sval")||Z(u,"str");h&&r.push(h)}else if(typeof u=="string")r.push(u);else{const h=Z(l,"sval")||Z(l,"str");h&&r.push(h)}}let s=r.join(".").toLowerCase();if(s.startsWith("pg_catalog.")&&(s=s.slice(11)),new Set(["count","sum","avg","min","max","string_agg","array_agg","bool_and","bool_or","stddev","stddev_pop","stddev_samp","variance","var_pop","var_samp","corr","covar_pop","covar_samp","regr_slope","regr_intercept","regr_r2","regr_count","regr_avgx","regr_avgy","regr_sxx","regr_syy","regr_sxy"]).has(s)){const l=L(e,"agg_star")===!0,u=se(L(e,"args"));let h;if(l||u.length===0)h=`${s}(*)`;else try{const d=L(u[0],"ColumnRef");if(d){const p=se(L(d,"fields")),m=[];for(const _ of p){const y=Z(_,"sval")||Z(_,"str");y&&m.push(y)}h=`${s}(${m.join(".")})`}else h=s}catch{h=s}if(h in t)return t[h];const f=`__having_agg_${JSON.stringify({FuncCall:e})}`;if(f in t)return t[f]}if(s==="nextval"&&this._sequences!==null){const l=se(L(e,"args")),u=l.length>0?M(this.evaluate(l[0],t)):"",h=this._sequences.get(u);if(h)return h.current+=h.increment,h.current;throw new Error(`Sequence not found: "${u}"`)}if(s==="currval"&&this._sequences!==null){const l=se(L(e,"args")),u=l.length>0?M(this.evaluate(l[0],t)):"",h=this._sequences.get(u);if(h)return h.current;throw new Error(`Sequence not found: "${u}"`)}if(s==="setval"&&this._sequences!==null){const l=se(L(e,"args"));if(l.length<2)throw new Error("setval() requires at least 2 arguments");const u=M(this.evaluate(l[0],t)),h=Number(this.evaluate(l[1],t)),f=this._sequences.get(u);if(f){const d=l.length>=3?!!this.evaluate(l[2],t):!0;return f.current=d?h:h-f.increment,h}throw new Error(`Sequence not found: "${u}"`)}if(s==="lastval"&&this._sequences!==null){let l=null;for(const u of this._sequences.values())(l===null||u.current>l)&&(l=u.current);if(l===null)throw new Error("lastval is not yet defined in this session");return l}if(L(e,"agg_star")===!0)return 1;const i=se(L(e,"args"));if(s==="make_interval"&&i.some(u=>L(u,"NamedArgExpr")!==null&&L(u,"NamedArgExpr")!==void 0)){const u={years:0,months:0,weeks:0,days:0,hours:0,mins:0,secs:0};for(const h of i){const f=L(h,"NamedArgExpr");if(f!=null){const d=f,p=(Z(d,"name")||"").toLowerCase(),m=L(d,"arg"),_=m!==null?Number(this.evaluate(m,t)):0;p in u&&(u[p]=_)}}return In(s,[u.years,u.months,u.weeks,u.days,u.hours,u.mins,u.secs])}const a=i.map(l=>this.evaluate(l,t));return In(s,a)}_evalNullTest(e,t){const n=L(e,"arg"),r=L(e,"nulltesttype"),s=this.evaluate(n,t);return r===0||r==="IS_NULL"?s==null:s!=null}_evalSQLValueFunction(e){const t=L(e,"op"),n=typeof t=="string"?t:"";if(n==="SVFOP_CURRENT_DATE"){const r=new Date,s=String(r.getFullYear()),o=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");return`${s}-${o}-${i}`}if(n==="SVFOP_CURRENT_TIMESTAMP"||n==="SVFOP_CURRENT_TIMESTAMP_N")return new Date().toISOString();if(n==="SVFOP_CURRENT_TIME"||n==="SVFOP_CURRENT_TIME_N"){const r=new Date,s=String(r.getHours()).padStart(2,"0"),o=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${s}:${o}:${i}`}if(n==="SVFOP_LOCALTIME"||n==="SVFOP_LOCALTIME_N"){const r=new Date,s=String(r.getHours()).padStart(2,"0"),o=String(r.getMinutes()).padStart(2,"0"),i=String(r.getSeconds()).padStart(2,"0");return`${s}:${o}:${i}`}if(n==="SVFOP_LOCALTIMESTAMP"||n==="SVFOP_LOCALTIMESTAMP_N")return new Date().toISOString();if(n==="SVFOP_CURRENT_ROLE"||n==="SVFOP_CURRENT_USER")return"current_user";if(n==="SVFOP_SESSION_USER")return"session_user";if(n==="SVFOP_USER")return"current_user";if(n==="SVFOP_CURRENT_CATALOG")return"uqa";if(n==="SVFOP_CURRENT_SCHEMA")return"public";throw new Error(`Unsupported SQLValueFunction op: ${n}`)}_evalCaseExpr(e,t){const n=L(e,"arg"),r=n!=null?this.evaluate(n,t):null,s=se(L(e,"args"));for(const i of s){const a=L(i,"CaseWhen")??i,l=L(a,"expr"),u=L(a,"result");if(r!==null){const h=this.evaluate(l,t);if(r===h)return this.evaluate(u,t)}else if(this.evaluate(l,t)===!0)return this.evaluate(u,t)}const o=L(e,"defresult");return o!=null?this.evaluate(o,t):null}_evalTypeCast(e,t){const n=L(e,"arg"),r=L(e,"typeName"),s=this.evaluate(n,t),o=r,i=se(L(o,"names"));let a="";for(const l of i){const u=L(l,"String")??L(l,"str");if(u!==null&&typeof u=="object"){const h=Z(u,"sval")||Z(u,"str");h&&h!=="pg_catalog"&&(a=h)}else if(typeof u=="string"&&u!=="pg_catalog")a=u;else{const h=Z(l,"sval")||Z(l,"str");h&&h!=="pg_catalog"&&(a=h)}}return a?to(s,a):s}_evalParamRef(e){const t=L(e,"number"),n=typeof t=="number"?t:0;if(n>0&&n<=this._params.length)return this._params[n-1];if(n>0&&n>this._params.length)throw new Error(`No value supplied for parameter $${String(n)}`);return null}_evalSubLink(e,t){if(this._subqueryExecutor===null)throw new Error("SubLink (subquery) evaluation requires a subqueryExecutor callback");const n=L(e,"subLinkType"),r=L(e,"subselect"),s=L(r,"SelectStmt")??r,o=this._subqueryExecutor(s,t);if(n===0||n==="EXISTS_SUBLINK")return o.rows.length>0;if(n===1||n==="ALL_SUBLINK"){const i=L(e,"testexpr"),a=this.evaluate(i,t),l=this._extractSubLinkOperator(e),u=o.columns[0];for(const h of o.rows){const f=h[u];if(!this._compareValues(a,l,f))return!1}return!0}if(n===2||n==="ANY_SUBLINK"){const i=L(e,"testexpr"),a=this.evaluate(i,t);if(o.columns.length===0)return!1;const l=o.columns[0],u=this._extractSubLinkOperator(e);for(const h of o.rows){const f=h[l];if(this._compareValues(a,u,f))return!0}return!1}if(n===4||n==="EXPR_SUBLINK"){if(o.rows.length===0)return null;const i=o.columns[0];return o.rows[0][i]??null}throw new Error(`Unsupported SubLink type: ${String(n)}`)}_extractSubLinkOperator(e){const t=se(L(e,"operName"));if(t.length>0){const n=t[0],r=L(n,"str");if(r!=null)return String(r);const s=L(L(n,"String")??n,"sval");if(s!=null)return String(s)}return"="}_compareValues(e,t,n){switch(t){case"=":return e==n;case"<>":case"!=":return e!=n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return e===n}}_evalCoalesceExpr(e,t){const n=se(L(e,"args"));for(const r of n){const s=this.evaluate(r,t);if(s!=null)return s}return null}_evalMinMaxExpr(e,t){const n=L(e,"op"),s=se(L(e,"args")).map(o=>this.evaluate(o,t)).filter(o=>o!=null);return s.length===0?null:n===0||n==="IS_GREATEST"?s.reduce((o,i)=>o>i?o:i):s.reduce((o,i)=>o<i?o:i)}_evalBooleanTest(e,t){const n=L(e,"arg"),r=L(e,"booltesttype"),s=this.evaluate(n,t);switch(r){case 0:case"IS_TRUE":return s===!0;case 1:case"IS_NOT_TRUE":return s!==!0;case 2:case"IS_FALSE":return s===!1;case 3:case"IS_NOT_FALSE":return s!==!1;case 4:case"IS_UNKNOWN":return s==null;case 5:case"IS_NOT_UNKNOWN":return s!=null;default:throw new Error(`Unknown BooleanTest type: ${M(r)}`)}}}function Ie(c,e,t){return{name:c,typeName:e,pythonType:(t==null?void 0:t.pythonType)??"string",primaryKey:(t==null?void 0:t.primaryKey)??!1,notNull:(t==null?void 0:t.notNull)??!1,autoIncrement:(t==null?void 0:t.autoIncrement)??!1,defaultValue:(t==null?void 0:t.defaultValue)??null,vectorDimensions:(t==null?void 0:t.vectorDimensions)??null,unique:(t==null?void 0:t.unique)??!1,numericPrecision:(t==null?void 0:t.numericPrecision)??null,numericScale:(t==null?void 0:t.numericScale)??null}}const wr=new Map([["INT",["integer","number"]],["INTEGER",["integer","number"]],["SERIAL",["integer","number"]],["BIGINT",["integer","number"]],["BIGSERIAL",["integer","number"]],["SMALLINT",["integer","number"]],["SMALLSERIAL",["integer","number"]],["INT2",["integer","number"]],["INT4",["integer","number"]],["INT8",["integer","number"]],["FLOAT",["float","number"]],["FLOAT4",["float","number"]],["FLOAT8",["float","number"]],["DOUBLE",["float","number"]],["DOUBLE PRECISION",["float","number"]],["REAL",["float","number"]],["NUMERIC",["float","number"]],["DECIMAL",["float","number"]],["TEXT",["text","string"]],["VARCHAR",["text","string"]],["CHAR",["text","string"]],["CHARACTER",["text","string"]],["CHARACTER VARYING",["text","string"]],["NAME",["text","string"]],["BOOLEAN",["boolean","boolean"]],["BOOL",["boolean","boolean"]],["DATE",["date","string"]],["TIME",["time","string"]],["TIMESTAMP",["timestamp","string"]],["TIMESTAMPTZ",["timestamp","string"]],["TIMESTAMP WITH TIME ZONE",["timestamp","string"]],["TIMESTAMP WITHOUT TIME ZONE",["timestamp","string"]],["INTERVAL",["interval","string"]],["VECTOR",["vector","object"]],["POINT",["point","object"]],["JSON",["json","object"]],["JSONB",["json","object"]],["BYTEA",["bytea","object"]],["ARRAY",["array","array"]],["UUID",["text","string"]]]);function xr(c,e){const t=c[c.length-1].toLowerCase();if(t==="vector")return["vector","object"];if(t==="point")return["point","object"];const n=c.map(o=>o.toUpperCase()).join(" "),r=wr.get(n);if(r)return[r[0],r[1]];const s=c[0];if(s!==void 0){const o=wr.get(s.toUpperCase());if(o)return[o[0],o[1]]}return["text","string"]}function no(c){return typeof c=="object"&&c!==null?c:typeof c=="string"?JSON.parse(c):c}function ro(c){return c instanceof Uint8Array?c:typeof c=="string"?new TextEncoder().encode(c):new TextEncoder().encode(String(c))}function so(c){return Array.isArray(c)?c:typeof c=="string"?JSON.parse(c):[c]}function oo(c,e){const t=typeof c=="number"?c:Number(c),n=Math.pow(10,e);return Math.round(t*n)/n}const io=100,ao=10;class Ut{constructor(e,t,n){b(this,"name");b(this,"columns");b(this,"primaryKey");b(this,"checkConstraints");b(this,"foreignKeys");b(this,"fkInsertValidators");b(this,"fkDeleteValidators");b(this,"fkUpdateValidators");b(this,"documentStore");b(this,"invertedIndex");b(this,"vectorIndexes");b(this,"spatialIndexes");b(this,"_stats");b(this,"_nextDocId");b(this,"_uniqueIndexes");b(this,"_uniqueIndexesBuilt");this.name=e,this.columns=new Map,this.checkConstraints=[],this.foreignKeys=[],this.fkInsertValidators=[],this.fkDeleteValidators=[],this.fkUpdateValidators=[],this._stats=new Map,this._nextDocId=1,this.vectorIndexes=new Map,this.spatialIndexes=new Map,this._uniqueIndexes=new Map,this._uniqueIndexesBuilt=!1;let r=null;for(const s of t)this.columns.set(s.name,s),s.primaryKey&&(r=s.name);this.primaryKey=r,this.documentStore=new or,this.invertedIndex=new ir;for(const s of t)s.typeName==="vector"&&s.vectorDimensions!==null&&this.vectorIndexes.set(s.name,new lr(s.vectorDimensions)),s.typeName==="point"&&this.spatialIndexes.set(s.name,new Ps(this.name,s.name))}get columnNames(){return[...this.columns.keys()]}get rowCount(){return this.documentStore.length}insert(e){let t;if(this.primaryKey!==null)if(this.columns.get(this.primaryKey).autoIncrement)(!(this.primaryKey in e)||e[this.primaryKey]===null||e[this.primaryKey]===void 0)&&(e[this.primaryKey]=this._nextDocId),t=e[this.primaryKey],this._nextDocId=Math.max(this._nextDocId,t+1);else{if(!(this.primaryKey in e)||e[this.primaryKey]===null||e[this.primaryKey]===void 0)throw new Error(`Missing primary key '${this.primaryKey}' for table '${this.name}'`);const l=e[this.primaryKey];typeof l=="number"?(t=l,this._nextDocId=Math.max(this._nextDocId,t+1)):(t=this._nextDocId,this._nextDocId++)}else t=this._nextDocId,this._nextDocId++;for(const[a,l]of this.columns)if(l.notNull&&!l.autoIncrement){const u=e[a];if(u==null)if(l.defaultValue!==null&&l.defaultValue!==void 0)e[a]=l.defaultValue;else throw new Error(`NOT NULL constraint violated: column '${a}' in table '${this.name}'`)}this._buildUniqueIndexes();for(const[a,l]of this.columns){if(!(l.unique||l.primaryKey)||l.autoIncrement)continue;const u=e[a];if(u==null)continue;const h=this._uniqueIndexes.get(a);if(h!==void 0&&h.has(u))throw new Error(`UNIQUE constraint violated: duplicate value '${String(u)}' for column '${a}' in table '${this.name}'`)}for(const[a,l]of this.checkConstraints)if(!l(e))throw new Error(`CHECK constraint '${a}' violated in table '${this.name}'`);for(const a of this.fkInsertValidators)a(e);for(const a of Object.keys(e))if(!this.columns.has(a))throw new Error(`Unknown column '${a}' for table '${this.name}'`);const n={},r={},s={};for(const[a,l]of this.columns){const u=e[a];if(u!=null)if(l.vectorDimensions!==null){const h=u instanceof Float64Array?u:new Float64Array(u);n[a]=Array.from(h),r[a]=h}else if(l.typeName==="point"){const h=u;let f,d;if(Array.isArray(h))f=h[0],d=h[1];else if(typeof h=="object"&&"x"in h)f=h.x,d=h.y;else throw new Error(`POINT column '${a}' requires [x, y] (2 elements), got ${JSON.stringify(h)}`);n[a]=[f,d],s[a]=[f,d]}else l.typeName==="json"||l.typeName==="jsonb"?n[a]=no(u):l.typeName.endsWith("[]")?n[a]=so(u):l.typeName==="bytea"?n[a]=ro(u):l.numericScale!==null?n[a]=oo(u,l.numericScale):l.pythonType==="number"?n[a]=Number(u):l.pythonType==="boolean"?n[a]=!!u:l.pythonType==="string"?n[a]=String(u):n[a]=u;else l.defaultValue!==null&&l.defaultValue!==void 0&&(n[a]=l.defaultValue)}this.documentStore.put(t,n);let o=null;const i={};for(const[a,l]of Object.entries(n))typeof l=="string"&&(i[a]=l);Object.keys(i).length>0&&(o=this.invertedIndex.addDocument(t,i));for(const[a,l]of Object.entries(r)){const u=this.vectorIndexes.get(a);u!==void 0&&u.add(t,l)}for(const[a,[l,u]]of Object.entries(s)){const h=this.spatialIndexes.get(a);h!==void 0&&h.add(t,l,u)}for(const[a,l]of this._uniqueIndexes){const u=n[a];u!=null&&l.set(u,t)}return[t,o]}_buildUniqueIndexes(){if(this._uniqueIndexesBuilt)return;this._uniqueIndexesBuilt=!0;const e=[];for(const[t,n]of this.columns)(n.unique||n.primaryKey)&&!n.autoIncrement&&(e.push(t),this._uniqueIndexes.set(t,new Map));if(e.length!==0)for(const t of this.documentStore.docIds)for(const n of e){const r=this.documentStore.getField(t,n);r!=null&&this._uniqueIndexes.get(n).set(r,t)}}removeFromUniqueIndexes(e){for(const[t,n]of this._uniqueIndexes){const r=this.documentStore.getField(e,t);r!=null&&n.delete(r)}}analyze(){const e=[...this.documentStore.docIds].sort((i,a)=>i-a),t=e.length,n=[...this.columns.keys()],r=new Map,s=new Map;for(const i of n)r.set(i,[]),s.set(i,0);for(const i of e){const a=this.documentStore.get(i);for(const l of n){const u=a!==null?a[l]??null:null;u===null?s.set(l,(s.get(l)??0)+1):r.get(l).push(u)}}const o=new Map;for(const i of n){const a=r.get(i),l=s.get(i),u=new Set(a.map(y=>typeof y=="object"?JSON.stringify(y):String(y))).size,h=a.filter(y=>typeof y=="number"||typeof y=="string");let f=null,d=null;h.length>0&&(f=h.reduce((y,x)=>y<x?y:x),d=h.reduce((y,x)=>y>x?y:x));const p=lo(h),[m,_]=co(a,t);o.set(i,{distinctCount:u,nullCount:l,minValue:f,maxValue:d,rowCount:t,histogram:p,mcvValues:m,mcvFrequencies:_})}return this._stats=o,new Map(o)}getColumnStats(e){return this._stats.get(e)??null}}function lo(c){if(c.length===0)return[];try{const e=[...c].sort((s,o)=>typeof s=="number"&&typeof o=="number"?s-o:String(s).localeCompare(String(o))),t=e.length,n=Math.min(io,t);if(n<=1)return[e[0],e[t-1]];const r=[e[0]];for(let s=1;s<n;s++){const o=Math.floor(s*t/n),i=e[o];i!==r[r.length-1]&&r.push(i)}return r[r.length-1]!==e[t-1]&&r.push(e[t-1]),r}catch{return[]}}function co(c,e){if(c.length===0||e<=0)return[[],[]];const t=new Map;for(const i of c){const a=typeof i=="object"?JSON.stringify(i):String(i),l=t.get(a);l!==void 0?l.count++:t.set(a,{value:i,count:1})}const n=t.size;if(n<=0)return[[],[]];const r=1/n,o=[...t.values()].sort((i,a)=>a.count-i.count).slice(0,ao).filter(i=>i.count/e>r);return o.length===0?[[],[]]:[o.map(i=>i.value),o.map(i=>i.count/e)]}function ne(c){return{subgraphVertices:(c==null?void 0:c.subgraphVertices)??new Set,subgraphEdges:(c==null?void 0:c.subgraphEdges)??new Set,score:(c==null?void 0:c.score)??0,graphName:(c==null?void 0:c.graphName)??""}}class W extends D{constructor(t,n){super(t);b(this,"_graphPayloads");this._graphPayloads=new Map(n??[])}setGraphPayload(t,n){this._graphPayloads.set(t,n)}getGraphPayload(t){return this._graphPayloads.get(t)??null}get graphPayloads(){return this._graphPayloads}toPostingList(){const t=[];for(const n of this){const r=this._graphPayloads.get(n.docId),s={...n.payload.fields};r&&(s._subgraph_vertices=[...r.subgraphVertices],s._subgraph_edges=[...r.subgraphEdges],s._graph_score=r.score,s._graph_name=r.graphName),t.push({docId:n.docId,payload:U({positions:n.payload.positions,score:r?r.score:n.payload.score,fields:s})})}return new D(t)}static fromPostingList(t){const n=[],r=new Map;for(const s of t){n.push(s);const o=s.payload.fields,i=o._subgraph_vertices,a=o._subgraph_edges,l=o._graph_score,u=o._graph_name;(i!==void 0||a!==void 0)&&r.set(s.docId,ne({subgraphVertices:new Set(Array.isArray(i)?i:[]),subgraphEdges:new Set(Array.isArray(a)?a:[]),score:typeof l=="number"?l:s.payload.score,graphName:typeof u=="string"?u:""}))}return new W(n,r)}}function ft(c){return{kind:"literal",value:c}}function Sr(c){return{kind:"identifier",name:c}}function Er(c,e){return{kind:"property_access",object:c,property:e}}function uo(c){return{kind:"parameter",name:c}}function dt(c,e,t){return{kind:"binary_op",op:c,left:e,right:t}}function Ir(c,e){return{kind:"unary_op",op:c,operand:e}}function ho(c,e){return{kind:"function_call",name:c,args:e}}function Nr(c,e,t){return{variable:c,labels:e??[],properties:t??new Map}}function Ar(c){return{variable:(c==null?void 0:c.variable)??null,types:(c==null?void 0:c.types)??[],properties:(c==null?void 0:c.properties)??new Map,direction:(c==null?void 0:c.direction)??"out",minHops:(c==null?void 0:c.minHops)??null,maxHops:(c==null?void 0:c.maxHops)??null}}function fo(c){return{elements:c}}function po(c){return{clauses:c}}var k=(c=>(c.MATCH="MATCH",c.OPTIONAL="OPTIONAL",c.WHERE="WHERE",c.RETURN="RETURN",c.WITH="WITH",c.CREATE="CREATE",c.DELETE="DELETE",c.DETACH="DETACH",c.SET="SET",c.REMOVE="REMOVE",c.MERGE="MERGE",c.ON="ON",c.ORDER="ORDER",c.BY="BY",c.ASC="ASC",c.DESC="DESC",c.SKIP="SKIP",c.LIMIT="LIMIT",c.DISTINCT="DISTINCT",c.AS="AS",c.AND="AND",c.OR="OR",c.XOR="XOR",c.NOT="NOT",c.IN="IN",c.IS="IS",c.NULL="NULL",c.TRUE="TRUE",c.FALSE="FALSE",c.CASE="CASE",c.WHEN="WHEN",c.THEN="THEN",c.ELSE="ELSE",c.END="END",c.EXISTS="EXISTS",c.UNWIND="UNWIND",c.CALL="CALL",c.YIELD="YIELD",c.INTEGER="INTEGER",c.FLOAT="FLOAT",c.STRING="STRING",c.IDENTIFIER="IDENTIFIER",c.PARAMETER="PARAMETER",c.EQ="EQ",c.NEQ="NEQ",c.LT="LT",c.GT="GT",c.LTE="LTE",c.GTE="GTE",c.PLUS="PLUS",c.PLUS_EQ="PLUS_EQ",c.MINUS="MINUS",c.STAR="STAR",c.SLASH="SLASH",c.PERCENT="PERCENT",c.STARTS_WITH="STARTS_WITH",c.ENDS_WITH="ENDS_WITH",c.CONTAINS="CONTAINS",c.LPAREN="LPAREN",c.RPAREN="RPAREN",c.LBRACKET="LBRACKET",c.RBRACKET="RBRACKET",c.LBRACE="LBRACE",c.RBRACE="RBRACE",c.COMMA="COMMA",c.DOT="DOT",c.COLON="COLON",c.PIPE="PIPE",c.DOTDOT="DOTDOT",c.DASH="DASH",c.ARROW_RIGHT="ARROW_RIGHT",c.ARROW_LEFT="ARROW_LEFT",c.EOF="EOF",c))(k||{});const go=new Map([["match","MATCH"],["optional","OPTIONAL"],["where","WHERE"],["return","RETURN"],["with","WITH"],["create","CREATE"],["delete","DELETE"],["detach","DETACH"],["set","SET"],["remove","REMOVE"],["merge","MERGE"],["on","ON"],["order","ORDER"],["by","BY"],["asc","ASC"],["ascending","ASC"],["desc","DESC"],["descending","DESC"],["skip","SKIP"],["limit","LIMIT"],["distinct","DISTINCT"],["as","AS"],["and","AND"],["or","OR"],["xor","XOR"],["not","NOT"],["in","IN"],["is","IS"],["null","NULL"],["true","TRUE"],["false","FALSE"],["case","CASE"],["when","WHEN"],["then","THEN"],["else","ELSE"],["end","END"],["exists","EXISTS"],["unwind","UNWIND"],["call","CALL"],["yield","YIELD"],["starts","STARTS_WITH"],["ends","ENDS_WITH"],["contains","CONTAINS"]]);function mo(c){const e=[];let t=0;for(;t<c.length;){const n=c[t];if(n===" "||n===" "||n===`
3
3
  `||n==="\r"){t++;continue}if(n==="/"&&t+1<c.length&&c[t+1]==="/"){for(;t<c.length&&c[t]!==`
4
4
  `;)t++;continue}const r=t;if(n==="'"||n==='"'){const s=n;t++;let o="";for(;t<c.length&&c[t]!==s;){if(c[t]==="\\"&&t+1<c.length){t++;const i=c[t];i==="n"?o+=`
5
5
  `:i==="t"?o+=" ":i==="\\"?o+="\\":i===s?o+=s:o+=i}else o+=c[t];t++}t<c.length&&t++,e.push({type:"STRING",value:o,position:r});continue}if(n>="0"&&n<="9"||n==="."&&t+1<c.length&&c[t+1]>="0"&&c[t+1]<="9"){let s="",o=!1;for(;t<c.length&&(c[t]>="0"&&c[t]<="9"||c[t]===".");){if(c[t]==="."){if(o||t+1<c.length&&c[t+1]===".")break;o=!0}s+=c[t],t++}e.push({type:o?"FLOAT":"INTEGER",value:s,position:r});continue}if(n==="$"){t++;let s="";for(;t<c.length&&(c[t]>="a"&&c[t]<="z"||c[t]>="A"&&c[t]<="Z"||c[t]>="0"&&c[t]<="9"||c[t]==="_");)s+=c[t],t++;e.push({type:"PARAMETER",value:s,position:r});continue}if(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_"){let s="";for(;t<c.length&&(c[t]>="a"&&c[t]<="z"||c[t]>="A"&&c[t]<="Z"||c[t]>="0"&&c[t]<="9"||c[t]==="_");)s+=c[t],t++;const o=s.toLowerCase(),i=go.get(o);if(i==="STARTS_WITH"){let a=t;for(;a<c.length&&(c[a]===" "||c[a]===" ");)a++;let l="";for(;a<c.length&&c[a]!==" "&&c[a]!==" "&&c[a]!==`
6
6
  `;)l+=c[a],a++;if(l.toLowerCase()==="with"){e.push({type:"STARTS_WITH",value:"STARTS WITH",position:r}),t=a;continue}}if(i==="ENDS_WITH"){let a=t;for(;a<c.length&&(c[a]===" "||c[a]===" ");)a++;let l="";for(;a<c.length&&c[a]!==" "&&c[a]!==" "&&c[a]!==`
7
- `;)l+=c[a],a++;if(l.toLowerCase()==="with"){e.push({type:"ENDS_WITH",value:"ENDS WITH",position:r}),t=a;continue}}i!==void 0&&i!=="STARTS_WITH"&&i!=="ENDS_WITH"?e.push({type:i,value:s,position:r}):e.push({type:"IDENTIFIER",value:s,position:r});continue}if(n==="`"){t++;let s="";for(;t<c.length&&c[t]!=="`";)s+=c[t],t++;t<c.length&&t++,e.push({type:"IDENTIFIER",value:s,position:r});continue}if(n==="("){e.push({type:"LPAREN",value:"(",position:r}),t++;continue}if(n===")"){e.push({type:"RPAREN",value:")",position:r}),t++;continue}if(n==="["){e.push({type:"LBRACKET",value:"[",position:r}),t++;continue}if(n==="]"){e.push({type:"RBRACKET",value:"]",position:r}),t++;continue}if(n==="{"){e.push({type:"LBRACE",value:"{",position:r}),t++;continue}if(n==="}"){e.push({type:"RBRACE",value:"}",position:r}),t++;continue}if(n===","){e.push({type:"COMMA",value:",",position:r}),t++;continue}if(n===":"){e.push({type:"COLON",value:":",position:r}),t++;continue}if(n==="|"){e.push({type:"PIPE",value:"|",position:r}),t++;continue}if(n==="+"){t+1<c.length&&c[t+1]==="="?(e.push({type:"PLUS_EQ",value:"+=",position:r}),t+=2):(e.push({type:"PLUS",value:"+",position:r}),t++);continue}if(n==="*"){e.push({type:"STAR",value:"*",position:r}),t++;continue}if(n==="%"){e.push({type:"PERCENT",value:"%",position:r}),t++;continue}if(n==="."){if(t+1<c.length&&c[t+1]==="."){e.push({type:"DOTDOT",value:"..",position:r}),t+=2;continue}e.push({type:"DOT",value:".",position:r}),t++;continue}if(n==="="){e.push({type:"EQ",value:"=",position:r}),t++;continue}if(n==="<"){if(t+1<c.length){if(c[t+1]===">"){e.push({type:"NEQ",value:"<>",position:r}),t+=2;continue}if(c[t+1]==="="){e.push({type:"LTE",value:"<=",position:r}),t+=2;continue}if(c[t+1]==="-"){e.push({type:"ARROW_LEFT",value:"<-",position:r}),t+=2;continue}}e.push({type:"LT",value:"<",position:r}),t++;continue}if(n===">"){if(t+1<c.length&&c[t+1]==="="){e.push({type:"GTE",value:">=",position:r}),t+=2;continue}e.push({type:"GT",value:">",position:r}),t++;continue}if(n==="-"){if(t+1<c.length&&c[t+1]===">"){e.push({type:"ARROW_RIGHT",value:"->",position:r}),t+=2;continue}e.push({type:"DASH",value:"-",position:r}),t++;continue}if(n==="/"){e.push({type:"SLASH",value:"/",position:r}),t++;continue}t++}return e.push({type:"EOF",value:"",position:t}),e}class _o{constructor(e){b(this,"tokens");b(this,"pos");this.tokens=mo(e),this.pos=0}peek(){return this.tokens[this.pos]??{type:k.EOF,value:"",position:-1}}advance(){const e=this.peek();return e.type!==k.EOF&&this.pos++,e}expect(e){const t=this.peek();if(t.type!==e)throw new Error(`Cypher parse error at position ${String(t.position)}: expected ${e}, got ${t.type} ('${t.value}')`);return this.advance()}match(e){return this.peek().type===e?(this.advance(),!0):!1}atClauseStart(){const e=this.peek();return new Set([k.MATCH,k.OPTIONAL,k.CREATE,k.MERGE,k.SET,k.DELETE,k.DETACH,k.RETURN,k.WITH,k.UNWIND]).has(e.type)}parse(){const e=[];for(;this.peek().type!==k.EOF;)e.push(this.parseClause());return po(e)}parseClause(){const e=this.peek();switch(e.type){case k.MATCH:return this.parseMatchClause(!1);case k.OPTIONAL:return this.advance(),this.expect(k.MATCH),this.parseMatchClauseInner(!0);case k.RETURN:return this.parseReturnClause();case k.WITH:return this.parseWithClause();case k.CREATE:return this.parseCreateClause();case k.DELETE:return this.parseDeleteClause(!1);case k.DETACH:return this.advance(),this.expect(k.DELETE),this.parseDeleteClauseInner(!0);case k.SET:return this.parseSetClause();case k.REMOVE:return this.parseRemoveClause();case k.MERGE:return this.parseMergeClause();case k.UNWIND:return this.parseUnwindClause();case k.CALL:return this.parseCallClause();default:throw new Error(`Cypher parse error at position ${String(e.position)}: unexpected token ${e.type} ('${e.value}')`)}}parseMatchClause(e){return this.expect(k.MATCH),this.parseMatchClauseInner(e)}parseMatchClauseInner(e){const t=this.parsePatternList();let n=null;return this.peek().type===k.WHERE&&(this.advance(),n=this.parseExpr()),{kind:"match",patterns:t,optional:e,where:n}}parseReturnClause(){this.expect(k.RETURN);const e=this.match(k.DISTINCT),t=this.parseReturnItems(),n=this.parseOptionalOrderBy(),r=this.parseOptionalSkip(),s=this.parseOptionalLimit();return{kind:"return",items:t,distinct:e,orderBy:n,skip:r,limit:s}}parseWithClause(){this.expect(k.WITH);const e=this.match(k.DISTINCT),t=this.parseReturnItems();let n=null;this.peek().type===k.WHERE&&(this.advance(),n=this.parseExpr());const r=this.parseOptionalOrderBy(),s=this.parseOptionalSkip(),o=this.parseOptionalLimit();return{kind:"with",items:t,distinct:e,where:n,orderBy:r,skip:s,limit:o}}parseCreateClause(){return this.expect(k.CREATE),{kind:"create",patterns:this.parsePatternList()}}parseDeleteClause(e){return this.expect(k.DELETE),this.parseDeleteClauseInner(e)}parseDeleteClauseInner(e){const t=[this.parseExpr()];for(;this.match(k.COMMA);)t.push(this.parseExpr());return{kind:"delete",exprs:t,detach:e}}parseSetClause(){this.expect(k.SET);const e=[];do{const t=this.parseExpr();let n="=";this.peek().type===k.PLUS_EQ?(this.advance(),n="+="):this.expect(k.EQ);const r=this.parseExpr();if(t.kind!=="property_access")throw new Error("SET requires property access on left side");e.push({property:t,value:r,operator:n})}while(this.match(k.COMMA));return{kind:"set",items:e}}parseRemoveClause(){this.expect(k.REMOVE);const e=[this.parseExpr()];for(;this.match(k.COMMA);)e.push(this.parseExpr());return{kind:"remove",items:e}}parseMergeClause(){this.expect(k.MERGE);const t=this.parsePatternList()[0];let n=null,r=null;for(;this.peek().type===k.ON;){this.advance();const s=this.peek();if(s.type===k.CREATE){this.advance(),this.expect(k.SET);const o=[];do{const i=this.parseExpr();let a="=";this.peek().type===k.PLUS_EQ?(this.advance(),a="+="):this.expect(k.EQ);const l=this.parseExpr();if(i.kind!=="property_access")throw new Error("ON CREATE SET requires property access");o.push({property:i,value:l,operator:a})}while(this.match(k.COMMA));n={kind:"set",items:o}}else if(s.type===k.MATCH){this.advance(),this.expect(k.SET);const o=[];do{const i=this.parseExpr();let a="=";this.peek().type===k.PLUS_EQ?(this.advance(),a="+="):this.expect(k.EQ);const l=this.parseExpr();if(i.kind!=="property_access")throw new Error("ON MATCH SET requires property access");o.push({property:i,value:l,operator:a})}while(this.match(k.COMMA));r={kind:"set",items:o}}}return{kind:"merge",pattern:t,onCreate:n,onMatch:r}}parseUnwindClause(){this.expect(k.UNWIND);const e=this.parseExpr();this.expect(k.AS);const t=this.expect(k.IDENTIFIER).value;return{kind:"unwind",expr:e,alias:t}}parseCallClause(){this.expect(k.CALL);let e=this.expect(k.IDENTIFIER).value;for(;this.match(k.DOT);)e+="."+this.expect(k.IDENTIFIER).value;this.expect(k.LPAREN);const t=[];if(this.peek().type!==k.RPAREN)for(t.push(this.parseExpr());this.match(k.COMMA);)t.push(this.parseExpr());this.expect(k.RPAREN);let n=null;if(this.peek().type===k.YIELD)for(this.advance(),n=[this.expect(k.IDENTIFIER).value];this.match(k.COMMA);)n.push(this.expect(k.IDENTIFIER).value);return{kind:"call",procedure:e,args:t,yields:n}}parsePatternList(){const e=[this.parsePathPattern()];for(;this.match(k.COMMA);)e.push(this.parsePathPattern());return e}parsePathPattern(){const e=[];for(e.push(this.parseNodePattern());this.isRelationshipStart();)e.push(this.parseRelationshipPattern()),e.push(this.parseNodePattern());return fo(e)}isRelationshipStart(){const e=this.peek().type;return e===k.DASH||e===k.ARROW_LEFT||e===k.ARROW_RIGHT}parseNodePattern(){this.expect(k.LPAREN);let e=null;const t=[],n=new Map;for(this.peek().type===k.IDENTIFIER&&(e=this.advance().value);this.peek().type===k.COLON;)this.advance(),t.push(this.expect(k.IDENTIFIER).value);return this.peek().type===k.LBRACE&&this.parsePropertyMap(n),this.expect(k.RPAREN),Nr(e,t,n)}parseRelationshipPattern(){let e="both",t=!1;this.peek().type===k.ARROW_LEFT?(this.advance(),t=!0):this.expect(k.DASH);let n=null;const r=[],s=new Map;let o=null,i=null;if(this.peek().type===k.LBRACKET){for(this.advance(),this.peek().type===k.IDENTIFIER&&(n=this.advance().value);this.peek().type===k.COLON;)for(this.advance(),r.push(this.expect(k.IDENTIFIER).value);this.match(k.PIPE);)this.peek().type===k.COLON&&this.advance(),r.push(this.expect(k.IDENTIFIER).value);this.peek().type===k.STAR&&(this.advance(),this.peek().type===k.INTEGER&&(o=parseInt(this.advance().value,10)),this.match(k.DOTDOT)?this.peek().type===k.INTEGER&&(i=parseInt(this.advance().value,10)):o!==null&&(i=o)),this.peek().type===k.LBRACE&&this.parsePropertyMap(s),this.expect(k.RBRACKET)}return this.peek().type===k.ARROW_RIGHT?(this.advance(),e=t?"both":"out"):(this.expect(k.DASH),e=t?"in":"both"),Ar({variable:n,types:r,properties:s,direction:e,minHops:o,maxHops:i})}parsePropertyMap(e){if(this.expect(k.LBRACE),this.peek().type!==k.RBRACE){const t=this.expect(k.IDENTIFIER).value;this.expect(k.COLON);const n=this.parseExpr();for(e.set(t,n);this.match(k.COMMA);){const r=this.expect(k.IDENTIFIER).value;this.expect(k.COLON);const s=this.parseExpr();e.set(r,s)}}this.expect(k.RBRACE)}parseReturnItems(){const e=[this.parseReturnItem()];for(;this.match(k.COMMA);)e.push(this.parseReturnItem());return e}parseReturnItem(){if(this.peek().type===k.STAR)return this.advance(),{expr:Sr("*"),alias:null};const e=this.parseExpr();let t=null;return this.match(k.AS)&&(t=this.expect(k.IDENTIFIER).value),{expr:e,alias:t}}parseOptionalOrderBy(){if(this.peek().type!==k.ORDER)return null;this.advance(),this.expect(k.BY);const e=[this.parseOrderByItem()];for(;this.match(k.COMMA);)e.push(this.parseOrderByItem());return e}parseOrderByItem(){const e=this.parseExpr();let t=!0;return this.peek().type===k.DESC?(this.advance(),t=!1):this.peek().type===k.ASC&&this.advance(),{expr:e,ascending:t}}parseOptionalSkip(){return this.peek().type!==k.SKIP?null:(this.advance(),this.parseExpr())}parseOptionalLimit(){return this.peek().type!==k.LIMIT?null:(this.advance(),this.parseExpr())}parseExpr(){return this.parseOr()}parseOr(){let e=this.parseXor();for(;this.peek().type===k.OR;){this.advance();const t=this.parseXor();e=ft("OR",e,t)}return e}parseXor(){let e=this.parseAnd();for(;this.peek().type===k.XOR;){this.advance();const t=this.parseAnd();e=ft("XOR",e,t)}return e}parseAnd(){let e=this.parseNot();for(;this.peek().type===k.AND;){this.advance();const t=this.parseNot();e=ft("AND",e,t)}return e}parseNot(){if(this.peek().type===k.NOT){this.advance();const e=this.parseNot();return Ir("NOT",e)}return this.parseComparison()}parseComparison(){let e=this.parseAddSub();const t=new Set([k.EQ,k.NEQ,k.LT,k.GT,k.LTE,k.GTE,k.STARTS_WITH,k.ENDS_WITH,k.CONTAINS]);for(;t.has(this.peek().type);){const n=this.advance(),r=this.parseAddSub();e=ft(n.value.toUpperCase(),e,r)}if(this.peek().type===k.IS){this.advance();const n=this.match(k.NOT);return this.expect(k.NULL),{kind:"is_null",value:e,negated:n}}if(this.peek().type===k.IN){this.advance();const n=this.parseAddSub();return{kind:"in",value:e,list:n}}return e}parseAddSub(){let e=this.parseMulDiv();for(;this.peek().type===k.PLUS||this.peek().type===k.MINUS;){const t=this.advance(),n=this.parseMulDiv();e=ft(t.value,e,n)}return e}parseMulDiv(){let e=this.parseUnaryExpr();for(;this.peek().type===k.STAR||this.peek().type===k.SLASH||this.peek().type===k.PERCENT;){const t=this.advance(),n=this.parseUnaryExpr();e=ft(t.value,e,n)}return e}parseUnaryExpr(){if(this.peek().type===k.MINUS){this.advance();const e=this.parsePrimary();return Ir("-",e)}return this.parsePrimary()}parsePrimary(){const e=this.peek();switch(e.type){case k.INTEGER:return this.advance(),ht(parseInt(e.value,10));case k.FLOAT:return this.advance(),ht(parseFloat(e.value));case k.STRING:return this.advance(),ht(e.value);case k.TRUE:return this.advance(),ht(!0);case k.FALSE:return this.advance(),ht(!1);case k.NULL:return this.advance(),ht(null);case k.PARAMETER:return this.advance(),uo(e.value);case k.LBRACKET:{this.advance();const t=[];if(this.peek().type!==k.RBRACKET)for(t.push(this.parseExpr());this.match(k.COMMA);)t.push(this.parseExpr());return this.expect(k.RBRACKET),{kind:"list",elements:t}}case k.CASE:return this.parseCaseExpr();case k.EXISTS:{this.advance(),this.expect(k.LPAREN);const t=this.parseNodePattern();return this.expect(k.RPAREN),{kind:"exists",pattern:t}}case k.LPAREN:{this.advance();const t=this.parseExpr();return this.expect(k.RPAREN),t}case k.IDENTIFIER:{if(this.advance(),this.peek().type===k.LPAREN){this.advance();const n=[],r=this.match(k.DISTINCT);if(this.peek().type!==k.RPAREN)for(n.push(this.parseExpr());this.match(k.COMMA);)n.push(this.parseExpr());this.expect(k.RPAREN);const s=r?e.value+"_distinct":e.value;let o=ho(s,n);for(;this.peek().type===k.DOT||this.peek().type===k.LBRACKET;)if(this.peek().type===k.DOT){this.advance();const i=this.expect(k.IDENTIFIER).value;o=Er(o,i)}else{this.advance();const i=this.parseExpr();this.expect(k.RBRACKET),o={kind:"index",value:o,index:i}}return o}let t=Sr(e.value);for(;this.peek().type===k.DOT||this.peek().type===k.LBRACKET;)if(this.peek().type===k.DOT){this.advance();const n=this.expect(k.IDENTIFIER).value;t=Er(t,n)}else{this.advance();const n=this.parseExpr();this.expect(k.RBRACKET),t={kind:"index",value:t,index:n}}return t}default:throw new Error(`Cypher parse error at position ${String(e.position)}: unexpected token ${e.type} ('${e.value}')`)}}parseCaseExpr(){this.expect(k.CASE);let e=null;this.peek().type!==k.WHEN&&(e=this.parseExpr());const t=[];for(;this.peek().type===k.WHEN;){this.advance();const r=this.parseExpr();this.expect(k.THEN);const s=this.parseExpr();t.push({when:r,then:s})}let n=null;return this.match(k.ELSE)&&(n=this.parseExpr()),this.expect(k.END),{kind:"case",operand:e,whens:t,elseExpr:n}}}function Nn(c){return new _o(c).parse()}class Ye{constructor(e){b(this,"__brand","vertex");b(this,"value");this.value=e}}class Wt{constructor(e){b(this,"__brand","edge");b(this,"value");this.value=e}}function ke(c){return c instanceof Ye}function Me(c){return c instanceof Wt}function ue(c){return c instanceof Ye||c instanceof Wt?c.value:typeof c=="number"?c:null}class yo{constructor(e,t,n){b(this,"_graph");b(this,"_graphName");b(this,"_params");b(this,"_nextDocId");this._graph=e,this._graphName=t,this._params=n??{},this._nextDocId=1}get store(){return this._graph}get graphName(){return this._graphName}execute(e,t){const n=Nn(e);return this.executeAST(n,t)}executePostingList(e,t){const n=Nn(e);return this.executeASTPostingList(n,t)}executeAST(e,t){return this.executeASTPostingList(e,t).toPostingList()}executeASTPostingList(e,t){if(t)for(const[r,s]of Object.entries(t))this._params[r]=s;let n=this._emptyBinding();for(const r of e.clauses)switch(r.kind){case"match":n=this._execMatch(r,n);break;case"create":n=this._execCreate(r,n);break;case"merge":n=this._execMerge(r,n);break;case"set":n=this._execSet(r,n);break;case"delete":n=this._execDelete(r,n);break;case"return":n=this._execReturnPostingList(r,n);break;case"with":n=this._execWith(r,n);break;case"unwind":n=this._execUnwind(r,n);break}return n}executeRows(e,t){const n=Nn(e);return this.executeASTRows(n,t)}executeASTRows(e,t){const n=this.executeASTPostingList(e,t),r=[];for(const s of n){const o={},i=s.payload.fields;for(const a of Object.keys(i))o[a]=i[a];r.push(o)}return r}_emptyBinding(){const e=this._allocDocId(),t={docId:e,payload:U({score:1,fields:{}})},n=new W([t]);return n.setGraphPayload(e,ne()),n}_allocDocId(){const e=this._nextDocId;return this._nextDocId+=1,e}_makeBindingEntry(e,t,n){const r=this._allocDocId();return[{docId:r,payload:U({score:1,fields:{...e}})},r]}_execMatch(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields};let i=this._matchPatterns(e.patterns,o);if(e.where!==null&&(i=i.filter(a=>this._eval(e.where,a))),e.optional&&i.length===0){const a={...o};for(const h of e.patterns)for(const f of h.elements)(Oe(f)&&f.variable!==null||It(f)&&f.variable!==null)&&(f.variable in a||(a[f.variable]=null));const[l,u]=this._makeBindingEntry(a,new Set,new Set);n.push(l),r.set(u,ne())}else for(const a of i){const l=new Set,u=new Set;for(const d of Object.values(a))ke(d)?l.add(d.value):Me(d)?u.add(d.value):typeof d=="number"&&(this._graph.getVertex(d)!==null?l.add(d):this._graph.getEdge(d)!==null&&u.add(d));const[h,f]=this._makeBindingEntry(a,l,u);n.push(h),r.set(f,ne({subgraphVertices:l,subgraphEdges:u}))}}return new W(n,r)}_matchPatterns(e,t){let n=[{...t}];for(const r of e){const s=[];for(const o of n)s.push(...this._matchPath(r,o));n=s}return n}_matchPath(e,t){const n=e.elements;if(n.length===0)return[{...t}];const r=this._assignAnonVars(n),s=r[0];if(!s||!Oe(s))return[{...t}];const o=this._nodeCandidates(s,t);let i=[];for(const u of o){const h={...t},f=s.variable;if(f!==null){if(f in t){const d=t[f],p=ue(d);if(p!==null&&p!==u.vertexId)continue}h[f]=new Ye(u.vertexId),i.push(h)}}let a=1;for(;a<r.length;){const u=r[a],h=r[a+1];if(!u||!h||!It(u)||!Oe(h))break;const f=[];for(const d of i)f.push(...this._expandRel(d,u,h,r,a));i=f,a+=2}const l=new Set;for(const u of r)if(Oe(u)||It(u)){const h=(Oe(u),u.variable);h!==null&&h.startsWith("_anon_")&&l.add(h)}return l.size>0&&(i=i.map(u=>{const h={};for(const f of Object.keys(u))l.has(f)||(h[f]=u[f]);return h})),i}_assignAnonVars(e){const t=[];for(const n of e)if(Oe(n)&&n.variable===null){const r=`_anon_${this._allocDocId()}`;t.push(Nr(r,[...n.labels],new Map(n.properties)))}else if(It(n)&&n.variable===null){const r=`_anon_${this._allocDocId()}`;t.push(Ar({variable:r,types:[...n.types],properties:new Map(n.properties),direction:n.direction,minHops:n.minHops,maxHops:n.maxHops}))}else t.push(n);return t}_nodeCandidates(e,t){if(e.variable!==null&&e.variable in t){const r=t[e.variable];if(r==null)return[];const s=ue(r);if(s===null)return[];const o=this._graph.getVertex(s);return o!==null&&this._vertexMatches(o,e,t)?[o]:[]}if(!this._graph.hasGraph(this._graphName))return[];let n;if(e.labels.length>0){const r=new Set;n=[];for(const s of e.labels)for(const o of this._graph.verticesByLabel(s,this._graphName))r.has(o.vertexId)||(r.add(o.vertexId),n.push(o))}else n=this._graph.verticesInGraph(this._graphName);return n.filter(r=>this._vertexMatches(r,e,t))}_vertexMatches(e,t,n){if(t.labels.length>0&&!t.labels.includes(e.label))return!1;if(t.properties.size>0){const r=n??{};for(const[s,o]of t.properties){const i=this._eval(o,r);if(e.properties[s]!==i)return!1}}return!0}_expandRel(e,t,n,r,s){const o=r[s-1];if(!o||!Oe(o))return[];const i=o.variable,a=i!==null?e[i]:void 0,l=ue(a);return l===null?[]:t.minHops!==null||t.maxHops!==null?this._expandVarLength(e,l,t,n):this._expandSingleHop(e,l,t,n)}_expandSingleHop(e,t,n,r){const s=[];for(const[o,i]of this._getEdges(t,n)){const a=this._graph.getVertex(i);if(a===null||!this._vertexMatches(a,r,e)||!this._edgeMatches(o,n,e))continue;const l={...e};if(n.variable!==null){if(n.variable in e){const u=ue(e[n.variable]);if(u!==null&&u!==o.edgeId)continue}l[n.variable]=new Wt(o.edgeId)}if(r.variable!==null){if(r.variable in e){const u=ue(e[r.variable]);if(u!==null&&u!==a.vertexId)continue}l[r.variable]=new Ye(a.vertexId)}s.push(l)}return s}_expandVarLength(e,t,n,r){const s=n.minHops!==null?n.minHops:1,o=n.maxHops,i=[],a=[[t,0,[]]];for(;a.length>0;){const l=a.shift(),u=l[0],h=l[1],f=l[2];if(h>=s){const d=this._graph.getVertex(u);if(d!==null&&this._vertexMatches(d,r,e)){const p={...e};if(n.variable!==null&&(p[n.variable]=[...f]),r.variable!==null){if(r.variable in e){const m=ue(e[r.variable]);if(m!==null&&m!==u)continue}p[r.variable]=new Ye(u)}i.push(p)}}if(!(o!==null&&h>=o))for(const[d,p]of this._getEdges(u,n))f.includes(d.edgeId)||this._edgeMatches(d,n,e)&&a.push([p,h+1,[...f,d.edgeId]])}return i}_getEdges(e,t){let n=[];const r=t.direction;if(r==="out"||r==="both")for(const s of this._graph.outEdgeIds(e,this._graphName)){const o=this._graph.getEdge(s);o!==null&&n.push([o,o.targetId])}if(r==="in"||r==="both")for(const s of this._graph.inEdgeIds(e,this._graphName)){const o=this._graph.getEdge(s);o!==null&&n.push([o,o.sourceId])}return t.types.length>0&&(n=n.filter(([s])=>t.types.includes(s.label))),n}_edgeMatches(e,t,n){if(t.properties.size>0){const r=n??{};for(const[s,o]of t.properties){const i=this._eval(o,r);if(e.properties[s]!==i)return!1}}return!0}_execCreate(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields},i=new Set,a=new Set;for(const h of e.patterns)this._createPath(h,o,i,a);const[l,u]=this._makeBindingEntry(o,i,a);n.push(l),r.set(u,ne({subgraphVertices:i,subgraphEdges:a}))}return new W(n,r)}_createPath(e,t,n,r){const s=e.elements;for(let o=0;o<s.length;o++){const i=s[o];if(Oe(i)){if(i.variable!==null&&i.variable in t)continue;const a=this._createVertex(i,t);n.add(a.vertexId),i.variable!==null&&(t[i.variable]=new Ye(a.vertexId))}else if(It(i)){const a=s[o+1];if(!a||!Oe(a))continue;if(a.variable!==null&&!(a.variable in t)){const m=this._createVertex(a,t);n.add(m.vertexId),t[a.variable]=new Ye(m.vertexId)}const l=s[o-1];if(!l||!Oe(l))continue;const u=l.variable!==null?t[l.variable]:void 0,h=a.variable!==null?t[a.variable]:void 0,f=ue(u),d=ue(h);if(f===null||d===null)continue;const p=this._createEdge(i,f,d,t);r.add(p.edgeId),i.variable!==null&&(t[i.variable]=new Wt(p.edgeId))}}}_createVertex(e,t){const n=this._graph.nextVertexId(),r=e.labels.length>0?e.labels[0]:"",s={};for(const[i,a]of e.properties)s[i]=this._eval(a,t);const o=an(n,r,s);return this._graph.addVertex(o,this._graphName),o}_createEdge(e,t,n,r){const s=this._graph.nextEdgeId(),o=e.types.length>0?e.types[0]:"",i={};for(const[h,f]of e.properties)i[h]=this._eval(f,r);let a=t,l=n;e.direction==="in"&&(a=n,l=t);const u=gt(s,a,l,o,i);return this._graph.addEdge(u,this._graphName),u}_execMerge(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields},i=this._matchPath(e.pattern,o);if(i.length>0)for(const a of i){if(e.onMatch!==null)for(const h of e.onMatch.items)this._applySetItem(h,a);const[l,u]=this._makeBindingEntry(a,new Set,new Set);n.push(l),r.set(u,ne())}else{const a=new Set,l=new Set;if(this._createPath(e.pattern,o,a,l),e.onCreate!==null)for(const f of e.onCreate.items)this._applySetItem(f,o);const[u,h]=this._makeBindingEntry(o,a,l);n.push(u),r.set(h,ne({subgraphVertices:a,subgraphEdges:l}))}}return new W(n,r)}_execSet(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields};for(const l of e.items)this._applySetItem(l,o);const[i,a]=this._makeBindingEntry(o,new Set,new Set);n.push(i),r.set(a,ne())}return new W(n,r)}_applySetItem(e,t){const n=this._eval(e.value,t),r=e.property,s=r.object;if(s.kind!=="identifier")return;const o=s.name,i=r.property,a=t[o];if(a!=null){if(!Me(a)){const l=ue(a);if(l!==null){const u=this._graph.getVertex(l);if(u!==null){const h={...u.properties};h[i]=n;const f=an(u.vertexId,u.label,h);this._graph.addVertex(f,this._graphName);return}}}if(!ke(a)){const l=ue(a);if(l!==null){const u=this._graph.getEdge(l);if(u!==null){const h={...u.properties};h[i]=n;const f=gt(u.edgeId,u.sourceId,u.targetId,u.label,h);this._graph.addEdge(f,this._graphName);return}}}}}_execDelete(e,t){const n=[],r=[];for(const s of t){const o=s.payload.fields;for(const i of e.exprs){const a=this._eval(i,o);a!=null&&(ke(a)?n.push(a.value):Me(a)?r.push(a.value):typeof a=="number"&&(this._graph.getVertex(a)!==null?n.push(a):this._graph.getEdge(a)!==null&&r.push(a)))}}for(const s of r)this._graph.removeEdge(s,this._graphName);for(const s of n){if(!e.detach){const o=this._graph.outEdgeIds(s,this._graphName).size>0,i=this._graph.inEdgeIds(s,this._graphName).size>0;if(o||i)throw new Error(`Cannot delete vertex ${String(s)}: has incident edges. Use DETACH DELETE.`)}this._graph.removeVertex(s,this._graphName)}return t}_execReturnPostingList(e,t){const n=[...t];if(e.items.some(a=>Ge(a.expr)))return this._execReturnWithAggregation(e,n);if(e.orderBy!==null)for(let a=e.orderBy.length-1;a>=0;a--){const l=e.orderBy[a];n.sort((u,h)=>{const f=this._eval(l.expr,u.payload.fields),d=this._eval(l.expr,h.payload.fields),p=Ht(ze(f),ze(d));return l.ascending?p:-p})}const s=[],o=new Map;for(const a of n){const l=a.payload.fields,u={};for(const d of e.items){if(d.expr.kind==="identifier"&&d.expr.name==="*"){for(const _ of Object.keys(l))u[_]=this._toAgtype(l[_]);continue}let p=this._eval(d.expr,l);const m=d.alias??Xe(d.expr);d.expr.kind==="identifier"&&(p=this._toAgtype(p)),u[m]=p}const[h,f]=this._makeBindingEntry(u,new Set,new Set);s.push(h),o.set(f,ne())}let i=new W(s,o);if(e.distinct&&(i=this._distinctGpl(i)),e.skip!==null){const a=this._eval(e.skip,{});i=this._sliceGpl(i,typeof a=="number"?a:0,null)}if(e.limit!==null){const a=this._eval(e.limit,{});i=this._sliceGpl(i,0,typeof a=="number"?a:null)}return i}_execReturnWithAggregation(e,t){const n=[],r=[];for(let u=0;u<e.items.length;u++){const h=e.items[u];Ge(h.expr)?r.push(u):n.push(u)}const s=new Map,o=[];for(const u of t){const h=u.payload.fields,f=[];for(const m of n){const _=e.items[m],y=this._eval(_.expr,h);f.push(An(y))}const d=f.join("\0"),p=s.get(d);p!==void 0?p.push(u):(s.set(d,[u]),o.push(d))}n.length===0&&t.length===0&&(o.push(""),s.set("",[]));const i=[],a=new Map;for(const u of o){const h=s.get(u)??[],f={},d=h.length>0?h[0].payload.fields:{};for(const _ of n){const y=e.items[_];let x=this._eval(y.expr,d);const v=y.alias??Xe(y.expr);y.expr.kind==="identifier"&&(x=this._toAgtype(x)),f[v]=x}for(const _ of r){const y=e.items[_],x=y.alias??Xe(y.expr);f[x]=this._evalAggregate(y.expr,h.map(v=>v.payload.fields))}const[p,m]=this._makeBindingEntry(f,new Set,new Set);i.push(p),a.set(m,ne())}let l=new W(i,a);if(e.distinct&&(l=this._distinctGpl(l)),e.orderBy!==null&&(l=this._orderByGpl(e.orderBy,l)),e.skip!==null){const u=this._eval(e.skip,{});l=this._sliceGpl(l,typeof u=="number"?u:0,null)}if(e.limit!==null){const u=this._eval(e.limit,{});l=this._sliceGpl(l,0,typeof u=="number"?u:null)}return l}_evalAggregate(e,t){if(e.kind==="function_call"){const n=e,r=n.name.toLowerCase();if(r==="count"){if(n.args.length===0)return t.length;const s=n.args[0];if(s.kind==="identifier"&&s.name==="*")return t.length;let o=0;for(const i of t){const a=this._eval(s,i);a!=null&&o++}return o}if(r==="sum"){const s=n.args[0];let o=0;for(const i of t){const a=this._eval(s,i);typeof a=="number"&&(o+=a)}return o}if(r==="avg"){const s=n.args[0];let o=0,i=0;for(const a of t){const l=this._eval(s,a);typeof l=="number"&&(o+=l,i++)}return i>0?o/i:null}if(r==="min"){const s=n.args[0];let o=null;for(const i of t){const a=this._eval(s,i);a!=null&&(o===null||Ht(ze(a),ze(o))<0)&&(o=a)}return o}if(r==="max"){const s=n.args[0];let o=null;for(const i of t){const a=this._eval(s,i);a!=null&&(o===null||Ht(ze(a),ze(o))>0)&&(o=a)}return o}if(r==="collect"){const s=n.args[0],o=[];for(const i of t){const a=this._eval(s,i);a!=null&&o.push(a)}return o}}return t.length>0?this._eval(e,t[0]):null}_execWith(e,t){if(e.items.some(i=>Ge(i.expr)))return this._execWithAggregation(e,t);const r=[],s=new Map;for(const i of t){const a=i.payload.fields,l={};for(const f of e.items){if(f.expr.kind==="identifier"&&f.expr.name==="*"){Object.assign(l,a);continue}const d=this._eval(f.expr,a),p=f.alias??Xe(f.expr);l[p]=d}const[u,h]=this._makeBindingEntry(l,new Set,new Set);r.push(u),s.set(h,ne())}let o=new W(r,s);if(e.distinct&&(o=this._distinctGpl(o)),e.orderBy!==null&&(o=this._orderByGpl(e.orderBy,o)),e.skip!==null){const i=this._eval(e.skip,{});o=this._sliceGpl(o,typeof i=="number"?i:0,null)}if(e.limit!==null){const i=this._eval(e.limit,{});o=this._sliceGpl(o,0,typeof i=="number"?i:null)}if(e.where!==null){const i=[],a=new Map;for(const l of o)if(this._eval(e.where,l.payload.fields)){i.push(l);const u=o.getGraphPayload(l.docId);u!==null&&a.set(l.docId,u)}o=new W(i,a)}return o}_execWithAggregation(e,t){const n=[...t],r=[],s=[];for(let h=0;h<e.items.length;h++){const f=e.items[h];Ge(f.expr)?s.push(h):r.push(h)}const o=new Map,i=[];for(const h of n){const f=h.payload.fields,d=[];for(const _ of r){const y=e.items[_],x=this._eval(y.expr,f);d.push(An(x))}const p=d.join("\0"),m=o.get(p);m!==void 0?m.push(h):(o.set(p,[h]),i.push(p))}r.length===0&&n.length===0&&(i.push(""),o.set("",[]));const a=[],l=new Map;for(const h of i){const f=o.get(h)??[],d={},p=f.length>0?f[0].payload.fields:{};for(const y of r){const x=e.items[y],v=this._eval(x.expr,p),E=x.alias??Xe(x.expr);d[E]=v}for(const y of s){const x=e.items[y],v=x.alias??Xe(x.expr);d[v]=this._evalAggregate(x.expr,f.map(E=>E.payload.fields))}const[m,_]=this._makeBindingEntry(d,new Set,new Set);a.push(m),l.set(_,ne())}let u=new W(a,l);if(e.distinct&&(u=this._distinctGpl(u)),e.orderBy!==null&&(u=this._orderByGpl(e.orderBy,u)),e.skip!==null){const h=this._eval(e.skip,{});u=this._sliceGpl(u,typeof h=="number"?h:0,null)}if(e.limit!==null){const h=this._eval(e.limit,{});u=this._sliceGpl(u,0,typeof h=="number"?h:null)}if(e.where!==null){const h=[],f=new Map;for(const d of u)if(this._eval(e.where,d.payload.fields)){h.push(d);const p=u.getGraphPayload(d.docId);p!==null&&f.set(d.docId,p)}u=new W(h,f)}return u}_execUnwind(e,t){const n=[],r=new Map;for(const s of t){const o=s.payload.fields,i=this._eval(e.expr,o);if(i!=null&&Array.isArray(i))for(const a of i){const l={...o};l[e.alias]=a;const[u,h]=this._makeBindingEntry(l,new Set,new Set);n.push(u),r.set(h,ne())}}return new W(n,r)}_toAgtype(e){if(e==null)return null;if(typeof e=="boolean")return e;if(ke(e)){const t=this._graph.getVertex(e.value);return t!==null?{id:t.vertexId,label:t.label,properties:{...t.properties}}:e.value}if(Me(e)){const t=this._graph.getEdge(e.value);return t!==null?{id:t.edgeId,label:t.label,start:t.sourceId,end:t.targetId,properties:{...t.properties}}:e.value}if(typeof e=="number"){const t=this._graph.getVertex(e);if(t!==null)return{id:t.vertexId,label:t.label,properties:{...t.properties}};const n=this._graph.getEdge(e);if(n!==null)return{id:n.edgeId,label:n.label,start:n.sourceId,end:n.targetId,properties:{...n.properties}}}return Array.isArray(e)?e.map(t=>this._toAgtype(t)):e}_distinctGpl(e){const t=new Set,n=[],r=new Map;for(const s of e){const o=s.payload.fields,i=[];for(const l of Object.keys(o).sort())i.push([l,An(o[l])]);const a=JSON.stringify(i);if(!t.has(a)){t.add(a),n.push(s);const l=e.getGraphPayload(s.docId);l!==null&&r.set(s.docId,l)}}return new W(n,r)}_orderByGpl(e,t){const n=[...t];for(let s=e.length-1;s>=0;s--){const o=e[s];n.sort((i,a)=>{const l=this._eval(o.expr,i.payload.fields),u=this._eval(o.expr,a.payload.fields),h=Ht(ze(l),ze(u));return o.ascending?h:-h})}const r=new Map;for(const s of n){const o=t.getGraphPayload(s.docId);o!==null&&r.set(s.docId,o)}return new W(n,r)}_sliceGpl(e,t,n){const r=[...e],s=n!==null?r.slice(t,t+n):r.slice(t),o=new Map;for(const i of s){const a=e.getGraphPayload(i.docId);a!==null&&o.set(i.docId,a)}return new W(s,o)}_eval(e,t){switch(e.kind){case"literal":return e.value;case"identifier":return t[e.name];case"parameter":return this._params[e.name];case"property_access":return this._evalPropertyAccess(e,t);case"binary_op":return this._evalBinary(e,t);case"unary_op":return this._evalUnary(e,t);case"function_call":return this._evalFunction(e,t);case"in":return this._evalIn(e,t);case"is_null":return this._evalIsNull(e,t);case"list":return e.elements.map(n=>this._eval(n,t));case"case":return this._evalCase(e,t);case"exists":return!1;case"index":{const n=this._eval(e.value,t),r=this._eval(e.index,t);return Array.isArray(n)&&typeof r=="number"?n[r]:null}default:{const n=e;throw new Error(`Cannot evaluate expression kind: ${String(n.kind)}`)}}}_evalPropertyAccess(e,t){let n=this._eval(e.object,t);if(n==null)return null;if(ke(n)){const s=this._graph.getVertex(n.value);s!==null&&(n=s)}else if(Me(n)){const s=this._graph.getEdge(n.value);s!==null&&(n=s)}else if(typeof n=="number"){const s=this._graph.getVertex(n);if(s!==null)n=s;else{const o=this._graph.getEdge(n);o!==null&&(n=o)}}const r=e.property;return bo(n)||vo(n)?n.properties[r]??null:typeof n=="object"&&n!==null&&!Array.isArray(n)?n[r]??null:null}_evalBinary(e,t){const n=e.op;if(n==="AND")return this._eval(e.left,t)?!!this._eval(e.right,t):!1;if(n==="OR")return this._eval(e.left,t)?!0:!!this._eval(e.right,t);if(n==="XOR")return!!this._eval(e.left,t)!=!!this._eval(e.right,t);const r=this._eval(e.left,t),s=this._eval(e.right,t);if(r==null||s===null||s===void 0)return n==="="?r==null&&s==null:n==="<>"?!(r==null&&s==null):null;switch(n){case"=":return Kt(r,s);case"<>":return!Kt(r,s);case"<":return Jt(r,s)<0;case">":return Jt(r,s)>0;case"<=":return Jt(r,s)<=0;case">=":return Jt(r,s)>=0;case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):Array.isArray(r)?[...r,...Array.isArray(s)?s:[s]]:r+s;case"-":return r-s;case"*":return r*s;case"/":return s===0?null:typeof r=="number"&&typeof s=="number"?Number.isInteger(r)&&Number.isInteger(s)?Math.trunc(r/s):r/s:null;case"%":return r%s;case"^":return Math.pow(r,s);case"STARTS WITH":return String(r).startsWith(String(s));case"ENDS WITH":return String(r).endsWith(String(s));case"CONTAINS":return String(r).includes(String(s));default:throw new Error(`Unknown binary operator: ${n}`)}}_evalUnary(e,t){const n=this._eval(e.operand,t);if(e.op==="NOT")return!n;if(e.op==="-")return n!=null?-n:null;throw new Error(`Unknown unary operator: ${e.op}`)}_evalFunction(e,t){const n=e.name.toLowerCase(),r=e.args;if(n==="id"){const s=r[0];if(!s)return null;const o=s.kind==="identifier"?t[s.name]:this._eval(s,t),i=ue(o);return i!==null?i:typeof o=="number"?o:null}if(n==="type"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.label}return null}if(n==="labels"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return i.label?[i.label]:[]}return null}if(n==="label"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return i.label}return null}if(n==="properties"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return{...i.properties};const a=this._graph.getEdge(o);if(a!==null)return{...a.properties}}return null}if(n==="keys"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return Object.keys(i.properties);const a=this._graph.getEdge(o);if(a!==null)return Object.keys(a.properties)}return typeof s=="object"&&s!==null&&!Array.isArray(s)?Object.keys(s):null}if(n==="tostring"||n==="tostr"){const s=r[0]?this._eval(r[0],t):null;return s!=null?String(s):null}if(n==="tointeger"||n==="toint"){const s=r[0]?this._eval(r[0],t):null;if(s==null)return null;const o=parseInt(String(s),10);return Number.isNaN(o)?null:o}if(n==="tofloat"){const s=r[0]?this._eval(r[0],t):null;if(s==null)return null;const o=parseFloat(String(s));return Number.isNaN(o)?null:o}if(n==="size"||n==="length"){const s=r[0]?this._eval(r[0],t):null;return s==null?null:typeof s=="string"||Array.isArray(s)?s.length:null}if(n==="head"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)&&s.length>0?s[0]:null}if(n==="last"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)&&s.length>0?s[s.length-1]:null}if(n==="tail"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)?s.slice(1):[]}if(n==="reverse"){const s=r[0]?this._eval(r[0],t):null;return s==null?null:typeof s=="string"?s.split("").reverse().join(""):Array.isArray(s)?[...s].reverse():null}if(n==="range"){const s=r[0]?this._eval(r[0],t):0,o=r[1]?this._eval(r[1],t):0,i=r[2]?this._eval(r[2],t):1;if(typeof s!="number"||typeof o!="number"||typeof i!="number"||i===0)return[];const a=[];if(i>0)for(let l=s;l<=o;l+=i)a.push(l);else for(let l=s;l>=o;l+=i)a.push(l);return a}if(n==="abs"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="number"?Math.abs(s):null}if(n==="coalesce"){for(const s of r){const o=this._eval(s,t);if(o!=null)return o}return null}if(n==="tolower"||n==="lower"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.toLowerCase():null}if(n==="toupper"||n==="upper"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.toUpperCase():null}if(n==="trim"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.trim():null}if(n==="replace"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null,i=r[2]?this._eval(r[2],t):null;return typeof s=="string"&&typeof o=="string"&&typeof i=="string"?s.split(o).join(i):null}if(n==="substring"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null;if(typeof s!="string"||typeof o!="number")return null;if(r[2]){const i=this._eval(r[2],t);if(typeof i=="number")return s.substring(o,o+i)}return s.substring(o)}if(n==="split"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null;return typeof s=="string"&&typeof o=="string"?s.split(o):null}if(n==="startnode"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.sourceId}return null}if(n==="endnode"){const s=r[0]?this._eval(r[0],t):null,o=ue(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.targetId}return null}if(n==="count")return 1;if(n==="collect")return[r[0]?this._eval(r[0],t):null];if(n==="sum"||n==="avg"||n==="min"||n==="max")return r[0]?this._eval(r[0],t):null;throw new Error(`Unknown function: ${e.name}`)}_evalIn(e,t){const n=this._eval(e.value,t),r=this._eval(e.list,t);return r==null?null:Array.isArray(r)?r.some(s=>Kt(s,n)):!1}_evalIsNull(e,t){const n=this._eval(e.value,t),r=n==null;return e.negated?!r:r}_evalCase(e,t){if(e.operand!==null){const n=this._eval(e.operand,t);for(const r of e.whens)if(Kt(n,this._eval(r.when,t)))return this._eval(r.then,t)}else for(const n of e.whens)if(this._eval(n.when,t))return this._eval(n.then,t);return e.elseExpr!==null?this._eval(e.elseExpr,t):null}}function Oe(c){return"labels"in c&&!("types"in c)}function It(c){return"types"in c}function bo(c){return typeof c!="object"||c===null?!1:"vertexId"in c&&"label"in c&&"properties"in c}function vo(c){return typeof c!="object"||c===null?!1:"edgeId"in c&&"sourceId"in c&&"targetId"in c}function Xe(c){switch(c.kind){case"identifier":return c.name;case"property_access":{const e=c;return`${Xe(e.object)}.${e.property}`}case"function_call":return c.name;default:return String(c)}}function ze(c){return c==null?[0,null]:typeof c=="boolean"?[1,c?1:0]:ke(c)?[2,c.value]:Me(c)?[2,c.value]:typeof c=="number"?[2,c]:typeof c=="string"?[3,c]:[4,String(c)]}function Ht(c,e){if(c[0]!==e[0])return c[0]-e[0];const t=c[1],n=e[1];return t===n?0:t===null?-1:n===null?1:typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"?t<n?-1:t>n?1:0:0}function Kt(c,e){return c===e?!0:c==null?e==null:e==null?!1:ke(c)?ke(e)?c.value===e.value:typeof e=="number"&&c.value===e:Me(c)?Me(e)?c.value===e.value:typeof e=="number"&&c.value===e:typeof c=="number"&&ke(e)||typeof c=="number"&&Me(e)?c===e.value:c===e}function Jt(c,e){if(typeof c=="number"&&typeof e=="number"||typeof c=="string"&&typeof e=="string")return c<e?-1:c>e?1:0;const t=String(c),n=String(e);return t<n?-1:t>n?1:0}function Ge(c){if(c.kind==="function_call"){const e=c,t=e.name.toLowerCase();if(t==="count"||t==="sum"||t==="avg"||t==="min"||t==="max"||t==="collect")return!0;for(const n of e.args)if(Ge(n))return!0}if(c.kind==="binary_op"){const e=c;return Ge(e.left)||Ge(e.right)}return c.kind==="unary_op"?Ge(c.operand):!1}function An(c){return c==null?"null":ke(c)?`vref:${String(c.value)}`:Me(c)?`eref:${String(c.value)}`:typeof c=="object"?JSON.stringify(c):String(c)}class Ee extends q{constructor(t,n){super();b(this,"source");b(this,"threshold");this.source=t,this.threshold=n}execute(t){const n=this.source.execute(t),r=[];for(const s of n){const o=s.payload.score-this.threshold;o>0&&r.push({docId:s.docId,payload:U({positions:s.payload.positions,score:o,fields:s.payload.fields})})}return D.fromSorted(r)}costEstimate(t){return this.source.costEstimate(t)}}class Ve extends q{constructor(t){super();b(this,"stages");if(t.length===0)throw new Error("MultiStageOperator requires at least one stage");this.stages=t}execute(t){if(this.stages.length===0)return new D;let n=this.stages[0][0].execute(t);n=kn(n,this.stages[0][1]);for(let r=1;r<this.stages.length;r++){const[s,o]=this.stages[r],i=s.execute(t),a=new Map;for(const u of i)a.set(u.docId,u.payload.score);const l=n.entries.map(u=>({docId:u.docId,payload:U({positions:u.payload.positions,score:a.get(u.docId)??u.payload.score,fields:u.payload.fields})}));n=kn(new D(l),o)}return n}costEstimate(t){let n=0,r=t.totalDocs;for(const[s,o]of this.stages)n+=s.costEstimate(t)*(r/Math.max(t.totalDocs,1)),r=typeof o=="number"&&Number.isInteger(o)?Math.min(o,r):r*.5;return n}static applyCutoff(t,n){return kn(t,n)}}function kn(c,e){if(Number.isInteger(e)&&e>0)return c.topK(e);const t=c.entries.filter(n=>n.payload.score>=e);return new D(t)}class Mn extends q{constructor(t,n,r){super();b(this,"fields");b(this,"query");b(this,"weights");this.fields=t,this.query=n,this.weights=r??t.map(()=>1)}execute(t){const n=t.invertedIndex;if(!n)return new D;const r=n.stats,s=[],o=new Set;for(const u of this.fields){const h=new me(this.query,u),f=new lt(Ke(),r),p=n.getSearchAnalyzer(u).analyze(this.query),_=new de(f,h,p,u).execute(t),y=new Map;for(const x of _)y.set(x.docId,x.payload.score),o.add(x.docId);s.push(y)}let i=0;for(const u of this.weights)i+=u;const a=this.weights.map(u=>u/i),l=[];for(const u of o){const h=[];for(let d=0;d<this.fields.length;d++)h.push(s[d].get(u)??.5);const f=h.length===1?h[0]:K.logOddsConjunction(h,0,a);l.push({docId:u,payload:U({score:f})})}return new D(l)}costEstimate(t){return t.totalDocs*this.fields.length}}class kr extends q{constructor(t,n=.5,r){super();b(this,"stages");b(this,"alpha");b(this,"gating");this.stages=t,this.alpha=n,this.gating=r??null}execute(t){const n=[];let r=null,s=new D;for(const[o,i]of this.stages){const a=o.map(h=>h.execute(t));if(r!==null)for(let h=0;h<a.length;h++){const f=a[h].entries.filter(d=>r.has(d.docId));a[h]=D.fromSorted(f)}n.push(...a);const l=n.map(h=>{let f=0;for(const d of h)d.payload.score>f&&(f=d.payload.score);return Math.max(f,.01)});s=new dr(n,l,this.alpha,i,this.gating).scoreTopK(),r=new Set(s.entries.map(h=>h.docId))}return s}costEstimate(t){let n=0,r=t.totalDocs;for(const[s,o]of this.stages){for(const i of s)n+=i.costEstimate(t)*(r/Math.max(t.totalDocs,1));r=Math.min(o,r)}return n}}function Yt(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function On(c,e){return e==="relu"?Math.max(0,c):e==="swish"?c*Yt(c):c}function wo(c){const e=new Float64Array(c.length);for(let t=0;t<c.length;t++)e[t]=Yt(c[t]);return e}function xo(c){const e=c.reduce((s,o)=>s+o,0),t=new Float64Array(9);if(e<=0)return t;const n=c[0]/e,r=(c.length>1?c[1]:0)/e;return t[4]=n,t[1]=r/4,t[7]=r/4,t[3]=r/4,t[5]=r/4,t}function So(c){return xo(c)}function Eo(c,e,t,n,r,s="none"){const[o]=e;let i=Math.floor(e[1]/(t*n));i<1&&(i=1);let a=t,l=n,u=new Float64Array(c);for(const f of r){const d=f.kernelShape;let p,m;d.length===4?(p=d[0],m=d[1]):(p=i,m=i);const _=d.length===4?d[2]:3,y=d.length===4?d[3]:3,x=Math.floor(_/2),v=Math.floor(y/2),E=new Float64Array(o*p*a*l);for(let I=0;I<o;I++)for(let S=0;S<p;S++)for(let N=0;N<a;N++)for(let A=0;A<l;A++){let O=0;for(let T=0;T<m;T++)for(let F=0;F<_;F++)for(let C=0;C<y;C++){const V=N+F-x,X=A+C-v;if(V>=0&&V<a&&X>=0&&X<l){const he=I*m*a*l+T*a*l+V*l+X,pt=S*m*_*y+T*_*y+F*y+C,pe=f.kernel[pt]??0;pe!==0&&(O+=(u[he]??0)*pe)}}const R=I*p*a*l+S*a*l+N*l+A;E[R]=On(O,s)}if(u=E,i=p,f.poolSize>1){const I=Math.floor(a/f.poolSize),S=Math.floor(l/f.poolSize),N=new Float64Array(o*p*I*S);for(let A=0;A<o;A++)for(let O=0;O<p;O++)for(let R=0;R<I;R++)for(let T=0;T<S;T++){let F=f.poolMethod==="max"?-1/0:0,C=0;for(let X=0;X<f.poolSize;X++)for(let he=0;he<f.poolSize;he++){const pt=R*f.poolSize+X,pe=T*f.poolSize+he;if(pt<a&&pe<l){const Ne=A*p*a*l+O*a*l+pt*l+pe,ss=u[Ne]??0;f.poolMethod==="max"?F=Math.max(F,ss):F+=ss,C++}}f.poolMethod==="avg"&&C>0&&(F/=C);const V=A*p*I*S+O*I*S+R*S+T;N[V]=F}u=N,a=I,l=S}}const h=i*a*l;return{data:u,shape:[o,h]}}function Io(c,e,t,n,r,s="none"){const[o]=e,[i]=n,a=Ms(t,n[0],n[1]),l=ks(c,e,a,[n[1],n[0]]);for(let u=0;u<o;u++)for(let h=0;h<i;h++){const f=u*i+h;l.data[f]=On(l.data[f]+r[h],s)}return{data:l.data,shape:[o,i]}}function No(c,e){const[t,n]=e,r=new Float64Array(c.length);for(let s=0;s<t;s++){const o=c.subarray(s*n,(s+1)*n),i=As(o);r.set(i,s*n)}return r}function Ao(c,e,t=1e-5){const[n,r]=e;if(n<2)return new Float64Array(c);const s=new Float64Array(r),o=new Float64Array(r);for(let a=0;a<n;a++)for(let l=0;l<r;l++)s[l]+=c[a*r+l]/n;for(let a=0;a<n;a++)for(let l=0;l<r;l++){const u=c[a*r+l]-s[l];o[l]+=u*u/n}const i=new Float64Array(c.length);for(let a=0;a<n;a++)for(let l=0;l<r;l++)i[a*r+l]=(c[a*r+l]-s[l])/Math.sqrt(o[l]+t);return i}function Mr(c,e,t=1,n=null,r=null,s=null,o="none"){const[i,a,l]=e;let u=t;l%u!==0&&(u=1);const h=Math.floor(l/u),f=n!==null?Cn(c,i,a,l,n,l,l):new Float64Array(c),d=r!==null?Cn(c,i,a,l,r,l,l):new Float64Array(c),p=s!==null?Cn(c,i,a,l,s,l,l):new Float64Array(c),m=1/Math.sqrt(h),_=new Float64Array(i*a*l);for(let y=0;y<i;y++)for(let x=0;x<u;x++){const v=new Float64Array(a*a);for(let E=0;E<a;E++)for(let I=0;I<a;I++){let S=0;for(let N=0;N<h;N++){const A=y*a*l+E*l+x*h+N,O=y*a*l+I*l+x*h+N;S+=f[A]*d[O]}v[E*a+I]=S*m}for(let E=0;E<a;E++){let I=-1/0;for(let N=0;N<a;N++)I=Math.max(I,v[E*a+N]);let S=0;for(let N=0;N<a;N++)v[E*a+N]=Math.exp(v[E*a+N]-I),S+=v[E*a+N];for(let N=0;N<a;N++)v[E*a+N]/=S}for(let E=0;E<a;E++)for(let I=0;I<h;I++){let S=0;for(let A=0;A<a;A++){const O=y*a*l+A*l+x*h+I;S+=v[E*a+A]*p[O]}const N=y*a*l+E*l+x*h+I;_[N]=S}}if(o==="relu")for(let y=0;y<_.length;y++)_[y]=Math.max(0,_[y]);else if(o==="swish")for(let y=0;y<_.length;y++)_[y]=_[y]*Yt(_[y]);return _}function ko(c,e,t,n,r="avg"){const[s,o]=e;let i=Math.floor(o/(t*n));i<1&&(i=1);const a=r==="avg_max"?i*2:i,l=new Float64Array(s*a);for(let u=0;u<s;u++)for(let h=0;h<i;h++){let f=0,d=-1/0;for(let m=0;m<t*n;m++){const _=c[u*o+h*t*n+m]??0;f+=_,d=Math.max(d,_)}const p=f/(t*n);r==="avg"?l[u*a+h]=p:r==="max"?l[u*a+h]=d:(l[u*a+h]=p,l[u*a+i+h]=d)}return{data:l,shape:[s,a]}}function Mo(c,e,t=42){const n=e*9,r=Math.max(c,n),s=Math.max(c,n);let o=t;function i(){o^=o<<13,o^=o>>17,o^=o<<5;const f=(o>>>0)/4294967295;o^=o<<13,o^=o>>17,o^=o<<5;const d=(o>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,f)))*Math.cos(2*Math.PI*d)}const a=new Float64Array(r*s);for(let f=0;f<r*s;f++)a[f]=i();const l=new Float64Array(r*s);for(let f=0;f<Math.min(r,s);f++){for(let p=0;p<s;p++)l[f*s+p]=a[f*s+p];for(let p=0;p<f;p++){let m=0,_=0;for(let y=0;y<s;y++)m+=l[f*s+y]*l[p*s+y],_+=l[p*s+y]*l[p*s+y];if(_>1e-12){const y=m/_;for(let x=0;x<s;x++)l[f*s+x]-=y*l[p*s+x]}}let d=0;for(let p=0;p<s;p++)d+=l[f*s+p]*l[f*s+p];if(d=Math.sqrt(d),d>1e-12)for(let p=0;p<s;p++)l[f*s+p]/=d}const u=new Float64Array(c*e*9),h=Math.sqrt(2/n)*Math.sqrt(n);for(let f=0;f<c;f++)for(let d=0;d<n&&d<s;d++)u[f*n+d]=l[f*s+d]*h;return u}function Oo(c,e,t=42){const r=Math.floor(1.5),s=8,o=[.5,1,1.5],i=[0,Math.PI/2],a=1,l=.5,u=[];for(let m=0;m<s;m++){const _=m*Math.PI/s,y=Math.cos(_),x=Math.sin(_);for(const v of o)for(const E of i){const I=new Float64Array(9);for(let A=0;A<3;A++)for(let O=0;O<3;O++){const R=O-r,T=A-r,F=R*y+T*x,C=-R*x+T*y,V=Math.exp(-(F*F+l*l*C*C)/(2*a*a)),X=Math.cos(2*Math.PI*v*F+E);I[A*3+O]=V*X}let S=0;for(let A=0;A<9;A++)S+=I[A]/9;for(let A=0;A<9;A++)I[A]-=S;let N=0;for(let A=0;A<9;A++)N+=I[A]*I[A];if(N=Math.sqrt(N),N>1e-6)for(let A=0;A<9;A++)I[A]/=N;u.push(I)}}const h=new Float64Array(c*e*9),f=u.length;let d=t;function p(){d^=d<<13,d^=d>>17,d^=d<<5;const m=(d>>>0)/4294967295;d^=d<<13,d^=d>>17,d^=d<<5;const _=(d>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,m)))*Math.cos(2*Math.PI*_)}for(let m=0;m<c;m++)if(m<f)for(let _=0;_<e;_++){const y=u[m];for(let x=0;x<9;x++)h[m*e*9+_*9+x]=y[x]}else{const _=e*9,y=Math.sqrt(2/_);for(let x=0;x<e;x++)for(let v=0;v<9;v++)h[m*e*9+x*9+v]=p()*y}return h}function Co(c,e,t,n,r,s,o=42,i=1e4,a=50){const l=n[0],u=3,h=Math.floor(u/2),f=e*u*u;let d=o;function p(v){return d^=d<<13,d^=d>>17,d^=d<<5,(d>>>0)%v}const m=new Float64Array(i*f);for(let v=0;v<i;v++){const E=p(l),I=h+p(r-u+1),S=h+p(s-u+1);for(let N=0;N<e;N++)for(let A=0;A<u;A++)for(let O=0;O<u;O++){const R=E*e*r*s+N*r*s+(I-h+A)*s+(S-h+O);m[v*f+N*u*u+A*u+O]=t[R]??0}}for(let v=0;v<i;v++){let E=0;for(let S=0;S<f;S++)E+=m[v*f+S]/f;for(let S=0;S<f;S++)m[v*f+S]-=E;let I=0;for(let S=0;S<f;S++)I+=m[v*f+S]*m[v*f+S];I=Math.sqrt(I),I<1e-6&&(I=1);for(let S=0;S<f;S++)m[v*f+S]/=I}const _=new Float64Array(c*f),y=p(i);for(let v=0;v<f;v++)_[v]=m[y*f+v];for(let v=1;v<c;v++){const E=new Float64Array(i);let I=0;for(let A=0;A<i;A++){let O=1/0;for(let R=0;R<v;R++){let T=0;for(let F=0;F<f;F++){const C=m[A*f+F]-_[R*f+F];T+=C*C}O=Math.min(O,T)}E[A]=O,I+=O}let S=p(1e6)/1e6*I,N=0;for(let A=0;A<i;A++)if(S-=E[A],S<=0){N=A;break}for(let A=0;A<f;A++)_[v*f+A]=m[N*f+A]}const x=new Int32Array(i);for(let v=0;v<a;v++){for(let N=0;N<i;N++){let A=1/0,O=0;for(let R=0;R<c;R++){let T=0;for(let F=0;F<f;F++){const C=m[N*f+F]-_[R*f+F];T+=C*C}T<A&&(A=T,O=R)}x[N]=O}const E=new Float64Array(c*f),I=new Int32Array(c);for(let N=0;N<i;N++){const A=x[N];I[A]++;for(let O=0;O<f;O++)E[A*f+O]+=m[N*f+O]}for(let N=0;N<c;N++)if(I[N]>0)for(let A=0;A<f;A++)E[N*f+A]/=I[N];else for(let A=0;A<f;A++)E[N*f+A]=_[N*f+A];let S=0;for(let N=0;N<c*f;N++)S=Math.max(S,Math.abs(E[N]-_[N]));for(let N=0;N<c*f;N++)_[N]=E[N];if(S<1e-6)break}return _}function Cn(c,e,t,n,r,s,o){const i=new Float64Array(e*t*o);for(let a=0;a<e;a++)for(let l=0;l<t;l++)for(let u=0;u<o;u++){let h=0;for(let f=0;f<n;f++)h+=c[a*t*n+l*n+f]*r[f*o+u];i[a*t*o+l*o+u]=h}return i}const Or=1e-15,Tn=1-1e-15;function Xt(c){const e=Math.max(Or,Math.min(Tn,c));return Math.log(e/(1-e))}function Rn(c){return Yt(c)}function Nt(c,e){return On(c,e)}const Cr=new Set(["propagate","conv","pool"]);function At(c,e,t,n,r){const s=c,o=[];return(n==="out"||n==="both")&&o.push(...s.neighbors(e,r,t||null,"out")),(n==="in"||n==="both")&&o.push(...s.neighbors(e,r,t||null,"in")),o}class _e extends q{constructor(t,n=.5,r="none",s=""){super();b(this,"layers");b(this,"alpha");b(this,"gating");b(this,"graphName");b(this,"embedMode");b(this,"_gridShape");if(t.length===0)throw new Error("deep_fusion requires at least one layer");if(Cr.has(t[0].type))throw new Error("deep_fusion: first layer must be a SignalLayer or EmbedLayer (no scores to propagate or convolve)");let o=!1;for(const i of t){if(Cr.has(i.type)&&o)throw new Error("deep_fusion: spatial layers (propagate, convolve, pool) must not appear after flatten() or global_pool()");if((i.type==="flatten"||i.type==="global_pool")&&(o=!0),i.type==="pool"&&i.poolSize<2)throw new Error("deep_fusion: pool() pool_size must be >= 2");if(i.type==="dropout"){const a=i.p;if(a<=0||a>=1)throw new Error("deep_fusion: dropout() p must be in (0, 1)")}}if(this.layers=t,this.alpha=n,this.gating=r,this.graphName=s,this.embedMode=t[0].type==="embed",this.embedMode){const i=t[0];i.gridH>0&&i.gridW>0?this._gridShape=[i.gridH,i.gridW]:this._gridShape=null}else this._gridShape=null}execute(t){let n=new Map,r=1,s=!1;if(this._gridShape!==null){const o=this._executeGrid(n,r,s,t);n=o.channelMap,r=o.numChannels,s=o.softmaxApplied}else for(const o of this.layers)switch(o.type){case"embed":_e._executeEmbedLayer(o,n);break;case"signal":this._executeSignalLayer(o,t,n,r);break;case"propagate":this._executePropagateLayer(o,t,n,r);break;case"conv":this._executeConvLayer(o,t,n);break;case"pool":this._executePoolLayer(o,t,n);break;case"dense":this._executeDenseLayer(o,n),r=o.outputChannels;break;case"flatten":{const i=_e._executeFlattenLayer(n);n=i.channelMap,r=i.numChannels;break}case"global_pool":{const i=_e._executeGlobalPoolLayer(o,n);n=i.channelMap,r=i.numChannels;break}case"softmax":_e._executeSoftmaxLayer(n),s=!0;break;case"batchnorm":_e._executeBatchNormLayer(o,n);break;case"dropout":_e._executeDropoutLayer(o,n);break;case"attention":this._executeAttentionLayer(o,n);break}return _e._buildResult(n,r,s)}static _buildResult(t,n,r){if(t.size===0)return new D;const o=[...t.keys()].sort((i,a)=>i-a).map(i=>{const a=t.get(i);if(r){let l=-1/0;for(let h=0;h<a.length;h++)a[h]>l&&(l=a[h]);const u=Array.from(a);return{docId:i,payload:U({score:l,fields:{class_probs:u}})}}else if(n===1){const l=Rn(a[0]??0);return{docId:i,payload:U({score:l})}}else{const l=wo(a);let u=-1/0;for(let h=0;h<l.length;h++)l[h]>u&&(u=l[h]);return{docId:i,payload:U({score:u})}}});return D.fromSorted(o)}_executeSignalLayer(t,n,r,s){const o=t.signals,i=o.map(p=>p.execute(n)),a=new Set,l=[];for(const p of i){const m=new Map;for(const _ of p)m.set(_.docId,_.payload.score),a.add(_.docId);l.push(m)}if(a.size===0)return;const u=a.size,h=l.map(p=>ct(p.size,u)),f=this.alpha,d=this.gating;if(o.length===1){const p=l[0],m=h[0];for(const _ of a){const y=p.get(_)??m;let x=Xt(y);x=Nt(x,d),r.has(_)||r.set(_,new Float64Array(s)),r.get(_)[0]+=x}}else for(const p of a){const m=[];for(let x=0;x<l.length;x++)m.push(l[x].get(p)??h[x]);const _=K.logOddsConjunction(m,f,void 0,"none");let y=Xt(_);y=Nt(y,d),r.has(p)||r.set(p,new Float64Array(s)),r.get(p)[0]+=y}}_executePropagateLayer(t,n,r,s){const o=n.graphStore;if(o==null)throw new Error("deep_fusion propagate layer requires a graph_store in ExecutionContext");const i=new Map;for(const[m,_]of r)i.set(m,Rn(_[0]));const a=new Map,{direction:l,edgeLabel:u,aggregation:h}=t,f=this.graphName,d=this.gating,p=new Set(r.keys());for(const m of[...p]){const _=At(o,m,u,l,f);for(const y of _)p.add(y)}for(const m of p){const _=[],y=At(o,m,u,l,f);for(const S of y){const N=i.get(S);N!==void 0&&_.push(N)}if(_.length===0){r.has(m)&&a.set(m,new Float64Array(r.get(m)));continue}let x;h==="mean"?x=_.reduce((S,N)=>S+N,0)/_.length:h==="sum"?x=Math.min(Tn,_.reduce((S,N)=>S+N,0)):h==="max"?x=Math.max(..._):x=_.reduce((S,N)=>S+N,0)/_.length;let v=Xt(x);v=Nt(v,d);const E=r.get(m);let I;E!==void 0?(I=new Float64Array(E),I[0]=E[0]+v):(I=new Float64Array(s),I[0]=v),a.set(m,I)}r.clear();for(const[m,_]of a)r.set(m,_)}_executeConvLayer(t,n,r){const s=n.graphStore;if(s==null)throw new Error("deep_fusion convolve layer requires a graph_store in ExecutionContext");const o=this.embedMode,i=new Map;for(const[_,y]of r)i.set(_,o?y[0]:Rn(y[0]));const a=t.hopWeights.reduce((_,y)=>_+y,0);if(a<=0)return;const l=t.hopWeights.map(_=>_/a),u=new Map,{edgeLabel:h,direction:f}=t,d=this.graphName,p=this.gating,m=t.hopWeights.length-1;for(const _ of[...r.keys()]){let y=0;const x=i.get(_);x!==void 0&&(y+=l[0]*x);let v=new Set([_]);const E=new Set([_]);for(let S=1;S<=m;S++){const N=new Set;for(const A of v)for(const O of At(s,A,h,f,d))E.has(O)||(N.add(O),E.add(O));if(N.size>0){const A=[];for(const O of N){const R=i.get(O);R!==void 0&&A.push(R)}if(A.length>0){const O=A.reduce((R,T)=>R+T,0)/A.length;y+=l[S]*O}}v=N}const I=new Float64Array(r.get(_));if(o)I[0]=Nt(y,p);else{let S=Xt(Math.max(Or,Math.min(Tn,y)));S=Nt(S,p),I[0]=r.get(_)[0]+S}u.set(_,I)}r.clear();for(const[_,y]of u)r.set(_,y)}_executePoolLayer(t,n,r){const s=n.graphStore;if(s==null)throw new Error("deep_fusion pool layer requires a graph_store in ExecutionContext");const{edgeLabel:o,direction:i,poolSize:a,method:l}=t,u=this.graphName,h=new Set(r.keys()),f=new Map;for(;h.size>0;){const d=Math.min(...h);h.delete(d);const p=[d];let m=new Set([d]);const _=new Set([d]);for(;p.length<a&&m.size>0;){const E=new Set;for(const I of m){for(const S of At(s,I,o,i,u))if(!_.has(S)&&(_.add(S),E.add(S),h.has(S)&&(p.push(S),h.delete(S),p.length>=a)))break;if(p.length>=a)break}m=E}const y=r.get(p[0]).length,x=new Float64Array(y);if(l==="max"){x.fill(-1/0);for(const E of p){const I=r.get(E);for(let S=0;S<y;S++)x[S]=Math.max(x[S],I[S])}}else for(const E of p){const I=r.get(E);for(let S=0;S<y;S++)x[S]+=I[S]/p.length}const v=Math.min(...p);f.set(v,x)}r.clear();for(const[d,p]of f)r.set(d,p)}_executeDenseLayer(t,n){const r=[...n.keys()].sort((h,f)=>h-f);if(r.length===0)return;const s=n.get(r[0]).length,o=r.length,i=new Float64Array(o*s);for(let h=0;h<o;h++)i.set(n.get(r[h]),h*s);const a=new Float64Array(t.weights),l=new Float64Array(t.bias),u=Io(i,[o,s],a,[t.outputChannels,t.inputChannels],l,this.gating);for(let h=0;h<o;h++)n.set(r[h],u.data.slice(h*t.outputChannels,(h+1)*t.outputChannels))}static _executeFlattenLayer(t){if(t.size===0)return{channelMap:new Map,numChannels:0};const n=[...t.keys()].sort((u,h)=>u-h),r=[];for(const u of n)r.push(t.get(u));let s=0;for(const u of r)s+=u.length;const o=new Float64Array(s);let i=0;for(const u of r)o.set(u,i),i+=u.length;const a=n[0],l=new Map;return l.set(a,o),{channelMap:l,numChannels:s}}static _executeGlobalPoolLayer(t,n){if(n.size===0)return{channelMap:new Map,numChannels:0};const r=[...n.keys()].sort((h,f)=>h-f),s=n.get(r[0]).length,o=r.length;if(t.method==="avg"){const h=new Float64Array(s);for(const d of r){const p=n.get(d);for(let m=0;m<s;m++)h[m]+=p[m]/o}const f=new Map;return f.set(r[0],h),{channelMap:f,numChannels:s}}if(t.method==="max"){const h=new Float64Array(s).fill(-1/0);for(const d of r){const p=n.get(d);for(let m=0;m<s;m++)h[m]=Math.max(h[m],p[m])}const f=new Map;return f.set(r[0],h),{channelMap:f,numChannels:s}}const i=new Float64Array(s),a=new Float64Array(s).fill(-1/0);for(const h of r){const f=n.get(h);for(let d=0;d<s;d++)i[d]+=f[d]/o,a[d]=Math.max(a[d],f[d])}const l=new Float64Array(s*2);l.set(i,0),l.set(a,s);const u=new Map;return u.set(r[0],l),{channelMap:u,numChannels:s*2}}static _executeSoftmaxLayer(t){const n=[...t.keys()].sort((a,l)=>a-l);if(n.length===0)return;const r=t.get(n[0]).length,s=n.length,o=new Float64Array(s*r);for(let a=0;a<s;a++)o.set(t.get(n[a]),a*r);const i=No(o,[s,r]);for(let a=0;a<s;a++)t.set(n[a],i.slice(a*r,(a+1)*r))}static _executeBatchNormLayer(t,n){if(n.size<2)return;const r=[...n.keys()].sort((u,h)=>u-h),s=n.get(r[0]).length,o=r.length,i=t.epsilon??1e-5,a=new Float64Array(o*s);for(let u=0;u<o;u++)a.set(n.get(r[u]),u*s);const l=Ao(a,[o,s],i);for(let u=0;u<o;u++)n.set(r[u],l.slice(u*s,(u+1)*s))}static _executeDropoutLayer(t,n){const r=1-t.p;for(const[s,o]of n){const i=new Float64Array(o.length);for(let a=0;a<o.length;a++)i[a]=o[a]*r;n.set(s,i)}}_executeAttentionLayer(t,n){if(n.size===0)return;const r=[...n.keys()].sort((f,d)=>f-d),s=n.get(r[0]).length,o=r.length,i=new Float64Array(o*s);for(let f=0;f<o;f++)i.set(n.get(r[f]),f*s);const a=t.qWeights&&t.qShape?new Float64Array(t.qWeights):null,l=t.kWeights&&t.kShape?new Float64Array(t.kWeights):null,u=t.vWeights&&t.vShape?new Float64Array(t.vWeights):null,h=Mr(i,[1,o,s],t.nHeads,a,l,u,this.gating);for(let f=0;f<o;f++)n.set(r[f],h.slice(f*s,(f+1)*s))}static _executeEmbedLayer(t,n){if(t.embedding)for(let r=0;r<t.embedding.length;r++)n.set(r+1,new Float64Array([t.embedding[r]]))}_executeGrid(t,n,r,s){const[o,i]=this._gridShape,a=[];let l=[];const u=[],h=this.layers.filter(A=>A.type!=="embed");let f=0;for(;f<h.length;){const A=h[f];if(A.type==="conv"){const O=A;let R=2,T="max";if(f+1<h.length&&h[f+1].type==="pool"){const V=h[f+1];R=V.poolSize,T=V.method,f+=2}else f+=1;let F,C;O.kernel!=null&&O.kernelShape!=null?(F=new Float64Array(O.kernel),C=[...O.kernelShape]):(F=So([...O.hopWeights]),C=[1,1,3,3]),l.push({kernel:F,kernelShape:C,poolSize:R,poolMethod:T})}else A.type==="attention"?(l.length>0&&(a.push(["conv_pool",l]),l=[]),a.push(["attention",A]),f+=1):A.type==="global_pool"?(l.length>0&&(a.push(["conv_pool",l]),l=[]),a.push(["global_pool",A]),f+=1):(l.length>0&&(a.push(["conv_pool",l]),l=[]),u.push(A),f+=1)}l.length>0&&a.push(["conv_pool",l]);const p=this.layers[0].embedding??[];let m=new Float64Array(p),_=o,y=i;const x=1;for(const[A,O]of a)if(A==="conv_pool"){const R=O;m=Eo(m,[x,m.length],_,y,R,this.gating).data;for(const F of R)_=Math.floor(_/F.poolSize),y=Math.floor(y/F.poolSize)}else if(A==="attention"){const R=O,T=Math.floor(m.length/(_*y)),F=_*y,C=new Float64Array(F*T);for(let pe=0;pe<F;pe++)for(let Ne=0;Ne<T;Ne++)C[pe*T+Ne]=m[Ne*F+pe]??0;const V=R.qWeights&&R.qShape?new Float64Array(R.qWeights):null,X=R.kWeights&&R.kShape?new Float64Array(R.kWeights):null,he=R.vWeights&&R.vShape?new Float64Array(R.vWeights):null,pt=Mr(C,[1,F,T],R.nHeads,V,X,he,this.gating);m=new Float64Array(T*F);for(let pe=0;pe<F;pe++)for(let Ne=0;Ne<T;Ne++)m[Ne*F+pe]=pt[pe*T+Ne]}else{const R=O;m=ko(m,[x,m.length],_,y,R.method).data,_=1,y=1}const v=new Map;if(a.some(([A])=>A==="global_pool"))v.set(1,m),n=m.length;else{for(let A=0;A<m.length;A++)v.set(A+1,new Float64Array([m[A]]));n=1}let I=v,S=n,N=r;for(const A of u)switch(A.type){case"flatten":{const O=_e._executeFlattenLayer(I);I=O.channelMap,S=O.numChannels;break}case"global_pool":{const O=_e._executeGlobalPoolLayer(A,I);I=O.channelMap,S=O.numChannels;break}case"dense":this._executeDenseLayer(A,I),S=A.outputChannels;break;case"softmax":_e._executeSoftmaxLayer(I),N=!0;break;case"batchnorm":_e._executeBatchNormLayer(A,I);break;case"dropout":_e._executeDropoutLayer(A,I);break}return{channelMap:I,numChannels:S,softmaxApplied:N}}costEstimate(t){let n=0;for(const r of this.layers)switch(r.type){case"signal":for(const s of r.signals)n+=s.costEstimate(t);break;case"embed":n+=(r.embedding??[]).length;break;case"propagate":case"conv":case"pool":n+=t.totalDocs;break;case"dense":n+=r.inputChannels*r.outputChannels;break;case"flatten":case"global_pool":case"softmax":case"batchnorm":case"dropout":n+=t.totalDocs;break;case"attention":n+=t.totalDocs**2;break}return n}}function To(c,e,t,n,r,s="embedding"){const o=e,i=c,a=new Map;for(const f of o.docIds){const d=o.getField(f,s);if(d!=null){const p=d instanceof Float64Array?d:new Float64Array(d);let m=0;for(let _=0;_<p.length;_++)m+=p[_]*p[_];if(m=Math.sqrt(m),m>0){const _=new Float64Array(p.length);for(let y=0;y<p.length;y++)_[y]=p[y]/m;a.set(f,_)}}}if(a.size<2){const f=1/(n+1);return new Array(n+1).fill(f)}const l=[];for(let f=0;f<=n;f++)l.push([]);for(const[f,d]of a){l[0].push(1);let p=new Set([f]);const m=new Set([f]);for(let _=1;_<=n;_++){const y=new Set;for(const x of p)for(const v of At(i,x,t,"both",r))m.has(v)||(y.add(v),m.add(v));for(const x of y){const v=a.get(x);if(v!==void 0){let E=0;for(let I=0;I<d.length;I++)E+=d[I]*v[I];l[_].push(E)}}p=y}}const u=[];for(let f=0;f<=n;f++){const d=l[f];if(d.length>0){const p=d.reduce((m,_)=>m+_,0)/d.length;u.push(Math.max(0,p))}else u.push(0)}const h=u.reduce((f,d)=>f+d,0);if(h<=0){const f=1/(n+1);return new Array(n+1).fill(f)}return u.map(f=>f/h)}class Qt extends q{constructor(t,n,r){super();b(this,"path");b(this,"predicate");b(this,"source");this.path=t,this.predicate=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;const r=Zn(this.predicate);let s;this.source?s=this.source.execute(t).entries.map(i=>i.docId):s=[...n.docIds].sort((i,a)=>i-a);const o=[];for(const i of s){const a=n.evalPath(i,this.path);if(Array.isArray(a))a.some(l=>this.predicate.evaluate(l))&&o.push({docId:i,payload:U({score:0})});else{if(!r&&a==null)continue;this.predicate.evaluate(a)&&o.push({docId:i,payload:U({score:0})})}}return D.fromSorted(o)}costEstimate(t){return this.source?this.source.costEstimate(t):t.totalDocs}}class Ro extends q{constructor(t,n){super();b(this,"paths");b(this,"source");this.paths=t,this.source=n}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return n;const s=[];for(const o of n){const i={};for(const a of this.paths){const l=r.evalPath(o.docId,a),u=a.join(".");i[u]=l}s.push({docId:o.docId,payload:U({positions:o.payload.positions,score:o.payload.score,fields:{...o.payload.fields,...i}})})}return D.fromSorted(s)}costEstimate(t){return this.source.costEstimate(t)}}class Fo extends q{constructor(t,n){super();b(this,"path");b(this,"source");this.path=t,this.source=n}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return n;const s=[];for(const o of n){const i=r.evalPath(o.docId,this.path);if(Array.isArray(i))for(const a of i)s.push({docId:o.docId,payload:U({positions:o.payload.positions,score:o.payload.score,fields:{...o.payload.fields,_unnested_data:a}})});else s.push(o)}return new D(s)}costEstimate(t){return this.source.costEstimate(t)*2}}class Po extends q{constructor(t,n,r){super();b(this,"path");b(this,"monoid");b(this,"source");this.path=t,this.monoid=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;let r;this.source?r=this.source.execute(t).entries.map(o=>o.docId):r=[...n.docIds].sort((o,i)=>o-i);const s=[];for(const o of r){const i=n.evalPath(o,this.path);let a=this.monoid.identity();if(Array.isArray(i))for(const h of i)h!=null&&(a=this.monoid.accumulate(a,h));else i!=null&&(a=this.monoid.accumulate(a,i));const l=this.monoid.finalize(a),u=typeof l=="number"?l:0;s.push({docId:o,payload:U({score:u,fields:{_path_agg_result:l,_path_agg_path:this.path.join(".")}})})}return D.fromSorted(s)}costEstimate(t){return this.source?this.source.costEstimate(t):t.totalDocs}}class dt extends q{constructor(t,n,r){super();b(this,"signals");b(this,"attention");b(this,"queryFeatures");this.signals=t,this.attention=n,this.queryFeatures=r}execute(t){const n=this.signals.map(l=>l.execute(t)),r=[],s=new Set;let o=0;for(const l of n){const u=new Map;for(const h of l)u.set(h.docId,h.payload.score),s.add(h.docId);r.push(u),o=Math.max(o,u.size)}const i=r.map(l=>ct(l.size,o)),a=[];for(const l of s){const u=[];for(let f=0;f<r.length;f++)u.push(r[f].get(l)??i[f]);const h=this.attention.fuse(u,this.queryFeatures);a.push({docId:l,payload:U({score:h})})}return new D(a)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class kt extends q{constructor(t,n){super();b(this,"signals");b(this,"learned");this.signals=t,this.learned=n}execute(t){const n=this.signals.map(l=>l.execute(t)),r=[],s=new Set;let o=0;for(const l of n){const u=new Map;for(const h of l)u.set(h.docId,h.payload.score),s.add(h.docId);r.push(u),o=Math.max(o,u.size)}const i=r.map(l=>ct(l.size,o)),a=[];for(const l of s){const u=[];for(let f=0;f<r.length;f++)u.push(r[f].get(l)??i[f]);const h=this.learned.fuse(u);a.push({docId:l,payload:U({score:h})})}return new D(a)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class Mt{}class Ce extends Mt{constructor(t){super();b(this,"name");this.name=t}equals(t){return t instanceof Ce&&t.name===this.name}toString(){return this.name}}class Qe extends Mt{constructor(t,n){super();b(this,"left");b(this,"right");this.left=t,this.right=n}equals(t){return t instanceof Qe&&this.left.equals(t.left)&&this.right.equals(t.right)}toString(){return`${this.left.toString()} / ${this.right.toString()}`}}class Ot extends Mt{constructor(t,n){super();b(this,"left");b(this,"right");this.left=t,this.right=n}equals(t){return t instanceof Ot&&this.left.equals(t.left)&&this.right.equals(t.right)}toString(){return`(${this.left.toString()} | ${this.right.toString()})`}}class Ct extends Mt{constructor(t){super();b(this,"inner");this.inner=t}equals(t){return t instanceof Ct&&this.inner.equals(t.inner)}toString(){return`(${this.inner.toString()})*`}}class Tt extends Mt{constructor(t,n,r){super();b(this,"name");b(this,"minCount");b(this,"maxCount");this.name=t,this.minCount=n,this.maxCount=r}equals(t){return t instanceof Tt&&t.name===this.name&&t.minCount===this.minCount&&t.maxCount===this.maxCount}toString(){return`${this.name}{${String(this.minCount)},${String(this.maxCount)}}`}}function Do(c){const e=[];let t=0;for(;t<c.length;){const n=c[t];if(n===" "||n===" "||n===`
7
+ `;)l+=c[a],a++;if(l.toLowerCase()==="with"){e.push({type:"ENDS_WITH",value:"ENDS WITH",position:r}),t=a;continue}}i!==void 0&&i!=="STARTS_WITH"&&i!=="ENDS_WITH"?e.push({type:i,value:s,position:r}):e.push({type:"IDENTIFIER",value:s,position:r});continue}if(n==="`"){t++;let s="";for(;t<c.length&&c[t]!=="`";)s+=c[t],t++;t<c.length&&t++,e.push({type:"IDENTIFIER",value:s,position:r});continue}if(n==="("){e.push({type:"LPAREN",value:"(",position:r}),t++;continue}if(n===")"){e.push({type:"RPAREN",value:")",position:r}),t++;continue}if(n==="["){e.push({type:"LBRACKET",value:"[",position:r}),t++;continue}if(n==="]"){e.push({type:"RBRACKET",value:"]",position:r}),t++;continue}if(n==="{"){e.push({type:"LBRACE",value:"{",position:r}),t++;continue}if(n==="}"){e.push({type:"RBRACE",value:"}",position:r}),t++;continue}if(n===","){e.push({type:"COMMA",value:",",position:r}),t++;continue}if(n===":"){e.push({type:"COLON",value:":",position:r}),t++;continue}if(n==="|"){e.push({type:"PIPE",value:"|",position:r}),t++;continue}if(n==="+"){t+1<c.length&&c[t+1]==="="?(e.push({type:"PLUS_EQ",value:"+=",position:r}),t+=2):(e.push({type:"PLUS",value:"+",position:r}),t++);continue}if(n==="*"){e.push({type:"STAR",value:"*",position:r}),t++;continue}if(n==="%"){e.push({type:"PERCENT",value:"%",position:r}),t++;continue}if(n==="."){if(t+1<c.length&&c[t+1]==="."){e.push({type:"DOTDOT",value:"..",position:r}),t+=2;continue}e.push({type:"DOT",value:".",position:r}),t++;continue}if(n==="="){e.push({type:"EQ",value:"=",position:r}),t++;continue}if(n==="<"){if(t+1<c.length){if(c[t+1]===">"){e.push({type:"NEQ",value:"<>",position:r}),t+=2;continue}if(c[t+1]==="="){e.push({type:"LTE",value:"<=",position:r}),t+=2;continue}if(c[t+1]==="-"){e.push({type:"ARROW_LEFT",value:"<-",position:r}),t+=2;continue}}e.push({type:"LT",value:"<",position:r}),t++;continue}if(n===">"){if(t+1<c.length&&c[t+1]==="="){e.push({type:"GTE",value:">=",position:r}),t+=2;continue}e.push({type:"GT",value:">",position:r}),t++;continue}if(n==="-"){if(t+1<c.length&&c[t+1]===">"){e.push({type:"ARROW_RIGHT",value:"->",position:r}),t+=2;continue}e.push({type:"DASH",value:"-",position:r}),t++;continue}if(n==="/"){e.push({type:"SLASH",value:"/",position:r}),t++;continue}t++}return e.push({type:"EOF",value:"",position:t}),e}class _o{constructor(e){b(this,"tokens");b(this,"pos");this.tokens=mo(e),this.pos=0}peek(){return this.tokens[this.pos]??{type:k.EOF,value:"",position:-1}}advance(){const e=this.peek();return e.type!==k.EOF&&this.pos++,e}expect(e){const t=this.peek();if(t.type!==e)throw new Error(`Cypher parse error at position ${String(t.position)}: expected ${e}, got ${t.type} ('${t.value}')`);return this.advance()}match(e){return this.peek().type===e?(this.advance(),!0):!1}atClauseStart(){const e=this.peek();return new Set([k.MATCH,k.OPTIONAL,k.CREATE,k.MERGE,k.SET,k.DELETE,k.DETACH,k.RETURN,k.WITH,k.UNWIND]).has(e.type)}parse(){const e=[];for(;this.peek().type!==k.EOF;)e.push(this.parseClause());return po(e)}parseClause(){const e=this.peek();switch(e.type){case k.MATCH:return this.parseMatchClause(!1);case k.OPTIONAL:return this.advance(),this.expect(k.MATCH),this.parseMatchClauseInner(!0);case k.RETURN:return this.parseReturnClause();case k.WITH:return this.parseWithClause();case k.CREATE:return this.parseCreateClause();case k.DELETE:return this.parseDeleteClause(!1);case k.DETACH:return this.advance(),this.expect(k.DELETE),this.parseDeleteClauseInner(!0);case k.SET:return this.parseSetClause();case k.REMOVE:return this.parseRemoveClause();case k.MERGE:return this.parseMergeClause();case k.UNWIND:return this.parseUnwindClause();case k.CALL:return this.parseCallClause();default:throw new Error(`Cypher parse error at position ${String(e.position)}: unexpected token ${e.type} ('${e.value}')`)}}parseMatchClause(e){return this.expect(k.MATCH),this.parseMatchClauseInner(e)}parseMatchClauseInner(e){const t=this.parsePatternList();let n=null;return this.peek().type===k.WHERE&&(this.advance(),n=this.parseExpr()),{kind:"match",patterns:t,optional:e,where:n}}parseReturnClause(){this.expect(k.RETURN);const e=this.match(k.DISTINCT),t=this.parseReturnItems(),n=this.parseOptionalOrderBy(),r=this.parseOptionalSkip(),s=this.parseOptionalLimit();return{kind:"return",items:t,distinct:e,orderBy:n,skip:r,limit:s}}parseWithClause(){this.expect(k.WITH);const e=this.match(k.DISTINCT),t=this.parseReturnItems();let n=null;this.peek().type===k.WHERE&&(this.advance(),n=this.parseExpr());const r=this.parseOptionalOrderBy(),s=this.parseOptionalSkip(),o=this.parseOptionalLimit();return{kind:"with",items:t,distinct:e,where:n,orderBy:r,skip:s,limit:o}}parseCreateClause(){return this.expect(k.CREATE),{kind:"create",patterns:this.parsePatternList()}}parseDeleteClause(e){return this.expect(k.DELETE),this.parseDeleteClauseInner(e)}parseDeleteClauseInner(e){const t=[this.parseExpr()];for(;this.match(k.COMMA);)t.push(this.parseExpr());return{kind:"delete",exprs:t,detach:e}}parseSetClause(){this.expect(k.SET);const e=[];do{const t=this.parseExpr();let n="=";this.peek().type===k.PLUS_EQ?(this.advance(),n="+="):this.expect(k.EQ);const r=this.parseExpr();if(t.kind!=="property_access")throw new Error("SET requires property access on left side");e.push({property:t,value:r,operator:n})}while(this.match(k.COMMA));return{kind:"set",items:e}}parseRemoveClause(){this.expect(k.REMOVE);const e=[this.parseExpr()];for(;this.match(k.COMMA);)e.push(this.parseExpr());return{kind:"remove",items:e}}parseMergeClause(){this.expect(k.MERGE);const t=this.parsePatternList()[0];let n=null,r=null;for(;this.peek().type===k.ON;){this.advance();const s=this.peek();if(s.type===k.CREATE){this.advance(),this.expect(k.SET);const o=[];do{const i=this.parseExpr();let a="=";this.peek().type===k.PLUS_EQ?(this.advance(),a="+="):this.expect(k.EQ);const l=this.parseExpr();if(i.kind!=="property_access")throw new Error("ON CREATE SET requires property access");o.push({property:i,value:l,operator:a})}while(this.match(k.COMMA));n={kind:"set",items:o}}else if(s.type===k.MATCH){this.advance(),this.expect(k.SET);const o=[];do{const i=this.parseExpr();let a="=";this.peek().type===k.PLUS_EQ?(this.advance(),a="+="):this.expect(k.EQ);const l=this.parseExpr();if(i.kind!=="property_access")throw new Error("ON MATCH SET requires property access");o.push({property:i,value:l,operator:a})}while(this.match(k.COMMA));r={kind:"set",items:o}}}return{kind:"merge",pattern:t,onCreate:n,onMatch:r}}parseUnwindClause(){this.expect(k.UNWIND);const e=this.parseExpr();this.expect(k.AS);const t=this.expect(k.IDENTIFIER).value;return{kind:"unwind",expr:e,alias:t}}parseCallClause(){this.expect(k.CALL);let e=this.expect(k.IDENTIFIER).value;for(;this.match(k.DOT);)e+="."+this.expect(k.IDENTIFIER).value;this.expect(k.LPAREN);const t=[];if(this.peek().type!==k.RPAREN)for(t.push(this.parseExpr());this.match(k.COMMA);)t.push(this.parseExpr());this.expect(k.RPAREN);let n=null;if(this.peek().type===k.YIELD)for(this.advance(),n=[this.expect(k.IDENTIFIER).value];this.match(k.COMMA);)n.push(this.expect(k.IDENTIFIER).value);return{kind:"call",procedure:e,args:t,yields:n}}parsePatternList(){const e=[this.parsePathPattern()];for(;this.match(k.COMMA);)e.push(this.parsePathPattern());return e}parsePathPattern(){const e=[];for(e.push(this.parseNodePattern());this.isRelationshipStart();)e.push(this.parseRelationshipPattern()),e.push(this.parseNodePattern());return fo(e)}isRelationshipStart(){const e=this.peek().type;return e===k.DASH||e===k.ARROW_LEFT||e===k.ARROW_RIGHT}parseNodePattern(){this.expect(k.LPAREN);let e=null;const t=[],n=new Map;for(this.peek().type===k.IDENTIFIER&&(e=this.advance().value);this.peek().type===k.COLON;)this.advance(),t.push(this.expect(k.IDENTIFIER).value);return this.peek().type===k.LBRACE&&this.parsePropertyMap(n),this.expect(k.RPAREN),Nr(e,t,n)}parseRelationshipPattern(){let e="both",t=!1;this.peek().type===k.ARROW_LEFT?(this.advance(),t=!0):this.expect(k.DASH);let n=null;const r=[],s=new Map;let o=null,i=null;if(this.peek().type===k.LBRACKET){for(this.advance(),this.peek().type===k.IDENTIFIER&&(n=this.advance().value);this.peek().type===k.COLON;)for(this.advance(),r.push(this.expect(k.IDENTIFIER).value);this.match(k.PIPE);)this.peek().type===k.COLON&&this.advance(),r.push(this.expect(k.IDENTIFIER).value);this.peek().type===k.STAR&&(this.advance(),this.peek().type===k.INTEGER&&(o=parseInt(this.advance().value,10)),this.match(k.DOTDOT)?this.peek().type===k.INTEGER&&(i=parseInt(this.advance().value,10)):o!==null&&(i=o)),this.peek().type===k.LBRACE&&this.parsePropertyMap(s),this.expect(k.RBRACKET)}return this.peek().type===k.ARROW_RIGHT?(this.advance(),e=t?"both":"out"):(this.expect(k.DASH),e=t?"in":"both"),Ar({variable:n,types:r,properties:s,direction:e,minHops:o,maxHops:i})}parsePropertyMap(e){if(this.expect(k.LBRACE),this.peek().type!==k.RBRACE){const t=this.expect(k.IDENTIFIER).value;this.expect(k.COLON);const n=this.parseExpr();for(e.set(t,n);this.match(k.COMMA);){const r=this.expect(k.IDENTIFIER).value;this.expect(k.COLON);const s=this.parseExpr();e.set(r,s)}}this.expect(k.RBRACE)}parseReturnItems(){const e=[this.parseReturnItem()];for(;this.match(k.COMMA);)e.push(this.parseReturnItem());return e}parseReturnItem(){if(this.peek().type===k.STAR)return this.advance(),{expr:Sr("*"),alias:null};const e=this.parseExpr();let t=null;return this.match(k.AS)&&(t=this.expect(k.IDENTIFIER).value),{expr:e,alias:t}}parseOptionalOrderBy(){if(this.peek().type!==k.ORDER)return null;this.advance(),this.expect(k.BY);const e=[this.parseOrderByItem()];for(;this.match(k.COMMA);)e.push(this.parseOrderByItem());return e}parseOrderByItem(){const e=this.parseExpr();let t=!0;return this.peek().type===k.DESC?(this.advance(),t=!1):this.peek().type===k.ASC&&this.advance(),{expr:e,ascending:t}}parseOptionalSkip(){return this.peek().type!==k.SKIP?null:(this.advance(),this.parseExpr())}parseOptionalLimit(){return this.peek().type!==k.LIMIT?null:(this.advance(),this.parseExpr())}parseExpr(){return this.parseOr()}parseOr(){let e=this.parseXor();for(;this.peek().type===k.OR;){this.advance();const t=this.parseXor();e=dt("OR",e,t)}return e}parseXor(){let e=this.parseAnd();for(;this.peek().type===k.XOR;){this.advance();const t=this.parseAnd();e=dt("XOR",e,t)}return e}parseAnd(){let e=this.parseNot();for(;this.peek().type===k.AND;){this.advance();const t=this.parseNot();e=dt("AND",e,t)}return e}parseNot(){if(this.peek().type===k.NOT){this.advance();const e=this.parseNot();return Ir("NOT",e)}return this.parseComparison()}parseComparison(){let e=this.parseAddSub();const t=new Set([k.EQ,k.NEQ,k.LT,k.GT,k.LTE,k.GTE,k.STARTS_WITH,k.ENDS_WITH,k.CONTAINS]);for(;t.has(this.peek().type);){const n=this.advance(),r=this.parseAddSub();e=dt(n.value.toUpperCase(),e,r)}if(this.peek().type===k.IS){this.advance();const n=this.match(k.NOT);return this.expect(k.NULL),{kind:"is_null",value:e,negated:n}}if(this.peek().type===k.IN){this.advance();const n=this.parseAddSub();return{kind:"in",value:e,list:n}}return e}parseAddSub(){let e=this.parseMulDiv();for(;this.peek().type===k.PLUS||this.peek().type===k.MINUS;){const t=this.advance(),n=this.parseMulDiv();e=dt(t.value,e,n)}return e}parseMulDiv(){let e=this.parseUnaryExpr();for(;this.peek().type===k.STAR||this.peek().type===k.SLASH||this.peek().type===k.PERCENT;){const t=this.advance(),n=this.parseUnaryExpr();e=dt(t.value,e,n)}return e}parseUnaryExpr(){if(this.peek().type===k.MINUS){this.advance();const e=this.parsePrimary();return Ir("-",e)}return this.parsePrimary()}parsePrimary(){const e=this.peek();switch(e.type){case k.INTEGER:return this.advance(),ft(parseInt(e.value,10));case k.FLOAT:return this.advance(),ft(parseFloat(e.value));case k.STRING:return this.advance(),ft(e.value);case k.TRUE:return this.advance(),ft(!0);case k.FALSE:return this.advance(),ft(!1);case k.NULL:return this.advance(),ft(null);case k.PARAMETER:return this.advance(),uo(e.value);case k.LBRACKET:{this.advance();const t=[];if(this.peek().type!==k.RBRACKET)for(t.push(this.parseExpr());this.match(k.COMMA);)t.push(this.parseExpr());return this.expect(k.RBRACKET),{kind:"list",elements:t}}case k.CASE:return this.parseCaseExpr();case k.EXISTS:{this.advance(),this.expect(k.LPAREN);const t=this.parseNodePattern();return this.expect(k.RPAREN),{kind:"exists",pattern:t}}case k.LPAREN:{this.advance();const t=this.parseExpr();return this.expect(k.RPAREN),t}case k.IDENTIFIER:{if(this.advance(),this.peek().type===k.LPAREN){this.advance();const n=[],r=this.match(k.DISTINCT);if(this.peek().type!==k.RPAREN)for(n.push(this.parseExpr());this.match(k.COMMA);)n.push(this.parseExpr());this.expect(k.RPAREN);const s=r?e.value+"_distinct":e.value;let o=ho(s,n);for(;this.peek().type===k.DOT||this.peek().type===k.LBRACKET;)if(this.peek().type===k.DOT){this.advance();const i=this.expect(k.IDENTIFIER).value;o=Er(o,i)}else{this.advance();const i=this.parseExpr();this.expect(k.RBRACKET),o={kind:"index",value:o,index:i}}return o}let t=Sr(e.value);for(;this.peek().type===k.DOT||this.peek().type===k.LBRACKET;)if(this.peek().type===k.DOT){this.advance();const n=this.expect(k.IDENTIFIER).value;t=Er(t,n)}else{this.advance();const n=this.parseExpr();this.expect(k.RBRACKET),t={kind:"index",value:t,index:n}}return t}default:throw new Error(`Cypher parse error at position ${String(e.position)}: unexpected token ${e.type} ('${e.value}')`)}}parseCaseExpr(){this.expect(k.CASE);let e=null;this.peek().type!==k.WHEN&&(e=this.parseExpr());const t=[];for(;this.peek().type===k.WHEN;){this.advance();const r=this.parseExpr();this.expect(k.THEN);const s=this.parseExpr();t.push({when:r,then:s})}let n=null;return this.match(k.ELSE)&&(n=this.parseExpr()),this.expect(k.END),{kind:"case",operand:e,whens:t,elseExpr:n}}}function Nn(c){return new _o(c).parse()}class Xe{constructor(e){b(this,"__brand","vertex");b(this,"value");this.value=e}}class Wt{constructor(e){b(this,"__brand","edge");b(this,"value");this.value=e}}function Me(c){return c instanceof Xe}function Oe(c){return c instanceof Wt}function fe(c){return c instanceof Xe||c instanceof Wt?c.value:typeof c=="number"?c:null}class yo{constructor(e,t,n){b(this,"_graph");b(this,"_graphName");b(this,"_params");b(this,"_nextDocId");this._graph=e,this._graphName=t,this._params=n??{},this._nextDocId=1}get store(){return this._graph}get graphName(){return this._graphName}execute(e,t){const n=Nn(e);return this.executeAST(n,t)}executePostingList(e,t){const n=Nn(e);return this.executeASTPostingList(n,t)}executeAST(e,t){return this.executeASTPostingList(e,t).toPostingList()}executeASTPostingList(e,t){if(t)for(const[r,s]of Object.entries(t))this._params[r]=s;let n=this._emptyBinding();for(const r of e.clauses)switch(r.kind){case"match":n=this._execMatch(r,n);break;case"create":n=this._execCreate(r,n);break;case"merge":n=this._execMerge(r,n);break;case"set":n=this._execSet(r,n);break;case"delete":n=this._execDelete(r,n);break;case"return":n=this._execReturnPostingList(r,n);break;case"with":n=this._execWith(r,n);break;case"unwind":n=this._execUnwind(r,n);break}return n}executeRows(e,t){const n=Nn(e);return this.executeASTRows(n,t)}executeASTRows(e,t){const n=this.executeASTPostingList(e,t),r=[];for(const s of n){const o={},i=s.payload.fields;for(const a of Object.keys(i))o[a]=i[a];r.push(o)}return r}_emptyBinding(){const e=this._allocDocId(),t={docId:e,payload:U({score:1,fields:{}})},n=new W([t]);return n.setGraphPayload(e,ne()),n}_allocDocId(){const e=this._nextDocId;return this._nextDocId+=1,e}_makeBindingEntry(e,t,n){const r=this._allocDocId();return[{docId:r,payload:U({score:1,fields:{...e}})},r]}_execMatch(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields};let i=this._matchPatterns(e.patterns,o);if(e.where!==null&&(i=i.filter(a=>this._eval(e.where,a))),e.optional&&i.length===0){const a={...o};for(const h of e.patterns)for(const f of h.elements)(Ce(f)&&f.variable!==null||It(f)&&f.variable!==null)&&(f.variable in a||(a[f.variable]=null));const[l,u]=this._makeBindingEntry(a,new Set,new Set);n.push(l),r.set(u,ne())}else for(const a of i){const l=new Set,u=new Set;for(const d of Object.values(a))Me(d)?l.add(d.value):Oe(d)?u.add(d.value):typeof d=="number"&&(this._graph.getVertex(d)!==null?l.add(d):this._graph.getEdge(d)!==null&&u.add(d));const[h,f]=this._makeBindingEntry(a,l,u);n.push(h),r.set(f,ne({subgraphVertices:l,subgraphEdges:u}))}}return new W(n,r)}_matchPatterns(e,t){let n=[{...t}];for(const r of e){const s=[];for(const o of n)s.push(...this._matchPath(r,o));n=s}return n}_matchPath(e,t){const n=e.elements;if(n.length===0)return[{...t}];const r=this._assignAnonVars(n),s=r[0];if(!s||!Ce(s))return[{...t}];const o=this._nodeCandidates(s,t);let i=[];for(const u of o){const h={...t},f=s.variable;if(f!==null){if(f in t){const d=t[f],p=fe(d);if(p!==null&&p!==u.vertexId)continue}h[f]=new Xe(u.vertexId),i.push(h)}}let a=1;for(;a<r.length;){const u=r[a],h=r[a+1];if(!u||!h||!It(u)||!Ce(h))break;const f=[];for(const d of i)f.push(...this._expandRel(d,u,h,r,a));i=f,a+=2}const l=new Set;for(const u of r)if(Ce(u)||It(u)){const h=(Ce(u),u.variable);h!==null&&h.startsWith("_anon_")&&l.add(h)}return l.size>0&&(i=i.map(u=>{const h={};for(const f of Object.keys(u))l.has(f)||(h[f]=u[f]);return h})),i}_assignAnonVars(e){const t=[];for(const n of e)if(Ce(n)&&n.variable===null){const r=`_anon_${this._allocDocId()}`;t.push(Nr(r,[...n.labels],new Map(n.properties)))}else if(It(n)&&n.variable===null){const r=`_anon_${this._allocDocId()}`;t.push(Ar({variable:r,types:[...n.types],properties:new Map(n.properties),direction:n.direction,minHops:n.minHops,maxHops:n.maxHops}))}else t.push(n);return t}_nodeCandidates(e,t){if(e.variable!==null&&e.variable in t){const r=t[e.variable];if(r==null)return[];const s=fe(r);if(s===null)return[];const o=this._graph.getVertex(s);return o!==null&&this._vertexMatches(o,e,t)?[o]:[]}if(!this._graph.hasGraph(this._graphName))return[];let n;if(e.labels.length>0){const r=new Set;n=[];for(const s of e.labels)for(const o of this._graph.verticesByLabel(s,this._graphName))r.has(o.vertexId)||(r.add(o.vertexId),n.push(o))}else n=this._graph.verticesInGraph(this._graphName);return n.filter(r=>this._vertexMatches(r,e,t))}_vertexMatches(e,t,n){if(t.labels.length>0&&!t.labels.includes(e.label))return!1;if(t.properties.size>0){const r=n??{};for(const[s,o]of t.properties){const i=this._eval(o,r);if(e.properties[s]!==i)return!1}}return!0}_expandRel(e,t,n,r,s){const o=r[s-1];if(!o||!Ce(o))return[];const i=o.variable,a=i!==null?e[i]:void 0,l=fe(a);return l===null?[]:t.minHops!==null||t.maxHops!==null?this._expandVarLength(e,l,t,n):this._expandSingleHop(e,l,t,n)}_expandSingleHop(e,t,n,r){const s=[];for(const[o,i]of this._getEdges(t,n)){const a=this._graph.getVertex(i);if(a===null||!this._vertexMatches(a,r,e)||!this._edgeMatches(o,n,e))continue;const l={...e};if(n.variable!==null){if(n.variable in e){const u=fe(e[n.variable]);if(u!==null&&u!==o.edgeId)continue}l[n.variable]=new Wt(o.edgeId)}if(r.variable!==null){if(r.variable in e){const u=fe(e[r.variable]);if(u!==null&&u!==a.vertexId)continue}l[r.variable]=new Xe(a.vertexId)}s.push(l)}return s}_expandVarLength(e,t,n,r){const s=n.minHops!==null?n.minHops:1,o=n.maxHops,i=[],a=[[t,0,[]]];for(;a.length>0;){const l=a.shift(),u=l[0],h=l[1],f=l[2];if(h>=s){const d=this._graph.getVertex(u);if(d!==null&&this._vertexMatches(d,r,e)){const p={...e};if(n.variable!==null&&(p[n.variable]=[...f]),r.variable!==null){if(r.variable in e){const m=fe(e[r.variable]);if(m!==null&&m!==u)continue}p[r.variable]=new Xe(u)}i.push(p)}}if(!(o!==null&&h>=o))for(const[d,p]of this._getEdges(u,n))f.includes(d.edgeId)||this._edgeMatches(d,n,e)&&a.push([p,h+1,[...f,d.edgeId]])}return i}_getEdges(e,t){let n=[];const r=t.direction;if(r==="out"||r==="both")for(const s of this._graph.outEdgeIds(e,this._graphName)){const o=this._graph.getEdge(s);o!==null&&n.push([o,o.targetId])}if(r==="in"||r==="both")for(const s of this._graph.inEdgeIds(e,this._graphName)){const o=this._graph.getEdge(s);o!==null&&n.push([o,o.sourceId])}return t.types.length>0&&(n=n.filter(([s])=>t.types.includes(s.label))),n}_edgeMatches(e,t,n){if(t.properties.size>0){const r=n??{};for(const[s,o]of t.properties){const i=this._eval(o,r);if(e.properties[s]!==i)return!1}}return!0}_execCreate(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields},i=new Set,a=new Set;for(const h of e.patterns)this._createPath(h,o,i,a);const[l,u]=this._makeBindingEntry(o,i,a);n.push(l),r.set(u,ne({subgraphVertices:i,subgraphEdges:a}))}return new W(n,r)}_createPath(e,t,n,r){const s=e.elements;for(let o=0;o<s.length;o++){const i=s[o];if(Ce(i)){if(i.variable!==null&&i.variable in t)continue;const a=this._createVertex(i,t);n.add(a.vertexId),i.variable!==null&&(t[i.variable]=new Xe(a.vertexId))}else if(It(i)){const a=s[o+1];if(!a||!Ce(a))continue;if(a.variable!==null&&!(a.variable in t)){const m=this._createVertex(a,t);n.add(m.vertexId),t[a.variable]=new Xe(m.vertexId)}const l=s[o-1];if(!l||!Ce(l))continue;const u=l.variable!==null?t[l.variable]:void 0,h=a.variable!==null?t[a.variable]:void 0,f=fe(u),d=fe(h);if(f===null||d===null)continue;const p=this._createEdge(i,f,d,t);r.add(p.edgeId),i.variable!==null&&(t[i.variable]=new Wt(p.edgeId))}}}_createVertex(e,t){const n=this._graph.nextVertexId(),r=e.labels.length>0?e.labels[0]:"",s={};for(const[i,a]of e.properties)s[i]=this._eval(a,t);const o=an(n,r,s);return this._graph.addVertex(o,this._graphName),o}_createEdge(e,t,n,r){const s=this._graph.nextEdgeId(),o=e.types.length>0?e.types[0]:"",i={};for(const[h,f]of e.properties)i[h]=this._eval(f,r);let a=t,l=n;e.direction==="in"&&(a=n,l=t);const u=gt(s,a,l,o,i);return this._graph.addEdge(u,this._graphName),u}_execMerge(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields},i=this._matchPath(e.pattern,o);if(i.length>0)for(const a of i){if(e.onMatch!==null)for(const h of e.onMatch.items)this._applySetItem(h,a);const[l,u]=this._makeBindingEntry(a,new Set,new Set);n.push(l),r.set(u,ne())}else{const a=new Set,l=new Set;if(this._createPath(e.pattern,o,a,l),e.onCreate!==null)for(const f of e.onCreate.items)this._applySetItem(f,o);const[u,h]=this._makeBindingEntry(o,a,l);n.push(u),r.set(h,ne({subgraphVertices:a,subgraphEdges:l}))}}return new W(n,r)}_execSet(e,t){const n=[],r=new Map;for(const s of t){const o={...s.payload.fields};for(const l of e.items)this._applySetItem(l,o);const[i,a]=this._makeBindingEntry(o,new Set,new Set);n.push(i),r.set(a,ne())}return new W(n,r)}_applySetItem(e,t){const n=this._eval(e.value,t),r=e.property,s=r.object;if(s.kind!=="identifier")return;const o=s.name,i=r.property,a=t[o];if(a!=null){if(!Oe(a)){const l=fe(a);if(l!==null){const u=this._graph.getVertex(l);if(u!==null){const h={...u.properties};h[i]=n;const f=an(u.vertexId,u.label,h);this._graph.addVertex(f,this._graphName);return}}}if(!Me(a)){const l=fe(a);if(l!==null){const u=this._graph.getEdge(l);if(u!==null){const h={...u.properties};h[i]=n;const f=gt(u.edgeId,u.sourceId,u.targetId,u.label,h);this._graph.addEdge(f,this._graphName);return}}}}}_execDelete(e,t){const n=[],r=[];for(const s of t){const o=s.payload.fields;for(const i of e.exprs){const a=this._eval(i,o);a!=null&&(Me(a)?n.push(a.value):Oe(a)?r.push(a.value):typeof a=="number"&&(this._graph.getVertex(a)!==null?n.push(a):this._graph.getEdge(a)!==null&&r.push(a)))}}for(const s of r)this._graph.removeEdge(s,this._graphName);for(const s of n){if(!e.detach){const o=this._graph.outEdgeIds(s,this._graphName).size>0,i=this._graph.inEdgeIds(s,this._graphName).size>0;if(o||i)throw new Error(`Cannot delete vertex ${String(s)}: has incident edges. Use DETACH DELETE.`)}this._graph.removeVertex(s,this._graphName)}return t}_execReturnPostingList(e,t){const n=[...t];if(e.items.some(a=>Be(a.expr)))return this._execReturnWithAggregation(e,n);if(e.orderBy!==null)for(let a=e.orderBy.length-1;a>=0;a--){const l=e.orderBy[a];n.sort((u,h)=>{const f=this._eval(l.expr,u.payload.fields),d=this._eval(l.expr,h.payload.fields),p=Ht(Ge(f),Ge(d));return l.ascending?p:-p})}const s=[],o=new Map;for(const a of n){const l=a.payload.fields,u={};for(const d of e.items){if(d.expr.kind==="identifier"&&d.expr.name==="*"){for(const _ of Object.keys(l))u[_]=this._toAgtype(l[_]);continue}let p=this._eval(d.expr,l);const m=d.alias??Qe(d.expr);d.expr.kind==="identifier"&&(p=this._toAgtype(p)),u[m]=p}const[h,f]=this._makeBindingEntry(u,new Set,new Set);s.push(h),o.set(f,ne())}let i=new W(s,o);if(e.distinct&&(i=this._distinctGpl(i)),e.skip!==null){const a=this._eval(e.skip,{});i=this._sliceGpl(i,typeof a=="number"?a:0,null)}if(e.limit!==null){const a=this._eval(e.limit,{});i=this._sliceGpl(i,0,typeof a=="number"?a:null)}return i}_execReturnWithAggregation(e,t){const n=[],r=[];for(let u=0;u<e.items.length;u++){const h=e.items[u];Be(h.expr)?r.push(u):n.push(u)}const s=new Map,o=[];for(const u of t){const h=u.payload.fields,f=[];for(const m of n){const _=e.items[m],y=this._eval(_.expr,h);f.push(An(y))}const d=f.join("\0"),p=s.get(d);p!==void 0?p.push(u):(s.set(d,[u]),o.push(d))}n.length===0&&t.length===0&&(o.push(""),s.set("",[]));const i=[],a=new Map;for(const u of o){const h=s.get(u)??[],f={},d=h.length>0?h[0].payload.fields:{};for(const _ of n){const y=e.items[_];let x=this._eval(y.expr,d);const v=y.alias??Qe(y.expr);y.expr.kind==="identifier"&&(x=this._toAgtype(x)),f[v]=x}for(const _ of r){const y=e.items[_],x=y.alias??Qe(y.expr);f[x]=this._evalAggregate(y.expr,h.map(v=>v.payload.fields))}const[p,m]=this._makeBindingEntry(f,new Set,new Set);i.push(p),a.set(m,ne())}let l=new W(i,a);if(e.distinct&&(l=this._distinctGpl(l)),e.orderBy!==null&&(l=this._orderByGpl(e.orderBy,l)),e.skip!==null){const u=this._eval(e.skip,{});l=this._sliceGpl(l,typeof u=="number"?u:0,null)}if(e.limit!==null){const u=this._eval(e.limit,{});l=this._sliceGpl(l,0,typeof u=="number"?u:null)}return l}_evalAggregate(e,t){if(e.kind==="function_call"){const n=e,r=n.name.toLowerCase();if(r==="count"){if(n.args.length===0)return t.length;const s=n.args[0];if(s.kind==="identifier"&&s.name==="*")return t.length;let o=0;for(const i of t){const a=this._eval(s,i);a!=null&&o++}return o}if(r==="sum"){const s=n.args[0];let o=0;for(const i of t){const a=this._eval(s,i);typeof a=="number"&&(o+=a)}return o}if(r==="avg"){const s=n.args[0];let o=0,i=0;for(const a of t){const l=this._eval(s,a);typeof l=="number"&&(o+=l,i++)}return i>0?o/i:null}if(r==="min"){const s=n.args[0];let o=null;for(const i of t){const a=this._eval(s,i);a!=null&&(o===null||Ht(Ge(a),Ge(o))<0)&&(o=a)}return o}if(r==="max"){const s=n.args[0];let o=null;for(const i of t){const a=this._eval(s,i);a!=null&&(o===null||Ht(Ge(a),Ge(o))>0)&&(o=a)}return o}if(r==="collect"){const s=n.args[0],o=[];for(const i of t){const a=this._eval(s,i);a!=null&&o.push(a)}return o}}return t.length>0?this._eval(e,t[0]):null}_execWith(e,t){if(e.items.some(i=>Be(i.expr)))return this._execWithAggregation(e,t);const r=[],s=new Map;for(const i of t){const a=i.payload.fields,l={};for(const f of e.items){if(f.expr.kind==="identifier"&&f.expr.name==="*"){Object.assign(l,a);continue}const d=this._eval(f.expr,a),p=f.alias??Qe(f.expr);l[p]=d}const[u,h]=this._makeBindingEntry(l,new Set,new Set);r.push(u),s.set(h,ne())}let o=new W(r,s);if(e.distinct&&(o=this._distinctGpl(o)),e.orderBy!==null&&(o=this._orderByGpl(e.orderBy,o)),e.skip!==null){const i=this._eval(e.skip,{});o=this._sliceGpl(o,typeof i=="number"?i:0,null)}if(e.limit!==null){const i=this._eval(e.limit,{});o=this._sliceGpl(o,0,typeof i=="number"?i:null)}if(e.where!==null){const i=[],a=new Map;for(const l of o)if(this._eval(e.where,l.payload.fields)){i.push(l);const u=o.getGraphPayload(l.docId);u!==null&&a.set(l.docId,u)}o=new W(i,a)}return o}_execWithAggregation(e,t){const n=[...t],r=[],s=[];for(let h=0;h<e.items.length;h++){const f=e.items[h];Be(f.expr)?s.push(h):r.push(h)}const o=new Map,i=[];for(const h of n){const f=h.payload.fields,d=[];for(const _ of r){const y=e.items[_],x=this._eval(y.expr,f);d.push(An(x))}const p=d.join("\0"),m=o.get(p);m!==void 0?m.push(h):(o.set(p,[h]),i.push(p))}r.length===0&&n.length===0&&(i.push(""),o.set("",[]));const a=[],l=new Map;for(const h of i){const f=o.get(h)??[],d={},p=f.length>0?f[0].payload.fields:{};for(const y of r){const x=e.items[y],v=this._eval(x.expr,p),E=x.alias??Qe(x.expr);d[E]=v}for(const y of s){const x=e.items[y],v=x.alias??Qe(x.expr);d[v]=this._evalAggregate(x.expr,f.map(E=>E.payload.fields))}const[m,_]=this._makeBindingEntry(d,new Set,new Set);a.push(m),l.set(_,ne())}let u=new W(a,l);if(e.distinct&&(u=this._distinctGpl(u)),e.orderBy!==null&&(u=this._orderByGpl(e.orderBy,u)),e.skip!==null){const h=this._eval(e.skip,{});u=this._sliceGpl(u,typeof h=="number"?h:0,null)}if(e.limit!==null){const h=this._eval(e.limit,{});u=this._sliceGpl(u,0,typeof h=="number"?h:null)}if(e.where!==null){const h=[],f=new Map;for(const d of u)if(this._eval(e.where,d.payload.fields)){h.push(d);const p=u.getGraphPayload(d.docId);p!==null&&f.set(d.docId,p)}u=new W(h,f)}return u}_execUnwind(e,t){const n=[],r=new Map;for(const s of t){const o=s.payload.fields,i=this._eval(e.expr,o);if(i!=null&&Array.isArray(i))for(const a of i){const l={...o};l[e.alias]=a;const[u,h]=this._makeBindingEntry(l,new Set,new Set);n.push(u),r.set(h,ne())}}return new W(n,r)}_toAgtype(e){if(e==null)return null;if(typeof e=="boolean")return e;if(Me(e)){const t=this._graph.getVertex(e.value);return t!==null?{id:t.vertexId,label:t.label,properties:{...t.properties}}:e.value}if(Oe(e)){const t=this._graph.getEdge(e.value);return t!==null?{id:t.edgeId,label:t.label,start:t.sourceId,end:t.targetId,properties:{...t.properties}}:e.value}if(typeof e=="number"){const t=this._graph.getVertex(e);if(t!==null)return{id:t.vertexId,label:t.label,properties:{...t.properties}};const n=this._graph.getEdge(e);if(n!==null)return{id:n.edgeId,label:n.label,start:n.sourceId,end:n.targetId,properties:{...n.properties}}}return Array.isArray(e)?e.map(t=>this._toAgtype(t)):e}_distinctGpl(e){const t=new Set,n=[],r=new Map;for(const s of e){const o=s.payload.fields,i=[];for(const l of Object.keys(o).sort())i.push([l,An(o[l])]);const a=JSON.stringify(i);if(!t.has(a)){t.add(a),n.push(s);const l=e.getGraphPayload(s.docId);l!==null&&r.set(s.docId,l)}}return new W(n,r)}_orderByGpl(e,t){const n=[...t];for(let s=e.length-1;s>=0;s--){const o=e[s];n.sort((i,a)=>{const l=this._eval(o.expr,i.payload.fields),u=this._eval(o.expr,a.payload.fields),h=Ht(Ge(l),Ge(u));return o.ascending?h:-h})}const r=new Map;for(const s of n){const o=t.getGraphPayload(s.docId);o!==null&&r.set(s.docId,o)}return new W(n,r)}_sliceGpl(e,t,n){const r=[...e],s=n!==null?r.slice(t,t+n):r.slice(t),o=new Map;for(const i of s){const a=e.getGraphPayload(i.docId);a!==null&&o.set(i.docId,a)}return new W(s,o)}_eval(e,t){switch(e.kind){case"literal":return e.value;case"identifier":return t[e.name];case"parameter":return this._params[e.name];case"property_access":return this._evalPropertyAccess(e,t);case"binary_op":return this._evalBinary(e,t);case"unary_op":return this._evalUnary(e,t);case"function_call":return this._evalFunction(e,t);case"in":return this._evalIn(e,t);case"is_null":return this._evalIsNull(e,t);case"list":return e.elements.map(n=>this._eval(n,t));case"case":return this._evalCase(e,t);case"exists":return!1;case"index":{const n=this._eval(e.value,t),r=this._eval(e.index,t);return Array.isArray(n)&&typeof r=="number"?n[r]:null}default:{const n=e;throw new Error(`Cannot evaluate expression kind: ${String(n.kind)}`)}}}_evalPropertyAccess(e,t){let n=this._eval(e.object,t);if(n==null)return null;if(Me(n)){const s=this._graph.getVertex(n.value);s!==null&&(n=s)}else if(Oe(n)){const s=this._graph.getEdge(n.value);s!==null&&(n=s)}else if(typeof n=="number"){const s=this._graph.getVertex(n);if(s!==null)n=s;else{const o=this._graph.getEdge(n);o!==null&&(n=o)}}const r=e.property;return bo(n)||vo(n)?n.properties[r]??null:typeof n=="object"&&n!==null&&!Array.isArray(n)?n[r]??null:null}_evalBinary(e,t){const n=e.op;if(n==="AND")return this._eval(e.left,t)?!!this._eval(e.right,t):!1;if(n==="OR")return this._eval(e.left,t)?!0:!!this._eval(e.right,t);if(n==="XOR")return!!this._eval(e.left,t)!=!!this._eval(e.right,t);const r=this._eval(e.left,t),s=this._eval(e.right,t);if(r==null||s===null||s===void 0)return n==="="?r==null&&s==null:n==="<>"?!(r==null&&s==null):null;switch(n){case"=":return Kt(r,s);case"<>":return!Kt(r,s);case"<":return Jt(r,s)<0;case">":return Jt(r,s)>0;case"<=":return Jt(r,s)<=0;case">=":return Jt(r,s)>=0;case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):Array.isArray(r)?[...r,...Array.isArray(s)?s:[s]]:r+s;case"-":return r-s;case"*":return r*s;case"/":return s===0?null:typeof r=="number"&&typeof s=="number"?Number.isInteger(r)&&Number.isInteger(s)?Math.trunc(r/s):r/s:null;case"%":return r%s;case"^":return Math.pow(r,s);case"STARTS WITH":return String(r).startsWith(String(s));case"ENDS WITH":return String(r).endsWith(String(s));case"CONTAINS":return String(r).includes(String(s));default:throw new Error(`Unknown binary operator: ${n}`)}}_evalUnary(e,t){const n=this._eval(e.operand,t);if(e.op==="NOT")return!n;if(e.op==="-")return n!=null?-n:null;throw new Error(`Unknown unary operator: ${e.op}`)}_evalFunction(e,t){const n=e.name.toLowerCase(),r=e.args;if(n==="id"){const s=r[0];if(!s)return null;const o=s.kind==="identifier"?t[s.name]:this._eval(s,t),i=fe(o);return i!==null?i:typeof o=="number"?o:null}if(n==="type"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.label}return null}if(n==="labels"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return i.label?[i.label]:[]}return null}if(n==="label"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return i.label}return null}if(n==="properties"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return{...i.properties};const a=this._graph.getEdge(o);if(a!==null)return{...a.properties}}return null}if(n==="keys"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getVertex(o);if(i!==null)return Object.keys(i.properties);const a=this._graph.getEdge(o);if(a!==null)return Object.keys(a.properties)}return typeof s=="object"&&s!==null&&!Array.isArray(s)?Object.keys(s):null}if(n==="tostring"||n==="tostr"){const s=r[0]?this._eval(r[0],t):null;return s!=null?String(s):null}if(n==="tointeger"||n==="toint"){const s=r[0]?this._eval(r[0],t):null;if(s==null)return null;const o=parseInt(String(s),10);return Number.isNaN(o)?null:o}if(n==="tofloat"){const s=r[0]?this._eval(r[0],t):null;if(s==null)return null;const o=parseFloat(String(s));return Number.isNaN(o)?null:o}if(n==="size"||n==="length"){const s=r[0]?this._eval(r[0],t):null;return s==null?null:typeof s=="string"||Array.isArray(s)?s.length:null}if(n==="head"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)&&s.length>0?s[0]:null}if(n==="last"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)&&s.length>0?s[s.length-1]:null}if(n==="tail"){const s=r[0]?this._eval(r[0],t):null;return Array.isArray(s)?s.slice(1):[]}if(n==="reverse"){const s=r[0]?this._eval(r[0],t):null;return s==null?null:typeof s=="string"?s.split("").reverse().join(""):Array.isArray(s)?[...s].reverse():null}if(n==="range"){const s=r[0]?this._eval(r[0],t):0,o=r[1]?this._eval(r[1],t):0,i=r[2]?this._eval(r[2],t):1;if(typeof s!="number"||typeof o!="number"||typeof i!="number"||i===0)return[];const a=[];if(i>0)for(let l=s;l<=o;l+=i)a.push(l);else for(let l=s;l>=o;l+=i)a.push(l);return a}if(n==="abs"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="number"?Math.abs(s):null}if(n==="coalesce"){for(const s of r){const o=this._eval(s,t);if(o!=null)return o}return null}if(n==="tolower"||n==="lower"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.toLowerCase():null}if(n==="toupper"||n==="upper"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.toUpperCase():null}if(n==="trim"){const s=r[0]?this._eval(r[0],t):null;return typeof s=="string"?s.trim():null}if(n==="replace"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null,i=r[2]?this._eval(r[2],t):null;return typeof s=="string"&&typeof o=="string"&&typeof i=="string"?s.split(o).join(i):null}if(n==="substring"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null;if(typeof s!="string"||typeof o!="number")return null;if(r[2]){const i=this._eval(r[2],t);if(typeof i=="number")return s.substring(o,o+i)}return s.substring(o)}if(n==="split"){const s=r[0]?this._eval(r[0],t):null,o=r[1]?this._eval(r[1],t):null;return typeof s=="string"&&typeof o=="string"?s.split(o):null}if(n==="startnode"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.sourceId}return null}if(n==="endnode"){const s=r[0]?this._eval(r[0],t):null,o=fe(s);if(o!==null){const i=this._graph.getEdge(o);if(i!==null)return i.targetId}return null}if(n==="count")return 1;if(n==="collect")return[r[0]?this._eval(r[0],t):null];if(n==="sum"||n==="avg"||n==="min"||n==="max")return r[0]?this._eval(r[0],t):null;throw new Error(`Unknown function: ${e.name}`)}_evalIn(e,t){const n=this._eval(e.value,t),r=this._eval(e.list,t);return r==null?null:Array.isArray(r)?r.some(s=>Kt(s,n)):!1}_evalIsNull(e,t){const n=this._eval(e.value,t),r=n==null;return e.negated?!r:r}_evalCase(e,t){if(e.operand!==null){const n=this._eval(e.operand,t);for(const r of e.whens)if(Kt(n,this._eval(r.when,t)))return this._eval(r.then,t)}else for(const n of e.whens)if(this._eval(n.when,t))return this._eval(n.then,t);return e.elseExpr!==null?this._eval(e.elseExpr,t):null}}function Ce(c){return"labels"in c&&!("types"in c)}function It(c){return"types"in c}function bo(c){return typeof c!="object"||c===null?!1:"vertexId"in c&&"label"in c&&"properties"in c}function vo(c){return typeof c!="object"||c===null?!1:"edgeId"in c&&"sourceId"in c&&"targetId"in c}function Qe(c){switch(c.kind){case"identifier":return c.name;case"property_access":{const e=c;return`${Qe(e.object)}.${e.property}`}case"function_call":return c.name;default:return String(c)}}function Ge(c){return c==null?[0,null]:typeof c=="boolean"?[1,c?1:0]:Me(c)?[2,c.value]:Oe(c)?[2,c.value]:typeof c=="number"?[2,c]:typeof c=="string"?[3,c]:[4,String(c)]}function Ht(c,e){if(c[0]!==e[0])return c[0]-e[0];const t=c[1],n=e[1];return t===n?0:t===null?-1:n===null?1:typeof t=="number"&&typeof n=="number"||typeof t=="string"&&typeof n=="string"?t<n?-1:t>n?1:0:0}function Kt(c,e){return c===e?!0:c==null?e==null:e==null?!1:Me(c)?Me(e)?c.value===e.value:typeof e=="number"&&c.value===e:Oe(c)?Oe(e)?c.value===e.value:typeof e=="number"&&c.value===e:typeof c=="number"&&Me(e)||typeof c=="number"&&Oe(e)?c===e.value:c===e}function Jt(c,e){if(typeof c=="number"&&typeof e=="number"||typeof c=="string"&&typeof e=="string")return c<e?-1:c>e?1:0;const t=String(c),n=String(e);return t<n?-1:t>n?1:0}function Be(c){if(c.kind==="function_call"){const e=c,t=e.name.toLowerCase();if(t==="count"||t==="sum"||t==="avg"||t==="min"||t==="max"||t==="collect")return!0;for(const n of e.args)if(Be(n))return!0}if(c.kind==="binary_op"){const e=c;return Be(e.left)||Be(e.right)}return c.kind==="unary_op"?Be(c.operand):!1}function An(c){return c==null?"null":Me(c)?`vref:${String(c.value)}`:Oe(c)?`eref:${String(c.value)}`:typeof c=="object"?JSON.stringify(c):String(c)}class Ne extends q{constructor(t,n){super();b(this,"source");b(this,"threshold");this.source=t,this.threshold=n}execute(t){const n=this.source.execute(t),r=[];for(const s of n){const o=s.payload.score-this.threshold;o>0&&r.push({docId:s.docId,payload:U({positions:s.payload.positions,score:o,fields:s.payload.fields})})}return D.fromSorted(r)}costEstimate(t){return this.source.costEstimate(t)}}class $e extends q{constructor(t){super();b(this,"stages");if(t.length===0)throw new Error("MultiStageOperator requires at least one stage");this.stages=t}execute(t){if(this.stages.length===0)return new D;let n=this.stages[0][0].execute(t);n=kn(n,this.stages[0][1]);for(let r=1;r<this.stages.length;r++){const[s,o]=this.stages[r],i=s.execute(t),a=new Map;for(const u of i)a.set(u.docId,u.payload.score);const l=n.entries.map(u=>({docId:u.docId,payload:U({positions:u.payload.positions,score:a.get(u.docId)??u.payload.score,fields:u.payload.fields})}));n=kn(new D(l),o)}return n}costEstimate(t){let n=0,r=t.totalDocs;for(const[s,o]of this.stages)n+=s.costEstimate(t)*(r/Math.max(t.totalDocs,1)),r=typeof o=="number"&&Number.isInteger(o)?Math.min(o,r):r*.5;return n}static applyCutoff(t,n){return kn(t,n)}}function kn(c,e){if(Number.isInteger(e)&&e>0)return c.topK(e);const t=c.entries.filter(n=>n.payload.score>=e);return new D(t)}class Mn extends q{constructor(t,n,r){super();b(this,"fields");b(this,"query");b(this,"weights");this.fields=t,this.query=n,this.weights=r??t.map(()=>1)}execute(t){const n=t.invertedIndex;if(!n)return new D;const r=n.stats,s=[],o=new Set;for(const u of this.fields){const h=new _e(this.query,u),f=new ct(Je(),r),p=n.getSearchAnalyzer(u).analyze(this.query),_=new pe(f,h,p,u).execute(t),y=new Map;for(const x of _)y.set(x.docId,x.payload.score),o.add(x.docId);s.push(y)}let i=0;for(const u of this.weights)i+=u;const a=this.weights.map(u=>u/i),l=[];for(const u of o){const h=[];for(let d=0;d<this.fields.length;d++)h.push(s[d].get(u)??.5);const f=h.length===1?h[0]:K.logOddsConjunction(h,0,a);l.push({docId:u,payload:U({score:f})})}return new D(l)}costEstimate(t){return t.totalDocs*this.fields.length}}class kr extends q{constructor(t,n=.5,r){super();b(this,"stages");b(this,"alpha");b(this,"gating");this.stages=t,this.alpha=n,this.gating=r??null}execute(t){const n=[];let r=null,s=new D;for(const[o,i]of this.stages){const a=o.map(h=>h.execute(t));if(r!==null)for(let h=0;h<a.length;h++){const f=a[h].entries.filter(d=>r.has(d.docId));a[h]=D.fromSorted(f)}n.push(...a);const l=n.map(h=>{let f=0;for(const d of h)d.payload.score>f&&(f=d.payload.score);return Math.max(f,.01)});s=new dr(n,l,this.alpha,i,this.gating).scoreTopK(),r=new Set(s.entries.map(h=>h.docId))}return s}costEstimate(t){let n=0,r=t.totalDocs;for(const[s,o]of this.stages){for(const i of s)n+=i.costEstimate(t)*(r/Math.max(t.totalDocs,1));r=Math.min(o,r)}return n}}function Yt(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function On(c,e){return e==="relu"?Math.max(0,c):e==="swish"?c*Yt(c):c}function wo(c){const e=new Float64Array(c.length);for(let t=0;t<c.length;t++)e[t]=Yt(c[t]);return e}function xo(c){const e=c.reduce((s,o)=>s+o,0),t=new Float64Array(9);if(e<=0)return t;const n=c[0]/e,r=(c.length>1?c[1]:0)/e;return t[4]=n,t[1]=r/4,t[7]=r/4,t[3]=r/4,t[5]=r/4,t}function So(c){return xo(c)}function Eo(c,e,t,n,r,s="none"){const[o]=e;let i=Math.floor(e[1]/(t*n));i<1&&(i=1);let a=t,l=n,u=new Float64Array(c);for(const f of r){const d=f.kernelShape;let p,m;d.length===4?(p=d[0],m=d[1]):(p=i,m=i);const _=d.length===4?d[2]:3,y=d.length===4?d[3]:3,x=Math.floor(_/2),v=Math.floor(y/2),E=new Float64Array(o*p*a*l);for(let I=0;I<o;I++)for(let S=0;S<p;S++)for(let N=0;N<a;N++)for(let A=0;A<l;A++){let O=0;for(let T=0;T<m;T++)for(let F=0;F<_;F++)for(let C=0;C<y;C++){const V=N+F-x,Y=A+C-v;if(V>=0&&V<a&&Y>=0&&Y<l){const oe=I*m*a*l+T*a*l+V*l+Y,xe=S*m*_*y+T*_*y+F*y+C,ue=f.kernel[xe]??0;ue!==0&&(O+=(u[oe]??0)*ue)}}const R=I*p*a*l+S*a*l+N*l+A;E[R]=On(O,s)}if(u=E,i=p,f.poolSize>1){const I=Math.floor(a/f.poolSize),S=Math.floor(l/f.poolSize),N=new Float64Array(o*p*I*S);for(let A=0;A<o;A++)for(let O=0;O<p;O++)for(let R=0;R<I;R++)for(let T=0;T<S;T++){let F=f.poolMethod==="max"?-1/0:0,C=0;for(let Y=0;Y<f.poolSize;Y++)for(let oe=0;oe<f.poolSize;oe++){const xe=R*f.poolSize+Y,ue=T*f.poolSize+oe;if(xe<a&&ue<l){const ge=A*p*a*l+O*a*l+xe*l+ue,ss=u[ge]??0;f.poolMethod==="max"?F=Math.max(F,ss):F+=ss,C++}}f.poolMethod==="avg"&&C>0&&(F/=C);const V=A*p*I*S+O*I*S+R*S+T;N[V]=F}u=N,a=I,l=S}}const h=i*a*l;return{data:u,shape:[o,h]}}function Io(c,e,t,n,r,s="none"){const[o]=e,[i]=n,a=Ms(t,n[0],n[1]),l=ks(c,e,a,[n[1],n[0]]);for(let u=0;u<o;u++)for(let h=0;h<i;h++){const f=u*i+h;l.data[f]=On(l.data[f]+r[h],s)}return{data:l.data,shape:[o,i]}}function No(c,e){const[t,n]=e,r=new Float64Array(c.length);for(let s=0;s<t;s++){const o=c.subarray(s*n,(s+1)*n),i=As(o);r.set(i,s*n)}return r}function Ao(c,e,t=1e-5){const[n,r]=e;if(n<2)return new Float64Array(c);const s=new Float64Array(r),o=new Float64Array(r);for(let a=0;a<n;a++)for(let l=0;l<r;l++)s[l]+=c[a*r+l]/n;for(let a=0;a<n;a++)for(let l=0;l<r;l++){const u=c[a*r+l]-s[l];o[l]+=u*u/n}const i=new Float64Array(c.length);for(let a=0;a<n;a++)for(let l=0;l<r;l++)i[a*r+l]=(c[a*r+l]-s[l])/Math.sqrt(o[l]+t);return i}function Mr(c,e,t=1,n=null,r=null,s=null,o="none"){const[i,a,l]=e;let u=t;l%u!==0&&(u=1);const h=Math.floor(l/u),f=n!==null?Cn(c,i,a,l,n,l,l):new Float64Array(c),d=r!==null?Cn(c,i,a,l,r,l,l):new Float64Array(c),p=s!==null?Cn(c,i,a,l,s,l,l):new Float64Array(c),m=1/Math.sqrt(h),_=new Float64Array(i*a*l);for(let y=0;y<i;y++)for(let x=0;x<u;x++){const v=new Float64Array(a*a);for(let E=0;E<a;E++)for(let I=0;I<a;I++){let S=0;for(let N=0;N<h;N++){const A=y*a*l+E*l+x*h+N,O=y*a*l+I*l+x*h+N;S+=f[A]*d[O]}v[E*a+I]=S*m}for(let E=0;E<a;E++){let I=-1/0;for(let N=0;N<a;N++)I=Math.max(I,v[E*a+N]);let S=0;for(let N=0;N<a;N++)v[E*a+N]=Math.exp(v[E*a+N]-I),S+=v[E*a+N];for(let N=0;N<a;N++)v[E*a+N]/=S}for(let E=0;E<a;E++)for(let I=0;I<h;I++){let S=0;for(let A=0;A<a;A++){const O=y*a*l+A*l+x*h+I;S+=v[E*a+A]*p[O]}const N=y*a*l+E*l+x*h+I;_[N]=S}}if(o==="relu")for(let y=0;y<_.length;y++)_[y]=Math.max(0,_[y]);else if(o==="swish")for(let y=0;y<_.length;y++)_[y]=_[y]*Yt(_[y]);return _}function ko(c,e,t,n,r="avg"){const[s,o]=e;let i=Math.floor(o/(t*n));i<1&&(i=1);const a=r==="avg_max"?i*2:i,l=new Float64Array(s*a);for(let u=0;u<s;u++)for(let h=0;h<i;h++){let f=0,d=-1/0;for(let m=0;m<t*n;m++){const _=c[u*o+h*t*n+m]??0;f+=_,d=Math.max(d,_)}const p=f/(t*n);r==="avg"?l[u*a+h]=p:r==="max"?l[u*a+h]=d:(l[u*a+h]=p,l[u*a+i+h]=d)}return{data:l,shape:[s,a]}}function Mo(c,e,t=42){const n=e*9,r=Math.max(c,n),s=Math.max(c,n);let o=t;function i(){o^=o<<13,o^=o>>17,o^=o<<5;const f=(o>>>0)/4294967295;o^=o<<13,o^=o>>17,o^=o<<5;const d=(o>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,f)))*Math.cos(2*Math.PI*d)}const a=new Float64Array(r*s);for(let f=0;f<r*s;f++)a[f]=i();const l=new Float64Array(r*s);for(let f=0;f<Math.min(r,s);f++){for(let p=0;p<s;p++)l[f*s+p]=a[f*s+p];for(let p=0;p<f;p++){let m=0,_=0;for(let y=0;y<s;y++)m+=l[f*s+y]*l[p*s+y],_+=l[p*s+y]*l[p*s+y];if(_>1e-12){const y=m/_;for(let x=0;x<s;x++)l[f*s+x]-=y*l[p*s+x]}}let d=0;for(let p=0;p<s;p++)d+=l[f*s+p]*l[f*s+p];if(d=Math.sqrt(d),d>1e-12)for(let p=0;p<s;p++)l[f*s+p]/=d}const u=new Float64Array(c*e*9),h=Math.sqrt(2/n)*Math.sqrt(n);for(let f=0;f<c;f++)for(let d=0;d<n&&d<s;d++)u[f*n+d]=l[f*s+d]*h;return u}function Oo(c,e,t=42){const r=Math.floor(1.5),s=8,o=[.5,1,1.5],i=[0,Math.PI/2],a=1,l=.5,u=[];for(let m=0;m<s;m++){const _=m*Math.PI/s,y=Math.cos(_),x=Math.sin(_);for(const v of o)for(const E of i){const I=new Float64Array(9);for(let A=0;A<3;A++)for(let O=0;O<3;O++){const R=O-r,T=A-r,F=R*y+T*x,C=-R*x+T*y,V=Math.exp(-(F*F+l*l*C*C)/(2*a*a)),Y=Math.cos(2*Math.PI*v*F+E);I[A*3+O]=V*Y}let S=0;for(let A=0;A<9;A++)S+=I[A]/9;for(let A=0;A<9;A++)I[A]-=S;let N=0;for(let A=0;A<9;A++)N+=I[A]*I[A];if(N=Math.sqrt(N),N>1e-6)for(let A=0;A<9;A++)I[A]/=N;u.push(I)}}const h=new Float64Array(c*e*9),f=u.length;let d=t;function p(){d^=d<<13,d^=d>>17,d^=d<<5;const m=(d>>>0)/4294967295;d^=d<<13,d^=d>>17,d^=d<<5;const _=(d>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,m)))*Math.cos(2*Math.PI*_)}for(let m=0;m<c;m++)if(m<f)for(let _=0;_<e;_++){const y=u[m];for(let x=0;x<9;x++)h[m*e*9+_*9+x]=y[x]}else{const _=e*9,y=Math.sqrt(2/_);for(let x=0;x<e;x++)for(let v=0;v<9;v++)h[m*e*9+x*9+v]=p()*y}return h}function Co(c,e,t,n,r,s,o=42,i=1e4,a=50){const l=n[0],u=3,h=Math.floor(u/2),f=e*u*u;let d=o;function p(v){return d^=d<<13,d^=d>>17,d^=d<<5,(d>>>0)%v}const m=new Float64Array(i*f);for(let v=0;v<i;v++){const E=p(l),I=h+p(r-u+1),S=h+p(s-u+1);for(let N=0;N<e;N++)for(let A=0;A<u;A++)for(let O=0;O<u;O++){const R=E*e*r*s+N*r*s+(I-h+A)*s+(S-h+O);m[v*f+N*u*u+A*u+O]=t[R]??0}}for(let v=0;v<i;v++){let E=0;for(let S=0;S<f;S++)E+=m[v*f+S]/f;for(let S=0;S<f;S++)m[v*f+S]-=E;let I=0;for(let S=0;S<f;S++)I+=m[v*f+S]*m[v*f+S];I=Math.sqrt(I),I<1e-6&&(I=1);for(let S=0;S<f;S++)m[v*f+S]/=I}const _=new Float64Array(c*f),y=p(i);for(let v=0;v<f;v++)_[v]=m[y*f+v];for(let v=1;v<c;v++){const E=new Float64Array(i);let I=0;for(let A=0;A<i;A++){let O=1/0;for(let R=0;R<v;R++){let T=0;for(let F=0;F<f;F++){const C=m[A*f+F]-_[R*f+F];T+=C*C}O=Math.min(O,T)}E[A]=O,I+=O}let S=p(1e6)/1e6*I,N=0;for(let A=0;A<i;A++)if(S-=E[A],S<=0){N=A;break}for(let A=0;A<f;A++)_[v*f+A]=m[N*f+A]}const x=new Int32Array(i);for(let v=0;v<a;v++){for(let N=0;N<i;N++){let A=1/0,O=0;for(let R=0;R<c;R++){let T=0;for(let F=0;F<f;F++){const C=m[N*f+F]-_[R*f+F];T+=C*C}T<A&&(A=T,O=R)}x[N]=O}const E=new Float64Array(c*f),I=new Int32Array(c);for(let N=0;N<i;N++){const A=x[N];I[A]++;for(let O=0;O<f;O++)E[A*f+O]+=m[N*f+O]}for(let N=0;N<c;N++)if(I[N]>0)for(let A=0;A<f;A++)E[N*f+A]/=I[N];else for(let A=0;A<f;A++)E[N*f+A]=_[N*f+A];let S=0;for(let N=0;N<c*f;N++)S=Math.max(S,Math.abs(E[N]-_[N]));for(let N=0;N<c*f;N++)_[N]=E[N];if(S<1e-6)break}return _}function Cn(c,e,t,n,r,s,o){const i=new Float64Array(e*t*o);for(let a=0;a<e;a++)for(let l=0;l<t;l++)for(let u=0;u<o;u++){let h=0;for(let f=0;f<n;f++)h+=c[a*t*n+l*n+f]*r[f*o+u];i[a*t*o+l*o+u]=h}return i}const Or=1e-15,Tn=1-1e-15;function Xt(c){const e=Math.max(Or,Math.min(Tn,c));return Math.log(e/(1-e))}function Rn(c){return Yt(c)}function Nt(c,e){return On(c,e)}const Cr=new Set(["propagate","conv","pool"]);function At(c,e,t,n,r){const s=c,o=[];return(n==="out"||n==="both")&&o.push(...s.neighbors(e,r,t||null,"out")),(n==="in"||n==="both")&&o.push(...s.neighbors(e,r,t||null,"in")),o}class ye extends q{constructor(t,n=.5,r="none",s=""){super();b(this,"layers");b(this,"alpha");b(this,"gating");b(this,"graphName");b(this,"embedMode");b(this,"_gridShape");if(t.length===0)throw new Error("deep_fusion requires at least one layer");if(Cr.has(t[0].type))throw new Error("deep_fusion: first layer must be a SignalLayer or EmbedLayer (no scores to propagate or convolve)");let o=!1;for(const i of t){if(Cr.has(i.type)&&o)throw new Error("deep_fusion: spatial layers (propagate, convolve, pool) must not appear after flatten() or global_pool()");if((i.type==="flatten"||i.type==="global_pool")&&(o=!0),i.type==="pool"&&i.poolSize<2)throw new Error("deep_fusion: pool() pool_size must be >= 2");if(i.type==="dropout"){const a=i.p;if(a<=0||a>=1)throw new Error("deep_fusion: dropout() p must be in (0, 1)")}}if(this.layers=t,this.alpha=n,this.gating=r,this.graphName=s,this.embedMode=t[0].type==="embed",this.embedMode){const i=t[0];i.gridH>0&&i.gridW>0?this._gridShape=[i.gridH,i.gridW]:this._gridShape=null}else this._gridShape=null}execute(t){let n=new Map,r=1,s=!1;if(this._gridShape!==null){const o=this._executeGrid(n,r,s,t);n=o.channelMap,r=o.numChannels,s=o.softmaxApplied}else for(const o of this.layers)switch(o.type){case"embed":ye._executeEmbedLayer(o,n);break;case"signal":this._executeSignalLayer(o,t,n,r);break;case"propagate":this._executePropagateLayer(o,t,n,r);break;case"conv":this._executeConvLayer(o,t,n);break;case"pool":this._executePoolLayer(o,t,n);break;case"dense":this._executeDenseLayer(o,n),r=o.outputChannels;break;case"flatten":{const i=ye._executeFlattenLayer(n);n=i.channelMap,r=i.numChannels;break}case"global_pool":{const i=ye._executeGlobalPoolLayer(o,n);n=i.channelMap,r=i.numChannels;break}case"softmax":ye._executeSoftmaxLayer(n),s=!0;break;case"batchnorm":ye._executeBatchNormLayer(o,n);break;case"dropout":ye._executeDropoutLayer(o,n);break;case"attention":this._executeAttentionLayer(o,n);break}return ye._buildResult(n,r,s)}static _buildResult(t,n,r){if(t.size===0)return new D;const o=[...t.keys()].sort((i,a)=>i-a).map(i=>{const a=t.get(i);if(r){let l=-1/0;for(let h=0;h<a.length;h++)a[h]>l&&(l=a[h]);const u=Array.from(a);return{docId:i,payload:U({score:l,fields:{class_probs:u}})}}else if(n===1){const l=Rn(a[0]??0);return{docId:i,payload:U({score:l})}}else{const l=wo(a);let u=-1/0;for(let h=0;h<l.length;h++)l[h]>u&&(u=l[h]);return{docId:i,payload:U({score:u})}}});return D.fromSorted(o)}_executeSignalLayer(t,n,r,s){const o=t.signals,i=o.map(p=>p.execute(n)),a=new Set,l=[];for(const p of i){const m=new Map;for(const _ of p)m.set(_.docId,_.payload.score),a.add(_.docId);l.push(m)}if(a.size===0)return;const u=a.size,h=l.map(p=>ut(p.size,u)),f=this.alpha,d=this.gating;if(o.length===1){const p=l[0],m=h[0];for(const _ of a){const y=p.get(_)??m;let x=Xt(y);x=Nt(x,d),r.has(_)||r.set(_,new Float64Array(s)),r.get(_)[0]+=x}}else for(const p of a){const m=[];for(let x=0;x<l.length;x++)m.push(l[x].get(p)??h[x]);const _=K.logOddsConjunction(m,f,void 0,"none");let y=Xt(_);y=Nt(y,d),r.has(p)||r.set(p,new Float64Array(s)),r.get(p)[0]+=y}}_executePropagateLayer(t,n,r,s){const o=n.graphStore;if(o==null)throw new Error("deep_fusion propagate layer requires a graph_store in ExecutionContext");const i=new Map;for(const[m,_]of r)i.set(m,Rn(_[0]));const a=new Map,{direction:l,edgeLabel:u,aggregation:h}=t,f=this.graphName,d=this.gating,p=new Set(r.keys());for(const m of[...p]){const _=At(o,m,u,l,f);for(const y of _)p.add(y)}for(const m of p){const _=[],y=At(o,m,u,l,f);for(const S of y){const N=i.get(S);N!==void 0&&_.push(N)}if(_.length===0){r.has(m)&&a.set(m,new Float64Array(r.get(m)));continue}let x;h==="mean"?x=_.reduce((S,N)=>S+N,0)/_.length:h==="sum"?x=Math.min(Tn,_.reduce((S,N)=>S+N,0)):h==="max"?x=Math.max(..._):x=_.reduce((S,N)=>S+N,0)/_.length;let v=Xt(x);v=Nt(v,d);const E=r.get(m);let I;E!==void 0?(I=new Float64Array(E),I[0]=E[0]+v):(I=new Float64Array(s),I[0]=v),a.set(m,I)}r.clear();for(const[m,_]of a)r.set(m,_)}_executeConvLayer(t,n,r){const s=n.graphStore;if(s==null)throw new Error("deep_fusion convolve layer requires a graph_store in ExecutionContext");const o=this.embedMode,i=new Map;for(const[_,y]of r)i.set(_,o?y[0]:Rn(y[0]));const a=t.hopWeights.reduce((_,y)=>_+y,0);if(a<=0)return;const l=t.hopWeights.map(_=>_/a),u=new Map,{edgeLabel:h,direction:f}=t,d=this.graphName,p=this.gating,m=t.hopWeights.length-1;for(const _ of[...r.keys()]){let y=0;const x=i.get(_);x!==void 0&&(y+=l[0]*x);let v=new Set([_]);const E=new Set([_]);for(let S=1;S<=m;S++){const N=new Set;for(const A of v)for(const O of At(s,A,h,f,d))E.has(O)||(N.add(O),E.add(O));if(N.size>0){const A=[];for(const O of N){const R=i.get(O);R!==void 0&&A.push(R)}if(A.length>0){const O=A.reduce((R,T)=>R+T,0)/A.length;y+=l[S]*O}}v=N}const I=new Float64Array(r.get(_));if(o)I[0]=Nt(y,p);else{let S=Xt(Math.max(Or,Math.min(Tn,y)));S=Nt(S,p),I[0]=r.get(_)[0]+S}u.set(_,I)}r.clear();for(const[_,y]of u)r.set(_,y)}_executePoolLayer(t,n,r){const s=n.graphStore;if(s==null)throw new Error("deep_fusion pool layer requires a graph_store in ExecutionContext");const{edgeLabel:o,direction:i,poolSize:a,method:l}=t,u=this.graphName,h=new Set(r.keys()),f=new Map;for(;h.size>0;){const d=Math.min(...h);h.delete(d);const p=[d];let m=new Set([d]);const _=new Set([d]);for(;p.length<a&&m.size>0;){const E=new Set;for(const I of m){for(const S of At(s,I,o,i,u))if(!_.has(S)&&(_.add(S),E.add(S),h.has(S)&&(p.push(S),h.delete(S),p.length>=a)))break;if(p.length>=a)break}m=E}const y=r.get(p[0]).length,x=new Float64Array(y);if(l==="max"){x.fill(-1/0);for(const E of p){const I=r.get(E);for(let S=0;S<y;S++)x[S]=Math.max(x[S],I[S])}}else for(const E of p){const I=r.get(E);for(let S=0;S<y;S++)x[S]+=I[S]/p.length}const v=Math.min(...p);f.set(v,x)}r.clear();for(const[d,p]of f)r.set(d,p)}_executeDenseLayer(t,n){const r=[...n.keys()].sort((h,f)=>h-f);if(r.length===0)return;const s=n.get(r[0]).length,o=r.length,i=new Float64Array(o*s);for(let h=0;h<o;h++)i.set(n.get(r[h]),h*s);const a=new Float64Array(t.weights),l=new Float64Array(t.bias),u=Io(i,[o,s],a,[t.outputChannels,t.inputChannels],l,this.gating);for(let h=0;h<o;h++)n.set(r[h],u.data.slice(h*t.outputChannels,(h+1)*t.outputChannels))}static _executeFlattenLayer(t){if(t.size===0)return{channelMap:new Map,numChannels:0};const n=[...t.keys()].sort((u,h)=>u-h),r=[];for(const u of n)r.push(t.get(u));let s=0;for(const u of r)s+=u.length;const o=new Float64Array(s);let i=0;for(const u of r)o.set(u,i),i+=u.length;const a=n[0],l=new Map;return l.set(a,o),{channelMap:l,numChannels:s}}static _executeGlobalPoolLayer(t,n){if(n.size===0)return{channelMap:new Map,numChannels:0};const r=[...n.keys()].sort((h,f)=>h-f),s=n.get(r[0]).length,o=r.length;if(t.method==="avg"){const h=new Float64Array(s);for(const d of r){const p=n.get(d);for(let m=0;m<s;m++)h[m]+=p[m]/o}const f=new Map;return f.set(r[0],h),{channelMap:f,numChannels:s}}if(t.method==="max"){const h=new Float64Array(s).fill(-1/0);for(const d of r){const p=n.get(d);for(let m=0;m<s;m++)h[m]=Math.max(h[m],p[m])}const f=new Map;return f.set(r[0],h),{channelMap:f,numChannels:s}}const i=new Float64Array(s),a=new Float64Array(s).fill(-1/0);for(const h of r){const f=n.get(h);for(let d=0;d<s;d++)i[d]+=f[d]/o,a[d]=Math.max(a[d],f[d])}const l=new Float64Array(s*2);l.set(i,0),l.set(a,s);const u=new Map;return u.set(r[0],l),{channelMap:u,numChannels:s*2}}static _executeSoftmaxLayer(t){const n=[...t.keys()].sort((a,l)=>a-l);if(n.length===0)return;const r=t.get(n[0]).length,s=n.length,o=new Float64Array(s*r);for(let a=0;a<s;a++)o.set(t.get(n[a]),a*r);const i=No(o,[s,r]);for(let a=0;a<s;a++)t.set(n[a],i.slice(a*r,(a+1)*r))}static _executeBatchNormLayer(t,n){if(n.size<2)return;const r=[...n.keys()].sort((u,h)=>u-h),s=n.get(r[0]).length,o=r.length,i=t.epsilon??1e-5,a=new Float64Array(o*s);for(let u=0;u<o;u++)a.set(n.get(r[u]),u*s);const l=Ao(a,[o,s],i);for(let u=0;u<o;u++)n.set(r[u],l.slice(u*s,(u+1)*s))}static _executeDropoutLayer(t,n){const r=1-t.p;for(const[s,o]of n){const i=new Float64Array(o.length);for(let a=0;a<o.length;a++)i[a]=o[a]*r;n.set(s,i)}}_executeAttentionLayer(t,n){if(n.size===0)return;const r=[...n.keys()].sort((f,d)=>f-d),s=n.get(r[0]).length,o=r.length,i=new Float64Array(o*s);for(let f=0;f<o;f++)i.set(n.get(r[f]),f*s);const a=t.qWeights&&t.qShape?new Float64Array(t.qWeights):null,l=t.kWeights&&t.kShape?new Float64Array(t.kWeights):null,u=t.vWeights&&t.vShape?new Float64Array(t.vWeights):null,h=Mr(i,[1,o,s],t.nHeads,a,l,u,this.gating);for(let f=0;f<o;f++)n.set(r[f],h.slice(f*s,(f+1)*s))}static _executeEmbedLayer(t,n){if(t.embedding)for(let r=0;r<t.embedding.length;r++)n.set(r+1,new Float64Array([t.embedding[r]]))}_executeGrid(t,n,r,s){const[o,i]=this._gridShape,a=[];let l=[];const u=[],h=this.layers.filter(A=>A.type!=="embed");let f=0;for(;f<h.length;){const A=h[f];if(A.type==="conv"){const O=A;let R=2,T="max";if(f+1<h.length&&h[f+1].type==="pool"){const V=h[f+1];R=V.poolSize,T=V.method,f+=2}else f+=1;let F,C;O.kernel!=null&&O.kernelShape!=null?(F=new Float64Array(O.kernel),C=[...O.kernelShape]):(F=So([...O.hopWeights]),C=[1,1,3,3]),l.push({kernel:F,kernelShape:C,poolSize:R,poolMethod:T})}else A.type==="attention"?(l.length>0&&(a.push(["conv_pool",l]),l=[]),a.push(["attention",A]),f+=1):A.type==="global_pool"?(l.length>0&&(a.push(["conv_pool",l]),l=[]),a.push(["global_pool",A]),f+=1):(l.length>0&&(a.push(["conv_pool",l]),l=[]),u.push(A),f+=1)}l.length>0&&a.push(["conv_pool",l]);const p=this.layers[0].embedding??[];let m=new Float64Array(p),_=o,y=i;const x=1;for(const[A,O]of a)if(A==="conv_pool"){const R=O;m=Eo(m,[x,m.length],_,y,R,this.gating).data;for(const F of R)_=Math.floor(_/F.poolSize),y=Math.floor(y/F.poolSize)}else if(A==="attention"){const R=O,T=Math.floor(m.length/(_*y)),F=_*y,C=new Float64Array(F*T);for(let ue=0;ue<F;ue++)for(let ge=0;ge<T;ge++)C[ue*T+ge]=m[ge*F+ue]??0;const V=R.qWeights&&R.qShape?new Float64Array(R.qWeights):null,Y=R.kWeights&&R.kShape?new Float64Array(R.kWeights):null,oe=R.vWeights&&R.vShape?new Float64Array(R.vWeights):null,xe=Mr(C,[1,F,T],R.nHeads,V,Y,oe,this.gating);m=new Float64Array(T*F);for(let ue=0;ue<F;ue++)for(let ge=0;ge<T;ge++)m[ge*F+ue]=xe[ue*T+ge]}else{const R=O;m=ko(m,[x,m.length],_,y,R.method).data,_=1,y=1}const v=new Map;if(a.some(([A])=>A==="global_pool"))v.set(1,m),n=m.length;else{for(let A=0;A<m.length;A++)v.set(A+1,new Float64Array([m[A]]));n=1}let I=v,S=n,N=r;for(const A of u)switch(A.type){case"flatten":{const O=ye._executeFlattenLayer(I);I=O.channelMap,S=O.numChannels;break}case"global_pool":{const O=ye._executeGlobalPoolLayer(A,I);I=O.channelMap,S=O.numChannels;break}case"dense":this._executeDenseLayer(A,I),S=A.outputChannels;break;case"softmax":ye._executeSoftmaxLayer(I),N=!0;break;case"batchnorm":ye._executeBatchNormLayer(A,I);break;case"dropout":ye._executeDropoutLayer(A,I);break}return{channelMap:I,numChannels:S,softmaxApplied:N}}costEstimate(t){let n=0;for(const r of this.layers)switch(r.type){case"signal":for(const s of r.signals)n+=s.costEstimate(t);break;case"embed":n+=(r.embedding??[]).length;break;case"propagate":case"conv":case"pool":n+=t.totalDocs;break;case"dense":n+=r.inputChannels*r.outputChannels;break;case"flatten":case"global_pool":case"softmax":case"batchnorm":case"dropout":n+=t.totalDocs;break;case"attention":n+=t.totalDocs**2;break}return n}}function To(c,e,t,n,r,s="embedding"){const o=e,i=c,a=new Map;for(const f of o.docIds){const d=o.getField(f,s);if(d!=null){const p=d instanceof Float64Array?d:new Float64Array(d);let m=0;for(let _=0;_<p.length;_++)m+=p[_]*p[_];if(m=Math.sqrt(m),m>0){const _=new Float64Array(p.length);for(let y=0;y<p.length;y++)_[y]=p[y]/m;a.set(f,_)}}}if(a.size<2){const f=1/(n+1);return new Array(n+1).fill(f)}const l=[];for(let f=0;f<=n;f++)l.push([]);for(const[f,d]of a){l[0].push(1);let p=new Set([f]);const m=new Set([f]);for(let _=1;_<=n;_++){const y=new Set;for(const x of p)for(const v of At(i,x,t,"both",r))m.has(v)||(y.add(v),m.add(v));for(const x of y){const v=a.get(x);if(v!==void 0){let E=0;for(let I=0;I<d.length;I++)E+=d[I]*v[I];l[_].push(E)}}p=y}}const u=[];for(let f=0;f<=n;f++){const d=l[f];if(d.length>0){const p=d.reduce((m,_)=>m+_,0)/d.length;u.push(Math.max(0,p))}else u.push(0)}const h=u.reduce((f,d)=>f+d,0);if(h<=0){const f=1/(n+1);return new Array(n+1).fill(f)}return u.map(f=>f/h)}class Qt extends q{constructor(t,n,r){super();b(this,"path");b(this,"predicate");b(this,"source");this.path=t,this.predicate=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;const r=Zn(this.predicate);let s;this.source?s=this.source.execute(t).entries.map(i=>i.docId):s=[...n.docIds].sort((i,a)=>i-a);const o=[];for(const i of s){const a=n.evalPath(i,this.path);if(Array.isArray(a))a.some(l=>this.predicate.evaluate(l))&&o.push({docId:i,payload:U({score:0})});else{if(!r&&a==null)continue;this.predicate.evaluate(a)&&o.push({docId:i,payload:U({score:0})})}}return D.fromSorted(o)}costEstimate(t){return this.source?this.source.costEstimate(t):t.totalDocs}}class Ro extends q{constructor(t,n){super();b(this,"paths");b(this,"source");this.paths=t,this.source=n}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return n;const s=[];for(const o of n){const i={};for(const a of this.paths){const l=r.evalPath(o.docId,a),u=a.join(".");i[u]=l}s.push({docId:o.docId,payload:U({positions:o.payload.positions,score:o.payload.score,fields:{...o.payload.fields,...i}})})}return D.fromSorted(s)}costEstimate(t){return this.source.costEstimate(t)}}class Fo extends q{constructor(t,n){super();b(this,"path");b(this,"source");this.path=t,this.source=n}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return n;const s=[];for(const o of n){const i=r.evalPath(o.docId,this.path);if(Array.isArray(i))for(const a of i)s.push({docId:o.docId,payload:U({positions:o.payload.positions,score:o.payload.score,fields:{...o.payload.fields,_unnested_data:a}})});else s.push(o)}return new D(s)}costEstimate(t){return this.source.costEstimate(t)*2}}class Po extends q{constructor(t,n,r){super();b(this,"path");b(this,"monoid");b(this,"source");this.path=t,this.monoid=n,this.source=r??null}execute(t){const n=t.documentStore;if(!n)return new D;let r;this.source?r=this.source.execute(t).entries.map(o=>o.docId):r=[...n.docIds].sort((o,i)=>o-i);const s=[];for(const o of r){const i=n.evalPath(o,this.path);let a=this.monoid.identity();if(Array.isArray(i))for(const h of i)h!=null&&(a=this.monoid.accumulate(a,h));else i!=null&&(a=this.monoid.accumulate(a,i));const l=this.monoid.finalize(a),u=typeof l=="number"?l:0;s.push({docId:o,payload:U({score:u,fields:{_path_agg_result:l,_path_agg_path:this.path.join(".")}})})}return D.fromSorted(s)}costEstimate(t){return this.source?this.source.costEstimate(t):t.totalDocs}}class pt extends q{constructor(t,n,r){super();b(this,"signals");b(this,"attention");b(this,"queryFeatures");this.signals=t,this.attention=n,this.queryFeatures=r}execute(t){const n=this.signals.map(l=>l.execute(t)),r=[],s=new Set;let o=0;for(const l of n){const u=new Map;for(const h of l)u.set(h.docId,h.payload.score),s.add(h.docId);r.push(u),o=Math.max(o,u.size)}const i=r.map(l=>ut(l.size,o)),a=[];for(const l of s){const u=[];for(let f=0;f<r.length;f++)u.push(r[f].get(l)??i[f]);const h=this.attention.fuse(u,this.queryFeatures);a.push({docId:l,payload:U({score:h})})}return new D(a)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class kt extends q{constructor(t,n){super();b(this,"signals");b(this,"learned");this.signals=t,this.learned=n}execute(t){const n=this.signals.map(l=>l.execute(t)),r=[],s=new Set;let o=0;for(const l of n){const u=new Map;for(const h of l)u.set(h.docId,h.payload.score),s.add(h.docId);r.push(u),o=Math.max(o,u.size)}const i=r.map(l=>ut(l.size,o)),a=[];for(const l of s){const u=[];for(let f=0;f<r.length;f++)u.push(r[f].get(l)??i[f]);const h=this.learned.fuse(u);a.push({docId:l,payload:U({score:h})})}return new D(a)}costEstimate(t){let n=0;for(const r of this.signals)n+=r.costEstimate(t);return n}}class Mt{}class Te extends Mt{constructor(t){super();b(this,"name");this.name=t}equals(t){return t instanceof Te&&t.name===this.name}toString(){return this.name}}class Ze extends Mt{constructor(t,n){super();b(this,"left");b(this,"right");this.left=t,this.right=n}equals(t){return t instanceof Ze&&this.left.equals(t.left)&&this.right.equals(t.right)}toString(){return`${this.left.toString()} / ${this.right.toString()}`}}class Ot extends Mt{constructor(t,n){super();b(this,"left");b(this,"right");this.left=t,this.right=n}equals(t){return t instanceof Ot&&this.left.equals(t.left)&&this.right.equals(t.right)}toString(){return`(${this.left.toString()} | ${this.right.toString()})`}}class Ct extends Mt{constructor(t){super();b(this,"inner");this.inner=t}equals(t){return t instanceof Ct&&this.inner.equals(t.inner)}toString(){return`(${this.inner.toString()})*`}}class Tt extends Mt{constructor(t,n,r){super();b(this,"name");b(this,"minCount");b(this,"maxCount");this.name=t,this.minCount=n,this.maxCount=r}equals(t){return t instanceof Tt&&t.name===this.name&&t.minCount===this.minCount&&t.maxCount===this.maxCount}toString(){return`${this.name}{${String(this.minCount)},${String(this.maxCount)}}`}}function Do(c){const e=[];let t=0;for(;t<c.length;){const n=c[t];if(n===" "||n===" "||n===`
8
8
  `||n==="\r"){t++;continue}if(n==="|")e.push({type:"PIPE",value:"|"}),t++;else if(n==="/")e.push({type:"SLASH",value:"/"}),t++;else if(n==="*")e.push({type:"STAR",value:"*"}),t++;else if(n==="(")e.push({type:"LPAREN",value:"("}),t++;else if(n===")")e.push({type:"RPAREN",value:")"}),t++;else if(n==="{")e.push({type:"LBRACE",value:"{"}),t++;else if(n==="}")e.push({type:"RBRACE",value:"}"}),t++;else if(n===",")e.push({type:"COMMA",value:","}),t++;else if(n>="0"&&n<="9"){let r="";for(;t<c.length&&c[t]>="0"&&c[t]<="9";)r+=c[t],t++;e.push({type:"NUMBER",value:r})}else{let r="";for(;t<c.length&&c[t]!==" "&&c[t]!==" "&&c[t]!==`
9
- `&&c[t]!=="\r"&&c[t]!=="|"&&c[t]!=="/"&&c[t]!=="*"&&c[t]!=="("&&c[t]!==")"&&c[t]!=="{"&&c[t]!=="}"&&c[t]!==",";)r+=c[t],t++;r.length>0&&e.push({type:"LABEL",value:r})}}return e}class Lo{constructor(e){b(this,"tokens");b(this,"pos");this.tokens=e,this.pos=0}peek(){return this.pos<this.tokens.length?this.tokens[this.pos]:null}consume(e){const t=this.peek();if(!t)throw new Error("RPQ parse error: unexpected end of input");if(e!==void 0&&t.type!==e)throw new Error(`RPQ parse error: expected ${e}, got ${t.type} ('${t.value}')`);return this.pos++,t}parseExpr(){var t;let e=this.parseConcat();for(;((t=this.peek())==null?void 0:t.type)==="PIPE";){this.consume("PIPE");const n=this.parseConcat();e=new Ot(e,n)}return e}parseConcat(){var t;let e=this.parseUnary();for(;((t=this.peek())==null?void 0:t.type)==="SLASH";){this.consume("SLASH");const n=this.parseUnary();e=new Qe(e,n)}return e}parseUnary(){let e=this.parsePrimary();const t=this.peek();if((t==null?void 0:t.type)==="STAR")this.consume("STAR"),e=new Ct(e);else if((t==null?void 0:t.type)==="LBRACE"){this.consume("LBRACE");const n=this.consume("NUMBER");this.consume("COMMA");const r=this.consume("NUMBER");if(this.consume("RBRACE"),e instanceof Ce)e=new Tt(e.name,parseInt(n.value,10),parseInt(r.value,10));else throw new Error("RPQ parse error: bounded repetition only supported on labels")}return e}parsePrimary(){const e=this.peek();if(!e)throw new Error("RPQ parse error: unexpected end of input");if(e.type==="LPAREN"){this.consume("LPAREN");const t=this.parseExpr();return this.consume("RPAREN"),t}if(e.type==="LABEL")return this.consume("LABEL"),new Ce(e.value);throw new Error(`RPQ parse error: unexpected token ${e.type} ('${e.value}')`)}}function Tr(c){const e=Do(c);if(e.length===0)throw new Error("RPQ parse error: empty expression");return new Lo(e).parseExpr()}function Rr(c){return[...c].sort((e,t)=>e-t).join(",")}function Fr(c,e){const t=new Set(e),n=[...e];for(;n.length>0;){const r=n.pop();for(const s of c.transitions)s.from===r&&s.label===null&&!t.has(s.to)&&(t.add(s.to),n.push(s.to))}return t}function jo(c,e,t){const n=new Set;for(const r of c.transitions)e.has(r.from)&&r.label===t&&n.add(r.to);return n}function Vo(c){const e=new Set;for(const t of c.transitions)t.label!==null&&e.add(t.label);return e}function Pr(c){const e=Vo(c),t=Fr(c,new Set([c.startState])),n=Rr(t),r=new Map,s=new Set,o=[[n,t]],i=new Set;for(t.has(c.acceptState)&&s.add(n);o.length>0;){const[a,l]=o.pop();if(!i.has(a)){i.add(a);for(const u of e){const h=jo(c,l,u);if(h.size===0)continue;const f=Fr(c,h),d=Rr(f);let p=r.get(a);p||(p=new Map,r.set(a,p)),p.set(u,d),f.has(c.acceptState)&&s.add(d),i.has(d)||o.push([d,f])}}}return{transitions:r,startState:n,acceptStates:s}}class Fn extends q{constructor(t,n,r,s,o,i){super();b(this,"startVertex");b(this,"graph");b(this,"label");b(this,"maxHops");b(this,"vertexPredicate");b(this,"score");this.startVertex=t,this.graph=n,this.label=r??null,this.maxHops=s??1/0,this.vertexPredicate=o??null,this.score=i??1}execute(t){const n=t.graphStore,r=this.graph,s=new Set,o=[],i=[[this.startVertex,0]];s.add(this.startVertex);const a=new Set,l=new Set;for(;i.length>0;){const[h,f]=i.shift(),d=n.getVertex(h);if(!d||this.vertexPredicate&&!this.vertexPredicate(d))continue;a.add(h);const p=this.score/(1+f);if(o.push(ce(h,{score:p,fields:{...d.properties,_depth:f}})),f<this.maxHops){const m=n.neighbors(h,r,this.label,"out");for(const y of m)s.has(y)||(s.add(y),i.push([y,f+1]));const _=n.outEdgeIds(h,r);for(const y of _){const x=n.getEdge(y);x&&(this.label===null||x.label===this.label)&&l.add(y)}}}const u=new W(o);for(const h of o)u.setGraphPayload(h.docId,ne({subgraphVertices:a,subgraphEdges:l,score:h.payload.score,graphName:r}));return u}}class Dr extends q{constructor(t,n,r){super();b(this,"pattern");b(this,"graph");b(this,"score");this.pattern=t,this.graph=n,this.score=r??1}execute(t){const n=t.graphStore,r=this._backtrackSearch(n);return this._buildPostingList(n,r)}_backtrackSearch(t){const n=this._computeCandidates(t),r=[],s=new Map,o=this.pattern.vertexPatterns.map(i=>i.variable);return this._backtrack(t,o,0,s,n,r),r}_computeCandidates(t){const n=new Map,r=t.vertexIdsInGraph(this.graph);for(const o of this.pattern.vertexPatterns){let i=new Set(r);if(o.constraints.length>0){const a=new Set;for(const l of i){const u=t.getVertex(l);if(u){let h=!0;for(const f of o.constraints)if(!f(u)){h=!1;break}h&&a.add(l)}}i=a}n.set(o.variable,i)}let s=!0;for(;s;){s=!1;for(const o of this.pattern.edgePatterns){if(o.negated)continue;const i=n.get(o.sourceVar),a=n.get(o.targetVar);if(!i||!a)continue;const l=new Set;for(const h of i){const f=t.neighbors(h,this.graph,o.label,"out");let d=!1;for(const p of f)if(a.has(p)){d=!0;break}d&&l.add(h)}l.size<i.size&&(n.set(o.sourceVar,l),s=!0);const u=new Set;for(const h of a){const f=t.neighbors(h,this.graph,o.label,"in");let d=!1;for(const p of f)if(l.has(p)){d=!0;break}d&&u.add(h)}u.size<a.size&&(n.set(o.targetVar,u),s=!0)}}return n}_backtrack(t,n,r,s,o,i){if(r===n.length){this._validateAllEdges(t,s)&&this._checkNegatedEdges(t,s)&&i.push(new Map(s));return}let a=r,l=1/0;for(let d=r;d<n.length;d++){const p=n[d],m=o.get(p),_=m?m.size:0;_<l&&(l=_,a=d)}if(a!==r){const d=n[r];n[r]=n[a],n[a]=d}const u=n[r],h=o.get(u)??new Set,f=new Set(s.values());for(const d of h)f.has(d)||(s.set(u,d),this._validateEdgesFor(t,s,u)&&this._backtrack(t,n,r+1,s,o,i),s.delete(u))}_validateEdgesFor(t,n,r){for(const s of this.pattern.edgePatterns){if(s.negated||s.sourceVar!==r&&s.targetVar!==r)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;if(!t.neighbors(o,this.graph,s.label,"out").includes(i))return!1;if(s.constraints.length>0){const l=t.outEdgeIds(o,this.graph);let u=!1;for(const h of l){const f=t.getEdge(h);if(f&&f.targetId===i&&(s.label===null||f.label===s.label)){let d=!0;for(const p of s.constraints)if(!p(f)){d=!1;break}if(d){u=!0;break}}}if(!u)return!1}}return!0}_validateAllEdges(t,n){for(const r of this.pattern.edgePatterns){if(r.negated)continue;const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0||!t.neighbors(s,this.graph,r.label,"out").includes(o))return!1;if(r.constraints.length>0){const a=t.outEdgeIds(s,this.graph);let l=!1;for(const u of a){const h=t.getEdge(u);if(h&&h.targetId===o&&(r.label===null||h.label===r.label)){let f=!0;for(const d of r.constraints)if(!d(h)){f=!1;break}if(f){l=!0;break}}}if(!l)return!1}}return!0}_checkNegatedEdges(t,n){for(const r of this.pattern.edgePatterns){if(!r.negated)continue;const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0)continue;if(t.neighbors(s,this.graph,r.label,"out").includes(o))return!1}return!0}_collectMatchEdges(t,n){const r=new Set;for(const s of this.pattern.edgePatterns){if(s.negated)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);for(const l of a){const u=t.getEdge(l);u&&u.targetId===i&&(s.label===null||u.label===s.label)&&r.add(l)}}return r}_buildPostingList(t,n){const r=[],s=new Map;for(let i=0;i<n.length;i++){const a=n[i],l=new Set(a.values()),u=this._collectMatchEdges(t,a),h=i,f={};for(const[d,p]of a)f[d]=p;r.push(ce(h,{score:this.score,fields:f})),s.set(h,ne({subgraphVertices:l,subgraphEdges:u,score:this.score,graphName:this.graph}))}const o=new W(r);for(const[i,a]of s)o.setGraphPayload(i,a);return o}}let Lr=0;function Ie(){return{id:Lr++}}function jr(){Lr=0}function $e(c){if(c instanceof Ce){const e=Ie(),t=Ie();return{states:[e,t],transitions:[{from:e.id,to:t.id,label:c.name}],startState:e.id,acceptState:t.id}}if(c instanceof Qe){const e=$e(c.left),t=$e(c.right),n=[...e.transitions,...t.transitions,{from:e.acceptState,to:t.startState,label:null}];return{states:[...e.states,...t.states],transitions:n,startState:e.startState,acceptState:t.acceptState}}if(c instanceof Ot){const e=Ie(),t=Ie(),n=$e(c.left),r=$e(c.right),s=[...n.transitions,...r.transitions,{from:e.id,to:n.startState,label:null},{from:e.id,to:r.startState,label:null},{from:n.acceptState,to:t.id,label:null},{from:r.acceptState,to:t.id,label:null}];return{states:[e,t,...n.states,...r.states],transitions:s,startState:e.id,acceptState:t.id}}if(c instanceof Ct){const e=Ie(),t=Ie(),n=$e(c.inner),r=[...n.transitions,{from:e.id,to:n.startState,label:null},{from:e.id,to:t.id,label:null},{from:n.acceptState,to:n.startState,label:null},{from:n.acceptState,to:t.id,label:null}];return{states:[e,t,...n.states],transitions:r,startState:e.id,acceptState:t.id}}if(c instanceof Tt){if(c.minCount===0&&c.maxCount===0){const t=Ie();return{states:[t],transitions:[],startState:t.id,acceptState:t.id}}let e=null;for(let t=0;t<c.minCount;t++){const n=$e(new Ce(c.name));if(e===null)e=n;else{const r=[...e.transitions,...n.transitions,{from:e.acceptState,to:n.startState,label:null}];e={states:[...e.states,...n.states],transitions:r,startState:e.startState,acceptState:n.acceptState}}}for(let t=c.minCount;t<c.maxCount;t++){const n=$e(new Ce(c.name));if(e===null){const r=Ie(),s=Ie(),o=[...n.transitions,{from:r.id,to:n.startState,label:null},{from:r.id,to:s.id,label:null},{from:n.acceptState,to:s.id,label:null}];e={states:[r,s,...n.states],transitions:o,startState:r.id,acceptState:s.id}}else{const r=Ie(),s=[...e.transitions,...n.transitions,{from:e.acceptState,to:n.startState,label:null},{from:e.acceptState,to:r.id,label:null},{from:n.acceptState,to:r.id,label:null}];e={states:[...e.states,r,...n.states],transitions:s,startState:e.startState,acceptState:r.id}}}if(e===null){const t=Ie();return{states:[t],transitions:[],startState:t.id,acceptState:t.id}}return e}throw new Error(`Unsupported RPQ expression type: ${String(c)}`)}class Vr extends q{constructor(t,n,r,s){super();b(this,"pathExpr");b(this,"graph");b(this,"startVertex");b(this,"score");this.pathExpr=t,this.graph=n,this.startVertex=r??null,this.score=s??1}execute(t){const n=t.graphStore,r=this._tryIndexLookup(t,n);if(r!==null)return r;jr();const s=$e(this.pathExpr),o=Pr(s),i=[],a=new Map,l=new Set,u=[];if(this.startVertex!==null)u.push(this.startVertex);else{const d=n.vertexIdsInGraph(this.graph);for(const p of d)u.push(p)}let h=0;for(const d of u){const p=this._simulateDfa(n,o,d);for(const[m,_]of p){const y=`${String(d)}-${String(m)}`;if(l.has(y))continue;l.add(y);const x=h++;i.push(ce(x,{score:this.score,fields:{start:d,end:m}})),a.set(x,ne({subgraphVertices:new Set([d,m]),subgraphEdges:_,score:this.score,graphName:this.graph}))}}const f=new W(i);for(const[d,p]of a)f.setGraphPayload(d,p);return f}_simulateDfa(t,n,r){const s=[],o=[[r,n.startState,new Set]],i=new Set;for(i.add(`${String(r)}:${n.startState}`),n.acceptStates.has(n.startState)&&s.push([r,new Set]);o.length>0;){const[a,l,u]=o.shift(),h=n.transitions.get(l);if(h)for(const[f,d]of h){const p=t.outEdgeIds(a,this.graph);for(const m of p){const _=t.getEdge(m);if(!_||_.label!==f)continue;const y=_.targetId,x=`${String(y)}:${d}`;if(i.has(x))continue;i.add(x);const v=new Set(u);v.add(m),n.acceptStates.has(d)&&s.push([y,v]),o.push([y,d,v])}}}return s}_tryIndexLookup(t,n){const r=t.pathIndex;if(!r||!r.hasPath||!r.lookup)return null;const s=this._extractLabelSequence(this.pathExpr);if(s===null||!r.hasPath(s,this.graph))return null;const o=r.lookup(s,this.graph),i=[];let a=0;for(const[l,u]of o)this.startVertex!==null&&l!==this.startVertex||(i.push(ce(a,{score:this.score,fields:{start:l,end:u}})),a++);return new W(i)}_extractLabelSequence(t){if(t instanceof Ce)return[t.name];if(t instanceof Qe){const n=this._extractLabelSequence(t.left),r=this._extractLabelSequence(t.right);if(n!==null&&r!==null)return[...n,...r]}return null}}class $r extends q{constructor(t,n,r){super();b(this,"source");b(this,"propertyName");b(this,"aggFn");this.source=t,this.propertyName=n,this.aggFn=r??(s=>{if(s.length===0)return 0;let o=0;for(let i=0;i<s.length;i++)o+=s[i];return o/s.length})}execute(t){const n=t.graphStore,r=this.source.execute(t),s=[];for(const a of r){const l=n.getVertex(a.docId);if(l){const u=l.properties[this.propertyName];typeof u=="number"&&s.push(u)}}const o=this.aggFn(s),i=[];for(const a of r)i.push({docId:a.docId,payload:U({positions:a.payload.positions,score:o,fields:{...a.payload.fields,_aggregated:o,_property:this.propertyName}})});return new D(i)}}class $o extends q{constructor(t,n,r){super();b(this,"pathExpr");b(this,"graph");b(this,"startVertex");b(this,"weightProperty");b(this,"aggregation");b(this,"weightThreshold");b(this,"score");this.pathExpr=t,this.graph=n,this.startVertex=(r==null?void 0:r.startVertex)??null,this.weightProperty=(r==null?void 0:r.weightProperty)??"weight",this.aggregation=(r==null?void 0:r.aggregation)??"sum",this.weightThreshold=(r==null?void 0:r.weightThreshold)??null,this.score=(r==null?void 0:r.score)??1}execute(t){const n=t.graphStore;jr();const r=$e(this.pathExpr),s=Pr(r),o=[],i=new Map,a=new Set,l=[];if(this.startVertex!==null)l.push(this.startVertex);else{const f=n.vertexIdsInGraph(this.graph);for(const d of f)l.push(d)}let u=0;for(const f of l){const d=this._simulateWeightedDfa(n,s,f);for(const[p,m,_]of d){if(this.weightThreshold!==null&&_<this.weightThreshold)continue;const y=`${String(f)}-${String(p)}`;if(a.has(y))continue;a.add(y);const x=u++;o.push(ce(x,{score:_*this.score,fields:{start:f,end:p,weight:_,path_length:m.size}})),i.set(x,ne({subgraphVertices:new Set([f,p]),subgraphEdges:m,score:_*this.score,graphName:this.graph}))}}const h=new W(o);for(const[f,d]of i)h.setGraphPayload(f,d);return h}_simulateWeightedDfa(t,n,r){const s=[],o=this.aggregation==="product"?1:0,i=[[r,n.startState,new Set,o]],a=new Set;for(a.add(`${String(r)}:${n.startState}`),n.acceptStates.has(n.startState)&&s.push([r,new Set,o]);i.length>0;){const[l,u,h,f]=i.shift(),d=n.transitions.get(u);if(d)for(const[p,m]of d){const _=t.outEdgeIds(l,this.graph);for(const y of _){const x=t.getEdge(y);if(!x||x.label!==p)continue;const v=x.targetId,E=`${String(v)}:${m}`;if(a.has(E))continue;a.add(E);const I=new Set(h);I.add(y);const S=typeof x.properties[this.weightProperty]=="number"?x.properties[this.weightProperty]:1;let N;switch(this.aggregation){case"sum":N=f+S;break;case"min":N=h.size===0?S:Math.min(f,S);break;case"max":N=Math.max(f,S);break;case"product":N=f*S;break}n.acceptStates.has(m)&&s.push([v,I,N]),i.push([v,m,I,N])}}}return s}}class Pn extends q{constructor(t){super();b(this,"startVertex");b(this,"graph");b(this,"temporalFilter");b(this,"label");b(this,"maxHops");b(this,"vertexPredicate");b(this,"score");this.startVertex=t.startVertex,this.graph=t.graph,this.temporalFilter=t.temporalFilter,this.label=t.label??null,this.maxHops=t.maxHops??1/0,this.vertexPredicate=t.vertexPredicate??null,this.score=t.score??1}execute(t){const n=t.graphStore,r=new Set,s=[],o=new Set,i=new Set,a=[[this.startVertex,0]];for(r.add(this.startVertex);a.length>0;){const[u,h]=a.shift(),f=n.getVertex(u);if(!f||this.vertexPredicate&&!this.vertexPredicate(f))continue;o.add(u);const d=this.score/(1+h);if(s.push(ce(u,{score:d,fields:{...f.properties,_depth:h}})),h<this.maxHops){const p=n.outEdgeIds(u,this.graph);for(const m of p){const _=n.getEdge(m);_&&(this.label!==null&&_.label!==this.label||this.temporalFilter.isValid(_)&&(i.add(m),r.has(_.targetId)||(r.add(_.targetId),a.push([_.targetId,h+1]))))}}}const l=new W(s);for(const u of s)l.setGraphPayload(u.docId,ne({subgraphVertices:o,subgraphEdges:i,score:u.payload.score,graphName:this.graph}));return l}}class Zt{constructor(e){b(this,"timestamp");b(this,"timeRange");const t=(e==null?void 0:e.timestamp)??null,n=(e==null?void 0:e.timeRange)??null;if(t!==null&&n!==null)throw new Error("TemporalFilter: timestamp and timeRange are mutually exclusive");this.timestamp=t,this.timeRange=n}isValid(e){const t=e.properties.valid_from,n=e.properties.valid_to;if(typeof t=="number"||typeof n=="number")return this._isValidRange(typeof t=="number"?t:null,typeof n=="number"?n:null);const s=e.properties.timestamp;if(typeof s!="number")return!0;if(this.timestamp!==null)return s<=this.timestamp;if(this.timeRange!==null){const[o,i]=this.timeRange;return s>=o&&s<=i}return!0}_isValidRange(e,t){if(this.timestamp!==null)return!(e!==null&&this.timestamp<e||t!==null&&this.timestamp>t);if(this.timeRange!==null){const[n,r]=this.timeRange;return!(e!==null&&e>r||t!==null&&t<n)}return!0}}class qr extends q{constructor(t){super();b(this,"damping");b(this,"maxIterations");b(this,"tolerance");b(this,"graph");this.damping=t.damping??.85,this.maxIterations=t.maxIterations??100,this.tolerance=t.tolerance??1e-6,this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let f=0;f<r.length;f++)o.set(r[f],f);let i=new Float64Array(s);i.fill(1/s);const a=new Float64Array(s);for(let f=0;f<s;f++){const d=r[f],p=n.outEdgeIds(d,this.graph);a[f]=p.size}for(let f=0;f<this.maxIterations;f++){const d=new Float64Array(s);d.fill((1-this.damping)/s);for(let m=0;m<s;m++){const _=r[m];if(a[m]===0){const y=i[m]/s;for(let x=0;x<s;x++)d[x]=d[x]+this.damping*y}else{const y=i[m]/a[m],x=n.neighbors(_,this.graph,null,"out");for(const v of x){const E=o.get(v);E!==void 0&&(d[E]=d[E]+this.damping*y)}}}let p=0;for(let m=0;m<s;m++)p+=Math.abs(d[m]-i[m]);if(i=d,p<this.tolerance)break}const l=[];for(let f=0;f<s;f++){const d=r[f];l.push(ce(d,{score:i[f],fields:{pagerank:i[f]}}))}const u=new Set(r),h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}class zr extends q{constructor(t){super();b(this,"maxIterations");b(this,"tolerance");b(this,"graph");this.maxIterations=t.maxIterations??100,this.tolerance=t.tolerance??1e-6,this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let f=0;f<r.length;f++)o.set(r[f],f);let i=new Float64Array(s),a=new Float64Array(s);i.fill(1),a.fill(1);for(let f=0;f<this.maxIterations;f++){const d=new Float64Array(s),p=new Float64Array(s);for(let x=0;x<s;x++){const v=r[x],E=n.neighbors(v,this.graph,null,"in");let I=0;for(const S of E){const N=o.get(S);N!==void 0&&(I+=i[N])}d[x]=I}for(let x=0;x<s;x++){const v=r[x],E=n.neighbors(v,this.graph,null,"out");let I=0;for(const S of E){const N=o.get(S);N!==void 0&&(I+=d[N])}p[x]=I}let m=0,_=0;for(let x=0;x<s;x++)m+=d[x]*d[x],_+=p[x]*p[x];if(m=Math.sqrt(m),_=Math.sqrt(_),m>0)for(let x=0;x<s;x++)d[x]=d[x]/m;if(_>0)for(let x=0;x<s;x++)p[x]=p[x]/_;let y=0;for(let x=0;x<s;x++)y+=Math.abs(d[x]-a[x]),y+=Math.abs(p[x]-i[x]);if(a=d,i=p,y<this.tolerance)break}const l=[];for(let f=0;f<s;f++){const d=r[f],p=a[f]+i[f];l.push(ce(d,{score:p,fields:{authority:a[f],hub:i[f]}}))}const u=new Set(r),h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}class Gr extends q{constructor(t){super();b(this,"graph");this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let h=0;h<r.length;h++)o.set(r[h],h);const i=new Float64Array(s);for(let h=0;h<s;h++){const f=[],d=new Array(s);for(let v=0;v<s;v++)d[v]=new Set;const p=new Float64Array(s);p[h]=1;const m=new Float64Array(s);m.fill(-1),m[h]=0;const _=[h];let y=0;for(;y<_.length;){const v=_[y];y++,f.push(v);const E=r[v],I=n.neighbors(E,this.graph,null,"out"),S=n.neighbors(E,this.graph,null,"in"),N=new Set([...I,...S]);for(const A of N){const O=o.get(A);O!==void 0&&(m[O]<0&&(_.push(O),m[O]=m[v]+1),m[O]===m[v]+1&&(p[O]=p[O]+p[v],d[O].add(v)))}}const x=new Float64Array(s);for(;f.length>0;){const v=f.pop();for(const E of d[v])x[E]=x[E]+p[E]/p[v]*(1+x[v]);v!==h&&(i[v]=i[v]+x[v])}}for(let h=0;h<s;h++)i[h]=i[h]/2;const a=[];for(let h=0;h<s;h++){const f=r[h];a.push(ce(f,{score:i[h],fields:{betweenness:i[h]}}))}const l=new Set(r),u=new W(a);for(const h of a)u.setGraphPayload(h.docId,ne({subgraphVertices:l,subgraphEdges:new Set,score:h.payload.score,graphName:this.graph}));return u}}class Dn extends q{constructor(t){super();b(this,"kLayers");b(this,"aggregation");b(this,"propertyName");b(this,"graph");this.kLayers=t.kLayers??2,this.aggregation=t.aggregation??"mean",this.propertyName=t.propertyName??"feature",this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let h=0;h<r.length;h++)o.set(r[h],h);let i=new Float64Array(s);for(let h=0;h<s;h++){const f=r[h],d=n.getVertex(f);if(d){const p=d.properties[this.propertyName];typeof p=="number"?i[h]=p:i[h]=0}}for(let h=0;h<this.kLayers;h++){const f=new Float64Array(s);for(let d=0;d<s;d++){const p=r[d],m=n.neighbors(p,this.graph,null,"out"),_=n.neighbors(p,this.graph,null,"in"),y=new Set([...m,..._]),x=[];for(const E of y){const I=o.get(E);I!==void 0&&x.push(i[I])}let v;if(x.length===0)v=i[d];else if(this.aggregation==="mean"){let E=0;for(const I of x)E+=I;v=E/x.length}else if(this.aggregation==="sum"){let E=0;for(const I of x)E+=I;v=E}else{let E=x[0];for(let I=1;I<x.length;I++)x[I]>E&&(E=x[I]);v=E}f[d]=v+i[d]}i=f}for(let h=0;h<s;h++)i[h]=1/(1+Math.exp(-i[h]));const a=[];for(let h=0;h<s;h++){const f=r[h];a.push(ce(f,{score:i[h],fields:{_mp_score:i[h]}}))}const l=new Set(r),u=new W(a);for(const h of a)u.setGraphPayload(h.docId,ne({subgraphVertices:l,subgraphEdges:new Set,score:h.payload.score,graphName:this.graph}));return u}}class Br extends q{constructor(t){super();b(this,"graph");b(this,"kHops");this.graph=t.graph,this.kHops=t.kHops??2}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const i=[...n.vertexLabelCounts(this.graph).keys()].sort(),a=new Map;for(let f=0;f<i.length;f++)a.set(i[f],f);const l=[],u=new Set(r);for(const f of r){const d=n.getVertex(f);if(!d)continue;const p=n.outEdgeIds(f,this.graph),m=n.inEdgeIds(f,this.graph),_=p.size,y=m.size,x=_+y,v=s>1?x/(2*(s-1)):0,E=new Float64Array(i.length),I=new Set;for(const C of n.neighbors(f,this.graph,null,"out"))I.add(C);for(const C of n.neighbors(f,this.graph,null,"in"))I.add(C);if(I.size>0){for(const C of I){const V=n.getVertex(C);if(V){const X=a.get(V.label);X!==void 0&&(E[X]=E[X]+1)}}for(let C=0;C<E.length;C++)E[C]=E[C]/I.size}const S=new Float64Array(this.kHops),N=new Set([f]);let A=new Set([f]);for(let C=0;C<this.kHops;C++){const V=new Set;for(const X of A){for(const he of n.neighbors(X,this.graph,null,"out"))N.has(he)||(N.add(he),V.add(he));for(const he of n.neighbors(X,this.graph,null,"in"))N.has(he)||(N.add(he),V.add(he))}S[C]=s>1?V.size/(s-1):0,A=V}const O=1+i.length+this.kHops,R=new Float64Array(O);R[0]=v;for(let C=0;C<E.length;C++)R[1+C]=E[C];for(let C=0;C<S.length;C++)R[1+i.length+C]=S[C];let T=0;for(let C=0;C<O;C++)T+=R[C]*R[C];const F=Math.sqrt(T);l.push(ce(f,{score:F,fields:{embedding:R,out_degree:_,in_degree:y,label:d.label}}))}const h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}function qo(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function Ur(c){return c<=0?-10:c>=1?10:Math.log(c/(1-c))}class zo{constructor(e,t,n){b(this,"_bm25");b(this,"_transform");b(this,"_priorFn");this._bm25=new xt(e.bm25,t),this._transform=new K.BayesianProbabilityTransform(e.alpha,e.beta,e.baseRate===.5?null:e.baseRate),this._priorFn=n}scoreWithPrior(e,t,n,r){const s=this._bm25.idf(n),o=this._bm25.scoreWithIdf(e,t,s),i=this._bm25.params.k1>0?t:1,a=i>0?t/i:1,l=this._transform.scoreToProbability(o,e,a);let u=this._priorFn(r);u=Math.max(1e-10,Math.min(1-1e-10,u));const h=Ur(l)+Ur(u);return qo(h)}}function Go(c,e=30){return t=>{const n=t[c];if(n==null)return .5;let r;if(n instanceof Date)r=n;else if(typeof n=="string"){if(r=new Date(n),isNaN(r.getTime()))return .5}else return .5;const s=(Date.now()-r.getTime())/864e5;return .5+.4*Math.exp(-s/e)}}function Bo(c,e){const t=e??{high:.8,medium:.6,low:.4};return n=>{const r=n[c];if(r==null)return .5;const s=typeof r=="string"?r:String(r);return t[s]??.5}}function Uo(c,e,t=42,n="kaiming",r=null,s=null,o=0,i=0){if(n==="orthogonal")return Mo(c,e,t);if(n==="gabor")return Oo(c,e,t);if(n==="kmeans"){if(r===null||s===null)throw new Error("kmeans init requires training_data");return Co(c,e,r,s,o,i,t)}let a=t;function l(){a^=a<<13,a^=a>>17,a^=a<<5;const d=(a>>>0)/4294967295;a^=a<<13,a^=a>>17,a^=a<<5;const p=(a>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,d)))*Math.cos(2*Math.PI*p)}const u=e*9,h=Math.sqrt(2/u),f=new Float64Array(c*e*9);for(let d=0;d<f.length;d++)f[d]=l()*h;return f}class Wr{constructor(e,t=6,n=.5,r=!1,s){b(this,"_attn");this._attn=new K.AttentionLogOddsWeights(e,t,n,r,0,s??null)}get nSignals(){return this._attn.nSignals}get nQueryFeatures(){return this._attn.nQueryFeatures}fuse(e,t){const n=this._attn.weightsMatrix,r=e.length,s=t.length,o=[];for(let l=0;l<r;l++){let u=0;const h=n[l];if(h)for(let f=0;f<s;f++)u+=(h[f]??0)*(t[f]??0);o.push(u)}let i=-1/0;for(const l of o)l>i&&(i=l);let a=0;for(let l=0;l<o.length;l++)o[l]=Math.exp(o[l]-i),a+=o[l];for(let l=0;l<o.length;l++)o[l]=o[l]/a;return K.logOddsConjunction(e,this._attn.alpha,o)}fit(e,t,n){this._attn.fit(e,t,n)}update(e,t,n){this._attn.update(e,t,n)}stateDict(){return{weights_matrix:this._attn.weightsMatrix,alpha:this._attn.alpha,n_signals:this._attn.nSignals,n_query_features:this._attn.nQueryFeatures}}loadStateDict(e){this._attn=new K.AttentionLogOddsWeights(e.n_signals,e.n_query_features,e.alpha);const t=e.weights_matrix;if(t!=null){const n=t;for(let r=0;r<n.length;r++)for(let s=0;s<n[r].length;s++)this._attn.weightsMatrix[r][s]=n[r][s]}}}class Wo{constructor(e,t=4,n=6,r=.5,s=!1){b(this,"_mh");b(this,"_nQueryFeatures");this._mh=new K.MultiHeadAttentionLogOddsWeights(t,e,n,r,s),this._nQueryFeatures=n}get nSignals(){var e;return((e=this._mh.heads[0])==null?void 0:e.nSignals)??0}get nQueryFeatures(){return this._nQueryFeatures}fuse(e,t){return this._mh.combine(e,t,!1)}fit(e,t,n){this._mh.fit(e,t,n)}stateDict(){var e;return{n_heads:this._mh.nHeads,n_signals:this.nSignals,n_query_features:this._nQueryFeatures,alpha:((e=this._mh.heads[0])==null?void 0:e.alpha)??.5}}loadStateDict(e){this._mh=new K.MultiHeadAttentionLogOddsWeights(e.n_heads,e.n_signals,e.n_query_features,e.alpha),this._nQueryFeatures=e.n_query_features}}class Hr{constructor(e,t=.5){b(this,"_learnable");this._learnable=new K.LearnableLogOddsWeights(e,t)}get nSignals(){return this._learnable.nSignals}fuse(e){const t=[...this._learnable.weights];return K.logOddsConjunction(e,this._learnable.alpha,t)}update(e,t,n){const r=e.map(o=>{const i=Math.max(1e-10,Math.min(.9999999999,o));return Math.log(i/(1-i))}),s=t-this.fuse(e);this._learnable.update(r,s,n)}stateDict(){return{weights:[...this._learnable.weights],alpha:this._learnable.alpha,n_signals:this._learnable.nSignals}}loadStateDict(e){this._learnable=new K.LearnableLogOddsWeights(e.n_signals,e.alpha);const t=e.weights;for(let n=0;n<t.length;n++)this._learnable.weights[n]=t[n]}}class Ho{constructor(e){b(this,"_index");this._index=e}get nFeatures(){return 6}extract(e,t){const n=this._index.stats,r=n.totalDocs;if(r===0)return new Float64Array(6);const s=t??"_default",o=[];let i=0;for(const m of e){const _=n.docFreq(s,m);if(_>0){i++;const y=Math.log((r-_+.5)/(_+.5)+1);o.push(y)}}if(o.length===0)return new Float64Array([0,0,0,0,e.length,0]);let a=0,l=-1/0,u=1/0;for(const m of o)a+=m,m>l&&(l=m),m<u&&(u=m);const h=a/o.length,f=o.length/Math.max(1,r),d=e.length,p=i/Math.max(1,e.length);return new Float64Array([h,l,u,f,d,p])}}class qe{constructor(e,t){b(this,"_columnStats");b(this,"_graphStats");b(this,"_graphStore");e instanceof Map?(this._columnStats=e,this._graphStats=(t==null?void 0:t.graphStats)??null,this._graphStore=(t==null?void 0:t.graphStore)??null):e!=null&&!(e instanceof Map)?(this._columnStats=e.columnStats??new Map,this._graphStats=e.graphStats??(t==null?void 0:t.graphStats)??null,this._graphStore=e.graphStore??(t==null?void 0:t.graphStore)??null):(this._columnStats=new Map,this._graphStats=(t==null?void 0:t.graphStats)??null,this._graphStore=(t==null?void 0:t.graphStore)??null)}estimate(e,t){const n=t.totalDocs>0?t.totalDocs:1;if(e instanceof me){const r=e.field??"_default";return t.docFreq(r,e.term)}if(e instanceof xe)return n*qe._vectorSelectivity(e.threshold);if(e instanceof Le)return e.k;if(e instanceof G)return n*this._filterSelectivity(e.field,e.predicate,n);if(e instanceof de)return this.estimate(e.source,t);if(e instanceof H){const r=e.operands.map(i=>this.estimate(i,t)).sort((i,a)=>i-a);if(r.length===0)return 0;const s=this._intersectionDamping(e.operands);let o=r[0];for(let i=1;i<r.length;i++){const a=n>0?r[i]/n:1;o*=a**s}if(this._columnStats.size>0){const i=[];for(const a of e.operands)if(a instanceof G&&a.field){const l=this._columnStats.get(a.field);l!==void 0&&i.push(en(l))}if(i.length>0){const a=Jo(n,i);o=Math.max(o,a)}}return Math.max(1,o)}if(e instanceof re){const r=e.operands.map(s=>this.estimate(s,t));return Math.min(n,r.reduce((s,o)=>s+o,0))}if(e instanceof fe){const r=this.estimate(e.operand,t);return Math.max(0,n-r)}if(e instanceof Ee)return this.estimate(e.source,t)*.5;if(e instanceof Ve){if(e.stages.length===0)return 0;const[,r]=e.stages[e.stages.length-1];return typeof r=="number"?r:n*.5}return Math.max(1,Math.floor(e.costEstimate(t)))}_intersectionDamping(e){const t=[];for(const n of e)n instanceof G&&t.push(n.field);if(t.length<2)return .5;if(new Set(t).size===1)return .1;if(this._columnStats.size>0&&t.length>=2){const n=this._columnStats.get(t[0]),r=this._columnStats.get(t[1]);if(n!==void 0&&r!==void 0){const s=Ko(n,r,.1);if(s>1)return .2;if(s>.5)return .3}}return .5}static _vectorSelectivity(e){return e>=.9?.01:e>=.7?.05:e>=.5?.1:.2}estimateJoinSide(e,t,n){return e instanceof q?this.estimate(e,t):(e!=null&&typeof e.execute=="function",n)}sampleGraphCardinality(e,t=100){if(this._graphStats===null)return-1;const n=this._graphStats.numVertices;if(n<=0)return 0;const r=e.vertexPatterns??[],s=e.edgePatterns??[],o=r.length;if(o===0)return 0;const i=this._graphStats.numEdges,a=i>0&&n>0?i/(n*n):.01;let l=1;for(const h of s)h.label!==null&&(l*=this._graphStats.labelSelectivity(h.label));const u=Math.pow(n,o)*Math.pow(a,s.length)*l;return Math.max(1,Math.floor(u))}estimateJoin(e,t,n){return n<=0?0:e*t/n}_filterSelectivity(e,t,n){var l;const r=this._columnStats.get(e);if(r===void 0||r.distinctCount<=0)return .5;const s=r.distinctCount;let o;const i=t,a=((l=i.constructor)==null?void 0:l.name)??"";if(a==="Equals"||i.type==="equals"?o=qe._equalitySelectivity(r,i.target,s):a==="NotEquals"||i.type==="not_equals"?o=1-qe._equalitySelectivity(r,i.target,s):a==="InSet"||i.type==="in_set"?o=Math.min(1,(i.values??[]).reduce((u,h)=>u+qe._equalitySelectivity(r,h,s),0)):a==="Between"||i.type==="between"?o=this._rangeSelectivity(r,i.low,i.high):a==="GreaterThan"||a==="GreaterThanOrEqual"||i.type==="gt"||i.type==="gte"?o=this._gtSelectivity(r,i.target):a==="LessThan"||a==="LessThanOrEqual"||i.type==="lt"||i.type==="lte"?o=this._ltSelectivity(r,i.target):o=.5,r.distinctCount>1){const u=en(r);if(u>0){const h=1/2**u;o=Math.max(h,o)}}return o}static _equalitySelectivity(e,t,n){if(e.mcvValues.length>0){for(let r=0;r<e.mcvValues.length;r++)if(e.mcvValues[r]===t)return e.mcvFrequencies[r]}return n>0?1/n:1}static histogramFraction(e,t,n){if(e.length<2)return .5;const r=e.length-1;let s=0;for(let o=0;o<r;o++){const i=e[o],a=e[o+1];try{if(n<i||t>a)continue;if(t<=i&&n>=a)s+=1;else{const l=a-i;if(l<=0){s+=1;continue}const u=Math.max(t,i),h=Math.min(n,a);s+=(h-u)/l}}catch{s+=1}}return Math.max(0,Math.min(1,s/r))}_rangeSelectivity(e,t,n){if(e.histogram.length>0)return qe.histogramFraction(e.histogram,t,n);if(e.minValue!=null&&e.maxValue!=null)try{const r=e.maxValue-e.minValue;if(r>0)return Math.max(0,Math.min(1,(n-t)/r))}catch{}return .25}_gtSelectivity(e,t){if(e.histogram.length>0)return qe.histogramFraction(e.histogram,t,e.histogram[e.histogram.length-1]);if(e.minValue!=null&&e.maxValue!=null)try{const n=e.maxValue-e.minValue;if(n>0)return Math.max(0,(e.maxValue-t)/n)}catch{}return 1/3}_ltSelectivity(e,t){if(e.histogram.length>0)return qe.histogramFraction(e.histogram,e.histogram[0],t);if(e.minValue!=null&&e.maxValue!=null)try{const n=e.maxValue-e.minValue;if(n>0)return Math.max(0,(t-e.minValue)/n)}catch{}return 1/3}estimateGraphPattern(e,t){if(this._graphStats===null)return 1;const n=this._graphStats,r=n.numVertices>0?n.numVertices:1,s=Math.max(1,Math.ceil(e/2)),o=Math.max(0,e-s),i=r>1?n.numEdges/(r*r):0;let a=1;if(t!==void 0&&n.numEdges>0)for(const h of t){const f=n.labelCounts.get(h)??0;a*=f/n.numEdges}let l=1;if(n.vertexLabelCounts.size>0&&r>0){let h=0;for(const d of n.vertexLabelCounts.values())h+=d;const f=h/(n.vertexLabelCounts.size*r);l=Math.pow(Math.min(1,f),s)}const u=Math.pow(r,s)*Math.pow(i,o)*a*l;return Math.max(1,Math.min(r,Math.floor(u)))}estimatePathQuery(e,t){if(this._graphStats===null)return 1;const n=this._graphStats,r=n.numVertices>0?n.numVertices:1;let s=n.avgOutDegree;if(t!==void 0&&n.numEdges>0){const a=(n.labelCounts.get(t)??0)/n.numEdges;s*=a}const o=r*Math.pow(s,e);return Math.max(1,Math.min(Math.floor(o),n.numEdges))}estimateTraverse(e,t=null){if(this._graphStats!==null){const r=this._graphStats;let s;if(t&&r.labelDegreeMap.size>0)s=r.labelDegreeMap.get(t)??r.avgOutDegree*r.labelSelectivity(t);else{const i=r.labelSelectivity(t);s=r.avgOutDegree*i}const o=r.numVertices>0?r.numVertices:1;return Math.min(o,s**e)}const n=1e3;return Math.min(n,Math.min(n*.1,10)**e)}estimatePatternMatch(e,t,n=[]){if(this._graphStats!==null){const r=this._graphStats,s=r.numVertices>0?r.numVertices:1,o=r.edgeDensity();let i=1;for(const l of n)i*=r.labelSelectivity(l);const a=s**e*o**t*i;return Math.max(1,Math.min(s,a))}return 1}estimateCrossParadigm(e,t,n){const r=t.totalDocs>0?t.totalDocs:1;switch(n){case"text_graph":{const s=this.estimate(e,t),o=this._graphStats!==null?Math.min(1,this._graphStats.avgOutDegree/Math.max(1,this._graphStats.numVertices)):.1;return Math.max(1,Math.floor(s*o))}case"text_vector":{const s=this.estimate(e,t);return Math.max(1,Math.floor(s*.3))}case"graph_vector":{const s=this._graphStats!==null?Math.min(r,this._graphStats.avgOutDegree**2):r*.1;return Math.max(1,Math.floor(s*.2))}case"text_graph_vector":{const s=this.estimate(e,t),o=this._graphStats!==null?Math.min(1,this._graphStats.avgOutDegree/Math.max(1,this._graphStats.numVertices)):.1;return Math.max(1,Math.floor(s*o*.3))}case"log_odds_fusion":return Math.max(1,Math.floor(r*.15));case"prob_bool_fusion":return Math.max(1,Math.floor(r*.25));case"attention_fusion":return Math.max(1,Math.floor(r*.2));case"learned_fusion":return Math.max(1,Math.floor(r*.2));default:return Math.max(1,Math.floor(r*.5))}}estimateTemporalPattern(e,t,n,r,s){const o=this.estimatePatternMatch(e,t,n);if(this._graphStats===null)return o;const i=this._graphStats;let a=1;if(r!==null&&s!==null&&i.minTimestamp!==null&&i.maxTimestamp!==null){const l=i.maxTimestamp-i.minTimestamp;if(l>0){const u=Math.min(s,i.maxTimestamp)-Math.max(r,i.minTimestamp);a=Math.max(0,Math.min(1,u/l))}}else(r!==null||s!==null)&&(a=.5);return Math.max(1,Math.floor(o*a))}estimateTemporalTraverse(e,t,n,r){const s=this.estimateTraverse(e,t);if(this._graphStats===null)return s;const o=this._graphStats;let i=1;if(n!==null&&r!==null&&o.minTimestamp!==null&&o.maxTimestamp!==null){const a=o.maxTimestamp-o.minTimestamp;if(a>0){const l=Math.min(r,o.maxTimestamp)-Math.max(n,o.minTimestamp);i=Math.max(0,Math.min(1,l/a))}}return Math.max(1,Math.floor(s*Math.pow(i,e)))}estimateWeightedRPQ(e,t,n){const r=this.estimatePathQuery(e,t.length>0?t[0]:void 0);let s=1;if(n!==null&&(s=Math.pow(1-n,e)),t.length>1&&this._graphStats!==null){const o=this._graphStats;let i=1;for(const a of t)i*=o.labelSelectivity(a);return Math.max(1,Math.floor(r*s*i))}return Math.max(1,Math.floor(r*s))}estimateBoundedRPQ(e,t,n){if(this._graphStats===null)return 1;const r=this._graphStats,s=r.numVertices>0?r.numVertices:1;let o=r.avgOutDegree;n!==null&&r.numEdges>0&&(o*=r.labelSelectivity(n));let i=0;for(let l=e;l<=t;l++)i+=s*Math.pow(o,l);const a=i/(t-e+1);return Math.max(1,Math.min(Math.floor(a),r.numEdges))}}function en(c){const e=c.distinctCount;if(e<=1)return 0;const t=c.mcvFrequencies;if(t.length>0){let r=0,s=1;for(const i of t)s-=i,i>0&&(r-=i*Math.log2(i));const o=Math.max(1,e-t.length);if(s>0&&o>0){const i=s/o;r-=s*Math.log2(i)}return Math.max(0,r)}const n=c.histogram;if(n.length>1){const r=n.length-1,s=1/r;return-r*s*Math.log2(s)}return Math.log2(e)}function Ko(c,e,t){const n=en(c),r=en(e),s=Math.max(1,c.distinctCount),o=Math.max(1,e.distinctCount),i=s*o,a=Math.max(1,i*t),l=Math.log2(Math.max(1,a));return Math.max(0,n+r-l)}function Jo(c,e){if(e.length===0||c<=0)return 1;const t=e.reduce((r,s)=>r+s,0),n=c*2**-t;return Math.max(1,n)}class Rt{}class Yo extends Rt{identity(){return 0}accumulate(e,t){return e+1}combine(e,t){return e+t}finalize(e){return e}}class Xo extends Rt{identity(){return 0}accumulate(e,t){return e+t}combine(e,t){return e+t}finalize(e){return e}}class Qo extends Rt{identity(){return[0,0]}accumulate(e,t){return[e[0]+t,e[1]+1]}combine(e,t){return[e[0]+t[0],e[1]+t[1]]}finalize(e){return e[1]===0?0:e[0]/e[1]}}class Zo extends Rt{identity(){return 1/0}accumulate(e,t){return Math.min(e,t)}combine(e,t){return Math.min(e,t)}finalize(e){return e}}class ei extends Rt{identity(){return-1/0}accumulate(e,t){return Math.max(e,t)}combine(e,t){return Math.max(e,t)}finalize(e){return e}}class ti extends q{constructor(t,n,r){super();b(this,"source");b(this,"field");b(this,"monoid");this.source=t,this.field=n,this.monoid=r}execute(t){const n=t.documentStore;let r;this.source?r=this.source.execute(t).entries.map(a=>a.docId):r=n?[...n.docIds].sort((a,l)=>a-l):[];let s=this.monoid.identity();for(const a of r){const l=n?n.getField(a,this.field):void 0;l!=null&&(s=this.monoid.accumulate(s,l))}const o=this.monoid.finalize(s),i=typeof o=="number"?o:0;return D.fromSorted([{docId:0,payload:U({score:i,fields:{_aggregate_field:this.field,_aggregate:o}})}])}costEstimate(t){return t.totalDocs}}class ni extends q{constructor(t,n,r,s){super();b(this,"source");b(this,"groupField");b(this,"aggField");b(this,"monoid");this.source=t,this.groupField=n,this.aggField=r,this.monoid=s}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return new D;const s=new Map;for(const a of n){const l=r.getField(a.docId,this.groupField);if(l==null)continue;const u=String(l);s.has(u)||s.set(u,this.monoid.identity());const h=r.getField(a.docId,this.aggField);h!=null&&s.set(u,this.monoid.accumulate(s.get(u),h))}const i=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0])).map(([a,l],u)=>{const h=this.monoid.finalize(l);return{docId:u,payload:U({score:typeof h=="number"?h:0,fields:{_group_key:a,_group_field:this.groupField,_aggregate_result:h}})}});return D.fromSorted(i)}}class ri extends q{constructor(t){super();b(this,"pattern");b(this,"graph");b(this,"temporalFilter");b(this,"score");this.pattern=t.pattern,this.graph=t.graph,this.temporalFilter=t.temporalFilter,this.score=t.score??1}execute(t){const n=t.graphStore,r=this._backtrackSearch(n);return this._buildPostingList(n,r)}_backtrackSearch(t){const n=this._computeCandidates(t),r=[],s=new Map,o=this.pattern.vertexPatterns.map(i=>i.variable);return this._backtrack(t,o,0,s,n,r),r}_computeCandidates(t){const n=new Map,r=t.vertexIdsInGraph(this.graph);for(const s of this.pattern.vertexPatterns){let o=new Set(r);if(s.constraints.length>0){const i=new Set;for(const a of o){const l=t.getVertex(a);if(l){let u=!0;for(const h of s.constraints)if(!h(l)){u=!1;break}u&&i.add(a)}}o=i}n.set(s.variable,o)}return n}_backtrack(t,n,r,s,o,i){if(r===n.length){this._validateAllEdges(t,s)&&i.push(new Map(s));return}const a=n[r],l=o.get(a)??new Set,u=new Set(s.values());for(const h of l)u.has(h)||(s.set(a,h),this._validateEdgesFor(t,s,a)&&this._backtrack(t,n,r+1,s,o,i),s.delete(a))}_validateEdgesFor(t,n,r){for(const s of this.pattern.edgePatterns){if(s.negated||s.sourceVar!==r&&s.targetVar!==r)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);let l=!1;for(const u of a){const h=t.getEdge(u);if(!h||h.targetId!==i||s.label!==null&&h.label!==s.label||!this.temporalFilter.isValid(h))continue;let f=!0;for(const d of s.constraints)if(!d(h)){f=!1;break}if(f){l=!0;break}}if(!l)return!1}return!0}_validateAllEdges(t,n){for(const r of this.pattern.edgePatterns){const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0)return!1;if(r.negated){const i=t.outEdgeIds(s,this.graph);for(const a of i){const l=t.getEdge(a);if(l&&l.targetId===o&&(r.label===null||l.label===r.label)&&this.temporalFilter.isValid(l))return!1}}else{const i=t.outEdgeIds(s,this.graph);let a=!1;for(const l of i){const u=t.getEdge(l);if(u&&u.targetId===o&&!(r.label!==null&&u.label!==r.label)&&this.temporalFilter.isValid(u)){a=!0;break}}if(!a)return!1}}return!0}_collectMatchEdges(t,n){const r=new Set;for(const s of this.pattern.edgePatterns){if(s.negated)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);for(const l of a){const u=t.getEdge(l);u&&u.targetId===i&&(s.label===null||u.label===s.label)&&this.temporalFilter.isValid(u)&&r.add(l)}}return r}_buildPostingList(t,n){const r=[],s=new Map;for(let i=0;i<n.length;i++){const a=n[i],l=new Set(a.values()),u=this._collectMatchEdges(t,a),h=i,f={};for(const[d,p]of a)f[d]=p;r.push(ce(h,{score:this.score,fields:f})),s.set(h,ne({subgraphVertices:l,subgraphEdges:u,score:this.score,graphName:this.graph}))}const o=new W(r);for(const[i,a]of s)o.setGraphPayload(i,a);return o}}function Te(c,e){return c!==null&&typeof c=="object"&&"execute"in c&&typeof c.execute=="function"?[...c.execute(e).entries]:c}class si{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"leftField");b(this,"rightField");b(this,"threshold");this.left=e,this.right=t,this.leftField=n,this.rightField=r,this.threshold=s}execute(e){const t=Te(this.left,e),n=Te(this.right,e),r=[];for(const s of t){const o=s.payload.fields[this.leftField],i=typeof o=="string"?o:"",a=new Set(sr.analyze(i));if(a.size!==0)for(const l of n){const u=l.payload.fields[this.rightField],h=typeof u=="string"?u:"",f=new Set(sr.analyze(h));if(f.size===0)continue;let d=0;for(const _ of a)f.has(_)&&d++;const p=a.size+f.size-d,m=p>0?d/p:0;m>=this.threshold&&r.push({docIds:[s.docId,l.docId],payload:U({score:m,fields:{...s.payload.fields,...l.payload.fields}})})}}return new we(r)}}class Kr{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"leftField");b(this,"rightField");b(this,"threshold");this.left=e,this.right=t,this.leftField=n,this.rightField=r,this.threshold=s}execute(e){const t=Te(this.left,e),n=Te(this.right,e),r=[];for(const s of t){const o=s.payload.fields[this.leftField];if(o)for(const i of n){const a=i.payload.fields[this.rightField];if(!a)continue;const l=at(o,a);l>=this.threshold&&r.push({docIds:[s.docId,i.docId],payload:U({score:l,fields:{...s.payload.fields,...i.payload.fields}})})}}return new we(r)}}class oi{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"structuredField");b(this,"vectorField");b(this,"threshold");this.left=e,this.right=t,this.structuredField=n,this.vectorField=r,this.threshold=s}execute(e){const t=Te(this.left,e),n=Te(this.right,e),r=new Map;for(const o of n){const i=o.payload.fields[this.structuredField];if(i==null)continue;let a=r.get(i);a||(a=[],r.set(i,a)),a.push(o)}const s=[];for(const o of t){const i=o.payload.fields[this.structuredField];if(i==null)continue;const a=o.payload.fields[this.vectorField];if(!a)continue;const l=r.get(i);if(l)for(const u of l){const h=u.payload.fields[this.vectorField];if(!h)continue;const f=at(a,h);f>=this.threshold&&s.push({docIds:[o.docId,u.docId],payload:U({score:f,fields:{...o.payload.fields,...u.payload.fields}})})}}return new we(s)}}class ii{constructor(e,t,n,r="test"){b(this,"left");b(this,"right");b(this,"label");b(this,"graphName");this.left=e,this.right=t,this.label=n??null,this.graphName=r}execute(e){const t=e.graphStore,n=Te(this.left,e),r=Te(this.right,e),s=new Map;for(const i of r)s.set(i.docId,i);const o=[];for(const i of n){const a=t.neighbors(i.docId,this.graphName,this.label,"out");for(const l of a){const u=s.get(l);u&&o.push({docIds:[i.docId,u.docId],payload:U({score:i.payload.score+u.payload.score,fields:{...i.payload.fields,...u.payload.fields}})})}}return new we(o)}}class ai{constructor(e,t,n,r){b(this,"left");b(this,"right");b(this,"vertexField");b(this,"docField");this.left=e,this.right=t,this.vertexField=n,this.docField=r}execute(e){const t=e.graphStore,n=Te(this.left,e),r=Te(this.right,e),s=new Map;for(const i of r){const a=i.payload.fields[this.docField];if(a==null)continue;let l=s.get(a);l||(l=[],s.set(a,l)),l.push(i)}const o=[];for(const i of n){const a=t.getVertex(i.docId);let l;if(a?l=a.properties[this.vertexField]:l=i.payload.fields[this.vertexField],l==null)continue;const u=s.get(l);if(u)for(const h of u){const f={};a&&Object.assign(f,a.properties),Object.assign(f,i.payload.fields),Object.assign(f,h.payload.fields),o.push({docIds:[i.docId,h.docId],payload:U({score:i.payload.score+h.payload.score,fields:f})})}}return new we(o)}}const li=1.1,ci=.1,ui=1.5,hi=.2,Jr=.1;class fi{constructor(e){b(this,"_graphStats");this._graphStats=e??null}estimate(e,t){if(e instanceof me){const r=e.field??"_default";return t.totalDocs>0?t.docFreq(r,e.term):1}if(e instanceof xe||e instanceof Le)return t.dimensions*Math.log2(t.totalDocs+1);if(e instanceof zt)return e.costEstimate(t);if(e instanceof de)return this.estimate(e.source,t)*li;if(e instanceof G){const r=t.totalDocs;return e.source!==null?this.estimate(e.source,t)+r*ci:r}if(e instanceof H){let r=0;for(const s of e.operands)r+=this.estimate(s,t);return r}if(e instanceof re){let r=0;for(const s of e.operands)r+=this.estimate(s,t);return r}if(e instanceof fe)return this.estimate(e.operand,t)+t.totalDocs;if(e instanceof ti)return t.totalDocs;if(e instanceof ni)return t.totalDocs*ui;if(e instanceof Ae){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof je){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof Ys){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof dt){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof kt){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof Gt)return this.estimate(e.signal,t)+t.totalDocs;if(e instanceof Ks){const r=e;return this.estimate(r._termOp,t)+this.estimate(r._vectorOp,t)}if(e instanceof Js){const r=e;return this.estimate(r.source,t)+this.estimate(r._vectorOp,t)}if(e instanceof En){const r=e;return this.estimate(r.positive,t)+this.estimate(r._negativeOp,t)}if(e instanceof pr){const r=e;let s=this.estimate(r._vectorOp,t);return r.source!==null&&(s+=this.estimate(r.source,t)),s}if(e instanceof $r)return t.totalDocs*hi;if(e instanceof Fn){if(this._graphStats!==null){const r=this._graphStats,s=e.label,o=e.maxHops,i=r.labelSelectivity(s),a=r.avgOutDegree*i;let l=0;for(let u=1;u<=o;u++)l+=Math.pow(a,u);return Math.max(1,l)}return t.totalDocs*Jr}if(e instanceof Dr){const r=e;let s;if(this._graphStats!==null){const i=this._graphStats,a=i.numVertices>0?i.numVertices:t.totalDocs,l=r.pattern.vertexPatterns.length;s=Math.max(1,Math.pow(a,l)*.01)}else s=Math.pow(t.totalDocs,2);let o=0;for(const i of r.pattern.edgePatterns)i.negated&&o++;return o>0&&(s*=1+.2*o),s}if(e instanceof Pn)return t.totalDocs*Jr;if(e instanceof ri)return Math.pow(t.totalDocs,2);if(e instanceof Vr){const r=e;if(Ln(r.pathExpr)!==null)return t.totalDocs*.1;if(this._graphStats!==null){const i=this._graphStats.numVertices,a=Ft(r.pathExpr);return Math.max(1,i*i*a*.001)}return Math.pow(t.totalDocs,2)}if(e instanceof Ee)return this.estimate(e.source,t)*.5;if(e instanceof Mn){const r=e;return t.totalDocs*r.fields.length}if(e instanceof Dn){const r=e;return t.totalDocs*r.kLayers}if(e instanceof Br){const r=e;return t.totalDocs*r.kLayers*2}if(e instanceof Ve)return e.costEstimate(t);const n=t.totalDocs;return e instanceof qr?n*e.maxIterations*.1:e instanceof zr?n*e.maxIterations*.2:e instanceof Gr?n*n*.5:e instanceof si?2*n*Math.max(t.dimensions,10):e instanceof Kr?n*n*Math.max(t.dimensions,1):e instanceof ii?n*10:e instanceof oi?n+n*Math.max(t.dimensions,1):e instanceof ai?n*10:e instanceof kr?e.costEstimate(t):n}}function Ln(c){if(c instanceof Ce)return[c.label];if(c instanceof Qe){const e=c,t=Ln(e.left),n=Ln(e.right);return t!==null&&n!==null?[...t,...n]:null}return null}function Ft(c){if(c instanceof Ce)return 1;if(c instanceof Qe||c instanceof Ot){const e=c;return Ft(e.left)+Ft(e.right)}if(c instanceof Ct)return Ft(c.inner)*2;if(c instanceof Tt){const e=c;return Ft(e.inner)*e.maxHops}return 1}class Re{constructor(e,t){b(this,"stats");b(this,"estimator");b(this,"_costModel");b(this,"_graphStats");b(this,"_indexManager");b(this,"_tableName");this.stats=e;const n=(t==null?void 0:t.columnStats)??new Map;this._graphStats=(t==null?void 0:t.graphStats)??null,this.estimator=new qe(n,{graphStats:this._graphStats??void 0}),this._costModel=new fi(this._graphStats),this._indexManager=(t==null?void 0:t.indexManager)??null,this._tableName=(t==null?void 0:t.tableName)??null}optimize(e){let t=e;return t=this._simplifyAlgebra(t),t=this._pushFiltersDown(t),t=this._pushGraphPatternFilters(t),t=this._pushFilterIntoTraverse(t),t=this._pushFilterBelowGraphJoin(t),t=this._fuseJoinPattern(t),t=this._mergeVectorThresholds(t),t=this._reorderIntersect(t),t=this._reorderFusionSignals(t),t=this._applyIndexScan(t),t}_simplifyAlgebra(e){if(e=this._recurseSimplify(e),e instanceof H){let t=e.operands;for(const s of t)if(Re._isEmptyOperator(s))return new H([]);const n=[];for(const s of t)n.some(o=>o===s)||n.push(s);t=n;const r=[];for(const s of t)s instanceof re&&t.some(o=>o!==s&&s.operands.some(i=>t.some(a=>a===i&&a!==s)))||r.push(s);return t=r,t.length===1?t[0]:new H(t)}if(e instanceof re){let t=e.operands;t=t.filter(s=>!Re._isEmptyOperator(s));const n=[];for(const s of t)n.some(o=>o===s)||n.push(s);t=n;const r=[];for(const s of t)s instanceof H&&t.some(o=>o!==s&&s.operands.some(i=>t.some(a=>a===i&&a!==s)))||r.push(s);return t=r,t.length===1?t[0]:t.length===0?new re([]):new re(t)}return e}_recurseSimplify(e){return e instanceof H?new H(e.operands.map(t=>this._simplifyAlgebra(t))):e instanceof re?new re(e.operands.map(t=>this._simplifyAlgebra(t))):e instanceof fe?new fe(this._simplifyAlgebra(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,this._simplifyAlgebra(e.source)):e instanceof Je?new Je(e.operators.map(t=>this._simplifyAlgebra(t))):e}static _isEmptyOperator(e){return e instanceof H||e instanceof re?e.operands.length===0:!1}_pushFiltersDown(e){if(!(e instanceof G))return this._recurseChildren(e);const t=e.source;if(t instanceof H){const n=[];let r=!1;for(const s of t.operands)Re._filterAppliesTo(e,s)?(n.push(new G(e.field,e.predicate,s)),r=!0):n.push(s);if(r){const s=n.map(o=>this._pushFiltersDown(o));return this._recurseChildren(new H(s))}}return t===null?e:new G(e.field,e.predicate,this._recurseChildren(t))}_pushGraphPatternFilters(e){if(e instanceof G&&e.source!==null){const t=this._pushGraphPatternFilters(e.source),n=t.constructor.name;if(n==="PatternMatchOperator"){const r=t;if(r.withVertexPredicate&&e.field)return r.withVertexPredicate(e.field,e.predicate)}if(n==="TraverseOperator"){const r=t;if(e.field){const s=r.vertexPredicate,o=e.field,i=e.predicate,a=l=>{const u=l;return i.evaluate(u[o])?s!==null?s(l):!0:!1};try{const l=t.constructor;return new l(r.startVertex,r.graph,r.label,r.maxHops,a,r.score)}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushGraphPatternFilters(t))}_pushFilterIntoTraverse(e){if(e instanceof G&&e.source!==null){const t=this._pushFilterIntoTraverse(e.source);if(t.constructor.name==="TraverseOperator"){const r=t;if(e.field){const s=e.field,o=e.predicate,i=r.vertexPredicate,a=l=>{const u=l,h=u.properties?u.properties[s]:u[s];return o.evaluate(h)?i===null||i(l):!1};try{const l=t.constructor;return new l(r.startVertex,r.graph,r.label,r.maxHops,a,r.score)}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushFilterIntoTraverse(t))}_pushFilterBelowGraphJoin(e){if(e instanceof G&&e.source!==null){const t=this._pushFilterBelowGraphJoin(e.source),n=t.constructor.name;if(n==="CrossParadigmJoinOperator"||n==="GraphJoinOperator"){const r=t;{const s=Re._filterAppliesTo(e,r.left),o=Re._filterAppliesTo(e,r.right);if(s&&!o)try{const i=t.constructor;return new i(new G(e.field,e.predicate,r.left),r.right)}catch{}if(o&&!s)try{const i=t.constructor;return new i(r.left,new G(e.field,e.predicate,r.right))}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushFilterBelowGraphJoin(t))}_fuseJoinPattern(e){if(e instanceof H){const t=e.operands.map(s=>this._fuseJoinPattern(s)),n=[],r=[];for(const s of t)s.constructor.name==="PatternMatchOperator"?n.push(s):r.push(s);if(n.length>=2){const s=new Map;for(const a of n){const l=a.graph;s.has(l)||s.set(l,[]),s.get(l).push(a)}const o=[];for(const[,a]of s)if(a.length>=2){a.sort((l,u)=>this._costModel.estimate(l,this.stats)-this._costModel.estimate(u,this.stats)),o.push(a[0]);for(let l=1;l<a.length;l++)o.push(a[l])}else o.push(a[0]);const i=[...r,...o];return i.length===1?i[0]:new H(i)}return t.length===1?t[0]:new H(t)}return this._recurseGeneric(e,t=>this._fuseJoinPattern(t))}_mergeVectorThresholds(e){if(!(e instanceof H))return this._recurseChildren(e);const t=[],n=[];for(let i of e.operands)i=this._recurseChildren(i),i instanceof xe?t.push(i):n.push(i);const r=[],s=new Array(t.length).fill(!1);for(let i=0;i<t.length;i++){if(s[i])continue;let a=t[i];for(let l=i+1;l<t.length;l++)s[l]||a.field===t[l].field&&this._vectorsClose(a.queryVector,t[l].queryVector)&&(a=new xe(a.queryVector,Math.max(a.threshold,t[l].threshold),a.field),s[l]=!0);s[i]=!0,r.push(a)}const o=[...n,...r];return o.length===1?o[0]:new H(o)}_vectorsClose(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(Math.abs(e[n]-t[n])>1e-7)return!1;return!0}_reorderIntersect(e){if(!(e instanceof H))return this._recurseChildren(e);const t=e.operands.map(n=>this._recurseChildren(n));return t.sort((n,r)=>this._costModel.estimate(n,this.stats)-this._costModel.estimate(r,this.stats)),new H(t)}_reorderFusionSignals(e){if(e instanceof Ae){const t=e.signals.map(n=>this._reorderFusionSignals(n));return t.sort((n,r)=>this._graphAwareSignalCost(n)-this._graphAwareSignalCost(r)),new Ae(t,e.alpha,void 0,e.gating)}if(e instanceof je){const t=e.signals.map(n=>this._reorderFusionSignals(n));return t.sort((n,r)=>this._graphAwareSignalCost(n)-this._graphAwareSignalCost(r)),new je(t,e.mode)}return this._recurseGeneric(e,t=>this._reorderFusionSignals(t))}_graphAwareSignalCost(e){const t=this.estimator.estimate(e,this.stats);if(this._graphStats!==null){const n=e.constructor.name;if(n==="TraverseOperator"){const r=this._graphStats.edgeDensity();return t*(r<.01?.3:.5)}if(n==="PatternMatchOperator")return t*.5;if(n==="RegularPathQueryOperator")return t*.6;if(n==="WeightedPathQueryOperator")return t*.7;if(n==="TemporalTraverseOperator")return t*.6;if(n==="CypherQueryOperator")return t*.5}return e instanceof xe?t*.8:e instanceof me?t*.3:t}_applyIndexScan(e){if(this._indexManager===null||this._tableName===null)return e;if(e instanceof G&&e.source===null){const t=this._indexManager.findCoveringIndex(this._tableName,e.field,e.predicate);if(t!==null){const n=t.scanCost(e.predicate),r=this.stats.totalDocs;if(n<r)return new zt(t,e.field,e.predicate)}}return e instanceof G&&e.source!==null?new G(e.field,e.predicate,this._applyIndexScan(e.source)):this._recurseGeneric(e,t=>this._applyIndexScan(t))}_recurseGeneric(e,t){return e instanceof H?new H(e.operands.map(t)):e instanceof re?new re(e.operands.map(t)):e instanceof fe?new fe(t(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,t(e.source)):e instanceof Je?new Je(e.operators.map(t)):e}_recurseChildren(e){return e instanceof H?new H(e.operands.map(t=>this.optimize(t))):e instanceof re?new re(e.operands.map(t=>this.optimize(t))):e instanceof fe?new fe(this.optimize(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,this.optimize(e.source)):e instanceof Je?new Je(e.operators.map(t=>this.optimize(t))):e instanceof de?new de(e.scorer,this.optimize(e.source),e.queryTerms,e.field):e instanceof Ee?new Ee(this.optimize(e.source),e.threshold):e instanceof Ae?new Ae(e.signals.map(t=>this.optimize(t)),e.alpha,void 0,e.gating):e instanceof je?new je(e.signals.map(t=>this.optimize(t)),e.mode):e instanceof Gt?new Gt(this.optimize(e.signal),e.defaultProb):e instanceof dt?new dt(e.signals.map(t=>this.optimize(t)),e.attention,e.queryFeatures):e instanceof kt?new kt(e.signals.map(t=>this.optimize(t)),e.learned):e}static _filterAppliesTo(e,t){const n=e.field;return t instanceof me?t.field===n||t.field===null:t instanceof G?t.field===n:t instanceof H?t.operands.some(r=>Re._filterAppliesTo(e,r)):!1}}class tn{constructor(e){b(this,"_context");b(this,"_lastStats",null);this._context=e}execute(e){const[t,n]=this._executeWithStats(e);return this._lastStats=n,t}explain(e){return this._explainNode(e,0)}get lastStats(){return this._lastStats}_executeWithStats(e){const t=this._operatorName(e),n=[],r=performance.now();let s;if(e instanceof re){const a=[];for(const l of e.operands){const[u,h]=this._executeWithStats(l);a.push(u),n.push(h)}s=new D;for(const l of a)s=s.union(l)}else if(e instanceof H)if(e.operands.length===0)s=new D;else{const[a,l]=this._executeWithStats(e.operands[0]);n.push(l),s=a;for(let u=1;u<e.operands.length&&s.length!==0;u++){const[h,f]=this._executeWithStats(e.operands[u]);n.push(f),s=s.intersect(h)}}else if(e instanceof fe){const[,a]=this._executeWithStats(e.operand);n.push(a),s=e.execute(this._context)}else if(e instanceof Ee){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof de){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof G&&e.source!==null){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof Ve){for(const[a]of e.stages){const[,l]=this._executeWithStats(a);n.push(l)}s=e.execute(this._context)}else s=e.execute(this._context);const o=performance.now()-r,i={operatorName:t,elapsedMs:o,resultCount:s.length,children:n};return[s,i]}_explainNode(e,t){const n=" ".repeat(t),r=this._operatorName(e),s=this._operatorDetails(e);let i=s.length>0?`${n}${r} (${s})
9
+ `&&c[t]!=="\r"&&c[t]!=="|"&&c[t]!=="/"&&c[t]!=="*"&&c[t]!=="("&&c[t]!==")"&&c[t]!=="{"&&c[t]!=="}"&&c[t]!==",";)r+=c[t],t++;r.length>0&&e.push({type:"LABEL",value:r})}}return e}class Lo{constructor(e){b(this,"tokens");b(this,"pos");this.tokens=e,this.pos=0}peek(){return this.pos<this.tokens.length?this.tokens[this.pos]:null}consume(e){const t=this.peek();if(!t)throw new Error("RPQ parse error: unexpected end of input");if(e!==void 0&&t.type!==e)throw new Error(`RPQ parse error: expected ${e}, got ${t.type} ('${t.value}')`);return this.pos++,t}parseExpr(){var t;let e=this.parseConcat();for(;((t=this.peek())==null?void 0:t.type)==="PIPE";){this.consume("PIPE");const n=this.parseConcat();e=new Ot(e,n)}return e}parseConcat(){var t;let e=this.parseUnary();for(;((t=this.peek())==null?void 0:t.type)==="SLASH";){this.consume("SLASH");const n=this.parseUnary();e=new Ze(e,n)}return e}parseUnary(){let e=this.parsePrimary();const t=this.peek();if((t==null?void 0:t.type)==="STAR")this.consume("STAR"),e=new Ct(e);else if((t==null?void 0:t.type)==="LBRACE"){this.consume("LBRACE");const n=this.consume("NUMBER");this.consume("COMMA");const r=this.consume("NUMBER");if(this.consume("RBRACE"),e instanceof Te)e=new Tt(e.name,parseInt(n.value,10),parseInt(r.value,10));else throw new Error("RPQ parse error: bounded repetition only supported on labels")}return e}parsePrimary(){const e=this.peek();if(!e)throw new Error("RPQ parse error: unexpected end of input");if(e.type==="LPAREN"){this.consume("LPAREN");const t=this.parseExpr();return this.consume("RPAREN"),t}if(e.type==="LABEL")return this.consume("LABEL"),new Te(e.value);throw new Error(`RPQ parse error: unexpected token ${e.type} ('${e.value}')`)}}function Tr(c){const e=Do(c);if(e.length===0)throw new Error("RPQ parse error: empty expression");return new Lo(e).parseExpr()}function Rr(c){return[...c].sort((e,t)=>e-t).join(",")}function Fr(c,e){const t=new Set(e),n=[...e];for(;n.length>0;){const r=n.pop();for(const s of c.transitions)s.from===r&&s.label===null&&!t.has(s.to)&&(t.add(s.to),n.push(s.to))}return t}function jo(c,e,t){const n=new Set;for(const r of c.transitions)e.has(r.from)&&r.label===t&&n.add(r.to);return n}function Vo(c){const e=new Set;for(const t of c.transitions)t.label!==null&&e.add(t.label);return e}function Pr(c){const e=Vo(c),t=Fr(c,new Set([c.startState])),n=Rr(t),r=new Map,s=new Set,o=[[n,t]],i=new Set;for(t.has(c.acceptState)&&s.add(n);o.length>0;){const[a,l]=o.pop();if(!i.has(a)){i.add(a);for(const u of e){const h=jo(c,l,u);if(h.size===0)continue;const f=Fr(c,h),d=Rr(f);let p=r.get(a);p||(p=new Map,r.set(a,p)),p.set(u,d),f.has(c.acceptState)&&s.add(d),i.has(d)||o.push([d,f])}}}return{transitions:r,startState:n,acceptStates:s}}class Fn extends q{constructor(t,n,r,s,o,i){super();b(this,"startVertex");b(this,"graph");b(this,"label");b(this,"maxHops");b(this,"vertexPredicate");b(this,"score");this.startVertex=t,this.graph=n,this.label=r??null,this.maxHops=s??1/0,this.vertexPredicate=o??null,this.score=i??1}execute(t){const n=t.graphStore,r=this.graph,s=new Set,o=[],i=[[this.startVertex,0]];s.add(this.startVertex);const a=new Set,l=new Set;for(;i.length>0;){const[h,f]=i.shift(),d=n.getVertex(h);if(!d||this.vertexPredicate&&!this.vertexPredicate(d))continue;a.add(h);const p=this.score/(1+f);if(o.push(he(h,{score:p,fields:{...d.properties,_depth:f}})),f<this.maxHops){const m=n.neighbors(h,r,this.label,"out");for(const y of m)s.has(y)||(s.add(y),i.push([y,f+1]));const _=n.outEdgeIds(h,r);for(const y of _){const x=n.getEdge(y);x&&(this.label===null||x.label===this.label)&&l.add(y)}}}const u=new W(o);for(const h of o)u.setGraphPayload(h.docId,ne({subgraphVertices:a,subgraphEdges:l,score:h.payload.score,graphName:r}));return u}}class Dr extends q{constructor(t,n,r){super();b(this,"pattern");b(this,"graph");b(this,"score");this.pattern=t,this.graph=n,this.score=r??1}execute(t){const n=t.graphStore,r=this._backtrackSearch(n);return this._buildPostingList(n,r)}_backtrackSearch(t){const n=this._computeCandidates(t),r=[],s=new Map,o=this.pattern.vertexPatterns.map(i=>i.variable);return this._backtrack(t,o,0,s,n,r),r}_computeCandidates(t){const n=new Map,r=t.vertexIdsInGraph(this.graph);for(const o of this.pattern.vertexPatterns){let i=new Set(r);if(o.constraints.length>0){const a=new Set;for(const l of i){const u=t.getVertex(l);if(u){let h=!0;for(const f of o.constraints)if(!f(u)){h=!1;break}h&&a.add(l)}}i=a}n.set(o.variable,i)}let s=!0;for(;s;){s=!1;for(const o of this.pattern.edgePatterns){if(o.negated)continue;const i=n.get(o.sourceVar),a=n.get(o.targetVar);if(!i||!a)continue;const l=new Set;for(const h of i){const f=t.neighbors(h,this.graph,o.label,"out");let d=!1;for(const p of f)if(a.has(p)){d=!0;break}d&&l.add(h)}l.size<i.size&&(n.set(o.sourceVar,l),s=!0);const u=new Set;for(const h of a){const f=t.neighbors(h,this.graph,o.label,"in");let d=!1;for(const p of f)if(l.has(p)){d=!0;break}d&&u.add(h)}u.size<a.size&&(n.set(o.targetVar,u),s=!0)}}return n}_backtrack(t,n,r,s,o,i){if(r===n.length){this._validateAllEdges(t,s)&&this._checkNegatedEdges(t,s)&&i.push(new Map(s));return}let a=r,l=1/0;for(let d=r;d<n.length;d++){const p=n[d],m=o.get(p),_=m?m.size:0;_<l&&(l=_,a=d)}if(a!==r){const d=n[r];n[r]=n[a],n[a]=d}const u=n[r],h=o.get(u)??new Set,f=new Set(s.values());for(const d of h)f.has(d)||(s.set(u,d),this._validateEdgesFor(t,s,u)&&this._backtrack(t,n,r+1,s,o,i),s.delete(u))}_validateEdgesFor(t,n,r){for(const s of this.pattern.edgePatterns){if(s.negated||s.sourceVar!==r&&s.targetVar!==r)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;if(!t.neighbors(o,this.graph,s.label,"out").includes(i))return!1;if(s.constraints.length>0){const l=t.outEdgeIds(o,this.graph);let u=!1;for(const h of l){const f=t.getEdge(h);if(f&&f.targetId===i&&(s.label===null||f.label===s.label)){let d=!0;for(const p of s.constraints)if(!p(f)){d=!1;break}if(d){u=!0;break}}}if(!u)return!1}}return!0}_validateAllEdges(t,n){for(const r of this.pattern.edgePatterns){if(r.negated)continue;const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0||!t.neighbors(s,this.graph,r.label,"out").includes(o))return!1;if(r.constraints.length>0){const a=t.outEdgeIds(s,this.graph);let l=!1;for(const u of a){const h=t.getEdge(u);if(h&&h.targetId===o&&(r.label===null||h.label===r.label)){let f=!0;for(const d of r.constraints)if(!d(h)){f=!1;break}if(f){l=!0;break}}}if(!l)return!1}}return!0}_checkNegatedEdges(t,n){for(const r of this.pattern.edgePatterns){if(!r.negated)continue;const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0)continue;if(t.neighbors(s,this.graph,r.label,"out").includes(o))return!1}return!0}_collectMatchEdges(t,n){const r=new Set;for(const s of this.pattern.edgePatterns){if(s.negated)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);for(const l of a){const u=t.getEdge(l);u&&u.targetId===i&&(s.label===null||u.label===s.label)&&r.add(l)}}return r}_buildPostingList(t,n){const r=[],s=new Map;for(let i=0;i<n.length;i++){const a=n[i],l=new Set(a.values()),u=this._collectMatchEdges(t,a),h=i,f={};for(const[d,p]of a)f[d]=p;r.push(he(h,{score:this.score,fields:f})),s.set(h,ne({subgraphVertices:l,subgraphEdges:u,score:this.score,graphName:this.graph}))}const o=new W(r);for(const[i,a]of s)o.setGraphPayload(i,a);return o}}let Lr=0;function Ae(){return{id:Lr++}}function jr(){Lr=0}function qe(c){if(c instanceof Te){const e=Ae(),t=Ae();return{states:[e,t],transitions:[{from:e.id,to:t.id,label:c.name}],startState:e.id,acceptState:t.id}}if(c instanceof Ze){const e=qe(c.left),t=qe(c.right),n=[...e.transitions,...t.transitions,{from:e.acceptState,to:t.startState,label:null}];return{states:[...e.states,...t.states],transitions:n,startState:e.startState,acceptState:t.acceptState}}if(c instanceof Ot){const e=Ae(),t=Ae(),n=qe(c.left),r=qe(c.right),s=[...n.transitions,...r.transitions,{from:e.id,to:n.startState,label:null},{from:e.id,to:r.startState,label:null},{from:n.acceptState,to:t.id,label:null},{from:r.acceptState,to:t.id,label:null}];return{states:[e,t,...n.states,...r.states],transitions:s,startState:e.id,acceptState:t.id}}if(c instanceof Ct){const e=Ae(),t=Ae(),n=qe(c.inner),r=[...n.transitions,{from:e.id,to:n.startState,label:null},{from:e.id,to:t.id,label:null},{from:n.acceptState,to:n.startState,label:null},{from:n.acceptState,to:t.id,label:null}];return{states:[e,t,...n.states],transitions:r,startState:e.id,acceptState:t.id}}if(c instanceof Tt){if(c.minCount===0&&c.maxCount===0){const t=Ae();return{states:[t],transitions:[],startState:t.id,acceptState:t.id}}let e=null;for(let t=0;t<c.minCount;t++){const n=qe(new Te(c.name));if(e===null)e=n;else{const r=[...e.transitions,...n.transitions,{from:e.acceptState,to:n.startState,label:null}];e={states:[...e.states,...n.states],transitions:r,startState:e.startState,acceptState:n.acceptState}}}for(let t=c.minCount;t<c.maxCount;t++){const n=qe(new Te(c.name));if(e===null){const r=Ae(),s=Ae(),o=[...n.transitions,{from:r.id,to:n.startState,label:null},{from:r.id,to:s.id,label:null},{from:n.acceptState,to:s.id,label:null}];e={states:[r,s,...n.states],transitions:o,startState:r.id,acceptState:s.id}}else{const r=Ae(),s=[...e.transitions,...n.transitions,{from:e.acceptState,to:n.startState,label:null},{from:e.acceptState,to:r.id,label:null},{from:n.acceptState,to:r.id,label:null}];e={states:[...e.states,r,...n.states],transitions:s,startState:e.startState,acceptState:r.id}}}if(e===null){const t=Ae();return{states:[t],transitions:[],startState:t.id,acceptState:t.id}}return e}throw new Error(`Unsupported RPQ expression type: ${String(c)}`)}class Vr extends q{constructor(t,n,r,s){super();b(this,"pathExpr");b(this,"graph");b(this,"startVertex");b(this,"score");this.pathExpr=t,this.graph=n,this.startVertex=r??null,this.score=s??1}execute(t){const n=t.graphStore,r=this._tryIndexLookup(t,n);if(r!==null)return r;jr();const s=qe(this.pathExpr),o=Pr(s),i=[],a=new Map,l=new Set,u=[];if(this.startVertex!==null)u.push(this.startVertex);else{const d=n.vertexIdsInGraph(this.graph);for(const p of d)u.push(p)}let h=0;for(const d of u){const p=this._simulateDfa(n,o,d);for(const[m,_]of p){const y=`${String(d)}-${String(m)}`;if(l.has(y))continue;l.add(y);const x=h++;i.push(he(x,{score:this.score,fields:{start:d,end:m}})),a.set(x,ne({subgraphVertices:new Set([d,m]),subgraphEdges:_,score:this.score,graphName:this.graph}))}}const f=new W(i);for(const[d,p]of a)f.setGraphPayload(d,p);return f}_simulateDfa(t,n,r){const s=[],o=[[r,n.startState,new Set]],i=new Set;for(i.add(`${String(r)}:${n.startState}`),n.acceptStates.has(n.startState)&&s.push([r,new Set]);o.length>0;){const[a,l,u]=o.shift(),h=n.transitions.get(l);if(h)for(const[f,d]of h){const p=t.outEdgeIds(a,this.graph);for(const m of p){const _=t.getEdge(m);if(!_||_.label!==f)continue;const y=_.targetId,x=`${String(y)}:${d}`;if(i.has(x))continue;i.add(x);const v=new Set(u);v.add(m),n.acceptStates.has(d)&&s.push([y,v]),o.push([y,d,v])}}}return s}_tryIndexLookup(t,n){const r=t.pathIndex;if(!r||!r.hasPath||!r.lookup)return null;const s=this._extractLabelSequence(this.pathExpr);if(s===null||!r.hasPath(s,this.graph))return null;const o=r.lookup(s,this.graph),i=[];let a=0;for(const[l,u]of o)this.startVertex!==null&&l!==this.startVertex||(i.push(he(a,{score:this.score,fields:{start:l,end:u}})),a++);return new W(i)}_extractLabelSequence(t){if(t instanceof Te)return[t.name];if(t instanceof Ze){const n=this._extractLabelSequence(t.left),r=this._extractLabelSequence(t.right);if(n!==null&&r!==null)return[...n,...r]}return null}}class $r extends q{constructor(t,n,r){super();b(this,"source");b(this,"propertyName");b(this,"aggFn");this.source=t,this.propertyName=n,this.aggFn=r??(s=>{if(s.length===0)return 0;let o=0;for(let i=0;i<s.length;i++)o+=s[i];return o/s.length})}execute(t){const n=t.graphStore,r=this.source.execute(t),s=[];for(const a of r){const l=n.getVertex(a.docId);if(l){const u=l.properties[this.propertyName];typeof u=="number"&&s.push(u)}}const o=this.aggFn(s),i=[];for(const a of r)i.push({docId:a.docId,payload:U({positions:a.payload.positions,score:o,fields:{...a.payload.fields,_aggregated:o,_property:this.propertyName}})});return new D(i)}}class $o extends q{constructor(t,n,r){super();b(this,"pathExpr");b(this,"graph");b(this,"startVertex");b(this,"weightProperty");b(this,"aggregation");b(this,"weightThreshold");b(this,"score");this.pathExpr=t,this.graph=n,this.startVertex=(r==null?void 0:r.startVertex)??null,this.weightProperty=(r==null?void 0:r.weightProperty)??"weight",this.aggregation=(r==null?void 0:r.aggregation)??"sum",this.weightThreshold=(r==null?void 0:r.weightThreshold)??null,this.score=(r==null?void 0:r.score)??1}execute(t){const n=t.graphStore;jr();const r=qe(this.pathExpr),s=Pr(r),o=[],i=new Map,a=new Set,l=[];if(this.startVertex!==null)l.push(this.startVertex);else{const f=n.vertexIdsInGraph(this.graph);for(const d of f)l.push(d)}let u=0;for(const f of l){const d=this._simulateWeightedDfa(n,s,f);for(const[p,m,_]of d){if(this.weightThreshold!==null&&_<this.weightThreshold)continue;const y=`${String(f)}-${String(p)}`;if(a.has(y))continue;a.add(y);const x=u++;o.push(he(x,{score:_*this.score,fields:{start:f,end:p,weight:_,path_length:m.size}})),i.set(x,ne({subgraphVertices:new Set([f,p]),subgraphEdges:m,score:_*this.score,graphName:this.graph}))}}const h=new W(o);for(const[f,d]of i)h.setGraphPayload(f,d);return h}_simulateWeightedDfa(t,n,r){const s=[],o=this.aggregation==="product"?1:0,i=[[r,n.startState,new Set,o]],a=new Set;for(a.add(`${String(r)}:${n.startState}`),n.acceptStates.has(n.startState)&&s.push([r,new Set,o]);i.length>0;){const[l,u,h,f]=i.shift(),d=n.transitions.get(u);if(d)for(const[p,m]of d){const _=t.outEdgeIds(l,this.graph);for(const y of _){const x=t.getEdge(y);if(!x||x.label!==p)continue;const v=x.targetId,E=`${String(v)}:${m}`;if(a.has(E))continue;a.add(E);const I=new Set(h);I.add(y);const S=typeof x.properties[this.weightProperty]=="number"?x.properties[this.weightProperty]:1;let N;switch(this.aggregation){case"sum":N=f+S;break;case"min":N=h.size===0?S:Math.min(f,S);break;case"max":N=Math.max(f,S);break;case"product":N=f*S;break}n.acceptStates.has(m)&&s.push([v,I,N]),i.push([v,m,I,N])}}}return s}}class Pn extends q{constructor(t){super();b(this,"startVertex");b(this,"graph");b(this,"temporalFilter");b(this,"label");b(this,"maxHops");b(this,"vertexPredicate");b(this,"score");this.startVertex=t.startVertex,this.graph=t.graph,this.temporalFilter=t.temporalFilter,this.label=t.label??null,this.maxHops=t.maxHops??1/0,this.vertexPredicate=t.vertexPredicate??null,this.score=t.score??1}execute(t){const n=t.graphStore,r=new Set,s=[],o=new Set,i=new Set,a=[[this.startVertex,0]];for(r.add(this.startVertex);a.length>0;){const[u,h]=a.shift(),f=n.getVertex(u);if(!f||this.vertexPredicate&&!this.vertexPredicate(f))continue;o.add(u);const d=this.score/(1+h);if(s.push(he(u,{score:d,fields:{...f.properties,_depth:h}})),h<this.maxHops){const p=n.outEdgeIds(u,this.graph);for(const m of p){const _=n.getEdge(m);_&&(this.label!==null&&_.label!==this.label||this.temporalFilter.isValid(_)&&(i.add(m),r.has(_.targetId)||(r.add(_.targetId),a.push([_.targetId,h+1]))))}}}const l=new W(s);for(const u of s)l.setGraphPayload(u.docId,ne({subgraphVertices:o,subgraphEdges:i,score:u.payload.score,graphName:this.graph}));return l}}class Zt{constructor(e){b(this,"timestamp");b(this,"timeRange");const t=(e==null?void 0:e.timestamp)??null,n=(e==null?void 0:e.timeRange)??null;if(t!==null&&n!==null)throw new Error("TemporalFilter: timestamp and timeRange are mutually exclusive");this.timestamp=t,this.timeRange=n}isValid(e){const t=e.properties.valid_from,n=e.properties.valid_to;if(typeof t=="number"||typeof n=="number")return this._isValidRange(typeof t=="number"?t:null,typeof n=="number"?n:null);const s=e.properties.timestamp;if(typeof s!="number")return!0;if(this.timestamp!==null)return s<=this.timestamp;if(this.timeRange!==null){const[o,i]=this.timeRange;return s>=o&&s<=i}return!0}_isValidRange(e,t){if(this.timestamp!==null)return!(e!==null&&this.timestamp<e||t!==null&&this.timestamp>t);if(this.timeRange!==null){const[n,r]=this.timeRange;return!(e!==null&&e>r||t!==null&&t<n)}return!0}}class qr extends q{constructor(t){super();b(this,"damping");b(this,"maxIterations");b(this,"tolerance");b(this,"graph");this.damping=t.damping??.85,this.maxIterations=t.maxIterations??100,this.tolerance=t.tolerance??1e-6,this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let f=0;f<r.length;f++)o.set(r[f],f);let i=new Float64Array(s);i.fill(1/s);const a=new Float64Array(s);for(let f=0;f<s;f++){const d=r[f],p=n.outEdgeIds(d,this.graph);a[f]=p.size}for(let f=0;f<this.maxIterations;f++){const d=new Float64Array(s);d.fill((1-this.damping)/s);for(let m=0;m<s;m++){const _=r[m];if(a[m]===0){const y=i[m]/s;for(let x=0;x<s;x++)d[x]=d[x]+this.damping*y}else{const y=i[m]/a[m],x=n.neighbors(_,this.graph,null,"out");for(const v of x){const E=o.get(v);E!==void 0&&(d[E]=d[E]+this.damping*y)}}}let p=0;for(let m=0;m<s;m++)p+=Math.abs(d[m]-i[m]);if(i=d,p<this.tolerance)break}const l=[];for(let f=0;f<s;f++){const d=r[f];l.push(he(d,{score:i[f],fields:{pagerank:i[f]}}))}const u=new Set(r),h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}class zr extends q{constructor(t){super();b(this,"maxIterations");b(this,"tolerance");b(this,"graph");this.maxIterations=t.maxIterations??100,this.tolerance=t.tolerance??1e-6,this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let f=0;f<r.length;f++)o.set(r[f],f);let i=new Float64Array(s),a=new Float64Array(s);i.fill(1),a.fill(1);for(let f=0;f<this.maxIterations;f++){const d=new Float64Array(s),p=new Float64Array(s);for(let x=0;x<s;x++){const v=r[x],E=n.neighbors(v,this.graph,null,"in");let I=0;for(const S of E){const N=o.get(S);N!==void 0&&(I+=i[N])}d[x]=I}for(let x=0;x<s;x++){const v=r[x],E=n.neighbors(v,this.graph,null,"out");let I=0;for(const S of E){const N=o.get(S);N!==void 0&&(I+=d[N])}p[x]=I}let m=0,_=0;for(let x=0;x<s;x++)m+=d[x]*d[x],_+=p[x]*p[x];if(m=Math.sqrt(m),_=Math.sqrt(_),m>0)for(let x=0;x<s;x++)d[x]=d[x]/m;if(_>0)for(let x=0;x<s;x++)p[x]=p[x]/_;let y=0;for(let x=0;x<s;x++)y+=Math.abs(d[x]-a[x]),y+=Math.abs(p[x]-i[x]);if(a=d,i=p,y<this.tolerance)break}const l=[];for(let f=0;f<s;f++){const d=r[f],p=a[f]+i[f];l.push(he(d,{score:p,fields:{authority:a[f],hub:i[f]}}))}const u=new Set(r),h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}class Gr extends q{constructor(t){super();b(this,"graph");this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let h=0;h<r.length;h++)o.set(r[h],h);const i=new Float64Array(s);for(let h=0;h<s;h++){const f=[],d=new Array(s);for(let v=0;v<s;v++)d[v]=new Set;const p=new Float64Array(s);p[h]=1;const m=new Float64Array(s);m.fill(-1),m[h]=0;const _=[h];let y=0;for(;y<_.length;){const v=_[y];y++,f.push(v);const E=r[v],I=n.neighbors(E,this.graph,null,"out"),S=n.neighbors(E,this.graph,null,"in"),N=new Set([...I,...S]);for(const A of N){const O=o.get(A);O!==void 0&&(m[O]<0&&(_.push(O),m[O]=m[v]+1),m[O]===m[v]+1&&(p[O]=p[O]+p[v],d[O].add(v)))}}const x=new Float64Array(s);for(;f.length>0;){const v=f.pop();for(const E of d[v])x[E]=x[E]+p[E]/p[v]*(1+x[v]);v!==h&&(i[v]=i[v]+x[v])}}for(let h=0;h<s;h++)i[h]=i[h]/2;const a=[];for(let h=0;h<s;h++){const f=r[h];a.push(he(f,{score:i[h],fields:{betweenness:i[h]}}))}const l=new Set(r),u=new W(a);for(const h of a)u.setGraphPayload(h.docId,ne({subgraphVertices:l,subgraphEdges:new Set,score:h.payload.score,graphName:this.graph}));return u}}class Dn extends q{constructor(t){super();b(this,"kLayers");b(this,"aggregation");b(this,"propertyName");b(this,"graph");this.kLayers=t.kLayers??2,this.aggregation=t.aggregation??"mean",this.propertyName=t.propertyName??"feature",this.graph=t.graph}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const o=new Map;for(let h=0;h<r.length;h++)o.set(r[h],h);let i=new Float64Array(s);for(let h=0;h<s;h++){const f=r[h],d=n.getVertex(f);if(d){const p=d.properties[this.propertyName];typeof p=="number"?i[h]=p:i[h]=0}}for(let h=0;h<this.kLayers;h++){const f=new Float64Array(s);for(let d=0;d<s;d++){const p=r[d],m=n.neighbors(p,this.graph,null,"out"),_=n.neighbors(p,this.graph,null,"in"),y=new Set([...m,..._]),x=[];for(const E of y){const I=o.get(E);I!==void 0&&x.push(i[I])}let v;if(x.length===0)v=i[d];else if(this.aggregation==="mean"){let E=0;for(const I of x)E+=I;v=E/x.length}else if(this.aggregation==="sum"){let E=0;for(const I of x)E+=I;v=E}else{let E=x[0];for(let I=1;I<x.length;I++)x[I]>E&&(E=x[I]);v=E}f[d]=v+i[d]}i=f}for(let h=0;h<s;h++)i[h]=1/(1+Math.exp(-i[h]));const a=[];for(let h=0;h<s;h++){const f=r[h];a.push(he(f,{score:i[h],fields:{_mp_score:i[h]}}))}const l=new Set(r),u=new W(a);for(const h of a)u.setGraphPayload(h.docId,ne({subgraphVertices:l,subgraphEdges:new Set,score:h.payload.score,graphName:this.graph}));return u}}class Br extends q{constructor(t){super();b(this,"graph");b(this,"kHops");this.graph=t.graph,this.kHops=t.kHops??2}execute(t){const n=t.graphStore,r=[...n.vertexIdsInGraph(this.graph)],s=r.length;if(s===0)return new W;const i=[...n.vertexLabelCounts(this.graph).keys()].sort(),a=new Map;for(let f=0;f<i.length;f++)a.set(i[f],f);const l=[],u=new Set(r);for(const f of r){const d=n.getVertex(f);if(!d)continue;const p=n.outEdgeIds(f,this.graph),m=n.inEdgeIds(f,this.graph),_=p.size,y=m.size,x=_+y,v=s>1?x/(2*(s-1)):0,E=new Float64Array(i.length),I=new Set;for(const C of n.neighbors(f,this.graph,null,"out"))I.add(C);for(const C of n.neighbors(f,this.graph,null,"in"))I.add(C);if(I.size>0){for(const C of I){const V=n.getVertex(C);if(V){const Y=a.get(V.label);Y!==void 0&&(E[Y]=E[Y]+1)}}for(let C=0;C<E.length;C++)E[C]=E[C]/I.size}const S=new Float64Array(this.kHops),N=new Set([f]);let A=new Set([f]);for(let C=0;C<this.kHops;C++){const V=new Set;for(const Y of A){for(const oe of n.neighbors(Y,this.graph,null,"out"))N.has(oe)||(N.add(oe),V.add(oe));for(const oe of n.neighbors(Y,this.graph,null,"in"))N.has(oe)||(N.add(oe),V.add(oe))}S[C]=s>1?V.size/(s-1):0,A=V}const O=1+i.length+this.kHops,R=new Float64Array(O);R[0]=v;for(let C=0;C<E.length;C++)R[1+C]=E[C];for(let C=0;C<S.length;C++)R[1+i.length+C]=S[C];let T=0;for(let C=0;C<O;C++)T+=R[C]*R[C];const F=Math.sqrt(T);l.push(he(f,{score:F,fields:{embedding:R,out_degree:_,in_degree:y,label:d.label}}))}const h=new W(l);for(const f of l)h.setGraphPayload(f.docId,ne({subgraphVertices:u,subgraphEdges:new Set,score:f.payload.score,graphName:this.graph}));return h}}function qo(c){if(c>=0)return 1/(1+Math.exp(-c));const e=Math.exp(c);return e/(1+e)}function Ur(c){return c<=0?-10:c>=1?10:Math.log(c/(1-c))}class zo{constructor(e,t,n){b(this,"_bm25");b(this,"_transform");b(this,"_priorFn");this._bm25=new xt(e.bm25,t),this._transform=new K.BayesianProbabilityTransform(e.alpha,e.beta,e.baseRate===.5?null:e.baseRate),this._priorFn=n}scoreWithPrior(e,t,n,r){const s=this._bm25.idf(n),o=this._bm25.scoreWithIdf(e,t,s),i=this._bm25.params.k1>0?t:1,a=i>0?t/i:1,l=this._transform.scoreToProbability(o,e,a);let u=this._priorFn(r);u=Math.max(1e-10,Math.min(1-1e-10,u));const h=Ur(l)+Ur(u);return qo(h)}}function Go(c,e=30){return t=>{const n=t[c];if(n==null)return .5;let r;if(n instanceof Date)r=n;else if(typeof n=="string"){if(r=new Date(n),isNaN(r.getTime()))return .5}else return .5;const s=(Date.now()-r.getTime())/864e5;return .5+.4*Math.exp(-s/e)}}function Bo(c,e){const t=e??{high:.8,medium:.6,low:.4};return n=>{const r=n[c];if(r==null)return .5;const s=typeof r=="string"?r:String(r);return t[s]??.5}}function Uo(c,e,t=42,n="kaiming",r=null,s=null,o=0,i=0){if(n==="orthogonal")return Mo(c,e,t);if(n==="gabor")return Oo(c,e,t);if(n==="kmeans"){if(r===null||s===null)throw new Error("kmeans init requires training_data");return Co(c,e,r,s,o,i,t)}let a=t;function l(){a^=a<<13,a^=a>>17,a^=a<<5;const d=(a>>>0)/4294967295;a^=a<<13,a^=a>>17,a^=a<<5;const p=(a>>>0)/4294967295;return Math.sqrt(-2*Math.log(Math.max(1e-10,d)))*Math.cos(2*Math.PI*p)}const u=e*9,h=Math.sqrt(2/u),f=new Float64Array(c*e*9);for(let d=0;d<f.length;d++)f[d]=l()*h;return f}class Wr{constructor(e,t=6,n=.5,r=!1,s){b(this,"_attn");this._attn=new K.AttentionLogOddsWeights(e,t,n,r,0,s??null)}get nSignals(){return this._attn.nSignals}get nQueryFeatures(){return this._attn.nQueryFeatures}fuse(e,t){const n=this._attn.weightsMatrix,r=e.length,s=t.length,o=[];for(let l=0;l<r;l++){let u=0;const h=n[l];if(h)for(let f=0;f<s;f++)u+=(h[f]??0)*(t[f]??0);o.push(u)}let i=-1/0;for(const l of o)l>i&&(i=l);let a=0;for(let l=0;l<o.length;l++)o[l]=Math.exp(o[l]-i),a+=o[l];for(let l=0;l<o.length;l++)o[l]=o[l]/a;return K.logOddsConjunction(e,this._attn.alpha,o)}fit(e,t,n){this._attn.fit(e,t,n)}update(e,t,n){this._attn.update(e,t,n)}stateDict(){return{weights_matrix:this._attn.weightsMatrix,alpha:this._attn.alpha,n_signals:this._attn.nSignals,n_query_features:this._attn.nQueryFeatures}}loadStateDict(e){this._attn=new K.AttentionLogOddsWeights(e.n_signals,e.n_query_features,e.alpha);const t=e.weights_matrix;if(t!=null){const n=t;for(let r=0;r<n.length;r++)for(let s=0;s<n[r].length;s++)this._attn.weightsMatrix[r][s]=n[r][s]}}}class Wo{constructor(e,t=4,n=6,r=.5,s=!1){b(this,"_mh");b(this,"_nQueryFeatures");this._mh=new K.MultiHeadAttentionLogOddsWeights(t,e,n,r,s),this._nQueryFeatures=n}get nSignals(){var e;return((e=this._mh.heads[0])==null?void 0:e.nSignals)??0}get nQueryFeatures(){return this._nQueryFeatures}fuse(e,t){return this._mh.combine(e,t,!1)}fit(e,t,n){this._mh.fit(e,t,n)}stateDict(){var e;return{n_heads:this._mh.nHeads,n_signals:this.nSignals,n_query_features:this._nQueryFeatures,alpha:((e=this._mh.heads[0])==null?void 0:e.alpha)??.5}}loadStateDict(e){this._mh=new K.MultiHeadAttentionLogOddsWeights(e.n_heads,e.n_signals,e.n_query_features,e.alpha),this._nQueryFeatures=e.n_query_features}}class Hr{constructor(e,t=.5){b(this,"_learnable");this._learnable=new K.LearnableLogOddsWeights(e,t)}get nSignals(){return this._learnable.nSignals}fuse(e){const t=[...this._learnable.weights];return K.logOddsConjunction(e,this._learnable.alpha,t)}update(e,t,n){const r=e.map(o=>{const i=Math.max(1e-10,Math.min(.9999999999,o));return Math.log(i/(1-i))}),s=t-this.fuse(e);this._learnable.update(r,s,n)}stateDict(){return{weights:[...this._learnable.weights],alpha:this._learnable.alpha,n_signals:this._learnable.nSignals}}loadStateDict(e){this._learnable=new K.LearnableLogOddsWeights(e.n_signals,e.alpha);const t=e.weights;for(let n=0;n<t.length;n++)this._learnable.weights[n]=t[n]}}class Ho{constructor(e){b(this,"_index");this._index=e}get nFeatures(){return 6}extract(e,t){const n=this._index.stats,r=n.totalDocs;if(r===0)return new Float64Array(6);const s=t??"_default",o=[];let i=0;for(const m of e){const _=n.docFreq(s,m);if(_>0){i++;const y=Math.log((r-_+.5)/(_+.5)+1);o.push(y)}}if(o.length===0)return new Float64Array([0,0,0,0,e.length,0]);let a=0,l=-1/0,u=1/0;for(const m of o)a+=m,m>l&&(l=m),m<u&&(u=m);const h=a/o.length,f=o.length/Math.max(1,r),d=e.length,p=i/Math.max(1,e.length);return new Float64Array([h,l,u,f,d,p])}}class ze{constructor(e,t){b(this,"_columnStats");b(this,"_graphStats");b(this,"_graphStore");e instanceof Map?(this._columnStats=e,this._graphStats=(t==null?void 0:t.graphStats)??null,this._graphStore=(t==null?void 0:t.graphStore)??null):e!=null&&!(e instanceof Map)?(this._columnStats=e.columnStats??new Map,this._graphStats=e.graphStats??(t==null?void 0:t.graphStats)??null,this._graphStore=e.graphStore??(t==null?void 0:t.graphStore)??null):(this._columnStats=new Map,this._graphStats=(t==null?void 0:t.graphStats)??null,this._graphStore=(t==null?void 0:t.graphStore)??null)}estimate(e,t){const n=t.totalDocs>0?t.totalDocs:1;if(e instanceof _e){const r=e.field??"_default";return t.docFreq(r,e.term)}if(e instanceof Ee)return n*ze._vectorSelectivity(e.threshold);if(e instanceof je)return e.k;if(e instanceof G)return n*this._filterSelectivity(e.field,e.predicate,n);if(e instanceof pe)return this.estimate(e.source,t);if(e instanceof H){const r=e.operands.map(i=>this.estimate(i,t)).sort((i,a)=>i-a);if(r.length===0)return 0;const s=this._intersectionDamping(e.operands);let o=r[0];for(let i=1;i<r.length;i++){const a=n>0?r[i]/n:1;o*=a**s}if(this._columnStats.size>0){const i=[];for(const a of e.operands)if(a instanceof G&&a.field){const l=this._columnStats.get(a.field);l!==void 0&&i.push(en(l))}if(i.length>0){const a=Jo(n,i);o=Math.max(o,a)}}return Math.max(1,o)}if(e instanceof re){const r=e.operands.map(s=>this.estimate(s,t));return Math.min(n,r.reduce((s,o)=>s+o,0))}if(e instanceof de){const r=this.estimate(e.operand,t);return Math.max(0,n-r)}if(e instanceof Ne)return this.estimate(e.source,t)*.5;if(e instanceof $e){if(e.stages.length===0)return 0;const[,r]=e.stages[e.stages.length-1];return typeof r=="number"?r:n*.5}return Math.max(1,Math.floor(e.costEstimate(t)))}_intersectionDamping(e){const t=[];for(const n of e)n instanceof G&&t.push(n.field);if(t.length<2)return .5;if(new Set(t).size===1)return .1;if(this._columnStats.size>0&&t.length>=2){const n=this._columnStats.get(t[0]),r=this._columnStats.get(t[1]);if(n!==void 0&&r!==void 0){const s=Ko(n,r,.1);if(s>1)return .2;if(s>.5)return .3}}return .5}static _vectorSelectivity(e){return e>=.9?.01:e>=.7?.05:e>=.5?.1:.2}estimateJoinSide(e,t,n){return e instanceof q?this.estimate(e,t):(e!=null&&typeof e.execute=="function",n)}sampleGraphCardinality(e,t=100){if(this._graphStats===null)return-1;const n=this._graphStats.numVertices;if(n<=0)return 0;const r=e.vertexPatterns??[],s=e.edgePatterns??[],o=r.length;if(o===0)return 0;const i=this._graphStats.numEdges,a=i>0&&n>0?i/(n*n):.01;let l=1;for(const h of s)h.label!==null&&(l*=this._graphStats.labelSelectivity(h.label));const u=Math.pow(n,o)*Math.pow(a,s.length)*l;return Math.max(1,Math.floor(u))}estimateJoin(e,t,n){return n<=0?0:e*t/n}_filterSelectivity(e,t,n){var l;const r=this._columnStats.get(e);if(r===void 0||r.distinctCount<=0)return .5;const s=r.distinctCount;let o;const i=t,a=((l=i.constructor)==null?void 0:l.name)??"";if(a==="Equals"||i.type==="equals"?o=ze._equalitySelectivity(r,i.target,s):a==="NotEquals"||i.type==="not_equals"?o=1-ze._equalitySelectivity(r,i.target,s):a==="InSet"||i.type==="in_set"?o=Math.min(1,(i.values??[]).reduce((u,h)=>u+ze._equalitySelectivity(r,h,s),0)):a==="Between"||i.type==="between"?o=this._rangeSelectivity(r,i.low,i.high):a==="GreaterThan"||a==="GreaterThanOrEqual"||i.type==="gt"||i.type==="gte"?o=this._gtSelectivity(r,i.target):a==="LessThan"||a==="LessThanOrEqual"||i.type==="lt"||i.type==="lte"?o=this._ltSelectivity(r,i.target):o=.5,r.distinctCount>1){const u=en(r);if(u>0){const h=1/2**u;o=Math.max(h,o)}}return o}static _equalitySelectivity(e,t,n){if(e.mcvValues.length>0){for(let r=0;r<e.mcvValues.length;r++)if(e.mcvValues[r]===t)return e.mcvFrequencies[r]}return n>0?1/n:1}static histogramFraction(e,t,n){if(e.length<2)return .5;const r=e.length-1;let s=0;for(let o=0;o<r;o++){const i=e[o],a=e[o+1];try{if(n<i||t>a)continue;if(t<=i&&n>=a)s+=1;else{const l=a-i;if(l<=0){s+=1;continue}const u=Math.max(t,i),h=Math.min(n,a);s+=(h-u)/l}}catch{s+=1}}return Math.max(0,Math.min(1,s/r))}_rangeSelectivity(e,t,n){if(e.histogram.length>0)return ze.histogramFraction(e.histogram,t,n);if(e.minValue!=null&&e.maxValue!=null)try{const r=e.maxValue-e.minValue;if(r>0)return Math.max(0,Math.min(1,(n-t)/r))}catch{}return .25}_gtSelectivity(e,t){if(e.histogram.length>0)return ze.histogramFraction(e.histogram,t,e.histogram[e.histogram.length-1]);if(e.minValue!=null&&e.maxValue!=null)try{const n=e.maxValue-e.minValue;if(n>0)return Math.max(0,(e.maxValue-t)/n)}catch{}return 1/3}_ltSelectivity(e,t){if(e.histogram.length>0)return ze.histogramFraction(e.histogram,e.histogram[0],t);if(e.minValue!=null&&e.maxValue!=null)try{const n=e.maxValue-e.minValue;if(n>0)return Math.max(0,(t-e.minValue)/n)}catch{}return 1/3}estimateGraphPattern(e,t){if(this._graphStats===null)return 1;const n=this._graphStats,r=n.numVertices>0?n.numVertices:1,s=Math.max(1,Math.ceil(e/2)),o=Math.max(0,e-s),i=r>1?n.numEdges/(r*r):0;let a=1;if(t!==void 0&&n.numEdges>0)for(const h of t){const f=n.labelCounts.get(h)??0;a*=f/n.numEdges}let l=1;if(n.vertexLabelCounts.size>0&&r>0){let h=0;for(const d of n.vertexLabelCounts.values())h+=d;const f=h/(n.vertexLabelCounts.size*r);l=Math.pow(Math.min(1,f),s)}const u=Math.pow(r,s)*Math.pow(i,o)*a*l;return Math.max(1,Math.min(r,Math.floor(u)))}estimatePathQuery(e,t){if(this._graphStats===null)return 1;const n=this._graphStats,r=n.numVertices>0?n.numVertices:1;let s=n.avgOutDegree;if(t!==void 0&&n.numEdges>0){const a=(n.labelCounts.get(t)??0)/n.numEdges;s*=a}const o=r*Math.pow(s,e);return Math.max(1,Math.min(Math.floor(o),n.numEdges))}estimateTraverse(e,t=null){if(this._graphStats!==null){const r=this._graphStats;let s;if(t&&r.labelDegreeMap.size>0)s=r.labelDegreeMap.get(t)??r.avgOutDegree*r.labelSelectivity(t);else{const i=r.labelSelectivity(t);s=r.avgOutDegree*i}const o=r.numVertices>0?r.numVertices:1;return Math.min(o,s**e)}const n=1e3;return Math.min(n,Math.min(n*.1,10)**e)}estimatePatternMatch(e,t,n=[]){if(this._graphStats!==null){const r=this._graphStats,s=r.numVertices>0?r.numVertices:1,o=r.edgeDensity();let i=1;for(const l of n)i*=r.labelSelectivity(l);const a=s**e*o**t*i;return Math.max(1,Math.min(s,a))}return 1}estimateCrossParadigm(e,t,n){const r=t.totalDocs>0?t.totalDocs:1;switch(n){case"text_graph":{const s=this.estimate(e,t),o=this._graphStats!==null?Math.min(1,this._graphStats.avgOutDegree/Math.max(1,this._graphStats.numVertices)):.1;return Math.max(1,Math.floor(s*o))}case"text_vector":{const s=this.estimate(e,t);return Math.max(1,Math.floor(s*.3))}case"graph_vector":{const s=this._graphStats!==null?Math.min(r,this._graphStats.avgOutDegree**2):r*.1;return Math.max(1,Math.floor(s*.2))}case"text_graph_vector":{const s=this.estimate(e,t),o=this._graphStats!==null?Math.min(1,this._graphStats.avgOutDegree/Math.max(1,this._graphStats.numVertices)):.1;return Math.max(1,Math.floor(s*o*.3))}case"log_odds_fusion":return Math.max(1,Math.floor(r*.15));case"prob_bool_fusion":return Math.max(1,Math.floor(r*.25));case"attention_fusion":return Math.max(1,Math.floor(r*.2));case"learned_fusion":return Math.max(1,Math.floor(r*.2));default:return Math.max(1,Math.floor(r*.5))}}estimateTemporalPattern(e,t,n,r,s){const o=this.estimatePatternMatch(e,t,n);if(this._graphStats===null)return o;const i=this._graphStats;let a=1;if(r!==null&&s!==null&&i.minTimestamp!==null&&i.maxTimestamp!==null){const l=i.maxTimestamp-i.minTimestamp;if(l>0){const u=Math.min(s,i.maxTimestamp)-Math.max(r,i.minTimestamp);a=Math.max(0,Math.min(1,u/l))}}else(r!==null||s!==null)&&(a=.5);return Math.max(1,Math.floor(o*a))}estimateTemporalTraverse(e,t,n,r){const s=this.estimateTraverse(e,t);if(this._graphStats===null)return s;const o=this._graphStats;let i=1;if(n!==null&&r!==null&&o.minTimestamp!==null&&o.maxTimestamp!==null){const a=o.maxTimestamp-o.minTimestamp;if(a>0){const l=Math.min(r,o.maxTimestamp)-Math.max(n,o.minTimestamp);i=Math.max(0,Math.min(1,l/a))}}return Math.max(1,Math.floor(s*Math.pow(i,e)))}estimateWeightedRPQ(e,t,n){const r=this.estimatePathQuery(e,t.length>0?t[0]:void 0);let s=1;if(n!==null&&(s=Math.pow(1-n,e)),t.length>1&&this._graphStats!==null){const o=this._graphStats;let i=1;for(const a of t)i*=o.labelSelectivity(a);return Math.max(1,Math.floor(r*s*i))}return Math.max(1,Math.floor(r*s))}estimateBoundedRPQ(e,t,n){if(this._graphStats===null)return 1;const r=this._graphStats,s=r.numVertices>0?r.numVertices:1;let o=r.avgOutDegree;n!==null&&r.numEdges>0&&(o*=r.labelSelectivity(n));let i=0;for(let l=e;l<=t;l++)i+=s*Math.pow(o,l);const a=i/(t-e+1);return Math.max(1,Math.min(Math.floor(a),r.numEdges))}}function en(c){const e=c.distinctCount;if(e<=1)return 0;const t=c.mcvFrequencies;if(t.length>0){let r=0,s=1;for(const i of t)s-=i,i>0&&(r-=i*Math.log2(i));const o=Math.max(1,e-t.length);if(s>0&&o>0){const i=s/o;r-=s*Math.log2(i)}return Math.max(0,r)}const n=c.histogram;if(n.length>1){const r=n.length-1,s=1/r;return-r*s*Math.log2(s)}return Math.log2(e)}function Ko(c,e,t){const n=en(c),r=en(e),s=Math.max(1,c.distinctCount),o=Math.max(1,e.distinctCount),i=s*o,a=Math.max(1,i*t),l=Math.log2(Math.max(1,a));return Math.max(0,n+r-l)}function Jo(c,e){if(e.length===0||c<=0)return 1;const t=e.reduce((r,s)=>r+s,0),n=c*2**-t;return Math.max(1,n)}class Rt{}class Yo extends Rt{identity(){return 0}accumulate(e,t){return e+1}combine(e,t){return e+t}finalize(e){return e}}class Xo extends Rt{identity(){return 0}accumulate(e,t){return e+t}combine(e,t){return e+t}finalize(e){return e}}class Qo extends Rt{identity(){return[0,0]}accumulate(e,t){return[e[0]+t,e[1]+1]}combine(e,t){return[e[0]+t[0],e[1]+t[1]]}finalize(e){return e[1]===0?0:e[0]/e[1]}}class Zo extends Rt{identity(){return 1/0}accumulate(e,t){return Math.min(e,t)}combine(e,t){return Math.min(e,t)}finalize(e){return e}}class ei extends Rt{identity(){return-1/0}accumulate(e,t){return Math.max(e,t)}combine(e,t){return Math.max(e,t)}finalize(e){return e}}class ti extends q{constructor(t,n,r){super();b(this,"source");b(this,"field");b(this,"monoid");this.source=t,this.field=n,this.monoid=r}execute(t){const n=t.documentStore;let r;this.source?r=this.source.execute(t).entries.map(a=>a.docId):r=n?[...n.docIds].sort((a,l)=>a-l):[];let s=this.monoid.identity();for(const a of r){const l=n?n.getField(a,this.field):void 0;l!=null&&(s=this.monoid.accumulate(s,l))}const o=this.monoid.finalize(s),i=typeof o=="number"?o:0;return D.fromSorted([{docId:0,payload:U({score:i,fields:{_aggregate_field:this.field,_aggregate:o}})}])}costEstimate(t){return t.totalDocs}}class ni extends q{constructor(t,n,r,s){super();b(this,"source");b(this,"groupField");b(this,"aggField");b(this,"monoid");this.source=t,this.groupField=n,this.aggField=r,this.monoid=s}execute(t){const n=this.source.execute(t),r=t.documentStore;if(!r)return new D;const s=new Map;for(const a of n){const l=r.getField(a.docId,this.groupField);if(l==null)continue;const u=String(l);s.has(u)||s.set(u,this.monoid.identity());const h=r.getField(a.docId,this.aggField);h!=null&&s.set(u,this.monoid.accumulate(s.get(u),h))}const i=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0])).map(([a,l],u)=>{const h=this.monoid.finalize(l);return{docId:u,payload:U({score:typeof h=="number"?h:0,fields:{_group_key:a,_group_field:this.groupField,_aggregate_result:h}})}});return D.fromSorted(i)}}class ri extends q{constructor(t){super();b(this,"pattern");b(this,"graph");b(this,"temporalFilter");b(this,"score");this.pattern=t.pattern,this.graph=t.graph,this.temporalFilter=t.temporalFilter,this.score=t.score??1}execute(t){const n=t.graphStore,r=this._backtrackSearch(n);return this._buildPostingList(n,r)}_backtrackSearch(t){const n=this._computeCandidates(t),r=[],s=new Map,o=this.pattern.vertexPatterns.map(i=>i.variable);return this._backtrack(t,o,0,s,n,r),r}_computeCandidates(t){const n=new Map,r=t.vertexIdsInGraph(this.graph);for(const s of this.pattern.vertexPatterns){let o=new Set(r);if(s.constraints.length>0){const i=new Set;for(const a of o){const l=t.getVertex(a);if(l){let u=!0;for(const h of s.constraints)if(!h(l)){u=!1;break}u&&i.add(a)}}o=i}n.set(s.variable,o)}return n}_backtrack(t,n,r,s,o,i){if(r===n.length){this._validateAllEdges(t,s)&&i.push(new Map(s));return}const a=n[r],l=o.get(a)??new Set,u=new Set(s.values());for(const h of l)u.has(h)||(s.set(a,h),this._validateEdgesFor(t,s,a)&&this._backtrack(t,n,r+1,s,o,i),s.delete(a))}_validateEdgesFor(t,n,r){for(const s of this.pattern.edgePatterns){if(s.negated||s.sourceVar!==r&&s.targetVar!==r)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);let l=!1;for(const u of a){const h=t.getEdge(u);if(!h||h.targetId!==i||s.label!==null&&h.label!==s.label||!this.temporalFilter.isValid(h))continue;let f=!0;for(const d of s.constraints)if(!d(h)){f=!1;break}if(f){l=!0;break}}if(!l)return!1}return!0}_validateAllEdges(t,n){for(const r of this.pattern.edgePatterns){const s=n.get(r.sourceVar),o=n.get(r.targetVar);if(s===void 0||o===void 0)return!1;if(r.negated){const i=t.outEdgeIds(s,this.graph);for(const a of i){const l=t.getEdge(a);if(l&&l.targetId===o&&(r.label===null||l.label===r.label)&&this.temporalFilter.isValid(l))return!1}}else{const i=t.outEdgeIds(s,this.graph);let a=!1;for(const l of i){const u=t.getEdge(l);if(u&&u.targetId===o&&!(r.label!==null&&u.label!==r.label)&&this.temporalFilter.isValid(u)){a=!0;break}}if(!a)return!1}}return!0}_collectMatchEdges(t,n){const r=new Set;for(const s of this.pattern.edgePatterns){if(s.negated)continue;const o=n.get(s.sourceVar),i=n.get(s.targetVar);if(o===void 0||i===void 0)continue;const a=t.outEdgeIds(o,this.graph);for(const l of a){const u=t.getEdge(l);u&&u.targetId===i&&(s.label===null||u.label===s.label)&&this.temporalFilter.isValid(u)&&r.add(l)}}return r}_buildPostingList(t,n){const r=[],s=new Map;for(let i=0;i<n.length;i++){const a=n[i],l=new Set(a.values()),u=this._collectMatchEdges(t,a),h=i,f={};for(const[d,p]of a)f[d]=p;r.push(he(h,{score:this.score,fields:f})),s.set(h,ne({subgraphVertices:l,subgraphEdges:u,score:this.score,graphName:this.graph}))}const o=new W(r);for(const[i,a]of s)o.setGraphPayload(i,a);return o}}function Re(c,e){return c!==null&&typeof c=="object"&&"execute"in c&&typeof c.execute=="function"?[...c.execute(e).entries]:c}class si{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"leftField");b(this,"rightField");b(this,"threshold");this.left=e,this.right=t,this.leftField=n,this.rightField=r,this.threshold=s}execute(e){const t=Re(this.left,e),n=Re(this.right,e),r=[];for(const s of t){const o=s.payload.fields[this.leftField],i=typeof o=="string"?o:"",a=new Set(sr.analyze(i));if(a.size!==0)for(const l of n){const u=l.payload.fields[this.rightField],h=typeof u=="string"?u:"",f=new Set(sr.analyze(h));if(f.size===0)continue;let d=0;for(const _ of a)f.has(_)&&d++;const p=a.size+f.size-d,m=p>0?d/p:0;m>=this.threshold&&r.push({docIds:[s.docId,l.docId],payload:U({score:m,fields:{...s.payload.fields,...l.payload.fields}})})}}return new Se(r)}}class Kr{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"leftField");b(this,"rightField");b(this,"threshold");this.left=e,this.right=t,this.leftField=n,this.rightField=r,this.threshold=s}execute(e){const t=Re(this.left,e),n=Re(this.right,e),r=[];for(const s of t){const o=s.payload.fields[this.leftField];if(o)for(const i of n){const a=i.payload.fields[this.rightField];if(!a)continue;const l=lt(o,a);l>=this.threshold&&r.push({docIds:[s.docId,i.docId],payload:U({score:l,fields:{...s.payload.fields,...i.payload.fields}})})}}return new Se(r)}}class oi{constructor(e,t,n,r,s=.5){b(this,"left");b(this,"right");b(this,"structuredField");b(this,"vectorField");b(this,"threshold");this.left=e,this.right=t,this.structuredField=n,this.vectorField=r,this.threshold=s}execute(e){const t=Re(this.left,e),n=Re(this.right,e),r=new Map;for(const o of n){const i=o.payload.fields[this.structuredField];if(i==null)continue;let a=r.get(i);a||(a=[],r.set(i,a)),a.push(o)}const s=[];for(const o of t){const i=o.payload.fields[this.structuredField];if(i==null)continue;const a=o.payload.fields[this.vectorField];if(!a)continue;const l=r.get(i);if(l)for(const u of l){const h=u.payload.fields[this.vectorField];if(!h)continue;const f=lt(a,h);f>=this.threshold&&s.push({docIds:[o.docId,u.docId],payload:U({score:f,fields:{...o.payload.fields,...u.payload.fields}})})}}return new Se(s)}}class ii{constructor(e,t,n,r="test"){b(this,"left");b(this,"right");b(this,"label");b(this,"graphName");this.left=e,this.right=t,this.label=n??null,this.graphName=r}execute(e){const t=e.graphStore,n=Re(this.left,e),r=Re(this.right,e),s=new Map;for(const i of r)s.set(i.docId,i);const o=[];for(const i of n){const a=t.neighbors(i.docId,this.graphName,this.label,"out");for(const l of a){const u=s.get(l);u&&o.push({docIds:[i.docId,u.docId],payload:U({score:i.payload.score+u.payload.score,fields:{...i.payload.fields,...u.payload.fields}})})}}return new Se(o)}}class ai{constructor(e,t,n,r){b(this,"left");b(this,"right");b(this,"vertexField");b(this,"docField");this.left=e,this.right=t,this.vertexField=n,this.docField=r}execute(e){const t=e.graphStore,n=Re(this.left,e),r=Re(this.right,e),s=new Map;for(const i of r){const a=i.payload.fields[this.docField];if(a==null)continue;let l=s.get(a);l||(l=[],s.set(a,l)),l.push(i)}const o=[];for(const i of n){const a=t.getVertex(i.docId);let l;if(a?l=a.properties[this.vertexField]:l=i.payload.fields[this.vertexField],l==null)continue;const u=s.get(l);if(u)for(const h of u){const f={};a&&Object.assign(f,a.properties),Object.assign(f,i.payload.fields),Object.assign(f,h.payload.fields),o.push({docIds:[i.docId,h.docId],payload:U({score:i.payload.score+h.payload.score,fields:f})})}}return new Se(o)}}const li=1.1,ci=.1,ui=1.5,hi=.2,Jr=.1;class fi{constructor(e){b(this,"_graphStats");this._graphStats=e??null}estimate(e,t){if(e instanceof _e){const r=e.field??"_default";return t.totalDocs>0?t.docFreq(r,e.term):1}if(e instanceof Ee||e instanceof je)return t.dimensions*Math.log2(t.totalDocs+1);if(e instanceof zt)return e.costEstimate(t);if(e instanceof pe)return this.estimate(e.source,t)*li;if(e instanceof G){const r=t.totalDocs;return e.source!==null?this.estimate(e.source,t)+r*ci:r}if(e instanceof H){let r=0;for(const s of e.operands)r+=this.estimate(s,t);return r}if(e instanceof re){let r=0;for(const s of e.operands)r+=this.estimate(s,t);return r}if(e instanceof de)return this.estimate(e.operand,t)+t.totalDocs;if(e instanceof ti)return t.totalDocs;if(e instanceof ni)return t.totalDocs*ui;if(e instanceof ke){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof Ve){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof Ys){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof pt){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof kt){let r=0;for(const s of e.signals)r+=this.estimate(s,t);return r}if(e instanceof Gt)return this.estimate(e.signal,t)+t.totalDocs;if(e instanceof Ks){const r=e;return this.estimate(r._termOp,t)+this.estimate(r._vectorOp,t)}if(e instanceof Js){const r=e;return this.estimate(r.source,t)+this.estimate(r._vectorOp,t)}if(e instanceof En){const r=e;return this.estimate(r.positive,t)+this.estimate(r._negativeOp,t)}if(e instanceof pr){const r=e;let s=this.estimate(r._vectorOp,t);return r.source!==null&&(s+=this.estimate(r.source,t)),s}if(e instanceof $r)return t.totalDocs*hi;if(e instanceof Fn){if(this._graphStats!==null){const r=this._graphStats,s=e.label,o=e.maxHops,i=r.labelSelectivity(s),a=r.avgOutDegree*i;let l=0;for(let u=1;u<=o;u++)l+=Math.pow(a,u);return Math.max(1,l)}return t.totalDocs*Jr}if(e instanceof Dr){const r=e;let s;if(this._graphStats!==null){const i=this._graphStats,a=i.numVertices>0?i.numVertices:t.totalDocs,l=r.pattern.vertexPatterns.length;s=Math.max(1,Math.pow(a,l)*.01)}else s=Math.pow(t.totalDocs,2);let o=0;for(const i of r.pattern.edgePatterns)i.negated&&o++;return o>0&&(s*=1+.2*o),s}if(e instanceof Pn)return t.totalDocs*Jr;if(e instanceof ri)return Math.pow(t.totalDocs,2);if(e instanceof Vr){const r=e;if(Ln(r.pathExpr)!==null)return t.totalDocs*.1;if(this._graphStats!==null){const i=this._graphStats.numVertices,a=Ft(r.pathExpr);return Math.max(1,i*i*a*.001)}return Math.pow(t.totalDocs,2)}if(e instanceof Ne)return this.estimate(e.source,t)*.5;if(e instanceof Mn){const r=e;return t.totalDocs*r.fields.length}if(e instanceof Dn){const r=e;return t.totalDocs*r.kLayers}if(e instanceof Br){const r=e;return t.totalDocs*r.kLayers*2}if(e instanceof $e)return e.costEstimate(t);const n=t.totalDocs;return e instanceof qr?n*e.maxIterations*.1:e instanceof zr?n*e.maxIterations*.2:e instanceof Gr?n*n*.5:e instanceof si?2*n*Math.max(t.dimensions,10):e instanceof Kr?n*n*Math.max(t.dimensions,1):e instanceof ii?n*10:e instanceof oi?n+n*Math.max(t.dimensions,1):e instanceof ai?n*10:e instanceof kr?e.costEstimate(t):n}}function Ln(c){if(c instanceof Te)return[c.label];if(c instanceof Ze){const e=c,t=Ln(e.left),n=Ln(e.right);return t!==null&&n!==null?[...t,...n]:null}return null}function Ft(c){if(c instanceof Te)return 1;if(c instanceof Ze||c instanceof Ot){const e=c;return Ft(e.left)+Ft(e.right)}if(c instanceof Ct)return Ft(c.inner)*2;if(c instanceof Tt){const e=c;return Ft(e.inner)*e.maxHops}return 1}class Fe{constructor(e,t){b(this,"stats");b(this,"estimator");b(this,"_costModel");b(this,"_graphStats");b(this,"_indexManager");b(this,"_tableName");this.stats=e;const n=(t==null?void 0:t.columnStats)??new Map;this._graphStats=(t==null?void 0:t.graphStats)??null,this.estimator=new ze(n,{graphStats:this._graphStats??void 0}),this._costModel=new fi(this._graphStats),this._indexManager=(t==null?void 0:t.indexManager)??null,this._tableName=(t==null?void 0:t.tableName)??null}optimize(e){let t=e;return t=this._simplifyAlgebra(t),t=this._pushFiltersDown(t),t=this._pushGraphPatternFilters(t),t=this._pushFilterIntoTraverse(t),t=this._pushFilterBelowGraphJoin(t),t=this._fuseJoinPattern(t),t=this._mergeVectorThresholds(t),t=this._reorderIntersect(t),t=this._reorderFusionSignals(t),t=this._applyIndexScan(t),t}_simplifyAlgebra(e){if(e=this._recurseSimplify(e),e instanceof H){let t=e.operands;for(const s of t)if(Fe._isEmptyOperator(s))return new H([]);const n=[];for(const s of t)n.some(o=>o===s)||n.push(s);t=n;const r=[];for(const s of t)s instanceof re&&t.some(o=>o!==s&&s.operands.some(i=>t.some(a=>a===i&&a!==s)))||r.push(s);return t=r,t.length===1?t[0]:new H(t)}if(e instanceof re){let t=e.operands;t=t.filter(s=>!Fe._isEmptyOperator(s));const n=[];for(const s of t)n.some(o=>o===s)||n.push(s);t=n;const r=[];for(const s of t)s instanceof H&&t.some(o=>o!==s&&s.operands.some(i=>t.some(a=>a===i&&a!==s)))||r.push(s);return t=r,t.length===1?t[0]:t.length===0?new re([]):new re(t)}return e}_recurseSimplify(e){return e instanceof H?new H(e.operands.map(t=>this._simplifyAlgebra(t))):e instanceof re?new re(e.operands.map(t=>this._simplifyAlgebra(t))):e instanceof de?new de(this._simplifyAlgebra(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,this._simplifyAlgebra(e.source)):e instanceof Ye?new Ye(e.operators.map(t=>this._simplifyAlgebra(t))):e}static _isEmptyOperator(e){return e instanceof H||e instanceof re?e.operands.length===0:!1}_pushFiltersDown(e){if(!(e instanceof G))return this._recurseChildren(e);const t=e.source;if(t instanceof H){const n=[];let r=!1;for(const s of t.operands)Fe._filterAppliesTo(e,s)?(n.push(new G(e.field,e.predicate,s)),r=!0):n.push(s);if(r){const s=n.map(o=>this._pushFiltersDown(o));return this._recurseChildren(new H(s))}}return t===null?e:new G(e.field,e.predicate,this._recurseChildren(t))}_pushGraphPatternFilters(e){if(e instanceof G&&e.source!==null){const t=this._pushGraphPatternFilters(e.source),n=t.constructor.name;if(n==="PatternMatchOperator"){const r=t;if(r.withVertexPredicate&&e.field)return r.withVertexPredicate(e.field,e.predicate)}if(n==="TraverseOperator"){const r=t;if(e.field){const s=r.vertexPredicate,o=e.field,i=e.predicate,a=l=>{const u=l;return i.evaluate(u[o])?s!==null?s(l):!0:!1};try{const l=t.constructor;return new l(r.startVertex,r.graph,r.label,r.maxHops,a,r.score)}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushGraphPatternFilters(t))}_pushFilterIntoTraverse(e){if(e instanceof G&&e.source!==null){const t=this._pushFilterIntoTraverse(e.source);if(t.constructor.name==="TraverseOperator"){const r=t;if(e.field){const s=e.field,o=e.predicate,i=r.vertexPredicate,a=l=>{const u=l,h=u.properties?u.properties[s]:u[s];return o.evaluate(h)?i===null||i(l):!1};try{const l=t.constructor;return new l(r.startVertex,r.graph,r.label,r.maxHops,a,r.score)}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushFilterIntoTraverse(t))}_pushFilterBelowGraphJoin(e){if(e instanceof G&&e.source!==null){const t=this._pushFilterBelowGraphJoin(e.source),n=t.constructor.name;if(n==="CrossParadigmJoinOperator"||n==="GraphJoinOperator"){const r=t;{const s=Fe._filterAppliesTo(e,r.left),o=Fe._filterAppliesTo(e,r.right);if(s&&!o)try{const i=t.constructor;return new i(new G(e.field,e.predicate,r.left),r.right)}catch{}if(o&&!s)try{const i=t.constructor;return new i(r.left,new G(e.field,e.predicate,r.right))}catch{}}}return new G(e.field,e.predicate,t)}return this._recurseGeneric(e,t=>this._pushFilterBelowGraphJoin(t))}_fuseJoinPattern(e){if(e instanceof H){const t=e.operands.map(s=>this._fuseJoinPattern(s)),n=[],r=[];for(const s of t)s.constructor.name==="PatternMatchOperator"?n.push(s):r.push(s);if(n.length>=2){const s=new Map;for(const a of n){const l=a.graph;s.has(l)||s.set(l,[]),s.get(l).push(a)}const o=[];for(const[,a]of s)if(a.length>=2){a.sort((l,u)=>this._costModel.estimate(l,this.stats)-this._costModel.estimate(u,this.stats)),o.push(a[0]);for(let l=1;l<a.length;l++)o.push(a[l])}else o.push(a[0]);const i=[...r,...o];return i.length===1?i[0]:new H(i)}return t.length===1?t[0]:new H(t)}return this._recurseGeneric(e,t=>this._fuseJoinPattern(t))}_mergeVectorThresholds(e){if(!(e instanceof H))return this._recurseChildren(e);const t=[],n=[];for(let i of e.operands)i=this._recurseChildren(i),i instanceof Ee?t.push(i):n.push(i);const r=[],s=new Array(t.length).fill(!1);for(let i=0;i<t.length;i++){if(s[i])continue;let a=t[i];for(let l=i+1;l<t.length;l++)s[l]||a.field===t[l].field&&this._vectorsClose(a.queryVector,t[l].queryVector)&&(a=new Ee(a.queryVector,Math.max(a.threshold,t[l].threshold),a.field),s[l]=!0);s[i]=!0,r.push(a)}const o=[...n,...r];return o.length===1?o[0]:new H(o)}_vectorsClose(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(Math.abs(e[n]-t[n])>1e-7)return!1;return!0}_reorderIntersect(e){if(!(e instanceof H))return this._recurseChildren(e);const t=e.operands.map(n=>this._recurseChildren(n));return t.sort((n,r)=>this._costModel.estimate(n,this.stats)-this._costModel.estimate(r,this.stats)),new H(t)}_reorderFusionSignals(e){if(e instanceof ke){const t=e.signals.map(n=>this._reorderFusionSignals(n));return t.sort((n,r)=>this._graphAwareSignalCost(n)-this._graphAwareSignalCost(r)),new ke(t,e.alpha,void 0,e.gating)}if(e instanceof Ve){const t=e.signals.map(n=>this._reorderFusionSignals(n));return t.sort((n,r)=>this._graphAwareSignalCost(n)-this._graphAwareSignalCost(r)),new Ve(t,e.mode)}return this._recurseGeneric(e,t=>this._reorderFusionSignals(t))}_graphAwareSignalCost(e){const t=this.estimator.estimate(e,this.stats);if(this._graphStats!==null){const n=e.constructor.name;if(n==="TraverseOperator"){const r=this._graphStats.edgeDensity();return t*(r<.01?.3:.5)}if(n==="PatternMatchOperator")return t*.5;if(n==="RegularPathQueryOperator")return t*.6;if(n==="WeightedPathQueryOperator")return t*.7;if(n==="TemporalTraverseOperator")return t*.6;if(n==="CypherQueryOperator")return t*.5}return e instanceof Ee?t*.8:e instanceof _e?t*.3:t}_applyIndexScan(e){if(this._indexManager===null||this._tableName===null)return e;if(e instanceof G&&e.source===null){const t=this._indexManager.findCoveringIndex(this._tableName,e.field,e.predicate);if(t!==null){const n=t.scanCost(e.predicate),r=this.stats.totalDocs;if(n<r)return new zt(t,e.field,e.predicate)}}return e instanceof G&&e.source!==null?new G(e.field,e.predicate,this._applyIndexScan(e.source)):this._recurseGeneric(e,t=>this._applyIndexScan(t))}_recurseGeneric(e,t){return e instanceof H?new H(e.operands.map(t)):e instanceof re?new re(e.operands.map(t)):e instanceof de?new de(t(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,t(e.source)):e instanceof Ye?new Ye(e.operators.map(t)):e}_recurseChildren(e){return e instanceof H?new H(e.operands.map(t=>this.optimize(t))):e instanceof re?new re(e.operands.map(t=>this.optimize(t))):e instanceof de?new de(this.optimize(e.operand)):e instanceof G&&e.source!==null?new G(e.field,e.predicate,this.optimize(e.source)):e instanceof Ye?new Ye(e.operators.map(t=>this.optimize(t))):e instanceof pe?new pe(e.scorer,this.optimize(e.source),e.queryTerms,e.field):e instanceof Ne?new Ne(this.optimize(e.source),e.threshold):e instanceof ke?new ke(e.signals.map(t=>this.optimize(t)),e.alpha,void 0,e.gating):e instanceof Ve?new Ve(e.signals.map(t=>this.optimize(t)),e.mode):e instanceof Gt?new Gt(this.optimize(e.signal),e.defaultProb):e instanceof pt?new pt(e.signals.map(t=>this.optimize(t)),e.attention,e.queryFeatures):e instanceof kt?new kt(e.signals.map(t=>this.optimize(t)),e.learned):e}static _filterAppliesTo(e,t){const n=e.field;return t instanceof _e?t.field===n||t.field===null:t instanceof G?t.field===n:t instanceof H?t.operands.some(r=>Fe._filterAppliesTo(e,r)):!1}}class tn{constructor(e){b(this,"_context");b(this,"_lastStats",null);this._context=e}execute(e){const[t,n]=this._executeWithStats(e);return this._lastStats=n,t}explain(e){return this._explainNode(e,0)}get lastStats(){return this._lastStats}_executeWithStats(e){const t=this._operatorName(e),n=[],r=performance.now();let s;if(e instanceof re){const a=[];for(const l of e.operands){const[u,h]=this._executeWithStats(l);a.push(u),n.push(h)}s=new D;for(const l of a)s=s.union(l)}else if(e instanceof H)if(e.operands.length===0)s=new D;else{const[a,l]=this._executeWithStats(e.operands[0]);n.push(l),s=a;for(let u=1;u<e.operands.length&&s.length!==0;u++){const[h,f]=this._executeWithStats(e.operands[u]);n.push(f),s=s.intersect(h)}}else if(e instanceof de){const[,a]=this._executeWithStats(e.operand);n.push(a),s=e.execute(this._context)}else if(e instanceof Ne){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof pe){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof G&&e.source!==null){const[,a]=this._executeWithStats(e.source);n.push(a),s=e.execute(this._context)}else if(e instanceof $e){for(const[a]of e.stages){const[,l]=this._executeWithStats(a);n.push(l)}s=e.execute(this._context)}else s=e.execute(this._context);const o=performance.now()-r,i={operatorName:t,elapsedMs:o,resultCount:s.length,children:n};return[s,i]}_explainNode(e,t){const n=" ".repeat(t),r=this._operatorName(e),s=this._operatorDetails(e);let i=s.length>0?`${n}${r} (${s})
10
10
  `:`${n}${r}
11
- `;if(e instanceof re)for(const a of e.operands)i+=this._explainNode(a,t+1);else if(e instanceof H)for(const a of e.operands)i+=this._explainNode(a,t+1);else if(e instanceof fe)i+=this._explainNode(e.operand,t+1);else if(e instanceof Ee)i+=this._explainNode(e.source,t+1);else if(e instanceof de)i+=this._explainNode(e.source,t+1);else if(e instanceof G&&e.source!==null)i+=this._explainNode(e.source,t+1);else if(e instanceof Ve)for(const[a,l]of e.stages)i+=`${n} [cutoff=${String(l)}]
12
- `,i+=this._explainNode(a,t+2);return i}_operatorName(e){return e instanceof me?"TermScan":e instanceof xe?"VectorThreshold":e instanceof Le?"KNN":e instanceof G?"Filter":e instanceof zt?"IndexScan":e instanceof de?"Score":e instanceof re?"Union":e instanceof H?"Intersect":e instanceof fe?"Complement":e instanceof Ee?"SparseThreshold":e instanceof Ve?"MultiStage":e.constructor.name}_operatorDetails(e){if(e instanceof me)return`${e.field!==null?`field=${e.field}, `:""}term="${e.term}"`;if(e instanceof xe)return`field=${e.field}, threshold=${String(e.threshold)}`;if(e instanceof Le)return`field=${e.field}, k=${String(e.k)}`;if(e instanceof G)return`field=${e.field}`;if(e instanceof zt)return`field=${e.field}`;if(e instanceof Ee)return`threshold=${String(e.threshold)}`;if(e instanceof re)return`operands=${String(e.operands.length)}`;if(e instanceof H)return`operands=${String(e.operands.length)}`;if(e instanceof de)return`terms=${String(e.queryTerms.length)}`;if(e instanceof Ve)return`stages=${String(e.stages.length)}`;const t=e.constructor.name;if(t==="TraverseOperator"){const n=e,r=n.label!==null?`, label=${n.label}`:"";return`graph=${n.graph}${r}, maxHops=${String(n.maxHops)}`}if(t==="PatternMatchOperator"){const n=e;return`graph=${n.graph}, vertices=${String(n.pattern.vertexPatterns.length)}`}if(t==="RegularPathQueryOperator"){const n=e,r=n.startVertex!==null?`, start=${String(n.startVertex)}`:"";return`graph=${n.graph}${r}`}if(t==="WeightedPathQueryOperator"){const n=e;return`graph=${n.graph}, agg=${n.aggregation}, weight=${n.weightProperty}`}if(t==="CypherQueryOperator"){const n=e,r=n.query.length>40?n.query.slice(0,40)+"...":n.query;return`graph=${n.graphName}, query="${r}"`}if(t==="LogOddsFusionOperator"){const n=e;return`signals=${String(n.signals.length)}, alpha=${String(n.alpha)}`}if(t==="ProbBoolFusionOperator"){const n=e;return`signals=${String(n.signals.length)}, mode=${n.mode}`}return t==="AttentionFusionOperator"?`signals=${String(e.signals.length)}`:t==="LearnedFusionOperator"?`signals=${String(e.signals.length)}`:t==="VertexAggregationOperator"?`property=${e.propertyName}`:""}explainAnalyze(e,t){const[,n]=this._executeWithStats(e);return this._explainAnalyzeNode(n,0,(t==null?void 0:t.verbose)??!1)}_explainAnalyzeNode(e,t,n){const r=" ".repeat(t);let s=`${r}${e.operatorName}`;s+=` (rows=${String(e.resultCount)}, time=${e.elapsedMs.toFixed(3)}ms)`,s+=`
11
+ `;if(e instanceof re)for(const a of e.operands)i+=this._explainNode(a,t+1);else if(e instanceof H)for(const a of e.operands)i+=this._explainNode(a,t+1);else if(e instanceof de)i+=this._explainNode(e.operand,t+1);else if(e instanceof Ne)i+=this._explainNode(e.source,t+1);else if(e instanceof pe)i+=this._explainNode(e.source,t+1);else if(e instanceof G&&e.source!==null)i+=this._explainNode(e.source,t+1);else if(e instanceof $e)for(const[a,l]of e.stages)i+=`${n} [cutoff=${String(l)}]
12
+ `,i+=this._explainNode(a,t+2);return i}_operatorName(e){return e instanceof _e?"TermScan":e instanceof Ee?"VectorThreshold":e instanceof je?"KNN":e instanceof G?"Filter":e instanceof zt?"IndexScan":e instanceof pe?"Score":e instanceof re?"Union":e instanceof H?"Intersect":e instanceof de?"Complement":e instanceof Ne?"SparseThreshold":e instanceof $e?"MultiStage":e.constructor.name}_operatorDetails(e){if(e instanceof _e)return`${e.field!==null?`field=${e.field}, `:""}term="${e.term}"`;if(e instanceof Ee)return`field=${e.field}, threshold=${String(e.threshold)}`;if(e instanceof je)return`field=${e.field}, k=${String(e.k)}`;if(e instanceof G)return`field=${e.field}`;if(e instanceof zt)return`field=${e.field}`;if(e instanceof Ne)return`threshold=${String(e.threshold)}`;if(e instanceof re)return`operands=${String(e.operands.length)}`;if(e instanceof H)return`operands=${String(e.operands.length)}`;if(e instanceof pe)return`terms=${String(e.queryTerms.length)}`;if(e instanceof $e)return`stages=${String(e.stages.length)}`;const t=e.constructor.name;if(t==="TraverseOperator"){const n=e,r=n.label!==null?`, label=${n.label}`:"";return`graph=${n.graph}${r}, maxHops=${String(n.maxHops)}`}if(t==="PatternMatchOperator"){const n=e;return`graph=${n.graph}, vertices=${String(n.pattern.vertexPatterns.length)}`}if(t==="RegularPathQueryOperator"){const n=e,r=n.startVertex!==null?`, start=${String(n.startVertex)}`:"";return`graph=${n.graph}${r}`}if(t==="WeightedPathQueryOperator"){const n=e;return`graph=${n.graph}, agg=${n.aggregation}, weight=${n.weightProperty}`}if(t==="CypherQueryOperator"){const n=e,r=n.query.length>40?n.query.slice(0,40)+"...":n.query;return`graph=${n.graphName}, query="${r}"`}if(t==="LogOddsFusionOperator"){const n=e;return`signals=${String(n.signals.length)}, alpha=${String(n.alpha)}`}if(t==="ProbBoolFusionOperator"){const n=e;return`signals=${String(n.signals.length)}, mode=${n.mode}`}return t==="AttentionFusionOperator"?`signals=${String(e.signals.length)}`:t==="LearnedFusionOperator"?`signals=${String(e.signals.length)}`:t==="VertexAggregationOperator"?`property=${e.propertyName}`:""}explainAnalyze(e,t){const[,n]=this._executeWithStats(e);return this._explainAnalyzeNode(n,0,(t==null?void 0:t.verbose)??!1)}_explainAnalyzeNode(e,t,n){const r=" ".repeat(t);let s=`${r}${e.operatorName}`;s+=` (rows=${String(e.resultCount)}, time=${e.elapsedMs.toFixed(3)}ms)`,s+=`
13
13
  `,n&&e.children.length>0&&(s+=`${r} children: ${String(e.children.length)}
14
- `);for(const o of e.children)s+=this._explainAnalyzeNode(o,t+1,n);return s}explainTree(e){return this._explainTreeNode(e)}_explainTreeNode(e){const t={operator:this._operatorName(e),details:this._operatorDetails(e)},n=[];if(e instanceof re)for(const r of e.operands)n.push(this._explainTreeNode(r));else if(e instanceof H)for(const r of e.operands)n.push(this._explainTreeNode(r));else if(e instanceof fe)n.push(this._explainTreeNode(e.operand));else if(e instanceof Ee)n.push(this._explainTreeNode(e.source));else if(e instanceof de)n.push(this._explainTreeNode(e.source));else if(e instanceof G&&e.source!==null)n.push(this._explainTreeNode(e.source));else if(e instanceof Ve)for(const[r,s]of e.stages){const o=this._explainTreeNode(r);o.cutoff=s,n.push(o)}else{const r=e.constructor.name;if(r==="LogOddsFusionOperator"||r==="ProbBoolFusionOperator"||r==="AttentionFusionOperator"||r==="LearnedFusionOperator"){const s=e;for(const o of s.signals)n.push(this._explainTreeNode(o))}}return n.length>0&&(t.children=n),t}}const Ze=new Set(["count","sum","avg","min","max","string_agg","array_agg","bool_and","bool_or","stddev","stddev_pop","stddev_samp","variance","var_pop","var_samp","percentile_cont","percentile_disc","mode","json_object_agg","jsonb_object_agg","corr","covar_pop","covar_samp","regr_count","regr_avgx","regr_avgy","regr_sxx","regr_syy","regr_sxy","regr_slope","regr_intercept","regr_r2"]),Yr=new Set(["text_match","bayesian_match","bayesian_match_with_prior","knn_match","bayesian_knn_match","traverse_match","temporal_traverse","path_filter","vector_exclude","spatial_within","fuse_log_odds","fuse_prob_and","fuse_prob_or","fuse_prob_not","fuse_attention","fuse_multihead","fuse_learned","sparse_threshold","multi_field_match","message_passing","graph_embedding","staged_retrieval","pagerank","hits","betweenness","weighted_rpq","progressive_fusion","deep_fusion"]),di=new Set(["random","nextval","currval","now","current_timestamp","clock_timestamp","statement_timestamp","timeofday"]);function g(c,e){return c[e]??null}function Xr(c){return typeof c=="string"?c:c==null?"":typeof c=="number"?c.toString(10):typeof c=="boolean"?c?"true":"false":JSON.stringify(c)}function j(c,e){const t=c[e];return t==null?"":Xr(t)}function w(c){return c??{}}function P(c){return Array.isArray(c)?c:[]}function J(c){const e=g(c,"String")??g(c,"str");if(e!==null&&typeof e=="object")return j(w(e),"sval")||j(w(e),"str");if(typeof e=="string")return e;const t=j(c,"sval")||j(c,"str");return t||""}function ie(c){return j(c,"relname")}function Be(c){const e=g(c,"alias");return e!==null&&typeof e=="object"&&j(w(e),"aliasname")||null}function pi(c){return j(c,"schemaname")||null}function B(c){const e=w(g(c,"ColumnRef")??c),t=P(g(e,"fields"));if(t.length>0){const r=t[t.length-1],s=J(r);if(s)return s}const n=j(e,"sval")||j(e,"str");if(n)return n;throw new Error("Expected ColumnRef, got "+JSON.stringify(c).slice(0,200))}function gi(c){const e=w(g(c,"ColumnRef")??c),t=P(g(e,"fields"));if(t.length>=2){const n=[];for(const r of t){const s=J(r);s&&n.push(s)}return n.join(".")}return B(c)}function Y(c){return g(c,"ColumnRef")!==null}function et(c){if(g(c,"A_Star")!==null&&g(c,"A_Star")!==void 0)return!0;const e=g(c,"ColumnRef");if(e!=null){const t=P(g(w(e),"fields"));for(const n of t)if(g(n,"A_Star")!==null&&g(n,"A_Star")!==void 0)return!0}return!1}function Q(c){return g(c,"FuncCall")!==null}function ae(c){const e=w(g(c,"FuncCall")??c),t=P(g(e,"funcname"));return t.length===0?"":J(t[t.length-1]).toLowerCase()}function be(c){const e=w(g(c,"FuncCall")??c);return P(g(e,"args"))}function tt(c){const e=w(g(c,"FuncCall")??c);return g(e,"agg_star")===!0}function Qr(c){const e=w(g(c,"FuncCall")??c);return g(e,"agg_distinct")===!0}function nt(c){const e=w(g(c,"FuncCall")??c),t=g(e,"over");return t!=null}function ye(c){return g(c,"A_Const")!==null}function Pt(c){return g(c,"ParamRef")!==null}function jn(c){return g(c,"A_Expr")!==null}function mi(c){return g(c,"BoolExpr")!==null}function Zr(c){return g(c,"NullTest")!==null}function nn(c){return g(c,"SubLink")!==null}function rn(c){return g(c,"TypeCast")!==null}function _i(c){return g(c,"A_ArrayExpr")!==null}function z(c,e){const t=g(c,"ParamRef");if(t!=null){const l=w(t),u=g(l,"number"),h=u-1;if(h<0||h>=e.length)throw new Error(`No value supplied for parameter $${String(u)}`);return e[h]}const n=w(g(c,"A_Const")??c);if(g(n,"isnull")===!0)return null;const r=g(n,"ival");if(r!=null)return typeof r=="number"?r:Number(r);const s=g(n,"fval");if(s!=null)return parseFloat(String(s));const o=g(n,"sval");if(o!=null)return String(o);const i=g(n,"boolval");if(i!=null)return i;const a=g(n,"val");if(a!=null&&typeof a=="object"){const l=w(a),u=g(l,"Integer")??g(l,"ival");if(u!=null){if(typeof u=="number")return u;const p=g(w(u),"ival");if(p!==null)return Number(p)}const h=g(l,"Float")??g(l,"fval");if(h!=null){if(typeof h=="number")return h;const p=g(w(h),"fval");return parseFloat(String(p!==null?p:h))}const f=g(l,"String")??g(l,"sval");if(f!=null){if(typeof f=="string")return f;const p=g(w(f),"sval");if(p!==null)return String(p)}const d=g(l,"Boolean")??g(l,"boolval");if(d!=null){if(typeof d=="boolean")return d;const p=g(w(d),"boolval");if(p!==null)return p}}return typeof c=="number"||typeof c=="string"?c:null}function ve(c,e){const t=z(c,e);return Number(t)}function ee(c,e){const t=z(c,e);return String(t)}function Ue(c,e){const t=g(c,"A_ArrayExpr");if(t!=null){const r=P(g(w(t),"elements"));return new Float64Array(r.map(s=>Number(z(s,e))))}const n=g(c,"ParamRef");if(n!=null){const r=w(n),s=g(r,"number"),o=s-1;if(o<0||o>=e.length)throw new Error(`No value supplied for parameter $${String(s)}`);const i=e[o];if(i instanceof Float64Array)return i;if(i instanceof Float32Array)return new Float64Array(i);if(Array.isArray(i))return new Float64Array(i.map(Number));throw new Error("Parameter for vector must be an array")}throw new Error("Expected ARRAY literal or $N parameter for vector")}function yi(c,e,t){if(Pt(c)){const n=w(g(c,"ParamRef")),r=g(n,"number"),s=r-1;if(s<0||s>=e.length)throw new Error(`Parameter $${String(r)} not provided`);const o=e[s];return o!==null&&typeof o=="object"&&"tolist"in o?o.tolist:o}if(_i(c)){const n=P(g(w(g(c,"A_ArrayExpr")),"elements"));return n.length===0?[]:n.map(r=>z(r,e))}if(rn(c))return t.evaluate(c,{});if(Q(c))return t.evaluate(c,{});try{return t.evaluate(c,{})}catch{return z(c,e)}}const bi=1e3;class le{constructor(e){b(this,"_tables");b(this,"_views");b(this,"_sequences");b(this,"_engine");b(this,"_transactionActive");b(this,"_prepared");b(this,"_params");b(this,"_expandedViews");b(this,"_shadowedTables");b(this,"_inlinedCTEs");b(this,"_correlatedOuterRow");b(this,"_foreignServers");b(this,"_foreignTables");b(this,"_currentGraphName","");this._tables=new Map,this._views=new Map,this._sequences=new Map,this._engine=e??null,this._transactionActive=!1,this._prepared=new Map,this._params=[],this._expandedViews=[],this._shadowedTables=new Map,this._inlinedCTEs=new Map,this._correlatedOuterRow=null,this._foreignServers=new Map,this._foreignTables=new Map}_makeSubqueryExecutor(e){return(t,n)=>this._compileSelect(t,e,n)}get tables(){return this._tables}get views(){return this._views}get engine(){return this._engine}async execute(e,t){this._params=t?[...t]:[];const n=await rt.parse(e),r=P(g(w(n),"stmts"));if(r.length===0)return null;let s=null;for(const o of r){const i=w(g(o,"stmt"));s=this._dispatchStatement(i,this._params)}return s}_dispatchStatement(e,t){const n=Object.keys(e);if(n.length===0)return null;const r=n[0],s=w(e[r]);switch(r){case"SelectStmt":return this._compileSelect(s,t);case"InsertStmt":return this._compileInsert(s,t);case"UpdateStmt":return this._compileUpdate(s,t);case"DeleteStmt":return this._compileDelete(s,t);case"CreateStmt":return this._compileCreateTable(s);case"CreateTableAsStmt":return this._compileCreateTableAs(s,t);case"DropStmt":return this._compileDrop(s);case"ViewStmt":return this._compileCreateView(s);case"TransactionStmt":return this._compileTransaction(s);case"CreateSeqStmt":return this._compileCreateSequence(s);case"AlterSeqStmt":return this._compileAlterSequence(s);case"IndexStmt":return this._compileCreateIndex(s);case"AlterTableStmt":return this._compileAlterTable(s);case"TruncateStmt":return this._compileTruncate(s);case"ExplainStmt":return this._compileExplain(s,t);case"RenameStmt":return this._compileRename(s);case"PrepareStmt":return this._compilePrepare(s);case"ExecuteStmt":return this._compileExecute(s,t);case"DeallocateStmt":return this._compileDeallocate(s);case"VacuumStmt":return this._compileAnalyze(s);case"CreateForeignServerStmt":return this._compileCreateForeignServer(s);case"CreateForeignTableStmt":return this._compileCreateForeignTable(s);case"VariableSetStmt":case"VariableShowStmt":case"DoStmt":case"LockStmt":case"DiscardStmt":return null;default:throw new Error(`Unsupported statement type: ${r}`)}}_compileCreateTable(e){const t=w(g(e,"relation")),n=ie(t),r=g(e,"if_not_exists")===!0;if(this._tables.has(n)){if(r)return null;throw new Error(`Table "${n}" already exists`)}const s=P(g(e,"tableElts")),o=[],i=[],a=[];let l=null;for(const h of s){const f=g(h,"ColumnDef");if(f!=null){const p=w(f),m=this._parseColumnDef(p);o.push(m),m.primaryKey&&(l=m.name);const _=P(g(p,"constraints"));for(const y of _){const x=w(g(y,"Constraint")??y),v=g(x,"contype");if(v===1||v==="CONSTR_CHECK"){const E=j(x,"conname")||`check_${String(a.length)}`,I=g(x,"raw_expr");if(I!=null){const S=new oe,N=w(I);a.push([E,A=>S.evaluate(N,A)===!0])}}if(v===8||v==="CONSTR_FOREIGN"){const E=w(g(x,"pktable")),I=P(g(x,"pk_attrs"));I.length>0&&i.push({column:m.name,refTable:ie(E),refColumn:J(I[0])})}}continue}const d=g(h,"Constraint");if(d!=null){const p=w(d),m=g(p,"contype");if(m===5||m==="CONSTR_PRIMARY"){const _=P(g(p,"keys"));_.length>0&&(l=J(_[0]))}if(m===8||m==="CONSTR_FOREIGN"){const _=P(g(p,"fk_attrs")),y=w(g(p,"pktable")),x=P(g(p,"pk_attrs"));_.length>0&&x.length>0&&i.push({column:J(_[0]),refTable:ie(y),refColumn:J(x[0])})}if(m===4||m==="CONSTR_UNIQUE"){const _=P(g(p,"keys"));for(const y of _){const x=J(y),v=o.findIndex(E=>E.name===x);if(v!==-1){const E=o[v];o[v]=Se(E.name,E.typeName,{...E,unique:!0})}}}if(m===1||m==="CONSTR_CHECK"){const _=j(p,"conname")||`check_${String(a.length)}`,y=g(p,"raw_expr");if(y!=null){const x=new oe,v=w(y);a.push([_,E=>x.evaluate(v,E)===!0])}}}}if(l!==null){const h=o.findIndex(f=>f.name===l);if(h!==-1){const f=o[h];o[h]=Se(f.name,f.typeName,{...f,primaryKey:!0,notNull:!0})}}const u=new Ut(n,o);u.foreignKeys=i,u.checkConstraints=a,this._tables.set(n,u),i.length>0&&this._registerFkValidators(n,u,i);for(const h of o)if(h.autoIncrement){const f=`${n}_${h.name}_seq`;this._sequences.set(f,{current:0,increment:1,start:1})}return null}_compileCreateTableAs(e,t){const n=w(g(e,"into")),r=w(g(n,"rel")),s=ie(r);if(this._tables.has(s))throw new Error(`Table "${s}" already exists`);const o=w(g(e,"query")),i=w(g(o,"SelectStmt")??o),a=this._compileSelect(i,t),l=[];for(const f of a.columns){let d="text",p="string";if(a.rows.length>0){const m=a.rows[0][f];typeof m=="number"?Number.isInteger(m)?(d="integer",p="number"):(d="real",p="number"):typeof m=="boolean"?(d="boolean",p="boolean"):Array.isArray(m)?(d="text[]",p="array"):typeof m=="object"&&m!==null&&(d="jsonb",p="object")}l.push(Se(f,d,{pythonType:p}))}const u=new Ut(s,l);this._tables.set(s,u);let h=0;for(const f of a.rows){const d={};for(const p of a.columns)d[p]=f[p]??null;u.insert(d),h++}return{columns:["inserted"],rows:[{inserted:h}]}}_compileCreateSequence(e){const t=w(g(e,"sequence")),n=ie(t),r=P(g(e,"options"));if(this._sequences.has(n)){if(g(e,"if_not_exists")===!0)return null;throw new Error(`Sequence "${n}" already exists`)}let s=1,o=1;for(const i of r){const a=w(g(i,"DefElem")??i),l=j(a,"defname"),u=g(a,"arg");if(l==="start"&&u!==null){const h=w(u);s=Number(g(h,"ival")??g(w(g(h,"Integer")??{}),"ival")??1)}if(l==="increment"&&u!==null){const h=w(u);o=Number(g(h,"ival")??g(w(g(h,"Integer")??{}),"ival")??1)}}return this._sequences.set(n,{current:s-o,increment:o,start:s}),null}_compileAlterSequence(e){const t=w(g(e,"sequence")),n=ie(t),r=this._sequences.get(n);if(r===void 0)throw new Error(`Sequence "${n}" does not exist`);const s=P(g(e,"options"));for(const o of s){const i=w(g(o,"DefElem")??o),a=j(i,"defname"),l=g(i,"arg");if(a==="restart")if(l!=null){const u=w(l),h=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??r.start??1);r.current=h-r.increment}else r.current=(r.start??1)-r.increment;else if(a==="increment"){if(l!=null){const u=w(l);r.increment=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??1)}}else if(a==="start"&&l!=null){const u=w(l);r.start=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??1)}}return null}_parseColumnDef(e){const t=j(e,"colname"),n=w(g(e,"typeName")),r=P(g(n,"names")),s=[];for(const I of r){const S=J(I);S&&S!=="pg_catalog"&&s.push(S)}const i=P(g(n,"arrayBounds")).length>0;let[a,l]=s.length>0?xr(s):["text","string"],u=!1;const h=s.join(" ").toUpperCase();(h==="SERIAL"||h==="BIGSERIAL"||h==="SMALLSERIAL")&&(u=!0),i&&(a="array",l="array");const f=P(g(n,"typmods"));let d=null,p=null,m=null;if(f.length>0){const I=g(f[0],"Integer")??g(f[0],"A_Const");if(I!=null){const S=g(w(I),"ival");S!==null&&typeof S=="number"&&(a==="vector"?m=S:d=S)}if(f.length>1){const S=g(f[1],"Integer")??g(f[1],"A_Const");if(S!=null){const N=g(w(S),"ival");N!==null&&typeof N=="number"&&(p=N)}}}let _=!1,y=!1,x=!1,v=null;const E=P(g(e,"constraints"));for(const I of E){const S=w(g(I,"Constraint")??I),N=g(S,"contype");if((N==="CONSTR_NOTNULL"||N===1)&&(y=!0),(N==="CONSTR_PRIMARY"||N===5)&&(_=!0,y=!0),(N==="CONSTR_UNIQUE"||N===4)&&(x=!0),N==="CONSTR_DEFAULT"||N===2){const A=g(S,"raw_expr");A!=null&&(v=new oe().evaluate(w(A),{}))}(N==="CONSTR_IDENTITY"||N===9)&&(u=!0,y=!0)}return u&&(y=!0),Se(t,a,{pythonType:l,primaryKey:_,notNull:y,autoIncrement:u,defaultValue:v,vectorDimensions:m,unique:x,numericPrecision:d,numericScale:p})}_compileDrop(e){const t=g(e,"removeType");return t===20||t==="OBJECT_INDEX"?this._compileDropIndex(e):t===51||t==="OBJECT_VIEW"?this._compileDropView(e):t===17||t==="OBJECT_FOREIGN_SERVER"?this._compileDropForeignServer(e):t===18||t==="OBJECT_FOREIGN_TABLE"?this._compileDropForeignTable(e):this._compileDropTable(e)}_compileDropTable(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){const s=P(r);let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(!this._tables.has(o)){if(n)continue;throw new Error(`Table "${o}" does not exist`)}this._tables.delete(o);for(const[i]of this._sequences)i.startsWith(`${o}_`)&&this._sequences.delete(i)}}return null}_compileDropView(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){let s=P(r);if(s.length===0){const i=g(w(r),"List");i!=null&&(s=P(g(w(i),"items")))}let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(!this._views.has(o)){if(n)continue;throw new Error(`View "${o}" does not exist`)}this._views.delete(o)}}return null}_compileDropIndex(e){return null}_compileCreateForeignServer(e){const t=j(e,"servername");if(this._foreignServers.has(t)){if(g(e,"if_not_exists")===!0)return null;throw new Error(`Foreign server '${t}' already exists`)}const n=j(e,"fdwname");if(n!=="duckdb_fdw"&&n!=="arrow_fdw")throw new Error(`Unsupported FDW type: '${n}'`);const r={},s=P(g(e,"options"));for(const o of s){const i=w(g(o,"DefElem")??o),a=j(i,"defname"),l=w(g(i,"arg")),u=j(l,"sval")||j(w(g(l,"String")??{}),"sval");a&&(r[a]=u)}return this._foreignServers.set(t,{name:t,fdwType:n,options:r}),null}_compileCreateForeignTable(e){const t=w(g(e,"base")),n=w(g(t,"relation")),r=ie(n);if(this._foreignTables.has(r)){if(g(t,"if_not_exists")===!0)return null;throw new Error(`Foreign table '${r}' already exists`)}if(this._tables.has(r))throw new Error(`Table '${r}' already exists`);const s=j(e,"servername");if(!this._foreignServers.has(s))throw new Error(`Foreign server '${s}' does not exist`);const o=new Map,i=P(g(t,"tableElts"));for(const u of i){const h=w(g(u,"ColumnDef")??u),f=this._parseColumnDef(h);o.set(f.name,f)}const a={},l=P(g(e,"options"));for(const u of l){const h=w(g(u,"DefElem")??u),f=j(h,"defname"),d=w(g(h,"arg")),p=j(d,"sval")||j(w(g(d,"String")??{}),"sval");f&&(a[f]=p)}return this._foreignTables.set(r,{name:r,serverName:s,columns:o,options:a}),null}_compileDropForeignServer(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){let s;if(Array.isArray(r)){const o=r;s=J(o[o.length-1])}else s=J(r);if(this._foreignServers.has(s)){for(const o of this._foreignTables.values())if(o.serverName===s)throw new Error(`Cannot drop server '${s}': foreign table '${o.name}' depends on it`);this._foreignServers.delete(s)}else if(!n)throw new Error(`Foreign server '${s}' does not exist`)}return null}_compileDropForeignTable(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){const s=P(r);let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(this._foreignTables.has(o))this._foreignTables.delete(o);else if(!n)throw new Error(`Foreign table '${o}' does not exist`)}}return null}_compileCreateView(e){const t=w(g(e,"view")),n=ie(t);if(this._tables.has(n))throw new Error(`"${n}" already exists as a table`);if(this._views.has(n))throw new Error(`View "${n}" already exists`);const r=w(g(e,"query")),s=w(g(r,"SelectStmt")??r);return this._views.set(n,s),null}_compileCreateIndex(e){return null}_compileAlterTable(e){const t=w(g(e,"relation")),n=ie(t),r=this._tables.get(n);if(!r)throw new Error(`Table "${n}" does not exist`);const s=P(g(e,"cmds"));for(const o of s){const i=w(g(o,"AlterTableCmd")??o),a=g(i,"subtype"),l=typeof a=="string"?a:"";if(l==="AT_AddColumn"||a===0||a===14){const u=w(g(i,"def")),h=w(g(u,"ColumnDef")??u),f=this._parseColumnDef(h);if(r.columns.has(f.name))throw new Error(`Column "${f.name}" already exists in table "${n}"`);r.columns.set(f.name,f)}else if(l==="AT_DropColumn"||a===10||a===12){const u=j(i,"name"),h=g(i,"missing_ok")===!0;if(!r.columns.has(u)){if(h)continue;throw new Error(`Column "${u}" does not exist in table "${n}"`)}r.columns.delete(u);for(const f of r.documentStore.docIds){const d=r.documentStore.get(f);d&&u in d&&(Reflect.deleteProperty(d,u),r.documentStore.put(f,d))}}else if(l==="AT_ColumnDefault"||a===5||a===6){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=g(i,"def"),f=r.columns.get(u);if(h!=null){const p=new oe().evaluate(w(h),{});r.columns.set(u,Se(f.name,f.typeName,{...f,defaultValue:p}))}else r.columns.set(u,Se(f.name,f.typeName,{...f,defaultValue:null}))}else if(l==="AT_SetNotNull"||a===7||a===9){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);for(const f of r.documentStore.docIds){const d=r.documentStore.get(f);if(d){const p=d[u];if(p==null)throw new Error(`Column "${u}" contains NULL values; cannot set NOT NULL`)}}const h=r.columns.get(u);r.columns.set(u,Se(h.name,h.typeName,{...h,notNull:!0}))}else if(l==="AT_DropNotNull"||a===6||a===8){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=r.columns.get(u);r.columns.set(u,Se(h.name,h.typeName,{...h,notNull:!1}))}else if(l==="AT_AlterColumnType"||a===25||a===28){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=w(g(i,"def")),f=w(g(h,"ColumnDef")??h),d=w(g(f,"typeName")),p=[];for(const x of P(g(d,"names"))){const v=J(x);v&&v!=="pg_catalog"&&p.push(v)}const[m,_]=p.length>0?xr(p):["text","string"],y=r.columns.get(u);r.columns.set(u,Se(u,m,{pythonType:_,primaryKey:y.primaryKey,notNull:y.notNull,autoIncrement:y.autoIncrement,defaultValue:y.defaultValue,vectorDimensions:y.vectorDimensions,unique:y.unique,numericPrecision:y.numericPrecision,numericScale:y.numericScale}));for(const x of Array.from(r.documentStore.docIds)){const v=r.documentStore.get(x);if(v&&v[u]!==null&&v[u]!==void 0){let E=v[u];_==="number"?(E=Number(E),isNaN(E)&&(E=v[u])):_==="string"?E=String(E):_==="boolean"&&(E=!!E),v[u]=E,r.documentStore.put(x,v)}}}else throw new Error(`Unsupported ALTER TABLE subcommand: ${String(a)}`)}return null}_compileRename(e){const t=g(e,"renameType"),n=typeof t=="string"?t:"";if(n==="OBJECT_TABLE"||t===36||t===42){const r=w(g(e,"relation")),s=ie(r),o=j(e,"newname"),i=this._tables.get(s);if(!i)throw new Error(`Table "${s}" does not exist`);if(this._tables.has(o))throw new Error(`Table "${o}" already exists`);return this._tables.delete(s),this._tables.set(o,i),null}if(n==="OBJECT_COLUMN"||t===8||t===9){const r=w(g(e,"relation")),s=ie(r),o=this._tables.get(s);if(!o)throw new Error(`Table "${s}" does not exist`);const i=j(e,"subname"),a=j(e,"newname");if(!o.columns.has(i))throw new Error(`Column "${i}" does not exist in table "${s}"`);if(o.columns.has(a))throw new Error(`Column "${a}" already exists in table "${s}"`);const l=[...o.columns.entries()];o.columns.clear();for(const[u,h]of l)if(u===i){const f=Se(a,h.typeName,{...h});o.columns.set(a,f)}else o.columns.set(u,h);for(const u of o.documentStore.docIds){const h=o.documentStore.get(u);h&&i in h&&(h[a]=h[i],Reflect.deleteProperty(h,i),o.documentStore.put(u,h))}return null}throw new Error(`Unsupported RENAME type: ${String(t)}`)}_compileTruncate(e){const t=P(g(e,"relations"));for(const n of t){const r=w(g(n,"RangeVar")??n),s=ie(r),o=this._tables.get(s);if(!o)throw new Error(`Table "${s}" does not exist`);o.documentStore.clear(),o.invertedIndex.clear();for(const[,i]of o.vectorIndexes)i.clear();for(const[,i]of o.spatialIndexes)i.clear();o._nextDocId=1;for(const i of o.columns.values())if(i.autoIncrement){const a=`${s}_${i.name}_seq`,l=this._sequences.get(a);l&&(l.current=(l.start??1)-l.increment)}}return null}_compileInsert(e,t){const n=w(g(e,"relation")),r=ie(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);const o=P(g(e,"cols"));let i;o.length>0?i=o.map(S=>{const N=w(g(S,"ResTarget")??S);return j(N,"name")}):i=s.columnNames;const a=w(g(e,"selectStmt")),l=w(g(a,"SelectStmt")??a),u=P(g(l,"valuesLists")),h=new oe({params:t,sequences:this._sequences,subqueryExecutor:this._makeSubqueryExecutor(t)}),f=[];if(u.length===0){const S=this._compileSelect(l,t);for(const N of S.rows){const A={};for(let O=0;O<i.length;O++)O<S.columns.length&&(A[i[O]]=N[S.columns[O]]??null);f.push(A)}}else for(const S of u){const N=w(g(S,"List")),A=P(g(N,"items")??S);if(A.length!==i.length)throw new Error(`VALUES has ${String(A.length)} columns but ${String(i.length)} were specified`);const O={};for(let R=0;R<i.length;R++)O[i[R]]=yi(A[R],t,h);f.push(O)}const d=g(e,"onConflictClause");let p=[],m=null,_=[];if(d!=null){const S=w(d),N=w(g(S,"infer"));p=P(g(N,"indexElems")).map(O=>{const R=w(g(O,"IndexElem")??O);return j(R,"name")}),m=g(S,"action"),_=P(g(S,"targetList"))}const y=new Map;if(p.length>0)for(const S of s.documentStore.docIds){const N=s.documentStore.get(S);if(N!==null){const A=p.map(O=>JSON.stringify(N[O])).join("\0");y.set(A,S)}}const x=P(g(e,"returningList")),v=x.length>0,E=[];let I=0;for(const S of f){if(p.length>0&&d!==null){const A=p.map(R=>JSON.stringify(S[R])).join("\0"),O=y.get(A);if(O!==void 0){if(m===1||m==="ONCONFLICT_NOTHING")continue;this._doConflictUpdate(s,O,S,_,h);const R=s.documentStore.get(O);if(R!==null){const T=p.map(F=>JSON.stringify(R[F])).join("\0");T!==A&&(y.delete(A),y.set(T,O))}v&&R!==null&&E.push(this._evaluateReturning(x,R,h,s)),I++;continue}}const[N]=s.insert(S);if(I++,p.length>0){const A=p.map(O=>JSON.stringify(S[O])).join("\0");y.set(A,N)}if(v){const A=s.documentStore.get(N);A!==null&&E.push(this._evaluateReturning(x,A,h,s))}}return v?{columns:this._extractReturningColumns(x,s),rows:E}:{columns:["inserted"],rows:[{inserted:I}]}}_doConflictUpdate(e,t,n,r,s){const o=e.documentStore.get(t);if(o===null)return;const i={...o},a={...o};for(const[u,h]of Object.entries(n))a[`excluded.${u}`]=h;for(const u of r){const h=w(g(u,"ResTarget")??u),f=j(h,"name"),d=g(h,"val");if(d!=null){const p=s.evaluate(w(d),a);p!=null?i[f]=p:Reflect.deleteProperty(i,f)}}e.invertedIndex.removeDocument(t),e.documentStore.put(t,i);const l={};for(const[u,h]of Object.entries(i))typeof h=="string"&&(l[u]=h);Object.keys(l).length>0&&e.invertedIndex.addDocument(t,l)}_compileUpdate(e,t){const n=w(g(e,"relation")),r=ie(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);if(P(g(e,"fromClause")).length>0)return this._compileUpdateFrom(e,s,t);const i=g(e,"whereClause"),a=P(g(e,"targetList")),l=P(g(e,"returningList")),u=l.length>0,h=[],f=new oe({params:t,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)}),d=[];for(const m of a){const _=w(g(m,"ResTarget")??m),y=j(_,"name");if(!s.columns.has(y))throw new Error(`Unknown column "${y}" for table "${r}"`);d.push([y,w(g(_,"val"))])}let p=0;for(const[m,_]of s.documentStore.iterAll()){if(i!=null&&f.evaluate(w(i),_)!==!0)continue;const y={..._};for(const[v,E]of d){const I=f.evaluate(E,_),S=s.columns.get(v);if(I!=null)y[v]=I;else{if(S&&S.notNull)throw new Error(`NOT NULL constraint violated: column "${v}" in table "${r}"`);Reflect.deleteProperty(y,v)}}for(const v of s.fkUpdateValidators)v(_,y);s.invertedIndex.removeDocument(m),s.documentStore.put(m,y);const x={};for(const[v,E]of Object.entries(y))typeof E=="string"&&(x[v]=E);Object.keys(x).length>0&&s.invertedIndex.addDocument(m,x),u&&h.push(this._evaluateReturning(l,y,f,s)),p++}return u?{columns:this._extractReturningColumns(l,s),rows:h}:{columns:["updated"],rows:[{updated:p}]}}_compileUpdateFrom(e,t,n){const r=t.name,s=w(g(e,"relation")),o=Be(s)??r,i=P(g(e,"fromClause")),a=g(e,"whereClause"),l=P(g(e,"targetList")),u=P(g(e,"returningList")),h=u.length>0,f=[],d=new oe({params:n,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(n)}),p=[];for(const y of l){const x=w(g(y,"ResTarget")??y),v=j(x,"name");if(!t.columns.has(v))throw new Error(`Unknown column "${v}" for table "${r}"`);p.push([v,w(g(x,"val"))])}const m=this._resolveFrom(i,n);let _=0;for(const[y,x]of t.documentStore.iterAll()){const v={...x};for(const[E,I]of Object.entries(x))v[`${o}.${E}`]=I;for(const E of m){const I={...v,...E};if(a!=null&&!d.evaluate(w(a),I))continue;const S={...x};for(const[A,O]of p){const R=d.evaluate(O,I),T=t.columns.get(A);if(R!=null)S[A]=R;else{if(T&&T.notNull)throw new Error(`NOT NULL constraint violated: column "${A}" in table "${r}"`);Reflect.deleteProperty(S,A)}}t.invertedIndex.removeDocument(y),t.documentStore.put(y,S);const N={};for(const[A,O]of Object.entries(S))typeof O=="string"&&(N[A]=O);Object.keys(N).length>0&&t.invertedIndex.addDocument(y,N),h&&f.push(this._evaluateReturning(u,S,d,t)),_++;break}}return h?{columns:this._extractReturningColumns(u,t),rows:f}:{columns:["updated"],rows:[{updated:_}]}}_compileDelete(e,t){const n=w(g(e,"relation")),r=ie(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);if(P(g(e,"usingClause")).length>0)return this._compileDeleteUsing(e,s,t);const i=g(e,"whereClause"),a=P(g(e,"returningList")),l=a.length>0,u=[],h=new oe({params:t,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)}),f=[];for(const[d,p]of s.documentStore.iterAll())i!=null&&h.evaluate(w(i),p)!==!0||(l&&u.push(this._evaluateReturning(a,p,h,s)),f.push(d));for(const d of f)for(const p of s.fkDeleteValidators)p(d);for(const d of f)s.invertedIndex.removeDocument(d),s.documentStore.delete(d);return l?{columns:this._extractReturningColumns(a,s),rows:u}:{columns:["deleted"],rows:[{deleted:f.length}]}}_compileDeleteUsing(e,t,n){const r=t.name,s=w(g(e,"relation")),o=Be(s)??r,i=P(g(e,"usingClause")),a=g(e,"whereClause"),l=P(g(e,"returningList")),u=l.length>0,h=[],f=new oe({params:n,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(n)}),d=this._resolveFrom(i,n),p=[];for(const[m,_]of t.documentStore.iterAll()){const y={..._};for(const[x,v]of Object.entries(_))y[`${o}.${x}`]=v;for(const x of d){const v={...y,...x};if(!(a!=null&&!f.evaluate(w(a),v))){u&&h.push(this._evaluateReturning(l,_,f,t)),p.push(m);break}}}for(const m of p)t.invertedIndex.removeDocument(m),t.documentStore.delete(m);return u?{columns:this._extractReturningColumns(l,t),rows:h}:{columns:["deleted"],rows:[{deleted:p.length}]}}_compileTransaction(e){return g(e,"kind"),this._transactionActive=!this._transactionActive,null}_compilePrepare(e){const t=j(e,"name");if(this._prepared.has(t))throw new Error(`Prepared statement "${t}" already exists`);const n=w(g(e,"query"));return this._prepared.set(t,n),null}_compileExecute(e,t){const n=j(e,"name"),r=this._prepared.get(n);if(r===void 0)throw new Error(`Prepared statement "${n}" does not exist`);const s=P(g(e,"params")),o=new oe({params:t}),i=[];for(const l of s)i.push(o.evaluate(l,{}));const a=this._params;this._params=i;try{return this._dispatchStatement(r,i)}finally{this._params=a}}_compileDeallocate(e){const t=j(e,"name");if(!t)this._prepared.clear();else{if(!this._prepared.has(t))throw new Error(`Prepared statement "${t}" does not exist`);this._prepared.delete(t)}return null}_compileExplain(e,t){const n=w(g(e,"query")),r=w(g(n,"SelectStmt")??n),s=P(g(r,"fromClause"));let o=`${String(this._tables.size)} tables`;if(s.length>0){const a=s[0],l=w(g(a,"RangeVar")??a),u=ie(l);if(u){const h=this._tables.get(u);h&&(o=`table "${u}" (${String(h.rowCount)} rows)`)}}const i=`Seq Scan on ${o}`;return{columns:["QUERY PLAN"],rows:[{"QUERY PLAN":i}]}}_compileAnalyze(e){const t=e.rels;if(t&&t.length>0)for(const n of t){const r=n,o=(r.VacuumRelation??r).relation,i=o?o.relname:null;i&&this._tables.has(i)&&this._tables.get(i).analyze()}else for(const n of this._tables.values())n.analyze();return null}_compileSelect(e,t,n){const r=g(e,"withClause");let s=[];if(r!=null){const a=w(r),l=P(g(a,"ctes")),u=g(a,"recursive")===!0;s=this._materializeCTEs(l,t,u,e)}const o=this._correlatedOuterRow;this._correlatedOuterRow=n??null;const i=new Map(this._inlinedCTEs);try{return this._compileSelectBody(e,t)}finally{this._correlatedOuterRow=o;for(const a of s)this._inlinedCTEs.delete(a);this._inlinedCTEs=i;for(const a of s)this._tables.delete(a);for(const a of this._expandedViews)this._shadowedTables.has(a)?(this._tables.set(a,this._shadowedTables.get(a)),this._shadowedTables.delete(a)):this._tables.delete(a);this._expandedViews=[]}}_compileSelectBody(e,t){const n=P(g(e,"valuesLists"));if(n.length>0)return this._compileValues(n,t);const r=g(e,"op");if(r!=null&&r!==0&&r!=="SETOP_NONE")return this._compileSetOp(e,t);e=this._tryPredicatePushdown(e,t);const s=P(g(e,"fromClause")),o=g(e,"whereClause"),i=P(g(e,"targetList")),a=P(g(e,"groupClause")),l=g(e,"havingClause"),u=P(g(e,"sortClause")),h=g(e,"limitCount"),f=g(e,"limitOffset"),d=g(e,"distinctClause"),p=P(g(e,"windowClause")),m=new oe({params:t,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)});let _;s.length===0?_=[{}]:_=this._resolveFrom(s,t),o!=null&&(_=_.filter(S=>m.evaluate(w(o),S)===!0));const y=this._hasAggregates(i);a.length>0?_=this._applyGroupBy(_,a,i,l,m):y&&(_=this._applyGroupBy(_,[],i,l,m));const x=this._hasWindowFunctions(i);x&&(_=this._applyWindowFunctions(_,i,p,m));let v,E;a.length>0||y||x?(v=this._resolveSelectColumnNames(i,_),E=_):[v,E]=this._projectColumns(i,_,m);let I=E;if(d!=null&&(I=this._applyDistinct(I,v)),u.length>0&&(I=this._applyOrderBy(I,u,m,i)),f!=null){const S=Number(m.evaluate(w(f),{}));I=I.slice(S)}if(h!=null){const S=Number(m.evaluate(w(h),{}));I=I.slice(0,S)}return{columns:v,rows:I}}_materializeCTEs(e,t,n,r){const s=[];for(const o of e){const i=w(g(o,"CommonTableExpr")??o),a=j(i,"ctename"),l=w(g(i,"ctequery")),u=w(g(l,"SelectStmt")??l),h=g(u,"op");if(n&&h!==null&&h!==void 0&&h!==0&&h!=="SETOP_NONE")this._materializeRecursiveCTE(i,u,t);else if(this._countCTERefs(a,r)===1)this._inlinedCTEs.set(a,u);else{const p=this._compileSelect(u,t),m=this._resultToTable(a,p);this._tables.set(a,m)}s.push(a)}return s}_materializeRecursiveCTE(e,t,n){const r=j(e,"ctename"),s=g(t,"all")===!0,o=P(g(e,"aliascolnames")),i=o.length>0?o.map(x=>J(x)):null,a=w(g(t,"larg")),l=w(g(a,"SelectStmt")??a),u=this._compileSelect(l,n),h=u.columns;let f,d;if(i!==null){d=[];for(const x of u.rows){const v={};for(let E=0;E<i.length;E++)E<h.length&&(v[i[E]]=x[h[E]]??null);d.push(v)}f=i}else d=[...u.rows],f=h;let p=null;if(!s){p=new Set;const x=[];for(const v of d){const E=f.map(I=>JSON.stringify(v[I])).join("\0");p.has(E)||(p.add(E),x.push(v))}d=x}let m=[...d];for(let x=0;x<bi;x++){const v={columns:f,rows:m},E=this._resultToTable(r,v);this._tables.set(r,E);const I=w(g(t,"rarg")),S=w(g(I,"SelectStmt")??I),N=this._compileSelect(S,n),A=i??f,O=[];for(const T of N.rows){const F={};for(let C=0;C<A.length;C++)C<N.columns.length&&(F[A[C]]=T[N.columns[C]]??null);O.push(F)}if(O.length===0)break;let R=O;if(p!==null){R=[];for(const T of O){const F=f.map(C=>JSON.stringify(T[C])).join("\0");p.has(F)||(p.add(F),R.push(T))}if(R.length===0)break}d.push(...R),m=R}const _={columns:f,rows:d},y=this._resultToTable(r,_);this._tables.set(r,y)}_countCTERefs(e,t){if(t==null||typeof t!="object")return 0;if(Array.isArray(t)){let o=0;for(const i of t)o+=this._countCTERefs(e,i);return o}const n=t,r=g(n,"RangeVar");if(r!=null&&j(w(r),"relname")===e||j(n,"relname")===e)return 1;let s=0;for(const[o,i]of Object.entries(n))o!=="withClause"&&i!==null&&typeof i=="object"&&(s+=this._countCTERefs(e,i));return s}_resultToTable(e,t){const n=[];for(const s of t.columns){let o="text",i="string";for(const a of t.rows){const l=a[s];if(l!=null){typeof l=="boolean"?(o="text",i="string"):typeof l=="number"&&(Number.isInteger(l)?(o="integer",i="number"):(o="real",i="number"));break}}n.push(Se(s,o,{pythonType:i}))}const r=new Ut(e,n);for(let s=0;s<t.rows.length;s++){const o=s+1,i={_id:o};Object.assign(i,t.rows[s]),r.documentStore.put(o,i)}return r}_compileSetOp(e,t){const n=g(e,"op"),r=w(g(e,"larg")),s=w(g(e,"rarg")),o=g(e,"all")===!0,i=w(g(r,"SelectStmt")??r),a=w(g(s,"SelectStmt")??s),l=this._compileSelect(i,t),u=this._compileSelect(a,t);if(l.columns.length!==u.columns.length)throw new Error(`Set operation column count mismatch: ${String(l.columns.length)} vs ${String(u.columns.length)}`);const h=l.columns,f=u.rows.map(y=>{const x={};for(let v=0;v<h.length;v++)x[h[v]]=y[u.columns[v]]??null;return x});let d;if(n===1||n==="SETOP_UNION")d=this._setUnion(l.rows,f,h,o);else if(n===2||n==="SETOP_INTERSECT")d=this._setIntersect(l.rows,f,h,o);else if(n===3||n==="SETOP_EXCEPT")d=this._setExcept(l.rows,f,h,o);else throw new Error(`Unsupported set operation: ${String(n)}`);const p=P(g(e,"sortClause"));if(p.length>0){const y=new oe({params:t}),x=P(g(i,"targetList"));d=this._applyOrderBy(d,p,y,x)}const m=g(e,"limitCount"),_=g(e,"limitOffset");if(_!=null){const y=new oe({params:t}),x=Number(y.evaluate(w(_),{}));d=d.slice(x)}if(m!=null){const y=new oe({params:t}),x=Number(y.evaluate(w(m),{}));d=d.slice(0,x)}return{columns:h,rows:d}}_setUnion(e,t,n,r){if(r)return[...e,...t];const s=new Set,o=[];for(const i of[...e,...t]){const a=n.map(l=>JSON.stringify(i[l])).join("\0");s.has(a)||(s.add(a),o.push(i))}return o}_setIntersect(e,t,n,r){if(r){const a=new Map;for(const u of t){const h=n.map(f=>JSON.stringify(u[f])).join("\0");a.set(h,(a.get(h)??0)+1)}const l=[];for(const u of e){const h=n.map(d=>JSON.stringify(u[d])).join("\0"),f=a.get(h)??0;f>0&&(l.push(u),a.set(h,f-1))}return l}const s=new Set(t.map(a=>n.map(l=>JSON.stringify(a[l])).join("\0"))),o=new Set,i=[];for(const a of e){const l=n.map(u=>JSON.stringify(a[u])).join("\0");s.has(l)&&!o.has(l)&&(o.add(l),i.push(a))}return i}_setExcept(e,t,n,r){if(r){const a=new Map;for(const u of t){const h=n.map(f=>JSON.stringify(u[f])).join("\0");a.set(h,(a.get(h)??0)+1)}const l=[];for(const u of e){const h=n.map(d=>JSON.stringify(u[d])).join("\0"),f=a.get(h)??0;f>0?a.set(h,f-1):l.push(u)}return l}const s=new Set(t.map(a=>n.map(l=>JSON.stringify(a[l])).join("\0"))),o=new Set,i=[];for(const a of e){const l=n.map(u=>JSON.stringify(a[u])).join("\0");!s.has(l)&&!o.has(l)&&(o.add(l),i.push(a))}return i}_compileValues(e,t){const n=new oe({params:t}),r=[];let s=0;for(const i of e){const a=w(g(i,"List")),l=P(g(a,"items")??i);s=Math.max(s,l.length);const u={};for(let h=0;h<l.length;h++){const f=`column${String(h+1)}`;u[f]=n.evaluate(l[h],{})}r.push(u)}const o=[];for(let i=0;i<s;i++)o.push(`column${String(i+1)}`);return{columns:o,rows:r}}_resolveFrom(e,t){let n=null;for(const r of e){const s=g(r,"RangeSubselect");if(s!=null){const i=w(s);if(g(i,"lateral")===!0&&n!==null){n=this._resolveLateralJoin(n,i,t);continue}}const o=this._resolveFromItem(r,t);n===null?n=o:n=this._crossJoin(n,o)}return n??[{}]}_resolveFromItem(e,t){const n=g(e,"RangeVar");if(n!=null){const i=w(n),a=ie(i),l=Be(i),u=pi(i);if(u==="information_schema")return this._buildInformationSchemaTable(a,l??a);if(u==="pg_catalog")return this._buildPgCatalogTable(a,l??a);const h=this._views.get(a);if(h!==void 0){const m=this._compileSelect(h,t);return this._applyAlias(m.rows,l??a)}const f=this._inlinedCTEs.get(a);if(f!==void 0){this._inlinedCTEs.delete(a);const m=this._compileSelect(f,t),_=this._resultToTable(a,m);this._tables.set(a,_),this._expandedViews.push(a);const y=[];for(const[,x]of _.documentStore.iterAll())y.push({...x});return this._applyAlias(y,l??a)}const d=this._tables.get(a);if(!d)throw new Error(`Table "${a}" does not exist`);const p=[];for(const[,m]of d.documentStore.iterAll())p.push({...m});return this._applyAlias(p,l??a)}const r=g(e,"JoinExpr");if(r!=null)return this._resolveJoin(w(r),t);const s=g(e,"RangeSubselect");if(s!=null){const i=w(s),a=w(g(i,"subquery")),l=w(g(a,"SelectStmt")??a),u=Be(i),h=this._compileSelect(l,t);return this._applyAlias(h.rows,u)}const o=g(e,"RangeFunction");if(o!=null)return this._compileFromFunction(w(o),t);throw new Error("Unsupported FROM clause item")}_applyAlias(e,t){return t===null?e:e.map(n=>{const r={...n};for(const[s,o]of Object.entries(n))s.includes(".")||(r[`${t}.${s}`]=o);return r})}_resolveLateralJoin(e,t,n){const r=w(g(t,"subquery")),s=w(g(r,"SelectStmt")??r),o=Be(t)??"_lateral",i=[];for(const a of e){const l=this._compileSelect(s,n,a);for(const u of l.rows){const h={};for(const[f,d]of Object.entries(u))h[f]=d,h[`${o}.${f}`]=d;i.push({...a,...h})}}return i}_compileFromFunction(e,t){const n=P(g(e,"functions"));if(n.length===0)throw new Error("Empty RangeFunction");const r=n[0],s=g(r,"List"),o=s!=null?P(g(w(s),"items")):P(r);if(o.length===0)throw new Error("Empty function list in RangeFunction");const i=w(g(o[0],"FuncCall")??o[0]),a=P(g(i,"funcname")),l=J(a[a.length-1]).toLowerCase(),u=P(g(i,"args")),h=Be(e),f=w(g(e,"alias")),d=P(g(f,"colnames")),p=d.length>0?J(d[0]):null,m=new oe({params:t});if(l==="generate_series")return this._buildGenerateSeries(u,m,h??"generate_series",p??"generate_series");if(l==="unnest")return this._buildUnnest(u,m,h??"unnest",p??"unnest");if(l==="json_each"||l==="jsonb_each"||l==="json_each_text"||l==="jsonb_each_text")return this._buildJSONEach(u,m,h??l,l.endsWith("_text"));if(l==="json_array_elements"||l==="jsonb_array_elements"||l==="json_array_elements_text"||l==="jsonb_array_elements_text")return this._buildJSONArrayElements(u,m,h??l,l.endsWith("_text"));if(l==="regexp_split_to_table")return this._buildRegexpSplitToTable(u,m,h??"regexp_split_to_table",p??"regexp_split_to_table");if(l==="create_graph")return this._buildCreateGraph(u,m);if(l==="drop_graph")return this._buildDropGraph(u,m);if(l==="create_analyzer")return this._buildCreateAnalyzer(u,m);if(l==="drop_analyzer")return this._buildDropAnalyzer(u,m);if(l==="list_analyzers")return this._buildListAnalyzers();if(l==="set_table_analyzer")return this._buildSetTableAnalyzer(u,m);if(l==="graph_add_vertex")return this._buildGraphAddVertex(u,m);if(l==="graph_add_edge")return this._buildGraphAddEdge(u,m);if(l==="build_grid_graph")return this._buildGridGraph(u,m);if(l==="cypher")return this._buildCypherFrom(u,m);throw new Error(`Unsupported FROM-clause function: ${l}`)}_buildCreateGraph(e,t){if(!e.length)throw new Error("create_graph() requires a graph name");const n=String(t.evaluate(e[0],{}));return this._engine.createGraph(n),[{create_graph:`graph '${n}' created`}]}_buildDropGraph(e,t){if(!e.length)throw new Error("drop_graph() requires a graph name");const n=String(t.evaluate(e[0],{}));return this._engine.dropGraph(n),[{drop_graph:`graph '${n}' dropped`}]}_buildCreateAnalyzer(e,t){if(e.length<2)throw new Error("create_analyzer() requires (name, config_json)");const n=String(t.evaluate(e[0],{})),r=JSON.parse(String(t.evaluate(e[1],{})));return this._engine.createAnalyzer(n,r),[{create_analyzer:`analyzer '${n}' created`}]}_buildDropAnalyzer(e,t){if(!e.length)throw new Error("drop_analyzer() requires a name");const n=String(t.evaluate(e[0],{}));return this._engine.dropAnalyzer(n),[{drop_analyzer:`analyzer '${n}' dropped`}]}_buildListAnalyzers(){return xs().map(e=>({analyzer_name:e}))}_buildSetTableAnalyzer(e,t){if(e.length<3)throw new Error("set_table_analyzer(table, field, analyzer[, phase])");const n=String(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=String(t.evaluate(e[2],{})),o=e.length>3?String(t.evaluate(e[3],{})):"both";return this._engine.setTableAnalyzer(n,r,s,{phase:o}),[{set_table_analyzer:`analyzer '${s}' assigned to ${n}.${r}`}]}_buildGraphAddVertex(e,t){if(e.length<3)throw new Error("graph_add_vertex(id, label, table[, props])");const n=Number(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=String(t.evaluate(e[2],{})),o={};if(e.length>3)for(const i of String(t.evaluate(e[3],{})).split(",")){const[a,l]=i.trim().split("=",2);a&&l&&(o[a.trim()]=isNaN(Number(l.trim()))?l.trim():Number(l.trim()))}return this._engine.addGraphVertex(an(n,r,o),{table:s}),[{result:`vertex ${String(n)} added to ${s}`}]}_buildGraphAddEdge(e,t){if(e.length<5)throw new Error("graph_add_edge(eid, src, tgt, label, table[, props])");const n=Number(t.evaluate(e[0],{})),r=Number(t.evaluate(e[1],{})),s=Number(t.evaluate(e[2],{})),o=String(t.evaluate(e[3],{})),i=String(t.evaluate(e[4],{})),a={};if(e.length>5)for(const l of String(t.evaluate(e[5],{})).split(",")){const[u,h]=l.trim().split("=",2);u&&h&&(a[u.trim()]=isNaN(Number(h.trim()))?h.trim():Number(h.trim()))}return this._engine.addGraphEdge(gt(n,r,s,o,a),{table:i}),[{result:`edge ${String(n)} added to ${i}`}]}_buildGridGraph(e,t){if(e.length<4)throw new Error("build_grid_graph(table, rows, cols, label)");const n=String(t.evaluate(e[0],{})),r=Number(t.evaluate(e[1],{})),s=Number(t.evaluate(e[2],{})),o=String(t.evaluate(e[3],{}));let i=1;for(let a=0;a<r;a++)for(let l=0;l<s;l++){const u=a*s+l+1;l<s-1&&this._engine.addGraphEdge(gt(i++,u,u+1,o),{table:n}),a<r-1&&this._engine.addGraphEdge(gt(i++,u,u+s,o),{table:n})}return[{table_name:n,rows:r,cols:s,edges:i-1}]}_buildCypherFrom(e,t){if(e.length<2)throw new Error("cypher() requires (graph_name, query)");const n=String(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=this._engine.getGraph(n),o={};for(let a=0;a<this._params.length;a++)o[String(a+1)]=this._params[a];return new yo(s,n,o).executeRows(r,o)}_buildGenerateSeries(e,t,n,r){if(e.length<2)throw new Error("generate_series requires at least 2 arguments");const s=Number(t.evaluate(e[0],{})),o=Number(t.evaluate(e[1],{})),i=e.length>2?Number(t.evaluate(e[2],{})):1;if(i===0)throw new Error("generate_series step cannot be zero");const a=[];if(i>0)for(let l=s;l<=o;l+=i){const u={[r]:l};u[`${n}.${r}`]=l,a.push(u)}else for(let l=s;l>=o;l+=i){const u={[r]:l};u[`${n}.${r}`]=l,a.push(u)}return a}_buildUnnest(e,t,n,r){if(e.length<1)throw new Error("unnest requires at least 1 argument");let s=t.evaluate(e[0],{});Array.isArray(s)||(s=[s]);const o=[];for(const i of s){const a={[r]:i};a[`${n}.${r}`]=i,o.push(a)}return o}_buildJSONEach(e,t,n,r){if(e.length<1)throw new Error("json_each requires at least 1 argument");let s=t.evaluate(e[0],{});if(typeof s=="string"&&(s=JSON.parse(s)),s===null||typeof s!="object"||Array.isArray(s))throw new Error("json_each expects a JSON object");const o=[];for(const[i,a]of Object.entries(s)){const l=r?String(a):a,u={key:i,value:l};u[`${n}.key`]=i,u[`${n}.value`]=l,o.push(u)}return o}_buildJSONArrayElements(e,t,n,r){if(e.length<1)throw new Error("json_array_elements requires at least 1 argument");let s=t.evaluate(e[0],{});if(typeof s=="string"&&(s=JSON.parse(s)),!Array.isArray(s))throw new Error("json_array_elements expects a JSON array");const o=[];for(const i of s){const a=r?String(i):i,l={value:a};l[`${n}.value`]=a,o.push(l)}return o}_buildRegexpSplitToTable(e,t,n,r){if(e.length<2)throw new Error("regexp_split_to_table requires at least 2 arguments");const s=String(t.evaluate(e[0],{})),o=String(t.evaluate(e[1],{})),i=e.length>2?String(t.evaluate(e[2],{})):"",a=new RegExp(o,i.includes("g")?i:i+"g"),l=s.split(a),u=[];for(const h of l){const f={[r]:h};f[`${n}.${r}`]=h,u.push(f)}return u}_crossJoin(e,t){const n=[];for(const r of e)for(const s of t)n.push({...r,...s});return n}_resolveJoin(e,t){const n=g(e,"jointype"),r=w(g(e,"larg")),s=w(g(e,"rarg")),o=g(e,"quals"),i=g(s,"RangeSubselect");if(i!=null){const _=w(i);if(g(_,"lateral")===!0){const y=this._resolveFromItem(r,t);return this._resolveLateralJoin(y,_,t)}}const a=this._resolveFromItem(r,t),l=this._resolveFromItem(s,t),u=new oe({params:t});if(n===5||n==="JOIN_CROSS")return this._crossJoin(a,l);if((n===0||n==="JOIN_INNER")&&o==null)return this._crossJoin(a,l);const h=[],f=n===1||n==="JOIN_LEFT",d=n===3||n==="JOIN_RIGHT",p=n===2||n==="JOIN_FULL",m=new Set;for(const _ of a){let y=!1;for(let x=0;x<l.length;x++){const v=l[x],E={..._,...v};o!=null&&u.evaluate(w(o),E)!==!0||(h.push(E),y=!0,m.add(x))}if(!y&&(f||p)){const x={..._};if(l.length>0)for(const v of Object.keys(l[0]))v in x||(x[v]=null);h.push(x)}}if(d||p){for(let _=0;_<l.length;_++)if(!m.has(_)){const y={};if(a.length>0)for(const x of Object.keys(a[0]))y[x]=null;for(const[x,v]of Object.entries(l[_]))y[x]=v;h.push(y)}}return h}_buildInformationSchemaTable(e,t){if(e==="tables"){const n=[];for(const r of[...this._tables.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"BASE TABLE"});for(const r of[...this._foreignTables.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"FOREIGN TABLE"});for(const r of[...this._views.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"VIEW"});return this._applyAlias(n,t)}if(e==="columns"){const n={int2:"smallint",int4:"integer",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean"},r=[];for(const s of[...this._tables.keys()].sort()){const o=this._tables.get(s);let i=1;for(const[a,l]of o.columns){const u=n[l.typeName]??l.typeName;r.push({table_catalog:"",table_schema:"public",table_name:s,column_name:a,ordinal_position:i,data_type:u,is_nullable:l.notNull?"NO":"YES"}),i++}}for(const s of[...this._foreignTables.keys()].sort()){const o=this._foreignTables.get(s);let i=1;for(const[a,l]of o.columns){const u=n[l.typeName]??l.typeName;r.push({table_catalog:"",table_schema:"public",table_name:s,column_name:a,ordinal_position:i,data_type:u,is_nullable:l.notNull?"NO":"YES"}),i++}}return this._applyAlias(r,t)}throw new Error(`Unknown information_schema view: "${e}"`)}_buildPgCatalogTable(e,t){if(e==="pg_tables"){const n=[];for(const r of[...this._tables.keys()].sort())n.push({schemaname:"public",tablename:r,tableowner:"",tablespace:""});return this._applyAlias(n,t)}if(e==="pg_views"){const n=[];for(const r of[...this._views.keys()].sort())n.push({schemaname:"public",viewname:r,viewowner:"",definition:""});return this._applyAlias(n,t)}if(e==="pg_indexes"){const n=[],r=this._engine,s=r!==null?r._indexManager:void 0;if(s!==void 0){const o=s._indexes;if(o!==void 0)for(const i of o.values()){const a=i.indexDef;if(a!==void 0){const l=a.tableName??"",u=a.name??"",h=a.columns??[];n.push({schemaname:"public",tablename:l,indexname:u,tablespace:"",indexdef:`CREATE INDEX ${u} ON ${l} (${h.join(", ")})`})}}}return this._applyAlias(n,t)}if(e==="pg_type"){const r=[[16,"boolean",11,1,"b","B"],[17,"bytea",11,-1,"b","U"],[20,"bigint",11,8,"b","N"],[21,"smallint",11,2,"b","N"],[23,"integer",11,4,"b","N"],[25,"text",11,-1,"b","S"],[114,"json",11,-1,"b","U"],[142,"xml",11,-1,"b","U"],[700,"real",11,4,"b","N"],[701,"float8",11,8,"b","N"],[1043,"varchar",11,-1,"b","S"],[1082,"date",11,4,"b","D"],[1083,"time",11,8,"b","D"],[1114,"timestamp",11,8,"b","D"],[1184,"timestamptz",11,8,"b","D"],[1186,"interval",11,16,"b","T"],[1700,"numeric",11,-1,"b","N"],[2950,"uuid",11,16,"b","U"],[3802,"jsonb",11,-1,"b","U"],[16385,"vector",11,-1,"b","U"]].map(([s,o,i,a,l,u])=>({oid:s,typname:o,typnamespace:i,typlen:a,typtype:l,typcategory:u}));return this._applyAlias(r,t)}throw new Error(`Unknown pg_catalog view: "${e}"`)}_projectColumns(e,t,n){if(e.length===0){if(t.length===0)return[[],[]];const i=Object.keys(t[0]).filter(a=>!a.includes("."));return[i,t.map(a=>{const l={};for(const u of i)l[u]=a[u];return l})]}const r=[],s=[];for(const i of e){const a=w(g(i,"ResTarget")??i),l=g(a,"val"),u=j(a,"name");if(l!=null){const h=w(l);if(et(h)){const d=g(h,"ColumnRef");if(d!=null){const p=P(g(w(d),"fields"));if(p.length>=2){const m=J(p[0]);if(t.length>0)for(const _ of Object.keys(t[0])){const y=`${m}.`;if(_.startsWith(y)){const x=_.slice(y.length);x.includes(".")||(r.push(x),s.push({name:x,node:null}))}}continue}}if(t.length>0)for(const p of Object.keys(t[0]))p.includes(".")||(r.push(p),s.push({name:p,node:null}));continue}let f=u;f||(f=this._deriveColumnName(h)),r.push(f),s.push({name:f,node:h})}}const o=[];for(const i of t){const a={};for(const l of s)l.node===null?a[l.name]=i[l.name]:a[l.name]=n.evaluate(l.node,i);o.push(a)}return[r,o]}_deriveColumnName(e){if(Y(e))try{return B(e)}catch{}if(Q(e)){const t=ae(e);if(Ze.has(t)){const n=be(e);if(tt(e)||n.length===0)return t;try{const r=B(n[0]);return`${t}_${r}`}catch{return t}}return t}if(rn(e)){const t=w(g(e,"TypeCast")),n=w(g(t,"arg"));if(Y(n))try{return B(n)}catch{}}return nn(e),"?column?"}_resolveSelectColumnNames(e,t){if(e.length===0)return t.length===0?[]:Object.keys(t[0]).filter(r=>!r.includes("."));const n=[];for(const r of e){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!=null){const a=w(o);if(et(a)){if(t.length>0)for(const l of Object.keys(t[0]))l.includes(".")||n.push(l);continue}n.push(i||this._deriveColumnName(a))}}return n}_hasAggregates(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&this._containsAggregate(w(r)))return!0}return!1}_containsAggregate(e){if(Q(e)){const t=ae(e);if(Ze.has(t)&&!nt(e))return!0}if(nn(e)||g(e,"SubLink")!==null)return!1;for(const[,t]of Object.entries(e))if(t!==null&&typeof t=="object"){if(Array.isArray(t)){for(const n of t)if(n!==null&&typeof n=="object"&&this._containsAggregate(n))return!0}else if(this._containsAggregate(t))return!0}return!1}_applyGroupBy(e,t,n,r,s){const o=new Map;if(t.length===0)o.set("__all__",e);else for(const l of e){const u=[];for(const d of t){const p=s.evaluate(d,l);u.push(p)}const h=JSON.stringify(u);let f=o.get(h);f||(f=[],o.set(h,f)),f.push(l)}const i=[],a=[];for(const[,l]of o){const u=this._computeAggregates(l,n,s);i.push(u),a.push(l)}if(r!=null){const l=[];for(let u=0;u<i.length;u++){const h=i[u],f=a[u],d=this._resolveHavingAggregates(w(r),f,h,s);s.evaluate(w(r),d)===!0&&l.push(h)}return l}return i}_computeAggregates(e,t,n){const r={},s=e[0];for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(Q(u)){const h=ae(u),f=tt(u),d=be(u),p=Qr(u);if(nt(u)){const v=l||h;r[v]=n.evaluate(u,s);continue}if(!Ze.has(h)){const v={...s};this._collectHavingAggregates(u,e,v,n);const E=l||this._deriveColumnName(u);r[E]=n.evaluate(u,v);continue}let _=l;if(!_)if(f||d.length===0)_=h;else try{const v=B(d[0]);_=`${h}_${v}`}catch{_=h}let y;const x=()=>{let v=[];for(const E of e){const I=n.evaluate(d[0],E);I!=null&&v.push(I)}if(p){const E=new Set,I=[];for(const S of v){const N=JSON.stringify(S);E.has(N)||(E.add(N),I.push(S))}v=I}return v};switch(h){case"count":f?y=e.length:y=x().length;break;case"sum":{const v=x();y=v.length>0?v.reduce((E,I)=>E+Number(I),0):null;break}case"avg":{const v=x();v.length>0?y=v.reduce((I,S)=>I+Number(S),0)/v.length:y=null;break}case"min":{const v=x();v.length===0?y=null:y=v.reduce((E,I)=>E<I?E:I);break}case"max":{const v=x();v.length===0?y=null:y=v.reduce((E,I)=>E>I?E:I);break}case"string_agg":{const v=d.length>=2?String(n.evaluate(d[1],s)):",",E=[];for(const I of e){const S=n.evaluate(d[0],I);S!=null&&E.push(Xr(S))}y=E.length>0?E.join(v):null;break}case"array_agg":{const v=[];for(const E of e)v.push(n.evaluate(d[0],E));y=v;break}case"bool_and":{const v=x();y=v.length>0?v.every(E=>!!E):null;break}case"bool_or":{const v=x();y=v.length>0?v.some(E=>!!E):null;break}case"stddev":case"stddev_samp":{const v=x().map(Number);if(v.length<2)y=null;else{const E=v.reduce((S,N)=>S+N,0)/v.length,I=v.reduce((S,N)=>S+(N-E)**2,0)/(v.length-1);y=Math.sqrt(I)}break}case"stddev_pop":{const v=x().map(Number);if(v.length===0)y=null;else{const E=v.reduce((S,N)=>S+N,0)/v.length,I=v.reduce((S,N)=>S+(N-E)**2,0)/v.length;y=Math.sqrt(I)}break}case"variance":case"var_samp":{const v=x().map(Number);if(v.length<2)y=null;else{const E=v.reduce((I,S)=>I+S,0)/v.length;y=v.reduce((I,S)=>I+(S-E)**2,0)/(v.length-1)}break}case"var_pop":{const v=x().map(Number);if(v.length===0)y=null;else{const E=v.reduce((I,S)=>I+S,0)/v.length;y=v.reduce((I,S)=>I+(S-E)**2,0)/v.length}break}case"json_object_agg":case"jsonb_object_agg":{if(d.length<2)y=null;else{const v={};for(const E of e){const I=n.evaluate(d[0],E),S=n.evaluate(d[1],E);I!=null&&(v[String(I)]=S)}y=v}break}case"percentile_cont":{if(d.length>0){const v=Number(n.evaluate(d[0],s)),E=w(g(u,"FuncCall")??u),I=P(g(E,"agg_order"));if(I.length>0){const S=w(g(I[0],"SortBy")??I[0]),N=w(g(S,"node")),A=[];for(const O of e){const R=n.evaluate(N,O);R!=null&&A.push(Number(R))}if(A.sort((O,R)=>O-R),A.length===0)y=null;else{const O=v*(A.length-1),R=Math.floor(O),T=Math.ceil(O);R===T?y=A[R]:y=A[R]+(O-R)*(A[T]-A[R])}}else y=null}else y=null;break}case"mode":{const v=w(g(u,"FuncCall")??u),E=P(g(v,"agg_order"));if(E.length>0){const I=w(g(E[0],"SortBy")??E[0]),S=w(g(I,"node")),N=new Map;for(const R of e){const T=n.evaluate(S,R),F=JSON.stringify(T),C=N.get(F);C?C.count++:N.set(F,{count:1,value:T})}let A=0,O=null;for(const R of N.values())R.count>A&&(A=R.count,O=R.value);y=O}else y=null;break}case"corr":case"covar_pop":case"covar_samp":case"regr_count":case"regr_avgx":case"regr_avgy":case"regr_sxx":case"regr_syy":case"regr_sxy":case"regr_slope":case"regr_intercept":case"regr_r2":{if(d.length<2){y=null;break}const v=[],E=[];for(const I of e){const S=n.evaluate(d[0],I),N=n.evaluate(d[1],I);S!=null&&N!==null&&N!==void 0&&(v.push(Number(S)),E.push(Number(N)))}y=this._computeStatAgg(h,v,E);break}default:y=n.evaluate(u,s);break}r[_]=y}else{const h=l||this._deriveColumnName(u);r[h]=n.evaluate(u,s)}}return r}_computeStatAgg(e,t,n){const r=t.length;if(r===0)return null;const s=n.reduce((f,d)=>f+d,0),o=t.reduce((f,d)=>f+d,0),i=s/r,a=o/r;let l=0,u=0,h=0;for(let f=0;f<r;f++){const d=n[f]-i,p=t[f]-a;l+=d*d,u+=p*p,h+=d*p}switch(e){case"regr_count":return r;case"regr_avgx":return i;case"regr_avgy":return a;case"regr_sxx":return l;case"regr_syy":return u;case"regr_sxy":return h;case"covar_pop":return h/r;case"covar_samp":return r<2?null:h/(r-1);case"corr":return l===0||u===0?null:h/Math.sqrt(l*u);case"regr_slope":return l===0?null:h/l;case"regr_intercept":return l===0?null:a-h/l*i;case"regr_r2":{if(l===0||u===0)return null;const f=h/Math.sqrt(l*u);return f*f}default:return null}}_resolveHavingAggregates(e,t,n,r){const s={...n};return this._collectHavingAggregates(e,t,s,r),s}_collectHavingAggregates(e,t,n,r){const s=e.FuncCall;if(s){const a=s.funcname;if(a.length>0){const l=a[a.length-1],u=l.String??l.str,h=typeof u=="object"&&u!==null?u.sval??u.str:u;if(h&&Ze.has(h.toLowerCase())){const f=this._computeInlineAggregate(h.toLowerCase(),s,t,r),d=tt(e),p=be(e);let m;if(d||p.length===0)m=`${h.toLowerCase()}(*)`;else try{const _=B(p[0]);m=`${h.toLowerCase()}(${_})`}catch{m=h.toLowerCase()}n[m]=f,n[`__having_agg_${JSON.stringify(e)}`]=f;return}}}const o=e.BoolExpr;if(o){const a=P(o.args);for(const l of a)this._collectHavingAggregates(w(l),t,n,r);return}const i=e.A_Expr;if(i){const a=i.lexpr,l=i.rexpr;a&&this._collectHavingAggregates(w(a),t,n,r),l&&this._collectHavingAggregates(w(l),t,n,r);return}for(const a of Object.values(e))if(Array.isArray(a))for(const l of a)typeof l=="object"&&l!==null&&this._collectHavingAggregates(l,t,n,r);else typeof a=="object"&&a!==null&&this._collectHavingAggregates(a,t,n,r)}_computeInlineAggregate(e,t,n,r){const s={FuncCall:t},o=tt(s),i=be(s),a=Qr(s),l=()=>{let h=[];for(const f of n){const d=i.length>0?r.evaluate(i[0],f):null;d!=null&&h.push(d)}if(a){const f=new Set,d=[];for(const p of h){const m=JSON.stringify(p);f.has(m)||(f.add(m),d.push(p))}h=d}return h},u=()=>{const h=[];if(i.length<2)return h;for(const f of n){const d=r.evaluate(i[0],f),p=r.evaluate(i[1],f);d!=null&&p!==null&&p!==void 0&&h.push([Number(d),Number(p)])}return h};switch(e){case"count":return o?n.length:l().length;case"sum":{const h=l();return h.length>0?h.reduce((f,d)=>f+Number(d),0):null}case"avg":{const h=l();return h.length>0?h.reduce((f,d)=>f+Number(d),0)/h.length:null}case"min":{const h=l();return h.length>0?h.reduce((f,d)=>Number(f)<Number(d)?f:d):null}case"max":{const h=l();return h.length>0?h.reduce((f,d)=>Number(f)>Number(d)?f:d):null}case"stddev":case"stddev_samp":{const h=l().map(Number);if(h.length<2)return null;const f=h.reduce((p,m)=>p+m,0)/h.length,d=h.reduce((p,m)=>p+(m-f)**2,0)/(h.length-1);return Math.sqrt(d)}case"stddev_pop":{const h=l().map(Number);if(h.length===0)return null;const f=h.reduce((p,m)=>p+m,0)/h.length,d=h.reduce((p,m)=>p+(m-f)**2,0)/h.length;return Math.sqrt(d)}case"variance":case"var_samp":{const h=l().map(Number);if(h.length<2)return null;const f=h.reduce((d,p)=>d+p,0)/h.length;return h.reduce((d,p)=>d+(p-f)**2,0)/(h.length-1)}case"var_pop":{const h=l().map(Number);if(h.length===0)return null;const f=h.reduce((d,p)=>d+p,0)/h.length;return h.reduce((d,p)=>d+(p-f)**2,0)/h.length}case"corr":case"covar_pop":case"covar_samp":case"regr_slope":case"regr_intercept":case"regr_r2":case"regr_count":case"regr_avgx":case"regr_avgy":case"regr_sxx":case"regr_syy":case"regr_sxy":{const h=u();if(h.length===0)return null;const f=h.length,d=h.reduce((x,v)=>x+v[0],0)/f,p=h.reduce((x,v)=>x+v[1],0)/f;let m=0,_=0,y=0;for(const[x,v]of h)m+=(v-p)**2,_+=(x-d)**2,y+=(v-p)*(x-d);switch(e){case"corr":return m===0||_===0?null:y/Math.sqrt(m*_);case"covar_pop":return y/f;case"covar_samp":return f<2?null:y/(f-1);case"regr_slope":return m===0?null:y/m;case"regr_intercept":return m===0?null:d-y/m*p;case"regr_r2":return m===0||_===0?null:y*y/(m*_);case"regr_count":return f;case"regr_avgx":return p;case"regr_avgy":return d;case"regr_sxx":return m;case"regr_syy":return _;case"regr_sxy":return y;default:return null}}default:return null}}_hasWindowFunctions(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&Q(w(r))&&nt(w(r)))return!0}return!1}_applyWindowFunctions(e,t,n,r){const s=new Map;for(const o of n){const i=w(g(o,"WindowDef")??o),a=j(i,"name");a&&s.set(a,i)}for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(!Q(u)||!nt(u))continue;const h=ae(u),f=l||h,d=w(g(u,"FuncCall")??u),p=be(u),m=w(g(d,"over")),_=j(m,"refname")||j(m,"name");let y=m;_&&s.has(_)&&(y=s.get(_));const x=[];for(const I of P(g(y,"partitionClause")))try{x.push(B(I))}catch{}const v=[];for(const I of P(g(y,"orderClause"))){const S=w(g(I,"SortBy")??I),N=w(g(S,"node"));try{const A=B(N),O=g(S,"sortby_dir"),R=O===2||O==="SORTBY_DESC";v.push({col:A,desc:R})}catch{}}const E=new Map;for(let I=0;I<e.length;I++){const S=e[I],N=x.map(O=>JSON.stringify(S[O])).join("\0");let A=E.get(N);A||(A={rows:[],indices:[]},E.set(N,A)),A.rows.push(S),A.indices.push(I)}for(const I of E.values())if(v.length>0){const S=I.rows.map((N,A)=>({row:N,origIdx:I.indices[A]}));S.sort((N,A)=>{for(const O of v){const R=N.row[O.col],T=A.row[O.col],F=R==null,C=T==null;if(F&&C)continue;if(F)return O.desc?-1:1;if(C)return O.desc?1:-1;let V;if(typeof R=="string"&&typeof T=="string"?V=R<T?-1:R>T?1:0:V=R-T,V!==0)return O.desc?-V:V}return 0}),I.rows=S.map(N=>N.row),I.indices=S.map(N=>N.origIdx)}for(const I of E.values()){const S=I.rows,N=S.length;for(let A=0;A<N;A++){let O=null;switch(h){case"row_number":O=A+1;break;case"rank":{let T=1;for(let F=0;F<A;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}C||(T=F+1+1)}T=1;for(let F=0;F<A;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}C||T++}T=1;for(let F=0;F<N;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}if(C){T=F+1;break}}O=T;break}case"dense_rank":{const T=new Set;for(let F=0;F<=A;F++){const C=v.map(V=>JSON.stringify(S[F][V.col])).join("\0");T.add(C)}O=T.size;break}case"percent_rank":{if(N<=1)O=0;else{let T=1;for(let F=0;F<N;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}if(C){T=F+1;break}}O=(T-1)/(N-1)}break}case"cume_dist":{let T=0;for(let F=0;F<N;F++){let C=!0;for(const V of v){const X=S[F][V.col],he=S[A][V.col];V.desc?X<he&&(C=!1):X>he&&(C=!1)}C&&T++}O=T/N;break}case"ntile":{const T=p.length>0?Number(r.evaluate(p[0],{})):1;O=Math.floor(A*T/N)+1;break}case"lag":{const T=p.length>1?Number(r.evaluate(p[1],{})):1,F=p.length>2?r.evaluate(p[2],{}):null,C=A-T;C>=0&&C<N&&p.length>0?O=r.evaluate(p[0],S[C]):O=F;break}case"lead":{const T=p.length>1?Number(r.evaluate(p[1],{})):1,F=p.length>2?r.evaluate(p[2],{}):null,C=A+T;C>=0&&C<N&&p.length>0?O=r.evaluate(p[0],S[C]):O=F;break}case"first_value":{p.length>0&&N>0&&(O=r.evaluate(p[0],S[0]));break}case"last_value":{p.length>0&&N>0&&(O=r.evaluate(p[0],S[N-1]));break}case"nth_value":{const T=p.length>1?Number(r.evaluate(p[1],{})):1;p.length>0&&T>=1&&T<=N&&(O=r.evaluate(p[0],S[T-1]));break}case"sum":{let T=0,F=!1;const C=v.length>0?A:N-1;for(let V=0;V<=C;V++){const X=p.length>0?r.evaluate(p[0],S[V]):null;X!=null&&(T+=Number(X),F=!0)}O=F?T:null;break}case"count":{const T=v.length>0?A:N-1;if(tt(u))O=T+1;else{let F=0;for(let C=0;C<=T;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&F++}O=F}break}case"avg":{let T=0,F=0;const C=v.length>0?A:N-1;for(let V=0;V<=C;V++){const X=p.length>0?r.evaluate(p[0],S[V]):null;X!=null&&(T+=Number(X),F++)}O=F>0?T/F:null;break}case"min":{let T=null;const F=v.length>0?A:N-1;for(let C=0;C<=F;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&(T===null||V<T)&&(T=V)}O=T;break}case"max":{let T=null;const F=v.length>0?A:N-1;for(let C=0;C<=F;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&(T===null||V>T)&&(T=V)}O=T;break}default:O=null;break}const R=I.indices[A];e[R][f]=O}}}for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(Q(u)&&nt(u))continue;const h=l||this._deriveColumnName(u);if(Y(u)){const f=B(u);if(f!==h)for(const d of e)d[h]=d[f]}else for(const f of e)f[h]=r.evaluate(u,f)}return e}_applyDistinct(e,t){const n=new Set,r=[];for(const s of e){const o=t.map(i=>JSON.stringify(s[i])).join("\0");n.has(o)||(n.add(o),r.push(s))}return r}_applyOrderBy(e,t,n,r){const s=[...e],o=new Map,i=new Set,a=new Map;if(r)for(let u=0;u<r.length;u++){const h=w(g(r[u],"ResTarget")??r[u]),f=j(h,"name"),d=g(h,"val");let p=f;if(!p&&d!==null&&d!==void 0&&(p=this._deriveColumnName(w(d))),p&&(o.set(u+1,p),f&&(i.add(f),d!==null&&Y(w(d)))))try{const m=B(w(d));a.set(m,f)}catch{}}const l=t.map(u=>{const h=w(g(u,"SortBy")??u),f=w(g(h,"node")),d=g(h,"sortby_dir"),p=d===2||d==="SORTBY_DESC",m=g(h,"sortby_nulls");let _;m===1||m==="SORTBY_NULLS_FIRST"?_=!0:m===2||m==="SORTBY_NULLS_LAST"?_=!1:_=p;let y=f;if(ye(f)){const x=z(f,[]);if(typeof x=="number"&&Number.isInteger(x)){const v=x,E=o.get(v);E!==void 0&&(y={ColumnRef:{fields:[{String:{sval:E}}]}})}}if(Y(y))try{const x=B(y);a.has(x)&&(y={ColumnRef:{fields:[{String:{sval:a.get(x)}}]}})}catch{}return{node:y,desc:p,nullsFirst:_}});return s.sort((u,h)=>{for(const f of l){const d=n.evaluate(f.node,u),p=n.evaluate(f.node,h),m=d==null,_=p==null;if(m&&_)continue;if(m)return f.nullsFirst?-1:1;if(_)return f.nullsFirst?1:-1;let y;if(typeof d=="string"&&typeof p=="string"?y=d<p?-1:d>p?1:0:y=d-p,y!==0)return f.desc?-y:y}return 0}),s}_evaluateReturning(e,t,n,r){const s={};for(const o of e){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a!=null){const u=w(a);if(et(u)){if(r)for(const f of r.columnNames)s[f]=t[f]??null;else Object.assign(s,t);continue}const h=l||this._deriveColumnName(u);s[h]=n.evaluate(u,t)}}return s}_extractReturningColumns(e,t){const n=[];for(const r of e){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!=null){const a=w(o);if(et(a)){t&&n.push(...t.columnNames);continue}n.push(i||this._deriveColumnName(a))}}return n}_contextForTable(e){if(e===null)return{};const t={};for(const[r,s]of e.vectorIndexes)t[r]=s;const n={};for(const[r,s]of e.spatialIndexes)n[r]=s;return{documentStore:e.documentStore,invertedIndex:e.invertedIndex,vectorIndexes:t,spatialIndexes:n}}static _containsUQAFunction(e){if(Q(e)){const s=ae(e);if(Yr.has(s))return!0}const t=w(g(e,"FuncCall")??{});if(Object.keys(t).length>0){const s=ae(t);if(Yr.has(s))return!0}const n=w(g(e,"A_Expr")??{});if(Object.keys(n).length>0){const s=P(g(n,"name"));if(s.length>0&&J(s[0])==="@@")return!0}for(const s of["lexpr","rexpr","args","arg"]){const o=g(e,s)??g(n,s);if(o!=null){if(Array.isArray(o)){for(const i of o)if(le._containsUQAFunction(w(i)))return!0}else if(typeof o=="object"&&le._containsUQAFunction(w(o)))return!0}}const r=w(g(e,"BoolExpr")??{});if(Object.keys(r).length>0){const s=P(g(r,"args"));for(const o of s)if(le._containsUQAFunction(o))return!0}return!1}_splitUQAConjuncts(e){const t=this._extractAndConjuncts(e),n=[],r=[];for(const i of t)le._containsUQAFunction(i)?n.push(i):r.push(i);const s=n.length===0?null:n.length===1?n[0]:{BoolExpr:{boolop:0,args:n}},o=r.length===0?null:r.length===1?r[0]:{BoolExpr:{boolop:0,args:r}};return[s,o]}_extractAndConjuncts(e){const t=w(g(e,"BoolExpr")??{});if(Object.keys(t).length>0){const n=g(t,"boolop");if(n===0||n==="AND_EXPR"){const r=P(g(t,"args")),s=[];for(const o of r)s.push(...this._extractAndConjuncts(o));return s}}return[e]}_compileWhere(e,t){const n=w(g(e,"BoolExpr")??{});if(Object.keys(n).length>0)return this._compileBoolExpr(n,t);if(jn(e))return this._compileComparison(w(g(e,"A_Expr")??e),t);const r=g(e,"A_Expr");if(r!=null)return this._compileComparison(w(r),t);if(Q(e))return this._compileFuncInWhere(w(g(e,"FuncCall")??e),t);const s=g(e,"FuncCall");if(s!=null)return this._compileFuncInWhere(w(s),t);if(Zr(e))return this._compileNullTest(w(g(e,"NullTest")??e));const o=g(e,"NullTest");if(o!=null)return this._compileNullTest(w(o));if(nn(e))return this._compileSublinkInWhere(w(g(e,"SubLink")??e),t);const i=g(e,"SubLink");return i!=null?this._compileSublinkInWhere(w(i),t):new $n(e,a=>this._compileSelect(a,this._params))}_compileBoolExpr(e,t){const n=g(e,"boolop"),r=P(g(e,"args"));if(n===0||n==="AND_EXPR")return this._compileAnd(r,t);if(n===1||n==="OR_EXPR")return new re(r.map(s=>this._compileWhere(s,t)));if(n===2||n==="NOT_EXPR")return new fe(this._compileWhere(r[0],t));throw new Error(`Unsupported BoolExpr type: ${String(n)}`)}_compileAnd(e,t){const n=[],r=[];for(const o of e){const i=this._compileWhere(o,t);i instanceof G&&i.source===null?r.push(i):n.push(i)}let s;if(n.length>0)s=n.length===1?n[0]:new H(n);else if(r.length>0)s=r.shift();else return new Vn;for(const o of r)s=new G(o.field,o.predicate,s);return s}_compileComparison(e,t){const n=g(e,"kind"),r=P(g(e,"name")),s=r.length>0?J(r[r.length-1]):"";if(n===0||n==="AEXPR_OP"){if(s==="@@"){const a=w(g(e,"lexpr")),l=w(g(e,"rexpr")),u=B(a),h=ee(l,this._params),f=u==="_all"?null:u;return this._makeTextSearchOp(f,h,t,!1)}const o=w(g(e,"lexpr")),i=w(g(e,"rexpr"));if(Y(o)&&(ye(i)||Pt(i))&&["=","!=","<>",">",">=","<","<="].includes(s)){const a=B(o),l=z(i,this._params);return new G(a,es(s,l))}return new $n(e.kind!==void 0?e:{A_Expr:e},a=>this._compileSelect(a,this._params))}if(n===7||n==="AEXPR_IN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=new Set;for(const u of a)l.add(z(u,this._params));return new G(i,new cn(l))}if(n===11||n==="AEXPR_BETWEEN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=Number(z(a[0],this._params)),u=Number(z(a[1],this._params));return new G(i,new un(l,u))}if(n===12||n==="AEXPR_NOT_BETWEEN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=Number(z(a[0],this._params)),u=Number(z(a[1],this._params));return new fe(new G(i,new un(l,u)))}if(n===8||n==="AEXPR_LIKE"){const o=w(g(e,"lexpr")),i=w(g(e,"rexpr")),a=B(o),l=ee(i,this._params);return s==="!~~"?new G(a,new as(l)):new G(a,new Xn(l))}if(n===9||n==="AEXPR_ILIKE"){const o=w(g(e,"lexpr")),i=w(g(e,"rexpr")),a=B(o),l=ee(i,this._params);return s==="!~~*"?new G(a,new ls(l)):new G(a,new Qn(l))}throw new Error(`Unsupported expression kind: ${String(n)}`)}_compileNullTest(e){const t=w(g(e,"arg")),n=B(t),r=g(e,"nulltesttype");return r===0||r==="IS_NULL"?new G(n,new hn):new G(n,new fn)}_compileSublinkInWhere(e,t){const n=g(e,"subLinkType"),r=w(g(e,"subselect")),s=w(g(r,"SelectStmt")??r);if(n===2||n==="ANY_SUBLINK"){const o=this._compileSelect(s,this._params);if(o.columns.length===0)throw new Error("Subquery must return at least one column");const i=o.columns[0],a=new Set;for(const h of o.rows){const f=h[i];f!=null&&a.add(f)}const l=w(g(e,"testexpr")),u=B(l);return new G(u,new cn(a))}if(n===0||n==="EXISTS_SUBLINK")return this._compileSelect(s,this._params).rows.length>0?new Vn:new fe(new Vn);throw new Error(`Unsupported subquery type: ${String(n)}`)}_compileFuncInWhere(e,t){const n=ae(e).toLowerCase(),r=be(e);if(n==="text_match"){const s=B(r[0]),o=ee(r[1],this._params);return this._makeTextSearchOp(s,o,t,!1)}if(n==="bayesian_match"){const s=B(r[0]),o=ee(r[1],this._params);return this._makeTextSearchOp(s,o,t,!0)}return n==="bayesian_match_with_prior"?this._makeBayesianWithPriorOp(r,t):n==="knn_match"?this._makeKnnOp(r):n==="bayesian_knn_match"?this._makeCalibratedKnnOp(r,t,!0):n==="traverse_match"?this._makeTraverseMatchOp(r):n==="temporal_traverse"?this._makeTemporalTraverseOp(r):n==="path_filter"?this._makePathFilterOp(r):n==="vector_exclude"?this._makeVectorExcludeOp(r):n==="spatial_within"?this._makeSpatialWithinOp(r):n==="fuse_log_odds"?this._makeFusionOp(r,t,"log_odds"):n==="fuse_prob_and"?this._makeFusionOp(r,t,"prob_and"):n==="fuse_prob_or"?this._makeFusionOp(r,t,"prob_or"):n==="fuse_prob_not"?this._makeProbNotOp(r,t):n==="fuse_attention"?this._makeAttentionFusionOp(r,t):n==="fuse_multihead"?this._makeMultiheadFusionOp(r,t):n==="fuse_learned"?this._makeLearnedFusionOp(r,t):n==="sparse_threshold"?this._makeSparseThresholdOp(r,t):n==="multi_field_match"?this._makeMultiFieldMatchOp(r):n==="message_passing"?this._makeMessagePassingOp(r):n==="graph_embedding"?this._makeGraphEmbeddingOp(r):n==="staged_retrieval"?this._makeStagedRetrievalOp(r,t):n==="pagerank"?this._makePageRankOp(r):n==="hits"?this._makeHITSOp(r):n==="betweenness"?this._makeBetweennessOp(r):n==="weighted_rpq"?this._makeWeightedRpqOp(r):n==="progressive_fusion"?this._makeProgressiveFusionOp(r,t):n==="deep_fusion"?this._makeDeepFusionOp(r,t):new $n(e,s=>this._compileSelect(s,this._params))}_compileCalibratedSignal(e,t){const n=w(g(e,"FuncCall")??e),r=ae(n).toLowerCase(),s=be(n);if(r==="text_match"||r==="bayesian_match"){const o=B(s[0]),i=ee(s[1],this._params);return this._makeTextSearchOp(o,i,t,!0)}if(r==="knn_match")return this._makeCalibratedKnnOp(s,t,!1);if(r==="bayesian_knn_match")return this._makeCalibratedKnnOp(s,t,!0);if(r==="traverse_match")return this._makeTraverseMatchOp(s);if(r==="spatial_within")return this._makeSpatialWithinOp(s);if(r==="pagerank")return this._makePageRankOp(s);if(r==="hits")return this._makeHITSOp(s);if(r==="betweenness")return this._makeBetweennessOp(s);if(r==="weighted_rpq")return this._makeWeightedRpqOp(s);if(r==="message_passing")return this._makeMessagePassingOp(s);throw new Error(`Unknown signal function for fusion: ${r}. Use text_match, bayesian_match, knn_match, bayesian_knn_match, traverse_match, spatial_within, pagerank, hits, betweenness, or weighted_rpq.`)}_makeTextSearchOp(e,t,n,r){const s=n.invertedIndex;let o=[];s&&(o=(e&&typeof s.getSearchAnalyzer=="function"?s.getSearchAnalyzer(e):s.analyzer).analyze(t));const i=new me(t,e??void 0);if(r)try{const a=s?s.stats:null;if(a){const l=new lt(Ke(),a);return new de(l,i,o,e??void 0)}}catch{}try{const a=s?s.stats:null;if(a){const l=new xt(qt(),a);return new de(l,i,o,e??void 0)}}catch{}return i}_makeMultiFieldMatchOp(e){if(e.length<3)throw new Error("multi_field_match() requires at least 3 arguments: multi_field_match(field1, field2, ..., query)");const t=[];let n=null;const r=[];for(let s=0;s<e.length;s++){const o=e[s];if(Y(o)||g(o,"ColumnRef")!==null)t.push(B(o));else{const i=z(o,this._params);if(typeof i=="string"&&n===null)n=i;else if(typeof i=="number")r.push(i);else if(typeof i=="string")throw new Error(`Unexpected string argument at position ${String(s)}`)}}if(n===null||t.length<2)throw new Error("multi_field_match() requires at least 2 field names and a query string");if(r.length>0&&r.length!==t.length)throw new Error(`Number of weights (${String(r.length)}) must match number of fields (${String(t.length)})`);return new Mn(t,n,r.length>0?r:void 0)}_makeMessagePassingOp(e){const t=e.length>0?ve(e[0],this._params):2,n=e.length>1?ee(e[1],this._params):"mean",r=e.length>2?ee(e[2],this._params):void 0;return new Dn({kLayers:t,aggregation:n,propertyName:r,graph:this._currentGraphName||""})}_makeGraphEmbeddingOp(e){const t=e.length>1?ve(e[1],this._params):2;return new Br({graph:this._currentGraphName||"",kHops:t})}_makeBayesianWithPriorOp(e,t){if(e.length<4)throw new Error("bayesian_match_with_prior() requires 4 arguments: bayesian_match_with_prior(field, query, prior_field, prior_mode)");const n=B(e[0]),r=ee(e[1],this._params),s=ee(e[2],this._params),o=ee(e[3],this._params);if(o!=="recency"&&o!=="authority")throw new Error(`Unknown prior mode: ${o}. Use 'recency' or 'authority'.`);let i;if(o==="recency")try{i=Go(s)}catch{i=h=>.5}else try{i=Bo(s)}catch{i=h=>.5}const a=t.invertedIndex;let l=[];a&&(l=a.analyzer.analyze(r));const u=new me(r,n);try{const h=a?a.stats:null;if(h){const f=new zo(Ke(),h,i);return new vi(u,f,l,n,t.documentStore??null)}}catch{}return u}_makeKnnOp(e){if(e.length!==3)throw new Error("knn_match() requires 3 arguments: knn_match(field, vector, k)");const t=B(e[0]),n=Ue(e[1],this._params),r=ve(e[2],this._params);return new Le(n,r,t)}_makeCalibratedKnnOp(e,t,n){var f;const r=[],s={};for(const d of e){const p=g(d,"NamedArgExpr");if(p!=null){const m=w(p),_=j(m,"name"),y=w(g(m,"arg"));s[_]=z(y,this._params)}else r.push(d)}if(r.length!==3)throw new Error("knn_match() requires 3 positional arguments: knn_match(field, vector, k)");const o=B(r[0]),i=Ue(r[1],this._params),a=ve(r[2],this._params),u=(f=t.vectorIndexes)==null?void 0:f[o];if(u!==null&&typeof u=="object"&&"backgroundStats"in u&&u.backgroundStats!==null||n||Object.keys(s).length>0){const d=new Set(["method","weight_source","bm25_query","bm25_field","base_rate","bandwidth_scale","density_gamma"]),p=Object.keys(s).filter(m=>!d.has(m));if(p.length>0)throw new Error(`Unknown option(s) for bayesian_knn_match: ${p.join(", ")}. Valid options: ${[...d].sort().join(", ")}`);return new fr(i,a,o,s.method??"kde",Number(s.base_rate??.5),s.weight_source??"density_prior",s.bm25_query!=null?String(s.bm25_query):void 0,s.bm25_field!=null?String(s.bm25_field):void 0,Number(s.density_gamma??1),Number(s.bandwidth_scale??1))}return new wi(i,a,o)}_makeSpatialWithinOp(e){if(e.length!==3)throw new Error("spatial_within() requires 3 arguments: spatial_within(field, POINT(x, y), distance)");const t=B(e[0]),[n,r]=this._extractPointArg(e[1]),s=Number(z(e[2],this._params));return new js(t,n,r,s)}_extractPointArg(e){const t=w(g(e,"FuncCall")??{});if(Object.keys(t).length>0){const n=ae(t);if(n!=="point")throw new Error(`Expected POINT(x, y), got ${n}()`);const r=be(t);if(r.length!==2)throw new Error("POINT() requires exactly 2 arguments");const s=Number(z(r[0],this._params)),o=Number(z(r[1],this._params));return[s,o]}if(Pt(e)){const n=z(e,this._params);if(Array.isArray(n)&&n.length===2)return[Number(n[0]),Number(n[1])];throw new Error("Parameter for POINT must be a [x, y] array")}throw new Error("Expected POINT(x, y) or $N parameter")}_makeTraverseMatchOp(e){const t=ve(e[0],this._params),n=e.length>1?ee(e[1],this._params):void 0,r=e.length>2?ve(e[2],this._params):1;return new Fn(t,this._currentGraphName||"",n??null,r)}_makeTemporalTraverseOp(e){if(e.length<4)throw new Error("temporal_traverse() requires at least 4 arguments: temporal_traverse(start, label, hops, timestamp)");const t=ve(e[0],this._params),n=e.length>1?ee(e[1],this._params):void 0,r=e.length>2?ve(e[2],this._params):1;let s;if(e.length===4){const o=Number(z(e[3],this._params));s=new Zt({timestamp:o})}else if(e.length>=5){const o=Number(z(e[3],this._params)),i=Number(z(e[4],this._params));s=new Zt({timeRange:[o,i]})}else s=new Zt;return new Pn({startVertex:t,graph:this._currentGraphName||"",temporalFilter:s,label:n??null,maxHops:r})}_makePathFilterOp(e){if(e.length<2)throw new Error("path_filter() requires at least 2 arguments: path_filter('path', value) or path_filter('path', 'op', value)");const t=ee(e[0],this._params),n=[];for(const o of t.split("."))/^\d+$/.test(o)?n.push(parseInt(o,10)):n.push(o);if(e.length===2){const o=z(e[1],this._params);return new Qt(n,new ln(o))}const r=ee(e[1],this._params),s=z(e[2],this._params);return new Qt(n,es(r,s))}_makeVectorExcludeOp(e){if(e.length!==5)throw new Error("vector_exclude() requires 5 arguments: vector_exclude(field, positive_vector, negative_vector, k, threshold)");const t=B(e[0]),n=Ue(e[1],this._params),r=Ue(e[2],this._params),s=ve(e[3],this._params),o=Number(z(e[4],this._params)),i=new Le(n,s,t);return new En(i,r,o,t)}_makeProbNotOp(e,t){if(e.length!==1)throw new Error("fuse_prob_not() requires exactly 1 signal function argument");const n=this._compileCalibratedSignal(e[0],t);return new Gt(n)}_makeSparseThresholdOp(e,t){if(e.length!==2)throw new Error("sparse_threshold() requires 2 arguments: sparse_threshold(signal, threshold)");const n=this._compileCalibratedSignal(e[0],t),r=Number(z(e[1],this._params));return new Ee(n,r)}_makeFusionOp(e,t,n){const r=[];let s=.5,o=null,i=null;for(const a of e)if(Q(a)||g(a,"FuncCall")!==null)r.push(this._compileCalibratedSignal(a,t));else{const l=g(a,"NamedArgExpr");if(l!=null&&n==="log_odds"){const u=w(l),h=j(u,"name"),f=z(w(g(u,"arg")),this._params);if(h==="alpha")s=Number(f);else if(h==="gating")o=String(f);else if(h==="gating_beta")i=Number(f);else throw new Error(`Unknown option for fuse_log_odds: ${h}. Valid options: alpha, gating, gating_beta`)}else if(ye(a)&&n==="log_odds"){const u=z(a,this._params);typeof u=="string"?o=u:s=Number(u)}else throw new Error("Fusion function arguments must be signal functions (text_match, knn_match, etc.)")}if(r.length<2)throw new Error("Fusion requires at least 2 signal functions");return n==="log_odds"?new Ae(r,s,null,o,i):n==="prob_and"?new je(r,"and"):new je(r,"or")}_makeStagedRetrievalOp(e,t){const n=[];let r=0;for(;r<e.length-1;){if(!Q(e[r])&&g(e[r],"FuncCall")===null)throw new Error(`staged_retrieval: argument ${String(r)} must be a signal function`);const s=this._compileCalibratedSignal(e[r],t);let o=z(e[r+1],this._params);typeof o=="number"&&o===Math.floor(o)&&(o=Math.floor(o)),n.push([s,o]),r+=2}if(n.length===0)throw new Error("staged_retrieval requires at least one (signal, cutoff) pair");return new Ve(n)}_splitCentralityArgs(e){const t=[];let n=this._currentGraphName;for(const r of e){try{const s=z(r,this._params);if(typeof s=="string"){n=s;continue}}catch{}t.push(r)}return[t,n]}_makePageRankOp(e){const[t,n]=this._splitCentralityArgs(e),r=t.length>0?Number(z(t[0],this._params)):.85,s=t.length>1?ve(t[1],this._params):100,o=t.length>2?Number(z(t[2],this._params)):1e-6;return new qr({damping:r,maxIterations:s,tolerance:o,graph:n||""})}_makeHITSOp(e){const[t,n]=this._splitCentralityArgs(e),r=t.length>0?ve(t[0],this._params):100,s=t.length>1?Number(z(t[1],this._params)):1e-6;return new zr({maxIterations:r,tolerance:s,graph:n||""})}_makeBetweennessOp(e){const[,t]=this._splitCentralityArgs(e);return new Gr({graph:t||""})}_makeWeightedRpqOp(e){if(e.length<3)throw new Error("weighted_rpq() requires at least 3 arguments: weighted_rpq('path_expr', start, 'weight_property'[, 'agg_fn'[, threshold]])");const t=ee(e[0],this._params),n=ve(e[1],this._params),r=ee(e[2],this._params),s=e.length>3?ee(e[3],this._params):"sum";let o=null;e.length>4&&(o=Number(z(e[4],this._params)));try{return new $o(Tr(t),this._currentGraphName||"",{startVertex:n,weightProperty:r,aggregation:s,weightThreshold:o})}catch{throw new Error("weighted_rpq() requires the WeightedPathQueryOperator")}}_makeProgressiveFusionOp(e,t){const n=[],r=[];let s=.5,o=null;for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else if(ye(i)||Pt(i)){const a=z(i,this._params);if(typeof a=="string")o=a;else if(typeof a=="number"&&a!==Math.floor(a))s=a;else{const l=Math.floor(Number(a));if(n.length===0)throw new Error("progressive_fusion: k must follow signal functions");r.push([[...n],l]),n.length=0}}else throw new Error("progressive_fusion: unexpected argument type");if(n.length>0)throw new Error("progressive_fusion: trailing signals without k cutoff");if(r.length===0)throw new Error("progressive_fusion requires at least one (signals, k) stage");return new kr(r,s,o)}_makeDeepFusionOp(e,t){const n=[];let r=.5,s="none";for(const o of e){const i=w(g(o,"FuncCall")??(Q(o)?o:{}));if(Object.keys(i).length>0){const l=ae(i).toLowerCase(),u=be(i);if(l==="layer"){const h=[];for(const f of u)if(Q(f)||g(f,"FuncCall")!==null)h.push(this._compileCalibratedSignal(f,t));else throw new Error("layer() arguments must be signal functions");if(h.length===0)throw new Error("layer() requires at least one signal");n.push({type:"signal",signals:h})}else if(l==="propagate"){if(u.length<2)throw new Error("propagate() requires at least 2 arguments: propagate('edge_label', 'aggregation'[, 'direction'])");const h=ee(u[0],this._params),f=ee(u[1],this._params);if(!["mean","sum","max"].includes(f))throw new Error(`propagate() aggregation must be 'mean', 'sum', or 'max', got '${f}'`);let d="both";if(u.length>=3&&(d=ee(u[2],this._params),!["both","out","in"].includes(d)))throw new Error(`propagate() direction must be 'both', 'out', or 'in', got '${d}'`);n.push({type:"propagate",edgeLabel:h,aggregation:f,direction:d})}else if(l==="convolve"){const h=[],f={};for(const _ of u){const y=g(_,"NamedArgExpr");if(y!=null){const x=w(y);f[j(x,"name")]=z(w(g(x,"arg")),this._params)}else h.push(_)}if(h.length===0)throw new Error("convolve() requires edge_label as first argument");const d=ee(h[0],this._params),p=Number(f.n_channels??0),m="both";if(p>1){const _=Number(f.seed??42),y=f.init??"kaiming";let x=1;for(let v=n.length-1;v>=0;v--){const E=n[v];if(E.type==="conv"){const I=E.kernelShape;I&&(x=I[0]);break}}try{const v=Uo(p,x,_,y);n.push({type:"conv",edgeLabel:d,hopWeights:[1],direction:m,kernel:Array.from(v),kernelShape:[p,x]})}catch{n.push({type:"conv",edgeLabel:d,hopWeights:[1],direction:m})}}else{if(h.length<2)throw new Error("convolve() requires ARRAY[w0, w1, ...] or n_channels => N");const _=Ue(h[1],this._params);n.push({type:"conv",edgeLabel:d,hopWeights:Array.from(_),direction:m})}}else if(l==="pool"){if(u.length<3)throw new Error("pool() requires at least 3 arguments: pool('edge_label', 'method', pool_size[, 'direction'])");const h=ee(u[0],this._params),f=ee(u[1],this._params);if(!["max","avg"].includes(f))throw new Error(`pool() method must be 'max' or 'avg', got '${f}'`);const d=ve(u[2],this._params);let p="both";if(u.length>=4&&(p=ee(u[3],this._params),!["both","out","in"].includes(p)))throw new Error(`pool() direction must be 'both', 'out', or 'in', got '${p}'`);n.push({type:"pool",edgeLabel:h,poolSize:d,method:f,direction:p})}else if(l==="dense"){const h=[],f={};for(const y of u){const x=g(y,"NamedArgExpr");if(x!=null){const v=w(x);f[j(v,"name")]=Number(z(w(g(v,"arg")),this._params))}else h.push(y)}if(h.length<2)throw new Error("dense() requires at least 2 positional arguments: ARRAY[weights], ARRAY[bias]");const d=Ue(h[0],this._params),p=Ue(h[1],this._params),m=f.output_channels,_=f.input_channels;if(m===void 0||_===void 0)throw new Error("dense() requires output_channels and input_channels named arguments");if(d.length!==m*_)throw new Error(`dense() weights array length (${String(d.length)}) must equal output_channels * input_channels (${String(m*_)})`);if(p.length!==m)throw new Error(`dense() bias array length (${String(p.length)}) must equal output_channels (${String(m)})`);n.push({type:"dense",weights:Array.from(d),bias:Array.from(p),outputChannels:m,inputChannels:_})}else if(l==="flatten")n.push({type:"flatten"});else if(l==="softmax")n.push({type:"softmax"});else if(l==="batch_norm"){let h=1e-5;for(const f of u){const d=g(f,"NamedArgExpr");if(d!=null){const p=w(d);j(p,"name")==="epsilon"&&(h=Number(z(w(g(p,"arg")),this._params)))}}n.push({type:"batchNorm",epsilon:h})}else if(l==="dropout"){if(u.length<1)throw new Error("dropout() requires 1 argument: dropout(p)");const h=Number(z(u[0],this._params));n.push({type:"dropout",p:h})}else if(l==="attention"){let h=1,f="content";for(const d of u){const p=g(d,"NamedArgExpr");if(p!=null){const m=w(p),_=j(m,"name");_==="n_heads"?h=Number(z(w(g(m,"arg")),this._params)):_==="mode"&&(f=String(z(w(g(m,"arg")),this._params)))}}n.push({type:"attention",nHeads:h,mode:f})}else if(l==="embed"){const h=[],f={};for(const y of u){const x=g(y,"NamedArgExpr");if(x!=null){const v=w(x);f[j(v,"name")]=Number(z(w(g(v,"arg")),this._params))}else h.push(y)}if(h.length===0)throw new Error("embed() requires vector argument");const d=Ue(h[0],this._params),p=f.in_channels??1;let m,_;if(f.grid_h!==void 0&&f.grid_w!==void 0)m=f.grid_h,_=f.grid_w;else{const y=Math.floor(Math.sqrt(d.length/p));y*y*p===d.length?(m=y,_=y):(m=0,_=0)}n.push({type:"embed",embedding:Array.from(d),gridH:m,gridW:_,inChannels:p})}else if(l==="global_pool"){let h="avg";for(const f of u){const d=g(f,"NamedArgExpr");if(d!=null){const p=w(d);j(p,"name")==="method"&&(h=String(z(w(g(p,"arg")),this._params)))}else h=ee(f,this._params)}if(!["avg","max","avg_max"].includes(h))throw new Error(`global_pool() method must be 'avg', 'max', or 'avg_max', got '${h}'`);n.push({type:"globalPool",method:h})}else throw new Error(`deep_fusion() unknown layer function: ${l}()`);continue}const a=g(o,"NamedArgExpr");if(a!=null){const l=w(a),u=j(l,"name"),h=z(w(g(l,"arg")),this._params);if(u==="alpha")r=Number(h);else if(u==="gating")s=String(h);else throw new Error(`Unknown option for deep_fusion: ${u}. Valid options: alpha, gating`);continue}throw new Error("deep_fusion() arguments must be layer() or propagate() calls")}if(n.length===0)throw new Error("deep_fusion requires at least one layer");return new _e(n,r,s,this._currentGraphName||void 0)}_makeAttentionFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_attention requires at least 2 signals");const s=new Set(["normalized","alpha","base_rate"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_attention: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=n.length,a=new Wr(i,6,Number(r.alpha??.5),!!(r.normalized??!1),r.base_rate??void 0),l=this._extractQueryFeatures(e,t);return new dt(n,a,l)}catch{return new Ae(n,Number(r.alpha??.5))}}_makeMultiheadFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_multihead requires at least 2 signals");const s=new Set(["n_heads","normalized","alpha"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_multihead: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=n.length,a=new Wo(i,Number(r.n_heads??4),6,Number(r.alpha??.5),!!(r.normalized??!1)),l=this._extractQueryFeatures(e,t);return new dt(n,a,l)}catch{return new Ae(n,Number(r.alpha??.5))}}_makeLearnedFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_learned requires at least 2 signals");const s=new Set(["alpha"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_learned: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=new Hr(n.length,Number(r.alpha??.5));return new kt(n,i)}catch{return new Ae(n,Number(r.alpha??.5))}}_extractQueryFeatures(e,t){const n=new Float64Array(6);if(t.invertedIndex)try{const r=new Ho(t.invertedIndex);for(const s of e){const o=w(g(s,"FuncCall")??(Q(s)?s:{}));if(Object.keys(o).length>0){const i=ae(o);if(i==="text_match"||i==="bayesian_match"){const a=be(o);if(a.length>=2){const l=ee(a[1],this._params),h=t.invertedIndex.analyzer.analyze(l);return r.extract(h)}}}}}catch{}return n}_foldStmtWhere(e){const t=g(e,"whereClause");if(t==null)return e;const n=this._foldConstants(w(t));return n===t?e:{...e,whereClause:n}}_foldConstants(e){return Object.keys(e).length===0||ye(e)||g(e,"A_Const")!==null||Y(e)||g(e,"ColumnRef")!==null?e:jn(e)||g(e,"A_Expr")!==null?this._foldAExpr(e):mi(e)||g(e,"BoolExpr")!==null?this._foldBoolExpr(e):Q(e)||g(e,"FuncCall")!==null?this._foldFuncCall(e):e}_foldAExpr(e){const t=w(g(e,"A_Expr")??e),n=this._foldConstants(w(g(t,"lexpr")??{})),r=this._foldConstants(w(g(t,"rexpr")??{}));if((ye(n)||g(n,"A_Const")!==null)&&(ye(r)||g(r,"A_Const")!==null))try{const s=new oe({params:this._params}),o={A_Expr:{...t,lexpr:n,rexpr:r}},i=s.evaluate(o,{});return ts(i)}catch{}if(n!==g(t,"lexpr")||r!==g(t,"rexpr")){const s={...t,lexpr:n,rexpr:r};return g(e,"A_Expr")!==null?{A_Expr:s}:s}return e}_foldBoolExpr(e){const t=w(g(e,"BoolExpr")??e),n=g(t,"boolop"),r=P(g(t,"args")),s=r.map(a=>this._foldConstants(a));if(s.every(a=>ye(a)||g(a,"A_Const")!==null))try{const a=new oe({params:this._params}),l={BoolExpr:{boolop:n,args:s}},u=a.evaluate(l,{});return ts(u)}catch{}if(n===0||n==="AND_EXPR"){const a=[];for(const u of s){if(ye(u)||g(u,"A_Const")!==null){if(ns(u)===!1)return{A_Const:{boolval:!1}};continue}a.push(u)}if(a.length===0)return{A_Const:{boolval:!0}};if(a.length===1)return a[0];const l={boolop:0,args:a};return g(e,"BoolExpr")!==null?{BoolExpr:l}:l}if(n===1||n==="OR_EXPR"){const a=[];for(const u of s){if(ye(u)||g(u,"A_Const")!==null){if(ns(u)===!0)return{A_Const:{boolval:!0}};continue}a.push(u)}if(a.length===0)return{A_Const:{boolval:!1}};if(a.length===1)return a[0];const l={boolop:1,args:a};return g(e,"BoolExpr")!==null?{BoolExpr:l}:l}if(s.some((a,l)=>a!==r[l])){const a={boolop:n,args:s};return g(e,"BoolExpr")!==null?{BoolExpr:a}:a}return e}_foldFuncCall(e){const t=w(g(e,"FuncCall")??e),n=ae(t);if(di.has(n))return e;const r=P(g(t,"args"));if(r.length===0)return e;const s=r.map(i=>this._foldConstants(i));if(s.some((i,a)=>i!==r[a])){const i={...t,args:s};return g(e,"FuncCall")!==null?{FuncCall:i}:i}return e}_optimize(e,t,n){try{const r=t.invertedIndex;if(!r)return e;const s=r.stats,o=n?n._stats:null,i=n?n.name:void 0;return new Re(s,{columnStats:o,indexManager:t.indexManager??void 0,tableName:i}).optimize(e)}catch{return e}}_executePlan(e,t){try{return new tn(t).execute(e)}catch{return e.execute(t)}}_explainPlan(e,t){try{const o=new tn(t).explain(e).split(`
15
- `).map(i=>({plan:i}));return{columns:["plan"],rows:o}}catch{return{columns:["plan"],rows:[{plan:e.constructor.name}]}}}_scanAll(e,t){if(!e.documentStore)return new D([ce(0,{score:0})]);let r=[...e.documentStore.docIds].sort((s,o)=>s-o);return t!==void 0&&t<r.length&&(r=r.slice(0,t)),new D(r.map(s=>ce(s,{score:0})))}_chainOnSource(e,t){return e instanceof G&&e.source===null?new G(e.field,e.predicate,t):new H([t,e])}static _isGraphOperator(e){if(e==null)return!1;const t=e.constructor.name;return["TraverseOperator","RegularPathQueryOperator","PatternMatchOperator","TemporalTraverseOperator","TemporalPatternMatchOperator","CypherQueryOperator"].includes(t)}static _isJoinOperator(e){if(e==null)return!1;const t=e.constructor.name;return["InnerJoinOperator","OuterJoinOperator","CrossJoinOperator","IndexJoinOperator","SortMergeJoinOperator","ExprJoinOperator","LateralJoinOperator","TableScanOperator"].includes(t)}_collectJoinTables(e){const t=[];for(const n of e)this._walkFromForTables(n,t);return t}_walkFromForTables(e,t){const n=w(g(e,"RangeVar")??{});if(Object.keys(n).length>0){const o=ie(n),i=Be(n)??o,a=this._tables.get(o);a&&t.push([i,a.columnNames]);return}const r=w(g(e,"JoinExpr")??{});if(Object.keys(r).length>0){const o=g(r,"larg"),i=g(r,"rarg");o!=null&&this._walkFromForTables(w(o),t),i!=null&&this._walkFromForTables(w(i),t);return}const s=w(g(e,"RangeSubselect")??{});if(Object.keys(s).length>0){const o=Be(s)??"_derived",i=this._tables.get(o);i&&t.push([o,i.columnNames])}}_applyDeferredWhere(e,t,n){return e.filter(r=>n.evaluate(t,r)===!0)}static _collectAstTableRefs(e){const t=new Set;return le._walkAstForTables(e,t),t}static _walkAstForTables(e,t){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(const o of e)le._walkAstForTables(o,t);return}const n=e,r=n.RangeVar;if(r!==void 0){const o=j(r,"schemaname");if(o!=="information_schema"&&o!=="pg_catalog"){const i=j(r,"relname");i&&t.add(i)}return}const s=n.relname;if(typeof s=="string"&&s){const o=n.schemaname;o!=="information_schema"&&o!=="pg_catalog"&&t.add(s)}for(const o of Object.values(n))o!==null&&typeof o=="object"&&le._walkAstForTables(o,t)}_partitionWhereForJoins(e,t){const n=this._extractAndConjuncts(e),r=new Map,s=[];for(const i of n){const a=le._collectConjunctAliases(i);if(a.size===1){const l=a.values().next().value;if(t.has(l)){r.has(l)||r.set(l,[]),r.get(l).push(i);continue}}s.push(i)}const o=le._reconstructAnd(s);return[r,o]}static _collectConjunctAliases(e){const t=new Set;return le._walkForColumnAliases(e,t),t}static _walkForColumnAliases(e,t){const n=w(g(e,"ColumnRef")??{});if(Object.keys(n).length>0){const o=P(g(n,"fields"));if(o.length>=2){const i=o[0],a=J(i);a&&t.add(a)}return}if(Y(e)){const o=P(g(w(g(e,"ColumnRef")??e),"fields"));if(o.length>=2){const i=o[0],a=J(i);a&&t.add(a)}return}for(const o of["lexpr","rexpr","args","arg","xpr","val"]){const i=g(e,o);if(i!=null)if(Array.isArray(i))for(const a of i)typeof a=="object"&&le._walkForColumnAliases(a,t);else typeof i=="object"&&le._walkForColumnAliases(i,t)}const r=w(g(e,"BoolExpr")??{});if(Object.keys(r).length>0){const o=P(g(r,"args"));for(const i of o)le._walkForColumnAliases(i,t)}const s=w(g(e,"A_Expr")??{});if(Object.keys(s).length>0){const o=g(s,"lexpr"),i=g(s,"rexpr");o!==null&&typeof o=="object"&&le._walkForColumnAliases(o,t),i!==null&&typeof i=="object"&&le._walkForColumnAliases(i,t)}}static _reconstructAnd(e){return e.length===0?null:e.length===1?e[0]:{BoolExpr:{boolop:0,args:e}}}_extractImplicitEquijoinPredicates(e,t){const n=[],r=w(g(e,"BoolExpr")??{});let s;if(Object.keys(r).length>0){const o=g(r,"boolop");o===0||o==="AND_EXPR"?s=P(g(r,"args")):s=[e]}else s=[e];for(const o of s){const i=w(g(o,"A_Expr")??{});if(Object.keys(i).length===0)continue;const a=P(g(i,"name"));if(a.length===0||J(a[a.length-1])!=="=")continue;const u=g(i,"lexpr"),h=g(i,"rexpr");if(u===null||h===null||!Y(w(u))||!Y(w(h)))continue;const f=w(g(w(u),"ColumnRef")??w(u)),d=w(g(w(h),"ColumnRef")??w(h)),p=P(g(f,"fields")),m=P(g(d,"fields"));if(p.length<2||m.length<2)continue;const _=J(p[0]),y=J(p[p.length-1]),x=J(m[0]),v=J(m[m.length-1]);!_||!y||!x||!v||!t.has(_)||!t.has(x)||n.push({leftAlias:_,leftCol:y,rightAlias:x,rightCol:v})}return n}_registerFkValidators(e,t,n){for(const r of n){const s=r.refTable,o=r.column,i=r.refColumn;t.fkInsertValidators.push(l=>{const u=l[o];if(u==null)return;const h=this._tables.get(s);if(!h)throw new Error(`Foreign key violation: parent table "${s}" does not exist`);if(!h.documentStore.hasValue(i,u))throw new Error(`Foreign key violation: ${e}.${o} = ${JSON.stringify(u)} not found in ${s}.${i}`)}),t.fkUpdateValidators.push((l,u)=>{const h=u[o];if(h==null)return;const f=this._tables.get(s);if(!f)throw new Error(`FOREIGN KEY constraint violated: parent table "${s}" does not exist`);if(!f.documentStore.hasValue(i,h))throw new Error(`FOREIGN KEY constraint violated: ${e}.${o} = ${JSON.stringify(h)} not found in ${s}.${i}`)});const a=this._tables.get(s);if(a){const l=e,u=t;a.fkDeleteValidators.push(h=>{const f=a.documentStore.get(h);if(!f)return;const d=f[i];if(d!=null&&u.documentStore.hasValue(o,d))throw new Error(`FOREIGN KEY constraint violated: row in "${s}" is still referenced from "${l}"`)}),a.fkUpdateValidators.push((h,f)=>{const d=h[i],p=f[i];if(d!==p&&d!=null&&u.documentStore.hasValue(o,d))throw new Error(`FOREIGN KEY constraint violated: row in "${s}" is still referenced from "${l}"`)})}}}_isPushablePredicate(e,t){const n=g(e,"A_Expr");if(n!=null){const s=w(n),o=g(s,"lexpr"),i=g(s,"rexpr");if(o!==null&&Y(w(o)))try{const a=B(w(o));if(!t.has(a))return!1}catch{return!1}else return!1;if(i!==null){const a=w(i);if(!ye(a)&&!Pt(a))return!1}return!0}const r=g(e,"NullTest");if(r!=null){const s=w(r),o=g(s,"arg");if(o!==null&&Y(w(o)))try{const i=B(w(o));return t.has(i)}catch{return!1}}return!1}_tryPredicatePushdown(e,t){const n=g(e,"whereClause");if(n==null)return e;const r=P(g(e,"fromClause"));if(r.length!==1)return e;const s=r[0];let o=null;const i=w(g(s,"RangeVar")??{}),a=w(g(s,"RangeSubselect")??{});if(Object.keys(i).length>0){const p=ie(i);this._views.has(p)?o=this._views.get(p):this._inlinedCTEs.has(p)&&(o=this._inlinedCTEs.get(p))}else if(Object.keys(a).length>0){const p=g(a,"subquery");p!=null&&(o=w(g(w(p),"SelectStmt")??p))}if(o===null||g(o,"groupClause")!==null&&P(g(o,"groupClause")).length>0||g(o,"distinctClause")!==null&&g(o,"distinctClause")!==void 0||g(o,"limitCount")!==null&&g(o,"limitCount")!==void 0)return e;const l=P(g(o,"targetList"));for(const p of l){const m=w(g(p,"ResTarget")??p),_=g(m,"val");if(_!=null&&Q(w(_))&&nt(w(_)))return e}if(this._hasAggregates(l))return e;const u=new Set;for(const p of l){const m=w(g(p,"ResTarget")??p),_=j(m,"name");if(_)u.add(_);else{const y=g(m,"val");if(y!==null&&Y(w(y)))try{u.add(B(w(y)))}catch{}}}if(u.size===0)return e;const[h,f]=this._splitPushable(w(n),u);if(h.length===0)return e;const d=h.length===1?h[0]:{BoolExpr:{boolop:0,args:h}};if(Object.keys(i).length>0){const p=ie(i);this._views.has(p)?this._views.set(p,le._injectWhere(this._views.get(p),d)):this._inlinedCTEs.has(p)&&this._inlinedCTEs.set(p,le._injectWhere(this._inlinedCTEs.get(p),d))}return{...e,whereClause:f}}_splitPushable(e,t){const n=w(g(e,"BoolExpr")??{});if(Object.keys(n).length>0){const r=g(n,"boolop");if(r===0||r==="AND_EXPR"){const s=P(g(n,"args")),o=[],i=[];for(const l of s)this._isPushablePredicate(l,t)?o.push(l):i.push(l);let a=null;return i.length===1?a=i[0]:i.length>1&&(a={BoolExpr:{boolop:0,args:i}}),[o,a]}}return this._isPushablePredicate(e,t)?[[e],null]:[[],e]}static _injectWhere(e,t){const n=g(e,"whereClause");let r;return n==null?r=t:r={BoolExpr:{boolop:0,args:[n,t]}},{...e,whereClause:r}}_extractNumericValue(e){const t=z(e,this._params);if(typeof t=="number")return t;if(typeof t=="string"){const n=Number(t);if(!isNaN(n))return n}throw new Error("Expected numeric constant or $N parameter, got "+JSON.stringify(e).slice(0,200))}static _isSelectStar(e){if(e.length===0)return!0;for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&et(w(r)))return!0}return!1}static _hasComputedExpressions(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r==null)continue;const s=w(r);if(!Y(s)){if(Q(s)){const o=ae(s);if(Ze.has(o)||o==="text_match"||o==="bayesian_match"||o==="bayesian_match_with_prior"||o==="knn_match"||o==="bayesian_knn_match"||o==="traverse_match"||o==="spatial_within")continue;return!0}if(ye(s)||jn(s)||g(s,"A_Expr")!==null||g(s,"CaseExpr")!==null||rn(s)||g(s,"CoalesceExpr")!==null||Zr(s)||nn(s)||g(s,"SubLink")!==null)return!0}}return!1}_inferTargetName(e){const t=w(g(e,"ResTarget")??e),n=j(t,"name");if(n)return n;const r=g(t,"val");if(r==null)return"?column?";const s=w(r);if(Y(s))try{return B(s)}catch{return"?column?"}if(Q(s)){const o=ae(s);if(Ze.has(o)){if(tt(s))return o;const i=be(s);if(i.length>0&&Y(i[0]))try{const a=B(i[0]);return`${o}_${a}`}catch{return o}return o}return o==="text_match"||o==="bayesian_match"||o==="bayesian_match_with_prior"?"_score":o}if(rn(s)){const o=w(g(s,"TypeCast")??s),i=g(o,"arg");if(i!==null&&Y(w(i)))try{return B(w(i))}catch{}}return"?column?"}_buildExprTargets(e){const t=[];for(const n of e){const r=w(g(n,"ResTarget")??n),s=this._inferTargetName(n);let o=g(r,"val");if(o==null)continue;const i=w(o);if(Q(i)){const a=ae(i);(a==="text_match"||a==="bayesian_match"||a==="bayesian_match_with_prior")&&(o={ColumnRef:{fields:[{String:{sval:"_score"}}]}})}t.push([s,w(o)])}return t}_sortNeedsExtraCols(e,t){const n=new Set;for(const r of t){const s=w(g(r,"ResTarget")??r),o=g(s,"val");if(o!=null&&et(w(o)))return!1;if(o!==null&&Y(w(o))){try{n.add(B(w(o)))}catch{}const i=j(s,"name");i&&n.add(i)}else{const i=j(s,"name");i&&n.add(i)}}for(const r of e){const s=w(g(r,"SortBy")??r),o=w(g(s,"node"));if(Y(o))try{const i=B(o);if(!n.has(i))return!0}catch{}}return!1}_buildGroupAliases(e,t){const n=new Map;for(const r of t){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!==null&&Y(w(o))&&i)try{const a=B(w(o));e.includes(a)&&n.set(a,i)}catch{}}return n}_buildPostGroupTargets(e,t,n){let r=!1;for(const i of e){const a=w(g(i,"ResTarget")??i),l=g(a,"val");if(l==null)continue;const u=w(l);if(Q(u)){const h=ae(u);if(!Ze.has(h)||nt(u)){r=!0;break}}else if(!Y(u)){const h=j(a,"name")||"?column?";if(!n.has(h)){r=!0;break}}}if(!r)return null;const s=new Set(t),o=[];for(const i of e){const a=w(g(i,"ResTarget")??i),l=j(a,"name")||this._inferTargetName(i);if(n.has(l)||s.has(l))o.push([l,{ColumnRef:{fields:[{String:{sval:l}}]}}]);else{const u=g(a,"val");if(u!==null&&Y(w(u)))try{const h=B(w(u));o.push([l,{ColumnRef:{fields:[{String:{sval:h}}]}}])}catch{o.push([l,w(u)])}else o.push([l,w(u??{})])}}return o}_buildPreAggTargets(e,t,n,r){const s=[];for(let i=0;i<e.length;i++){const a=e[i];(Q(a)||g(a,"FuncCall")!==null)&&i<t.length&&s.push([t[i],a])}for(const i of n)i.inputExpr!==void 0&&s.push(["_agg_expr",i.inputExpr]);if(s.length===0)return null;const o=[];if(r)for(const i of r.columnNames)o.push([i,{ColumnRef:{fields:[{String:{sval:i}}]}}]);for(const[i,a]of s)o.push([i,a]);return o}_resolveGroupByCols(e,t){const n=new Map,r=[];for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a!==null&&Y(w(a)))try{const u=B(w(a));r.push(l||u),l&&n.set(l,u)}catch{r.push(l||"?column?")}else if(a!==null&&Q(w(a))){const u=ae(w(a));let h;if(tt(w(a)))h=u;else{const f=be(w(a));let d=null;for(const p of f)if(Y(p))try{d=B(p)}catch{}h=d!==null?`${u}_${d}`:u}r.push(l||h)}else r.push(l||"?column?")}const s=[];for(const o of e){if(ye(o)){const i=z(o,[]);if(typeof i=="number"&&Number.isInteger(i)){const a=i-1;if(a>=0&&a<r.length){s.push(r[a]);continue}throw new Error(`GROUP BY position ${String(i)} is not in select list`)}}if(Y(o))try{const i=B(o);s.push(n.get(i)??i);continue}catch{}if(Q(o)||g(o,"FuncCall")!==null){const i=ae(o);let a=null;for(const l of t){const u=w(g(l,"ResTarget")??l),h=g(u,"val"),f=j(u,"name");if(h!==null&&Q(w(h))&&ae(w(h))===i&&f){a=f;break}}if(a!==null)s.push(a);else{const l=be(o);let u=null;for(const h of l)if(Y(h))try{u=B(h)}catch{}s.push(u!==null?`${i}_${u}`:i)}continue}try{s.push(B(o))}catch{s.push("?column?")}}return s}_getTable(e){const t=this._tables.get(e);if(!t)throw new Error(`Table "${e}" does not exist`);return t}_substituteParams(e,t){const n=g(e,"ParamRef");if(n!=null){const o=w(n).number,i=t.get(o);return i!==void 0?i:e}const r={};for(const[s,o]of Object.entries(e))Array.isArray(o)?r[s]=o.map(i=>i!==null&&typeof i=="object"?this._substituteParams(i,t):i):o!==null&&typeof o=="object"?r[s]=this._substituteParams(o,t):r[s]=o;return r}_hasOuterRefs(e,t){if(Y(e))try{const n=B(e);if(t.has(n))return!0;const r=gi(e);if(t.has(r))return!0}catch{}for(const n of Object.values(e))if(Array.isArray(n)){for(const r of n)if(r!==null&&typeof r=="object"&&this._hasOuterRefs(r,t))return!0}else if(n!==null&&typeof n=="object"&&this._hasOuterRefs(n,t))return!0;return!1}_buildSortKeys(e,t){const n=new Map,r=new Set,s=new Map;for(let i=0;i<t.length;i++){const a=w(g(t[i],"ResTarget")??t[i]),l=g(a,"val"),u=j(a,"name");if(l!=null&&!et(w(l))){let h;try{h=u||this._deriveColumnName(w(l))}catch{h=u||"?column?"}if(n.set(i+1,h),u&&(r.add(u),Y(w(l))))try{const f=B(w(l));s.set(f,u)}catch{}}}const o=[];for(const i of e){const a=w(g(i,"SortBy")??i),l=w(g(a,"node")),u=g(a,"sortby_dir"),h=u===2||u==="SORTBY_DESC"||String(u).includes("DESC"),f=!h,d=g(a,"sortby_nulls");let p;d===1||d==="SORTBY_NULLS_FIRST"||String(d).includes("FIRST")?p=!0:d===2||d==="SORTBY_NULLS_LAST"||String(d).includes("LAST")?p=!1:p=h;let m;if(ye(l)){const _=Number(z(l,this._params)),y=n.get(_);if(!y)throw new Error(`ORDER BY position ${String(_)} is not in select list`);m=y}else{try{m=B(l)}catch{m=this._deriveColumnName(l)}!r.has(m)&&s.has(m)&&(m=s.get(m))}o.push({column:m,ascending:f,nullsFirst:p})}return o}}class Vn extends q{execute(e){const t=e.documentStore;if(!t)return new D;const n=[...t.docIds].sort((r,s)=>r-s);return new D(n.map(r=>ce(r,{score:0})))}costEstimate(e){return e.totalDocs}}class $n extends q{constructor(t,n=null){super();b(this,"exprNode");b(this,"_subqueryExecutor");this.exprNode=t,this._subqueryExecutor=n}execute(t){const n=new oe,r=t.documentStore;if(!r)return new D;const s=[];for(const o of[...r.docIds].sort((i,a)=>i-a)){const i=r.get(o);if(!i)continue;n.evaluate(this.exprNode,i)&&s.push(ce(o,{score:0}))}return new D(s)}costEstimate(t){return t.totalDocs}}class vi extends q{constructor(t,n,r,s,o){super();b(this,"source");b(this,"scorer");b(this,"terms");b(this,"field");b(this,"documentStore");this.source=t,this.scorer=n,this.terms=r,this.field=s,this.documentStore=o}execute(t){const n=this.source.execute(t),r=this.documentStore??t.documentStore,s=t.invertedIndex,o=[],i=this.scorer;for(const a of n){const l=a.docId,u=(r==null?void 0:r.get(l))??{},h=a.payload.positions.length>0?a.payload.positions.length:1,f=this.field??"_default";let d=h;s&&typeof s.getDocLength=="function"&&(d=s.getDocLength(l,f));const m=n.length,_=i.scoreWithPrior(h,d,m,u);o.push(ce(l,{score:_}))}return new D(o)}costEstimate(t){return this.source.costEstimate(t)*1.1}}class wi extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"k");b(this,"field");this.queryVector=t,this.k=n,this.field=r}execute(t){var o;const n=(o=t.vectorIndexes)==null?void 0:o[this.field];let r;n?r=n.searchKnn(this.queryVector,this.k):r=new Le(this.queryVector,this.k,this.field).execute(t);const s=[];for(const i of r)s.push(ce(i.docId,{score:(1+i.payload.score)/2}));return new D(s)}costEstimate(t){return(t.dimensions||128)*Math.log2(t.totalDocs+1)}}function es(c,e){switch(c){case"=":return new ln(e);case"!=":case"<>":return new Un(e);case">":return new Wn(Number(e));case">=":return new Hn(Number(e));case"<":return new Kn(Number(e));case"<=":return new Jn(Number(e));default:throw new Error(`Unsupported operator: ${c}`)}}function ts(c){if(c==null)return{A_Const:{isnull:!0}};if(typeof c=="boolean")return{A_Const:{boolval:c}};if(typeof c=="number")return Number.isInteger(c)?{A_Const:{ival:c}}:{A_Const:{fval:String(c)}};if(typeof c=="string")return{A_Const:{sval:c}};throw new Error(`Cannot convert ${typeof c} to A_Const`)}function ns(c){const e=w(g(c,"A_Const")??c);if(g(e,"isnull")===!0)return null;const t=g(e,"boolval");if(t!=null)return!!t;const n=g(e,"ival");if(n!=null)return Number(n)!==0;const r=g(e,"fval");if(r!=null)return parseFloat(String(r))!==0;const s=g(e,"sval");return s!=null?String(s).length>0:null}function rs(c){return"docIds"in c?c.docIds[0]:c.docId}class xi{constructor(e,t,n){b(this,"left");b(this,"right");b(this,"condition");this.left=e,this.right=t,this.condition=n}_getEntries(e,t){return e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function"?[...e.execute(t).entries]:e}}class Si extends xi{execute(e){const t=this._getEntries(this.left,e),n=this._getEntries(this.right,e),r=t.length<=n.length,s=r?t:n,o=r?n:t,i=r?this.condition.leftField:this.condition.rightField,a=r?this.condition.rightField:this.condition.leftField,l=new Map;for(const h of s){const f=h.payload.fields[i];if(f==null)continue;let d=l.get(f);d||(d=[],l.set(f,d)),d.push(h)}const u=[];for(const h of o){const f=h.payload.fields[a];if(f==null)continue;const d=l.get(f);if(d)for(const p of d){const m=r?p:h,_=r?h:p,y=rs(m),x=rs(_);u.push({docIds:[y,x],payload:U({score:m.payload.score+_.payload.score,fields:{...m.payload.fields,..._.payload.fields}})})}}return new we(u)}}class sn{constructor(e){b(this,"value");this.value=e}}class qn{constructor(e){b(this,"counts");this.counts=e}}class te{constructor(e,t){b(this,"_engine");b(this,"_table");b(this,"_root");this._engine=e,this._table=t,this._root=null}term(e,t){const n=new me(e,t);return this._chain(n)}vector(e,t,n){const r=new xe(e,t,n??"embedding");return this._chain(r)}knn(e,t,n){const r=new Le(e,t,n??"embedding");return this._chain(r)}bayesianKnn(e,t,n="embedding",r){const s=new fr(e,t,n,(r==null?void 0:r.estimationMethod)??"kde",(r==null?void 0:r.baseRate)??.5,(r==null?void 0:r.weightSource)??"density_prior",(r==null?void 0:r.bm25Query)??null,(r==null?void 0:r.bm25Field)??null,(r==null?void 0:r.densityGamma)??1,(r==null?void 0:r.bandwidthScale)??1);return this._chain(s)}and(e){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before combining");const t=new H([this._root,e._root]),n=new te(this._engine,this._table);return n._root=t,n}or(e){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before combining");const t=new re([this._root,e._root]),n=new te(this._engine,this._table);return n._root=t,n}not(){if(this._root===null)throw new Error("Builder must have an operator before negation");const e=new fe(this._root),t=new te(this._engine,this._table);return t._root=e,t}filter(e,t){if(e.includes(".")){const s=[];for(const a of e.split("."))/^\d+$/.test(a)?s.push(parseInt(a,10)):s.push(a);const o=new Qt(s,t,this._root),i=new te(this._engine,this._table);return i._root=o,i}const n=new G(e,t,this._root),r=new te(this._engine,this._table);return r._root=n,r}join(e,t,n){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before joining");const r={leftField:t,rightField:n},s=new Si(this._root,e._root,r),o=new te(this._engine,this._table);return o._root=s,o}vectorJoin(e,t,n,r){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before joining");const s=new Kr(this._root,e._root,t,n,r),o=new te(this._engine,this._table);return o._root=s,o}traverse(e,t,n=1){const r=new Fn(e,this._table,t??null,n);return this._chain(r)}temporalTraverse(e,t,n=1,r){const s=new Pn({startVertex:e,graph:this._table,temporalFilter:new Zt({timestamp:(r==null?void 0:r.timestamp)??null,timeRange:(r==null?void 0:r.timeRange)??null}),label:t??null,maxHops:n});return this._chain(s)}matchPattern(e){const t=new Dr(e,this._table);return this._chain(t)}rpq(e,t){const n=Tr(e),r=new Vr(n,this._table,t??null);return this._chain(r)}vertexAggregate(e,t="sum"){if(this._root===null)throw new Error("vertexAggregate requires a graph traversal source");const n={sum:i=>i.reduce((a,l)=>a+l,0),avg:i=>i.length>0?i.reduce((a,l)=>a+l,0)/i.length:0,min:i=>i.length>0?Math.min(...i):0,max:i=>i.length>0?Math.max(...i):0,count:i=>i.length},r=new $r(this._root,e,n[t]),s=this._engine._contextForTable(this._table),o=r.execute(s);if(o.length>0){const i=o.entries[0];return new sn(i.payload.fields._vertex_agg_result)}return new sn(0)}vectorExclude(e,t){if(this._root===null)throw new Error("vectorExclude requires a source query");const n=new En(this._root,e,t),r=new te(this._engine,this._table);return r._root=n,r}sparseThreshold(e){if(this._root===null)throw new Error("sparseThreshold requires a source query");const t=new Ee(this._root,e),n=new te(this._engine,this._table);return n._root=t,n}messagePassing(e=2,t="mean",n){const r=new Dn({kLayers:e,aggregation:t,propertyName:n??void 0,graph:this._table});return this._chain(r)}aggregate(e,t){const n=this._engine.getTable(this._table),r=this._buildContext(n);let s;if(this._root!==null)s=this._root.execute(r);else{const u=[...n.documentStore.docIds].sort((h,f)=>h-f).map(h=>({docId:h,payload:{positions:[],score:0,fields:{}}}));s=D.fromSorted(u)}const o=n.documentStore,i=[];for(const l of s){const u=o.getField(l.docId,e);typeof u=="number"&&i.push(u)}let a;switch(t.toLowerCase()){case"count":a=i.length;break;case"sum":a=i.reduce((l,u)=>l+u,0);break;case"avg":{const l=i.reduce((u,h)=>u+h,0);a=i.length>0?l/i.length:0;break}case"min":a=i.length>0?Math.min(...i):null;break;case"max":a=i.length>0?Math.max(...i):null;break;default:throw new Error(`Unknown aggregation function: ${t}`)}return new sn(a)}facet(e){const t=this._engine.getTable(this._table),n=this._buildContext(t),s=new Vs(e,this._root).execute(n),o=new Map;for(const i of s){const a=i.payload.fields._facet_value,l=i.payload.fields._facet_count;a!==void 0&&l!==void 0&&o.set(String(a),l)}return new qn(o)}vectorFacet(e,t,n){const r=this._engine.getTable(this._table),s=this._buildContext(r),i=new pr(e,t,n,this._root).execute(s),a=new Map;for(const l of i){const u=l.payload.fields._facet_value,h=l.payload.fields._facet_count;u!==void 0&&h!==void 0&&a.set(String(u),h)}return new qn(a)}pathFilter(e,t){const n=new Qt(e,t,this._root),r=new te(this._engine,this._table);return r._root=n,r}pathProject(...e){const t=new Ro(e,this._root),n=new te(this._engine,this._table);return n._root=t,n}unnest(e){const t=new Fo(e,this._root),n=new te(this._engine,this._table);return n._root=t,n}pathAggregate(e,t){const r={count:Yo,sum:Xo,avg:Qo,min:Zo,max:ei}[t.toLowerCase()];if(r===void 0)throw new Error(`Unknown aggregation: ${t}`);let s;if(typeof e=="string"){const a=[];for(const l of e.split("."))/^\d+$/.test(l)?a.push(parseInt(l,10)):a.push(l);s=a}else s=e;const o=new Po(s,new r,this._root),i=new te(this._engine,this._table);return i._root=o,i}scoreBm25(e,t){const r=this._engine._contextForTable(this._table).invertedIndex,o=(t?r.getFieldAnalyzer(t):r.analyzer).analyze(e),i=new xt(qt(),r.stats),a=new de(i,this._root,o,t??null),l=new te(this._engine,this._table);return l._root=a,l}scoreBayesianBm25(e,t){const r=this._engine._contextForTable(this._table).invertedIndex,o=(t?r.getFieldAnalyzer(t):r.analyzer).analyze(e),i=new lt(Ke(),r.stats),a=new de(i,this._root,o,t??null),l=new te(this._engine,this._table);return l._root=a,l}scoreMultiFieldBayesian(e,t,n){const r=new Mn(t,e,n??null),s=new te(this._engine,this._table);return s._root=r,s}scoreBayesianWithPrior(e,t,n){if((n==null?void 0:n.priorFn)===void 0||n.priorFn===null)throw new Error("priorFn is required for scoreBayesianWithPrior");return this.scoreBayesianBm25(e,t)}learnParams(e,t,n){const r=(n==null?void 0:n.field)??"_default";return this._engine.learnScoringParams(this._table,r,e,t,{mode:(n==null?void 0:n.mode)??"balanced"})}fuseLogOdds(...e){let t=.5;const n=[];for(const o of e)typeof o=="number"?t=o:o._root!==null&&n.push(o);if(n.length===0)return this;const r=n.map(o=>o._root),s=new te(this._engine,this._table);return s._root=new Ae(r,t),s}fuseProbAnd(...e){const t=e.filter(r=>r._root!==null).map(r=>r._root),n=new te(this._engine,this._table);return n._root=new je(t,"and"),n}fuseProbOr(...e){const t=e.filter(r=>r._root!==null).map(r=>r._root),n=new te(this._engine,this._table);return n._root=new je(t,"or"),n}fuseAttention(e,t=.5){const n=e.filter(i=>i._root!==null).map(i=>i._root);if(n.length<2)throw new Error("fuseAttention requires at least 2 signals");const r=new Wr(n.length,6,t),s=new Float64Array(6),o=new te(this._engine,this._table);return o._root=new dt(n,r,s),o}fuseLearned(e,t=.5){const n=e.filter(o=>o._root!==null).map(o=>o._root);if(n.length<2)throw new Error("fuseLearned requires at least 2 signals");const r=new Hr(n.length,t),s=new te(this._engine,this._table);return s._root=new kt(n,r),s}multiStage(e){const t=[];for(const[s,o]of e){if(s._root===null)throw new Error("Each stage must have an operator");t.push([s._root,o])}const n=new Ve(t),r=new te(this._engine,this._table);return r._root=n,r}execute(){if(this._root===null)return new D;const e=this._engine._contextForTable(this._table);let t=this._root;if(e.invertedIndex){const r=e.invertedIndex.stats;t=new Re(r).optimize(this._root)}return new tn(e).execute(t)}explain(){if(this._root===null)return"(empty query)";const e=this._engine._contextForTable(this._table);let t=this._root;if(e.invertedIndex){const r=e.invertedIndex.stats;t=new Re(r).optimize(this._root)}return new tn(e).explain(t)}_chain(e){this._root!==null&&(e=new H([this._root,e]));const t=new te(this._engine,this._table);return t._root=e,t}_buildContext(e){const t={};for(const[r,s]of e.vectorIndexes)t[r]=s;const n={};for(const[r,s]of e.spatialIndexes)n[r]=s;return{documentStore:e.documentStore,invertedIndex:e.invertedIndex,vectorIndexes:t,spatialIndexes:n}}}class Ei{constructor(e){b(this,"_conn");b(this,"_finished");this._conn=e,this._finished=!1,this._conn.beginTransaction()}get active(){return!this._finished}commit(){if(this._finished)throw new Error("Transaction already finished");this._conn.commitTransaction(),this._finished=!0}rollback(){if(this._finished)throw new Error("Transaction already finished");this._conn.rollbackTransaction(),this._finished=!0}savepoint(e){if(this._finished)throw new Error("Transaction already finished");this._conn.savepoint(e)}releaseSavepoint(e){if(this._finished)throw new Error("Transaction already finished");this._conn.releaseSavepoint(e)}rollbackTo(e){if(this._finished)throw new Error("Transaction already finished");this._conn.rollbackToSavepoint(e)}autoRollback(){this._finished||this.rollback()}}class Ii{constructor(){b(this,"_index",new Map)}_makeKey(e,t){return`${t}\0${e.join("\0")}`}_pairKey(e,t){return`${String(e)}\0${String(t)}`}_parsePairKey(e){const t=e.split("\0");return[parseInt(t[0],10),parseInt(t[1],10)]}build(e,t,n){for(const r of n){const s=this._makeKey(r,t),o=new Set,i=e.vertexIdsInGraph(t);for(const a of i){const l=this._findReachable(e,t,a,r);for(const u of l)o.add(this._pairKey(a,u))}this._index.set(s,o)}}_findReachable(e,t,n,r){let s=new Set([n]);for(const o of r){const i=new Set;for(const a of s){const l=e.neighbors(a,t,o,"out");for(const u of l)i.add(u)}if(s=i,s.size===0)break}return[...s]}lookup(e,t){const n=this._makeKey(e,t),r=this._index.get(n);return r?[...r].map(s=>this._parsePairKey(s)):[]}hasPath(e,t){const n=this._makeKey(e,t);return this._index.has(n)}indexedPaths(){const e=[];for(const t of this._index.keys()){const n=t.split("\0");e.push(n.slice(1))}return e}}class zn{constructor(e=1,t=0,n=.5){b(this,"_transform");this._transform=new K.BayesianProbabilityTransform(e,t,n===.5?null:n)}fit(e,t,n){return this._transform.fit(e,t,n),this.params()}update(e,t,n){this._transform.update(e,t,n)}params(){return{alpha:this._transform.alpha,beta:this._transform.beta,baseRate:this._transform.baseRate??.5}}}class Ni{constructor(e){b(this,"_tables");b(this,"_views");b(this,"_prepared");b(this,"_sequences");b(this,"_tempTables");b(this,"_graphStore");b(this,"_versionedGraphs");b(this,"_pathIndexes");b(this,"_foreignServers");b(this,"_foreignTables");b(this,"_models");b(this,"_catalog");b(this,"_indexManager");b(this,"_transaction");b(this,"_compiler");b(this,"_dbPath");b(this,"_parallelWorkers");b(this,"_spillThreshold");this._dbPath=(e==null?void 0:e.dbPath)??null,this._parallelWorkers=(e==null?void 0:e.parallelWorkers)??4,this._spillThreshold=(e==null?void 0:e.spillThreshold)??0,this._tables=new Map,this._views=new Map,this._prepared=new Map,this._sequences=new Map,this._tempTables=new Set,this._graphStore=new cr,this._versionedGraphs=new Map,this._pathIndexes=new Map,this._foreignServers=new Map,this._foreignTables=new Map,this._models=new Map,this._catalog=null,this._indexManager=null,this._transaction=null,this._compiler=new le(this)}async sql(e,t){return this._compiler.execute(e,t)}getTable(e){const t=this._tables.get(e);if(t!==void 0)return t;const n=this._compiler.tables.get(e);if(n!==void 0)return this._tables.set(e,n),n;throw new Error(`Table not found: ${e}`)}hasTable(e){return this._tables.has(e)||this._compiler.tables.has(e)}registerTable(e,t){this._tables.set(e,t),this._compiler.tables.set(e,t)}addDocument(e,t,n,r){const s=this._tables.get(n);if(s===void 0)throw new Error(`Table '${n}' does not exist`);const o={...t};s.primaryKey!==null&&!(s.primaryKey in o)&&s.columns.get(s.primaryKey)!==void 0&&(o[s.primaryKey]=e);let i=null,a=null;if(r!=null){for(const[u,h]of s.columns)if(h.vectorDimensions!==null){i=u;break}i!==null&&(a=r,o[i]=Array.from(r))}s.documentStore.put(e,o);const l={};for(const[u,h]of Object.entries(o))typeof h=="string"&&(l[u]=h);if(Object.keys(l).length>0&&s.invertedIndex.addDocument(e,l),i!==null&&a!==null){const u=s.vectorIndexes.get(i);u!==void 0&&u.add(e,a)}}getDocument(e,t){const n=this._tables.get(t);if(n===void 0)throw new Error(`Table '${t}' does not exist`);return n.documentStore.get(e)}deleteDocument(e,t){const n=this._tables.get(t);if(n===void 0)throw new Error(`Table '${t}' does not exist`);n.documentStore.delete(e),n.invertedIndex.removeDocument(e)}getGraphStore(e){return this._graphStore}addGraphVertex(e,t){this._graphStore.addVertex(e,t)}addGraphEdge(e,t){this._graphStore.addEdge(e,t)}createGraph(e){return this._graphStore.createGraph(e),this._catalog!==null&&this._catalog.saveNamedGraph(e),this._graphStore}dropGraph(e){this._graphStore.dropGraph(e),this._catalog!==null&&this._catalog.dropNamedGraph(e)}getGraph(e){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);return this._graphStore}hasGraph(e){return this._graphStore.hasGraph(e)}get graphStore(){return this._graphStore}estimateConvWeights(e,t,n,r="embedding"){return To(this,e,t,n,r)}saveModel(e,t){this._models.set(e,t),this._catalog!==null&&this._catalog.saveModel(e,t)}loadModel(e){const t=this._models.get(e);if(t!==void 0)return t;if(this._catalog!==null){const n=this._catalog.loadModel(e);return n!==null&&this._models.set(e,n),n}return null}deleteModel(e){this._models.delete(e),this._catalog!==null&&this._catalog.deleteModel(e)}buildPathIndex(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);const n=new Ii;n.build(this._graphStore,e,t),this._pathIndexes.set(e,n),this._catalog!==null&&this._catalog.savePathIndex(e,t)}getPathIndex(e){return this._pathIndexes.get(e)??null}dropPathIndex(e){this._pathIndexes.delete(e),this._catalog!==null&&this._catalog.dropPathIndex(e)}createAnalyzer(e,t){const n=De.fromDict(t);bs(e,n),this._catalog!==null&&this._catalog.saveAnalyzer(e,t)}dropAnalyzer(e){ws(e),this._catalog!==null&&this._catalog.dropAnalyzer(e)}setTableAnalyzer(e,t,n,r="both"){const s=this._tables.get(e);if(s===void 0)throw new Error(`Table '${e}' does not exist`);const o=vs(n);s.invertedIndex.setFieldAnalyzer(t,o,r),this._catalog!==null&&(r==="both"?(this._catalog.saveTableFieldAnalyzer(e,t,"index",n),this._catalog.saveTableFieldAnalyzer(e,t,"search",n)):this._catalog.saveTableFieldAnalyzer(e,t,r,n))}getTableAnalyzer(e,t,n="index"){const r=this._tables.get(e);if(r===void 0)throw new Error(`Table '${e}' does not exist`);return n==="search"?r.invertedIndex.getSearchAnalyzer(t):r.invertedIndex.getFieldAnalyzer(t)}saveScoringParams(e,t){this._catalog!==null&&this._catalog.saveScoringParams(e,t)}loadScoringParams(e){return this._catalog!==null?this._catalog.loadScoringParams(e):null}loadAllScoringParams(){return this._catalog!==null?this._catalog.loadAllScoringParams():[]}learnScoringParams(e,t,n,r,s){const o=(s==null?void 0:s.mode)??"balanced",i=this._tables.get(e);if(i===void 0)throw new Error(`Table '${e}' does not exist`);const a=this._contextForTable(e),l=a.invertedIndex,h=(t?l.getSearchAnalyzer(t):l.analyzer).analyze(n),f=new lt(Ke(),l.stats),d=new me(n,t||null),m=new de(f,d,h,t||null).execute(a),_=new Map;for(const S of m)_.set(S.docId,S.payload.score);const y=[...i.documentStore.docIds].sort((S,N)=>S-N);if(r.length!==y.length)throw new Error(`labels length (${String(r.length)}) must match document count (${String(y.length)})`);const x=y.map(S=>_.get(S)??0),E=new zn().fit(x,r,{mode:o}),I=`${e}.${t}.${n}`;return this.saveScoringParams(I,E),E}updateScoringParams(e,t,n,r){const s=`${e}.${t}`,o=this.loadScoringParams(s);let i;o!==null?i=new zn(o.alpha??1,o.beta??0,o.base_rate??.5):i=new zn,i.update(n,r),this.saveScoringParams(s,i.params())}vectorBackgroundStats(e,t){const n=this._tables.get(e);if(n===void 0)return null;const r=n.vectorIndexes.get(t);return r!==void 0&&r.backgroundStats!==void 0?r.backgroundStats:null}begin(){if(this._catalog===null)throw new Error("Transactions require a persistent engine (dbPath)");if(this._transaction!==null&&this._transaction.active)throw new Error("Transaction already active");return this._transaction=new Ei(this._catalog.conn),this._transaction}query(e){return new te(this,e)}insert(e,t,n){const r=this.getTable(e);r.documentStore.put(t,n);const s={};for(const[o,i]of r.columns){const a=n[o];i.pythonType==="string"&&a!==null&&a!==void 0&&(s[o]=typeof a=="string"?a:String(a))}Object.keys(s).length>0&&r.invertedIndex.addDocument(t,s);for(const[o,i]of r.vectorIndexes){const a=n[o];a!=null&&(a instanceof Float64Array?i.add(t,a):Array.isArray(a)&&i.add(t,new Float64Array(a)))}}get dbPath(){return this._dbPath}get parallelWorkers(){return this._parallelWorkers}get spillThreshold(){return this._spillThreshold}get compiler(){return this._compiler}get catalog(){return this._catalog}get indexManager(){return this._indexManager}_contextForTable(e){const t=this._tables.get(e);if(t===void 0)throw new Error(`Table '${e}' does not exist`);const n={};for(const[s,o]of t.vectorIndexes)n[s]=o;const r={};for(const[s,o]of t.spatialIndexes)r[s]=o;return{documentStore:t.documentStore,invertedIndex:t.invertedIndex,vectorIndexes:n,spatialIndexes:r,graphStore:this._graphStore,indexManager:this._indexManager}}deepLearn(e,t,n){if(this._tables.get(e)===void 0)throw new Error(`Table '${e}' does not exist`);const s={...n,_model_name:t,_table:e,_trained_at:new Date().toISOString(),_status:"trained"};return this.saveModel(t,s),s}deepPredict(e,t){if(this.loadModel(e)===null)throw new Error(`Model '${e}' not found`);return t.map((r,s)=>({_input_idx:s,_model:e,_prediction:null,...r}))}applyGraphDelta(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);if(t.removeEdges)for(const n of t.removeEdges)this._graphStore.removeEdge(n,e);if(t.removeVertices)for(const n of t.removeVertices)this._graphStore.removeVertex(n,e);if(t.addVertices)for(const n of t.addVertices)this._graphStore.addVertex(n,e);if(t.addEdges)for(const n of t.addEdges)this._graphStore.addEdge(n,e);this._catalog!==null&&this._catalog.saveNamedGraph(e)}createGraphVersion(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);const n=this._versionedGraphs.get(e);if(n===void 0){const r={versions:new Map},s=new Map,o=new Map;for(const i of this._graphStore.verticesInGraph(e))s.set(i.vertexId,{...i});for(const i of this._graphStore.edgesInGraph(e))o.set(i.edgeId,{...i});r.versions.set(t,{vertices:s,edges:o}),this._versionedGraphs.set(e,r)}else{const r=new Map,s=new Map;for(const o of this._graphStore.verticesInGraph(e))r.set(o.vertexId,{...o});for(const o of this._graphStore.edgesInGraph(e))s.set(o.edgeId,{...o});n.versions.set(t,{vertices:r,edges:s})}}graphVersions(e){const t=this._versionedGraphs.get(e);return t===void 0?[]:[...t.versions.keys()]}restoreGraphVersion(e,t){const n=this._versionedGraphs.get(e);if(n===void 0)throw new Error(`No versions exist for graph '${e}'`);const r=n.versions.get(t);if(r===void 0)throw new Error(`Version '${t}' not found for graph '${e}'`);const s=this._graphStore.verticesInGraph(e);for(const o of s)this._graphStore.removeVertex(o.vertexId,e);for(const o of r.vertices.values())this._graphStore.addVertex(o,e);for(const o of r.edges.values())this._graphStore.addEdge(o,e)}calibrationReport(e,t){const r=this.loadAllScoringParams().filter(([o])=>o.startsWith(`${e}.${t}`)),s={table:e,field:t,numCalibrations:r.length,params:r.map(([o,i])=>({name:o,alpha:i.alpha??null,beta:i.beta??null,baseRate:i.base_rate??null}))};if(r.length>0){const o=r.map(([,a])=>a.alpha).filter(a=>typeof a=="number"),i=r.map(([,a])=>a.beta).filter(a=>typeof a=="number");o.length>0&&(s.mean_alpha=o.reduce((a,l)=>a+l,0)/o.length,s.std_alpha=o.length>1?Math.sqrt(o.reduce((a,l)=>a+(l-s.mean_alpha)**2,0)/(o.length-1)):0),i.length>0&&(s.mean_beta=i.reduce((a,l)=>a+l,0)/i.length)}return s}saveToCatalog(){if(this._catalog!==null){for(const[e,t]of this._tables)if(!this._tempTables.has(e)){const n=[];for(const[r,s]of t.columns)n.push({...s,name:r});this._catalog.saveTableSchema(e,n)}for(const[e,t]of this._sequences)this._catalog.setMetadata(`seq:${e}`,JSON.stringify(t));for(const e of this._graphStore.graphNames())this._catalog.saveNamedGraph(e);for(const[e,t]of this._models)this._catalog.saveModel(e,t)}}loadFromCatalog(){if(this._catalog===null)return;const e=this._catalog.loadTableSchemas();for(const[n]of e);const t=this._catalog.loadNamedGraphs();for(const n of t)this._graphStore.hasGraph(n)||this._graphStore.createGraph(n)}close(){this._transaction!==null&&this._transaction.active&&(this._transaction.rollback(),this._transaction=null),this._foreignTables.clear(),this._foreignServers.clear();for(const e of this._tempTables)this._tables.delete(e);this._tempTables.clear(),this._catalog!==null&&(this._catalog.close(),this._catalog=null),this._tables.clear(),this._graphStore.clear()}}$.AggregateResult=sn,$.Analyzer=De,$.BM25Scorer=xt,$.BayesianBM25Scorer=lt,$.Between=un,$.ComplementOperator=fe,$.Engine=Ni,$.Equals=ln,$.FacetResult=qn,$.FilterOperator=G,$.FlatVectorIndex=lr,$.GeneralizedPostingList=we,$.GreaterThan=Wn,$.GreaterThanOrEqual=Hn,$.HierarchicalDocument=cs,$.ILike=Qn,$.InSet=cn,$.IndexStats=Bn,$.IntersectOperator=H,$.IsNotNull=fn,$.IsNull=hn,$.KNNOperator=Le,$.LessThan=Kn,$.LessThanOrEqual=Jn,$.Like=Xn,$.MemoryDocumentStore=or,$.MemoryGraphStore=cr,$.MemoryInvertedIndex=ir,$.NotEquals=Un,$.Operator=q,$.PostingList=D,$.QueryBuilder=te,$.Table=Ut,$.TermOperator=me,$.UnionOperator=re,$.createBM25Params=qt,$.createBayesianBM25Params=Ke,$.keywordAnalyzer=rr,$.standardAnalyzer=Sn,$.whitespaceAnalyzer=nr,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
14
+ `);for(const o of e.children)s+=this._explainAnalyzeNode(o,t+1,n);return s}explainTree(e){return this._explainTreeNode(e)}_explainTreeNode(e){const t={operator:this._operatorName(e),details:this._operatorDetails(e)},n=[];if(e instanceof re)for(const r of e.operands)n.push(this._explainTreeNode(r));else if(e instanceof H)for(const r of e.operands)n.push(this._explainTreeNode(r));else if(e instanceof de)n.push(this._explainTreeNode(e.operand));else if(e instanceof Ne)n.push(this._explainTreeNode(e.source));else if(e instanceof pe)n.push(this._explainTreeNode(e.source));else if(e instanceof G&&e.source!==null)n.push(this._explainTreeNode(e.source));else if(e instanceof $e)for(const[r,s]of e.stages){const o=this._explainTreeNode(r);o.cutoff=s,n.push(o)}else{const r=e.constructor.name;if(r==="LogOddsFusionOperator"||r==="ProbBoolFusionOperator"||r==="AttentionFusionOperator"||r==="LearnedFusionOperator"){const s=e;for(const o of s.signals)n.push(this._explainTreeNode(o))}}return n.length>0&&(t.children=n),t}}const et=new Set(["count","sum","avg","min","max","string_agg","array_agg","bool_and","bool_or","stddev","stddev_pop","stddev_samp","variance","var_pop","var_samp","percentile_cont","percentile_disc","mode","json_object_agg","jsonb_object_agg","corr","covar_pop","covar_samp","regr_count","regr_avgx","regr_avgy","regr_sxx","regr_syy","regr_sxy","regr_slope","regr_intercept","regr_r2"]),Yr=new Set(["text_match","bayesian_match","bayesian_match_with_prior","knn_match","bayesian_knn_match","traverse_match","temporal_traverse","path_filter","vector_exclude","spatial_within","fuse_log_odds","fuse_prob_and","fuse_prob_or","fuse_prob_not","fuse_attention","fuse_multihead","fuse_learned","sparse_threshold","multi_field_match","message_passing","graph_embedding","staged_retrieval","pagerank","hits","betweenness","weighted_rpq","progressive_fusion","deep_fusion"]),di=new Set(["random","nextval","currval","now","current_timestamp","clock_timestamp","statement_timestamp","timeofday"]);function g(c,e){return c[e]??null}function Xr(c){return typeof c=="string"?c:c==null?"":typeof c=="number"?c.toString(10):typeof c=="boolean"?c?"true":"false":JSON.stringify(c)}function j(c,e){const t=c[e];return t==null?"":Xr(t)}function w(c){return c??{}}function P(c){return Array.isArray(c)?c:[]}function J(c){const e=g(c,"String")??g(c,"str");if(e!==null&&typeof e=="object")return j(w(e),"sval")||j(w(e),"str");if(typeof e=="string")return e;const t=j(c,"sval")||j(c,"str");return t||""}function ae(c){return j(c,"relname")}function Ue(c){const e=g(c,"alias");return e!==null&&typeof e=="object"&&j(w(e),"aliasname")||null}function pi(c){return j(c,"schemaname")||null}function B(c){const e=w(g(c,"ColumnRef")??c),t=P(g(e,"fields"));if(t.length>0){const r=t[t.length-1],s=J(r);if(s)return s}const n=j(e,"sval")||j(e,"str");if(n)return n;throw new Error("Expected ColumnRef, got "+JSON.stringify(c).slice(0,200))}function gi(c){const e=w(g(c,"ColumnRef")??c),t=P(g(e,"fields"));if(t.length>=2){const n=[];for(const r of t){const s=J(r);s&&n.push(s)}return n.join(".")}return B(c)}function X(c){return g(c,"ColumnRef")!==null}function tt(c){if(g(c,"A_Star")!==null&&g(c,"A_Star")!==void 0)return!0;const e=g(c,"ColumnRef");if(e!=null){const t=P(g(w(e),"fields"));for(const n of t)if(g(n,"A_Star")!==null&&g(n,"A_Star")!==void 0)return!0}return!1}function Q(c){return g(c,"FuncCall")!==null}function ce(c){const e=w(g(c,"FuncCall")??c),t=P(g(e,"funcname"));return t.length===0?"":J(t[t.length-1]).toLowerCase()}function ve(c){const e=w(g(c,"FuncCall")??c);return P(g(e,"args"))}function nt(c){const e=w(g(c,"FuncCall")??c);return g(e,"agg_star")===!0}function Qr(c){const e=w(g(c,"FuncCall")??c);return g(e,"agg_distinct")===!0}function rt(c){const e=w(g(c,"FuncCall")??c),t=g(e,"over");return t!=null}function be(c){return g(c,"A_Const")!==null}function Pt(c){return g(c,"ParamRef")!==null}function jn(c){return g(c,"A_Expr")!==null}function mi(c){return g(c,"BoolExpr")!==null}function Zr(c){return g(c,"NullTest")!==null}function nn(c){return g(c,"SubLink")!==null}function rn(c){return g(c,"TypeCast")!==null}function _i(c){return g(c,"A_ArrayExpr")!==null}function z(c,e){const t=g(c,"ParamRef");if(t!=null){const l=w(t),u=g(l,"number"),h=u-1;if(h<0||h>=e.length)throw new Error(`No value supplied for parameter $${String(u)}`);return e[h]}const n=w(g(c,"A_Const")??c);if(g(n,"isnull")===!0)return null;const r=g(n,"ival");if(r!=null){if(typeof r=="number")return r;if(typeof r=="object"){const l=g(w(r),"ival");if(l!=null)return Number(l)}return Number(r)}const s=g(n,"fval");if(s!=null)return parseFloat(String(s));const o=g(n,"sval");if(o!=null){if(typeof o=="string")return o;if(typeof o=="object"){const l=g(w(o),"sval");if(l!=null)return String(l)}return String(o)}const i=g(n,"boolval");if(i!=null)return i;const a=g(n,"val");if(a!=null&&typeof a=="object"){const l=w(a),u=g(l,"Integer")??g(l,"ival");if(u!=null){if(typeof u=="number")return u;const p=g(w(u),"ival");if(p!==null)return Number(p)}const h=g(l,"Float")??g(l,"fval");if(h!=null){if(typeof h=="number")return h;const p=g(w(h),"fval");return parseFloat(String(p!==null?p:h))}const f=g(l,"String")??g(l,"sval");if(f!=null){if(typeof f=="string")return f;const p=g(w(f),"sval");if(p!==null)return String(p)}const d=g(l,"Boolean")??g(l,"boolval");if(d!=null){if(typeof d=="boolean")return d;const p=g(w(d),"boolval");if(p!==null)return p}}return typeof c=="number"||typeof c=="string"?c:null}function we(c,e){const t=z(c,e);return Number(t)}function ee(c,e){const t=z(c,e);return String(t)}function We(c,e){const t=g(c,"A_ArrayExpr");if(t!=null){const r=P(g(w(t),"elements"));return new Float64Array(r.map(s=>Number(z(s,e))))}const n=g(c,"ParamRef");if(n!=null){const r=w(n),s=g(r,"number"),o=s-1;if(o<0||o>=e.length)throw new Error(`No value supplied for parameter $${String(s)}`);const i=e[o];if(i instanceof Float64Array)return i;if(i instanceof Float32Array)return new Float64Array(i);if(Array.isArray(i))return new Float64Array(i.map(Number));throw new Error("Parameter for vector must be an array")}throw new Error("Expected ARRAY literal or $N parameter for vector")}function yi(c,e,t){if(Pt(c)){const n=w(g(c,"ParamRef")),r=g(n,"number"),s=r-1;if(s<0||s>=e.length)throw new Error(`Parameter $${String(r)} not provided`);const o=e[s];return o!==null&&typeof o=="object"&&"tolist"in o?o.tolist:o}if(_i(c)){const n=P(g(w(g(c,"A_ArrayExpr")),"elements"));return n.length===0?[]:n.map(r=>z(r,e))}if(rn(c))return t.evaluate(c,{});if(Q(c))return t.evaluate(c,{});try{return t.evaluate(c,{})}catch{return z(c,e)}}const bi=1e3;class le{constructor(e){b(this,"_tables");b(this,"_views");b(this,"_sequences");b(this,"_engine");b(this,"_transactionActive");b(this,"_prepared");b(this,"_params");b(this,"_expandedViews");b(this,"_shadowedTables");b(this,"_inlinedCTEs");b(this,"_correlatedOuterRow");b(this,"_foreignServers");b(this,"_foreignTables");b(this,"_currentGraphName","");this._tables=new Map,this._views=new Map,this._sequences=new Map,this._engine=e??null,this._transactionActive=!1,this._prepared=new Map,this._params=[],this._expandedViews=[],this._shadowedTables=new Map,this._inlinedCTEs=new Map,this._correlatedOuterRow=null,this._foreignServers=new Map,this._foreignTables=new Map}_makeSubqueryExecutor(e){return(t,n)=>this._compileSelect(t,e,n)}get tables(){return this._tables}get views(){return this._views}get engine(){return this._engine}async execute(e,t){this._params=t?[...t]:[];const n=await st.parse(e),r=P(g(w(n),"stmts"));if(r.length===0)return null;let s=null;for(const o of r){const i=w(g(o,"stmt"));s=this._dispatchStatement(i,this._params)}return s}_dispatchStatement(e,t){const n=Object.keys(e);if(n.length===0)return null;const r=n[0],s=w(e[r]);switch(r){case"SelectStmt":return this._compileSelect(s,t);case"InsertStmt":return this._compileInsert(s,t);case"UpdateStmt":return this._compileUpdate(s,t);case"DeleteStmt":return this._compileDelete(s,t);case"CreateStmt":return this._compileCreateTable(s);case"CreateTableAsStmt":return this._compileCreateTableAs(s,t);case"DropStmt":return this._compileDrop(s);case"ViewStmt":return this._compileCreateView(s);case"TransactionStmt":return this._compileTransaction(s);case"CreateSeqStmt":return this._compileCreateSequence(s);case"AlterSeqStmt":return this._compileAlterSequence(s);case"IndexStmt":return this._compileCreateIndex(s);case"AlterTableStmt":return this._compileAlterTable(s);case"TruncateStmt":return this._compileTruncate(s);case"ExplainStmt":return this._compileExplain(s,t);case"RenameStmt":return this._compileRename(s);case"PrepareStmt":return this._compilePrepare(s);case"ExecuteStmt":return this._compileExecute(s,t);case"DeallocateStmt":return this._compileDeallocate(s);case"VacuumStmt":return this._compileAnalyze(s);case"CreateForeignServerStmt":return this._compileCreateForeignServer(s);case"CreateForeignTableStmt":return this._compileCreateForeignTable(s);case"VariableSetStmt":case"VariableShowStmt":case"DoStmt":case"LockStmt":case"DiscardStmt":return null;default:throw new Error(`Unsupported statement type: ${r}`)}}_compileCreateTable(e){const t=w(g(e,"relation")),n=ae(t),r=g(e,"if_not_exists")===!0;if(this._tables.has(n)){if(r)return null;throw new Error(`Table "${n}" already exists`)}const s=P(g(e,"tableElts")),o=[],i=[],a=[];let l=null;for(const h of s){const f=g(h,"ColumnDef");if(f!=null){const p=w(f),m=this._parseColumnDef(p);o.push(m),m.primaryKey&&(l=m.name);const _=P(g(p,"constraints"));for(const y of _){const x=w(g(y,"Constraint")??y),v=g(x,"contype");if(v===1||v==="CONSTR_CHECK"){const E=j(x,"conname")||`check_${String(a.length)}`,I=g(x,"raw_expr");if(I!=null){const S=new ie,N=w(I);a.push([E,A=>S.evaluate(N,A)===!0])}}if(v===8||v==="CONSTR_FOREIGN"){const E=w(g(x,"pktable")),I=P(g(x,"pk_attrs"));I.length>0&&i.push({column:m.name,refTable:ae(E),refColumn:J(I[0])})}}continue}const d=g(h,"Constraint");if(d!=null){const p=w(d),m=g(p,"contype");if(m===5||m==="CONSTR_PRIMARY"){const _=P(g(p,"keys"));_.length>0&&(l=J(_[0]))}if(m===8||m==="CONSTR_FOREIGN"){const _=P(g(p,"fk_attrs")),y=w(g(p,"pktable")),x=P(g(p,"pk_attrs"));_.length>0&&x.length>0&&i.push({column:J(_[0]),refTable:ae(y),refColumn:J(x[0])})}if(m===4||m==="CONSTR_UNIQUE"){const _=P(g(p,"keys"));for(const y of _){const x=J(y),v=o.findIndex(E=>E.name===x);if(v!==-1){const E=o[v];o[v]=Ie(E.name,E.typeName,{...E,unique:!0})}}}if(m===1||m==="CONSTR_CHECK"){const _=j(p,"conname")||`check_${String(a.length)}`,y=g(p,"raw_expr");if(y!=null){const x=new ie,v=w(y);a.push([_,E=>x.evaluate(v,E)===!0])}}}}if(l!==null){const h=o.findIndex(f=>f.name===l);if(h!==-1){const f=o[h];o[h]=Ie(f.name,f.typeName,{...f,primaryKey:!0,notNull:!0})}}const u=new Ut(n,o);u.foreignKeys=i,u.checkConstraints=a,this._tables.set(n,u),i.length>0&&this._registerFkValidators(n,u,i);for(const h of o)if(h.autoIncrement){const f=`${n}_${h.name}_seq`;this._sequences.set(f,{current:0,increment:1,start:1})}return null}_compileCreateTableAs(e,t){const n=w(g(e,"into")),r=w(g(n,"rel")),s=ae(r);if(this._tables.has(s))throw new Error(`Table "${s}" already exists`);const o=w(g(e,"query")),i=w(g(o,"SelectStmt")??o),a=this._compileSelect(i,t),l=[];for(const f of a.columns){let d="text",p="string";if(a.rows.length>0){const m=a.rows[0][f];typeof m=="number"?Number.isInteger(m)?(d="integer",p="number"):(d="real",p="number"):typeof m=="boolean"?(d="boolean",p="boolean"):Array.isArray(m)?(d="text[]",p="array"):typeof m=="object"&&m!==null&&(d="jsonb",p="object")}l.push(Ie(f,d,{pythonType:p}))}const u=new Ut(s,l);this._tables.set(s,u);let h=0;for(const f of a.rows){const d={};for(const p of a.columns)d[p]=f[p]??null;u.insert(d),h++}return{columns:["inserted"],rows:[{inserted:h}]}}_compileCreateSequence(e){const t=w(g(e,"sequence")),n=ae(t),r=P(g(e,"options"));if(this._sequences.has(n)){if(g(e,"if_not_exists")===!0)return null;throw new Error(`Sequence "${n}" already exists`)}let s=1,o=1;for(const i of r){const a=w(g(i,"DefElem")??i),l=j(a,"defname"),u=g(a,"arg");if(l==="start"&&u!==null){const h=w(u);s=Number(g(h,"ival")??g(w(g(h,"Integer")??{}),"ival")??1)}if(l==="increment"&&u!==null){const h=w(u);o=Number(g(h,"ival")??g(w(g(h,"Integer")??{}),"ival")??1)}}return this._sequences.set(n,{current:s-o,increment:o,start:s}),null}_compileAlterSequence(e){const t=w(g(e,"sequence")),n=ae(t),r=this._sequences.get(n);if(r===void 0)throw new Error(`Sequence "${n}" does not exist`);const s=P(g(e,"options"));for(const o of s){const i=w(g(o,"DefElem")??o),a=j(i,"defname"),l=g(i,"arg");if(a==="restart")if(l!=null){const u=w(l),h=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??r.start??1);r.current=h-r.increment}else r.current=(r.start??1)-r.increment;else if(a==="increment"){if(l!=null){const u=w(l);r.increment=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??1)}}else if(a==="start"&&l!=null){const u=w(l);r.start=Number(g(u,"ival")??g(w(g(u,"Integer")??{}),"ival")??1)}}return null}_parseColumnDef(e){const t=j(e,"colname"),n=w(g(e,"typeName")),r=P(g(n,"names")),s=[];for(const I of r){const S=J(I);S&&S!=="pg_catalog"&&s.push(S)}const i=P(g(n,"arrayBounds")).length>0;let[a,l]=s.length>0?xr(s):["text","string"],u=!1;const h=s.join(" ").toUpperCase();(h==="SERIAL"||h==="BIGSERIAL"||h==="SMALLSERIAL")&&(u=!0),i&&(a="array",l="array");const f=P(g(n,"typmods"));let d=null,p=null,m=null;if(f.length>0){const I=g(f[0],"Integer")??g(f[0],"A_Const");if(I!=null){const S=g(w(I),"ival");S!==null&&typeof S=="number"&&(a==="vector"?m=S:d=S)}if(f.length>1){const S=g(f[1],"Integer")??g(f[1],"A_Const");if(S!=null){const N=g(w(S),"ival");N!==null&&typeof N=="number"&&(p=N)}}}let _=!1,y=!1,x=!1,v=null;const E=P(g(e,"constraints"));for(const I of E){const S=w(g(I,"Constraint")??I),N=g(S,"contype");if((N==="CONSTR_NOTNULL"||N===1)&&(y=!0),(N==="CONSTR_PRIMARY"||N===5)&&(_=!0,y=!0),(N==="CONSTR_UNIQUE"||N===4)&&(x=!0),N==="CONSTR_DEFAULT"||N===2){const A=g(S,"raw_expr");A!=null&&(v=new ie().evaluate(w(A),{}))}(N==="CONSTR_IDENTITY"||N===9)&&(u=!0,y=!0)}return u&&(y=!0),Ie(t,a,{pythonType:l,primaryKey:_,notNull:y,autoIncrement:u,defaultValue:v,vectorDimensions:m,unique:x,numericPrecision:d,numericScale:p})}_compileDrop(e){const t=g(e,"removeType");return t===20||t==="OBJECT_INDEX"?this._compileDropIndex(e):t===51||t==="OBJECT_VIEW"?this._compileDropView(e):t===17||t==="OBJECT_FOREIGN_SERVER"?this._compileDropForeignServer(e):t===18||t==="OBJECT_FOREIGN_TABLE"?this._compileDropForeignTable(e):this._compileDropTable(e)}_compileDropTable(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){const s=P(r);let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(!this._tables.has(o)){if(n)continue;throw new Error(`Table "${o}" does not exist`)}this._tables.delete(o);for(const[i]of this._sequences)i.startsWith(`${o}_`)&&this._sequences.delete(i)}}return null}_compileDropView(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){let s=P(r);if(s.length===0){const i=g(w(r),"List");i!=null&&(s=P(g(w(i),"items")))}let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(!this._views.has(o)){if(n)continue;throw new Error(`View "${o}" does not exist`)}this._views.delete(o)}}return null}_compileDropIndex(e){return null}_compileCreateForeignServer(e){const t=j(e,"servername");if(this._foreignServers.has(t)){if(g(e,"if_not_exists")===!0)return null;throw new Error(`Foreign server '${t}' already exists`)}const n=j(e,"fdwname");if(n!=="duckdb_fdw"&&n!=="arrow_fdw")throw new Error(`Unsupported FDW type: '${n}'`);const r={},s=P(g(e,"options"));for(const o of s){const i=w(g(o,"DefElem")??o),a=j(i,"defname"),l=w(g(i,"arg")),u=j(l,"sval")||j(w(g(l,"String")??{}),"sval");a&&(r[a]=u)}return this._foreignServers.set(t,{name:t,fdwType:n,options:r}),null}_compileCreateForeignTable(e){const t=w(g(e,"base")),n=w(g(t,"relation")),r=ae(n);if(this._foreignTables.has(r)){if(g(t,"if_not_exists")===!0)return null;throw new Error(`Foreign table '${r}' already exists`)}if(this._tables.has(r))throw new Error(`Table '${r}' already exists`);const s=j(e,"servername");if(!this._foreignServers.has(s))throw new Error(`Foreign server '${s}' does not exist`);const o=new Map,i=P(g(t,"tableElts"));for(const u of i){const h=w(g(u,"ColumnDef")??u),f=this._parseColumnDef(h);o.set(f.name,f)}const a={},l=P(g(e,"options"));for(const u of l){const h=w(g(u,"DefElem")??u),f=j(h,"defname"),d=w(g(h,"arg")),p=j(d,"sval")||j(w(g(d,"String")??{}),"sval");f&&(a[f]=p)}return this._foreignTables.set(r,{name:r,serverName:s,columns:o,options:a}),null}_compileDropForeignServer(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){let s;if(Array.isArray(r)){const o=r;s=J(o[o.length-1])}else s=J(r);if(this._foreignServers.has(s)){for(const o of this._foreignTables.values())if(o.serverName===s)throw new Error(`Cannot drop server '${s}': foreign table '${o.name}' depends on it`);this._foreignServers.delete(s)}else if(!n)throw new Error(`Foreign server '${s}' does not exist`)}return null}_compileDropForeignTable(e){const t=P(g(e,"objects")),n=g(e,"missing_ok")===!0;for(const r of t){const s=P(r);let o;if(s.length>0?o=J(s[s.length-1]):o=J(r),!!o){if(this._foreignTables.has(o))this._foreignTables.delete(o);else if(!n)throw new Error(`Foreign table '${o}' does not exist`)}}return null}_compileCreateView(e){const t=w(g(e,"view")),n=ae(t);if(this._tables.has(n))throw new Error(`"${n}" already exists as a table`);if(this._views.has(n))throw new Error(`View "${n}" already exists`);const r=w(g(e,"query")),s=w(g(r,"SelectStmt")??r);return this._views.set(n,s),null}_compileCreateIndex(e){return null}_compileAlterTable(e){const t=w(g(e,"relation")),n=ae(t),r=this._tables.get(n);if(!r)throw new Error(`Table "${n}" does not exist`);const s=P(g(e,"cmds"));for(const o of s){const i=w(g(o,"AlterTableCmd")??o),a=g(i,"subtype"),l=typeof a=="string"?a:"";if(l==="AT_AddColumn"||a===0||a===14){const u=w(g(i,"def")),h=w(g(u,"ColumnDef")??u),f=this._parseColumnDef(h);if(r.columns.has(f.name))throw new Error(`Column "${f.name}" already exists in table "${n}"`);r.columns.set(f.name,f)}else if(l==="AT_DropColumn"||a===10||a===12){const u=j(i,"name"),h=g(i,"missing_ok")===!0;if(!r.columns.has(u)){if(h)continue;throw new Error(`Column "${u}" does not exist in table "${n}"`)}r.columns.delete(u);for(const f of r.documentStore.docIds){const d=r.documentStore.get(f);d&&u in d&&(Reflect.deleteProperty(d,u),r.documentStore.put(f,d))}}else if(l==="AT_ColumnDefault"||a===5||a===6){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=g(i,"def"),f=r.columns.get(u);if(h!=null){const p=new ie().evaluate(w(h),{});r.columns.set(u,Ie(f.name,f.typeName,{...f,defaultValue:p}))}else r.columns.set(u,Ie(f.name,f.typeName,{...f,defaultValue:null}))}else if(l==="AT_SetNotNull"||a===7||a===9){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);for(const f of r.documentStore.docIds){const d=r.documentStore.get(f);if(d){const p=d[u];if(p==null)throw new Error(`Column "${u}" contains NULL values; cannot set NOT NULL`)}}const h=r.columns.get(u);r.columns.set(u,Ie(h.name,h.typeName,{...h,notNull:!0}))}else if(l==="AT_DropNotNull"||a===6||a===8){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=r.columns.get(u);r.columns.set(u,Ie(h.name,h.typeName,{...h,notNull:!1}))}else if(l==="AT_AlterColumnType"||a===25||a===28){const u=j(i,"name");if(!r.columns.has(u))throw new Error(`Column "${u}" does not exist in table "${n}"`);const h=w(g(i,"def")),f=w(g(h,"ColumnDef")??h),d=w(g(f,"typeName")),p=[];for(const x of P(g(d,"names"))){const v=J(x);v&&v!=="pg_catalog"&&p.push(v)}const[m,_]=p.length>0?xr(p):["text","string"],y=r.columns.get(u);r.columns.set(u,Ie(u,m,{pythonType:_,primaryKey:y.primaryKey,notNull:y.notNull,autoIncrement:y.autoIncrement,defaultValue:y.defaultValue,vectorDimensions:y.vectorDimensions,unique:y.unique,numericPrecision:y.numericPrecision,numericScale:y.numericScale}));for(const x of Array.from(r.documentStore.docIds)){const v=r.documentStore.get(x);if(v&&v[u]!==null&&v[u]!==void 0){let E=v[u];_==="number"?(E=Number(E),isNaN(E)&&(E=v[u])):_==="string"?E=String(E):_==="boolean"&&(E=!!E),v[u]=E,r.documentStore.put(x,v)}}}else throw new Error(`Unsupported ALTER TABLE subcommand: ${String(a)}`)}return null}_compileRename(e){const t=g(e,"renameType"),n=typeof t=="string"?t:"";if(n==="OBJECT_TABLE"||t===36||t===42){const r=w(g(e,"relation")),s=ae(r),o=j(e,"newname"),i=this._tables.get(s);if(!i)throw new Error(`Table "${s}" does not exist`);if(this._tables.has(o))throw new Error(`Table "${o}" already exists`);return this._tables.delete(s),this._tables.set(o,i),null}if(n==="OBJECT_COLUMN"||t===8||t===9){const r=w(g(e,"relation")),s=ae(r),o=this._tables.get(s);if(!o)throw new Error(`Table "${s}" does not exist`);const i=j(e,"subname"),a=j(e,"newname");if(!o.columns.has(i))throw new Error(`Column "${i}" does not exist in table "${s}"`);if(o.columns.has(a))throw new Error(`Column "${a}" already exists in table "${s}"`);const l=[...o.columns.entries()];o.columns.clear();for(const[u,h]of l)if(u===i){const f=Ie(a,h.typeName,{...h});o.columns.set(a,f)}else o.columns.set(u,h);for(const u of o.documentStore.docIds){const h=o.documentStore.get(u);h&&i in h&&(h[a]=h[i],Reflect.deleteProperty(h,i),o.documentStore.put(u,h))}return null}throw new Error(`Unsupported RENAME type: ${String(t)}`)}_compileTruncate(e){const t=P(g(e,"relations"));for(const n of t){const r=w(g(n,"RangeVar")??n),s=ae(r),o=this._tables.get(s);if(!o)throw new Error(`Table "${s}" does not exist`);o.documentStore.clear(),o.invertedIndex.clear();for(const[,i]of o.vectorIndexes)i.clear();for(const[,i]of o.spatialIndexes)i.clear();o._nextDocId=1;for(const i of o.columns.values())if(i.autoIncrement){const a=`${s}_${i.name}_seq`,l=this._sequences.get(a);l&&(l.current=(l.start??1)-l.increment)}}return null}_compileInsert(e,t){const n=w(g(e,"relation")),r=ae(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);const o=P(g(e,"cols"));let i;o.length>0?i=o.map(S=>{const N=w(g(S,"ResTarget")??S);return j(N,"name")}):i=s.columnNames;const a=w(g(e,"selectStmt")),l=w(g(a,"SelectStmt")??a),u=P(g(l,"valuesLists")),h=new ie({params:t,sequences:this._sequences,subqueryExecutor:this._makeSubqueryExecutor(t)}),f=[];if(u.length===0){const S=this._compileSelect(l,t);for(const N of S.rows){const A={};for(let O=0;O<i.length;O++)O<S.columns.length&&(A[i[O]]=N[S.columns[O]]??null);f.push(A)}}else for(const S of u){const N=w(g(S,"List")),A=P(g(N,"items")??S);if(A.length!==i.length)throw new Error(`VALUES has ${String(A.length)} columns but ${String(i.length)} were specified`);const O={};for(let R=0;R<i.length;R++)O[i[R]]=yi(A[R],t,h);f.push(O)}const d=g(e,"onConflictClause");let p=[],m=null,_=[];if(d!=null){const S=w(d),N=w(g(S,"infer"));p=P(g(N,"indexElems")).map(O=>{const R=w(g(O,"IndexElem")??O);return j(R,"name")}),m=g(S,"action"),_=P(g(S,"targetList"))}const y=new Map;if(p.length>0)for(const S of s.documentStore.docIds){const N=s.documentStore.get(S);if(N!==null){const A=p.map(O=>JSON.stringify(N[O])).join("\0");y.set(A,S)}}const x=P(g(e,"returningList")),v=x.length>0,E=[];let I=0;for(const S of f){if(p.length>0&&d!==null){const A=p.map(R=>JSON.stringify(S[R])).join("\0"),O=y.get(A);if(O!==void 0){if(m===1||m==="ONCONFLICT_NOTHING")continue;this._doConflictUpdate(s,O,S,_,h);const R=s.documentStore.get(O);if(R!==null){const T=p.map(F=>JSON.stringify(R[F])).join("\0");T!==A&&(y.delete(A),y.set(T,O))}v&&R!==null&&E.push(this._evaluateReturning(x,R,h,s)),I++;continue}}const[N]=s.insert(S);if(I++,p.length>0){const A=p.map(O=>JSON.stringify(S[O])).join("\0");y.set(A,N)}if(v){const A=s.documentStore.get(N);A!==null&&E.push(this._evaluateReturning(x,A,h,s))}}return v?{columns:this._extractReturningColumns(x,s),rows:E}:{columns:["inserted"],rows:[{inserted:I}]}}_doConflictUpdate(e,t,n,r,s){const o=e.documentStore.get(t);if(o===null)return;const i={...o},a={...o};for(const[u,h]of Object.entries(n))a[`excluded.${u}`]=h;for(const u of r){const h=w(g(u,"ResTarget")??u),f=j(h,"name"),d=g(h,"val");if(d!=null){const p=s.evaluate(w(d),a);p!=null?i[f]=p:Reflect.deleteProperty(i,f)}}e.invertedIndex.removeDocument(t),e.documentStore.put(t,i);const l={};for(const[u,h]of Object.entries(i))typeof h=="string"&&(l[u]=h);Object.keys(l).length>0&&e.invertedIndex.addDocument(t,l)}_compileUpdate(e,t){const n=w(g(e,"relation")),r=ae(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);if(P(g(e,"fromClause")).length>0)return this._compileUpdateFrom(e,s,t);const i=g(e,"whereClause"),a=P(g(e,"targetList")),l=P(g(e,"returningList")),u=l.length>0,h=[],f=new ie({params:t,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)}),d=[];for(const m of a){const _=w(g(m,"ResTarget")??m),y=j(_,"name");if(!s.columns.has(y))throw new Error(`Unknown column "${y}" for table "${r}"`);d.push([y,w(g(_,"val"))])}let p=0;for(const[m,_]of s.documentStore.iterAll()){if(i!=null&&f.evaluate(w(i),_)!==!0)continue;const y={..._};for(const[v,E]of d){const I=f.evaluate(E,_),S=s.columns.get(v);if(I!=null)y[v]=I;else{if(S&&S.notNull)throw new Error(`NOT NULL constraint violated: column "${v}" in table "${r}"`);Reflect.deleteProperty(y,v)}}for(const v of s.fkUpdateValidators)v(_,y);s.invertedIndex.removeDocument(m),s.documentStore.put(m,y);const x={};for(const[v,E]of Object.entries(y))typeof E=="string"&&(x[v]=E);Object.keys(x).length>0&&s.invertedIndex.addDocument(m,x),u&&h.push(this._evaluateReturning(l,y,f,s)),p++}return u?{columns:this._extractReturningColumns(l,s),rows:h}:{columns:["updated"],rows:[{updated:p}]}}_compileUpdateFrom(e,t,n){const r=t.name,s=w(g(e,"relation")),o=Ue(s)??r,i=P(g(e,"fromClause")),a=g(e,"whereClause"),l=P(g(e,"targetList")),u=P(g(e,"returningList")),h=u.length>0,f=[],d=new ie({params:n,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(n)}),p=[];for(const y of l){const x=w(g(y,"ResTarget")??y),v=j(x,"name");if(!t.columns.has(v))throw new Error(`Unknown column "${v}" for table "${r}"`);p.push([v,w(g(x,"val"))])}const m=this._resolveFrom(i,n);let _=0;for(const[y,x]of t.documentStore.iterAll()){const v={...x};for(const[E,I]of Object.entries(x))v[`${o}.${E}`]=I;for(const E of m){const I={...v,...E};if(a!=null&&!d.evaluate(w(a),I))continue;const S={...x};for(const[A,O]of p){const R=d.evaluate(O,I),T=t.columns.get(A);if(R!=null)S[A]=R;else{if(T&&T.notNull)throw new Error(`NOT NULL constraint violated: column "${A}" in table "${r}"`);Reflect.deleteProperty(S,A)}}t.invertedIndex.removeDocument(y),t.documentStore.put(y,S);const N={};for(const[A,O]of Object.entries(S))typeof O=="string"&&(N[A]=O);Object.keys(N).length>0&&t.invertedIndex.addDocument(y,N),h&&f.push(this._evaluateReturning(u,S,d,t)),_++;break}}return h?{columns:this._extractReturningColumns(u,t),rows:f}:{columns:["updated"],rows:[{updated:_}]}}_compileDelete(e,t){const n=w(g(e,"relation")),r=ae(n),s=this._tables.get(r);if(!s)throw new Error(`Table "${r}" does not exist`);if(P(g(e,"usingClause")).length>0)return this._compileDeleteUsing(e,s,t);const i=g(e,"whereClause"),a=P(g(e,"returningList")),l=a.length>0,u=[],h=new ie({params:t,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)}),f=[];for(const[d,p]of s.documentStore.iterAll())i!=null&&h.evaluate(w(i),p)!==!0||(l&&u.push(this._evaluateReturning(a,p,h,s)),f.push(d));for(const d of f)for(const p of s.fkDeleteValidators)p(d);for(const d of f)s.invertedIndex.removeDocument(d),s.documentStore.delete(d);return l?{columns:this._extractReturningColumns(a,s),rows:u}:{columns:["deleted"],rows:[{deleted:f.length}]}}_compileDeleteUsing(e,t,n){const r=t.name,s=w(g(e,"relation")),o=Ue(s)??r,i=P(g(e,"usingClause")),a=g(e,"whereClause"),l=P(g(e,"returningList")),u=l.length>0,h=[],f=new ie({params:n,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(n)}),d=this._resolveFrom(i,n),p=[];for(const[m,_]of t.documentStore.iterAll()){const y={..._};for(const[x,v]of Object.entries(_))y[`${o}.${x}`]=v;for(const x of d){const v={...y,...x};if(!(a!=null&&!f.evaluate(w(a),v))){u&&h.push(this._evaluateReturning(l,_,f,t)),p.push(m);break}}}for(const m of p)t.invertedIndex.removeDocument(m),t.documentStore.delete(m);return u?{columns:this._extractReturningColumns(l,t),rows:h}:{columns:["deleted"],rows:[{deleted:p.length}]}}_compileTransaction(e){return g(e,"kind"),this._transactionActive=!this._transactionActive,null}_compilePrepare(e){const t=j(e,"name");if(this._prepared.has(t))throw new Error(`Prepared statement "${t}" already exists`);const n=w(g(e,"query"));return this._prepared.set(t,n),null}_compileExecute(e,t){const n=j(e,"name"),r=this._prepared.get(n);if(r===void 0)throw new Error(`Prepared statement "${n}" does not exist`);const s=P(g(e,"params")),o=new ie({params:t}),i=[];for(const l of s)i.push(o.evaluate(l,{}));const a=this._params;this._params=i;try{return this._dispatchStatement(r,i)}finally{this._params=a}}_compileDeallocate(e){const t=j(e,"name");if(!t)this._prepared.clear();else{if(!this._prepared.has(t))throw new Error(`Prepared statement "${t}" does not exist`);this._prepared.delete(t)}return null}_compileExplain(e,t){const n=w(g(e,"query")),r=w(g(n,"SelectStmt")??n),s=P(g(r,"fromClause"));let o=`${String(this._tables.size)} tables`;if(s.length>0){const a=s[0],l=w(g(a,"RangeVar")??a),u=ae(l);if(u){const h=this._tables.get(u);h&&(o=`table "${u}" (${String(h.rowCount)} rows)`)}}const i=`Seq Scan on ${o}`;return{columns:["QUERY PLAN"],rows:[{"QUERY PLAN":i}]}}_compileAnalyze(e){const t=e.rels;if(t&&t.length>0)for(const n of t){const r=n,o=(r.VacuumRelation??r).relation,i=o?o.relname:null;i&&this._tables.has(i)&&this._tables.get(i).analyze()}else for(const n of this._tables.values())n.analyze();return null}_compileSelect(e,t,n){const r=g(e,"withClause");let s=[];if(r!=null){const a=w(r),l=P(g(a,"ctes")),u=g(a,"recursive")===!0;s=this._materializeCTEs(l,t,u,e)}const o=this._correlatedOuterRow;this._correlatedOuterRow=n??null;const i=new Map(this._inlinedCTEs);try{return this._compileSelectBody(e,t)}finally{this._correlatedOuterRow=o;for(const a of s)this._inlinedCTEs.delete(a);this._inlinedCTEs=i;for(const a of s)this._tables.delete(a);for(const a of this._expandedViews)this._shadowedTables.has(a)?(this._tables.set(a,this._shadowedTables.get(a)),this._shadowedTables.delete(a)):this._tables.delete(a);this._expandedViews=[]}}_compileSelectBody(e,t){const n=P(g(e,"valuesLists"));if(n.length>0)return this._compileValues(n,t);const r=g(e,"op");if(r!=null&&r!==0&&r!=="SETOP_NONE")return this._compileSetOp(e,t);e=this._tryPredicatePushdown(e,t);const s=P(g(e,"fromClause")),o=g(e,"whereClause"),i=P(g(e,"targetList")),a=P(g(e,"groupClause")),l=g(e,"havingClause"),u=P(g(e,"sortClause")),h=g(e,"limitCount"),f=g(e,"limitOffset"),d=g(e,"distinctClause"),p=P(g(e,"windowClause")),m=new ie({params:t,sequences:this._sequences,outerRow:this._correlatedOuterRow??void 0,subqueryExecutor:this._makeSubqueryExecutor(t)});let _;if(s.length===0?_=[{}]:_=this._resolveFrom(s,t),o!=null){const S=w(o);if(le._containsUQAFunction(S)){const N=this._resolveFromTableName(s);if(N){const A=this._tables.get(N);if(A){const O=this._contextForTable(A),[R,T]=this._splitUQAConjuncts(S);let F=null;if(R&&(F=this._compileWhere(R,O)),F){const C=F.execute(O),V=[],Y=A.documentStore,oe=A.primaryKey;for(const xe of C){const ue=Y.get(xe.docId);if(!ue)continue;const ge={...ue,_score:xe.payload.score};oe&&(ge[oe]=xe.docId),ge._doc_id=xe.docId,V.push(ge)}_=V,T&&(_=_.filter(xe=>m.evaluate(w(T),xe)===!0))}}else _=_.filter(O=>m.evaluate(S,O)===!0)}else _=_.filter(A=>m.evaluate(S,A)===!0)}else _=_.filter(N=>m.evaluate(S,N)===!0)}const y=this._hasAggregates(i);a.length>0?_=this._applyGroupBy(_,a,i,l,m):y&&(_=this._applyGroupBy(_,[],i,l,m));const x=this._hasWindowFunctions(i);x&&(_=this._applyWindowFunctions(_,i,p,m));let v,E;a.length>0||y||x?(v=this._resolveSelectColumnNames(i,_),E=_):[v,E]=this._projectColumns(i,_,m);let I=E;if(d!=null&&(I=this._applyDistinct(I,v)),u.length>0&&(I=this._applyOrderBy(I,u,m,i)),f!=null){const S=Number(m.evaluate(w(f),{}));I=I.slice(S)}if(h!=null){const S=Number(m.evaluate(w(h),{}));I=I.slice(0,S)}return{columns:v,rows:I}}_materializeCTEs(e,t,n,r){const s=[];for(const o of e){const i=w(g(o,"CommonTableExpr")??o),a=j(i,"ctename"),l=w(g(i,"ctequery")),u=w(g(l,"SelectStmt")??l),h=g(u,"op");if(n&&h!==null&&h!==void 0&&h!==0&&h!=="SETOP_NONE")this._materializeRecursiveCTE(i,u,t);else if(this._countCTERefs(a,r)===1)this._inlinedCTEs.set(a,u);else{const p=this._compileSelect(u,t),m=this._resultToTable(a,p);this._tables.set(a,m)}s.push(a)}return s}_materializeRecursiveCTE(e,t,n){const r=j(e,"ctename"),s=g(t,"all")===!0,o=P(g(e,"aliascolnames")),i=o.length>0?o.map(x=>J(x)):null,a=w(g(t,"larg")),l=w(g(a,"SelectStmt")??a),u=this._compileSelect(l,n),h=u.columns;let f,d;if(i!==null){d=[];for(const x of u.rows){const v={};for(let E=0;E<i.length;E++)E<h.length&&(v[i[E]]=x[h[E]]??null);d.push(v)}f=i}else d=[...u.rows],f=h;let p=null;if(!s){p=new Set;const x=[];for(const v of d){const E=f.map(I=>JSON.stringify(v[I])).join("\0");p.has(E)||(p.add(E),x.push(v))}d=x}let m=[...d];for(let x=0;x<bi;x++){const v={columns:f,rows:m},E=this._resultToTable(r,v);this._tables.set(r,E);const I=w(g(t,"rarg")),S=w(g(I,"SelectStmt")??I),N=this._compileSelect(S,n),A=i??f,O=[];for(const T of N.rows){const F={};for(let C=0;C<A.length;C++)C<N.columns.length&&(F[A[C]]=T[N.columns[C]]??null);O.push(F)}if(O.length===0)break;let R=O;if(p!==null){R=[];for(const T of O){const F=f.map(C=>JSON.stringify(T[C])).join("\0");p.has(F)||(p.add(F),R.push(T))}if(R.length===0)break}d.push(...R),m=R}const _={columns:f,rows:d},y=this._resultToTable(r,_);this._tables.set(r,y)}_countCTERefs(e,t){if(t==null||typeof t!="object")return 0;if(Array.isArray(t)){let o=0;for(const i of t)o+=this._countCTERefs(e,i);return o}const n=t,r=g(n,"RangeVar");if(r!=null&&j(w(r),"relname")===e||j(n,"relname")===e)return 1;let s=0;for(const[o,i]of Object.entries(n))o!=="withClause"&&i!==null&&typeof i=="object"&&(s+=this._countCTERefs(e,i));return s}_resultToTable(e,t){const n=[];for(const s of t.columns){let o="text",i="string";for(const a of t.rows){const l=a[s];if(l!=null){typeof l=="boolean"?(o="text",i="string"):typeof l=="number"&&(Number.isInteger(l)?(o="integer",i="number"):(o="real",i="number"));break}}n.push(Ie(s,o,{pythonType:i}))}const r=new Ut(e,n);for(let s=0;s<t.rows.length;s++){const o=s+1,i={_id:o};Object.assign(i,t.rows[s]),r.documentStore.put(o,i)}return r}_compileSetOp(e,t){const n=g(e,"op"),r=w(g(e,"larg")),s=w(g(e,"rarg")),o=g(e,"all")===!0,i=w(g(r,"SelectStmt")??r),a=w(g(s,"SelectStmt")??s),l=this._compileSelect(i,t),u=this._compileSelect(a,t);if(l.columns.length!==u.columns.length)throw new Error(`Set operation column count mismatch: ${String(l.columns.length)} vs ${String(u.columns.length)}`);const h=l.columns,f=u.rows.map(y=>{const x={};for(let v=0;v<h.length;v++)x[h[v]]=y[u.columns[v]]??null;return x});let d;if(n===1||n==="SETOP_UNION")d=this._setUnion(l.rows,f,h,o);else if(n===2||n==="SETOP_INTERSECT")d=this._setIntersect(l.rows,f,h,o);else if(n===3||n==="SETOP_EXCEPT")d=this._setExcept(l.rows,f,h,o);else throw new Error(`Unsupported set operation: ${String(n)}`);const p=P(g(e,"sortClause"));if(p.length>0){const y=new ie({params:t}),x=P(g(i,"targetList"));d=this._applyOrderBy(d,p,y,x)}const m=g(e,"limitCount"),_=g(e,"limitOffset");if(_!=null){const y=new ie({params:t}),x=Number(y.evaluate(w(_),{}));d=d.slice(x)}if(m!=null){const y=new ie({params:t}),x=Number(y.evaluate(w(m),{}));d=d.slice(0,x)}return{columns:h,rows:d}}_setUnion(e,t,n,r){if(r)return[...e,...t];const s=new Set,o=[];for(const i of[...e,...t]){const a=n.map(l=>JSON.stringify(i[l])).join("\0");s.has(a)||(s.add(a),o.push(i))}return o}_setIntersect(e,t,n,r){if(r){const a=new Map;for(const u of t){const h=n.map(f=>JSON.stringify(u[f])).join("\0");a.set(h,(a.get(h)??0)+1)}const l=[];for(const u of e){const h=n.map(d=>JSON.stringify(u[d])).join("\0"),f=a.get(h)??0;f>0&&(l.push(u),a.set(h,f-1))}return l}const s=new Set(t.map(a=>n.map(l=>JSON.stringify(a[l])).join("\0"))),o=new Set,i=[];for(const a of e){const l=n.map(u=>JSON.stringify(a[u])).join("\0");s.has(l)&&!o.has(l)&&(o.add(l),i.push(a))}return i}_setExcept(e,t,n,r){if(r){const a=new Map;for(const u of t){const h=n.map(f=>JSON.stringify(u[f])).join("\0");a.set(h,(a.get(h)??0)+1)}const l=[];for(const u of e){const h=n.map(d=>JSON.stringify(u[d])).join("\0"),f=a.get(h)??0;f>0?a.set(h,f-1):l.push(u)}return l}const s=new Set(t.map(a=>n.map(l=>JSON.stringify(a[l])).join("\0"))),o=new Set,i=[];for(const a of e){const l=n.map(u=>JSON.stringify(a[u])).join("\0");!s.has(l)&&!o.has(l)&&(o.add(l),i.push(a))}return i}_compileValues(e,t){const n=new ie({params:t}),r=[];let s=0;for(const i of e){const a=w(g(i,"List")),l=P(g(a,"items")??i);s=Math.max(s,l.length);const u={};for(let h=0;h<l.length;h++){const f=`column${String(h+1)}`;u[f]=n.evaluate(l[h],{})}r.push(u)}const o=[];for(let i=0;i<s;i++)o.push(`column${String(i+1)}`);return{columns:o,rows:r}}_resolveFromTableName(e){if(e.length!==1)return null;const n=e[0].RangeVar;return n?n.relname??null:null}_resolveFrom(e,t){let n=null;for(const r of e){const s=g(r,"RangeSubselect");if(s!=null){const i=w(s);if(g(i,"lateral")===!0&&n!==null){n=this._resolveLateralJoin(n,i,t);continue}}const o=this._resolveFromItem(r,t);n===null?n=o:n=this._crossJoin(n,o)}return n??[{}]}_resolveFromItem(e,t){const n=g(e,"RangeVar");if(n!=null){const i=w(n),a=ae(i),l=Ue(i),u=pi(i);if(u==="information_schema")return this._buildInformationSchemaTable(a,l??a);if(u==="pg_catalog")return this._buildPgCatalogTable(a,l??a);const h=this._views.get(a);if(h!==void 0){const m=this._compileSelect(h,t);return this._applyAlias(m.rows,l??a)}const f=this._inlinedCTEs.get(a);if(f!==void 0){this._inlinedCTEs.delete(a);const m=this._compileSelect(f,t),_=this._resultToTable(a,m);this._tables.set(a,_),this._expandedViews.push(a);const y=[];for(const[,x]of _.documentStore.iterAll())y.push({...x});return this._applyAlias(y,l??a)}const d=this._tables.get(a);if(!d)throw new Error(`Table "${a}" does not exist`);const p=[];for(const[,m]of d.documentStore.iterAll())p.push({...m});return this._applyAlias(p,l??a)}const r=g(e,"JoinExpr");if(r!=null)return this._resolveJoin(w(r),t);const s=g(e,"RangeSubselect");if(s!=null){const i=w(s),a=w(g(i,"subquery")),l=w(g(a,"SelectStmt")??a),u=Ue(i),h=this._compileSelect(l,t);return this._applyAlias(h.rows,u)}const o=g(e,"RangeFunction");if(o!=null)return this._compileFromFunction(w(o),t);throw new Error("Unsupported FROM clause item")}_applyAlias(e,t){return t===null?e:e.map(n=>{const r={...n};for(const[s,o]of Object.entries(n))s.includes(".")||(r[`${t}.${s}`]=o);return r})}_resolveLateralJoin(e,t,n){const r=w(g(t,"subquery")),s=w(g(r,"SelectStmt")??r),o=Ue(t)??"_lateral",i=[];for(const a of e){const l=this._compileSelect(s,n,a);for(const u of l.rows){const h={};for(const[f,d]of Object.entries(u))h[f]=d,h[`${o}.${f}`]=d;i.push({...a,...h})}}return i}_compileFromFunction(e,t){const n=P(g(e,"functions"));if(n.length===0)throw new Error("Empty RangeFunction");const r=n[0],s=g(r,"List"),o=s!=null?P(g(w(s),"items")):P(r);if(o.length===0)throw new Error("Empty function list in RangeFunction");const i=w(g(o[0],"FuncCall")??o[0]),a=P(g(i,"funcname")),l=J(a[a.length-1]).toLowerCase(),u=P(g(i,"args")),h=Ue(e),f=w(g(e,"alias")),d=P(g(f,"colnames")),p=d.length>0?J(d[0]):null,m=new ie({params:t});if(l==="generate_series")return this._buildGenerateSeries(u,m,h??"generate_series",p??"generate_series");if(l==="unnest")return this._buildUnnest(u,m,h??"unnest",p??"unnest");if(l==="json_each"||l==="jsonb_each"||l==="json_each_text"||l==="jsonb_each_text")return this._buildJSONEach(u,m,h??l,l.endsWith("_text"));if(l==="json_array_elements"||l==="jsonb_array_elements"||l==="json_array_elements_text"||l==="jsonb_array_elements_text")return this._buildJSONArrayElements(u,m,h??l,l.endsWith("_text"));if(l==="regexp_split_to_table")return this._buildRegexpSplitToTable(u,m,h??"regexp_split_to_table",p??"regexp_split_to_table");if(l==="create_graph")return this._buildCreateGraph(u,m);if(l==="drop_graph")return this._buildDropGraph(u,m);if(l==="create_analyzer")return this._buildCreateAnalyzer(u,m);if(l==="drop_analyzer")return this._buildDropAnalyzer(u,m);if(l==="list_analyzers")return this._buildListAnalyzers();if(l==="set_table_analyzer")return this._buildSetTableAnalyzer(u,m);if(l==="graph_add_vertex")return this._buildGraphAddVertex(u,m);if(l==="graph_add_edge")return this._buildGraphAddEdge(u,m);if(l==="build_grid_graph")return this._buildGridGraph(u,m);if(l==="cypher")return this._buildCypherFrom(u,m);throw new Error(`Unsupported FROM-clause function: ${l}`)}_buildCreateGraph(e,t){if(!e.length)throw new Error("create_graph() requires a graph name");const n=String(t.evaluate(e[0],{}));return this._engine.createGraph(n),[{create_graph:`graph '${n}' created`}]}_buildDropGraph(e,t){if(!e.length)throw new Error("drop_graph() requires a graph name");const n=String(t.evaluate(e[0],{}));return this._engine.dropGraph(n),[{drop_graph:`graph '${n}' dropped`}]}_buildCreateAnalyzer(e,t){if(e.length<2)throw new Error("create_analyzer() requires (name, config_json)");const n=String(t.evaluate(e[0],{})),r=JSON.parse(String(t.evaluate(e[1],{})));return this._engine.createAnalyzer(n,r),[{create_analyzer:`analyzer '${n}' created`}]}_buildDropAnalyzer(e,t){if(!e.length)throw new Error("drop_analyzer() requires a name");const n=String(t.evaluate(e[0],{}));return this._engine.dropAnalyzer(n),[{drop_analyzer:`analyzer '${n}' dropped`}]}_buildListAnalyzers(){return xs().map(e=>({analyzer_name:e}))}_buildSetTableAnalyzer(e,t){if(e.length<3)throw new Error("set_table_analyzer(table, field, analyzer[, phase])");const n=String(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=String(t.evaluate(e[2],{})),o=e.length>3?String(t.evaluate(e[3],{})):"both";return this._engine.setTableAnalyzer(n,r,s,o),[{set_table_analyzer:`analyzer '${s}' assigned to ${n}.${r}`}]}_buildGraphAddVertex(e,t){if(e.length<3)throw new Error("graph_add_vertex(id, label, table[, props])");const n=Number(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=String(t.evaluate(e[2],{})),o={};if(e.length>3)for(const i of String(t.evaluate(e[3],{})).split(",")){const[a,l]=i.trim().split("=",2);a&&l&&(o[a.trim()]=isNaN(Number(l.trim()))?l.trim():Number(l.trim()))}return this._engine.addGraphVertex(an(n,r,o),{table:s}),[{result:`vertex ${String(n)} added to ${s}`}]}_buildGraphAddEdge(e,t){if(e.length<5)throw new Error("graph_add_edge(eid, src, tgt, label, table[, props])");const n=Number(t.evaluate(e[0],{})),r=Number(t.evaluate(e[1],{})),s=Number(t.evaluate(e[2],{})),o=String(t.evaluate(e[3],{})),i=String(t.evaluate(e[4],{})),a={};if(e.length>5)for(const l of String(t.evaluate(e[5],{})).split(",")){const[u,h]=l.trim().split("=",2);u&&h&&(a[u.trim()]=isNaN(Number(h.trim()))?h.trim():Number(h.trim()))}return this._engine.addGraphEdge(gt(n,r,s,o,a),{table:i}),[{result:`edge ${String(n)} added to ${i}`}]}_buildGridGraph(e,t){if(e.length<4)throw new Error("build_grid_graph(table, rows, cols, label)");const n=String(t.evaluate(e[0],{})),r=Number(t.evaluate(e[1],{})),s=Number(t.evaluate(e[2],{})),o=String(t.evaluate(e[3],{}));let i=1;for(let a=0;a<r;a++)for(let l=0;l<s;l++){const u=a*s+l+1;l<s-1&&this._engine.addGraphEdge(gt(i++,u,u+1,o),{table:n}),a<r-1&&this._engine.addGraphEdge(gt(i++,u,u+s,o),{table:n})}return[{table_name:n,rows:r,cols:s,edges:i-1}]}_buildCypherFrom(e,t){if(e.length<2)throw new Error("cypher() requires (graph_name, query)");const n=String(t.evaluate(e[0],{})),r=String(t.evaluate(e[1],{})),s=this._engine.getGraph(n),o={};for(let a=0;a<this._params.length;a++)o[String(a+1)]=this._params[a];return new yo(s,n,o).executeRows(r,o)}_buildGenerateSeries(e,t,n,r){if(e.length<2)throw new Error("generate_series requires at least 2 arguments");const s=Number(t.evaluate(e[0],{})),o=Number(t.evaluate(e[1],{})),i=e.length>2?Number(t.evaluate(e[2],{})):1;if(i===0)throw new Error("generate_series step cannot be zero");const a=[];if(i>0)for(let l=s;l<=o;l+=i){const u={[r]:l};u[`${n}.${r}`]=l,a.push(u)}else for(let l=s;l>=o;l+=i){const u={[r]:l};u[`${n}.${r}`]=l,a.push(u)}return a}_buildUnnest(e,t,n,r){if(e.length<1)throw new Error("unnest requires at least 1 argument");let s=t.evaluate(e[0],{});Array.isArray(s)||(s=[s]);const o=[];for(const i of s){const a={[r]:i};a[`${n}.${r}`]=i,o.push(a)}return o}_buildJSONEach(e,t,n,r){if(e.length<1)throw new Error("json_each requires at least 1 argument");let s=t.evaluate(e[0],{});if(typeof s=="string"&&(s=JSON.parse(s)),s===null||typeof s!="object"||Array.isArray(s))throw new Error("json_each expects a JSON object");const o=[];for(const[i,a]of Object.entries(s)){const l=r?String(a):a,u={key:i,value:l};u[`${n}.key`]=i,u[`${n}.value`]=l,o.push(u)}return o}_buildJSONArrayElements(e,t,n,r){if(e.length<1)throw new Error("json_array_elements requires at least 1 argument");let s=t.evaluate(e[0],{});if(typeof s=="string"&&(s=JSON.parse(s)),!Array.isArray(s))throw new Error("json_array_elements expects a JSON array");const o=[];for(const i of s){const a=r?String(i):i,l={value:a};l[`${n}.value`]=a,o.push(l)}return o}_buildRegexpSplitToTable(e,t,n,r){if(e.length<2)throw new Error("regexp_split_to_table requires at least 2 arguments");const s=String(t.evaluate(e[0],{})),o=String(t.evaluate(e[1],{})),i=e.length>2?String(t.evaluate(e[2],{})):"",a=new RegExp(o,i.includes("g")?i:i+"g"),l=s.split(a),u=[];for(const h of l){const f={[r]:h};f[`${n}.${r}`]=h,u.push(f)}return u}_crossJoin(e,t){const n=[];for(const r of e)for(const s of t)n.push({...r,...s});return n}_resolveJoin(e,t){const n=g(e,"jointype"),r=w(g(e,"larg")),s=w(g(e,"rarg")),o=g(e,"quals"),i=g(s,"RangeSubselect");if(i!=null){const _=w(i);if(g(_,"lateral")===!0){const y=this._resolveFromItem(r,t);return this._resolveLateralJoin(y,_,t)}}const a=this._resolveFromItem(r,t),l=this._resolveFromItem(s,t),u=new ie({params:t});if(n===5||n==="JOIN_CROSS")return this._crossJoin(a,l);if((n===0||n==="JOIN_INNER")&&o==null)return this._crossJoin(a,l);const h=[],f=n===1||n==="JOIN_LEFT",d=n===3||n==="JOIN_RIGHT",p=n===2||n==="JOIN_FULL",m=new Set;for(const _ of a){let y=!1;for(let x=0;x<l.length;x++){const v=l[x],E={..._,...v};o!=null&&u.evaluate(w(o),E)!==!0||(h.push(E),y=!0,m.add(x))}if(!y&&(f||p)){const x={..._};if(l.length>0)for(const v of Object.keys(l[0]))v in x||(x[v]=null);h.push(x)}}if(d||p){for(let _=0;_<l.length;_++)if(!m.has(_)){const y={};if(a.length>0)for(const x of Object.keys(a[0]))y[x]=null;for(const[x,v]of Object.entries(l[_]))y[x]=v;h.push(y)}}return h}_buildInformationSchemaTable(e,t){if(e==="tables"){const n=[];for(const r of[...this._tables.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"BASE TABLE"});for(const r of[...this._foreignTables.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"FOREIGN TABLE"});for(const r of[...this._views.keys()].sort())n.push({table_catalog:"",table_schema:"public",table_name:r,table_type:"VIEW"});return this._applyAlias(n,t)}if(e==="columns"){const n={int2:"smallint",int4:"integer",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean"},r=[];for(const s of[...this._tables.keys()].sort()){const o=this._tables.get(s);let i=1;for(const[a,l]of o.columns){const u=n[l.typeName]??l.typeName;r.push({table_catalog:"",table_schema:"public",table_name:s,column_name:a,ordinal_position:i,data_type:u,is_nullable:l.notNull?"NO":"YES"}),i++}}for(const s of[...this._foreignTables.keys()].sort()){const o=this._foreignTables.get(s);let i=1;for(const[a,l]of o.columns){const u=n[l.typeName]??l.typeName;r.push({table_catalog:"",table_schema:"public",table_name:s,column_name:a,ordinal_position:i,data_type:u,is_nullable:l.notNull?"NO":"YES"}),i++}}return this._applyAlias(r,t)}throw new Error(`Unknown information_schema view: "${e}"`)}_buildPgCatalogTable(e,t){if(e==="pg_tables"){const n=[];for(const r of[...this._tables.keys()].sort())n.push({schemaname:"public",tablename:r,tableowner:"",tablespace:""});return this._applyAlias(n,t)}if(e==="pg_views"){const n=[];for(const r of[...this._views.keys()].sort())n.push({schemaname:"public",viewname:r,viewowner:"",definition:""});return this._applyAlias(n,t)}if(e==="pg_indexes"){const n=[],r=this._engine,s=r!==null?r._indexManager:void 0;if(s!==void 0){const o=s._indexes;if(o!==void 0)for(const i of o.values()){const a=i.indexDef;if(a!==void 0){const l=a.tableName??"",u=a.name??"",h=a.columns??[];n.push({schemaname:"public",tablename:l,indexname:u,tablespace:"",indexdef:`CREATE INDEX ${u} ON ${l} (${h.join(", ")})`})}}}return this._applyAlias(n,t)}if(e==="pg_type"){const r=[[16,"boolean",11,1,"b","B"],[17,"bytea",11,-1,"b","U"],[20,"bigint",11,8,"b","N"],[21,"smallint",11,2,"b","N"],[23,"integer",11,4,"b","N"],[25,"text",11,-1,"b","S"],[114,"json",11,-1,"b","U"],[142,"xml",11,-1,"b","U"],[700,"real",11,4,"b","N"],[701,"float8",11,8,"b","N"],[1043,"varchar",11,-1,"b","S"],[1082,"date",11,4,"b","D"],[1083,"time",11,8,"b","D"],[1114,"timestamp",11,8,"b","D"],[1184,"timestamptz",11,8,"b","D"],[1186,"interval",11,16,"b","T"],[1700,"numeric",11,-1,"b","N"],[2950,"uuid",11,16,"b","U"],[3802,"jsonb",11,-1,"b","U"],[16385,"vector",11,-1,"b","U"]].map(([s,o,i,a,l,u])=>({oid:s,typname:o,typnamespace:i,typlen:a,typtype:l,typcategory:u}));return this._applyAlias(r,t)}throw new Error(`Unknown pg_catalog view: "${e}"`)}_projectColumns(e,t,n){if(e.length===0){if(t.length===0)return[[],[]];const i=Object.keys(t[0]).filter(a=>!a.includes("."));return[i,t.map(a=>{const l={};for(const u of i)l[u]=a[u];return l})]}const r=[],s=[];for(const i of e){const a=w(g(i,"ResTarget")??i),l=g(a,"val"),u=j(a,"name");if(l!=null){const h=w(l);if(tt(h)){const d=g(h,"ColumnRef");if(d!=null){const p=P(g(w(d),"fields"));if(p.length>=2){const m=J(p[0]);if(t.length>0)for(const _ of Object.keys(t[0])){const y=`${m}.`;if(_.startsWith(y)){const x=_.slice(y.length);x.includes(".")||(r.push(x),s.push({name:x,node:null}))}}continue}}if(t.length>0)for(const p of Object.keys(t[0]))p.includes(".")||(r.push(p),s.push({name:p,node:null}));continue}let f=u;f||(f=this._deriveColumnName(h)),r.push(f),s.push({name:f,node:h})}}const o=[];for(const i of t){const a={};for(const l of s)l.node===null?a[l.name]=i[l.name]:a[l.name]=n.evaluate(l.node,i);o.push(a)}return[r,o]}_deriveColumnName(e){if(X(e))try{return B(e)}catch{}if(Q(e)){const t=ce(e);if(et.has(t)){const n=ve(e);if(nt(e)||n.length===0)return t;try{const r=B(n[0]);return`${t}_${r}`}catch{return t}}return t}if(rn(e)){const t=w(g(e,"TypeCast")),n=w(g(t,"arg"));if(X(n))try{return B(n)}catch{}}return nn(e),"?column?"}_resolveSelectColumnNames(e,t){if(e.length===0)return t.length===0?[]:Object.keys(t[0]).filter(r=>!r.includes("."));const n=[];for(const r of e){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!=null){const a=w(o);if(tt(a)){if(t.length>0)for(const l of Object.keys(t[0]))l.includes(".")||n.push(l);continue}n.push(i||this._deriveColumnName(a))}}return n}_hasAggregates(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&this._containsAggregate(w(r)))return!0}return!1}_containsAggregate(e){if(Q(e)){const t=ce(e);if(et.has(t)&&!rt(e))return!0}if(nn(e)||g(e,"SubLink")!==null)return!1;for(const[,t]of Object.entries(e))if(t!==null&&typeof t=="object"){if(Array.isArray(t)){for(const n of t)if(n!==null&&typeof n=="object"&&this._containsAggregate(n))return!0}else if(this._containsAggregate(t))return!0}return!1}_applyGroupBy(e,t,n,r,s){const o=new Map;if(t.length===0)o.set("__all__",e);else for(const l of e){const u=[];for(const d of t){const p=s.evaluate(d,l);u.push(p)}const h=JSON.stringify(u);let f=o.get(h);f||(f=[],o.set(h,f)),f.push(l)}const i=[],a=[];for(const[,l]of o){const u=this._computeAggregates(l,n,s);i.push(u),a.push(l)}if(r!=null){const l=[];for(let u=0;u<i.length;u++){const h=i[u],f=a[u],d=this._resolveHavingAggregates(w(r),f,h,s);s.evaluate(w(r),d)===!0&&l.push(h)}return l}return i}_computeAggregates(e,t,n){const r={},s=e[0];for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(Q(u)){const h=ce(u),f=nt(u),d=ve(u),p=Qr(u);if(rt(u)){const v=l||h;r[v]=n.evaluate(u,s);continue}if(!et.has(h)){const v={...s};this._collectHavingAggregates(u,e,v,n);const E=l||this._deriveColumnName(u);r[E]=n.evaluate(u,v);continue}let _=l;if(!_)if(f||d.length===0)_=h;else try{const v=B(d[0]);_=`${h}_${v}`}catch{_=h}let y;const x=()=>{let v=[];for(const E of e){const I=n.evaluate(d[0],E);I!=null&&v.push(I)}if(p){const E=new Set,I=[];for(const S of v){const N=JSON.stringify(S);E.has(N)||(E.add(N),I.push(S))}v=I}return v};switch(h){case"count":f?y=e.length:y=x().length;break;case"sum":{const v=x();y=v.length>0?v.reduce((E,I)=>E+Number(I),0):null;break}case"avg":{const v=x();v.length>0?y=v.reduce((I,S)=>I+Number(S),0)/v.length:y=null;break}case"min":{const v=x();v.length===0?y=null:y=v.reduce((E,I)=>E<I?E:I);break}case"max":{const v=x();v.length===0?y=null:y=v.reduce((E,I)=>E>I?E:I);break}case"string_agg":{const v=d.length>=2?String(n.evaluate(d[1],s)):",",E=[];for(const I of e){const S=n.evaluate(d[0],I);S!=null&&E.push(Xr(S))}y=E.length>0?E.join(v):null;break}case"array_agg":{const v=[];for(const E of e)v.push(n.evaluate(d[0],E));y=v;break}case"bool_and":{const v=x();y=v.length>0?v.every(E=>!!E):null;break}case"bool_or":{const v=x();y=v.length>0?v.some(E=>!!E):null;break}case"stddev":case"stddev_samp":{const v=x().map(Number);if(v.length<2)y=null;else{const E=v.reduce((S,N)=>S+N,0)/v.length,I=v.reduce((S,N)=>S+(N-E)**2,0)/(v.length-1);y=Math.sqrt(I)}break}case"stddev_pop":{const v=x().map(Number);if(v.length===0)y=null;else{const E=v.reduce((S,N)=>S+N,0)/v.length,I=v.reduce((S,N)=>S+(N-E)**2,0)/v.length;y=Math.sqrt(I)}break}case"variance":case"var_samp":{const v=x().map(Number);if(v.length<2)y=null;else{const E=v.reduce((I,S)=>I+S,0)/v.length;y=v.reduce((I,S)=>I+(S-E)**2,0)/(v.length-1)}break}case"var_pop":{const v=x().map(Number);if(v.length===0)y=null;else{const E=v.reduce((I,S)=>I+S,0)/v.length;y=v.reduce((I,S)=>I+(S-E)**2,0)/v.length}break}case"json_object_agg":case"jsonb_object_agg":{if(d.length<2)y=null;else{const v={};for(const E of e){const I=n.evaluate(d[0],E),S=n.evaluate(d[1],E);I!=null&&(v[String(I)]=S)}y=v}break}case"percentile_cont":{if(d.length>0){const v=Number(n.evaluate(d[0],s)),E=w(g(u,"FuncCall")??u),I=P(g(E,"agg_order"));if(I.length>0){const S=w(g(I[0],"SortBy")??I[0]),N=w(g(S,"node")),A=[];for(const O of e){const R=n.evaluate(N,O);R!=null&&A.push(Number(R))}if(A.sort((O,R)=>O-R),A.length===0)y=null;else{const O=v*(A.length-1),R=Math.floor(O),T=Math.ceil(O);R===T?y=A[R]:y=A[R]+(O-R)*(A[T]-A[R])}}else y=null}else y=null;break}case"mode":{const v=w(g(u,"FuncCall")??u),E=P(g(v,"agg_order"));if(E.length>0){const I=w(g(E[0],"SortBy")??E[0]),S=w(g(I,"node")),N=new Map;for(const R of e){const T=n.evaluate(S,R),F=JSON.stringify(T),C=N.get(F);C?C.count++:N.set(F,{count:1,value:T})}let A=0,O=null;for(const R of N.values())R.count>A&&(A=R.count,O=R.value);y=O}else y=null;break}case"corr":case"covar_pop":case"covar_samp":case"regr_count":case"regr_avgx":case"regr_avgy":case"regr_sxx":case"regr_syy":case"regr_sxy":case"regr_slope":case"regr_intercept":case"regr_r2":{if(d.length<2){y=null;break}const v=[],E=[];for(const I of e){const S=n.evaluate(d[0],I),N=n.evaluate(d[1],I);S!=null&&N!==null&&N!==void 0&&(v.push(Number(S)),E.push(Number(N)))}y=this._computeStatAgg(h,v,E);break}default:y=n.evaluate(u,s);break}r[_]=y}else{const h=l||this._deriveColumnName(u);r[h]=n.evaluate(u,s)}}return r}_computeStatAgg(e,t,n){const r=t.length;if(r===0)return null;const s=n.reduce((f,d)=>f+d,0),o=t.reduce((f,d)=>f+d,0),i=s/r,a=o/r;let l=0,u=0,h=0;for(let f=0;f<r;f++){const d=n[f]-i,p=t[f]-a;l+=d*d,u+=p*p,h+=d*p}switch(e){case"regr_count":return r;case"regr_avgx":return i;case"regr_avgy":return a;case"regr_sxx":return l;case"regr_syy":return u;case"regr_sxy":return h;case"covar_pop":return h/r;case"covar_samp":return r<2?null:h/(r-1);case"corr":return l===0||u===0?null:h/Math.sqrt(l*u);case"regr_slope":return l===0?null:h/l;case"regr_intercept":return l===0?null:a-h/l*i;case"regr_r2":{if(l===0||u===0)return null;const f=h/Math.sqrt(l*u);return f*f}default:return null}}_resolveHavingAggregates(e,t,n,r){const s={...n};return this._collectHavingAggregates(e,t,s,r),s}_collectHavingAggregates(e,t,n,r){const s=e.FuncCall;if(s){const a=s.funcname;if(a.length>0){const l=a[a.length-1],u=l.String??l.str,h=typeof u=="object"&&u!==null?u.sval??u.str:u;if(h&&et.has(h.toLowerCase())){const f=this._computeInlineAggregate(h.toLowerCase(),s,t,r),d=nt(e),p=ve(e);let m;if(d||p.length===0)m=`${h.toLowerCase()}(*)`;else try{const _=B(p[0]);m=`${h.toLowerCase()}(${_})`}catch{m=h.toLowerCase()}n[m]=f,n[`__having_agg_${JSON.stringify(e)}`]=f;return}}}const o=e.BoolExpr;if(o){const a=P(o.args);for(const l of a)this._collectHavingAggregates(w(l),t,n,r);return}const i=e.A_Expr;if(i){const a=i.lexpr,l=i.rexpr;a&&this._collectHavingAggregates(w(a),t,n,r),l&&this._collectHavingAggregates(w(l),t,n,r);return}for(const a of Object.values(e))if(Array.isArray(a))for(const l of a)typeof l=="object"&&l!==null&&this._collectHavingAggregates(l,t,n,r);else typeof a=="object"&&a!==null&&this._collectHavingAggregates(a,t,n,r)}_computeInlineAggregate(e,t,n,r){const s={FuncCall:t},o=nt(s),i=ve(s),a=Qr(s),l=()=>{let h=[];for(const f of n){const d=i.length>0?r.evaluate(i[0],f):null;d!=null&&h.push(d)}if(a){const f=new Set,d=[];for(const p of h){const m=JSON.stringify(p);f.has(m)||(f.add(m),d.push(p))}h=d}return h},u=()=>{const h=[];if(i.length<2)return h;for(const f of n){const d=r.evaluate(i[0],f),p=r.evaluate(i[1],f);d!=null&&p!==null&&p!==void 0&&h.push([Number(d),Number(p)])}return h};switch(e){case"count":return o?n.length:l().length;case"sum":{const h=l();return h.length>0?h.reduce((f,d)=>f+Number(d),0):null}case"avg":{const h=l();return h.length>0?h.reduce((f,d)=>f+Number(d),0)/h.length:null}case"min":{const h=l();return h.length>0?h.reduce((f,d)=>Number(f)<Number(d)?f:d):null}case"max":{const h=l();return h.length>0?h.reduce((f,d)=>Number(f)>Number(d)?f:d):null}case"stddev":case"stddev_samp":{const h=l().map(Number);if(h.length<2)return null;const f=h.reduce((p,m)=>p+m,0)/h.length,d=h.reduce((p,m)=>p+(m-f)**2,0)/(h.length-1);return Math.sqrt(d)}case"stddev_pop":{const h=l().map(Number);if(h.length===0)return null;const f=h.reduce((p,m)=>p+m,0)/h.length,d=h.reduce((p,m)=>p+(m-f)**2,0)/h.length;return Math.sqrt(d)}case"variance":case"var_samp":{const h=l().map(Number);if(h.length<2)return null;const f=h.reduce((d,p)=>d+p,0)/h.length;return h.reduce((d,p)=>d+(p-f)**2,0)/(h.length-1)}case"var_pop":{const h=l().map(Number);if(h.length===0)return null;const f=h.reduce((d,p)=>d+p,0)/h.length;return h.reduce((d,p)=>d+(p-f)**2,0)/h.length}case"corr":case"covar_pop":case"covar_samp":case"regr_slope":case"regr_intercept":case"regr_r2":case"regr_count":case"regr_avgx":case"regr_avgy":case"regr_sxx":case"regr_syy":case"regr_sxy":{const h=u();if(h.length===0)return null;const f=h.length,d=h.reduce((x,v)=>x+v[0],0)/f,p=h.reduce((x,v)=>x+v[1],0)/f;let m=0,_=0,y=0;for(const[x,v]of h)m+=(v-p)**2,_+=(x-d)**2,y+=(v-p)*(x-d);switch(e){case"corr":return m===0||_===0?null:y/Math.sqrt(m*_);case"covar_pop":return y/f;case"covar_samp":return f<2?null:y/(f-1);case"regr_slope":return m===0?null:y/m;case"regr_intercept":return m===0?null:d-y/m*p;case"regr_r2":return m===0||_===0?null:y*y/(m*_);case"regr_count":return f;case"regr_avgx":return p;case"regr_avgy":return d;case"regr_sxx":return m;case"regr_syy":return _;case"regr_sxy":return y;default:return null}}default:return null}}_hasWindowFunctions(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&Q(w(r))&&rt(w(r)))return!0}return!1}_applyWindowFunctions(e,t,n,r){const s=new Map;for(const o of n){const i=w(g(o,"WindowDef")??o),a=j(i,"name");a&&s.set(a,i)}for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(!Q(u)||!rt(u))continue;const h=ce(u),f=l||h,d=w(g(u,"FuncCall")??u),p=ve(u),m=w(g(d,"over")),_=j(m,"refname")||j(m,"name");let y=m;_&&s.has(_)&&(y=s.get(_));const x=[];for(const I of P(g(y,"partitionClause")))try{x.push(B(I))}catch{}const v=[];for(const I of P(g(y,"orderClause"))){const S=w(g(I,"SortBy")??I),N=w(g(S,"node"));try{const A=B(N),O=g(S,"sortby_dir"),R=O===2||O==="SORTBY_DESC";v.push({col:A,desc:R})}catch{}}const E=new Map;for(let I=0;I<e.length;I++){const S=e[I],N=x.map(O=>JSON.stringify(S[O])).join("\0");let A=E.get(N);A||(A={rows:[],indices:[]},E.set(N,A)),A.rows.push(S),A.indices.push(I)}for(const I of E.values())if(v.length>0){const S=I.rows.map((N,A)=>({row:N,origIdx:I.indices[A]}));S.sort((N,A)=>{for(const O of v){const R=N.row[O.col],T=A.row[O.col],F=R==null,C=T==null;if(F&&C)continue;if(F)return O.desc?-1:1;if(C)return O.desc?1:-1;let V;if(typeof R=="string"&&typeof T=="string"?V=R<T?-1:R>T?1:0:V=R-T,V!==0)return O.desc?-V:V}return 0}),I.rows=S.map(N=>N.row),I.indices=S.map(N=>N.origIdx)}for(const I of E.values()){const S=I.rows,N=S.length;for(let A=0;A<N;A++){let O=null;switch(h){case"row_number":O=A+1;break;case"rank":{let T=1;for(let F=0;F<A;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}C||(T=F+1+1)}T=1;for(let F=0;F<A;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}C||T++}T=1;for(let F=0;F<N;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}if(C){T=F+1;break}}O=T;break}case"dense_rank":{const T=new Set;for(let F=0;F<=A;F++){const C=v.map(V=>JSON.stringify(S[F][V.col])).join("\0");T.add(C)}O=T.size;break}case"percent_rank":{if(N<=1)O=0;else{let T=1;for(let F=0;F<N;F++){let C=!0;for(const V of v)if(S[F][V.col]!==S[A][V.col]){C=!1;break}if(C){T=F+1;break}}O=(T-1)/(N-1)}break}case"cume_dist":{let T=0;for(let F=0;F<N;F++){let C=!0;for(const V of v){const Y=S[F][V.col],oe=S[A][V.col];V.desc?Y<oe&&(C=!1):Y>oe&&(C=!1)}C&&T++}O=T/N;break}case"ntile":{const T=p.length>0?Number(r.evaluate(p[0],{})):1;O=Math.floor(A*T/N)+1;break}case"lag":{const T=p.length>1?Number(r.evaluate(p[1],{})):1,F=p.length>2?r.evaluate(p[2],{}):null,C=A-T;C>=0&&C<N&&p.length>0?O=r.evaluate(p[0],S[C]):O=F;break}case"lead":{const T=p.length>1?Number(r.evaluate(p[1],{})):1,F=p.length>2?r.evaluate(p[2],{}):null,C=A+T;C>=0&&C<N&&p.length>0?O=r.evaluate(p[0],S[C]):O=F;break}case"first_value":{p.length>0&&N>0&&(O=r.evaluate(p[0],S[0]));break}case"last_value":{p.length>0&&N>0&&(O=r.evaluate(p[0],S[N-1]));break}case"nth_value":{const T=p.length>1?Number(r.evaluate(p[1],{})):1;p.length>0&&T>=1&&T<=N&&(O=r.evaluate(p[0],S[T-1]));break}case"sum":{let T=0,F=!1;const C=v.length>0?A:N-1;for(let V=0;V<=C;V++){const Y=p.length>0?r.evaluate(p[0],S[V]):null;Y!=null&&(T+=Number(Y),F=!0)}O=F?T:null;break}case"count":{const T=v.length>0?A:N-1;if(nt(u))O=T+1;else{let F=0;for(let C=0;C<=T;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&F++}O=F}break}case"avg":{let T=0,F=0;const C=v.length>0?A:N-1;for(let V=0;V<=C;V++){const Y=p.length>0?r.evaluate(p[0],S[V]):null;Y!=null&&(T+=Number(Y),F++)}O=F>0?T/F:null;break}case"min":{let T=null;const F=v.length>0?A:N-1;for(let C=0;C<=F;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&(T===null||V<T)&&(T=V)}O=T;break}case"max":{let T=null;const F=v.length>0?A:N-1;for(let C=0;C<=F;C++){const V=p.length>0?r.evaluate(p[0],S[C]):null;V!=null&&(T===null||V>T)&&(T=V)}O=T;break}default:O=null;break}const R=I.indices[A];e[R][f]=O}}}for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a==null)continue;const u=w(a);if(Q(u)&&rt(u))continue;const h=l||this._deriveColumnName(u);if(X(u)){const f=B(u);if(f!==h)for(const d of e)d[h]=d[f]}else for(const f of e)f[h]=r.evaluate(u,f)}return e}_applyDistinct(e,t){const n=new Set,r=[];for(const s of e){const o=t.map(i=>JSON.stringify(s[i])).join("\0");n.has(o)||(n.add(o),r.push(s))}return r}_applyOrderBy(e,t,n,r){const s=[...e],o=new Map,i=new Set,a=new Map;if(r)for(let u=0;u<r.length;u++){const h=w(g(r[u],"ResTarget")??r[u]),f=j(h,"name"),d=g(h,"val");let p=f;if(!p&&d!==null&&d!==void 0&&(p=this._deriveColumnName(w(d))),p&&(o.set(u+1,p),f&&(i.add(f),d!==null&&X(w(d)))))try{const m=B(w(d));a.set(m,f)}catch{}}const l=t.map(u=>{const h=w(g(u,"SortBy")??u),f=w(g(h,"node")),d=g(h,"sortby_dir"),p=d===2||d==="SORTBY_DESC",m=g(h,"sortby_nulls");let _;m===1||m==="SORTBY_NULLS_FIRST"?_=!0:m===2||m==="SORTBY_NULLS_LAST"?_=!1:_=p;let y=f;if(be(f)){const x=z(f,[]);if(typeof x=="number"&&Number.isInteger(x)){const v=x,E=o.get(v);E!==void 0&&(y={ColumnRef:{fields:[{String:{sval:E}}]}})}}if(X(y))try{const x=B(y);a.has(x)&&(y={ColumnRef:{fields:[{String:{sval:a.get(x)}}]}})}catch{}return{node:y,desc:p,nullsFirst:_}});return s.sort((u,h)=>{for(const f of l){const d=n.evaluate(f.node,u),p=n.evaluate(f.node,h),m=d==null,_=p==null;if(m&&_)continue;if(m)return f.nullsFirst?-1:1;if(_)return f.nullsFirst?1:-1;let y;if(typeof d=="string"&&typeof p=="string"?y=d<p?-1:d>p?1:0:y=d-p,y!==0)return f.desc?-y:y}return 0}),s}_evaluateReturning(e,t,n,r){const s={};for(const o of e){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a!=null){const u=w(a);if(tt(u)){if(r)for(const f of r.columnNames)s[f]=t[f]??null;else Object.assign(s,t);continue}const h=l||this._deriveColumnName(u);s[h]=n.evaluate(u,t)}}return s}_extractReturningColumns(e,t){const n=[];for(const r of e){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!=null){const a=w(o);if(tt(a)){t&&n.push(...t.columnNames);continue}n.push(i||this._deriveColumnName(a))}}return n}_contextForTable(e){if(e===null)return{};const t={};for(const[r,s]of e.vectorIndexes)t[r]=s;const n={};for(const[r,s]of e.spatialIndexes)n[r]=s;return{documentStore:e.documentStore,invertedIndex:e.invertedIndex,vectorIndexes:t,spatialIndexes:n}}static _containsUQAFunction(e){if(Q(e)){const s=ce(e);if(Yr.has(s))return!0}const t=w(g(e,"FuncCall")??{});if(Object.keys(t).length>0){const s=ce(t);if(Yr.has(s))return!0}const n=w(g(e,"A_Expr")??{});if(Object.keys(n).length>0){const s=P(g(n,"name"));if(s.length>0&&J(s[0])==="@@")return!0}for(const s of["lexpr","rexpr","args","arg"]){const o=g(e,s)??g(n,s);if(o!=null){if(Array.isArray(o)){for(const i of o)if(le._containsUQAFunction(w(i)))return!0}else if(typeof o=="object"&&le._containsUQAFunction(w(o)))return!0}}const r=w(g(e,"BoolExpr")??{});if(Object.keys(r).length>0){const s=P(g(r,"args"));for(const o of s)if(le._containsUQAFunction(o))return!0}return!1}_splitUQAConjuncts(e){const t=this._extractAndConjuncts(e),n=[],r=[];for(const i of t)le._containsUQAFunction(i)?n.push(i):r.push(i);const s=n.length===0?null:n.length===1?n[0]:{BoolExpr:{boolop:0,args:n}},o=r.length===0?null:r.length===1?r[0]:{BoolExpr:{boolop:0,args:r}};return[s,o]}_extractAndConjuncts(e){const t=w(g(e,"BoolExpr")??{});if(Object.keys(t).length>0){const n=g(t,"boolop");if(n===0||n==="AND_EXPR"){const r=P(g(t,"args")),s=[];for(const o of r)s.push(...this._extractAndConjuncts(o));return s}}return[e]}_compileWhere(e,t){const n=w(g(e,"BoolExpr")??{});if(Object.keys(n).length>0)return this._compileBoolExpr(n,t);if(jn(e))return this._compileComparison(w(g(e,"A_Expr")??e),t);const r=g(e,"A_Expr");if(r!=null)return this._compileComparison(w(r),t);if(Q(e))return this._compileFuncInWhere(w(g(e,"FuncCall")??e),t);const s=g(e,"FuncCall");if(s!=null)return this._compileFuncInWhere(w(s),t);if(Zr(e))return this._compileNullTest(w(g(e,"NullTest")??e));const o=g(e,"NullTest");if(o!=null)return this._compileNullTest(w(o));if(nn(e))return this._compileSublinkInWhere(w(g(e,"SubLink")??e),t);const i=g(e,"SubLink");return i!=null?this._compileSublinkInWhere(w(i),t):new $n(e,a=>this._compileSelect(a,this._params))}_compileBoolExpr(e,t){const n=g(e,"boolop"),r=P(g(e,"args"));if(n===0||n==="AND_EXPR")return this._compileAnd(r,t);if(n===1||n==="OR_EXPR")return new re(r.map(s=>this._compileWhere(s,t)));if(n===2||n==="NOT_EXPR")return new de(this._compileWhere(r[0],t));throw new Error(`Unsupported BoolExpr type: ${String(n)}`)}_compileAnd(e,t){const n=[],r=[];for(const o of e){const i=this._compileWhere(o,t);i instanceof G&&i.source===null?r.push(i):n.push(i)}let s;if(n.length>0)s=n.length===1?n[0]:new H(n);else if(r.length>0)s=r.shift();else return new Vn;for(const o of r)s=new G(o.field,o.predicate,s);return s}_compileComparison(e,t){const n=g(e,"kind"),r=P(g(e,"name")),s=r.length>0?J(r[r.length-1]):"";if(n===0||n==="AEXPR_OP"){if(s==="@@"){const a=w(g(e,"lexpr")),l=w(g(e,"rexpr")),u=B(a),h=ee(l,this._params),f=u==="_all"?null:u;return this._makeTextSearchOp(f,h,t,!1)}const o=w(g(e,"lexpr")),i=w(g(e,"rexpr"));if(X(o)&&(be(i)||Pt(i))&&["=","!=","<>",">",">=","<","<="].includes(s)){const a=B(o),l=z(i,this._params);return new G(a,es(s,l))}return new $n(e.kind!==void 0?e:{A_Expr:e},a=>this._compileSelect(a,this._params))}if(n===7||n==="AEXPR_IN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=new Set;for(const u of a)l.add(z(u,this._params));return new G(i,new cn(l))}if(n===11||n==="AEXPR_BETWEEN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=Number(z(a[0],this._params)),u=Number(z(a[1],this._params));return new G(i,new un(l,u))}if(n===12||n==="AEXPR_NOT_BETWEEN"){const o=w(g(e,"lexpr")),i=B(o),a=P(g(e,"rexpr")),l=Number(z(a[0],this._params)),u=Number(z(a[1],this._params));return new de(new G(i,new un(l,u)))}if(n===8||n==="AEXPR_LIKE"){const o=w(g(e,"lexpr")),i=w(g(e,"rexpr")),a=B(o),l=ee(i,this._params);return s==="!~~"?new G(a,new as(l)):new G(a,new Xn(l))}if(n===9||n==="AEXPR_ILIKE"){const o=w(g(e,"lexpr")),i=w(g(e,"rexpr")),a=B(o),l=ee(i,this._params);return s==="!~~*"?new G(a,new ls(l)):new G(a,new Qn(l))}throw new Error(`Unsupported expression kind: ${String(n)}`)}_compileNullTest(e){const t=w(g(e,"arg")),n=B(t),r=g(e,"nulltesttype");return r===0||r==="IS_NULL"?new G(n,new hn):new G(n,new fn)}_compileSublinkInWhere(e,t){const n=g(e,"subLinkType"),r=w(g(e,"subselect")),s=w(g(r,"SelectStmt")??r);if(n===2||n==="ANY_SUBLINK"){const o=this._compileSelect(s,this._params);if(o.columns.length===0)throw new Error("Subquery must return at least one column");const i=o.columns[0],a=new Set;for(const h of o.rows){const f=h[i];f!=null&&a.add(f)}const l=w(g(e,"testexpr")),u=B(l);return new G(u,new cn(a))}if(n===0||n==="EXISTS_SUBLINK")return this._compileSelect(s,this._params).rows.length>0?new Vn:new de(new Vn);throw new Error(`Unsupported subquery type: ${String(n)}`)}_compileFuncInWhere(e,t){const n=ce(e).toLowerCase(),r=ve(e);if(n==="text_match"){const s=B(r[0]),o=ee(r[1],this._params);return this._makeTextSearchOp(s,o,t,!1)}if(n==="bayesian_match"){const s=B(r[0]),o=ee(r[1],this._params);return this._makeTextSearchOp(s,o,t,!0)}return n==="bayesian_match_with_prior"?this._makeBayesianWithPriorOp(r,t):n==="knn_match"?this._makeKnnOp(r):n==="bayesian_knn_match"?this._makeCalibratedKnnOp(r,t,!0):n==="traverse_match"?this._makeTraverseMatchOp(r):n==="temporal_traverse"?this._makeTemporalTraverseOp(r):n==="path_filter"?this._makePathFilterOp(r):n==="vector_exclude"?this._makeVectorExcludeOp(r):n==="spatial_within"?this._makeSpatialWithinOp(r):n==="fuse_log_odds"?this._makeFusionOp(r,t,"log_odds"):n==="fuse_prob_and"?this._makeFusionOp(r,t,"prob_and"):n==="fuse_prob_or"?this._makeFusionOp(r,t,"prob_or"):n==="fuse_prob_not"?this._makeProbNotOp(r,t):n==="fuse_attention"?this._makeAttentionFusionOp(r,t):n==="fuse_multihead"?this._makeMultiheadFusionOp(r,t):n==="fuse_learned"?this._makeLearnedFusionOp(r,t):n==="sparse_threshold"?this._makeSparseThresholdOp(r,t):n==="multi_field_match"?this._makeMultiFieldMatchOp(r):n==="message_passing"?this._makeMessagePassingOp(r):n==="graph_embedding"?this._makeGraphEmbeddingOp(r):n==="staged_retrieval"?this._makeStagedRetrievalOp(r,t):n==="pagerank"?this._makePageRankOp(r):n==="hits"?this._makeHITSOp(r):n==="betweenness"?this._makeBetweennessOp(r):n==="weighted_rpq"?this._makeWeightedRpqOp(r):n==="progressive_fusion"?this._makeProgressiveFusionOp(r,t):n==="deep_fusion"?this._makeDeepFusionOp(r,t):new $n(e,s=>this._compileSelect(s,this._params))}_compileCalibratedSignal(e,t){const n=w(g(e,"FuncCall")??e),r=ce(n).toLowerCase(),s=ve(n);if(r==="text_match"||r==="bayesian_match"){const o=B(s[0]),i=ee(s[1],this._params);return this._makeTextSearchOp(o,i,t,!0)}if(r==="knn_match")return this._makeCalibratedKnnOp(s,t,!1);if(r==="bayesian_knn_match")return this._makeCalibratedKnnOp(s,t,!0);if(r==="traverse_match")return this._makeTraverseMatchOp(s);if(r==="spatial_within")return this._makeSpatialWithinOp(s);if(r==="pagerank")return this._makePageRankOp(s);if(r==="hits")return this._makeHITSOp(s);if(r==="betweenness")return this._makeBetweennessOp(s);if(r==="weighted_rpq")return this._makeWeightedRpqOp(s);if(r==="message_passing")return this._makeMessagePassingOp(s);throw new Error(`Unknown signal function for fusion: ${r}. Use text_match, bayesian_match, knn_match, bayesian_knn_match, traverse_match, spatial_within, pagerank, hits, betweenness, or weighted_rpq.`)}_makeTextSearchOp(e,t,n,r){const s=n.invertedIndex;let o=[];s&&(o=(e&&typeof s.getSearchAnalyzer=="function"?s.getSearchAnalyzer(e):s.analyzer).analyze(t));const i=new _e(t,e??void 0);if(r)try{const a=s?s.stats:null;if(a){const l=new ct(Je(),a);return new pe(l,i,o,e??void 0)}}catch{}try{const a=s?s.stats:null;if(a){const l=new xt(qt(),a);return new pe(l,i,o,e??void 0)}}catch{}return i}_makeMultiFieldMatchOp(e){if(e.length<3)throw new Error("multi_field_match() requires at least 3 arguments: multi_field_match(field1, field2, ..., query)");const t=[];let n=null;const r=[];for(let s=0;s<e.length;s++){const o=e[s];if(X(o)||g(o,"ColumnRef")!==null)t.push(B(o));else{const i=z(o,this._params);if(typeof i=="string"&&n===null)n=i;else if(typeof i=="number")r.push(i);else if(typeof i=="string")throw new Error(`Unexpected string argument at position ${String(s)}`)}}if(n===null||t.length<2)throw new Error("multi_field_match() requires at least 2 field names and a query string");if(r.length>0&&r.length!==t.length)throw new Error(`Number of weights (${String(r.length)}) must match number of fields (${String(t.length)})`);return new Mn(t,n,r.length>0?r:void 0)}_makeMessagePassingOp(e){const t=e.length>0?we(e[0],this._params):2,n=e.length>1?ee(e[1],this._params):"mean",r=e.length>2?ee(e[2],this._params):void 0;return new Dn({kLayers:t,aggregation:n,propertyName:r,graph:this._currentGraphName||""})}_makeGraphEmbeddingOp(e){const t=e.length>1?we(e[1],this._params):2;return new Br({graph:this._currentGraphName||"",kHops:t})}_makeBayesianWithPriorOp(e,t){if(e.length<4)throw new Error("bayesian_match_with_prior() requires 4 arguments: bayesian_match_with_prior(field, query, prior_field, prior_mode)");const n=B(e[0]),r=ee(e[1],this._params),s=ee(e[2],this._params),o=ee(e[3],this._params);if(o!=="recency"&&o!=="authority")throw new Error(`Unknown prior mode: ${o}. Use 'recency' or 'authority'.`);let i;if(o==="recency")try{i=Go(s)}catch{i=h=>.5}else try{i=Bo(s)}catch{i=h=>.5}const a=t.invertedIndex;let l=[];a&&(l=a.analyzer.analyze(r));const u=new _e(r,n);try{const h=a?a.stats:null;if(h){const f=new zo(Je(),h,i);return new vi(u,f,l,n,t.documentStore??null)}}catch{}return u}_makeKnnOp(e){if(e.length!==3)throw new Error("knn_match() requires 3 arguments: knn_match(field, vector, k)");const t=B(e[0]),n=We(e[1],this._params),r=we(e[2],this._params);return new je(n,r,t)}_makeCalibratedKnnOp(e,t,n){var f;const r=[],s={};for(const d of e){const p=g(d,"NamedArgExpr");if(p!=null){const m=w(p),_=j(m,"name"),y=w(g(m,"arg"));s[_]=z(y,this._params)}else r.push(d)}if(r.length!==3)throw new Error("knn_match() requires 3 positional arguments: knn_match(field, vector, k)");const o=B(r[0]),i=We(r[1],this._params),a=we(r[2],this._params),u=(f=t.vectorIndexes)==null?void 0:f[o];if(u!==null&&typeof u=="object"&&"backgroundStats"in u&&u.backgroundStats!==null||n||Object.keys(s).length>0){const d=new Set(["method","weight_source","bm25_query","bm25_field","base_rate","bandwidth_scale","density_gamma"]),p=Object.keys(s).filter(m=>!d.has(m));if(p.length>0)throw new Error(`Unknown option(s) for bayesian_knn_match: ${p.join(", ")}. Valid options: ${[...d].sort().join(", ")}`);return new fr(i,a,o,s.method??"kde",Number(s.base_rate??.5),s.weight_source??"density_prior",s.bm25_query!=null?String(s.bm25_query):void 0,s.bm25_field!=null?String(s.bm25_field):void 0,Number(s.density_gamma??1),Number(s.bandwidth_scale??1))}return new wi(i,a,o)}_makeSpatialWithinOp(e){if(e.length!==3)throw new Error("spatial_within() requires 3 arguments: spatial_within(field, POINT(x, y), distance)");const t=B(e[0]),[n,r]=this._extractPointArg(e[1]),s=Number(z(e[2],this._params));return new js(t,n,r,s)}_extractPointArg(e){const t=w(g(e,"FuncCall")??{});if(Object.keys(t).length>0){const n=ce(t);if(n!=="point")throw new Error(`Expected POINT(x, y), got ${n}()`);const r=ve(t);if(r.length!==2)throw new Error("POINT() requires exactly 2 arguments");const s=Number(z(r[0],this._params)),o=Number(z(r[1],this._params));return[s,o]}if(Pt(e)){const n=z(e,this._params);if(Array.isArray(n)&&n.length===2)return[Number(n[0]),Number(n[1])];throw new Error("Parameter for POINT must be a [x, y] array")}throw new Error("Expected POINT(x, y) or $N parameter")}_makeTraverseMatchOp(e){const t=we(e[0],this._params),n=e.length>1?ee(e[1],this._params):void 0,r=e.length>2?we(e[2],this._params):1;return new Fn(t,this._currentGraphName||"",n??null,r)}_makeTemporalTraverseOp(e){if(e.length<4)throw new Error("temporal_traverse() requires at least 4 arguments: temporal_traverse(start, label, hops, timestamp)");const t=we(e[0],this._params),n=e.length>1?ee(e[1],this._params):void 0,r=e.length>2?we(e[2],this._params):1;let s;if(e.length===4){const o=Number(z(e[3],this._params));s=new Zt({timestamp:o})}else if(e.length>=5){const o=Number(z(e[3],this._params)),i=Number(z(e[4],this._params));s=new Zt({timeRange:[o,i]})}else s=new Zt;return new Pn({startVertex:t,graph:this._currentGraphName||"",temporalFilter:s,label:n??null,maxHops:r})}_makePathFilterOp(e){if(e.length<2)throw new Error("path_filter() requires at least 2 arguments: path_filter('path', value) or path_filter('path', 'op', value)");const t=ee(e[0],this._params),n=[];for(const o of t.split("."))/^\d+$/.test(o)?n.push(parseInt(o,10)):n.push(o);if(e.length===2){const o=z(e[1],this._params);return new Qt(n,new ln(o))}const r=ee(e[1],this._params),s=z(e[2],this._params);return new Qt(n,es(r,s))}_makeVectorExcludeOp(e){if(e.length!==5)throw new Error("vector_exclude() requires 5 arguments: vector_exclude(field, positive_vector, negative_vector, k, threshold)");const t=B(e[0]),n=We(e[1],this._params),r=We(e[2],this._params),s=we(e[3],this._params),o=Number(z(e[4],this._params)),i=new je(n,s,t);return new En(i,r,o,t)}_makeProbNotOp(e,t){if(e.length!==1)throw new Error("fuse_prob_not() requires exactly 1 signal function argument");const n=this._compileCalibratedSignal(e[0],t);return new Gt(n)}_makeSparseThresholdOp(e,t){if(e.length!==2)throw new Error("sparse_threshold() requires 2 arguments: sparse_threshold(signal, threshold)");const n=this._compileCalibratedSignal(e[0],t),r=Number(z(e[1],this._params));return new Ne(n,r)}_makeFusionOp(e,t,n){const r=[];let s=.5,o=null,i=null;for(const a of e)if(Q(a)||g(a,"FuncCall")!==null)r.push(this._compileCalibratedSignal(a,t));else{const l=g(a,"NamedArgExpr");if(l!=null&&n==="log_odds"){const u=w(l),h=j(u,"name"),f=z(w(g(u,"arg")),this._params);if(h==="alpha")s=Number(f);else if(h==="gating")o=String(f);else if(h==="gating_beta")i=Number(f);else throw new Error(`Unknown option for fuse_log_odds: ${h}. Valid options: alpha, gating, gating_beta`)}else if(be(a)&&n==="log_odds"){const u=z(a,this._params);typeof u=="string"?o=u:s=Number(u)}else throw new Error("Fusion function arguments must be signal functions (text_match, knn_match, etc.)")}if(r.length<2)throw new Error("Fusion requires at least 2 signal functions");return n==="log_odds"?new ke(r,s,null,o,i):n==="prob_and"?new Ve(r,"and"):new Ve(r,"or")}_makeStagedRetrievalOp(e,t){const n=[];let r=0;for(;r<e.length-1;){if(!Q(e[r])&&g(e[r],"FuncCall")===null)throw new Error(`staged_retrieval: argument ${String(r)} must be a signal function`);const s=this._compileCalibratedSignal(e[r],t);let o=z(e[r+1],this._params);typeof o=="number"&&o===Math.floor(o)&&(o=Math.floor(o)),n.push([s,o]),r+=2}if(n.length===0)throw new Error("staged_retrieval requires at least one (signal, cutoff) pair");return new $e(n)}_splitCentralityArgs(e){const t=[];let n=this._currentGraphName;for(const r of e){try{const s=z(r,this._params);if(typeof s=="string"){n=s;continue}}catch{}t.push(r)}return[t,n]}_makePageRankOp(e){const[t,n]=this._splitCentralityArgs(e),r=t.length>0?Number(z(t[0],this._params)):.85,s=t.length>1?we(t[1],this._params):100,o=t.length>2?Number(z(t[2],this._params)):1e-6;return new qr({damping:r,maxIterations:s,tolerance:o,graph:n||""})}_makeHITSOp(e){const[t,n]=this._splitCentralityArgs(e),r=t.length>0?we(t[0],this._params):100,s=t.length>1?Number(z(t[1],this._params)):1e-6;return new zr({maxIterations:r,tolerance:s,graph:n||""})}_makeBetweennessOp(e){const[,t]=this._splitCentralityArgs(e);return new Gr({graph:t||""})}_makeWeightedRpqOp(e){if(e.length<3)throw new Error("weighted_rpq() requires at least 3 arguments: weighted_rpq('path_expr', start, 'weight_property'[, 'agg_fn'[, threshold]])");const t=ee(e[0],this._params),n=we(e[1],this._params),r=ee(e[2],this._params),s=e.length>3?ee(e[3],this._params):"sum";let o=null;e.length>4&&(o=Number(z(e[4],this._params)));try{return new $o(Tr(t),this._currentGraphName||"",{startVertex:n,weightProperty:r,aggregation:s,weightThreshold:o})}catch{throw new Error("weighted_rpq() requires the WeightedPathQueryOperator")}}_makeProgressiveFusionOp(e,t){const n=[],r=[];let s=.5,o=null;for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else if(be(i)||Pt(i)){const a=z(i,this._params);if(typeof a=="string")o=a;else if(typeof a=="number"&&a!==Math.floor(a))s=a;else{const l=Math.floor(Number(a));if(n.length===0)throw new Error("progressive_fusion: k must follow signal functions");r.push([[...n],l]),n.length=0}}else throw new Error("progressive_fusion: unexpected argument type");if(n.length>0)throw new Error("progressive_fusion: trailing signals without k cutoff");if(r.length===0)throw new Error("progressive_fusion requires at least one (signals, k) stage");return new kr(r,s,o)}_makeDeepFusionOp(e,t){const n=[];let r=.5,s="none";for(const o of e){const i=w(g(o,"FuncCall")??(Q(o)?o:{}));if(Object.keys(i).length>0){const l=ce(i).toLowerCase(),u=ve(i);if(l==="layer"){const h=[];for(const f of u)if(Q(f)||g(f,"FuncCall")!==null)h.push(this._compileCalibratedSignal(f,t));else throw new Error("layer() arguments must be signal functions");if(h.length===0)throw new Error("layer() requires at least one signal");n.push({type:"signal",signals:h})}else if(l==="propagate"){if(u.length<2)throw new Error("propagate() requires at least 2 arguments: propagate('edge_label', 'aggregation'[, 'direction'])");const h=ee(u[0],this._params),f=ee(u[1],this._params);if(!["mean","sum","max"].includes(f))throw new Error(`propagate() aggregation must be 'mean', 'sum', or 'max', got '${f}'`);let d="both";if(u.length>=3&&(d=ee(u[2],this._params),!["both","out","in"].includes(d)))throw new Error(`propagate() direction must be 'both', 'out', or 'in', got '${d}'`);n.push({type:"propagate",edgeLabel:h,aggregation:f,direction:d})}else if(l==="convolve"){const h=[],f={};for(const _ of u){const y=g(_,"NamedArgExpr");if(y!=null){const x=w(y);f[j(x,"name")]=z(w(g(x,"arg")),this._params)}else h.push(_)}if(h.length===0)throw new Error("convolve() requires edge_label as first argument");const d=ee(h[0],this._params),p=Number(f.n_channels??0),m="both";if(p>1){const _=Number(f.seed??42),y=f.init??"kaiming";let x=1;for(let v=n.length-1;v>=0;v--){const E=n[v];if(E.type==="conv"){const I=E.kernelShape;I&&(x=I[0]);break}}try{const v=Uo(p,x,_,y);n.push({type:"conv",edgeLabel:d,hopWeights:[1],direction:m,kernel:Array.from(v),kernelShape:[p,x]})}catch{n.push({type:"conv",edgeLabel:d,hopWeights:[1],direction:m})}}else{if(h.length<2)throw new Error("convolve() requires ARRAY[w0, w1, ...] or n_channels => N");const _=We(h[1],this._params);n.push({type:"conv",edgeLabel:d,hopWeights:Array.from(_),direction:m})}}else if(l==="pool"){if(u.length<3)throw new Error("pool() requires at least 3 arguments: pool('edge_label', 'method', pool_size[, 'direction'])");const h=ee(u[0],this._params),f=ee(u[1],this._params);if(!["max","avg"].includes(f))throw new Error(`pool() method must be 'max' or 'avg', got '${f}'`);const d=we(u[2],this._params);let p="both";if(u.length>=4&&(p=ee(u[3],this._params),!["both","out","in"].includes(p)))throw new Error(`pool() direction must be 'both', 'out', or 'in', got '${p}'`);n.push({type:"pool",edgeLabel:h,poolSize:d,method:f,direction:p})}else if(l==="dense"){const h=[],f={};for(const y of u){const x=g(y,"NamedArgExpr");if(x!=null){const v=w(x);f[j(v,"name")]=Number(z(w(g(v,"arg")),this._params))}else h.push(y)}if(h.length<2)throw new Error("dense() requires at least 2 positional arguments: ARRAY[weights], ARRAY[bias]");const d=We(h[0],this._params),p=We(h[1],this._params),m=f.output_channels,_=f.input_channels;if(m===void 0||_===void 0)throw new Error("dense() requires output_channels and input_channels named arguments");if(d.length!==m*_)throw new Error(`dense() weights array length (${String(d.length)}) must equal output_channels * input_channels (${String(m*_)})`);if(p.length!==m)throw new Error(`dense() bias array length (${String(p.length)}) must equal output_channels (${String(m)})`);n.push({type:"dense",weights:Array.from(d),bias:Array.from(p),outputChannels:m,inputChannels:_})}else if(l==="flatten")n.push({type:"flatten"});else if(l==="softmax")n.push({type:"softmax"});else if(l==="batch_norm"){let h=1e-5;for(const f of u){const d=g(f,"NamedArgExpr");if(d!=null){const p=w(d);j(p,"name")==="epsilon"&&(h=Number(z(w(g(p,"arg")),this._params)))}}n.push({type:"batchNorm",epsilon:h})}else if(l==="dropout"){if(u.length<1)throw new Error("dropout() requires 1 argument: dropout(p)");const h=Number(z(u[0],this._params));n.push({type:"dropout",p:h})}else if(l==="attention"){let h=1,f="content";for(const d of u){const p=g(d,"NamedArgExpr");if(p!=null){const m=w(p),_=j(m,"name");_==="n_heads"?h=Number(z(w(g(m,"arg")),this._params)):_==="mode"&&(f=String(z(w(g(m,"arg")),this._params)))}}n.push({type:"attention",nHeads:h,mode:f})}else if(l==="embed"){const h=[],f={};for(const y of u){const x=g(y,"NamedArgExpr");if(x!=null){const v=w(x);f[j(v,"name")]=Number(z(w(g(v,"arg")),this._params))}else h.push(y)}if(h.length===0)throw new Error("embed() requires vector argument");const d=We(h[0],this._params),p=f.in_channels??1;let m,_;if(f.grid_h!==void 0&&f.grid_w!==void 0)m=f.grid_h,_=f.grid_w;else{const y=Math.floor(Math.sqrt(d.length/p));y*y*p===d.length?(m=y,_=y):(m=0,_=0)}n.push({type:"embed",embedding:Array.from(d),gridH:m,gridW:_,inChannels:p})}else if(l==="global_pool"){let h="avg";for(const f of u){const d=g(f,"NamedArgExpr");if(d!=null){const p=w(d);j(p,"name")==="method"&&(h=String(z(w(g(p,"arg")),this._params)))}else h=ee(f,this._params)}if(!["avg","max","avg_max"].includes(h))throw new Error(`global_pool() method must be 'avg', 'max', or 'avg_max', got '${h}'`);n.push({type:"globalPool",method:h})}else throw new Error(`deep_fusion() unknown layer function: ${l}()`);continue}const a=g(o,"NamedArgExpr");if(a!=null){const l=w(a),u=j(l,"name"),h=z(w(g(l,"arg")),this._params);if(u==="alpha")r=Number(h);else if(u==="gating")s=String(h);else throw new Error(`Unknown option for deep_fusion: ${u}. Valid options: alpha, gating`);continue}throw new Error("deep_fusion() arguments must be layer() or propagate() calls")}if(n.length===0)throw new Error("deep_fusion requires at least one layer");return new ye(n,r,s,this._currentGraphName||void 0)}_makeAttentionFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_attention requires at least 2 signals");const s=new Set(["normalized","alpha","base_rate"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_attention: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=n.length,a=new Wr(i,6,Number(r.alpha??.5),!!(r.normalized??!1),r.base_rate??void 0),l=this._extractQueryFeatures(e,t);return new pt(n,a,l)}catch{return new ke(n,Number(r.alpha??.5))}}_makeMultiheadFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_multihead requires at least 2 signals");const s=new Set(["n_heads","normalized","alpha"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_multihead: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=n.length,a=new Wo(i,Number(r.n_heads??4),6,Number(r.alpha??.5),!!(r.normalized??!1)),l=this._extractQueryFeatures(e,t);return new pt(n,a,l)}catch{return new ke(n,Number(r.alpha??.5))}}_makeLearnedFusionOp(e,t){const n=[],r={};for(const i of e)if(Q(i)||g(i,"FuncCall")!==null)n.push(this._compileCalibratedSignal(i,t));else{const a=g(i,"NamedArgExpr");if(a!=null){const l=w(a);r[j(l,"name")]=z(w(g(l,"arg")),this._params)}}if(n.length<2)throw new Error("fuse_learned requires at least 2 signals");const s=new Set(["alpha"]),o=Object.keys(r).filter(i=>!s.has(i));if(o.length>0)throw new Error(`Unknown option(s) for fuse_learned: ${o.join(", ")}. Valid options: ${[...s].sort().join(", ")}`);try{const i=new Hr(n.length,Number(r.alpha??.5));return new kt(n,i)}catch{return new ke(n,Number(r.alpha??.5))}}_extractQueryFeatures(e,t){const n=new Float64Array(6);if(t.invertedIndex)try{const r=new Ho(t.invertedIndex);for(const s of e){const o=w(g(s,"FuncCall")??(Q(s)?s:{}));if(Object.keys(o).length>0){const i=ce(o);if(i==="text_match"||i==="bayesian_match"){const a=ve(o);if(a.length>=2){const l=ee(a[1],this._params),h=t.invertedIndex.analyzer.analyze(l);return r.extract(h)}}}}}catch{}return n}_foldStmtWhere(e){const t=g(e,"whereClause");if(t==null)return e;const n=this._foldConstants(w(t));return n===t?e:{...e,whereClause:n}}_foldConstants(e){return Object.keys(e).length===0||be(e)||g(e,"A_Const")!==null||X(e)||g(e,"ColumnRef")!==null?e:jn(e)||g(e,"A_Expr")!==null?this._foldAExpr(e):mi(e)||g(e,"BoolExpr")!==null?this._foldBoolExpr(e):Q(e)||g(e,"FuncCall")!==null?this._foldFuncCall(e):e}_foldAExpr(e){const t=w(g(e,"A_Expr")??e),n=this._foldConstants(w(g(t,"lexpr")??{})),r=this._foldConstants(w(g(t,"rexpr")??{}));if((be(n)||g(n,"A_Const")!==null)&&(be(r)||g(r,"A_Const")!==null))try{const s=new ie({params:this._params}),o={A_Expr:{...t,lexpr:n,rexpr:r}},i=s.evaluate(o,{});return ts(i)}catch{}if(n!==g(t,"lexpr")||r!==g(t,"rexpr")){const s={...t,lexpr:n,rexpr:r};return g(e,"A_Expr")!==null?{A_Expr:s}:s}return e}_foldBoolExpr(e){const t=w(g(e,"BoolExpr")??e),n=g(t,"boolop"),r=P(g(t,"args")),s=r.map(a=>this._foldConstants(a));if(s.every(a=>be(a)||g(a,"A_Const")!==null))try{const a=new ie({params:this._params}),l={BoolExpr:{boolop:n,args:s}},u=a.evaluate(l,{});return ts(u)}catch{}if(n===0||n==="AND_EXPR"){const a=[];for(const u of s){if(be(u)||g(u,"A_Const")!==null){if(ns(u)===!1)return{A_Const:{boolval:!1}};continue}a.push(u)}if(a.length===0)return{A_Const:{boolval:!0}};if(a.length===1)return a[0];const l={boolop:0,args:a};return g(e,"BoolExpr")!==null?{BoolExpr:l}:l}if(n===1||n==="OR_EXPR"){const a=[];for(const u of s){if(be(u)||g(u,"A_Const")!==null){if(ns(u)===!0)return{A_Const:{boolval:!0}};continue}a.push(u)}if(a.length===0)return{A_Const:{boolval:!1}};if(a.length===1)return a[0];const l={boolop:1,args:a};return g(e,"BoolExpr")!==null?{BoolExpr:l}:l}if(s.some((a,l)=>a!==r[l])){const a={boolop:n,args:s};return g(e,"BoolExpr")!==null?{BoolExpr:a}:a}return e}_foldFuncCall(e){const t=w(g(e,"FuncCall")??e),n=ce(t);if(di.has(n))return e;const r=P(g(t,"args"));if(r.length===0)return e;const s=r.map(i=>this._foldConstants(i));if(s.some((i,a)=>i!==r[a])){const i={...t,args:s};return g(e,"FuncCall")!==null?{FuncCall:i}:i}return e}_optimize(e,t,n){try{const r=t.invertedIndex;if(!r)return e;const s=r.stats,o=n?n._stats:null,i=n?n.name:void 0;return new Fe(s,{columnStats:o,indexManager:t.indexManager??void 0,tableName:i}).optimize(e)}catch{return e}}_executePlan(e,t){try{return new tn(t).execute(e)}catch{return e.execute(t)}}_explainPlan(e,t){try{const o=new tn(t).explain(e).split(`
15
+ `).map(i=>({plan:i}));return{columns:["plan"],rows:o}}catch{return{columns:["plan"],rows:[{plan:e.constructor.name}]}}}_scanAll(e,t){if(!e.documentStore)return new D([he(0,{score:0})]);let r=[...e.documentStore.docIds].sort((s,o)=>s-o);return t!==void 0&&t<r.length&&(r=r.slice(0,t)),new D(r.map(s=>he(s,{score:0})))}_chainOnSource(e,t){return e instanceof G&&e.source===null?new G(e.field,e.predicate,t):new H([t,e])}static _isGraphOperator(e){if(e==null)return!1;const t=e.constructor.name;return["TraverseOperator","RegularPathQueryOperator","PatternMatchOperator","TemporalTraverseOperator","TemporalPatternMatchOperator","CypherQueryOperator"].includes(t)}static _isJoinOperator(e){if(e==null)return!1;const t=e.constructor.name;return["InnerJoinOperator","OuterJoinOperator","CrossJoinOperator","IndexJoinOperator","SortMergeJoinOperator","ExprJoinOperator","LateralJoinOperator","TableScanOperator"].includes(t)}_collectJoinTables(e){const t=[];for(const n of e)this._walkFromForTables(n,t);return t}_walkFromForTables(e,t){const n=w(g(e,"RangeVar")??{});if(Object.keys(n).length>0){const o=ae(n),i=Ue(n)??o,a=this._tables.get(o);a&&t.push([i,a.columnNames]);return}const r=w(g(e,"JoinExpr")??{});if(Object.keys(r).length>0){const o=g(r,"larg"),i=g(r,"rarg");o!=null&&this._walkFromForTables(w(o),t),i!=null&&this._walkFromForTables(w(i),t);return}const s=w(g(e,"RangeSubselect")??{});if(Object.keys(s).length>0){const o=Ue(s)??"_derived",i=this._tables.get(o);i&&t.push([o,i.columnNames])}}_applyDeferredWhere(e,t,n){return e.filter(r=>n.evaluate(t,r)===!0)}static _collectAstTableRefs(e){const t=new Set;return le._walkAstForTables(e,t),t}static _walkAstForTables(e,t){if(e==null||typeof e!="object")return;if(Array.isArray(e)){for(const o of e)le._walkAstForTables(o,t);return}const n=e,r=n.RangeVar;if(r!==void 0){const o=j(r,"schemaname");if(o!=="information_schema"&&o!=="pg_catalog"){const i=j(r,"relname");i&&t.add(i)}return}const s=n.relname;if(typeof s=="string"&&s){const o=n.schemaname;o!=="information_schema"&&o!=="pg_catalog"&&t.add(s)}for(const o of Object.values(n))o!==null&&typeof o=="object"&&le._walkAstForTables(o,t)}_partitionWhereForJoins(e,t){const n=this._extractAndConjuncts(e),r=new Map,s=[];for(const i of n){const a=le._collectConjunctAliases(i);if(a.size===1){const l=a.values().next().value;if(t.has(l)){r.has(l)||r.set(l,[]),r.get(l).push(i);continue}}s.push(i)}const o=le._reconstructAnd(s);return[r,o]}static _collectConjunctAliases(e){const t=new Set;return le._walkForColumnAliases(e,t),t}static _walkForColumnAliases(e,t){const n=w(g(e,"ColumnRef")??{});if(Object.keys(n).length>0){const o=P(g(n,"fields"));if(o.length>=2){const i=o[0],a=J(i);a&&t.add(a)}return}if(X(e)){const o=P(g(w(g(e,"ColumnRef")??e),"fields"));if(o.length>=2){const i=o[0],a=J(i);a&&t.add(a)}return}for(const o of["lexpr","rexpr","args","arg","xpr","val"]){const i=g(e,o);if(i!=null)if(Array.isArray(i))for(const a of i)typeof a=="object"&&le._walkForColumnAliases(a,t);else typeof i=="object"&&le._walkForColumnAliases(i,t)}const r=w(g(e,"BoolExpr")??{});if(Object.keys(r).length>0){const o=P(g(r,"args"));for(const i of o)le._walkForColumnAliases(i,t)}const s=w(g(e,"A_Expr")??{});if(Object.keys(s).length>0){const o=g(s,"lexpr"),i=g(s,"rexpr");o!==null&&typeof o=="object"&&le._walkForColumnAliases(o,t),i!==null&&typeof i=="object"&&le._walkForColumnAliases(i,t)}}static _reconstructAnd(e){return e.length===0?null:e.length===1?e[0]:{BoolExpr:{boolop:0,args:e}}}_extractImplicitEquijoinPredicates(e,t){const n=[],r=w(g(e,"BoolExpr")??{});let s;if(Object.keys(r).length>0){const o=g(r,"boolop");o===0||o==="AND_EXPR"?s=P(g(r,"args")):s=[e]}else s=[e];for(const o of s){const i=w(g(o,"A_Expr")??{});if(Object.keys(i).length===0)continue;const a=P(g(i,"name"));if(a.length===0||J(a[a.length-1])!=="=")continue;const u=g(i,"lexpr"),h=g(i,"rexpr");if(u===null||h===null||!X(w(u))||!X(w(h)))continue;const f=w(g(w(u),"ColumnRef")??w(u)),d=w(g(w(h),"ColumnRef")??w(h)),p=P(g(f,"fields")),m=P(g(d,"fields"));if(p.length<2||m.length<2)continue;const _=J(p[0]),y=J(p[p.length-1]),x=J(m[0]),v=J(m[m.length-1]);!_||!y||!x||!v||!t.has(_)||!t.has(x)||n.push({leftAlias:_,leftCol:y,rightAlias:x,rightCol:v})}return n}_registerFkValidators(e,t,n){for(const r of n){const s=r.refTable,o=r.column,i=r.refColumn;t.fkInsertValidators.push(l=>{const u=l[o];if(u==null)return;const h=this._tables.get(s);if(!h)throw new Error(`Foreign key violation: parent table "${s}" does not exist`);if(!h.documentStore.hasValue(i,u))throw new Error(`Foreign key violation: ${e}.${o} = ${JSON.stringify(u)} not found in ${s}.${i}`)}),t.fkUpdateValidators.push((l,u)=>{const h=u[o];if(h==null)return;const f=this._tables.get(s);if(!f)throw new Error(`FOREIGN KEY constraint violated: parent table "${s}" does not exist`);if(!f.documentStore.hasValue(i,h))throw new Error(`FOREIGN KEY constraint violated: ${e}.${o} = ${JSON.stringify(h)} not found in ${s}.${i}`)});const a=this._tables.get(s);if(a){const l=e,u=t;a.fkDeleteValidators.push(h=>{const f=a.documentStore.get(h);if(!f)return;const d=f[i];if(d!=null&&u.documentStore.hasValue(o,d))throw new Error(`FOREIGN KEY constraint violated: row in "${s}" is still referenced from "${l}"`)}),a.fkUpdateValidators.push((h,f)=>{const d=h[i],p=f[i];if(d!==p&&d!=null&&u.documentStore.hasValue(o,d))throw new Error(`FOREIGN KEY constraint violated: row in "${s}" is still referenced from "${l}"`)})}}}_isPushablePredicate(e,t){const n=g(e,"A_Expr");if(n!=null){const s=w(n),o=g(s,"lexpr"),i=g(s,"rexpr");if(o!==null&&X(w(o)))try{const a=B(w(o));if(!t.has(a))return!1}catch{return!1}else return!1;if(i!==null){const a=w(i);if(!be(a)&&!Pt(a))return!1}return!0}const r=g(e,"NullTest");if(r!=null){const s=w(r),o=g(s,"arg");if(o!==null&&X(w(o)))try{const i=B(w(o));return t.has(i)}catch{return!1}}return!1}_tryPredicatePushdown(e,t){const n=g(e,"whereClause");if(n==null)return e;const r=P(g(e,"fromClause"));if(r.length!==1)return e;const s=r[0];let o=null;const i=w(g(s,"RangeVar")??{}),a=w(g(s,"RangeSubselect")??{});if(Object.keys(i).length>0){const p=ae(i);this._views.has(p)?o=this._views.get(p):this._inlinedCTEs.has(p)&&(o=this._inlinedCTEs.get(p))}else if(Object.keys(a).length>0){const p=g(a,"subquery");p!=null&&(o=w(g(w(p),"SelectStmt")??p))}if(o===null||g(o,"groupClause")!==null&&P(g(o,"groupClause")).length>0||g(o,"distinctClause")!==null&&g(o,"distinctClause")!==void 0||g(o,"limitCount")!==null&&g(o,"limitCount")!==void 0)return e;const l=P(g(o,"targetList"));for(const p of l){const m=w(g(p,"ResTarget")??p),_=g(m,"val");if(_!=null&&Q(w(_))&&rt(w(_)))return e}if(this._hasAggregates(l))return e;const u=new Set;for(const p of l){const m=w(g(p,"ResTarget")??p),_=j(m,"name");if(_)u.add(_);else{const y=g(m,"val");if(y!==null&&X(w(y)))try{u.add(B(w(y)))}catch{}}}if(u.size===0)return e;const[h,f]=this._splitPushable(w(n),u);if(h.length===0)return e;const d=h.length===1?h[0]:{BoolExpr:{boolop:0,args:h}};if(Object.keys(i).length>0){const p=ae(i);this._views.has(p)?this._views.set(p,le._injectWhere(this._views.get(p),d)):this._inlinedCTEs.has(p)&&this._inlinedCTEs.set(p,le._injectWhere(this._inlinedCTEs.get(p),d))}return{...e,whereClause:f}}_splitPushable(e,t){const n=w(g(e,"BoolExpr")??{});if(Object.keys(n).length>0){const r=g(n,"boolop");if(r===0||r==="AND_EXPR"){const s=P(g(n,"args")),o=[],i=[];for(const l of s)this._isPushablePredicate(l,t)?o.push(l):i.push(l);let a=null;return i.length===1?a=i[0]:i.length>1&&(a={BoolExpr:{boolop:0,args:i}}),[o,a]}}return this._isPushablePredicate(e,t)?[[e],null]:[[],e]}static _injectWhere(e,t){const n=g(e,"whereClause");let r;return n==null?r=t:r={BoolExpr:{boolop:0,args:[n,t]}},{...e,whereClause:r}}_extractNumericValue(e){const t=z(e,this._params);if(typeof t=="number")return t;if(typeof t=="string"){const n=Number(t);if(!isNaN(n))return n}throw new Error("Expected numeric constant or $N parameter, got "+JSON.stringify(e).slice(0,200))}static _isSelectStar(e){if(e.length===0)return!0;for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r!=null&&tt(w(r)))return!0}return!1}static _hasComputedExpressions(e){for(const t of e){const n=w(g(t,"ResTarget")??t),r=g(n,"val");if(r==null)continue;const s=w(r);if(!X(s)){if(Q(s)){const o=ce(s);if(et.has(o)||o==="text_match"||o==="bayesian_match"||o==="bayesian_match_with_prior"||o==="knn_match"||o==="bayesian_knn_match"||o==="traverse_match"||o==="spatial_within")continue;return!0}if(be(s)||jn(s)||g(s,"A_Expr")!==null||g(s,"CaseExpr")!==null||rn(s)||g(s,"CoalesceExpr")!==null||Zr(s)||nn(s)||g(s,"SubLink")!==null)return!0}}return!1}_inferTargetName(e){const t=w(g(e,"ResTarget")??e),n=j(t,"name");if(n)return n;const r=g(t,"val");if(r==null)return"?column?";const s=w(r);if(X(s))try{return B(s)}catch{return"?column?"}if(Q(s)){const o=ce(s);if(et.has(o)){if(nt(s))return o;const i=ve(s);if(i.length>0&&X(i[0]))try{const a=B(i[0]);return`${o}_${a}`}catch{return o}return o}return o==="text_match"||o==="bayesian_match"||o==="bayesian_match_with_prior"?"_score":o}if(rn(s)){const o=w(g(s,"TypeCast")??s),i=g(o,"arg");if(i!==null&&X(w(i)))try{return B(w(i))}catch{}}return"?column?"}_buildExprTargets(e){const t=[];for(const n of e){const r=w(g(n,"ResTarget")??n),s=this._inferTargetName(n);let o=g(r,"val");if(o==null)continue;const i=w(o);if(Q(i)){const a=ce(i);(a==="text_match"||a==="bayesian_match"||a==="bayesian_match_with_prior")&&(o={ColumnRef:{fields:[{String:{sval:"_score"}}]}})}t.push([s,w(o)])}return t}_sortNeedsExtraCols(e,t){const n=new Set;for(const r of t){const s=w(g(r,"ResTarget")??r),o=g(s,"val");if(o!=null&&tt(w(o)))return!1;if(o!==null&&X(w(o))){try{n.add(B(w(o)))}catch{}const i=j(s,"name");i&&n.add(i)}else{const i=j(s,"name");i&&n.add(i)}}for(const r of e){const s=w(g(r,"SortBy")??r),o=w(g(s,"node"));if(X(o))try{const i=B(o);if(!n.has(i))return!0}catch{}}return!1}_buildGroupAliases(e,t){const n=new Map;for(const r of t){const s=w(g(r,"ResTarget")??r),o=g(s,"val"),i=j(s,"name");if(o!==null&&X(w(o))&&i)try{const a=B(w(o));e.includes(a)&&n.set(a,i)}catch{}}return n}_buildPostGroupTargets(e,t,n){let r=!1;for(const i of e){const a=w(g(i,"ResTarget")??i),l=g(a,"val");if(l==null)continue;const u=w(l);if(Q(u)){const h=ce(u);if(!et.has(h)||rt(u)){r=!0;break}}else if(!X(u)){const h=j(a,"name")||"?column?";if(!n.has(h)){r=!0;break}}}if(!r)return null;const s=new Set(t),o=[];for(const i of e){const a=w(g(i,"ResTarget")??i),l=j(a,"name")||this._inferTargetName(i);if(n.has(l)||s.has(l))o.push([l,{ColumnRef:{fields:[{String:{sval:l}}]}}]);else{const u=g(a,"val");if(u!==null&&X(w(u)))try{const h=B(w(u));o.push([l,{ColumnRef:{fields:[{String:{sval:h}}]}}])}catch{o.push([l,w(u)])}else o.push([l,w(u??{})])}}return o}_buildPreAggTargets(e,t,n,r){const s=[];for(let i=0;i<e.length;i++){const a=e[i];(Q(a)||g(a,"FuncCall")!==null)&&i<t.length&&s.push([t[i],a])}for(const i of n)i.inputExpr!==void 0&&s.push(["_agg_expr",i.inputExpr]);if(s.length===0)return null;const o=[];if(r)for(const i of r.columnNames)o.push([i,{ColumnRef:{fields:[{String:{sval:i}}]}}]);for(const[i,a]of s)o.push([i,a]);return o}_resolveGroupByCols(e,t){const n=new Map,r=[];for(const o of t){const i=w(g(o,"ResTarget")??o),a=g(i,"val"),l=j(i,"name");if(a!==null&&X(w(a)))try{const u=B(w(a));r.push(l||u),l&&n.set(l,u)}catch{r.push(l||"?column?")}else if(a!==null&&Q(w(a))){const u=ce(w(a));let h;if(nt(w(a)))h=u;else{const f=ve(w(a));let d=null;for(const p of f)if(X(p))try{d=B(p)}catch{}h=d!==null?`${u}_${d}`:u}r.push(l||h)}else r.push(l||"?column?")}const s=[];for(const o of e){if(be(o)){const i=z(o,[]);if(typeof i=="number"&&Number.isInteger(i)){const a=i-1;if(a>=0&&a<r.length){s.push(r[a]);continue}throw new Error(`GROUP BY position ${String(i)} is not in select list`)}}if(X(o))try{const i=B(o);s.push(n.get(i)??i);continue}catch{}if(Q(o)||g(o,"FuncCall")!==null){const i=ce(o);let a=null;for(const l of t){const u=w(g(l,"ResTarget")??l),h=g(u,"val"),f=j(u,"name");if(h!==null&&Q(w(h))&&ce(w(h))===i&&f){a=f;break}}if(a!==null)s.push(a);else{const l=ve(o);let u=null;for(const h of l)if(X(h))try{u=B(h)}catch{}s.push(u!==null?`${i}_${u}`:i)}continue}try{s.push(B(o))}catch{s.push("?column?")}}return s}_getTable(e){const t=this._tables.get(e);if(!t)throw new Error(`Table "${e}" does not exist`);return t}_substituteParams(e,t){const n=g(e,"ParamRef");if(n!=null){const o=w(n).number,i=t.get(o);return i!==void 0?i:e}const r={};for(const[s,o]of Object.entries(e))Array.isArray(o)?r[s]=o.map(i=>i!==null&&typeof i=="object"?this._substituteParams(i,t):i):o!==null&&typeof o=="object"?r[s]=this._substituteParams(o,t):r[s]=o;return r}_hasOuterRefs(e,t){if(X(e))try{const n=B(e);if(t.has(n))return!0;const r=gi(e);if(t.has(r))return!0}catch{}for(const n of Object.values(e))if(Array.isArray(n)){for(const r of n)if(r!==null&&typeof r=="object"&&this._hasOuterRefs(r,t))return!0}else if(n!==null&&typeof n=="object"&&this._hasOuterRefs(n,t))return!0;return!1}_buildSortKeys(e,t){const n=new Map,r=new Set,s=new Map;for(let i=0;i<t.length;i++){const a=w(g(t[i],"ResTarget")??t[i]),l=g(a,"val"),u=j(a,"name");if(l!=null&&!tt(w(l))){let h;try{h=u||this._deriveColumnName(w(l))}catch{h=u||"?column?"}if(n.set(i+1,h),u&&(r.add(u),X(w(l))))try{const f=B(w(l));s.set(f,u)}catch{}}}const o=[];for(const i of e){const a=w(g(i,"SortBy")??i),l=w(g(a,"node")),u=g(a,"sortby_dir"),h=u===2||u==="SORTBY_DESC"||String(u).includes("DESC"),f=!h,d=g(a,"sortby_nulls");let p;d===1||d==="SORTBY_NULLS_FIRST"||String(d).includes("FIRST")?p=!0:d===2||d==="SORTBY_NULLS_LAST"||String(d).includes("LAST")?p=!1:p=h;let m;if(be(l)){const _=Number(z(l,this._params)),y=n.get(_);if(!y)throw new Error(`ORDER BY position ${String(_)} is not in select list`);m=y}else{try{m=B(l)}catch{m=this._deriveColumnName(l)}!r.has(m)&&s.has(m)&&(m=s.get(m))}o.push({column:m,ascending:f,nullsFirst:p})}return o}}class Vn extends q{execute(e){const t=e.documentStore;if(!t)return new D;const n=[...t.docIds].sort((r,s)=>r-s);return new D(n.map(r=>he(r,{score:0})))}costEstimate(e){return e.totalDocs}}class $n extends q{constructor(t,n=null){super();b(this,"exprNode");b(this,"_subqueryExecutor");this.exprNode=t,this._subqueryExecutor=n}execute(t){const n=new ie,r=t.documentStore;if(!r)return new D;const s=[];for(const o of[...r.docIds].sort((i,a)=>i-a)){const i=r.get(o);if(!i)continue;n.evaluate(this.exprNode,i)&&s.push(he(o,{score:0}))}return new D(s)}costEstimate(t){return t.totalDocs}}class vi extends q{constructor(t,n,r,s,o){super();b(this,"source");b(this,"scorer");b(this,"terms");b(this,"field");b(this,"documentStore");this.source=t,this.scorer=n,this.terms=r,this.field=s,this.documentStore=o}execute(t){const n=this.source.execute(t),r=this.documentStore??t.documentStore,s=t.invertedIndex,o=[],i=this.scorer;for(const a of n){const l=a.docId,u=(r==null?void 0:r.get(l))??{},h=a.payload.positions.length>0?a.payload.positions.length:1,f=this.field??"_default";let d=h;s&&typeof s.getDocLength=="function"&&(d=s.getDocLength(l,f));const m=n.length,_=i.scoreWithPrior(h,d,m,u);o.push(he(l,{score:_}))}return new D(o)}costEstimate(t){return this.source.costEstimate(t)*1.1}}class wi extends q{constructor(t,n,r="embedding"){super();b(this,"queryVector");b(this,"k");b(this,"field");this.queryVector=t,this.k=n,this.field=r}execute(t){var o;const n=(o=t.vectorIndexes)==null?void 0:o[this.field];let r;n?r=n.searchKnn(this.queryVector,this.k):r=new je(this.queryVector,this.k,this.field).execute(t);const s=[];for(const i of r)s.push(he(i.docId,{score:(1+i.payload.score)/2}));return new D(s)}costEstimate(t){return(t.dimensions||128)*Math.log2(t.totalDocs+1)}}function es(c,e){switch(c){case"=":return new ln(e);case"!=":case"<>":return new Un(e);case">":return new Wn(Number(e));case">=":return new Hn(Number(e));case"<":return new Kn(Number(e));case"<=":return new Jn(Number(e));default:throw new Error(`Unsupported operator: ${c}`)}}function ts(c){if(c==null)return{A_Const:{isnull:!0}};if(typeof c=="boolean")return{A_Const:{boolval:c}};if(typeof c=="number")return Number.isInteger(c)?{A_Const:{ival:c}}:{A_Const:{fval:String(c)}};if(typeof c=="string")return{A_Const:{sval:c}};throw new Error(`Cannot convert ${typeof c} to A_Const`)}function ns(c){const e=w(g(c,"A_Const")??c);if(g(e,"isnull")===!0)return null;const t=g(e,"boolval");if(t!=null)return!!t;const n=g(e,"ival");if(n!=null)return Number(n)!==0;const r=g(e,"fval");if(r!=null)return parseFloat(String(r))!==0;const s=g(e,"sval");return s!=null?String(s).length>0:null}function rs(c){return"docIds"in c?c.docIds[0]:c.docId}class xi{constructor(e,t,n){b(this,"left");b(this,"right");b(this,"condition");this.left=e,this.right=t,this.condition=n}_getEntries(e,t){return e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function"?[...e.execute(t).entries]:e}}class Si extends xi{execute(e){const t=this._getEntries(this.left,e),n=this._getEntries(this.right,e),r=t.length<=n.length,s=r?t:n,o=r?n:t,i=r?this.condition.leftField:this.condition.rightField,a=r?this.condition.rightField:this.condition.leftField,l=new Map;for(const h of s){const f=h.payload.fields[i];if(f==null)continue;let d=l.get(f);d||(d=[],l.set(f,d)),d.push(h)}const u=[];for(const h of o){const f=h.payload.fields[a];if(f==null)continue;const d=l.get(f);if(d)for(const p of d){const m=r?p:h,_=r?h:p,y=rs(m),x=rs(_);u.push({docIds:[y,x],payload:U({score:m.payload.score+_.payload.score,fields:{...m.payload.fields,..._.payload.fields}})})}}return new Se(u)}}class sn{constructor(e){b(this,"value");this.value=e}}class qn{constructor(e){b(this,"counts");this.counts=e}}class te{constructor(e,t){b(this,"_engine");b(this,"_table");b(this,"_root");this._engine=e,this._table=t,this._root=null}term(e,t){const n=new _e(e,t);return this._chain(n)}vector(e,t,n){const r=new Ee(e,t,n??"embedding");return this._chain(r)}knn(e,t,n){const r=new je(e,t,n??"embedding");return this._chain(r)}bayesianKnn(e,t,n="embedding",r){const s=new fr(e,t,n,(r==null?void 0:r.estimationMethod)??"kde",(r==null?void 0:r.baseRate)??.5,(r==null?void 0:r.weightSource)??"density_prior",(r==null?void 0:r.bm25Query)??null,(r==null?void 0:r.bm25Field)??null,(r==null?void 0:r.densityGamma)??1,(r==null?void 0:r.bandwidthScale)??1);return this._chain(s)}and(e){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before combining");const t=new H([this._root,e._root]),n=new te(this._engine,this._table);return n._root=t,n}or(e){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before combining");const t=new re([this._root,e._root]),n=new te(this._engine,this._table);return n._root=t,n}not(){if(this._root===null)throw new Error("Builder must have an operator before negation");const e=new de(this._root),t=new te(this._engine,this._table);return t._root=e,t}filter(e,t){if(e.includes(".")){const s=[];for(const a of e.split("."))/^\d+$/.test(a)?s.push(parseInt(a,10)):s.push(a);const o=new Qt(s,t,this._root),i=new te(this._engine,this._table);return i._root=o,i}const n=new G(e,t,this._root),r=new te(this._engine,this._table);return r._root=n,r}join(e,t,n){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before joining");const r={leftField:t,rightField:n},s=new Si(this._root,e._root,r),o=new te(this._engine,this._table);return o._root=s,o}vectorJoin(e,t,n,r){if(this._root===null||e._root===null)throw new Error("Both builders must have operators before joining");const s=new Kr(this._root,e._root,t,n,r),o=new te(this._engine,this._table);return o._root=s,o}traverse(e,t,n=1){const r=new Fn(e,this._table,t??null,n);return this._chain(r)}temporalTraverse(e,t,n=1,r){const s=new Pn({startVertex:e,graph:this._table,temporalFilter:new Zt({timestamp:(r==null?void 0:r.timestamp)??null,timeRange:(r==null?void 0:r.timeRange)??null}),label:t??null,maxHops:n});return this._chain(s)}matchPattern(e){const t=new Dr(e,this._table);return this._chain(t)}rpq(e,t){const n=Tr(e),r=new Vr(n,this._table,t??null);return this._chain(r)}vertexAggregate(e,t="sum"){if(this._root===null)throw new Error("vertexAggregate requires a graph traversal source");const n={sum:i=>i.reduce((a,l)=>a+l,0),avg:i=>i.length>0?i.reduce((a,l)=>a+l,0)/i.length:0,min:i=>i.length>0?Math.min(...i):0,max:i=>i.length>0?Math.max(...i):0,count:i=>i.length},r=new $r(this._root,e,n[t]),s=this._engine._contextForTable(this._table),o=r.execute(s);if(o.length>0){const i=o.entries[0];return new sn(i.payload.fields._vertex_agg_result)}return new sn(0)}vectorExclude(e,t){if(this._root===null)throw new Error("vectorExclude requires a source query");const n=new En(this._root,e,t),r=new te(this._engine,this._table);return r._root=n,r}sparseThreshold(e){if(this._root===null)throw new Error("sparseThreshold requires a source query");const t=new Ne(this._root,e),n=new te(this._engine,this._table);return n._root=t,n}messagePassing(e=2,t="mean",n){const r=new Dn({kLayers:e,aggregation:t,propertyName:n??void 0,graph:this._table});return this._chain(r)}aggregate(e,t){const n=this._engine.getTable(this._table),r=this._buildContext(n);let s;if(this._root!==null)s=this._root.execute(r);else{const u=[...n.documentStore.docIds].sort((h,f)=>h-f).map(h=>({docId:h,payload:{positions:[],score:0,fields:{}}}));s=D.fromSorted(u)}const o=n.documentStore,i=[];for(const l of s){const u=o.getField(l.docId,e);typeof u=="number"&&i.push(u)}let a;switch(t.toLowerCase()){case"count":a=i.length;break;case"sum":a=i.reduce((l,u)=>l+u,0);break;case"avg":{const l=i.reduce((u,h)=>u+h,0);a=i.length>0?l/i.length:0;break}case"min":a=i.length>0?Math.min(...i):null;break;case"max":a=i.length>0?Math.max(...i):null;break;default:throw new Error(`Unknown aggregation function: ${t}`)}return new sn(a)}facet(e){const t=this._engine.getTable(this._table),n=this._buildContext(t),s=new Vs(e,this._root).execute(n),o=new Map;for(const i of s){const a=i.payload.fields._facet_value,l=i.payload.fields._facet_count;a!==void 0&&l!==void 0&&o.set(String(a),l)}return new qn(o)}vectorFacet(e,t,n){const r=this._engine.getTable(this._table),s=this._buildContext(r),i=new pr(e,t,n,this._root).execute(s),a=new Map;for(const l of i){const u=l.payload.fields._facet_value,h=l.payload.fields._facet_count;u!==void 0&&h!==void 0&&a.set(String(u),h)}return new qn(a)}pathFilter(e,t){const n=new Qt(e,t,this._root),r=new te(this._engine,this._table);return r._root=n,r}pathProject(...e){const t=new Ro(e,this._root),n=new te(this._engine,this._table);return n._root=t,n}unnest(e){const t=new Fo(e,this._root),n=new te(this._engine,this._table);return n._root=t,n}pathAggregate(e,t){const r={count:Yo,sum:Xo,avg:Qo,min:Zo,max:ei}[t.toLowerCase()];if(r===void 0)throw new Error(`Unknown aggregation: ${t}`);let s;if(typeof e=="string"){const a=[];for(const l of e.split("."))/^\d+$/.test(l)?a.push(parseInt(l,10)):a.push(l);s=a}else s=e;const o=new Po(s,new r,this._root),i=new te(this._engine,this._table);return i._root=o,i}scoreBm25(e,t){const r=this._engine._contextForTable(this._table).invertedIndex,o=(t?r.getFieldAnalyzer(t):r.analyzer).analyze(e),i=new xt(qt(),r.stats),a=new pe(i,this._root,o,t??null),l=new te(this._engine,this._table);return l._root=a,l}scoreBayesianBm25(e,t){const r=this._engine._contextForTable(this._table).invertedIndex,o=(t?r.getFieldAnalyzer(t):r.analyzer).analyze(e),i=new ct(Je(),r.stats),a=new pe(i,this._root,o,t??null),l=new te(this._engine,this._table);return l._root=a,l}scoreMultiFieldBayesian(e,t,n){const r=new Mn(t,e,n??null),s=new te(this._engine,this._table);return s._root=r,s}scoreBayesianWithPrior(e,t,n){if((n==null?void 0:n.priorFn)===void 0||n.priorFn===null)throw new Error("priorFn is required for scoreBayesianWithPrior");return this.scoreBayesianBm25(e,t)}learnParams(e,t,n){const r=(n==null?void 0:n.field)??"_default";return this._engine.learnScoringParams(this._table,r,e,t,{mode:(n==null?void 0:n.mode)??"balanced"})}fuseLogOdds(...e){let t=.5;const n=[];for(const o of e)typeof o=="number"?t=o:o._root!==null&&n.push(o);if(n.length===0)return this;const r=n.map(o=>o._root),s=new te(this._engine,this._table);return s._root=new ke(r,t),s}fuseProbAnd(...e){const t=e.filter(r=>r._root!==null).map(r=>r._root),n=new te(this._engine,this._table);return n._root=new Ve(t,"and"),n}fuseProbOr(...e){const t=e.filter(r=>r._root!==null).map(r=>r._root),n=new te(this._engine,this._table);return n._root=new Ve(t,"or"),n}fuseAttention(e,t=.5){const n=e.filter(i=>i._root!==null).map(i=>i._root);if(n.length<2)throw new Error("fuseAttention requires at least 2 signals");const r=new Wr(n.length,6,t),s=new Float64Array(6),o=new te(this._engine,this._table);return o._root=new pt(n,r,s),o}fuseLearned(e,t=.5){const n=e.filter(o=>o._root!==null).map(o=>o._root);if(n.length<2)throw new Error("fuseLearned requires at least 2 signals");const r=new Hr(n.length,t),s=new te(this._engine,this._table);return s._root=new kt(n,r),s}multiStage(e){const t=[];for(const[s,o]of e){if(s._root===null)throw new Error("Each stage must have an operator");t.push([s._root,o])}const n=new $e(t),r=new te(this._engine,this._table);return r._root=n,r}execute(){if(this._root===null)return new D;const e=this._engine._contextForTable(this._table);let t=this._root;if(e.invertedIndex){const r=e.invertedIndex.stats;t=new Fe(r).optimize(this._root)}return new tn(e).execute(t)}explain(){if(this._root===null)return"(empty query)";const e=this._engine._contextForTable(this._table);let t=this._root;if(e.invertedIndex){const r=e.invertedIndex.stats;t=new Fe(r).optimize(this._root)}return new tn(e).explain(t)}_chain(e){this._root!==null&&(e=new H([this._root,e]));const t=new te(this._engine,this._table);return t._root=e,t}_buildContext(e){const t={};for(const[r,s]of e.vectorIndexes)t[r]=s;const n={};for(const[r,s]of e.spatialIndexes)n[r]=s;return{documentStore:e.documentStore,invertedIndex:e.invertedIndex,vectorIndexes:t,spatialIndexes:n}}}class Ei{constructor(e){b(this,"_conn");b(this,"_finished");this._conn=e,this._finished=!1,this._conn.beginTransaction()}get active(){return!this._finished}commit(){if(this._finished)throw new Error("Transaction already finished");this._conn.commitTransaction(),this._finished=!0}rollback(){if(this._finished)throw new Error("Transaction already finished");this._conn.rollbackTransaction(),this._finished=!0}savepoint(e){if(this._finished)throw new Error("Transaction already finished");this._conn.savepoint(e)}releaseSavepoint(e){if(this._finished)throw new Error("Transaction already finished");this._conn.releaseSavepoint(e)}rollbackTo(e){if(this._finished)throw new Error("Transaction already finished");this._conn.rollbackToSavepoint(e)}autoRollback(){this._finished||this.rollback()}}class Ii{constructor(){b(this,"_index",new Map)}_makeKey(e,t){return`${t}\0${e.join("\0")}`}_pairKey(e,t){return`${String(e)}\0${String(t)}`}_parsePairKey(e){const t=e.split("\0");return[parseInt(t[0],10),parseInt(t[1],10)]}build(e,t,n){for(const r of n){const s=this._makeKey(r,t),o=new Set,i=e.vertexIdsInGraph(t);for(const a of i){const l=this._findReachable(e,t,a,r);for(const u of l)o.add(this._pairKey(a,u))}this._index.set(s,o)}}_findReachable(e,t,n,r){let s=new Set([n]);for(const o of r){const i=new Set;for(const a of s){const l=e.neighbors(a,t,o,"out");for(const u of l)i.add(u)}if(s=i,s.size===0)break}return[...s]}lookup(e,t){const n=this._makeKey(e,t),r=this._index.get(n);return r?[...r].map(s=>this._parsePairKey(s)):[]}hasPath(e,t){const n=this._makeKey(e,t);return this._index.has(n)}indexedPaths(){const e=[];for(const t of this._index.keys()){const n=t.split("\0");e.push(n.slice(1))}return e}}class zn{constructor(e=1,t=0,n=.5){b(this,"_transform");this._transform=new K.BayesianProbabilityTransform(e,t,n===.5?null:n)}fit(e,t,n){return this._transform.fit(e,t,n),this.params()}update(e,t,n){this._transform.update(e,t,n)}params(){return{alpha:this._transform.alpha,beta:this._transform.beta,baseRate:this._transform.baseRate??.5}}}class Ni{constructor(e){b(this,"_tables");b(this,"_views");b(this,"_prepared");b(this,"_sequences");b(this,"_tempTables");b(this,"_graphStore");b(this,"_versionedGraphs");b(this,"_pathIndexes");b(this,"_foreignServers");b(this,"_foreignTables");b(this,"_models");b(this,"_catalog");b(this,"_indexManager");b(this,"_transaction");b(this,"_compiler");b(this,"_dbPath");b(this,"_parallelWorkers");b(this,"_spillThreshold");this._dbPath=(e==null?void 0:e.dbPath)??null,this._parallelWorkers=(e==null?void 0:e.parallelWorkers)??4,this._spillThreshold=(e==null?void 0:e.spillThreshold)??0,this._tables=new Map,this._views=new Map,this._prepared=new Map,this._sequences=new Map,this._tempTables=new Set,this._graphStore=new cr,this._versionedGraphs=new Map,this._pathIndexes=new Map,this._foreignServers=new Map,this._foreignTables=new Map,this._models=new Map,this._catalog=null,this._indexManager=null,this._transaction=null,this._compiler=new le(this)}async sql(e,t){return this._compiler.execute(e,t)}getTable(e){const t=this._tables.get(e);if(t!==void 0)return t;const n=this._compiler.tables.get(e);if(n!==void 0)return this._tables.set(e,n),n;throw new Error(`Table not found: ${e}`)}hasTable(e){return this._tables.has(e)||this._compiler.tables.has(e)}registerTable(e,t){this._tables.set(e,t),this._compiler.tables.set(e,t)}addDocument(e,t,n,r){const s=this._tables.get(n);if(s===void 0)throw new Error(`Table '${n}' does not exist`);const o={...t};s.primaryKey!==null&&!(s.primaryKey in o)&&s.columns.get(s.primaryKey)!==void 0&&(o[s.primaryKey]=e);let i=null,a=null;if(r!=null){for(const[u,h]of s.columns)if(h.vectorDimensions!==null){i=u;break}i!==null&&(a=r,o[i]=Array.from(r))}s.documentStore.put(e,o);const l={};for(const[u,h]of Object.entries(o))typeof h=="string"&&(l[u]=h);if(Object.keys(l).length>0&&s.invertedIndex.addDocument(e,l),i!==null&&a!==null){const u=s.vectorIndexes.get(i);u!==void 0&&u.add(e,a)}}getDocument(e,t){const n=this._tables.get(t);if(n===void 0)throw new Error(`Table '${t}' does not exist`);return n.documentStore.get(e)}deleteDocument(e,t){const n=this._tables.get(t);if(n===void 0)throw new Error(`Table '${t}' does not exist`);n.documentStore.delete(e),n.invertedIndex.removeDocument(e)}getGraphStore(e){return this._graphStore}addGraphVertex(e,t){this._graphStore.addVertex(e,t)}addGraphEdge(e,t){this._graphStore.addEdge(e,t)}createGraph(e){return this._graphStore.createGraph(e),this._catalog!==null&&this._catalog.saveNamedGraph(e),this._graphStore}dropGraph(e){this._graphStore.dropGraph(e),this._catalog!==null&&this._catalog.dropNamedGraph(e)}getGraph(e){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);return this._graphStore}hasGraph(e){return this._graphStore.hasGraph(e)}get graphStore(){return this._graphStore}estimateConvWeights(e,t,n,r="embedding"){return To(this,e,t,n,r)}saveModel(e,t){this._models.set(e,t),this._catalog!==null&&this._catalog.saveModel(e,t)}loadModel(e){const t=this._models.get(e);if(t!==void 0)return t;if(this._catalog!==null){const n=this._catalog.loadModel(e);return n!==null&&this._models.set(e,n),n}return null}deleteModel(e){this._models.delete(e),this._catalog!==null&&this._catalog.deleteModel(e)}buildPathIndex(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);const n=new Ii;n.build(this._graphStore,e,t),this._pathIndexes.set(e,n),this._catalog!==null&&this._catalog.savePathIndex(e,t)}getPathIndex(e){return this._pathIndexes.get(e)??null}dropPathIndex(e){this._pathIndexes.delete(e),this._catalog!==null&&this._catalog.dropPathIndex(e)}createAnalyzer(e,t){const n=Le.fromDict(t);bs(e,n),this._catalog!==null&&this._catalog.saveAnalyzer(e,t)}dropAnalyzer(e){ws(e),this._catalog!==null&&this._catalog.dropAnalyzer(e)}setTableAnalyzer(e,t,n,r="both"){const s=this.getTable(e),o=vs(n);s.invertedIndex.setFieldAnalyzer(t,o,r),this._catalog!==null&&(r==="both"?(this._catalog.saveTableFieldAnalyzer(e,t,"index",n),this._catalog.saveTableFieldAnalyzer(e,t,"search",n)):this._catalog.saveTableFieldAnalyzer(e,t,r,n))}getTableAnalyzer(e,t,n="index"){const r=this._tables.get(e);if(r===void 0)throw new Error(`Table '${e}' does not exist`);return n==="search"?r.invertedIndex.getSearchAnalyzer(t):r.invertedIndex.getFieldAnalyzer(t)}saveScoringParams(e,t){this._catalog!==null&&this._catalog.saveScoringParams(e,t)}loadScoringParams(e){return this._catalog!==null?this._catalog.loadScoringParams(e):null}loadAllScoringParams(){return this._catalog!==null?this._catalog.loadAllScoringParams():[]}learnScoringParams(e,t,n,r,s){const o=(s==null?void 0:s.mode)??"balanced",i=this._tables.get(e);if(i===void 0)throw new Error(`Table '${e}' does not exist`);const a=this._contextForTable(e),l=a.invertedIndex,h=(t?l.getSearchAnalyzer(t):l.analyzer).analyze(n),f=new ct(Je(),l.stats),d=new _e(n,t||null),m=new pe(f,d,h,t||null).execute(a),_=new Map;for(const S of m)_.set(S.docId,S.payload.score);const y=[...i.documentStore.docIds].sort((S,N)=>S-N);if(r.length!==y.length)throw new Error(`labels length (${String(r.length)}) must match document count (${String(y.length)})`);const x=y.map(S=>_.get(S)??0),E=new zn().fit(x,r,{mode:o}),I=`${e}.${t}.${n}`;return this.saveScoringParams(I,E),E}updateScoringParams(e,t,n,r){const s=`${e}.${t}`,o=this.loadScoringParams(s);let i;o!==null?i=new zn(o.alpha??1,o.beta??0,o.base_rate??.5):i=new zn,i.update(n,r),this.saveScoringParams(s,i.params())}vectorBackgroundStats(e,t){const n=this._tables.get(e);if(n===void 0)return null;const r=n.vectorIndexes.get(t);return r!==void 0&&r.backgroundStats!==void 0?r.backgroundStats:null}begin(){if(this._catalog===null)throw new Error("Transactions require a persistent engine (dbPath)");if(this._transaction!==null&&this._transaction.active)throw new Error("Transaction already active");return this._transaction=new Ei(this._catalog.conn),this._transaction}query(e){return new te(this,e)}insert(e,t,n){const r=this.getTable(e);r.documentStore.put(t,n);const s={};for(const[o,i]of r.columns){const a=n[o];i.pythonType==="string"&&a!==null&&a!==void 0&&(s[o]=typeof a=="string"?a:String(a))}Object.keys(s).length>0&&r.invertedIndex.addDocument(t,s);for(const[o,i]of r.vectorIndexes){const a=n[o];a!=null&&(a instanceof Float64Array?i.add(t,a):Array.isArray(a)&&i.add(t,new Float64Array(a)))}}get dbPath(){return this._dbPath}get parallelWorkers(){return this._parallelWorkers}get spillThreshold(){return this._spillThreshold}get compiler(){return this._compiler}get catalog(){return this._catalog}get indexManager(){return this._indexManager}_contextForTable(e){const t=this._tables.get(e);if(t===void 0)throw new Error(`Table '${e}' does not exist`);const n={};for(const[s,o]of t.vectorIndexes)n[s]=o;const r={};for(const[s,o]of t.spatialIndexes)r[s]=o;return{documentStore:t.documentStore,invertedIndex:t.invertedIndex,vectorIndexes:n,spatialIndexes:r,graphStore:this._graphStore,indexManager:this._indexManager}}deepLearn(e,t,n){if(this._tables.get(e)===void 0)throw new Error(`Table '${e}' does not exist`);const s={...n,_model_name:t,_table:e,_trained_at:new Date().toISOString(),_status:"trained"};return this.saveModel(t,s),s}deepPredict(e,t){if(this.loadModel(e)===null)throw new Error(`Model '${e}' not found`);return t.map((r,s)=>({_input_idx:s,_model:e,_prediction:null,...r}))}applyGraphDelta(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);if(t.removeEdges)for(const n of t.removeEdges)this._graphStore.removeEdge(n,e);if(t.removeVertices)for(const n of t.removeVertices)this._graphStore.removeVertex(n,e);if(t.addVertices)for(const n of t.addVertices)this._graphStore.addVertex(n,e);if(t.addEdges)for(const n of t.addEdges)this._graphStore.addEdge(n,e);this._catalog!==null&&this._catalog.saveNamedGraph(e)}createGraphVersion(e,t){if(!this._graphStore.hasGraph(e))throw new Error(`Graph '${e}' does not exist`);const n=this._versionedGraphs.get(e);if(n===void 0){const r={versions:new Map},s=new Map,o=new Map;for(const i of this._graphStore.verticesInGraph(e))s.set(i.vertexId,{...i});for(const i of this._graphStore.edgesInGraph(e))o.set(i.edgeId,{...i});r.versions.set(t,{vertices:s,edges:o}),this._versionedGraphs.set(e,r)}else{const r=new Map,s=new Map;for(const o of this._graphStore.verticesInGraph(e))r.set(o.vertexId,{...o});for(const o of this._graphStore.edgesInGraph(e))s.set(o.edgeId,{...o});n.versions.set(t,{vertices:r,edges:s})}}graphVersions(e){const t=this._versionedGraphs.get(e);return t===void 0?[]:[...t.versions.keys()]}restoreGraphVersion(e,t){const n=this._versionedGraphs.get(e);if(n===void 0)throw new Error(`No versions exist for graph '${e}'`);const r=n.versions.get(t);if(r===void 0)throw new Error(`Version '${t}' not found for graph '${e}'`);const s=this._graphStore.verticesInGraph(e);for(const o of s)this._graphStore.removeVertex(o.vertexId,e);for(const o of r.vertices.values())this._graphStore.addVertex(o,e);for(const o of r.edges.values())this._graphStore.addEdge(o,e)}calibrationReport(e,t){const r=this.loadAllScoringParams().filter(([o])=>o.startsWith(`${e}.${t}`)),s={table:e,field:t,numCalibrations:r.length,params:r.map(([o,i])=>({name:o,alpha:i.alpha??null,beta:i.beta??null,baseRate:i.base_rate??null}))};if(r.length>0){const o=r.map(([,a])=>a.alpha).filter(a=>typeof a=="number"),i=r.map(([,a])=>a.beta).filter(a=>typeof a=="number");o.length>0&&(s.mean_alpha=o.reduce((a,l)=>a+l,0)/o.length,s.std_alpha=o.length>1?Math.sqrt(o.reduce((a,l)=>a+(l-s.mean_alpha)**2,0)/(o.length-1)):0),i.length>0&&(s.mean_beta=i.reduce((a,l)=>a+l,0)/i.length)}return s}saveToCatalog(){if(this._catalog!==null){for(const[e,t]of this._tables)if(!this._tempTables.has(e)){const n=[];for(const[r,s]of t.columns)n.push({...s,name:r});this._catalog.saveTableSchema(e,n)}for(const[e,t]of this._sequences)this._catalog.setMetadata(`seq:${e}`,JSON.stringify(t));for(const e of this._graphStore.graphNames())this._catalog.saveNamedGraph(e);for(const[e,t]of this._models)this._catalog.saveModel(e,t)}}loadFromCatalog(){if(this._catalog===null)return;const e=this._catalog.loadTableSchemas();for(const[n]of e);const t=this._catalog.loadNamedGraphs();for(const n of t)this._graphStore.hasGraph(n)||this._graphStore.createGraph(n)}close(){this._transaction!==null&&this._transaction.active&&(this._transaction.rollback(),this._transaction=null),this._foreignTables.clear(),this._foreignServers.clear();for(const e of this._tempTables)this._tables.delete(e);this._tempTables.clear(),this._catalog!==null&&(this._catalog.close(),this._catalog=null),this._tables.clear(),this._graphStore.clear()}}$.AggregateResult=sn,$.Analyzer=Le,$.BM25Scorer=xt,$.BayesianBM25Scorer=ct,$.Between=un,$.ComplementOperator=de,$.Engine=Ni,$.Equals=ln,$.FacetResult=qn,$.FilterOperator=G,$.FlatVectorIndex=lr,$.GeneralizedPostingList=Se,$.GreaterThan=Wn,$.GreaterThanOrEqual=Hn,$.HierarchicalDocument=cs,$.ILike=Qn,$.InSet=cn,$.IndexStats=Bn,$.IntersectOperator=H,$.IsNotNull=fn,$.IsNull=hn,$.KNNOperator=je,$.LessThan=Kn,$.LessThanOrEqual=Jn,$.Like=Xn,$.MemoryDocumentStore=or,$.MemoryGraphStore=cr,$.MemoryInvertedIndex=ir,$.NotEquals=Un,$.Operator=q,$.PostingList=D,$.QueryBuilder=te,$.Table=Ut,$.TermOperator=_e,$.UnionOperator=re,$.createBM25Params=qt,$.createBayesianBM25Params=Je,$.keywordAnalyzer=rr,$.standardAnalyzer=Sn,$.whitespaceAnalyzer=nr,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
16
16
  //# sourceMappingURL=uqa.umd.js.map