semanticdb-v2 2.0.0-alpha.8 → 2.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- "use strict";var Sa=Object.create;var ko=Object.defineProperty;var Ia=Object.getOwnPropertyDescriptor;var ba=Object.getOwnPropertyNames;var Ra=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var Oa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ba(e))!Na.call(t,o)&&o!==r&&ko(t,o,{get:()=>e[o],enumerable:!(n=Ia(e,o))||n.enumerable});return t};var Ke=(t,e,r)=>(r=t!=null?Sa(Ra(t)):{},Oa(e||!t||!t.__esModule?ko(r,"default",{value:t,enumerable:!0}):r,t));var Zr=require("node:perf_hooks"),ae=require("dayjs"),qt=require("dayjs/plugin/isoWeek.js"),cr=require("dayjs/plugin/quarterOfYear.js"),Uo=require("dayjs/plugin/customParseFormat.js"),en=require("node:crypto"),Mo=require("node:util"),Ta=require("redis"),Pa=require("semanticdb-core"),de=require("@duckdb/node-api");const F=t=>typeof t=="string",jt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},qo=t=>t==null?"":""+t,La=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Ca=/###/g,jo=t=>t&&t.indexOf("###")>-1?t.replace(Ca,"."):t,xo=t=>!t||F(t),xt=(t,e,r)=>{const n=F(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(xo(t))return{};const i=jo(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return xo(t)?{}:{obj:t,k:jo(n[o])}},Bo=(t,e,r)=>{const{obj:n,k:o}=xt(t,e,Object);if(n!==void 0||e.length===1){n[o]=r;return}let i=e[e.length-1],s=e.slice(0,e.length-1),a=xt(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=xt(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},Da=(t,e,r,n)=>{const{obj:o,k:i}=xt(t,e,Object);o[i]=o[i]||[],o[i].push(r)},ur=(t,e)=>{const{obj:r,k:n}=xt(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},ka=(t,e,r)=>{const n=ur(t,r);return n!==void 0?n:ur(e,r)},Vo=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?F(t[n])||t[n]instanceof String||F(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Vo(t[n],e[n],r):t[n]=e[n]);return t},nt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ua={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Ma=t=>F(t)?t.replace(/[&<>"'\/]/g,e=>Ua[e]):t;class qa{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const ja=[" ",",","?","!",";"],xa=new qa(20),Ba=(t,e,r)=>{e=e||"",r=r||"";const n=ja.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=xa.getRegExp(`(${n.map(s=>s==="?"?"\\?":s).join("|")})`);let i=!o.test(t);if(!i){const s=t.indexOf(r);s>0&&!o.test(t.substring(0,s))&&(i=!0)}return i},tn=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},Bt=t=>t?.replace(/_/g,"-"),Va={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Wr{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Va,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,o){return o&&!this.debug?null:(F(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Wr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Wr(this.logger,e)}}var Me=new Wr;class dr{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(r)||0;this.observers[n].set(r,o+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o.apply(o,[e,...r])})}}class Fo extends dr{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,o={}){const i=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,r],n&&(Array.isArray(n)?a.push(...n):F(n)&&i?a.push(...n.split(i)):a.push(n)));const u=ur(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!F(n)?u:tn(this.data?.[e]?.[r],n,i)}addResource(e,r,n,o,i={silent:!1}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let a=[e,r];n&&(a=a.concat(s?n.split(s):n)),e.indexOf(".")>-1&&(a=e.split("."),o=r,r=a[1]),this.addNamespaces(r),Bo(this.data,a,o),i.silent||this.emit("added",e,r,n,o)}addResources(e,r,n,o={silent:!1}){for(const i in n)(F(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=ur(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Vo(u,n,i):u={...u,...n},Bo(this.data,a,u),s.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var Yo={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,o){return t.forEach(i=>{e=this.processors[i]?.process(e,r,n,o)??e}),e}};const vo=Symbol("i18next/PATH_KEY");function Fa(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===vo?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function yt(t,e){const{[vo]:r}=t(Fa()),n=e?.keySeparator??".",o=e?.nsSeparator??":";if(r.length>1&&o){const i=e?.ns,s=Array.isArray(i)?i:null;if(s&&s.length>1&&s.slice(1).includes(r[0]))return`${r[0]}${o}${r.slice(1).join(n)}`}return r.join(n)}const Qo={},rn=t=>!F(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends dr{constructor(e,r={}){super(),La(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Me.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const o=this.resolve(e,n);if(o?.res===void 0)return!1;const i=rn(o.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const s=n&&e.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!Ba(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:F(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:F(i)?[i]:i}}translate(e,r,n){let o=typeof r=="object"?{...r}:r;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=yt(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(U=>typeof U=="function"?yt(U,{...this.options,...o}):String(U));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return f?i?{res:`${c}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let y=m?.res;const h=m?.usedKey||a,g=m?.exactUsedKey||a,_=["[object Number]","[object Function]","[object RegExp]"],E=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,w=o.count!==void 0&&!F(o.count),A=zr.hasDefaultValue(o),R=w?this.pluralResolver.getSuffix(l,o.count,o):"",T=o.ordinal&&w?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",P=w&&!o.ordinal&&o.count===0,x=P&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${T}`]||o.defaultValue;let K=y;S&&!y&&A&&(K=x);const B=rn(K),Q=Object.prototype.toString.apply(K);if(S&&K&&B&&_.indexOf(Q)<0&&!(F(E)&&Array.isArray(K))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const U=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,K,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=U,m.usedParams=this.getUsedParamsDetails(o),m):U}if(s){const U=Array.isArray(K),z=U?[]:{},ue=U?g:h;for(const J in K)if(Object.prototype.hasOwnProperty.call(K,J)){const le=`${ue}${s}${J}`;A&&!y?z[J]=this.translate(le,{...o,defaultValue:rn(x)?x[J]:void 0,joinArrays:!1,ns:u}):z[J]=this.translate(le,{...o,joinArrays:!1,ns:u}),z[J]===le&&(z[J]=K[J])}y=z}}else if(S&&F(E)&&Array.isArray(y))y=y.join(E),y&&(y=this.extendTranslation(y,e,o,n));else{let U=!1,z=!1;!this.isValidLookup(y)&&A&&(U=!0,y=x),this.isValidLookup(y)||(z=!0,y=a);const J=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&z?void 0:y,le=A&&x!==y&&this.options.updateMissing;if(z||U||le){if(this.logger.log(le?"updateKey":"missingKey",l,c,a,le?x:y),s){const k=this.resolve(a,{...o,keySeparator:!1});k&&k.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Oe=[];const ke=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ke&&ke[0])for(let k=0;k<ke.length;k++)Oe.push(ke[k]);else this.options.saveMissingTo==="all"?Oe=this.languageUtils.toResolveHierarchy(o.lng||this.language):Oe.push(o.lng||this.language);const D=(k,Y,$)=>{const I=A&&$!==y?$:J;this.options.missingKeyHandler?this.options.missingKeyHandler(k,c,Y,I,le,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(k,c,Y,I,le,o),this.emit("missingKey",k,c,Y,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?Oe.forEach(k=>{const Y=this.pluralResolver.getSuffixes(k,o);P&&o[`defaultValue${this.options.pluralSeparator}zero`]&&Y.indexOf(`${this.options.pluralSeparator}zero`)<0&&Y.push(`${this.options.pluralSeparator}zero`),Y.forEach($=>{D([k],a+$,o[`defaultValue${$}`]||x)})}):D(Oe,a,x))}y=this.extendTranslation(y,e,o,m,n),z&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${c}${p}${a}`),(z||U)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${p}${a}`:a,U?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(e,r,n,o,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=F(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const l=e.match(this.interpolator.nestingRegexp);c=l&&l.length}let p=n.replace&&!F(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||o.usedLng,n),u){const l=e.match(this.interpolator.nestingRegexp),f=l&&l.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...l)=>i?.[0]===l[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${l[0]} in key: ${r[0]}`),null):this.translate(...l,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=F(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Yo.handle(a,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,o,i,s,a;return F(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?yt(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),p=c.key;o=p;let l=c.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const f=r.count!==void 0&&!F(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(F(r.context)||typeof r.context=="number")&&r.context!=="",h=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach(g=>{this.isValidLookup(n)||(a=g,!Qo[`${h[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(Qo[`${h[0]}-${g}`]=!0,this.logger.warn(`key "${o}" for languages "${h.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach(_=>{if(this.isValidLookup(n))return;s=_;const E=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(E,p,_,g,r);else{let w;f&&(w=this.pluralResolver.getSuffix(_,r.count,r));const A=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&w.indexOf(R)===0&&E.push(p+w.replace(R,this.options.pluralSeparator)),E.push(p+w),m&&E.push(p+A)),y){const T=`${p}${this.options.contextSeparator||"_"}${r.context}`;E.push(T),f&&(r.ordinal&&w.indexOf(R)===0&&E.push(T+w.replace(R,this.options.pluralSeparator)),E.push(T+w),m&&E.push(T+A))}}let S;for(;S=E.pop();)this.isValidLookup(n)||(i=S,n=this.getResource(_,g,S,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,r,n,o):this.resourceStore.getResource(e,r,n,o)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!F(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o.count=e.count),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const i of r)delete o[i]}return o}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&r===n.substring(0,r.length)&&e[n]!==void 0)return!0;return!1}}class Ho{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Me.create("languageUtils")}getScriptPartFromCode(e){if(e=Bt(e),!e||e.indexOf("-")<0)return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=Bt(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(F(e)&&e.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return r=o;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=this.options.supportedLngs.find(s=>{if(s===i)return s;if(!(s.indexOf("-")<0&&i.indexOf("-")<0)&&(s.indexOf("-")>0&&i.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===i||s.indexOf(i)===0&&i.length>1))return s})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),F(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return F(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):F(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const Go={zero:0,one:1,two:2,few:3,many:4,other:5},Wo={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Ya{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Me.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Bt(e==="dev"?"en":e),o=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:o});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let s;try{s=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Wo;if(!e.match(/-|_/))return Wo;const u=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(u,r)}return this.pluralRulesCache[i]=s,s}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(o=>`${r}${o}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>Go[o]-Go[i]).map(o=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(e,r,n={}){const o=this.getRule(e,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const zo=(t,e,r,n=".",o=!0)=>{let i=ka(t,e,r);return!i&&o&&F(r)&&(i=tn(t,r,n),i===void 0&&(i=tn(e,r,n))),i},nn=t=>t.replace(/\$/g,"$$$$");class Ko{constructor(e={}){this.logger=Me.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:h,nestingOptionsSeparator:g,maxReplaces:_,alwaysFormat:E}=e.interpolation;this.escape=r!==void 0?r:Ma,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?nt(i):s||"{{",this.suffix=a?nt(a):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=f?nt(f):m||nt("$t("),this.nestingSuffix=y?nt(y):h||nt(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=_||1e3,this.alwaysFormat=E!==void 0?E:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const _=zo(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(_,void 0,n,{...o,...r,interpolationkey:m}):_}const y=m.split(this.formatSeparator),h=y.shift().trim(),g=y.join(this.formatSeparator).trim();return this.format(zo(r,u,h,this.options.keySeparator,this.options.ignoreJSONStructure),g,n,{...o,...r,interpolationkey:h})};this.resetRegExp();const p=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,l=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>nn(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?nn(this.escape(m)):nn(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const y=i[1].trim();if(s=c(y),s===void 0)if(typeof p=="function"){const g=p(e,i,o);s=F(g)?g:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!F(s)&&!this.useRawValueToEscape&&(s=qo(s));const h=m.safeValue(s);if(e=e.replace(i[0],h),l?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const p=this.nestingOptionsSeparator;if(u.indexOf(p)<0)return u;const l=u.split(new RegExp(`${nt(p)}[ ]*{`));let f=`{${l[1]}`;u=l[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(h){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,h),`${u}${p}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!F(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!F(i))return i;F(i)||(i=qo(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((p,l)=>this.format(p,l,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const va=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=c),c==="false"&&(r[p]=!1),c==="true"&&(r[p]=!0),isNaN(c)||(r[p]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},Jo=t=>{const e={};return(r,n,o)=>{let i=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(i={...i,[o.interpolationkey]:void 0});const s=n+JSON.stringify(i);let a=e[s];return a||(a=t(Bt(n),o),e[s]=a),a(r)}},Qa=t=>(e,r,n)=>t(Bt(r),n)(e);class Ha{constructor(e={}){this.logger=Me.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Jo:Qa;this.formats={number:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i});return a=>s.format(a)}),currency:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i,style:"currency"});return a=>s.format(a)}),datetime:n((o,i)=>{const s=new Intl.DateTimeFormat(o,{...i});return a=>s.format(a)}),relativetime:n((o,i)=>{const s=new Intl.RelativeTimeFormat(o,{...i});return a=>s.format(a,i.range||"day")}),list:n((o,i)=>{const s=new Intl.ListFormat(o,{...i});return a=>s.format(a)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=Jo(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:p}=va(u);if(this.formats[c]){let l=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;l=this.formats[c](a,m,{...p,...o,...f})}catch(f){this.logger.warn(f)}return l}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const Ga=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Wa extends dr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Me.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let p=!0;r.forEach(l=>{const f=`${c}|${l}`;!n.reload&&this.store.hasResourceBundle(c,l)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,p=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[l]===void 0&&(u[l]=!0)))}),p||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{Da(u.loaded,[i],s),Ga(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const p=u.loaded[c];p.length&&p.forEach(l=>{a[c][l]===void 0&&(a[c][l]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,p)=>{if(this.readingCalls--,this.waitingReads.length>0){const l=this.waitingReads.shift();this.read(l.lng,l.ns,l.fcName,l.tried,l.wait,l.callback)}if(c&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,p)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(p=>a(null,p)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();F(e)&&(e=this.languageUtils.toResolveHierarchy(e)),F(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let p;c.length===5?p=c(e,r,n,o,u):p=c(e,r,n,o),p&&typeof p.then=="function"?p.then(l=>a(null,l)).catch(a):a(null,p)}catch(p){a(p)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const on=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),F(t[1])&&(e.defaultValue=t[1]),F(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Xo=t=>(F(t.ns)&&(t.ns=[t.ns]),F(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),F(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),lr=()=>{},za=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Zo="__i18next_supportNoticeShown",Ka=()=>!!(typeof globalThis<"u"&&globalThis[Zo]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),Ja=()=>{typeof globalThis<"u"&&(globalThis[Zo]=!0)},Xa=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class ar extends dr{constructor(e={},r){if(super(),this.options=Xo(e),this.services={},this.logger=Me,this.modules={external:[]},za(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(F(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=on();this.options={...n,...this.options,...Xo(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Xa(this)&&!Ka()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("\u{1F310} i18next is made possible by our own product, Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"),Ja());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?Me.init(o(this.modules.logger),this.options):Me.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=Ha;const p=new Ho(this.options);this.store=new Fo(this.options.resources,this.options);const l=this.services;l.logger=Me,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Ya(p,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(c),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new Ko(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Wa(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(l.languageDetector=o(this.modules.languageDetector),l.languageDetector.init&&l.languageDetector.init(l,this.options.detection,this.options)),this.modules.i18nFormat&&(l.i18nFormat=o(this.modules.i18nFormat),l.i18nFormat.init&&l.i18nFormat.init(this)),this.translator=new zr(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=lr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...p)=>this.store[c](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...p)=>(this.store[c](...p),this)});const a=jt(),u=()=>{const c=(p,l)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(l),r(p,l)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=lr){let n=r;const o=F(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=jt();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=lr),this.services.backendConnector.reload(e,r,i=>{o.resolve(),n(i)}),o}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Yo.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=jt();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=F(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(F(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,p=>{i(p,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=yt(u.keyPrefix,c));const p=this.options.keySeparator||".";let l;return u.keyPrefix&&Array.isArray(i)?l=i.map(f=>(typeof f=="function"&&(f=yt(f,c)),`${u.keyPrefix}${p}${f}`)):(typeof i=="function"&&(i=yt(i,c)),l=u.keyPrefix?`${u.keyPrefix}${p}${i}`:i),this.t(l,u)};return F(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=jt();return this.options.ns?(F(e)&&(e=[e]),e.forEach(o=>{this.options.ns.indexOf(o)<0&&this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=jt();F(e)&&(e=[e]);const o=this.options.preload||[],i=e.filter(s=>o.indexOf(s)<0&&this.services.languageUtils.isSupportedCode(s));return i.length?(this.options.preload=o.concat(i),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const i=o.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new Ho(on());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new ar(e,r);return n.createInstance=ar.createInstance,n}cloneInstance(e={},r=lr){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new ar(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((p,l)=>(p[l]={...u[c][l]},p),u[c]),u),{});i.store=new Fo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...on().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new Ko(c)}return i.translator=new zr(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const _e=ar.createInstance(),Za=_e.createInstance;_e.dir,_e.init,_e.loadResources,_e.reloadResources,_e.use,_e.changeLanguage,_e.getFixedT,_e.t,_e.exists,_e.setDefaultNamespace,_e.hasLoadedNamespace,_e.loadNamespaces,_e.loadLanguages;const ei={locale:"en-US",messages:{"operator.rows":"rows","operator.$sum":"Total {operandName}","operator.$avg":"Average {operandName}","operator.$min":"Minimum {operandName}","operator.$max":"Maximum {operandName}","operator.$count":"{operandName} count","operator.$count.rows":"Row count","operator.$countDistinct":"Distinct {operandName} count","operator.$add":"{inputNames}","operator.$add.empty":"Sum of {operandName}","operator.$subtract":"{input0} minus {input1}","operator.$subtract.fallback":"{operandName} difference","operator.$multiply":"{inputNames}","operator.$multiply.empty":"Product of {operandName}","operator.$divide":"{input0} divided by {input1}","operator.$divide.fallback":"{operandName} ratio","operator.$concat":"Combined {inputNames}","operator.$concat.empty":"Combined {operandName}","operator.$abs":"Absolute {operandName}","operator.$substring":"{operandName} substring","operator.$case":"{operandName} category","operator.$constant":"Constant","operator.$sql":"Calculated value","operator.$rowNumber":"Row number","operator.$rank":"{operandName} rank","operator.$accumulate":"Cumulative {operandName}","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.autoCase":"Resolve automatic bucket boundaries","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.total":"Count result rows before pagination","sql.semanticResolution":"Semantic resolution"}},ti={locale:"zh-CN",messages:{"operator.rows":"\u6570\u636E\u884C","operator.$sum":"\u603B{operandName}","operator.$avg":"\u5E73\u5747{operandName}","operator.$min":"{operandName}\u6700\u5C0F\u503C","operator.$max":"{operandName}\u6700\u5927\u503C","operator.$count":"{operandName}\u6570\u91CF","operator.$count.rows":"\u884C\u6570","operator.$countDistinct":"{operandName}\u53BB\u91CD\u8BA1\u6570","operator.$add":"{inputNames}","operator.$add.empty":"{operandName}\u6C42\u548C","operator.$subtract":"{input0}\u51CF\u53BB{input1}","operator.$subtract.fallback":"{operandName}\u5DEE\u503C","operator.$multiply":"{inputNames}","operator.$multiply.empty":"{operandName}\u4E58\u79EF","operator.$divide":"{input0}\u9664\u4EE5{input1}","operator.$divide.fallback":"{operandName}\u6BD4\u503C","operator.$concat":"{inputNames}\u62FC\u63A5\u503C","operator.$concat.empty":"{operandName}\u62FC\u63A5\u503C","operator.$abs":"{operandName}\u7EDD\u5BF9\u503C","operator.$substring":"{operandName}\u5B50\u4E32","operator.$case":"{operandName}\u5206\u7C7B","operator.$constant":"\u5E38\u91CF","operator.$sql":"\u8BA1\u7B97\u503C","operator.$rowNumber":"\u884C\u53F7","operator.$rank":"{operandName}\u6392\u540D","operator.$accumulate":"{operandName}\u7D2F\u8BA1\u503C","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.autoCase":"\u8BA1\u7B97\u81EA\u52A8\u5206\u6BB5\u8FB9\u754C","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.total":"\u8BA1\u7B97\u5206\u9875\u524D\u7684\u7ED3\u679C\u603B\u6570","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},ec=[ti,ei],Vt=t=>t.trim().toLowerCase(),tc=t=>t?"locale"in t?[t]:t:[],rc=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return typeof e.locale=="string"&&e.locale.trim().length>0&&typeof e.messages=="object"&&e.messages!==null&&!Array.isArray(e.messages)};class sn{definitions=new Map;i18n;constructor(e){this.i18n=Za(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(ec),this.register(e)}register(e){for(const r of tc(e)){const n=r;if(!rc(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Vt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Vt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Vt(e));if(r)return r;const n=Vt(e).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(e){return this.definitions.has(Vt(e))}translate(e,r,n,o){const i=this.resolve(e);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(e="zh-CN"){return(r,n,o)=>this.translate(e,r,n,o)}}const pr=t=>new sn(t),fr=new sn;class d extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=fr){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(e,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&e.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}ae.extend(qt),ae.extend(cr);const nc=new Set(["year","quarter","month","week"]),an=t=>t.format("YYYY-MM-DD HH:mm:ss"),cn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?cn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&cn(r,e)),mr=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new d("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:mr(t.input,e,r)};if(t.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:t,...r};if(t.kind!=="operator")return{kind:"cumulative",function:"sum",input:t,...r};const n=e.getOperator(t.operator);if(n.kind==="component")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${t.operator}`);if(n.kind==="aggregate"){if(t.operator==="$avg"){const s={...t,operator:"$sum"},a={...t,operator:"$count"};return{kind:"operator",operator:"$divide",args:{},inputs:[{kind:"cumulative",function:"sum",input:s,...r},{kind:"cumulative",function:"sum",input:a,...r}]}}const i={$sum:"sum",$count:"sum",$min:"min",$max:"max"}[t.operator];if(!i)throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${t.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:t,...r}}if(n.kind!=="scalar")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:mr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>mr(o,e,r))}:{}}},oc=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new d("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(t.inputProperty?.comparable&&t.input.kind!=="ordinal-decode")throw new d("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const e=t.args.partitionBy??[],r=t.args.orderBy;if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:t.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return mr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},ic=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!cn(t.pred.pred,t.getOperator))throw new d("ACCUMULATE_AGGREGATE_REQUIRED","$accumulate over a grouped physical relation requires an aggregate expression");const e=t.pred.args?.partitionBy,r=t.pred.args?.orderBy;if(e!==void 0&&!Array.isArray(e)||!Array.isArray(r)||r.length===0||r.some(i=>typeof i!="object"||i===null||Array.isArray(i)||typeof i.pred!="string"||Object.keys(i).some(s=>s!=="pred"&&s!=="direction")||i.direction!==void 0&&i.direction!=="asc"&&i.direction!=="desc"))return;const n=[...e??[],...r.map(i=>i.pred)];if(n.some(i=>typeof i!="string"))return;const o=n.map(i=>t.resolveGroupName(String(i)));if(o.length!==t.groupByNames.length||new Set(o).size!==t.groupByNames.length||t.groupByNames.some(i=>!o.includes(i)))throw new d("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:t.groupByNames,received:o})},sc=(t,e,r)=>{if(t.from||t.having)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,w])=>{if(typeof w!="object"||w===null||Array.isArray(w))return!1;const A=w;return typeof A.$gte=="string"&&typeof A.$lte=="string"});if(!n)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=ae(String(s.$gte)),u=ae(String(s.$lte));if(!a.isValid()||!u.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map(w=>{if(!w.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return w.name}),p=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...t.query,[o]:{...s,$gte:an(p)}},f=new Set([...(t.groupby??[]).map(({name:w})=>w),...(t.preds??[]).map(({name:w})=>w)]),m=w=>{let A=w;for(;f.has(A);)A=`_${A}`;return f.add(A),A},y=m("__accumulate_period"),h=e.map((w,A)=>m(`__accumulate_metric_${A}`)),g=(t.groupby??[]).map(({name:w})=>String(w)),_=r==="year"||r==="quarter"?"month":"day",E={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:_},name:y}],preds:e.map((w,A)=>({...w.pred,name:h[A]??`__accumulate_metric_${A}`}))},S={version:t.version,from:E,preds:[...g.map(w=>({pred:w,name:w})),{pred:y,name:y},...e.map((w,A)=>({operator:"$accumulate",pred:h[A]??`__accumulate_metric_${A}`,args:{partitionBy:g,orderBy:[{pred:y,direction:"asc"}]},name:c[A]??`accumulate_${A}`}))]};return{version:t.version,from:S,query:{[y]:{$gte:an(a),$lte:an(u)}},preds:[...g.map(w=>({pred:w,name:w})),...c.map(w=>({pred:w,name:w}))],...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},ac={name:"$accumulate",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Cumulative ${t}`:`${t}\u7D2F\u8BA1\u503C`,kind:"logical",normalizePred({pred:t}){const e=t.args?.period;if(e!==void 0&&(typeof e!="string"||!nc.has(e)))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period must be year, quarter, month, or week");if(e!==void 0&&(t.args?.partitionBy!==void 0||t.args?.orderBy!==void 0))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return t},planExpression:oc,validatePlan:ic,rewriteLogicform({logicform:t,schema:e}){const r=(t.preds??[]).filter(s=>s.operator==="$accumulate"&&s.args?.period!==void 0);if(r.length===0)return;const n=r[0]?.args?.period;if(r.some(s=>s.args?.period!==n))throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","All $accumulate args.period projections in one LogicForm must use the same period");const o=new Set(Object.keys(t.query??{}));if(e.properties.filter(s=>s.primal_type==="date"&&o.has(s.name)).length!==1)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return sc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},cc={name:"$abs",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Absolute ${t}`:`${t}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:t}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},ht=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new d("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},yr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),uc={name:"$add",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" plus "):`Sum of ${t}`:e.length>0?e.join("\u52A0"):`${t}\u6C42\u548C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$add.empty":"operator.$add",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:yr(t)}},te=t=>structuredClone(t),dc=(t,e)=>{const r=e[t];if(!r)throw new d("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in r||"_sid"in r)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in r)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(r.id!==t)throw new d("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${r.id}`,{registryKey:t,schemaId:r.id});return r},lc=(t,e)=>{const r=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!r)throw new d("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return r},pc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},ri=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,fc=(t,e)=>t.properties.flatMap(r=>[...e.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&e.startsWith(`${r.name}_`)?[{property:r,prefix:r.name}]:[]]).sort((r,n)=>n.prefix.length-r.prefix.length||(n.prefix===n.property.id?1:0)-(r.prefix===r.property.id?1:0)),ce=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:ri(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of fc(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=ce(s,e.slice(i.length+1),r);return{canonicalName:`${ri(t,o)}_${a.canonicalName}`,canonicalId:`${o.id}_${a.canonicalId}`,schema:a.schema,property:a.property,relations:[{sourceSchema:t,property:o,targetSchema:s},...a.relations]}}throw new d("PROPERTY_NOT_FOUND",`\u5728 Schema\uFF1A${t.name}(${t.id})\u4E2D\u672A\u627E\u5230\u5C5E\u6027: ${e}`,{schemaId:t.id,schemaName:t.name,property:e,propertyName:e})},un=(t,e)=>t.name===e||t.id===e,mc=(t,e,r)=>{const n=new Set,o=[t];for(;o.length>0;){const i=o.shift();if(!i||n.has(i.name))continue;n.add(i.name);const s=[...i.hierarchy?.up?r.properties.filter(a=>un(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&un(i,a.hierarchy.down))];if(s.some(a=>un(e,a.name)))return!0;o.push(...s)}return!1},ni=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ce(r,t.pred,n)}catch{return!1}return o.property.isArray||o.property.primal_type==="entity"||o.property.primal_type==="object"||o.relations.some(({property:i})=>i.isArray)?!1:e.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=ce(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return mc(s.property,o.property,r);if(s.relations.length!==0||o.relations.length===0)return!1;const[a]=o.relations;return s.property.name===a?.property.name})},yc=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new d("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},hc=t=>{if(!t.hierarchy)return;const e=t.properties.find(({name:r})=>r===t.hierarchy?.property);if(!e)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${t.hierarchy.property}`,{schemaId:t.id,property:t.hierarchy.property});return e},gc=(t,e,r)=>{const n=ce(t,e,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new d("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},Ac={name:"$hierarchyLevel",defaultName:({operandName:t,args:e,locale:r})=>{const n=typeof e.level=="string"?e.level:"";return r.toLowerCase().startsWith("en")?`${t}${n?` ${n}`:""} level`:`${t}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:t,args:e,schema:r,resolveSchema:n}){const o=Object.keys(e).filter(y=>y!=="level");if(o.length>0||e.level!==void 0&&(typeof e.level!="string"||e.level.length===0))throw new d("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=gc(r,t,n),s=i.schema.hierarchy;if(!s)throw new d("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:y})=>y===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==ce(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((y,h)=>y+h.codeLength,0),c=i.schema.properties.filter(({type:y})=>y==="ID"),l=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:l,args:{levels:s.levels.map(({name:h,codeLength:g})=>(y+=g,{name:h,codeLength:y})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(y=>(f+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!m)throw new d("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:l,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),c=e.totalLength,p=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:y,codeLength:h},g)=>y.length===0||h<=0||h>Number(c)||g>0&&h<=Number(u[g-1]?.codeLength))||u.at(-1)?.codeLength!==c||p!=="compact"&&p!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const l=`WHEN ${t} IS NULL THEN NULL`;if(p==="compact"){const y=r.stringLength(t),h=u.map(g=>`WHEN ${y} = ${g.codeLength} THEN ${r.value(g.name)}`);return`(CASE ${l} ${h.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(y=>{const h=Number(c)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,h)} = ${r.value("0".repeat(h))} THEN ${r.value(y.name)}`}),m=u.at(-1);return`(CASE ${l} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(t,1,Number(n)),a=Number(o)-Number(n);return i==="zero-padded"&&a>0?r.concat([s,r.value("0".repeat(a))]):s},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},gt=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===2&&e.kind==="hierarchy"&&typeof e.level=="string"&&e.level.trim().length>0},At=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),dn=(t,e,{schema:r,resolveSchema:n})=>{if(typeof e!="string")return;const o=t.primal_type==="entity"||t.primal_type==="object"?t.ref?n?.(t.ref).hierarchy:void 0:r.hierarchy?.property===t.name?r.hierarchy:void 0,i=o?.levels.find(s=>s.name===e||s.syno?.includes(e));if(!(!o||!i))return{name:i.name,index:o.levels.indexOf(i)}},hr=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>At(e,o)?.id===t.id)),oi=(t,e,r)=>{const n=At(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=dn(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=hr(n,r);if(!gt(i?.granularity))return;const s=dn(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},wc=(t,e)=>{const r=i=>{const s=n(i.query);if(s)return s;if(i.operator==="$hierarchyLevel"&&typeof i.pred=="string")if(i.args?.level!==void 0){const u=oi(i.pred,i.args.level,e);if(u)return u}else{const u=At(e.schema,i.pred),c=u&&hr(u,e);if(gt(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=At(e.schema,s),c=u&&hr(u,e);if(gt(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=oi(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=At(e.schema,i.pred),a=s&&hr(s,e);if(gt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},$c={kind:"hierarchy",isGranularity:gt,validateItem(t,e){const r=t.granularity;if(gt(r))return t.propertyTarget?.every(n=>{const o=At(e.schema,n);return o!==void 0&&dn(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:wc,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Ec={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new d("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=t.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new d("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new d("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new d("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new d("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new d("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new d("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,p=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,h=Object.keys(y).filter(_=>_!=="name"&&_!=="syno"&&_!=="codeLength");if(h.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:h});if(typeof y.name!="string"||y.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(y.name)||c.has(y.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some(_=>typeof _!="string"||_.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const g=y.syno??[];for(const _ of g){if(_===y.name||u.has(_)||c.has(_))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${_}`);c.add(_)}return u.add(y.name),{name:y.name,...g.length>0?{syno:[...g]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},_c=Object.freeze({name:"hierarchy",schemaMetadata:Ec,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:yc,resolveEntityFilterProperty:hc,operators:[Ac],mappingGranularity:$c}),Sc=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),ln="$periodValue",Ic=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:ln,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${ln}; ${e.name} describes a time range`,{operator:e.name});return{operator:ln,boundary:"end",implicit:!0}},bc={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!Sc(r,e))return;const s=Ic(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},Rc=new Set(["second","minute","hour","day","week","month","quarter","year"]),ii=t=>typeof t=="string"&&Rc.has(t),Nc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gr=(t,e,r)=>{const n=t instanceof Date?t.getTime():typeof t=="string"||typeof t=="number"?new Date(t).getTime():Number.NaN;if(Number.isNaN(n))throw new d(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},ot=(t,e=2)=>String(t).padStart(e,"0"),pn=t=>`${ot(t.getFullYear(),4)}-${ot(t.getMonth()+1)}-${ot(t.getDate())} ${ot(t.getHours())}:${ot(t.getMinutes())}:${ot(t.getSeconds())}.`+ot(t.getMilliseconds(),3),Oc=(t,e)=>{if(!Nc(t)){const a=gr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=gr(r,"$eq",e);return{lower:a,upper:a}}const n=t.$gte??t.$gt,o=t.$lte??t.$lt;if(n===void 0||o===void 0)throw new d(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=gr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=gr(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new d(`${e.codePrefix}_PERIOD_INVALID_RANGE`,`${e.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},Tc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setMilliseconds(0);break;case"minute":r.setSeconds(0,0);break;case"hour":r.setMinutes(0,0,0);break;case"day":r.setHours(0,0,0,0);break;case"week":{r.setHours(0,0,0,0);const n=(r.getDay()+6)%7;r.setDate(r.getDate()-n);break}case"month":r.setDate(1),r.setHours(0,0,0,0);break;case"quarter":r.setMonth(Math.floor(r.getMonth()/3)*3,1),r.setHours(0,0,0,0);break;case"year":r.setMonth(0,1),r.setHours(0,0,0,0);break}return r},Pc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setSeconds(r.getSeconds()+1);break;case"minute":r.setMinutes(r.getMinutes()+1);break;case"hour":r.setHours(r.getHours()+1);break;case"day":r.setDate(r.getDate()+1);break;case"week":r.setDate(r.getDate()+7);break;case"month":r.setMonth(r.getMonth()+1);break;case"quarter":r.setMonth(r.getMonth()+3);break;case"year":r.setFullYear(r.getFullYear()+1);break}return r},si=(t,e,r)=>{const{lower:n,upper:o}=Oc(t,r),i=[];let s=Tc(n,e);for(;s.getTime()<=o;){if(i.length>=1e4)throw new d(`${r.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${r.label} period grouping cannot generate more than 10000 periods`);const a=Pc(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:pn(s),start:pn(s),end:pn(u)}),s=a}return i},Lc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Cc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Dc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=Lc(t,r),o=t.preds??[],i=o.filter(({operator:l})=>l==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!ii(s))throw new d("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values require $dateBucket with a supported time granularity",{property:r.name});if(i.length!==o.length)throw new d("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(l=>{const f=l.args?.boundary;if(f!=="start"&&f!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!l.pred||typeof l.pred!="object"||Array.isArray(l.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:l,effectivePred:{...l.pred,...l.name?{name:l.name}:{}}}});if(new Set(i.map(({args:l})=>l?.boundary)).size!==1)throw new d("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,p=t.query?.[r.name];if(p===void 0)throw new d("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:si(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[c]}))}},ai=["second","minute","hour","day","week","month","quarter","year"],kc=Object.freeze({name:"observation",schemaMetadata:{keys:["temporalSemantics"],resolve(t){const e=t.temporalSemantics??"normal";if(e!=="normal"&&e!=="snapshot")throw new d("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:t.id,temporalSemantics:e});return{temporalSemantics:e}}},validateResolvedSchema(t){if(t.temporalSemantics==="snapshot"&&!t.properties.some(({type:e})=>e==="timestamp"))throw new d("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.id})},plannerSemantics:[bc],relationSemantics:{plan({sourceSchema:t,targetSchema:e}){if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:s})=>s==="timestamp");if(!r)throw new d("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${e.id} requires an ID and timestamp Property when joined`,{schemaId:e.id});const n=t.properties.find(({type:s})=>s==="timestamp");if(!n)throw new d("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});const o=n.granularity??"day",i=r.granularity??"day";if(ai.indexOf(o)>ai.indexOf(i))throw new d("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${e.id} snapshot granularity ${i} to coarser source granularity ${o}`,{sourceSchemaId:t.id,targetSchemaId:e.id,sourceGranularity:o,targetGranularity:i});return{kind:"date-bucket-equal",sourceTimestamp:n,targetTimestamp:r}}},plannerPeriod:{resolve(t,e){const r=Dc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Cc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Ft=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Uc={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new d("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators")},async normalize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{root:t},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Ft(o,i);if(!a||i===void 0&&s.length!==1)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),l=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof l!="string"||l.length===0)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(r.includeSelf!==void 0&&typeof r.includeSelf!="boolean"||r.include_self!==void 0&&typeof r.include_self!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:p,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:l}},authorize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=e.resolveSchema(n);if(e.assertSchemaAllowed(n),e.hasRowPermissions(n))throw new d("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):Ft(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=Ft(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const r=t,n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=Ft(o,r.idProperty),s=Ft(o,r.parentProperty);if(!i)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId);return{value:{schemaId:n,connectionId:a.connectionId,source:a.source,...a.sourceSql?{sourceSql:a.sourceSql}:{},idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:a.source,...a.connectionId?{connectionId:a.connectionId}:{}}]}},compile(t,{field:e,provider:r,bind:n,renderSource:o}){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(typeof i.source!="string"||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new d("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(w=>n(w)).join(", "),h=(w,A=!1)=>s.length===1?`${w} ${A?"<>":"="} ${y()}`:`${w} ${A?"NOT IN":"IN"} (${y()})`,g=`${c}.${l}`,_=i.includeSelf?h(g):`${h(`${c}.${f}`)} AND ${h(g,!0)}`,E=r.recursiveCteUnion??"UNION",S=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${g} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${_} ${E} SELECT ${p}.${l} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${p}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${S}`}},Mc=Object.freeze({name:"recursive",schemaMetadata:{keys:["parentProperty"],resolve(t,e){if(t.parentProperty===void 0)return{};const r=e.find(({id:n,name:o})=>n===t.parentProperty||o===t.parentProperty);if(!r)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${t.parentProperty}`,{schemaId:t.id,property:t.parentProperty});return{parentProperty:r.name}}},queryOperators:[Uc]});ae.extend(qt);const fn=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...fn(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:fn(r))]:e},ci=(t,e)=>ae(t).endOf(e==="week"?"isoWeek":e).toDate(),mn=t=>ae(t).format("YYYY-MM-DD HH:mm:ss"),qc=(t,e)=>{const r=t??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},ui=(t,e)=>{if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be an object`);const r=t,n=Object.keys(r);if(!(r.type==="database_latest"&&n.length===1)&&!(r.type==="now_offset"&&n.every(o=>o==="type"||o==="offset")&&Number.isInteger(r.offset)))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},jc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return ui(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(ui(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new d("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(fn).filter(l=>l!==e.id))],c=[{schema:e,property:r}];for(const l of u){const f=s(l),m=t.propertyResolve?.[l],y=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!y)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const h=f.properties.find(({id:g,name:_})=>g===y||_===y);if(!h||h.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${y}`,{schemaId:l,property:y});c.push({schema:f,property:h})}const p=c.map(({schema:l,property:f})=>{const m=qc(f.timeWatermark??l.timeWatermark??i,`${l.id}.${f.id}`);if(m.type==="now_offset"){const y=ci(ae(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:mn(y),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:mn(ci(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:mn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),Ar=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Yt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=Ar(t.properties,"ID"),r=Ar(t.properties,"timestamp"),n=Ar(t.properties,"start_date"),o=Ar(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},di=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),xc=(t,e)=>di(t,e)!==void 0,Bc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Vc=(t,e)=>{const r=di(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!ii(n))throw new d("VALIDITY_PERIOD_GRANULARITY_UNSUPPORTED","Valid-time period grouping requires $dateBucket with a supported time granularity",{property:e.timestamp.name});const o=t.query?.[e.timestamp.name];if(o===void 0)throw new d("VALIDITY_PERIOD_BOUNDS_REQUIRED",`Valid-time period grouping on ${e.timestamp.name} requires a bounded query`,{property:e.timestamp.name});return{group:r,granularity:n,periods:si(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},Fc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Yc=t=>Fc(t)?t.$lte??t.$lt??t.$eq:t,li=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,u])=>[a,(a==="$and"||a==="$or")&&Array.isArray(u)?u.map(c=>li(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=Yc(o);if(i===void 0)throw new d("VALIDITY_POINT_IN_TIME_REQUIRED",`Valid-time query on ${e.timestamp.name} requires an upper bound or a point in time`,{property:e.timestamp.name});return{...Object.fromEntries(Object.entries(r).filter(([a])=>a!==e.timestamp.name)),[e.start.name]:t[e.start.name]??{$lte:i},[e.end.name]:t[e.end.name]??{$or:[{$exists:!1},{$gt:i}]}}},pi=(t,e)=>!!(t&&Object.entries(t).some(([r,n])=>e.has(r)||(r==="$and"||r==="$or")&&Array.isArray(n)&&n.some(o=>typeof o=="object"&&o!==null&&pi(o,e)))),vc={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Yt(e);if(!n)return r;if(xc(t,n))return Bc(r,n);const i=pi(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return li(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Yt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Qc={name:"start_date",primalType:"date"},Hc={name:"end_date",primalType:"date"},Gc=Object.freeze({name:"validity",semanticTypes:[Qc,Hc],prepareSchema(t){const e=t.properties.filter(({type:s})=>s==="ID"),r=t.properties.filter(({type:s})=>s==="start_date"),n=t.properties.filter(({type:s})=>s==="end_date"),o=r[0];if(t.type!=="entity"||t.properties.some(({type:s})=>s==="timestamp")||t.temporalSemantics==="snapshot"||e.length!==1||r.length!==1||n.length!==1||t.properties.some(({name:s})=>s==="\u65E5\u671F")||!o)return t;const i={id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",is_supplementary:!0,udf:{sql:o.id??o.name}};return{...t,properties:[...t.properties,i]}},plannerSemantics:[vc],intervalSemantics:{resolve:Yt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Yt(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new d("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});return{kind:"point-in-interval",point:n,start:r.start,end:r.end}}},plannerPeriod:{resolve(t,e){const r=Yt(e);if(!r)return;const n=Vc(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),fi=(t,e,r,n)=>{if(r===void 0)return;if(typeof r!="string"||r.length===0)throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${e.name} hierarchy.${n} must be a non-empty Property name or id`,{property:e.name,direction:n,reference:r});const o=t.find(i=>i.id===r)??t.find(i=>i.name===r);if(!o)throw new d("PROPERTY_HIERARCHY_TARGET_NOT_FOUND",`Property ${e.name} hierarchy.${n} does not exist: ${r}`,{property:e.name,direction:n,reference:r});if(o===e)throw new d("PROPERTY_HIERARCHY_CYCLE",`Property ${e.name} cannot point to itself in hierarchy.${n}`,{property:e.name,direction:n});return o.name},Wc=Object.freeze({name:"property-hierarchy",propertyMetadata:{keys:["hierarchy"],resolve:()=>({}),resolveAll(t,e){const r=t.map((o,i)=>{const s=e[i]?.hierarchy;if(s===void 0)return o;if(typeof s!="object"||s===null||Array.isArray(s))throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=fi(t,o,a.up,"up"),p=fi(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...p?{down:p}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new d("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r}}}),mi=Object.freeze([_c,Mc,jc,kc,Gc,Wc]),fe=(t=[])=>{const e=[...mi,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,p=new Set;for(const l of e){if(!l.name)throw new d("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(l.name))throw new d("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${l.name}`,{plugin:l.name});r.add(l.name);for(const m of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!m)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:l.name});n.add(m)}for(const m of l.propertyMetadata?.keys??[]){if(!m)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:l.name});o.add(m)}for(const m of l.operators??[]){if(i.has(m.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:l.name});i.add(m.name)}for(const m of l.semanticTypes??[]){if(s.has(m.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:l.name});s.add(m.name)}for(const m of l.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:l.name});a.add(m.name)}for(const m of l.queryOperators??[]){if(!m.name||u.has(m.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:l.name});u.add(m.name)}for(const m of l.outputHandlers??[]){if(!m.type||c.has(m.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:l.name});c.add(m.type)}const f=l.mappingGranularity;if(f){if(!f.kind||p.has(f.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);p.add(f.kind)}}return Object.freeze(e)},wt=(t,e=[])=>fe(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),yi=(t,e=[])=>fe(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),yn=(t,e)=>{if(e.length>1)throw new d("PLUGIN_SEMANTIC_CAPABILITY_AMBIGUOUS",`Multiple plugins matched ${t}: ${e.map(({plugin:r})=>r).join(", ")}`,{capability:t,plugins:e.map(({plugin:r})=>r)});return e[0]?.value},hi=(t,e=[])=>yn("interval semantics",fe(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),zc=(t,e,r=[])=>yn("relation semantics",fe(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Kc=(t,e,r=[])=>yn("planner period semantics",fe(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),hn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),Jc=t=>{const e=t.properties.filter(({type:r})=>r==="ID");if(e.length!==1)throw new d("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${t.id} must contain exactly one ID property to use entity_id`,{schemaId:t.id,idPropertyCount:e.length});return e[0]},gn=(t,e=[])=>{for(const r of fe(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return Jc(t)},An=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},wn=t=>typeof t.pred=="string"?t.pred:void 0,Xc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Zc={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},eu={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},$n=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!Xc(o))return r?.("period.comparison",n?"period-over-period":"\u540C\u671F")??(n?"period-over-period":"\u540C\u671F");if(typeof o.granularity=="string"&&typeof o.offset=="number"){if(o.offset===-1&&o.granularity==="year")return r?.("period.yearOverYear",n?"year-over-year":"\u540C\u6BD4")??(n?"year-over-year":"\u540C\u6BD4");if(o.offset===-1&&o.granularity==="month")return r?.("period.monthOverMonth",n?"month-over-month":"\u73AF\u6BD4")??(n?"month-over-month":"\u73AF\u6BD4");if(o.offset===-1&&o.granularity==="week")return r?.("period.weekOverWeek",n?"week-over-week":"\u5468\u73AF\u6BD4")??(n?"week-over-week":"\u5468\u73AF\u6BD4");if(o.offset===0)return r?.("period.current",n?"current-period":"\u672C\u671F")??(n?"current-period":"\u672C\u671F");const s=Math.abs(o.offset),a=o.offset<0?"before":"after";return n?`${s} ${o.granularity}${s===1?"":"s"} ${a}`:`\u8F83${a==="before"?"\u524D":"\u540E"}${s}${Zc[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${eu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};ae.extend(qt),ae.extend(cr);const tu=["second","minute","hour","day","week","month","quarter","year"],ru=new Set(tu),En=["year","quarter","month","week","day","hour","minute","second"],gi=t=>Object.prototype.toString.call(t)==="[object Object]",Je=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},nu=t=>{const e=t.time;gi(e)||Je("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!ru.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&Je("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!En.includes(a)||!Number.isInteger(u)))&&Je("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&Je("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<u||Number(p)>c)&&Je(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&Je("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&Je("Absolute period shift day requires month"),r},Ai=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),ou=(t,e)=>{if("granularity"in e){const n=e.granularity==="week"?"week":e.granularity;return t.add(e.offset,n)}let r=t;for(const n of En){const o=e[n];typeof o=="number"&&(r=Ai(r,n,o))}return r},_n=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),iu=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=wn(i);return s?ce(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:An(i),granularity:a,offset:u}}),Sn=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>Sn(i,e,r));if(gi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,Sn(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=ae(t);if(!n.isValid())return t;const o=ou(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,_n(t,o)},su=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,p])=>{if((c==="$and"||c==="$or")&&Array.isArray(p))return[c,p.map(f=>s(f))];const l=ce(e,c,r);return l.property.primal_type!=="date"?[c,p]:(i.add(l.canonicalName),[c,Sn(p,n,o)])})),a=s(t);if(i.size===0||o.shiftedValues===0)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new d("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},it=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},Xe=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Xe(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:Xe(r)):[]],au=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=ae(t);if(!n.isValid())return t;if("granularity"in e)return _n(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of En)if(e[i]!==void 0){const s=i==="month"?r.originalAnchor.month()+1:i==="day"?r.originalAnchor.date():i==="week"?r.originalAnchor.isoWeek():i==="quarter"?r.originalAnchor.quarter():r.originalAnchor.get(i);o=Ai(o,i,s)}return _n(t,o)},In=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&Je("$periodShift pred must be a nested metric");const s=nu(e.args??{}),a={shiftedValues:0},u=it([t.query,...Xe(e)]);if(!u)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=su(u,n,o,s,a),p=te(i);p.name=r,delete p.query;const l=te(t);l.query=c,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const f=new Set((t.groupby??[]).filter(m=>{const y=wn(m);return y?ce(n,y,o).property.primal_type==="date":!1}).map(An));return{kind:"query",logicform:l,groupKeyShifts:iu(t,n,o,s,a),mapResult:m=>m.map(y=>{const h={...y};for(const g of f)h[g]=au(h[g],s,a);return h})}},cu={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=$n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} baseline`:`${t}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:In,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},uu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),wr=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,wi=(t,e)=>{const r=t.properties.find(({type:n})=>n==="timestamp");if(!r)throw new d("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},$i=(t,e)=>{if(wr(t)){e.start??=t,e.end??=t;return}if(!uu(t))return;const r=t.$eq;wr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;wr(n)&&(e.start??=n),wr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)$i(a,e)}},du=(t,e,r,n)=>{const o=wi(e,n),i=new Set,s={},a=(l,f)=>{for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const g of y)a(g,f||m==="$or");continue}if(m.startsWith("$"))continue;const h=ce(e,m,r);if(h.property.type==="timestamp"){if(f)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(h.canonicalName),$i(y,s)}}};if(a(t,!1),i.size!==1)throw new d(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const u=[...i][0];if(!u||u!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const c=l=>{const f=[];for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const h=y.map(g=>c(g)).filter(g=>g!==void 0);h.length>0&&f.push([m,h]);continue}!m.startsWith("$")&&ce(e,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},p=c(t);return{property:o,propertyName:u,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Ei=(t,e,r,n,o)=>{const i=it([t,...Xe(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return du(i,r,n,o)},_i=(t,e,r)=>it([t,{[e]:r}]),lu=new Set(["day","week","month","quarter","year"]),pu={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},fu=t=>{if(typeof t!="string"||!lu.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Si=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},bn=t=>{const e=te(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=bn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:bn(r))),e},mu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${pu[String(e.granularity)]??"\u5468\u671F"}\u5747\u503C`,kind:"component",createComponent({logicform:t,pred:e,schema:r,outputName:n,t:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=fu(e.args?.granularity),s=wi(r,"$averagePerPeriod"),a=bn(e.pred),u=it([t.query,...Xe(e)]),c=Si(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const p=Si(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(p.query=u);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:c},{name:f,logicform:p}],expression:`${l} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},yu={name:"$avg",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Average ${t}`:`\u5E73\u5747${t}`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$avg requires a column");return r.aggregateFunction("avg",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$avg requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},$t=t=>{throw new d("INVALID_CASE_ARGS",t)},hu=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&$t("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&$t("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&$t("$case auto mode args.buckets must be an integer between 2 and 100");const r=t.count;if(r!==void 0&&(!Number.isSafeInteger(r)||r<0)&&$t("$case auto mode args.count must be a non-negative safe integer"),t.empty===!0)return{empty:!0};for(const o of["min","max"])(typeof t[o]!="number"||!Number.isFinite(t[o]))&&$t(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&$t("$case auto mode args.min cannot be greater than args.max");const n=e===void 0?r===void 0?10:Math.min(12,Math.max(5,Math.ceil(Math.log2(Math.max(r,1))+1))):e;return{empty:!1,minimum:t.min,maximum:t.max,targetBuckets:n}},gu=t=>{const r=10**Math.floor(Math.log10(t)),n=t/r;return(n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*r},$r=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},Rn=t=>String($r(t)),Au=(t,e,r)=>{if(t===e)return[t,e];const n=gu((e-t)/r),o=$r(Math.floor(t/n)*n),i=$r(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,u)=>u===s?i:$r(o+n*u))},wu=t=>{if(!Array.isArray(t)||t.length===0)throw new d("INVALID_CASE_ARGS","$case requires a non-empty args.cases array");return t.map(e=>{if(typeof e!="object"||e===null||!("when"in e)||!("then"in e))throw new d("INVALID_CASE_ARGS","Each $case item requires when and then");const r=e;return{when:r.when,then:r.then}})},$u={name:"$case",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} category`:`${t}\u5206\u7C7B`,kind:"scalar",validateGroupby({pred:t}){if(t.args?.mode==="auto"&&t.args.empty!==!0&&(t.args.min===void 0||t.args.max===void 0))throw new d("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires resolved args.min and args.max")},toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=hu(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,u=n.maximum;if(a===u)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(Rn(a))} END`;const c=Au(a,u,n.targetBuckets),p=c.slice(0,-1).map((f,m)=>{const y=c[m+1],h=m===c.length-2?"]":")";return`[${Rn(f)}, ${Rn(y)}${h}`}),l=p.slice(0,-1).map((f,m)=>`WHEN ${t} < ${r.value(c[m+1])} THEN ${r.value(f)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=wu(e.cases).map(({when:s,then:a})=>`WHEN ${r.condition(t,s)} THEN ${r.value(a)}`),i=Object.hasOwn(e,"default")?` ELSE ${r.value(e.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:t}){return{name:t,type:"category",primal_type:"string",isArray:!1}}},Eu={name:"$concat",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?`Combined ${e.join(" and ")}`:`Combined ${t}`:e.length>0?`${e.join("\u4E0E")}\u62FC\u63A5\u503C`:`${t}\u62FC\u63A5\u503C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$concat.empty":"operator.$concat",kind:"scalar",requiresProperty:!1,toSQL(t){return t.sql.concat(ht("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},_u={name:"$count",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?t==="rows"?"Row count":`${t} count`:t==="\u6570\u636E\u884C"?"\u884C\u6570":`${t}\u6570\u91CF`,defaultNameKey:({inputName:t,inputNames:e})=>t||e.length>0?"operator.$count":"operator.$count.rows",kind:"aggregate",requiresProperty:!1,toSQL(t){const{column:e,sql:r}=t;return r.aggregateFunction("count",e)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Su={name:"$countDistinct",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Distinct ${t} count`:`${t}\u53BB\u91CD\u8BA1\u6570`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$countDistinct requires a column");return r.aggregateFunction("count",`DISTINCT ${e}`)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Iu=new Set(["second","minute","hour","day","week","month","quarter","year"]),bu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ii=t=>{if(typeof t!="string"||!Iu.has(t))throw new d("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be second, minute, hour, day, week, month, quarter, or year");return t},Ru={name:"$dateBucket",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} by ${typeof e.granularity=="string"?e.granularity:"time"}`:`${t}\uFF08\u6309${bu[String(e.granularity)]??"\u65F6\u95F4"}\uFF09`,kind:"scalar",supportsGroupedSourceGroupby:!0,groupedSourceTimeGranularity:({pred:t})=>t.args?.granularity,toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$dateBucket requires a date pred");return r.dateBucket(t,Ii(e.granularity))},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=Ii(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Nu={name:"$divide",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} divided by ${e[1]}`:`${t} ratio`:e.length>=2?`${e[0]}\u9664\u4EE5${e[1]}`:`${t}\u6BD4\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$divide.fallback":"operator.$divide",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return yr(t)}},Ou=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$max",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Tu={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Ou,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$max requires a column");return r.aggregateFunction("max",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$max requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},Pu=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$min",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Lu={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Pu,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$min requires a column");return r.aggregateFunction("min",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$min requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},Cu={name:"$multiply",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" times "):`Product of ${t}`:e.length>0?e.join("\u4E58\u4EE5"):`${t}\u4E58\u79EF`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$multiply.empty":"operator.$multiply",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return yr(t)}},Du=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Nn=t=>{const e=te(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Nn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Nn(r))),e},ku={name:"$newly",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`New ${t}`:`\u65B0\u589E${t}`,kind:"component",createComponent({logicform:t,pred:e,schema:r,resolveSchema:n,outputName:o,t:i}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(l=>{const f=wn(l);return f?ce(r,f,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Ei(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new d("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=Nn(e.pred),u=(l,f)=>{const m=Du(t);return m.query=_i(s.queryWithoutTime,s.propertyName,{$lte:l}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:p,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Uu=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},On=t=>{const e=te(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=On(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:On(r))),e},Mu={name:"$periodValue",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,defaultNameKey:({args:t})=>`operator.$periodValue.${t.boundary==="start"?"start":"end"}`,kind:"component",skipComponentExecution:({plan:t})=>t.periodSource?.match.kind==="latest",periodBoundaryPolicy({pred:t}){const e=t.args?.boundary;if(e!=="start"&&e!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:e});return{boundary:e,implicit:!1}},createComponent({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=Ei(t.query,e,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new d("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=Uu(t);return c.query=_i(s.queryWithoutTime,s.propertyName,u),c.preds=[{...On(e.pred),name:r}],{kind:"query",logicform:c}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},qu=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},ju=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodDifference pred must be a nested metric");const a=te(e.pred);a.name="__period_diff_current__";const u=qu(t);u.preds=[a];const c=it([t.query,...Xe(e)]);c&&(u.query=c);const p={pred:te(e.pred),...e.args?{args:e.args}:{}},l=In({logicform:t,pred:p,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},xu={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=$n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} difference`:`${t}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:ju,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Bu=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Vu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=te(e.pred);a.name="__period_growth_current__";const u=Bu(t);u.preds=[a];const c=it([t.query,...Xe(e)]);c&&(u.query=c);const p={pred:te(e.pred),...e.args?{args:e.args}:{}},l=In({logicform:t,pred:p,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},Fu={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=$n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} growth`:`${t}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Vu,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Yu={name:"$sum",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Total ${t}`:`\u603B${t}`,kind:"aggregate",supportsGroupedSourceRollup:!0,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$sum requires a column");return r.aggregateFunction("sum",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$sum requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},vu={name:"$subtract",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} minus ${e[1]}`:`${t} difference`:e.length>=2?`${e[0]}\u51CF\u53BB${e[1]}`:`${t}\u5DEE\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$subtract.fallback":"operator.$subtract",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$subtract",t,2);if(t.args.nullAsZero!==void 0&&typeof t.args.nullAsZero!="boolean")throw new d("INVALID_SUBTRACT_ARGS","$subtract args.nullAsZero must be boolean");return t.args.nullAsZero===!0?`(COALESCE(${e}, 0) - COALESCE(${r}, 0))`:`(${e} - ${r})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:yr(t)}},bi=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Tn=t=>{const e=te(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Tn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Tn(r))),e},Qu={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e,outputName:r,t:n}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=e.args?.dimension;if(o!==void 0&&typeof o!="string")throw new d("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=t.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||An(y)===o);if(o!==void 0&&s<0)throw new d("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,h)=>h!==s),u=Tn(e.pred),c=bi(t);c.preds=[{...u,name:"__share_numerator__"}];const p=it([t.query,...Xe(e)]);p&&(c.query=p);const l=bi(t);l.groupby=a,l.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Hu={name:"$substring",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} substring`:`${t}\u5B50\u4E32`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:n,length:o}=e;if(!Number.isInteger(n)||Number(n)<0||!Number.isInteger(o)||Number(o)<1)throw new d("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return r.substring(t,Number(n)+1,Number(o))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Ri=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new d("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new d("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},Gu=new Set(["boolean","date","number","entity","object","string"]),Wu=t=>{if(t===void 0)return[];if(!Array.isArray(t))throw new d("INVALID_SQL_ARGS","$sql args.parameters must be an array");return t},zu=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!Gu.has(n))throw new d("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new d("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new d("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:t,type:r,primal_type:n==="object"?"entity":n,isArray:e.isArray===!0,...typeof e.ref=="string"?{ref:e.ref}:{}}},Ku={name:"$sql",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:t,expression:e,expressions:r,sql:n}){if(e||r&&r.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Ri(t.sql,Wu(t.parameters),o=>n.value(o))},getOutputProperty({name:t,args:e,inputProperty:r,inputProperties:n}){if(r||n&&n.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return zu(t,e)}},Ju=t=>{const e=new Set,r=n=>{for(const[o,i]of Object.entries(n)){if(o==="$and"||o==="$or"){for(const s of i)r(s);continue}e.add(o)}};return r(t),[...e]},Xu=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},Zu=(t,e,r)=>{const n=t.preds;if(n.filter(p=>p.operator==="$rank"&&p.query).length!==1)throw new d("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=Ju(r),[s]=i;if(i.length!==1||!s)throw new d("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=te(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(p=>{if(p.name!==e.name)return p;const l={...p};return delete l.query,Xu(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:p})=>p).filter(p=>!!p),c=te(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(p=>({pred:p,name:p}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},ed={name:"$rank",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} rank`:`${t}\u6392\u540D`,kind:"window",windowFunction:"rank",rewriteLogicform({logicform:t}){if(t.groupby?.length)return;const e=t.preds?.find(r=>r.operator==="$rank"&&r.query);return e?.query?Zu(t,e,e.query):void 0},validatePlan({pred:t,groupByNames:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(e.length===0&&!t.query&&typeof t.pred!="string")throw new d("RANK_GROUPBY_OR_TARGET_REQUIRED","$rank requires groupby or a pred.query target used to infer the ranking dimension")},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},td={name:"$rowNumber",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},rd=new Set(["string","number","boolean","date","entity","object"]),Pn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&rd.has(t))return{type:t,primal_type:t};throw new d("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},nd={name:"$constant",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(t.pred!==void 0)throw new d("INVALID_CONSTANT_INPUT","$constant does not accept pred");return Pn(t.args?.type),t},toSQL({args:t,sql:e}){return Pn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...Pn(e.type),isArray:!1}}},od={name:"$periodBoundary",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D":"\u671F\u672B"}`,defaultNameKey:({args:t})=>`operator.$periodBoundary.${t.boundary==="start"?"start":"end"}`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=e.boundary;if(n!=="start"&&n!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=e.granularity;if(typeof o!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");const i=r.dateBucket(t,o);return r.datePeriodBoundary?r.datePeriodBoundary(t,o,n):n==="start"?i:r.dateShift(r.dateShift(i,o,1),"second",-1)},planExpression({input:t,inputProperty:e,args:r}){if(!t)return;const n=e?.granularity??r.granularity;return{kind:"operator",operator:"$periodBoundary",input:t,args:{...r,granularity:n}}},normalizePred({pred:t,schema:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodBoundary requires one pred");if(typeof t.pred=="string"){const r=e.properties.find(({id:n,name:o})=>n===t.pred||o===t.pred);return{...t,args:{...t.args,granularity:r?.granularity}}}return t},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=e.granularity??r.granularity;if(typeof n!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...e,name:t,granularity:n,isArray:!1}}},Ni="__scalarExtremumInputs",Ln=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Ln(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Ln(r)??[]))];if(e.length===1)return e[0]}},id=t=>{const e=te(t);return delete e.from,delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.representation,delete e.output,e},sd=(t,e)=>{if(e.args?.[Ni]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new d("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${e.operator} with multiple pred inputs must be the only LogicForm projection`);const r=e.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:te(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??Ln(s);return{...s,name:a,...u?{schema:u}:{}}}),n=id(t);return n.preds=r,{version:t.version,from:n,preds:[{operator:e.operator,pred:r.map(({name:o})=>o),...e.name?{name:e.name}:{},args:{...e.args,[Ni]:!0}}],...t.having?{having:t.having}:{},...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},ad=(t,e)=>{const r=t==="$least"?"MIN":"MAX",n=e.map(o=>`SELECT ${o} AS value`).join(" UNION ALL ");return`(SELECT ${r}(value) FROM (${n}) AS __scalar_extremum_values)`},cd=(t,e,r)=>{const[n,...o]=r??[];if(!n)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new d("INCOMPATIBLE_OPERATOR_INPUTS",`${t} pred inputs must have the same primal type`);return{...n,name:e,isArray:!1}},Oi=t=>({name:t,defaultName:({inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t==="$least"?"Least":"Greatest"} of ${e.join(", ")}`:`${e.join("\u3001")}\u4E2D\u7684${t==="$least"?"\u6700\u65E9\u503C":"\u6700\u665A\u503C"}`,kind:"scalar",requiresProperty:!1,normalizePred({pred:e}){if(!Array.isArray(e.pred)||e.pred.length<2)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires at least two pred inputs`);return e},rewriteLogicform({logicform:e}){const r=e.preds?.[0];return r?.operator===t?sd(e,r):void 0},toSQL(e){const r=ht(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??ad(t,r)},getOutputProperty({name:e,inputProperties:r}){return cd(t,e,r)}}),ud=Oi("$least"),dd=Oi("$greatest"),Cn={second:{en:"second",zh:"\u79D2"},minute:{en:"minute",zh:"\u5206\u949F"},hour:{en:"hour",zh:"\u5C0F\u65F6"},weekday:{en:"weekday",zh:"\u661F\u671F"},day:{en:"day",zh:"\u65E5"},week:{en:"week",zh:"\u5468"},month:{en:"month",zh:"\u6708"},quarter:{en:"quarter",zh:"\u5B63\u5EA6"},year:{en:"year",zh:"\u5E74"}},ld={name:"$length",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} length`:`${t}\u957F\u5EA6`,kind:"scalar",toSQL({expression:t,sql:e}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$length requires a pred");return e.stringLength(t)},getOutputProperty({name:t,inputProperty:e}){if(!e||e.primal_type!=="string"||e.isArray)throw new d("LENGTH_STRING_REQUIRED","$length requires a scalar string-valued pred");return{name:t,type:"int",primal_type:"number",isArray:!1}}},pd=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${Cn[t].en}`:`${e}${Cn[t].zh}`,kind:"scalar",toSQL({expression:e,sql:r}){if(!e)throw new d("PRED_PROPERTY_REQUIRED",`$${t} requires a pred`);return r.datePart(e,t)},getOutputProperty({name:e,inputProperty:r}){if(!r||r.primal_type!=="date"||r.isArray)throw new d("DATE_PART_DATE_REQUIRED",`$${t} requires a scalar date-valued pred`);return{name:e,type:"int",primal_type:"number",isArray:!1}}}),fd=Object.freeze(Object.keys(Cn).map(pd)),Ti=Object.freeze([ac,Yu,_u,Su,yu,Lu,Tu,cu,Fu,xu,mu,Mu,ku,uc,vu,Cu,Nu,cc,Qu,$u,Eu,Hu,Ru,Ku,ed,td,nd,od,ud,dd,ld,...fd]),md={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},yd={name:"category",primalType:"string"},hd={name:"currency",primalType:"number"},gd={name:"date",primalType:"date"},Ad={name:"duration",primalType:"number"},Pi=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),wd={name:"object",primalType:"object",hydrateResult:Pi},$d={name:"entity",primalType:"entity",hydrateResult:Pi},Ed={name:"file",primalType:"string"},_d={name:"humanName",primalType:"string"},Sd={name:"ID",primalType:"string"},Id={name:"image",primalType:"string"},bd={name:"int",primalType:"number"},Rd={name:"name",primalType:"string"},Nd={name:"number",primalType:"number"},Od={name:"order",primalType:"number"},Td={name:"percentage",primalType:"number"},Pd={name:"string",primalType:"string"},Ld={name:"timestamp",primalType:"date"},Dn=Object.freeze([Sd,Pd,Rd,_d,yd,Id,Ed,Nd,bd,hd,Td,Ad,Od,md,Ld,gd,$d,wd]),Cd=(t,e,r)=>{if(typeof t=="function")return t;if(typeof t!="string"||t.trim().length===0)return;const n=new Function(`return (${t})`)();if(typeof n!="function")throw new TypeError(`Operator ${r} ${e} must resolve to a function`);return n},Li=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Operator definition must be an object");const e=t,r=e.name,n=typeof r=="string"?r:"",o=e.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=Cd(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=Dn.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class Mt{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new Mt(this.definitions(),e)}register(e){const r=Li(e);if(!r.name)throw new d("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new d("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new d("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new d("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(e){const r=this.#e.get(e);if(!r)throw new d("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return r}requiresPerPeriodEvaluation(e,r){return this.get(e).requiresPerPeriodEvaluation?.({...r,executionContext:this.executionContext})??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const Dd=Object.freeze([...Ti,...mi.flatMap(({operators:t})=>t??[])]),De=(t=[])=>new Mt([...Ti,...fe(t).flatMap(({operators:e})=>e??[])]),Et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Ci=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",kd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Di=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Ud=(t,e)=>{const r=lc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},ki=(t,e,r)=>{const n=t.fieldReferences?.[r];return n?{schemaId:n.schemaId,propertyId:n.propertyId??n.column,propertyName:n.property,physicalColumn:n.sql??n.column}:Ud(e,r)},vt=(t,e,r,n)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>vt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>vt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=vt(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>vt(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Er(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>ki(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function Er(t){if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&e.push(...Er(o));else r==="$expr"&&Di(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const Ye=t=>t.kind==="window"?[...Ye(t.input),...t.partitionBy.flatMap(Ye)]:t.kind==="cumulative"?[...Ye(t.input),...t.partitionBy.flatMap(Ye),...t.orderBy.flatMap(({expression:e})=>Ye(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Ye(t.input):t.kind==="operator"?[...Er(t.query),...t.input?Ye(t.input):[],...(t.inputs??[]).flatMap(Ye)]:[],Ui=(t,e,r,n=De(),o)=>{if(t.subplans){const s=t.subplans.map(u=>Ui(u,e,r,n,o)),a=new Map;for(const u of s){u.source.connectionId&&a.set(u.source.connectionId,u.source.provider);for(const c of u.source.connections??[])a.set(c.connectionId,c.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:u})=>u.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([u,c])=>({connectionId:u,provider:c}))},outputs:t.projections.map(({name:u})=>{const c=s.flatMap(({outputs:p})=>p.filter(l=>l.name===u));return{name:u,sources:c.flatMap(({sources:p})=>p),transformations:[...new Set([...c.flatMap(({transformations:p})=>p),"compose"])]}}),filters:s.flatMap(({filters:u})=>u)}}const i=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source,...(t.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...vt(s.expression,t,e,n)})),filters:[...new Set([...Er(t.query),...t.projections.flatMap(({expression:s})=>Ye(s))])].map(s=>ki(t,e,s))}},Se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Md=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,Mi=t=>{const e=Md.exec(t);if(!e)return;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);if(!(r>23||n>59||o>59))return{hour:r,minute:n,second:o}},qi=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new d("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!Mi(e.expireAt))throw new d("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone}).format()}catch{throw new d("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}},qd=new Set(["second","minute","hour","day","week","month","quarter","year"]),kn=t=>typeof t=="string"&&qd.has(t),Un=(t,e=fe())=>kn(t)||typeof t=="object"&&t!==null&&!Array.isArray(t)&&e.some(r=>{const n=r.mappingGranularity;return n!==void 0&&n.kind===t.kind&&n.isGranularity(t)});class Mn{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=fe(r);for(const n of e)this.register(n)}register(e){for(const s of this.plugins){const a=s.schemaMapping?.validate?.(e);if(a)throw new d("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${s.name}: ${a}`,{plugin:s.name,reason:a})}if(!e.schemaId)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");const r=new Set,n=new Set;for(const s of e.enrichments??[]){if(!s.id||r.has(s.id))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");if(!s.source||s.source===e.source||n.has(s.source))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(s.sourceSql!==void 0&&s.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sourceSql must not be empty");if(s.on.length===0||s.on.some(({baseColumn:a,targetColumn:u})=>!a||!u))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(s.temporal?.kind==="point"&&!s.temporal.pointColumn)throw new d("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");qi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!Un(s.granularity,this.plugins)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping granularity requires a property item and a supported physical granularity");if(s.mappingType==="property"&&(!s.sourceColumn||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||!s.predItem?.operator||typeof s.predItem.pred!="string"))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred");if(s.sourceRef!==void 0&&(s.mappingType!=="property"||!r.has(s.sourceRef)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceRef requires a property item and a registered enrichment id")}qi(e);const o=this.#e.get(e.schemaId)??[],i=e.id??e.source;if(o.some(s=>s.connectionId===e.connectionId&&((s.id??s.source)===i||s.source===e.source)))throw new d("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${i}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:i});return this.#e.set(e.schemaId,[...o,e]),this}get(e,r){const n=this.list(e),o=r===void 0?n:n.filter(s=>s.connectionId===r);if(o.length===0)throw new d("SCHEMA_MAPPING_CONNECTION_NOT_FOUND",`Schema ${e} has no mapping on connection ${r}`,{schemaId:e,connectionId:r});if(o.length===1)return o[0];const i=o.filter(s=>(s.mappings??[]).length===0);if(i.length===1)return i[0];throw new d("SCHEMA_MAPPING_AMBIGUOUS",r===void 0?`Schema ${e} has multiple mappings and requires LogicForm-based selection`:`Schema ${e} has multiple mappings on connection ${r} and requires LogicForm-based selection`,{schemaId:e,...r===void 0?{}:{connectionId:r},mappingIds:o.map(s=>s.id??s.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const jd=t=>{if(t.tablePath?.trim())return t.tablePath;const e=[t.physicalDatabase,t.physicalSchema,t.physicalTable].filter(r=>!!r?.trim());if(e.length>0)return e.join(".");if(t.sourceSql?.trim())return t.sourceSql;throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping ${t.id} has no physical source`)},xd=(t,e=[])=>{const r=fe(e);if(!t.schemaSid||!t.datasourceSid)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(t.enabled===!1)throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("dimensions"in t)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const n=[];for(const o of t.mappings){if(o.granularity!==void 0&&(o.mappingType!=="property"||!Un(o.granularity,r)))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires a property item and a supported physical granularity");if(o.mappingType==="property"){if(!o.sourceColumn||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:jd(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class ji{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${e.name}`,{rule:e.name});return this.#e.set(e.name,e),this}resolveProjection(e){return[...this.#e.values()].reduce((r,n)=>n.resolveProjection?.({...e,outputProperty:r})?.outputProperty??r,e.outputProperty)}resolveQuery(e){return[...this.#e.values()].reduce((r,n)=>n.resolveQuery?.({...e,...r?{query:r}:{}})??r,e.query)}rules(){return[...this.#e.values()]}}const xi=(t=[])=>new ji([...fe(t).flatMap(e=>e.plannerSemantics??[])]);ae.extend(Uo),ae.extend(qt),ae.extend(cr);const _t=["second","minute","hour","day","week","month","quarter","year"],Bd=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),Vd="YYYY-MM-DD HH:mm:ss",St=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Fd=(t,e)=>t==="week"?e==="week":e==="week"?_t.indexOf(t)<=_t.indexOf("day"):_t.indexOf(t)<=_t.indexOf(e),Bi=(t,e,r)=>{if(typeof t!="string")return"second";const n=ae(t,Vd,!0);if(!n.isValid())return"second";for(const o of[..._t].reverse()){const i=o==="week"?n.startOf("isoWeek"):n.startOf(o),s=o==="week"?n.endOf("isoWeek"):n.endOf(o),a=e==="lower"?r?i:s:r?s:i;if(n.isSame(a.millisecond(0),"second"))return o}return"second"},Vi=t=>{if(!t||typeof t!="object"||Array.isArray(t))return["second"];const e=Object.entries(t);return e.length===0?["second"]:e.flatMap(([r,n])=>Bd.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(Vi):["second"]:r==="$gte"||r==="$gt"?[Bi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[Bi(n,"upper",r==="$lte")]:["second"])},Yd=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&_t.includes(n))return n}return e.granularity??"day"}},vd=(t,e,r,n,o=fe(),i=De(o))=>{const s=r.mappings??[],a=s.filter(g=>g.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(g=>!Un(g.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(g=>kn(g.granularity)&&!g.propertyTarget?.every(_=>St(e,_)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const g of a)for(const _ of o){const E=_.mappingGranularity;if(!E||!E.isGranularity(g.granularity))continue;const S=E.validateItem?.(g,u);if(S)return S}if(!(a.length>0))return;const l=g=>s.find(_=>_.mappingType==="property"&&_.propertyTarget?.some(E=>St(e,E)?.id===g.id)),f=(g,_,E="filterOrGroup")=>{const S=St(e,g);if(!S)return`property is not available: ${g}`;const w=l(S);if(!w&&!(E==="operand"&&s.some(A=>A.mappingType==="predItem"&&typeof A.predItem?.pred=="string"&&St(e,A.predItem.pred)?.id===S.id)))return`property is not available on grouped source: ${g}`;if(E==="filterOrGroup"&&S.primal_type==="number"&&S.type!=="category"&&S.type!=="ID")return`measure cannot be used as a grouped source dimension: ${g}`;if(S.primal_type==="date"&&(!w?.granularity||!kn(w.granularity)||!Fd(w.granularity,_??S.granularity??"day")))return`time dimension ${g} is too coarse for ${_}`};function m(g){if(g)for(const[_,E]of Object.entries(g)){if(E===void 0)continue;if(_==="$and"||_==="$or"){if(!Array.isArray(E))return"unsupported dimension query";for(const A of E){const R=m(A);if(R)return R}continue}if(_==="$expr"){if(typeof E!="object"||E===null||Array.isArray(E))return"unsupported expression query";const A=E.pred;if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const R=y(A);if(R)return R;continue}if(_.startsWith("$"))return"unsupported dimension query";const S=St(e,_);if(!S)return`dimension property is not available: ${_}`;const w=S.primal_type==="date"?Vi(E):[void 0];for(const A of w){const R=f(_,A);if(R)return R}}}function y(g){const _=m(g.query);if(_)return _;const E=Array.isArray(g.pred)?g.pred:g.pred===void 0?[]:[g.pred];for(const S of E){const w=typeof S=="string"?f(S,void 0,"operand"):y(S);if(w)return w}}const h=m(t.query);if(h)return h;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const g of t.preds){const _=y(g);if(_)return _;if(typeof g.pred!="string"||!g.operator||!i.get(g.operator).supportsGroupedSourceRollup)return`PredItem ${g.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const g of t.groupby??[]){if(typeof g.pred!="string")return"computed groupby is not covered by the grouped source";const _=St(e,g.pred);if(!_)return`groupby property is not available: ${g.pred}`;if(g.operator!==void 0&&!i.get(g.operator).supportsGroupedSourceGroupby&&!o.some(S=>S.mappingGranularity?.supportsGroupby?.(g)))return`computed groupby is not covered: ${g.pred}`;const E=f(g.pred,Yd(g,_,i));if(E)return E}for(const g of o){const _=g.mappingGranularity?.candidateReason?.(t,u);if(_)return _}};function Qt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Qt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Qt(e)):[]]}const qn=t=>t.id??t.source,_r=(t,e)=>{if(t===e)return!0;if(t instanceof Date||e instanceof Date)return t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,i)=>_r(o,e[i]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const r=Object.entries(t),n=e;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&_r(i,n[o]))},It=t=>{if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=It(o);if(!i)return;e.push(...i)}continue}if(r==="$expr"){if(typeof n!="object"||n===null||Array.isArray(n))return;const o=n.pred;if(typeof o!="object"||o===null||Array.isArray(o))return;const i=Qt(o);if(i.length===0)return;e.push(...i.map(s=>({property:s,condition:{$expr:n}})));continue}if(r.startsWith("$"))return;e.push({property:r,condition:n})}return e},jn=(t,e,r)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>jn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>Sr(r,s.property,o)&&_r(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},st=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Sr=(t,e,r)=>e===r||st(t,e)?.id===st(t,r)?.id&&st(t,e)!==void 0&&st(t,r)!==void 0,Ie=(t,e,r)=>Ir(t,e,r)?.column,Ir=(t,e,r)=>{const n=st(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Sr(e,s,r)));return o?.sourceColumn?{column:o.sourceColumn,...o.sourceRef?{sourceRef:o.sourceRef}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property")?void 0:{column:n.id}},xn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||Ie(t,e,r)!==void 0,Fi=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=It(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!xn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},Qd=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?st(r,e.pred):void 0,s=st(r,t.match.pred),a=typeof e.pred=="string"&&Sr(r,e.pred,t.match.pred)&&!!(i&&s);if(e.operator!==t.match.operator||!a||Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const u=It(t.match.query);return u!==void 0&&u.every(c=>o.some(p=>Sr(r,p.property,c.property)&&_r(p.condition,c.condition)))},Hd=(t,e,r,n,o,i=De(o))=>{const s=(r.mappings??[]).flatMap(g=>{if(g.mappingType!=="predItem"||!g.sourceColumn||!g.predItem||!g.predItem.operator||typeof g.predItem.pred!="string")return[];const _=g.predItem,E=_.operator,S=_.pred;return!E||typeof S!="string"?[]:[{match:{operator:E,pred:S,..._.schema?{schema:_.schema}:{},..._.query?{query:_.query}:{}},column:g.sourceColumn}]}),a=(r.mappings??[]).some(g=>g.mappingType==="property");if(s.length===0&&!a){const g={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const _ of o??[]){const E=_.schemaMapping?.candidateReason?.(t,g);if(E)return E}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=It(t.query);if(!u&&s.length>0)return"query contains $or or another unsupported logical expression";const c=te(t),p=[],l=[];for(const[g,_]of(t.preds??[]).entries()){const E=It(_.query);if(!E&&s.length>0)return`PredItem ${g} query contains an unsupported logical expression`;if(s.length>0){const w=[...u??[],...E??[]],A=s.filter(x=>Qd(x,_,e,_.schema??e.id,w));if(A.length===0)return`PredItem ${g} is not mapped`;if(A.length>1)return`PredItem ${g} matches multiple mapping rules`;const R=A[0],T=It(R.match.query)??[];l.push(...T);const P=c.preds?.[g];if(P){const x=jn(P.query,T,e);x?P.query=x:delete P.query}p.push({predIndex:g,column:R.column});continue}const S=Qt(_).find(w=>!xn(r,e,w));if(S)return`PredItem ${g} property is not available: ${S}`}const f=jn(c.query,l,e);f?c.query=f:delete c.query;const m=Fi(c.query,r,e);if(m)return m;for(const[g,_]of(c.preds??[]).entries()){const E=Fi(_.query,r,e);if(E)return`PredItem ${g} ${E}`}for(const g of c.groupby??[]){const E=Qt(g).find(S=>!xn(r,e,S));if(E)return`groupby property is not available: ${E}`}const y=vd(c,e,r,n,o,i);if(y)return y;const h={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const g of o??[]){const _=g.schemaMapping?.candidateReason?.(c,h);if(_)return _}return{mapping:r,logicform:c,predRewrites:p,priority:r.priority??0,specificity:p.length}},Gd=(t,e,r,n={})=>{const o=n.plugins?fe(n.plugins):r.plugins,i=n.operators??De(n.plugins),s=[],a=[];for(const l of r.list(e.id)){const f=Hd(t,e,l,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:qn(l),reason:f}):s.push(f)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:e.id,requiredDataLayer:"detail",rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(u.length>0?u:s).reduce((l,f)=>f.priority>l.priority||f.priority===l.priority&&f.specificity>l.specificity?f:l);for(const l of s){if(l===p)continue;let f;u.length>0&&l.mapping.connectionId!==n.preferredConnectionId?f=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?f=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?f=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:qn(l.mapping),reason:f})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:qn(p.mapping),rejectedMappings:a}}},Ht=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),Gt=(t,e)=>Ht(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Gt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Gt(r,e)),Yi=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Gt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Gt(r,e)),vi=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),Wd=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!Ht(m,e)&&Yi(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(vi).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const y=i();return s.push(typeof m=="string"?{pred:m,name:y}:{...te(m),name:y}),y},u=m=>{if(m.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const y=te(m);return Array.isArray(m.pred)?y.pred=m.pred.map(h=>typeof h=="string"||!Gt(h,e)||Ht(h,e)?a(h):u(h)):m.pred&&typeof m.pred=="object"&&(y.pred=Ht(m.pred,e)?a(m.pred):u(m.pred)),y},c=r.map(m=>{const y=m.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Ht(m,e)&&Yi(m,e)?{...u(m),name:y}:(s.push({...te(m),name:y}),{pred:y,name:y})}),p=te(t);p.preds=s,delete p.having,delete p.sort,delete p.limit,delete p.limitBy,delete p.page,delete p.output,delete p.representation;const l=(t.groupby??[]).map(m=>{const y=vi(m);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),f=te(t);return f.from=p,f.preds=[...l,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},zd=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Qi=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:zd(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Hi=(t,e)=>({...Qi(t,e),id:e.id,name:e.name,type:e.type}),Bn=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},br=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?br(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:br(e)):[]],Vn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Vn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Vn(r,e))}:{}}),Gi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Gi(o,e))];if(r==="$expr"&&typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=n.pred;if(typeof o=="object"&&o!==null&&!Array.isArray(o))return[r,{...n,pred:Vn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Fn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Se(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Wi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Wi(i,e))];if(r==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const o=e.find(({name:i})=>i===r)?.comparable;return o&&Fn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),Kd=(t,e,r)=>{if(!e.udf)return{};const o=e.udf.sql.includes("$TS")?t.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:e.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},zi=t=>t.sql?{kind:"property-sql",schemaId:t.schemaId,property:t.property,propertyId:t.column,sql:t.sql,qualifier:t.qualifier,...t.timestampColumn?{timestampColumn:t.timestampColumn}:{},...t.timestampQualifier?{timestampQualifier:t.timestampQualifier}:{}}:{kind:"column",...t},Ki=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...r}),bt=(t,e,r,n,o,i,s,a,u="projection")=>{const c=Bn(t);if(u==="groupby"&&t.query)throw new d("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new d("PRED_PROPERTY_REQUIRED","A projection must reference a property");const w=r(t.pred);return{expression:zi(w.field),outputProperty:Ki(w.reference,w.property),sourceProperty:w.property,sourceField:w.field}}const p=e.get(t.operator);if(u==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(u==="groupby"&&!p.toSQL)throw new d("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(p.planInput&&typeof t.pred!="string")throw new d("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const l=p.planInput&&typeof t.pred=="string"?p.planInput({executionContext:e.executionContext,reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=l?.reference??t.pred,m=l?.args??t.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?bt(f,e,r,n,o,i,s,a,u):typeof f=="string"?bt({pred:f,name:f},e,r,n,o,i,s,a,u):void 0,h=Array.isArray(f)?f.map(w=>bt(typeof w=="string"?{pred:w,name:w}:w,e,r,n,o,i,s,a,u)):[];if(p.requiresProperty!==!1&&!y&&h.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const g=c,_=p.getOutputProperty?.({executionContext:e.executionContext,name:g,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:g}}:{},...h.length>0?{inputProperties:h.map(({outputProperty:w})=>w)}:{},args:m}),E=_?.description??p.description??y?.outputProperty.description,S={..._??(y?Ki(g,y.outputProperty,{isArray:!1}):{name:g,type:"number",primal_type:"number",isArray:!1}),...E!==void 0?{description:E}:{}};if(p.planExpression){const w=p.planExpression({executionContext:e.executionContext,pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:h.map(({expression:A})=>A),args:m,resolveKey:o,getOperator:A=>e.get(A),planQuery:i});if(w)return{expression:w,outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(p.kind==="window"){if(!y||h.length>0||t.query)throw new d("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const w=t.args?.direction??"desc";if(w!=="asc"&&w!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const A=t.args?.partitionBy??[];if(!Array.isArray(A)||A.some(R=>typeof R!="string"))throw new d("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:p.windowFunction,input:y.expression,partitionBy:A.map(R=>n(String(R))),direction:w==="asc"?"ASC":"DESC"},outputProperty:S}}return{expression:{kind:"operator",operator:t.operator,args:m,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...h.length>0?{inputs:h.map(({expression:w})=>w)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},Jd=(t,e,r,n,o,i,s,a,u,c,p,l=t)=>{const f=Bn(t),m=typeof t.pred=="string"?t.pred:void 0,y=!c||!m?r:E=>{const S=r(E);return E===m?{...S,field:{...S.field,column:c}}:S},h=p?{...t,operator:p}:t,g=bt(h,e,y,n,o,i,s,a),_=u?.resolveProjection({pred:l,schema:s,executionContext:e.executionContext,...g.sourceProperty?{sourceProperty:g.sourceProperty}:{},outputProperty:{...g.outputProperty,name:f},...l.operator?{operator:e.get(l.operator)}:{}})??{...g.outputProperty,name:f};return{name:f,expression:g.expression,outputProperty:_}},Xd=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new d("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new d("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},Yn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},Zd=(t,e,r,n,o,i)=>{if(e.length<2)throw new d("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(h=>Pe(h,Yn(h,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:h})=>h)??[];for(const h of s){const g=h.groupBy.map(({name:_})=>_);if(g.length!==a.length||g.some((_,E)=>_!==a[E]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:g});if(h.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new d("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],p=new Map;s.forEach((h,g)=>{h.projections.forEach((_,E)=>{const S=a.includes(_.name),w=p.get(_.name);if(w!==void 0&&!S)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${_.name}`,{name:_.name,childIndexes:[w,g]});if(w!==void 0)return;p.set(_.name,g),u.push({name:_.name,expression:{kind:"column",property:_.name,column:_.name}});const A=h.columnProperties?.[E];A&&c.push(A)})});const l=new Set(u.map(({name:h})=>h)),f=Object.entries(t.sort??{}).map(([h,g])=>{if(!l.has(h))throw new d("INVALID_SORT",`Sort field is not an output: ${h}`);const _=c.find(E=>E.name===h);return{name:h,direction:g===1?"ASC":"DESC",..._?.comparable?{comparable:_.comparable}:{},..._?.comparable?{expression:{kind:"column",property:h,column:h}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const h=a.at(-1)??"",g=c.find(_=>_.name===h);return[{name:h,direction:"ASC",...g?.comparable?{comparable:g.comparable}:{}}]})()},y=t.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:t.limitBy}:t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit};return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(u.map(({name:h})=>[h,h])),projections:u,columnProperties:c,groupBy:u.filter(({name:h})=>a.includes(h)),...t.having?{having:Wi(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},Pe=(t,e,r=De(),n=new Mn,o={})=>{const i=[...new Set((t.preds??[]).map($=>$.schema).filter($=>!!($&&$!==e.id)))];if(i.length>0){const $=t.propertyResolve??{},I=[e.id,...i].map(b=>{const{having:N,sort:L,limit:V,limitBy:M,page:ne,...C}=t,ee=H=>{let q=H;try{q=ce(e,H,o.resolveSchema).canonicalName}catch{}return $[b]?.[H]??$[b]?.[q]??H};return{...C,schema:b,preds:(t.preds??[]).filter(H=>(H.schema??e.id)===b).map(({schema:H,...q})=>q),...b===e.id||!t.query?{}:{query:Gi(t.query,ee)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(H=>({...H,...typeof H.pred=="string"?{pred:ee(H.pred)}:{}}))}:{}}});return Zd(t,I,e,r,n,o)}const s=Wd(t,r);if(s)return Pe(s,e,r,n,o);for(const $ of t.preds??[]){if(!$.operator)continue;const I=r.get($.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:b=>r.get(b)});if(I)return Pe(I,e,r,n,o)}const a=o.semanticRegistry??xi(o.plugins);if(t.from){const $=Yn(t.from,e,o),I=Pe(t.from,$,r,n,o),b=Hi(I,e),N={...t};delete N.from,N.schema??=b.id;const L=Pe(N,b,r,n,o),V=new Set(L.projections.map(({name:q})=>q)),M=I.rowIdentity.kind==="group"&&I.rowIdentity.names.every(q=>V.has(q))||I.rowIdentity.kind==="singleton"?I.rowIdentity:{kind:"generated"},ne=I.groupBy.map(({name:q})=>q).filter(q=>V.has(q)),C=ne.at(-1),ee=I.columnProperties?.find(q=>q.name===C),H=t.limitBy!==void 0&&ne.length>0?{count:t.limitBy,partitionBy:ne.slice(0,-1),orderBy:L.orderBy.length>0?L.orderBy:ne.slice(-1).map(q=>({name:q,direction:"ASC",...ee?.comparable?{comparable:ee.comparable}:{}}))}:void 0;return{...L,source:I.source,sourcePlan:I,sourceLogicform:t.from,rowIdentity:M,...H?{groupLimit:H}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const u=Gd(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const c=new Map(u.predRewrites.map(({predIndex:$,column:I})=>[$,I])),p=hi(e,o.plugins),l=Kc(t,e,o.plugins),f=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),m=l?.rewriteQuery?l.rewriteQuery(f):f,y=e.id,h=new Map,g=new Map,_=new Map,E=new Map,S=$=>{const I=g.get($);if(I)return I.alias;const b=u.mapping.enrichments?.find(V=>V.id===$);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${$}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:$});const N=`__enrichment_${$}`,L=b.temporal?(()=>{if(!p)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${$} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:$});const V=Ir(u.mapping,e,p.start.name),M=Ir(u.mapping,e,p.end.name);if(!V||!M)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${$} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:$});if(V.sourceRef||M.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${$} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:$});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:V.column,endColumn:M.column}})():void 0;return g.set($,{kind:"enrichment-left",id:$,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:N,baseAlias:y,keys:b.on,...L?{temporalCondition:L}:{}}),N},w=$=>{const I=ce(e,$,o.resolveSchema);let b=y,N=u.mapping;const L=[];for(const C of I.relations){L.push(C.property.name);const ee=L.join("_"),H=ee,q=n.get(C.targetSchema.id,u.mapping.connectionId);if(N=q,!h.has(ee)){const me=C.targetSchema.properties.filter(({type:G})=>G==="ID"),[ie]=me;if(me.length!==1||!ie)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${C.targetSchema.id} must contain exactly one ID property`,{schemaId:C.targetSchema.id,count:me.length});const Ae=C.sourceSchema.id===e.id?u.mapping:n.get(C.sourceSchema.id,u.mapping.connectionId),Te=Ie(Ae,C.sourceSchema,C.property.name)??C.property.id,et=Ie(q,C.targetSchema,ie.name)??ie.id,tt=C.sourceSchema.properties.find(({type:G})=>G==="timestamp"),We=C.targetSchema.properties.find(({type:G})=>G==="timestamp"),he=zc(C.sourceSchema,C.targetSchema,o.plugins),Be=tt?Ie(Ae,C.sourceSchema,tt.name)??tt.id:void 0,Jr=We?Ie(q,C.targetSchema,We.name)??We.id:void 0,O=he?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Ie(Ae,C.sourceSchema,he.sourceTimestamp.name)??he.sourceTimestamp.id,targetColumn:Ie(q,C.targetSchema,he.targetTimestamp.name)??he.targetTimestamp.id,sourceGranularity:he.sourceTimestamp.granularity??"day",targetGranularity:he.targetTimestamp.granularity??"day"}:he?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:Ie(Ae,C.sourceSchema,he.point.name)??he.point.id,intervalSide:"target",startColumn:Ie(q,C.targetSchema,he.start.name)??he.start.id,endColumn:Ie(q,C.targetSchema,he.end.name)??he.end.id}:void 0,j=C.property.isArray?ee:void 0;j&&!_.has(j)&&_.set(j,{path:j,sourceAlias:b,sourceColumn:Te,...C.property.udf?{sourceSql:C.property.udf.sql,...Be?{sourceTimestampColumn:Be}:{}}:{},alias:`__array_${ee}`}),h.set(ee,{kind:"left",path:ee,sourceAlias:b,sourceColumn:Te,...C.property.udf?{sourceSql:C.property.udf.sql,...Be?{sourceTimestampColumn:Be}:{}}:{},targetSchemaId:C.targetSchema.id,targetConnectionId:q.connectionId,targetSource:q.source,...q.sourceSql?{targetSourceSql:q.sourceSql}:{},targetAlias:H,targetColumn:et,...j?{sourceArrayExpansionPath:j}:{},...ie.udf?{targetSql:ie.udf.sql,...Jr?{targetTimestampColumn:Jr}:{}}:{},...O?{temporalCondition:O}:{}})}b=H}const V=Ir(N,I.schema,I.property.name);if(I.relations.length>0&&V?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${I.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:I.schema.id,property:I.property.name});const M=V?.sourceRef?S(V.sourceRef):b,ne={schemaId:I.schema.id,property:I.property.name,propertyId:I.property.id,column:V?.column??I.property.id,qualifier:M,...I.property.isArray?{isArray:!0}:{},...I.property.comparable?{comparable:I.property.comparable}:{},...Kd(I.relations.length>0?e:I.schema,I.property,y)};return E.set(I.canonicalName,ne),{reference:I.canonicalName,schema:I.schema,property:I.property,field:ne}},A=$=>{if($)for(const[I,b]of Object.entries($))if((I==="$and"||I==="$or")&&Array.isArray(b))for(const N of b)typeof N=="object"&&N!==null&&!Array.isArray(N)&&A(N);else if(I==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const N=b.pred;typeof N=="object"&&N!==null&&!Array.isArray(N)&&br(N).forEach(w)}else I.startsWith("$")||w(I)},R=$=>{if(Se($)){const I=Yn($,e,o),b=Pe($,I,r,n,o);if(b.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${b.projections.length}`,{schemaId:$.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray($)?$.map(R):typeof $!="object"||$===null||$ instanceof Date?$:Object.fromEntries(Object.entries($).map(([I,b])=>[I,R(b)]))},T=$=>Object.fromEntries(Object.entries($).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(L=>T(L))];if(I==="$expr"){if(typeof b!="object"||b===null||Array.isArray(b))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const L=b;if(typeof L.pred!="object"||L.pred===null||Array.isArray(L.pred)||!Object.prototype.hasOwnProperty.call(L,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const V=L.pred,M=bt(V,r,w,K,B,T,e,o.resolveSchema,"groupby");if(M.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const ne=R(L.condition);return M.outputProperty.comparable&&Fn(ne,V.name??V.operator??"$expr",M.outputProperty.comparable.values),[I,{kind:"expression-query",expression:M.expression,condition:M.outputProperty.comparable?{kind:"ordinal-query",comparable:M.outputProperty.comparable,condition:ne}:ne,properties:br(V)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const V=Object.entries(b).find(([M])=>wt(M,o.plugins));if(V){const[M,ne]=V,C=wt(M,o.plugins);if(!C)throw new Error(`Query Operator disappeared: ${M}`);const ee=w(I),H=C.plan(ne,{schema:ee.schema,property:ee.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(q,me)=>n.get(q,me)});return[I,{[M]:{kind:"query-operator",operator:M,value:H.value,definition:C,...H.sources?{sources:H.sources}:{}}}]}}const N=I.startsWith("$")?void 0:w(I).property.comparable;return[I,N?{kind:"ordinal-query",comparable:N,condition:R(b)}:R(b)]})),P=$=>{const I=N=>{if(!N||typeof N!="object")return!1;if(Array.isArray(N))return N.some(I);const L=N;return Object.prototype.hasOwnProperty.call(L,"$and")||Object.values(L).some(I)};if(I($))return $;const b=new Set(Object.keys($).flatMap(N=>{if(N.startsWith("$"))return[];const L=ce(e,N,o.resolveSchema);return L.relations.length===1&&L.property.type==="ID"?[L.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries($).map(([N,L])=>{if(N==="$and"||N==="$or")return Array.isArray(L)?[N,L.map(ie=>typeof ie=="object"&&ie!==null&&!Array.isArray(ie)?P(ie):ie)]:[N,L];if(N.startsWith("$"))return[N,L];const V=ce(e,N,o.resolveSchema);if(V.relations.length===0)return[N,L];if(V.property.udf?.sql.includes("$TS")===!0||V.relations.some(({property:ie})=>ie.udf?.sql.includes("$TS")===!0))return[N,L];const ne=V.relations.map(({property:ie})=>ie.name).join("_");if(h.has(ne))return[N,L];const[C]=V.relations;if(!C)return[N,L];if(b.has(C.property.name))return[N,L];const ee=C.property.name,H=V.canonicalName.slice(ee.length+1),q=C.targetSchema.properties.find(({type:ie})=>ie==="ID");if(!q)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${C.targetSchema.id} must contain an ID property`,{schemaId:C.targetSchema.id});if(V.relations.length===1&&V.property.id===q.id)return[C.property.id,L];const me={version:t.version,schema:C.targetSchema.id,query:H?{[H]:L}:{},preds:[{pred:q.name,name:q.name}]};return[C.property.id,{$in:me}]}))},x=(t.groupby??[]).map($=>{const I=Bn($);$.operator&&r.get($.operator).validateGroupby?.({pred:$,executionContext:r.executionContext});const b=bt($,r,w,K,B,T,e,o.resolveSchema,"groupby");let N=b.expression;if(l?.group===$&&(N={kind:"column",schemaId:e.id,property:l.property.name,propertyId:l.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const L=`groupby:${I}`;_.set(L,{path:L,sourceAlias:b.sourceField.qualifier,sourceColumn:b.sourceField.column,...b.sourceField.sql?{sourceSql:b.sourceField.sql,...b.sourceField.timestampColumn?{sourceTimestampColumn:b.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${_.size}`}),N={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:L}}return{name:I,expression:N,outputProperty:{...b.outputProperty,name:I,isArray:!1}}});function K($){const I=(t.groupby??[]).findIndex(N=>typeof N.pred=="string"&&N.pred===$||N.name===$),b=I>=0?x[I]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${$}`);return b.expression}function B($){const I=(t.groupby??[]).findIndex(N=>typeof N.pred=="string"&&N.pred===$||N.name===$),b=I>=0?x[I]:void 0;return b?b.expression:zi(w($).field)}const Q=$=>{$.operator&&r.get($.operator).validatePlan?.({executionContext:r.executionContext,pred:$,groupByNames:x.map(({name:I})=>I),resolveGroupName:I=>{const b=(t.groupby??[]).findIndex(N=>N.name===I||typeof N.pred=="string"&&N.pred===I);return b>=0?x[b]?.name:void 0},getOperator:I=>r.get(I)}),$.pred&&typeof $.pred=="object"&&!Array.isArray($.pred)&&Q($.pred);for(const I of Array.isArray($.pred)?$.pred:[])Q(typeof I=="string"?{pred:I}:I)};for(const $ of t.preds??[])Q($);const U=[...x,...(t.preds??[]).map(($,I)=>{const b=l?.rewritePred?.($)??$;return Jd(b,r,w,K,B,T,e,o.resolveSchema,a,c.get(I),ni(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,$)})],z=$=>Object.fromEntries(Object.entries($).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(L=>z(L))];if(I==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const N=U.find(({name:L})=>L===I)?.outputProperty.comparable;return N&&Fn(b,I,N.values),[I,N?{kind:"ordinal-query",comparable:N,condition:R(b)}:R(b)]})),ue=m?P(m):void 0;A(ue);const J=$=>{A($.query),$.pred&&typeof $.pred=="object"&&!Array.isArray($.pred)&&J($.pred);for(const I of Array.isArray($.pred)?$.pred:[])J(typeof I=="string"?{pred:I}:I)};for(const $ of t.preds??[])J($);if(U.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");Xd(U);const le=new Set(U.map(({name:$})=>$)),Oe=x.length>0?{kind:"group",names:x.map(({name:$})=>$),separator:"_",nullLabel:"\u7A7A\u503C"}:U.every(({expression:$})=>$.kind==="column"||$.kind==="property-sql")||U.some(({expression:$})=>$.kind==="property-sql"&&e.properties.some(({id:I,type:b})=>b==="ID"&&I===$.propertyId))?(()=>{const $=e.properties.find(({type:I})=>I==="ID");return $&&(o.canUsePropertyRowIdentity?.(e,$)??!0)?{kind:"property",column:$.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},ke=Object.entries(t.sort??{}).map(([$,I])=>{if(!le.has($))throw new d("INVALID_SORT",`Sort field is not an output: ${$}`);const b=U.find(N=>N.name===$);return{name:$,direction:I===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),D=t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit},k=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:x.slice(0,-1).map(({name:$})=>$),orderBy:ke.length>0?ke:(()=>{const $=x.at(-1);return[{name:$?.name??"",direction:"ASC",...$?.outputProperty.comparable?{comparable:$.outputProperty.comparable,expression:$.expression}:{}}]})()},Y=E.size===0&&h.size===0&&g.size===0&&_.size===0&&!ue&&x.length===0&&U.length>0&&U.every(({expression:$})=>$.kind==="operator"&&$.operator==="$constant");return{schemaId:e.id,source:Y?"":u.mapping.source,...Y?{}:{connectionId:u.mapping.connectionId},...!Y&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:y,fields:{...pc(e),...Object.fromEntries(e.properties.flatMap($=>{const I=Ie(u.mapping,e,$.name);return I?[[$.name,I],[$.id,I]]:[]}))},fieldReferences:Object.fromEntries(E),joins:[...h.values()],enrichmentJoins:[...g.values()],arrayExpansions:[..._.values()],...l?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:l.periods,match:l.source.kind==="interval"?{kind:"interval",startColumn:Ie(u.mapping,e,l.source.start.name)??l.source.start.id,endColumn:Ie(u.mapping,e,l.source.end.name)??l.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Ie(u.mapping,e,l.source.timestamp.name)??l.source.timestamp.id}}}:{},projections:U.map(({name:$,expression:I})=>({name:$,expression:I})),columnProperties:U.map(({outputProperty:$})=>$),groupBy:x.map(({name:$,expression:I})=>({name:$,expression:I})),...ue?{query:T(ue)}:{},...t.having?{having:z(t.having)}:{},orderBy:ke,rowIdentity:Y?{kind:"singleton"}:Oe,...D?{pagination:D}:{},...k?{groupLimit:k}:{}}};class el{provider;parameterOffset;values=[];constructor(e,r=0){this.provider=e,this.parameterOffset=r}add(e){const r=this.parameterOffset+this.values.length;return this.values.push(e),this.provider.parameter(r,e)}get nextParameterOffset(){return this.parameterOffset+this.values.length}append(e){this.values.push(...e)}}const tl=(t,e)=>{const r=e.split(".");if(r.some(n=>n.length===0))throw new d("INVALID_SOURCE",`Invalid physical source: ${e}`);return r.map(n=>t.quoteIdentifier(n)).join(".")},Rr=(t,e,r)=>r===void 0?tl(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Wt=(t,e,r,n,o)=>{const i=Ri(t,[],String,`Property ${e} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:e});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},qe=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"array-element":if(!a)throw new d("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return Wt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(be(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>qe(f,e,r,n,o,i,s,a)).join(", ")} `:"",p=qe(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(be(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const c=qe(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>qe(f,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(f=>`${qe(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${p}ORDER BY ${l} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${qe(t.input,e,r,n,o,i,s,a)} = ${i(p)} THEN ${t.comparable.direction*l}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${qe(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(c.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(c.toSQL&&(t.input&&be(t.input,r)||t.inputs?.some(f=>be(f,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?qe(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const l=t.inputs?.map(f=>qe(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new d("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new d("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");p=`CASE WHEN ${o(t.query)} THEN ${p??"1"} END`}if(c.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return c.toSQL?c.toSQL({executionContext:r.executionContext,sql:{aggregateFunction:e.aggregateFunction.bind(e),quoteIdentifier:e.quoteIdentifier.bind(e),concat:e.concat.bind(e),substring:e.substring.bind(e),stringLength:e.stringLength.bind(e),datePart:e.datePart.bind(e),dateBucket:e.dateBucket.bind(e),dateShift:e.dateShift.bind(e),...e.datePeriodBoundary?{datePeriodBoundary:e.datePeriodBoundary.bind(e)}:{},...e.scalarExtremum?{scalarExtremum:e.scalarExtremum.bind(e)}:{},value:(f,m)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&e.castValue?e.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},be=(t,e)=>t.kind==="window"?be(t.input,e)||t.partitionBy.some(r=>be(r,e)):t.kind==="cumulative"?be(t.input,e)||t.partitionBy.some(r=>be(r,e))||t.orderBy.some(r=>be(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?be(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?be(t.input,e):!1)||(t.inputs?.some(r=>be(r,e))??!1)),rl=(t,e)=>t.sourceSql?Wt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`,Ji=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),Xi={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},zt=(t,e,r,n,o,i,s,a)=>{if(Ci(r)){if(r.operator!==e)throw new d("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const l=r.definition??s(e);if(!l)throw new d("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return l.compile(r.value,{field:t,provider:o,bind:f=>n.add(f),renderSource:(f,m)=>Rr(o,f,m)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const p={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(p){const l=Et(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(Et(r))return`${t} ${l} (${i(r)})`;if(!Array.isArray(r))throw new d("INVALID_QUERY_VALUE",`${e} requires an array or query LogicForm`);if(r.length===0)return e==="$in"?"0 = 1":"1 = 1";const f=r.filter(Et);if(f.length>0){if(f.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${f.map(i).join(" UNION ALL ")})`}const m=r.map(y=>n.add(y)).join(", ");return`${t} ${l} (${m})`}if(Et(r))throw new d("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${e}`);if(e==="$exists")return`${t} IS ${r?"NOT ":""}NULL`;if(e==="$contains")return`${t} LIKE ${n.add(`%${String(r)}%`)}`;if(e==="$startsWith"){if(typeof r!="string")throw new d("INVALID_QUERY_VALUE","$startsWith requires a string");return`${t} LIKE ${n.add(`${r}%`)}`}if(e==="$regex"){if(typeof r!="string"||a!==void 0&&typeof a!="string")throw new d("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(t,n.add(r),a)}throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},vn=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Et(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>vn(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},at=(t,e,r,n,o,i)=>{if(kd(e)){const c=()=>`CASE ${e.comparable.values.map((m,y)=>`WHEN ${t} = ${r.add(m)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=f=>typeof f!="object"||f===null||Array.isArray(f)?at(t,f,r,n,o,i):Object.entries(f).filter(([m])=>m!=="args").map(([m,y])=>(m==="$and"||m==="$or")&&Array.isArray(y)?`(${y.map(l).join(m==="$and"?" AND ":" OR ")})`:p.has(m)?zt(c(),m,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):zt(t,m,y,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return zt(t,"$in",e,r,n,o,i);if(!Ji(e))return zt(t,"$eq",e,r,n,o,i);const s=[],a=e.args;if(a!==void 0){if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_QUERY_VALUE","Query args.options must be a string");const c=a.options;if(c!==void 0&&typeof c!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const u=a?.options;for(const[c,p]of Object.entries(e))if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const l=p.map(f=>at(t,f,r,n,o,i));s.push(`(${l.join(c==="$and"?" AND ":" OR ")})`)}else Xi[c]?(vn(p,c),s.push(at(n.datePart(t,Xi[c]),p,r,n,o,i))):c==="$length"?(vn(p,"$length"),s.push(at(n.stringLength(t),p,r,n,o,i))):c!=="args"&&s.push(zt(t,c,p,r,n,o,i,c==="$regex"?u:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Zi=(t,e,r,n)=>{if(!n.arrayContains)throw new d("ARRAY_CONDITION_UNSUPPORTED",`Provider ${n.kind} does not support array conditions`);const o=n.arrayContains.bind(n),i=a=>o(t,r.add(a));if(Array.isArray(e))return`(${e.map(i).join(" OR ")})`;if(!Ji(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(p=>Zi(t,p,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),p=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new d("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Rt=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,p]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const f=p.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${c} items must be query objects`);return Rt(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!Di(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(at(s(p.expression),p.condition,n,o,i,a));continue}const l=e(c);u.push(r(c)?Zi(l,p,n,o):at(l,p,n,o,i,a))}return u.join(" AND ")},Nr=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((l,f)=>`WHEN ${c} = ${r.add(l)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Qn=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},es=(t,e,r,n)=>e.concat(t.flatMap((o,i)=>[...i>0?[`'${r.replaceAll("'","''")}'`]:[],`CASE WHEN ${o} IS NULL THEN '${n.replaceAll("'","''")}' ELSE ${e.stringify(o)} END`])),ts=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:P})=>P)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),p=Qn("__sdb_row_number",i),l=Qn("__sdb_total_rows",i),f=n.quoteIdentifier(p),m=n.quoteIdentifier(l),y=Nr(e,n,o,u),h=y?`ORDER BY ${y}`:"",g=`CEIL(${m} * ${r.ratio})`,_=r.page-1,E=r.page,w=[...e.projections.map(({name:P})=>P),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(P=>`${c}.${n.quoteIdentifier(P)}`).join(", "),A=Nr(e,n,o,c),R=`SELECT ${u}.*, ROW_NUMBER() OVER (${h}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let T=`SELECT ${w} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${c}.${f} > ${_} * ${g} AND ${c}.${f} <= ${E} * ${g}`;return A&&(T+=` ORDER BY ${A}`),T},rs=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:E})=>E)),p=Qn("__sdb_limit_by_row_number",c),l=r.quoteIdentifier(p),f=o.partitionBy.map(E=>`${a}.${r.quoteIdentifier(E)}`).join(", "),m=o.orderBy.map(({name:E,direction:S,comparable:w})=>{const A=`${a}.${r.quoteIdentifier(E)}`;return`${w?`CASE ${w.values.map((T,P)=>`WHEN ${A} = ${n.add(T)} THEN ${w.direction*P}`).join(" ")} END`:A} ${S}`}).join(", "),h=[...e.projections.map(({name:E})=>E),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(E=>`${u}.${r.quoteIdentifier(E)}`).join(", "),g=`PARTITION BY ${f} ORDER BY ${m}`,_=`SELECT ${a}.*, ROW_NUMBER() OVER (${g}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${h} FROM ${r.tableAlias(`(${_})`,s)} WHERE ${u}.${l} <= ${o.count}`},ye=(t,e,r=De(),n=0)=>{const o=new el(e,n),i=A=>wt(A);if(t.subplans){const A=t.projections.map(({name:Q})=>Q),R=new Set(t.groupBy.map(({name:Q})=>Q)),T=t.subplans.map((Q,U)=>{const z=ye(Q,e,r,o.nextParameterOffset);o.append(z.parameters);const ue=`__composition_child_${U}`,J=e.quoteIdentifier(ue),le=new Set(Q.projections.map(({name:Oe})=>Oe));return{aliasName:ue,alias:J,available:le,sql:z.sql}}),P=T[0];if(!P)throw new d("INVALID_COMPOSITION","Composition has no children");const x=A.map(Q=>{const U=T.filter(J=>J.available.has(Q)),z=U[0]??P;return`${R.has(Q)&&U.length>1?`COALESCE(${U.map(J=>`${J.alias}.${e.quoteIdentifier(Q)}`).join(", ")})`:`${z.alias}.${e.quoteIdentifier(Q)}`} AS ${e.quoteIdentifier(Q)}`}),K=T.map(Q=>`${Q.alias} AS (${Q.sql})`);let B;if(t.rowIdentity.kind==="group"){const U=e.quoteIdentifier("__composition_keys"),z=e.quoteIdentifier("_id");K.push(`${U} AS (${T.map(ue=>`SELECT ${z} FROM ${ue.alias}`).join(" UNION ")})`),x.push(`${U}.${z} AS ${z}`),B=`WITH ${K.join(", ")} SELECT ${x.join(", ")} FROM ${U}`;for(const ue of T)B+=` LEFT JOIN ${ue.alias} ON ${U}.${z} = ${ue.alias}.${z}`}else{B=`WITH ${K.join(", ")} SELECT ${x.join(", ")} FROM ${P.alias}`;for(const Q of T.slice(1))B+=` LEFT JOIN ${Q.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const Q="__composition_having",U=e.quoteIdentifier(Q),z=new Set(A),ue=Rt(t.having,J=>{if(!z.has(J))throw new d("INVALID_HAVING",`Having field is not an output: ${J}`);return`${U}.${e.quoteIdentifier(J)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);B=`SELECT ${U}.* FROM ${e.tableAlias(`(${B})`,Q)} WHERE ${ue}`}if(t.groupLimit&&(B=rs(B,t,e,o)),t.pagination?.kind==="ratio")B=ts(B,t,t.pagination,e,o);else if(t.orderBy.length>0&&(B+=` ORDER BY ${Nr(t,e,o)}`),t.pagination?.kind==="rows"){const Q=(t.pagination.page-1)*t.pagination.pageSize;B=e.paginate(B,t.pagination.pageSize,Q)}return{sql:B,parameters:o.values}}const s=A=>{if(A.plan.projections.some(({expression:T})=>be(T,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=ye(A.plan.rowIdentity.kind==="property"||A.plan.rowIdentity.kind==="group"?{...A.plan,rowIdentity:{kind:"generated"}}:A.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(A=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(rl(A,e),A.alias,"value");return p.set(A.path,R.valueExpression),R}),f=A=>{const R=t.fieldReferences?.[A];if(R?.sql)return Wt(R.sql,R.property,e,R.timestampColumn,c?R.timestampQualifier??R.qualifier:void 0);if(R&&c)return`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;const T=t.fields[A];if(!T)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${A}`);return e.quoteIdentifier(T)},m=A=>qe(A,e,r,c,R=>Rt(R,f,T=>t.fieldReferences?.[T]?.isArray===!0,o,e,s,m,i),R=>o.add(R),(R,T)=>at(R,T,o,e,s,i),R=>{const T=p.get(R);if(!T)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return T}),y=t.projections.map(A=>`${m(A.expression)} AS ${e.quoteIdentifier(A.name)}`),h=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const A=t.rowIdentity.names.map(R=>{const T=t.groupBy.find(P=>P.name===R)??t.projections.find(P=>P.name===R);if(!T)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return m(T.expression)});return`${es(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,g=[...y,...h?[h]:[]].join(", "),_=t.sourcePlan?(()=>{const A=ye(t.sourcePlan,e,r,o.nextParameterOffset);return o.append(A.parameters),`(${A.sql})`})():t.source?Rr(e,t.source,t.sourceSql):"",E=c&&t.sourceAlias?e.tableAlias(_,t.sourceAlias):_;let S=`SELECT ${g}`;if(t.periodSource){const A=t.periodSource,R=A.periods.map(({label:U,asOf:z},ue)=>{const J=o.add(U),le=o.add(z);return ue===0?`SELECT ${J} AS ${e.quoteIdentifier(A.labelColumn)}, ${le} AS ${e.quoteIdentifier(A.asOfColumn)}`:`SELECT ${J}, ${le}`}).join(" UNION ALL "),T=e.tableAlias(`(${R})`,A.alias),P=e.tableAlias(_,A.sourceAlias),x=e.quoteIdentifier(A.alias),K=e.quoteIdentifier(A.sourceAlias),B=`${x}.${e.quoteIdentifier(A.asOfColumn)}`,Q=A.match.kind==="interval"?(()=>{const U=`${K}.${e.quoteIdentifier(A.match.startColumn)}`,z=`${K}.${e.quoteIdentifier(A.match.endColumn)}`;return`${U} <= ${B} AND (${z} > ${B} OR ${z} IS NULL)`})():(()=>{const U=e.tableAlias(_,A.match.lookupAlias),z=e.quoteIdentifier(A.match.lookupAlias),ue=`${K}.${e.quoteIdentifier(A.match.timestampColumn)}`,J=`${z}.${e.quoteIdentifier(A.match.timestampColumn)}`,le=`SELECT ${e.aggregateFunction("max",J)} FROM ${U} WHERE ${J} <= ${B}`;return`${ue} = (${le})`})();S+=` FROM ${T} LEFT JOIN ${P} ON ${Q}`,t.query&&Object.keys(t.query).length>0&&(S+=` AND ${Rt(t.query,f,U=>t.fieldReferences?.[U]?.isArray===!0,o,e,s,m,i)}`)}else E&&(S+=` FROM ${E}`);for(const A of l)S+=` ${A.joinSql}`;for(const A of t.enrichmentJoins??[]){const R=e.quoteIdentifier(A.alias),T=e.quoteIdentifier(A.baseAlias);S+=` LEFT JOIN ${e.tableAlias(Rr(e,A.source,A.sourceSql),A.alias)}`;const P=A.keys.map(({baseColumn:x,targetColumn:K})=>`${T}.${e.quoteIdentifier(x)} = ${R}.${e.quoteIdentifier(K)}`);if(A.temporalCondition?.kind==="point-in-interval"){const x=z=>z==="source"?T:R,K=`${x(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,B=x(A.temporalCondition.intervalSide),Q=`${B}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,U=`${B}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;P.push(`${Q} <= ${K}`),P.push(`(${U} > ${K} OR ${U} IS NULL)`)}S+=` ON ${P.join(" AND ")}`}for(const A of t.joins??[]){S+=` LEFT JOIN ${e.tableAlias(Rr(e,A.targetSource,A.targetSourceSql),A.targetAlias)}`;const R=A.sourceArrayExpansionPath?p.get(A.sourceArrayExpansionPath):A.sourceSql?Wt(A.sourceSql,A.sourceColumn,e,A.sourceTimestampColumn,A.sourceAlias):`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.sourceColumn)}`,T=A.targetSql?Wt(A.targetSql,A.targetColumn,e,A.targetTimestampColumn,A.targetAlias):`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${A.path}`);if(S+=` ON ${R} = ${T}`,A.temporalCondition?.kind==="date-bucket-equal"){const P=`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.temporalCondition.sourceColumn)}`,x=`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.temporalCondition.targetColumn)}`;S+=` AND ${e.dateBucket(P,A.temporalCondition.sourceGranularity)} = ${e.dateBucket(x,A.temporalCondition.targetGranularity)}`}else if(A.temporalCondition?.kind==="point-in-interval"){const P=U=>U==="source"?e.quoteIdentifier(A.sourceAlias):e.quoteIdentifier(A.targetAlias),x=`${P(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,K=P(A.temporalCondition.intervalSide),B=`${K}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,Q=`${K}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;S+=` AND ${B} <= ${x} AND (${Q} > ${x} OR ${Q} IS NULL)`}}const w=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&w.push(Rt(t.query,f,A=>t.fieldReferences?.[A]?.isArray===!0,o,e,s,m,i)),w.length>0&&(S+=` WHERE ${w.join(" AND ")}`),t.groupBy.length>0){const A=t.groupBy.map(T=>m(T.expression)),R=t.rowIdentity.kind==="group"?[es(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];S+=` GROUP BY ${[...A,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const A=R=>{const T=t.projections.find(P=>P.name===R);if(!T)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?m(T.expression):e.quoteIdentifier(R)};S+=` HAVING ${Rt(t.having,A,()=>!1,o,e,s,m,i)}`}if(t.groupLimit&&(S=rs(S,t,e,o)),t.pagination?.kind==="ratio")S=ts(S,t,t.pagination,e,o);else if(t.orderBy.length>0&&(S+=` ORDER BY ${Nr(t,e,o,void 0,m)}`),t.pagination?.kind==="rows"){const A=(t.pagination.page-1)*t.pagination.pageSize;S=e.paginate(S,t.pagination.pageSize,A)}return{sql:S,parameters:o.values}},nl=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(g=>t.startsWith(g,o));if(y){n.push(y),o+=y.length;continue}const h=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(h?.[0]){n.push(h[0]),o+=h[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${y.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},p=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},ol=t=>`__sdb_cte_${t}`,ns=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},il=(t,e)=>t?.find(r=>r.name===e),sl=(t,e,r)=>r===0?t:e.kind==="postgresql"?t.replace(/\$(\d+)/g,(n,o)=>`$${Number(o)+r}`):e.kind==="oracle"?t.replace(/:(\d+)/g,(n,o)=>`:${Number(o)+r}`):e.kind==="clickhouse"?t.replace(/\{p(\d+):([^}]+)\}/g,(n,o,i)=>`{p${Number(o)+r}:${i}}`):t,Hn=(t,e,r,n=De())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((E,S)=>{const w={...E.compiled,sql:sl(E.compiled.sql,r,o)};return o+=E.compiled.parameters.length,{...E,compiled:w,alias:`__sdb_exec_${S}`}}),s=i.map(({alias:E,compiled:S})=>`${r.quoteIdentifier(E)} AS (${S.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:E})=>E),p=e.orderBy??[],l=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(l){const E=S=>[...c.map(w=>`${S}.${r.quoteIdentifier(w)}`),`${S}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:S})=>`SELECT ${E(r.quoteIdentifier(S))} FROM ${r.quoteIdentifier(S)}`).join(" UNION ")})`)}const m=l?f:u,y=[...c,...t.flatMap(({outputs:E})=>E)],h=y.filter((E,S,w)=>w.indexOf(E)===S).map(E=>{if(c.includes(E))return`${m}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`;const S=i.find(({outputs:A})=>A.includes(E));if(!S)throw new Error(`CTE execution unit does not expose output projection: ${E}`);return`${r.quoteIdentifier(S.alias)}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`});l&&h.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let g=`SELECT ${h.join(", ")} FROM ${m}`;for(const E of l?i:i.slice(1)){const S=r.quoteIdentifier(E.alias);g+=` LEFT JOIN ${S}`,g+=l?` ON ${m}.${r.quoteIdentifier("_id")} = ${S}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const E={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:g,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(w=>[w,w])),projections:y.map(w=>({name:w,expression:{kind:"column",property:w,column:w}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:p.map(({name:w,direction:A,comparable:R})=>({name:w,direction:A,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},S=ye(E,r,n,o);return{sql:`WITH ${s.join(", ")} ${S.sql}`,parameters:[...i.flatMap(({compiled:w})=>w.parameters),...S.parameters]}}return{sql:`WITH ${s.join(", ")} ${g}`,parameters:i.flatMap(({compiled:E})=>E.parameters)}},Or=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const E of e){const S=ye(E.plan,o,i,a);a+=S.parameters.length,s.push({input:E,sql:S,alias:ol(E.name)})}const u=s.map(({sql:E,alias:S})=>`${o.quoteIdentifier(S)} AS (${E.sql})`).join(", "),c=s[0];if(!c)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(c.alias),l=r.groupBy.map(({name:E})=>E),f=l.map(E=>`${p}.${o.quoteIdentifier(E)} AS ${o.quoteIdentifier(E)}`);let m="";for(const E of s.slice(1)){const S=o.quoteIdentifier(E.alias),w=E.input.plan.groupBy.map(({name:T})=>T),R=(E.input.joinKeys??l.filter(T=>w.includes(T))).map(T=>{const P=il(E.input.groupKeyShifts,T),x=P?o.dateShift(`${S}.${o.quoteIdentifier(T)}`,P.granularity,P.offset):`${S}.${o.quoteIdentifier(T)}`;return`${p}.${o.quoteIdentifier(T)} = ${x}`});m+=` LEFT JOIN ${S} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:E,alias:S})=>[E.name,`${o.quoteIdentifier(S)}.${o.quoteIdentifier(ns(E.plan))}`])),h=nl(t.expression,y),g=[...f,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:E,alias:S})=>`${`${o.quoteIdentifier(S)}.${o.quoteIdentifier(ns(E.plan))}`} AS ${o.quoteIdentifier(E.name)}`),`${h} AS ${o.quoteIdentifier(n)}`].join(", ");let _=`WITH ${u} SELECT ${g} FROM ${p}`;return _+=m,{sql:_,parameters:s.flatMap(({sql:E})=>E.parameters)}},al=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=is(t).length*2+2;for(let n=0;n<r;n+=1){const o=cl(e);if(o===e)return e;e=o}return e}catch{return t}},cl=t=>{const e=is(t),r=ul(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ss(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?Il(t.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(h=>h.trim()==="*"))continue;const u=_l(dl(t.slice(i.fromStart,i.close),i,e)),c=ll(t,i),p=pl(t,i);if(p&&fl(c,p))continue;let l=s.filter(h=>{const g=as(h);if(!g||g==="_id")return!0;const _=new RegExp(`(^|[^\\w$])${Gn(g)}([^\\w$]|$)`,"i");return _.test(u)||_.test(c)}),f=!0;for(;f;){f=!1;const h=ds(l.join(" ")),g=s.filter(_=>{if(l.includes(_))return!1;const E=as(_);return E?new RegExp(`(^|[^\\w$])${Gn(E)}([^\\w$]|$)`,"i").test(h):!1});g.length>0&&(l=s.filter(_=>l.includes(_)||g.includes(_)),f=!0)}if(l.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),y=l.length===0&&Sl(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":l.map(h=>h.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},ul=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=os(t,"FROM",n);if(o===-1||!ss(t,n,o)?.every(El))return t;const s=e.find(f=>f.open>o&&t.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const u=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(u))return t;const c=wl.exec(u)?.[1],p=$l.exec(t.slice(s.close+1));if(!c||!p||cs(c)!==cs(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},dl=(t,e,r)=>ml(t,r.filter(n=>n.open>e.open&&n.close<e.close).map(n=>({start:n.open-e.fromStart,end:n.close-e.fromStart+1}))),ll=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return ds(r)},pl=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ve})(?=\\s|$)`,"i"))?.[1]??null,fl=(t,e)=>new RegExp(`(^|[^\\w$])${Gn(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),ml=(t,e)=>{if(!e.length)return t;const r=t.split("");for(const n of e)for(let o=Math.max(0,n.start);o<Math.min(r.length,n.end);o+=1)r[o]=" ";return r.join("")},os=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
2
- `&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},is=t=>{const e=[],r=[];let n="",o="";for(let i=0;i<t.length;i+=1){const s=t[i],a=t[i+1];if(o==="--"){s===`
3
- `&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),p=/^\s*SELECT\b/i.exec(c);if(!p)continue;const l=u.open+1+p.index,f=os(t,"FROM",l+6);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:l+6,fromStart:f})}return e},ss=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const p=n[c];if(u){p===u&&n[c-1]!=="\\"&&(u="");continue}if(p==="`"||p==='"'||p==="'"){u=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},as=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ve='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',yl=new RegExp(`\\s+AS\\s+${ve}\\s*$`,"i"),hl=new RegExp(`\\bAS\\s+${ve}`,"gi"),gl=new RegExp(`(?:${ve}\\s*\\.\\s*)+${ve}`,"g"),Al=new RegExp(`^${ve}(?:\\s*\\.\\s*${ve})*$`),wl=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s+WHERE\\b`,"i"),$l=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s*;?\\s*$`,"i"),cs=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),El=t=>{const e=t.replace(yl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},us=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),ds=t=>us(t,hl),_l=t=>us(t,gl),Sl=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),Il=t=>{const e=t.trim();return Al.test(e)?e:null},Gn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wn=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?Wn(t.input,e):!1)||(t.inputs?.some(n=>Wn(n,e))??!1)},ls=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?ls(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({executionContext:n.executionContext,input:s,args:t.args})):i},ct=async(t,e,r)=>{const n=e.filter(({expression:o})=>Wn(o,r));return n.length===0?[...t]:Promise.all(t.map(async o=>{const i={...o};for(const s of n)i[s.name]=await ls(s.expression,i,s.name,r);return i}))},Tr=t=>t==null?"\u7A7A\u503C":typeof t=="object"?"_id"in t?String(t._id):"id"in t?String(t.id):JSON.stringify(t):String(t),zn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:Tr(t[o])).join(r),Kn=(t,e)=>t.map(r=>{if(e.kind==="property"){const{[e.internalName]:n,...o}=r;return{...o,_id:String(n)}}return e.kind==="group"?{...r,_id:r._id===void 0?zn(r,e.names,e.separator,e.nullLabel):Tr(r._id)}:{...r,_id:e.kind==="singleton"?"0":en.randomUUID()}}),bl=t=>{const e=te(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Kt=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Kt(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Kt(r,e)),Pr=(t,e,r,n,o,i,s="zh-CN",a=fr.translator(s))=>{const u=t.preds??[],c=u.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({definition:m})=>m?.kind==="component"&&!m.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&Kt(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&Kt(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=u.filter((m,y)=>!c.some(h=>h.index===y));if(l.length>0){const m=bl(t);m.preds=l,p.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:y,definition:h}of c){const g=h?.createComponent;if(!g)continue;const _=e.projections[f+y]?.name;if(!_)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const E=i?.preds?.[y],S=g({executionContext:n.executionContext,logicform:t,pred:E??m,outputName:_,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:i}:{}});if("logicform"in S&&(S.logicform.preds??[]).some(w=>Kt(w,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in S?{...S,outputName:_}:S)}return p},je=t=>t instanceof Date?t.getTime():t,Rl=(t,e,r,n)=>{const o=je(t),i=je(r);switch(e){case"$eq":return o===i;case"$ne":return o!==i;case"$gt":return o!=null&&i!==void 0&&i!==null&&o>i;case"$gte":return o!=null&&i!==void 0&&i!==null&&o>=i;case"$lt":return o!=null&&i!==void 0&&i!==null&&o<i;case"$lte":return o!=null&&i!==void 0&&i!==null&&o<=i;case"$in":return Array.isArray(r)&&r.some(s=>je(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>je(s)!==o);case"$exists":return r?t!=null:t==null;case"$contains":return String(t).includes(String(r));case"$startsWith":return typeof t=="string"&&typeof r=="string"&&t.startsWith(r);case"$regex":return typeof r=="string"&&new RegExp(r,n).test(String(t));default:throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${e}`)}},Jn=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return je(t)===je(e);const r=Object.entries(e),n=e.args,o=n&&typeof n=="object"&&!Array.isArray(n)?n.options:void 0;return r.every(([i,s])=>{if(i==="args")return!0;if(i==="$and"||i==="$or"){if(!Array.isArray(s))return!1;const a=s.map(u=>Jn(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&Jn(t.length,s):Rl(t,i,s,typeof o=="string"?o:void 0)})},ps=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ps(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Jn(t[r],n)}),fs=(t,e)=>e.length===0?"0":t._id===void 0?zn(t,e):Tr(t._id),Xn=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=fs(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Zn=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=Xn(t,r);if(e.having&&(n=n.filter(o=>ps(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=fs(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const p=je(a[c.name]),l=je(u[c.name]);if(p!==l)return p==null?c.direction==="ASC"?-1:1:l==null?c.direction==="ASC"?1:-1:(p<l?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=je(o[s.name]),u=je(i[s.name]);if(a!==u)return a==null?s.direction==="ASC"?-1:1:u==null?s.direction==="ASC"?1:-1:(a<u?-1:1)*(s.direction==="ASC"?1:-1)}return 0}),e.pagination?.kind==="rows"){const o=(e.pagination.page-1)*e.pagination.pageSize;n=n.slice(o,o+e.pagination.pageSize)}else if(e.pagination?.kind==="ratio"){const o=Math.ceil(n.length*e.pagination.ratio),i=(e.pagination.page-1)*o;n=n.slice(i,i+o)}return n},ms=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n};class eo{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${e.name}`,{type:e.name});return this.#e.set(e.name,e),this}get(e){const r=this.#e.get(e);if(!r)throw new d("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${e}`,{type:e});return r}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}requiresPerPeriodEvaluation(e){return e.property?this.get(e.property.type).requiresPerPeriodEvaluation?.({...e,property:e.property})??!1:!1}}const Nl=t=>{const e=new Set,r=new Set;for(const n of t){if(!n.name)throw new d("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new d("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(e.has(n.name))throw new d("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new d("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});e.add(n.name),r.add(n.id)}},ys=t=>{Nl(t);const e=t.filter(({type:r})=>r==="timestamp");if(e.length>1)throw new d("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:e.map(({name:r})=>r)})},Ol=new Set(["second","minute","hour","day","week","month","quarter","year"]),Tl=(t,e)=>{if("_id"in t||"_sid"in t)throw new d("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${t.name} must use id instead of _id; _sid is not supported`,{property:t.name});if("sid"in t)throw new d("PROPERTY_SID_NOT_ALLOWED",`Property ${t.name} must not declare sid`,{property:t.name});const r=t;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new d("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${t.name} must use comparable instead of is_comparable/comparable_order`,{property:t.name});if(t.udf!==void 0){const a=t.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const u=a,c=Object.keys(u).filter(p=>p!=="sql");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:c});if(typeof u.sql!="string"||u.sql.trim().length===0)throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf.sql must be a non-empty string`,{property:t.name})}const n=e.get(t.type),o=t.primal_type==="object"?"entity":t.primal_type;if(o!==void 0&&o!==n.primalType)throw new d("PRIMAL_TYPE_MISMATCH",`Property ${t.name} declares primal_type ${t.primal_type}, but ${t.type} requires ${n.primalType}`,{property:t.name,type:t.type,declared:t.primal_type,expected:n.primalType});if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new d("INVALID_IS_ARRAY",`Property ${t.name} isArray must be a boolean`,{property:t.name,isArray:t.isArray});if("is_observation"in t)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${t.name} must use Schema temporalSemantics; is_observation is not supported`,{property:t.name});if(t.comparable!==void 0){const a=t.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction`);const u=a;if(Object.keys(u).some(c=>c!=="values"&&c!=="direction")||!Array.isArray(u.values)||u.values.length===0||u.values.some(c=>typeof c!="string")||new Set(u.values).size!==u.values.length||u.direction!==1&&u.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1`,{property:t.name,comparable:a});if(t.type!=="category"||t.isArray===!0)throw new d("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const i={...t,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new d("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new d("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(n.primalType==="date"||t.type==="duration"){if(i.granularity!==void 0&&!Ol.has(i.granularity))throw new d("INVALID_GRANULARITY",`Property ${i.name} has unsupported granularity: ${i.granularity}`,{property:i.name,granularity:i.granularity})}else if(i.granularity!==void 0)throw new d("GRANULARITY_NOT_ALLOWED",`Property ${i.name} cannot declare granularity unless its type supports it`,{property:i.name,type:i.type});return n.validateProperty?.(i),i},hs=(t,e,r=[])=>{const n=fe(r),o=n.reduce((m,y)=>y.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new d("INVALID_SCHEMA_ID","Schema id must not be empty");if(o.is_calendar!==void 0&&typeof o.is_calendar!="boolean")throw new d("INVALID_CALENDAR_SCHEMA_FLAG",`Schema ${o.id} is_calendar must be a boolean`,{schemaId:o.id,is_calendar:o.is_calendar});const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const y=Object.fromEntries(Object.entries(m).filter(([g])=>!s.has(g))),h=Tl(y,e);return i.reduce((g,_)=>({...g,..._.resolve(m,g,o)}),h)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];ys(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const p=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!p.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f};ae.extend(Uo),ae.extend(qt),ae.extend(cr);const Pl="YYYY-MM-DD HH:mm:ss",Ll=new Set(["YTD","QTD","MTD","WTD","DTD"]),gs=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Cl=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Lr=["second","minute","hour","day","week","month","quarter","year"],ut=t=>Object.prototype.toString.call(t)==="[object Object]",As=(t,e)=>{const r=n=>{if(typeof n!="number"||!Number.isSafeInteger(n))throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)};if(typeof t=="number"){r(t);return}if(Array.isArray(t)){t.forEach(r);return}if(ut(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!gs.has(o)))throw new d("INVALID_DATE_PART_QUERY",`${e} requires numeric comparison operators`);for(const[o,i]of n)if(o==="$and"||o==="$or"){if(!Array.isArray(i)||i.length===0)throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires a non-empty array`);i.forEach(s=>As(s,e))}else if(o==="$in"||o==="$nin"){if(!Array.isArray(i))throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires an array`);i.forEach(r)}else r(i);return}throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)},to=t=>!ut(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Lr.includes(t.granularity)&&typeof t.offset=="number"||Lr.some(e=>e in t),Nt=t=>ae(t).format(Pl),Dl=(t,e)=>Lr.find(r=>r in t||e!==void 0),kl=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),ws=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Dl(t,void 0)??"day";let i=ae(e).millisecond(0);for(const a of[...Lr].reverse()){const u=t[a];typeof u=="number"&&(i=kl(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:Nt(i.startOf(s)),$lte:Nt(i.endOf(s))}},Ul=(t,e)=>{const r=ae(e),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[t];return{$gte:Nt(o()),$lte:Nt(r.endOf("day"))}},ro=async(t,e)=>{const r=ae(String(t.$lte)),n=await e.requestTimeWatermark(r.toDate());if(!n)return t;const o=e.property.granularity??"day",i=o==="week"?"isoWeek":o,s=ae(n).endOf(i),a=ae(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:Nt(u)}},no=async(t,e)=>Se(t)?t:t instanceof Date||typeof t=="string"&&ae(t).isValid()?Nt(t):typeof t=="string"&&Ll.has(t)?ro(Ul(t,e.now),e):to(t)?ro(ws(t,e.now),e):t,$s=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Cr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>no(o,r)));const n=await no(e,r);return t==="$eq"&&ut(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?ut(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&ut(n)&&"$lte"in n?n.$lte:n},Cr=async(t,e)=>{if(Se(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Cr(o,e)));if(!ut(t))return no(t,e);if("$options"in t)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new d("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!to(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(to(t))return ro(ws(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await $s("$eq",r[0][1],e);if(ut(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Cl.has(o)&&As(i,o),n[o]=gs.has(o)?await $s(o,i,e):await Cr(i,e);return n},Ml=(t,e)=>e.property.primal_type==="date"?Cr(t,e):t,oo=(t=[])=>new eo([...Dn,...fe(t).flatMap(({semanticTypes:e})=>e??[])]),Es=(t,e)=>{const r=new eo(t.definitions());for(const n of fe(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},ql=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,jl=t=>{if(typeof t!="string")return!1;const e=ql.exec(t);if(!e)return!1;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);return r!==2?r>2:n>0||o>0?!0:e[4]===void 0},io=t=>{if(!jl(t.version))throw new d("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(t.version)}`,{minimumVersion:"2.0",receivedVersion:t.version})},_s=(t,e)=>Object.entries(t).some(([r,n])=>e.has(r)?!0:r!=="$and"&&r!=="$or"||!Array.isArray(n)?!1:n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&_s(o,e))),Ss=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!hn(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=gn(r,n);return t&&_s(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Ot=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),xl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Is={$second:{zh:"\u79D2",en:"second"},$minute:{zh:"\u5206\u949F",en:"minute"},$hour:{zh:"\u5C0F\u65F6",en:"hour"},$weekday:{zh:"\u661F\u671F",en:"weekday"},$day:{zh:"\u65E5",en:"day of month"},$week:{zh:"\u5468",en:"week"},$month:{zh:"\u6708",en:"month"},$quarter:{zh:"\u5B63\u5EA6",en:"quarter"},$year:{zh:"\u5E74",en:"year"}},Tt=(t,e)=>{if(t===null)return e?"null":"\u7A7A\u503C";if(typeof t=="string"||typeof t=="number")return String(t);if(typeof t=="boolean")return e?String(t):t?"\u662F":"\u5426";if(Array.isArray(t))return t.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(!Ot(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Tt(t.root,e);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>t[n]!==void 0).map(n=>e?`${n} ${String(t[n])}`:`${String(t[n])}${xl[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Dr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),bs=(t,e,r,n)=>{const s=(n?{$eq:"is",$ne:"is not",$gt:"is greater than",$gte:"is at least",$lt:"is less than",$lte:"is at most",$in:"is one of",$nin:"is none of",$contains:"contains",$startsWith:"starts with",$regex:"matches",$recursive:"is"}:{$eq:"\u4E3A",$ne:"\u4E0D\u4E3A",$gt:"\u5927\u4E8E",$gte:"\u5927\u4E8E\u7B49\u4E8E",$lt:"\u5C0F\u4E8E",$lte:"\u5C0F\u4E8E\u7B49\u4E8E",$in:"\u4E3A",$nin:"\u4E0D\u4E3A",$contains:"\u5305\u542B",$startsWith:"\u4EE5",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[t];if(!s)return;const a=t==="$startsWith"?n?"":"\u5F00\u5934":t==="$in"?n?"":"\u4E4B\u4E00":t==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":t==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${e} ${s} ${r}${a}`:`${e}${s}${r}${a}`},Jt=(t,e,r)=>{if(!Ot(e)||Object.keys(e).every(o=>!o.startsWith("$")))return bs("$eq",t,Tt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Dr(i.map(s=>Jt(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Is[o]){const s=Is[o];n.push(Jt(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Jt(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Ot(i)?Tt(i.pattern,r):Tt(i,r),a=bs(o,t,s,r);a&&n.push(a)}return Dr(n,"$and",r)},Rs=(t,e="zh-CN")=>{const r=e.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Dr(i.map(s=>Ot(s)?Rs(s,e):""),o,r));else if(o==="$expr"&&Ot(i)){const s=i.pred,a=Ot(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(Jt(a,i.condition,r))}else i!==void 0&&n.push(Jt(o,i,r));return Dr(n,"$and",r)},Pt=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??fr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:Pt(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Pt(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const m=e.get(t.operator),y={executionContext:e.executionContext,operandName:c,...u?{inputName:u}:{},inputNames:a,args:p,locale:n,t:s},h=m.defaultName(y);if(typeof h!="string"||h.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const g=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),_=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return h;const E=typeof m.defaultNameKey=="function"?m.defaultNameKey(y):m.defaultNameKey??`operator.${t.operator}`;return s(E,h,{...p,operandName:c,inputName:u??"",inputNames:a.join(_),input0:a[0]??"",input1:a[1]??"",granularity:g})})():c;if(typeof l!="string"||l.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return l;const f=Rs(t.query,n);return f?i?`${l} where ${f}`:`${f}\u7684${l}`:l},Bl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Vl=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},Fl=async(t,e,r)=>{if(t.operator!=="$case"||t.args?.mode!=="auto"||t.args.min!==void 0||t.args.max!==void 0||t.args.empty===!0)return t;if(typeof t.pred!="string")throw new d("AUTO_CASE_PROPERTY_REQUIRED","$case auto mode requires a direct property pred when bounds are not explicit");if(!r.requestAutoCaseBounds)return t;const n=await r.requestAutoCaseBounds(e,t.pred,r.autoCaseQuery);return{...t,args:{...t.args,...n}}},Xt=async(t,e,r,n)=>{if("components"in t)throw new d("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const o=r.operators,i={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!o)throw new Error("Normalizer operator registry is not initialized");if(t.name!==void 0&&(typeof t.name!="string"||t.name.length===0))throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new d("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!Bl(t.args))throw new d("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const s=t.schema===void 0||t.schema===e.id?e:r.resolveSchema?.(t.schema);if(!s)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>Xt(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...p}=t,l={...p,...a?{query:a}:{},...u?{pred:u}:{}},f=async m=>{const y=await Fl(m,s,r),h=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s,executionContext:o.executionContext})??y:y;return Vl(h)};if(typeof t.pred=="string"){const m=ce(s,t.pred,r.resolveSchema),y={...l,pred:m.canonicalName};return f({...y,name:y.name??Pt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...l,pred:await Xt(t.pred,s,r,n)};return f({...m,name:m.name??Pt(m,o,i)})}if(u)return f({...l,name:l.name??Pt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...l,name:l.name??Pt(l,o,i)})},Yl=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),vl=t=>{if(!Se(t))return!1;const e=t;return e.groupby!==void 0||e.preds!==void 0||e.from!==void 0||e.having!==void 0||e.sort!==void 0||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},kr=async(t,e)=>{if(Se(t)){if(!e.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>kr(r,e))):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(await Promise.all(Object.entries(t).map(async([r,n])=>[r,await kr(n,e)])))},Ns=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Ns(o,e))]:[`${e}_${r}`,n])),so=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=Object.entries(t),[r]=e;return e.length===1&&r?.[0]==="$eq"?r[1]:t},Os=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),ao=new Set([...Os,"$length"]),Ur=t=>Array.isArray(t)?t.some(Ur):typeof t!="object"||t===null||Se(t)?!1:Object.entries(t).some(([e,r])=>ao.has(e)||Ur(r)),Ts=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Se(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Ts(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},Mr=(t,e)=>{if(t.schema!==void 0)throw new d("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new d("EXPRESSION_QUERY_PRED_QUERY_NOT_ALLOWED","$expr.pred cannot define pred.query");if(t.operator){if(!e.operators)throw new Error("Normalizer operator registry is not initialized");const r=e.operators.get(t.operator);if(r.kind!=="scalar"||!r.toSQL)throw new d("OPERATOR_NOT_ALLOWED_IN_EXPRESSION_QUERY",`Operator ${t.operator} cannot be used in $expr`,{operator:t.operator})}t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Mr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&Mr(r,e)},Ps=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must contain exactly pred and condition",{unsupported:o});if(typeof n.pred!="object"||n.pred===null||Array.isArray(n.pred))throw new d("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new d("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");Mr(i,r);const s=await Xt(i,e,r,()=>Promise.resolve(void 0));Mr(s,r);const a=so(await kr(n.condition,r));return ao.has(s.operator)&&Ts(a,s.operator),{pred:s,condition:a}},Ls=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Se(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))ao.has(s)?i.push({$expr:await Ps({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(Ur)?i.push({[s]:await Promise.all(a.map(u=>Ls(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:so(o)}),i.length===1?i[0]??{}:{$and:i}},co=t=>Array.isArray(t)?t.some(co):typeof t!="object"||t===null||Se(t)?!1:Object.entries(t).some(([e,r])=>Os.has(e)||co(r)),Cs=async(t,e,r,n)=>{const o=c=>{if(Array.isArray(c)){c.forEach(o);return}if(typeof c!="object"||c===null||Se(c))return;const p=c;if("$options"in p)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(p).forEach(o)};if(o(t),r.primal_type!=="date"&&co(t))throw new d("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const i=n.semanticTypes.get(r.type),s={schema:e,property:r,now:n.now??new Date,requestTimeWatermark:c=>n.requestTimeWatermark?.(e,r,c)??Promise.resolve(void 0)},a=await Ml(te(t),s),u=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const c=new Set(r.comparable.values),p=(l,f)=>{if(!(Se(l)||l===null)){if(Array.isArray(l)){l.forEach(m=>p(m,f));return}if(typeof l=="object"){Object.entries(l).forEach(([m,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(m)||p(y,m)});return}if(!(f&&["$exists","$regex","$contains","$startsWith","$length"].includes(f))&&(typeof l!="string"||!c.has(l)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(l)}`,{property:r.name,value:l})}};p(u)}return u},uo=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const u=Object.entries(a);if(u.length===1&&u[0]?.[0]==="$and"&&Array.isArray(u[0][1]))for(const c of u[0][1])s(c);else u.length===1&&u[0]?.[0]==="$expr"?o.push(a):u.every(([c])=>!c.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,u]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(u.map(async m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return uo(m,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Ps(u,e,r)});continue}const c=ce(e,a,r.resolveSchema);if(vl(u)&&(c.property.primal_type==="entity"||c.property.primal_type==="object")&&c.property.ref){if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const m=await r.normalizeNestedLogicform(u);n[c.canonicalName]={$in:m};continue}if(Yl(u)){if(u.version!==void 0&&io(u),c.property.primal_type!=="entity"&&c.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!c.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${c.canonicalName}`);if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema}`);const m=r.resolveSchema?.(u.schema);if(!m)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${u.schema}`);const y=Ss(u.query,u.entity_id,m,r.plugins),h=await uo(y,m,r);Object.assign(n,Ns(h,c.canonicalName));continue}if(typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=u,y=Object.entries(m).filter(([h])=>wt(h,r.plugins));if(y.length>0){const[h]=y,g=h?wt(h[0],r.plugins):void 0;if(g?.validateCondition?.(m),!h||y.length!==1||Object.keys(m).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[_,E]=h;if(!g)throw new Error(`Query Operator disappeared: ${_}`);n[c.canonicalName]={[_]:await g.normalize(E,{schema:c.schema,property:c.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(S,w,A)=>Cs(S,w,A,r)})};continue}}const p=await kr(u,r),l=await Cs(p,c.schema,c.property,r),f=so(l);if(Ur(f)){s(await Ls(c.canonicalName,f,e,r));continue}n[c.canonicalName]=f}if(i.length>0){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...i]}if(o.length===1)n.$expr=o[0]?.$expr;else if(o.length>1){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...o]}return n},Ds=async(t,e,r)=>{if(!t)return;const n=await uo(t,e,r);return Object.keys(n).length===0?void 0:n},ks=(t,e,r)=>Promise.all((t??[]).map(n=>Xt(n,e,r,Ds))),Ql=(t,e,r)=>ks(t??[],e,r),Lt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},Hl=t=>{"skip"in t&&Lt("skip has been removed; use the 1-based page field",{skip:t.skip});const e=t.groupby?.length??0;t.limitBy!==void 0&&((!Number.isInteger(t.limitBy)||t.limitBy<=0)&&Lt("limitBy must be a positive integer",{limitBy:t.limitBy}),e<2&&(t.limit=t.limitBy,delete t.limitBy));const{limit:r,page:n}=t;if(r===void 0){n!==void 0&&Lt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Lt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Lt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Lt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},Gl=t=>t.property.name,Us=(t,e,r,n,o=new Set)=>{if(o.has(t.id))return;const i=new Set(o).add(t.id),s=t.properties.find(a=>a.id===e||a.name===e);if(s)return s.name;if(n==="timestamp"){const a=t.properties.find(u=>u.type==="timestamp");if(a)return a.name}for(const a of t.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const u=r?.(a.ref);if(!u)continue;const c=Us(u,e,r,n,i);if(c)return`${a.name}_${c}`}},Ms=(t,e,r,n)=>{try{const o=ce(t,e,n);return Us(r,Gl(o),n,o.property.type)}catch{return}},lo=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?lo(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:lo(e)):[]],qs=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>qs(n));if(e==="$expr"&&typeof r=="object"&&r!==null&&!Array.isArray(r)){const n=r.pred;return typeof n=="object"&&n!==null&&!Array.isArray(n)?lo(n):[]}return e.startsWith("$")?[]:[e]}):[],Wl=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[p,l]of Object.entries(a))try{const f=ce(e,p,r.resolveSchema),m=u?ce(u,l,r.resolveSchema):void 0;c[f.canonicalName]=m?.canonicalName??l}catch{c[p]=l}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...qs(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ce(e,s,r.resolveSchema)}catch{continue}for(const u of n){const c=r.resolveSchema?.(u),p=c&&Ms(e,s,c,r.resolveSchema);p&&p!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},zl=t=>{if(t!==void 0){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_PROPERTY_RESOLVE","propertyResolve must be an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e} must be an object`);for(const[n,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e}.${n} must be a non-empty string`)}}},Kl=async(t,e,r)=>{if(!t)return;const n=ms(t,e,r);return dt(t,n,r)},dt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:pr([...fe(r.plugins).flatMap(h=>h.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:De(r.plugins)}},io(t),zl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!yi(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=te(t),i={...r,normalizeNestedLogicform:async h=>{const g=ms(h,e,r);return dt(h,g,r)}};Hl(o);const s=await Kl(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,u=await Ds(Ss(o.query,o.entity_id,a,r.plugins),a,i),c=o.preds===void 0&&o.groupby===void 0?a.properties.filter(h=>r.canProjectProperty?.(a,h)??!0).map(h=>({pred:h.name,name:h.name})):o.preds,p={...i,...u?{autoCaseQuery:u}:{}};let l=await ks(c,a,p),f=await Ql(o.groupby,a,p);const m=f.filter(h=>ni(h,f,a,r.resolveSchema));if(m.length>0){const h=new Set(m.map(({name:g})=>g));f=f.filter(({name:g})=>!h.has(g)),l=[...l,...m]}return o.preds=l,f.length>0?o.groupby=f:delete o.groupby,s?o.from=s:delete o.from,u?o.query=u:delete o.query,Wl(o,a,i)},js=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Qe=(t,e)=>{if(t){if(!js(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},lt=(t,e,r)=>{const n=Qe(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},Zt=(t,e,r)=>{if(!lt(t,e.id,r))throw new d("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},po=(t,e,r,n)=>{const o=ce(e,t,n);for(const i of o.relations)Qe(r,i.targetSchema.id),Zt(r,i.sourceSchema,i.property);Zt(r,o.schema,o.property)},xs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),qr=(t,e,r,n)=>{if(Se(t)){xr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)qr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))qr(o,e,r,n)};function er(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Qe(r,t.schema),typeof t.pred=="string"?po(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&er(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?po(s,i,r,n):er(s,i,r,n,o);jr(t.query,i,r,n,o)}const jr=(t,e,r,n,o)=>{if(t)for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const u of s)jr(u,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const u=s.pred;typeof u=="object"&&u!==null&&!Array.isArray(u)&&er(u,e,r,n,o),qr(s.condition,r,n,o)}continue}const a=ce(e,i,n);if(po(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[u,c]of Object.entries(s))wt(u,o)?.authorize?.(c,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{Qe(r,p)},assertPropertyAllowed:(p,l)=>Zt(r,p,l),hasRowPermissions:p=>Qe(r,p)?.rowPermissions!==void 0});if(xs(s)){if(a.property.ref!==s.schema)continue;const u=n(s.schema);Qe(r,u.id),hn(s.entity_id)&&Zt(r,u,gn(u,o)),jr(s.query,u,r,n,o);continue}qr(s,r,n,o)}},xr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){xr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Qe(e,o.id),hn(t.entity_id)&&Zt(e,o,gn(o,n)),t.from){xr(t.from,e,r,n);return}jr(t.query,o,e,r,n);for(const i of t.preds??[])er(i,o,e,r,n);for(const i of t.groupby??[])er(i,o,e,r,n)},Br=(t,e)=>{if(Array.isArray(t))return t.map(o=>Br(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Br(i,e)]),n=Object.fromEntries(r);return xs(t)&&!js(t,"version")&&(n.version=e),n},Jl=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[u,c]of Object.entries(s))if((u==="$and"||u==="$or")&&Array.isArray(c))for(const p of c)o(p,a);else if(u==="$expr"&&typeof c=="object"&&c!==null&&!Array.isArray(c)){const p=c.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else u.startsWith("$")||n.push(ce(a,u,r))},i=(s,a)=>{const u=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(ce(u,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,u);for(const c of Array.isArray(s.pred)?s.pred:[])typeof c=="string"?n.push(ce(u,c,r)):i(c,u);o(s.query,u)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},Xl=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Jl(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},f)=>{e[l.id]?.rowPermissions!==void 0&&(a=f)}),a<0)continue;const u=s.relations.slice(0,a+1),c=u.map(({property:l})=>l.name).join("_");if(o.has(c))continue;o.add(c);let p={};for(const l of[...u].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Ct=(t,e,r,n,o,i)=>Se(t)?pt(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Ct(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Ct(a,e,r,n,o,i)])),fo=(t,e,r,n,o,i)=>({...t,...t.query?{query:Ct(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:fo(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:fo(s,e,r,n,o,i))}:{}}),pt=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return te(t);if(!t.schema){const m=te(t);return m.from&&(m.from=pt(m.from,e,r,n,new Set,i)),m}n&&xr(t,e,r,i);const s=Qe(e,t.schema),a=o.has(t.schema),u=new Set(o).add(t.schema),c=te(t);c.query&&(c.query=Ct(c.query,e,r,n,new Set,i)),c.preds&&(c.preds=c.preds.map(m=>fo(m,e,r,n,new Set,i))),c.from&&(c.from=pt(c.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:Xl(t,e,r)).map(m=>Ct(Br(m,t.version),e,r,!1,u,i));p&&l.push(Ct(Br(te(p),t.version),e,r,!1,u,i));const f=[c.query,...l].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?c.query=f[0]:f.length>1?c.query={$and:f}:delete c.query,c},Zl=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const o=e(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new d("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:u})=>a===s||u===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},Bs=(t,e)=>{const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(t),n=o=>Number(r.find(i=>i.type===o)?.value);return{year:n("year"),month:n("month"),day:n("day"),hour:n("hour"),minute:n("minute"),second:n("second")}},Vs=(t,e)=>{const r=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second);let n=r;for(let o=0;o<3;o+=1){const i=Bs(new Date(n),e),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);n+=r-s}return new Date(n)},ep=(t,e)=>{const r=Mi(t.expireAt);if(!r)throw new Error(`Invalid daily expiration time: ${t.expireAt}`);if(!t.timeZone){const i=new Date(e);return i.setHours(r.hour,r.minute,r.second,0),i.getTime()<=e.getTime()&&i.setDate(i.getDate()+1),i}const n=Bs(e,t.timeZone);let o=Vs({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Vs({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},tp=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[ep(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},mo=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?t.map(mo):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,mo(r)])):t,Fs=t=>en.createHash("sha256").update(JSON.stringify(mo(t))).digest("hex"),rp=t=>Fs({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),np=(t,e)=>Fs({namespace:t,source:e}),yo=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?{type:"array",value:t.map(yo)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,yo(r)])}:t,ho=t=>{if(t===null||typeof t!="object")return t;switch(t.type){case"undefined":return;case"bigint":return BigInt(t.value);case"number":return Number(t.value);case"date":return new Date(t.value);case"array":return t.value.map(ho);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,ho(r)]))}},op=t=>JSON.stringify(yo(t)),ip=t=>{const e=ho(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},sp=Number.MAX_SAFE_INTEGER;class ap{#e;#t;#r;constructor(e,r={}){this.#e=e,this.#t=r.keyPrefix??"semanticdb:cache",this.#r=r.ownsClient??!1}#n(e){return`${this.#t}:query:${rp(e)}`}#o(e,r){return`${this.#t}:source:${np(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return ip(r)}async set(e,r,n){const o=this.#n(e),i=op(r),s=n.expiresAt?.getTime(),a=s??sp,u=this.#e.multi();s===void 0?u.set(o,i):u.set(o,i,{PXAT:s});for(const c of new Set(n.sources)){const p=this.#o(e.namespace,c);u.zRemRangeByScore(p,0,Date.now()),u.zAdd(p,{score:a,value:o})}await u.exec()}async invalidateSource(e,r){const n=this.#o(e,r),o=await this.#e.zRange(n,0,-1);o.length>0&&await this.#e.del(o),await this.#e.del(n)}async close(){this.#r&&await this.#e.close()}}const cp=async(t={})=>{const e=Ta.createClient(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new ap(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function up(t){if(!t||typeof t!="object")throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache configuration must be an object");const e=t;if(typeof e.id!="string"||e.id.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache id must not be empty");if(e.kind!=="redis")throw new d("INVALID_QUERY_CACHE_CONFIGURATION",`Unsupported query cache kind: ${String(e.kind)}`);if(typeof e.url!="string"||e.url.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache url must not be empty");if(e.keyPrefix!==void 0&&(typeof e.keyPrefix!="string"||e.keyPrefix.trim().length===0))throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache keyPrefix must not be empty");if(typeof e.namespace!="string"||e.namespace.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache namespace must not be empty")}const dp=({namespace:t,...e})=>e,lp=async t=>cp({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class pp{create;#e=new Map;constructor(e=lp){this.create=e}async get(e){up(e);const r=dp(e),n=this.#e.get(r.id);if(n){if(!Mo.isDeepStrictEqual(n.connection,r))throw new d("QUERY_CACHE_CONFIGURATION_MISMATCH",`Query cache configuration changed for id: ${r.id}`,{cacheId:r.id});return{store:await n.store,namespace:e.namespace}}const o=this.create(r),i={connection:r,store:o};this.#e.set(r.id,i);try{return{store:await o,namespace:e.namespace}}catch(s){throw this.#e.get(r.id)===i&&this.#e.delete(r.id),s}}async close(){const e=[...this.#e.values()];this.#e.clear();const n=(await Promise.allSettled(e.map(async({store:o})=>(await o).close()))).flatMap(o=>o.status==="rejected"?[o.reason]:[]);if(n.length>0)throw new AggregateError(n,"Failed to close one or more query cache connections")}}const Ys=new pp,vs=t=>Ys.get(t),fp=()=>Ys.close(),mp=async({cache:t,source:e})=>{if(typeof e!="string"||e.trim().length===0)throw new d("INVALID_QUERY_CACHE_SOURCE","Query cache source must not be empty");const r=await vs(t);await r.store.invalidateSource(r.namespace,e)},yp=Object.freeze({invalidateSource:mp}),go=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),tr=(t,e,r)=>{if(Et(t)){e.push(t.plan);return}if(Ci(t)){for(const n of t.sources??[])r.set(`${n.schemaId}:${n.connectionId??""}:${n.source}`,n);return}if(Array.isArray(t)){for(const n of t)tr(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))tr(n,e,r)},rr=(t,e,r)=>{if(t.kind==="window"){rr(t.input,e,r);for(const n of t.partitionBy)rr(n,e,r);return}if(t.kind==="operator"){tr(t.query,e,r),t.input&&rr(t.input,e,r);for(const n of t.inputs??[])rr(n,e,r)}},$e=t=>{const e=new Map,r=o=>{e.set(`${o.schemaId}:${o.connectionId??""}:${o.mappingSource??""}:${o.source}`,o)};if(t.subplans)for(const o of t.subplans)for(const i of $e(o))r(i);else if(t.sourcePlan)for(const o of $e(t.sourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}});for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];tr(t.query,n,e),tr(t.having,n,e);for(const o of t.projections)rr(o.expression,n,e);for(const o of n)for(const i of $e(o))r(i);return[...e.values()]},nr=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.source}`,r);return[...e.values()]},Qs=async(t,e)=>{try{return await t.execute(e)}catch(r){const n=r instanceof Error?r.message:String(r),o=`${t.kind} provider \u6267\u884C SQL \u4EA7\u751F\u9519\u8BEF\uFF1A`;throw r instanceof Error?(r.message.startsWith(o)||(r.message=`${o}${n}`),r):new Error(`${o}${n}`,{cause:r})}},hp=(t,e)=>{const r=[];for(const n of t){const o=go(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Re=async(t,e,r)=>{t=Hs(t),r.signal?.throwIfAborted();const n=r.cache?hp(e,r.schemaMappings):void 0;if(!r.cache||!n)return Qs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const o={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const s=await r.cache.store.get(o);if(r.signal?.throwIfAborted(),s)return[...s]}catch{r.signal?.throwIfAborted()}const i=await Qs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const s=tp(n,new Date);await r.cache.store.set(o,i,{sources:[...new Set(e.map(({source:a})=>a))],...s?{expiresAt:s}:{}})}catch{}return i},Hs=t=>({...t,sql:al(t.sql)}),gp=t=>{if(t.every(e=>typeof e=="string"))return[...t];if(t.every(e=>typeof e=="number"))return[...t];if(t.every(e=>typeof e=="boolean"))return[...t];throw new TypeError("Entity IDs must have one scalar type")},Ap=(t,e,r)=>{const n=gp(e);if(!r||n.length<=r)return{[t]:{$in:n}};const o=[];for(let i=0;i<n.length;i+=r)o.push({[t]:{$in:n.slice(i,i+r)}});return{$or:o}},Gs=async(t,e)=>{if(!lt(e.permissions,t.schema.id,t.idProperty))throw new d("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${t.schema.id}.${t.idProperty.name}`,{schemaId:t.schema.id,property:t.idProperty.name});const r=t.schema.properties.filter(h=>lt(e.permissions,t.schema.id,h)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:h})=>h===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:Ap(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(h=>({pred:h.name,name:h.name}))},a=pt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await dt(a,t.schema,{semanticTypes:e.semanticTypes,operators:e.operators,...e.plugins?{plugins:e.plugins}:{},...e.locale?{locale:e.locale}:{},...e.localeRegistry?{localeRegistry:e.localeRegistry}:{},resolveSchema:e.resolveSchema}),c=Pe(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(h,g)=>lt(e.permissions,h.id,g)}),p=new Set($e(c).map(h=>e.schemaMappings.findSource(h.schemaId,h.source,h.connectionId)?.connectionId).filter(h=>!!h));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,f=l&&e.providerForConnection?e.providerForConnection(l):i,m=ye(c,f,e.operators);e.onCompiled?.(m,u,f,l);const y=await Re(m,$e(c),{provider:f,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}});return Kn(y,c.rowIdentity)},Ws=t=>String(t),wp=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Ws(r)}\u300D\u7684\u5B9E\u4F53`,o={};for(const i of t.properties)i.id===e.id?o[i.name]=r:i.isArray?o[i.name]=[]:o[i.name]=i.primal_type==="string"?n:null;return o._id=Ws(r),o},zs=(t,e)=>`${t}:${String(e)}`,$p=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),r=e[0];if(e.length!==1||!r)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r};class Ep{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=zs(e,r),o=this.#t.get(n);if(o)return Promise.resolve(o);const i=this.#r.get(n);if(i)return i;const s=this.#e.resolveSchema(e);if(hi(s,this.#e.plugins))throw new d("INTERVAL_ENTITY_HYDRATION_REQUIRES_POINT",`Cannot hydrate interval-versioned entity ${e} by ID without a selection point; use a relation path to select its point-in-time properties`,{schemaId:e});const a=$p(s);let u,c;const p=new Promise((f,m)=>{u=f,c=m}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:f=>u?.(f),reject:f=>c?.(f)}),this.#n.set(e,l),this.#r.set(n,p),this.#s(),p};#s(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#i()}))}async#i(){this.#o=!1;const e=this.#n;this.#n=new Map,await Promise.all([...e.values()].map(r=>this.#a(r)))}async#a(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n)};try{const n=await this.#e.fetchEntities(r),o=new Map;for(const i of n){const s=i[e.idProperty.name]??i._id;if(s!=null){const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(zs(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??wp(e.schema,e.idProperty,s.id);this.#t.set(i,a),this.#r.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of e.loads)this.#r.delete(o),i.reject(n)}}}const _p=(t,e)=>{if(!e.isArray||typeof t!="string")return t;const r=t.trim();if(!r.startsWith("[")||!r.endsWith("]"))return t;try{const n=JSON.parse(r);if(!Array.isArray(n))throw new Error("JSON result is not an array");return n}catch(n){throw new d("INVALID_ARRAY_RESULT",`Result column ${e.name} contains invalid array JSON`,{property:e.name,cause:n})}},Sp=async(t,e,r,n)=>{await Promise.all(t.map(async o=>{await Promise.all(e.map(async i=>{if(!(i.name in o))return;const s=_p(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(u=>a(u,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},Ks=5,Ip=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),bp=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Rp=(t,e)=>{const r=Pa.getNameProperty(e);t._title=t[r.name]??t._id},Np=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=bp(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Op=(t,e,r,n)=>{const o=`${e.id}:${n?"recursive":"leaf"}`,i=t.get(o);if(i){i.rows.push(r);return}t.set(o,{rows:[r],properties:e.properties,schema:e,expandEntities:n})},Tp=async(t,e,r)=>{const n=new Ep(r);let o=[{rows:t,properties:e,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<Ks;return Sp(a.rows,a.properties,r.semanticTypes,u?n.load:(c,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const u of a.rows)Rp(u,a.schema);if(i>=Ks)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const p of a.rows){if(!(u.name in p))continue;const l=p[u.name],f=u.isArray?Array.isArray(l)?l:[l]:[l];for(const[m,y]of f.entries()){if(!Ip(y))continue;const h=Np(y,c);u.isArray?f[m]=h:p[u.name]=h,Op(s,c,h,!u.isArray)}u.isArray&&(p[u.name]=f)}}o=[...s.values()]}},Js=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Tp(n,e,r),n},Ao=t=>`'${t.replaceAll("'","''")}'`,Xs=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
4
- `,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},or=(t,e)=>{if(t==null)return"NULL";if(typeof t=="boolean")return e==="mysql"?t?"true":"false":e==="sqlserver"?t?"1":"0":t?"TRUE":"FALSE";if(typeof t=="number")return String(t);if(typeof t=="bigint")return e==="mysql"||e==="sqlserver"?t.toString():Ao(t.toString());if(typeof t=="string")return e==="mysql"?Xs(t):Ao(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Xs(r):Ao(r)}if(Buffer.isBuffer(t)){const r=t.toString("hex");return e==="mysql"?`X'${r}'`:e==="dameng"||e==="oracle"?`HEXTORAW('${r}')`:e==="postgresql"?`decode('${r}', 'hex')`:e==="snowflake"?`TO_BINARY('${r}', 'HEX')`:e==="sqlserver"?`0x${r}`:`unhex('${r}')`}throw new TypeError(`Unsupported ${e} display parameter type: ${typeof t}`)},Pp=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?or(e[o],"clickhouse"):r}),Lp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?or(e[o],"oracle"):r}),Cp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=or(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},wo=(t,e,r)=>{let n="",o=0,i;for(let s=0;s<t.length;s+=1){const a=t[s];if(a){if(i){n+=a,a===i&&(t[s+1]===i?(n+=i,s+=1):i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a,n+=a;continue}if(a==="?"&&o<e.length){n+=or(e[o],r),o+=1;continue}n+=a}}return n},Dp=(t,e)=>wo(t,e,"mysql"),$o=(t,e)=>wo(t,e,"snowflake"),kp=(t,e)=>wo(t,e,"dameng"),Up=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=or(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},Ze=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),ir=t=>{for(const[e,r]of Object.entries({database:t.database,schema:t.schema}))if(r!==void 0&&!r.trim())throw new d("INVALID_TABLE_SCOPE",`Table discovery ${e} must not be empty`)},Le=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},xe=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Ne=(t,e)=>{const r=xe(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},Zs=t=>{const e=Ne(t,"table_name"),r=xe(t,"table_database"),n=xe(t,"table_schema"),o=Ne(t,"table_type").toUpperCase();if(!["BASE TABLE","TABLE","FOREIGN TABLE","EXTERNAL TABLE","EVENT TABLE","VIEW","SYSTEM VIEW","MATERIALIZED VIEW"].includes(o))throw new d("INVALID_TABLE_METADATA",`Unsupported metadata table type: ${o}`);return{name:e,...typeof r=="string"?{database:r}:{},...typeof n=="string"?{schema:n}:{},type:o.includes("VIEW")?"view":"table"}},Mp=t=>t.map(Zs),ft=async(t,e)=>{e.signal?.throwIfAborted(),ir(e);const r=[],n=u=>{const c=t.parameter(r.length,u);return r.push(u),c},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Le(t,"schema"),s="SELECT TABLE_NAME AS table_name, TABLE_SCHEMA AS table_database, TABLE_TYPE AS table_type FROM information_schema.tables WHERE TABLE_SCHEMA = "+(o!==void 0?n(o):"DATABASE()");break;case"postgresql":o!==void 0&&Le(t,"database"),s="SELECT table_name, table_catalog AS table_database, table_schema, table_type FROM information_schema.tables WHERE table_schema = "+(i!==void 0?n(i):"current_schema()");break;case"sqlserver":case"snowflake":{s=`SELECT TABLE_NAME AS table_name, TABLE_CATALOG AS table_database, TABLE_SCHEMA AS table_schema, TABLE_TYPE AS table_type FROM ${`${o!==void 0?`${t.quoteIdentifier(o)}.`:""}INFORMATION_SCHEMA.TABLES`}`,i!==void 0?s+=` WHERE TABLE_SCHEMA = ${n(i)}`:t.kind==="snowflake"&&(s+=" WHERE TABLE_SCHEMA = CURRENT_SCHEMA()");break}case"oracle":case"dameng":o!==void 0&&Le(t,"database"),s="SELECT OBJECT_NAME AS table_name, OWNER AS table_schema, OBJECT_TYPE AS table_type FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TABLE', 'VIEW') AND OWNER = "+(i!==void 0?n(i):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')");break;case"clickhouse":i!==void 0&&Le(t,"schema"),s="SELECT name AS table_name, database AS table_database, if(engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables WHERE database = "+(o!==void 0?n(o):"currentDatabase()");break;default:throw new d("UNSUPPORTED_TABLE_DISCOVERY",`No metadata SQL for provider: ${t.kind}`)}s+=" ORDER BY table_name";const a=await t.execute({sql:s,parameters:r,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),Mp(a)},Eo=t=>{if(ir(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},Vr=(t,e)=>{const r=xe(t,e);return typeof r=="string"?r:""},qp=t=>{const e=Ne(t,"column_type"),r=xe(t,"type_length"),n=xe(t,"type_precision"),o=xe(t,"type_scale");return/^(?:n?varchar2?|n?char|n?varbinary|binary|raw)$/i.test(e)&&typeof r=="number"?`${e}(${r===-1?"max":r})`:/^(?:number|numeric|decimal)$/i.test(e)&&typeof n=="number"?`${e}(${n}${typeof o=="number"?`,${o}`:""})`:e},ea=t=>{const e=xe(t,"is_primary_key");let r;if(e!=null)if([!0,1,"1","true","TRUE","YES","Y"].includes(e))r=!0;else if([!1,0,"0","false","FALSE","NO","N"].includes(e))r=!1;else throw new d("INVALID_TABLE_METADATA","Invalid primary-key metadata");return{name:Ne(t,"column_name"),type:qp(t),comment:Vr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},jp=(t,e)=>{const r=[],n=c=>{const p=t.parameter(r.length,c);return r.push(c),p},o=n(e.table),{database:i,schema:s}=e;let a,u;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Le(t,"schema");const c=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${i!==void 0?n(i):"DATABASE()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_SCHEMA AS table_database, c.TABLE_TYPE AS table_type, c.TABLE_COMMENT AS table_comment FROM information_schema.tables c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.COLUMN_TYPE AS column_type, c.COLUMN_COMMENT AS column_comment, (c.COLUMN_KEY = 'PRI') AS is_primary_key FROM information_schema.columns c WHERE ${c} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&Le(t,"database");const c=`c.relname = ${o} AND n.nspname = ${s!==void 0?n(s):"current_schema()"}`;a=`SELECT c.relname AS table_name, current_database() AS table_database, n.nspname AS table_schema, CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW' ELSE 'TABLE' END AS table_type, obj_description(c.oid, 'pg_class') AS table_comment FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,u=`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS column_type, col_description(c.oid, a.attnum) AS column_comment, EXISTS (SELECT 1 FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid AND i.indisprimary AND a.attnum = ANY(i.indkey)) AS is_primary_key FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const c=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${c}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${c}sys.objects o ON o.schema_id = s.schema_id AND o.name = c.TABLE_NAME `;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, CAST(ep.value AS nvarchar(max)) AS table_comment FROM ${c}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale, CAST(ep.value AS nvarchar(max)) AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ${c}sys.indexes i JOIN ${c}sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE i.object_id = o.object_id AND i.is_primary_key = 1 AND ic.key_ordinal > 0 AND ic.column_id = sc.column_id) THEN 1 ELSE 0 END AS is_primary_key FROM ${c}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${c}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = sc.column_id AND ep.name = 'MS_Description' WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const c=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"CURRENT_SCHEMA()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENT AS table_comment FROM ${c}.TABLES c WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.COMMENT AS column_comment, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale FROM ${c}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Le(t,"database");const c=`c.TABLE_NAME = ${o} AND c.OWNER = ${s!==void 0?n(s):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"}`;a=`SELECT c.TABLE_NAME AS table_name, c.OWNER AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENTS AS table_comment FROM ALL_TAB_COMMENTS c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, CASE WHEN c.DATA_TYPE = 'RAW' THEN c.DATA_LENGTH ELSE c.CHAR_LENGTH END AS type_length, c.DATA_PRECISION AS type_precision, c.DATA_SCALE AS type_scale, cm.COMMENTS AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ALL_CONS_COLUMNS k JOIN ALL_CONSTRAINTS t ON t.OWNER = k.OWNER AND t.CONSTRAINT_NAME = k.CONSTRAINT_NAME WHERE t.CONSTRAINT_TYPE = 'P' AND k.OWNER = c.OWNER AND k.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END AS is_primary_key FROM ALL_TAB_COLUMNS c LEFT JOIN ALL_COL_COMMENTS cm ON cm.OWNER = c.OWNER AND cm.TABLE_NAME = c.TABLE_NAME AND cm.COLUMN_NAME = c.COLUMN_NAME WHERE ${c} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&Le(t,"schema");const c=i!==void 0?n(i):"currentDatabase()";a=`SELECT c.name AS table_name, c.database AS table_database, c.comment AS table_comment, if(c.engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables c WHERE c.name = ${o} AND c.database = ${c}`,u=`SELECT c.name AS column_name, c.type AS column_type, c.comment AS column_comment, c.is_in_primary_key AS is_primary_key FROM system.columns c WHERE c.table = ${o} AND c.database = ${c} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:u,parameters:r}},ta=(t,e)=>{const r=[];return!["postgresql","oracle","dameng"].includes(t.kind)&&e.database!==void 0&&r.push(e.database),e.schema!==void 0&&r.push(e.schema),r.push(e.name),r.map(n=>t.quoteIdentifier(n)).join(".")},Dt=async(t,e,r,n=[])=>{e.signal?.throwIfAborted();const o=await t.execute({sql:r,parameters:n,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),o},_o=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=ta(t,r.tableInfo),o=t.kind==="sqlserver"?`SELECT TOP (1) * FROM ${n}`:["oracle","dameng"].includes(t.kind)?`SELECT * FROM ${n} FETCH FIRST 1 ROWS ONLY`:`SELECT * FROM ${n} LIMIT 1`;let i;try{[i]=await Dt(t,e,o)}catch{return e.signal?.throwIfAborted(),r}return i?{...r,columns:r.columns.map(s=>({...s,...Object.hasOwn(i,s.name)?{exampleValue:i[s.name]}:{}}))}:r},xp=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Dt(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!l)throw new d("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=Ne(l,"table_database"),n??=Ne(l,"table_schema")}const o=ta(t,{name:e.table,database:r,schema:n}),i=await Dt(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,u=!1,c="",p="table";for(const l of i){const f=xe(l,"col_name"),m=xe(l,"data_type"),y=(f==="# Partition Information"||f==="# Detailed Table Information")&&!m;(f===""||y)&&(a=!1),y&&f==="# Detailed Table Information"&&(u=!0),a?s.push({name:Ne(l,"col_name"),type:Ne(l,"data_type"),comment:Vr(l,"comment")}):u&&f==="Comment"?c=Vr(l,"data_type"):u&&f==="Type"&&m==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return _o(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:c}})},Bp=async(t,e)=>{e.database!==void 0&&Le(t,"database"),e.schema!==void 0&&Le(t,"schema");const n=(await Dt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(ea);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return _o(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},He=async(t,e)=>{if(e.signal?.throwIfAborted(),Eo(e),t.kind==="databricks")return xp(t,e);if(t.kind==="maxcompute")return Bp(t,e);const{tableSql:r,columnSql:n,parameters:o}=jp(t,e),i=await Dt(t,e,r,o),[s]=i;if(!s)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);if(i.length!==1)throw new d("AMBIGUOUS_TABLE",`More than one table matched: ${e.table}`);const a={...Zs(s),comment:Vr(s,"table_comment")},u=(await Dt(t,e,n,o)).map(ea);return _o(t,e,{columns:u,tableInfo:a})},Vp=t=>{if(t.url!==void 0)return t.url;const e=t.host??"localhost";if(/^[a-z][a-z\d+.-]*:\/\//iu.test(e)){if(t.port===void 0)return e;const n=new URL(e);return n.port=String(t.port),n.toString()}return`http://${e}:${t.port??8123}`},Fp=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",ra=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Yp{kind="clickhouse";supportsRecursiveCte=!0;recursiveCteUnion="UNION ALL";#e;#t;constructor(e={}){this.#e=e,this.#t=e.client?Promise.resolve(e.client):void 0}async#r(){this.#t??=(async()=>{const{createClient:e}=await import("@clickhouse/client").catch(r=>{throw Ze("@clickhouse/client",r)});return e({url:Vp(this.#e),username:this.#e.username??this.#e.user??"default",password:this.#e.password??"",database:this.#e.database??"default"})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`{p${e}:${Fp(r)}}`}displayQuery(e,r){return Pp(e,r)}dateBucket(e,r){if(r==="second")return`toDateTime64(${e}, 0)`;const o={minute:"toStartOfMinute",hour:"toStartOfHour",day:"toStartOfDay",week:"toStartOfWeek",month:"toStartOfMonth",quarter:"toStartOfQuarter",year:"toStartOfYear"}[r];if(!o)throw new Error(`Unsupported ClickHouse date level: ${r}`);return`${o}(${e})`}datePart(e,r){return`${{second:"toSecond",minute:"toMinute",hour:"toHour",weekday:"toDayOfWeek",day:"toDayOfMonth",week:"toISOWeek",month:"toMonth",quarter:"toQuarter",year:"toYear"}[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported ClickHouse date shift: ${r}/${n}`);return`dateAdd(${r}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`toDateTime(${e})`:r==="date"?`toDate(${e})`:e}scalarExtremum(e,r){const n=`[${r.map(s=>`toNullable(${s})`).join(", ")}]`,o=`arrayFilter(value -> isNotNull(value), ${n})`;return`if(arrayExists(value -> isNotNull(value), ${n}), ${e==="least"?"arrayMin":"arrayMax"}(${o}), NULL)`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported ClickHouse aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`toString(${e})`}concat(e){return`concat(${e.join(", ")})`}substring(e,r,n){return`substring(${e}, ${r}, ${n})`}stringLength(e){return`lengthUTF8(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported ClickHouse regex options: ${n}`);const o=n==="i"?`concat('(?i)', ${r})`:r;return`match(${e}, ${o})`}arrayContains(e,r){return`has(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${e} AS ${o}`,valueExpression:o}}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=Object.fromEntries(e.parameters.map((i,s)=>[`p${s}`,ra(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();if(e.signal?.throwIfAborted(),!r.exec)throw new d("UNSUPPORTED_RAW_SQL","ClickHouse native SQL requires client.exec");const n=await r.exec({query:e.sql,query_params:Object.fromEntries(e.parameters.map((a,u)=>[`p${u}`,ra(a)])),clickhouse_settings:{default_format:"JSONEachRow"},...e.signal?{abort_signal:e.signal}:{}}),o=[];for await(const a of n.stream)e.signal?.throwIfAborted(),o.push(Buffer.isBuffer(a)?a:Buffer.from(a));e.signal?.throwIfAborted();const i=Buffer.concat(o).toString("utf8").trim();return{rows:i?i.split(`
5
- `).map(a=>{const u=JSON.parse(a);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("ClickHouse provider expected object rows");return u}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const vp=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Qp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Databricks connection options must be an object");const e=t,{host:r,path:n,authType:o}=e;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0)throw new Error("Databricks connection requires host and path");if(o==="databricks-oauth"){const{oauthClientId:i,oauthClientSecret:s}=e;if(typeof i!="string"||i.length===0||typeof s!="string"||s.length===0)throw new Error("Databricks OAuth requires oauthClientId and oauthClientSecret");if("token"in e)throw new Error("Databricks OAuth connection must not define token");if("azureTenantId"in e&&typeof e.azureTenantId!="string")throw new Error("Databricks OAuth azureTenantId must be a string");if("oauthScopes"in e&&(!Array.isArray(e.oauthScopes)||e.oauthScopes.some(a=>typeof a!="string")))throw new Error("Databricks OAuth oauthScopes must be a string array");if("useDatabricksOAuthInAzure"in e&&typeof e.useDatabricksOAuthInAzure!="boolean")throw new Error("Databricks OAuth useDatabricksOAuthInAzure must be boolean");return{host:r,path:n,authType:o,oauthClientId:i,oauthClientSecret:s,...typeof e.azureTenantId=="string"?{azureTenantId:e.azureTenantId}:{},...Array.isArray(e.oauthScopes)?{oauthScopes:e.oauthScopes}:{},useDatabricksOAuthInAzure:e.useDatabricksOAuthInAzure??(vp(r)&&!e.azureTenantId)}}if(o==="access-token"){if(typeof e.token!="string"||e.token.length===0)throw new Error("Databricks access-token connection requires token");if(["oauthClientId","oauthClientSecret","azureTenantId","oauthScopes","useDatabricksOAuthInAzure"].some(i=>i in e))throw new Error("Databricks access-token connection must not define OAuth fields");return{host:r,path:n,authType:o,token:e.token}}throw new Error(`Unsupported Databricks authType: ${String(o)}`)},Hp=t=>{if(t==null)return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||t instanceof Date)return t;throw new TypeError(`Unsupported Databricks parameter type: ${typeof t}`)};class Gp{kind="databricks";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;#r;constructor(e={}){this.#e=e.connection,this.#t=e.client}async#n(){this.#r??=(async()=>{const e=this.#t??new(await import("@databricks/sql").catch(r=>{throw Ze("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Qp(this.#e))}catch(r){throw await e.close().catch(()=>{}),r}return e})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return $o(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Databricks date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){const n={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",week:"WEEKOFYEAR",month:"MONTH",quarter:"QUARTER",year:"YEAR"};return r==="weekday"?`(WEEKDAY(${e}) + 1)`:`${n[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Databricks date shift: ${r}/${n}`);return`TIMESTAMPADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS TIMESTAMP)`:r==="date"?`CAST(${e} AS DATE)`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Databricks aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS STRING)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Databricks regex options: ${n}`);return`${e} RLIKE ${n==="i"?`CONCAT('(?i)', ${r})`:r}`}arrayContains(e,r){return`ARRAY_CONTAINS(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`LATERAL VIEW EXPLODE(${e}) ${o} AS ${i}`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=this.#e?.schema??this.#e?.database,o=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let i;const s=()=>{i&&i.cancel().catch(()=>{})};e.signal?.addEventListener("abort",s,{once:!0});try{e.signal?.throwIfAborted(),i=await o.executeStatement(e.sql,{ordinalParameters:e.parameters.map(Hp)}),e.signal?.aborted&&s(),e.signal?.throwIfAborted(),await i.finished?.(),e.signal?.throwIfAborted();const a=await i.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(a))throw new Error("Databricks provider expected an array result");return a}finally{e.signal?.removeEventListener("abort",s);try{i&&await i.close()}finally{await o.close()}}}async runSQL(e){return{rows:await this.execute(e)}}describeTable(e){const r=e.database??this.#e?.catalog,n=e.schema??this.#e?.schema??this.#e?.database;return He(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),ir(e);const r=c=>this.execute({sql:c,parameters:[],...e.signal?{signal:e.signal}:{}});let n=e.database??this.#e?.catalog,o=e.schema??this.#e?.schema??this.#e?.database;if(n===void 0||o===void 0){const[c]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!c)throw new Error("Databricks current namespace was not returned");n??=Ne(c,"table_database"),o??=Ne(c,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),u=new Map;for(const c of s){const p=Ne(c,"tableName");u.set(p,{name:p,database:n,schema:o,type:"table"})}for(const c of a){const p=Ne(c,"viewName");u.set(p,{name:p,database:n,schema:o,type:"view"})}return[...u.values()].sort((c,p)=>c.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const na=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Dameng parameter type: ${typeof t}`)},Wp=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class zp{kind="dameng";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e={...Wp(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${en.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw Ze("dmdb",n)});return r.createPool(e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return"?"}displayQuery(e,r){return kp(e,r.map(na))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Dameng date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Dameng aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Dameng regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return ft(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return He(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection();try{e.signal?.throwIfAborted();const i=await o.execute(e.sql,e.parameters.map(na),{outFormat:4002,...r?{autoCommit:!0}:{}});if(e.signal?.throwIfAborted(),!(r&&i.rows===void 0)&&!Array.isArray(i.rows))throw new Error("Dameng provider expected an array result");return{rows:i.rows??[],...typeof i.rowsAffected=="number"?{affectedRows:i.rowsAffected}:{}}}finally{await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}const X={quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``},tableAlias(t,e){return`${t} AS ${this.quoteIdentifier(e)}`},paginate(t,e,r){return`${t} LIMIT ${e}${r>0?` OFFSET ${r}`:""}`},parameter(t,e){return"?"},displayQuery(t,e){return Dp(t,e)},dateBucket(t,e){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(e==="week")return`DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;if(e==="quarter")return`MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${e}`);return`DATE_FORMAT(${t}, '${n}')`},datePart(t,e){const r={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",month:"MONTH",quarter:"QUARTER",year:"YEAR"};if(e==="weekday")return`(WEEKDAY(${t}) + 1)`;if(e==="week")return`WEEK(${t}, 3)`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date part: ${e}`);return`${n}(${t})`},dateShift(t,e,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${e}/${r}`);return`DATE_ADD(${t}, INTERVAL ${r} ${e.toUpperCase()})`},datePeriodBoundary(t,e,r){if(r==="start")return this.dateBucket(t,e);switch(e){case"hour":return`DATE_FORMAT(${t}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${t}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${t}), '23:59:59')`;case"year":return`CONCAT(YEAR(${t}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(t,e),e,1),"second",-1)}},aggregateFunction(t,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported MySQL-compatible aggregate function: ${t}`);return`${t.toUpperCase()}(${e})`},stringify(t){return`CAST(${t} AS CHAR)`},concat(t){return`CONCAT(${t.join(", ")})`},substring(t,e,r){return`SUBSTRING(${t}, ${e}, ${r})`},stringLength(t){return`CHAR_LENGTH(${t})`},regex(t,e,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${t}) REGEXP LOWER(${e})`:`${t} REGEXP ${e}`},arrayContains(t,e){return`JSON_OVERLAPS(${t}, JSON_ARRAY(${e}))`},expandArray(t,e,r){const n=this.quoteIdentifier(e),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},Kp={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Fr{supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{createPool:e}=await import("mysql2/promise").catch(r=>{throw Ze("mysql2",r)});return e({...Kp,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}arrayContains(e,r){const n=X.arrayContains?.bind(X);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n){const o=X.expandArray?.bind(X);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(e,r,n)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async#n(e,r){e.signal?.throwIfAborted();const n=await this.#r();e.signal?.throwIfAborted();const[o]=await n.execute(e.sql,e.parameters);if(e.signal?.throwIfAborted(),r&&typeof o=="object"&&o!==null&&"affectedRows"in o&&typeof o.affectedRows=="number")return{rows:[],affectedRows:o.affectedRows};if(!Array.isArray(o))throw new Error(`${this.kind} provider expected an array result`);return{rows:o}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}class Jp extends Fr{kind="doris";constructor(e={}){super(e)}}class Xp extends Fr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class Zp{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#e.execute(e);if(e.signal?.throwIfAborted(),!Array.isArray(r))throw new Error("MaxCompute provider expected an array result");return r}async runSQL(e){e.signal?.throwIfAborted();const r=this.#e.runSQL?await this.#e.runSQL(e):{rows:await this.execute(e)};return e.signal?.throwIfAborted(),r}async getTableList(e){if(e.signal?.throwIfAborted(),ir(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Le(this,"database"),e.schema!==void 0&&Le(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Ne(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Eo(e),!this.#e.describeTable)return He(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class ef extends Fr{kind="mysql";constructor(e={}){super(e)}}const oa=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Oracle parameter type: ${typeof t}`)},tf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class rf{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return`:${e+1}`}displayQuery(e,r){return Lp(e,r.map(oa))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Oracle aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}arrayContains(e,r){return`JSON_EXISTS(${e}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${e}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#r??=(async()=>{if(this.#t)return this.#t.createPool(this.#e);const{default:e}=await import("oracledb").catch(r=>{throw Ze("oracledb",r)});return e.createPool(this.#e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection(),i=e.signal,s=()=>{o.break().catch(()=>{})};i?.addEventListener("abort",s,{once:!0});try{i?.throwIfAborted();const a=await o.execute(e.sql,e.parameters.map(oa),{outFormat:4002,...r?{autoCommit:!0}:{}});if(i?.throwIfAborted(),!(r&&a.rows===void 0)&&!Array.isArray(a.rows))throw new Error("Oracle provider expected an array result");return{rows:a.rows??[],...typeof a.rowsAffected=="number"?{affectedRows:a.rowsAffected}:{}}}catch(a){throw i?.aborted?tf(i):a}finally{i?.removeEventListener("abort",s),await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}class nf{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{Pool:e}=await import("pg").catch(r=>{throw Ze("pg",r)});return new e(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`$${e+1}`}displayQuery(e,r){return Cp(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported PostgreSQL date shift: ${r}/${n}`);return`(${e} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported PostgreSQL aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS TEXT)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e} FROM ${r} FOR ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${e} ${n==="i"?"~*":"~"} ${r}`}arrayContains(e,r){return`${r} = ANY(${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(e){return(await this.runSQL(e)).rows}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=await r.query(e.sql,[...e.parameters]);if(e.signal?.throwIfAborted(),!Array.isArray(n.rows))throw new Error("PostgreSQL provider expected an array result");return{rows:n.rows,...typeof n.rowCount=="number"&&["INSERT","UPDATE","DELETE","MERGE"].includes(n.command??"")?{affectedRows:n.rowCount}:{}}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}const ia=t=>{if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof t}`)},of=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class sf{kind="snowflake";#e;#t;#r=!1;#n;constructor(e={}){this.#e=e.connection??{},this.#t=e.client?Promise.resolve(e.client):void 0}async#o(){this.#t??=(async()=>{const{default:e}=await import("snowflake-sdk").catch(r=>{throw Ze("snowflake-sdk",r)});return e.createConnection(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return $o(e,r.map(ia))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){return`DATE_PART(${r==="weekday"?"DAYOFWEEKISO":r==="week"?"WEEKISO":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Snowflake date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_VARCHAR(${e})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#s(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){return(await this.#i(e,!1)).rows}async runSQL(e){return this.#i(e,!0)}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async#i(e,r){e.signal?.throwIfAborted(),await this.#s(),e.signal?.throwIfAborted();const n=await this.#o();e.signal?.throwIfAborted();const o=e.parameters.map(ia);return new Promise((i,s)=>{const a=e.signal,u={};let c=!1;const p=f=>{c||(c=!0,a?.removeEventListener("abort",l),f())},l=()=>{u.current?.cancel(),a&&p(()=>s(of(a)))};a?.addEventListener("abort",l,{once:!0}),u.current=n.execute({sqlText:e.sql,binds:o,complete:(f,m,y)=>{if(f){p(()=>s(f));return}if(!(r&&y===void 0)&&!Array.isArray(y)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const h=r?m.getNumUpdatedRows?.():void 0;p(()=>i({rows:y??[],...typeof h=="number"&&h>=0?{affectedRows:h}:{}}))}}),a?.aborted&&l()})}async close(){if(!this.#r)return;const e=await this.#o();await new Promise((r,n)=>{e.destroy(o=>{if(o){n(o);return}this.#r=!1,this.#n=void 0,this.#t=void 0,r()})})}}const af=t=>{const{host:e,server:r,options:n,pool:o,...i}=t;return{...i,server:r??e??"localhost",port:t.port??1433,requestTimeout:t.requestTimeout??6e4,connectionTimeout:t.connectionTimeout??3e4,options:{encrypt:!1,trustServerCertificate:!0,enableArithAbort:!0,...n},pool:{max:10,min:0,idleTimeoutMillis:3e4,...o}}},cf=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported SQL Server parameter type: ${typeof t}`)},uf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),df=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),lf=t=>{let e=0,r;for(let n=0;n<t.length;n+=1){const o=t[n];if(o){if(r){o===r&&(t[n+1]===r?n+=1:r=void 0);continue}if(o==="'"||o==='"')r=o;else if(o==="[")r="]";else if(o==="(")e+=1;else if(o===")")e=Math.max(0,e-1);else if(e===0&&/^ORDER\s+BY\b/i.test(t.slice(n)))return!0}}return!1};class pf{kind="sqlserver";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e=this.#t??await import("mssql").then(n=>n.default,n=>{throw Ze("mssql",n)}),r=new e.ConnectionPool(af(this.#e));return await r.connect(),r})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`[${e.replaceAll("]","]]")}]`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${lf(e)?e:`${e} ORDER BY (SELECT NULL)`} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`}parameter(e,r){return`@p${e}`}displayQuery(e,r){return Up(e,r)}dateBucket(e,r){const n=new Set(["second","minute","hour","day","month","quarter","year"]);if(r==="week")return`DATEADD(DAY, -(((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7), CAST(${e} AS DATE))`;if(!n.has(r))throw new Error(`Unsupported SQL Server date level: ${r}`);const o=r==="second"||r==="minute"?"'20000101'":"0";return`DATEADD(${r.toUpperCase()}, DATEDIFF(${r.toUpperCase()}, ${o}, ${e}), ${o})`}datePart(e,r){return r==="weekday"?`((((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7) + 1)`:`DATEPART(${r==="week"?"ISO_WEEK":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported SQL Server date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS DATETIME2)`:r==="date"?`CAST(${e} AS DATE)`:r==="string"?`CAST(${e} AS NVARCHAR(MAX))`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported SQL Server aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS NVARCHAR(MAX))`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LEN(${e})`}regex(e,r,n){throw new Error("SQL Server does not provide a native regular-expression predicate")}arrayContains(e,r){return`EXISTS (SELECT 1 FROM OPENJSON(${e}) AS [semanticdb_array] WHERE [semanticdb_array].[value] = ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`CROSS APPLY OPENJSON(${e}) AS ${o}`,valueExpression:`${o}.[value]`}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return ft(this,e)}describeTable(e){return He(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=n.request();return e.parameters.forEach((i,s)=>o.input(`p${s}`,cf(i))),new Promise((i,s)=>{const a=e.signal;let u=!1;const c=l=>{u||(u=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&c(()=>s(uf(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){c(()=>s(new Error("SQL Server provider expected an array result")));return}c(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((f,m)=>f+m,0)}:{}}))},l=>c(()=>s(df(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class ff extends Fr{kind="starrocks";constructor(e={}){super(e)}}const Ce=t=>{const{id:e,kind:r,...n}=t;return n},mf=Object.freeze([{kind:"mysql",create:t=>new ef({connection:Ce(t)})},{kind:"doris",create:t=>new Jp({connection:Ce(t)})},{kind:"gbase",create:t=>new Xp({connection:Ce(t)})},{kind:"starrocks",create:t=>new ff({connection:Ce(t)})},{kind:"maxcompute",create:t=>new Zp(Ce(t))},{kind:"postgresql",create:t=>new nf({connection:Ce(t)})},{kind:"clickhouse",create:t=>new Yp(Ce(t))},{kind:"databricks",create:t=>new Gp({connection:Ce(t)})},{kind:"dameng",create:t=>new zp({connection:Ce(t)})},{kind:"snowflake",create:t=>new sf({connection:Ce(t)})},{kind:"sqlserver",create:t=>new pf({connection:Ce(t)})},{kind:"oracle",create:t=>new rf({connection:Ce(t)})}]);class sa{#e=new Map;constructor(e=mf){e.forEach(r=>this.register(r))}register(e){if(!e.kind)throw new d("INVALID_PROVIDER","Provider kind must not be empty");if(this.#e.has(e.kind))throw new d("PROVIDER_ALREADY_REGISTERED",`Provider is already registered: ${e.kind}`,{provider:e.kind});return this.#e.set(e.kind,e),this}create(e){const r=this.#e.get(e.kind);if(!r)throw new d("PROVIDER_NOT_FOUND",`Provider is not registered: ${e.kind}`,{provider:e.kind});return r.create(e)}has(e){return this.#e.has(e)}}const aa=new sa,ca=(t,e=aa)=>e.create(t);class yf{create;#e=new Map;constructor(e=ca){this.create=e}get(e){const r=this.#e.get(e.id);if(r){if(!Mo.isDeepStrictEqual(r.connection,e))throw new d("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${e.id}`,{connectionId:e.id});return r.provider}const n=this.create(e);return this.#e.set(e.id,{connection:e,provider:n}),n}async close(){const e=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(e.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Yr=new Map,hf=t=>{const e=Yr.get(t);if(e)return e;const r=new yf(n=>ca(n,t));return Yr.set(t,r),r},vr=(t,e=aa)=>hf(e).get(t),gf=async()=>{const t=[...Yr.values()];Yr.clear();const r=(await Promise.allSettled(t.map(async n=>n.close()))).flatMap(n=>n.status==="rejected"?[n.reason]:[]);if(r.length>0)throw new AggregateError(r,"Failed to close one or more connection registries")},ua=async()=>{const e=(await Promise.allSettled([gf(),fp()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},Af=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=vr(t.connection,t.providerRegistry);if(!e.runSQL)throw new d("UNSUPPORTED_RAW_SQL",`Provider does not support native SQL: ${e.kind}`);const r=await e.runSQL({sql:t.sql,parameters:t.parameters??[],...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},wf=async t=>{t.signal?.throwIfAborted(),ir(t);const e=vr(t.connection,t.providerRegistry);if(!e.getTableList)throw new d("UNSUPPORTED_TABLE_DISCOVERY",`Provider does not support table discovery: ${e.kind}`);const r=await e.getTableList({...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},$f=async t=>{t.signal?.throwIfAborted(),Eo(t);const e=vr(t.connection,t.providerRegistry);if(!e.describeTable)throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`Provider does not support table description: ${e.kind}`);const r=await e.describeTable({table:t.table,...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.includeSample!==void 0?{includeSample:t.includeSample}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Ef=Object.freeze({runSQL:Af,getTableList:wf,describeTable:$f,close:ua}),_f=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:de.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:de.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:de.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:de.VARCHAR,sqlType:"VARCHAR"}}},Sf=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,If=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return de.jsToDuckDBValue(Sf(t),de.BOOLEAN);case"date":{const r=t instanceof Date?t:new Date(typeof t=="number"||typeof t=="string"?t:Number.NaN);return Number.isNaN(r.getTime())?null:de.jsToDuckDBValue(r,de.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?de.jsToDuckDBValue(r,de.DOUBLE):null}case"string":return typeof t=="string"?de.jsToDuckDBValue(t,de.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?de.jsToDuckDBValue(t.toString(),de.VARCHAR):typeof t=="symbol"?de.jsToDuckDBValue(t.description??"",de.VARCHAR):typeof t=="function"?de.jsToDuckDBValue(t.name,de.VARCHAR):de.jsToDuckDBValue(JSON.stringify(t),de.VARCHAR)}},bf=t=>{if(t==null)return null;if(t instanceof Date)return de.jsToDuckDBValue(t,de.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return de.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class Kr{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await de.DuckDBInstance.create(":memory:"),r=await e.connect();return new Kr(e,r)}constructor(e,r){this.instance=e,this.connection=r}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return $o(e,r)}dateBucket(e,r){return`DATE_TRUNC('${r.replaceAll("'","''")}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){return`(${e} + INTERVAL '${n} ${r.replaceAll("'","''")}')`}datePeriodBoundary(e,r,n){const o=this.dateBucket(e,r);return n==="start"?o:`(${o} + INTERVAL '1 ${r.replaceAll("'","''")}' - INTERVAL '1 microsecond')`}castValue(e,r){return`CAST(${e} AS ${r==="timestamp"?"TIMESTAMP":r==="date"?"DATE":"VARCHAR"})`}scalarExtremum(e,r){return`${e.toUpperCase()}(${r.join(", ")})`}aggregateFunction(e,r){const n={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"};if(e==="countDistinct")return`COUNT(DISTINCT ${r??"*"})`;const o=n[e];if(!o)throw new Error(`Unsupported DuckDB aggregate: ${e}`);return`${o}(${r??"*"})`}stringify(e){return`CAST(${e} AS VARCHAR)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){return n?`REGEXP_MATCHES(${e}, ${r}, '${n.replaceAll("'","''")}')`:`REGEXP_MATCHES(${e}, ${r})`}arrayContains(e,r){return`LIST_CONTAINS(${e}, ${r})`}async materialize(e,r,n){const o=r.map(_f),i=o.map(a=>`${this.quoteIdentifier(a.name)} ${a.sqlType}`).join(", ");await this.connection.run(`CREATE TABLE ${this.quoteIdentifier(e)} (${i})`);const s=await this.connection.createAppender(e);try{for(const a of n){for(const u of o){const c=If(a[u.name],u);c===null?s.appendNull():s.appendValue(c,u.type)}s.endRow()}s.flushSync()}finally{s.closeSync()}}async execute(e){e.signal?.throwIfAborted();const r=await this.connection.runAndReadAll(e.sql,e.parameters.map(bf));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const So="__sdb_total__",Rf="__sdb_total_source__",Io=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Nf=t=>{const e={...t};return delete e.limit,delete e.page,e},bo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(So)} FROM ${e.tableAlias(`(${t.sql})`,Rf)}`,parameters:t.parameters}),Qr=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[So]??e[So.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new d("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},kt="__semanticdb_coordinator__",da=(t,e)=>{const r=new Set;for(const n of $e(t)){const o=e.findSource(n.schemaId,n.source,n.connectionId);if(!o)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${n.schemaId}:${n.source}`,{schemaId:n.schemaId,source:n.source});r.add(o.connectionId)}return[...r]},sr=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>da(r,e))).size>1||!!(t.sourcePlan&&sr(t.sourcePlan,e)),Of=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Tf=(t,e)=>{const r=t.map(n=>n[e]).find(n=>n!=null);return typeof r=="number"||typeof r=="bigint"?"number":typeof r=="boolean"?"boolean":r instanceof Date?"date":"string"},la=(t,e)=>{const r=new Map((t.columnProperties??[]).map(n=>[n.name,n]));return[...t.projections.map(({name:n})=>n),"_id"].map(n=>{const o=r.get(n),i=n==="_id"?"string":o?.primal_type==="number"?"number":o?.primal_type==="boolean"?"boolean":o?.primal_type==="date"?"date":o?.primal_type==="entity"||o?.primal_type==="object"?Tf(e,n):"string";return{name:n,kind:i}})},Pf=(t,e)=>{const r=t.projections.map(({name:n})=>n);return{schemaId:t.schemaId,source:e,sourceAlias:e,fields:Object.fromEntries([...r,"_id"].map(n=>[n,n])),projections:[...r,"_id"].map(n=>Of(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Lf=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:JSON.stringify(r.names.map(o=>{const i=n[o];return i==null?["null"]:i instanceof Date?["date",i.toISOString()]:typeof i=="bigint"?["bigint",i.toString()]:typeof i=="object"?"_id"in i||"id"in i?["entity",Tr(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new d("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},pa=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:zn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},Hr=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&sr(t.sourcePlan,e.schemaMappings)){const s=await Hr(t.sourcePlan,e),a=await Kr.create();try{const u="__federated_source";await a.materialize(u,la(t.sourcePlan,s.rows),s.rows);const c={...t,source:u};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const p=ye(c,a,e.operators),l=bo(ye(Io(c),a,e.operators),a);e.onCompiled({compiled:p,connectionId:kt,provider:a,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:l,connectionId:kt,provider:a,type:"total",logicform:e.logicform});const f=await a.execute({...l,...e.signal?{signal:e.signal}:{}}),m=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:pa(m,t),total:Qr(f),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new d("INVALID_FEDERATED_PLAN","A federated composition requires at least two child plans");const r=new Map,n=await Promise.all(t.subplans.map(async s=>{const a=da(s,e.schemaMappings);if(a.length!==1)throw new d("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const p=ye(s,c,e.operators);e.onCompiled({compiled:p,connectionId:u,provider:c,type:"computation",logicform:e.logicform});const l=await Re(p,$e(s),{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}}),f=await ct(l,s.projections,e.operators);return{child:s,rows:Lf(f,s)}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new d("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await Kr.create();try{const s=n.flatMap(({rows:m})=>m),a=[];for(const[m,{child:y,rows:h}]of n.entries()){const g=`__federated_branch_${m}`;await i.materialize(g,la(y,s),h),a.push(Pf(y,g))}const u={...t,subplans:a},c=ye(u,i,e.operators),p=bo(ye(Io(u),i,e.operators),i);e.onCompiled({compiled:c,connectionId:kt,provider:i,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:p,connectionId:kt,provider:i,type:"total",logicform:e.logicform});const l=await i.execute({...p,...e.signal?{signal:e.signal}:{}}),f=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:pa(f,t),total:Qr(l),connections:[...r].map(([m,y])=>({connectionId:m,provider:y}))}}finally{await i.close()}},Cf=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),Ro=t=>!W(t)||!Array.isArray(t.properties)?[]:t.properties.filter(W),Df=(t,e)=>{const r=e[t];return W(r)?r:Object.values(e).find(n=>W(n)&&(n.id===t||n._id===t))},fa=(t,e,r)=>{const n=Df(t,r);if(!n)return;const i=Ro(n).map(s=>{const u=[s.id,s._id,s.name].filter(c=>typeof c=="string").filter(c=>e===c||e.startsWith(`${c}_`)).sort((c,p)=>p.length-c.length)[0];return u?{property:s,key:u}:void 0}).filter(s=>s!==void 0).sort((s,a)=>a.key.length-s.key.length)[0];if(i)return e===i.key?i.property:typeof i.property.ref=="string"?fa(i.property.ref,e.slice(i.key.length+1),r):void 0},Ut=(t,e,r)=>{const n=(o,i,s)=>{const c=Ro(r[o]).map(y=>{const h=typeof y.id=="string"?y.id:void 0,g=typeof y.name=="string"?y.name:void 0,E=[h,g].filter(S=>!!S&&(i===S||i.startsWith(`${S}_`))).sort((S,w)=>w.length-S.length)[0];return E?{property:y,key:E}:void 0}).filter(y=>!!y).sort((y,h)=>h.key.length-y.key.length)[0];if(!c)return;const p=String(c.property.id??c.property.name),l=i===c.key?"":i.slice(c.key.length+1);if(!l)return p;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,l,new Set(s).add(f));return m?`${p}_${m}`:void 0};return n(t,e,new Set([t]))},No=(t,e,r)=>{const n=Ro(r[t]).filter(o=>typeof o.id=="string").sort((o,i)=>String(i.id).length-String(o.id).length).find(o=>e===o.id||e.startsWith(`${String(o.id)}_`));if(!(!n||typeof n.id!="string")){if(e===n.id)return n.id;if(typeof n.ref=="string")return No(n.ref,e.slice(n.id.length+1),r)}},ma=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),W=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ya=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),ha=t=>{if(!W(t))return t;if(W(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return t},kf=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),Uf=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>W(u)&&(u.id===t||u._id===t));if(!W(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:W(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!W(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?W(s)&&s.use_full_length===!0?"zero-padded":"compact":W(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},Mf=(t,e,r)=>{const n=Uf(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new d("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},qf=(t,e)=>e.length===0?t:e.length===1&&t.$expr===void 0?{...t,$expr:e[0]}:{$and:[...Object.keys(t).length>0?[t]:[],...e.map(n=>({$expr:n}))]},Oo=(t,e)=>{const r={},n=[];for(const[o,i]of Object.entries(t)){if((o==="$and"||o==="$or")&&Array.isArray(i)){r[o]=i.map(y=>W(y)?Oo(y,e):y);continue}if(!W(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!W(i.query)||!kf(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:Mf(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:p,...l}=i,f=Oo(i.query,e),m=Object.keys(l).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...l,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return qf(r,n)},jf=(t,e)=>{const n=t&&({$sply:"$periodShift",$splm:"$periodShift",$splq:"$periodShift",$splw:"$periodShift",$yoy:"$periodGrowth",$mom:"$periodGrowth",$qoq:"$periodGrowth",$wow:"$periodGrowth",$yoyd:"$periodDifference",$momd:"$periodDifference",$qoqd:"$periodDifference",$wowd:"$periodDifference",$dailyavg:"$averagePerPeriod",$weeklyavg:"$averagePerPeriod",$monthlyavg:"$averagePerPeriod",$startOfPeriod:"$periodValue",$endOfPeriod:"$periodValue",$dateLevel:"$dateBucket",$uniq:"$countDistinct",$percentage:"$shareOfTotal"}[t]??t),o={...e};return t==="$sply"||t==="$yoy"||t==="$yoyd"?o.time??={granularity:"year",offset:-1}:t==="$splm"||t==="$mom"||t==="$momd"?o.time??={granularity:"month",offset:-1}:t==="$splq"||t==="$qoq"||t==="$qoqd"?o.time??={granularity:"quarter",offset:-1}:t==="$splw"||t==="$wow"||t==="$wowd"?o.time??={granularity:"week",offset:-1}:t==="$dailyavg"?o.granularity??="day":t==="$weeklyavg"?o.granularity??="week":t==="$monthlyavg"?o.granularity??="month":t==="$startOfPeriod"?o.boundary??="start":t==="$endOfPeriod"&&(o.boundary??="end"),{...n?{operator:n}:{},args:o}},ga=(t,e)=>{if(!W(e)||!Array.isArray(e.cases)||e.cases.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} requires a non-empty params.cases array`);return{cases:e.cases.map((n,o)=>{if(!W(n))throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} must be an object`);if(n.sql!==void 0)throw new d("LEGACY_CASE_SQL_UNSUPPORTED",`${t} case.sql cannot be migrated to the structured v2 $case operator`);if(!W(n.query)||typeof n.name!="string"||n.name.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} requires query and a non-empty name`);return{when:n.query,then:n.name}}),...Object.hasOwn(e,"default")?{default:e.default}:{}}},Ge=(t,e,r)=>{if(Array.isArray(t))return t.map(u=>Ge(u,e,r));if(!W(t))return t;const n=ha(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[u,c]of Object.entries(o))u==="skip"||u==="_snapshot"||u==="_snapshots"||(s[u]=Ge(c,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const u=o.groupby;s.groupby=u.map(c=>{if(!W(c))return c;const p=Ge(c,e,i);if(!W(p))return p;const{_id:l,level:f,...m}=p,y={...m,...m.pred===void 0&&typeof l=="string"?{pred:l}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...W(y.args)?y.args:{},granularity:f}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const u=o.limit;a===0?delete s.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&a%u===0?s.page=a/u+1:s.skip=a}else a!==void 0&&(s.skip=Ge(a,e,i));if(o.operator&&typeof o.operator=="string"){const u=jf(o.operator,W(s.args)?s.args:{});if(u.operator&&(s.operator=u.operator),s.args=u.args,o.operator==="$comp"||o.operator==="$compabs"){const c=W(s.args)?s.args.preds:void 0;if(!Array.isArray(c)||c.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const p={operator:"$subtract",pred:c,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?p:c,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const c=W(s.params)?s.params:s.args;s.operator="$case",s.args=ga("$switch",c),delete s.params}if(o.operator==="$piecewise"){const c=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&c&&fa(i,c,e)?.cases!==void 0)throw new d("LEGACY_PIECEWISE_PROPERTY_CASES_UNSUPPORTED","$piecewise property cases contain trusted SQL and cannot be migrated safely to v2 $case",{schemaId:i,property:c});const p=W(s.params)?s.params:W(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(p.cases)?ga("$piecewise",p):{mode:"auto",buckets:Number.isInteger(p.buckets)?p.buckets:10},delete s.params}Cf.has(o.operator)&&typeof s.pred=="string"&&(s.pred={operator:"$sum",pred:s.pred})}return o.params!==void 0&&s.args===void 0&&(s.args=Array.isArray(o.params)?{values:Ge(o.params,e,i)}:Ge(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(u=>Ge(u,e,i)),W(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...W(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...W(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&ya(o.$gte)&&ya(o.$lte)&&delete s.$options,o.query&&W(o.query)&&(s.query=xf(o.query,e,i)),s},xf=(t,e,r)=>{const n=Ge(t,e,r);for(const[o,i]of Object.entries(n))n[o]=ha(i);return Oo(n,e)},Aa=(t,e)=>{const r=W(t)?t:void 0,n=Ge(t,e);if(!W(n))return n;if(r&&typeof r.operator=="string"&&r.preds===void 0){const o={};for(const a of["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],Aa(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Bf(n,e):n},Bf=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)W(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>W(u)&&typeof u.pred=="string"?Ut(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,p)=>{if(!W(c)||typeof c.pred!="string")return c;const l=u===o?Ut(u,c.pred,e):Ut(u,No(o,s[p]??"",e)??c.pred,e);if(!l)return c;const f=l.split("_").at(-1)??c.pred;return{...c,pred:l,name:f}}),W(r.query))for(const c of ma(r.query)){const p=Ut(o,c,e);if(!(u===o?p:Ut(u,(p&&No(o,p,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!W(u)||typeof u.pred!="string")return u;const p=s[c];return p?{...u,pred:p}:u})),W(r.query)){const u=r.query,c=ma(u).map(p=>[Ut(o,p,e)??p,u[p]]);a.query=Object.fromEntries(c)}return a},Vf=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(W(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs","entity_level","entity_codelength"].includes(o))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},To=t=>{if(Array.isArray(t))return t.map(To).filter(n=>n!==void 0);if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return t;const e=Object.entries(t),r=e.filter(([,n])=>n!==null).map(([n,o])=>[n,To(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Ff=t=>{if(t.comparable!=null)return t.comparable;if(t.is_comparable!==!0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!Array.isArray(t.constraints?.enum))return;const r=t.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:t.comparable_order===-1?-1:1}},Yf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=t;if(e.sql!=null)return Object.keys(e).every(r=>r==="sql")?t:{sql:e.sql}},vf=(t,e=[],r=!0)=>{const n=fe(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=To(a),c=u,l=(Array.isArray(c.properties)?c.properties:[]).some(S=>S.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:y}=u,h=Object.fromEntries(Object.entries(u).filter(([S])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(S):S!=="properties")&&S!=="properties"&&!i.has(S))),g=y.map(S=>{const w=S,A=typeof w.id=="string"&&w.id.length>0?w.id:r&&typeof w._id=="string"&&w._id.length>0?w._id:w.id,{udf:R,...T}=w,P=Ff(w),x=Yf(R),K=P!==void 0&&w.comparable==null?"category":w.type==="object"?"entity":w.type;return{...r?Object.fromEntries(Object.entries(T).filter(([Q])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(Q))):T,type:K,...w.primal_type==="object"?{primal_type:"entity"}:{},...A!==void 0?{id:A}:{},...x!==void 0?{udf:x}:{},...P!==void 0?{comparable:P}:{}}});let _={};for(const S of n)for(const w of S.schemaMetadata?.keys??[])u[w]!==void 0&&(_={..._,[w]:u[w]});for(const S of n)_={..._,...S.normalizeLegacySchema?.({source:u,properties:g})};const E={...h,...m!==void 0?{id:m}:{},properties:g,...r&&(f||l)?{temporalSemantics:"snapshot"}:{},..._};o[s]=E}return o},wa=(t,e)=>[...fe(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Gr=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),$a=t=>t instanceof Error?t:new Error(String(t)),Qf=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,Hf=(t,e,r={},n="zh-CN",o)=>{const i=$a(t);return{errorCode:"100",error:Qf(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},Gf=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,p)=>{const l=r.parameter(i.length,p);i.push(p);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(l,f):l},a=c=>`SELECT ${n.map(p=>`${s(p,c[p])} AS ${r.quoteIdentifier(p)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Wf=(t,e,r)=>{if(t.length<2||t.some(i=>i.kind==="js"||i.kind==="query"&&i.unit.mapResult))return!1;const n=new Set,o=[...t.flatMap(({sources:i})=>i),...$e(r)];for(const i of o){const s=go(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},zf=async(t,e,r)=>{await t?.({...e,partialResult:r})},Kf=(t,e,r,n,o,i,s=r,a)=>({type:r,...a?{connectionId:a}:{},provider:e.kind,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="auto-case"?"sql.autoCase":s==="entity-expansion"?"sql.entityExpansion":s==="total"?"sql.total":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),Po=(t,e)=>{if(e.connectionId)for(const r of $e(t)){const n=go(r,e.schemaMappings);if(!n)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${r.schemaId}:${r.source}`,{schemaId:r.schemaId,source:r.source});if(n.connectionId!==e.connectionId)throw new d("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One physical query cannot use multiple database connections: ${e.connectionId}, ${n.connectionId}`,{schemaId:r.schemaId,source:r.source,connectionId:n.connectionId})}},Jf=t=>{const e=new Set,r=n=>{n.from&&r(n.from),n.schema&&e.add(n.schema);for(const o of n.preds??[])for(const i of Lo(o))e.add(i)};return r(t),[...e]},Lo=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...Lo(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:Lo(r))]:e},Ea=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??pr(wa(e.plugins,e.locales)),o=e.plugins??[],i=t.version,s=typeof i=="string"&&(/^2\./.test(i)||/^[3-9]\d*\./.test(i)),a=i===void 0||typeof i=="string"&&/^1\./.test(i);s&&Vf(t);const u=a?Aa(t,e.schemas):t,c={...e,locale:r,localeRegistry:n,schemas:vf(e.schemas,o,a)},p=Zr.performance.now(),l=c.semanticTypes===void 0?oo(o):c.semanticTypesResolved?c.semanticTypes:Es(c.semanticTypes,o);let f=c.operators??De(o);if(c.operators&&!c.operatorsResolved)for(const D of o)for(const k of D.operators??[])if(f.has(k.name)){if(f.get(k.name)!==k)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${k.name}`,{operator:k.name,plugin:D.name})}else f.register(k);const m=c.schemaMappings,y=new Date,h=new Map,g=new Map,_=[],E=new Set,S=D=>{const k=JSON.stringify(D);E.has(k)||(E.add(k),_.push(D),w={...w,schemaMappingSelections:[..._]})};let w={provider:c.provider.kind};const A=[],R=new Map;c.connectionId&&R.set(c.connectionId,c.provider.kind);const T=(D,k,Y,$=k,I=c.provider,b=c.connectionId)=>{b&&b!==kt&&R.set(b,I.kind),A.push(Kf(Hs(D),I,k,Y,c.locale??"zh-CN",n,$,b)),w={...w,sqls:[...A],providers:[...R].map(([N,L])=>({connectionId:N,provider:L}))}},P=async(D,k={})=>{w={...w,...k},await zf(c.onProgress,D,w)},x=D=>hs(dc(D,c.schemas),l,o),K=new Map,B=D=>{const k=K.get(D);return k||(Qe(c.permissions,D),x(D))},Q=D=>{if(D.schema)return B(D.schema);if(D.from)return Q(D.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},U=D=>{if(D.schema)return x(D.schema);if(D.from)return U(D.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},z=async()=>{const D=Object.values(c.schemas).filter(M=>M.is_calendar===!0);if(D.length!==1)return Object.freeze({});const k=D[0];if(!k)return Object.freeze({});const Y=m.list(k.id),$=Y.find(({connectionId:M})=>M===c.connectionId)??Y[0];if(!$)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${k.id}`,{schemaId:k.id});const I=c.providerForConnection?.($.connectionId)??c.provider,{onProgress:b,executionContext:N,...L}=c,V=await Ea({version:"2.0",schema:k.id,limit:-1},{...L,provider:I,connectionId:$.connectionId,operators:f,operatorsResolved:!0,executionContext:Object.freeze({})});A.push(...V.sqls.map(M=>({...M,type:"semantic-resolution",explain:n.translate(c.locale??"zh-CN","sql.semanticResolution")})));for(const M of V.providers)R.set(M.connectionId,M.provider);for(const M of V.schemaMappingSelections)S(M);return Object.freeze({calendar:Object.freeze(V.result.map(({_id:M,...ne})=>Object.freeze(ne)))})},ue=e.executionContext??await z();f=f.withExecutionContext(ue);const J={plugins:o,resolveSchema:B,onSchemaMappingSelection:S,...c.connectionId?{preferredConnectionId:c.connectionId}:{},canUsePropertyRowIdentity:(D,k)=>lt(c.permissions,D.id,k)},le=(D,k)=>{const Y=Hi(Pe(D,Q(D),f,m,J),k);return K.set(Y.id,Y),Y},Oe=async(D,k,Y)=>{const $=`${D.id}:${k.id}:${Y.toISOString()}`,I=h.get($);if(I)return I;const b=(async()=>{const N=fe(o).find(q=>q.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!N)return;const L=N({logicform:u,rootSchema:D,rootProperty:k,requestedUpperBound:Y,now:y,...c.timeWatermark?{defaultPolicy:c.timeWatermark}:{},resolveSchema:B,inferPropertyPath:(q,me,ie)=>Ms(q,me,ie,B)}),V=pt(L,c.permissions,B,!1,new Set,o),M=await dt(V,D,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,resolveFromSchema:le}),ne=Pe(M,D,f,m,J);let C;if(sr(ne,m)){const q=c.providerForConnection;if(!q)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");C=(await Hr(ne,{logicform:M,operators:f,schemaMappings:m,providerForConnection:q,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:ie,logicform:Ae,provider:Te,connectionId:et})=>T(ie,"semantic-resolution",Ae,"time-watermark",Te,et)})).rows}else{Po(ne,c);const q=ye(ne,c.provider,f);T(q,"semantic-resolution",M,"time-watermark"),C=await Re(q,$e(ne),c)}const ee=C[0]?.__timeWatermark__??Object.values(C[0]??{})[0];if(ee==null||!(ee instanceof Date)&&typeof ee!="string"&&typeof ee!="number")return;const H=ee instanceof Date?ee:new Date(ee);return Number.isNaN(H.getTime())?void 0:H})();return h.set($,b),b},ke=async(D,k,Y)=>{const $=JSON.stringify([D.id,k,Y??null]),I=g.get($);if(I)return I;const b=(async()=>{const N={version:"2.0",schema:D.id,...Y?{query:Y}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:k},{name:"__autoCaseMax__",operator:"$max",pred:k},{name:"__autoCaseCount__",operator:"$count",pred:k}]},L=await dt(N,D,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,resolveFromSchema:le}),V=Pe(L,D,f,m,J);let M;if(sr(V,m)){const Ae=c.providerForConnection;if(!Ae)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");M=(await Hr(V,{logicform:L,operators:f,schemaMappings:m,providerForConnection:Ae,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:et,logicform:tt,provider:We,connectionId:he})=>T(et,"semantic-resolution",tt,"auto-case",We,he)})).rows}else{Po(V,c);const Ae=ye(V,c.provider,f);T(Ae,"semantic-resolution",L,"auto-case"),M=await Re(Ae,$e(V),c)}const ne=M[0],C=ne?.__autoCaseMin__,ee=ne?.__autoCaseMax__,H=ne?.__autoCaseCount__;if(C==null||ee===null||ee===void 0||H===null||H===void 0||Number(H)===0)return{empty:!0};const q=Number(C),me=Number(ee),ie=Number(H);if(!Number.isFinite(q)||!Number.isFinite(me)||!Number.isSafeInteger(ie)||ie<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:C,max:ee,count:H});return{min:q,max:me,count:ie}})();return g.set($,b),b};try{c.signal?.throwIfAborted(),io(u),await P({stage:"started",logicform:u}),Zl(c.permissions,x);const D=Q(u);await P({stage:"validated",schema:D});const k=pt(u,c.permissions,B,!0,new Set,o),Y=await dt(k,D,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,resolveFromSchema:le,canProjectProperty:(O,j)=>lt(c.permissions,O.id,j),requestTimeWatermark:Oe,requestAutoCaseBounds:ke});await P({stage:"normalized",normedLogicform:Y},{normedLogicform:Y});const $=Pe(Y,D,f,m,J),I=sr($,m);I||Po($,c);const b=$.columnProperties??[],N=Qi($,D);K.set(N.id,N),await P({stage:"planned",plan:$},{schema:N});const L=Ui($,D,c.provider,f,c.providerForConnection);if(await P({stage:"lineage",lineage:L},{lineage:L}),I){const O=c.providerForConnection;if(!O)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const j=await Hr($,{logicform:Y,operators:f,schemaMappings:m,providerForConnection:O,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:Ee,type:se,logicform:re,provider:we,connectionId:pe})=>T(Ee,se,re,se,we,pe)});await P({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await P({stage:"executing",provider:"duckdb",connectionId:kt}),await P({stage:"hydrating"});const G=j.connections.length===1?j.connections[0]?.connectionId:void 0,v=await Js(j.rows,b,{semanticTypes:l,plugins:o,resolveSchema:B,fetchEntities:Ee=>Gs(Ee,{version:Y.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,providerForConnection:O,...G?{preferredConnectionId:G}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(se,re,we,pe)=>T(se,"semantic-resolution",re,"entity-expansion",we,pe)})}),Z=Kn(v,$.rowIdentity);return await P({stage:"result",result:Z},{result:Z,total:j.total,sqls:[...A],providers:j.connections}),await P({stage:"completed",durationMs:Zr.performance.now()-p}),{result:Z,total:j.total,schema:N,normedLogicform:Y,sqls:[...A],lineage:L,provider:"duckdb",providers:j.connections,schemaMappingSelections:[..._]}}const V=Pr(Y,$,D,f,B,void 0,r,n.translator(r)),M=async(O,j)=>{const G=j&&O.logicform.schema===j.id?j:Q(O.logicform),v=O.prepare?await dt(pt(O.logicform,c.permissions,B,!0,new Set,o),G,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,resolveFromSchema:le,canProjectProperty:(se,re)=>lt(c.permissions,se.id,re),requestTimeWatermark:Oe}):O.logicform,Z=Pe(v,G,f,m,J),Ee=Pr(v,Z,G,f,B,O.logicform,r,n.translator(r));if(Ee){if(Ee.length!==1)throw new Error("A generated component must produce exactly one execution unit");const se=Ee[0];if("logicform"in se){const pe=await M(se,G),mt=pe.component.mapResult,Ve=O.mapResult;return{...pe,component:{...O,logicform:pe.component.logicform,...mt||Ve?{mapResult:Fe=>{const rt=mt?.(Fe)??[...Fe];return Ve?.(rt)??[...rt]}}:{}}}}if("mergeRow"in se)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const re=await Promise.all(se.components.map(async pe=>({name:pe.name,prepared:await M(Gr(pe)),...pe.groupKeyShifts?{groupKeyShifts:pe.groupKeyShifts}:{},...pe.joinKeys?{joinKeys:pe.joinKeys}:{}}))),we=Or(se,re.map(({name:pe,prepared:mt,...Ve})=>({name:pe,plan:mt.plan,...Ve})),Z,se.outputName,c.provider,f);return{component:{...O,logicform:v},plan:Z,compiled:we,sources:nr(re.map(({prepared:pe})=>pe.sources))}}return{component:{...O,logicform:v},plan:Z,compiled:ye(Z,c.provider,f),sources:$e(Z)}},ne=async(O,j)=>{const G=Pr(O,j,Q(O),f,B,void 0,r,n.translator(r));if(!G)return{compiled:ye(j,c.provider,f),sources:$e(j)};const v=await Promise.all(G.map(async Z=>{if("logicform"in Z){const re=await M(Z);return{plan:re.plan,compiled:re.compiled,outputs:re.plan.projections.map(({name:we})=>we).filter(we=>!j.groupBy.some(pe=>pe.name===we))}}if("mergeRow"in Z)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ee=await Promise.all(Z.components.map(async re=>{const we=await M(Gr(re));return{name:re.name,plan:we.plan,...re.joinKeys?{joinKeys:re.joinKeys}:{},...re.groupKeyShifts?{groupKeyShifts:re.groupKeyShifts}:{}}})),se=Or(Z,Ee,j,Z.outputName,c.provider,f);return{plan:j,compiled:se,outputs:[Z.outputName,...Z.components.map(re=>re.name)]}}));return{compiled:Hn(v,j,c.provider,f),sources:nr(v.map(({plan:Z})=>$e(Z)))}},C=new WeakMap,ee=async O=>{if(!O.sourcePlan||!O.sourceLogicform)return ye(O,c.provider,f);const j=U(O.sourceLogicform),G=Pr(O.sourceLogicform,O.sourcePlan,j,f,B,void 0,r,n.translator(r));if(G?.some(re=>"mergeRow"in re)){const re=C.get(O.sourcePlan);if(re){const oe={...O};delete oe.sourcePlan,delete oe.sourceLogicform;const ze=ye({...oe,sourceSql:re.sql,source:O.source},c.provider,f,re.parameters.length);return{sql:ze.sql,parameters:[...re.parameters,...ze.parameters]}}const we=await Promise.all(G.map(async oe=>{if("logicform"in oe)return{kind:"query",unit:oe,prepared:await M(oe,j)};const ze=await Promise.all(oe.components.map(async ge=>({input:ge,prepared:await M(Gr(ge),j)})));return"mergeRow"in oe?{kind:"js",unit:oe,components:ze}:{kind:"component",unit:oe,components:ze,compiled:Or(oe,ze.map(({input:ge,prepared:Ue})=>({name:ge.name,plan:Ue.plan,...ge.joinKeys?{joinKeys:ge.joinKeys}:{},...ge.groupKeyShifts?{groupKeyShifts:ge.groupKeyShifts}:{}})),O.sourcePlan,oe.outputName,c.provider,f)}})),pe=O.sourcePlan.groupBy.map(({name:oe})=>oe),mt=await Promise.all(we.map(async oe=>{if(oe.kind==="query"){T(oe.prepared.compiled,"computation",oe.prepared.component.logicform);const ge=await Re(oe.prepared.compiled,oe.prepared.sources,c),Ue=await ct(ge,oe.prepared.plan.projections,f);return oe.unit.mapResult?.(Ue)??Ue}if(oe.kind==="component")return T(oe.compiled,"computation",O.sourceLogicform),Re(oe.compiled,nr(oe.components.map(({prepared:ge})=>ge.sources)),c);const ze=await Promise.all(oe.components.map(async({input:ge,prepared:Ue})=>{T(Ue.compiled,"computation",Ue.component.logicform);const _a=await Re(Ue.compiled,Ue.sources,c),Do=await ct(_a,Ue.plan.projections,f);return ge.mapResult?.(Do)??Do}));return Promise.all(Xn(ze,pe).map(async ge=>({...ge,[oe.unit.outputName]:await oe.unit.mergeRow(ge)})))})),Ve=Zn(mt,O.sourcePlan),Fe=c.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(Fe)||Fe<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:Fe});if(Ve.length>Fe)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Ve.length} rows; maximum is ${Fe}`,{materializedRowCount:Ve.length,maxMaterializedRows:Fe});const rt=Gf(Ve,O.sourcePlan,c.provider);C.set(O.sourcePlan,rt);const Xr={...O};delete Xr.sourcePlan,delete Xr.sourceLogicform;const Co=ye({...Xr,sourceSql:rt.sql,source:O.source},c.provider,f,rt.parameters.length);return{sql:Co.sql,parameters:[...rt.parameters,...Co.parameters]}}const v=await ne(O.sourceLogicform,O.sourcePlan),Z={...O};delete Z.sourcePlan,delete Z.sourceLogicform;const Ee={...Z,sourceSql:v.compiled.sql,source:O.source},se=ye(Ee,c.provider,f,v.compiled.parameters.length);return{sql:se.sql,parameters:[...v.compiled.parameters,...se.parameters]}},H=V?await Promise.all(V.map(async O=>{if("logicform"in O)return{kind:"query",unit:O,...await M(O)};const j=await Promise.all(O.components.map(async v=>({name:v.name,prepared:await M(Gr(v)),...v.groupKeyShifts?{groupKeyShifts:v.groupKeyShifts}:{},...v.joinKeys?{joinKeys:v.joinKeys}:{}})));if("mergeRow"in O)return{kind:"js",unit:O,components:j.map(({prepared:v})=>v)};const G=j.map(({name:v,prepared:Z,...Ee})=>({name:v,plan:Z.plan,...Ee}));return{kind:"component",unit:O,plan:$,compiled:Or(O,G,$,O.outputName,c.provider,f),sources:nr(j.map(({prepared:v})=>v.sources))}})):void 0,q=H&&Wf(H,m,$)?H.map(O=>{const j=new Set($.groupBy.map(({name:v})=>v));if(O.kind==="query")return{plan:O.plan,compiled:O.compiled,outputs:O.plan.projections.map(({name:v})=>v).filter(v=>!j.has(v))};const G=O.unit.outputName;if(!G)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:O.plan,compiled:O.compiled,outputs:[G,...O.unit.components.map(v=>v.name)]}}):void 0,me=q?Hn(q,$,c.provider,f):void 0,ie=H?void 0:await ee($),Ae=Io($),Te=$.pagination&&(me||ie)?bo(q?Hn(q,Ae,c.provider,f):await ee(Ae),c.provider):void 0;if(me)T(me,"computation",Y);else if(H)for(const O of H)if(O.kind==="js")for(const j of O.components)T(j.compiled,"computation",j.component.logicform);else T(O.compiled,"computation",Y);else T(ie,"computation",Y);Te&&T(Te,"total",Nf(Y)),await P({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await P({stage:"executing",provider:c.provider.kind});const et=me?await(async()=>{const O=nr([...H.map(Z=>Z.sources),$e($)]),[j,G]=await Promise.all([Re(me,O,c),Te?Re(Te,O,c):Promise.resolve(void 0)]),v=await ct(j,$.projections,f);return{rows:v,total:G?Qr(G):v.length}})():H?await(async()=>{const O=await Promise.all(H.map(async G=>{if(G.kind==="js"){const Ee=await Promise.all(G.components.map(async se=>{const re=await Re(se.compiled,se.sources,c),we=await ct(re,se.plan.projections,f);return se.component.mapResult?.(we)??we}));return Promise.all(Xn(Ee,$.groupBy.map(({name:se})=>se)).map(async se=>{const re=await G.unit.mergeRow(se);return{...se,[G.unit.outputName]:re}}))}const v=await Re(G.compiled,G.sources,c),Z=G.kind==="query"?await ct(v,G.plan.projections,f):v;return G.kind==="query"?G.unit.mapResult?.(Z)??Z:Z})),j=Zn(O,Ae);return{rows:$.pagination?Zn(O,$):j,total:j.length}})():await(async()=>{const O=$e($),[j,G]=await Promise.all([Re(ie,O,c),Te?Re(Te,O,c):Promise.resolve(void 0)]),v=await ct(j,$.projections,f);return{rows:v,total:G?Qr(G):v.length}})(),{rows:tt,total:We}=et;await P({stage:"hydrating"});const he=await Js(tt,b,{semanticTypes:l,plugins:o,resolveSchema:B,fetchEntities:O=>Gs(O,{version:Y.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:B,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,...c.connectionId?{preferredConnectionId:c.connectionId}:{},...c.providerForConnection?{providerForConnection:c.providerForConnection}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(j,G,v,Z)=>T(j,"semantic-resolution",G,"entity-expansion",v,Z)})}),Be=Kn(he,$.rowIdentity);return await P({stage:"result",result:Be},{result:Be,total:We,sqls:[...A]}),await P({stage:"completed",durationMs:Zr.performance.now()-p}),{result:Be,total:We,schema:N,normedLogicform:Y,sqls:[...A],lineage:L,provider:c.provider.kind,providers:[...R].map(([O,j])=>({connectionId:O,provider:j})),schemaMappingSelections:[..._],...Y.output?await(async()=>{const O=yi(Y.output?.type??"",o);return O?{output:await O.handle({rows:Be,logicform:Y,schema:N})}:{}})():{}}}catch(D){const k=$a(D);try{await P({stage:"failed",error:k})}catch{}throw k}},Xf=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=pr(wa(e.plugins,e.locales));try{if(e.connections.length===0)throw new d("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const i=new Map;for(const w of e.connections){if(w.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(w.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${w.id}`,{connectionId:w.id});i.set(w.id,w)}const s=new Mn(e.schemaMappings,e.plugins),u=Jf(t).flatMap(w=>s.list(w)).map(({connectionId:w})=>w)[0];if(!u)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const c=w=>{const A=i.get(w);if(!A)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${w}`,{connectionId:w});return vr(A,e.providerRegistry)},p=c(u);r={provider:p.kind};const l=De(e.plugins),f=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],m=new Mt(f),y=new Set(m.definitions().map(({name:w})=>w)),h=f.length===0?l:new Mt([...l.definitions().filter(({name:w})=>!y.has(w)),...m.definitions()]),g=e.semanticTypes===void 0?oo(e.plugins):Es(e.semanticTypes,e.plugins??[]),{cache:_,...E}=e,S=_?await vs(_):void 0;return await Ea(t,{...E,schemaMappings:s,locale:n,localeRegistry:o,provider:p,providerForConnection:c,operators:h,operatorsResolved:!0,semanticTypes:g,semanticTypesResolved:!0,connectionId:u,...S?{cache:S}:{},onProgress:async w=>{r=w.partialResult,await e.onProgress?.(w)}})}catch(i){return Hf(i,t,r,n,o)}},Zf=Object.freeze({execute:Xf,close:ua});exports.DBConnector=Ef,exports.LocaleRegistry=sn,exports.Logicform=Zf,exports.OperatorRegistry=Mt,exports.PlannerSemanticRegistry=ji,exports.ProviderRegistry=sa,exports.QueryCacheManager=yp,exports.SchemaMappingRegistry=Mn,exports.SemanticDBError=d,exports.SemanticTypeRegistry=eo,exports.builtinOperators=Dd,exports.builtinSemanticTypes=Dn,exports.createLocaleRegistry=pr,exports.createOperatorRegistry=De,exports.createPlannerSemanticRegistry=xi,exports.createSemanticTypeRegistry=oo,exports.defaultLocaleRegistry=fr,exports.enUS=ei,exports.fromYiAskSchemaMapping=xd,exports.resolveOperator=Li,exports.resolveSchema=hs,exports.validateResolvedSchema=ys,exports.zhCN=ti;
1
+ "use strict";var ba=Object.create;var qo=Object.defineProperty;var Ra=Object.getOwnPropertyDescriptor;var Na=Object.getOwnPropertyNames;var Oa=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var Pa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Na(e))!Ta.call(t,o)&&o!==r&&qo(t,o,{get:()=>e[o],enumerable:!(n=Ra(e,o))||n.enumerable});return t};var Je=(t,e,r)=>(r=t!=null?ba(Oa(t)):{},Pa(e||!t||!t.__esModule?qo(r,"default",{value:t,enumerable:!0}):r,t));var tn=require("node:perf_hooks"),se=require("dayjs"),xt=require("dayjs/plugin/isoWeek.js"),dr=require("dayjs/plugin/quarterOfYear.js"),jo=require("dayjs/plugin/customParseFormat.js"),rn=require("node:crypto"),xo=require("node:util"),La=require("redis"),Ca=require("semanticdb-core"),ue=require("@duckdb/node-api");const x=t=>typeof t=="string",Bt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},Bo=t=>t==null?"":""+t,Da=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},ka=/###/g,Vo=t=>t&&t.indexOf("###")>-1?t.replace(ka,"."):t,Fo=t=>!t||x(t),Vt=(t,e,r)=>{const n=x(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(Fo(t))return{};const i=Vo(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return Fo(t)?{}:{obj:t,k:Vo(n[o])}},Yo=(t,e,r)=>{const{obj:n,k:o}=Vt(t,e,Object);if(n!==void 0||e.length===1){n[o]=r;return}let i=e[e.length-1],s=e.slice(0,e.length-1),a=Vt(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Vt(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},Ua=(t,e,r,n)=>{const{obj:o,k:i}=Vt(t,e,Object);o[i]=o[i]||[],o[i].push(r)},lr=(t,e)=>{const{obj:r,k:n}=Vt(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},Ma=(t,e,r)=>{const n=lr(t,r);return n!==void 0?n:lr(e,r)},vo=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?x(t[n])||t[n]instanceof String||x(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):vo(t[n],e[n],r):t[n]=e[n]);return t},ot=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var qa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const ja=t=>x(t)?t.replace(/[&<>"'\/]/g,e=>qa[e]):t;class xa{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const Ba=[" ",",","?","!",";"],Va=new xa(20),Fa=(t,e,r)=>{e=e||"",r=r||"";const n=Ba.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=Va.getRegExp(`(${n.map(s=>s==="?"?"\\?":s).join("|")})`);let i=!o.test(t);if(!i){const s=t.indexOf(r);s>0&&!o.test(t.substring(0,s))&&(i=!0)}return i},nn=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},Ft=t=>t?.replace(/_/g,"-"),Ya={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Jr{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Ya,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,o){return o&&!this.debug?null:(x(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Jr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Jr(this.logger,e)}}var Me=new Jr;class pr{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(r)||0;this.observers[n].set(r,o+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o.apply(o,[e,...r])})}}class Qo extends pr{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,o={}){const i=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,r],n&&(Array.isArray(n)?a.push(...n):x(n)&&i?a.push(...n.split(i)):a.push(n)));const u=lr(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!x(n)?u:nn(this.data?.[e]?.[r],n,i)}addResource(e,r,n,o,i={silent:!1}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let a=[e,r];n&&(a=a.concat(s?n.split(s):n)),e.indexOf(".")>-1&&(a=e.split("."),o=r,r=a[1]),this.addNamespaces(r),Yo(this.data,a,o),i.silent||this.emit("added",e,r,n,o)}addResources(e,r,n,o={silent:!1}){for(const i in n)(x(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=lr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?vo(u,n,i):u={...u,...n},Yo(this.data,a,u),s.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var Ho={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,o){return t.forEach(i=>{e=this.processors[i]?.process(e,r,n,o)??e}),e}};const Go=Symbol("i18next/PATH_KEY");function va(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===Go?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function gt(t,e){const{[Go]:r}=t(va()),n=e?.keySeparator??".",o=e?.nsSeparator??":";if(r.length>1&&o){const i=e?.ns,s=Array.isArray(i)?i:null;if(s&&s.length>1&&s.slice(1).includes(r[0]))return`${r[0]}${o}${r.slice(1).join(n)}`}return r.join(n)}const Wo={},on=t=>!x(t)&&typeof t!="boolean"&&typeof t!="number";class Xr extends pr{constructor(e,r={}){super(),Da(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Me.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const o=this.resolve(e,n);if(o?.res===void 0)return!1;const i=on(o.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const s=n&&e.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!Fa(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:x(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:x(i)?[i]:i}}translate(e,r,n){let o=typeof r=="object"?{...r}:r;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=gt(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(P=>typeof P=="function"?gt(P,{...this.options,...o}):String(P));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return f?i?{res:`${c}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let y=m?.res;const g=m?.usedKey||a,h=m?.exactUsedKey||a,_=["[object Number]","[object Function]","[object RegExp]"],E=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,I=!this.i18nFormat||this.i18nFormat.handleAsObject,$=o.count!==void 0&&!x(o.count),A=Xr.hasDefaultValue(o),R=$?this.pluralResolver.getSuffix(l,o.count,o):"",L=o.ordinal&&$?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",D=$&&!o.ordinal&&o.count===0,U=D&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${L}`]||o.defaultValue;let q=y;I&&!y&&A&&(q=U);const X=on(q),F=Object.prototype.toString.apply(q);if(I&&q&&X&&_.indexOf(F)<0&&!(x(E)&&Array.isArray(q))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const P=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,q,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=P,m.usedParams=this.getUsedParamsDetails(o),m):P}if(s){const P=Array.isArray(q),Y=P?[]:{},ce=P?h:g;for(const ee in q)if(Object.prototype.hasOwnProperty.call(q,ee)){const le=`${ce}${s}${ee}`;A&&!y?Y[ee]=this.translate(le,{...o,defaultValue:on(U)?U[ee]:void 0,joinArrays:!1,ns:u}):Y[ee]=this.translate(le,{...o,joinArrays:!1,ns:u}),Y[ee]===le&&(Y[ee]=q[ee])}y=Y}}else if(I&&x(E)&&Array.isArray(y))y=y.join(E),y&&(y=this.extendTranslation(y,e,o,n));else{let P=!1,Y=!1;!this.isValidLookup(y)&&A&&(P=!0,y=U),this.isValidLookup(y)||(Y=!0,y=a);const ee=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&Y?void 0:y,le=A&&U!==y&&this.options.updateMissing;if(Y||P||le){if(this.logger.log(le?"updateKey":"missingKey",l,c,a,le?U:y),s){const me=this.resolve(a,{...o,keySeparator:!1});me&&me.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let $e=[];const Re=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Re&&Re[0])for(let me=0;me<Re.length;me++)$e.push(Re[me]);else this.options.saveMissingTo==="all"?$e=this.languageUtils.toResolveHierarchy(o.lng||this.language):$e.push(o.lng||this.language);const ze=(me,C,w)=>{const S=A&&w!==y?w:ee;this.options.missingKeyHandler?this.options.missingKeyHandler(me,c,C,S,le,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(me,c,C,S,le,o),this.emit("missingKey",me,c,C,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&$?$e.forEach(me=>{const C=this.pluralResolver.getSuffixes(me,o);D&&o[`defaultValue${this.options.pluralSeparator}zero`]&&C.indexOf(`${this.options.pluralSeparator}zero`)<0&&C.push(`${this.options.pluralSeparator}zero`),C.forEach(w=>{ze([me],a+w,o[`defaultValue${w}`]||U)})}):ze($e,a,U))}y=this.extendTranslation(y,e,o,m,n),Y&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${c}${p}${a}`),(Y||P)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${p}${a}`:a,P?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(e,r,n,o,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=x(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const l=e.match(this.interpolator.nestingRegexp);c=l&&l.length}let p=n.replace&&!x(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||o.usedLng,n),u){const l=e.match(this.interpolator.nestingRegexp),f=l&&l.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...l)=>i?.[0]===l[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${l[0]} in key: ${r[0]}`),null):this.translate(...l,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=x(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Ho.handle(a,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,o,i,s,a;return x(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?gt(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),p=c.key;o=p;let l=c.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const f=r.count!==void 0&&!x(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(x(r.context)||typeof r.context=="number")&&r.context!=="",g=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach(h=>{this.isValidLookup(n)||(a=h,!Wo[`${g[0]}-${h}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(Wo[`${g[0]}-${h}`]=!0,this.logger.warn(`key "${o}" for languages "${g.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(_=>{if(this.isValidLookup(n))return;s=_;const E=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(E,p,_,h,r);else{let $;f&&($=this.pluralResolver.getSuffix(_,r.count,r));const A=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&$.indexOf(R)===0&&E.push(p+$.replace(R,this.options.pluralSeparator)),E.push(p+$),m&&E.push(p+A)),y){const L=`${p}${this.options.contextSeparator||"_"}${r.context}`;E.push(L),f&&(r.ordinal&&$.indexOf(R)===0&&E.push(L+$.replace(R,this.options.pluralSeparator)),E.push(L+$),m&&E.push(L+A))}}let I;for(;I=E.pop();)this.isValidLookup(n)||(i=I,n=this.getResource(_,h,I,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,r,n,o):this.resourceStore.getResource(e,r,n,o)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!x(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o.count=e.count),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const i of r)delete o[i]}return o}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&r===n.substring(0,r.length)&&e[n]!==void 0)return!0;return!1}}class zo{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Me.create("languageUtils")}getScriptPartFromCode(e){if(e=Ft(e),!e||e.indexOf("-")<0)return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=Ft(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(x(e)&&e.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return r=o;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=this.options.supportedLngs.find(s=>{if(s===i)return s;if(!(s.indexOf("-")<0&&i.indexOf("-")<0)&&(s.indexOf("-")>0&&i.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===i||s.indexOf(i)===0&&i.length>1))return s})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),x(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return x(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):x(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const Ko={zero:0,one:1,two:2,few:3,many:4,other:5},Jo={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Qa{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Me.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Ft(e==="dev"?"en":e),o=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:o});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let s;try{s=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Jo;if(!e.match(/-|_/))return Jo;const u=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(u,r)}return this.pluralRulesCache[i]=s,s}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(o=>`${r}${o}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>Ko[o]-Ko[i]).map(o=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(e,r,n={}){const o=this.getRule(e,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const Xo=(t,e,r,n=".",o=!0)=>{let i=Ma(t,e,r);return!i&&o&&x(r)&&(i=nn(t,r,n),i===void 0&&(i=nn(e,r,n))),i},sn=t=>t.replace(/\$/g,"$$$$");class Zo{constructor(e={}){this.logger=Me.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:g,nestingOptionsSeparator:h,maxReplaces:_,alwaysFormat:E}=e.interpolation;this.escape=r!==void 0?r:ja,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?ot(i):s||"{{",this.suffix=a?ot(a):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=f?ot(f):m||ot("$t("),this.nestingSuffix=y?ot(y):g||ot(")"),this.nestingOptionsSeparator=h||",",this.maxReplaces=_||1e3,this.alwaysFormat=E!==void 0?E:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const _=Xo(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(_,void 0,n,{...o,...r,interpolationkey:m}):_}const y=m.split(this.formatSeparator),g=y.shift().trim(),h=y.join(this.formatSeparator).trim();return this.format(Xo(r,u,g,this.options.keySeparator,this.options.ignoreJSONStructure),h,n,{...o,...r,interpolationkey:g})};this.resetRegExp();const p=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,l=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>sn(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?sn(this.escape(m)):sn(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const y=i[1].trim();if(s=c(y),s===void 0)if(typeof p=="function"){const h=p(e,i,o);s=x(h)?h:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!x(s)&&!this.useRawValueToEscape&&(s=Bo(s));const g=m.safeValue(s);if(e=e.replace(i[0],g),l?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const p=this.nestingOptionsSeparator;if(u.indexOf(p)<0)return u;const l=u.split(new RegExp(`${ot(p)}[ ]*{`));let f=`{${l[1]}`;u=l[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,g),`${u}${p}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!x(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!x(i))return i;x(i)||(i=Bo(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((p,l)=>this.format(p,l,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const Ha=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=c),c==="false"&&(r[p]=!1),c==="true"&&(r[p]=!0),isNaN(c)||(r[p]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},ei=t=>{const e={};return(r,n,o)=>{let i=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(i={...i,[o.interpolationkey]:void 0});const s=n+JSON.stringify(i);let a=e[s];return a||(a=t(Ft(n),o),e[s]=a),a(r)}},Ga=t=>(e,r,n)=>t(Ft(r),n)(e);class Wa{constructor(e={}){this.logger=Me.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?ei:Ga;this.formats={number:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i});return a=>s.format(a)}),currency:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i,style:"currency"});return a=>s.format(a)}),datetime:n((o,i)=>{const s=new Intl.DateTimeFormat(o,{...i});return a=>s.format(a)}),relativetime:n((o,i)=>{const s=new Intl.RelativeTimeFormat(o,{...i});return a=>s.format(a,i.range||"day")}),list:n((o,i)=>{const s=new Intl.ListFormat(o,{...i});return a=>s.format(a)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=ei(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:p}=Ha(u);if(this.formats[c]){let l=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;l=this.formats[c](a,m,{...p,...o,...f})}catch(f){this.logger.warn(f)}return l}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const za=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Ka extends pr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Me.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let p=!0;r.forEach(l=>{const f=`${c}|${l}`;!n.reload&&this.store.hasResourceBundle(c,l)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,p=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[l]===void 0&&(u[l]=!0)))}),p||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{Ua(u.loaded,[i],s),za(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const p=u.loaded[c];p.length&&p.forEach(l=>{a[c][l]===void 0&&(a[c][l]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,p)=>{if(this.readingCalls--,this.waitingReads.length>0){const l=this.waitingReads.shift();this.read(l.lng,l.ns,l.fcName,l.tried,l.wait,l.callback)}if(c&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,p)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(p=>a(null,p)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();x(e)&&(e=this.languageUtils.toResolveHierarchy(e)),x(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let p;c.length===5?p=c(e,r,n,o,u):p=c(e,r,n,o),p&&typeof p.then=="function"?p.then(l=>a(null,l)).catch(a):a(null,p)}catch(p){a(p)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const an=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),x(t[1])&&(e.defaultValue=t[1]),x(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ti=t=>(x(t.ns)&&(t.ns=[t.ns]),x(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),x(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),fr=()=>{},Ja=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},ri="__i18next_supportNoticeShown",Xa=()=>!!(typeof globalThis<"u"&&globalThis[ri]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),Za=()=>{typeof globalThis<"u"&&(globalThis[ri]=!0)},ec=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class ur extends pr{constructor(e={},r){if(super(),this.options=ti(e),this.services={},this.logger=Me,this.modules={external:[]},Ja(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(x(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=an();this.options={...n,...this.options,...ti(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!ec(this)&&!Xa()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("\u{1F310} i18next is made possible by our own product, Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"),Za());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?Me.init(o(this.modules.logger),this.options):Me.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=Wa;const p=new zo(this.options);this.store=new Qo(this.options.resources,this.options);const l=this.services;l.logger=Me,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Qa(p,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(c),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new Zo(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Ka(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(l.languageDetector=o(this.modules.languageDetector),l.languageDetector.init&&l.languageDetector.init(l,this.options.detection,this.options)),this.modules.i18nFormat&&(l.i18nFormat=o(this.modules.i18nFormat),l.i18nFormat.init&&l.i18nFormat.init(this)),this.translator=new Xr(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=fr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...p)=>this.store[c](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...p)=>(this.store[c](...p),this)});const a=Bt(),u=()=>{const c=(p,l)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(l),r(p,l)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=fr){let n=r;const o=x(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=Bt();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=fr),this.services.backendConnector.reload(e,r,i=>{o.resolve(),n(i)}),o}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Ho.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=Bt();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=x(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(x(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,p=>{i(p,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=gt(u.keyPrefix,c));const p=this.options.keySeparator||".";let l;return u.keyPrefix&&Array.isArray(i)?l=i.map(f=>(typeof f=="function"&&(f=gt(f,c)),`${u.keyPrefix}${p}${f}`)):(typeof i=="function"&&(i=gt(i,c)),l=u.keyPrefix?`${u.keyPrefix}${p}${i}`:i),this.t(l,u)};return x(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=Bt();return this.options.ns?(x(e)&&(e=[e]),e.forEach(o=>{this.options.ns.indexOf(o)<0&&this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=Bt();x(e)&&(e=[e]);const o=this.options.preload||[],i=e.filter(s=>o.indexOf(s)<0&&this.services.languageUtils.isSupportedCode(s));return i.length?(this.options.preload=o.concat(i),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const i=o.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new zo(an());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new ur(e,r);return n.createInstance=ur.createInstance,n}cloneInstance(e={},r=fr){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new ur(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((p,l)=>(p[l]={...u[c][l]},p),u[c]),u),{});i.store=new Qo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...an().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new Zo(c)}return i.translator=new Xr(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Se=ur.createInstance(),tc=Se.createInstance;Se.dir,Se.init,Se.loadResources,Se.reloadResources,Se.use,Se.changeLanguage,Se.getFixedT,Se.t,Se.exists,Se.setDefaultNamespace,Se.hasLoadedNamespace,Se.loadNamespaces,Se.loadLanguages;const ni={locale:"en-US",messages:{"operator.rows":"rows","operator.$sum":"Total {operandName}","operator.$avg":"Average {operandName}","operator.$min":"Minimum {operandName}","operator.$max":"Maximum {operandName}","operator.$count":"{operandName} count","operator.$count.rows":"Row count","operator.$countDistinct":"Distinct {operandName} count","operator.$add":"{inputNames}","operator.$add.empty":"Sum of {operandName}","operator.$subtract":"{input0} minus {input1}","operator.$subtract.fallback":"{operandName} difference","operator.$multiply":"{inputNames}","operator.$multiply.empty":"Product of {operandName}","operator.$divide":"{input0} divided by {input1}","operator.$divide.fallback":"{operandName} ratio","operator.$concat":"Combined {inputNames}","operator.$concat.empty":"Combined {operandName}","operator.$abs":"Absolute {operandName}","operator.$substring":"{operandName} substring","operator.$case":"{operandName} category","operator.$constant":"Constant","operator.$sql":"Calculated value","operator.$rowNumber":"Row number","operator.$rank":"{operandName} rank","operator.$accumulate":"Cumulative {operandName}","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.autoCase":"Resolve automatic bucket boundaries","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.total":"Count result rows before pagination","sql.semanticResolution":"Semantic resolution"}},oi={locale:"zh-CN",messages:{"operator.rows":"\u6570\u636E\u884C","operator.$sum":"\u603B{operandName}","operator.$avg":"\u5E73\u5747{operandName}","operator.$min":"{operandName}\u6700\u5C0F\u503C","operator.$max":"{operandName}\u6700\u5927\u503C","operator.$count":"{operandName}\u6570\u91CF","operator.$count.rows":"\u884C\u6570","operator.$countDistinct":"{operandName}\u53BB\u91CD\u8BA1\u6570","operator.$add":"{inputNames}","operator.$add.empty":"{operandName}\u6C42\u548C","operator.$subtract":"{input0}\u51CF\u53BB{input1}","operator.$subtract.fallback":"{operandName}\u5DEE\u503C","operator.$multiply":"{inputNames}","operator.$multiply.empty":"{operandName}\u4E58\u79EF","operator.$divide":"{input0}\u9664\u4EE5{input1}","operator.$divide.fallback":"{operandName}\u6BD4\u503C","operator.$concat":"{inputNames}\u62FC\u63A5\u503C","operator.$concat.empty":"{operandName}\u62FC\u63A5\u503C","operator.$abs":"{operandName}\u7EDD\u5BF9\u503C","operator.$substring":"{operandName}\u5B50\u4E32","operator.$case":"{operandName}\u5206\u7C7B","operator.$constant":"\u5E38\u91CF","operator.$sql":"\u8BA1\u7B97\u503C","operator.$rowNumber":"\u884C\u53F7","operator.$rank":"{operandName}\u6392\u540D","operator.$accumulate":"{operandName}\u7D2F\u8BA1\u503C","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.autoCase":"\u8BA1\u7B97\u81EA\u52A8\u5206\u6BB5\u8FB9\u754C","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.total":"\u8BA1\u7B97\u5206\u9875\u524D\u7684\u7ED3\u679C\u603B\u6570","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},rc=[oi,ni],Yt=t=>t.trim().toLowerCase(),nc=t=>t?"locale"in t?[t]:t:[],oc=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return typeof e.locale=="string"&&e.locale.trim().length>0&&typeof e.messages=="object"&&e.messages!==null&&!Array.isArray(e.messages)};class cn{definitions=new Map;i18n;constructor(e){this.i18n=tc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(rc),this.register(e)}register(e){for(const r of nc(e)){const n=r;if(!oc(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Yt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Yt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Yt(e));if(r)return r;const n=Yt(e).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(e){return this.definitions.has(Yt(e))}translate(e,r,n,o){const i=this.resolve(e);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(e="zh-CN"){return(r,n,o)=>this.translate(e,r,n,o)}}const mr=t=>new cn(t),yr=new cn;class d extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=yr){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(e,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&e.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}se.extend(xt),se.extend(dr);const ic=new Set(["year","quarter","month","week"]),un=t=>t.format("YYYY-MM-DD HH:mm:ss"),dn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?dn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&dn(r,e)),hr=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new d("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:hr(t.input,e,r)};if(t.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:t,...r};if(t.kind!=="operator")return{kind:"cumulative",function:"sum",input:t,...r};const n=e.getOperator(t.operator);if(n.kind==="component")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${t.operator}`);if(n.kind==="aggregate"){if(t.operator==="$avg"){const s={...t,operator:"$sum"},a={...t,operator:"$count"};return{kind:"operator",operator:"$divide",args:{},inputs:[{kind:"cumulative",function:"sum",input:s,...r},{kind:"cumulative",function:"sum",input:a,...r}]}}const i={$sum:"sum",$count:"sum",$min:"min",$max:"max"}[t.operator];if(!i)throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${t.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:t,...r}}if(n.kind!=="scalar")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:hr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>hr(o,e,r))}:{}}},sc=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new d("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(t.inputProperty?.comparable&&t.input.kind!=="ordinal-decode")throw new d("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const e=t.args.partitionBy??[],r=t.args.orderBy;if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:t.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return hr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},ac=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!dn(t.pred.pred,t.getOperator))throw new d("ACCUMULATE_AGGREGATE_REQUIRED","$accumulate over a grouped physical relation requires an aggregate expression");const e=t.pred.args?.partitionBy,r=t.pred.args?.orderBy;if(e!==void 0&&!Array.isArray(e)||!Array.isArray(r)||r.length===0||r.some(i=>typeof i!="object"||i===null||Array.isArray(i)||typeof i.pred!="string"||Object.keys(i).some(s=>s!=="pred"&&s!=="direction")||i.direction!==void 0&&i.direction!=="asc"&&i.direction!=="desc"))return;const n=[...e??[],...r.map(i=>i.pred)];if(n.some(i=>typeof i!="string"))return;const o=n.map(i=>t.resolveGroupName(String(i)));if(o.length!==t.groupByNames.length||new Set(o).size!==t.groupByNames.length||t.groupByNames.some(i=>!o.includes(i)))throw new d("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:t.groupByNames,received:o})},cc=(t,e,r)=>{if(t.from||t.having)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,$])=>{if(typeof $!="object"||$===null||Array.isArray($))return!1;const A=$;return typeof A.$gte=="string"&&typeof A.$lte=="string"});if(!n)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=se(String(s.$gte)),u=se(String(s.$lte));if(!a.isValid()||!u.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map($=>{if(!$.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return $.name}),p=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...t.query,[o]:{...s,$gte:un(p)}},f=new Set([...(t.groupby??[]).map(({name:$})=>$),...(t.preds??[]).map(({name:$})=>$)]),m=$=>{let A=$;for(;f.has(A);)A=`_${A}`;return f.add(A),A},y=m("__accumulate_period"),g=e.map(($,A)=>m(`__accumulate_metric_${A}`)),h=(t.groupby??[]).map(({name:$})=>String($)),_=r==="year"||r==="quarter"?"month":"day",E={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:_},name:y}],preds:e.map(($,A)=>({...$.pred,name:g[A]??`__accumulate_metric_${A}`}))},I={version:t.version,from:E,preds:[...h.map($=>({pred:$,name:$})),{pred:y,name:y},...e.map(($,A)=>({operator:"$accumulate",pred:g[A]??`__accumulate_metric_${A}`,args:{partitionBy:h,orderBy:[{pred:y,direction:"asc"}]},name:c[A]??`accumulate_${A}`}))]};return{version:t.version,from:I,query:{[y]:{$gte:un(a),$lte:un(u)}},preds:[...h.map($=>({pred:$,name:$})),...c.map($=>({pred:$,name:$}))],...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},uc={name:"$accumulate",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Cumulative ${t}`:`${t}\u7D2F\u8BA1\u503C`,kind:"logical",normalizePred({pred:t}){const e=t.args?.period;if(e!==void 0&&(typeof e!="string"||!ic.has(e)))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period must be year, quarter, month, or week");if(e!==void 0&&(t.args?.partitionBy!==void 0||t.args?.orderBy!==void 0))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return t},planExpression:sc,validatePlan:ac,rewriteLogicform({logicform:t,schema:e}){const r=(t.preds??[]).filter(s=>s.operator==="$accumulate"&&s.args?.period!==void 0);if(r.length===0)return;const n=r[0]?.args?.period;if(r.some(s=>s.args?.period!==n))throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","All $accumulate args.period projections in one LogicForm must use the same period");const o=new Set(Object.keys(t.query??{}));if(e.properties.filter(s=>s.primal_type==="date"&&o.has(s.name)).length!==1)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return cc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},dc={name:"$abs",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Absolute ${t}`:`${t}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:t}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},At=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new d("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},gr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),lc={name:"$add",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" plus "):`Sum of ${t}`:e.length>0?e.join("\u52A0"):`${t}\u6C42\u548C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$add.empty":"operator.$add",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${At("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:gr(t)}},Z=t=>structuredClone(t),pc=(t,e)=>{const r=e[t];if(!r)throw new d("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in r||"_sid"in r)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in r)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(r.id!==t)throw new d("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${r.id}`,{registryKey:t,schemaId:r.id});return r},fc=(t,e)=>{const r=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!r)throw new d("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return r},mc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},ii=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,yc=(t,e)=>t.properties.flatMap(r=>[...e.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&e.startsWith(`${r.name}_`)?[{property:r,prefix:r.name}]:[]]).sort((r,n)=>n.prefix.length-r.prefix.length||(n.prefix===n.property.id?1:0)-(r.prefix===r.property.id?1:0)),ae=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:ii(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of yc(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=ae(s,e.slice(i.length+1),r);return{canonicalName:`${ii(t,o)}_${a.canonicalName}`,canonicalId:`${o.id}_${a.canonicalId}`,schema:a.schema,property:a.property,relations:[{sourceSchema:t,property:o,targetSchema:s},...a.relations]}}throw new d("PROPERTY_NOT_FOUND",`\u5728 Schema\uFF1A${t.name}(${t.id})\u4E2D\u672A\u627E\u5230\u5C5E\u6027: ${e}`,{schemaId:t.id,schemaName:t.name,property:e,propertyName:e})},ln=(t,e)=>t.name===e||t.id===e,hc=(t,e,r)=>{const n=new Set,o=[t];for(;o.length>0;){const i=o.shift();if(!i||n.has(i.name))continue;n.add(i.name);const s=[...i.hierarchy?.up?r.properties.filter(a=>ln(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&ln(i,a.hierarchy.down))];if(s.some(a=>ln(e,a.name)))return!0;o.push(...s)}return!1},si=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ae(r,t.pred,n)}catch{return!1}return o.property.isArray||o.property.primal_type==="entity"||o.property.primal_type==="object"||o.relations.some(({property:i})=>i.isArray)?!1:e.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=ae(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return hc(s.property,o.property,r);if(s.relations.length!==0||o.relations.length===0)return!1;const[a]=o.relations;return s.property.name===a?.property.name})},gc=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new d("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},Ac=t=>{if(!t.hierarchy)return;const e=t.properties.find(({name:r})=>r===t.hierarchy?.property);if(!e)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${t.hierarchy.property}`,{schemaId:t.id,property:t.hierarchy.property});return e},wc=(t,e,r)=>{const n=ae(t,e,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new d("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},$c={name:"$hierarchyLevel",defaultName:({operandName:t,args:e,locale:r})=>{const n=typeof e.level=="string"?e.level:"";return r.toLowerCase().startsWith("en")?`${t}${n?` ${n}`:""} level`:`${t}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:t,args:e,schema:r,resolveSchema:n}){const o=Object.keys(e).filter(y=>y!=="level");if(o.length>0||e.level!==void 0&&(typeof e.level!="string"||e.level.length===0))throw new d("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=wc(r,t,n),s=i.schema.hierarchy;if(!s)throw new d("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:y})=>y===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==ae(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((y,g)=>y+g.codeLength,0),c=i.schema.properties.filter(({type:y})=>y==="ID"),l=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:l,args:{levels:s.levels.map(({name:g,codeLength:h})=>(y+=h,{name:g,codeLength:y})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(y=>(f+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!m)throw new d("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:l,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),c=e.totalLength,p=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:y,codeLength:g},h)=>y.length===0||g<=0||g>Number(c)||h>0&&g<=Number(u[h-1]?.codeLength))||u.at(-1)?.codeLength!==c||p!=="compact"&&p!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const l=`WHEN ${t} IS NULL THEN NULL`;if(p==="compact"){const y=r.stringLength(t),g=u.map(h=>`WHEN ${y} = ${h.codeLength} THEN ${r.value(h.name)}`);return`(CASE ${l} ${g.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(y=>{const g=Number(c)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,g)} = ${r.value("0".repeat(g))} THEN ${r.value(y.name)}`}),m=u.at(-1);return`(CASE ${l} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(t,1,Number(n)),a=Number(o)-Number(n);return i==="zero-padded"&&a>0?r.concat([s,r.value("0".repeat(a))]):s},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},wt=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===2&&e.kind==="hierarchy"&&typeof e.level=="string"&&e.level.trim().length>0},$t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),pn=(t,e,{schema:r,resolveSchema:n})=>{if(typeof e!="string")return;const o=t.primal_type==="entity"||t.primal_type==="object"?t.ref?n?.(t.ref).hierarchy:void 0:r.hierarchy?.property===t.name?r.hierarchy:void 0,i=o?.levels.find(s=>s.name===e||s.syno?.includes(e));if(!(!o||!i))return{name:i.name,index:o.levels.indexOf(i)}},Ar=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>$t(e,o)?.id===t.id)),ai=(t,e,r)=>{const n=$t(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=pn(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Ar(n,r);if(!wt(i?.granularity))return;const s=pn(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},Ec=(t,e)=>{const r=i=>{const s=n(i.query);if(s)return s;if(i.operator==="$hierarchyLevel"&&typeof i.pred=="string")if(i.args?.level!==void 0){const u=ai(i.pred,i.args.level,e);if(u)return u}else{const u=$t(e.schema,i.pred),c=u&&Ar(u,e);if(wt(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=$t(e.schema,s),c=u&&Ar(u,e);if(wt(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=ai(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=$t(e.schema,i.pred),a=s&&Ar(s,e);if(wt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},_c={kind:"hierarchy",isGranularity:wt,validateItem(t,e){const r=t.granularity;if(wt(r))return t.propertyTarget?.every(n=>{const o=$t(e.schema,n);return o!==void 0&&pn(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:Ec,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Sc={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new d("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=t.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new d("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new d("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new d("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new d("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new d("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new d("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,p=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,g=Object.keys(y).filter(_=>_!=="name"&&_!=="syno"&&_!=="codeLength");if(g.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:g});if(typeof y.name!="string"||y.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(y.name)||c.has(y.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some(_=>typeof _!="string"||_.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const h=y.syno??[];for(const _ of h){if(_===y.name||u.has(_)||c.has(_))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${_}`);c.add(_)}return u.add(y.name),{name:y.name,...h.length>0?{syno:[...h]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},Ic=Object.freeze({name:"hierarchy",schemaMetadata:Sc,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:gc,resolveEntityFilterProperty:Ac,operators:[$c],mappingGranularity:_c}),bc=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),fn="$periodValue",Rc=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:fn,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${fn}; ${e.name} describes a time range`,{operator:e.name});return{operator:fn,boundary:"end",implicit:!0}},Nc={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!bc(r,e))return;const s=Rc(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},Oc=new Set(["second","minute","hour","day","week","month","quarter","year"]),ci=t=>typeof t=="string"&&Oc.has(t),Tc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),wr=(t,e,r)=>{const n=t instanceof Date?t.getTime():typeof t=="string"||typeof t=="number"?new Date(t).getTime():Number.NaN;if(Number.isNaN(n))throw new d(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},it=(t,e=2)=>String(t).padStart(e,"0"),mn=t=>`${it(t.getFullYear(),4)}-${it(t.getMonth()+1)}-${it(t.getDate())} ${it(t.getHours())}:${it(t.getMinutes())}:${it(t.getSeconds())}.`+it(t.getMilliseconds(),3),Pc=(t,e)=>{if(!Tc(t)){const a=wr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=wr(r,"$eq",e);return{lower:a,upper:a}}const n=t.$gte??t.$gt,o=t.$lte??t.$lt;if(n===void 0||o===void 0)throw new d(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=wr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=wr(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new d(`${e.codePrefix}_PERIOD_INVALID_RANGE`,`${e.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},Lc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setMilliseconds(0);break;case"minute":r.setSeconds(0,0);break;case"hour":r.setMinutes(0,0,0);break;case"day":r.setHours(0,0,0,0);break;case"week":{r.setHours(0,0,0,0);const n=(r.getDay()+6)%7;r.setDate(r.getDate()-n);break}case"month":r.setDate(1),r.setHours(0,0,0,0);break;case"quarter":r.setMonth(Math.floor(r.getMonth()/3)*3,1),r.setHours(0,0,0,0);break;case"year":r.setMonth(0,1),r.setHours(0,0,0,0);break}return r},Cc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setSeconds(r.getSeconds()+1);break;case"minute":r.setMinutes(r.getMinutes()+1);break;case"hour":r.setHours(r.getHours()+1);break;case"day":r.setDate(r.getDate()+1);break;case"week":r.setDate(r.getDate()+7);break;case"month":r.setMonth(r.getMonth()+1);break;case"quarter":r.setMonth(r.getMonth()+3);break;case"year":r.setFullYear(r.getFullYear()+1);break}return r},ui=(t,e,r)=>{const{lower:n,upper:o}=Pc(t,r),i=[];let s=Lc(n,e);for(;s.getTime()<=o;){if(i.length>=1e4)throw new d(`${r.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${r.label} period grouping cannot generate more than 10000 periods`);const a=Cc(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:mn(s),start:mn(s),end:mn(u)}),s=a}return i},Dc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),kc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Uc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=Dc(t,r),o=t.preds??[],i=o.filter(({operator:l})=>l==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!ci(s))throw new d("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values require $dateBucket with a supported time granularity",{property:r.name});if(i.length!==o.length)throw new d("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(l=>{const f=l.args?.boundary;if(f!=="start"&&f!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!l.pred||typeof l.pred!="object"||Array.isArray(l.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:l,effectivePred:{...l.pred,...l.name?{name:l.name}:{}}}});if(new Set(i.map(({args:l})=>l?.boundary)).size!==1)throw new d("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,p=t.query?.[r.name];if(p===void 0)throw new d("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:ui(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[c]}))}},di=["second","minute","hour","day","week","month","quarter","year"],Mc=Object.freeze({name:"observation",schemaMetadata:{keys:["temporalSemantics"],resolve(t){const e=t.temporalSemantics??"normal";if(e!=="normal"&&e!=="snapshot")throw new d("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:t.id,temporalSemantics:e});return{temporalSemantics:e}}},validateResolvedSchema(t){if(t.temporalSemantics==="snapshot"&&!t.properties.some(({type:e})=>e==="timestamp"))throw new d("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.id})},plannerSemantics:[Nc],relationSemantics:{plan({sourceSchema:t,targetSchema:e}){if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:s})=>s==="timestamp");if(!r)throw new d("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${e.id} requires an ID and timestamp Property when joined`,{schemaId:e.id});const n=t.properties.find(({type:s})=>s==="timestamp");if(!n)throw new d("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});const o=n.granularity??"day",i=r.granularity??"day";if(di.indexOf(o)>di.indexOf(i))throw new d("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${e.id} snapshot granularity ${i} to coarser source granularity ${o}`,{sourceSchemaId:t.id,targetSchemaId:e.id,sourceGranularity:o,targetGranularity:i});return{kind:"date-bucket-equal",sourceTimestamp:n,targetTimestamp:r}}},plannerPeriod:{resolve(t,e){const r=Uc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>kc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),vt=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,qc={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new d("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators")},async normalize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{root:t},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:vt(o,i);if(!a||i===void 0&&s.length!==1)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),l=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof l!="string"||l.length===0)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(r.includeSelf!==void 0&&typeof r.includeSelf!="boolean"||r.include_self!==void 0&&typeof r.include_self!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:p,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:l}},authorize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=e.resolveSchema(n);if(e.assertSchemaAllowed(n),e.hasRowPermissions(n))throw new d("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):vt(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=vt(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const r=t,n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=vt(o,r.idProperty),s=vt(o,r.parentProperty);if(!i)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId);return{value:{schemaId:n,connectionId:a.connectionId,source:a.source,...a.sourceSql?{sourceSql:a.sourceSql}:{},idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:a.source,...a.connectionId?{connectionId:a.connectionId}:{}}]}},compile(t,{field:e,provider:r,bind:n,renderSource:o}){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(typeof i.source!="string"||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new d("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map($=>n($)).join(", "),g=($,A=!1)=>s.length===1?`${$} ${A?"<>":"="} ${y()}`:`${$} ${A?"NOT IN":"IN"} (${y()})`,h=`${c}.${l}`,_=i.includeSelf?g(h):`${g(`${c}.${f}`)} AND ${g(h,!0)}`,E=r.recursiveCteUnion??"UNION",I=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${h} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${_} ${E} SELECT ${p}.${l} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${p}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${I}`}},jc=Object.freeze({name:"recursive",schemaMetadata:{keys:["parentProperty"],resolve(t,e){if(t.parentProperty===void 0)return{};const r=e.find(({id:n,name:o})=>n===t.parentProperty||o===t.parentProperty);if(!r)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${t.parentProperty}`,{schemaId:t.id,property:t.parentProperty});return{parentProperty:r.name}}},queryOperators:[qc]});se.extend(xt);const yn=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...yn(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:yn(r))]:e},li=(t,e)=>se(t).endOf(e==="week"?"isoWeek":e).toDate(),hn=t=>se(t).format("YYYY-MM-DD HH:mm:ss"),xc=(t,e)=>{const r=t??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},pi=(t,e)=>{if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be an object`);const r=t,n=Object.keys(r);if(!(r.type==="database_latest"&&n.length===1)&&!(r.type==="now_offset"&&n.every(o=>o==="type"||o==="offset")&&Number.isInteger(r.offset)))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},Bc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return pi(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(pi(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new d("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(yn).filter(l=>l!==e.id))],c=[{schema:e,property:r}];for(const l of u){const f=s(l),m=t.propertyResolve?.[l],y=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!y)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const g=f.properties.find(({id:h,name:_})=>h===y||_===y);if(!g||g.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${y}`,{schemaId:l,property:y});c.push({schema:f,property:g})}const p=c.map(({schema:l,property:f})=>{const m=xc(f.timeWatermark??l.timeWatermark??i,`${l.id}.${f.id}`);if(m.type==="now_offset"){const y=li(se(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:hn(y),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:hn(li(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:hn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),$r=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Qt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=$r(t.properties,"ID"),r=$r(t.properties,"timestamp"),n=$r(t.properties,"start_date"),o=$r(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},fi=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Vc=(t,e)=>fi(t,e)!==void 0,Fc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Yc=(t,e)=>{const r=fi(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!ci(n))throw new d("VALIDITY_PERIOD_GRANULARITY_UNSUPPORTED","Valid-time period grouping requires $dateBucket with a supported time granularity",{property:e.timestamp.name});const o=t.query?.[e.timestamp.name];if(o===void 0)throw new d("VALIDITY_PERIOD_BOUNDS_REQUIRED",`Valid-time period grouping on ${e.timestamp.name} requires a bounded query`,{property:e.timestamp.name});return{group:r,granularity:n,periods:ui(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},vc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qc=t=>vc(t)?t.$lte??t.$lt??t.$eq:t,mi=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,u])=>[a,(a==="$and"||a==="$or")&&Array.isArray(u)?u.map(c=>mi(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=Qc(o);if(i===void 0)throw new d("VALIDITY_POINT_IN_TIME_REQUIRED",`Valid-time query on ${e.timestamp.name} requires an upper bound or a point in time`,{property:e.timestamp.name});return{...Object.fromEntries(Object.entries(r).filter(([a])=>a!==e.timestamp.name)),[e.start.name]:t[e.start.name]??{$lte:i},[e.end.name]:t[e.end.name]??{$or:[{$exists:!1},{$gt:i}]}}},yi=(t,e)=>!!(t&&Object.entries(t).some(([r,n])=>e.has(r)||(r==="$and"||r==="$or")&&Array.isArray(n)&&n.some(o=>typeof o=="object"&&o!==null&&yi(o,e)))),Hc={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Qt(e);if(!n)return r;if(Vc(t,n))return Fc(r,n);const i=yi(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return mi(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Qt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Gc={name:"start_date",primalType:"date"},Wc={name:"end_date",primalType:"date"},zc=Object.freeze({name:"validity",semanticTypes:[Gc,Wc],prepareSchema(t){const e=t.properties.filter(({type:s})=>s==="ID"),r=t.properties.filter(({type:s})=>s==="start_date"),n=t.properties.filter(({type:s})=>s==="end_date"),o=r[0];if(t.type!=="entity"||t.properties.some(({type:s})=>s==="timestamp")||t.temporalSemantics==="snapshot"||e.length!==1||r.length!==1||n.length!==1||t.properties.some(({name:s})=>s==="\u65E5\u671F")||!o)return t;const i={id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",is_supplementary:!0,udf:{sql:o.id??o.name}};return{...t,properties:[...t.properties,i]}},plannerSemantics:[Hc],intervalSemantics:{resolve:Qt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Qt(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new d("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});return{kind:"point-in-interval",point:n,start:r.start,end:r.end}}},plannerPeriod:{resolve(t,e){const r=Qt(e);if(!r)return;const n=Yc(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),hi=(t,e,r,n)=>{if(r===void 0)return;if(typeof r!="string"||r.length===0)throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${e.name} hierarchy.${n} must be a non-empty Property name or id`,{property:e.name,direction:n,reference:r});const o=t.find(i=>i.id===r)??t.find(i=>i.name===r);if(!o)throw new d("PROPERTY_HIERARCHY_TARGET_NOT_FOUND",`Property ${e.name} hierarchy.${n} does not exist: ${r}`,{property:e.name,direction:n,reference:r});if(o===e)throw new d("PROPERTY_HIERARCHY_CYCLE",`Property ${e.name} cannot point to itself in hierarchy.${n}`,{property:e.name,direction:n});return o.name},Kc=Object.freeze({name:"property-hierarchy",propertyMetadata:{keys:["hierarchy"],resolve:()=>({}),resolveAll(t,e){const r=t.map((o,i)=>{const s=e[i]?.hierarchy;if(s===void 0)return o;if(typeof s!="object"||s===null||Array.isArray(s))throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=hi(t,o,a.up,"up"),p=hi(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...p?{down:p}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new d("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r}}}),gi=Object.freeze([Ic,jc,Bc,Mc,zc,Kc]),pe=(t=[])=>{const e=[...gi,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,p=new Set;for(const l of e){if(!l.name)throw new d("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(l.name))throw new d("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${l.name}`,{plugin:l.name});r.add(l.name);for(const m of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!m)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:l.name});n.add(m)}for(const m of l.propertyMetadata?.keys??[]){if(!m)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:l.name});o.add(m)}for(const m of l.operators??[]){if(i.has(m.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:l.name});i.add(m.name)}for(const m of l.semanticTypes??[]){if(s.has(m.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:l.name});s.add(m.name)}for(const m of l.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:l.name});a.add(m.name)}for(const m of l.queryOperators??[]){if(!m.name||u.has(m.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:l.name});u.add(m.name)}for(const m of l.outputHandlers??[]){if(!m.type||c.has(m.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:l.name});c.add(m.type)}const f=l.mappingGranularity;if(f){if(!f.kind||p.has(f.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);p.add(f.kind)}}return Object.freeze(e)},Et=(t,e=[])=>pe(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Ai=(t,e=[])=>pe(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),gn=(t,e)=>{if(e.length>1)throw new d("PLUGIN_SEMANTIC_CAPABILITY_AMBIGUOUS",`Multiple plugins matched ${t}: ${e.map(({plugin:r})=>r).join(", ")}`,{capability:t,plugins:e.map(({plugin:r})=>r)});return e[0]?.value},wi=(t,e=[])=>gn("interval semantics",pe(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Jc=(t,e,r=[])=>gn("relation semantics",pe(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Xc=(t,e,r=[])=>gn("planner period semantics",pe(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),An=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),Zc=t=>{const e=t.properties.filter(({type:r})=>r==="ID");if(e.length!==1)throw new d("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${t.id} must contain exactly one ID property to use entity_id`,{schemaId:t.id,idPropertyCount:e.length});return e[0]},wn=(t,e=[])=>{for(const r of pe(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return Zc(t)},$n=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},En=t=>typeof t.pred=="string"?t.pred:void 0,eu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),tu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},ru={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},_n=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!eu(o))return r?.("period.comparison",n?"period-over-period":"\u540C\u671F")??(n?"period-over-period":"\u540C\u671F");if(typeof o.granularity=="string"&&typeof o.offset=="number"){if(o.offset===-1&&o.granularity==="year")return r?.("period.yearOverYear",n?"year-over-year":"\u540C\u6BD4")??(n?"year-over-year":"\u540C\u6BD4");if(o.offset===-1&&o.granularity==="month")return r?.("period.monthOverMonth",n?"month-over-month":"\u73AF\u6BD4")??(n?"month-over-month":"\u73AF\u6BD4");if(o.offset===-1&&o.granularity==="week")return r?.("period.weekOverWeek",n?"week-over-week":"\u5468\u73AF\u6BD4")??(n?"week-over-week":"\u5468\u73AF\u6BD4");if(o.offset===0)return r?.("period.current",n?"current-period":"\u672C\u671F")??(n?"current-period":"\u672C\u671F");const s=Math.abs(o.offset),a=o.offset<0?"before":"after";return n?`${s} ${o.granularity}${s===1?"":"s"} ${a}`:`\u8F83${a==="before"?"\u524D":"\u540E"}${s}${tu[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${ru[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};se.extend(xt),se.extend(dr);const nu=["second","minute","hour","day","week","month","quarter","year"],ou=new Set(nu),Sn=["year","quarter","month","week","day","hour","minute","second"],$i=t=>Object.prototype.toString.call(t)==="[object Object]",Xe=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},iu=t=>{const e=t.time;$i(e)||Xe("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!ou.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&Xe("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!Sn.includes(a)||!Number.isInteger(u)))&&Xe("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&Xe("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<u||Number(p)>c)&&Xe(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&Xe("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&Xe("Absolute period shift day requires month"),r},Ei=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),su=(t,e)=>{if("granularity"in e){const n=e.granularity==="week"?"week":e.granularity;return t.add(e.offset,n)}let r=t;for(const n of Sn){const o=e[n];typeof o=="number"&&(r=Ei(r,n,o))}return r},In=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),au=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=En(i);return s?ae(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:$n(i),granularity:a,offset:u}}),bn=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>bn(i,e,r));if($i(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,bn(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=se(t);if(!n.isValid())return t;const o=su(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,In(t,o)},cu=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,p])=>{if((c==="$and"||c==="$or")&&Array.isArray(p))return[c,p.map(f=>s(f))];const l=ae(e,c,r);return l.property.primal_type!=="date"?[c,p]:(i.add(l.canonicalName),[c,bn(p,n,o)])})),a=s(t);if(i.size===0||o.shiftedValues===0)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new d("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},st=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},Ze=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Ze(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:Ze(r)):[]],uu=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=se(t);if(!n.isValid())return t;if("granularity"in e)return In(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of Sn)if(e[i]!==void 0){const s=i==="month"?r.originalAnchor.month()+1:i==="day"?r.originalAnchor.date():i==="week"?r.originalAnchor.isoWeek():i==="quarter"?r.originalAnchor.quarter():r.originalAnchor.get(i);o=Ei(o,i,s)}return In(t,o)},Rn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&Xe("$periodShift pred must be a nested metric");const s=iu(e.args??{}),a={shiftedValues:0},u=st([t.query,...Ze(e)]);if(!u)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=cu(u,n,o,s,a),p=Z(i);p.name=r,delete p.query;const l=Z(t);l.query=c,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const f=new Set((t.groupby??[]).filter(m=>{const y=En(m);return y?ae(n,y,o).property.primal_type==="date":!1}).map($n));return{kind:"query",logicform:l,groupKeyShifts:au(t,n,o,s,a),mapResult:m=>m.map(y=>{const g={...y};for(const h of f)g[h]=uu(g[h],s,a);return g})}},du={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=_n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} baseline`:`${t}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Rn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},lu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Er=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,_i=(t,e)=>{const r=t.properties.find(({type:n})=>n==="timestamp");if(!r)throw new d("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},Si=(t,e)=>{if(Er(t)){e.start??=t,e.end??=t;return}if(!lu(t))return;const r=t.$eq;Er(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Er(n)&&(e.start??=n),Er(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Si(a,e)}},pu=(t,e,r,n)=>{const o=_i(e,n),i=new Set,s={},a=(l,f)=>{for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const h of y)a(h,f||m==="$or");continue}if(m.startsWith("$"))continue;const g=ae(e,m,r);if(g.property.type==="timestamp"){if(f)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(g.canonicalName),Si(y,s)}}};if(a(t,!1),i.size!==1)throw new d(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const u=[...i][0];if(!u||u!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const c=l=>{const f=[];for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const g=y.map(h=>c(h)).filter(h=>h!==void 0);g.length>0&&f.push([m,g]);continue}!m.startsWith("$")&&ae(e,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},p=c(t);return{property:o,propertyName:u,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Ii=(t,e,r,n,o)=>{const i=st([t,...Ze(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return pu(i,r,n,o)},bi=(t,e,r)=>st([t,{[e]:r}]),fu=new Set(["day","week","month","quarter","year"]),mu={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},yu=t=>{if(typeof t!="string"||!fu.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Ri=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Nn=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Nn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Nn(r))),e},hu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${mu[String(e.granularity)]??"\u5468\u671F"}\u5747\u503C`,kind:"component",createComponent({logicform:t,pred:e,schema:r,outputName:n,t:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=yu(e.args?.granularity),s=_i(r,"$averagePerPeriod"),a=Nn(e.pred),u=st([t.query,...Ze(e)]),c=Ri(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const p=Ri(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(p.query=u);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:c},{name:f,logicform:p}],expression:`${l} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},gu={name:"$avg",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Average ${t}`:`\u5E73\u5747${t}`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$avg requires a column");return r.aggregateFunction("avg",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$avg requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},_t=t=>{throw new d("INVALID_CASE_ARGS",t)},Au=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&_t("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&_t("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&_t("$case auto mode args.buckets must be an integer between 2 and 100");const r=t.count;if(r!==void 0&&(!Number.isSafeInteger(r)||r<0)&&_t("$case auto mode args.count must be a non-negative safe integer"),t.empty===!0)return{empty:!0};for(const o of["min","max"])(typeof t[o]!="number"||!Number.isFinite(t[o]))&&_t(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&_t("$case auto mode args.min cannot be greater than args.max");const n=e===void 0?r===void 0?10:Math.min(12,Math.max(5,Math.ceil(Math.log2(Math.max(r,1))+1))):e;return{empty:!1,minimum:t.min,maximum:t.max,targetBuckets:n}},wu=t=>{const r=10**Math.floor(Math.log10(t)),n=t/r;return(n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*r},_r=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},On=t=>String(_r(t)),$u=(t,e,r)=>{if(t===e)return[t,e];const n=wu((e-t)/r),o=_r(Math.floor(t/n)*n),i=_r(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,u)=>u===s?i:_r(o+n*u))},Eu=t=>{if(!Array.isArray(t)||t.length===0)throw new d("INVALID_CASE_ARGS","$case requires a non-empty args.cases array");return t.map(e=>{if(typeof e!="object"||e===null||!("when"in e)||!("then"in e))throw new d("INVALID_CASE_ARGS","Each $case item requires when and then");const r=e;return{when:r.when,then:r.then}})},_u={name:"$case",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} category`:`${t}\u5206\u7C7B`,kind:"scalar",validateGroupby({pred:t}){if(t.args?.mode==="auto"&&t.args.empty!==!0&&(t.args.min===void 0||t.args.max===void 0))throw new d("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires resolved args.min and args.max")},toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=Au(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,u=n.maximum;if(a===u)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(On(a))} END`;const c=$u(a,u,n.targetBuckets),p=c.slice(0,-1).map((f,m)=>{const y=c[m+1],g=m===c.length-2?"]":")";return`[${On(f)}, ${On(y)}${g}`}),l=p.slice(0,-1).map((f,m)=>`WHEN ${t} < ${r.value(c[m+1])} THEN ${r.value(f)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=Eu(e.cases).map(({when:s,then:a})=>`WHEN ${r.condition(t,s)} THEN ${r.value(a)}`),i=Object.hasOwn(e,"default")?` ELSE ${r.value(e.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:t}){return{name:t,type:"category",primal_type:"string",isArray:!1}}},Su={name:"$concat",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?`Combined ${e.join(" and ")}`:`Combined ${t}`:e.length>0?`${e.join("\u4E0E")}\u62FC\u63A5\u503C`:`${t}\u62FC\u63A5\u503C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$concat.empty":"operator.$concat",kind:"scalar",requiresProperty:!1,toSQL(t){return t.sql.concat(At("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Iu={name:"$count",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?t==="rows"?"Row count":`${t} count`:t==="\u6570\u636E\u884C"?"\u884C\u6570":`${t}\u6570\u91CF`,defaultNameKey:({inputName:t,inputNames:e})=>t||e.length>0?"operator.$count":"operator.$count.rows",kind:"aggregate",requiresProperty:!1,toSQL(t){const{column:e,sql:r}=t;return r.aggregateFunction("count",e)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},bu={name:"$countDistinct",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Distinct ${t} count`:`${t}\u53BB\u91CD\u8BA1\u6570`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$countDistinct requires a column");return r.aggregateFunction("count",`DISTINCT ${e}`)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Ru=new Set(["second","minute","hour","day","week","month","quarter","year"]),Nu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ni=t=>{if(typeof t!="string"||!Ru.has(t))throw new d("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be second, minute, hour, day, week, month, quarter, or year");return t},Ou={name:"$dateBucket",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} by ${typeof e.granularity=="string"?e.granularity:"time"}`:`${t}\uFF08\u6309${Nu[String(e.granularity)]??"\u65F6\u95F4"}\uFF09`,kind:"scalar",supportsGroupedSourceGroupby:!0,groupedSourceTimeGranularity:({pred:t})=>t.args?.granularity,toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$dateBucket requires a date pred");return r.dateBucket(t,Ni(e.granularity))},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=Ni(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Tu={name:"$divide",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} divided by ${e[1]}`:`${t} ratio`:e.length>=2?`${e[0]}\u9664\u4EE5${e[1]}`:`${t}\u6BD4\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$divide.fallback":"operator.$divide",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=At("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return gr(t)}},Pu=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$max",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Lu={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Pu,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$max requires a column");return r.aggregateFunction("max",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$max requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},Cu=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$min",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Du={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Cu,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$min requires a column");return r.aggregateFunction("min",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$min requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},ku={name:"$multiply",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" times "):`Product of ${t}`:e.length>0?e.join("\u4E58\u4EE5"):`${t}\u4E58\u79EF`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$multiply.empty":"operator.$multiply",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${At("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return gr(t)}},Uu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Tn=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Tn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Tn(r))),e},Mu={name:"$newly",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`New ${t}`:`\u65B0\u589E${t}`,kind:"component",createComponent({logicform:t,pred:e,schema:r,resolveSchema:n,outputName:o,t:i}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(l=>{const f=En(l);return f?ae(r,f,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Ii(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new d("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=Tn(e.pred),u=(l,f)=>{const m=Uu(t);return m.query=bi(s.queryWithoutTime,s.propertyName,{$lte:l}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:p,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},qu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Pn=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Pn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Pn(r))),e},ju={name:"$periodValue",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,defaultNameKey:({args:t})=>`operator.$periodValue.${t.boundary==="start"?"start":"end"}`,kind:"component",skipComponentExecution:({plan:t})=>t.periodSource?.match.kind==="latest",periodBoundaryPolicy({pred:t}){const e=t.args?.boundary;if(e!=="start"&&e!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:e});return{boundary:e,implicit:!1}},createComponent({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=Ii(t.query,e,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new d("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=qu(t);return c.query=bi(s.queryWithoutTime,s.propertyName,u),c.preds=[{...Pn(e.pred),name:r}],{kind:"query",logicform:c}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},xu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Bu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodDifference pred must be a nested metric");const a=Z(e.pred);a.name="__period_diff_current__";const u=xu(t);u.preds=[a];const c=st([t.query,...Ze(e)]);c&&(u.query=c);const p={pred:Z(e.pred),...e.args?{args:e.args}:{}},l=Rn({logicform:t,pred:p,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},Vu={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=_n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} difference`:`${t}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Bu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Fu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Yu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=Z(e.pred);a.name="__period_growth_current__";const u=Fu(t);u.preds=[a];const c=st([t.query,...Ze(e)]);c&&(u.query=c);const p={pred:Z(e.pred),...e.args?{args:e.args}:{}},l=Rn({logicform:t,pred:p,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},vu={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=_n(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} growth`:`${t}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Yu,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Qu={name:"$sum",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Total ${t}`:`\u603B${t}`,kind:"aggregate",supportsGroupedSourceRollup:!0,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$sum requires a column");return r.aggregateFunction("sum",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$sum requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},Hu={name:"$subtract",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} minus ${e[1]}`:`${t} difference`:e.length>=2?`${e[0]}\u51CF\u53BB${e[1]}`:`${t}\u5DEE\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$subtract.fallback":"operator.$subtract",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=At("$subtract",t,2);if(t.args.nullAsZero!==void 0&&typeof t.args.nullAsZero!="boolean")throw new d("INVALID_SUBTRACT_ARGS","$subtract args.nullAsZero must be boolean");return t.args.nullAsZero===!0?`(COALESCE(${e}, 0) - COALESCE(${r}, 0))`:`(${e} - ${r})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:gr(t)}},Oi=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Ln=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Ln(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Ln(r))),e},Gu={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e,outputName:r,t:n}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=e.args?.dimension;if(o!==void 0&&typeof o!="string")throw new d("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=t.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||$n(y)===o);if(o!==void 0&&s<0)throw new d("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,g)=>g!==s),u=Ln(e.pred),c=Oi(t);c.preds=[{...u,name:"__share_numerator__"}];const p=st([t.query,...Ze(e)]);p&&(c.query=p);const l=Oi(t);l.groupby=a,l.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Wu={name:"$substring",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} substring`:`${t}\u5B50\u4E32`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:n,length:o}=e;if(!Number.isInteger(n)||Number(n)<0||!Number.isInteger(o)||Number(o)<1)throw new d("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return r.substring(t,Number(n)+1,Number(o))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Ti=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new d("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new d("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},zu=new Set(["boolean","date","number","entity","object","string"]),Ku=t=>{if(t===void 0)return[];if(!Array.isArray(t))throw new d("INVALID_SQL_ARGS","$sql args.parameters must be an array");return t},Ju=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!zu.has(n))throw new d("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new d("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new d("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:t,type:r,primal_type:n==="object"?"entity":n,isArray:e.isArray===!0,...typeof e.ref=="string"?{ref:e.ref}:{}}},Xu={name:"$sql",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:t,expression:e,expressions:r,sql:n}){if(e||r&&r.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Ti(t.sql,Ku(t.parameters),o=>n.value(o))},getOutputProperty({name:t,args:e,inputProperty:r,inputProperties:n}){if(r||n&&n.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Ju(t,e)}},Zu=t=>{const e=new Set,r=n=>{for(const[o,i]of Object.entries(n)){if(o==="$and"||o==="$or"){for(const s of i)r(s);continue}e.add(o)}};return r(t),[...e]},ed=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},td=(t,e,r)=>{const n=t.preds;if(n.filter(p=>p.operator==="$rank"&&p.query).length!==1)throw new d("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=Zu(r),[s]=i;if(i.length!==1||!s)throw new d("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=Z(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(p=>{if(p.name!==e.name)return p;const l={...p};return delete l.query,ed(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:p})=>p).filter(p=>!!p),c=Z(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(p=>({pred:p,name:p}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},rd={name:"$rank",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} rank`:`${t}\u6392\u540D`,kind:"window",windowFunction:"rank",rewriteLogicform({logicform:t}){if(t.groupby?.length)return;const e=t.preds?.find(r=>r.operator==="$rank"&&r.query);return e?.query?td(t,e,e.query):void 0},validatePlan({pred:t,groupByNames:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(e.length===0&&!t.query&&typeof t.pred!="string")throw new d("RANK_GROUPBY_OR_TARGET_REQUIRED","$rank requires groupby or a pred.query target used to infer the ranking dimension")},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},nd={name:"$rowNumber",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},od=new Set(["string","number","boolean","date","entity","object"]),Cn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&od.has(t))return{type:t,primal_type:t};throw new d("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},id={name:"$constant",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(t.pred!==void 0)throw new d("INVALID_CONSTANT_INPUT","$constant does not accept pred");return Cn(t.args?.type),t},toSQL({args:t,sql:e}){return Cn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...Cn(e.type),isArray:!1}}},sd={name:"$periodBoundary",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D":"\u671F\u672B"}`,defaultNameKey:({args:t})=>`operator.$periodBoundary.${t.boundary==="start"?"start":"end"}`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=e.boundary;if(n!=="start"&&n!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=e.granularity;if(typeof o!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");const i=r.dateBucket(t,o);return r.datePeriodBoundary?r.datePeriodBoundary(t,o,n):n==="start"?i:r.dateShift(r.dateShift(i,o,1),"second",-1)},planExpression({input:t,inputProperty:e,args:r}){if(!t)return;const n=e?.granularity??r.granularity;return{kind:"operator",operator:"$periodBoundary",input:t,args:{...r,granularity:n}}},normalizePred({pred:t,schema:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodBoundary requires one pred");if(typeof t.pred=="string"){const r=e.properties.find(({id:n,name:o})=>n===t.pred||o===t.pred);return{...t,args:{...t.args,granularity:r?.granularity}}}return t},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=e.granularity??r.granularity;if(typeof n!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...e,name:t,granularity:n,isArray:!1}}},Pi="__scalarExtremumInputs",Dn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Dn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Dn(r)??[]))];if(e.length===1)return e[0]}},ad=t=>{const e=Z(t);return delete e.from,delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.representation,delete e.output,e},cd=(t,e)=>{if(e.args?.[Pi]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new d("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${e.operator} with multiple pred inputs must be the only LogicForm projection`);const r=e.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:Z(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??Dn(s);return{...s,name:a,...u?{schema:u}:{}}}),n=ad(t);return n.preds=r,{version:t.version,from:n,preds:[{operator:e.operator,pred:r.map(({name:o})=>o),...e.name?{name:e.name}:{},args:{...e.args,[Pi]:!0}}],...t.having?{having:t.having}:{},...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},ud=(t,e)=>{const r=t==="$least"?"MIN":"MAX",n=e.map(o=>`SELECT ${o} AS value`).join(" UNION ALL ");return`(SELECT ${r}(value) FROM (${n}) AS __scalar_extremum_values)`},dd=(t,e,r)=>{const[n,...o]=r??[];if(!n)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new d("INCOMPATIBLE_OPERATOR_INPUTS",`${t} pred inputs must have the same primal type`);return{...n,name:e,isArray:!1}},Li=t=>({name:t,defaultName:({inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t==="$least"?"Least":"Greatest"} of ${e.join(", ")}`:`${e.join("\u3001")}\u4E2D\u7684${t==="$least"?"\u6700\u65E9\u503C":"\u6700\u665A\u503C"}`,kind:"scalar",requiresProperty:!1,normalizePred({pred:e}){if(!Array.isArray(e.pred)||e.pred.length<2)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires at least two pred inputs`);return e},rewriteLogicform({logicform:e}){const r=e.preds?.[0];return r?.operator===t?cd(e,r):void 0},toSQL(e){const r=At(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??ud(t,r)},getOutputProperty({name:e,inputProperties:r}){return dd(t,e,r)}}),ld=Li("$least"),pd=Li("$greatest"),kn={second:{en:"second",zh:"\u79D2"},minute:{en:"minute",zh:"\u5206\u949F"},hour:{en:"hour",zh:"\u5C0F\u65F6"},weekday:{en:"weekday",zh:"\u661F\u671F"},day:{en:"day",zh:"\u65E5"},week:{en:"week",zh:"\u5468"},month:{en:"month",zh:"\u6708"},quarter:{en:"quarter",zh:"\u5B63\u5EA6"},year:{en:"year",zh:"\u5E74"}},fd={name:"$length",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} length`:`${t}\u957F\u5EA6`,kind:"scalar",toSQL({expression:t,sql:e}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$length requires a pred");return e.stringLength(t)},getOutputProperty({name:t,inputProperty:e}){if(!e||e.primal_type!=="string"||e.isArray)throw new d("LENGTH_STRING_REQUIRED","$length requires a scalar string-valued pred");return{name:t,type:"int",primal_type:"number",isArray:!1}}},md=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${kn[t].en}`:`${e}${kn[t].zh}`,kind:"scalar",toSQL({expression:e,sql:r}){if(!e)throw new d("PRED_PROPERTY_REQUIRED",`$${t} requires a pred`);return r.datePart(e,t)},getOutputProperty({name:e,inputProperty:r}){if(!r||r.primal_type!=="date"||r.isArray)throw new d("DATE_PART_DATE_REQUIRED",`$${t} requires a scalar date-valued pred`);return{name:e,type:"int",primal_type:"number",isArray:!1}}}),yd=Object.freeze(Object.keys(kn).map(md)),Ci=Object.freeze([uc,Qu,Iu,bu,gu,Du,Lu,du,vu,Vu,hu,ju,Mu,lc,Hu,ku,Tu,dc,Gu,_u,Su,Wu,Ou,Xu,rd,nd,id,sd,ld,pd,fd,...yd]),hd={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},gd={name:"category",primalType:"string"},Ad={name:"currency",primalType:"number"},wd={name:"date",primalType:"date"},$d={name:"duration",primalType:"number"},Di=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),Ed={name:"object",primalType:"object",hydrateResult:Di},_d={name:"entity",primalType:"entity",hydrateResult:Di},Sd={name:"file",primalType:"string"},Id={name:"humanName",primalType:"string"},bd={name:"ID",primalType:"string"},Rd={name:"image",primalType:"string"},Nd={name:"int",primalType:"number"},Od={name:"name",primalType:"string"},Td={name:"number",primalType:"number"},Pd={name:"order",primalType:"number"},Ld={name:"percentage",primalType:"number"},Cd={name:"string",primalType:"string"},Dd={name:"timestamp",primalType:"date"},Un=Object.freeze([bd,Cd,Od,Id,gd,Rd,Sd,Td,Nd,Ad,Ld,$d,Pd,hd,Dd,wd,_d,Ed]),kd=(t,e,r)=>{if(typeof t=="function")return t;if(typeof t!="string"||t.trim().length===0)return;const n=new Function(`return (${t})`)();if(typeof n!="function")throw new TypeError(`Operator ${r} ${e} must resolve to a function`);return n},ki=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Operator definition must be an object");const e=t,r=e.name,n=typeof r=="string"?r:"",o=e.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=kd(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=Un.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class jt{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new jt(this.definitions(),e)}register(e){const r=ki(e);if(!r.name)throw new d("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new d("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new d("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new d("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(e){const r=this.#e.get(e);if(!r)throw new d("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return r}requiresPerPeriodEvaluation(e,r){return this.get(e).requiresPerPeriodEvaluation?.({...r,executionContext:this.executionContext})??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const Ud=Object.freeze([...Ci,...gi.flatMap(({operators:t})=>t??[])]),ke=(t=[])=>new jt([...Ci,...pe(t).flatMap(({operators:e})=>e??[])]),St=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Ui=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Md=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Mi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",qd=(t,e)=>{const r=fc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},qi=(t,e,r)=>{const n=t.fieldReferences?.[r];return n?{schemaId:n.schemaId,propertyId:n.propertyId??n.column,propertyName:n.property,physicalColumn:n.sql??n.column}:qd(e,r)},Ht=(t,e,r,n)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>Ht(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>Ht(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=Ht(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>Ht(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Sr(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>qi(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function Sr(t){if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&e.push(...Sr(o));else r==="$expr"&&Mi(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const ve=t=>t.kind==="window"?[...ve(t.input),...t.partitionBy.flatMap(ve)]:t.kind==="cumulative"?[...ve(t.input),...t.partitionBy.flatMap(ve),...t.orderBy.flatMap(({expression:e})=>ve(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?ve(t.input):t.kind==="operator"?[...Sr(t.query),...t.input?ve(t.input):[],...(t.inputs??[]).flatMap(ve)]:[],ji=(t,e,r,n=ke(),o)=>{if(t.subplans){const s=t.subplans.map(u=>ji(u,e,r,n,o)),a=new Map;for(const u of s){u.source.connectionId&&a.set(u.source.connectionId,u.source.provider);for(const c of u.source.connections??[])a.set(c.connectionId,c.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:u})=>u.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([u,c])=>({connectionId:u,provider:c}))},outputs:t.projections.map(({name:u})=>{const c=s.flatMap(({outputs:p})=>p.filter(l=>l.name===u));return{name:u,sources:c.flatMap(({sources:p})=>p),transformations:[...new Set([...c.flatMap(({transformations:p})=>p),"compose"])]}}),filters:s.flatMap(({filters:u})=>u)}}const i=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source,...(t.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...Ht(s.expression,t,e,n)})),filters:[...new Set([...Sr(t.query),...t.projections.flatMap(({expression:s})=>ve(s))])].map(s=>qi(t,e,s))}},Ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),jd=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,xi=t=>{const e=jd.exec(t);if(!e)return;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);if(!(r>23||n>59||o>59))return{hour:r,minute:n,second:o}},Bi=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new d("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!xi(e.expireAt))throw new d("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone}).format()}catch{throw new d("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}},xd=new Set(["second","minute","hour","day","week","month","quarter","year"]),Mn=t=>typeof t=="string"&&xd.has(t),qn=(t,e=pe())=>Mn(t)||typeof t=="object"&&t!==null&&!Array.isArray(t)&&e.some(r=>{const n=r.mappingGranularity;return n!==void 0&&n.kind===t.kind&&n.isGranularity(t)});class jn{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=pe(r);for(const n of e)this.register(n)}register(e){for(const s of this.plugins){const a=s.schemaMapping?.validate?.(e);if(a)throw new d("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${s.name}: ${a}`,{plugin:s.name,reason:a})}if(!e.schemaId)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");const r=new Set,n=new Set;for(const s of e.enrichments??[]){if(!s.id||r.has(s.id))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");if(!s.source||s.source===e.source||n.has(s.source))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(s.sourceSql!==void 0&&s.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sourceSql must not be empty");if(s.on.length===0||s.on.some(({baseColumn:a,targetColumn:u})=>!a||!u))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(s.temporal?.kind==="point"&&!s.temporal.pointColumn)throw new d("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");Bi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!qn(s.granularity,this.plugins)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping granularity requires a property item and a supported physical granularity");if(s.mappingType==="property"&&(!s.sourceColumn||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||!s.predItem?.operator||typeof s.predItem.pred!="string"))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred");if(s.sourceRef!==void 0&&(s.mappingType!=="property"||!r.has(s.sourceRef)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceRef requires a property item and a registered enrichment id")}Bi(e);const o=this.#e.get(e.schemaId)??[],i=e.id??e.source;if(o.some(s=>s.connectionId===e.connectionId&&((s.id??s.source)===i||s.source===e.source)))throw new d("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${i}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:i});return this.#e.set(e.schemaId,[...o,e]),this}get(e,r){const n=this.list(e),o=r===void 0?n:n.filter(s=>s.connectionId===r);if(o.length===0)throw new d("SCHEMA_MAPPING_CONNECTION_NOT_FOUND",`Schema ${e} has no mapping on connection ${r}`,{schemaId:e,connectionId:r});if(o.length===1)return o[0];const i=o.filter(s=>(s.mappings??[]).length===0);if(i.length===1)return i[0];throw new d("SCHEMA_MAPPING_AMBIGUOUS",r===void 0?`Schema ${e} has multiple mappings and requires LogicForm-based selection`:`Schema ${e} has multiple mappings on connection ${r} and requires LogicForm-based selection`,{schemaId:e,...r===void 0?{}:{connectionId:r},mappingIds:o.map(s=>s.id??s.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Bd=t=>{if(t.tablePath?.trim())return t.tablePath;const e=[t.physicalDatabase,t.physicalSchema,t.physicalTable].filter(r=>!!r?.trim());if(e.length>0)return e.join(".");if(t.sourceSql?.trim())return t.sourceSql;throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping ${t.id} has no physical source`)},Vd=(t,e=[])=>{const r=pe(e);if(!t.schemaSid||!t.datasourceSid)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(t.enabled===!1)throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("dimensions"in t)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const n=[];for(const o of t.mappings){if(o.granularity!==void 0&&(o.mappingType!=="property"||!qn(o.granularity,r)))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires a property item and a supported physical granularity");if(o.mappingType==="property"){if(!o.sourceColumn||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:Bd(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Vi{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${e.name}`,{rule:e.name});return this.#e.set(e.name,e),this}resolveProjection(e){return[...this.#e.values()].reduce((r,n)=>n.resolveProjection?.({...e,outputProperty:r})?.outputProperty??r,e.outputProperty)}resolveQuery(e){return[...this.#e.values()].reduce((r,n)=>n.resolveQuery?.({...e,...r?{query:r}:{}})??r,e.query)}rules(){return[...this.#e.values()]}}const Fi=(t=[])=>new Vi([...pe(t).flatMap(e=>e.plannerSemantics??[])]);se.extend(jo),se.extend(xt),se.extend(dr);const It=["second","minute","hour","day","week","month","quarter","year"],Fd=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),Yd="YYYY-MM-DD HH:mm:ss",bt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),vd=(t,e)=>t==="week"?e==="week":e==="week"?It.indexOf(t)<=It.indexOf("day"):It.indexOf(t)<=It.indexOf(e),Yi=(t,e,r)=>{if(typeof t!="string")return"second";const n=se(t,Yd,!0);if(!n.isValid())return"second";for(const o of[...It].reverse()){const i=o==="week"?n.startOf("isoWeek"):n.startOf(o),s=o==="week"?n.endOf("isoWeek"):n.endOf(o),a=e==="lower"?r?i:s:r?s:i;if(n.isSame(a.millisecond(0),"second"))return o}return"second"},vi=t=>{if(!t||typeof t!="object"||Array.isArray(t))return["second"];const e=Object.entries(t);return e.length===0?["second"]:e.flatMap(([r,n])=>Fd.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(vi):["second"]:r==="$gte"||r==="$gt"?[Yi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[Yi(n,"upper",r==="$lte")]:["second"])},Qd=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&It.includes(n))return n}return e.granularity??"day"}},Hd=(t,e,r,n,o=pe(),i=ke(o))=>{const s=r.mappings??[],a=s.filter(h=>h.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(h=>!qn(h.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(h=>Mn(h.granularity)&&!h.propertyTarget?.every(_=>bt(e,_)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const h of a)for(const _ of o){const E=_.mappingGranularity;if(!E||!E.isGranularity(h.granularity))continue;const I=E.validateItem?.(h,u);if(I)return I}if(!(a.length>0))return;const l=h=>s.find(_=>_.mappingType==="property"&&_.propertyTarget?.some(E=>bt(e,E)?.id===h.id)),f=(h,_,E="filterOrGroup")=>{const I=bt(e,h);if(!I)return`property is not available: ${h}`;const $=l(I);if(!$&&!(E==="operand"&&s.some(A=>A.mappingType==="predItem"&&typeof A.predItem?.pred=="string"&&bt(e,A.predItem.pred)?.id===I.id)))return`property is not available on grouped source: ${h}`;if(E==="filterOrGroup"&&I.primal_type==="number"&&I.type!=="category"&&I.type!=="ID")return`measure cannot be used as a grouped source dimension: ${h}`;if(I.primal_type==="date"&&(!$?.granularity||!Mn($.granularity)||!vd($.granularity,_??I.granularity??"day")))return`time dimension ${h} is too coarse for ${_}`};function m(h){if(h)for(const[_,E]of Object.entries(h)){if(E===void 0)continue;if(_==="$and"||_==="$or"){if(!Array.isArray(E))return"unsupported dimension query";for(const A of E){const R=m(A);if(R)return R}continue}if(_==="$expr"){if(typeof E!="object"||E===null||Array.isArray(E))return"unsupported expression query";const A=E.pred;if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const R=y(A);if(R)return R;continue}if(_.startsWith("$"))return"unsupported dimension query";const I=bt(e,_);if(!I)return`dimension property is not available: ${_}`;const $=I.primal_type==="date"?vi(E):[void 0];for(const A of $){const R=f(_,A);if(R)return R}}}function y(h){const _=m(h.query);if(_)return _;const E=Array.isArray(h.pred)?h.pred:h.pred===void 0?[]:[h.pred];for(const I of E){const $=typeof I=="string"?f(I,void 0,"operand"):y(I);if($)return $}}const g=m(t.query);if(g)return g;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const h of t.preds){const _=y(h);if(_)return _;if(typeof h.pred!="string"||!h.operator||!i.get(h.operator).supportsGroupedSourceRollup)return`PredItem ${h.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const h of t.groupby??[]){if(typeof h.pred!="string")return"computed groupby is not covered by the grouped source";const _=bt(e,h.pred);if(!_)return`groupby property is not available: ${h.pred}`;if(h.operator!==void 0&&!i.get(h.operator).supportsGroupedSourceGroupby&&!o.some(I=>I.mappingGranularity?.supportsGroupby?.(h)))return`computed groupby is not covered: ${h.pred}`;const E=f(h.pred,Qd(h,_,i));if(E)return E}for(const h of o){const _=h.mappingGranularity?.candidateReason?.(t,u);if(_)return _}};function Gt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Gt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Gt(e)):[]]}const xn=t=>t.id??t.source,Ir=(t,e)=>{if(t===e)return!0;if(t instanceof Date||e instanceof Date)return t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,i)=>Ir(o,e[i]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const r=Object.entries(t),n=e;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&Ir(i,n[o]))},Rt=t=>{if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=Rt(o);if(!i)return;e.push(...i)}continue}if(r==="$expr"){if(typeof n!="object"||n===null||Array.isArray(n))return;const o=n.pred;if(typeof o!="object"||o===null||Array.isArray(o))return;const i=Gt(o);if(i.length===0)return;e.push(...i.map(s=>({property:s,condition:{$expr:n}})));continue}if(r.startsWith("$"))return;e.push({property:r,condition:n})}return e},Bn=(t,e,r)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>Bn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>br(r,s.property,o)&&Ir(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},at=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),br=(t,e,r)=>e===r||at(t,e)?.id===at(t,r)?.id&&at(t,e)!==void 0&&at(t,r)!==void 0,be=(t,e,r)=>Rr(t,e,r)?.column,Rr=(t,e,r)=>{const n=at(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>br(e,s,r)));return o?.sourceColumn?{column:o.sourceColumn,...o.sourceRef?{sourceRef:o.sourceRef}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property")?void 0:{column:n.id}},Vn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||be(t,e,r)!==void 0,Qi=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=Rt(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Vn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},Gd=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?at(r,e.pred):void 0,s=at(r,t.match.pred),a=typeof e.pred=="string"&&br(r,e.pred,t.match.pred)&&!!(i&&s);if(e.operator!==t.match.operator||!a||Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const u=Rt(t.match.query);return u!==void 0&&u.every(c=>o.some(p=>br(r,p.property,c.property)&&Ir(p.condition,c.condition)))},Wd=(t,e,r,n,o,i=ke(o))=>{const s=(r.mappings??[]).flatMap(h=>{if(h.mappingType!=="predItem"||!h.sourceColumn||!h.predItem||!h.predItem.operator||typeof h.predItem.pred!="string")return[];const _=h.predItem,E=_.operator,I=_.pred;return!E||typeof I!="string"?[]:[{match:{operator:E,pred:I,..._.schema?{schema:_.schema}:{},..._.query?{query:_.query}:{}},column:h.sourceColumn}]}),a=(r.mappings??[]).some(h=>h.mappingType==="property");if(s.length===0&&!a){const h={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const _ of o??[]){const E=_.schemaMapping?.candidateReason?.(t,h);if(E)return E}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=Rt(t.query);if(!u&&s.length>0)return"query contains $or or another unsupported logical expression";const c=Z(t),p=[],l=[];for(const[h,_]of(t.preds??[]).entries()){const E=Rt(_.query);if(!E&&s.length>0)return`PredItem ${h} query contains an unsupported logical expression`;if(s.length>0){const $=[...u??[],...E??[]],A=s.filter(U=>Gd(U,_,e,_.schema??e.id,$));if(A.length===0)return`PredItem ${h} is not mapped`;if(A.length>1)return`PredItem ${h} matches multiple mapping rules`;const R=A[0],L=Rt(R.match.query)??[];l.push(...L);const D=c.preds?.[h];if(D){const U=Bn(D.query,L,e);U?D.query=U:delete D.query}p.push({predIndex:h,column:R.column});continue}const I=Gt(_).find($=>!Vn(r,e,$));if(I)return`PredItem ${h} property is not available: ${I}`}const f=Bn(c.query,l,e);f?c.query=f:delete c.query;const m=Qi(c.query,r,e);if(m)return m;for(const[h,_]of(c.preds??[]).entries()){const E=Qi(_.query,r,e);if(E)return`PredItem ${h} ${E}`}for(const h of c.groupby??[]){const E=Gt(h).find(I=>!Vn(r,e,I));if(E)return`groupby property is not available: ${E}`}const y=Hd(c,e,r,n,o,i);if(y)return y;const g={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const h of o??[]){const _=h.schemaMapping?.candidateReason?.(c,g);if(_)return _}return{mapping:r,logicform:c,predRewrites:p,priority:r.priority??0,specificity:p.length}},zd=(t,e,r,n={})=>{const o=n.plugins?pe(n.plugins):r.plugins,i=n.operators??ke(n.plugins),s=[],a=[];for(const l of r.list(e.id)){const f=Wd(t,e,l,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:xn(l),reason:f}):s.push(f)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:e.id,requiredDataLayer:"detail",rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(u.length>0?u:s).reduce((l,f)=>f.priority>l.priority||f.priority===l.priority&&f.specificity>l.specificity?f:l);for(const l of s){if(l===p)continue;let f;u.length>0&&l.mapping.connectionId!==n.preferredConnectionId?f=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?f=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?f=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:xn(l.mapping),reason:f})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:xn(p.mapping),rejectedMappings:a}}},Wt=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),zt=(t,e)=>Wt(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?zt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&zt(r,e)),Hi=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?zt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&zt(r,e)),Gi=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),Kd=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!Wt(m,e)&&Hi(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(Gi).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const y=i();return s.push(typeof m=="string"?{pred:m,name:y}:{...Z(m),name:y}),y},u=m=>{if(m.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const y=Z(m);return Array.isArray(m.pred)?y.pred=m.pred.map(g=>typeof g=="string"||!zt(g,e)||Wt(g,e)?a(g):u(g)):m.pred&&typeof m.pred=="object"&&(y.pred=Wt(m.pred,e)?a(m.pred):u(m.pred)),y},c=r.map(m=>{const y=m.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Wt(m,e)&&Hi(m,e)?{...u(m),name:y}:(s.push({...Z(m),name:y}),{pred:y,name:y})}),p=Z(t);p.preds=s,delete p.having,delete p.sort,delete p.limit,delete p.limitBy,delete p.page,delete p.output,delete p.representation;const l=(t.groupby??[]).map(m=>{const y=Gi(m);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),f=Z(t);return f.from=p,f.preds=[...l,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},Jd=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Wi=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:Jd(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},zi=(t,e)=>({...Wi(t,e),id:e.id,name:e.name,type:e.type}),Fn=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},Nr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Nr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Nr(e)):[]],Yn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Yn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Yn(r,e))}:{}}),Ki=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Ki(o,e))];if(r==="$expr"&&typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=n.pred;if(typeof o=="object"&&o!==null&&!Array.isArray(o))return[r,{...n,pred:Yn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),vn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Ie(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Ji=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Ji(i,e))];if(r==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const o=e.find(({name:i})=>i===r)?.comparable;return o&&vn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),Xd=(t,e,r)=>{if(!e.udf)return{};const o=e.udf.sql.includes("$TS")?t.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:e.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},Xi=t=>t.sql?{kind:"property-sql",schemaId:t.schemaId,property:t.property,propertyId:t.column,sql:t.sql,qualifier:t.qualifier,...t.timestampColumn?{timestampColumn:t.timestampColumn}:{},...t.timestampQualifier?{timestampQualifier:t.timestampQualifier}:{}}:{kind:"column",...t},Zi=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...r}),Nt=(t,e,r,n,o,i,s,a,u="projection")=>{const c=Fn(t);if(u==="groupby"&&t.query)throw new d("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new d("PRED_PROPERTY_REQUIRED","A projection must reference a property");const $=r(t.pred);return{expression:Xi($.field),outputProperty:Zi($.reference,$.property),sourceProperty:$.property,sourceField:$.field}}const p=e.get(t.operator);if(u==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(u==="groupby"&&!p.toSQL)throw new d("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(p.planInput&&typeof t.pred!="string")throw new d("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const l=p.planInput&&typeof t.pred=="string"?p.planInput({executionContext:e.executionContext,reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=l?.reference??t.pred,m=l?.args??t.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?Nt(f,e,r,n,o,i,s,a,u):typeof f=="string"?Nt({pred:f,name:f},e,r,n,o,i,s,a,u):void 0,g=Array.isArray(f)?f.map($=>Nt(typeof $=="string"?{pred:$,name:$}:$,e,r,n,o,i,s,a,u)):[];if(p.requiresProperty!==!1&&!y&&g.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const h=c,_=p.getOutputProperty?.({executionContext:e.executionContext,name:h,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:h}}:{},...g.length>0?{inputProperties:g.map(({outputProperty:$})=>$)}:{},args:m}),E=_?.description??p.description??y?.outputProperty.description,I={..._??(y?Zi(h,y.outputProperty,{isArray:!1}):{name:h,type:"number",primal_type:"number",isArray:!1}),...E!==void 0?{description:E}:{}};if(p.planExpression){const $=p.planExpression({executionContext:e.executionContext,pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:g.map(({expression:A})=>A),args:m,resolveKey:o,getOperator:A=>e.get(A),planQuery:i});if($)return{expression:$,outputProperty:I,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(p.kind==="window"){if(!y||g.length>0||t.query)throw new d("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const $=t.args?.direction??"desc";if($!=="asc"&&$!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const A=t.args?.partitionBy??[];if(!Array.isArray(A)||A.some(R=>typeof R!="string"))throw new d("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:p.windowFunction,input:y.expression,partitionBy:A.map(R=>n(String(R))),direction:$==="asc"?"ASC":"DESC"},outputProperty:I}}return{expression:{kind:"operator",operator:t.operator,args:m,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...g.length>0?{inputs:g.map(({expression:$})=>$)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:I,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},Zd=(t,e,r,n,o,i,s,a,u,c,p,l=t)=>{const f=Fn(t),m=typeof t.pred=="string"?t.pred:void 0,y=!c||!m?r:E=>{const I=r(E);return E===m?{...I,field:{...I.field,column:c}}:I},g=p?{...t,operator:p}:t,h=Nt(g,e,y,n,o,i,s,a),_=u?.resolveProjection({pred:l,schema:s,executionContext:e.executionContext,...h.sourceProperty?{sourceProperty:h.sourceProperty}:{},outputProperty:{...h.outputProperty,name:f},...l.operator?{operator:e.get(l.operator)}:{}})??{...h.outputProperty,name:f};return{name:f,expression:h.expression,outputProperty:_}},el=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new d("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new d("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},Qn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},tl=(t,e,r,n,o,i)=>{if(e.length<2)throw new d("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(g=>Le(g,Qn(g,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:g})=>g)??[];for(const g of s){const h=g.groupBy.map(({name:_})=>_);if(h.length!==a.length||h.some((_,E)=>_!==a[E]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:h});if(g.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new d("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],p=new Map;s.forEach((g,h)=>{g.projections.forEach((_,E)=>{const I=a.includes(_.name),$=p.get(_.name);if($!==void 0&&!I)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${_.name}`,{name:_.name,childIndexes:[$,h]});if($!==void 0)return;p.set(_.name,h),u.push({name:_.name,expression:{kind:"column",property:_.name,column:_.name}});const A=g.columnProperties?.[E];A&&c.push(A)})});const l=new Set(u.map(({name:g})=>g)),f=Object.entries(t.sort??{}).map(([g,h])=>{if(!l.has(g))throw new d("INVALID_SORT",`Sort field is not an output: ${g}`);const _=c.find(E=>E.name===g);return{name:g,direction:h===1?"ASC":"DESC",..._?.comparable?{comparable:_.comparable}:{},..._?.comparable?{expression:{kind:"column",property:g,column:g}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const g=a.at(-1)??"",h=c.find(_=>_.name===g);return[{name:g,direction:"ASC",...h?.comparable?{comparable:h.comparable}:{}}]})()},y=t.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:t.limitBy}:t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit};return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(u.map(({name:g})=>[g,g])),projections:u,columnProperties:c,groupBy:u.filter(({name:g})=>a.includes(g)),...t.having?{having:Ji(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},Le=(t,e,r=ke(),n=new jn,o={})=>{const i=[...new Set((t.preds??[]).map(w=>w.schema).filter(w=>!!(w&&w!==e.id)))];if(i.length>0){const w=t.propertyResolve??{},S=[e.id,...i].map(b=>{const{having:O,sort:k,limit:j,limitBy:Q,page:W,...T}=t,re=H=>{let M=H;try{M=ae(e,H,o.resolveSchema).canonicalName}catch{}return w[b]?.[H]??w[b]?.[M]??H};return{...T,schema:b,preds:(t.preds??[]).filter(H=>(H.schema??e.id)===b).map(({schema:H,...M})=>M),...b===e.id||!t.query?{}:{query:Ki(t.query,re)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(H=>({...H,...typeof H.pred=="string"?{pred:re(H.pred)}:{}}))}:{}}});return tl(t,S,e,r,n,o)}const s=Kd(t,r);if(s)return Le(s,e,r,n,o);for(const w of t.preds??[]){if(!w.operator)continue;const S=r.get(w.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:b=>r.get(b)});if(S)return Le(S,e,r,n,o)}const a=o.semanticRegistry??Fi(o.plugins);if(t.from){const w=Qn(t.from,e,o),S=Le(t.from,w,r,n,o),b=zi(S,e),O={...t};delete O.from,O.schema??=b.id;const k=Le(O,b,r,n,o),j=new Set(k.projections.map(({name:M})=>M)),Q=S.rowIdentity.kind==="group"&&S.rowIdentity.names.every(M=>j.has(M))||S.rowIdentity.kind==="singleton"?S.rowIdentity:{kind:"generated"},W=S.groupBy.map(({name:M})=>M).filter(M=>j.has(M)),T=W.at(-1),re=S.columnProperties?.find(M=>M.name===T),H=t.limitBy!==void 0&&W.length>0?{count:t.limitBy,partitionBy:W.slice(0,-1),orderBy:k.orderBy.length>0?k.orderBy:W.slice(-1).map(M=>({name:M,direction:"ASC",...re?.comparable?{comparable:re.comparable}:{}}))}:void 0;return{...k,source:S.source,sourcePlan:S,sourceLogicform:t.from,rowIdentity:Q,...H?{groupLimit:H}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const u=zd(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const c=new Map(u.predRewrites.map(({predIndex:w,column:S})=>[w,S])),p=wi(e,o.plugins),l=Xc(t,e,o.plugins),f=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),m=l?.rewriteQuery?l.rewriteQuery(f):f,y=e.id,g=new Map,h=new Map,_=new Map,E=new Map,I=w=>{const S=h.get(w);if(S)return S.alias;const b=u.mapping.enrichments?.find(j=>j.id===w);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${w}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:w});const O=`__enrichment_${w}`,k=b.temporal?(()=>{if(!p)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${w} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:w});const j=Rr(u.mapping,e,p.start.name),Q=Rr(u.mapping,e,p.end.name);if(!j||!Q)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${w} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:w});if(j.sourceRef||Q.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${w} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:w});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:j.column,endColumn:Q.column}})():void 0;return h.set(w,{kind:"enrichment-left",id:w,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:O,baseAlias:y,keys:b.on,...k?{temporalCondition:k}:{}}),O},$=w=>{const S=ae(e,w,o.resolveSchema);let b=y,O=u.mapping;const k=[];for(const T of S.relations){k.push(T.property.name);const re=k.join("_"),H=re,M=n.get(T.targetSchema.id,u.mapping.connectionId);if(O=M,!g.has(re)){const ie=T.targetSchema.properties.filter(({type:N})=>N==="ID"),[K]=ie;if(ie.length!==1||!K)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${T.targetSchema.id} must contain exactly one ID property`,{schemaId:T.targetSchema.id,count:ie.length});const ge=T.sourceSchema.id===e.id?u.mapping:n.get(T.sourceSchema.id,u.mapping.connectionId),_e=be(ge,T.sourceSchema,T.property.name)??T.property.id,Ne=be(M,T.targetSchema,K.name)??K.id,Oe=T.sourceSchema.properties.find(({type:N})=>N==="timestamp"),Be=T.targetSchema.properties.find(({type:N})=>N==="timestamp"),ye=Jc(T.sourceSchema,T.targetSchema,o.plugins),Ve=Oe?be(ge,T.sourceSchema,Oe.name)??Oe.id:void 0,yt=Be?be(M,T.targetSchema,Be.name)??Be.id:void 0,tt=ye?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:be(ge,T.sourceSchema,ye.sourceTimestamp.name)??ye.sourceTimestamp.id,targetColumn:be(M,T.targetSchema,ye.targetTimestamp.name)??ye.targetTimestamp.id,sourceGranularity:ye.sourceTimestamp.granularity??"day",targetGranularity:ye.targetTimestamp.granularity??"day"}:ye?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:be(ge,T.sourceSchema,ye.point.name)??ye.point.id,intervalSide:"target",startColumn:be(M,T.targetSchema,ye.start.name)??ye.start.id,endColumn:be(M,T.targetSchema,ye.end.name)??ye.end.id}:void 0,rt=T.property.isArray?re:void 0;rt&&!_.has(rt)&&_.set(rt,{path:rt,sourceAlias:b,sourceColumn:_e,...T.property.udf?{sourceSql:T.property.udf.sql,...Ve?{sourceTimestampColumn:Ve}:{}}:{},alias:`__array_${re}`}),g.set(re,{kind:"left",path:re,sourceAlias:b,sourceColumn:_e,...T.property.udf?{sourceSql:T.property.udf.sql,...Ve?{sourceTimestampColumn:Ve}:{}}:{},targetSchemaId:T.targetSchema.id,targetConnectionId:M.connectionId,targetSource:M.source,...M.sourceSql?{targetSourceSql:M.sourceSql}:{},targetAlias:H,targetColumn:Ne,...rt?{sourceArrayExpansionPath:rt}:{},...K.udf?{targetSql:K.udf.sql,...yt?{targetTimestampColumn:yt}:{}}:{},...tt?{temporalCondition:tt}:{}})}b=H}const j=Rr(O,S.schema,S.property.name);if(S.relations.length>0&&j?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${S.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:S.schema.id,property:S.property.name});const Q=j?.sourceRef?I(j.sourceRef):b,W={schemaId:S.schema.id,property:S.property.name,propertyId:S.property.id,column:j?.column??S.property.id,qualifier:Q,...S.property.isArray?{isArray:!0}:{},...S.property.comparable?{comparable:S.property.comparable}:{},...Xd(S.relations.length>0?e:S.schema,S.property,y)};return E.set(S.canonicalName,W),{reference:S.canonicalName,schema:S.schema,property:S.property,field:W}},A=w=>{if(w)for(const[S,b]of Object.entries(w))if((S==="$and"||S==="$or")&&Array.isArray(b))for(const O of b)typeof O=="object"&&O!==null&&!Array.isArray(O)&&A(O);else if(S==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const O=b.pred;typeof O=="object"&&O!==null&&!Array.isArray(O)&&Nr(O).forEach($)}else S.startsWith("$")||$(S)},R=w=>{if(Ie(w)){const S=Qn(w,e,o),b=Le(w,S,r,n,o);if(b.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${b.projections.length}`,{schemaId:w.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray(w)?w.map(R):typeof w!="object"||w===null||w instanceof Date?w:Object.fromEntries(Object.entries(w).map(([S,b])=>[S,R(b)]))},L=w=>Object.fromEntries(Object.entries(w).map(([S,b])=>{if((S==="$and"||S==="$or")&&Array.isArray(b))return[S,b.map(k=>L(k))];if(S==="$expr"){if(typeof b!="object"||b===null||Array.isArray(b))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const k=b;if(typeof k.pred!="object"||k.pred===null||Array.isArray(k.pred)||!Object.prototype.hasOwnProperty.call(k,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const j=k.pred,Q=Nt(j,r,$,q,X,L,e,o.resolveSchema,"groupby");if(Q.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const W=R(k.condition);return Q.outputProperty.comparable&&vn(W,j.name??j.operator??"$expr",Q.outputProperty.comparable.values),[S,{kind:"expression-query",expression:Q.expression,condition:Q.outputProperty.comparable?{kind:"ordinal-query",comparable:Q.outputProperty.comparable,condition:W}:W,properties:Nr(j)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const j=Object.entries(b).find(([Q])=>Et(Q,o.plugins));if(j){const[Q,W]=j,T=Et(Q,o.plugins);if(!T)throw new Error(`Query Operator disappeared: ${Q}`);const re=$(S),H=T.plan(W,{schema:re.schema,property:re.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(M,ie)=>n.get(M,ie)});return[S,{[Q]:{kind:"query-operator",operator:Q,value:H.value,definition:T,...H.sources?{sources:H.sources}:{}}}]}}const O=S.startsWith("$")?void 0:$(S).property.comparable;return[S,O?{kind:"ordinal-query",comparable:O,condition:R(b)}:R(b)]})),D=w=>{const S=O=>{if(!O||typeof O!="object")return!1;if(Array.isArray(O))return O.some(S);const k=O;return Object.prototype.hasOwnProperty.call(k,"$and")||Object.values(k).some(S)};if(S(w))return w;const b=new Set(Object.keys(w).flatMap(O=>{if(O.startsWith("$"))return[];const k=ae(e,O,o.resolveSchema);return k.relations.length===1&&k.property.type==="ID"?[k.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(w).map(([O,k])=>{if(O==="$and"||O==="$or")return Array.isArray(k)?[O,k.map(K=>typeof K=="object"&&K!==null&&!Array.isArray(K)?D(K):K)]:[O,k];if(O.startsWith("$"))return[O,k];const j=ae(e,O,o.resolveSchema);if(j.relations.length===0)return[O,k];if(j.property.udf?.sql.includes("$TS")===!0||j.relations.some(({property:K})=>K.udf?.sql.includes("$TS")===!0))return[O,k];const W=j.relations.map(({property:K})=>K.name).join("_");if(g.has(W))return[O,k];const[T]=j.relations;if(!T)return[O,k];if(b.has(T.property.name))return[O,k];const re=T.property.name,H=j.canonicalName.slice(re.length+1),M=T.targetSchema.properties.find(({type:K})=>K==="ID");if(!M)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${T.targetSchema.id} must contain an ID property`,{schemaId:T.targetSchema.id});if(j.relations.length===1&&j.property.id===M.id)return[T.property.id,k];const ie={version:t.version,schema:T.targetSchema.id,query:H?{[H]:k}:{},preds:[{pred:M.name,name:M.name}]};return[T.property.id,{$in:ie}]}))},U=(t.groupby??[]).map(w=>{const S=Fn(w);w.operator&&r.get(w.operator).validateGroupby?.({pred:w,executionContext:r.executionContext});const b=Nt(w,r,$,q,X,L,e,o.resolveSchema,"groupby");let O=b.expression;if(l?.group===w&&(O={kind:"column",schemaId:e.id,property:l.property.name,propertyId:l.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const k=`groupby:${S}`;_.set(k,{path:k,sourceAlias:b.sourceField.qualifier,sourceColumn:b.sourceField.column,...b.sourceField.sql?{sourceSql:b.sourceField.sql,...b.sourceField.timestampColumn?{sourceTimestampColumn:b.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${_.size}`}),O={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:k}}return{name:S,expression:O,outputProperty:{...b.outputProperty,name:S,isArray:!1}}});function q(w){const S=(t.groupby??[]).findIndex(O=>typeof O.pred=="string"&&O.pred===w||O.name===w),b=S>=0?U[S]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${w}`);return b.expression}function X(w){const S=(t.groupby??[]).findIndex(O=>typeof O.pred=="string"&&O.pred===w||O.name===w),b=S>=0?U[S]:void 0;return b?b.expression:Xi($(w).field)}const F=w=>{w.operator&&r.get(w.operator).validatePlan?.({executionContext:r.executionContext,pred:w,groupByNames:U.map(({name:S})=>S),resolveGroupName:S=>{const b=(t.groupby??[]).findIndex(O=>O.name===S||typeof O.pred=="string"&&O.pred===S);return b>=0?U[b]?.name:void 0},getOperator:S=>r.get(S)}),w.pred&&typeof w.pred=="object"&&!Array.isArray(w.pred)&&F(w.pred);for(const S of Array.isArray(w.pred)?w.pred:[])F(typeof S=="string"?{pred:S}:S)};for(const w of t.preds??[])F(w);const P=[...U,...(t.preds??[]).map((w,S)=>{const b=l?.rewritePred?.(w)??w;return Zd(b,r,$,q,X,L,e,o.resolveSchema,a,c.get(S),si(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,w)})],Y=w=>Object.fromEntries(Object.entries(w).map(([S,b])=>{if((S==="$and"||S==="$or")&&Array.isArray(b))return[S,b.map(k=>Y(k))];if(S==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const O=P.find(({name:k})=>k===S)?.outputProperty.comparable;return O&&vn(b,S,O.values),[S,O?{kind:"ordinal-query",comparable:O,condition:R(b)}:R(b)]})),ce=m?D(m):void 0;A(ce);const ee=w=>{A(w.query),w.pred&&typeof w.pred=="object"&&!Array.isArray(w.pred)&&ee(w.pred);for(const S of Array.isArray(w.pred)?w.pred:[])ee(typeof S=="string"?{pred:S}:S)};for(const w of t.preds??[])ee(w);if(P.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");el(P);const le=new Set(P.map(({name:w})=>w)),$e=U.length>0?{kind:"group",names:U.map(({name:w})=>w),separator:"_",nullLabel:"\u7A7A\u503C"}:P.every(({expression:w})=>w.kind==="column"||w.kind==="property-sql")||P.some(({expression:w})=>w.kind==="property-sql"&&e.properties.some(({id:S,type:b})=>b==="ID"&&S===w.propertyId))?(()=>{const w=e.properties.find(({type:S})=>S==="ID");return w&&(o.canUsePropertyRowIdentity?.(e,w)??!0)?{kind:"property",column:w.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},Re=Object.entries(t.sort??{}).map(([w,S])=>{if(!le.has(w))throw new d("INVALID_SORT",`Sort field is not an output: ${w}`);const b=P.find(O=>O.name===w);return{name:w,direction:S===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),ze=t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit},me=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:U.slice(0,-1).map(({name:w})=>w),orderBy:Re.length>0?Re:(()=>{const w=U.at(-1);return[{name:w?.name??"",direction:"ASC",...w?.outputProperty.comparable?{comparable:w.outputProperty.comparable,expression:w.expression}:{}}]})()},C=E.size===0&&g.size===0&&h.size===0&&_.size===0&&!ce&&U.length===0&&P.length>0&&P.every(({expression:w})=>w.kind==="operator"&&w.operator==="$constant");return{schemaId:e.id,source:C?"":u.mapping.source,...C?{}:{connectionId:u.mapping.connectionId},...!C&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:y,fields:{...mc(e),...Object.fromEntries(e.properties.flatMap(w=>{const S=be(u.mapping,e,w.name);return S?[[w.name,S],[w.id,S]]:[]}))},fieldReferences:Object.fromEntries(E),joins:[...g.values()],enrichmentJoins:[...h.values()],arrayExpansions:[..._.values()],...l?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:l.periods,match:l.source.kind==="interval"?{kind:"interval",startColumn:be(u.mapping,e,l.source.start.name)??l.source.start.id,endColumn:be(u.mapping,e,l.source.end.name)??l.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:be(u.mapping,e,l.source.timestamp.name)??l.source.timestamp.id}}}:{},projections:P.map(({name:w,expression:S})=>({name:w,expression:S})),columnProperties:P.map(({outputProperty:w})=>w),groupBy:U.map(({name:w,expression:S})=>({name:w,expression:S})),...ce?{query:L(ce)}:{},...t.having?{having:Y(t.having)}:{},orderBy:Re,rowIdentity:C?{kind:"singleton"}:$e,...ze?{pagination:ze}:{},...me?{groupLimit:me}:{}}};class rl{provider;parameterOffset;values=[];constructor(e,r=0){this.provider=e,this.parameterOffset=r}add(e){const r=this.parameterOffset+this.values.length;return this.values.push(e),this.provider.parameter(r,e)}get nextParameterOffset(){return this.parameterOffset+this.values.length}append(e){this.values.push(...e)}}const nl=(t,e)=>{const r=e.split(".");if(r.some(n=>n.length===0))throw new d("INVALID_SOURCE",`Invalid physical source: ${e}`);return r.map(n=>t.quoteIdentifier(n)).join(".")},Or=(t,e,r)=>r===void 0?nl(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Kt=(t,e,r,n,o)=>{const i=Ti(t,[],String,`Property ${e} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:e});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},qe=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"array-element":if(!a)throw new d("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return Kt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(Te(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>qe(f,e,r,n,o,i,s,a)).join(", ")} `:"",p=qe(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(Te(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const c=qe(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>qe(f,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(f=>`${qe(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${p}ORDER BY ${l} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${qe(t.input,e,r,n,o,i,s,a)} = ${i(p)} THEN ${t.comparable.direction*l}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${qe(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(c.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(c.toSQL&&(t.input&&Te(t.input,r)||t.inputs?.some(f=>Te(f,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?qe(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const l=t.inputs?.map(f=>qe(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new d("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new d("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");p=`CASE WHEN ${o(t.query)} THEN ${p??"1"} END`}if(c.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return c.toSQL?c.toSQL({executionContext:r.executionContext,sql:{aggregateFunction:e.aggregateFunction.bind(e),quoteIdentifier:e.quoteIdentifier.bind(e),concat:e.concat.bind(e),substring:e.substring.bind(e),stringLength:e.stringLength.bind(e),datePart:e.datePart.bind(e),dateBucket:e.dateBucket.bind(e),dateShift:e.dateShift.bind(e),...e.datePeriodBoundary?{datePeriodBoundary:e.datePeriodBoundary.bind(e)}:{},...e.scalarExtremum?{scalarExtremum:e.scalarExtremum.bind(e)}:{},value:(f,m)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&e.castValue?e.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},Te=(t,e)=>t.kind==="window"?Te(t.input,e)||t.partitionBy.some(r=>Te(r,e)):t.kind==="cumulative"?Te(t.input,e)||t.partitionBy.some(r=>Te(r,e))||t.orderBy.some(r=>Te(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Te(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?Te(t.input,e):!1)||(t.inputs?.some(r=>Te(r,e))??!1)),ol=(t,e)=>t.sourceSql?Kt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`,es=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),ts={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},Jt=(t,e,r,n,o,i,s,a)=>{if(Ui(r)){if(r.operator!==e)throw new d("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const l=r.definition??s(e);if(!l)throw new d("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return l.compile(r.value,{field:t,provider:o,bind:f=>n.add(f),renderSource:(f,m)=>Or(o,f,m)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const p={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(p){const l=St(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(St(r))return`${t} ${l} (${i(r)})`;if(!Array.isArray(r))throw new d("INVALID_QUERY_VALUE",`${e} requires an array or query LogicForm`);if(r.length===0)return e==="$in"?"0 = 1":"1 = 1";const f=r.filter(St);if(f.length>0){if(f.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${f.map(i).join(" UNION ALL ")})`}const m=r.map(y=>n.add(y)).join(", ");return`${t} ${l} (${m})`}if(St(r))throw new d("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${e}`);if(e==="$exists")return`${t} IS ${r?"NOT ":""}NULL`;if(e==="$contains")return`${t} LIKE ${n.add(`%${String(r)}%`)}`;if(e==="$startsWith"){if(typeof r!="string")throw new d("INVALID_QUERY_VALUE","$startsWith requires a string");return`${t} LIKE ${n.add(`${r}%`)}`}if(e==="$regex"){if(typeof r!="string"||a!==void 0&&typeof a!="string")throw new d("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(t,n.add(r),a)}throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},Hn=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!St(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Hn(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},ct=(t,e,r,n,o,i)=>{if(Md(e)){const c=()=>`CASE ${e.comparable.values.map((m,y)=>`WHEN ${t} = ${r.add(m)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=f=>typeof f!="object"||f===null||Array.isArray(f)?ct(t,f,r,n,o,i):Object.entries(f).filter(([m])=>m!=="args").map(([m,y])=>(m==="$and"||m==="$or")&&Array.isArray(y)?`(${y.map(l).join(m==="$and"?" AND ":" OR ")})`:p.has(m)?Jt(c(),m,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):Jt(t,m,y,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return Jt(t,"$in",e,r,n,o,i);if(!es(e))return Jt(t,"$eq",e,r,n,o,i);const s=[],a=e.args;if(a!==void 0){if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_QUERY_VALUE","Query args.options must be a string");const c=a.options;if(c!==void 0&&typeof c!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const u=a?.options;for(const[c,p]of Object.entries(e))if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const l=p.map(f=>ct(t,f,r,n,o,i));s.push(`(${l.join(c==="$and"?" AND ":" OR ")})`)}else ts[c]?(Hn(p,c),s.push(ct(n.datePart(t,ts[c]),p,r,n,o,i))):c==="$length"?(Hn(p,"$length"),s.push(ct(n.stringLength(t),p,r,n,o,i))):c!=="args"&&s.push(Jt(t,c,p,r,n,o,i,c==="$regex"?u:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},rs=(t,e,r,n)=>{if(!n.arrayContains)throw new d("ARRAY_CONDITION_UNSUPPORTED",`Provider ${n.kind} does not support array conditions`);const o=n.arrayContains.bind(n),i=a=>o(t,r.add(a));if(Array.isArray(e))return`(${e.map(i).join(" OR ")})`;if(!es(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(p=>rs(t,p,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),p=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new d("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Ot=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,p]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const f=p.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${c} items must be query objects`);return Ot(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!Mi(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(ct(s(p.expression),p.condition,n,o,i,a));continue}const l=e(c);u.push(r(c)?rs(l,p,n,o):ct(l,p,n,o,i,a))}return u.join(" AND ")},Tr=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((l,f)=>`WHEN ${c} = ${r.add(l)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Gn=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},ns=(t,e,r,n)=>e.concat(t.flatMap((o,i)=>[...i>0?[`'${r.replaceAll("'","''")}'`]:[],`CASE WHEN ${o} IS NULL THEN '${n.replaceAll("'","''")}' ELSE ${e.stringify(o)} END`])),os=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:D})=>D)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),p=Gn("__sdb_row_number",i),l=Gn("__sdb_total_rows",i),f=n.quoteIdentifier(p),m=n.quoteIdentifier(l),y=Tr(e,n,o,u),g=y?`ORDER BY ${y}`:"",h=`CEIL(${m} * ${r.ratio})`,_=r.page-1,E=r.page,$=[...e.projections.map(({name:D})=>D),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(D=>`${c}.${n.quoteIdentifier(D)}`).join(", "),A=Tr(e,n,o,c),R=`SELECT ${u}.*, ROW_NUMBER() OVER (${g}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let L=`SELECT ${$} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${c}.${f} > ${_} * ${h} AND ${c}.${f} <= ${E} * ${h}`;return A&&(L+=` ORDER BY ${A}`),L},is=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:E})=>E)),p=Gn("__sdb_limit_by_row_number",c),l=r.quoteIdentifier(p),f=o.partitionBy.map(E=>`${a}.${r.quoteIdentifier(E)}`).join(", "),m=o.orderBy.map(({name:E,direction:I,comparable:$})=>{const A=`${a}.${r.quoteIdentifier(E)}`;return`${$?`CASE ${$.values.map((L,D)=>`WHEN ${A} = ${n.add(L)} THEN ${$.direction*D}`).join(" ")} END`:A} ${I}`}).join(", "),g=[...e.projections.map(({name:E})=>E),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(E=>`${u}.${r.quoteIdentifier(E)}`).join(", "),h=`PARTITION BY ${f} ORDER BY ${m}`,_=`SELECT ${a}.*, ROW_NUMBER() OVER (${h}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${g} FROM ${r.tableAlias(`(${_})`,s)} WHERE ${u}.${l} <= ${o.count}`},fe=(t,e,r=ke(),n=0)=>{const o=new rl(e,n),i=A=>Et(A);if(t.subplans){const A=t.projections.map(({name:F})=>F),R=new Set(t.groupBy.map(({name:F})=>F)),L=t.subplans.map((F,P)=>{const Y=fe(F,e,r,o.nextParameterOffset);o.append(Y.parameters);const ce=`__composition_child_${P}`,ee=e.quoteIdentifier(ce),le=new Set(F.projections.map(({name:$e})=>$e));return{aliasName:ce,alias:ee,available:le,sql:Y.sql}}),D=L[0];if(!D)throw new d("INVALID_COMPOSITION","Composition has no children");const U=A.map(F=>{const P=L.filter(ee=>ee.available.has(F)),Y=P[0]??D;return`${R.has(F)&&P.length>1?`COALESCE(${P.map(ee=>`${ee.alias}.${e.quoteIdentifier(F)}`).join(", ")})`:`${Y.alias}.${e.quoteIdentifier(F)}`} AS ${e.quoteIdentifier(F)}`}),q=L.map(F=>`${F.alias} AS (${F.sql})`);let X;if(t.rowIdentity.kind==="group"){const P=e.quoteIdentifier("__composition_keys"),Y=e.quoteIdentifier("_id");q.push(`${P} AS (${L.map(ce=>`SELECT ${Y} FROM ${ce.alias}`).join(" UNION ")})`),U.push(`${P}.${Y} AS ${Y}`),X=`WITH ${q.join(", ")} SELECT ${U.join(", ")} FROM ${P}`;for(const ce of L)X+=` LEFT JOIN ${ce.alias} ON ${P}.${Y} = ${ce.alias}.${Y}`}else{X=`WITH ${q.join(", ")} SELECT ${U.join(", ")} FROM ${D.alias}`;for(const F of L.slice(1))X+=` LEFT JOIN ${F.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const F="__composition_having",P=e.quoteIdentifier(F),Y=new Set(A),ce=Ot(t.having,ee=>{if(!Y.has(ee))throw new d("INVALID_HAVING",`Having field is not an output: ${ee}`);return`${P}.${e.quoteIdentifier(ee)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);X=`SELECT ${P}.* FROM ${e.tableAlias(`(${X})`,F)} WHERE ${ce}`}if(t.groupLimit&&(X=is(X,t,e,o)),t.pagination?.kind==="ratio")X=os(X,t,t.pagination,e,o);else if(t.orderBy.length>0&&(X+=` ORDER BY ${Tr(t,e,o)}`),t.pagination?.kind==="rows"){const F=(t.pagination.page-1)*t.pagination.pageSize;X=e.paginate(X,t.pagination.pageSize,F)}return{sql:X,parameters:o.values}}const s=A=>{if(A.plan.projections.some(({expression:L})=>Te(L,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=fe(A.plan.rowIdentity.kind==="property"||A.plan.rowIdentity.kind==="group"?{...A.plan,rowIdentity:{kind:"generated"}}:A.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(A=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(ol(A,e),A.alias,"value");return p.set(A.path,R.valueExpression),R}),f=A=>{const R=t.fieldReferences?.[A];if(R?.sql)return Kt(R.sql,R.property,e,R.timestampColumn,c?R.timestampQualifier??R.qualifier:void 0);if(R&&c)return`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;const L=t.fields[A];if(!L)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${A}`);return e.quoteIdentifier(L)},m=A=>qe(A,e,r,c,R=>Ot(R,f,L=>t.fieldReferences?.[L]?.isArray===!0,o,e,s,m,i),R=>o.add(R),(R,L)=>ct(R,L,o,e,s,i),R=>{const L=p.get(R);if(!L)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return L}),y=t.projections.map(A=>`${m(A.expression)} AS ${e.quoteIdentifier(A.name)}`),g=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const A=t.rowIdentity.names.map(R=>{const L=t.groupBy.find(D=>D.name===R)??t.projections.find(D=>D.name===R);if(!L)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return m(L.expression)});return`${ns(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,h=[...y,...g?[g]:[]].join(", "),_=t.sourcePlan?(()=>{const A=fe(t.sourcePlan,e,r,o.nextParameterOffset);return o.append(A.parameters),`(${A.sql})`})():t.source?Or(e,t.source,t.sourceSql):"",E=c&&t.sourceAlias?e.tableAlias(_,t.sourceAlias):_;let I=`SELECT ${h}`;if(t.periodSource){const A=t.periodSource,R=A.periods.map(({label:P,asOf:Y},ce)=>{const ee=o.add(P),le=o.add(Y);return ce===0?`SELECT ${ee} AS ${e.quoteIdentifier(A.labelColumn)}, ${le} AS ${e.quoteIdentifier(A.asOfColumn)}`:`SELECT ${ee}, ${le}`}).join(" UNION ALL "),L=e.tableAlias(`(${R})`,A.alias),D=e.tableAlias(_,A.sourceAlias),U=e.quoteIdentifier(A.alias),q=e.quoteIdentifier(A.sourceAlias),X=`${U}.${e.quoteIdentifier(A.asOfColumn)}`,F=A.match.kind==="interval"?(()=>{const P=`${q}.${e.quoteIdentifier(A.match.startColumn)}`,Y=`${q}.${e.quoteIdentifier(A.match.endColumn)}`;return`${P} <= ${X} AND (${Y} > ${X} OR ${Y} IS NULL)`})():(()=>{const P=e.tableAlias(_,A.match.lookupAlias),Y=e.quoteIdentifier(A.match.lookupAlias),ce=`${q}.${e.quoteIdentifier(A.match.timestampColumn)}`,ee=`${Y}.${e.quoteIdentifier(A.match.timestampColumn)}`,le=`SELECT ${e.aggregateFunction("max",ee)} FROM ${P} WHERE ${ee} <= ${X}`;return`${ce} = (${le})`})();I+=` FROM ${L} LEFT JOIN ${D} ON ${F}`,t.query&&Object.keys(t.query).length>0&&(I+=` AND ${Ot(t.query,f,P=>t.fieldReferences?.[P]?.isArray===!0,o,e,s,m,i)}`)}else E&&(I+=` FROM ${E}`);for(const A of l)I+=` ${A.joinSql}`;for(const A of t.enrichmentJoins??[]){const R=e.quoteIdentifier(A.alias),L=e.quoteIdentifier(A.baseAlias);I+=` LEFT JOIN ${e.tableAlias(Or(e,A.source,A.sourceSql),A.alias)}`;const D=A.keys.map(({baseColumn:U,targetColumn:q})=>`${L}.${e.quoteIdentifier(U)} = ${R}.${e.quoteIdentifier(q)}`);if(A.temporalCondition?.kind==="point-in-interval"){const U=Y=>Y==="source"?L:R,q=`${U(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,X=U(A.temporalCondition.intervalSide),F=`${X}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,P=`${X}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;D.push(`${F} <= ${q}`),D.push(`(${P} > ${q} OR ${P} IS NULL)`)}I+=` ON ${D.join(" AND ")}`}for(const A of t.joins??[]){I+=` LEFT JOIN ${e.tableAlias(Or(e,A.targetSource,A.targetSourceSql),A.targetAlias)}`;const R=A.sourceArrayExpansionPath?p.get(A.sourceArrayExpansionPath):A.sourceSql?Kt(A.sourceSql,A.sourceColumn,e,A.sourceTimestampColumn,A.sourceAlias):`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.sourceColumn)}`,L=A.targetSql?Kt(A.targetSql,A.targetColumn,e,A.targetTimestampColumn,A.targetAlias):`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${A.path}`);if(I+=` ON ${R} = ${L}`,A.temporalCondition?.kind==="date-bucket-equal"){const D=`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.temporalCondition.sourceColumn)}`,U=`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.temporalCondition.targetColumn)}`;I+=` AND ${e.dateBucket(D,A.temporalCondition.sourceGranularity)} = ${e.dateBucket(U,A.temporalCondition.targetGranularity)}`}else if(A.temporalCondition?.kind==="point-in-interval"){const D=P=>P==="source"?e.quoteIdentifier(A.sourceAlias):e.quoteIdentifier(A.targetAlias),U=`${D(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,q=D(A.temporalCondition.intervalSide),X=`${q}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,F=`${q}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;I+=` AND ${X} <= ${U} AND (${F} > ${U} OR ${F} IS NULL)`}}const $=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&$.push(Ot(t.query,f,A=>t.fieldReferences?.[A]?.isArray===!0,o,e,s,m,i)),$.length>0&&(I+=` WHERE ${$.join(" AND ")}`),t.groupBy.length>0){const A=t.groupBy.map(L=>m(L.expression)),R=t.rowIdentity.kind==="group"?[ns(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];I+=` GROUP BY ${[...A,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const A=R=>{const L=t.projections.find(D=>D.name===R);if(!L)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?m(L.expression):e.quoteIdentifier(R)};I+=` HAVING ${Ot(t.having,A,()=>!1,o,e,s,m,i)}`}if(t.groupLimit&&(I=is(I,t,e,o)),t.pagination?.kind==="ratio")I=os(I,t,t.pagination,e,o);else if(t.orderBy.length>0&&(I+=` ORDER BY ${Tr(t,e,o,void 0,m)}`),t.pagination?.kind==="rows"){const A=(t.pagination.page-1)*t.pagination.pageSize;I=e.paginate(I,t.pagination.pageSize,A)}return{sql:I,parameters:o.values}},il=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(h=>t.startsWith(h,o));if(y){n.push(y),o+=y.length;continue}const g=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(g?.[0]){n.push(g[0]),o+=g[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${y.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},p=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},sl=t=>`__sdb_cte_${t}`,ss=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},al=(t,e)=>t?.find(r=>r.name===e),cl=(t,e,r)=>r===0?t:e.kind==="postgresql"?t.replace(/\$(\d+)/g,(n,o)=>`$${Number(o)+r}`):e.kind==="oracle"?t.replace(/:(\d+)/g,(n,o)=>`:${Number(o)+r}`):e.kind==="clickhouse"?t.replace(/\{p(\d+):([^}]+)\}/g,(n,o,i)=>`{p${Number(o)+r}:${i}}`):t,Wn=(t,e,r,n=ke())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((E,I)=>{const $={...E.compiled,sql:cl(E.compiled.sql,r,o)};return o+=E.compiled.parameters.length,{...E,compiled:$,alias:`__sdb_exec_${I}`}}),s=i.map(({alias:E,compiled:I})=>`${r.quoteIdentifier(E)} AS (${I.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:E})=>E),p=e.orderBy??[],l=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(l){const E=I=>[...c.map($=>`${I}.${r.quoteIdentifier($)}`),`${I}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:I})=>`SELECT ${E(r.quoteIdentifier(I))} FROM ${r.quoteIdentifier(I)}`).join(" UNION ")})`)}const m=l?f:u,y=[...c,...t.flatMap(({outputs:E})=>E)],g=y.filter((E,I,$)=>$.indexOf(E)===I).map(E=>{if(c.includes(E))return`${m}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`;const I=i.find(({outputs:A})=>A.includes(E));if(!I)throw new Error(`CTE execution unit does not expose output projection: ${E}`);return`${r.quoteIdentifier(I.alias)}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`});l&&g.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let h=`SELECT ${g.join(", ")} FROM ${m}`;for(const E of l?i:i.slice(1)){const I=r.quoteIdentifier(E.alias);h+=` LEFT JOIN ${I}`,h+=l?` ON ${m}.${r.quoteIdentifier("_id")} = ${I}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const E={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:h,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map($=>[$,$])),projections:y.map($=>({name:$,expression:{kind:"column",property:$,column:$}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:p.map(({name:$,direction:A,comparable:R})=>({name:$,direction:A,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},I=fe(E,r,n,o);return{sql:`WITH ${s.join(", ")} ${I.sql}`,parameters:[...i.flatMap(({compiled:$})=>$.parameters),...I.parameters]}}return{sql:`WITH ${s.join(", ")} ${h}`,parameters:i.flatMap(({compiled:E})=>E.parameters)}},Pr=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const E of e){const I=fe(E.plan,o,i,a);a+=I.parameters.length,s.push({input:E,sql:I,alias:sl(E.name)})}const u=s.map(({sql:E,alias:I})=>`${o.quoteIdentifier(I)} AS (${E.sql})`).join(", "),c=s[0];if(!c)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(c.alias),l=r.groupBy.map(({name:E})=>E),f=l.map(E=>`${p}.${o.quoteIdentifier(E)} AS ${o.quoteIdentifier(E)}`);let m="";for(const E of s.slice(1)){const I=o.quoteIdentifier(E.alias),$=E.input.plan.groupBy.map(({name:L})=>L),R=(E.input.joinKeys??l.filter(L=>$.includes(L))).map(L=>{const D=al(E.input.groupKeyShifts,L),U=D?o.dateShift(`${I}.${o.quoteIdentifier(L)}`,D.granularity,D.offset):`${I}.${o.quoteIdentifier(L)}`;return`${p}.${o.quoteIdentifier(L)} = ${U}`});m+=` LEFT JOIN ${I} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:E,alias:I})=>[E.name,`${o.quoteIdentifier(I)}.${o.quoteIdentifier(ss(E.plan))}`])),g=il(t.expression,y),h=[...f,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:E,alias:I})=>`${`${o.quoteIdentifier(I)}.${o.quoteIdentifier(ss(E.plan))}`} AS ${o.quoteIdentifier(E.name)}`),`${g} AS ${o.quoteIdentifier(n)}`].join(", ");let _=`WITH ${u} SELECT ${h} FROM ${p}`;return _+=m,{sql:_,parameters:s.flatMap(({sql:E})=>E.parameters)}},ul=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=cs(t).length*2+2;for(let n=0;n<r;n+=1){const o=dl(e);if(o===e)return e;e=o}return e}catch{return t}},dl=t=>{const e=cs(t),r=ll(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=us(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?Rl(t.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(g=>g.trim()==="*"))continue;const u=Il(pl(t.slice(i.fromStart,i.close),i,e)),c=fl(t,i),p=ml(t,i);if(p&&yl(c,p))continue;let l=s.filter(g=>{const h=ds(g);if(!h||h==="_id")return!0;const _=new RegExp(`(^|[^\\w$])${zn(h)}([^\\w$]|$)`,"i");return _.test(u)||_.test(c)}),f=!0;for(;f;){f=!1;const g=fs(l.join(" ")),h=s.filter(_=>{if(l.includes(_))return!1;const E=ds(_);return E?new RegExp(`(^|[^\\w$])${zn(E)}([^\\w$]|$)`,"i").test(g):!1});h.length>0&&(l=s.filter(_=>l.includes(_)||h.includes(_)),f=!0)}if(l.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),y=l.length===0&&bl(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":l.map(g=>g.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},ll=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=as(t,"FROM",n);if(o===-1||!us(t,n,o)?.every(Sl))return t;const s=e.find(f=>f.open>o&&t.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const u=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(u))return t;const c=El.exec(u)?.[1],p=_l.exec(t.slice(s.close+1));if(!c||!p||ls(c)!==ls(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},pl=(t,e,r)=>hl(t,r.filter(n=>n.open>e.open&&n.close<e.close).map(n=>({start:n.open-e.fromStart,end:n.close-e.fromStart+1}))),fl=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return fs(r)},ml=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${Qe})(?=\\s|$)`,"i"))?.[1]??null,yl=(t,e)=>new RegExp(`(^|[^\\w$])${zn(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),hl=(t,e)=>{if(!e.length)return t;const r=t.split("");for(const n of e)for(let o=Math.max(0,n.start);o<Math.min(r.length,n.end);o+=1)r[o]=" ";return r.join("")},as=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
2
+ `&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},cs=t=>{const e=[],r=[];let n="",o="";for(let i=0;i<t.length;i+=1){const s=t[i],a=t[i+1];if(o==="--"){s===`
3
+ `&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),p=/^\s*SELECT\b/i.exec(c);if(!p)continue;const l=u.open+1+p.index,f=as(t,"FROM",l+6);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:l+6,fromStart:f})}return e},us=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const p=n[c];if(u){p===u&&n[c-1]!=="\\"&&(u="");continue}if(p==="`"||p==='"'||p==="'"){u=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},ds=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,Qe='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',gl=new RegExp(`\\s+AS\\s+${Qe}\\s*$`,"i"),Al=new RegExp(`\\bAS\\s+${Qe}`,"gi"),wl=new RegExp(`(?:${Qe}\\s*\\.\\s*)+${Qe}`,"g"),$l=new RegExp(`^${Qe}(?:\\s*\\.\\s*${Qe})*$`),El=new RegExp(`^\\s*(?:AS\\s+)?(${Qe})\\s+WHERE\\b`,"i"),_l=new RegExp(`^\\s*(?:AS\\s+)?(${Qe})\\s*;?\\s*$`,"i"),ls=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Sl=t=>{const e=t.replace(gl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},ps=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),fs=t=>ps(t,Al),Il=t=>ps(t,wl),bl=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),Rl=t=>{const e=t.trim();return $l.test(e)?e:null},zn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Kn=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?Kn(t.input,e):!1)||(t.inputs?.some(n=>Kn(n,e))??!1)},ms=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?ms(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({executionContext:n.executionContext,input:s,args:t.args})):i},ut=async(t,e,r)=>{const n=e.filter(({expression:o})=>Kn(o,r));return n.length===0?[...t]:Promise.all(t.map(async o=>{const i={...o};for(const s of n)i[s.name]=await ms(s.expression,i,s.name,r);return i}))},Lr=t=>t==null?"\u7A7A\u503C":typeof t=="object"?"_id"in t?String(t._id):"id"in t?String(t.id):JSON.stringify(t):String(t),Cr=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:Lr(t[o])).join(r),Jn=(t,e)=>t.map(r=>{if(e.kind==="property"){const{[e.internalName]:n,...o}=r;return{...o,_id:String(n)}}return e.kind==="group"?{...r,_id:r._id===void 0?Cr(r,e.names,e.separator,e.nullLabel):Lr(r._id)}:{...r,_id:e.kind==="singleton"?"0":rn.randomUUID()}}),Xn=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},Xt=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Xt(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Xt(r,e)),Dr=(t,e,r,n,o,i,s="zh-CN",a=yr.translator(s))=>{const u=t.preds??[],c=u.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({definition:m})=>m?.kind==="component"&&!m.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&Xt(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&Xt(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=u.filter((m,y)=>!c.some(g=>g.index===y));if(l.length>0){const m=Xn(t);m.preds=l,p.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:y,definition:g}of c){const h=g?.createComponent;if(!h)continue;const _=e.projections[f+y]?.name;if(!_)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const E=i?.preds?.[y],I=h({executionContext:n.executionContext,logicform:Xn(t),pred:E??m,outputName:_,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:Xn(i)}:{}});if("logicform"in I&&(I.logicform.preds??[]).some($=>Xt($,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in I?{...I,outputName:_}:I)}return p},je=t=>t instanceof Date?t.getTime():t,Nl=(t,e,r,n)=>{const o=je(t),i=je(r);switch(e){case"$eq":return o===i;case"$ne":return o!==i;case"$gt":return o!=null&&i!==void 0&&i!==null&&o>i;case"$gte":return o!=null&&i!==void 0&&i!==null&&o>=i;case"$lt":return o!=null&&i!==void 0&&i!==null&&o<i;case"$lte":return o!=null&&i!==void 0&&i!==null&&o<=i;case"$in":return Array.isArray(r)&&r.some(s=>je(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>je(s)!==o);case"$exists":return r?t!=null:t==null;case"$contains":return String(t).includes(String(r));case"$startsWith":return typeof t=="string"&&typeof r=="string"&&t.startsWith(r);case"$regex":return typeof r=="string"&&new RegExp(r,n).test(String(t));default:throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${e}`)}},Zn=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return je(t)===je(e);const r=Object.entries(e),n=e.args,o=n&&typeof n=="object"&&!Array.isArray(n)?n.options:void 0;return r.every(([i,s])=>{if(i==="args")return!0;if(i==="$and"||i==="$or"){if(!Array.isArray(s))return!1;const a=s.map(u=>Zn(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&Zn(t.length,s):Nl(t,i,s,typeof o=="string"?o:void 0)})},ys=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ys(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Zn(t[r],n)}),Ol=(t,e)=>e.length===0?"0":t._id===void 0?Cr(t,e):Lr(t._id),eo=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=Ol(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},to=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=eo(t,r);if(e.having&&(n=n.filter(o=>ys(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=Cr(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const p=je(a[c.name]),l=je(u[c.name]);if(p!==l)return p==null?c.direction==="ASC"?-1:1:l==null?c.direction==="ASC"?1:-1:(p<l?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=je(o[s.name]),u=je(i[s.name]);if(a!==u)return a==null?s.direction==="ASC"?-1:1:u==null?s.direction==="ASC"?1:-1:(a<u?-1:1)*(s.direction==="ASC"?1:-1)}return 0}),e.pagination?.kind==="rows"){const o=(e.pagination.page-1)*e.pagination.pageSize;n=n.slice(o,o+e.pagination.pageSize)}else if(e.pagination?.kind==="ratio"){const o=Math.ceil(n.length*e.pagination.ratio),i=(e.pagination.page-1)*o;n=n.slice(i,i+o)}return n},hs=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n};class ro{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${e.name}`,{type:e.name});return this.#e.set(e.name,e),this}get(e){const r=this.#e.get(e);if(!r)throw new d("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${e}`,{type:e});return r}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}requiresPerPeriodEvaluation(e){return e.property?this.get(e.property.type).requiresPerPeriodEvaluation?.({...e,property:e.property})??!1:!1}}const Tl=t=>{const e=new Set,r=new Set;for(const n of t){if(!n.name)throw new d("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new d("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(e.has(n.name))throw new d("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new d("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});e.add(n.name),r.add(n.id)}},gs=t=>{Tl(t);const e=t.filter(({type:r})=>r==="timestamp");if(e.length>1)throw new d("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:e.map(({name:r})=>r)})},Pl=new Set(["second","minute","hour","day","week","month","quarter","year"]),Ll=(t,e)=>{if("_id"in t||"_sid"in t)throw new d("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${t.name} must use id instead of _id; _sid is not supported`,{property:t.name});if("sid"in t)throw new d("PROPERTY_SID_NOT_ALLOWED",`Property ${t.name} must not declare sid`,{property:t.name});const r=t;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new d("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${t.name} must use comparable instead of is_comparable/comparable_order`,{property:t.name});if(t.udf!==void 0){const a=t.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const u=a,c=Object.keys(u).filter(p=>p!=="sql");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:c});if(typeof u.sql!="string"||u.sql.trim().length===0)throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf.sql must be a non-empty string`,{property:t.name})}const n=e.get(t.type),o=t.primal_type==="object"?"entity":t.primal_type;if(o!==void 0&&o!==n.primalType)throw new d("PRIMAL_TYPE_MISMATCH",`Property ${t.name} declares primal_type ${t.primal_type}, but ${t.type} requires ${n.primalType}`,{property:t.name,type:t.type,declared:t.primal_type,expected:n.primalType});if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new d("INVALID_IS_ARRAY",`Property ${t.name} isArray must be a boolean`,{property:t.name,isArray:t.isArray});if("is_observation"in t)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${t.name} must use Schema temporalSemantics; is_observation is not supported`,{property:t.name});if(t.comparable!==void 0){const a=t.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction`);const u=a;if(Object.keys(u).some(c=>c!=="values"&&c!=="direction")||!Array.isArray(u.values)||u.values.length===0||u.values.some(c=>typeof c!="string")||new Set(u.values).size!==u.values.length||u.direction!==1&&u.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1`,{property:t.name,comparable:a});if(t.type!=="category"||t.isArray===!0)throw new d("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const i={...t,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new d("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new d("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(n.primalType==="date"||t.type==="duration"){if(i.granularity!==void 0&&!Pl.has(i.granularity))throw new d("INVALID_GRANULARITY",`Property ${i.name} has unsupported granularity: ${i.granularity}`,{property:i.name,granularity:i.granularity})}else if(i.granularity!==void 0)throw new d("GRANULARITY_NOT_ALLOWED",`Property ${i.name} cannot declare granularity unless its type supports it`,{property:i.name,type:i.type});return n.validateProperty?.(i),i},As=(t,e,r=[])=>{const n=pe(r),o=n.reduce((m,y)=>y.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new d("INVALID_SCHEMA_ID","Schema id must not be empty");if(o.is_calendar!==void 0&&typeof o.is_calendar!="boolean")throw new d("INVALID_CALENDAR_SCHEMA_FLAG",`Schema ${o.id} is_calendar must be a boolean`,{schemaId:o.id,is_calendar:o.is_calendar});const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const y=Object.fromEntries(Object.entries(m).filter(([h])=>!s.has(h))),g=Ll(y,e);return i.reduce((h,_)=>({...h,..._.resolve(m,h,o)}),g)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];gs(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const p=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!p.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f};se.extend(jo),se.extend(xt),se.extend(dr);const Cl="YYYY-MM-DD HH:mm:ss",Dl=new Set(["YTD","QTD","MTD","WTD","DTD"]),ws=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),kl=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),kr=["second","minute","hour","day","week","month","quarter","year"],dt=t=>Object.prototype.toString.call(t)==="[object Object]",$s=(t,e)=>{const r=n=>{if(typeof n!="number"||!Number.isSafeInteger(n))throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)};if(typeof t=="number"){r(t);return}if(Array.isArray(t)){t.forEach(r);return}if(dt(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!ws.has(o)))throw new d("INVALID_DATE_PART_QUERY",`${e} requires numeric comparison operators`);for(const[o,i]of n)if(o==="$and"||o==="$or"){if(!Array.isArray(i)||i.length===0)throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires a non-empty array`);i.forEach(s=>$s(s,e))}else if(o==="$in"||o==="$nin"){if(!Array.isArray(i))throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires an array`);i.forEach(r)}else r(i);return}throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)},no=t=>!dt(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&kr.includes(t.granularity)&&typeof t.offset=="number"||kr.some(e=>e in t),Tt=t=>se(t).format(Cl),Ul=(t,e)=>kr.find(r=>r in t||e!==void 0),Ml=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),Es=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Ul(t,void 0)??"day";let i=se(e).millisecond(0);for(const a of[...kr].reverse()){const u=t[a];typeof u=="number"&&(i=Ml(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:Tt(i.startOf(s)),$lte:Tt(i.endOf(s))}},ql=(t,e)=>{const r=se(e),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[t];return{$gte:Tt(o()),$lte:Tt(r.endOf("day"))}},oo=async(t,e)=>{const r=se(String(t.$lte)),n=await e.requestTimeWatermark(r.toDate());if(!n)return t;const o=e.property.granularity??"day",i=o==="week"?"isoWeek":o,s=se(n).endOf(i),a=se(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:Tt(u)}},io=async(t,e)=>Ie(t)?t:t instanceof Date||typeof t=="string"&&se(t).isValid()?Tt(t):typeof t=="string"&&Dl.has(t)?oo(ql(t,e.now),e):no(t)?oo(Es(t,e.now),e):t,_s=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Ur(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>io(o,r)));const n=await io(e,r);return t==="$eq"&&dt(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?dt(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&dt(n)&&"$lte"in n?n.$lte:n},Ur=async(t,e)=>{if(Ie(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Ur(o,e)));if(!dt(t))return io(t,e);if("$options"in t)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new d("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!no(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(no(t))return oo(Es(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await _s("$eq",r[0][1],e);if(dt(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)kl.has(o)&&$s(i,o),n[o]=ws.has(o)?await _s(o,i,e):await Ur(i,e);return n},jl=(t,e)=>e.property.primal_type==="date"?Ur(t,e):t,so=(t=[])=>new ro([...Un,...pe(t).flatMap(({semanticTypes:e})=>e??[])]),Ss=(t,e)=>{const r=new ro(t.definitions());for(const n of pe(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},xl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Bl=t=>{if(typeof t!="string")return!1;const e=xl.exec(t);if(!e)return!1;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);return r!==2?r>2:n>0||o>0?!0:e[4]===void 0},ao=t=>{if(!Bl(t.version))throw new d("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(t.version)}`,{minimumVersion:"2.0",receivedVersion:t.version})},Is=(t,e)=>Object.entries(t).some(([r,n])=>e.has(r)?!0:r!=="$and"&&r!=="$or"||!Array.isArray(n)?!1:n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&Is(o,e))),bs=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!An(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=wn(r,n);return t&&Is(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Pt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Vl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Rs={$second:{zh:"\u79D2",en:"second"},$minute:{zh:"\u5206\u949F",en:"minute"},$hour:{zh:"\u5C0F\u65F6",en:"hour"},$weekday:{zh:"\u661F\u671F",en:"weekday"},$day:{zh:"\u65E5",en:"day of month"},$week:{zh:"\u5468",en:"week"},$month:{zh:"\u6708",en:"month"},$quarter:{zh:"\u5B63\u5EA6",en:"quarter"},$year:{zh:"\u5E74",en:"year"}},Lt=(t,e)=>{if(t===null)return e?"null":"\u7A7A\u503C";if(typeof t=="string"||typeof t=="number")return String(t);if(typeof t=="boolean")return e?String(t):t?"\u662F":"\u5426";if(Array.isArray(t))return t.map(n=>Lt(n,e)).join(e?", ":"\u3001");if(!Pt(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Lt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Lt(t.root,e);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>t[n]!==void 0).map(n=>e?`${n} ${String(t[n])}`:`${String(t[n])}${Vl[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Mr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),Ns=(t,e,r,n)=>{const s=(n?{$eq:"is",$ne:"is not",$gt:"is greater than",$gte:"is at least",$lt:"is less than",$lte:"is at most",$in:"is one of",$nin:"is none of",$contains:"contains",$startsWith:"starts with",$regex:"matches",$recursive:"is"}:{$eq:"\u4E3A",$ne:"\u4E0D\u4E3A",$gt:"\u5927\u4E8E",$gte:"\u5927\u4E8E\u7B49\u4E8E",$lt:"\u5C0F\u4E8E",$lte:"\u5C0F\u4E8E\u7B49\u4E8E",$in:"\u4E3A",$nin:"\u4E0D\u4E3A",$contains:"\u5305\u542B",$startsWith:"\u4EE5",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[t];if(!s)return;const a=t==="$startsWith"?n?"":"\u5F00\u5934":t==="$in"?n?"":"\u4E4B\u4E00":t==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":t==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${e} ${s} ${r}${a}`:`${e}${s}${r}${a}`},Zt=(t,e,r)=>{if(!Pt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return Ns("$eq",t,Lt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Mr(i.map(s=>Zt(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Rs[o]){const s=Rs[o];n.push(Zt(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Zt(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Pt(i)?Lt(i.pattern,r):Lt(i,r),a=Ns(o,t,s,r);a&&n.push(a)}return Mr(n,"$and",r)},Os=(t,e="zh-CN")=>{const r=e.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Mr(i.map(s=>Pt(s)?Os(s,e):""),o,r));else if(o==="$expr"&&Pt(i)){const s=i.pred,a=Pt(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(Zt(a,i.condition,r))}else i!==void 0&&n.push(Zt(o,i,r));return Mr(n,"$and",r)},Ct=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??yr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:Ct(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Ct(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const m=e.get(t.operator),y={executionContext:e.executionContext,operandName:c,...u?{inputName:u}:{},inputNames:a,args:p,locale:n,t:s},g=m.defaultName(y);if(typeof g!="string"||g.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const h=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),_=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return g;const E=typeof m.defaultNameKey=="function"?m.defaultNameKey(y):m.defaultNameKey??`operator.${t.operator}`;return s(E,g,{...p,operandName:c,inputName:u??"",inputNames:a.join(_),input0:a[0]??"",input1:a[1]??"",granularity:h})})():c;if(typeof l!="string"||l.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return l;const f=Os(t.query,n);return f?i?`${l} where ${f}`:`${f}\u7684${l}`:l},Fl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Yl=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},vl=async(t,e,r)=>{if(t.operator!=="$case"||t.args?.mode!=="auto"||t.args.min!==void 0||t.args.max!==void 0||t.args.empty===!0)return t;if(typeof t.pred!="string")throw new d("AUTO_CASE_PROPERTY_REQUIRED","$case auto mode requires a direct property pred when bounds are not explicit");if(!r.requestAutoCaseBounds)return t;const n=await r.requestAutoCaseBounds(e,t.pred,r.autoCaseQuery);return{...t,args:{...t.args,...n}}},er=async(t,e,r,n)=>{if("components"in t)throw new d("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const o=r.operators,i={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!o)throw new Error("Normalizer operator registry is not initialized");if(t.name!==void 0&&(typeof t.name!="string"||t.name.length===0))throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new d("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!Fl(t.args))throw new d("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const s=t.schema===void 0||t.schema===e.id?e:r.resolveSchema?.(t.schema);if(!s)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>er(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...p}=t,l={...p,...a?{query:a}:{},...u?{pred:u}:{}},f=async m=>{const y=await vl(m,s,r),g=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s,executionContext:o.executionContext})??y:y;return Yl(g)};if(typeof t.pred=="string"){const m=ae(s,t.pred,r.resolveSchema),y={...l,pred:m.canonicalName};return f({...y,name:y.name??Ct(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...l,pred:await er(t.pred,s,r,n)};return f({...m,name:m.name??Ct(m,o,i)})}if(u)return f({...l,name:l.name??Ct(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...l,name:l.name??Ct(l,o,i)})},Ql=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Hl=t=>{if(!Ie(t))return!1;const e=t;return e.groupby!==void 0||e.preds!==void 0||e.from!==void 0||e.having!==void 0||e.sort!==void 0||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},qr=async(t,e)=>{if(Ie(t)){if(!e.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>qr(r,e))):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(await Promise.all(Object.entries(t).map(async([r,n])=>[r,await qr(n,e)])))},Ts=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Ts(o,e))]:[`${e}_${r}`,n])),co=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=Object.entries(t),[r]=e;return e.length===1&&r?.[0]==="$eq"?r[1]:t},Ps=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),uo=new Set([...Ps,"$length"]),jr=t=>Array.isArray(t)?t.some(jr):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>uo.has(e)||jr(r)),Ls=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Ie(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Ls(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},xr=(t,e)=>{if(t.schema!==void 0)throw new d("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new d("EXPRESSION_QUERY_PRED_QUERY_NOT_ALLOWED","$expr.pred cannot define pred.query");if(t.operator){if(!e.operators)throw new Error("Normalizer operator registry is not initialized");const r=e.operators.get(t.operator);if(r.kind!=="scalar"||!r.toSQL)throw new d("OPERATOR_NOT_ALLOWED_IN_EXPRESSION_QUERY",`Operator ${t.operator} cannot be used in $expr`,{operator:t.operator})}t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&xr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&xr(r,e)},Cs=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must contain exactly pred and condition",{unsupported:o});if(typeof n.pred!="object"||n.pred===null||Array.isArray(n.pred))throw new d("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new d("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");xr(i,r);const s=await er(i,e,r,()=>Promise.resolve(void 0));xr(s,r);const a=co(await qr(n.condition,r));return uo.has(s.operator)&&Ls(a,s.operator),{pred:s,condition:a}},Ds=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Ie(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))uo.has(s)?i.push({$expr:await Cs({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(jr)?i.push({[s]:await Promise.all(a.map(u=>Ds(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:co(o)}),i.length===1?i[0]??{}:{$and:i}},lo=t=>Array.isArray(t)?t.some(lo):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>Ps.has(e)||lo(r)),ks=async(t,e,r,n)=>{const o=c=>{if(Array.isArray(c)){c.forEach(o);return}if(typeof c!="object"||c===null||Ie(c))return;const p=c;if("$options"in p)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(p).forEach(o)};if(o(t),r.primal_type!=="date"&&lo(t))throw new d("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const i=n.semanticTypes.get(r.type),s={schema:e,property:r,now:n.now??new Date,requestTimeWatermark:c=>n.requestTimeWatermark?.(e,r,c)??Promise.resolve(void 0)},a=await jl(Z(t),s),u=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const c=new Set(r.comparable.values),p=(l,f)=>{if(!(Ie(l)||l===null)){if(Array.isArray(l)){l.forEach(m=>p(m,f));return}if(typeof l=="object"){Object.entries(l).forEach(([m,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(m)||p(y,m)});return}if(!(f&&["$exists","$regex","$contains","$startsWith","$length"].includes(f))&&(typeof l!="string"||!c.has(l)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(l)}`,{property:r.name,value:l})}};p(u)}return u},po=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const u=Object.entries(a);if(u.length===1&&u[0]?.[0]==="$and"&&Array.isArray(u[0][1]))for(const c of u[0][1])s(c);else u.length===1&&u[0]?.[0]==="$expr"?o.push(a):u.every(([c])=>!c.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,u]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(u.map(async m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return po(m,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Cs(u,e,r)});continue}const c=ae(e,a,r.resolveSchema);if(Hl(u)&&(c.property.primal_type==="entity"||c.property.primal_type==="object")&&c.property.ref){if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const m=await r.normalizeNestedLogicform(u);n[c.canonicalName]={$in:m};continue}if(Ql(u)){if(u.version!==void 0&&ao(u),c.property.primal_type!=="entity"&&c.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!c.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${c.canonicalName}`);if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema}`);const m=r.resolveSchema?.(u.schema);if(!m)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${u.schema}`);const y=bs(u.query,u.entity_id,m,r.plugins),g=await po(y,m,r);Object.assign(n,Ts(g,c.canonicalName));continue}if(typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=u,y=Object.entries(m).filter(([g])=>Et(g,r.plugins));if(y.length>0){const[g]=y,h=g?Et(g[0],r.plugins):void 0;if(h?.validateCondition?.(m),!g||y.length!==1||Object.keys(m).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[_,E]=g;if(!h)throw new Error(`Query Operator disappeared: ${_}`);n[c.canonicalName]={[_]:await h.normalize(E,{schema:c.schema,property:c.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(I,$,A)=>ks(I,$,A,r)})};continue}}const p=await qr(u,r),l=await ks(p,c.schema,c.property,r),f=co(l);if(jr(f)){s(await Ds(c.canonicalName,f,e,r));continue}n[c.canonicalName]=f}if(i.length>0){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...i]}if(o.length===1)n.$expr=o[0]?.$expr;else if(o.length>1){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...o]}return n},Us=async(t,e,r)=>{if(!t)return;const n=await po(t,e,r);return Object.keys(n).length===0?void 0:n},Ms=(t,e,r)=>Promise.all((t??[]).map(n=>er(n,e,r,Us))),Gl=(t,e,r)=>Ms(t??[],e,r),Dt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},Wl=t=>{"skip"in t&&Dt("skip has been removed; use the 1-based page field",{skip:t.skip});const e=t.groupby?.length??0;t.limitBy!==void 0&&((!Number.isInteger(t.limitBy)||t.limitBy<=0)&&Dt("limitBy must be a positive integer",{limitBy:t.limitBy}),e<2&&(t.limit=t.limitBy,delete t.limitBy));const{limit:r,page:n}=t;if(r===void 0){n!==void 0&&Dt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Dt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Dt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Dt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},zl=t=>t.property.name,qs=(t,e,r,n,o=new Set)=>{if(o.has(t.id))return;const i=new Set(o).add(t.id),s=t.properties.find(a=>a.id===e||a.name===e);if(s)return s.name;if(n==="timestamp"){const a=t.properties.find(u=>u.type==="timestamp");if(a)return a.name}for(const a of t.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const u=r?.(a.ref);if(!u)continue;const c=qs(u,e,r,n,i);if(c)return`${a.name}_${c}`}},js=(t,e,r,n)=>{try{const o=ae(t,e,n);return qs(r,zl(o),n,o.property.type)}catch{return}},fo=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?fo(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:fo(e)):[]],xs=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>xs(n));if(e==="$expr"&&typeof r=="object"&&r!==null&&!Array.isArray(r)){const n=r.pred;return typeof n=="object"&&n!==null&&!Array.isArray(n)?fo(n):[]}return e.startsWith("$")?[]:[e]}):[],Kl=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[p,l]of Object.entries(a))try{const f=ae(e,p,r.resolveSchema),m=u?ae(u,l,r.resolveSchema):void 0;c[f.canonicalName]=m?.canonicalName??l}catch{c[p]=l}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...xs(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ae(e,s,r.resolveSchema)}catch{continue}for(const u of n){const c=r.resolveSchema?.(u),p=c&&js(e,s,c,r.resolveSchema);p&&p!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},Jl=t=>{if(t!==void 0){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_PROPERTY_RESOLVE","propertyResolve must be an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e} must be an object`);for(const[n,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e}.${n} must be a non-empty string`)}}},Xl=async(t,e,r)=>{if(!t)return;const n=hs(t,e,r);return lt(t,n,r)},lt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:mr([...pe(r.plugins).flatMap(g=>g.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:ke(r.plugins)}},ao(t),Jl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!Ai(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=Z(t),i={...r,normalizeNestedLogicform:async g=>{const h=hs(g,e,r);return lt(g,h,r)}};Wl(o);const s=await Xl(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,u=await Us(bs(o.query,o.entity_id,a,r.plugins),a,i),c=o.preds===void 0&&o.groupby===void 0?a.properties.filter(g=>r.canProjectProperty?.(a,g)??!0).map(g=>({pred:g.name,name:g.name})):o.preds,p={...i,...u?{autoCaseQuery:u}:{}};let l=await Ms(c,a,p),f=await Gl(o.groupby,a,p);const m=f.filter(g=>si(g,f,a,r.resolveSchema));if(m.length>0){const g=new Set(m.map(({name:h})=>h));f=f.filter(({name:h})=>!g.has(h)),l=[...l,...m]}return o.preds=l,f.length>0?o.groupby=f:delete o.groupby,s?o.from=s:delete o.from,u?o.query=u:delete o.query,Kl(o,a,i)},Bs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),He=(t,e)=>{if(t){if(!Bs(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},pt=(t,e,r)=>{const n=He(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},tr=(t,e,r)=>{if(!pt(t,e.id,r))throw new d("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},mo=(t,e,r,n)=>{const o=ae(e,t,n);for(const i of o.relations)He(r,i.targetSchema.id),tr(r,i.sourceSchema,i.property);tr(r,o.schema,o.property)},Vs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Br=(t,e,r,n)=>{if(Ie(t)){Fr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)Br(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))Br(o,e,r,n)};function rr(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&He(r,t.schema),typeof t.pred=="string"?mo(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&rr(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?mo(s,i,r,n):rr(s,i,r,n,o);Vr(t.query,i,r,n,o)}const Vr=(t,e,r,n,o)=>{if(t)for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const u of s)Vr(u,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const u=s.pred;typeof u=="object"&&u!==null&&!Array.isArray(u)&&rr(u,e,r,n,o),Br(s.condition,r,n,o)}continue}const a=ae(e,i,n);if(mo(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[u,c]of Object.entries(s))Et(u,o)?.authorize?.(c,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{He(r,p)},assertPropertyAllowed:(p,l)=>tr(r,p,l),hasRowPermissions:p=>He(r,p)?.rowPermissions!==void 0});if(Vs(s)){if(a.property.ref!==s.schema)continue;const u=n(s.schema);He(r,u.id),An(s.entity_id)&&tr(r,u,wn(u,o)),Vr(s.query,u,r,n,o);continue}Br(s,r,n,o)}},Fr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){Fr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(He(e,o.id),An(t.entity_id)&&tr(e,o,wn(o,n)),t.from){Fr(t.from,e,r,n);return}Vr(t.query,o,e,r,n);for(const i of t.preds??[])rr(i,o,e,r,n);for(const i of t.groupby??[])rr(i,o,e,r,n)},Yr=(t,e)=>{if(Array.isArray(t))return t.map(o=>Yr(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Yr(i,e)]),n=Object.fromEntries(r);return Vs(t)&&!Bs(t,"version")&&(n.version=e),n},Zl=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[u,c]of Object.entries(s))if((u==="$and"||u==="$or")&&Array.isArray(c))for(const p of c)o(p,a);else if(u==="$expr"&&typeof c=="object"&&c!==null&&!Array.isArray(c)){const p=c.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else u.startsWith("$")||n.push(ae(a,u,r))},i=(s,a)=>{const u=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(ae(u,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,u);for(const c of Array.isArray(s.pred)?s.pred:[])typeof c=="string"?n.push(ae(u,c,r)):i(c,u);o(s.query,u)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},ep=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Zl(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},f)=>{e[l.id]?.rowPermissions!==void 0&&(a=f)}),a<0)continue;const u=s.relations.slice(0,a+1),c=u.map(({property:l})=>l.name).join("_");if(o.has(c))continue;o.add(c);let p={};for(const l of[...u].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},kt=(t,e,r,n,o,i)=>Ie(t)?ft(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>kt(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,kt(a,e,r,n,o,i)])),yo=(t,e,r,n,o,i)=>({...t,...t.query?{query:kt(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:yo(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:yo(s,e,r,n,o,i))}:{}}),ft=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return Z(t);if(!t.schema){const m=Z(t);return m.from&&(m.from=ft(m.from,e,r,n,new Set,i)),m}n&&Fr(t,e,r,i);const s=He(e,t.schema),a=o.has(t.schema),u=new Set(o).add(t.schema),c=Z(t);c.query&&(c.query=kt(c.query,e,r,n,new Set,i)),c.preds&&(c.preds=c.preds.map(m=>yo(m,e,r,n,new Set,i))),c.from&&(c.from=ft(c.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:ep(t,e,r)).map(m=>kt(Yr(m,t.version),e,r,!1,u,i));p&&l.push(kt(Yr(Z(p),t.version),e,r,!1,u,i));const f=[c.query,...l].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?c.query=f[0]:f.length>1?c.query={$and:f}:delete c.query,c},tp=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const o=e(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new d("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:u})=>a===s||u===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},Fs=(t,e)=>{const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(t),n=o=>Number(r.find(i=>i.type===o)?.value);return{year:n("year"),month:n("month"),day:n("day"),hour:n("hour"),minute:n("minute"),second:n("second")}},Ys=(t,e)=>{const r=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second);let n=r;for(let o=0;o<3;o+=1){const i=Fs(new Date(n),e),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);n+=r-s}return new Date(n)},rp=(t,e)=>{const r=xi(t.expireAt);if(!r)throw new Error(`Invalid daily expiration time: ${t.expireAt}`);if(!t.timeZone){const i=new Date(e);return i.setHours(r.hour,r.minute,r.second,0),i.getTime()<=e.getTime()&&i.setDate(i.getDate()+1),i}const n=Fs(e,t.timeZone);let o=Ys({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Ys({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},np=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[rp(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},ho=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?t.map(ho):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,ho(r)])):t,vs=t=>rn.createHash("sha256").update(JSON.stringify(ho(t))).digest("hex"),op=t=>vs({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),ip=(t,e)=>vs({namespace:t,source:e}),go=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?{type:"array",value:t.map(go)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,go(r)])}:t,Ao=t=>{if(t===null||typeof t!="object")return t;switch(t.type){case"undefined":return;case"bigint":return BigInt(t.value);case"number":return Number(t.value);case"date":return new Date(t.value);case"array":return t.value.map(Ao);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,Ao(r)]))}},sp=t=>JSON.stringify(go(t)),ap=t=>{const e=Ao(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},cp=Number.MAX_SAFE_INTEGER;class up{#e;#t;#r;constructor(e,r={}){this.#e=e,this.#t=r.keyPrefix??"semanticdb:cache",this.#r=r.ownsClient??!1}#n(e){return`${this.#t}:query:${op(e)}`}#o(e,r){return`${this.#t}:source:${ip(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return ap(r)}async set(e,r,n){const o=this.#n(e),i=sp(r),s=n.expiresAt?.getTime(),a=s??cp,u=this.#e.multi();s===void 0?u.set(o,i):u.set(o,i,{PXAT:s});for(const c of new Set(n.sources)){const p=this.#o(e.namespace,c);u.zRemRangeByScore(p,0,Date.now()),u.zAdd(p,{score:a,value:o})}await u.exec()}async invalidateSource(e,r){const n=this.#o(e,r),o=await this.#e.zRange(n,0,-1);o.length>0&&await this.#e.del(o),await this.#e.del(n)}async close(){this.#r&&await this.#e.close()}}const dp=async(t={})=>{const e=La.createClient(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new up(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function lp(t){if(!t||typeof t!="object")throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache configuration must be an object");const e=t;if(typeof e.id!="string"||e.id.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache id must not be empty");if(e.kind!=="redis")throw new d("INVALID_QUERY_CACHE_CONFIGURATION",`Unsupported query cache kind: ${String(e.kind)}`);if(typeof e.url!="string"||e.url.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache url must not be empty");if(e.keyPrefix!==void 0&&(typeof e.keyPrefix!="string"||e.keyPrefix.trim().length===0))throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache keyPrefix must not be empty");if(typeof e.namespace!="string"||e.namespace.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache namespace must not be empty")}const pp=({namespace:t,...e})=>e,fp=async t=>dp({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class mp{create;#e=new Map;constructor(e=fp){this.create=e}async get(e){lp(e);const r=pp(e),n=this.#e.get(r.id);if(n){if(!xo.isDeepStrictEqual(n.connection,r))throw new d("QUERY_CACHE_CONFIGURATION_MISMATCH",`Query cache configuration changed for id: ${r.id}`,{cacheId:r.id});return{store:await n.store,namespace:e.namespace}}const o=this.create(r),i={connection:r,store:o};this.#e.set(r.id,i);try{return{store:await o,namespace:e.namespace}}catch(s){throw this.#e.get(r.id)===i&&this.#e.delete(r.id),s}}async close(){const e=[...this.#e.values()];this.#e.clear();const n=(await Promise.allSettled(e.map(async({store:o})=>(await o).close()))).flatMap(o=>o.status==="rejected"?[o.reason]:[]);if(n.length>0)throw new AggregateError(n,"Failed to close one or more query cache connections")}}const Qs=new mp,Hs=t=>Qs.get(t),yp=()=>Qs.close(),hp=async({cache:t,source:e})=>{if(typeof e!="string"||e.trim().length===0)throw new d("INVALID_QUERY_CACHE_SOURCE","Query cache source must not be empty");const r=await Hs(t);await r.store.invalidateSource(r.namespace,e)},gp=Object.freeze({invalidateSource:hp}),Ap=()=>{},wo=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),nr=(t,e,r)=>{if(St(t)){e.push(t.plan);return}if(Ui(t)){for(const n of t.sources??[])r.set(`${n.schemaId}:${n.connectionId??""}:${n.source}`,n);return}if(Array.isArray(t)){for(const n of t)nr(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))nr(n,e,r)},or=(t,e,r)=>{if(t.kind==="window"){or(t.input,e,r);for(const n of t.partitionBy)or(n,e,r);return}if(t.kind==="operator"){nr(t.query,e,r),t.input&&or(t.input,e,r);for(const n of t.inputs??[])or(n,e,r)}},we=t=>{const e=new Map,r=o=>{e.set(`${o.schemaId}:${o.connectionId??""}:${o.mappingSource??""}:${o.source}`,o)};if(t.subplans)for(const o of t.subplans)for(const i of we(o))r(i);else if(t.sourcePlan)for(const o of we(t.sourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}});for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];nr(t.query,n,e),nr(t.having,n,e);for(const o of t.projections)or(o.expression,n,e);for(const o of n)for(const i of we(o))r(i);return[...e.values()]},ir=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.source}`,r);return[...e.values()]},Gs=async(t,e)=>{try{return await t.execute(e)}catch(r){const n=r instanceof Error?r.message:String(r),o=`${t.kind} provider \u6267\u884C SQL \u4EA7\u751F\u9519\u8BEF\uFF1A`;throw r instanceof Error?(r.message.startsWith(o)||(r.message=`${o}${n}`),r):new Error(`${o}${n}`,{cause:r})}},wp=(t,e)=>{const r=[];for(const n of t){const o=wo(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},$o=async(t,e,r,n=Ap)=>{t=Ws(t),r.signal?.throwIfAborted();const o=r.cache?wp(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),Gs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const i={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const a=await r.cache.store.get(i);if(r.signal?.throwIfAborted(),a)return n("cache"),[...a]}catch{r.signal?.throwIfAborted()}n("database");const s=await Gs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=np(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:u})=>u))],...a?{expiresAt:a}:{}})}catch{}return s},Ws=t=>({...t,sql:ul(t.sql)}),$p=t=>{if(t.every(e=>typeof e=="string"))return[...t];if(t.every(e=>typeof e=="number"))return[...t];if(t.every(e=>typeof e=="boolean"))return[...t];throw new TypeError("Entity IDs must have one scalar type")},Ep=(t,e,r)=>{const n=$p(e);if(!r||n.length<=r)return{[t]:{$in:n}};const o=[];for(let i=0;i<n.length;i+=r)o.push({[t]:{$in:n.slice(i,i+r)}});return{$or:o}},zs=async(t,e)=>{if(!pt(e.permissions,t.schema.id,t.idProperty))throw new d("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${t.schema.id}.${t.idProperty.name}`,{schemaId:t.schema.id,property:t.idProperty.name});const r=t.schema.properties.filter(h=>pt(e.permissions,t.schema.id,h)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:h})=>h===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:Ep(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(h=>({pred:h.name,name:h.name}))},a=ft(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await lt(a,t.schema,{semanticTypes:e.semanticTypes,operators:e.operators,...e.plugins?{plugins:e.plugins}:{},...e.locale?{locale:e.locale}:{},...e.localeRegistry?{localeRegistry:e.localeRegistry}:{},resolveSchema:e.resolveSchema}),c=Le(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(h,_)=>pt(e.permissions,h.id,_)}),p=new Set(we(c).map(h=>e.schemaMappings.findSource(h.schemaId,h.source,h.connectionId)?.connectionId).filter(h=>!!h));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,f=l&&e.providerForConnection?e.providerForConnection(l):i,m=fe(c,f,e.operators),y=e.onCompiled?.(m,u,f,l),g=await $o(m,we(c),{provider:f,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return Jn(g,c.rowIdentity)},Ks=t=>String(t),_p=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Ks(r)}\u300D\u7684\u5B9E\u4F53`,o={};for(const i of t.properties)i.id===e.id?o[i.name]=r:i.isArray?o[i.name]=[]:o[i.name]=i.primal_type==="string"?n:null;return o._id=Ks(r),o},Js=(t,e)=>`${t}:${String(e)}`,Sp=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),r=e[0];if(e.length!==1||!r)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r};class Ip{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=Js(e,r),o=this.#t.get(n);if(o)return Promise.resolve(o);const i=this.#r.get(n);if(i)return i;const s=this.#e.resolveSchema(e);if(wi(s,this.#e.plugins))throw new d("INTERVAL_ENTITY_HYDRATION_REQUIRES_POINT",`Cannot hydrate interval-versioned entity ${e} by ID without a selection point; use a relation path to select its point-in-time properties`,{schemaId:e});const a=Sp(s);let u,c;const p=new Promise((f,m)=>{u=f,c=m}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:f=>u?.(f),reject:f=>c?.(f)}),this.#n.set(e,l),this.#r.set(n,p),this.#s(),p};#s(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#i()}))}async#i(){this.#o=!1;const e=this.#n;this.#n=new Map,await Promise.all([...e.values()].map(r=>this.#a(r)))}async#a(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n)};try{const n=await this.#e.fetchEntities(r),o=new Map;for(const i of n){const s=i[e.idProperty.name]??i._id;if(s!=null){const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(Js(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??_p(e.schema,e.idProperty,s.id);this.#t.set(i,a),this.#r.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of e.loads)this.#r.delete(o),i.reject(n)}}}const bp=(t,e)=>{if(!e.isArray||typeof t!="string")return t;const r=t.trim();if(!r.startsWith("[")||!r.endsWith("]"))return t;try{const n=JSON.parse(r);if(!Array.isArray(n))throw new Error("JSON result is not an array");return n}catch(n){throw new d("INVALID_ARRAY_RESULT",`Result column ${e.name} contains invalid array JSON`,{property:e.name,cause:n})}},Rp=async(t,e,r,n)=>{await Promise.all(t.map(async o=>{await Promise.all(e.map(async i=>{if(!(i.name in o))return;const s=bp(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(u=>a(u,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},Xs=5,Np=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Op=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Tp=(t,e)=>{const r=Ca.getNameProperty(e);t._title=t[r.name]??t._id},Pp=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Op(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Lp=(t,e,r,n)=>{const o=`${e.id}:${n?"recursive":"leaf"}`,i=t.get(o);if(i){i.rows.push(r);return}t.set(o,{rows:[r],properties:e.properties,schema:e,expandEntities:n})},Cp=async(t,e,r)=>{const n=new Ip(r);let o=[{rows:t,properties:e,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<Xs;return Rp(a.rows,a.properties,r.semanticTypes,u?n.load:(c,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const u of a.rows)Tp(u,a.schema);if(i>=Xs)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const p of a.rows){if(!(u.name in p))continue;const l=p[u.name],f=u.isArray?Array.isArray(l)?l:[l]:[l];for(const[m,y]of f.entries()){if(!Np(y))continue;const g=Pp(y,c);u.isArray?f[m]=g:p[u.name]=g,Lp(s,c,g,!u.isArray)}u.isArray&&(p[u.name]=f)}}o=[...s.values()]}},Zs=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Cp(n,e,r),n},Eo=t=>`'${t.replaceAll("'","''")}'`,ea=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
4
+ `,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},sr=(t,e)=>{if(t==null)return"NULL";if(typeof t=="boolean")return e==="mysql"?t?"true":"false":e==="sqlserver"?t?"1":"0":t?"TRUE":"FALSE";if(typeof t=="number")return String(t);if(typeof t=="bigint")return e==="mysql"||e==="sqlserver"?t.toString():Eo(t.toString());if(typeof t=="string")return e==="mysql"?ea(t):Eo(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?ea(r):Eo(r)}if(Buffer.isBuffer(t)){const r=t.toString("hex");return e==="mysql"?`X'${r}'`:e==="dameng"||e==="oracle"?`HEXTORAW('${r}')`:e==="postgresql"?`decode('${r}', 'hex')`:e==="snowflake"?`TO_BINARY('${r}', 'HEX')`:e==="sqlserver"?`0x${r}`:`unhex('${r}')`}throw new TypeError(`Unsupported ${e} display parameter type: ${typeof t}`)},Dp=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?sr(e[o],"clickhouse"):r}),kp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?sr(e[o],"oracle"):r}),Up=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=sr(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},_o=(t,e,r)=>{let n="",o=0,i;for(let s=0;s<t.length;s+=1){const a=t[s];if(a){if(i){n+=a,a===i&&(t[s+1]===i?(n+=i,s+=1):i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a,n+=a;continue}if(a==="?"&&o<e.length){n+=sr(e[o],r),o+=1;continue}n+=a}}return n},Mp=(t,e)=>_o(t,e,"mysql"),So=(t,e)=>_o(t,e,"snowflake"),qp=(t,e)=>_o(t,e,"dameng"),jp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=sr(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},et=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),ar=t=>{for(const[e,r]of Object.entries({database:t.database,schema:t.schema}))if(r!==void 0&&!r.trim())throw new d("INVALID_TABLE_SCOPE",`Table discovery ${e} must not be empty`)},Ce=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},xe=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Pe=(t,e)=>{const r=xe(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},ta=t=>{const e=Pe(t,"table_name"),r=xe(t,"table_database"),n=xe(t,"table_schema"),o=Pe(t,"table_type").toUpperCase();if(!["BASE TABLE","TABLE","FOREIGN TABLE","EXTERNAL TABLE","EVENT TABLE","VIEW","SYSTEM VIEW","MATERIALIZED VIEW"].includes(o))throw new d("INVALID_TABLE_METADATA",`Unsupported metadata table type: ${o}`);return{name:e,...typeof r=="string"?{database:r}:{},...typeof n=="string"?{schema:n}:{},type:o.includes("VIEW")?"view":"table"}},xp=t=>t.map(ta),mt=async(t,e)=>{e.signal?.throwIfAborted(),ar(e);const r=[],n=u=>{const c=t.parameter(r.length,u);return r.push(u),c},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Ce(t,"schema"),s="SELECT TABLE_NAME AS table_name, TABLE_SCHEMA AS table_database, TABLE_TYPE AS table_type FROM information_schema.tables WHERE TABLE_SCHEMA = "+(o!==void 0?n(o):"DATABASE()");break;case"postgresql":o!==void 0&&Ce(t,"database"),s="SELECT table_name, table_catalog AS table_database, table_schema, table_type FROM information_schema.tables WHERE table_schema = "+(i!==void 0?n(i):"current_schema()");break;case"sqlserver":case"snowflake":{s=`SELECT TABLE_NAME AS table_name, TABLE_CATALOG AS table_database, TABLE_SCHEMA AS table_schema, TABLE_TYPE AS table_type FROM ${`${o!==void 0?`${t.quoteIdentifier(o)}.`:""}INFORMATION_SCHEMA.TABLES`}`,i!==void 0?s+=` WHERE TABLE_SCHEMA = ${n(i)}`:t.kind==="snowflake"&&(s+=" WHERE TABLE_SCHEMA = CURRENT_SCHEMA()");break}case"oracle":case"dameng":o!==void 0&&Ce(t,"database"),s="SELECT OBJECT_NAME AS table_name, OWNER AS table_schema, OBJECT_TYPE AS table_type FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TABLE', 'VIEW') AND OWNER = "+(i!==void 0?n(i):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')");break;case"clickhouse":i!==void 0&&Ce(t,"schema"),s="SELECT name AS table_name, database AS table_database, if(engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables WHERE database = "+(o!==void 0?n(o):"currentDatabase()");break;default:throw new d("UNSUPPORTED_TABLE_DISCOVERY",`No metadata SQL for provider: ${t.kind}`)}s+=" ORDER BY table_name";const a=await t.execute({sql:s,parameters:r,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),xp(a)},Io=t=>{if(ar(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},vr=(t,e)=>{const r=xe(t,e);return typeof r=="string"?r:""},Bp=t=>{const e=Pe(t,"column_type"),r=xe(t,"type_length"),n=xe(t,"type_precision"),o=xe(t,"type_scale");return/^(?:n?varchar2?|n?char|n?varbinary|binary|raw)$/i.test(e)&&typeof r=="number"?`${e}(${r===-1?"max":r})`:/^(?:number|numeric|decimal)$/i.test(e)&&typeof n=="number"?`${e}(${n}${typeof o=="number"?`,${o}`:""})`:e},ra=t=>{const e=xe(t,"is_primary_key");let r;if(e!=null)if([!0,1,"1","true","TRUE","YES","Y"].includes(e))r=!0;else if([!1,0,"0","false","FALSE","NO","N"].includes(e))r=!1;else throw new d("INVALID_TABLE_METADATA","Invalid primary-key metadata");return{name:Pe(t,"column_name"),type:Bp(t),comment:vr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},Vp=(t,e)=>{const r=[],n=c=>{const p=t.parameter(r.length,c);return r.push(c),p},o=n(e.table),{database:i,schema:s}=e;let a,u;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Ce(t,"schema");const c=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${i!==void 0?n(i):"DATABASE()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_SCHEMA AS table_database, c.TABLE_TYPE AS table_type, c.TABLE_COMMENT AS table_comment FROM information_schema.tables c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.COLUMN_TYPE AS column_type, c.COLUMN_COMMENT AS column_comment, (c.COLUMN_KEY = 'PRI') AS is_primary_key FROM information_schema.columns c WHERE ${c} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&Ce(t,"database");const c=`c.relname = ${o} AND n.nspname = ${s!==void 0?n(s):"current_schema()"}`;a=`SELECT c.relname AS table_name, current_database() AS table_database, n.nspname AS table_schema, CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW' ELSE 'TABLE' END AS table_type, obj_description(c.oid, 'pg_class') AS table_comment FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,u=`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS column_type, col_description(c.oid, a.attnum) AS column_comment, EXISTS (SELECT 1 FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid AND i.indisprimary AND a.attnum = ANY(i.indkey)) AS is_primary_key FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const c=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${c}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${c}sys.objects o ON o.schema_id = s.schema_id AND o.name = c.TABLE_NAME `;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, CAST(ep.value AS nvarchar(max)) AS table_comment FROM ${c}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale, CAST(ep.value AS nvarchar(max)) AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ${c}sys.indexes i JOIN ${c}sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE i.object_id = o.object_id AND i.is_primary_key = 1 AND ic.key_ordinal > 0 AND ic.column_id = sc.column_id) THEN 1 ELSE 0 END AS is_primary_key FROM ${c}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${c}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = sc.column_id AND ep.name = 'MS_Description' WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const c=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"CURRENT_SCHEMA()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENT AS table_comment FROM ${c}.TABLES c WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.COMMENT AS column_comment, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale FROM ${c}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Ce(t,"database");const c=`c.TABLE_NAME = ${o} AND c.OWNER = ${s!==void 0?n(s):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"}`;a=`SELECT c.TABLE_NAME AS table_name, c.OWNER AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENTS AS table_comment FROM ALL_TAB_COMMENTS c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, CASE WHEN c.DATA_TYPE = 'RAW' THEN c.DATA_LENGTH ELSE c.CHAR_LENGTH END AS type_length, c.DATA_PRECISION AS type_precision, c.DATA_SCALE AS type_scale, cm.COMMENTS AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ALL_CONS_COLUMNS k JOIN ALL_CONSTRAINTS t ON t.OWNER = k.OWNER AND t.CONSTRAINT_NAME = k.CONSTRAINT_NAME WHERE t.CONSTRAINT_TYPE = 'P' AND k.OWNER = c.OWNER AND k.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END AS is_primary_key FROM ALL_TAB_COLUMNS c LEFT JOIN ALL_COL_COMMENTS cm ON cm.OWNER = c.OWNER AND cm.TABLE_NAME = c.TABLE_NAME AND cm.COLUMN_NAME = c.COLUMN_NAME WHERE ${c} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&Ce(t,"schema");const c=i!==void 0?n(i):"currentDatabase()";a=`SELECT c.name AS table_name, c.database AS table_database, c.comment AS table_comment, if(c.engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables c WHERE c.name = ${o} AND c.database = ${c}`,u=`SELECT c.name AS column_name, c.type AS column_type, c.comment AS column_comment, c.is_in_primary_key AS is_primary_key FROM system.columns c WHERE c.table = ${o} AND c.database = ${c} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:u,parameters:r}},na=(t,e)=>{const r=[];return!["postgresql","oracle","dameng"].includes(t.kind)&&e.database!==void 0&&r.push(e.database),e.schema!==void 0&&r.push(e.schema),r.push(e.name),r.map(n=>t.quoteIdentifier(n)).join(".")},Ut=async(t,e,r,n=[])=>{e.signal?.throwIfAborted();const o=await t.execute({sql:r,parameters:n,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),o},bo=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=na(t,r.tableInfo),o=t.kind==="sqlserver"?`SELECT TOP (1) * FROM ${n}`:["oracle","dameng"].includes(t.kind)?`SELECT * FROM ${n} FETCH FIRST 1 ROWS ONLY`:`SELECT * FROM ${n} LIMIT 1`;let i;try{[i]=await Ut(t,e,o)}catch{return e.signal?.throwIfAborted(),r}return i?{...r,columns:r.columns.map(s=>({...s,...Object.hasOwn(i,s.name)?{exampleValue:i[s.name]}:{}}))}:r},Fp=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Ut(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!l)throw new d("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=Pe(l,"table_database"),n??=Pe(l,"table_schema")}const o=na(t,{name:e.table,database:r,schema:n}),i=await Ut(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,u=!1,c="",p="table";for(const l of i){const f=xe(l,"col_name"),m=xe(l,"data_type"),y=(f==="# Partition Information"||f==="# Detailed Table Information")&&!m;(f===""||y)&&(a=!1),y&&f==="# Detailed Table Information"&&(u=!0),a?s.push({name:Pe(l,"col_name"),type:Pe(l,"data_type"),comment:vr(l,"comment")}):u&&f==="Comment"?c=vr(l,"data_type"):u&&f==="Type"&&m==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return bo(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:c}})},Yp=async(t,e)=>{e.database!==void 0&&Ce(t,"database"),e.schema!==void 0&&Ce(t,"schema");const n=(await Ut(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(ra);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return bo(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Ge=async(t,e)=>{if(e.signal?.throwIfAborted(),Io(e),t.kind==="databricks")return Fp(t,e);if(t.kind==="maxcompute")return Yp(t,e);const{tableSql:r,columnSql:n,parameters:o}=Vp(t,e),i=await Ut(t,e,r,o),[s]=i;if(!s)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);if(i.length!==1)throw new d("AMBIGUOUS_TABLE",`More than one table matched: ${e.table}`);const a={...ta(s),comment:vr(s,"table_comment")},u=(await Ut(t,e,n,o)).map(ra);return bo(t,e,{columns:u,tableInfo:a})},vp=t=>{if(t.url!==void 0)return t.url;const e=t.host??"localhost";if(/^[a-z][a-z\d+.-]*:\/\//iu.test(e)){if(t.port===void 0)return e;const n=new URL(e);return n.port=String(t.port),n.toString()}return`http://${e}:${t.port??8123}`},Qp=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",oa=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Hp{kind="clickhouse";supportsRecursiveCte=!0;recursiveCteUnion="UNION ALL";#e;#t;constructor(e={}){this.#e=e,this.#t=e.client?Promise.resolve(e.client):void 0}async#r(){this.#t??=(async()=>{const{createClient:e}=await import("@clickhouse/client").catch(r=>{throw et("@clickhouse/client",r)});return e({url:vp(this.#e),username:this.#e.username??this.#e.user??"default",password:this.#e.password??"",database:this.#e.database??"default"})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`{p${e}:${Qp(r)}}`}displayQuery(e,r){return Dp(e,r)}dateBucket(e,r){if(r==="second")return`toDateTime64(${e}, 0)`;const o={minute:"toStartOfMinute",hour:"toStartOfHour",day:"toStartOfDay",week:"toStartOfWeek",month:"toStartOfMonth",quarter:"toStartOfQuarter",year:"toStartOfYear"}[r];if(!o)throw new Error(`Unsupported ClickHouse date level: ${r}`);return`${o}(${e})`}datePart(e,r){return`${{second:"toSecond",minute:"toMinute",hour:"toHour",weekday:"toDayOfWeek",day:"toDayOfMonth",week:"toISOWeek",month:"toMonth",quarter:"toQuarter",year:"toYear"}[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported ClickHouse date shift: ${r}/${n}`);return`dateAdd(${r}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`toDateTime(${e})`:r==="date"?`toDate(${e})`:e}scalarExtremum(e,r){const n=`[${r.map(s=>`toNullable(${s})`).join(", ")}]`,o=`arrayFilter(value -> isNotNull(value), ${n})`;return`if(arrayExists(value -> isNotNull(value), ${n}), ${e==="least"?"arrayMin":"arrayMax"}(${o}), NULL)`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported ClickHouse aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`toString(${e})`}concat(e){return`concat(${e.join(", ")})`}substring(e,r,n){return`substring(${e}, ${r}, ${n})`}stringLength(e){return`lengthUTF8(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported ClickHouse regex options: ${n}`);const o=n==="i"?`concat('(?i)', ${r})`:r;return`match(${e}, ${o})`}arrayContains(e,r){return`has(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${e} AS ${o}`,valueExpression:o}}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=Object.fromEntries(e.parameters.map((i,s)=>[`p${s}`,oa(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();if(e.signal?.throwIfAborted(),!r.exec)throw new d("UNSUPPORTED_RAW_SQL","ClickHouse native SQL requires client.exec");const n=await r.exec({query:e.sql,query_params:Object.fromEntries(e.parameters.map((a,u)=>[`p${u}`,oa(a)])),clickhouse_settings:{default_format:"JSONEachRow"},...e.signal?{abort_signal:e.signal}:{}}),o=[];for await(const a of n.stream)e.signal?.throwIfAborted(),o.push(Buffer.isBuffer(a)?a:Buffer.from(a));e.signal?.throwIfAborted();const i=Buffer.concat(o).toString("utf8").trim();return{rows:i?i.split(`
5
+ `).map(a=>{const u=JSON.parse(a);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("ClickHouse provider expected object rows");return u}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const Gp=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Wp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Databricks connection options must be an object");const e=t,{host:r,path:n,authType:o}=e;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0)throw new Error("Databricks connection requires host and path");if(o==="databricks-oauth"){const{oauthClientId:i,oauthClientSecret:s}=e;if(typeof i!="string"||i.length===0||typeof s!="string"||s.length===0)throw new Error("Databricks OAuth requires oauthClientId and oauthClientSecret");if("token"in e)throw new Error("Databricks OAuth connection must not define token");if("azureTenantId"in e&&typeof e.azureTenantId!="string")throw new Error("Databricks OAuth azureTenantId must be a string");if("oauthScopes"in e&&(!Array.isArray(e.oauthScopes)||e.oauthScopes.some(a=>typeof a!="string")))throw new Error("Databricks OAuth oauthScopes must be a string array");if("useDatabricksOAuthInAzure"in e&&typeof e.useDatabricksOAuthInAzure!="boolean")throw new Error("Databricks OAuth useDatabricksOAuthInAzure must be boolean");return{host:r,path:n,authType:o,oauthClientId:i,oauthClientSecret:s,...typeof e.azureTenantId=="string"?{azureTenantId:e.azureTenantId}:{},...Array.isArray(e.oauthScopes)?{oauthScopes:e.oauthScopes}:{},useDatabricksOAuthInAzure:e.useDatabricksOAuthInAzure??(Gp(r)&&!e.azureTenantId)}}if(o==="access-token"){if(typeof e.token!="string"||e.token.length===0)throw new Error("Databricks access-token connection requires token");if(["oauthClientId","oauthClientSecret","azureTenantId","oauthScopes","useDatabricksOAuthInAzure"].some(i=>i in e))throw new Error("Databricks access-token connection must not define OAuth fields");return{host:r,path:n,authType:o,token:e.token}}throw new Error(`Unsupported Databricks authType: ${String(o)}`)},zp=t=>{if(t==null)return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||t instanceof Date)return t;throw new TypeError(`Unsupported Databricks parameter type: ${typeof t}`)};class Kp{kind="databricks";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;#r;constructor(e={}){this.#e=e.connection,this.#t=e.client}async#n(){this.#r??=(async()=>{const e=this.#t??new(await import("@databricks/sql").catch(r=>{throw et("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Wp(this.#e))}catch(r){throw await e.close().catch(()=>{}),r}return e})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return So(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Databricks date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){const n={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",week:"WEEKOFYEAR",month:"MONTH",quarter:"QUARTER",year:"YEAR"};return r==="weekday"?`(WEEKDAY(${e}) + 1)`:`${n[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Databricks date shift: ${r}/${n}`);return`TIMESTAMPADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS TIMESTAMP)`:r==="date"?`CAST(${e} AS DATE)`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Databricks aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS STRING)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Databricks regex options: ${n}`);return`${e} RLIKE ${n==="i"?`CONCAT('(?i)', ${r})`:r}`}arrayContains(e,r){return`ARRAY_CONTAINS(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`LATERAL VIEW EXPLODE(${e}) ${o} AS ${i}`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=this.#e?.schema??this.#e?.database,o=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let i;const s=()=>{i&&i.cancel().catch(()=>{})};e.signal?.addEventListener("abort",s,{once:!0});try{e.signal?.throwIfAborted(),i=await o.executeStatement(e.sql,{ordinalParameters:e.parameters.map(zp)}),e.signal?.aborted&&s(),e.signal?.throwIfAborted(),await i.finished?.(),e.signal?.throwIfAborted();const a=await i.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(a))throw new Error("Databricks provider expected an array result");return a}finally{e.signal?.removeEventListener("abort",s);try{i&&await i.close()}finally{await o.close()}}}async runSQL(e){return{rows:await this.execute(e)}}describeTable(e){const r=e.database??this.#e?.catalog,n=e.schema??this.#e?.schema??this.#e?.database;return Ge(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),ar(e);const r=c=>this.execute({sql:c,parameters:[],...e.signal?{signal:e.signal}:{}});let n=e.database??this.#e?.catalog,o=e.schema??this.#e?.schema??this.#e?.database;if(n===void 0||o===void 0){const[c]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!c)throw new Error("Databricks current namespace was not returned");n??=Pe(c,"table_database"),o??=Pe(c,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),u=new Map;for(const c of s){const p=Pe(c,"tableName");u.set(p,{name:p,database:n,schema:o,type:"table"})}for(const c of a){const p=Pe(c,"viewName");u.set(p,{name:p,database:n,schema:o,type:"view"})}return[...u.values()].sort((c,p)=>c.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const ia=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Dameng parameter type: ${typeof t}`)},Jp=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class Xp{kind="dameng";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e={...Jp(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${rn.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw et("dmdb",n)});return r.createPool(e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return"?"}displayQuery(e,r){return qp(e,r.map(ia))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Dameng date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Dameng aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Dameng regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return mt(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Ge(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection();try{e.signal?.throwIfAborted();const i=await o.execute(e.sql,e.parameters.map(ia),{outFormat:4002,...r?{autoCommit:!0}:{}});if(e.signal?.throwIfAborted(),!(r&&i.rows===void 0)&&!Array.isArray(i.rows))throw new Error("Dameng provider expected an array result");return{rows:i.rows??[],...typeof i.rowsAffected=="number"?{affectedRows:i.rowsAffected}:{}}}finally{await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}const z={quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``},tableAlias(t,e){return`${t} AS ${this.quoteIdentifier(e)}`},paginate(t,e,r){return`${t} LIMIT ${e}${r>0?` OFFSET ${r}`:""}`},parameter(t,e){return"?"},displayQuery(t,e){return Mp(t,e)},dateBucket(t,e){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(e==="week")return`DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;if(e==="quarter")return`MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${e}`);return`DATE_FORMAT(${t}, '${n}')`},datePart(t,e){const r={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",month:"MONTH",quarter:"QUARTER",year:"YEAR"};if(e==="weekday")return`(WEEKDAY(${t}) + 1)`;if(e==="week")return`WEEK(${t}, 3)`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date part: ${e}`);return`${n}(${t})`},dateShift(t,e,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${e}/${r}`);return`DATE_ADD(${t}, INTERVAL ${r} ${e.toUpperCase()})`},datePeriodBoundary(t,e,r){if(r==="start")return this.dateBucket(t,e);switch(e){case"hour":return`DATE_FORMAT(${t}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${t}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${t}), '23:59:59')`;case"year":return`CONCAT(YEAR(${t}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(t,e),e,1),"second",-1)}},aggregateFunction(t,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported MySQL-compatible aggregate function: ${t}`);return`${t.toUpperCase()}(${e})`},stringify(t){return`CAST(${t} AS CHAR)`},concat(t){return`CONCAT(${t.join(", ")})`},substring(t,e,r){return`SUBSTRING(${t}, ${e}, ${r})`},stringLength(t){return`CHAR_LENGTH(${t})`},regex(t,e,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${t}) REGEXP LOWER(${e})`:`${t} REGEXP ${e}`},arrayContains(t,e){return`JSON_OVERLAPS(${t}, JSON_ARRAY(${e}))`},expandArray(t,e,r){const n=this.quoteIdentifier(e),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},Zp={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Qr{supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{createPool:e}=await import("mysql2/promise").catch(r=>{throw et("mysql2",r)});return e({...Zp,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return z.quoteIdentifier(e)}tableAlias(e,r){return z.tableAlias(e,r)}paginate(e,r,n){return z.paginate(e,r,n)}parameter(e,r){return z.parameter(e,r)}displayQuery(e,r){return z.displayQuery(e,r)}dateBucket(e,r){return z.dateBucket(e,r)}datePart(e,r){return z.datePart(e,r)}dateShift(e,r,n){return z.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=z.datePeriodBoundary?.bind(z);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return z.aggregateFunction(e,r)}stringify(e){return z.stringify(e)}concat(e){return z.concat(e)}substring(e,r,n){return z.substring(e,r,n)}stringLength(e){return z.stringLength(e)}regex(e,r,n){return z.regex(e,r,n)}arrayContains(e,r){const n=z.arrayContains?.bind(z);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n){const o=z.expandArray?.bind(z);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(e,r,n)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async#n(e,r){e.signal?.throwIfAborted();const n=await this.#r();e.signal?.throwIfAborted();const[o]=await n.execute(e.sql,e.parameters);if(e.signal?.throwIfAborted(),r&&typeof o=="object"&&o!==null&&"affectedRows"in o&&typeof o.affectedRows=="number")return{rows:[],affectedRows:o.affectedRows};if(!Array.isArray(o))throw new Error(`${this.kind} provider expected an array result`);return{rows:o}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}class ef extends Qr{kind="doris";constructor(e={}){super(e)}}class tf extends Qr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class rf{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return z.quoteIdentifier(e)}tableAlias(e,r){return z.tableAlias(e,r)}paginate(e,r,n){return z.paginate(e,r,n)}parameter(e,r){return z.parameter(e,r)}displayQuery(e,r){return z.displayQuery(e,r)}dateBucket(e,r){return z.dateBucket(e,r)}datePart(e,r){return z.datePart(e,r)}dateShift(e,r,n){return z.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=z.datePeriodBoundary?.bind(z);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return z.aggregateFunction(e,r)}stringify(e){return z.stringify(e)}concat(e){return z.concat(e)}substring(e,r,n){return z.substring(e,r,n)}stringLength(e){return z.stringLength(e)}regex(e,r,n){return z.regex(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#e.execute(e);if(e.signal?.throwIfAborted(),!Array.isArray(r))throw new Error("MaxCompute provider expected an array result");return r}async runSQL(e){e.signal?.throwIfAborted();const r=this.#e.runSQL?await this.#e.runSQL(e):{rows:await this.execute(e)};return e.signal?.throwIfAborted(),r}async getTableList(e){if(e.signal?.throwIfAborted(),ar(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Ce(this,"database"),e.schema!==void 0&&Ce(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Pe(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Io(e),!this.#e.describeTable)return Ge(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class nf extends Qr{kind="mysql";constructor(e={}){super(e)}}const sa=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Oracle parameter type: ${typeof t}`)},of=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class sf{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return`:${e+1}`}displayQuery(e,r){return kp(e,r.map(sa))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Oracle aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}arrayContains(e,r){return`JSON_EXISTS(${e}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${e}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#r??=(async()=>{if(this.#t)return this.#t.createPool(this.#e);const{default:e}=await import("oracledb").catch(r=>{throw et("oracledb",r)});return e.createPool(this.#e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection(),i=e.signal,s=()=>{o.break().catch(()=>{})};i?.addEventListener("abort",s,{once:!0});try{i?.throwIfAborted();const a=await o.execute(e.sql,e.parameters.map(sa),{outFormat:4002,...r?{autoCommit:!0}:{}});if(i?.throwIfAborted(),!(r&&a.rows===void 0)&&!Array.isArray(a.rows))throw new Error("Oracle provider expected an array result");return{rows:a.rows??[],...typeof a.rowsAffected=="number"?{affectedRows:a.rowsAffected}:{}}}catch(a){throw i?.aborted?of(i):a}finally{i?.removeEventListener("abort",s),await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}class af{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{Pool:e}=await import("pg").catch(r=>{throw et("pg",r)});return new e(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`$${e+1}`}displayQuery(e,r){return Up(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported PostgreSQL date shift: ${r}/${n}`);return`(${e} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported PostgreSQL aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS TEXT)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e} FROM ${r} FOR ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${e} ${n==="i"?"~*":"~"} ${r}`}arrayContains(e,r){return`${r} = ANY(${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(e){return(await this.runSQL(e)).rows}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=await r.query(e.sql,[...e.parameters]);if(e.signal?.throwIfAborted(),!Array.isArray(n.rows))throw new Error("PostgreSQL provider expected an array result");return{rows:n.rows,...typeof n.rowCount=="number"&&["INSERT","UPDATE","DELETE","MERGE"].includes(n.command??"")?{affectedRows:n.rowCount}:{}}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}const aa=t=>{if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof t}`)},cf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class uf{kind="snowflake";#e;#t;#r=!1;#n;constructor(e={}){this.#e=e.connection??{},this.#t=e.client?Promise.resolve(e.client):void 0}async#o(){this.#t??=(async()=>{const{default:e}=await import("snowflake-sdk").catch(r=>{throw et("snowflake-sdk",r)});return e.createConnection(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return So(e,r.map(aa))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){return`DATE_PART(${r==="weekday"?"DAYOFWEEKISO":r==="week"?"WEEKISO":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Snowflake date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_VARCHAR(${e})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#s(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){return(await this.#i(e,!1)).rows}async runSQL(e){return this.#i(e,!0)}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async#i(e,r){e.signal?.throwIfAborted(),await this.#s(),e.signal?.throwIfAborted();const n=await this.#o();e.signal?.throwIfAborted();const o=e.parameters.map(aa);return new Promise((i,s)=>{const a=e.signal,u={};let c=!1;const p=f=>{c||(c=!0,a?.removeEventListener("abort",l),f())},l=()=>{u.current?.cancel(),a&&p(()=>s(cf(a)))};a?.addEventListener("abort",l,{once:!0}),u.current=n.execute({sqlText:e.sql,binds:o,complete:(f,m,y)=>{if(f){p(()=>s(f));return}if(!(r&&y===void 0)&&!Array.isArray(y)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const g=r?m.getNumUpdatedRows?.():void 0;p(()=>i({rows:y??[],...typeof g=="number"&&g>=0?{affectedRows:g}:{}}))}}),a?.aborted&&l()})}async close(){if(!this.#r)return;const e=await this.#o();await new Promise((r,n)=>{e.destroy(o=>{if(o){n(o);return}this.#r=!1,this.#n=void 0,this.#t=void 0,r()})})}}const df=t=>{const{host:e,server:r,options:n,pool:o,...i}=t;return{...i,server:r??e??"localhost",port:t.port??1433,requestTimeout:t.requestTimeout??6e4,connectionTimeout:t.connectionTimeout??3e4,options:{encrypt:!1,trustServerCertificate:!0,enableArithAbort:!0,...n},pool:{max:10,min:0,idleTimeoutMillis:3e4,...o}}},lf=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported SQL Server parameter type: ${typeof t}`)},pf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),ff=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),mf=t=>{let e=0,r;for(let n=0;n<t.length;n+=1){const o=t[n];if(o){if(r){o===r&&(t[n+1]===r?n+=1:r=void 0);continue}if(o==="'"||o==='"')r=o;else if(o==="[")r="]";else if(o==="(")e+=1;else if(o===")")e=Math.max(0,e-1);else if(e===0&&/^ORDER\s+BY\b/i.test(t.slice(n)))return!0}}return!1};class yf{kind="sqlserver";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e=this.#t??await import("mssql").then(n=>n.default,n=>{throw et("mssql",n)}),r=new e.ConnectionPool(df(this.#e));return await r.connect(),r})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`[${e.replaceAll("]","]]")}]`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${mf(e)?e:`${e} ORDER BY (SELECT NULL)`} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`}parameter(e,r){return`@p${e}`}displayQuery(e,r){return jp(e,r)}dateBucket(e,r){const n=new Set(["second","minute","hour","day","month","quarter","year"]);if(r==="week")return`DATEADD(DAY, -(((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7), CAST(${e} AS DATE))`;if(!n.has(r))throw new Error(`Unsupported SQL Server date level: ${r}`);const o=r==="second"||r==="minute"?"'20000101'":"0";return`DATEADD(${r.toUpperCase()}, DATEDIFF(${r.toUpperCase()}, ${o}, ${e}), ${o})`}datePart(e,r){return r==="weekday"?`((((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7) + 1)`:`DATEPART(${r==="week"?"ISO_WEEK":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported SQL Server date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS DATETIME2)`:r==="date"?`CAST(${e} AS DATE)`:r==="string"?`CAST(${e} AS NVARCHAR(MAX))`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported SQL Server aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS NVARCHAR(MAX))`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LEN(${e})`}regex(e,r,n){throw new Error("SQL Server does not provide a native regular-expression predicate")}arrayContains(e,r){return`EXISTS (SELECT 1 FROM OPENJSON(${e}) AS [semanticdb_array] WHERE [semanticdb_array].[value] = ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`CROSS APPLY OPENJSON(${e}) AS ${o}`,valueExpression:`${o}.[value]`}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return mt(this,e)}describeTable(e){return Ge(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=n.request();return e.parameters.forEach((i,s)=>o.input(`p${s}`,lf(i))),new Promise((i,s)=>{const a=e.signal;let u=!1;const c=l=>{u||(u=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&c(()=>s(pf(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){c(()=>s(new Error("SQL Server provider expected an array result")));return}c(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((f,m)=>f+m,0)}:{}}))},l=>c(()=>s(ff(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class hf extends Qr{kind="starrocks";constructor(e={}){super(e)}}const De=t=>{const{id:e,kind:r,...n}=t;return n},gf=Object.freeze([{kind:"mysql",create:t=>new nf({connection:De(t)})},{kind:"doris",create:t=>new ef({connection:De(t)})},{kind:"gbase",create:t=>new tf({connection:De(t)})},{kind:"starrocks",create:t=>new hf({connection:De(t)})},{kind:"maxcompute",create:t=>new rf(De(t))},{kind:"postgresql",create:t=>new af({connection:De(t)})},{kind:"clickhouse",create:t=>new Hp(De(t))},{kind:"databricks",create:t=>new Kp({connection:De(t)})},{kind:"dameng",create:t=>new Xp({connection:De(t)})},{kind:"snowflake",create:t=>new uf({connection:De(t)})},{kind:"sqlserver",create:t=>new yf({connection:De(t)})},{kind:"oracle",create:t=>new sf({connection:De(t)})}]);class ca{#e=new Map;constructor(e=gf){e.forEach(r=>this.register(r))}register(e){if(!e.kind)throw new d("INVALID_PROVIDER","Provider kind must not be empty");if(this.#e.has(e.kind))throw new d("PROVIDER_ALREADY_REGISTERED",`Provider is already registered: ${e.kind}`,{provider:e.kind});return this.#e.set(e.kind,e),this}create(e){const r=this.#e.get(e.kind);if(!r)throw new d("PROVIDER_NOT_FOUND",`Provider is not registered: ${e.kind}`,{provider:e.kind});return r.create(e)}has(e){return this.#e.has(e)}}const ua=new ca,da=(t,e=ua)=>e.create(t);class Af{create;#e=new Map;constructor(e=da){this.create=e}get(e){const r=this.#e.get(e.id);if(r){if(!xo.isDeepStrictEqual(r.connection,e))throw new d("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${e.id}`,{connectionId:e.id});return r.provider}const n=this.create(e);return this.#e.set(e.id,{connection:e,provider:n}),n}async close(){const e=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(e.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Hr=new Map,wf=t=>{const e=Hr.get(t);if(e)return e;const r=new Af(n=>da(n,t));return Hr.set(t,r),r},Gr=(t,e=ua)=>wf(e).get(t),$f=async()=>{const t=[...Hr.values()];Hr.clear();const r=(await Promise.allSettled(t.map(async n=>n.close()))).flatMap(n=>n.status==="rejected"?[n.reason]:[]);if(r.length>0)throw new AggregateError(r,"Failed to close one or more connection registries")},la=async()=>{const e=(await Promise.allSettled([$f(),yp()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},Ef=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=Gr(t.connection,t.providerRegistry);if(!e.runSQL)throw new d("UNSUPPORTED_RAW_SQL",`Provider does not support native SQL: ${e.kind}`);const r=await e.runSQL({sql:t.sql,parameters:t.parameters??[],...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},_f=async t=>{t.signal?.throwIfAborted(),ar(t);const e=Gr(t.connection,t.providerRegistry);if(!e.getTableList)throw new d("UNSUPPORTED_TABLE_DISCOVERY",`Provider does not support table discovery: ${e.kind}`);const r=await e.getTableList({...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Sf=async t=>{t.signal?.throwIfAborted(),Io(t);const e=Gr(t.connection,t.providerRegistry);if(!e.describeTable)throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`Provider does not support table description: ${e.kind}`);const r=await e.describeTable({table:t.table,...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.includeSample!==void 0?{includeSample:t.includeSample}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},If=Object.freeze({runSQL:Ef,getTableList:_f,describeTable:Sf,close:la}),bf=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:ue.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:ue.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:ue.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:ue.VARCHAR,sqlType:"VARCHAR"}}},Rf=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Nf=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return ue.jsToDuckDBValue(Rf(t),ue.BOOLEAN);case"date":{const r=t instanceof Date?t:new Date(typeof t=="number"||typeof t=="string"?t:Number.NaN);return Number.isNaN(r.getTime())?null:ue.jsToDuckDBValue(r,ue.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?ue.jsToDuckDBValue(r,ue.DOUBLE):null}case"string":return typeof t=="string"?ue.jsToDuckDBValue(t,ue.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?ue.jsToDuckDBValue(t.toString(),ue.VARCHAR):typeof t=="symbol"?ue.jsToDuckDBValue(t.description??"",ue.VARCHAR):typeof t=="function"?ue.jsToDuckDBValue(t.name,ue.VARCHAR):ue.jsToDuckDBValue(JSON.stringify(t),ue.VARCHAR)}},Of=t=>{if(t==null)return null;if(t instanceof Date)return ue.jsToDuckDBValue(t,ue.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return ue.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class Zr{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await ue.DuckDBInstance.create(":memory:"),r=await e.connect();return new Zr(e,r)}constructor(e,r){this.instance=e,this.connection=r}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return So(e,r)}dateBucket(e,r){return`DATE_TRUNC('${r.replaceAll("'","''")}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){return`(${e} + INTERVAL '${n} ${r.replaceAll("'","''")}')`}datePeriodBoundary(e,r,n){const o=this.dateBucket(e,r);return n==="start"?o:`(${o} + INTERVAL '1 ${r.replaceAll("'","''")}' - INTERVAL '1 microsecond')`}castValue(e,r){return`CAST(${e} AS ${r==="timestamp"?"TIMESTAMP":r==="date"?"DATE":"VARCHAR"})`}scalarExtremum(e,r){return`${e.toUpperCase()}(${r.join(", ")})`}aggregateFunction(e,r){const n={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"};if(e==="countDistinct")return`COUNT(DISTINCT ${r??"*"})`;const o=n[e];if(!o)throw new Error(`Unsupported DuckDB aggregate: ${e}`);return`${o}(${r??"*"})`}stringify(e){return`CAST(${e} AS VARCHAR)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){return n?`REGEXP_MATCHES(${e}, ${r}, '${n.replaceAll("'","''")}')`:`REGEXP_MATCHES(${e}, ${r})`}arrayContains(e,r){return`LIST_CONTAINS(${e}, ${r})`}async materialize(e,r,n){const o=r.map(bf),i=o.map(a=>`${this.quoteIdentifier(a.name)} ${a.sqlType}`).join(", ");await this.connection.run(`CREATE TABLE ${this.quoteIdentifier(e)} (${i})`);const s=await this.connection.createAppender(e);try{for(const a of n){for(const u of o){const c=Nf(a[u.name],u);c===null?s.appendNull():s.appendValue(c,u.type)}s.endRow()}s.flushSync()}finally{s.closeSync()}}async execute(e){e.signal?.throwIfAborted();const r=await this.connection.runAndReadAll(e.sql,e.parameters.map(Of));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Ro="__sdb_total__",Tf="__sdb_total_source__",No=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Pf=t=>{const e={...t};return delete e.limit,delete e.page,e},Oo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(Ro)} FROM ${e.tableAlias(`(${t.sql})`,Tf)}`,parameters:t.parameters}),Wr=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[Ro]??e[Ro.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new d("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},Mt="__semanticdb_coordinator__",pa=(t,e)=>{const r=new Set;for(const n of we(t)){const o=e.findSource(n.schemaId,n.source,n.connectionId);if(!o)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${n.schemaId}:${n.source}`,{schemaId:n.schemaId,source:n.source});r.add(o.connectionId)}return[...r]},cr=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>pa(r,e))).size>1||!!(t.sourcePlan&&cr(t.sourcePlan,e)),Lf=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Cf=(t,e)=>{const r=t.map(n=>n[e]).find(n=>n!=null);return typeof r=="number"||typeof r=="bigint"?"number":typeof r=="boolean"?"boolean":r instanceof Date?"date":"string"},fa=(t,e)=>{const r=new Map((t.columnProperties??[]).map(n=>[n.name,n]));return[...t.projections.map(({name:n})=>n),"_id"].map(n=>{const o=r.get(n),i=n==="_id"?"string":o?.primal_type==="number"?"number":o?.primal_type==="boolean"?"boolean":o?.primal_type==="date"?"date":o?.primal_type==="entity"||o?.primal_type==="object"?Cf(e,n):"string";return{name:n,kind:i}})},Df=(t,e)=>{const r=t.projections.map(({name:n})=>n);return{schemaId:t.schemaId,source:e,sourceAlias:e,fields:Object.fromEntries([...r,"_id"].map(n=>[n,n])),projections:[...r,"_id"].map(n=>Lf(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},kf=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:JSON.stringify(r.names.map(o=>{const i=n[o];return i==null?["null"]:i instanceof Date?["date",i.toISOString()]:typeof i=="bigint"?["bigint",i.toString()]:typeof i=="object"?"_id"in i||"id"in i?["entity",Lr(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new d("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},ma=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:Cr(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},zr=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&cr(t.sourcePlan,e.schemaMappings)){const s=await zr(t.sourcePlan,e),a=await Zr.create();try{const u="__federated_source";await a.materialize(u,fa(t.sourcePlan,s.rows),s.rows);const c={...t,source:u};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const p=fe(c,a,e.operators),l=Oo(fe(No(c),a,e.operators),a),f=e.onCompiled({compiled:p,connectionId:Mt,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:l,connectionId:Mt,provider:a,type:"total",logicform:e.logicform})("database");const y=await a.execute({...l,...e.signal?{signal:e.signal}:{}});f("database");const g=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:ma(g,t),total:Wr(y),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new d("INVALID_FEDERATED_PLAN","A federated composition requires at least two child plans");const r=new Map,n=await Promise.all(t.subplans.map(async s=>{const a=pa(s,e.schemaMappings);if(a.length!==1)throw new d("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const p=fe(s,c,e.operators),l=e.onCompiled({compiled:p,connectionId:u,provider:c,type:"computation",logicform:e.logicform}),f=await $o(p,we(s),{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},l),m=await ut(f,s.projections,e.operators);return{child:s,rows:kf(m,s)}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new d("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await Zr.create();try{const s=n.flatMap(({rows:g})=>g),a=[];for(const[g,{child:h,rows:_}]of n.entries()){const E=`__federated_branch_${g}`;await i.materialize(E,fa(h,s),_),a.push(Df(h,E))}const u={...t,subplans:a},c=fe(u,i,e.operators),p=Oo(fe(No(u),i,e.operators),i),l=e.onCompiled({compiled:c,connectionId:Mt,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,connectionId:Mt,provider:i,type:"total",logicform:e.logicform})("database");const m=await i.execute({...p,...e.signal?{signal:e.signal}:{}});l("database");const y=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:ma(y,t),total:Wr(m),connections:[...r].map(([g,h])=>({connectionId:g,provider:h}))}}finally{await i.close()}},Uf=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),To=t=>!v(t)||!Array.isArray(t.properties)?[]:t.properties.filter(v),Mf=(t,e)=>{const r=e[t];return v(r)?r:Object.values(e).find(n=>v(n)&&(n.id===t||n._id===t))},ya=(t,e,r)=>{const n=Mf(t,r);if(!n)return;const i=To(n).map(s=>{const u=[s.id,s._id,s.name].filter(c=>typeof c=="string").filter(c=>e===c||e.startsWith(`${c}_`)).sort((c,p)=>p.length-c.length)[0];return u?{property:s,key:u}:void 0}).filter(s=>s!==void 0).sort((s,a)=>a.key.length-s.key.length)[0];if(i)return e===i.key?i.property:typeof i.property.ref=="string"?ya(i.property.ref,e.slice(i.key.length+1),r):void 0},qt=(t,e,r)=>{const n=(o,i,s)=>{const c=To(r[o]).map(y=>{const g=typeof y.id=="string"?y.id:void 0,h=typeof y.name=="string"?y.name:void 0,E=[g,h].filter(I=>!!I&&(i===I||i.startsWith(`${I}_`))).sort((I,$)=>$.length-I.length)[0];return E?{property:y,key:E}:void 0}).filter(y=>!!y).sort((y,g)=>g.key.length-y.key.length)[0];if(!c)return;const p=String(c.property.id??c.property.name),l=i===c.key?"":i.slice(c.key.length+1);if(!l)return p;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,l,new Set(s).add(f));return m?`${p}_${m}`:void 0};return n(t,e,new Set([t]))},Po=(t,e,r)=>{const n=To(r[t]).filter(o=>typeof o.id=="string").sort((o,i)=>String(i.id).length-String(o.id).length).find(o=>e===o.id||e.startsWith(`${String(o.id)}_`));if(!(!n||typeof n.id!="string")){if(e===n.id)return n.id;if(typeof n.ref=="string")return Po(n.ref,e.slice(n.id.length+1),r)}},ha=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),v=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ga=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),Aa=t=>{if(!v(t))return t;if(v(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return t},qf=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),jf=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>v(u)&&(u.id===t||u._id===t));if(!v(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:v(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!v(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?v(s)&&s.use_full_length===!0?"zero-padded":"compact":v(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},xf=(t,e,r)=>{const n=jf(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new d("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},Bf=(t,e)=>e.length===0?t:e.length===1&&t.$expr===void 0?{...t,$expr:e[0]}:{$and:[...Object.keys(t).length>0?[t]:[],...e.map(n=>({$expr:n}))]},Lo=(t,e)=>{const r={},n=[];for(const[o,i]of Object.entries(t)){if((o==="$and"||o==="$or")&&Array.isArray(i)){r[o]=i.map(y=>v(y)?Lo(y,e):y);continue}if(!v(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!v(i.query)||!qf(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:xf(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:p,...l}=i,f=Lo(i.query,e),m=Object.keys(l).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...l,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return Bf(r,n)},Vf=(t,e)=>{const n=t&&({$sply:"$periodShift",$splm:"$periodShift",$splq:"$periodShift",$splw:"$periodShift",$yoy:"$periodGrowth",$mom:"$periodGrowth",$qoq:"$periodGrowth",$wow:"$periodGrowth",$yoyd:"$periodDifference",$momd:"$periodDifference",$qoqd:"$periodDifference",$wowd:"$periodDifference",$dailyavg:"$averagePerPeriod",$weeklyavg:"$averagePerPeriod",$monthlyavg:"$averagePerPeriod",$startOfPeriod:"$periodValue",$endOfPeriod:"$periodValue",$dateLevel:"$dateBucket",$uniq:"$countDistinct",$percentage:"$shareOfTotal"}[t]??t),o={...e};return t==="$sply"||t==="$yoy"||t==="$yoyd"?o.time??={granularity:"year",offset:-1}:t==="$splm"||t==="$mom"||t==="$momd"?o.time??={granularity:"month",offset:-1}:t==="$splq"||t==="$qoq"||t==="$qoqd"?o.time??={granularity:"quarter",offset:-1}:t==="$splw"||t==="$wow"||t==="$wowd"?o.time??={granularity:"week",offset:-1}:t==="$dailyavg"?o.granularity??="day":t==="$weeklyavg"?o.granularity??="week":t==="$monthlyavg"?o.granularity??="month":t==="$startOfPeriod"?o.boundary??="start":t==="$endOfPeriod"&&(o.boundary??="end"),{...n?{operator:n}:{},args:o}},wa=(t,e)=>{if(!v(e)||!Array.isArray(e.cases)||e.cases.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} requires a non-empty params.cases array`);return{cases:e.cases.map((n,o)=>{if(!v(n))throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} must be an object`);if(n.sql!==void 0)throw new d("LEGACY_CASE_SQL_UNSUPPORTED",`${t} case.sql cannot be migrated to the structured v2 $case operator`);if(!v(n.query)||typeof n.name!="string"||n.name.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} requires query and a non-empty name`);return{when:n.query,then:n.name}}),...Object.hasOwn(e,"default")?{default:e.default}:{}}},We=(t,e,r)=>{if(Array.isArray(t))return t.map(u=>We(u,e,r));if(!v(t))return t;const n=Aa(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[u,c]of Object.entries(o))u==="skip"||u==="_snapshot"||u==="_snapshots"||(s[u]=We(c,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const u=o.groupby;s.groupby=u.map(c=>{if(!v(c))return c;const p=We(c,e,i);if(!v(p))return p;const{_id:l,level:f,...m}=p,y={...m,...m.pred===void 0&&typeof l=="string"?{pred:l}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...v(y.args)?y.args:{},granularity:f}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const u=o.limit;a===0?delete s.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&a%u===0?s.page=a/u+1:s.skip=a}else a!==void 0&&(s.skip=We(a,e,i));if(o.operator&&typeof o.operator=="string"){const u=Vf(o.operator,v(s.args)?s.args:{});if(u.operator&&(s.operator=u.operator),s.args=u.args,o.operator==="$comp"||o.operator==="$compabs"){const c=v(s.args)?s.args.preds:void 0;if(!Array.isArray(c)||c.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const p={operator:"$subtract",pred:c,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?p:c,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const c=v(s.params)?s.params:s.args;s.operator="$case",s.args=wa("$switch",c),delete s.params}if(o.operator==="$piecewise"){const c=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&c&&ya(i,c,e)?.cases!==void 0)throw new d("LEGACY_PIECEWISE_PROPERTY_CASES_UNSUPPORTED","$piecewise property cases contain trusted SQL and cannot be migrated safely to v2 $case",{schemaId:i,property:c});const p=v(s.params)?s.params:v(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(p.cases)?wa("$piecewise",p):{mode:"auto",buckets:Number.isInteger(p.buckets)?p.buckets:10},delete s.params}Uf.has(o.operator)&&typeof s.pred=="string"&&(s.pred={operator:"$sum",pred:s.pred})}return o.params!==void 0&&s.args===void 0&&(s.args=Array.isArray(o.params)?{values:We(o.params,e,i)}:We(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(u=>We(u,e,i)),v(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...v(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...v(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&ga(o.$gte)&&ga(o.$lte)&&delete s.$options,o.query&&v(o.query)&&(s.query=Ff(o.query,e,i)),s},Ff=(t,e,r)=>{const n=We(t,e,r);for(const[o,i]of Object.entries(n))n[o]=Aa(i);return Lo(n,e)},$a=(t,e)=>{const r=v(t)?t:void 0,n=We(t,e);if(!v(n))return n;if(r&&typeof r.operator=="string"&&r.preds===void 0){const o={};for(const a of["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],$a(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Yf(n,e):n},Yf=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)v(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>v(u)&&typeof u.pred=="string"?qt(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,p)=>{if(!v(c)||typeof c.pred!="string")return c;const l=u===o?qt(u,c.pred,e):qt(u,Po(o,s[p]??"",e)??c.pred,e);if(!l)return c;const f=l.split("_").at(-1)??c.pred;return{...c,pred:l,name:f}}),v(r.query))for(const c of ha(r.query)){const p=qt(o,c,e);if(!(u===o?p:qt(u,(p&&Po(o,p,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!v(u)||typeof u.pred!="string")return u;const p=s[c];return p?{...u,pred:p}:u})),v(r.query)){const u=r.query,c=ha(u).map(p=>[qt(o,p,e)??p,u[p]]);a.query=Object.fromEntries(c)}return a},vf=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(v(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs","entity_level","entity_codelength"].includes(o))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},Co=t=>{if(Array.isArray(t))return t.map(Co).filter(n=>n!==void 0);if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return t;const e=Object.entries(t),r=e.filter(([,n])=>n!==null).map(([n,o])=>[n,Co(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Qf=t=>{if(t.comparable!=null)return t.comparable;if(t.is_comparable!==!0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!Array.isArray(t.constraints?.enum))return;const r=t.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:t.comparable_order===-1?-1:1}},Hf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=t;if(e.sql!=null)return Object.keys(e).every(r=>r==="sql")?t:{sql:e.sql}},Gf=(t,e=[],r=!0)=>{const n=pe(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=Co(a),c=u,l=(Array.isArray(c.properties)?c.properties:[]).some(I=>I.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:y}=u,g=Object.fromEntries(Object.entries(u).filter(([I])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(I):I!=="properties")&&I!=="properties"&&!i.has(I))),h=y.map(I=>{const $=I,A=typeof $.id=="string"&&$.id.length>0?$.id:r&&typeof $._id=="string"&&$._id.length>0?$._id:$.id,{udf:R,...L}=$,D=Qf($),U=Hf(R),q=D!==void 0&&$.comparable==null?"category":$.type==="object"?"entity":$.type;return{...r?Object.fromEntries(Object.entries(L).filter(([F])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(F))):L,type:q,...$.primal_type==="object"?{primal_type:"entity"}:{},...A!==void 0?{id:A}:{},...U!==void 0?{udf:U}:{},...D!==void 0?{comparable:D}:{}}});let _={};for(const I of n)for(const $ of I.schemaMetadata?.keys??[])u[$]!==void 0&&(_={..._,[$]:u[$]});for(const I of n)_={..._,...I.normalizeLegacySchema?.({source:u,properties:h})};const E={...g,...m!==void 0?{id:m}:{},properties:h,...r&&(f||l)?{temporalSemantics:"snapshot"}:{},..._};o[s]=E}return o},Ea=(t,e)=>[...pe(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Kr=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),_a=t=>t instanceof Error?t:new Error(String(t)),Wf=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,zf=(t,e,r={},n="zh-CN",o)=>{const i=_a(t);return{errorCode:"100",error:Wf(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},Kf=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,p)=>{const l=r.parameter(i.length,p);i.push(p);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(l,f):l},a=c=>`SELECT ${n.map(p=>`${s(p,c[p])} AS ${r.quoteIdentifier(p)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Jf=(t,e,r)=>{if(t.length<2||t.some(i=>i.kind==="js"||i.kind==="query"&&i.unit.mapResult))return!1;const n=new Set,o=[...t.flatMap(({sources:i})=>i),...we(r)];for(const i of o){const s=wo(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Xf=async(t,e,r)=>{await t?.({...e,partialResult:r})},Zf=(t,e,r,n,o,i,s=r,a)=>({type:r,...a?{connectionId:a}:{},provider:e.kind,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="auto-case"?"sql.autoCase":s==="entity-expansion"?"sql.entityExpansion":s==="total"?"sql.total":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),Do=(t,e)=>{if(e.connectionId)for(const r of we(t)){const n=wo(r,e.schemaMappings);if(!n)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${r.schemaId}:${r.source}`,{schemaId:r.schemaId,source:r.source});if(n.connectionId!==e.connectionId)throw new d("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One physical query cannot use multiple database connections: ${e.connectionId}, ${n.connectionId}`,{schemaId:r.schemaId,source:r.source,connectionId:n.connectionId})}},em=t=>{const e=new Set,r=n=>{n.from&&r(n.from),n.schema&&e.add(n.schema);for(const o of n.preds??[])for(const i of ko(o))e.add(i)};return r(t),[...e]},ko=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...ko(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:ko(r))]:e},Sa=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??mr(Ea(e.plugins,e.locales)),o=e.plugins??[],i=t.version,s=typeof i=="string"&&(/^2\./.test(i)||/^[3-9]\d*\./.test(i)),a=i===void 0||typeof i=="string"&&/^1\./.test(i);s&&vf(t);const u=a?$a(t,e.schemas):t,c={...e,locale:r,localeRegistry:n,schemas:Gf(e.schemas,o,a)},p=tn.performance.now(),l=c.semanticTypes===void 0?so(o):c.semanticTypesResolved?c.semanticTypes:Ss(c.semanticTypes,o);let f=c.operators??ke(o);if(c.operators&&!c.operatorsResolved)for(const C of o)for(const w of C.operators??[])if(f.has(w.name)){if(f.get(w.name)!==w)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${w.name}`,{operator:w.name,plugin:C.name})}else f.register(w);const m=c.schemaMappings,y=new Date,g=new Map,h=new Map,_=[],E=new Set,I=C=>{const w=JSON.stringify(C);E.has(w)||(E.add(w),_.push(C),$={...$,schemaMappingSelections:[..._]})};let $={provider:c.provider.kind};const A=[],R=new WeakMap,L=new Map;c.connectionId&&L.set(c.connectionId,c.provider.kind);const D=(C,w,S,b=w,O=c.provider,k=c.connectionId)=>{k&&k!==Mt&&L.set(k,O.kind);const j=A.length;A.push(Zf(Ws(C),O,w,S,c.locale??"zh-CN",n,b,k)),$={...$,sqls:[...A],providers:[...L].map(([W,T])=>({connectionId:W,provider:T}))};const Q=W=>{A[j]={...A[j],executionSource:W},$={...$,sqls:[...A]}};return R.set(C,Q),Q},U=(C,w)=>$o(C,w,c,R.get(C)),q=async(C,w={})=>{$={...$,...w},await Xf(c.onProgress,C,$)},X=C=>As(pc(C,c.schemas),l,o),F=new Map,P=C=>{const w=F.get(C);return w||(He(c.permissions,C),X(C))},Y=C=>{if(C.schema)return P(C.schema);if(C.from)return Y(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},ce=C=>{if(C.schema)return X(C.schema);if(C.from)return ce(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},ee=async()=>{const C=Object.values(c.schemas).filter(T=>T.is_calendar===!0);if(C.length!==1)return Object.freeze({});const w=C[0];if(!w)return Object.freeze({});const S=m.list(w.id),b=S.find(({connectionId:T})=>T===c.connectionId)??S[0];if(!b)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${w.id}`,{schemaId:w.id});const O=c.providerForConnection?.(b.connectionId)??c.provider,{onProgress:k,executionContext:j,...Q}=c,W=await Sa({version:"2.0",schema:w.id,limit:-1},{...Q,provider:O,connectionId:b.connectionId,operators:f,operatorsResolved:!0,executionContext:Object.freeze({})});A.push(...W.sqls.map(T=>({...T,type:"semantic-resolution",explain:n.translate(c.locale??"zh-CN","sql.semanticResolution")})));for(const T of W.providers)L.set(T.connectionId,T.provider);for(const T of W.schemaMappingSelections)I(T);return Object.freeze({calendar:Object.freeze(W.result.map(({_id:T,...re})=>Object.freeze(re)))})},le=e.executionContext??await ee();f=f.withExecutionContext(le);const $e={plugins:o,resolveSchema:P,onSchemaMappingSelection:I,...c.connectionId?{preferredConnectionId:c.connectionId}:{},canUsePropertyRowIdentity:(C,w)=>pt(c.permissions,C.id,w)},Re=(C,w)=>{const S=zi(Le(C,Y(C),f,m,$e),w);return F.set(S.id,S),S},ze=async(C,w,S)=>{const b=`${C.id}:${w.id}:${S.toISOString()}`,O=g.get(b);if(O)return O;const k=(async()=>{const j=pe(o).find(K=>K.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!j)return;const Q=j({logicform:u,rootSchema:C,rootProperty:w,requestedUpperBound:S,now:y,...c.timeWatermark?{defaultPolicy:c.timeWatermark}:{},resolveSchema:P,inferPropertyPath:(K,ge,_e)=>js(K,ge,_e,P)}),W=ft(Q,c.permissions,P,!1,new Set,o),T=await lt(W,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,resolveFromSchema:Re}),re=Le(T,C,f,m,$e);let H;if(cr(re,m)){const K=c.providerForConnection;if(!K)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");H=(await zr(re,{logicform:T,operators:f,schemaMappings:m,providerForConnection:K,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:_e,logicform:Ne,provider:Oe,connectionId:Be})=>D(_e,"semantic-resolution",Ne,"time-watermark",Oe,Be)})).rows}else{Do(re,c);const K=fe(re,c.provider,f);D(K,"semantic-resolution",T,"time-watermark"),H=await U(K,we(re))}const M=H[0]?.__timeWatermark__??Object.values(H[0]??{})[0];if(M==null||!(M instanceof Date)&&typeof M!="string"&&typeof M!="number")return;const ie=M instanceof Date?M:new Date(M);return Number.isNaN(ie.getTime())?void 0:ie})();return g.set(b,k),k},me=async(C,w,S)=>{const b=JSON.stringify([C.id,w,S??null]),O=h.get(b);if(O)return O;const k=(async()=>{const j={version:"2.0",schema:C.id,...S?{query:S}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:w},{name:"__autoCaseMax__",operator:"$max",pred:w},{name:"__autoCaseCount__",operator:"$count",pred:w}]},Q=await lt(j,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,resolveFromSchema:Re}),W=Le(Q,C,f,m,$e);let T;if(cr(W,m)){const Ne=c.providerForConnection;if(!Ne)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");T=(await zr(W,{logicform:Q,operators:f,schemaMappings:m,providerForConnection:Ne,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:Be,logicform:ye,provider:Ve,connectionId:yt})=>D(Be,"semantic-resolution",ye,"auto-case",Ve,yt)})).rows}else{Do(W,c);const Ne=fe(W,c.provider,f);D(Ne,"semantic-resolution",Q,"auto-case"),T=await U(Ne,we(W))}const re=T[0],H=re?.__autoCaseMin__,M=re?.__autoCaseMax__,ie=re?.__autoCaseCount__;if(H==null||M===null||M===void 0||ie===null||ie===void 0||Number(ie)===0)return{empty:!0};const K=Number(H),ge=Number(M),_e=Number(ie);if(!Number.isFinite(K)||!Number.isFinite(ge)||!Number.isSafeInteger(_e)||_e<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:H,max:M,count:ie});return{min:K,max:ge,count:_e}})();return h.set(b,k),k};try{c.signal?.throwIfAborted(),ao(u),await q({stage:"started",logicform:u}),tp(c.permissions,X);const C=Y(u);await q({stage:"validated",schema:C});const w=ft(u,c.permissions,P,!0,new Set,o),S=await lt(w,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,resolveFromSchema:Re,canProjectProperty:(N,B)=>pt(c.permissions,N.id,B),requestTimeWatermark:ze,requestAutoCaseBounds:me});await q({stage:"normalized",normedLogicform:S},{normedLogicform:S});const b=Le(S,C,f,m,$e),O=cr(b,m);O||Do(b,c);const k=b.columnProperties??[],j=Wi(b,C);F.set(j.id,j),await q({stage:"planned",plan:b},{schema:j});const Q=ji(b,C,c.provider,f,c.providerForConnection);if(await q({stage:"lineage",lineage:Q},{lineage:Q}),O){const N=c.providerForConnection;if(!N)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const B=await zr(b,{logicform:S,operators:f,schemaMappings:m,providerForConnection:N,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:Ee,type:oe,logicform:te,provider:Ae,connectionId:de})=>D(Ee,oe,te,oe,Ae,de)});await q({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await q({stage:"executing",provider:"duckdb",connectionId:Mt}),await q({stage:"hydrating"});const G=B.connections.length===1?B.connections[0]?.connectionId:void 0,V=await Zs(B.rows,k,{semanticTypes:l,plugins:o,resolveSchema:P,fetchEntities:Ee=>zs(Ee,{version:S.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,providerForConnection:N,...G?{preferredConnectionId:G}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(oe,te,Ae,de)=>D(oe,"semantic-resolution",te,"entity-expansion",Ae,de)})}),J=Jn(V,b.rowIdentity);return await q({stage:"result",result:J},{result:J,total:B.total,sqls:[...A],providers:B.connections}),await q({stage:"completed",durationMs:tn.performance.now()-p}),{result:J,total:B.total,schema:j,normedLogicform:S,sqls:[...A],lineage:Q,provider:"duckdb",providers:B.connections,schemaMappingSelections:[..._]}}const W=Dr(S,b,C,f,P,void 0,r,n.translator(r)),T=async(N,B)=>{const G=B&&N.logicform.schema===B.id?B:Y(N.logicform),V=N.prepare?await lt(ft(N.logicform,c.permissions,P,!0,new Set,o),G,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,resolveFromSchema:Re,canProjectProperty:(oe,te)=>pt(c.permissions,oe.id,te),requestTimeWatermark:ze}):N.logicform,J=Le(V,G,f,m,$e),Ee=Dr(V,J,G,f,P,N.logicform,r,n.translator(r));if(Ee){if(Ee.length!==1)throw new Error("A generated component must produce exactly one execution unit");const oe=Ee[0];if("logicform"in oe){const de=await T(oe,G),ht=de.component.mapResult,Fe=N.mapResult;return{...de,component:{...N,logicform:de.component.logicform,...ht||Fe?{mapResult:Ye=>{const nt=ht?.(Ye)??[...Ye];return Fe?.(nt)??[...nt]}}:{}}}}if("mergeRow"in oe)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const te=await Promise.all(oe.components.map(async de=>({name:de.name,prepared:await T(Kr(de)),...de.groupKeyShifts?{groupKeyShifts:de.groupKeyShifts}:{},...de.joinKeys?{joinKeys:de.joinKeys}:{}}))),Ae=Pr(oe,te.map(({name:de,prepared:ht,...Fe})=>({name:de,plan:ht.plan,...Fe})),J,oe.outputName,c.provider,f);return{component:{...N,logicform:V},plan:J,compiled:Ae,sources:ir(te.map(({prepared:de})=>de.sources))}}return{component:{...N,logicform:V},plan:J,compiled:fe(J,c.provider,f),sources:we(J)}},re=async(N,B)=>{const G=Dr(N,B,Y(N),f,P,void 0,r,n.translator(r));if(!G)return{compiled:fe(B,c.provider,f),sources:we(B)};const V=await Promise.all(G.map(async J=>{if("logicform"in J){const te=await T(J);return{plan:te.plan,compiled:te.compiled,outputs:te.plan.projections.map(({name:Ae})=>Ae).filter(Ae=>!B.groupBy.some(de=>de.name===Ae))}}if("mergeRow"in J)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ee=await Promise.all(J.components.map(async te=>{const Ae=await T(Kr(te));return{name:te.name,plan:Ae.plan,...te.joinKeys?{joinKeys:te.joinKeys}:{},...te.groupKeyShifts?{groupKeyShifts:te.groupKeyShifts}:{}}})),oe=Pr(J,Ee,B,J.outputName,c.provider,f);return{plan:B,compiled:oe,outputs:[J.outputName,...J.components.map(te=>te.name)]}}));return{compiled:Wn(V,B,c.provider,f),sources:ir(V.map(({plan:J})=>we(J)))}},H=new WeakMap,M=async N=>{if(!N.sourcePlan||!N.sourceLogicform)return fe(N,c.provider,f);const B=ce(N.sourceLogicform),G=Dr(N.sourceLogicform,N.sourcePlan,B,f,P,void 0,r,n.translator(r));if(G?.some(te=>"mergeRow"in te)){const te=H.get(N.sourcePlan);if(te){const ne={...N};delete ne.sourcePlan,delete ne.sourceLogicform;const Ke=fe({...ne,sourceSql:te.sql,source:N.source},c.provider,f,te.parameters.length);return{sql:Ke.sql,parameters:[...te.parameters,...Ke.parameters]}}const Ae=await Promise.all(G.map(async ne=>{if("logicform"in ne)return{kind:"query",unit:ne,prepared:await T(ne,B)};const Ke=await Promise.all(ne.components.map(async he=>({input:he,prepared:await T(Kr(he),B)})));return"mergeRow"in ne?{kind:"js",unit:ne,components:Ke}:{kind:"component",unit:ne,components:Ke,compiled:Pr(ne,Ke.map(({input:he,prepared:Ue})=>({name:he.name,plan:Ue.plan,...he.joinKeys?{joinKeys:he.joinKeys}:{},...he.groupKeyShifts?{groupKeyShifts:he.groupKeyShifts}:{}})),N.sourcePlan,ne.outputName,c.provider,f)}})),de=N.sourcePlan.groupBy.map(({name:ne})=>ne),ht=await Promise.all(Ae.map(async ne=>{if(ne.kind==="query"){D(ne.prepared.compiled,"computation",ne.prepared.component.logicform);const he=await U(ne.prepared.compiled,ne.prepared.sources),Ue=await ut(he,ne.prepared.plan.projections,f);return ne.unit.mapResult?.(Ue)??Ue}if(ne.kind==="component")return D(ne.compiled,"computation",N.sourceLogicform),U(ne.compiled,ir(ne.components.map(({prepared:he})=>he.sources)));const Ke=await Promise.all(ne.components.map(async({input:he,prepared:Ue})=>{D(Ue.compiled,"computation",Ue.component.logicform);const Ia=await U(Ue.compiled,Ue.sources),Mo=await ut(Ia,Ue.plan.projections,f);return he.mapResult?.(Mo)??Mo}));return Promise.all(eo(Ke,de).map(async he=>({...he,[ne.unit.outputName]:await ne.unit.mergeRow(he)})))})),Fe=to(ht,N.sourcePlan),Ye=c.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(Ye)||Ye<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:Ye});if(Fe.length>Ye)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Fe.length} rows; maximum is ${Ye}`,{materializedRowCount:Fe.length,maxMaterializedRows:Ye});const nt=Kf(Fe,N.sourcePlan,c.provider);H.set(N.sourcePlan,nt);const en={...N};delete en.sourcePlan,delete en.sourceLogicform;const Uo=fe({...en,sourceSql:nt.sql,source:N.source},c.provider,f,nt.parameters.length);return{sql:Uo.sql,parameters:[...nt.parameters,...Uo.parameters]}}const V=await re(N.sourceLogicform,N.sourcePlan),J={...N};delete J.sourcePlan,delete J.sourceLogicform;const Ee={...J,sourceSql:V.compiled.sql,source:N.source},oe=fe(Ee,c.provider,f,V.compiled.parameters.length);return{sql:oe.sql,parameters:[...V.compiled.parameters,...oe.parameters]}},ie=W?await Promise.all(W.map(async N=>{if("logicform"in N)return{kind:"query",unit:N,...await T(N)};const B=await Promise.all(N.components.map(async V=>({name:V.name,prepared:await T(Kr(V)),...V.groupKeyShifts?{groupKeyShifts:V.groupKeyShifts}:{},...V.joinKeys?{joinKeys:V.joinKeys}:{}})));if("mergeRow"in N)return{kind:"js",unit:N,components:B.map(({prepared:V})=>V)};const G=B.map(({name:V,prepared:J,...Ee})=>({name:V,plan:J.plan,...Ee}));return{kind:"component",unit:N,plan:b,compiled:Pr(N,G,b,N.outputName,c.provider,f),sources:ir(B.map(({prepared:V})=>V.sources))}})):void 0,K=ie&&Jf(ie,m,b)?ie.map(N=>{const B=new Set(b.groupBy.map(({name:V})=>V));if(N.kind==="query")return{plan:N.plan,compiled:N.compiled,outputs:N.plan.projections.map(({name:V})=>V).filter(V=>!B.has(V))};const G=N.unit.outputName;if(!G)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:N.plan,compiled:N.compiled,outputs:[G,...N.unit.components.map(V=>V.name)]}}):void 0,ge=K?Wn(K,b,c.provider,f):void 0,_e=ie?void 0:await M(b),Ne=No(b),Oe=b.pagination&&(ge||_e)?Oo(K?Wn(K,Ne,c.provider,f):await M(Ne),c.provider):void 0;if(ge)D(ge,"computation",S);else if(ie)for(const N of ie)if(N.kind==="js")for(const B of N.components)D(B.compiled,"computation",B.component.logicform);else D(N.compiled,"computation",S);else D(_e,"computation",S);Oe&&D(Oe,"total",Pf(S)),await q({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await q({stage:"executing",provider:c.provider.kind});const Be=ge?await(async()=>{const N=ir([...ie.map(J=>J.sources),we(b)]),[B,G]=await Promise.all([U(ge,N),Oe?U(Oe,N):Promise.resolve(void 0)]),V=await ut(B,b.projections,f);return{rows:V,total:G?Wr(G):V.length}})():ie?await(async()=>{const N=await Promise.all(ie.map(async G=>{if(G.kind==="js"){const Ee=await Promise.all(G.components.map(async oe=>{const te=await U(oe.compiled,oe.sources),Ae=await ut(te,oe.plan.projections,f);return oe.component.mapResult?.(Ae)??Ae}));return Promise.all(eo(Ee,b.groupBy.map(({name:oe})=>oe)).map(async oe=>{const te=await G.unit.mergeRow(oe);return{...oe,[G.unit.outputName]:te}}))}const V=await U(G.compiled,G.sources),J=G.kind==="query"?await ut(V,G.plan.projections,f):V;return G.kind==="query"?G.unit.mapResult?.(J)??J:J})),B=to(N,b);return{rows:B,total:b.pagination?to(N,Ne).length:B.length}})():await(async()=>{const N=we(b),[B,G]=await Promise.all([U(_e,N),Oe?U(Oe,N):Promise.resolve(void 0)]),V=await ut(B,b.projections,f);return{rows:V,total:G?Wr(G):V.length}})(),{rows:ye,total:Ve}=Be;await q({stage:"hydrating"});const yt=await Zs(ye,k,{semanticTypes:l,plugins:o,resolveSchema:P,fetchEntities:N=>zs(N,{version:S.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:P,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,...c.connectionId?{preferredConnectionId:c.connectionId}:{},...c.providerForConnection?{providerForConnection:c.providerForConnection}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(B,G,V,J)=>D(B,"semantic-resolution",G,"entity-expansion",V,J)})}),tt=Jn(yt,b.rowIdentity);return await q({stage:"result",result:tt},{result:tt,total:Ve,sqls:[...A]}),await q({stage:"completed",durationMs:tn.performance.now()-p}),{result:tt,total:Ve,schema:j,normedLogicform:S,sqls:[...A],lineage:Q,provider:c.provider.kind,providers:[...L].map(([N,B])=>({connectionId:N,provider:B})),schemaMappingSelections:[..._],...S.output?await(async()=>{const N=Ai(S.output?.type??"",o);return N?{output:await N.handle({rows:tt,logicform:S,schema:j})}:{}})():{}}}catch(C){const w=_a(C);try{await q({stage:"failed",error:w})}catch{}throw w}},tm=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=mr(Ea(e.plugins,e.locales));try{if(e.connections.length===0)throw new d("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const i=new Map;for(const $ of e.connections){if($.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has($.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${$.id}`,{connectionId:$.id});i.set($.id,$)}const s=new jn(e.schemaMappings,e.plugins),u=em(t).flatMap($=>s.list($)).map(({connectionId:$})=>$)[0];if(!u)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const c=$=>{const A=i.get($);if(!A)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${$}`,{connectionId:$});return Gr(A,e.providerRegistry)},p=c(u);r={provider:p.kind};const l=ke(e.plugins),f=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],m=new jt(f),y=new Set(m.definitions().map(({name:$})=>$)),g=f.length===0?l:new jt([...l.definitions().filter(({name:$})=>!y.has($)),...m.definitions()]),h=e.semanticTypes===void 0?so(e.plugins):Ss(e.semanticTypes,e.plugins??[]),{cache:_,...E}=e,I=_?await Hs(_):void 0;return await Sa(t,{...E,schemaMappings:s,locale:n,localeRegistry:o,provider:p,providerForConnection:c,operators:g,operatorsResolved:!0,semanticTypes:h,semanticTypesResolved:!0,connectionId:u,...I?{cache:I}:{},onProgress:async $=>{r=$.partialResult,await e.onProgress?.($)}})}catch(i){return zf(i,t,r,n,o)}},rm=Object.freeze({execute:tm,close:la});exports.DBConnector=If,exports.LocaleRegistry=cn,exports.Logicform=rm,exports.OperatorRegistry=jt,exports.PlannerSemanticRegistry=Vi,exports.ProviderRegistry=ca,exports.QueryCacheManager=gp,exports.SchemaMappingRegistry=jn,exports.SemanticDBError=d,exports.SemanticTypeRegistry=ro,exports.builtinOperators=Ud,exports.builtinSemanticTypes=Un,exports.createLocaleRegistry=mr,exports.createOperatorRegistry=ke,exports.createPlannerSemanticRegistry=Fi,exports.createSemanticTypeRegistry=so,exports.defaultLocaleRegistry=yr,exports.enUS=ni,exports.fromYiAskSchemaMapping=Vd,exports.resolveOperator=ki,exports.resolveSchema=As,exports.validateResolvedSchema=gs,exports.zhCN=oi;