semanticdb-v2 2.0.0-alpha.10 → 2.0.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/executor/execute.d.ts +1 -1
- package/dist/executor/federated-execution.d.ts +2 -1
- package/dist/executor/fetch-entities.d.ts +2 -2
- package/dist/executor/index.d.ts +1 -1
- package/dist/executor/partition.d.ts +17 -0
- package/dist/executor/types.d.ts +14 -10
- package/dist/index.d.ts +4 -2
- package/dist/logicform/dimensions.d.ts +16 -0
- package/dist/logicform/index.d.ts +2 -0
- package/dist/normalizer/core.d.ts +1 -1
- package/dist/operators/types.d.ts +8 -1
- package/dist/planner/build-mapping-source-plan.d.ts +6 -0
- package/dist/planner/create-logical-plan.d.ts +4 -0
- package/dist/planner/select-schema-mapping.d.ts +3 -0
- package/dist/planner/types.d.ts +12 -0
- package/dist/schema-mappings/index.d.ts +1 -0
- package/dist/schema-mappings/registry.d.ts +1 -0
- package/dist/schema-mappings/supported-dimensions.d.ts +10 -0
- package/dist/schema-mappings/types.d.ts +7 -1
- package/dist/schema-mappings/yiask.d.ts +1 -0
- package/dist/semantic-types/index.d.ts +1 -1
- package/dist/semantic-types/types.d.ts +29 -1
- package/dist/semanticdb.esm.js +5 -5
- package/dist/semanticdb.js +5 -5
- package/package.json +1 -1
package/dist/semanticdb.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{performance as mr}from"node:perf_hooks";import ce from"dayjs";import Vt from"dayjs/plugin/isoWeek.js";import yr from"dayjs/plugin/quarterOfYear.js";import Qo from"dayjs/plugin/customParseFormat.js";import{randomUUID as vo,createHash as Ba}from"node:crypto";import{isDeepStrictEqual as Ho}from"node:util";import{createClient as Va}from"redis";import{getNameProperty as Ya}from"semanticdb-core";import{DuckDBInstance as Fa,VARCHAR as gt,DOUBLE as Go,TIMESTAMP as ln,BOOLEAN as zo,jsToDuckDBValue as ze,blobValue as Qa}from"@duckdb/node-api";const V=t=>typeof t=="string",Yt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},Wo=t=>t==null?"":""+t,va=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Ha=/###/g,Ko=t=>t&&t.indexOf("###")>-1?t.replace(Ha,"."):t,Jo=t=>!t||V(t),Ft=(t,e,r)=>{const n=V(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(Jo(t))return{};const i=Ko(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return Jo(t)?{}:{obj:t,k:Ko(n[o])}},Xo=(t,e,r)=>{const{obj:n,k:o}=Ft(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=Ft(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Ft(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},Ga=(t,e,r,n)=>{const{obj:o,k:i}=Ft(t,e,Object);o[i]=o[i]||[],o[i].push(r)},hr=(t,e)=>{const{obj:r,k:n}=Ft(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},za=(t,e,r)=>{const n=hr(t,r);return n!==void 0?n:hr(e,r)},Zo=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?V(t[n])||t[n]instanceof String||V(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Zo(t[n],e[n],r):t[n]=e[n]);return t},it=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Wa={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Ka=t=>V(t)?t.replace(/[&<>"'\/]/g,e=>Wa[e]):t;class Ja{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 Xa=[" ",",","?","!",";"],Za=new Ja(20),ec=(t,e,r)=>{e=e||"",r=r||"";const n=Xa.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=Za.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},fn=(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 c=i;c<n.length;++c)if(c!==i&&(a+=r),a+=n[c],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&c<n.length-1)continue;i+=c-i+1;break}o=s}return o},Qt=t=>t?.replace(/_/g,"-"),tc={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 sn{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||tc,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:(V(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new sn(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new sn(this.logger,e)}}var Ye=new sn;class gr{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 ei extends gr{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):V(n)&&i?a.push(...n.split(i)):a.push(n)));const c=hr(this.data,a);return!c&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),c||!s||!V(n)?c:fn(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),Xo(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)(V(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 c=hr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Zo(c,n,i):c={...c,...n},Xo(this.data,a,c),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 ti={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 ri=Symbol("i18next/PATH_KEY");function rc(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===ri?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function At(t,e){const{[ri]:r}=t(rc()),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 ni={},mn=t=>!V(t)&&typeof t!="boolean"&&typeof t!="number";class an extends gr{constructor(e,r={}){super(),va(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Ye.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=mn(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&&!ec(e,n,o);if(s&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:V(i)?[i]:i};const u=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),e=u.join(o)}return{key:e,namespaces:V(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=At(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(U=>typeof U=="function"?At(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:c}=this.extractFromKey(e[e.length-1],o),u=c[c.length-1];let l=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;l===void 0&&(l=":");const p=o.lng||this.language,m=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p?.toLowerCase()==="cimode")return m?i?{res:`${u}${l}${a}`,usedKey:a,exactUsedKey:a,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:`${u}${l}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:p,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:a;const f=this.resolve(e,o);let y=f?.res;const h=f?.usedKey||a,g=f?.exactUsedKey||a,$=["[object Number]","[object Function]","[object RegExp]"],A=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,_=!this.i18nFormat||this.i18nFormat.handleAsObject,E=o.count!==void 0&&!V(o.count),w=an.hasDefaultValue(o),R=E?this.pluralResolver.getSuffix(p,o.count,o):"",C=o.ordinal&&E?this.pluralResolver.getSuffix(p,o.count,{ordinal:!1}):"",k=E&&!o.ordinal&&o.count===0,T=k&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${C}`]||o.defaultValue;let G=y;_&&!y&&w&&(G=T);const Q=mn(G),q=Object.prototype.toString.apply(G);if(_&&G&&Q&&$.indexOf(q)<0&&!(V(A)&&Array.isArray(G))){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,G,{...o,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(f.res=U,f.usedParams=this.getUsedParamsDetails(o),f):U}if(s){const U=Array.isArray(G),Y=U?[]:{},z=U?g:h;for(const v in G)if(Object.prototype.hasOwnProperty.call(G,v)){const W=`${z}${s}${v}`;w&&!y?Y[v]=this.translate(W,{...o,defaultValue:mn(T)?T[v]:void 0,joinArrays:!1,ns:c}):Y[v]=this.translate(W,{...o,joinArrays:!1,ns:c}),Y[v]===W&&(Y[v]=G[v])}y=Y}}else if(_&&V(A)&&Array.isArray(y))y=y.join(A),y&&(y=this.extendTranslation(y,e,o,n));else{let U=!1,Y=!1;!this.isValidLookup(y)&&w&&(U=!0,y=T),this.isValidLookup(y)||(Y=!0,y=a);const v=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&Y?void 0:y,W=w&&T!==y&&this.options.updateMissing;if(Y||U||W){if(this.logger.log(W?"updateKey":"missingKey",p,u,a,W?T:y),s){const fe=this.resolve(a,{...o,keySeparator:!1});fe&&fe.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 De=[];const Me=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Me&&Me[0])for(let fe=0;fe<Me.length;fe++)De.push(Me[fe]);else this.options.saveMissingTo==="all"?De=this.languageUtils.toResolveHierarchy(o.lng||this.language):De.push(o.lng||this.language);const de=(fe,be,S)=>{const I=w&&S!==y?S:v;this.options.missingKeyHandler?this.options.missingKeyHandler(fe,u,be,I,W,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(fe,u,be,I,W,o),this.emit("missingKey",fe,u,be,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?De.forEach(fe=>{const be=this.pluralResolver.getSuffixes(fe,o);k&&o[`defaultValue${this.options.pluralSeparator}zero`]&&be.indexOf(`${this.options.pluralSeparator}zero`)<0&&be.push(`${this.options.pluralSeparator}zero`),be.forEach(S=>{de([fe],a+S,o[`defaultValue${S}`]||T)})}):de(De,a,T))}y=this.extendTranslation(y,e,o,f,n),Y&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${u}${l}${a}`),(Y||U)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${l}${a}`:a,U?y:void 0,o))}return i?(f.res=y,f.usedParams=this.getUsedParamsDetails(o),f):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 c=V(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const p=e.match(this.interpolator.nestingRegexp);u=p&&p.length}let l=n.replace&&!V(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),e=this.interpolator.interpolate(e,l,n.lng||this.language||o.usedLng,n),c){const p=e.match(this.interpolator.nestingRegexp),m=p&&p.length;u<m&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...p)=>i?.[0]===p[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${r[0]}`),null):this.translate(...p,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=V(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=ti.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 V(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?At(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const u=this.extractFromKey(c,r),l=u.key;o=l;let p=u.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const m=r.count!==void 0&&!V(r.count),f=m&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(V(r.context)||typeof r.context=="number")&&r.context!=="",h=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);p.forEach(g=>{this.isValidLookup(n)||(a=g,!ni[`${h[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(ni[`${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 A=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,l,$,g,r);else{let E;m&&(E=this.pluralResolver.getSuffix($,r.count,r));const w=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(r.ordinal&&E.indexOf(R)===0&&A.push(l+E.replace(R,this.options.pluralSeparator)),A.push(l+E),f&&A.push(l+w)),y){const C=`${l}${this.options.contextSeparator||"_"}${r.context}`;A.push(C),m&&(r.ordinal&&E.indexOf(R)===0&&A.push(C+E.replace(R,this.options.pluralSeparator)),A.push(C+E),f&&A.push(C+w))}}let _;for(;_=A.pop();)this.isValidLookup(n)||(i=_,n=this.getResource($,g,_,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&&!V(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 oi{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ye.create("languageUtils")}getScriptPartFromCode(e){if(e=Qt(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=Qt(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(V(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)),V(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 V(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))):V(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const ii={zero:0,one:1,two:2,few:3,many:4,other:5},si={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class nc{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Ye.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Qt(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!"),si;if(!e.match(/-|_/))return si;const c=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(c,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)=>ii[o]-ii[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 ai=(t,e,r,n=".",o=!0)=>{let i=za(t,e,r);return!i&&o&&V(r)&&(i=fn(t,r,n),i===void 0&&(i=fn(e,r,n))),i},yn=t=>t.replace(/\$/g,"$$$$");class ci{constructor(e={}){this.logger=Ye.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:c,formatSeparator:u,unescapeSuffix:l,unescapePrefix:p,nestingPrefix:m,nestingPrefixEscaped:f,nestingSuffix:y,nestingSuffixEscaped:h,nestingOptionsSeparator:g,maxReplaces:$,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:Ka,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?it(i):s||"{{",this.suffix=a?it(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=l?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":l||"",this.nestingPrefix=m?it(m):f||it("$t("),this.nestingSuffix=y?it(y):h||it(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=$||1e3,this.alwaysFormat=A!==void 0?A:!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 c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=f=>{if(f.indexOf(this.formatSeparator)<0){const $=ai(r,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format($,void 0,n,{...o,...r,interpolationkey:f}):$}const y=f.split(this.formatSeparator),h=y.shift().trim(),g=y.join(this.formatSeparator).trim();return this.format(ai(r,c,h,this.options.keySeparator,this.options.ignoreJSONStructure),g,n,{...o,...r,interpolationkey:h})};this.resetRegExp();const l=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>yn(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?yn(this.escape(f)):yn(f)}].forEach(f=>{for(a=0;i=f.regex.exec(e);){const y=i[1].trim();if(s=u(y),s===void 0)if(typeof l=="function"){const g=l(e,i,o);s=V(g)?g:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(p){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!V(s)&&!this.useRawValueToEscape&&(s=Wo(s));const h=f.safeValue(s);if(e=e.replace(i[0],h),p?(f.regex.lastIndex+=s.length,f.regex.lastIndex-=i[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(c,u)=>{const l=this.nestingOptionsSeparator;if(c.indexOf(l)<0)return c;const p=c.split(new RegExp(`${it(l)}[ ]*{`));let m=`{${p[1]}`;c=p[0],m=this.interpolate(m,s);const f=m.match(/'/g),y=m.match(/"/g);((f?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{s=JSON.parse(m),u&&(s={...u,...s})}catch(h){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,h),`${c}${l}${m}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,c};for(;o=this.nestingRegexp.exec(e);){let c=[];s={...n},s=s.replace&&!V(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const u=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(u!==-1&&(c=o[1].slice(u).split(this.formatSeparator).map(l=>l.trim()).filter(Boolean),o[1]=o[1].slice(0,u)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!V(i))return i;V(i)||(i=Wo(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),c.length&&(i=c.reduce((l,p)=>this.format(l,p,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const oc=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,...c]=s.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),l=a.trim();r[l]||(r[l]=u),u==="false"&&(r[l]=!1),u==="true"&&(r[l]=!0),isNaN(u)||(r[l]=parseInt(u,10))}})}return{formatName:e,formatOptions:r}},ui=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(Qt(n),o),e[s]=a),a(r)}},ic=t=>(e,r,n)=>t(Qt(r),n)(e);class sc{constructor(e={}){this.logger=Ye.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?ui:ic;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()]=ui(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(c=>c.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,c)=>{const{formatName:u,formatOptions:l}=oc(c);if(this.formats[u]){let p=a;try{const m=o?.formatParams?.[o.interpolationkey]||{},f=m.locale||m.lng||o.locale||o.lng||n;p=this.formats[u](a,f,{...l,...o,...m})}catch(m){this.logger.warn(m)}return p}else this.logger.warn(`there was no format function for ${u}`);return a},e)}}const ac=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class cc extends gr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Ye.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={},c={};return e.forEach(u=>{let l=!0;r.forEach(p=>{const m=`${u}|${p}`;!n.reload&&this.store.hasResourceBundle(u,p)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?s[m]===void 0&&(s[m]=!0):(this.state[m]=1,l=!1,s[m]===void 0&&(s[m]=!0),i[m]===void 0&&(i[m]=!0),c[p]===void 0&&(c[p]=!0)))}),l||(a[u]=!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(c)}}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(c=>{Ga(c.loaded,[i],s),ac(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{a[u]||(a[u]={});const l=c.loaded[u];l.length&&l.forEach(p=>{a[u][p]===void 0&&(a[u][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.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=(u,l)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(u&&l&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(u,l)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const u=c(e,r);u&&typeof u.then=="function"?u.then(l=>a(null,l)).catch(a):a(null,u)}catch(u){a(u)}return}return c(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();V(e)&&(e=this.languageUtils.toResolveHierarchy(e)),V(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 c={...s,isUpdate:i},u=this.backend.create.bind(this.backend);if(u.length<6)try{let l;u.length===5?l=u(e,r,n,o,c):l=u(e,r,n,o),l&&typeof l.then=="function"?l.then(p=>a(null,p)).catch(a):a(null,l)}catch(l){a(l)}else u(e,r,n,o,a,c)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const hn=()=>({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]),V(t[1])&&(e.defaultValue=t[1]),V(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}),di=t=>(V(t.ns)&&(t.ns=[t.ns]),V(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),V(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),Ar=()=>{},uc=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},pi="__i18next_supportNoticeShown",dc=()=>!!(typeof globalThis<"u"&&globalThis[pi]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),pc=()=>{typeof globalThis<"u"&&(globalThis[pi]=!0)},lc=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 pr extends gr{constructor(e={},r){if(super(),this.options=di(e),this.services={},this.logger=Ye,this.modules={external:[]},uc(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&&(V(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=hn();this.options={...n,...this.options,...di(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&&!lc(this)&&!dc()&&(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}"),pc());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Ye.init(o(this.modules.logger),this.options):Ye.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=sc;const l=new oi(this.options);this.store=new ei(this.options.resources,this.options);const p=this.services;p.logger=Ye,p.resourceStore=this.store,p.languageUtils=l,p.pluralResolver=new nc(l,{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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(p.formatter=o(u),p.formatter.init&&p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new ci(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new cc(o(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(f,...y)=>{this.emit(f,...y)}),this.modules.languageDetector&&(p.languageDetector=o(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=o(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new an(this.services,this.options),this.translator.on("*",(f,...y)=>{this.emit(f,...y)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Ar),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...l)=>this.store[u](...l)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...l)=>(this.store[u](...l),this)});const a=Yt(),c=()=>{const u=(l,p)=>{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(p),r(l,p)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,r=Ar){let n=r;const o=V(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(u=>{u!=="cimode"&&i.indexOf(u)<0&&i.push(u)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>s(c)),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=Yt();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=Ar),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"&&ti.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=Yt();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,c)=>{c?this.isLanguageChangingTo===e&&(o(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(a,(...u)=>this.t(...u))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=V(a)?a:a&&a[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(V(a)?[a]:a);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,l=>{i(l,u)})};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 c;typeof s!="object"?c=this.options.overloadTranslationOptionHandler([i,s].concat(a)):c={...s},c.lng=c.lng||o.lng,c.lngs=c.lngs||o.lngs,c.ns=c.ns||o.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||o.keyPrefix);const u={...this.options,...c};typeof c.keyPrefix=="function"&&(c.keyPrefix=At(c.keyPrefix,u));const l=this.options.keySeparator||".";let p;return c.keyPrefix&&Array.isArray(i)?p=i.map(m=>(typeof m=="function"&&(m=At(m,u)),`${c.keyPrefix}${l}${m}`)):(typeof i=="function"&&(i=At(i,u)),p=c.keyPrefix?`${c.keyPrefix}${l}${i}`:i),this.t(p,c)};return V(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,c)=>{const u=this.services.backendConnector.state[`${a}|${c}`];return u===-1||u===0||u===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=Yt();return this.options.ns?(V(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=Yt();V(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 oi(hn());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 pr(e,r);return n.createInstance=pr.createInstance,n}cloneInstance(e={},r=Ar){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new pr(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((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((l,p)=>(l[p]={...c[u][p]},l),c[u]),c),{});i.store=new ei(a,o),i.services.resourceStore=i.store}if(e.interpolation){const c={...hn().interpolation,...this.options.interpolation,...e.interpolation},u={...o,interpolation:c};i.services.interpolator=new ci(u)}return i.translator=new an(i.services,o),i.translator.on("*",(a,...c)=>{i.emit(a,...c)}),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 Pe=pr.createInstance(),fc=Pe.createInstance;Pe.dir,Pe.init,Pe.loadResources,Pe.reloadResources,Pe.use,Pe.changeLanguage,Pe.getFixedT,Pe.t,Pe.exists,Pe.setDefaultNamespace,Pe.hasLoadedNamespace,Pe.loadNamespaces,Pe.loadLanguages;const li={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"}},fi={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"}},mc=[fi,li],vt=t=>t.trim().toLowerCase(),yc=t=>t?"locale"in t?[t]:t:[],hc=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 gn{definitions=new Map;i18n;constructor(e){this.i18n=fc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(mc),this.register(e)}register(e){for(const r of yc(e)){const n=r;if(!hc(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 wr=t=>new gn(t),$r=new gn;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=$r){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}}ce.extend(Vt),ce.extend(yr);const gc=new Set(["year","quarter","month","week"]),An=t=>t.format("YYYY-MM-DD HH:mm:ss"),wn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?wn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&wn(r,e)),Er=(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:Er(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:Er(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>Er(o,e,r))}:{}}},Ac=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 Er(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},wc=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!wn(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})},$c=(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(([,E])=>{if(typeof E!="object"||E===null||Array.isArray(E))return!1;const w=E;return typeof w.$gte=="string"&&typeof w.$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=ce(String(s.$gte)),c=ce(String(s.$lte));if(!a.isValid()||!c.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const u=e.map(E=>{if(!E.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return E.name}),l=r==="week"?a.startOf("isoWeek"):a.startOf(r),p={...t.query,[o]:{...s,$gte:An(l)}},m=new Set([...(t.groupby??[]).map(({name:E})=>E),...(t.preds??[]).map(({name:E})=>E)]),f=E=>{let w=E;for(;m.has(w);)w=`_${w}`;return m.add(w),w},y=f("__accumulate_period"),h=e.map((E,w)=>f(`__accumulate_metric_${w}`)),g=(t.groupby??[]).map(({name:E})=>String(E)),$=r==="year"||r==="quarter"?"month":"day",A={version:t.version,...t.schema?{schema:t.schema}:{},query:p,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:$},name:y}],preds:e.map((E,w)=>({...E.pred,name:h[w]??`__accumulate_metric_${w}`}))},_={version:t.version,from:A,preds:[...g.map(E=>({pred:E,name:E})),{pred:y,name:y},...e.map((E,w)=>({operator:"$accumulate",pred:h[w]??`__accumulate_metric_${w}`,args:{partitionBy:g,orderBy:[{pred:y,direction:"asc"}]},name:u[w]??`accumulate_${w}`}))]};return{version:t.version,from:_,query:{[y]:{$gte:An(a),$lte:An(c)}},preds:[...g.map(E=>({pred:E,name:E})),...u.map(E=>({pred:E,name:E}))],...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}:{}}},Ec={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"||!gc.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:Ac,validatePlan:wc,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 $c(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},_c={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}}},wt=(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},_r=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),Sc={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`(${wt("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:_r(t)}},oe=t=>structuredClone(t),Ic=(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},bc=(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},Rc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},mi=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Nc=(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)),ue=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:mi(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Nc(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=ue(s,e.slice(i.length+1),r);return{canonicalName:`${mi(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})},$n=(t,e)=>t.name===e||t.id===e,Oc=(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=>$n(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&$n(i,a.hierarchy.down))];if(s.some(a=>$n(e,a.name)))return!0;o.push(...s)}return!1},yi=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ue(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=ue(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Oc(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})},Tc=({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:c})=>c==="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}}},Pc=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},Lc=(t,e,r)=>{const n=ue(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}},Cc={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=Lc(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!==ue(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const c=s.levels.reduce((y,h)=>y+h.codeLength,0),u=i.schema.properties.filter(({type:y})=>y==="ID"),p=i.relation&&u.length===1&&u[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:p,args:{levels:s.levels.map(({name:h,codeLength:g})=>(y+=g,{name:h,codeLength:y})),totalLength:c,storage:s.storage}}}let m=0;const f=s.levels.find(y=>(m+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!f)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:p,args:{level:f.name,codeLength:m,totalLength:c,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 c=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),u=e.totalLength,l=e.storage;if(c.length!==e.levels.length||c.length===0||!Number.isInteger(u)||Number(u)<=0||c.some(({name:y,codeLength:h},g)=>y.length===0||h<=0||h>Number(u)||g>0&&h<=Number(c[g-1]?.codeLength))||c.at(-1)?.codeLength!==u||l!=="compact"&&l!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const p=`WHEN ${t} IS NULL THEN NULL`;if(l==="compact"){const y=r.stringLength(t),h=c.map(g=>`WHEN ${y} = ${g.codeLength} THEN ${r.value(g.name)}`);return`(CASE ${p} ${h.join(" ")} ELSE NULL END)`}const m=c.slice(0,-1).map(y=>{const h=Number(u)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,h)} = ${r.value("0".repeat(h))} THEN ${r.value(y.name)}`}),f=c.at(-1);return`(CASE ${p} ${m.join(" ")} ELSE ${r.value(f?.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}}},$t=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},Et=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),En=(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)}},Sr=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>Et(e,o)?.id===t.id)),hi=(t,e,r)=>{const n=Et(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=En(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Sr(n,r);if(!$t(i?.granularity))return;const s=En(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},Dc=(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 c=hi(i.pred,i.args.level,e);if(c)return c}else{const c=Et(e.schema,i.pred),u=c&&Sr(c,e);if($t(u?.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 c of a){if(typeof c=="string")continue;const u=r(c);if(u)return u}},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 c of a){const u=n(c);if(u)return u}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const c=a.pred;if(typeof c!="object"||c===null||Array.isArray(c))continue;const u=r(c);if(u)return u}else if(!s.startsWith("$")){const c=Et(e.schema,s),u=c&&Sr(c,e);if($t(u?.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=hi(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=Et(e.schema,i.pred),a=s&&Sr(s,e);if($t(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},kc={kind:"hierarchy",isGranularity:$t,validateItem(t,e){const r=t.granularity;if($t(r))return t.propertyTarget?.every(n=>{const o=Et(e.schema,n);return o!==void 0&&En(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:Dc,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Uc={keys:["hierarchy"],resolve(t,e){for(const m of e)if(m.level!==void 0){if(typeof m.level!="string"||m.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${m.name} level must be a non-empty string`,{property:m.name,level:m.level});if(m.primal_type!=="entity"&&m.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${m.name} level requires an entity relation`,{property:m.name,type:m.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(m=>m!=="property"&&m!=="storage"&&m!=="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 m=e.filter(f=>f.type==="ID");if(m.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:m.length});return m[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(m=>m.name===n.property||m.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 c=new Set,u=new Set,l=n.levels.map((m,f)=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} must be an object`);const y=m,h=Object.keys(y).filter($=>$!=="name"&&$!=="syno"&&$!=="codeLength");if(h.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${f} 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 ${f} name must not be empty`);if(c.has(y.name)||u.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||c.has($)||u.has($))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${$}`);u.add($)}return c.add(y.name),{name:y.name,...g.length>0?{syno:[...g]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:l}}}},Mc=Object.freeze({name:"hierarchy",schemaMetadata:Uc,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:Tc,resolveEntityFilterProperty:Pc,operators:[Cc],mappingGranularity:kc}),qc=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),_n="$periodValue",jc=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:_n,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${_n}; ${e.name} describes a time range`,{operator:e.name});return{operator:_n,boundary:"end",implicit:!0}},xc={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!qc(r,e))return;const s=jc(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},Bc=new Set(["second","minute","hour","day","week","month","quarter","year"]),gi=t=>typeof t=="string"&&Bc.has(t),Vc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ir=(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},st=(t,e=2)=>String(t).padStart(e,"0"),Sn=t=>`${st(t.getFullYear(),4)}-${st(t.getMonth()+1)}-${st(t.getDate())} ${st(t.getHours())}:${st(t.getMinutes())}:${st(t.getSeconds())}.`+st(t.getMilliseconds(),3),Yc=(t,e)=>{if(!Vc(t)){const a=Ir(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=Ir(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=Ir(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=Ir(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}},Fc=(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},Qc=(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},Ai=(t,e,r)=>{const{lower:n,upper:o}=Yc(t,r),i=[];let s=Fc(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=Qc(s,e),c=new Date(Math.min(a.getTime()-1,o));i.push({label:Sn(s),start:Sn(s),end:Sn(c)}),s=a}return i},vc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Hc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Gc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:p})=>p==="timestamp");if(!r)return;const n=vc(t,r),o=t.preds??[],i=o.filter(({operator:p})=>p==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!gi(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(p=>{const m=p.args?.boundary;if(m!=="start"&&m!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:m});if(!p.pred||typeof p.pred!="object"||Array.isArray(p.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:p,effectivePred:{...p.pred,...p.name?{name:p.name}:{}}}});if(new Set(i.map(({args:p})=>p?.boundary)).size!==1)throw new d("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const u=i[0]?.args?.boundary,l=t.query?.[r.name];if(l===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:u,metrics:a,periods:Ai(l,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(p=>({label:p.label,asOf:p[u]}))}},wi=["second","minute","hour","day","week","month","quarter","year"],zc=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:[xc],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(wi.indexOf(o)>wi.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=Gc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Hc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Ht=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Wc={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:m})=>m==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Ht(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 c=Array.isArray(r.roots),u=c?r.roots:r.root===void 0?[]:[r.root];if(!c&&u.length===0||u.some(m=>m===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const l=await Promise.all(u.map(m=>e.normalizeValue(m,o,a))),p=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof p!="string"||p.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:l,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:p}},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:u})=>u==="ID"):Ht(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",c=Ht(o,a);s&&e.assertPropertyAllowed(o,s),c&&e.assertPropertyAllowed(o,c)},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=Ht(o,r.idProperty),s=Ht(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__"),c=r.quoteIdentifier("__recursive_id__"),u=r.quoteIdentifier("__recursive_node__"),l=r.quoteIdentifier("__recursive_child__"),p=r.quoteIdentifier(i.idColumn),m=r.quoteIdentifier(i.parentColumn),f=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(E=>n(E)).join(", "),h=(E,w=!1)=>s.length===1?`${E} ${w?"<>":"="} ${y()}`:`${E} ${w?"NOT IN":"IN"} (${y()})`,g=`${u}.${p}`,$=i.includeSelf?h(g):`${h(`${u}.${m}`)} AND ${h(g,!0)}`,A=r.recursiveCteUnion??"UNION",_=`(WITH RECURSIVE ${a}(${c}) AS ( SELECT ${g} FROM ${r.tableAlias(f,"__recursive_node__")} WHERE ${$} ${A} SELECT ${l}.${p} FROM ${r.tableAlias(f,"__recursive_child__")} JOIN ${a} ON ${l}.${m} = ${a}.${c}) SELECT DISTINCT ${c} FROM ${a})`;return`${e} IN ${_}`}},Kc=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:[Wc]});ce.extend(Vt);const In=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...In(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:In(r))]:e},$i=(t,e)=>ce(t).endOf(e==="week"?"isoWeek":e).toDate(),bn=t=>ce(t).format("YYYY-MM-DD HH:mm:ss"),Jc=(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})},Ei=(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})},Xc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return Ei(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(Ei(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 c=[...new Set((t.preds??[]).flatMap(In).filter(p=>p!==e.id))],u=[{schema:e,property:r}];for(const p of c){const m=s(p),f=t.propertyResolve?.[p],y=f?.[r.id]??f?.[r.name]??a(e,r.name,m);if(!y)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${p}.${r.name}`,{schemaId:p,property:r.name});const h=m.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: ${p}.${y}`,{schemaId:p,property:y});u.push({schema:m,property:h})}const l=u.map(({schema:p,property:m})=>{const f=Jc(m.timeWatermark??p.timeWatermark??i,`${p.id}.${m.id}`);if(f.type==="now_offset"){const y=$i(ce(o).add(f.offset,"day").toDate(),m.granularity??"day");return{operator:"$constant",args:{value:bn(y),type:"timestamp"},name:`${p.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:m.name,schema:p.id},name:`${p.name}\u6700\u65B0\u65F6\u95F4`}});return l.some(({operator:p})=>p==="$periodBoundary")&&l.push({operator:"$constant",args:{value:bn($i(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),l.push({operator:"$constant",args:{value:bn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:l}]}}}),br=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Gt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=br(t.properties,"ID"),r=br(t.properties,"timestamp"),n=br(t.properties,"start_date"),o=br(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},_i=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Zc=(t,e)=>_i(t,e)!==void 0,eu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),tu=(t,e)=>{const r=_i(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!gi(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:Ai(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},ru=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),nu=t=>ru(t)?t.$lte??t.$lt??t.$eq:t,Si=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,c])=>[a,(a==="$and"||a==="$or")&&Array.isArray(c)?c.map(u=>Si(u,e)):c])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=nu(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}]}}},Ii=(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&&Ii(o,e)))),ou={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Gt(e);if(!n)return r;if(Zc(t,n))return eu(r,n);const i=Ii(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Si(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Gt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},iu={name:"start_date",primalType:"date"},su={name:"end_date",primalType:"date"},au=Object.freeze({name:"validity",semanticTypes:[iu,su],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:[ou],intervalSemantics:{resolve:Gt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Gt(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=Gt(e);if(!r)return;const n=tu(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),bi=(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},cu=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,c=Object.keys(a).filter(p=>p!=="up"&&p!=="down");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:c});const u=bi(t,o,a.up,"up"),l=bi(t,o,a.down,"down");return{...o,hierarchy:{...u?{up:u}:{},...l?{down:l}:{}}}}),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}}}),Ri=Object.freeze([Mc,Kc,Xc,zc,au,cu]),ge=(t=[])=>{const e=[...Ri,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,c=new Set,u=new Set,l=new Set;for(const p of e){if(!p.name)throw new d("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(p.name))throw new d("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${p.name}`,{plugin:p.name});r.add(p.name);for(const f of[...p.schemaMetadata?.keys??[],...p.legacySchemaKeys??[]]){if(!f)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(f))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${f}`,{key:f,plugin:p.name});n.add(f)}for(const f of p.propertyMetadata?.keys??[]){if(!f)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(f))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${f}`,{key:f,plugin:p.name});o.add(f)}for(const f of p.operators??[]){if(i.has(f.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${f.name}`,{operator:f.name,plugin:p.name});i.add(f.name)}for(const f of p.semanticTypes??[]){if(s.has(f.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${f.name}`,{semanticType:f.name,plugin:p.name});s.add(f.name)}for(const f of p.plannerSemantics??[]){if(!f.name||a.has(f.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${f.name}`,{rule:f.name,plugin:p.name});a.add(f.name)}for(const f of p.queryOperators??[]){if(!f.name||c.has(f.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${f.name}`,{operator:f.name,plugin:p.name});c.add(f.name)}for(const f of p.outputHandlers??[]){if(!f.type||u.has(f.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${f.type}`,{type:f.type,plugin:p.name});u.add(f.type)}const m=p.mappingGranularity;if(m){if(!m.kind||l.has(m.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${m.kind}`);l.add(m.kind)}}return Object.freeze(e)},_t=(t,e=[])=>ge(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Rn=(t,e=[])=>ge(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),Nn=(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},Ni=(t,e=[])=>Nn("interval semantics",ge(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),uu=(t,e,r=[])=>Nn("relation semantics",ge(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),du=(t,e,r=[])=>Nn("planner period semantics",ge(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),On=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),pu=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]},Tn=(t,e=[])=>{for(const r of ge(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return pu(t)},Pn=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},Ln=t=>typeof t.pred=="string"?t.pred:void 0,lu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},mu={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Cn=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!lu(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}${fu[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${mu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};ce.extend(Vt),ce.extend(yr);const yu=["second","minute","hour","day","week","month","quarter","year"],hu=new Set(yu),Dn=["year","quarter","month","week","day","hour","minute","second"],Oi=t=>Object.prototype.toString.call(t)==="[object Object]",tt=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},gu=t=>{const e=t.time;Oi(e)||tt("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!hu.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&tt("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,c])=>!Dn.includes(a)||!Number.isInteger(c)))&&tt("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&tt("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,[c,u]]of Object.entries(i)){const l=r[a];l!==void 0&&(Number(l)<c||Number(l)>u)&&tt(`Invalid absolute period shift ${a}: ${JSON.stringify(l)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&tt("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&tt("Absolute period shift day requires month"),r},Ti=(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),Au=(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 Dn){const o=e[n];typeof o=="number"&&(r=Ti(r,n,o))}return r},kn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),wu=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=Ln(i);return s?ue(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",c="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:Pn(i),granularity:a,offset:c}}),Un=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>Un(i,e,r));if(Oi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,Un(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=ce(t);if(!n.isValid())return t;const o=Au(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,kn(t,o)},$u=(t,e,r,n,o)=>{const i=new Set,s=c=>Object.fromEntries(Object.entries(c).map(([u,l])=>{if((u==="$and"||u==="$or")&&Array.isArray(l))return[u,l.map(m=>s(m))];const p=ue(e,u,r);return p.property.primal_type!=="date"?[u,l]:(i.add(p.canonicalName),[u,Un(l,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},at=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},rt=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?rt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:rt(r)):[]],Eu=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=ce(t);if(!n.isValid())return t;if("granularity"in e)return kn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of Dn)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=Ti(o,i,s)}return kn(t,o)},Mn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&tt("$periodShift pred must be a nested metric");const s=gu(e.args??{}),a={shiftedValues:0},c=at([t.query,...rt(e)]);if(!c)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=$u(c,n,o,s,a),l=oe(i);l.name=r,delete l.query;const p=oe(t);p.query=u,p.preds=[l],delete p.having,delete p.sort,delete p.limit,delete p.page;const m=new Set((t.groupby??[]).filter(f=>{const y=Ln(f);return y?ue(n,y,o).property.primal_type==="date":!1}).map(Pn));return{kind:"query",logicform:p,groupKeyShifts:wu(t,n,o,s,a),mapResult:f=>f.map(y=>{const h={...y};for(const g of m)h[g]=Eu(h[g],s,a);return h})}},_u={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:Mn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},Su=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Rr=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,Pi=(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},Li=(t,e)=>{if(Rr(t)){e.start??=t,e.end??=t;return}if(!Su(t))return;const r=t.$eq;Rr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Rr(n)&&(e.start??=n),Rr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Li(a,e)}},Iu=(t,e,r,n)=>{const o=Pi(e,n),i=new Set,s={},a=(p,m)=>{for(const[f,y]of Object.entries(p)){if((f==="$and"||f==="$or")&&Array.isArray(y)){for(const g of y)a(g,m||f==="$or");continue}if(f.startsWith("$"))continue;const h=ue(e,f,r);if(h.property.type==="timestamp"){if(m)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(h.canonicalName),Li(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 c=[...i][0];if(!c||c!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const u=p=>{const m=[];for(const[f,y]of Object.entries(p)){if((f==="$and"||f==="$or")&&Array.isArray(y)){const h=y.map(g=>u(g)).filter(g=>g!==void 0);h.length>0&&m.push([f,h]);continue}!f.startsWith("$")&&ue(e,f,r).property.type==="timestamp"||m.push([f,y])}return m.length>0?Object.fromEntries(m):void 0},l=u(t);return{property:o,propertyName:c,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...l?{queryWithoutTime:l}:{}}},Ci=(t,e,r,n,o)=>{const i=at([t,...rt(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return Iu(i,r,n,o)},Di=(t,e,r)=>at([t,{[e]:r}]),bu=new Set(["day","week","month","quarter","year"]),Ru={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Nu=t=>{if(typeof t!="string"||!bu.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},ki=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},qn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=qn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:qn(r))),e},Ou={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Ru[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=Nu(e.args?.granularity),s=Pi(r,"$averagePerPeriod"),a=qn(e.pred),c=at([t.query,...rt(e)]),u=ki(t);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const l=ki(t);l.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],c&&(l.query=c);const p=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),m=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:p,logicform:u},{name:m,logicform:l}],expression:`${p} / NULLIF(${m}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},Tu={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}}},St=t=>{throw new d("INVALID_CASE_ARGS",t)},Pu=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&St("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&St("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&St("$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)&&St("$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]))&&St(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&St("$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}},Lu=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},Nr=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},jn=t=>String(Nr(t)),Cu=(t,e,r)=>{if(t===e)return[t,e];const n=Lu((e-t)/r),o=Nr(Math.floor(t/n)*n),i=Nr(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,c)=>c===s?i:Nr(o+n*c))},Du=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}})},ku={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=Pu(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,c=n.maximum;if(a===c)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(jn(a))} END`;const u=Cu(a,c,n.targetBuckets),l=u.slice(0,-1).map((m,f)=>{const y=u[f+1],h=f===u.length-2?"]":")";return`[${jn(m)}, ${jn(y)}${h}`}),p=l.slice(0,-1).map((m,f)=>`WHEN ${t} < ${r.value(u[f+1])} THEN ${r.value(m)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${p.join(" ")} ELSE ${r.value(l.at(-1))} END`}const o=Du(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}}},Uu={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(wt("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Mu={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}}},qu={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}}},ju=new Set(["second","minute","hour","day","week","month","quarter","year"]),xu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ui=t=>{if(typeof t!="string"||!ju.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},Bu={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${xu[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,Ui(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=Ui(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Vu={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]=wt("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return _r(t)}},Yu=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}}}},Fu={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Yu,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}:{}}}},Qu=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}}}},vu={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Qu,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}:{}}}},Hu={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`(${wt("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return _r(t)}},Gu=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},xn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=xn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:xn(r))),e},zu={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(p=>{const m=Ln(p);return m?ue(r,m,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Ci(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=xn(e.pred),c=(p,m)=>{const f=Gu(t);return f.query=Di(s.queryWithoutTime,s.propertyName,{$lte:p}),f.preds=[{...a,name:m}],f},u=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),l=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:u,logicform:c(s.end,"__newly_end__")},{name:l,logicform:c(s.start,"__newly_start__")}],expression:`${u} - COALESCE(${l}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Wu=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Bn=t=>{const e=oe(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},Ku={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=Ci(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 c={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},u=Wu(t);return u.query=Di(s.queryWithoutTime,s.propertyName,c),u.preds=[{...Bn(e.pred),name:r}],{kind:"query",logicform:u}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Ju=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Xu=({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=oe(e.pred);a.name="__period_diff_current__";const c=Ju(t);c.preds=[a];const u=at([t.query,...rt(e)]);u&&(c.query=u);const l={pred:oe(e.pred),...e.args?{args:e.args}:{}},p=Mn({logicform:t,pred:l,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in p))throw new Error("$periodDifference period shift must produce a query component");const m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:p.logicform,...p.groupKeyShifts?{groupKeyShifts:p.groupKeyShifts}:{}}],expression:`${m} - ${f}`}},Zu={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:Xu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},ed=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},td=({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=oe(e.pred);a.name="__period_growth_current__";const c=ed(t);c.preds=[a];const u=at([t.query,...rt(e)]);u&&(c.query=u);const l={pred:oe(e.pred),...e.args?{args:e.args}:{}},p=Mn({logicform:t,pred:l,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in p))throw new Error("$periodGrowth period shift must produce a query component");const m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:p.logicform,...p.groupKeyShifts?{groupKeyShifts:p.groupKeyShifts}:{}}],expression:`${m} / NULLIF(ABS(${f}), 0) - 1`}},rd={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:td,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},nd={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}}},od={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]=wt("$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}:_r(t)}},Mi=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Vn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Vn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Vn(r))),e},id={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||Pn(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),c=Vn(e.pred),u=Mi(t);u.preds=[{...c,name:"__share_numerator__"}];const l=at([t.query,...rt(e)]);l&&(u.query=l);const p=Mi(t);p.groupby=a,p.preds=[{...c,name:"__share_denominator__"}];const m=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),f=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:m,logicform:u},{name:f,logicform:p}],expression:`${m} / NULLIF(${f}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},sd={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}}},qi=(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 c=t[a];if(!c)continue;if(s){o+=c,c===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(c==="'"||c==='"'||c==="`"){s=c,o+=c;continue}const u=t.slice(a,a+2);if(c===";"||u==="--"||u==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(c==="?"){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+=c}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},ad=new Set(["boolean","date","number","entity","object","string"]),cd=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},ud=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!ad.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}:{}}},dd={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 qi(t.sql,cd(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 ud(t,e)}},pd=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]},ld=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},fd=(t,e,r)=>{const n=t.preds;if(n.filter(l=>l.operator==="$rank"&&l.query).length!==1)throw new d("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=pd(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=oe(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(l=>{if(l.name!==e.name)return l;const p={...l};return delete p.query,ld(p)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const c=n.map(({name:l})=>l).filter(l=>!!l),u=oe(t);return u.from=a,u.query=r,u.preds=[{pred:s,name:s},...c.map(l=>({pred:l,name:l}))],delete u.groupby,delete u.having,delete u.entity_id,delete u.propertyResolve,u},md={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?fd(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}}},yd={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}}},hd=new Set(["string","number","boolean","date","entity","object"]),Yn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&hd.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")},gd={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 Yn(t.args?.type),t},toSQL({args:t,sql:e}){return Yn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...Yn(e.type),isArray:!1}}},Ad={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}}},ji="__scalarExtremumInputs",Fn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Fn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Fn(r)??[]))];if(e.length===1)return e[0]}},wd=t=>{const e=oe(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},$d=(t,e)=>{if(e.args?.[ji]===!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}:oe(o),a=s.name??`__scalar_extremum_input_${i}__`,c=s.schema??Fn(s);return{...s,name:a,...c?{schema:c}:{}}}),n=wd(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,[ji]:!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}:{}}},Ed=(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)`},_d=(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}},xi=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?$d(e,r):void 0},toSQL(e){const r=wt(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??Ed(t,r)},getOutputProperty({name:e,inputProperties:r}){return _d(t,e,r)}}),Sd=xi("$least"),Id=xi("$greatest"),Qn={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"}},bd={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}}},Rd=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${Qn[t].en}`:`${e}${Qn[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}}}),Nd=Object.freeze(Object.keys(Qn).map(Rd)),Bi=Object.freeze([Ec,nd,Mu,qu,Tu,vu,Fu,_u,rd,Zu,Ou,Ku,zu,Sc,od,Hu,Vu,_c,id,ku,Uu,sd,Bu,dd,md,yd,gd,Ad,Sd,Id,bd,...Nd]),Od={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},Td={name:"category",primalType:"string"},Pd={name:"currency",primalType:"number"},Ld={name:"date",primalType:"date"},Cd={name:"duration",primalType:"number"},Vi=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),Dd={name:"object",primalType:"object",hydrateResult:Vi},kd={name:"entity",primalType:"entity",hydrateResult:Vi},Ud={name:"file",primalType:"string"},Md={name:"humanName",primalType:"string"},qd={name:"ID",primalType:"string"},jd={name:"image",primalType:"string"},xd={name:"int",primalType:"number"},Bd={name:"name",primalType:"string"},Vd={name:"number",primalType:"number"},Yd={name:"order",primalType:"number"},Fd={name:"percentage",primalType:"number"},Qd={name:"string",primalType:"string"},vd={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},Hd={name:"timestamp",primalType:"date"},vn=Object.freeze([qd,Qd,Bd,Md,Td,vd,jd,Ud,Vd,xd,Pd,Fd,Cd,Yd,Od,Hd,Ld,kd,Dd]),Gd=(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},Yi=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 c=Gd(e[a],a,n);c&&(s[a]=c)}if(!s.getOutputProperty&&typeof o=="string"){const a=vn.find(({name:c})=>c===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 xt{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new xt(this.definitions(),e)}register(e){const r=Yi(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 zd=Object.freeze([...Bi,...Ri.flatMap(({operators:t})=>t??[])]),Be=(t=[])=>new xt([...Bi,...ge(t).flatMap(({operators:e})=>e??[])]),It=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Fi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Wd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Qi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Kd=(t,e)=>{const r=bc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},vi=(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}:Kd(e,r)},zt=(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 c=[t.input,...t.partitionBy].map(u=>zt(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const c=[t.input,...t.partitionBy,...t.orderBy.map(({expression:u})=>u)].map(u=>zt(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const c=zt(t.input,e,r,n);return{sources:c.sources,transformations:[...c.transformations.filter(u=>u!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(c=>zt(c,e,r,n)),i={sources:o.flatMap(({sources:c})=>c),transformations:o.flatMap(({transformations:c})=>c)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Or(t.query)]);return{sources:[...i.sources,...[...a].filter(c=>!i.sources.some(u=>u.propertyName===c)).map(c=>vi(e,r,c))],transformations:[...i.transformations.filter(c=>c!=="projection"),`operator:${t.operator}`]}};function Or(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(...Or(o));else r==="$expr"&&Qi(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const We=t=>t.kind==="window"?[...We(t.input),...t.partitionBy.flatMap(We)]:t.kind==="cumulative"?[...We(t.input),...t.partitionBy.flatMap(We),...t.orderBy.flatMap(({expression:e})=>We(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?We(t.input):t.kind==="operator"?[...Or(t.query),...t.input?We(t.input):[],...(t.inputs??[]).flatMap(We)]:[],Hi=(t,e,r,n=Be(),o)=>{if(t.subplans){const s=t.subplans.map(c=>Hi(c,e,r,n,o)),a=new Map;for(const c of s){c.source.connectionId&&a.set(c.source.connectionId,c.source.provider);for(const u of c.source.connections??[])a.set(u.connectionId,u.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:c})=>c.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([c,u])=>({connectionId:c,provider:u}))},outputs:t.projections.map(({name:c})=>{const u=s.flatMap(({outputs:l})=>l.filter(p=>p.name===c));return{name:c,sources:u.flatMap(({sources:l})=>l),transformations:[...new Set([...u.flatMap(({transformations:l})=>l),"compose"])]}}),filters:s.flatMap(({filters:c})=>c)}}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,...zt(s.expression,t,e,n)})),filters:[...new Set([...Or(t.query),...t.projections.flatMap(({expression:s})=>We(s))])].map(s=>vi(t,e,s))}},Le=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}))?$/,Gi=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}},zi=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(!Gi(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"]),Hn=t=>typeof t=="string"&&Xd.has(t),Gn=(t,e=ge())=>Hn(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 Tr{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=ge(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:c})=>!a||!c))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");zi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!Gn(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")}zi(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}definitions(){return[...this.#e.values()].flat()}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Zd=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`)},ep=(t,e=[])=>{const r=ge(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"||!Gn(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:Zd(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Wi{#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 Ki=(t=[])=>new Wi([...ge(t).flatMap(e=>e.plannerSemantics??[])]);ce.extend(Qo),ce.extend(Vt),ce.extend(yr);const bt=["second","minute","hour","day","week","month","quarter","year"],tp=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),rp="YYYY-MM-DD HH:mm:ss",Rt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),np=(t,e)=>t==="week"?e==="week":e==="week"?bt.indexOf(t)<=bt.indexOf("day"):bt.indexOf(t)<=bt.indexOf(e),Ji=(t,e,r)=>{if(typeof t!="string")return"second";const n=ce(t,rp,!0);if(!n.isValid())return"second";for(const o of[...bt].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"},Xi=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])=>tp.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(Xi):["second"]:r==="$gte"||r==="$gt"?[Ji(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[Ji(n,"upper",r==="$lte")]:["second"])},op=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&bt.includes(n))return n}return e.granularity??"day"}},ip=(t,e,r,n,o=ge(),i=Be(o))=>{const s=r.mappings??[],a=s.filter(g=>g.granularity!==void 0),c={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(g=>!Gn(g.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(g=>Hn(g.granularity)&&!g.propertyTarget?.every($=>Rt(e,$)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const g of a)for(const $ of o){const A=$.mappingGranularity;if(!A||!A.isGranularity(g.granularity))continue;const _=A.validateItem?.(g,c);if(_)return _}if(!(a.length>0))return;const p=g=>s.find($=>$.mappingType==="property"&&$.propertyTarget?.some(A=>Rt(e,A)?.id===g.id)),m=(g,$,A="filterOrGroup")=>{const _=Rt(e,g);if(!_)return`property is not available: ${g}`;const E=p(_);if(!E&&!(A==="operand"&&s.some(w=>w.mappingType==="predItem"&&typeof w.predItem?.pred=="string"&&Rt(e,w.predItem.pred)?.id===_.id)))return`property is not available on grouped source: ${g}`;if(A==="filterOrGroup"&&_.primal_type==="number"&&_.type!=="category"&&_.type!=="ID")return`measure cannot be used as a grouped source dimension: ${g}`;if(_.primal_type==="date"&&(!E?.granularity||!Hn(E.granularity)||!np(E.granularity,$??_.granularity??"day")))return`time dimension ${g} is too coarse for ${$}`};function f(g){if(g)for(const[$,A]of Object.entries(g)){if(A===void 0)continue;if($==="$and"||$==="$or"){if(!Array.isArray(A))return"unsupported dimension query";for(const w of A){const R=f(w);if(R)return R}continue}if($==="$expr"){if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const w=A.pred;if(typeof w!="object"||w===null||Array.isArray(w))return"unsupported expression query";const R=y(w);if(R)return R;continue}if($.startsWith("$"))return"unsupported dimension query";const _=Rt(e,$);if(!_)return`dimension property is not available: ${$}`;const E=_.primal_type==="date"?Xi(A):[void 0];for(const w of E){const R=m($,w);if(R)return R}}}function y(g){const $=f(g.query);if($)return $;const A=Array.isArray(g.pred)?g.pred:g.pred===void 0?[]:[g.pred];for(const _ of A){const E=typeof _=="string"?m(_,void 0,"operand"):y(_);if(E)return E}}const h=f(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 $=Rt(e,g.pred);if(!$)return`groupby property is not available: ${g.pred}`;if(g.operator!==void 0&&!i.get(g.operator).supportsGroupedSourceGroupby&&!o.some(_=>_.mappingGranularity?.supportsGroupby?.(g)))return`computed groupby is not covered: ${g.pred}`;const A=m(g.pred,op(g,$,i));if(A)return A}for(const g of o){const $=g.mappingGranularity?.candidateReason?.(t,c);if($)return $}};function Wt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Wt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Wt(e)):[]]}const zn=t=>t.id??t.source,Pr=(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)=>Pr(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)&&Pr(i,n[o]))},Nt=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=Nt(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=Wt(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},Wn=(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=>Wn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>Lr(r,s.property,o)&&Pr(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},ct=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Lr=(t,e,r)=>e===r||ct(t,e)?.id===ct(t,r)?.id&&ct(t,e)!==void 0&&ct(t,r)!==void 0,Ce=(t,e,r)=>Cr(t,e,r)?.column,Cr=(t,e,r)=>{const n=ct(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Lr(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}},Kn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||Ce(t,e,r)!==void 0,Zi=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=Nt(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Kn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},sp=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?ct(r,e.pred):void 0,s=ct(r,t.match.pred),a=typeof e.pred=="string"&&Lr(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 c=Nt(t.match.query);return c!==void 0&&c.every(u=>o.some(l=>Lr(r,l.property,u.property)&&Pr(l.condition,u.condition)))},ap=(t,e,r,n,o,i=Be(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,A=$.operator,_=$.pred;return!A||typeof _!="string"?[]:[{match:{operator:A,pred:_,...$.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 A=$.schemaMapping?.candidateReason?.(t,g);if(A)return A}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const c=Nt(t.query);if(!c&&s.length>0)return"query contains $or or another unsupported logical expression";const u=oe(t),l=[],p=[];for(const[g,$]of(t.preds??[]).entries()){const A=Nt($.query);if(!A&&s.length>0)return`PredItem ${g} query contains an unsupported logical expression`;if(s.length>0){const E=[...c??[],...A??[]],w=s.filter(T=>sp(T,$,e,$.schema??e.id,E));if(w.length===0)return`PredItem ${g} is not mapped`;if(w.length>1)return`PredItem ${g} matches multiple mapping rules`;const R=w[0],C=Nt(R.match.query)??[];p.push(...C);const k=u.preds?.[g];if(k){const T=Wn(k.query,C,e);T?k.query=T:delete k.query}l.push({predIndex:g,column:R.column});continue}const _=Wt($).find(E=>!Kn(r,e,E));if(_)return`PredItem ${g} property is not available: ${_}`}const m=Wn(u.query,p,e);m?u.query=m:delete u.query;const f=Zi(u.query,r,e);if(f)return f;for(const[g,$]of(u.preds??[]).entries()){const A=Zi($.query,r,e);if(A)return`PredItem ${g} ${A}`}for(const g of u.groupby??[]){const A=Wt(g).find(_=>!Kn(r,e,_));if(A)return`groupby property is not available: ${A}`}const y=ip(u,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?.(u,h);if($)return $}return{mapping:r,logicform:u,predRewrites:l,priority:r.priority??0,specificity:l.length}},cp=(t,e,r,n={})=>{const o=n.plugins?ge(n.plugins):r.plugins,i=n.operators??Be(n.plugins),s=[],a=[];for(const p of r.list(e.id)){const m=ap(t,e,p,n.resolveSchema,o,i);typeof m=="string"?a.push({mappingId:zn(p),reason:m}):s.push(m)}if(s.length===0){const p=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${p}\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 c=n.preferredConnectionId===void 0?[]:s.filter(({mapping:p})=>p.connectionId===n.preferredConnectionId),l=(c.length>0?c:s).reduce((p,m)=>m.priority>p.priority||m.priority===p.priority&&m.specificity>p.specificity?m:p);for(const p of s){if(p===l)continue;let m;c.length>0&&p.mapping.connectionId!==n.preferredConnectionId?m=`connection ${p.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:p.priority<l.priority?m=`priority ${p.priority} is lower than selected priority ${l.priority}`:p.specificity<l.specificity?m=`specificity ${p.specificity} is lower than selected specificity ${l.specificity}`:m="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:zn(p.mapping),reason:m})}return{mapping:l.mapping,logicform:l.logicform,predRewrites:l.predRewrites,selection:{schemaId:e.id,selectedMappingId:zn(l.mapping),rejectedMappings:a}}},Kt=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),Jt=(t,e)=>Kt(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Jt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Jt(r,e)),es=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Jt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Jt(r,e)),ts=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),up=(t,e)=>{const r=t.preds??[];if(!r.some(f=>!Kt(f,e)&&es(f,e)))return;const n=new Set([...r.map(({name:f})=>f).filter(f=>!!f),...(t.groupby??[]).map(ts).filter(f=>!!f)]);let o=0;const i=()=>{let f;do f=`__nested_component_input_${o}__`,o+=1;while(n.has(f));return n.add(f),f},s=[],a=f=>{const y=i();return s.push(typeof f=="string"?{pred:f,name:y}:{...oe(f),name:y}),y},c=f=>{if(f.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=oe(f);return Array.isArray(f.pred)?y.pred=f.pred.map(h=>typeof h=="string"||!Jt(h,e)||Kt(h,e)?a(h):c(h)):f.pred&&typeof f.pred=="object"&&(y.pred=Kt(f.pred,e)?a(f.pred):c(f.pred)),y},u=r.map(f=>{const y=f.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Kt(f,e)&&es(f,e)?{...c(f),name:y}:(s.push({...oe(f),name:y}),{pred:y,name:y})}),l=oe(t);l.preds=s,delete l.having,delete l.sort,delete l.limit,delete l.limitBy,delete l.page,delete l.output,delete l.representation;const p=(t.groupby??[]).map(f=>{const y=ts(f);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),m=oe(t);return m.from=l,m.preds=[...p,...u],delete m.query,delete m.groupby,delete m.entity_id,delete m.propertyResolve,m},dp=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,rs=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:dp(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},ns=(t,e)=>({...rs(t,e),id:e.id,name:e.name,type:e.type}),Jn=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},Dr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Dr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Dr(e)):[]],Xn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Xn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Xn(r,e))}:{}}),os=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>os(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:Xn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Zn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Le(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,c])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(c,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)},is=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>is(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&&Zn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),pp=(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}:{}}},ss=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},as=(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}),Ot=(t,e,r,n,o,i,s,a,c="projection")=>{const u=Jn(t);if(c==="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 E=r(t.pred);return{expression:ss(E.field),outputProperty:as(E.reference,E.property),sourceProperty:E.property,sourceField:E.field}}const l=e.get(t.operator);if(c==="groupby"&&l.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(c==="groupby"&&!l.toSQL)throw new d("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(l.planInput&&typeof t.pred!="string")throw new d("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const p=l.planInput&&typeof t.pred=="string"?l.planInput({executionContext:e.executionContext,reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,m=p?.reference??t.pred,f=p?.args??t.args??{},y=m&&typeof m=="object"&&!Array.isArray(m)?Ot(m,e,r,n,o,i,s,a,c):typeof m=="string"?Ot({pred:m,name:m},e,r,n,o,i,s,a,c):void 0,h=Array.isArray(m)?m.map(E=>Ot(typeof E=="string"?{pred:E,name:E}:E,e,r,n,o,i,s,a,c)):[];if(l.requiresProperty!==!1&&!y&&h.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const g=u,$=l.getOutputProperty?.({executionContext:e.executionContext,name:g,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:g}}:{},...h.length>0?{inputProperties:h.map(({outputProperty:E})=>E)}:{},args:f}),A=$?.description??l.description??y?.outputProperty.description,_={...$??(y?as(g,y.outputProperty,{isArray:!1}):{name:g,type:"number",primal_type:"number",isArray:!1}),...A!==void 0?{description:A}:{}};if(l.planExpression){const E=l.planExpression({executionContext:e.executionContext,pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:h.map(({expression:w})=>w),args:f,resolveKey:o,getOperator:w=>e.get(w),planQuery:i});if(E)return{expression:E,outputProperty:_,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(l.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 E=t.args?.direction??"desc";if(E!=="asc"&&E!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const w=t.args?.partitionBy??[];if(!Array.isArray(w)||w.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:l.windowFunction,input:y.expression,partitionBy:w.map(R=>n(String(R))),direction:E==="asc"?"ASC":"DESC"},outputProperty:_}}return{expression:{kind:"operator",operator:t.operator,args:f,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...h.length>0?{inputs:h.map(({expression:E})=>E)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:_,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},lp=(t,e,r,n,o,i,s,a,c,u,l,p=t)=>{const m=Jn(t),f=typeof t.pred=="string"?t.pred:void 0,y=!u||!f?r:A=>{const _=r(A);return A===f?{..._,field:{..._.field,column:u}}:_},h=l?{...t,operator:l}:t,g=Ot(h,e,y,n,o,i,s,a),$=c?.resolveProjection({pred:p,schema:s,executionContext:e.executionContext,...g.sourceProperty?{sourceProperty:g.sourceProperty}:{},outputProperty:{...g.outputProperty,name:m},...p.operator?{operator:e.get(p.operator)}:{}})??{...g.outputProperty,name:m};return{name:m,expression:g.expression,outputProperty:$}},fp=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)}},eo=(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},mp=(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=>qe(h,eo(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(($,A)=>$!==a[A]))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 c=[],u=[],l=new Map;s.forEach((h,g)=>{h.projections.forEach(($,A)=>{const _=a.includes($.name),E=l.get($.name);if(E!==void 0&&!_)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${$.name}`,{name:$.name,childIndexes:[E,g]});if(E!==void 0)return;l.set($.name,g),c.push({name:$.name,expression:{kind:"column",property:$.name,column:$.name}});const w=h.columnProperties?.[A];w&&u.push(w)})});const p=new Set(c.map(({name:h})=>h)),m=Object.entries(t.sort??{}).map(([h,g])=>{if(!p.has(h))throw new d("INVALID_SORT",`Sort field is not an output: ${h}`);const $=u.find(A=>A.name===h);return{name:h,direction:g===1?"ASC":"DESC",...$?.comparable?{comparable:$.comparable}:{},...$?.comparable?{expression:{kind:"column",property:h,column:h}}:{}}}),f=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:m.length>0?m:(()=>{const h=a.at(-1)??"",g=u.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(c.map(({name:h})=>[h,h])),projections:c,columnProperties:u,groupBy:c.filter(({name:h})=>a.includes(h)),...t.having?{having:is(t.having,u)}:{},orderBy:m,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...f?{groupLimit:f}:{},...y?{pagination:y}:{}}},qe=(t,e,r=Be(),n=new Tr,o={})=>{const i=[...new Set((t.preds??[]).map(S=>S.schema).filter(S=>!!(S&&S!==e.id)))];if(i.length>0){const S=t.propertyResolve??{},I=[e.id,...i].map(b=>{const{having:L,sort:j,limit:te,limitBy:N,page:D,...P}=t,M=K=>{let x=K;try{x=ue(e,K,o.resolveSchema).canonicalName}catch{}return S[b]?.[K]??S[b]?.[x]??K};return{...P,schema:b,preds:(t.preds??[]).filter(K=>(K.schema??e.id)===b).map(({schema:K,...x})=>x),...b===e.id||!t.query?{}:{query:os(t.query,M)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(K=>({...K,...typeof K.pred=="string"?{pred:M(K.pred)}:{}}))}:{}}});return mp(t,I,e,r,n,o)}const s=up(t,r);if(s)return qe(s,e,r,n,o);for(const S of t.preds??[]){if(!S.operator)continue;const I=r.get(S.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:b=>r.get(b)});if(I)return qe(I,e,r,n,o)}const a=o.semanticRegistry??Ki(o.plugins);if(t.from){const S=eo(t.from,e,o),I=qe(t.from,S,r,n,o),b=ns(I,e),L={...t};delete L.from,L.schema??=b.id;const j=qe(L,b,r,n,o),te=new Set(j.projections.map(({name:x})=>x)),N=I.rowIdentity.kind==="group"&&I.rowIdentity.names.every(x=>te.has(x))||I.rowIdentity.kind==="singleton"?I.rowIdentity:{kind:"generated"},D=I.groupBy.map(({name:x})=>x).filter(x=>te.has(x)),P=D.at(-1),M=I.columnProperties?.find(x=>x.name===P),K=t.limitBy!==void 0&&D.length>0?{count:t.limitBy,partitionBy:D.slice(0,-1),orderBy:j.orderBy.length>0?j.orderBy:D.slice(-1).map(x=>({name:x,direction:"ASC",...M?.comparable?{comparable:M.comparable}:{}}))}:void 0;return{...j,source:I.source,sourcePlan:I,sourceLogicform:t.from,rowIdentity:N,...K?{groupLimit:K}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const c=cp(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(c.selection),t=c.logicform;const u=new Map(c.predRewrites.map(({predIndex:S,column:I})=>[S,I])),l=Ni(e,o.plugins),p=du(t,e,o.plugins),m=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),f=p?.rewriteQuery?p.rewriteQuery(m):m,y=e.id,h=new Map,g=new Map,$=new Map,A=new Map,_=S=>{const I=g.get(S);if(I)return I.alias;const b=c.mapping.enrichments?.find(te=>te.id===S);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${S}`,{schemaId:e.id,mappingId:c.mapping.id,enrichmentId:S});const L=`__enrichment_${S}`,j=b.temporal?(()=>{if(!l)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${S} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:S});const te=Cr(c.mapping,e,l.start.name),N=Cr(c.mapping,e,l.end.name);if(!te||!N)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${S} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:S});if(te.sourceRef||N.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${S} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:S});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:te.column,endColumn:N.column}})():void 0;return g.set(S,{kind:"enrichment-left",id:S,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:L,baseAlias:y,keys:b.on,...j?{temporalCondition:j}:{}}),L},E=S=>{const I=ue(e,S,o.resolveSchema);let b=y,L=c.mapping;const j=[];for(const P of I.relations){j.push(P.property.name);const M=j.join("_"),K=M,x=n.get(P.targetSchema.id,c.mapping.connectionId);if(L=x,!h.has(M)){const pe=P.targetSchema.properties.filter(({type:Re})=>Re==="ID"),[ee]=pe;if(pe.length!==1||!ee)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${P.targetSchema.id} must contain exactly one ID property`,{schemaId:P.targetSchema.id,count:pe.length});const le=P.sourceSchema.id===e.id?c.mapping:n.get(P.sourceSchema.id,c.mapping.connectionId),re=Ce(le,P.sourceSchema,P.property.name)??P.property.id,_e=Ce(x,P.targetSchema,ee.name)??ee.id,Se=P.sourceSchema.properties.find(({type:Re})=>Re==="timestamp"),he=P.targetSchema.properties.find(({type:Re})=>Re==="timestamp"),ne=uu(P.sourceSchema,P.targetSchema,o.plugins),me=Se?Ce(le,P.sourceSchema,Se.name)??Se.id:void 0,Oe=he?Ce(x,P.targetSchema,he.name)??he.id:void 0,Te=ne?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Ce(le,P.sourceSchema,ne.sourceTimestamp.name)??ne.sourceTimestamp.id,targetColumn:Ce(x,P.targetSchema,ne.targetTimestamp.name)??ne.targetTimestamp.id,sourceGranularity:ne.sourceTimestamp.granularity??"day",targetGranularity:ne.targetTimestamp.granularity??"day"}:ne?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:Ce(le,P.sourceSchema,ne.point.name)??ne.point.id,intervalSide:"target",startColumn:Ce(x,P.targetSchema,ne.start.name)??ne.start.id,endColumn:Ce(x,P.targetSchema,ne.end.name)??ne.end.id}:void 0,we=P.property.isArray?M:void 0;we&&!$.has(we)&&$.set(we,{path:we,sourceAlias:b,sourceColumn:re,...P.property.udf?{sourceSql:P.property.udf.sql,...me?{sourceTimestampColumn:me}:{}}:{},alias:`__array_${M}`}),h.set(M,{kind:"left",path:M,sourceAlias:b,sourceColumn:re,...P.property.udf?{sourceSql:P.property.udf.sql,...me?{sourceTimestampColumn:me}:{}}:{},targetSchemaId:P.targetSchema.id,targetConnectionId:x.connectionId,targetSource:x.source,...x.sourceSql?{targetSourceSql:x.sourceSql}:{},targetAlias:K,targetColumn:_e,...we?{sourceArrayExpansionPath:we}:{},...ee.udf?{targetSql:ee.udf.sql,...Oe?{targetTimestampColumn:Oe}:{}}:{},...Te?{temporalCondition:Te}:{}})}b=K}const te=Cr(L,I.schema,I.property.name);if(I.relations.length>0&&te?.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 N=te?.sourceRef?_(te.sourceRef):b,D={schemaId:I.schema.id,property:I.property.name,propertyId:I.property.id,column:te?.column??I.property.id,qualifier:N,...I.property.isArray?{isArray:!0}:{},...I.property.type==="tag"?{normalizeStringArray:!0}:{},...I.property.comparable?{comparable:I.property.comparable}:{},...pp(I.relations.length>0?e:I.schema,I.property,y)};return A.set(I.canonicalName,D),{reference:I.canonicalName,schema:I.schema,property:I.property,field:D}},w=S=>{if(S)for(const[I,b]of Object.entries(S))if((I==="$and"||I==="$or")&&Array.isArray(b))for(const L of b)typeof L=="object"&&L!==null&&!Array.isArray(L)&&w(L);else if(I==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const L=b.pred;typeof L=="object"&&L!==null&&!Array.isArray(L)&&Dr(L).forEach(E)}else I.startsWith("$")||E(I)},R=S=>{if(Le(S)){const I=eo(S,e,o),b=qe(S,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:S.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray(S)?S.map(R):typeof S!="object"||S===null||S instanceof Date?S:Object.fromEntries(Object.entries(S).map(([I,b])=>[I,R(b)]))},C=S=>Object.fromEntries(Object.entries(S).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(j=>C(j))];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 j=b;if(typeof j.pred!="object"||j.pred===null||Array.isArray(j.pred)||!Object.prototype.hasOwnProperty.call(j,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const te=j.pred,N=Ot(te,r,E,G,Q,C,e,o.resolveSchema,"groupby");if(N.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const D=R(j.condition);return N.outputProperty.comparable&&Zn(D,te.name??te.operator??"$expr",N.outputProperty.comparable.values),[I,{kind:"expression-query",expression:N.expression,condition:N.outputProperty.comparable?{kind:"ordinal-query",comparable:N.outputProperty.comparable,condition:D}:D,properties:Dr(te)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const te=Object.entries(b).find(([N])=>_t(N,o.plugins));if(te){const[N,D]=te,P=_t(N,o.plugins);if(!P)throw new Error(`Query Operator disappeared: ${N}`);const M=E(I),K=P.plan(D,{schema:M.schema,property:M.property,connectionId:c.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(x,pe)=>n.get(x,pe)});return[I,{[N]:{kind:"query-operator",operator:N,value:K.value,definition:P,...K.sources?{sources:K.sources}:{}}}]}}const L=I.startsWith("$")?void 0:E(I).property.comparable;return[I,L?{kind:"ordinal-query",comparable:L,condition:R(b)}:R(b)]})),k=S=>{const I=L=>{if(!L||typeof L!="object")return!1;if(Array.isArray(L))return L.some(I);const j=L;return Object.prototype.hasOwnProperty.call(j,"$and")||Object.values(j).some(I)};if(I(S))return S;const b=new Set(Object.keys(S).flatMap(L=>{if(L.startsWith("$"))return[];const j=ue(e,L,o.resolveSchema);return j.relations.length===1&&j.property.type==="ID"?[j.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(S).map(([L,j])=>{if(L==="$and"||L==="$or")return Array.isArray(j)?[L,j.map(ee=>typeof ee=="object"&&ee!==null&&!Array.isArray(ee)?k(ee):ee)]:[L,j];if(L.startsWith("$"))return[L,j];const te=ue(e,L,o.resolveSchema);if(te.relations.length===0)return[L,j];if(te.property.udf?.sql.includes("$TS")===!0||te.relations.some(({property:ee})=>ee.udf?.sql.includes("$TS")===!0))return[L,j];const D=te.relations.map(({property:ee})=>ee.name).join("_");if(h.has(D))return[L,j];const[P]=te.relations;if(!P)return[L,j];if(b.has(P.property.name))return[L,j];const M=P.property.name,K=te.canonicalName.slice(M.length+1),x=P.targetSchema.properties.find(({type:ee})=>ee==="ID");if(!x)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${P.targetSchema.id} must contain an ID property`,{schemaId:P.targetSchema.id});if(te.relations.length===1&&te.property.id===x.id)return[P.property.id,j];const pe={version:t.version,schema:P.targetSchema.id,query:K?{[K]:j}:{},preds:[{pred:x.name,name:x.name}]};return[P.property.id,{$in:pe}]}))},T=(t.groupby??[]).map(S=>{const I=Jn(S);S.operator&&r.get(S.operator).validateGroupby?.({pred:S,executionContext:r.executionContext});const b=Ot(S,r,E,G,Q,C,e,o.resolveSchema,"groupby");let L=b.expression;if(p?.group===S&&(L={kind:"column",schemaId:e.id,property:p.property.name,propertyId:p.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const j=`groupby:${I}`;$.set(j,{path:j,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}`,...b.sourceProperty.type==="tag"?{normalizeStringArray:!0}:{},...b.sourceProperty.type==="tag"?{elementType:"string"}:{}}),L={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:j}}return{name:I,expression:L,outputProperty:{...b.outputProperty,name:I,isArray:!1}}});function G(S){const I=(t.groupby??[]).findIndex(L=>typeof L.pred=="string"&&L.pred===S||L.name===S),b=I>=0?T[I]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${S}`);return b.expression}function Q(S){const I=(t.groupby??[]).findIndex(L=>typeof L.pred=="string"&&L.pred===S||L.name===S),b=I>=0?T[I]:void 0;return b?b.expression:ss(E(S).field)}const q=S=>{S.operator&&r.get(S.operator).validatePlan?.({executionContext:r.executionContext,pred:S,groupByNames:T.map(({name:I})=>I),resolveGroupName:I=>{const b=(t.groupby??[]).findIndex(L=>L.name===I||typeof L.pred=="string"&&L.pred===I);return b>=0?T[b]?.name:void 0},getOperator:I=>r.get(I)}),S.pred&&typeof S.pred=="object"&&!Array.isArray(S.pred)&&q(S.pred);for(const I of Array.isArray(S.pred)?S.pred:[])q(typeof I=="string"?{pred:I}:I)};for(const S of t.preds??[])q(S);const U=[...T,...(t.preds??[]).map((S,I)=>{const b=p?.rewritePred?.(S)??S;return lp(b,r,E,G,Q,C,e,o.resolveSchema,a,u.get(I),yi(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,S)})],Y=S=>Object.fromEntries(Object.entries(S).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(j=>Y(j))];if(I==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const L=U.find(({name:j})=>j===I)?.outputProperty.comparable;return L&&Zn(b,I,L.values),[I,L?{kind:"ordinal-query",comparable:L,condition:R(b)}:R(b)]})),z=f?k(f):void 0;w(z);const v=S=>{w(S.query),S.pred&&typeof S.pred=="object"&&!Array.isArray(S.pred)&&v(S.pred);for(const I of Array.isArray(S.pred)?S.pred:[])v(typeof I=="string"?{pred:I}:I)};for(const S of t.preds??[])v(S);if(U.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");fp(U);const W=new Set(U.map(({name:S})=>S)),De=T.length>0?{kind:"group",names:T.map(({name:S})=>S),separator:"_",nullLabel:"\u7A7A\u503C"}:U.every(({expression:S})=>S.kind==="column"||S.kind==="property-sql")||U.some(({expression:S})=>S.kind==="property-sql"&&e.properties.some(({id:I,type:b})=>b==="ID"&&I===S.propertyId))?(()=>{const S=e.properties.find(({type:I})=>I==="ID");return S&&(o.canUsePropertyRowIdentity?.(e,S)??!0)?{kind:"property",column:S.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},Me=Object.entries(t.sort??{}).map(([S,I])=>{if(!W.has(S))throw new d("INVALID_SORT",`Sort field is not an output: ${S}`);const b=U.find(L=>L.name===S);return{name:S,direction:I===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),de=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},fe=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:T.slice(0,-1).map(({name:S})=>S),orderBy:Me.length>0?Me:(()=>{const S=T.at(-1);return[{name:S?.name??"",direction:"ASC",...S?.outputProperty.comparable?{comparable:S.outputProperty.comparable,expression:S.expression}:{}}]})()},be=A.size===0&&h.size===0&&g.size===0&&$.size===0&&!z&&T.length===0&&U.length>0&&U.every(({expression:S})=>S.kind==="operator"&&S.operator==="$constant");return{schemaId:e.id,source:be?"":c.mapping.source,...be?{}:{connectionId:c.mapping.connectionId},...!be&&c.mapping.sourceSql?{sourceSql:c.mapping.sourceSql}:{},mappingId:c.mapping.id??c.mapping.source,sourceAlias:y,fields:{...Rc(e),...Object.fromEntries(e.properties.flatMap(S=>{const I=Ce(c.mapping,e,S.name);return I?[[S.name,I],[S.id,I]]:[]}))},fieldReferences:Object.fromEntries(A),joins:[...h.values()],enrichmentJoins:[...g.values()],arrayExpansions:[...$.values()],...p?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:p.periods,match:p.source.kind==="interval"?{kind:"interval",startColumn:Ce(c.mapping,e,p.source.start.name)??p.source.start.id,endColumn:Ce(c.mapping,e,p.source.end.name)??p.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Ce(c.mapping,e,p.source.timestamp.name)??p.source.timestamp.id}}}:{},projections:U.map(({name:S,expression:I})=>({name:S,expression:I})),columnProperties:U.map(({outputProperty:S})=>S),groupBy:T.map(({name:S,expression:I})=>({name:S,expression:I})),...z?{query:C(z)}:{},...t.having?{having:Y(t.having)}:{},orderBy:Me,rowIdentity:be?{kind:"singleton"}:De,...de?{pagination:de}:{},...fe?{groupLimit:fe}:{}}};class yp{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 hp=(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(".")},kr=(t,e,r)=>r===void 0?hp(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Xt=(t,e,r,n,o)=>{const i=qi(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)},Fe=(t,e,r,n=!1,o,i,s,a)=>{const c=(u,l)=>n&&l?`${e.quoteIdentifier(l)}.${e.quoteIdentifier(u)}`:e.quoteIdentifier(u);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 c(t.column,t.qualifier);case"property-sql":return Xt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(ke(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const u=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>Fe(m,e,r,n,o,i,s,a)).join(", ")} `:"",l=Fe(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${u}ORDER BY ${l} ${t.direction})`}case"cumulative":{if(ke(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=Fe(t.input,e,r,n,o,i,s,a),l=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>Fe(m,e,r,n,o,i,s,a)).join(", ")} `:"",p=t.orderBy.map(m=>`${Fe(m.expression,e,r,n,o,i,s,a)} ${m.direction}`).join(", ");return`${e.aggregateFunction(t.function,u)} OVER (${l}ORDER BY ${p} 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((l,p)=>`WHEN ${Fe(t.input,e,r,n,o,i,s,a)} = ${i(l)} THEN ${t.comparable.direction*p}`).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((l,p)=>`WHEN ${Fe(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*p} THEN ${i(l)}`).join(" ")} END`}case"operator":{const u=r.get(t.operator);if(u.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(u.toSQL&&(t.input&&ke(t.input,r)||t.inputs?.some(m=>ke(m,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let l=t.input?Fe(t.input,e,r,n,o,i,s,a):t.column?c(t.column,t.qualifier):void 0;const p=t.inputs?.map(m=>Fe(m,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(u.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");l=`CASE WHEN ${o(t.query)} THEN ${l??"1"} END`}if(u.requiresProperty!==!1&&!l)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return u.toSQL?u.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:(m,f)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(m);return f&&e.castValue?e.castValue(y,f):y},condition:(m,f)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(m,f)}},...l?{expression:l,column:l}:{},...p?{expressions:p}:{},args:t.args}):l??"NULL"}}},ke=(t,e)=>t.kind==="window"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e)):t.kind==="cumulative"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e))||t.orderBy.some(r=>ke(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?ke(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?ke(t.input,e):!1)||(t.inputs?.some(r=>ke(r,e))??!1)),gp=(t,e)=>{const r=t.sourceSql?Xt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`;return t.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(r):r},cs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),us={$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(Fi(r)){if(r.operator!==e)throw new d("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const p=r.definition??s(e);if(!p)throw new d("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return p.compile(r.value,{field:t,provider:o,bind:m=>n.add(m),renderSource:(m,f)=>kr(o,m,f)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&a!==void 0){if(typeof r!="string"||a!=="i")throw new d("INVALID_QUERY_VALUE",'$eq args.options supports only case-insensitive string equality with "i"');const p=n.add(r);return"LOWER("+t+") = LOWER("+p+")"}if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const l={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(l){const p=It(r)?`(${i(r)})`:n.add(r);return`${t} ${l} ${p}`}if(e==="$in"||e==="$nin"){const p=e==="$in"?"IN":"NOT IN";if(It(r))return`${t} ${p} (${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 m=r.filter(It);if(m.length>0){if(m.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${p} (${m.map(i).join(" UNION ALL ")})`}const f=r.map(y=>n.add(y)).join(", ");return`${t} ${p} (${f})`}if(It(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}`)},to=(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&&!It(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=>to(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`)}},ut=(t,e,r,n,o,i)=>{if(Wd(e)){const u=()=>`CASE ${e.comparable.values.map((f,y)=>`WHEN ${t} = ${r.add(f)} THEN ${e.comparable.direction*y}`).join(" ")} END`,l=new Set(["$gt","$gte","$lt","$lte"]),p=m=>typeof m!="object"||m===null||Array.isArray(m)?ut(t,m,r,n,o,i):Object.entries(m).filter(([f])=>f!=="args").map(([f,y])=>(f==="$and"||f==="$or")&&Array.isArray(y)?`(${y.map(p).join(f==="$and"?" AND ":" OR ")})`:l.has(f)?Zt(u(),f,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):Zt(t,f,y,r,n,o,i)).join(" AND ");return p(e.condition)}if(Array.isArray(e))return Zt(t,"$in",e,r,n,o,i);if(!cs(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 u=a.options;if(u!==void 0&&typeof u!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const c=a?.options;for(const[u,l]of Object.entries(e))if(u==="$and"||u==="$or"){if(!Array.isArray(l))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const p=l.map(m=>ut(t,m,r,n,o,i));s.push(`(${p.join(u==="$and"?" AND ":" OR ")})`)}else us[u]?(to(l,u),s.push(ut(n.datePart(t,us[u]),l,r,n,o,i))):u==="$length"?(to(l,"$length"),s.push(ut(n.stringLength(t),l,r,n,o,i))):u!=="args"&&s.push(Zt(t,u,l,r,n,o,i,u==="$regex"||u==="$eq"?c:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},ds=(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(!cs(e))return i(e);const s=[];for(const[a,c]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(l=>ds(t,l,r,n));s.push(`(${u.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(c));else if(a==="$ne")s.push(`NOT (${i(c)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(i),l=u.length===0?a==="$in"?"0 = 1":"1 = 1":u.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&u.length>0?`NOT (${u.join(" OR ")})`:`(${l})`)}else if(a==="$exists")s.push(`${t} IS ${c?"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 ")},Tt=(t,e,r,n,o,i,s,a)=>{const c=[];for(const[u,l]of Object.entries(t)){if(u==="$and"||u==="$or"){if(!Array.isArray(l))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const m=l.map(f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${u} items must be query objects`);return Tt(f,e,r,n,o,i,s,a)});c.push(`(${m.join(u==="$and"?" AND ":" OR ")})`);continue}if(u==="$expr"){if(!Qi(l))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");c.push(ut(s(l.expression),l.condition,n,o,i,a));continue}const p=e(u);c.push(r(u)?ds(p,l,n,o):ut(p,l,n,o,i,a))}return c.join(" AND ")},Ur=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,c=i.comparable,u=!n&&o&&i.expression?o(i.expression):a;return`${c?`CASE ${c.values.map((p,m)=>`WHEN ${u} = ${r.add(p)} THEN ${c.direction*m}`).join(" ")} END`:a} ${i.direction}`}).join(", "),ro=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},ps=(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`])),ls=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:k})=>k)),s="__sdb_page_source",a="__sdb_page",c=n.quoteIdentifier(s),u=n.quoteIdentifier(a),l=ro("__sdb_row_number",i),p=ro("__sdb_total_rows",i),m=n.quoteIdentifier(l),f=n.quoteIdentifier(p),y=Ur(e,n,o,c),h=y?`ORDER BY ${y}`:"",g=`CEIL(${f} * ${r.ratio})`,$=r.page-1,A=r.page,E=[...e.projections.map(({name:k})=>k),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(k=>`${u}.${n.quoteIdentifier(k)}`).join(", "),w=Ur(e,n,o,u),R=`SELECT ${c}.*, ROW_NUMBER() OVER (${h}) AS ${m}, COUNT(*) OVER () AS ${f} FROM ${n.tableAlias(`(${t})`,s)}`;let C=`SELECT ${E} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${u}.${m} > ${$} * ${g} AND ${u}.${m} <= ${A} * ${g}`;return w&&(C+=` ORDER BY ${w}`),C},fs=(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),c=r.quoteIdentifier(s),u=new Set(e.projections.map(({name:A})=>A)),l=ro("__sdb_limit_by_row_number",u),p=r.quoteIdentifier(l),m=o.partitionBy.map(A=>`${a}.${r.quoteIdentifier(A)}`).join(", "),f=o.orderBy.map(({name:A,direction:_,comparable:E})=>{const w=`${a}.${r.quoteIdentifier(A)}`;return`${E?`CASE ${E.values.map((C,k)=>`WHEN ${w} = ${n.add(C)} THEN ${E.direction*k}`).join(" ")} END`:w} ${_}`}).join(", "),h=[...e.projections.map(({name:A})=>A),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(A=>`${c}.${r.quoteIdentifier(A)}`).join(", "),g=`PARTITION BY ${m} ORDER BY ${f}`,$=`SELECT ${a}.*, ROW_NUMBER() OVER (${g}) AS ${p} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${h} FROM ${r.tableAlias(`(${$})`,s)} WHERE ${c}.${p} <= ${o.count}`},Ae=(t,e,r=Be(),n=0)=>{const o=new yp(e,n),i=w=>_t(w);if(t.subplans){const w=t.projections.map(({name:q})=>q),R=new Set(t.groupBy.map(({name:q})=>q)),C=t.subplans.map((q,U)=>{const Y=Ae(q,e,r,o.nextParameterOffset);o.append(Y.parameters);const z=`__composition_child_${U}`,v=e.quoteIdentifier(z),W=new Set(q.projections.map(({name:De})=>De));return{aliasName:z,alias:v,available:W,sql:Y.sql}}),k=C[0];if(!k)throw new d("INVALID_COMPOSITION","Composition has no children");const T=w.map(q=>{const U=C.filter(v=>v.available.has(q)),Y=U[0]??k;return`${R.has(q)&&U.length>1?`COALESCE(${U.map(v=>`${v.alias}.${e.quoteIdentifier(q)}`).join(", ")})`:`${Y.alias}.${e.quoteIdentifier(q)}`} AS ${e.quoteIdentifier(q)}`}),G=C.map(q=>`${q.alias} AS (${q.sql})`);let Q;if(t.rowIdentity.kind==="group"){const U=e.quoteIdentifier("__composition_keys"),Y=e.quoteIdentifier("_id");G.push(`${U} AS (${C.map(z=>`SELECT ${Y} FROM ${z.alias}`).join(" UNION ")})`),T.push(`${U}.${Y} AS ${Y}`),Q=`WITH ${G.join(", ")} SELECT ${T.join(", ")} FROM ${U}`;for(const z of C)Q+=` LEFT JOIN ${z.alias} ON ${U}.${Y} = ${z.alias}.${Y}`}else{Q=`WITH ${G.join(", ")} SELECT ${T.join(", ")} FROM ${k.alias}`;for(const q of C.slice(1))Q+=` LEFT JOIN ${q.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const q="__composition_having",U=e.quoteIdentifier(q),Y=new Set(w),z=Tt(t.having,v=>{if(!Y.has(v))throw new d("INVALID_HAVING",`Having field is not an output: ${v}`);return`${U}.${e.quoteIdentifier(v)}`},()=>!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);Q=`SELECT ${U}.* FROM ${e.tableAlias(`(${Q})`,q)} WHERE ${z}`}if(t.groupLimit&&(Q=fs(Q,t,e,o)),t.pagination?.kind==="ratio")Q=ls(Q,t,t.pagination,e,o);else if(t.orderBy.length>0&&(Q+=` ORDER BY ${Ur(t,e,o)}`),t.pagination?.kind==="rows"){const q=(t.pagination.page-1)*t.pagination.pageSize;Q=e.paginate(Q,t.pagination.pageSize,q)}return{sql:Q,parameters:o.values}}const s=w=>{if(w.plan.projections.some(({expression:C})=>ke(C,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=Ae(w.plan.rowIdentity.kind==="property"||w.plan.rowIdentity.kind==="group"?{...w.plan,rowIdentity:{kind:"generated"}}:w.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,c=(t.arrayExpansions?.length??0)>0,u=a||c||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,l=new Map,p=(t.arrayExpansions??[]).map(w=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(gp(w,e),w.alias,"value",w.elementType);return l.set(w.path,R.valueExpression),R}),m=w=>{const R=t.fieldReferences?.[w];if(R?.sql){const T=Xt(R.sql,R.property,e,R.timestampColumn,u?R.timestampQualifier??R.qualifier:void 0);return R.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(T):T}if(R&&u){const T=`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;return R.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(T):T}const C=t.fields[w];if(!C)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${w}`);const k=e.quoteIdentifier(C);return R?.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(k):k},f=w=>Fe(w,e,r,u,R=>Tt(R,m,C=>t.fieldReferences?.[C]?.isArray===!0,o,e,s,f,i),R=>o.add(R),(R,C)=>ut(R,C,o,e,s,i),R=>{const C=l.get(R);if(!C)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return C}),y=t.projections.map(w=>`${f(w.expression)} AS ${e.quoteIdentifier(w.name)}`),h=t.rowIdentity.kind==="property"?`${u&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const w=t.rowIdentity.names.map(R=>{const C=t.groupBy.find(k=>k.name===R)??t.projections.find(k=>k.name===R);if(!C)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return f(C.expression)});return`${ps(w,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,g=[...y,...h?[h]:[]].join(", "),$=t.sourcePlan?(()=>{const w=Ae(t.sourcePlan,e,r,o.nextParameterOffset);return o.append(w.parameters),`(${w.sql})`})():t.source?kr(e,t.source,t.sourceSql):"",A=u&&t.sourceAlias?e.tableAlias($,t.sourceAlias):$;let _=`SELECT ${g}`;if(t.periodSource){const w=t.periodSource,R=w.periods.map(({label:U,asOf:Y},z)=>{const v=o.add(U),W=o.add(Y);return z===0?`SELECT ${v} AS ${e.quoteIdentifier(w.labelColumn)}, ${W} AS ${e.quoteIdentifier(w.asOfColumn)}`:`SELECT ${v}, ${W}`}).join(" UNION ALL "),C=e.tableAlias(`(${R})`,w.alias),k=e.tableAlias($,w.sourceAlias),T=e.quoteIdentifier(w.alias),G=e.quoteIdentifier(w.sourceAlias),Q=`${T}.${e.quoteIdentifier(w.asOfColumn)}`,q=w.match.kind==="interval"?(()=>{const U=`${G}.${e.quoteIdentifier(w.match.startColumn)}`,Y=`${G}.${e.quoteIdentifier(w.match.endColumn)}`;return`${U} <= ${Q} AND (${Y} > ${Q} OR ${Y} IS NULL)`})():(()=>{const U=e.tableAlias($,w.match.lookupAlias),Y=e.quoteIdentifier(w.match.lookupAlias),z=`${G}.${e.quoteIdentifier(w.match.timestampColumn)}`,v=`${Y}.${e.quoteIdentifier(w.match.timestampColumn)}`,W=`SELECT ${e.aggregateFunction("max",v)} FROM ${U} WHERE ${v} <= ${Q}`;return`${z} = (${W})`})();_+=` FROM ${C} LEFT JOIN ${k} ON ${q}`,t.query&&Object.keys(t.query).length>0&&(_+=` AND ${Tt(t.query,m,U=>t.fieldReferences?.[U]?.isArray===!0,o,e,s,f,i)}`)}else A&&(_+=` FROM ${A}`);for(const w of p)_+=` ${w.joinSql}`;for(const w of t.enrichmentJoins??[]){const R=e.quoteIdentifier(w.alias),C=e.quoteIdentifier(w.baseAlias);_+=` LEFT JOIN ${e.tableAlias(kr(e,w.source,w.sourceSql),w.alias)}`;const k=w.keys.map(({baseColumn:T,targetColumn:G})=>`${C}.${e.quoteIdentifier(T)} = ${R}.${e.quoteIdentifier(G)}`);if(w.temporalCondition?.kind==="point-in-interval"){const T=Y=>Y==="source"?C:R,G=`${T(w.temporalCondition.pointSide)}.${e.quoteIdentifier(w.temporalCondition.pointColumn)}`,Q=T(w.temporalCondition.intervalSide),q=`${Q}.${e.quoteIdentifier(w.temporalCondition.startColumn)}`,U=`${Q}.${e.quoteIdentifier(w.temporalCondition.endColumn)}`;k.push(`${q} <= ${G}`),k.push(`(${U} > ${G} OR ${U} IS NULL)`)}_+=` ON ${k.join(" AND ")}`}for(const w of t.joins??[]){_+=` LEFT JOIN ${e.tableAlias(kr(e,w.targetSource,w.targetSourceSql),w.targetAlias)}`;const R=w.sourceArrayExpansionPath?l.get(w.sourceArrayExpansionPath):w.sourceSql?Xt(w.sourceSql,w.sourceColumn,e,w.sourceTimestampColumn,w.sourceAlias):`${e.quoteIdentifier(w.sourceAlias)}.${e.quoteIdentifier(w.sourceColumn)}`,C=w.targetSql?Xt(w.targetSql,w.targetColumn,e,w.targetTimestampColumn,w.targetAlias):`${e.quoteIdentifier(w.targetAlias)}.${e.quoteIdentifier(w.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${w.path}`);if(_+=` ON ${R} = ${C}`,w.temporalCondition?.kind==="date-bucket-equal"){const k=`${e.quoteIdentifier(w.sourceAlias)}.${e.quoteIdentifier(w.temporalCondition.sourceColumn)}`,T=`${e.quoteIdentifier(w.targetAlias)}.${e.quoteIdentifier(w.temporalCondition.targetColumn)}`;_+=` AND ${e.dateBucket(k,w.temporalCondition.sourceGranularity)} = ${e.dateBucket(T,w.temporalCondition.targetGranularity)}`}else if(w.temporalCondition?.kind==="point-in-interval"){const k=U=>U==="source"?e.quoteIdentifier(w.sourceAlias):e.quoteIdentifier(w.targetAlias),T=`${k(w.temporalCondition.pointSide)}.${e.quoteIdentifier(w.temporalCondition.pointColumn)}`,G=k(w.temporalCondition.intervalSide),Q=`${G}.${e.quoteIdentifier(w.temporalCondition.startColumn)}`,q=`${G}.${e.quoteIdentifier(w.temporalCondition.endColumn)}`;_+=` AND ${Q} <= ${T} AND (${q} > ${T} OR ${q} IS NULL)`}}const E=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&E.push(Tt(t.query,m,w=>t.fieldReferences?.[w]?.isArray===!0,o,e,s,f,i)),E.length>0&&(_+=` WHERE ${E.join(" AND ")}`),t.groupBy.length>0){const w=t.groupBy.map(C=>f(C.expression)),R=t.rowIdentity.kind==="group"?[ps(w,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];_+=` GROUP BY ${[...w,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const w=R=>{const C=t.projections.find(k=>k.name===R);if(!C)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?f(C.expression):e.quoteIdentifier(R)};_+=` HAVING ${Tt(t.having,w,()=>!1,o,e,s,f,i)}`}if(t.groupLimit&&(_=fs(_,t,e,o)),t.pagination?.kind==="ratio")_=ls(_,t,t.pagination,e,o);else if(t.orderBy.length>0&&(_+=` ORDER BY ${Ur(t,e,o,void 0,f)}`),t.pagination?.kind==="rows"){const w=(t.pagination.page-1)*t.pagination.pageSize;_=e.paginate(_,t.pagination.pageSize,w)}return{sql:_,parameters:o.values}},Ap=(t,e)=>{const r=Object.keys(e).sort((m,f)=>f.length-m.length),n=[];let o=0;for(;o<t.length;){const m=t[o];if(m&&/\s/.test(m)){o+=1;continue}if(m&&/[()+\-*/,]/.test(m)){n.push(m),o+=1;continue}const f=t.slice(o).match(/^\d+(?:\.\d+)?/);if(f?.[0]){n.push(f[0]),o+=f[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(m??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],c=()=>{const m=a();if(!m)throw new Error("Component expression is incomplete");if(m==="("){const y=l();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(m))return m;if(!e[m]&&!/^[A-Za-z_$][\w$]*$/.test(m))throw new Error(`Invalid component expression token: ${m}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(l()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(m.toUpperCase()))throw new Error(`Unsupported component expression function: ${m}`);return`${m.toUpperCase()}(${y.join(", ")})`}const f=e[m];if(!f)throw new Error(`Unknown component in expression: ${m}`);return f},u=()=>{let m=c();for(;s()==="*"||s()==="/";)m=`${m} ${a()} ${c()}`;return m},l=()=>{let m=u();for(;s()==="+"||s()==="-";)m=`${m} ${a()} ${u()}`;return m},p=l();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return p},wp=t=>`__sdb_cte_${t}`,ms=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},$p=(t,e)=>t?.find(r=>r.name===e),Ep=(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,no=(t,e,r,n=Be())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((A,_)=>{const E={...A.compiled,sql:Ep(A.compiled.sql,r,o)};return o+=A.compiled.parameters.length,{...A,compiled:E,alias:`__sdb_exec_${_}`}}),s=i.map(({alias:A,compiled:_})=>`${r.quoteIdentifier(A)} AS (${_.sql})`),a=i[0],c=r.quoteIdentifier(a.alias),u=e.groupBy.map(({name:A})=>A),l=e.orderBy??[],p=e.rowIdentity.kind==="group",m=r.quoteIdentifier("__sdb_exec_keys");if(p){const A=_=>[...u.map(E=>`${_}.${r.quoteIdentifier(E)}`),`${_}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${m} AS (${i.map(({alias:_})=>`SELECT ${A(r.quoteIdentifier(_))} FROM ${r.quoteIdentifier(_)}`).join(" UNION ")})`)}const f=p?m:c,y=[...u,...t.flatMap(({outputs:A})=>A)],h=y.filter((A,_,E)=>E.indexOf(A)===_).map(A=>{if(u.includes(A))return`${f}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`;const _=i.find(({outputs:w})=>w.includes(A));if(!_)throw new Error(`CTE execution unit does not expose output projection: ${A}`);return`${r.quoteIdentifier(_.alias)}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`});p&&h.push(`${f}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let g=`SELECT ${h.join(", ")} FROM ${f}`;for(const A of p?i:i.slice(1)){const _=r.quoteIdentifier(A.alias);g+=` LEFT JOIN ${_}`,g+=p?` ON ${f}.${r.quoteIdentifier("_id")} = ${_}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||l.length>0||e.pagination||e.groupLimit)){const A={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:g,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(E=>[E,E])),projections:y.map(E=>({name:E,expression:{kind:"column",property:E,column:E}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:l.map(({name:E,direction:w,comparable:R})=>({name:E,direction:w,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},_=Ae(A,r,n,o);return{sql:`WITH ${s.join(", ")} ${_.sql}`,parameters:[...i.flatMap(({compiled:E})=>E.parameters),..._.parameters]}}return{sql:`WITH ${s.join(", ")} ${g}`,parameters:i.flatMap(({compiled:A})=>A.parameters)}},Mr=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const A of e){const _=Ae(A.plan,o,i,a);a+=_.parameters.length,s.push({input:A,sql:_,alias:wp(A.name)})}const c=s.map(({sql:A,alias:_})=>`${o.quoteIdentifier(_)} AS (${A.sql})`).join(", "),u=s[0];if(!u)throw new Error("CTE calculation requires a current component");const l=o.quoteIdentifier(u.alias),p=r.groupBy.map(({name:A})=>A),m=p.map(A=>`${l}.${o.quoteIdentifier(A)} AS ${o.quoteIdentifier(A)}`);let f="";for(const A of s.slice(1)){const _=o.quoteIdentifier(A.alias),E=A.input.plan.groupBy.map(({name:C})=>C),R=(A.input.joinKeys??p.filter(C=>E.includes(C))).map(C=>{const k=$p(A.input.groupKeyShifts,C),T=k?o.dateShift(`${_}.${o.quoteIdentifier(C)}`,k.granularity,k.offset):`${_}.${o.quoteIdentifier(C)}`;return`${l}.${o.quoteIdentifier(C)} = ${T}`});f+=` LEFT JOIN ${_} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:A,alias:_})=>[A.name,`${o.quoteIdentifier(_)}.${o.quoteIdentifier(ms(A.plan))}`])),h=Ap(t.expression,y),g=[...m,...r.rowIdentity.kind==="group"?[`${l}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:A,alias:_})=>`${`${o.quoteIdentifier(_)}.${o.quoteIdentifier(ms(A.plan))}`} AS ${o.quoteIdentifier(A.name)}`),`${h} AS ${o.quoteIdentifier(n)}`].join(", ");let $=`WITH ${c} SELECT ${g} FROM ${l}`;return $+=f,{sql:$,parameters:s.flatMap(({sql:A})=>A.parameters)}},_p=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=hs(t).length*2+2;for(let n=0;n<r;n+=1){const o=Sp(e);if(o===e)return e;e=o}return e}catch{return t}},Sp=t=>{const e=hs(t),r=Ip(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=gs(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?xp(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 c=qp(bp(t.slice(i.fromStart,i.close),i,e)),u=Rp(t,i),l=Np(t,i);if(l&&Op(u,l))continue;let p=s.filter(h=>{const g=As(h);if(!g||g==="_id")return!0;const $=new RegExp(`(^|[^\\w$])${oo(g)}([^\\w$]|$)`,"i");return $.test(c)||$.test(u)}),m=!0;for(;m;){m=!1;const h=Es(p.join(" ")),g=s.filter($=>{if(p.includes($))return!1;const A=As($);return A?new RegExp(`(^|[^\\w$])${oo(A)}([^\\w$]|$)`,"i").test(h):!1});g.length>0&&(p=s.filter($=>p.includes($)||g.includes($)),m=!0)}if(p.length===s.length)continue;const f=t.slice(i.selectEnd,i.fromStart),y=p.length===0&&jp(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(u)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(f)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(c);p.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:f.match(/^\s*/)[0]+(y?"1":p.map(h=>h.trim()).join(", "))+f.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},Ip=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ys(t,"FROM",n);if(o===-1||!gs(t,n,o)?.every(Mp))return t;const s=e.find(m=>m.open>o&&t.slice(o+4,m.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(m=>m.open>s.fromStart&&m.close<s.close).sort((m,f)=>f.close-f.open-(m.close-m.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const c=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(c))return t;const u=kp.exec(c)?.[1],l=Up.exec(t.slice(s.close+1));if(!u||!l||ws(u)!==ws(l[1]))return t;const p=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+p},bp=(t,e,r)=>Tp(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}))),Rp=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return Es(r)},Np=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${Ke})(?=\\s|$)`,"i"))?.[1]??null,Op=(t,e)=>new RegExp(`(^|[^\\w$])${oo(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Tp=(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("")},ys=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const c=t[a],u=t[a+1];if(s==="--"){c===`
|
|
2
|
-
`&&(s="");continue}if(s==="/*"){c==="*"&&u==="/"&&(s="",a+=1);continue}if(i){c===i&&t[a-1]!=="\\"&&(i="");continue}if(c==="-"&&u==="-"){s="--",a+=1;continue}if(c==="/"&&u==="*"){s="/*",a+=1;continue}if(c==="`"||c==='"'||c==="'"){i=c;continue}if(c==="("){n+=1;continue}if(c===")"){n-=1;continue}if(c==="["){o+=1;continue}if(c==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},
|
|
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 c=r.pop();if(!c)continue;const u=t.slice(c.open+1,i),l=/^\s*SELECT\b/i.exec(u);if(!l)continue;const p=c.open+1+l[0].length,m=ys(t,"FROM",p);m===-1||m>=i||e.push({open:c.open,close:i,selectEnd:p,fromStart:m})}return e},gs=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,c="";for(let u=0;u<n.length;u+=1){const l=n[u];if(c){l===c&&n[u-1]!=="\\"&&(c="");continue}if(l==="`"||l==='"'||l==="'"){c=l;continue}l==="("?s+=1:l===")"?s-=1:l==="["?a+=1:l==="]"?a-=1:l===","&&s===0&&a===0&&(o.push(n.slice(i,u)),i=u+1)}return c||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,Ke='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Pp=new RegExp(`\\s+AS\\s+${Ke}\\s*$`,"i"),Lp=new RegExp(`\\bAS\\s+${Ke}`,"gi"),Cp=new RegExp(`(?:${Ke}\\s*\\.\\s*)+${Ke}`,"g"),Dp=new RegExp(`^${Ke}(?:\\s*\\.\\s*${Ke})*$`),kp=new RegExp(`^\\s*(?:AS\\s+)?(${Ke})\\s+WHERE\\b`,"i"),Up=new RegExp(`^\\s*(?:AS\\s+)?(${Ke})\\s*;?\\s*$`,"i"),ws=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Mp=t=>{const e=t.replace(Pp,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},$s=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),Es=t=>$s(t,Lp),qp=t=>$s(t,Cp),jp=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),xp=t=>{const e=t.trim();return Dp.test(e)?e:null},oo=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),io=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?io(t.input,e):!1)||(t.inputs?.some(n=>io(n,e))??!1)},_s=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?_s(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},dt=async(t,e,r)=>{const n=e.filter(({expression:o})=>io(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 _s(s.expression,i,s.name,r);return i}))},qr=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),jr=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:qr(t[o])).join(r),so=(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?jr(r,e.names,e.separator,e.nullLabel):qr(r._id)}:{...r,_id:e.kind==="singleton"?"0":vo()}}),ao=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},er=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&er(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&er(r,e)),xr=(t,e,r,n,o,i,s="zh-CN",a=$r.translator(s))=>{const c=t.preds??[],u=c.map((f,y)=>({pred:f,index:y,definition:f.operator?n.get(f.operator):void 0})).filter(({definition:f})=>f?.kind==="component"&&!f.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(u.length===0&&e.sourcePlan||u.length===0)return;for(const f of c)if((!f.operator||n.get(f.operator).kind!=="component")&&(f.pred&&typeof f.pred=="object"&&!Array.isArray(f.pred)&&er(f.pred,n)||Array.isArray(f.pred)&&f.pred.some(y=>typeof y!="string"&&er(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const l=[],p=c.filter((f,y)=>!u.some(h=>h.index===y));if(p.length>0){const f=ao(t);f.preds=p,l.push({kind:"query",logicform:f})}const m=t.groupby?.length??0;for(const{pred:f,index:y,definition:h}of u){const g=h?.createComponent;if(!g)continue;const $=e.projections[m+y]?.name;if(!$)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const A=i?.preds?.[y],_=g({executionContext:n.executionContext,logicform:ao(t),pred:A??f,outputName:$,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:ao(i)}:{}});if("logicform"in _&&(_.logicform.preds??[]).some(E=>er(E,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");l.push("components"in _?{..._,outputName:$}:_)}return l},Qe=t=>t instanceof Date?t.getTime():t,Bp=(t,e,r,n)=>{const o=Qe(t),i=Qe(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=>Qe(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Qe(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}`)}},co=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return Qe(t)===Qe(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(c=>co(t,c));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&co(t.length,s):Bp(t,i,s,typeof o=="string"?o:void 0)})},Ss=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>Ss(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return co(t[r],n)}),Vp=(t,e)=>e.length===0?"0":t._id===void 0?jr(t,e):qr(t._id),uo=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=Vp(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},po=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=uo(t,r);if(e.having&&(n=n.filter(o=>Ss(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=jr(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,c)=>{for(const u of o.orderBy){const l=Qe(a[u.name]),p=Qe(c[u.name]);if(l!==p)return l==null?u.direction==="ASC"?-1:1:p==null?u.direction==="ASC"?1:-1:(l<p?-1:1)*(u.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=Qe(o[s.name]),c=Qe(i[s.name]);if(a!==c)return a==null?s.direction==="ASC"?-1:1:c==null?s.direction==="ASC"?1:-1:(a<c?-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},Is=(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 lo{#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 Yp=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)}},bs=t=>{Yp(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)})},Fp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Qp=(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 c=a,u=Object.keys(c).filter(l=>l!=="sql");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:u});if(typeof c.sql!="string"||c.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(n.isArray&&t.isArray===!1)throw new d("INVALID_IS_ARRAY",`Property ${t.name} of type ${t.type} must be an array`,{property:t.name,type:t.type});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; received ${JSON.stringify(a)}`,{property:t.name,comparable:a});const c=a;if(Object.keys(c).some(u=>u!=="values"&&u!=="direction")||!Array.isArray(c.values)||c.values.length===0||c.values.some(u=>typeof u!="string")||new Set(c.values).size!==c.values.length||c.direction!==1&&c.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1; received ${JSON.stringify(a)}`,{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??n.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&&!Fp.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},Rs=(t,e,r=[])=>{const n=ge(r),o=n.reduce((f,y)=>y.prepareSchema?.(f)??f,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(f=>f.propertyMetadata?[f.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:f})=>f));let a=o.properties.map(f=>{const y=Object.fromEntries(Object.entries(f).filter(([g])=>!s.has(g))),h=Qp(y,e);return i.reduce((g,$)=>({...g,...$.resolve(f,g,o)}),h)});for(const f of i)a=[...f.resolveAll?.(a,o.properties,o)??a];bs(a);const c=n.flatMap(f=>f.schemaMetadata?[f.schemaMetadata]:[]);let u={};for(const f of c)u={...u,...f.resolve(o,a)};const l=new Set(n.flatMap(f=>[...f.schemaMetadata?.keys??[],...f.legacySchemaKeys??[]])),m={...Object.fromEntries(Object.entries(o).filter(([f])=>!l.has(f))),properties:a,...u};for(const f of n)f.validateResolvedSchema?.(m);return m};ce.extend(Qo),ce.extend(Vt),ce.extend(yr);const vp="YYYY-MM-DD HH:mm:ss",Hp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Ns=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Gp=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Br=["second","minute","hour","day","week","month","quarter","year"],pt=t=>Object.prototype.toString.call(t)==="[object Object]",Os=(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(pt(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Ns.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=>Os(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`)},fo=t=>!pt(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Br.includes(t.granularity)&&typeof t.offset=="number"||Br.some(e=>e in t),Pt=t=>ce(t).format(vp),zp=(t,e)=>Br.find(r=>r in t||e!==void 0),Wp=(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),Ts=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??zp(t,void 0)??"day";let i=ce(e).millisecond(0);for(const a of[...Br].reverse()){const c=t[a];typeof c=="number"&&(i=Wp(i,a,c));const u=n?.[a];typeof u=="number"&&u!==0&&(i=i.add(u,a))}const s=o==="week"?"isoWeek":o;return{$gte:Pt(i.startOf(s)),$lte:Pt(i.endOf(s))}},Kp=(t,e)=>{const r=ce(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:Pt(o()),$lte:Pt(r.endOf("day"))}},mo=async(t,e)=>{const r=ce(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=ce(n).endOf(i),a=ce(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const c=s.isBefore(r)?s:r;return{...t,$lte:Pt(c)}},yo=async(t,e)=>Le(t)?t:t instanceof Date||typeof t=="string"&&ce(t).isValid()?Pt(t):typeof t=="string"&&Hp.has(t)?mo(Kp(t,e.now),e):fo(t)?mo(Ts(t,e.now),e):t,Ps=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Vr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>yo(o,r)));const n=await yo(e,r);return t==="$eq"&&pt(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?pt(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&pt(n)&&"$lte"in n?n.$lte:n},Vr=async(t,e)=>{if(Le(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Vr(o,e)));if(!pt(t))return yo(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)&&(!fo(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(fo(t))return mo(Ts(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Ps("$eq",r[0][1],e);if(pt(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Gp.has(o)&&Os(i,o),n[o]=Ns.has(o)?await Ps(o,i,e):await Vr(i,e);return n},Jp=(t,e)=>e.property.primal_type==="date"?Vr(t,e):t,ho=(t=[])=>new lo([...vn,...ge(t).flatMap(({semanticTypes:e})=>e??[])]),Ls=(t,e)=>{const r=new lo(t.definitions());for(const n of ge(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},Xp=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Zp=t=>{if(typeof t!="string")return!1;const e=Xp.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},go=t=>{if(!Zp(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})},Cs=(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)&&Cs(o,e))),Ds=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!On(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Tn(r,n);return t&&Cs(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Lt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),el={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},ks={$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"}},Ct=(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=>Ct(n,e)).join(e?", ":"\u3001");if(!Lt(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Ct(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Ct(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])}${el[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Yr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),Us=(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}`},tr=(t,e,r)=>{if(!Lt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return Us("$eq",t,Ct(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Yr(i.map(s=>tr(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(ks[o]){const s=ks[o];n.push(tr(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(tr(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Lt(i)?Ct(i.pattern,r):Ct(i,r),a=Us(o,t,s,r);a&&n.push(a)}return Yr(n,"$and",r)},Ms=(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(Yr(i.map(s=>Lt(s)?Ms(s,e):""),o,r));else if(o==="$expr"&&Lt(i)){const s=i.pred,a=Lt(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(tr(a,i.condition,r))}else i!==void 0&&n.push(tr(o,i,r));return Yr(n,"$and",r)},Dt=(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??$r,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(f=>typeof f=="string"?f:Dt(f,e,r)):[],c=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Dt(t.pred,e,r):void 0,u=c??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),l=t.args??{},p=t.operator?(()=>{const f=e.get(t.operator),y={executionContext:e.executionContext,operandName:u,...c?{inputName:c}:{},inputNames:a,args:l,locale:n,t:s},h=f.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 l.granularity=="string"?s(`time.granularity.${l.granularity}`,l.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(f.defaultNameIsLocalized)return h;const A=typeof f.defaultNameKey=="function"?f.defaultNameKey(y):f.defaultNameKey??`operator.${t.operator}`;return s(A,h,{...l,operandName:u,inputName:c??"",inputNames:a.join($),input0:a[0]??"",input1:a[1]??"",granularity:g})})():u;if(typeof p!="string"||p.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 p;const m=Ms(t.query,n);return m?i?`${p} where ${m}`:`${m}\u7684${p}`:p},tl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},rl=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},nl=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}}},rr=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&&!tl(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),c=Array.isArray(t.pred)?await Promise.all(t.pred.map(f=>rr(typeof f=="string"?{pred:f}:f,s,r,n))):void 0,{query:u,...l}=t,p={...l,...a?{query:a}:{},...c?{pred:c}:{}},m=async f=>{const y=await nl(f,s,r),h=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s,executionContext:o.executionContext})??y:y;return rl(h)};if(typeof t.pred=="string"){const f=ue(s,t.pred,r.resolveSchema),y={...p,pred:f.canonicalName};return m({...y,name:y.name??Dt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const f={...p,pred:await rr(t.pred,s,r,n)};return m({...f,name:f.name??Dt(f,o,i)})}if(c)return m({...p,name:p.name??Dt(p,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return m({...p,name:p.name??Dt(p,o,i)})},ol=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),il=t=>{if(!Le(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},Fr=async(t,e)=>{if(Le(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=>Fr(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 Fr(n,e)])))},qs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>qs(o,e))]:[`${e}_${r}`,n])),Ao=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},js=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),wo=new Set([...js,"$length"]),Qr=t=>Array.isArray(t)?t.some(Qr):typeof t!="object"||t===null||Le(t)?!1:Object.entries(t).some(([e,r])=>wo.has(e)||Qr(r)),xs=(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&&!Le(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=>xs(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`)}},vr=(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)&&vr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&vr(r,e)},Bs=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(c=>c!=="pred"&&c!=="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");vr(i,r);const s=await rr(i,e,r,()=>Promise.resolve(void 0));vr(s,r);const a=Ao(await Fr(n.condition,r));return wo.has(s.operator)&&xs(a,s.operator),{pred:s,condition:a}},Vs=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Le(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))wo.has(s)?i.push({$expr:await Bs({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(Qr)?i.push({[s]:await Promise.all(a.map(c=>Vs(t,c,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:Ao(o)}),i.length===1?i[0]??{}:{$and:i}},$o=t=>Array.isArray(t)?t.some($o):typeof t!="object"||t===null||Le(t)?!1:Object.entries(t).some(([e,r])=>js.has(e)||$o(r)),Ys=async(t,e,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||Le(u))return;const l=u;if("$options"in l)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(l).forEach(o)};if(o(t),r.primal_type!=="date"&&$o(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:u=>n.requestTimeWatermark?.(e,r,u)??Promise.resolve(void 0)},a=await Jp(oe(t),s),c=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const u=new Set(r.comparable.values),l=(p,m)=>{if(!(Le(p)||p===null)){if(Array.isArray(p)){p.forEach(f=>l(f,m));return}if(typeof p=="object"){Object.entries(p).forEach(([f,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(f)||l(y,f)});return}if(!(m&&["$exists","$regex","$contains","$startsWith","$length"].includes(m))&&(typeof p!="string"||!u.has(p)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(p)}`,{property:r.name,value:p})}};l(c)}return c},Eo=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const c=Object.entries(a);if(c.length===1&&c[0]?.[0]==="$and"&&Array.isArray(c[0][1]))for(const u of c[0][1])s(u);else c.length===1&&c[0]?.[0]==="$expr"?o.push(a):c.every(([u])=>!u.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,c]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(c.map(async f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return Eo(f,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Bs(c,e,r)});continue}const u=ue(e,a,r.resolveSchema);if(il(c)&&(u.property.primal_type==="entity"||u.property.primal_type==="object")&&u.property.ref){if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const f=await r.normalizeNestedLogicform(c);n[u.canonicalName]={$in:f};continue}if(ol(c)){if(c.version!==void 0&&go(c),u.property.primal_type!=="entity"&&u.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!u.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${u.canonicalName}`);if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema}`);const f=r.resolveSchema?.(c.schema);if(!f)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${c.schema}`);const y=Ds(c.query,c.entity_id,f,r.plugins),h=await Eo(y,f,r);Object.assign(n,qs(h,u.canonicalName));continue}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){const f=c,y=Object.entries(f).filter(([h])=>_t(h,r.plugins));if(y.length>0){const[h]=y,g=h?_t(h[0],r.plugins):void 0;if(g?.validateCondition?.(f),!h||y.length!==1||Object.keys(f).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[$,A]=h;if(!g)throw new Error(`Query Operator disappeared: ${$}`);n[u.canonicalName]={[$]:await g.normalize(A,{schema:u.schema,property:u.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(_,E,w)=>Ys(_,E,w,r)})};continue}}const l=await Fr(c,r),p=await Ys(l,u.schema,u.property,r),m=Ao(p);if(Qr(m)){s(await Vs(u.canonicalName,m,e,r));continue}n[u.canonicalName]=m}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},Fs=async(t,e,r)=>{if(!t)return;const n=await Eo(t,e,r);return Object.keys(n).length===0?void 0:n},Qs=(t,e,r)=>Promise.all((t??[]).map(n=>rr(n,e,r,Fs))),sl=(t,e,r)=>Qs(t??[],e,r),kt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},al=t=>{"skip"in t&&kt("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)&&kt("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&&kt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&kt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&kt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&kt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},cl=t=>t.property.name,vs=(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(c=>c.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 c=r?.(a.ref);if(!c)continue;const u=vs(c,e,r,n,i);if(u)return`${a.name}_${u}`}},Hs=(t,e,r,n)=>{try{const o=ue(t,e,n);return vs(r,cl(o),n,o.property.type)}catch{return}},_o=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?_o(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:_o(e)):[]],Gs=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>Gs(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)?_o(n):[]}return e.startsWith("$")?[]:[e]}):[],ul=(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 c=r.resolveSchema?.(s),u={};for(const[l,p]of Object.entries(a))try{const m=ue(e,l,r.resolveSchema),f=c?ue(c,p,r.resolveSchema):void 0;u[m.canonicalName]=f?.canonicalName??p}catch{u[l]=p}o[s]=u}const i=[...(t.groupby??[]).map(s=>s.pred),...Gs(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ue(e,s,r.resolveSchema)}catch{continue}for(const c of n){const u=r.resolveSchema?.(c),l=u&&Hs(e,s,u,r.resolveSchema);l&&l!==a.canonicalName&&(o[c]={...o[c]??{},[a.canonicalName]:l})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},dl=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`)}}},pl=async(t,e,r)=>{if(!t)return;const n=Is(t,e,r);return lt(t,n,r)},lt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:wr([...ge(r.plugins).flatMap(h=>h.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Be(r.plugins)}},go(t),dl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!Rn(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=oe(t),i={...r,normalizeNestedLogicform:async h=>{const g=Is(h,e,r);return lt(h,g,r)}};al(o);const s=await pl(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,c=await Fs(Ds(o.query,o.entity_id,a,r.plugins),a,i),u=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,l={...i,...c?{autoCaseQuery:c}:{}};let p=await Qs(u,a,l),m=await sl(o.groupby,a,l);const f=m.filter(h=>yi(h,m,a,r.resolveSchema));if(f.length>0){const h=new Set(f.map(({name:g})=>g));m=m.filter(({name:g})=>!h.has(g)),p=[...p,...f]}return o.preds=p,m.length>0?o.groupby=m:delete o.groupby,s?o.from=s:delete o.from,c?o.query=c:delete o.query,ul(o,a,i)},zs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Je=(t,e)=>{if(t){if(!zs(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},ft=(t,e,r)=>{const n=Je(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},nr=(t,e,r)=>{if(!ft(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})},So=(t,e,r,n)=>{const o=ue(e,t,n);for(const i of o.relations)Je(r,i.targetSchema.id),nr(r,i.sourceSchema,i.property);nr(r,o.schema,o.property)},Ws=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Hr=(t,e,r,n)=>{if(Le(t)){zr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)Hr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))Hr(o,e,r,n)};function or(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Je(r,t.schema),typeof t.pred=="string"?So(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&or(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?So(s,i,r,n):or(s,i,r,n,o);Gr(t.query,i,r,n,o)}const Gr=(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 c of s)Gr(c,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const c=s.pred;typeof c=="object"&&c!==null&&!Array.isArray(c)&&or(c,e,r,n,o),Hr(s.condition,r,n,o)}continue}const a=ue(e,i,n);if(So(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[c,u]of Object.entries(s))_t(c,o)?.authorize?.(u,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:l=>{Je(r,l)},assertPropertyAllowed:(l,p)=>nr(r,l,p),hasRowPermissions:l=>Je(r,l)?.rowPermissions!==void 0});if(Ws(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);Je(r,c.id),On(s.entity_id)&&nr(r,c,Tn(c,o)),Gr(s.query,c,r,n,o);continue}Hr(s,r,n,o)}},zr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){zr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Je(e,o.id),On(t.entity_id)&&nr(e,o,Tn(o,n)),t.from){zr(t.from,e,r,n);return}Gr(t.query,o,e,r,n);for(const i of t.preds??[])or(i,o,e,r,n);for(const i of t.groupby??[])or(i,o,e,r,n)},Wr=(t,e)=>{if(Array.isArray(t))return t.map(o=>Wr(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Wr(i,e)]),n=Object.fromEntries(r);return Ws(t)&&!zs(t,"version")&&(n.version=e),n},ll=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[c,u]of Object.entries(s))if((c==="$and"||c==="$or")&&Array.isArray(u))for(const l of u)o(l,a);else if(c==="$expr"&&typeof u=="object"&&u!==null&&!Array.isArray(u)){const l=u.pred;typeof l=="object"&&l!==null&&!Array.isArray(l)&&i(l,a)}else c.startsWith("$")||n.push(ue(a,c,r))},i=(s,a)=>{const c=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(ue(c,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,c);for(const u of Array.isArray(s.pred)?s.pred:[])typeof u=="string"?n.push(ue(c,u,r)):i(u,c);o(s.query,c)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},fl=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of ll(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:p},m)=>{e[p.id]?.rowPermissions!==void 0&&(a=m)}),a<0)continue;const c=s.relations.slice(0,a+1),u=c.map(({property:p})=>p.name).join("_");if(o.has(u))continue;o.add(u);let l={};for(const p of[...c].reverse())l={[p.property.name]:{schema:p.targetSchema.id,query:l}};i.push(l)}return i},Ut=(t,e,r,n,o,i)=>Le(t)?mt(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Ut(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Ut(a,e,r,n,o,i)])),Io=(t,e,r,n,o,i)=>({...t,...t.query?{query:Ut(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Io(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:Io(s,e,r,n,o,i))}:{}}),mt=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return oe(t);if(!t.schema){const f=oe(t);return f.from&&(f.from=mt(f.from,e,r,n,new Set,i)),f}n&&zr(t,e,r,i);const s=Je(e,t.schema),a=o.has(t.schema),c=new Set(o).add(t.schema),u=oe(t);u.query&&(u.query=Ut(u.query,e,r,n,new Set,i)),u.preds&&(u.preds=u.preds.map(f=>Io(f,e,r,n,new Set,i))),u.from&&(u.from=mt(u.from,e,r,n,new Set,i));const l=a||t.from?void 0:s?.rowPermissions,p=(t.from?[]:fl(t,e,r)).map(f=>Ut(Wr(f,t.version),e,r,!1,c,i));l&&p.push(Ut(Wr(oe(l),t.version),e,r,!1,c,i));const m=[u.query,...p].filter(f=>f!==void 0&&Object.keys(f).length>0);return m.length===1?u.query=m[0]:m.length>1?u.query={$and:m}:delete u.query,u},ml=(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:c})=>a===s||c===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},Ks=(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")}},Js=(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=Ks(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)},yl=(t,e)=>{const r=Gi(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=Ks(e,t.timeZone);let o=Js({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Js({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},hl=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[yl(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},bo=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(bo):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,bo(r)])):t,Xs=t=>Ba("sha256").update(JSON.stringify(bo(t))).digest("hex"),gl=t=>Xs({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),Al=(t,e)=>Xs({namespace:t,source:e}),Ro=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(Ro)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Ro(r)])}:t,No=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(No);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,No(r)]))}},wl=t=>JSON.stringify(Ro(t)),$l=t=>{const e=No(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},El=Number.MAX_SAFE_INTEGER;class _l{#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:${gl(e)}`}#o(e,r){return`${this.#t}:source:${Al(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return $l(r)}async set(e,r,n){const o=this.#n(e),i=wl(r),s=n.expiresAt?.getTime(),a=s??El,c=this.#e.multi();s===void 0?c.set(o,i):c.set(o,i,{PXAT:s});for(const u of new Set(n.sources)){const l=this.#o(e.namespace,u);c.zRemRangeByScore(l,0,Date.now()),c.zAdd(l,{score:a,value:o})}await c.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 Sl=async(t={})=>{const e=Va(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new _l(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function Il(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 bl=({namespace:t,...e})=>e,Rl=async t=>Sl({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class Nl{create;#e=new Map;constructor(e=Rl){this.create=e}async get(e){Il(e);const r=bl(e),n=this.#e.get(r.id);if(n){if(!Ho(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 Zs=new Nl,ea=t=>Zs.get(t),Ol=()=>Zs.close(),Tl=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 ea(t);await r.store.invalidateSource(r.namespace,e)},Pl=Object.freeze({invalidateSource:Tl}),Ll=()=>{},Kr=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),ir=(t,e,r)=>{if(It(t)){e.push(t.plan);return}if(Fi(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)ir(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))ir(n,e,r)},sr=(t,e,r)=>{if(t.kind==="window"){sr(t.input,e,r);for(const n of t.partitionBy)sr(n,e,r);return}if(t.kind==="operator"){ir(t.query,e,r),t.input&&sr(t.input,e,r);for(const n of t.inputs??[])sr(n,e,r)}},Ee=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 Ee(o))r(i);else if(t.sourcePlan)for(const o of Ee(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=[];ir(t.query,n,e),ir(t.having,n,e);for(const o of t.projections)sr(o.expression,n,e);for(const o of n)for(const i of Ee(o))r(i);return[...e.values()]},ar=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()]},ta=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})}},Cl=(t,e)=>{const r=[];for(const n of t){const o=Kr(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Oo=async(t,e,r,n=Ll)=>{t=ra(t),r.signal?.throwIfAborted();const o=r.cache?Cl(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),ta(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 ta(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=hl(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:c})=>c))],...a?{expiresAt:a}:{}})}catch{}return s},ra=t=>({...t,sql:_p(t.sql)}),Dl=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")},kl=(t,e,r)=>{const n=Dl(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}},na=async(t,e)=>{if(!ft(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(g=>ft(e.permissions,t.schema.id,g)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:g})=>g===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:kl(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(g=>({pred:g.name,name:g.name}))},a=mt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),c=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}),u=qe(c,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(g,$)=>ft(e.permissions,g.id,$)}),l=new Set(Ee(u).map(g=>e.schemaMappings.findSource(g.schemaId,g.source,g.connectionId)?.connectionId).filter(g=>!!g));if(l.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...l].join(", ")}`);const p=[...l][0]??o,m=p&&e.providerForConnection?e.providerForConnection(p):i,f=Ae(u,m,e.operators),y=e.onCompiled?.(f,c,m,p),h=await Oo(f,Ee(u),{provider:m,...p?{connectionId:p}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return so(h,u.rowIdentity)},oa=t=>String(t),Ul=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${oa(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=oa(r),o},ia=(t,e)=>`${t}:${String(e)}`,Ml=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 ql{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=ia(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(Ni(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=Ml(s);let c,u;const l=new Promise((m,f)=>{c=m,u=f}),p=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return p.loads.set(n,{id:r,resolve:m=>c?.(m),reject:m=>u?.(m)}),this.#n.set(e,p),this.#r.set(n,l),this.#s(),l};#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),c=i._id===a?i:{...i,_id:a};o.set(ia(e.schema.id,s),c)}}for(const[i,s]of e.loads){const a=o.get(i)??Ul(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 jl=(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})}},xl=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=r.get(i.type),a=jl(o[i.name],i),c={property:i,requestEntity:n},u=s.normalizeResult?await s.normalizeResult(a,c):a,l=s.hydrateResult;if(!l){o[i.name]=u;return}o[i.name]=i.isArray&&Array.isArray(u)?await Promise.all(u.map(p=>l(p,c))):await l(u,c)}))}))},sa=5,Bl=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Vl=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Yl=(t,e)=>{const r=Ya(e);t._title=t[r.name]??t._id},Fl=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Vl(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Ql=(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})},vl=async(t,e,r)=>{const n=new ql(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 c=a.expandEntities&&i<sa;return xl(a.rows,a.properties,r.semanticTypes,c?n.load:(u,l)=>Promise.resolve(l))}));for(const a of o)if(a.schema)for(const c of a.rows)Yl(c,a.schema);if(i>=sa)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const c of a.properties){if(c.primal_type!=="entity"&&c.primal_type!=="object"||!c.ref)continue;const u=r.resolveSchema(c.ref);for(const l of a.rows){if(!(c.name in l))continue;const p=l[c.name],m=c.isArray?Array.isArray(p)?p:[p]:[p];for(const[f,y]of m.entries()){if(!Bl(y))continue;const h=Fl(y,u);c.isArray?m[f]=h:l[c.name]=h,Ql(s,u,h,!c.isArray)}c.isArray&&(l[c.name]=m)}}o=[...s.values()]}},aa=async(t,e,r)=>{const n=t.map(o=>({...o}));return await vl(n,e,r),n},To=t=>`'${t.replaceAll("'","''")}'`,ca=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}'`},cr=(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():To(t.toString());if(typeof t=="string")return e==="mysql"?ca(t):To(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?ca(r):To(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}`)},Hl=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?cr(e[o],"clickhouse"):r}),Gl=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?cr(e[o],"oracle"):r}),zl=(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 c=Number(a)-1;if(c in e){r+=cr(e[c],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},Po=(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+=cr(e[o],r),o+=1;continue}n+=a}}return n},Wl=(t,e)=>Po(t,e,"mysql"),Lo=(t,e)=>Po(t,e,"snowflake"),Kl=(t,e)=>Po(t,e,"dameng"),Jl=(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 c=Number(a);if(c in e){r+=cr(e[c],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},nt=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),ur=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`)},je=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},ve=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Ue=(t,e)=>{const r=ve(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},ua=t=>{const e=Ue(t,"table_name"),r=ve(t,"table_database"),n=ve(t,"table_schema"),o=Ue(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"}},Xl=t=>t.map(ua),yt=async(t,e)=>{e.signal?.throwIfAborted(),ur(e);const r=[],n=c=>{const u=t.parameter(r.length,c);return r.push(c),u},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&je(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&&je(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&&je(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&&je(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(),Xl(a)},Co=t=>{if(ur(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},Jr=(t,e)=>{const r=ve(t,e);return typeof r=="string"?r:""},Zl=t=>{const e=Ue(t,"column_type"),r=ve(t,"type_length"),n=ve(t,"type_precision"),o=ve(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},da=t=>{const e=ve(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:Ue(t,"column_name"),type:Zl(t),comment:Jr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},ef=(t,e)=>{const r=[],n=u=>{const l=t.parameter(r.length,u);return r.push(u),l},o=n(e.table),{database:i,schema:s}=e;let a,c;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&je(t,"schema");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&je(t,"database");const u=`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 ${u} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,c=`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 ${u} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const u=i!==void 0?`${t.quoteIdentifier(i)}.`:"",l=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,p=`JOIN ${u}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${u}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 ${u}INFORMATION_SCHEMA.TABLES c ${p}LEFT JOIN ${u}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 ${l}`,c=`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 ${u}sys.indexes i JOIN ${u}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 ${u}INFORMATION_SCHEMA.COLUMNS c ${p}JOIN ${u}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${u}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 ${l} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const u=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,l=`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 ${u}.TABLES c WHERE ${l}`,c=`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 ${u}.COLUMNS c WHERE ${l} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&je(t,"database");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&je(t,"schema");const u=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 = ${u}`,c=`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 = ${u} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:c,parameters:r}},pa=(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(".")},Mt=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},Do=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=pa(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 Mt(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},tf=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[p]=await Mt(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!p)throw new d("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=Ue(p,"table_database"),n??=Ue(p,"table_schema")}const o=pa(t,{name:e.table,database:r,schema:n}),i=await Mt(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,c=!1,u="",l="table";for(const p of i){const m=ve(p,"col_name"),f=ve(p,"data_type"),y=(m==="# Partition Information"||m==="# Detailed Table Information")&&!f;(m===""||y)&&(a=!1),y&&m==="# Detailed Table Information"&&(c=!0),a?s.push({name:Ue(p,"col_name"),type:Ue(p,"data_type"),comment:Jr(p,"comment")}):c&&m==="Comment"?u=Jr(p,"data_type"):c&&m==="Type"&&f==="VIEW"&&(l="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return Do(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:l,comment:u}})},rf=async(t,e)=>{e.database!==void 0&&je(t,"database"),e.schema!==void 0&&je(t,"schema");const n=(await Mt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(da);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return Do(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Xe=async(t,e)=>{if(e.signal?.throwIfAborted(),Co(e),t.kind==="databricks")return tf(t,e);if(t.kind==="maxcompute")return rf(t,e);const{tableSql:r,columnSql:n,parameters:o}=ef(t,e),i=await Mt(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={...ua(s),comment:Jr(s,"table_comment")},c=(await Mt(t,e,n,o)).map(da);return Do(t,e,{columns:c,tableInfo:a})},nf=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}`},of=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",la=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class sf{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 nt("@clickhouse/client",r)});return e({url:nf(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}:${of(r)}}`}displayQuery(e,r){return Hl(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}`,la(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return yt(this,e)}describeTable(e){return Xe(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,c)=>[`p${c}`,la(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 c=JSON.parse(a);if(typeof c!="object"||c===null||Array.isArray(c))throw new Error("ClickHouse provider expected object rows");return c}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const af=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),cf=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??(af(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)}`)},uf=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 df{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 nt("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(cf(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 Lo(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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(uf)}),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 Xe(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),ur(e);const r=u=>this.execute({sql:u,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[u]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!u)throw new Error("Databricks current namespace was not returned");n??=Ue(u,"table_database"),o??=Ue(u,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),c=new Map;for(const u of s){const l=Ue(u,"tableName");c.set(l,{name:l,database:n,schema:o,type:"table"})}for(const u of a){const l=Ue(u,"viewName");c.set(l,{name:l,database:n,schema:o,type:"view"})}return[...c.values()].sort((u,l)=>u.name.localeCompare(l.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const fa=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}`)},pf=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class lf{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={...pf(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${vo()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw nt("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 Kl(e,r.map(fa))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 yt(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Xe(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(fa),{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 Wl(t,e)},dateBucket(t,e){const r={second:"%Y-%m-%d %H:%i:%s",minute:"%Y-%m-%d %H:%i:00",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,n){const o=this.quoteIdentifier(e),i=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${i} ${n==="string"?"VARCHAR(4000)":"JSON"} PATH '$')) AS ${o}`,valueExpression:`${o}.${i}`}}},ff={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Xr{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 nt("mysql2",r)});return e({...ff,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,o){const i=X.expandArray?.bind(X);if(!i)throw new Error("MySQL-compatible array expansion is unavailable");return i(e,r,n,o)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return yt(this,e)}describeTable(e){return Xe(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 mf extends Xr{kind="doris";constructor(e={}){super(e)}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}`}}}class yf extends Xr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class hf{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(),ur(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&je(this,"database"),e.schema!==void 0&&je(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Ue(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Co(e),!this.#e.describeTable)return Xe(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class gf extends Xr{kind="mysql";constructor(e={}){super(e)}}const ma=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}`)},Af=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class wf{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 Gl(e,r.map(ma))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 nt("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 yt(this,e)}describeTable(e){return Xe(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(ma),{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?Af(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 $f{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{default:e}=await import("pg").catch(r=>{throw nt("pg",r)});return new e.Pool(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 zl(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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})`}normalizeStringArray(e){const r=`to_jsonb(${e})`;return`(CASE WHEN ${e} IS NULL THEN ARRAY[]::text[] WHEN jsonb_typeof(${r}) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(${r})) ELSE ARRAY[${r} #>> '{}'] END)`}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 yt(this,e)}describeTable(e){return Xe(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 ya=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}`)},Ef=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class _f{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 nt("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 Lo(e,r.map(ya))}dateBucket(e,r){if(!new Set(["second","minute","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 yt(this,e)}describeTable(e){return Xe(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(ya);return new Promise((i,s)=>{const a=e.signal,c={};let u=!1;const l=m=>{u||(u=!0,a?.removeEventListener("abort",p),m())},p=()=>{c.current?.cancel(),a&&l(()=>s(Ef(a)))};a?.addEventListener("abort",p,{once:!0}),c.current=n.execute({sqlText:e.sql,binds:o,complete:(m,f,y)=>{if(m){l(()=>s(m));return}if(!(r&&y===void 0)&&!Array.isArray(y)){l(()=>s(new Error("Snowflake provider expected an array result")));return}const h=r?f.getNumUpdatedRows?.():void 0;l(()=>i({rows:y??[],...typeof h=="number"&&h>=0?{affectedRows:h}:{}}))}}),a?.aborted&&p()})}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 Sf=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}}},If=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}`)},bf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),Rf=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),Nf=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 Of{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 nt("mssql",n)}),r=new e.ConnectionPool(Sf(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`${Nf(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 Jl(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 yt(this,e)}describeTable(e){return Xe(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}`,If(i))),new Promise((i,s)=>{const a=e.signal;let c=!1;const u=p=>{c||(c=!0,a?.removeEventListener("abort",l),p())},l=()=>{o.cancel(),a&&u(()=>s(bf(a)))};a?.addEventListener("abort",l,{once:!0}),o.query(e.sql).then(p=>{if(!Array.isArray(p.recordset)&&!(r&&p.recordset===void 0)){u(()=>s(new Error("SQL Server provider expected an array result")));return}u(()=>i({rows:p.recordset??[],...p.rowsAffected?{affectedRows:p.rowsAffected.reduce((m,f)=>m+f,0)}:{}}))},p=>u(()=>s(Rf(p)))),a?.aborted&&l()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class Tf extends Xr{kind="starrocks";constructor(e={}){super(e)}arrayContains(e,r){return`array_contains(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`, UNNEST(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}}const xe=t=>{const{id:e,kind:r,...n}=t;return n},Pf=Object.freeze([{kind:"mysql",create:t=>new gf({connection:xe(t)})},{kind:"doris",create:t=>new mf({connection:xe(t)})},{kind:"gbase",create:t=>new yf({connection:xe(t)})},{kind:"starrocks",create:t=>new Tf({connection:xe(t)})},{kind:"maxcompute",create:t=>new hf(xe(t))},{kind:"postgresql",create:t=>new $f({connection:xe(t)})},{kind:"clickhouse",create:t=>new sf(xe(t))},{kind:"databricks",create:t=>new df({connection:xe(t)})},{kind:"dameng",create:t=>new lf({connection:xe(t)})},{kind:"snowflake",create:t=>new _f({connection:xe(t)})},{kind:"sqlserver",create:t=>new Of({connection:xe(t)})},{kind:"oracle",create:t=>new wf({connection:xe(t)})}]);class ha{#e=new Map;constructor(e=Pf){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 ga=new ha,Aa=(t,e=ga)=>e.create(t);class Lf{create;#e=new Map;#t=new Set;#r=[];constructor(e=Aa){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&Ho(r.connection,e))return r.provider;const n=this.create(e);return this.#e.set(e.id,{connection:{...e},provider:n}),r&&r.provider!==n&&this.#n(r.provider),n}#n(e){const r=Promise.resolve().then(()=>e.close()).then(()=>{this.#t.delete(r)},n=>{this.#t.delete(r),this.#r.push(n)});this.#t.add(r)}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()),...this.#t]),n=this.#r.splice(0);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 Zr=new Map,Cf=t=>{const e=Zr.get(t);if(e)return e;const r=new Lf(n=>Aa(n,t));return Zr.set(t,r),r},en=(t,e=ga)=>Cf(e).get(t),Df=async()=>{const t=[...Zr.values()];Zr.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")},wa=async()=>{const e=(await Promise.allSettled([Df(),Ol()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},kf=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=en(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},Uf=async t=>{t.signal?.throwIfAborted(),ur(t);const e=en(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},Mf=async t=>{t.signal?.throwIfAborted(),Co(t);const e=en(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},qf=Object.freeze({runSQL:kf,getTableList:Uf,describeTable:Mf,close:wa}),jf=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:zo,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:ln,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:Go,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:gt,sqlType:"VARCHAR"}}},xf=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Bf=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return ze(xf(t),zo);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:ze(r,ln)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?ze(r,Go):null}case"string":return typeof t=="string"?ze(t,gt):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?ze(t.toString(),gt):typeof t=="symbol"?ze(t.description??"",gt):typeof t=="function"?ze(t.name,gt):ze(JSON.stringify(t),gt)}},Vf=t=>{if(t==null)return null;if(t instanceof Date)return ze(t,ln);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return Qa(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class cn{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await Fa.create(":memory:"),r=await e.connect();return new cn(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 Lo(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(jf),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 c of o){const u=Bf(a[c.name],c);u===null?s.appendNull():s.appendValue(u,c.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(Vf));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const ko="__sdb_total__",Yf="__sdb_total_source__",Uo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Ff=t=>{const e={...t};return delete e.limit,delete e.page,e},Mo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(ko)} FROM ${e.tableAlias(`(${t.sql})`,Yf)}`,parameters:t.parameters}),tn=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[ko]??e[ko.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},qt="__semanticdb_coordinator__",$a=(t,e)=>{const r=new Set;for(const n of Ee(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]},dr=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>$a(r,e))).size>1||!!(t.sourcePlan&&dr(t.sourcePlan,e)),Qf=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),vf=(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"},Ea=(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"?vf(e,n):"string";return{name:n,kind:i}})},Hf=(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=>Qf(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Gf=(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",qr(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")},_a=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:jr(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},rn=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&&dr(t.sourcePlan,e.schemaMappings)){const s=await rn(t.sourcePlan,e),a=await cn.create();try{const c="__federated_source";await a.materialize(c,Ea(t.sourcePlan,s.rows),s.rows);const u={...t,source:c};delete u.sourcePlan,delete u.sourceLogicform,delete u.connectionId;const l=Ae(u,a,e.operators),p=Mo(Ae(Uo(u),a,e.operators),a),m=e.onCompiled({compiled:l,connectionId:qt,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,connectionId:qt,provider:a,type:"total",logicform:e.logicform})("database");const y=await a.execute({...p,...e.signal?{signal:e.signal}:{}});m("database");const h=await a.execute({...l,...e.signal?{signal:e.signal}:{}});return{rows:_a(h,t),total:tn(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=$a(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 c=a[0],u=e.providerForConnection(c);r.set(c,u.kind);const l=Ae(s,u,e.operators),p=e.onCompiled({compiled:l,connectionId:c,provider:u,type:"computation",logicform:e.logicform}),m=await Oo(l,Ee(s),{provider:u,connectionId:c,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},p),f=await dt(m,s.projections,e.operators);return{child:s,rows:Gf(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 cn.create();try{const s=n.flatMap(({rows:h})=>h),a=[];for(const[h,{child:g,rows:$}]of n.entries()){const A=`__federated_branch_${h}`;await i.materialize(A,Ea(g,s),$),a.push(Hf(g,A))}const c={...t,subplans:a},u=Ae(c,i,e.operators),l=Mo(Ae(Uo(c),i,e.operators),i),p=e.onCompiled({compiled:u,connectionId:qt,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:l,connectionId:qt,provider:i,type:"total",logicform:e.logicform})("database");const f=await i.execute({...l,...e.signal?{signal:e.signal}:{}});p("database");const y=await i.execute({...u,...e.signal?{signal:e.signal}:{}});return{rows:_a(y,t),total:tn(f),connections:[...r].map(([h,g])=>({connectionId:h,provider:g}))}}finally{await i.close()}},zf=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),nn=t=>!H(t)||!Array.isArray(t.properties)?[]:t.properties.filter(H),Sa=new Set(["second","minute","hour","day","week","month","quarter","year"]),Wf={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},Ia=(t,e)=>{const r=e[t];return H(r)?r:Object.values(e).find(n=>H(n)&&(n.id===t||n._id===t))},ba=(t,e)=>{const r=t&&e?nn(Ia(t,e)).find(o=>o.type==="timestamp"):void 0,n=r?.name??r?.id??r?._id;return typeof n=="string"&&n.length>0?n:void 0},Ra=(t,e,r)=>{const n=Ia(t,r);if(!n)return;const i=nn(n).map(s=>{const c=[s.id,s._id,s.name].filter(u=>typeof u=="string").filter(u=>e===u||e.startsWith(`${u}_`)).sort((u,l)=>l.length-u.length)[0];return c?{property:s,key:c}: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"?Ra(i.property.ref,e.slice(i.key.length+1),r):void 0},jt=(t,e,r)=>{const n=(o,i,s)=>{const u=nn(r[o]).map(y=>{const h=typeof y.id=="string"?y.id:void 0,g=typeof y.name=="string"?y.name:void 0,A=[h,g].filter(_=>!!_&&(i===_||i.startsWith(`${_}_`))).sort((_,E)=>E.length-_.length)[0];return A?{property:y,key:A}:void 0}).filter(y=>!!y).sort((y,h)=>h.key.length-y.key.length)[0];if(!u)return;const l=String(u.property.id??u.property.name),p=i===u.key?"":i.slice(u.key.length+1);if(!p)return l;const m=typeof u.property.ref=="string"?u.property.ref:void 0;if(!m||s.has(m))return;const f=n(m,p,new Set(s).add(m));return f?`${l}_${f}`:void 0};return n(t,e,new Set([t]))},qo=(t,e,r)=>{const n=nn(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 qo(n.ref,e.slice(n.id.length+1),r)}},Na=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),H=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Oa=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),Ta=t=>{if(!H(t))return t;if(H(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),Jf=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(c=>H(c)&&(c.id===t||c._id===t));if(!H(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:H(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(c=>{if(!H(c)||typeof c.name!="string")return;const u=c.codeLength??c.code_length;return Number.isInteger(u)&&Number(u)>0?{name:c.name,codeLength:Number(u)}:void 0});if(i.length===0||i.some(c=>c===void 0))return;const s=o[0],a=Array.isArray(n)?H(s)&&s.use_full_length===!0?"zero-padded":"compact":H(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(c=>c!==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,c)=>a+c.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})},Zf=(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}))]},jo=(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=>H(y)?jo(y,e):y);continue}if(!H(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!H(i.query)||!Kf(s)){r[o]=i;continue}const a=i.entity_level,c=typeof a=="string"&&a.length>0?a:Xf(i.schema,s,e);if(!c){r[o]=i;continue}const{entity_id:u,entity_level:l,...p}=i,m=jo(i.query,e),f=Object.keys(p).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(m).length>0||f.length>0)&&(r[o]={...p,query:m}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:c}},condition:s})}return Zf(r,n)},em=(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}},Pa=(t,e)=>{if(!H(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(!H(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(!H(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}:{}}},Ze=(t,e,r)=>{if(Array.isArray(t))return t.map(c=>Ze(c,e,r));if(!H(t))return t;const n=Ta(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[c,u]of Object.entries(o))c==="skip"||c==="_snapshot"||c==="_snapshots"||(s[c]=Ze(u,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const c=o.groupby;s.groupby=c.map(u=>{if(!H(u))return u;const l=Ze(u,e,i);if(!H(l))return l;const{_id:p,level:m,...f}=l;if(typeof p=="string"&&p.startsWith("$")){const h=p.slice(1);if(!Sa.has(h))throw new d("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${p}`,{groupby:p});const g=ba(i,e);if(!g)throw new d("LEGACY_TIME_GROUPBY_TIMESTAMP_REQUIRED",`Legacy time groupby ${p} requires a timestamp Property in Schema ${i??"(unknown)"}`,{groupby:p,schemaId:i});return{...f,pred:g,operator:"$dateBucket",args:{...H(f.args)?f.args:{},granularity:h},...f.name===void 0?{name:`${g}(${h})`}:{}}}const y={...f,...f.pred===void 0&&typeof p=="string"?{pred:p}:{}};return typeof m=="string"&&(y.operator="$dateBucket",y.args={...H(y.args)?y.args:{},granularity:m}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const c=o.limit;a===0?delete s.skip:typeof c=="number"&&Number.isInteger(c)&&c>0&&a%c===0?s.page=a/c+1:s.skip=a}else a!==void 0&&(s.skip=Ze(a,e,i));if(o.operator&&typeof o.operator=="string"){const c=em(o.operator,H(s.args)?s.args:{});c.operator&&(s.operator=c.operator),s.args=c.args;const u=typeof o.pred=="string"&&o.pred.startsWith("$")?o.pred.slice(1):"",l=Wf[u];if(o.operator==="$count"&&(Sa.has(u)||l)){const p=ba(i,e);if(!p)throw new d("LEGACY_TIME_COUNT_TIMESTAMP_REQUIRED",`Legacy $count($${u}) requires a timestamp Property in Schema ${i??"(unknown)"}`,{schemaId:i,pred:o.pred});s.operator="$countDistinct",s.pred=l?{operator:`$${l}`,pred:p}:{operator:"$dateBucket",pred:p,args:{granularity:u}}}if(o.operator==="$comp"||o.operator==="$compabs"){const p=H(s.args)?s.args.preds:void 0;if(!Array.isArray(p)||p.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const m={operator:"$subtract",pred:p,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?m:p,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const p=H(s.params)?s.params:s.args;s.operator="$case",s.args=Pa("$switch",p),delete s.params}if(o.operator==="$piecewise"){const p=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&p&&Ra(i,p,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:p});const m=H(s.params)?s.params:H(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(m.cases)?Pa("$piecewise",m):{mode:"auto",buckets:Number.isInteger(m.buckets)?m.buckets:10},delete s.params}zf.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:Ze(o.params,e,i)}:Ze(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(c=>Ze(c,e,i)),H(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...H(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...H(s.args)?s.args:{},options:o.$options},delete s.$options):typeof o.$eq=="string"&&typeof o.$options=="string"?(s.args={...H(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&Oa(o.$gte)&&Oa(o.$lte)&&delete s.$options,o.query&&H(o.query)&&(s.query=tm(o.query,e,i)),s},tm=(t,e,r)=>{const n=Ze(t,e,r);for(const[o,i]of Object.entries(n))n[o]=Ta(i);return jo(n,e)},La=(t,e)=>{const r=H(t)?t:void 0,n=Ze(t,e);if(!H(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],La(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?rm(n,e):n},rm=(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 c of n)H(c)&&typeof c.schema=="string"&&i.add(c.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(c=>H(c)&&typeof c.pred=="string"?jt(o,c.pred,e):void 0):[];for(const c of i)if(Array.isArray(r.groupby)&&r.groupby.map((u,l)=>{if(!H(u)||typeof u.pred!="string")return u;const p=c===o?jt(c,u.pred,e):jt(c,qo(o,s[l]??"",e)??u.pred,e);if(!p)return u;const m=p.split("_").at(-1)??u.pred;return{...u,pred:p,name:m}}),H(r.query))for(const u of Na(r.query)){const l=jt(o,u,e);if(!(c===o?l:jt(c,(l&&qo(o,l,e))??u,e))&&c===o)throw new Error(`Cannot align legacy query field ${u} in Schema ${c}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((c,u)=>{if(!H(c)||typeof c.pred!="string")return c;const l=s[u];return l?{...c,pred:l}:c})),H(r.query)){const c=r.query,u=Na(c).map(l=>[jt(o,l,e)??l,c[l]]);a.query=Object.fromEntries(u)}return a},nm=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(H(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,"$")},xo=t=>{if(Array.isArray(t))return t.map(xo).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,xo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},om=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},im=(t,e,r)=>{const n=t.comparable;if(!r||n!=null&&typeof n!="string")return t.comparable;const o=n==="asc"?1:n==="desc"?-1:n==null&&t.is_comparable===!0?t.comparable_order===-1?-1:1:void 0;if(o===void 0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!e)return;const i=e.map(s=>Array.isArray(s)?s[0]:s);if(!(i.length===0||i.some(s=>typeof s!="string")))return{values:[...new Set(i)],direction:o}},sm=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}},am=(t,e=[],r=!0)=>{const n=ge(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const c=xo(a),u=c,p=(Array.isArray(u.properties)?u.properties:[]).some(_=>_.is_observation===!0)||u.is_observation===!0,m=u.is_snapshot===!0,f=typeof c.id=="string"&&c.id.length>0?c.id:r&&typeof c._id=="string"&&c._id.length>0?c._id:c.id,{properties:y}=c,h=Object.fromEntries(Object.entries(c).filter(([_])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(_):_!=="properties")&&_!=="properties"&&!i.has(_))),g=y.map(_=>{const E=_,w=typeof E.id=="string"&&E.id.length>0?E.id:r&&typeof E._id=="string"&&E._id.length>0?E._id:E.id,{udf:R,...C}=E,k=r?om(E):void 0,T=im(E,k,r),G=sm(R),Q=r&&T!==void 0&&E.type==="string"?"category":E.type==="object"?"entity":E.type,q=Q==="entity"||E.primal_type==="entity"||E.primal_type==="object";return{...r?Object.fromEntries(Object.entries(C).filter(([Y])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order","comparable","enum"].includes(Y)&&(Y!=="level"||q))):C,type:Q,...r&&k&&!Array.isArray(E.constraints?.enum)?{constraints:{...E.constraints,enum:k}}:{},...E.primal_type==="object"?{primal_type:"entity"}:{},...w!==void 0?{id:w}:{},...G!==void 0?{udf:G}:{},...T!==void 0?{comparable:T}:{}}});let $={};for(const _ of n)for(const E of _.schemaMetadata?.keys??[])c[E]!==void 0&&($={...$,[E]:c[E]});for(const _ of n)$={...$,..._.normalizeLegacySchema?.({source:c,properties:g})};const A={...h,...f!==void 0?{id:f}:{},properties:g,...r&&(m||p)?{temporalSemantics:"snapshot"}:{},...$};o[s]=A}return o},Ca=Symbol("legacy-empty-source"),Da=t=>t!==void 0&&Ca in t,ka=(t,e,r,n=[],o=r?[r]:[])=>{const i=[...e],s=new Set(n);for(const[a,c]of Object.entries(t)){const u=c,l=typeof u.id=="string"&&u.id.length>0?u.id:typeof u._id=="string"&&u._id.length>0?u._id:a;if(i.some(y=>y.schemaId===l))continue;const p=typeof u.db=="string"&&u.db.trim().length>0?u.db.trim():void 0;if(typeof u.from!="string"||u.from.trim().length===0){if(p){i.push({schemaId:l,connectionId:p,source:l});continue}for(const y of new Set(o.filter(Boolean))){const h={schemaId:l,connectionId:y,source:`legacy-empty-schema:${l}`,[Ca]:!0};i.push(h)}continue}const m=p??r;if(!m){if(s.has(l)||s.has(a))throw new d("LEGACY_SCHEMA_FROM_CONNECTION_REQUIRED",`Cannot create a Schema mapping for legacy Schema ${l}: provide Schema.db or one unambiguous connection`,{schemaId:l});continue}const f=u.from.trim();i.push({schemaId:l,connectionId:m,source:`legacy-schema-from:${l}`,sourceSql:f})}return i},Ua=(t,e)=>[...ge(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],on=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),Ma=t=>t instanceof Error?t:new Error(String(t)),cm=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,um=(t,e,r={},n="zh-CN",o)=>{const i=Ma(t);return{errorCode:"100",error:cm(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}:{}}},dm=(t,e,r)=>{const n=e.projections.map(({name:u})=>u),o=new Map((e.columnProperties??[]).map(u=>[u.name,u])),i=[],s=(u,l)=>{const p=r.parameter(i.length,l);i.push(l);const m=o.get(u)?.type;return m&&(m==="date"||m==="timestamp")&&r.castValue?r.castValue(p,m):p},a=u=>`SELECT ${n.map(l=>`${s(l,u[l])} AS ${r.quoteIdentifier(l)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(u=>`NULL AS ${r.quoteIdentifier(u)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},pm=(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),...Ee(r)];for(const i of o){const s=Kr(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},lm=async(t,e,r)=>{await t?.({...e,partialResult:r})},fm=(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)}),Bo=(t,e)=>{if(e.connectionId)for(const r of Ee(t)){const n=Kr(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})}},qa=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 Vo(o))e.add(i)};return r(t),[...e]},Vo=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...Vo(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:Vo(r))]:e},ja=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??wr(Ua(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&&nm(t);const c=a?La(t,e.schemas):t,u=e.schemaMappings.definitions(),l=qa(c),p=[...new Set(u.filter(({schemaId:N})=>l.includes(N)).map(({connectionId:N})=>N))],m=e.connectionId??(p.length===1?p[0]:void 0)??e.provider.kind,f=a?ka(e.schemas,u,m,l):u,y=f.length===u.length?e.schemaMappings:new Tr(f,e.schemaMappings.plugins),h={...e,locale:r,localeRegistry:n,schemaMappings:y,schemas:am(e.schemas,o,a)},g=mr.now(),$=h.semanticTypes===void 0?ho(o):h.semanticTypesResolved?h.semanticTypes:Ls(h.semanticTypes,o);let A=h.operators??Be(o);if(h.operators&&!h.operatorsResolved)for(const N of o)for(const D of N.operators??[])if(A.has(D.name)){if(A.get(D.name)!==D)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${D.name}`,{operator:D.name,plugin:N.name})}else A.register(D);const _=h.schemaMappings,E=N=>Ee(N).some(D=>Da(Kr(D,_))),w=new Date,R=new Map,C=new Map,k=[],T=new Set,G=N=>{const D=JSON.stringify(N);T.has(D)||(T.add(D),k.push(N),Q={...Q,schemaMappingSelections:[...k]})};let Q={provider:h.provider.kind};const q=[],U=new WeakMap,Y=new Map;h.connectionId&&Y.set(h.connectionId,h.provider.kind);const z=(N,D,P,M=D,K=h.provider,x=h.connectionId)=>{x&&x!==qt&&Y.set(x,K.kind);const pe=q.length;q.push(fm(ra(N),K,D,P,h.locale??"zh-CN",n,M,x)),Q={...Q,sqls:[...q],providers:[...Y].map(([le,re])=>({connectionId:le,provider:re}))};const ee=le=>{q[pe]={...q[pe],executionSource:le},Q={...Q,sqls:[...q]}};return U.set(N,ee),ee},v=(N,D)=>Oo(N,D,h,U.get(N)),W=async(N,D={})=>{Q={...Q,...D},await lm(h.onProgress,N,Q)},De=N=>Rs(Ic(N,h.schemas),$,o),Me=new Map,de=N=>{const D=Me.get(N);return D||(Je(h.permissions,N),De(N))},fe=N=>{if(N.schema)return de(N.schema);if(N.from)return fe(N.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},be=N=>{if(N.schema)return De(N.schema);if(N.from)return be(N.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},S=async()=>{const N=Object.values(h.schemas).filter(re=>re.is_calendar===!0);if(N.length!==1)return Object.freeze({});const D=N[0];if(!D)return Object.freeze({});const P=_.list(D.id),M=P.find(({connectionId:re})=>re===h.connectionId)??P[0];if(!M)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${D.id}`,{schemaId:D.id});if(Da(M))return Object.freeze({calendar:Object.freeze([])});const K=h.providerForConnection?.(M.connectionId)??h.provider,{onProgress:x,executionContext:pe,...ee}=h,le=await ja({version:"2.0",schema:D.id,limit:-1},{...ee,provider:K,connectionId:M.connectionId,operators:A,operatorsResolved:!0,executionContext:Object.freeze({})});q.push(...le.sqls.map(re=>({...re,type:"semantic-resolution",explain:n.translate(h.locale??"zh-CN","sql.semanticResolution")})));for(const re of le.providers)Y.set(re.connectionId,re.provider);for(const re of le.schemaMappingSelections)G(re);return Object.freeze({calendar:Object.freeze(le.result.map(({_id:re,..._e})=>Object.freeze(_e)))})},I=e.executionContext??await S();A=A.withExecutionContext(I);const b={plugins:o,resolveSchema:de,onSchemaMappingSelection:G,...h.connectionId?{preferredConnectionId:h.connectionId}:{},canUsePropertyRowIdentity:(N,D)=>ft(h.permissions,N.id,D)},L=(N,D)=>{const P=ns(qe(N,fe(N),A,_,b),D);return Me.set(P.id,P),P},j=async(N,D,P)=>{const M=`${N.id}:${D.id}:${P.toISOString()}`,K=R.get(M);if(K)return K;const x=(async()=>{const pe=ge(o).find(me=>me.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!pe)return;const ee=pe({logicform:c,rootSchema:N,rootProperty:D,requestedUpperBound:P,now:w,...h.timeWatermark?{defaultPolicy:h.timeWatermark}:{},resolveSchema:de,inferPropertyPath:(me,Oe,Te)=>Hs(me,Oe,Te,de)}),le=mt(ee,h.permissions,de,!1,new Set,o),re=await lt(le,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L}),_e=qe(re,N,A,_,b);if(E(_e))return;let Se;if(dr(_e,_)){const me=h.providerForConnection;if(!me)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");Se=(await rn(_e,{logicform:re,operators:A,schemaMappings:_,providerForConnection:me,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Te,logicform:we,provider:Re,connectionId:Bt})=>z(Te,"semantic-resolution",we,"time-watermark",Re,Bt)})).rows}else{Bo(_e,h);const me=Ae(_e,h.provider,A);z(me,"semantic-resolution",re,"time-watermark"),Se=await v(me,Ee(_e))}const he=Se[0]?.__timeWatermark__??Object.values(Se[0]??{})[0];if(he==null||!(he instanceof Date)&&typeof he!="string"&&typeof he!="number")return;const ne=he instanceof Date?he:new Date(he);return Number.isNaN(ne.getTime())?void 0:ne})();return R.set(M,x),x},te=async(N,D,P)=>{const M=JSON.stringify([N.id,D,P??null]),K=C.get(M);if(K)return K;const x=(async()=>{const pe={version:"2.0",schema:N.id,...P?{query:P}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:D},{name:"__autoCaseMax__",operator:"$max",pred:D},{name:"__autoCaseCount__",operator:"$count",pred:D}]},ee=await lt(pe,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L}),le=qe(ee,N,A,_,b);if(E(le))return{empty:!0};let re;if(dr(le,_)){const we=h.providerForConnection;if(!we)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");re=(await rn(le,{logicform:ee,operators:A,schemaMappings:_,providerForConnection:we,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Bt,logicform:un,provider:lr,connectionId:dn})=>z(Bt,"semantic-resolution",un,"auto-case",lr,dn)})).rows}else{Bo(le,h);const we=Ae(le,h.provider,A);z(we,"semantic-resolution",ee,"auto-case"),re=await v(we,Ee(le))}const _e=re[0],Se=_e?.__autoCaseMin__,he=_e?.__autoCaseMax__,ne=_e?.__autoCaseCount__;if(Se==null||he===null||he===void 0||ne===null||ne===void 0||Number(ne)===0)return{empty:!0};const me=Number(Se),Oe=Number(he),Te=Number(ne);if(!Number.isFinite(me)||!Number.isFinite(Oe)||!Number.isSafeInteger(Te)||Te<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:Se,max:he,count:ne});return{min:me,max:Oe,count:Te}})();return C.set(M,x),x};try{h.signal?.throwIfAborted(),go(c),await W({stage:"started",logicform:c}),ml(h.permissions,De);const N=fe(c);await W({stage:"validated",schema:N});const D=mt(c,h.permissions,de,!0,new Set,o),P=await lt(D,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L,canProjectProperty:(O,B)=>ft(h.permissions,O.id,B),requestTimeWatermark:j,requestAutoCaseBounds:te});await W({stage:"normalized",normedLogicform:P},{normedLogicform:P});const M=qe(P,N,A,_,b),K=dr(M,_);K||Bo(M,h);const x=M.columnProperties??[],pe=rs(M,N);Me.set(pe.id,pe),await W({stage:"planned",plan:M},{schema:pe});const ee=Hi(M,N,h.provider,A,h.providerForConnection);if(await W({stage:"lineage",lineage:ee},{lineage:ee}),a&&E(M)){const O=[];await W({stage:"compiled",sqls:[]},{sqls:[]}),await W({stage:"result",result:O},{result:O,total:0,providers:[]}),await W({stage:"completed",durationMs:mr.now()-g});const B=P.output?Rn(P.output.type,o):void 0;return{result:O,total:0,schema:pe,normedLogicform:P,sqls:[],lineage:ee,provider:h.provider.kind,providers:[],schemaMappingSelections:[...k],...B?{output:await B.handle({rows:O,logicform:P,schema:pe})}:{}}}if(K){const O=h.providerForConnection;if(!O)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const B=await rn(M,{logicform:P,operators:A,schemaMappings:_,providerForConnection:O,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Ne,type:ae,logicform:ie,provider:Ie,connectionId:ye})=>z(Ne,ae,ie,ae,Ie,ye)});await W({stage:"compiled",sqls:[...q]},{sqls:[...q]}),await W({stage:"executing",provider:"duckdb",connectionId:qt}),await W({stage:"hydrating"});const J=B.connections.length===1?B.connections[0]?.connectionId:void 0,F=await aa(B.rows,x,{semanticTypes:$,plugins:o,resolveSchema:de,fetchEntities:Ne=>na(Ne,{version:P.version,operators:A,schemaMappings:_,semanticTypes:$,plugins:o,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,...h.permissions?{permissions:h.permissions}:{},provider:h.provider,providerForConnection:O,...J?{preferredConnectionId:J}:{},...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:(ae,ie,Ie,ye)=>z(ae,"semantic-resolution",ie,"entity-expansion",Ie,ye)})}),Z=so(F,M.rowIdentity);return await W({stage:"result",result:Z},{result:Z,total:B.total,sqls:[...q],providers:B.connections}),await W({stage:"completed",durationMs:mr.now()-g}),{result:Z,total:B.total,schema:pe,normedLogicform:P,sqls:[...q],lineage:ee,provider:"duckdb",providers:B.connections,schemaMappingSelections:[...k]}}const le=xr(P,M,N,A,de,void 0,r,n.translator(r)),re=async(O,B)=>{const J=B&&O.logicform.schema===B.id?B:fe(O.logicform),F=O.prepare?await lt(mt(O.logicform,h.permissions,de,!0,new Set,o),J,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L,canProjectProperty:(ae,ie)=>ft(h.permissions,ae.id,ie),requestTimeWatermark:j}):O.logicform,Z=qe(F,J,A,_,b),Ne=xr(F,Z,J,A,de,O.logicform,r,n.translator(r));if(Ne){if(Ne.length!==1)throw new Error("A generated component must produce exactly one execution unit");const ae=Ne[0];if("logicform"in ae){const ye=await re(ae,J),ht=ye.component.mapResult,He=O.mapResult;return{...ye,component:{...O,logicform:ye.component.logicform,...ht||He?{mapResult:Ge=>{const ot=ht?.(Ge)??[...Ge];return He?.(ot)??[...ot]}}:{}}}}if("mergeRow"in ae)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const ie=await Promise.all(ae.components.map(async ye=>({name:ye.name,prepared:await re(on(ye)),...ye.groupKeyShifts?{groupKeyShifts:ye.groupKeyShifts}:{},...ye.joinKeys?{joinKeys:ye.joinKeys}:{}}))),Ie=Mr(ae,ie.map(({name:ye,prepared:ht,...He})=>({name:ye,plan:ht.plan,...He})),Z,ae.outputName,h.provider,A);return{component:{...O,logicform:F},plan:Z,compiled:Ie,sources:ar(ie.map(({prepared:ye})=>ye.sources))}}return{component:{...O,logicform:F},plan:Z,compiled:Ae(Z,h.provider,A),sources:Ee(Z)}},_e=async(O,B)=>{const J=xr(O,B,fe(O),A,de,void 0,r,n.translator(r));if(!J)return{compiled:Ae(B,h.provider,A),sources:Ee(B)};const F=await Promise.all(J.map(async Z=>{if("logicform"in Z){const ie=await re(Z);return{plan:ie.plan,compiled:ie.compiled,outputs:ie.plan.projections.map(({name:Ie})=>Ie).filter(Ie=>!B.groupBy.some(ye=>ye.name===Ie))}}if("mergeRow"in Z)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ne=await Promise.all(Z.components.map(async ie=>{const Ie=await re(on(ie));return{name:ie.name,plan:Ie.plan,...ie.joinKeys?{joinKeys:ie.joinKeys}:{},...ie.groupKeyShifts?{groupKeyShifts:ie.groupKeyShifts}:{}}})),ae=Mr(Z,Ne,B,Z.outputName,h.provider,A);return{plan:B,compiled:ae,outputs:[Z.outputName,...Z.components.map(ie=>ie.name)]}}));return{compiled:no(F,B,h.provider,A),sources:ar(F.map(({plan:Z})=>Ee(Z)))}},Se=new WeakMap,he=async O=>{if(!O.sourcePlan||!O.sourceLogicform)return Ae(O,h.provider,A);const B=be(O.sourceLogicform),J=xr(O.sourceLogicform,O.sourcePlan,B,A,de,void 0,r,n.translator(r));if(J?.some(ie=>"mergeRow"in ie)){const ie=Se.get(O.sourcePlan);if(ie){const se={...O};delete se.sourcePlan,delete se.sourceLogicform;const et=Ae({...se,sourceSql:ie.sql,source:O.source},h.provider,A,ie.parameters.length);return{sql:et.sql,parameters:[...ie.parameters,...et.parameters]}}const Ie=await Promise.all(J.map(async se=>{if("logicform"in se)return{kind:"query",unit:se,prepared:await re(se,B)};const et=await Promise.all(se.components.map(async $e=>({input:$e,prepared:await re(on($e),B)})));return"mergeRow"in se?{kind:"js",unit:se,components:et}:{kind:"component",unit:se,components:et,compiled:Mr(se,et.map(({input:$e,prepared:Ve})=>({name:$e.name,plan:Ve.plan,...$e.joinKeys?{joinKeys:$e.joinKeys}:{},...$e.groupKeyShifts?{groupKeyShifts:$e.groupKeyShifts}:{}})),O.sourcePlan,se.outputName,h.provider,A)}})),ye=O.sourcePlan.groupBy.map(({name:se})=>se),ht=await Promise.all(Ie.map(async se=>{if(se.kind==="query"){z(se.prepared.compiled,"computation",se.prepared.component.logicform);const $e=await v(se.prepared.compiled,se.prepared.sources),Ve=await dt($e,se.prepared.plan.projections,A);return se.unit.mapResult?.(Ve)??Ve}if(se.kind==="component")return z(se.compiled,"computation",O.sourceLogicform),v(se.compiled,ar(se.components.map(({prepared:$e})=>$e.sources)));const et=await Promise.all(se.components.map(async({input:$e,prepared:Ve})=>{z(Ve.compiled,"computation",Ve.component.logicform);const xa=await v(Ve.compiled,Ve.sources),Fo=await dt(xa,Ve.plan.projections,A);return $e.mapResult?.(Fo)??Fo}));return Promise.all(uo(et,ye).map(async $e=>({...$e,[se.unit.outputName]:await se.unit.mergeRow($e)})))})),He=po(ht,O.sourcePlan),Ge=h.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(Ge)||Ge<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:Ge});if(He.length>Ge)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${He.length} rows; maximum is ${Ge}`,{materializedRowCount:He.length,maxMaterializedRows:Ge});const ot=dm(He,O.sourcePlan,h.provider);Se.set(O.sourcePlan,ot);const pn={...O};delete pn.sourcePlan,delete pn.sourceLogicform;const Yo=Ae({...pn,sourceSql:ot.sql,source:O.source},h.provider,A,ot.parameters.length);return{sql:Yo.sql,parameters:[...ot.parameters,...Yo.parameters]}}const F=await _e(O.sourceLogicform,O.sourcePlan),Z={...O};delete Z.sourcePlan,delete Z.sourceLogicform;const Ne={...Z,sourceSql:F.compiled.sql,source:O.source},ae=Ae(Ne,h.provider,A,F.compiled.parameters.length);return{sql:ae.sql,parameters:[...F.compiled.parameters,...ae.parameters]}},ne=le?await Promise.all(le.map(async O=>{if("logicform"in O)return{kind:"query",unit:O,...await re(O)};const B=await Promise.all(O.components.map(async F=>({name:F.name,prepared:await re(on(F)),...F.groupKeyShifts?{groupKeyShifts:F.groupKeyShifts}:{},...F.joinKeys?{joinKeys:F.joinKeys}:{}})));if("mergeRow"in O)return{kind:"js",unit:O,components:B.map(({prepared:F})=>F)};const J=B.map(({name:F,prepared:Z,...Ne})=>({name:F,plan:Z.plan,...Ne}));return{kind:"component",unit:O,plan:M,compiled:Mr(O,J,M,O.outputName,h.provider,A),sources:ar(B.map(({prepared:F})=>F.sources))}})):void 0,me=ne&&pm(ne,_,M)?ne.map(O=>{const B=new Set(M.groupBy.map(({name:F})=>F));if(O.kind==="query")return{plan:O.plan,compiled:O.compiled,outputs:O.plan.projections.map(({name:F})=>F).filter(F=>!B.has(F))};const J=O.unit.outputName;if(!J)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:O.plan,compiled:O.compiled,outputs:[J,...O.unit.components.map(F=>F.name)]}}):void 0,Oe=me?no(me,M,h.provider,A):void 0,Te=ne?void 0:await he(M),we=Uo(M),Re=M.pagination&&(Oe||Te)?Mo(me?no(me,we,h.provider,A):await he(we),h.provider):void 0;if(Oe)z(Oe,"computation",P);else if(ne)for(const O of ne)if(O.kind==="js")for(const B of O.components)z(B.compiled,"computation",B.component.logicform);else z(O.compiled,"computation",P);else z(Te,"computation",P);Re&&z(Re,"total",Ff(P)),await W({stage:"compiled",sqls:[...q]},{sqls:[...q]}),await W({stage:"executing",provider:h.provider.kind});const Bt=Oe?await(async()=>{const O=ar([...ne.map(Z=>Z.sources),Ee(M)]),[B,J]=await Promise.all([v(Oe,O),Re?v(Re,O):Promise.resolve(void 0)]),F=await dt(B,M.projections,A);return{rows:F,total:J?tn(J):F.length}})():ne?await(async()=>{const O=await Promise.all(ne.map(async J=>{if(J.kind==="js"){const Ne=await Promise.all(J.components.map(async ae=>{const ie=await v(ae.compiled,ae.sources),Ie=await dt(ie,ae.plan.projections,A);return ae.component.mapResult?.(Ie)??Ie}));return Promise.all(uo(Ne,M.groupBy.map(({name:ae})=>ae)).map(async ae=>{const ie=await J.unit.mergeRow(ae);return{...ae,[J.unit.outputName]:ie}}))}const F=await v(J.compiled,J.sources),Z=J.kind==="query"?await dt(F,J.plan.projections,A):F;return J.kind==="query"?J.unit.mapResult?.(Z)??Z:Z})),B=po(O,M);return{rows:B,total:M.pagination?po(O,we).length:B.length}})():await(async()=>{const O=Ee(M),[B,J]=await Promise.all([v(Te,O),Re?v(Re,O):Promise.resolve(void 0)]),F=await dt(B,M.projections,A);return{rows:F,total:J?tn(J):F.length}})(),{rows:un,total:lr}=Bt;await W({stage:"hydrating"});const dn=await aa(un,x,{semanticTypes:$,plugins:o,resolveSchema:de,fetchEntities:O=>na(O,{version:P.version,operators:A,schemaMappings:_,semanticTypes:$,plugins:o,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,...h.permissions?{permissions:h.permissions}:{},provider:h.provider,...h.connectionId?{preferredConnectionId:h.connectionId}:{},...h.providerForConnection?{providerForConnection:h.providerForConnection}:{},...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:(B,J,F,Z)=>z(B,"semantic-resolution",J,"entity-expansion",F,Z)})}),fr=so(dn,M.rowIdentity);return await W({stage:"result",result:fr},{result:fr,total:lr,sqls:[...q]}),await W({stage:"completed",durationMs:mr.now()-g}),{result:fr,total:lr,schema:pe,normedLogicform:P,sqls:[...q],lineage:ee,provider:h.provider.kind,providers:[...Y].map(([O,B])=>({connectionId:O,provider:B})),schemaMappingSelections:[...k],...P.output?await(async()=>{const O=Rn(P.output?.type??"",o);return O?{output:await O.handle({rows:fr,logicform:P,schema:pe})}:{}})():{}}}catch(N){const D=Ma(N);try{await W({stage:"failed",error:D})}catch{}throw D}},mm=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=wr(Ua(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 T of e.connections){if(T.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(T.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${T.id}`,{connectionId:T.id});i.set(T.id,T)}const s=qa(t),a=t.version,c=a===void 0||typeof a=="string"&&/^1\./.test(a),u=[...new Set(e.schemaMappings.filter(({schemaId:T})=>s.includes(T)).map(({connectionId:T})=>T))],l=e.connections.length===1?e.connections[0]?.id:u.length===1?u[0]:void 0,p=c?ka(e.schemas,e.schemaMappings,l,s,e.connections.map(({id:T})=>T)):e.schemaMappings,m=new Tr(p,e.plugins),f=s.flatMap(T=>m.list(T)).map(({connectionId:T})=>T)[0];if(!f)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const y=T=>{const G=i.get(T);if(!G)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${T}`,{connectionId:T});return en(G,e.providerRegistry)},h=y(f);r={provider:h.kind};const g=Be(e.plugins),$=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],A=new xt($),_=new Set(A.definitions().map(({name:T})=>T)),E=$.length===0?g:new xt([...g.definitions().filter(({name:T})=>!_.has(T)),...A.definitions()]),w=e.semanticTypes===void 0?ho(e.plugins):Ls(e.semanticTypes,e.plugins??[]),{cache:R,...C}=e,k=R?await ea(R):void 0;return await ja(t,{...C,schemaMappings:m,locale:n,localeRegistry:o,provider:h,providerForConnection:y,operators:E,operatorsResolved:!0,semanticTypes:w,semanticTypesResolved:!0,connectionId:f,...k?{cache:k}:{},onProgress:async T=>{r=T.partialResult,await e.onProgress?.(T)}})}catch(i){return um(i,t,r,n,o)}},ym=Object.freeze({execute:mm,close:wa});export{qf as DBConnector,gn as LocaleRegistry,ym as Logicform,xt as OperatorRegistry,Wi as PlannerSemanticRegistry,ha as ProviderRegistry,Pl as QueryCacheManager,Tr as SchemaMappingRegistry,d as SemanticDBError,lo as SemanticTypeRegistry,zd as builtinOperators,vn as builtinSemanticTypes,wr as createLocaleRegistry,Be as createOperatorRegistry,Ki as createPlannerSemanticRegistry,ho as createSemanticTypeRegistry,$r as defaultLocaleRegistry,li as enUS,ep as fromYiAskSchemaMapping,Yi as resolveOperator,Rs as resolveSchema,bs as validateResolvedSchema,fi as zhCN};
|
|
1
|
+
import{performance as Lr}from"node:perf_hooks";import le from"dayjs";import tr from"dayjs/plugin/isoWeek.js";import Cr from"dayjs/plugin/quarterOfYear.js";import ui from"dayjs/plugin/customParseFormat.js";import{randomUUID as di,createHash as lc}from"node:crypto";import{isDeepStrictEqual as pi}from"node:util";import{createClient as fc}from"redis";import{getNameProperty as mc}from"semanticdb-core";import{DuckDBInstance as yc,VARCHAR as Lt,DOUBLE as li,TIMESTAMP as Nn,BOOLEAN as fi,jsToDuckDBValue as et,blobValue as hc}from"@duckdb/node-api";const Z=t=>typeof t=="string",rr=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},mi=t=>t==null?"":""+t,gc=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Ac=/###/g,yi=t=>t&&t.indexOf("###")>-1?t.replace(Ac,"."):t,hi=t=>!t||Z(t),nr=(t,e,r)=>{const n=Z(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(hi(t))return{};const i=yi(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return hi(t)?{}:{obj:t,k:yi(n[o])}},gi=(t,e,r)=>{const{obj:n,k:o}=nr(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=nr(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=nr(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},$c=(t,e,r,n)=>{const{obj:o,k:i}=nr(t,e,Object);o[i]=o[i]||[],o[i].push(r)},Dr=(t,e)=>{const{obj:r,k:n}=nr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},wc=(t,e,r)=>{const n=Dr(t,r);return n!==void 0?n:Dr(e,r)},Ai=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?Z(t[n])||t[n]instanceof String||Z(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Ai(t[n],e[n],r):t[n]=e[n]);return t},mt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ec={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const _c=t=>Z(t)?t.replace(/[&<>"'\/]/g,e=>Ec[e]):t;class Ic{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 Sc=[" ",",","?","!",";"],bc=new Ic(20),Rc=(t,e,r)=>{e=e||"",r=r||"";const n=Sc.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=bc.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},On=(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 c=i;c<n.length;++c)if(c!==i&&(a+=r),a+=n[c],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&c<n.length-1)continue;i+=c-i+1;break}o=s}return o},or=t=>t?.replace(/_/g,"-"),Nc={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 In{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Nc,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:(Z(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new In(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new In(this.logger,e)}}var ze=new In;class Mr{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 $i extends Mr{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):Z(n)&&i?a.push(...n.split(i)):a.push(n)));const c=Dr(this.data,a);return!c&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),c||!s||!Z(n)?c:On(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),gi(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)(Z(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 c=Dr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Ai(c,n,i):c={...c,...n},gi(this.data,a,c),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 wi={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 Ei=Symbol("i18next/PATH_KEY");function Oc(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===Ei?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Ct(t,e){const{[Ei]:r}=t(Oc()),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 _i={},Tn=t=>!Z(t)&&typeof t!="boolean"&&typeof t!="number";class Sn extends Mr{constructor(e,r={}){super(),gc(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=ze.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=Tn(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&&!Rc(e,n,o);if(s&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:Z(i)?[i]:i};const u=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),e=u.join(o)}return{key:e,namespaces:Z(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=Ct(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(x=>typeof x=="function"?Ct(x,{...this.options,...o}):String(x));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],o),u=c[c.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,m=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return m?i?{res:`${u}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:`${u}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:a;const f=this.resolve(e,o);let h=f?.res;const y=f?.usedKey||a,$=f?.exactUsedKey||a,E=["[object Number]","[object Function]","[object RegExp]"],A=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,g=!this.i18nFormat||this.i18nFormat.handleAsObject,w=o.count!==void 0&&!Z(o.count),L=Sn.hasDefaultValue(o),I=w?this.pluralResolver.getSuffix(l,o.count,o):"",S=o.ordinal&&w?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",R=w&&!o.ordinal&&o.count===0,N=R&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${I}`]||o[`defaultValue${S}`]||o.defaultValue;let D=h;g&&!h&&L&&(D=N);const F=Tn(D),V=Object.prototype.toString.apply(D);if(g&&D&&F&&E.indexOf(V)<0&&!(Z(A)&&Array.isArray(D))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const x=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,D,{...o,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(f.res=x,f.usedParams=this.getUsedParamsDetails(o),f):x}if(s){const x=Array.isArray(D),M=x?[]:{},j=x?$:y;for(const K in D)if(Object.prototype.hasOwnProperty.call(D,K)){const Q=`${j}${s}${K}`;L&&!h?M[K]=this.translate(Q,{...o,defaultValue:Tn(N)?N[K]:void 0,joinArrays:!1,ns:c}):M[K]=this.translate(Q,{...o,joinArrays:!1,ns:c}),M[K]===Q&&(M[K]=D[K])}h=M}}else if(g&&Z(A)&&Array.isArray(h))h=h.join(A),h&&(h=this.extendTranslation(h,e,o,n));else{let x=!1,M=!1;!this.isValidLookup(h)&&L&&(x=!0,h=N),this.isValidLookup(h)||(M=!0,h=a);const K=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&M?void 0:h,Q=L&&N!==h&&this.options.updateMissing;if(M||x||Q){if(this.logger.log(Q?"updateKey":"missingKey",l,u,a,Q?N:h),s){const fe=this.resolve(a,{...o,keySeparator:!1});fe&&fe.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 re=[];const ye=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ye&&ye[0])for(let fe=0;fe<ye.length;fe++)re.push(ye[fe]);else this.options.saveMissingTo==="all"?re=this.languageUtils.toResolveHierarchy(o.lng||this.language):re.push(o.lng||this.language);const Me=(fe,be,se)=>{const Re=L&&se!==h?se:K;this.options.missingKeyHandler?this.options.missingKeyHandler(fe,u,be,Re,Q,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(fe,u,be,Re,Q,o),this.emit("missingKey",fe,u,be,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?re.forEach(fe=>{const be=this.pluralResolver.getSuffixes(fe,o);R&&o[`defaultValue${this.options.pluralSeparator}zero`]&&be.indexOf(`${this.options.pluralSeparator}zero`)<0&&be.push(`${this.options.pluralSeparator}zero`),be.forEach(se=>{Me([fe],a+se,o[`defaultValue${se}`]||N)})}):Me(re,a,N))}h=this.extendTranslation(h,e,o,f,n),M&&h===a&&this.options.appendNamespaceToMissingKey&&(h=`${u}${p}${a}`),(M||x)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${p}${a}`:a,x?h:void 0,o))}return i?(f.res=h,f.usedParams=this.getUsedParamsDetails(o),f):h}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 c=Z(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const l=e.match(this.interpolator.nestingRegexp);u=l&&l.length}let p=n.replace&&!Z(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),c){const l=e.match(this.interpolator.nestingRegexp),m=l&&l.length;u<m&&(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=Z(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=wi.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 Z(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?Ct(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const u=this.extractFromKey(c,r),p=u.key;o=p;let l=u.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const m=r.count!==void 0&&!Z(r.count),f=m&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(Z(r.context)||typeof r.context=="number")&&r.context!=="",y=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach($=>{this.isValidLookup(n)||(a=$,!_i[`${y[0]}-${$}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(_i[`${y[0]}-${$}`]=!0,this.logger.warn(`key "${o}" for languages "${y.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!!!")),y.forEach(E=>{if(this.isValidLookup(n))return;s=E;const A=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,p,E,$,r);else{let w;m&&(w=this.pluralResolver.getSuffix(E,r.count,r));const L=`${this.options.pluralSeparator}zero`,I=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(r.ordinal&&w.indexOf(I)===0&&A.push(p+w.replace(I,this.options.pluralSeparator)),A.push(p+w),f&&A.push(p+L)),h){const S=`${p}${this.options.contextSeparator||"_"}${r.context}`;A.push(S),m&&(r.ordinal&&w.indexOf(I)===0&&A.push(S+w.replace(I,this.options.pluralSeparator)),A.push(S+w),f&&A.push(S+L))}}let g;for(;g=A.pop();)this.isValidLookup(n)||(i=g,n=this.getResource(E,$,g,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&&!Z(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 Ii{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=ze.create("languageUtils")}getScriptPartFromCode(e){if(e=or(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=or(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(Z(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)),Z(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 Z(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))):Z(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const Si={zero:0,one:1,two:2,few:3,many:4,other:5},bi={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Tc{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=ze.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=or(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!"),bi;if(!e.match(/-|_/))return bi;const c=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(c,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)=>Si[o]-Si[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 Ri=(t,e,r,n=".",o=!0)=>{let i=wc(t,e,r);return!i&&o&&Z(r)&&(i=On(t,r,n),i===void 0&&(i=On(e,r,n))),i},Pn=t=>t.replace(/\$/g,"$$$$");class Ni{constructor(e={}){this.logger=ze.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:c,formatSeparator:u,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:m,nestingPrefixEscaped:f,nestingSuffix:h,nestingSuffixEscaped:y,nestingOptionsSeparator:$,maxReplaces:E,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:_c,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?mt(i):s||"{{",this.suffix=a?mt(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=m?mt(m):f||mt("$t("),this.nestingSuffix=h?mt(h):y||mt(")"),this.nestingOptionsSeparator=$||",",this.maxReplaces=E||1e3,this.alwaysFormat=A!==void 0?A:!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 c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=f=>{if(f.indexOf(this.formatSeparator)<0){const E=Ri(r,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(E,void 0,n,{...o,...r,interpolationkey:f}):E}const h=f.split(this.formatSeparator),y=h.shift().trim(),$=h.join(this.formatSeparator).trim();return this.format(Ri(r,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),$,n,{...o,...r,interpolationkey:y})};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:f=>Pn(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?Pn(this.escape(f)):Pn(f)}].forEach(f=>{for(a=0;i=f.regex.exec(e);){const h=i[1].trim();if(s=u(h),s===void 0)if(typeof p=="function"){const $=p(e,i,o);s=Z($)?$:""}else if(o&&Object.prototype.hasOwnProperty.call(o,h))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${e}`),s="";else!Z(s)&&!this.useRawValueToEscape&&(s=mi(s));const y=f.safeValue(s);if(e=e.replace(i[0],y),l?(f.regex.lastIndex+=s.length,f.regex.lastIndex-=i[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(c,u)=>{const p=this.nestingOptionsSeparator;if(c.indexOf(p)<0)return c;const l=c.split(new RegExp(`${mt(p)}[ ]*{`));let m=`{${l[1]}`;c=l[0],m=this.interpolate(m,s);const f=m.match(/'/g),h=m.match(/"/g);((f?.length??0)%2===0&&!h||(h?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{s=JSON.parse(m),u&&(s={...u,...s})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,y),`${c}${p}${m}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,c};for(;o=this.nestingRegexp.exec(e);){let c=[];s={...n},s=s.replace&&!Z(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const u=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(u!==-1&&(c=o[1].slice(u).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,u)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!Z(i))return i;Z(i)||(i=mi(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),c.length&&(i=c.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 Pc=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,...c]=s.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=u),u==="false"&&(r[p]=!1),u==="true"&&(r[p]=!0),isNaN(u)||(r[p]=parseInt(u,10))}})}return{formatName:e,formatOptions:r}},Oi=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(or(n),o),e[s]=a),a(r)}},Lc=t=>(e,r,n)=>t(or(r),n)(e);class Cc{constructor(e={}){this.logger=ze.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Oi:Lc;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()]=Oi(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(c=>c.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,c)=>{const{formatName:u,formatOptions:p}=Pc(c);if(this.formats[u]){let l=a;try{const m=o?.formatParams?.[o.interpolationkey]||{},f=m.locale||m.lng||o.locale||o.lng||n;l=this.formats[u](a,f,{...p,...o,...m})}catch(m){this.logger.warn(m)}return l}else this.logger.warn(`there was no format function for ${u}`);return a},e)}}const Dc=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Mc extends Mr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=ze.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={},c={};return e.forEach(u=>{let p=!0;r.forEach(l=>{const m=`${u}|${l}`;!n.reload&&this.store.hasResourceBundle(u,l)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?s[m]===void 0&&(s[m]=!0):(this.state[m]=1,p=!1,s[m]===void 0&&(s[m]=!0),i[m]===void 0&&(i[m]=!0),c[l]===void 0&&(c[l]=!0)))}),p||(a[u]=!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(c)}}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(c=>{$c(c.loaded,[i],s),Dc(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{a[u]||(a[u]={});const p=c.loaded[u];p.length&&p.forEach(l=>{a[u][l]===void 0&&(a[u][l]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.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=(u,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(u&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(u,p)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const u=c(e,r);u&&typeof u.then=="function"?u.then(p=>a(null,p)).catch(a):a(null,u)}catch(u){a(u)}return}return c(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();Z(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Z(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 c={...s,isUpdate:i},u=this.backend.create.bind(this.backend);if(u.length<6)try{let p;u.length===5?p=u(e,r,n,o,c):p=u(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 u(e,r,n,o,a,c)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const Ln=()=>({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]),Z(t[1])&&(e.defaultValue=t[1]),Z(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=>(Z(t.ns)&&(t.ns=[t.ns]),Z(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Z(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),Ur=()=>{},Uc=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Pi="__i18next_supportNoticeShown",qc=()=>!!(typeof globalThis<"u"&&globalThis[Pi]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),kc=()=>{typeof globalThis<"u"&&(globalThis[Pi]=!0)},jc=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 Tr extends Mr{constructor(e={},r){if(super(),this.options=Ti(e),this.services={},this.logger=ze,this.modules={external:[]},Uc(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&&(Z(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=Ln();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&&!jc(this)&&!qc()&&(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}"),kc());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?ze.init(o(this.modules.logger),this.options):ze.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=Cc;const p=new Ii(this.options);this.store=new $i(this.options.resources,this.options);const l=this.services;l.logger=ze,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Tc(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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(u),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new Ni(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Mc(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(f,...h)=>{this.emit(f,...h)}),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 Sn(this.services,this.options),this.translator.on("*",(f,...h)=>{this.emit(f,...h)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Ur),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...p)=>this.store[u](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...p)=>(this.store[u](...p),this)});const a=rr(),c=()=>{const u=(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 u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,r=Ur){let n=r;const o=Z(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(u=>{u!=="cimode"&&i.indexOf(u)<0&&i.push(u)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>s(c)),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=rr();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=Ur),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"&&wi.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=rr();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,c)=>{c?this.isLanguageChangingTo===e&&(o(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(a,(...u)=>this.t(...u))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=Z(a)?a:a&&a[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(Z(a)?[a]:a);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,p=>{i(p,u)})};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 c;typeof s!="object"?c=this.options.overloadTranslationOptionHandler([i,s].concat(a)):c={...s},c.lng=c.lng||o.lng,c.lngs=c.lngs||o.lngs,c.ns=c.ns||o.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||o.keyPrefix);const u={...this.options,...c};typeof c.keyPrefix=="function"&&(c.keyPrefix=Ct(c.keyPrefix,u));const p=this.options.keySeparator||".";let l;return c.keyPrefix&&Array.isArray(i)?l=i.map(m=>(typeof m=="function"&&(m=Ct(m,u)),`${c.keyPrefix}${p}${m}`)):(typeof i=="function"&&(i=Ct(i,u)),l=c.keyPrefix?`${c.keyPrefix}${p}${i}`:i),this.t(l,c)};return Z(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,c)=>{const u=this.services.backendConnector.state[`${a}|${c}`];return u===-1||u===0||u===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=rr();return this.options.ns?(Z(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=rr();Z(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 Ii(Ln());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 Tr(e,r);return n.createInstance=Tr.createInstance,n}cloneInstance(e={},r=Ur){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new Tr(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((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((p,l)=>(p[l]={...c[u][l]},p),c[u]),c),{});i.store=new $i(a,o),i.services.resourceStore=i.store}if(e.interpolation){const c={...Ln().interpolation,...this.options.interpolation,...e.interpolation},u={...o,interpolation:c};i.services.interpolator=new Ni(u)}return i.translator=new Sn(i.services,o),i.translator.on("*",(a,...c)=>{i.emit(a,...c)}),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 Ue=Tr.createInstance(),xc=Ue.createInstance;Ue.dir,Ue.init,Ue.loadResources,Ue.reloadResources,Ue.use,Ue.changeLanguage,Ue.getFixedT,Ue.t,Ue.exists,Ue.setDefaultNamespace,Ue.hasLoadedNamespace,Ue.loadNamespaces,Ue.loadLanguages;const Li={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","error.QUERY_NOT_COVERED_BY_DATA_SOURCE":'The data sources connected to Schema "{schemaLabel}" cannot answer this query. Check their fields, dimension combinations, and time granularity.',"error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions":'No data source for Schema "{schemaLabel}" fully covers the required dimensions [{dimensions}]. Check the dimension combinations in the connected tables.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":'No data mapping covers shard {shardNumber} of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions":'No data source covers dimensions [{dimensions}] for shard {shardNumber} of Schema "{schemaLabel}".',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":'No data mapping covers both the current and comparison periods for shard {shardNumber} of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":'No data source covers dimensions [{dimensions}] for both the current and comparison periods of shard {shardNumber} of Schema "{schemaLabel}".',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component":'No data mapping covers the component partition of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"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"}},Ci={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","error.QUERY_NOT_COVERED_BY_DATA_SOURCE":"Schema\u300C{schemaLabel}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions":"Schema\u300C{schemaLabel}\u300D\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u67E5\u8BE2\u6240\u9700\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002\u8BF7\u68C0\u67E5\u5DF2\u63A5\u5165\u6570\u636E\u8868\u7684\u7EF4\u5EA6\u7EC4\u5408\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u6240\u9700\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component":"Schema\u300C{schemaLabel}\u300D\u7684\u7EC4\u4EF6\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","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"}},Bc=[Ci,Li],ir=t=>t.trim().toLowerCase(),Vc=t=>t?"locale"in t?[t]:t:[],Yc=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=xc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(Bc),this.register(e)}register(e){for(const r of Vc(e)){const n=r;if(!Yc(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(ir(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(ir(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(ir(e));if(r)return r;const n=ir(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(ir(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 qr=t=>new Cn(t),kr=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=kr){const n=this.details?.schemaLabel,o=this.details?.uncoveredDimensions,i=Array.isArray(o)&&o.length>0&&o.every(s=>typeof s=="string")?o.join(e.toLowerCase().startsWith("en")?", ":"\u3001"):void 0;if(this.code==="QUERY_NOT_COVERED_BY_DATA_SOURCE"&&typeof n=="string")return r.translate(e,i===void 0?"error.QUERY_NOT_COVERED_BY_DATA_SOURCE":"error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions",this.message,{schemaLabel:n,...i?{dimensions:i}:{}});if(this.code==="SCHEMA_PARTITION_MAPPING_NOT_FOUND"&&typeof n=="string"){const s=this.details?.shardIndex;if(typeof s=="number"){const a=this.details?.comparison?i===void 0?"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":i===void 0?"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions";return r.translate(e,a,this.message,{schemaLabel:n,shardNumber:s+1,...i?{dimensions:i}:{}})}return r.translate(e,"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component",this.message,{schemaLabel:n})}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 s=this.details?.schemaId,a=this.details?.schemaName,c=this.details?.property,u=this.details?.propertyName;if(typeof s=="string"&&typeof a=="string"&&typeof c=="string"&&typeof u=="string")return`Property not found in Schema: ${a}(${s}): ${u}`}return this.message}}le.extend(tr),le.extend(Cr);const Fc=new Set(["year","quarter","month","week"]),Dn=t=>t.format("YYYY-MM-DD HH:mm:ss"),Mn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Mn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Mn(r,e)),jr=(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:jr(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:jr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>jr(o,e,r))}:{}}},Qc=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 jr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},Hc=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!Mn(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})},vc=(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 L=w;return typeof L.$gte=="string"&&typeof L.$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=le(String(s.$gte)),c=le(String(s.$lte));if(!a.isValid()||!c.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const u=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:Dn(p)}},m=new Set([...(t.groupby??[]).map(({name:w})=>w),...(t.preds??[]).map(({name:w})=>w)]),f=w=>{let L=w;for(;m.has(L);)L=`_${L}`;return m.add(L),L},h=f("__accumulate_period"),y=e.map((w,L)=>f(`__accumulate_metric_${L}`)),$=(t.groupby??[]).map(({name:w})=>String(w)),E=r==="year"||r==="quarter"?"month":"day",A={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:E},name:h}],preds:e.map((w,L)=>({...w.pred,name:y[L]??`__accumulate_metric_${L}`}))},g={version:t.version,from:A,preds:[...$.map(w=>({pred:w,name:w})),{pred:h,name:h},...e.map((w,L)=>({operator:"$accumulate",pred:y[L]??`__accumulate_metric_${L}`,args:{partitionBy:$,orderBy:[{pred:h,direction:"asc"}]},name:u[L]??`accumulate_${L}`}))]};return{version:t.version,from:g,query:{[h]:{$gte:Dn(a),$lte:Dn(c)}},preds:[...$.map(w=>({pred:w,name:w})),...u.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}:{}}},Gc={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"||!Fc.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:Qc,validatePlan:Hc,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 vc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},zc={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}}},Dt=(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},xr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),Wc={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`(${Dt("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:xr(t)}},ae=t=>structuredClone(t),Di=(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},Kc=(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},Jc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},Mi=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Xc=(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)),oe=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:Mi(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Xc(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=oe(s,e.slice(i.length+1),r);return{canonicalName:`${Mi(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,Zc=(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},Ui=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=oe(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=oe(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Zc(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})},eu=({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:c})=>c==="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}}},tu=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},ru=(t,e,r)=>{const n=oe(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}},nu={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(h=>h!=="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=ru(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:h})=>h===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==oe(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const c=s.levels.reduce((h,y)=>h+y.codeLength,0),u=i.schema.properties.filter(({type:h})=>h==="ID"),l=i.relation&&u.length===1&&u[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let h=0;return{reference:l,args:{levels:s.levels.map(({name:y,codeLength:$})=>(h+=$,{name:y,codeLength:h})),totalLength:c,storage:s.storage}}}let m=0;const f=s.levels.find(h=>(m+=h.codeLength,h.name===e.level||h.syno?.includes(e.level)));if(!f)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:f.name,codeLength:m,totalLength:c,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 c=e.levels.filter(h=>typeof h=="object"&&h!==null&&!Array.isArray(h)&&typeof h.name=="string"&&Number.isInteger(h.codeLength)),u=e.totalLength,p=e.storage;if(c.length!==e.levels.length||c.length===0||!Number.isInteger(u)||Number(u)<=0||c.some(({name:h,codeLength:y},$)=>h.length===0||y<=0||y>Number(u)||$>0&&y<=Number(c[$-1]?.codeLength))||c.at(-1)?.codeLength!==u||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 h=r.stringLength(t),y=c.map($=>`WHEN ${h} = ${$.codeLength} THEN ${r.value($.name)}`);return`(CASE ${l} ${y.join(" ")} ELSE NULL END)`}const m=c.slice(0,-1).map(h=>{const y=Number(u)-h.codeLength;return`WHEN ${r.substring(t,h.codeLength+1,y)} = ${r.value("0".repeat(y))} THEN ${r.value(h.name)}`}),f=c.at(-1);return`(CASE ${l} ${m.join(" ")} ELSE ${r.value(f?.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}}},Mt=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},Ut=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),qn=(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)}},Br=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>Ut(e,o)?.id===t.id)),qi=(t,e,r)=>{const n=Ut(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=qn(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Br(n,r);if(!Mt(i?.granularity))return;const s=qn(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},ou=(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 c=qi(i.pred,i.args.level,e);if(c)return c}else{const c=Ut(e.schema,i.pred),u=c&&Br(c,e);if(Mt(u?.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 c of a){if(typeof c=="string")continue;const u=r(c);if(u)return u}},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 c of a){const u=n(c);if(u)return u}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const c=a.pred;if(typeof c!="object"||c===null||Array.isArray(c))continue;const u=r(c);if(u)return u}else if(!s.startsWith("$")){const c=Ut(e.schema,s),u=c&&Br(c,e);if(Mt(u?.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=qi(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=Ut(e.schema,i.pred),a=s&&Br(s,e);if(Mt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},iu={kind:"hierarchy",isGranularity:Mt,validateItem(t,e){const r=t.granularity;if(Mt(r))return t.propertyTarget?.every(n=>{const o=Ut(e.schema,n);return o!==void 0&&qn(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:ou,supportsGroupby:t=>t.operator==="$hierarchyLevel"},su={keys:["hierarchy"],resolve(t,e){for(const m of e)if(m.level!==void 0){if(typeof m.level!="string"||m.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${m.name} level must be a non-empty string`,{property:m.name,level:m.level});if(m.primal_type!=="entity"&&m.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${m.name} level requires an entity relation`,{property:m.name,type:m.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(m=>m!=="property"&&m!=="storage"&&m!=="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 m=e.filter(f=>f.type==="ID");if(m.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:m.length});return m[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(m=>m.name===n.property||m.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 c=new Set,u=new Set,p=n.levels.map((m,f)=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} must be an object`);const h=m,y=Object.keys(h).filter(E=>E!=="name"&&E!=="syno"&&E!=="codeLength");if(y.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${f} only supports name, syno, and codeLength`,{unsupportedKeys:y});if(typeof h.name!="string"||h.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} name must not be empty`);if(c.has(h.name)||u.has(h.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${h.name}`);if(!Number.isInteger(h.codeLength)||Number(h.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${h.name} codeLength must be a positive integer`);if(h.syno!==void 0&&(!Array.isArray(h.syno)||h.syno.some(E=>typeof E!="string"||E.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${h.name} syno must contain only non-empty strings`);const $=h.syno??[];for(const E of $){if(E===h.name||c.has(E)||u.has(E))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${E}`);u.add(E)}return c.add(h.name),{name:h.name,...$.length>0?{syno:[...$]}:{},codeLength:Number(h.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},au=Object.freeze({name:"hierarchy",schemaMetadata:su,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:eu,resolveEntityFilterProperty:tu,operators:[nu],mappingGranularity:iu}),cu=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),kn="$periodValue",uu=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:kn,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${kn}; ${e.name} describes a time range`,{operator:e.name});return{operator:kn,boundary:"end",implicit:!0}},du={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!cu(r,e))return;const s=uu(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},pu=new Set(["second","minute","hour","day","week","month","quarter","year"]),ki=t=>typeof t=="string"&&pu.has(t),lu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Vr=(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},yt=(t,e=2)=>String(t).padStart(e,"0"),jn=t=>`${yt(t.getFullYear(),4)}-${yt(t.getMonth()+1)}-${yt(t.getDate())} ${yt(t.getHours())}:${yt(t.getMinutes())}:${yt(t.getSeconds())}.`+yt(t.getMilliseconds(),3),fu=(t,e)=>{if(!lu(t)){const a=Vr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=Vr(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=Vr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=Vr(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}},mu=(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},yu=(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},ji=(t,e,r)=>{const{lower:n,upper:o}=fu(t,r),i=[];let s=mu(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=yu(s,e),c=new Date(Math.min(a.getTime()-1,o));i.push({label:jn(s),start:jn(s),end:jn(c)}),s=a}return i},hu=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),gu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Au=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=hu(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"||!ki(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 m=l.args?.boundary;if(m!=="start"&&m!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:m});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 u=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:u,metrics:a,periods:ji(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[u]}))}},xi=["second","minute","hour","day","week","month","quarter","year"],$u=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:[du],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(xi.indexOf(o)>xi.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=Au(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>gu(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),sr=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,wu={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:m})=>m==="ID"),a=i===void 0?s.length===1?s[0]:void 0:sr(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 c=Array.isArray(r.roots),u=c?r.roots:r.root===void 0?[]:[r.root];if(!c&&u.length===0||u.some(m=>m===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(u.map(m=>e.normalizeValue(m,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:u})=>u==="ID"):sr(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",c=sr(o,a);s&&e.assertPropertyAllowed(o,s),c&&e.assertPropertyAllowed(o,c)},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=sr(o,r.idProperty),s=sr(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__"),c=r.quoteIdentifier("__recursive_id__"),u=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),m=r.quoteIdentifier(i.parentColumn),f=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),h=()=>s.map(w=>n(w)).join(", "),y=(w,L=!1)=>s.length===1?`${w} ${L?"<>":"="} ${h()}`:`${w} ${L?"NOT IN":"IN"} (${h()})`,$=`${u}.${l}`,E=i.includeSelf?y($):`${y(`${u}.${m}`)} AND ${y($,!0)}`,A=r.recursiveCteUnion??"UNION",g=`(WITH RECURSIVE ${a}(${c}) AS ( SELECT ${$} FROM ${r.tableAlias(f,"__recursive_node__")} WHERE ${E} ${A} SELECT ${p}.${l} FROM ${r.tableAlias(f,"__recursive_child__")} JOIN ${a} ON ${p}.${m} = ${a}.${c}) SELECT DISTINCT ${c} FROM ${a})`;return`${e} IN ${g}`}},Eu=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:[wu]});le.extend(tr);const xn=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...xn(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:xn(r))]:e},Bi=(t,e)=>le(t).endOf(e==="week"?"isoWeek":e).toDate(),Bn=t=>le(t).format("YYYY-MM-DD HH:mm:ss"),_u=(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})},Vi=(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})},Iu=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return Vi(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(Vi(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 c=[...new Set((t.preds??[]).flatMap(xn).filter(l=>l!==e.id))],u=[{schema:e,property:r}];for(const l of c){const m=s(l),f=t.propertyResolve?.[l],h=f?.[r.id]??f?.[r.name]??a(e,r.name,m);if(!h)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const y=m.properties.find(({id:$,name:E})=>$===h||E===h);if(!y||y.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${h}`,{schemaId:l,property:h});u.push({schema:m,property:y})}const p=u.map(({schema:l,property:m})=>{const f=_u(m.timeWatermark??l.timeWatermark??i,`${l.id}.${m.id}`);if(f.type==="now_offset"){const h=Bi(le(o).add(f.offset,"day").toDate(),m.granularity??"day");return{operator:"$constant",args:{value:Bn(h),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:m.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:Bn(Bi(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:Bn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),Yr=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},ar=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=Yr(t.properties,"ID"),r=Yr(t.properties,"timestamp"),n=Yr(t.properties,"start_date"),o=Yr(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},Yi=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Su=(t,e)=>Yi(t,e)!==void 0,bu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Ru=(t,e)=>{const r=Yi(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!ki(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:ji(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},Nu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ou=t=>Nu(t)?t.$lte??t.$lt??t.$eq:t,Fi=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,c])=>[a,(a==="$and"||a==="$or")&&Array.isArray(c)?c.map(u=>Fi(u,e)):c])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=Ou(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}]}}},Qi=(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&&Qi(o,e)))),Tu={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=ar(e);if(!n)return r;if(Su(t,n))return bu(r,n);const i=Qi(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Fi(i,n)},resolveProjection({schema:t,outputProperty:e}){if(ar(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Pu={name:"start_date",primalType:"date"},Lu={name:"end_date",primalType:"date"},Cu=Object.freeze({name:"validity",semanticTypes:[Pu,Lu],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:[Tu],intervalSemantics:{resolve:ar},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=ar(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=ar(e);if(!r)return;const n=Ru(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},Du=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,c=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:c});const u=Hi(t,o,a.up,"up"),p=Hi(t,o,a.down,"down");return{...o,hierarchy:{...u?{up:u}:{},...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}}}),Fr=Object.freeze([au,Eu,Iu,$u,Cu,Du]),Se=(t=[])=>{const e=[...Fr,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,c=new Set,u=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 f of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!f)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(f))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${f}`,{key:f,plugin:l.name});n.add(f)}for(const f of l.propertyMetadata?.keys??[]){if(!f)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(f))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${f}`,{key:f,plugin:l.name});o.add(f)}for(const f of l.operators??[]){if(i.has(f.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${f.name}`,{operator:f.name,plugin:l.name});i.add(f.name)}for(const f of l.semanticTypes??[]){if(s.has(f.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${f.name}`,{semanticType:f.name,plugin:l.name});s.add(f.name)}for(const f of l.plannerSemantics??[]){if(!f.name||a.has(f.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${f.name}`,{rule:f.name,plugin:l.name});a.add(f.name)}for(const f of l.queryOperators??[]){if(!f.name||c.has(f.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${f.name}`,{operator:f.name,plugin:l.name});c.add(f.name)}for(const f of l.outputHandlers??[]){if(!f.type||u.has(f.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${f.type}`,{type:f.type,plugin:l.name});u.add(f.type)}const m=l.mappingGranularity;if(m){if(!m.kind||p.has(m.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${m.kind}`);p.add(m.kind)}}return Object.freeze(e)},qt=(t,e=[])=>Se(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Vn=(t,e=[])=>Se(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},Fn=(t,e=[])=>Yn("interval semantics",Se(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Mu=(t,e,r=[])=>Yn("relation semantics",Se(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Uu=(t,e,r=[])=>Yn("planner period semantics",Se(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),Qn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),qu=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]},Hn=(t,e=[])=>{for(const r of Se(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return qu(t)},vn=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},Gn=t=>typeof t.pred=="string"?t.pred:void 0,ku=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ju={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},xu={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},zn=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!ku(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}${ju[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${xu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};le.extend(tr),le.extend(Cr);const Bu=["second","minute","hour","day","week","month","quarter","year"],Vu=new Set(Bu),Wn=["year","quarter","month","week","day","hour","minute","second"],vi=t=>Object.prototype.toString.call(t)==="[object Object]",ct=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Yu=t=>{const e=t.time;vi(e)||ct("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!Vu.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&ct("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,c])=>!Wn.includes(a)||!Number.isInteger(c)))&&ct("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&ct("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,[c,u]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<c||Number(p)>u)&&ct(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&ct("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&ct("Absolute period shift day requires month"),r},Gi=(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),Fu=(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 Wn){const o=e[n];typeof o=="number"&&(r=Gi(r,n,o))}return r},Kn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),Qu=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=Gn(i);return s?oe(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",c="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:vn(i),granularity:a,offset:c}}),Jn=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>Jn(i,e,r));if(vi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,Jn(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=le(t);if(!n.isValid())return t;const o=Fu(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,Kn(t,o)},zi=(t,e,r,n,o)=>{const i=new Set,s=c=>Object.fromEntries(Object.entries(c).map(([u,p])=>{if((u==="$and"||u==="$or")&&Array.isArray(p))return[u,p.map(m=>s(m))];const l=oe(e,u,r);return l.property.primal_type!=="date"?[u,p]:(i.add(l.canonicalName),[u,Jn(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},ht=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},ut=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?ut(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:ut(r)):[]],Hu=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=le(t);if(!n.isValid())return t;if("granularity"in e)return Kn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of Wn)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=Gi(o,i,s)}return Kn(t,o)},Xn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&ct("$periodShift pred must be a nested metric");const s=Yu(e.args??{}),a={shiftedValues:0},c=ht([t.query,...ut(e)]);if(!c)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=zi(c,n,o,s,a),p=ae(i);p.name=r,delete p.query;const l=ae(t);l.query=u,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const m=new Set((t.groupby??[]).filter(f=>{const h=Gn(f);return h?oe(n,h,o).property.primal_type==="date":!1}).map(vn));return{kind:"query",logicform:l,partitionCurrentLogicform:{...ae(t),query:c,preds:[{...ae(p),name:"__partition_current__"}]},partitionQuery:f=>zi(f,n,o,s,{shiftedValues:0}),groupKeyShifts:Qu(t,n,o,s,a),mapResult:f=>f.map(h=>{const y={...h};for(const $ of m)y[$]=Hu(y[$],s,a);return y})}},vu={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:Xn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},Gu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Qr=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},Ki=(t,e)=>{if(Qr(t)){e.start??=t,e.end??=t;return}if(!Gu(t))return;const r=t.$eq;Qr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Qr(n)&&(e.start??=n),Qr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Ki(a,e)}},zu=(t,e,r,n)=>{const o=Wi(e,n),i=new Set,s={},a=(l,m)=>{for(const[f,h]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(h)){for(const $ of h)a($,m||f==="$or");continue}if(f.startsWith("$"))continue;const y=oe(e,f,r);if(y.property.type==="timestamp"){if(m)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(y.canonicalName),Ki(h,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 c=[...i][0];if(!c||c!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const u=l=>{const m=[];for(const[f,h]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(h)){const y=h.map($=>u($)).filter($=>$!==void 0);y.length>0&&m.push([f,y]);continue}!f.startsWith("$")&&oe(e,f,r).property.type==="timestamp"||m.push([f,h])}return m.length>0?Object.fromEntries(m):void 0},p=u(t);return{property:o,propertyName:c,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Ji=(t,e,r,n,o)=>{const i=ht([t,...ut(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return zu(i,r,n,o)},Xi=(t,e,r)=>ht([t,{[e]:r}]),Wu=new Set(["day","week","month","quarter","year"]),Ku={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ju=t=>{if(typeof t!="string"||!Wu.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Zi=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Zn=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Zn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Zn(r))),e},Xu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Ku[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=Ju(e.args?.granularity),s=Wi(r,"$averagePerPeriod"),a=Zn(e.pred),c=ht([t.query,...ut(e)]),u=Zi(t);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const p=Zi(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],c&&(p.query=c);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),m=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:u},{name:m,logicform:p}],expression:`${l} / NULLIF(${m}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},Zu={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}}},kt=t=>{throw new d("INVALID_CASE_ARGS",t)},ed=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&kt("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&kt("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&kt("$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)&&kt("$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]))&&kt(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&kt("$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}},td=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},Hr=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},eo=t=>String(Hr(t)),rd=(t,e,r)=>{if(t===e)return[t,e];const n=td((e-t)/r),o=Hr(Math.floor(t/n)*n),i=Hr(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,c)=>c===s?i:Hr(o+n*c))},nd=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}})},od={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=ed(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,c=n.maximum;if(a===c)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(eo(a))} END`;const u=rd(a,c,n.targetBuckets),p=u.slice(0,-1).map((m,f)=>{const h=u[f+1],y=f===u.length-2?"]":")";return`[${eo(m)}, ${eo(h)}${y}`}),l=p.slice(0,-1).map((m,f)=>`WHEN ${t} < ${r.value(u[f+1])} THEN ${r.value(m)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=nd(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}}},id={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(Dt("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},sd={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}}},ad={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}}},cd=new Set(["second","minute","hour","day","week","month","quarter","year"]),ud={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},es=t=>{if(typeof t!="string"||!cd.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},dd={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${ud[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,es(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=es(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},pd={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]=Dt("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return xr(t)}},ld=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}}}},fd={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:ld,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}:{}}}},md=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}}}},yd={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:md,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}:{}}}},hd={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`(${Dt("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return xr(t)}},gd=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},to=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=to(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:to(r))),e},Ad={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 m=Gn(l);return m?oe(r,m,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Ji(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=to(e.pred),c=(l,m)=>{const f=gd(t);return f.query=Xi(s.queryWithoutTime,s.propertyName,{$lte:l}),f.preds=[{...a,name:m}],f},u=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:u,logicform:c(s.end,"__newly_end__")},{name:p,logicform:c(s.start,"__newly_start__")}],expression:`${u} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},$d=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},ro=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=ro(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:ro(r))),e},wd={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=Ji(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 c={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},u=$d(t);return u.query=Xi(s.queryWithoutTime,s.propertyName,c),u.preds=[{...ro(e.pred),name:r}],{kind:"query",logicform:u}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Ed=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},_d=({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=ae(e.pred);a.name="__period_diff_current__";const c=Ed(t);c.preds=[a];const u=ht([t.query,...ut(e)]);u&&(c.query=u);const p={pred:ae(e.pred),...e.args?{args:e.args}:{}},l=Xn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,comparisonOf:m,...l.partitionQuery?{partitionQuery:l.partitionQuery}:{},...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} - ${f}`}},Id={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:_d,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Sd=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},bd=({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=ae(e.pred);a.name="__period_growth_current__";const c=Sd(t);c.preds=[a];const u=ht([t.query,...ut(e)]);u&&(c.query=u);const p={pred:ae(e.pred),...e.args?{args:e.args}:{}},l=Xn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,comparisonOf:m,...l.partitionQuery?{partitionQuery:l.partitionQuery}:{},...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} / NULLIF(ABS(${f}), 0) - 1`}},Rd={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:bd,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Nd={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}}},Od={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]=Dt("$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}:xr(t)}},ts=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},no=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=no(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:no(r))),e},Td={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(h=>typeof h.pred=="string"&&h.pred===o||vn(h)===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((h,y)=>y!==s),c=no(e.pred),u=ts(t);u.preds=[{...c,name:"__share_numerator__"}];const p=ht([t.query,...ut(e)]);p&&(u.query=p);const l=ts(t);l.groupby=a,l.preds=[{...c,name:"__share_denominator__"}];const m=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),f=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:m,logicform:u},{name:f,logicform:l}],expression:`${m} / NULLIF(${f}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Pd={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}}},rs=(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 c=t[a];if(!c)continue;if(s){o+=c,c===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(c==="'"||c==='"'||c==="`"){s=c,o+=c;continue}const u=t.slice(a,a+2);if(c===";"||u==="--"||u==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(c==="?"){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+=c}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},Ld=new Set(["boolean","date","number","entity","object","string"]),Cd=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},Dd=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!Ld.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}:{}}},Md={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 rs(t.sql,Cd(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 Dd(t,e)}},Ud=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]},qd=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},kd=(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=Ud(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=ae(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,qd(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const c=n.map(({name:p})=>p).filter(p=>!!p),u=ae(t);return u.from=a,u.query=r,u.preds=[{pred:s,name:s},...c.map(p=>({pred:p,name:p}))],delete u.groupby,delete u.having,delete u.entity_id,delete u.propertyResolve,u},jd={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?kd(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}}},xd={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}}},Bd=new Set(["string","number","boolean","date","entity","object"]),oo=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&Bd.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")},Vd={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 oo(t.args?.type),t},toSQL({args:t,sql:e}){return oo(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...oo(e.type),isArray:!1}}},Yd={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}}},ns="__scalarExtremumInputs",io=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return io(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:io(r)??[]))];if(e.length===1)return e[0]}},Fd=t=>{const e=ae(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},Qd=(t,e)=>{if(e.args?.[ns]===!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}:ae(o),a=s.name??`__scalar_extremum_input_${i}__`,c=s.schema??io(s);return{...s,name:a,...c?{schema:c}:{}}}),n=Fd(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,[ns]:!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}:{}}},Hd=(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)`},vd=(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}},os=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?Qd(e,r):void 0},toSQL(e){const r=Dt(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??Hd(t,r)},getOutputProperty({name:e,inputProperties:r}){return vd(t,e,r)}}),Gd=os("$least"),zd=os("$greatest"),so={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"}},Wd={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}}},Kd=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${so[t].en}`:`${e}${so[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}}}),Jd=Object.freeze(Object.keys(so).map(Kd)),is=Object.freeze([Gc,Nd,sd,ad,Zu,yd,fd,vu,Rd,Id,Xu,wd,Ad,Wc,Od,hd,pd,zc,Td,od,id,Pd,dd,Md,jd,xd,Vd,Yd,Gd,zd,Wd,...Jd]),Xd={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},Zd={name:"category",primalType:"string"},ep={name:"currency",primalType:"number"},tp={name:"date",primalType:"date"},rp={name:"duration",primalType:"number"},ss=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),np={name:"object",primalType:"object",hydrateResult:ss},op={name:"entity",primalType:"entity",hydrateResult:ss},ip={name:"file",primalType:"string"},sp={name:"humanName",primalType:"string"},ap={name:"ID",primalType:"string"},cp={name:"image",primalType:"string"},up={name:"int",primalType:"number"},dp={name:"name",primalType:"string"},pp={name:"number",primalType:"number"},lp={name:"order",primalType:"number"},fp={name:"percentage",primalType:"number"},mp={name:"string",primalType:"string"},yp={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},hp={name:"timestamp",primalType:"date"},ao=Object.freeze([ap,mp,dp,sp,Zd,yp,cp,ip,pp,up,ep,fp,rp,lp,Xd,hp,tp,op,np]),gp=(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},as=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 c=gp(e[a],a,n);c&&(s[a]=c)}if(!s.getOutputProperty&&typeof o=="string"){const a=ao.find(({name:c})=>c===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 er{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new er(this.definitions(),e)}register(e){const r=as(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 Ap=Object.freeze([...is,...Fr.flatMap(({operators:t})=>t??[])]),Qe=(t=[])=>new er([...is,...Se(t).flatMap(({operators:e})=>e??[])]),jt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,cs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",$p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",us=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",wp=(t,e)=>{const r=Kc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},ds=(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}:wp(e,r)},cr=(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 c=[t.input,...t.partitionBy].map(u=>cr(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const c=[t.input,...t.partitionBy,...t.orderBy.map(({expression:u})=>u)].map(u=>cr(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const c=cr(t.input,e,r,n);return{sources:c.sources,transformations:[...c.transformations.filter(u=>u!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(c=>cr(c,e,r,n)),i={sources:o.flatMap(({sources:c})=>c),transformations:o.flatMap(({transformations:c})=>c)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...vr(t.query)]);return{sources:[...i.sources,...[...a].filter(c=>!i.sources.some(u=>u.propertyName===c)).map(c=>ds(e,r,c))],transformations:[...i.transformations.filter(c=>c!=="projection"),`operator:${t.operator}`]}};function vr(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(...vr(o));else r==="$expr"&&us(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const tt=t=>t.kind==="window"?[...tt(t.input),...t.partitionBy.flatMap(tt)]:t.kind==="cumulative"?[...tt(t.input),...t.partitionBy.flatMap(tt),...t.orderBy.flatMap(({expression:e})=>tt(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?tt(t.input):t.kind==="operator"?[...vr(t.query),...t.input?tt(t.input):[],...(t.inputs??[]).flatMap(tt)]:[],ps=(t,e,r,n=Qe(),o)=>{if(t.subplans){const s=t.subplans.map(c=>ps(c,e,r,n,o)),a=new Map;for(const c of s){c.source.connectionId&&a.set(c.source.connectionId,c.source.provider);for(const u of c.source.connections??[])a.set(u.connectionId,u.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:c})=>c.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([c,u])=>({connectionId:c,provider:u}))},outputs:t.projections.map(({name:c})=>{const u=s.flatMap(({outputs:p})=>p.filter(l=>l.name===c));return{name:c,sources:u.flatMap(({sources:p})=>p),transformations:[...new Set([...u.flatMap(({transformations:p})=>p),t.sumPartition?"sum-partition":t.splitGroup?"split-group":"compose"])]}}),filters:s.flatMap(({filters:c})=>c)}}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),...(t.mappingSourcePlan?.sourcePlan?.enrichmentJoins??t.mappingSourcePlan?.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...cr(s.expression,t,e,n)})),filters:[...new Set([...vr(t.query),...t.projections.flatMap(({expression:s})=>tt(s))])].map(s=>ds(t,e,s))}},De=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Ep=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,ls=t=>{const e=Ep.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}},fs=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(!ls(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}`)}}}},_p=new Set(["second","minute","hour","day","week","month","quarter","year"]),Gr=t=>typeof t=="string"&&_p.has(t),co=(t,e=Se())=>Gr(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 gt{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=Se(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:c})=>!a||!c))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");fs(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.propertySql!==void 0&&(s.mappingType!=="property"||typeof s.propertySql!="string"||s.propertySql.trim().length===0))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping propertySql requires a property item and a non-empty SQL expression");if(s.granularity!==void 0&&(s.mappingType!=="property"||!co(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.propertySql||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn or propertySql, and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||typeof s.predItem?.pred!="string"||s.predItem.operator!==void 0&&!s.predItem.operator))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem pred; operator must be non-empty when supplied");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")}fs(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}findById(e,r){const n=this.#e.get(e)?.filter(o=>(o.id??o.source)===r)??[];if(n.length>1)throw new d("SCHEMA_MAPPING_ID_AMBIGUOUS",`Schema mapping id ${r} is ambiguous across connections for ${e}`,{schemaId:e,mappingId:r,connectionIds:n.map(({connectionId:o})=>o)});return n[0]}definitions(){return[...this.#e.values()].flat()}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Ip=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),zr=t=>!te(t)||!Array.isArray(t.properties)?[]:t.properties.filter(te),ms=new Set(["second","minute","hour","day","week","month","quarter","year"]),Sp={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},ys=(t,e)=>{const r=e[t];return te(r)?r:Object.values(e).find(n=>te(n)&&(n.id===t||n._id===t))},hs=(t,e)=>{const r=t&&e?zr(ys(t,e)).find(o=>o.type==="timestamp"):void 0,n=r?.name??r?.id??r?._id;return typeof n=="string"&&n.length>0?n:void 0},gs=(t,e,r)=>{const n=ys(t,r);if(!n)return;const i=zr(n).map(s=>{const c=[s.id,s._id,s.name].filter(u=>typeof u=="string").filter(u=>e===u||e.startsWith(`${u}_`)).sort((u,p)=>p.length-u.length)[0];return c?{property:s,key:c}: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"?gs(i.property.ref,e.slice(i.key.length+1),r):void 0},xt=(t,e,r)=>{const n=(o,i,s)=>{const u=zr(r[o]).map(h=>{const y=typeof h.id=="string"?h.id:void 0,$=typeof h.name=="string"?h.name:void 0,A=[y,$].filter(g=>!!g&&(i===g||i.startsWith(`${g}_`))).sort((g,w)=>w.length-g.length)[0];return A?{property:h,key:A}:void 0}).filter(h=>!!h).sort((h,y)=>y.key.length-h.key.length)[0];if(!u)return;const p=String(u.property.id??u.property.name),l=i===u.key?"":i.slice(u.key.length+1);if(!l)return p;const m=typeof u.property.ref=="string"?u.property.ref:void 0;if(!m||s.has(m))return;const f=n(m,l,new Set(s).add(m));return f?`${p}_${f}`:void 0};return n(t,e,new Set([t]))},uo=(t,e,r)=>{const n=zr(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 uo(n.ref,e.slice(n.id.length+1),r)}},As=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$s=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),ws=t=>{if(!te(t))return t;if(te(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},bp=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),Rp=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(c=>te(c)&&(c.id===t||c._id===t));if(!te(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:te(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(c=>{if(!te(c)||typeof c.name!="string")return;const u=c.codeLength??c.code_length;return Number.isInteger(u)&&Number(u)>0?{name:c.name,codeLength:Number(u)}:void 0});if(i.length===0||i.some(c=>c===void 0))return;const s=o[0],a=Array.isArray(n)?te(s)&&s.use_full_length===!0?"zero-padded":"compact":te(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(c=>c!==void 0),storage:a}},Np=(t,e,r)=>{const n=Rp(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,c)=>a+c.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})},Op=(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}))]},po=(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(h=>te(h)?po(h,e):h);continue}if(!te(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!te(i.query)||!bp(s)){r[o]=i;continue}const a=i.entity_level,c=typeof a=="string"&&a.length>0?a:Np(i.schema,s,e);if(!c){r[o]=i;continue}const{entity_id:u,entity_level:p,...l}=i,m=po(i.query,e),f=Object.keys(l).filter(h=>h!=="schema"&&h!=="version"&&h!=="query");(Object.keys(m).length>0||f.length>0)&&(r[o]={...l,query:m}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:c}},condition:s})}return Op(r,n)},Tp=(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}},Es=(t,e)=>{if(!te(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(!te(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(!te(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}:{}}},rt=(t,e,r,n=!1)=>{if(Array.isArray(t))return t.map(u=>rt(u,e,r));if(!te(t))return t;const o=ws(t);if(o!==t)return o;const i=t,s=typeof i.schema=="string"?i.schema:r,a={};for(const[u,p]of Object.entries(i))u==="skip"||u==="_snapshot"||u==="_snapshots"||(a[u]=rt(p,e,s,u==="from"));if(typeof i.version=="string"&&/^1\./.test(i.version)&&(a.version="2.0"),i.version===void 0&&(n||typeof i.schema=="string"&&(Array.isArray(i.preds)||Array.isArray(i.groupby)||i.from!==void 0))&&(a.version="2.0"),Array.isArray(i.groupby)){const u=i.groupby;a.groupby=u.map(p=>{if(!te(p))return p;const l=rt(p,e,s);if(!te(l))return l;const{_id:m,level:f,...h}=l;if(typeof m=="string"&&m.startsWith("$")){const $=m.slice(1);if(!ms.has($))throw new d("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${m}`,{groupby:m});const E=hs(s,e);if(!E)throw new d("LEGACY_TIME_GROUPBY_TIMESTAMP_REQUIRED",`Legacy time groupby ${m} requires a timestamp Property in Schema ${s??"(unknown)"}`,{groupby:m,schemaId:s});return{...h,pred:E,operator:"$dateBucket",args:{...te(h.args)?h.args:{},granularity:$},...h.name===void 0?{name:`${E}(${$})`}:{}}}const y={...h,...h.pred===void 0&&typeof m=="string"?{pred:m}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...te(y.args)?y.args:{},granularity:f}),y})}const c=i.skip;if(typeof c=="number"&&Number.isInteger(c)&&c>=0){const u=i.limit;c===0?delete a.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&c%u===0?a.page=c/u+1:a.skip=c}else c!==void 0&&(a.skip=rt(c,e,s));if(i.operator&&typeof i.operator=="string"){const u=Tp(i.operator,te(a.args)?a.args:{});u.operator&&(a.operator=u.operator),a.args=u.args;const p=typeof i.pred=="string"&&i.pred.startsWith("$")?i.pred.slice(1):"",l=Sp[p];if(i.operator==="$count"&&(ms.has(p)||l)){const m=hs(s,e);if(!m)throw new d("LEGACY_TIME_COUNT_TIMESTAMP_REQUIRED",`Legacy $count($${p}) requires a timestamp Property in Schema ${s??"(unknown)"}`,{schemaId:s,pred:i.pred});a.operator="$countDistinct",a.pred=l?{operator:`$${l}`,pred:m}:{operator:"$dateBucket",pred:m,args:{granularity:p}}}if(i.operator==="$comp"||i.operator==="$compabs"){const m=te(a.args)?a.args.preds:void 0;if(!Array.isArray(m)||m.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${i.operator} requires exactly 2 preds in args.preds`);const f={operator:"$subtract",pred:m,args:{nullAsZero:!0}};a.operator=i.operator==="$comp"?"$subtract":"$abs",a.pred=i.operator==="$compabs"?f:m,a.args=i.operator==="$comp"?{nullAsZero:!0}:{}}if(i.operator==="$switch"){const m=te(a.params)?a.params:a.args;a.operator="$case",a.args=Es("$switch",m),delete a.params}if(i.operator==="$piecewise"){const m=typeof a.pred=="string"?a.pred:typeof i._id=="string"?i._id:void 0;if(e&&s&&m&&gs(s,m,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:s,property:m});const f=te(a.params)?a.params:te(a.args)?a.args:{};a.operator="$case",a.args=Array.isArray(f.cases)?Es("$piecewise",f):{mode:"auto",buckets:Number.isInteger(f.buckets)?f.buckets:10},delete a.params}Ip.has(i.operator)&&typeof a.pred=="string"&&(a.pred={operator:"$sum",pred:a.pred})}return i.params!==void 0&&a.args===void 0&&(a.args=Array.isArray(i.params)?{values:rt(i.params,e,s)}:rt(i.params,e,s)),i.inputs!==void 0&&a.pred===void 0&&Array.isArray(i.inputs)&&(a.pred=i.inputs.map(u=>rt(u,e,s)),te(a.args)&&delete a.args.inputs),i.pred===void 0&&typeof i.operator=="string"&&i.operator==="$sql"&&typeof i.sql=="string"&&(a.args={...te(a.args)?a.args:{},sql:i.sql},delete a.sql),i.$options!==void 0&&a.$regex!==void 0?(a.args={...te(a.args)?a.args:{},options:i.$options},delete a.$options):typeof i.$eq=="string"&&typeof i.$options=="string"?(a.args={...te(a.args)?a.args:{},options:i.$options},delete a.$options):"$options"in i&&$s(i.$gte)&&$s(i.$lte)&&delete a.$options,i.query&&te(i.query)&&(a.query=Pp(i.query,e,s)),a},Pp=(t,e,r)=>{const n=rt(t,e,r);for(const[o,i]of Object.entries(n))n[o]=ws(i);return po(n,e)},_s=(t,e)=>{const r=te(t)?t:void 0,n=rt(t,e);if(!te(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],_s(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Lp(n,e):n},Lp=(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 c of n)te(c)&&typeof c.schema=="string"&&i.add(c.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(c=>te(c)&&typeof c.pred=="string"?xt(o,c.pred,e):void 0):[];for(const c of i)if(Array.isArray(r.groupby)&&r.groupby.map((u,p)=>{if(!te(u)||typeof u.pred!="string")return u;const l=c===o?xt(c,u.pred,e):xt(c,uo(o,s[p]??"",e)??u.pred,e);if(!l)return u;const m=l.split("_").at(-1)??u.pred;return{...u,pred:l,name:m}}),te(r.query))for(const u of As(r.query)){const p=xt(o,u,e);if(!(c===o?p:xt(c,(p&&uo(o,p,e))??u,e))&&c===o)throw new Error(`Cannot align legacy query field ${u} in Schema ${c}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((c,u)=>{if(!te(c)||typeof c.pred!="string")return c;const p=s[u];return p?{...c,pred:p}:c})),te(r.query)){const c=r.query,u=As(c).map(p=>[xt(o,p,e)??p,c[p]]);a.query=Object.fromEntries(u)}return a},Cp=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(te(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,"$")},lo=t=>{if(Array.isArray(t))return t.map(lo).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,lo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Dp=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},Mp=(t,e,r)=>{const n=t.comparable;if(!r||n!=null&&typeof n!="string")return t.comparable;const o=n==="asc"?1:n==="desc"?-1:n==null&&t.is_comparable===!0?t.comparable_order===-1?-1:1:void 0;if(o===void 0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!e)return;const i=e.map(s=>Array.isArray(s)?s[0]:s);if(!(i.length===0||i.some(s=>typeof s!="string")))return{values:[...new Set(i)],direction:o}},Up=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}},Is=(t,e=[],r=!0)=>{const n=Se(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const c=lo(a),u=c,l=(Array.isArray(u.properties)?u.properties:[]).some(g=>g.is_observation===!0)||u.is_observation===!0,m=u.is_snapshot===!0,f=typeof c.id=="string"&&c.id.length>0?c.id:r&&typeof c._id=="string"&&c._id.length>0?c._id:c.id,{properties:h}=c,y=Object.fromEntries(Object.entries(c).filter(([g])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(g):g!=="properties")&&g!=="properties"&&!i.has(g))),$=h.map(g=>{const w=g,L=typeof w.id=="string"&&w.id.length>0?w.id:r&&typeof w._id=="string"&&w._id.length>0?w._id:w.id,{udf:I,...S}=w,R=r?Dp(w):void 0,N=Mp(w,R,r),D=Up(I),F=r&&N!==void 0&&w.type==="string"?"category":w.type==="object"?"entity":w.type,V=F==="entity"||w.primal_type==="entity"||w.primal_type==="object";return{...r?Object.fromEntries(Object.entries(S).filter(([M])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order","comparable","enum"].includes(M)&&(M!=="level"||V))):S,type:F,...r&&R&&!Array.isArray(w.constraints?.enum)?{constraints:{...w.constraints,enum:R}}:{},...w.primal_type==="object"?{primal_type:"entity"}:{},...L!==void 0?{id:L}:{},...D!==void 0?{udf:D}:{},...N!==void 0?{comparable:N}:{}}});let E={};for(const g of n)for(const w of g.schemaMetadata?.keys??[])c[w]!==void 0&&(E={...E,[w]:c[w]});for(const g of n)E={...E,...g.normalizeLegacySchema?.({source:c,properties:$})};const A={...y,...f!==void 0?{id:f}:{},properties:$,...r&&(m||l)?{temporalSemantics:"snapshot"}:{},...E};o[s]=A}return o},Ss=Symbol("legacy-empty-source"),bs=t=>t!==void 0&&Ss in t,Rs=(t,e,r,n=[],o=r?[r]:[])=>{const i=[...e],s=new Set(n);for(const[a,c]of Object.entries(t)){const u=c,p=typeof u.id=="string"&&u.id.length>0?u.id:typeof u._id=="string"&&u._id.length>0?u._id:a;if(i.some(h=>h.schemaId===p))continue;const l=typeof u.db=="string"&&u.db.trim().length>0?u.db.trim():void 0;if(typeof u.from!="string"||u.from.trim().length===0){if(l){i.push({schemaId:p,connectionId:l,source:p});continue}for(const h of new Set(o.filter(Boolean))){const y={schemaId:p,connectionId:h,source:`legacy-empty-schema:${p}`,[Ss]:!0};i.push(y)}continue}const m=l??r;if(!m){if(s.has(p)||s.has(a))throw new d("LEGACY_SCHEMA_FROM_CONNECTION_REQUIRED",`Cannot create a Schema mapping for legacy Schema ${p}: provide Schema.db or one unambiguous connection`,{schemaId:p});continue}const f=u.from.trim();i.push({schemaId:p,connectionId:m,source:`legacy-schema-from:${p}`,sourceSql:f})}return i},Bt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qp=t=>Bt(t)&&typeof t.schema=="string"&&Bt(t.query),kp=t=>Bt(t)&&["preds","groupby","from","having","sort","limit","limitBy","page"].some(e=>t[e]!==void 0),ur=(t,e,r,n="")=>{if(typeof t=="string"){r.push({reference:n?`${n}_${t}`:t,use:e});return}t&&(Wr(t.query,r,n),Array.isArray(t.pred)?t.pred.forEach(o=>ur(o,e,r,n)):ur(t.pred,e,r,n))},Wr=(t,e,r="")=>{if(t)for(const[n,o]of Object.entries(t)){if(n==="$and"||n==="$or"){Array.isArray(o)&&o.forEach(s=>{Bt(s)&&Wr(s,e,r)});continue}if(n==="$expr"){Bt(o)&&"pred"in o&&Bt(o.pred)&&ur(o.pred,"query",e,r);continue}if(n.startsWith("$"))continue;const i=r?`${r}_${n}`:n;qp(o)&&!kp(o)?(o.entity_id!==void 0&&o.entity_id!=="placeholder"&&e.push({reference:i,use:"query"}),Wr(o.query,e,i)):e.push({reference:i,use:"query"})}},dr=t=>{const e=[];return Wr(t.query,e),t.preds?.forEach(r=>ur(r,"pred",e)),t.groupby?.forEach(r=>ur(r,"groupby",e)),e},jp=(t,e)=>e.length>0&&dr(t).some(({reference:r})=>r===e);class fo{#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 xp=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)}},Ns=t=>{xp(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)})},Bp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Vp=(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 c=a,u=Object.keys(c).filter(p=>p!=="sql");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:u});if(typeof c.sql!="string"||c.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(n.isArray&&t.isArray===!1)throw new d("INVALID_IS_ARRAY",`Property ${t.name} of type ${t.type} must be an array`,{property:t.name,type:t.type});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; received ${JSON.stringify(a)}`,{property:t.name,comparable:a});const c=a;if(Object.keys(c).some(u=>u!=="values"&&u!=="direction")||!Array.isArray(c.values)||c.values.length===0||c.values.some(u=>typeof u!="string")||new Set(c.values).size!==c.values.length||c.direction!==1&&c.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1; received ${JSON.stringify(a)}`,{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??n.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&&!Bp.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},mo=(t,e,r=[])=>{const n=Se(r),o=n.reduce((f,h)=>h.prepareSchema?.(f)??f,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});if(o.partition!==void 0&&typeof o.partition!="function")throw new d("INVALID_SCHEMA_PARTITION",`Schema ${o.id} partition must be a function`,{schemaId:o.id});const i=n.flatMap(f=>f.propertyMetadata?[f.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:f})=>f));let a=o.properties.map(f=>{const h=Object.fromEntries(Object.entries(f).filter(([$])=>!s.has($))),y=Vp(h,e);return i.reduce(($,E)=>({...$,...E.resolve(f,$,o)}),y)});for(const f of i)a=[...f.resolveAll?.(a,o.properties,o)??a];Ns(a);const c=n.flatMap(f=>f.schemaMetadata?[f.schemaMetadata]:[]);let u={};for(const f of c)u={...u,...f.resolve(o,a)};const p=new Set(n.flatMap(f=>[...f.schemaMetadata?.keys??[],...f.legacySchemaKeys??[]])),m={...Object.fromEntries(Object.entries(o).filter(([f])=>!p.has(f))),properties:a,...u};for(const f of n)f.validateResolvedSchema?.(m);return m};le.extend(ui),le.extend(tr),le.extend(Cr);const Yp="YYYY-MM-DD HH:mm:ss",Fp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Os=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Qp=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Kr=["second","minute","hour","day","week","month","quarter","year"],At=t=>Object.prototype.toString.call(t)==="[object Object]",Ts=(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(At(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Os.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=>Ts(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`)},yo=t=>!At(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),Vt=t=>le(t).format(Yp),Hp=(t,e)=>Kr.find(r=>r in t||e!==void 0),vp=(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),Ps=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Hp(t,void 0)??"day";let i=le(e).millisecond(0);for(const a of[...Kr].reverse()){const c=t[a];typeof c=="number"&&(i=vp(i,a,c));const u=n?.[a];typeof u=="number"&&u!==0&&(i=i.add(u,a))}const s=o==="week"?"isoWeek":o;return{$gte:Vt(i.startOf(s)),$lte:Vt(i.endOf(s))}},Gp=(t,e)=>{const r=le(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:Vt(o()),$lte:Vt(r.endOf("day"))}},ho=async(t,e)=>{const r=le(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=le(n).endOf(i),a=le(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const c=s.isBefore(r)?s:r;return{...t,$lte:Vt(c)}},go=async(t,e)=>De(t)?t:t instanceof Date||typeof t=="string"&&le(t).isValid()?Vt(t):typeof t=="string"&&Fp.has(t)?ho(Gp(t,e.now),e):yo(t)?ho(Ps(t,e.now),e):t,Ls=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Jr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>go(o,r)));const n=await go(e,r);return t==="$eq"&&At(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?At(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&At(n)&&"$lte"in n?n.$lte:n},Jr=async(t,e)=>{if(De(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Jr(o,e)));if(!At(t))return go(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)&&(!yo(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(yo(t))return ho(Ps(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Ls("$eq",r[0][1],e);if(At(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Qp.has(o)&&Ts(i,o),n[o]=Os.has(o)?await Ls(o,i,e):await Jr(i,e);return n},zp=(t,e)=>e.property.primal_type==="date"?Jr(t,e):t,Xr=(t=[])=>new fo([...ao,...Se(t).flatMap(({semanticTypes:e})=>e??[])]),Cs=(t,e)=>{const r=new fo(t.definitions());for(const n of Se(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},Ds=t=>!t.isArray&&(t.primal_type!=="number"||t.type==="ID"||t.type==="category"||t.is_categorical===!0),Ms=(t,e,r)=>{const n=t.mappings??[];if(!n.some(i=>i.mappingType==="property"||i.mappingType==="predItem"))return{};const o=n.find(i=>i.mappingType==="property"&&(i.sourceColumn||i.propertySql)&&i.propertyTarget?.some(s=>e.properties.find(({id:c,name:u})=>c===s||u===s)?.id===r.id));return o?{...o.sourceRef?{sourceRef:o.sourceRef}:{}}:void 0},Ao=t=>{if(!(t instanceof d&&t.code==="PROPERTY_NOT_FOUND"))throw t},Wp=(t,e,r)=>{const n=r.plugins.filter(m=>!Fr.some(f=>f.name===m.name)),o=Is(e,n),i=Xr(n),s=new Map,a=m=>{const f=s.get(m);if(f)return f;const h=mo(Di(m,o),i,n);return s.set(m,h),h},c=a(t),u=new Set,p=m=>{for(const f of m.mappings??[]){if(f.mappingType!=="predItem"||!f.sourceColumn||!f.predItem?.query||typeof f.predItem.pred!="string"||f.predItem.schema&&f.predItem.schema!==t)continue;try{oe(c,f.predItem.pred,a)}catch($){Ao($);continue}const h=dr({query:f.predItem.query}).filter(({use:$})=>$==="query").map(({reference:$})=>$),y=new Set(h.flatMap($=>{try{return[oe(c,$,a).canonicalId]}catch(E){return Ao(E),[]}}));for(const $ of f.propertyTarget?.length?[f.propertyTarget.join("_")]:h)try{const E=oe(c,$,a);y.has(E.canonicalId)&&Ds(E.property)&&u.add(E.canonicalName)}catch(E){Ao(E)}}},l=(m,f,h,y)=>{for(const $ of m.properties){const E=Ms(f,m,$);if(!E)continue;const A=oe(m,$.id).canonicalName,g=h?`${h}_${A}`:A;if(Ds($)&&(!h||$.type!=="ID")&&u.add(g),$.primal_type!=="entity"&&$.primal_type!=="object"||!$.ref||E.sourceRef||y.has($.ref))continue;const w=a($.ref),L=w.properties.find(S=>S.type==="ID");if(!L)continue;let I;try{I=r.get(w.id,f.connectionId)}catch(S){if(!(S instanceof d)||!["SCHEMA_MAPPING_CONNECTION_NOT_FOUND","SCHEMA_MAPPING_AMBIGUOUS"].includes(S.code))throw S;continue}Ms(I,w,L)&&l(w,I,g,new Set([...y,w.id]))}};for(const m of r.list(t))l(c,m,"",new Set([t])),p(m);return[...u]},Kp=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`)},Jp=(t,e=[])=>{const r=Se(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.propertySql!==void 0&&(o.mappingType!=="property"||typeof o.propertySql!="string"||o.propertySql.trim().length===0||!o.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping propertySql requires a valid property item and a non-empty SQL expression");if(o.granularity!==void 0&&(o.mappingType!=="property"||!co(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.propertySql||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn or propertySql, and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||typeof o.predItem?.pred!="string"||o.predItem.operator!==void 0&&!o.predItem.operator||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:Kp(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Us{#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 qs=(t=[])=>new Us([...Se(t).flatMap(e=>e.plannerSemantics??[])]);le.extend(ui),le.extend(tr),le.extend(Cr);const Yt=["second","minute","hour","day","week","month","quarter","year"],Xp=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),Zp="YYYY-MM-DD HH:mm:ss",$t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),el=(t,e)=>t==="week"?e==="week":e==="week"?Yt.indexOf(t)<=Yt.indexOf("day"):Yt.indexOf(t)<=Yt.indexOf(e),ks=(t,e,r)=>{if(typeof t!="string")return"second";const n=le(t,Zp,!0);if(!n.isValid())return"second";for(const o of[...Yt].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"},js=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])=>Xp.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(js):["second"]:r==="$gte"||r==="$gt"?[ks(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[ks(n,"upper",r==="$lte")]:["second"])},tl=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&Yt.includes(n))return n}return e.granularity??"day"}},rl=(t,e,r,n,o=Se(),i=Qe(o))=>{const s=r.mappings??[],a=s.filter($=>$.granularity!==void 0),c={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some($=>!co($.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find($=>Gr($.granularity)&&!$.propertyTarget?.every(E=>$t(e,E)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const $ of a)for(const E of o){const A=E.mappingGranularity;if(!A||!A.isGranularity($.granularity))continue;const g=A.validateItem?.($,c);if(g)return g}if(!(a.length>0))return;const l=$=>s.find(E=>E.mappingType==="property"&&E.propertyTarget?.some(A=>$t(e,A)?.id===$.id)),m=($,E,A="filterOrGroup")=>{const g=$t(e,$);if(!g)return`property is not available: ${$}`;const w=l(g);if(!w&&!(A==="operand"&&s.some(L=>L.mappingType==="predItem"&&typeof L.predItem?.pred=="string"&&$t(e,L.predItem.pred)?.id===g.id)))return`property is not available on grouped source: ${$}`;if(A==="filterOrGroup"&&g.primal_type==="number"&&g.type!=="category"&&g.type!=="ID")return`measure cannot be used as a grouped source dimension: ${$}`;if(g.primal_type==="date"&&(!w?.granularity||!Gr(w.granularity)||!el(w.granularity,E??g.granularity??"day")))return`time dimension ${$} is too coarse for ${E}`};function f($){if($)for(const[E,A]of Object.entries($)){if(A===void 0)continue;if(E==="$and"||E==="$or"){if(!Array.isArray(A))return"unsupported dimension query";for(const L of A){const I=f(L);if(I)return I}continue}if(E==="$expr"){if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const L=A.pred;if(typeof L!="object"||L===null||Array.isArray(L))return"unsupported expression query";const I=h(L);if(I)return I;continue}if(E.startsWith("$"))return"unsupported dimension query";const g=$t(e,E);if(!g)return`dimension property is not available: ${E}`;const w=g.primal_type==="date"?js(A):[void 0];for(const L of w){const I=m(E,L);if(I)return I}}}function h($){const E=f($.query);if(E)return E;const A=Array.isArray($.pred)?$.pred:$.pred===void 0?[]:[$.pred];for(const g of A){const w=typeof g=="string"&&($.operator==="$max"||$.operator==="$min")?$t(e,g):void 0,L=w?.primal_type==="date"?l(w)?.granularity:void 0,I=typeof g=="string"?m(g,Gr(L)?L:void 0,"operand"):h(g);if(I)return I}}const y=f(t.query);if(y)return y;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const $ of t.preds){const E=h($);if(E)return E;if(typeof $.pred!="string"||!$.operator||!i.get($.operator).supportsGroupedSourceRollup)return`PredItem ${$.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const $ of t.groupby??[]){if(typeof $.pred!="string")return"computed groupby is not covered by the grouped source";const E=$t(e,$.pred);if(!E)return`groupby property is not available: ${$.pred}`;if($.operator!==void 0&&!i.get($.operator).supportsGroupedSourceGroupby&&!o.some(g=>g.mappingGranularity?.supportsGroupby?.($)))return`computed groupby is not covered: ${$.pred}`;const A=m($.pred,tl($,E,i));if(A)return A}for(const $ of o){const E=$.mappingGranularity?.candidateReason?.(t,c);if(E)return E}},nt=t=>t.mappings?.some(e=>e.mappingType==="property"&&!!e.propertySql)??!1;function wt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?wt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:wt(e)):[]]}const Ft=t=>t.id??t.source,pr=(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)=>pr(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)&&pr(i,n[o]))},Et=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=Et(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=wt(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},$o=(t,e,r,n)=>{if(!t)return;const o={};for(const[i,s]of Object.entries(t))if(s!==void 0){if(i==="$and"&&Array.isArray(s)){const a=s.map(c=>$o(c,e,r,n)).filter(c=>c!==void 0);a.length>0&&(o[i]=a);continue}i!=="$or"&&e.some(a=>It(r,a.property,i,n)&&pr(a.condition,s))||(o[i]=s)}return Object.keys(o).length>0?o:void 0},_t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),It=(t,e,r,n)=>{if(e===r)return!0;const o=_t(t,e),i=_t(t,r);if(o&&i)return o.id===i.id;if(!n)return!1;try{return oe(t,e,n).canonicalId===oe(t,r,n).canonicalId}catch{return!1}},Pe=(t,e,r)=>{const n=He(t,e,r);if(n)return nt(t)?_t(e,r)?.id:n.column},He=(t,e,r)=>{const n=_t(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>It(e,s,r)));return o?.sourceColumn||o?.propertySql?{column:o.sourceColumn||n.id,...o.sourceRef?{sourceRef:o.sourceRef}:{},...o.propertySql?{sql:o.propertySql}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem")?void 0:{column:n.id}},Qt=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property"||n.mappingType==="predItem")||Pe(t,e,r)!==void 0,wo=(t,e,r,n,o)=>{if(Qt(t,e,r))return!0;if(!o)return!1;try{const i=oe(e,r,o);if(i.relations.length===0)return!1;for(const a of i.relations){const c=a.sourceSchema.id===e.id?t:n.get(a.sourceSchema.id,t.connectionId),u=He(c,a.sourceSchema,a.property.id),p=n.get(a.targetSchema.id,t.connectionId),l=a.targetSchema.properties.find(({type:m})=>m==="ID");if(!u||u.sourceRef||!l||Pe(p,a.targetSchema,l.id)===void 0)return!1}const s=n.get(i.schema.id,t.connectionId);return Pe(s,i.schema,i.property.id)!==void 0}catch{return!1}},xs=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem"))return;const n=Et(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Qt(e,r,i));return o?`query property is not available: ${o.property}`:void 0},nl=(t,e,r,n,o,i,s)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const a=typeof e.pred=="string"?_t(r,e.pred):void 0,c=_t(r,t.match.pred);if(!(typeof e.pred=="string"&&It(r,e.pred,t.match.pred)&&!!(a&&c))||!e.operator)return!1;if(t.match.operator===void 0){if(s.get(e.operator).kind!=="aggregate")return!1}else if(e.operator!==t.match.operator)return!1;if(Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const p=Et(t.match.query);return p!==void 0&&p.every(l=>o.some(m=>It(r,m.property,l.property,i)&&pr(m.condition,l.condition)))},ol=(t,e,r,n,o,i,s=Qe(i))=>{const a=(r.mappings??[]).flatMap(S=>{if(S.mappingType!=="predItem"||!S.sourceColumn||!S.predItem||typeof S.predItem.pred!="string")return[];const R=S.predItem,N=R.operator,D=R.pred;return typeof D!="string"?[]:[{match:{pred:D,...N?{operator:N}:{},...R.schema?{schema:R.schema}:{},...R.query?{query:R.query}:{}},column:S.sourceColumn,...S.propertyTarget?{propertyTarget:S.propertyTarget}:{}}]}),c=(r.mappings??[]).some(S=>S.mappingType==="property");if(a.length===0&&!c){const S={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const R of i??[]){const N=R.schemaMapping?.candidateReason?.(t,S);if(N)return N}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=Et(t.query),p=ae(t),l=[],m=[],f=new Map,h=S=>Qt(r,e,S)||a.some(R=>{const N=Et(R.match.query)??[];return N.some(F=>It(e,F.property,S,o))?(R.propertyTarget?.length?[R.propertyTarget.join("_")]:N.map(({property:F})=>F)).some(F=>It(e,F,S,o)):!1}),y=S=>{let R=_t(e,S),N=R?.name;if(!R&&o)try{const D=oe(e,S,o);R=D.property,N=D.canonicalName}catch{return}if(!(!R||R.primal_type==="number"&&R.type!=="category"&&R.type!=="ID"))return N},$=()=>{const S=new Set;for(const{reference:R,use:N}of dr(p)){if(N!=="query"||h(R))continue;const D=y(R);D&&S.add(D)}for(const R of p.groupby??[])for(const N of wt(R)){if(wo(r,e,N,n,o))continue;const D=y(N);D&&S.add(D)}return[...S]},E=S=>{const R=$();return{reason:S,...R.length>0?{missingDimensions:R}:{}}};for(const{reference:S,use:R}of dr(t)){if(R==="pred"||!y(S))continue;if(!(R==="groupby"?wo(r,e,S,n,o):h(S)))return E(`${R} property is not available: ${S}`)}if(!u&&a.length>0)return"query contains $or or another unsupported logical expression";for(const[S,R]of(t.preds??[]).entries()){const N=Et(R.query);if(!N&&a.length>0)return`PredItem ${S} query contains an unsupported logical expression`;if(a.length>0){const F=t.groupby?.length?[...N??[]]:[...u??[],...N??[]],V=a.filter(K=>nl(K,R,e,R.schema??e.id,F,o,s));if(V.length===0){const K=wt(R);if(!(K.length===0&&R.operator!==void 0&&s.get(R.operator).requiresProperty===!1)&&(K.length===0||K.some(re=>!Qt(r,e,re))))return`PredItem ${S} is not mapped`;continue}if(V.length>1)return`PredItem ${S} matches multiple mapping rules`;const x=V[0],M=Et(x.match.query)??[];f.set(S,M),t.groupby?.length||m.push(...M);const j=p.preds?.[S];if(j){const K=$o(j.query,M,e,o);K?j.query=K:delete j.query}l.push({predIndex:S,column:x.column});continue}const D=wt(R).find(F=>!Qt(r,e,F));if(D)return`PredItem ${S} property is not available: ${D}`}const A=(u??[]).filter(({property:S})=>!Qt(r,e,S));for(const[S]of(t.preds??[]).entries()){const R=A.find(N=>!f.get(S)?.some(D=>It(e,D.property,N.property,o)&&pr(D.condition,N.condition)));if(R){const N=y(R.property);return{reason:`PredItem ${S} cannot apply root query dimension: ${R.property}`,...N?{missingDimensions:[N]}:{}}}}const g=$o(p.query,m,e,o);g?p.query=g:delete p.query;const w=xs(p.query,r,e);if(w)return w.startsWith("query property is not available:")?E(w):w;for(const[S,R]of(p.preds??[]).entries()){const N=xs(R.query,r,e);if(N)return N.startsWith("query property is not available:")?E(`PredItem ${S} ${N}`):`PredItem ${S} ${N}`}for(const S of p.groupby??[]){const N=wt(S).find(D=>!wo(r,e,D,n,o));if(N)return E(`groupby property is not available: ${N}`)}const L=rl(p,e,r,o,i,s);if(L)return L;const I={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const S of i??[]){const R=S.schemaMapping?.candidateReason?.(p,I);if(R)return R}return{mapping:r,logicform:p,predRewrites:l,priority:r.priority??0,specificity:l.length}},il=(t,e,r,n={})=>{const o=n.plugins?Se(n.plugins):r.plugins,i=n.operators??Qe(n.plugins),s=[],a=[];for(const l of r.list(e.id)){if(n.mappingCandidates&&!n.mappingCandidates.includes(Ft(l))){a.push({mappingId:Ft(l),reason:"mapping is not a partition candidate"});continue}const m=ol(t,e,l,r,n.resolveSchema,o,i);typeof m=="string"?a.push({mappingId:Ft(l),reason:m}):"reason"in m?a.push({mappingId:Ft(l),...m}):s.push(m)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,m=a.filter(({reason:h})=>h!=="mapping is not a partition candidate"),f=m.length>0&&m.every(({missingDimensions:h})=>h&&h.length>0)?[...new Set(m.flatMap(({missingDimensions:h})=>h??[]))]:[];throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",f.length>0?`Schema\u300C${l}\u300D\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u67E5\u8BE2\u6240\u9700\u7EF4\u5EA6\u3010${f.join("\u3001")}\u3011\u3002\u8BF7\u68C0\u67E5\u5DF2\u63A5\u5165\u6570\u636E\u8868\u7684\u7EF4\u5EA6\u7EC4\u5408\u3002`:`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:l,...f.length>0?{uncoveredDimensions:f}:{},rejectedMappings:a})}const c=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(c.length>0?c:s).reduce((l,m)=>m.priority>l.priority||m.priority===l.priority&&m.specificity>l.specificity?m:l);for(const l of s){if(l===p)continue;let m;c.length>0&&l.mapping.connectionId!==n.preferredConnectionId?m=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?m=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?m=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:m="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:Ft(l.mapping),reason:m})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:Ft(p.mapping),rejectedMappings:a}}},Bs=(t,e,r)=>{const n=t.id,o="__sdb_mapping",i=t.properties.flatMap(g=>{const w=He(e,t,g.id);return w?[{property:g,source:w}]:[]}),s=(e.mappings??[]).flatMap(g=>g.mappingType==="predItem"&&g.sourceColumn?[{column:g.sourceColumn,sourceRef:g.sourceRef}]:[]),a=new Set([...i.flatMap(({source:g})=>g.sourceRef?[g.sourceRef]:[]),...s.flatMap(({sourceRef:g})=>g?[g]:[])]),c=Fn(t,r),u=(e.enrichments??[]).filter(({id:g})=>a.has(g)).map(g=>{const w=g.temporal?(()=>{if(!c)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${g.id} requires an entity with interval semantics`);const L=He(e,t,c.start.name),I=He(e,t,c.end.name);if(!L||!I||L.sourceRef||I.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${g.id} requires base-source interval columns`);return{kind:"point-in-interval",pointSide:"target",pointColumn:g.temporal.pointColumn,intervalSide:"source",startColumn:L.column,endColumn:I.column}})():void 0;return{kind:"enrichment-left",id:g.id,source:g.source,...g.sourceSql?{sourceSql:g.sourceSql}:{},alias:`__enrichment_${g.id}`,baseAlias:n,keys:g.on,...w?{temporalCondition:w}:{}}}),p=t.properties.find(({type:g})=>g==="timestamp"),l=p?He(e,t,p.id):void 0,m=i.map(({property:g,source:w})=>({name:g.id,expression:w.sql?{kind:"property-sql",schemaId:t.id,property:g.name,propertyId:g.id,sql:w.sql,qualifier:w.sourceRef?`__enrichment_${w.sourceRef}`:n,...l?{timestampColumn:l.column}:{},...l?.sourceRef?{timestampQualifier:`__enrichment_${l.sourceRef}`}:{timestampQualifier:n}}:{kind:"column",schemaId:t.id,property:g.name,propertyId:g.id,column:w.column,qualifier:w.sourceRef?`__enrichment_${w.sourceRef}`:n}})),f=new Set(i.map(({property:g})=>g.id)),h=new Set;for(const g of[...i.map(w=>w.source),...s])f.has(g.column)||h.has(g.column)||(h.add(g.column),m.push({name:g.column,expression:{kind:"column",property:g.column,column:g.column,qualifier:g.sourceRef?`__enrichment_${g.sourceRef}`:n}}));const y={schemaId:t.id,source:e.source,connectionId:e.connectionId,...e.sourceSql?{sourceSql:e.sourceSql}:{},sourceAlias:n,fields:{},enrichmentJoins:u,projections:m,groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}};if(!i.some(({property:g})=>g.udf?.sql))return y;const $=l?p?.id:void 0,E=i.map(({property:g})=>{const w=g.udf?.sql?{kind:"property-sql",schemaId:t.id,property:g.name,propertyId:g.id,sql:g.udf.sql,qualifier:o,...$?{timestampColumn:$}:{},timestampQualifier:o}:{kind:"column",schemaId:t.id,property:g.name,propertyId:g.id,column:g.id,qualifier:o};return{name:g.id,expression:w}});for(const{column:g}of s)f.has(g)||E.some(({name:w})=>w===g)||E.push({name:g,expression:{kind:"column",property:g,column:g,qualifier:o}});const A=i.find(({property:g})=>g.type==="ID");return A&&E.push({name:"__sdb_physical_id",expression:{kind:"column",property:A.property.name,column:A.property.id,qualifier:o}}),{schemaId:t.id,source:e.source,connectionId:e.connectionId,sourcePlan:y,sourceAlias:o,fields:{},projections:E,groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}}},lr=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),fr=(t,e)=>lr(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?fr(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&fr(r,e)),Vs=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?fr(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&fr(r,e)),Ys=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),sl=(t,e)=>{const r=t.preds??[];if(!r.some(f=>!lr(f,e)&&Vs(f,e)))return;const n=new Set([...r.map(({name:f})=>f).filter(f=>!!f),...(t.groupby??[]).map(Ys).filter(f=>!!f)]);let o=0;const i=()=>{let f;do f=`__nested_component_input_${o}__`,o+=1;while(n.has(f));return n.add(f),f},s=[],a=f=>{const h=i();return s.push(typeof f=="string"?{pred:f,name:h}:{...ae(f),name:h}),h},c=f=>{if(f.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const h=ae(f);return Array.isArray(f.pred)?h.pred=f.pred.map(y=>typeof y=="string"||!fr(y,e)||lr(y,e)?a(y):c(y)):f.pred&&typeof f.pred=="object"&&(h.pred=lr(f.pred,e)?a(f.pred):c(f.pred)),h},u=r.map(f=>{const h=f.name;if(!h)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!lr(f,e)&&Vs(f,e)?{...c(f),name:h}:(s.push({...ae(f),name:h}),{pred:h,name:h})}),p=ae(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(f=>{const h=Ys(f);if(!h)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:h,name:h}}),m=ae(t);return m.from=p,m.preds=[...l,...u],delete m.query,delete m.groupby,delete m.entity_id,delete m.propertyResolve,m},al=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Fs=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:al(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Qs=(t,e)=>({...Fs(t,e),id:e.id,name:e.name,type:e.type}),mr=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},Zr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Zr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Zr(e)):[]],Eo=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Eo(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Eo(r,e))}:{}}),Hs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Hs(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:Eo(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),_o=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(De(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,c])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(c,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)},Io=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Io(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&&_o(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),cl=(t,e,r,n)=>{if(!e)return{};const o=e.includes("$TS"),i=o?t.properties.find(({type:a})=>a==="timestamp"):void 0,s=o?i&&(Pe(r,t,i.name)??i.id):void 0;return{sql:e,...s?{timestampColumn:s}:{},...s&&n?{timestampQualifier:n}:{}}},vs=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},Gs=(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}),Ht=(t,e,r,n,o,i,s,a,c="projection")=>{const u=mr(t);if(c==="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:vs(w.field),outputProperty:Gs(w.reference,w.property),sourceProperty:w.property,sourceField:w.field}}const p=e.get(t.operator);if(c==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(c==="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,m=l?.reference??t.pred,f=l?.args??t.args??{},h=m&&typeof m=="object"&&!Array.isArray(m)?Ht(m,e,r,n,o,i,s,a,c):typeof m=="string"?Ht({pred:m,name:m},e,r,n,o,i,s,a,c):void 0,y=Array.isArray(m)?m.map(w=>Ht(typeof w=="string"?{pred:w,name:w}:w,e,r,n,o,i,s,a,c)):[];if(p.requiresProperty!==!1&&!h&&y.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const $=u,E=p.getOutputProperty?.({executionContext:e.executionContext,name:$,...h?.sourceProperty?{property:h.sourceProperty}:{},...h?{inputProperty:{...h.outputProperty,name:$}}:{},...y.length>0?{inputProperties:y.map(({outputProperty:w})=>w)}:{},args:f}),A=E?.description??p.description??h?.outputProperty.description,g={...E??(h?Gs($,h.outputProperty,{isArray:!1}):{name:$,type:"number",primal_type:"number",isArray:!1}),...A!==void 0?{description:A}:{}};if(p.planExpression){const w=p.planExpression({executionContext:e.executionContext,pred:t,...h?{input:h.expression,inputProperty:h.outputProperty}:{},inputs:y.map(({expression:L})=>L),args:f,resolveKey:o,getOperator:L=>e.get(L),planQuery:i});if(w)return{expression:w,outputProperty:g,...h?.sourceProperty?{sourceProperty:h.sourceProperty}:{},...h?.sourceField?{sourceField:h.sourceField}:{}}}if(p.kind==="window"){if(!h||y.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 L=t.args?.partitionBy??[];if(!Array.isArray(L)||L.some(I=>typeof I!="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:h.expression,partitionBy:L.map(I=>n(String(I))),direction:w==="asc"?"ASC":"DESC"},outputProperty:g}}return{expression:{kind:"operator",operator:t.operator,args:f,...t.query?{query:i(t.query)}:{},...h?{input:h.expression}:{},...y.length>0?{inputs:y.map(({expression:w})=>w)}:{},...h?.sourceProperty?{property:h.sourceProperty.name,column:h.sourceProperty.id}:{},...h?.sourceField?{qualifier:h.sourceField.qualifier,schemaId:h.sourceField.schemaId}:{}},outputProperty:g,...h?.sourceProperty?{sourceProperty:h.sourceProperty}:{},...h?.sourceField?{sourceField:h.sourceField}:{}}},ul=(t,e,r,n,o,i,s,a,c,u,p,l=t)=>{const m=mr(t),f=typeof t.pred=="string"?t.pred:void 0,h=!u||!f?r:A=>{const g=r(A);return A===f?{...g,field:{...g.field,column:u}}:g},y=p?{...t,operator:p}:t,$=Ht(y,e,h,n,o,i,s,a),E=c?.resolveProjection({pred:l,schema:s,executionContext:e.executionContext,...$.sourceProperty?{sourceProperty:$.sourceProperty}:{},outputProperty:{...$.outputProperty,name:m},...l.operator?{operator:e.get(l.operator)}:{}})??{...$.outputProperty,name:m};return{name:m,expression:$.expression,outputProperty:E}},zs=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)}},So=(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},dl=(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(y=>Le(y,So(y,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:y})=>y)??[];for(const y of s){const $=y.groupBy.map(({name:E})=>E);if($.length!==a.length||$.some((E,A)=>E!==a[A]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:$});if(y.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 c=[],u=[],p=new Map;s.forEach((y,$)=>{y.projections.forEach((E,A)=>{const g=a.includes(E.name),w=p.get(E.name);if(w!==void 0&&!g)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${E.name}`,{name:E.name,childIndexes:[w,$]});if(w!==void 0)return;p.set(E.name,$),c.push({name:E.name,expression:{kind:"column",property:E.name,column:E.name}});const L=y.columnProperties?.[A];L&&u.push(L)})});const l=new Set(c.map(({name:y})=>y)),m=Object.entries(t.sort??{}).map(([y,$])=>{if(!l.has(y))throw new d("INVALID_SORT",`Sort field is not an output: ${y}`);const E=u.find(A=>A.name===y);return{name:y,direction:$===1?"ASC":"DESC",...E?.comparable?{comparable:E.comparable}:{},...E?.comparable?{expression:{kind:"column",property:y,column:y}}:{}}}),f=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:m.length>0?m:(()=>{const y=a.at(-1)??"",$=u.find(E=>E.name===y);return[{name:y,direction:"ASC",...$?.comparable?{comparable:$.comparable}:{}}]})()},h=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(c.map(({name:y})=>[y,y])),projections:c,columnProperties:u,groupBy:c.filter(({name:y})=>a.includes(y)),...t.having?{having:Io(t.having,u)}:{},orderBy:m,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...f?{groupLimit:f}:{},...h?{pagination:h}:{}}},pl=(t,e,r,n,o)=>{const i=t.groupby??[];if(i.length===0||!t.preds?.length)return;const a=i.filter(_=>typeof _.pred=="string"&&!_.operator&&!_.args).flatMap(_=>{try{const T=oe(e,_.pred,o.resolveSchema);return Array.isArray(T.property.constraints?.enum)&&T.property.constraints.enum.length>0?[{group:_,path:T}]:[]}catch{return[]}});if(a.length!==1)return;const{group:c,path:u}=a[0],p=i.filter(_=>_!==c),l=i.map(mr);if(new Set(l).size!==l.length)return;const f=(u.property.constraints?.enum).map(_=>Array.isArray(_)?_[0]:_);if(f.some(_=>typeof _!="string"||_.length===0)||new Set(f).size!==f.length)return;const h=f,y=_=>{try{return oe(e,_,o.resolveSchema).canonicalId===u.canonicalId}catch{return!1}},$=_=>Object.entries(_).some(([T,k])=>T==="$expr"||(T==="$and"||T==="$or")&&Array.isArray(k)&&k.some(U=>$(U))||!T.startsWith("$")&&y(T)),E=Object.entries(t.query??{}).filter(([_])=>y(_)),A=Object.fromEntries(Object.entries(t.query??{}).filter(([_])=>!y(_)));if(E.length>1||$(A))return;const g=E[0]?.[1],w=g===void 0?h:typeof g=="string"?[g]:typeof g=="object"&&g!==null&&!Array.isArray(g)&&Array.isArray(g.$in)?g.$in:[],L=h.filter(_=>w.includes(_));if(L.length===0)return;const I=t.preds;if(I.some(_=>typeof _.pred!="string"||_.query||_.args||!_.operator||!["$sum","$avg","$min","$max"].includes(_.operator)||_.schema&&_.schema!==e.id))return;const S=n.list(e.id);if(!S.some(_=>I.every(T=>h.every(k=>(_.mappings??[]).filter(U=>{if(U.mappingType!=="predItem"||!U.sourceColumn||typeof U.predItem?.pred!="string"||!U.predItem.query||U.predItem.schema&&U.predItem.schema!==e.id||U.propertyTarget?.length&&!y(U.propertyTarget.join("_"))||U.predItem.operator&&U.predItem.operator!==T.operator)return!1;const B=e.properties.find(G=>G.id===T.pred||G.name===T.pred),Y=e.properties.find(G=>G.id===U.predItem?.pred||G.name===U.predItem?.pred);if(!B||B.id!==Y?.id)return!1;const v=Object.entries(U.predItem.query);return v.length===1&&v.some(([G,z])=>y(G)&&z===k)}).length===1)))){if(!S.some(k=>(k.mappings??[]).some(U=>{if(U.mappingType!=="predItem"||typeof U.predItem?.pred!="string"||!U.predItem.query||U.propertyTarget?.length&&!y(U.propertyTarget.join("_")))return!1;const B=e.properties.find(Y=>Y.id===U.predItem?.pred||Y.name===U.predItem?.pred);return I.some(Y=>{const v=e.properties.find(G=>G.id===Y.pred||G.name===Y.pred);return!!(v&&B&&v.id===B.id)&&Object.keys(U.predItem?.query??{}).some(y)})})))return;const T=`${e.name}(${e.id})`;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${T}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:T,reason:"enumerated group is missing a unique conditional measure for every enum value"})}const{query:N,groupby:D,having:F,sort:V,limit:x,limitBy:M,page:j,...K}=t,Q=L.map(_=>Le({...K,...Object.keys(A).length>0?{query:A}:{},...p.length>0?{groupby:p}:{},preds:I.map(T=>({...T,query:{[c.pred]:_}}))},e,r,n,o));if(new Set(Q.map(_=>_.connectionId)).size!==1)throw new d("SPLIT_GROUP_CONNECTION_MISMATCH","Enumerated group branches must use one physical connection");const re=mr(c),ye={name:re,type:u.property.type,primal_type:u.property.primal_type,isArray:!1,...u.property.comparable?{comparable:u.property.comparable}:{}},Me=Q[0],fe=l.map(_=>({name:_,expression:{kind:"column",property:_,column:_}})),be=Me.projections.filter(_=>!p.some(T=>T.name===_.name)),se=[...fe,...be.map(({name:_})=>({name:_,expression:{kind:"column",property:_,column:_}}))];zs(se);const Re=Me.columnProperties??[],b=[...l.map(_=>_===re?ye:Re.find(T=>T.name===_)),...Re.filter(_=>!l.includes(_.name))],O=new Set(se.map(_=>_.name)),C=Object.entries(t.sort??{}).map(([_,T])=>{if(!O.has(_))throw new d("INVALID_SORT",`Sort field is not an output: ${_}`);const k=b.find(U=>U.name===_)?.comparable;return{name:_,direction:T===1?"ASC":"DESC",...k?{comparable:k,expression:{kind:"column",property:_,column:_}}:{}}}),q=t.limitBy!==void 0?{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:e.id,source:"",...Me.connectionId?{connectionId:Me.connectionId}:{},subplans:Q,splitGroup:{name:re,values:L,groupNames:l},fields:Object.fromEntries(se.map(_=>[_.name,_.name])),projections:se,columnProperties:b,groupBy:fe,...t.having?{having:Io(t.having,b)}:{},orderBy:C,rowIdentity:{kind:"group",names:l,separator:"_",nullLabel:"\u7A7A\u503C"},...q?{pagination:q}:{}}},Le=(t,e,r=Qe(),n=new gt,o={})=>{if(!o.mappingCandidates){const b=o.preplannedPartitions?.get(JSON.stringify(t));if(b)return b}const i=[...new Set((t.preds??[]).map(b=>b.schema).filter(b=>!!(b&&b!==e.id)))];if(i.length>0){const b=t.propertyResolve??{},O=[e.id,...i].map(C=>{const{having:q,sort:_,limit:T,limitBy:k,page:U,...B}=t,Y=v=>{let G=v;try{G=oe(e,v,o.resolveSchema).canonicalName}catch{}return b[C]?.[v]??b[C]?.[G]??v};return{...B,schema:C,preds:(t.preds??[]).filter(v=>(v.schema??e.id)===C).map(({schema:v,...G})=>G),...C===e.id||!t.query?{}:{query:Hs(t.query,Y)},...C!==e.id&&t.groupby?{groupby:t.groupby.map(v=>({...v,...typeof v.pred=="string"?{pred:Y(v.pred)}:{}}))}:{}}});return dl(t,O,e,r,n,o)}const s=sl(t,r);if(s)return Le(s,e,r,n,o);for(const b of t.preds??[]){if(!b.operator)continue;const O=r.get(b.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:C=>r.get(C)});if(O)return Le(O,e,r,n,o)}const a=o.semanticRegistry??qs(o.plugins);if(t.from){const b=So(t.from,e,o),O=Le(t.from,b,r,n,o),C=Qs(O,e),q={...t};delete q.from,q.schema??=C.id;const _=new gt([...n.definitions().filter(({schemaId:ee})=>ee!==C.id),{schemaId:C.id,connectionId:O.connectionId??o.preferredConnectionId??"__derived__",source:O.source||"__derived__"}],n.plugins.filter(ee=>!Fr.includes(ee))),{onSchemaMappingSelection:T,...k}=o,U=Le(q,C,r,_,k),B=new Set(U.projections.map(({name:ee})=>ee)),Y=O.rowIdentity.kind==="group"&&O.rowIdentity.names.every(ee=>B.has(ee))||O.rowIdentity.kind==="singleton"?O.rowIdentity:{kind:"generated"},v=O.groupBy.map(({name:ee})=>ee).filter(ee=>B.has(ee)),G=v.at(-1),z=O.columnProperties?.find(ee=>ee.name===G),W=t.limitBy!==void 0&&v.length>0?{count:t.limitBy,partitionBy:v.slice(0,-1),orderBy:U.orderBy.length>0?U.orderBy:v.slice(-1).map(ee=>({name:ee,direction:"ASC",...z?.comparable?{comparable:z.comparable}:{}}))}:void 0;return{...U,source:O.source||"__derived__",sourcePlan:O,sourceLogicform:t.from,rowIdentity:Y,...W?{groupLimit:W}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const c=pl(t,e,r,n,o);if(c)return c;const u=il(t,e,n,{operators:r,...o.mappingCandidates?{mappingCandidates:o.mappingCandidates}:{},...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const p=nt(u.mapping)&&e.properties.some(b=>b.udf?.sql&&He(u.mapping,e,b.id)),l=new Map(u.predRewrites.map(({predIndex:b,column:O})=>[b,O])),m=Fn(e,o.plugins),f=Uu(t,e,o.plugins),h=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),y=f?.rewriteQuery?f.rewriteQuery(h):h,$=e.id,E=new Map,A=new Map,g=new Map,w=new Map,L=b=>{const O=A.get(b);if(O)return O.alias;const C=u.mapping.enrichments?.find(T=>T.id===b);if(!C)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${b}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:b});const q=`__enrichment_${b}`,_=C.temporal?(()=>{if(!m)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${b} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:b});const T=He(u.mapping,e,m.start.name),k=He(u.mapping,e,m.end.name);if(!T||!k)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${b} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:b});if(T.sourceRef||k.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${b} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:b});return{kind:"point-in-interval",pointSide:"target",pointColumn:C.temporal.pointColumn,intervalSide:"source",startColumn:T.column,endColumn:k.column}})():void 0;return A.set(b,{kind:"enrichment-left",id:b,source:C.source,...C.sourceSql?{sourceSql:C.sourceSql}:{},alias:q,baseAlias:$,keys:C.on,..._?{temporalCondition:_}:{}}),q},I=b=>{const O=oe(e,b,o.resolveSchema);let C=$,q=u.mapping;const _=[];for(const Y of O.relations){_.push(Y.property.name);const v=_.join("_"),G=v,z=n.get(Y.targetSchema.id,u.mapping.connectionId);if(q=z,!E.has(v)){const W=Y.targetSchema.properties.filter(({type:Fe})=>Fe==="ID"),[ee]=W;if(W.length!==1||!ee)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${Y.targetSchema.id} must contain exactly one ID property`,{schemaId:Y.targetSchema.id,count:W.length});const de=Y.sourceSchema.id===e.id?u.mapping:n.get(Y.sourceSchema.id,u.mapping.connectionId),ge=Pe(de,Y.sourceSchema,Y.property.name)??Y.property.id,we=nt(de)?void 0:Y.property.udf?.sql,Ee=Pe(z,Y.targetSchema,ee.name)??ee.id,me=nt(z)?void 0:ee.udf?.sql,_e=Y.sourceSchema.properties.find(({type:Fe})=>Fe==="timestamp"),Ne=Y.targetSchema.properties.find(({type:Fe})=>Fe==="timestamp"),he=Mu(Y.sourceSchema,Y.targetSchema,o.plugins),xe=_e?Pe(de,Y.sourceSchema,_e.name)??_e.id:void 0,ve=Ne?Pe(z,Y.targetSchema,Ne.name)??Ne.id:void 0,Tt=he?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Pe(de,Y.sourceSchema,he.sourceTimestamp.name)??he.sourceTimestamp.id,targetColumn:Pe(z,Y.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:Pe(de,Y.sourceSchema,he.point.name)??he.point.id,intervalSide:"target",startColumn:Pe(z,Y.targetSchema,he.start.name)??he.start.id,endColumn:Pe(z,Y.targetSchema,he.end.name)??he.end.id}:void 0,Ye=Y.property.isArray?v:void 0;Ye&&!g.has(Ye)&&g.set(Ye,{path:Ye,sourceAlias:C,sourceColumn:ge,...we?{sourceSql:we,...xe?{sourceTimestampColumn:xe}:{}}:{},alias:`__array_${v}`}),E.set(v,{kind:"left",path:v,sourceAlias:C,sourceColumn:ge,...we?{sourceSql:we,...xe?{sourceTimestampColumn:xe}:{}}:{},targetSchemaId:Y.targetSchema.id,targetConnectionId:z.connectionId,targetSource:z.source,...z.sourceSql?{targetSourceSql:z.sourceSql}:{},...nt(z)?{targetMappingSourcePlan:Bs(Y.targetSchema,z,o.plugins)}:{},targetAlias:G,targetColumn:Ee,...Ye?{sourceArrayExpansionPath:Ye}:{},...me?{targetSql:me,...ve?{targetTimestampColumn:ve}:{}}:{},...Tt?{temporalCondition:Tt}:{}})}C=G}const T=He(q,O.schema,O.property.name);if(O.relations.length>0&&T?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${O.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:O.schema.id,property:O.property.name});const k=nt(q),U=!k&&T?.sourceRef?L(T.sourceRef):C,B={schemaId:O.schema.id,property:O.property.name,propertyId:O.property.id,column:k?O.property.id:T?.column??O.property.id,qualifier:U,...O.property.isArray?{isArray:!0}:{},...O.property.type==="tag"?{normalizeStringArray:!0}:{},...O.property.comparable?{comparable:O.property.comparable}:{},...cl(O.relations.length>0?e:O.schema,k?void 0:O.property.udf?.sql,O.relations.length>0?u.mapping:q,$)};return w.set(O.canonicalName,B),{reference:O.canonicalName,schema:O.schema,property:O.property,field:B}},S=b=>{if(b)for(const[O,C]of Object.entries(b))if((O==="$and"||O==="$or")&&Array.isArray(C))for(const q of C)typeof q=="object"&&q!==null&&!Array.isArray(q)&&S(q);else if(O==="$expr"&&typeof C=="object"&&C!==null&&!Array.isArray(C)){const q=C.pred;typeof q=="object"&&q!==null&&!Array.isArray(q)&&Zr(q).forEach(I)}else O.startsWith("$")||I(O)},R=b=>{if(De(b)){const O=So(b,e,o),C=Le(b,O,r,n,o);if(C.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${C.projections.length}`,{schemaId:b.schema,projectionCount:C.projections.length});return{kind:"logicform-subquery",plan:C}}return Array.isArray(b)?b.map(R):typeof b!="object"||b===null||b instanceof Date?b:Object.fromEntries(Object.entries(b).map(([O,C])=>[O,R(C)]))},N=b=>Object.fromEntries(Object.entries(b).map(([O,C])=>{if((O==="$and"||O==="$or")&&Array.isArray(C))return[O,C.map(_=>N(_))];if(O==="$expr"){if(typeof C!="object"||C===null||Array.isArray(C))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const _=C;if(typeof _.pred!="object"||_.pred===null||Array.isArray(_.pred)||!Object.prototype.hasOwnProperty.call(_,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const T=_.pred,k=Ht(T,r,I,V,x,N,e,o.resolveSchema,"groupby");if(k.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const U=R(_.condition);return k.outputProperty.comparable&&_o(U,T.name??T.operator??"$expr",k.outputProperty.comparable.values),[O,{kind:"expression-query",expression:k.expression,condition:k.outputProperty.comparable?{kind:"ordinal-query",comparable:k.outputProperty.comparable,condition:U}:U,properties:Zr(T)}]}if(typeof C=="object"&&C!==null&&!Array.isArray(C)){const T=Object.entries(C).find(([k])=>qt(k,o.plugins));if(T){const[k,U]=T,B=qt(k,o.plugins);if(!B)throw new Error(`Query Operator disappeared: ${k}`);const Y=I(O),v=B.plan(U,{schema:Y.schema,property:Y.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(G,z)=>n.get(G,z)});return[O,{[k]:{kind:"query-operator",operator:k,value:v.value,definition:B,...v.sources?{sources:v.sources}:{}}}]}}const q=O.startsWith("$")?void 0:I(O).property.comparable;return[O,q?{kind:"ordinal-query",comparable:q,condition:R(C)}:R(C)]})),D=b=>{const O=q=>{if(!q||typeof q!="object")return!1;if(Array.isArray(q))return q.some(O);const _=q;return Object.prototype.hasOwnProperty.call(_,"$and")||Object.values(_).some(O)};if(O(b))return b;const C=new Set(Object.keys(b).flatMap(q=>{if(q.startsWith("$"))return[];const _=oe(e,q,o.resolveSchema);return _.relations.length===1&&_.property.type==="ID"?[_.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(b).map(([q,_])=>{if(q==="$and"||q==="$or")return Array.isArray(_)?[q,_.map(W=>typeof W=="object"&&W!==null&&!Array.isArray(W)?D(W):W)]:[q,_];if(q.startsWith("$"))return[q,_];const T=oe(e,q,o.resolveSchema);if(T.relations.length===0)return[q,_];if(T.property.udf?.sql.includes("$TS")===!0||T.relations.some(({property:W})=>W.udf?.sql.includes("$TS")===!0))return[q,_];const U=T.relations.map(({property:W})=>W.name).join("_");if(E.has(U))return[q,_];const[B]=T.relations;if(!B)return[q,_];if(C.has(B.property.name))return[q,_];const Y=B.property.name,v=T.canonicalName.slice(Y.length+1),G=B.targetSchema.properties.find(({type:W})=>W==="ID");if(!G)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${B.targetSchema.id} must contain an ID property`,{schemaId:B.targetSchema.id});if(T.relations.length===1&&T.property.id===G.id)return[B.property.id,_];const z={version:t.version,schema:B.targetSchema.id,query:v?{[v]:_}:{},preds:[{pred:G.name,name:G.name}]};return[B.property.id,{$in:z}]}))},F=(t.groupby??[]).map(b=>{const O=mr(b);b.operator&&r.get(b.operator).validateGroupby?.({pred:b,executionContext:r.executionContext});const C=Ht(b,r,I,V,x,N,e,o.resolveSchema,"groupby");let q=C.expression;if(f?.group===b&&(q={kind:"column",schemaId:e.id,property:f.property.name,propertyId:f.property.id,column:"__period_start",qualifier:"__periods"}),C.sourceProperty?.isArray&&C.sourceField){const _=`groupby:${O}`;g.set(_,{path:_,sourceAlias:C.sourceField.qualifier,sourceColumn:C.sourceField.column,...C.sourceField.sql?{sourceSql:C.sourceField.sql,...C.sourceField.timestampColumn?{sourceTimestampColumn:C.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${g.size}`,...C.sourceProperty.type==="tag"?{normalizeStringArray:!0}:{},...C.sourceProperty.type==="tag"?{elementType:"string"}:{}}),q={kind:"array-element",schemaId:C.sourceField.schemaId,property:C.sourceProperty.name,expansionPath:_}}return{name:O,expression:q,outputProperty:{...C.outputProperty,name:O,isArray:!1}}});function V(b){const O=(t.groupby??[]).findIndex(q=>typeof q.pred=="string"&&q.pred===b||q.name===b),C=O>=0?F[O]:void 0;if(!C)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${b}`);return C.expression}function x(b){const O=(t.groupby??[]).findIndex(q=>typeof q.pred=="string"&&q.pred===b||q.name===b),C=O>=0?F[O]:void 0;return C?C.expression:vs(I(b).field)}const M=b=>{b.operator&&r.get(b.operator).validatePlan?.({executionContext:r.executionContext,pred:b,groupByNames:F.map(({name:O})=>O),resolveGroupName:O=>{const C=(t.groupby??[]).findIndex(q=>q.name===O||typeof q.pred=="string"&&q.pred===O);return C>=0?F[C]?.name:void 0},getOperator:O=>r.get(O)}),b.pred&&typeof b.pred=="object"&&!Array.isArray(b.pred)&&M(b.pred);for(const O of Array.isArray(b.pred)?b.pred:[])M(typeof O=="string"?{pred:O}:O)};for(const b of t.preds??[])M(b);const j=[...F,...(t.preds??[]).map((b,O)=>{const C=f?.rewritePred?.(b)??b;return ul(C,r,I,V,x,N,e,o.resolveSchema,a,l.get(O),Ui(C,t.groupby??[],e,o.resolveSchema)?"$min":void 0,b)})],K=b=>Object.fromEntries(Object.entries(b).map(([O,C])=>{if((O==="$and"||O==="$or")&&Array.isArray(C))return[O,C.map(_=>K(_))];if(O==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const q=j.find(({name:_})=>_===O)?.outputProperty.comparable;return q&&_o(C,O,q.values),[O,q?{kind:"ordinal-query",comparable:q,condition:R(C)}:R(C)]})),Q=y?D(y):void 0;S(Q);const re=b=>{S(b.query),b.pred&&typeof b.pred=="object"&&!Array.isArray(b.pred)&&re(b.pred);for(const O of Array.isArray(b.pred)?b.pred:[])re(typeof O=="string"?{pred:O}:O)};for(const b of t.preds??[])re(b);if(j.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");zs(j);const ye=new Set(j.map(({name:b})=>b)),Me=F.length>0?{kind:"group",names:F.map(({name:b})=>b),separator:"_",nullLabel:"\u7A7A\u503C"}:j.every(({expression:b})=>b.kind==="column"||b.kind==="property-sql")||j.some(({expression:b})=>b.kind==="property-sql"&&e.properties.some(({id:O,type:C})=>C==="ID"&&O===b.propertyId))?(()=>{const b=e.properties.find(({type:C})=>C==="ID");if(!b||!(o.canUsePropertyRowIdentity?.(e,b)??!0))return{kind:"generated"};const O=He(u.mapping,e,b.name);return{kind:"property",column:p&&O?"__sdb_physical_id":nt(u.mapping)&&O?b.id:O?.column??b.id,internalName:"_id"}})():{kind:"singleton"},fe=Object.entries(t.sort??{}).map(([b,O])=>{if(!ye.has(b))throw new d("INVALID_SORT",`Sort field is not an output: ${b}`);const C=j.find(q=>q.name===b);return{name:b,direction:O===1?"ASC":"DESC",...C?.outputProperty.comparable?{comparable:C.outputProperty.comparable,expression:C.expression}:{}}}),be=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},se=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:F.slice(0,-1).map(({name:b})=>b),orderBy:fe.length>0?fe:(()=>{const b=F.at(-1);return[{name:b?.name??"",direction:"ASC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}]})()},Re=w.size===0&&E.size===0&&A.size===0&&g.size===0&&!Q&&F.length===0&&j.length>0&&j.every(({expression:b})=>b.kind==="operator"&&b.operator==="$constant");return{schemaId:e.id,source:Re?"":u.mapping.source,...Re?{}:{connectionId:u.mapping.connectionId},...!Re&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},...!Re&&nt(u.mapping)?{mappingSourcePlan:Bs(e,u.mapping,o.plugins)}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:$,fields:{...Jc(e),...Object.fromEntries(e.properties.flatMap(b=>{const O=Pe(u.mapping,e,b.name);return O?[[b.name,O],[b.id,O]]:[]}))},fieldReferences:Object.fromEntries(w),joins:[...E.values()],enrichmentJoins:nt(u.mapping)?[]:[...A.values()],arrayExpansions:[...g.values()],...f?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:$,periods:f.periods,match:f.source.kind==="interval"?{kind:"interval",startColumn:Pe(u.mapping,e,f.source.start.name)??f.source.start.id,endColumn:Pe(u.mapping,e,f.source.end.name)??f.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Pe(u.mapping,e,f.source.timestamp.name)??f.source.timestamp.id}}}:{},projections:j.map(({name:b,expression:O})=>({name:b,expression:O})),columnProperties:j.map(({outputProperty:b})=>b),groupBy:F.map(({name:b,expression:O})=>({name:b,expression:O})),...Q?{query:N(Q)}:{},...t.having?{having:K(t.having)}:{},orderBy:fe,rowIdentity:Re?{kind:"singleton"}:Me,...be?{pagination:be}:{},...se?{groupLimit:se}:{}}};class ll{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 fl=(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(".")},en=(t,e,r)=>r===void 0?fl(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,yr=(t,e,r,n,o)=>{const i=rs(t,[],String,`Property ${e} SQL expression`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} SQL expression 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)},We=(t,e,r,n=!1,o,i,s,a)=>{const c=(u,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(u)}`:e.quoteIdentifier(u);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 c(t.column,t.qualifier);case"property-sql":return yr(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(ke(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const u=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>We(m,e,r,n,o,i,s,a)).join(", ")} `:"",p=We(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${u}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(ke(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=We(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>We(m,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(m=>`${We(m.expression,e,r,n,o,i,s,a)} ${m.direction}`).join(", ");return`${e.aggregateFunction(t.function,u)} 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 ${We(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 ${We(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const u=r.get(t.operator);if(u.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(u.toSQL&&(t.input&&ke(t.input,r)||t.inputs?.some(m=>ke(m,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?We(t.input,e,r,n,o,i,s,a):t.column?c(t.column,t.qualifier):void 0;const l=t.inputs?.map(m=>We(m,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(u.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(u.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return u.toSQL?u.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:(m,f)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const h=i(m);return f&&e.castValue?e.castValue(h,f):h},condition:(m,f)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(m,f)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},ke=(t,e)=>t.kind==="window"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e)):t.kind==="cumulative"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e))||t.orderBy.some(r=>ke(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?ke(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?ke(t.input,e):!1)||(t.inputs?.some(r=>ke(r,e))??!1)),ml=(t,e)=>{const r=t.sourceSql?yr(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`;return t.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(r):r},Ws=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),Ks={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},hr=(t,e,r,n,o,i,s,a)=>{if(cs(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:m=>n.add(m),renderSource:(m,f)=>en(o,m,f)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&a!==void 0){if(typeof r!="string"||a!=="i")throw new d("INVALID_QUERY_VALUE",'$eq args.options supports only case-insensitive string equality with "i"');const l=n.add(r);return"LOWER("+t+") = LOWER("+l+")"}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=jt(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(jt(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 m=r.filter(jt);if(m.length>0){if(m.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${m.map(i).join(" UNION ALL ")})`}const f=r.map(h=>n.add(h)).join(", ");return`${t} ${l} (${f})`}if(jt(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}`)},bo=(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&&!jt(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=>bo(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`)}},St=(t,e,r,n,o,i)=>{if($p(e)){const u=()=>`CASE ${e.comparable.values.map((f,h)=>`WHEN ${t} = ${r.add(f)} THEN ${e.comparable.direction*h}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=m=>typeof m!="object"||m===null||Array.isArray(m)?St(t,m,r,n,o,i):Object.entries(m).filter(([f])=>f!=="args").map(([f,h])=>(f==="$and"||f==="$or")&&Array.isArray(h)?`(${h.map(l).join(f==="$and"?" AND ":" OR ")})`:p.has(f)?hr(u(),f,e.comparable.direction*e.comparable.values.indexOf(String(h)),r,n,o,i):hr(t,f,h,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return hr(t,"$in",e,r,n,o,i);if(!Ws(e))return hr(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 u=a.options;if(u!==void 0&&typeof u!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const c=a?.options;for(const[u,p]of Object.entries(e))if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const l=p.map(m=>St(t,m,r,n,o,i));s.push(`(${l.join(u==="$and"?" AND ":" OR ")})`)}else Ks[u]?(bo(p,u),s.push(St(n.datePart(t,Ks[u]),p,r,n,o,i))):u==="$length"?(bo(p,"$length"),s.push(St(n.stringLength(t),p,r,n,o,i))):u!=="args"&&s.push(hr(t,u,p,r,n,o,i,u==="$regex"||u==="$eq"?c:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Js=(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(!Ws(e))return i(e);const s=[];for(const[a,c]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(p=>Js(t,p,r,n));s.push(`(${u.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(c));else if(a==="$ne")s.push(`NOT (${i(c)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(i),p=u.length===0?a==="$in"?"0 = 1":"1 = 1":u.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&u.length>0?`NOT (${u.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${c?"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 ")},dt=(t,e,r,n,o,i,s,a)=>{const c=[];for(const[u,p]of Object.entries(t)){if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const m=p.map(f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${u} items must be query objects`);return dt(f,e,r,n,o,i,s,a)});c.push(`(${m.join(u==="$and"?" AND ":" OR ")})`);continue}if(u==="$expr"){if(!us(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");c.push(St(s(p.expression),p.condition,n,o,i,a));continue}const l=e(u);c.push(r(u)?Js(l,p,n,o):St(l,p,n,o,i,a))}return c.join(" AND ")},vt=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,c=i.comparable,u=!n&&o&&i.expression?o(i.expression):a;return`${c?`CASE ${c.values.map((l,m)=>`WHEN ${u} = ${r.add(l)} THEN ${c.direction*m}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Ro=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},tn=(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`])),rn=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:R})=>R)),s="__sdb_page_source",a="__sdb_page",c=n.quoteIdentifier(s),u=n.quoteIdentifier(a),p=Ro("__sdb_row_number",i),l=Ro("__sdb_total_rows",i),m=n.quoteIdentifier(p),f=n.quoteIdentifier(l),h=vt(e,n,o,c),y=h?`ORDER BY ${h}`:"",$=`CEIL(${f} * ${r.ratio})`,E=r.page-1,A=r.page,w=[...e.projections.map(({name:R})=>R),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(R=>`${u}.${n.quoteIdentifier(R)}`).join(", "),L=vt(e,n,o,u),I=`SELECT ${c}.*, ROW_NUMBER() OVER (${y}) AS ${m}, COUNT(*) OVER () AS ${f} FROM ${n.tableAlias(`(${t})`,s)}`;let S=`SELECT ${w} FROM ${n.tableAlias(`(${I})`,a)} WHERE ${u}.${m} > ${E} * ${$} AND ${u}.${m} <= ${A} * ${$}`;return L&&(S+=` ORDER BY ${L}`),S},Xs=(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),c=r.quoteIdentifier(s),u=new Set(e.projections.map(({name:A})=>A)),p=Ro("__sdb_limit_by_row_number",u),l=r.quoteIdentifier(p),m=o.partitionBy.map(A=>`${a}.${r.quoteIdentifier(A)}`).join(", "),f=o.orderBy.map(({name:A,direction:g,comparable:w})=>{const L=`${a}.${r.quoteIdentifier(A)}`;return`${w?`CASE ${w.values.map((S,R)=>`WHEN ${L} = ${n.add(S)} THEN ${w.direction*R}`).join(" ")} END`:L} ${g}`}).join(", "),y=[...e.projections.map(({name:A})=>A),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(A=>`${c}.${r.quoteIdentifier(A)}`).join(", "),$=`PARTITION BY ${m} ORDER BY ${f}`,E=`SELECT ${a}.*, ROW_NUMBER() OVER (${$}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${y} FROM ${r.tableAlias(`(${E})`,s)} WHERE ${c}.${l} <= ${o.count}`},$e=(t,e,r=Qe(),n=0)=>{const o=new ll(e,n),i=I=>qt(I);if(t.sumPartition){const I=t.subplans??[];if(I.length===0)throw new d("INVALID_PARTITION_PLAN","A sum partition requires child plans");const S=t.groupBy.map(({name:j})=>j),R=t.projections.map(({name:j})=>j).filter(j=>!S.includes(j)),N=I.map((j,K)=>{const Q=$e(j,e,r,o.nextParameterOffset);o.append(Q.parameters);const re=`__sum_partition_child_${K}`,ye=e.quoteIdentifier(re);return`SELECT ${[...S,...R].map(fe=>`${ye}.${e.quoteIdentifier(fe)}`).join(", ")} FROM ${e.tableAlias(`(${Q.sql})`,re)}`}),D="__sum_partition",F=e.quoteIdentifier(D),V=S.map(j=>`${F}.${e.quoteIdentifier(j)}`),x=[...V.map((j,K)=>`${j} AS ${e.quoteIdentifier(S[K])}`),...R.map(j=>`SUM(${F}.${e.quoteIdentifier(j)}) AS ${e.quoteIdentifier(j)}`)];t.rowIdentity.kind==="group"&&x.push(`${tn(V,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`);let M=`SELECT ${x.join(", ")} FROM ${e.tableAlias(`(${N.join(" UNION ALL ")})`,D)}`;if(V.length>0&&(M+=` GROUP BY ${V.join(", ")}`),t.having&&Object.keys(t.having).length>0){const j="__sum_partition_having",K=e.quoteIdentifier(j),Q=new Set(t.projections.map(({name:ye})=>ye)),re=dt(t.having,ye=>{if(!Q.has(ye))throw new d("INVALID_HAVING",`Having field is not an output: ${ye}`);return`${K}.${e.quoteIdentifier(ye)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_PARTITION_HAVING_UNSUPPORTED","Partition having cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query")},i);M=`SELECT ${K}.* FROM ${e.tableAlias(`(${M})`,j)} WHERE ${re}`}if(t.pagination?.kind==="ratio")M=rn(M,t,t.pagination,e,o);else if(t.orderBy.length>0&&(M+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const j=(t.pagination.page-1)*t.pagination.pageSize;M=e.paginate(M,t.pagination.pageSize,j)}return{sql:M,parameters:o.values}}if(t.splitGroup){const I=t.splitGroup,S=I.name,R=t.projections.map(({name:F})=>F).filter(F=>!I.groupNames.includes(F));let D=(t.subplans??[]).map((F,V)=>{const x=I.values[V];if(x===void 0)throw new d("INVALID_SPLIT_GROUP","A split group branch has no enum value");const M=I.groupNames.map(se=>se===S?o.add(x):`${e.quoteIdentifier(`__split_group_${V}`)}.${e.quoteIdentifier(se)}`),j=I.groupNames.map(se=>se===S?`'${x.replaceAll("'","''")}'`:`${e.quoteIdentifier(`__split_group_${V}`)}.${e.quoteIdentifier(se)}`),K=tn(j,e,t.rowIdentity.kind==="group"?t.rowIdentity.separator:"_",t.rowIdentity.kind==="group"?t.rowIdentity.nullLabel:"\u7A7A\u503C"),Q=$e(F,e,r,o.nextParameterOffset);o.append(Q.parameters);const re=`__split_group_${V}`,ye=e.quoteIdentifier(re),Me=I.groupNames.map((se,Re)=>`${M[Re]} AS ${e.quoteIdentifier(se)}`),fe=R.map(se=>`${ye}.${e.quoteIdentifier(se)} AS ${e.quoteIdentifier(se)}`),be=R.map(se=>`${ye}.${e.quoteIdentifier(se)} IS NOT NULL`).join(" OR ");return`SELECT ${[...Me,...fe].join(", ")}, ${K} AS ${e.quoteIdentifier("_id")} FROM ${e.tableAlias(`(${Q.sql})`,re)} WHERE (${be})`}).join(" UNION ALL ");if(t.having&&Object.keys(t.having).length>0){const F="__split_group_having",V=e.quoteIdentifier(F),x=new Set(t.projections.map(({name:j})=>j)),M=dt(t.having,j=>{if(!x.has(j))throw new d("INVALID_HAVING",`Having field is not an output: ${j}`);return`${V}.${e.quoteIdentifier(j)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A split group 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);D=`SELECT ${V}.* FROM ${e.tableAlias(`(${D})`,F)} WHERE ${M}`}if(t.pagination?.kind==="ratio")D=rn(D,t,t.pagination,e,o);else if(t.orderBy.length>0&&(D+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const F=(t.pagination.page-1)*t.pagination.pageSize;D=e.paginate(D,t.pagination.pageSize,F)}return{sql:D,parameters:o.values}}if(t.subplans){const I=t.projections.map(({name:x})=>x),S=new Set(t.groupBy.map(({name:x})=>x)),R=t.subplans.map((x,M)=>{const j=$e(x,e,r,o.nextParameterOffset);o.append(j.parameters);const K=`__composition_child_${M}`,Q=e.quoteIdentifier(K),re=new Set(x.projections.map(({name:ye})=>ye));return{aliasName:K,alias:Q,available:re,sql:j.sql}}),N=R[0];if(!N)throw new d("INVALID_COMPOSITION","Composition has no children");const D=I.map(x=>{const M=R.filter(Q=>Q.available.has(x)),j=M[0]??N;return`${S.has(x)&&M.length>1?`COALESCE(${M.map(Q=>`${Q.alias}.${e.quoteIdentifier(x)}`).join(", ")})`:`${j.alias}.${e.quoteIdentifier(x)}`} AS ${e.quoteIdentifier(x)}`}),F=R.map(x=>`${x.alias} AS (${x.sql})`);let V;if(t.rowIdentity.kind==="group"){const M=e.quoteIdentifier("__composition_keys"),j=e.quoteIdentifier("_id");F.push(`${M} AS (${R.map(K=>`SELECT ${j} FROM ${K.alias}`).join(" UNION ")})`),D.push(`${M}.${j} AS ${j}`),V=`WITH ${F.join(", ")} SELECT ${D.join(", ")} FROM ${M}`;for(const K of R)V+=` LEFT JOIN ${K.alias} ON ${M}.${j} = ${K.alias}.${j}`}else{V=`WITH ${F.join(", ")} SELECT ${D.join(", ")} FROM ${N.alias}`;for(const x of R.slice(1))V+=` LEFT JOIN ${x.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const x="__composition_having",M=e.quoteIdentifier(x),j=new Set(I),K=dt(t.having,Q=>{if(!j.has(Q))throw new d("INVALID_HAVING",`Having field is not an output: ${Q}`);return`${M}.${e.quoteIdentifier(Q)}`},()=>!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);V=`SELECT ${M}.* FROM ${e.tableAlias(`(${V})`,x)} WHERE ${K}`}if(t.groupLimit&&(V=Xs(V,t,e,o)),t.pagination?.kind==="ratio")V=rn(V,t,t.pagination,e,o);else if(t.orderBy.length>0&&(V+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const x=(t.pagination.page-1)*t.pagination.pageSize;V=e.paginate(V,t.pagination.pageSize,x)}return{sql:V,parameters:o.values}}const s=I=>{if(I.plan.projections.some(({expression:R})=>ke(R,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const S=$e(I.plan.rowIdentity.kind==="property"||I.plan.rowIdentity.kind==="group"?{...I.plan,rowIdentity:{kind:"generated"}}:I.plan,e,r,o.nextParameterOffset);return o.append(S.parameters),S.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,c=(t.arrayExpansions?.length??0)>0,u=a||c||t.sourcePlan!==void 0||t.mappingSourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(I=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const S=e.expandArray(ml(I,e),I.alias,"value",I.elementType);return p.set(I.path,S.valueExpression),S}),m=I=>{const S=t.fieldReferences?.[I];if(S?.sql){const D=yr(S.sql,S.property,e,S.timestampColumn,u?S.timestampQualifier??S.qualifier:void 0);return S.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(D):D}if(S&&u){const D=`${e.quoteIdentifier(S.qualifier)}.${e.quoteIdentifier(S.column)}`;return S.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(D):D}const R=t.fields[I];if(!R)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${I}`);const N=e.quoteIdentifier(R);return S?.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(N):N},f=I=>We(I,e,r,u,S=>dt(S,m,R=>t.fieldReferences?.[R]?.isArray===!0,o,e,s,f,i),S=>o.add(S),(S,R)=>St(S,R,o,e,s,i),S=>{const R=p.get(S);if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${S}`);return R}),h=t.projections.map(I=>`${f(I.expression)} AS ${e.quoteIdentifier(I.name)}`),y=t.rowIdentity.kind==="property"?`${u&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const I=t.rowIdentity.names.map(S=>{const R=t.groupBy.find(N=>N.name===S)??t.projections.find(N=>N.name===S);if(!R)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${S}`);return f(R.expression)});return`${tn(I,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,$=[...h,...y?[y]:[]].join(", "),E=t.sourcePlan??t.mappingSourcePlan,A=E?(()=>{const I=$e(E,e,r,o.nextParameterOffset);return o.append(I.parameters),`(${I.sql})`})():t.source?en(e,t.source,t.sourceSql):"",g=u&&t.sourceAlias?e.tableAlias(A,t.sourceAlias):A;let w=`SELECT ${$}`;if(t.periodSource){const I=t.periodSource,S=I.periods.map(({label:M,asOf:j},K)=>{const Q=o.add(M),re=o.add(j);return K===0?`SELECT ${Q} AS ${e.quoteIdentifier(I.labelColumn)}, ${re} AS ${e.quoteIdentifier(I.asOfColumn)}`:`SELECT ${Q}, ${re}`}).join(" UNION ALL "),R=e.tableAlias(`(${S})`,I.alias),N=e.tableAlias(A,I.sourceAlias),D=e.quoteIdentifier(I.alias),F=e.quoteIdentifier(I.sourceAlias),V=`${D}.${e.quoteIdentifier(I.asOfColumn)}`,x=I.match.kind==="interval"?(()=>{const M=`${F}.${e.quoteIdentifier(I.match.startColumn)}`,j=`${F}.${e.quoteIdentifier(I.match.endColumn)}`;return`${M} <= ${V} AND (${j} > ${V} OR ${j} IS NULL)`})():(()=>{const M=e.tableAlias(A,I.match.lookupAlias),j=e.quoteIdentifier(I.match.lookupAlias),K=`${F}.${e.quoteIdentifier(I.match.timestampColumn)}`,Q=`${j}.${e.quoteIdentifier(I.match.timestampColumn)}`,re=`SELECT ${e.aggregateFunction("max",Q)} FROM ${M} WHERE ${Q} <= ${V}`;return`${K} = (${re})`})();w+=` FROM ${R} LEFT JOIN ${N} ON ${x}`,t.query&&Object.keys(t.query).length>0&&(w+=` AND ${dt(t.query,m,M=>t.fieldReferences?.[M]?.isArray===!0,o,e,s,f,i)}`)}else g&&(w+=` FROM ${g}`);for(const I of l)w+=` ${I.joinSql}`;for(const I of t.enrichmentJoins??[]){const S=e.quoteIdentifier(I.alias),R=e.quoteIdentifier(I.baseAlias);w+=` LEFT JOIN ${e.tableAlias(en(e,I.source,I.sourceSql),I.alias)}`;const N=I.keys.map(({baseColumn:D,targetColumn:F})=>`${R}.${e.quoteIdentifier(D)} = ${S}.${e.quoteIdentifier(F)}`);if(I.temporalCondition?.kind==="point-in-interval"){const D=j=>j==="source"?R:S,F=`${D(I.temporalCondition.pointSide)}.${e.quoteIdentifier(I.temporalCondition.pointColumn)}`,V=D(I.temporalCondition.intervalSide),x=`${V}.${e.quoteIdentifier(I.temporalCondition.startColumn)}`,M=`${V}.${e.quoteIdentifier(I.temporalCondition.endColumn)}`;N.push(`${x} <= ${F}`),N.push(`(${M} > ${F} OR ${M} IS NULL)`)}w+=` ON ${N.join(" AND ")}`}for(const I of t.joins??[]){const S=I.targetMappingSourcePlan?(()=>{const D=$e(I.targetMappingSourcePlan,e,r,o.nextParameterOffset);return o.append(D.parameters),`(${D.sql})`})():en(e,I.targetSource,I.targetSourceSql);w+=` LEFT JOIN ${e.tableAlias(S,I.targetAlias)}`;const R=I.sourceArrayExpansionPath?p.get(I.sourceArrayExpansionPath):I.sourceSql?yr(I.sourceSql,I.sourceColumn,e,I.sourceTimestampColumn,I.sourceAlias):`${e.quoteIdentifier(I.sourceAlias)}.${e.quoteIdentifier(I.sourceColumn)}`,N=I.targetSql?yr(I.targetSql,I.targetColumn,e,I.targetTimestampColumn,I.targetAlias):`${e.quoteIdentifier(I.targetAlias)}.${e.quoteIdentifier(I.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${I.path}`);if(w+=` ON ${R} = ${N}`,I.temporalCondition?.kind==="date-bucket-equal"){const D=`${e.quoteIdentifier(I.sourceAlias)}.${e.quoteIdentifier(I.temporalCondition.sourceColumn)}`,F=`${e.quoteIdentifier(I.targetAlias)}.${e.quoteIdentifier(I.temporalCondition.targetColumn)}`;w+=` AND ${e.dateBucket(D,I.temporalCondition.sourceGranularity)} = ${e.dateBucket(F,I.temporalCondition.targetGranularity)}`}else if(I.temporalCondition?.kind==="point-in-interval"){const D=j=>j==="source"?e.quoteIdentifier(I.sourceAlias):e.quoteIdentifier(I.targetAlias),F=`${D(I.temporalCondition.pointSide)}.${e.quoteIdentifier(I.temporalCondition.pointColumn)}`,V=D(I.temporalCondition.intervalSide),x=`${V}.${e.quoteIdentifier(I.temporalCondition.startColumn)}`,M=`${V}.${e.quoteIdentifier(I.temporalCondition.endColumn)}`;w+=` AND ${x} <= ${F} AND (${M} > ${F} OR ${M} IS NULL)`}}const L=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&L.push(dt(t.query,m,I=>t.fieldReferences?.[I]?.isArray===!0,o,e,s,f,i)),L.length>0&&(w+=` WHERE ${L.join(" AND ")}`),t.groupBy.length>0){const I=t.groupBy.map(R=>f(R.expression)),S=t.rowIdentity.kind==="group"?[tn(I,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];w+=` GROUP BY ${[...I,...S].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const I=S=>{const R=t.projections.find(N=>N.name===S);if(!R)throw new d("INVALID_HAVING",`Having field is not an output: ${S}`);return e.supportsHavingAlias===!1?f(R.expression):e.quoteIdentifier(S)};w+=` HAVING ${dt(t.having,I,()=>!1,o,e,s,f,i)}`}if(t.groupLimit&&(w=Xs(w,t,e,o)),t.pagination?.kind==="ratio")w=rn(w,t,t.pagination,e,o);else if(t.orderBy.length>0&&(w+=` ORDER BY ${vt(t,e,o,void 0,f)}`),t.pagination?.kind==="rows"){const I=(t.pagination.page-1)*t.pagination.pageSize;w=e.paginate(w,t.pagination.pageSize,I)}return{sql:w,parameters:o.values}},yl=(t,e)=>{const r=Object.keys(e).sort((m,f)=>f.length-m.length),n=[];let o=0;for(;o<t.length;){const m=t[o];if(m&&/\s/.test(m)){o+=1;continue}if(m&&/[()+\-*/,]/.test(m)){n.push(m),o+=1;continue}const f=t.slice(o).match(/^\d+(?:\.\d+)?/);if(f?.[0]){n.push(f[0]),o+=f[0].length;continue}const h=r.find($=>t.startsWith($,o));if(h){n.push(h),o+=h.length;continue}const y=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(y?.[0]){n.push(y[0]),o+=y[0].length;continue}n.push(m??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],c=()=>{const m=a();if(!m)throw new Error("Component expression is incomplete");if(m==="("){const h=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${h})`}if(/^\d/.test(m))return m;if(!e[m]&&!/^[A-Za-z_$][\w$]*$/.test(m))throw new Error(`Invalid component expression token: ${m}`);if(s()==="("){a();const h=[];if(s()!==")")for(;h.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(m.toUpperCase()))throw new Error(`Unsupported component expression function: ${m}`);return`${m.toUpperCase()}(${h.join(", ")})`}const f=e[m];if(!f)throw new Error(`Unknown component in expression: ${m}`);return f},u=()=>{let m=c();for(;s()==="*"||s()==="/";)m=`${m} ${a()} ${c()}`;return m},p=()=>{let m=u();for(;s()==="+"||s()==="-";)m=`${m} ${a()} ${u()}`;return m},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},hl=t=>`__sdb_cte_${t}`,Zs=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},gl=(t,e)=>t?.find(r=>r.name===e),Al=(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,No=(t,e,r,n=Qe())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((A,g)=>{const w={...A.compiled,sql:Al(A.compiled.sql,r,o)};return o+=A.compiled.parameters.length,{...A,compiled:w,alias:`__sdb_exec_${g}`}}),s=i.map(({alias:A,compiled:g})=>`${r.quoteIdentifier(A)} AS (${g.sql})`),a=i[0],c=r.quoteIdentifier(a.alias),u=e.groupBy.map(({name:A})=>A),p=e.orderBy??[],l=e.rowIdentity.kind==="group",m=r.quoteIdentifier("__sdb_exec_keys");if(l){const A=g=>[...u.map(w=>`${g}.${r.quoteIdentifier(w)}`),`${g}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${m} AS (${i.map(({alias:g})=>`SELECT ${A(r.quoteIdentifier(g))} FROM ${r.quoteIdentifier(g)}`).join(" UNION ")})`)}const f=l?m:c,h=[...u,...t.flatMap(({outputs:A})=>A)],y=h.filter((A,g,w)=>w.indexOf(A)===g).map(A=>{if(u.includes(A))return`${f}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`;const g=i.find(({outputs:L})=>L.includes(A));if(!g)throw new Error(`CTE execution unit does not expose output projection: ${A}`);return`${r.quoteIdentifier(g.alias)}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`});l&&y.push(`${f}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let $=`SELECT ${y.join(", ")} FROM ${f}`;for(const A of l?i:i.slice(1)){const g=r.quoteIdentifier(A.alias);$+=` LEFT JOIN ${g}`,$+=l?` ON ${f}.${r.quoteIdentifier("_id")} = ${g}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const A={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:$,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(h.map(w=>[w,w])),projections:h.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:L,comparable:I})=>({name:w,direction:L,...I?{comparable:I}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},g=$e(A,r,n,o);return{sql:`WITH ${s.join(", ")} ${g.sql}`,parameters:[...i.flatMap(({compiled:w})=>w.parameters),...g.parameters]}}return{sql:`WITH ${s.join(", ")} ${$}`,parameters:i.flatMap(({compiled:A})=>A.parameters)}},nn=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const A of e){const g=$e(A.plan,o,i,a);a+=g.parameters.length,s.push({input:A,sql:g,alias:hl(A.name)})}const c=s.map(({sql:A,alias:g})=>`${o.quoteIdentifier(g)} AS (${A.sql})`).join(", "),u=s[0];if(!u)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(u.alias),l=r.groupBy.map(({name:A})=>A),m=l.map(A=>`${p}.${o.quoteIdentifier(A)} AS ${o.quoteIdentifier(A)}`);let f="";for(const A of s.slice(1)){const g=o.quoteIdentifier(A.alias),w=A.input.plan.groupBy.map(({name:S})=>S),I=(A.input.joinKeys??l.filter(S=>w.includes(S))).map(S=>{const R=gl(A.input.groupKeyShifts,S),N=R?o.dateShift(`${g}.${o.quoteIdentifier(S)}`,R.granularity,R.offset):`${g}.${o.quoteIdentifier(S)}`;return`${p}.${o.quoteIdentifier(S)} = ${N}`});f+=` LEFT JOIN ${g} ON ${I.length>0?I.join(" AND "):"1 = 1"}`}const h=Object.fromEntries(s.map(({input:A,alias:g})=>[A.name,`${o.quoteIdentifier(g)}.${o.quoteIdentifier(Zs(A.plan))}`])),y=yl(t.expression,h),$=[...m,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:A,alias:g})=>`${`${o.quoteIdentifier(g)}.${o.quoteIdentifier(Zs(A.plan))}`} AS ${o.quoteIdentifier(A.name)}`),`${y} AS ${o.quoteIdentifier(n)}`].join(", ");let E=`WITH ${c} SELECT ${$} FROM ${p}`;return E+=f,{sql:E,parameters:s.flatMap(({sql:A})=>A.parameters)}},$l=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=ta(t).length*2+2;for(let n=0;n<r;n+=1){const o=wl(e);if(o===e)return e;e=o}return e}catch{return t}},wl=t=>{const e=ta(t),r=El(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ra(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?ql(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(y=>y.trim()==="*"))continue;const c=Ml(_l(t.slice(i.fromStart,i.close),i,e)),u=Il(t,i),p=Sl(t,i);if(p&&bl(u,p))continue;let l=s.filter(y=>{const $=na(y);if(!$||$==="_id")return!0;const E=new RegExp(`(^|[^\\w$])${Oo($)}([^\\w$]|$)`,"i");return E.test(c)||E.test(u)}),m=!0;for(;m;){m=!1;const y=sa(l.join(" ")),$=s.filter(E=>{if(l.includes(E))return!1;const A=na(E);return A?new RegExp(`(^|[^\\w$])${Oo(A)}([^\\w$]|$)`,"i").test(y):!1});$.length>0&&(l=s.filter(E=>l.includes(E)||$.includes(E)),m=!0)}if(l.length===s.length)continue;const f=t.slice(i.selectEnd,i.fromStart),h=l.length===0&&Ul(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(u)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(f)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(c);l.length===0&&!h||n.push({start:i.selectEnd,end:i.fromStart,value:f.match(/^\s*/)[0]+(h?"1":l.map(y=>y.trim()).join(", "))+f.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},El=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ea(t,"FROM",n);if(o===-1||!ra(t,n,o)?.every(Dl))return t;const s=e.find(m=>m.open>o&&t.slice(o+4,m.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(m=>m.open>s.fromStart&&m.close<s.close).sort((m,f)=>f.close-f.open-(m.close-m.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const c=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(c))return t;const u=Ll.exec(c)?.[1],p=Cl.exec(t.slice(s.close+1));if(!u||!p||oa(u)!==oa(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},_l=(t,e,r)=>Rl(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}))),Il=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return sa(r)},Sl=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ot})(?=\\s|$)`,"i"))?.[1]??null,bl=(t,e)=>new RegExp(`(^|[^\\w$])${Oo(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Rl=(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("")},ea=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const c=t[a],u=t[a+1];if(s==="--"){c===`
|
|
2
|
+
`&&(s="");continue}if(s==="/*"){c==="*"&&u==="/"&&(s="",a+=1);continue}if(i){c===i&&t[a-1]!=="\\"&&(i="");continue}if(c==="-"&&u==="-"){s="--",a+=1;continue}if(c==="/"&&u==="*"){s="/*",a+=1;continue}if(c==="`"||c==='"'||c==="'"){i=c;continue}if(c==="("){n+=1;continue}if(c===")"){n-=1;continue}if(c==="["){o+=1;continue}if(c==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},ta=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 c=r.pop();if(!c)continue;const u=t.slice(c.open+1,i),p=/^\s*SELECT\b/i.exec(u);if(!p)continue;const l=c.open+1+p[0].length,m=ea(t,"FROM",l);m===-1||m>=i||e.push({open:c.open,close:i,selectEnd:l,fromStart:m})}return e},ra=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,c="";for(let u=0;u<n.length;u+=1){const p=n[u];if(c){p===c&&n[u-1]!=="\\"&&(c="");continue}if(p==="`"||p==='"'||p==="'"){c=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,u)),i=u+1)}return c||s!==0||a!==0?null:(o.push(n.slice(i)),o)},na=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ot='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Nl=new RegExp(`\\s+AS\\s+${ot}\\s*$`,"i"),Ol=new RegExp(`\\bAS\\s+${ot}`,"gi"),Tl=new RegExp(`(?:${ot}\\s*\\.\\s*)+${ot}`,"g"),Pl=new RegExp(`^${ot}(?:\\s*\\.\\s*${ot})*$`),Ll=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s+WHERE\\b`,"i"),Cl=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s*;?\\s*$`,"i"),oa=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Dl=t=>{const e=t.replace(Nl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},ia=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),sa=t=>ia(t,Ol),Ml=t=>ia(t,Tl),Ul=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),ql=t=>{const e=t.trim();return Pl.test(e)?e:null},Oo=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),To=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?To(t.input,e):!1)||(t.inputs?.some(n=>To(n,e))??!1)},aa=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?aa(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},bt=async(t,e,r)=>{const n=e.filter(({expression:o})=>To(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 aa(s.expression,i,s.name,r);return i}))},on=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),sn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:on(t[o])).join(r),Po=(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?sn(r,e.names,e.separator,e.nullLabel):on(r._id)}:{...r,_id:e.kind==="singleton"?"0":di()}}),Lo=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},gr=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&gr(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&gr(r,e)),an=(t,e,r,n,o,i,s="zh-CN",a=kr.translator(s))=>{const c=t.preds??[],u=c.map((f,h)=>({pred:f,index:h,definition:f.operator?n.get(f.operator):void 0})).filter(({definition:f})=>f?.kind==="component"&&!f.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(u.length===0&&e.sourcePlan||u.length===0)return;for(const f of c)if((!f.operator||n.get(f.operator).kind!=="component")&&(f.pred&&typeof f.pred=="object"&&!Array.isArray(f.pred)&&gr(f.pred,n)||Array.isArray(f.pred)&&f.pred.some(h=>typeof h!="string"&&gr(h,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=c.filter((f,h)=>!u.some(y=>y.index===h));if(l.length>0){const f=Lo(t);f.preds=l,p.push({kind:"query",logicform:f})}const m=t.groupby?.length??0;for(const{pred:f,index:h,definition:y}of u){const $=y?.createComponent;if(!$)continue;const E=e.projections[m+h]?.name;if(!E)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const A=i?.preds?.[h],g=$({executionContext:n.executionContext,logicform:Lo(t),pred:A??f,outputName:E,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:Lo(i)}:{}});if("logicform"in g&&(g.logicform.preds??[]).some(w=>gr(w,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in g?{...g,outputName:E}:g)}return p},Ke=t=>t instanceof Date?t.getTime():t,kl=(t,e,r,n)=>{const o=Ke(t),i=Ke(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=>Ke(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Ke(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}`)}},Co=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return Ke(t)===Ke(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(c=>Co(t,c));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&Co(t.length,s):kl(t,i,s,typeof o=="string"?o:void 0)})},ca=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ca(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Co(t[r],n)}),jl=(t,e)=>e.length===0?"0":t._id===void 0?sn(t,e):on(t._id),Do=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=jl(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Mo=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=Do(t,r);if(e.having&&(n=n.filter(o=>ca(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=sn(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,c)=>{for(const u of o.orderBy){const p=Ke(a[u.name]),l=Ke(c[u.name]);if(p!==l)return p==null?u.direction==="ASC"?-1:1:l==null?u.direction==="ASC"?1:-1:(p<l?-1:1)*(u.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=Ke(o[s.name]),c=Ke(i[s.name]);if(a!==c)return a==null?s.direction==="ASC"?-1:1:c==null?s.direction==="ASC"?1:-1:(a<c?-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},ua=(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},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},Uo=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})},da=(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)&&da(o,e))),pa=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!Qn(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Hn(r,n);return t&&da(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Gt=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"},la={$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"}},zt=(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=>zt(n,e)).join(e?", ":"\u3001");if(!Gt(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>zt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return zt(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"},cn=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),fa=(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}`},Ar=(t,e,r)=>{if(!Gt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return fa("$eq",t,zt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(cn(i.map(s=>Ar(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(la[o]){const s=la[o];n.push(Ar(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Ar(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Gt(i)?zt(i.pattern,r):zt(i,r),a=fa(o,t,s,r);a&&n.push(a)}return cn(n,"$and",r)},ma=(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(cn(i.map(s=>Gt(s)?ma(s,e):""),o,r));else if(o==="$expr"&&Gt(i)){const s=i.pred,a=Gt(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(Ar(a,i.condition,r))}else i!==void 0&&n.push(Ar(o,i,r));return cn(n,"$and",r)},Wt=(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??kr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(f=>typeof f=="string"?f:Wt(f,e,r)):[],c=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Wt(t.pred,e,r):void 0,u=c??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const f=e.get(t.operator),h={executionContext:e.executionContext,operandName:u,...c?{inputName:c}:{},inputNames:a,args:p,locale:n,t:s},y=f.defaultName(h);if(typeof y!="string"||y.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const $=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),E=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(f.defaultNameIsLocalized)return y;const A=typeof f.defaultNameKey=="function"?f.defaultNameKey(h):f.defaultNameKey??`operator.${t.operator}`;return s(A,y,{...p,operandName:u,inputName:c??"",inputNames:a.join(E),input0:a[0]??"",input1:a[1]??"",granularity:$})})():u;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 m=ma(t.query,n);return m?i?`${l} where ${m}`:`${m}\u7684${l}`:l},Yl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Fl=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},Ql=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}}},$r=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&&!Yl(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),c=Array.isArray(t.pred)?await Promise.all(t.pred.map(f=>$r(typeof f=="string"?{pred:f}:f,s,r,n))):void 0,{query:u,...p}=t,l={...p,...a?{query:a}:{},...c?{pred:c}:{}},m=async f=>{const h=await Ql(f,s,r),y=h.operator?o.get(h.operator).normalizePred?.({pred:h,schema:s,executionContext:o.executionContext})??h:h;return Fl(y)};if(typeof t.pred=="string"){const f=oe(s,t.pred,r.resolveSchema),h={...l,pred:f.canonicalName};return m({...h,name:h.name??Wt(h,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const f={...l,pred:await $r(t.pred,s,r,n)};return m({...f,name:f.name??Wt(f,o,i)})}if(c)return m({...l,name:l.name??Wt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return m({...l,name:l.name??Wt(l,o,i)})},Hl=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(!De(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},un=async(t,e)=>{if(De(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=>un(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 un(n,e)])))},ya=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>ya(o,e))]:[`${e}_${r}`,n])),qo=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},ha=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),ko=new Set([...ha,"$length"]),dn=t=>Array.isArray(t)?t.some(dn):typeof t!="object"||t===null||De(t)?!1:Object.entries(t).some(([e,r])=>ko.has(e)||dn(r)),ga=(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&&!De(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=>ga(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`)}},pn=(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)&&pn(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&pn(r,e)},Aa=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(c=>c!=="pred"&&c!=="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");pn(i,r);const s=await $r(i,e,r,()=>Promise.resolve(void 0));pn(s,r);const a=qo(await un(n.condition,r));return ko.has(s.operator)&&ga(a,s.operator),{pred:s,condition:a}},$a=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||De(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))ko.has(s)?i.push({$expr:await Aa({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(dn)?i.push({[s]:await Promise.all(a.map(c=>$a(t,c,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:qo(o)}),i.length===1?i[0]??{}:{$and:i}},jo=t=>Array.isArray(t)?t.some(jo):typeof t!="object"||t===null||De(t)?!1:Object.entries(t).some(([e,r])=>ha.has(e)||jo(r)),wa=async(t,e,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||De(u))return;const p=u;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"&&jo(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:u=>n.requestTimeWatermark?.(e,r,u)??Promise.resolve(void 0)},a=await zp(ae(t),s),c=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const u=new Set(r.comparable.values),p=(l,m)=>{if(!(De(l)||l===null)){if(Array.isArray(l)){l.forEach(f=>p(f,m));return}if(typeof l=="object"){Object.entries(l).forEach(([f,h])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(f)||p(h,f)});return}if(!(m&&["$exists","$regex","$contains","$startsWith","$length"].includes(m))&&(typeof l!="string"||!u.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(c)}return c},xo=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const c=Object.entries(a);if(c.length===1&&c[0]?.[0]==="$and"&&Array.isArray(c[0][1]))for(const u of c[0][1])s(u);else c.length===1&&c[0]?.[0]==="$expr"?o.push(a):c.every(([u])=>!u.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,c]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(c.map(async f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return xo(f,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Aa(c,e,r)});continue}const u=oe(e,a,r.resolveSchema);if(vl(c)&&(u.property.primal_type==="entity"||u.property.primal_type==="object")&&u.property.ref){if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const f=await r.normalizeNestedLogicform(c);n[u.canonicalName]={$in:f};continue}if(Hl(c)){if(c.version!==void 0&&Uo(c),u.property.primal_type!=="entity"&&u.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!u.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${u.canonicalName}`);if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema}`);const f=r.resolveSchema?.(c.schema);if(!f)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${c.schema}`);const h=pa(c.query,c.entity_id,f,r.plugins),y=await xo(h,f,r);Object.assign(n,ya(y,u.canonicalName));continue}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){const f=c,h=Object.entries(f).filter(([y])=>qt(y,r.plugins));if(h.length>0){const[y]=h,$=y?qt(y[0],r.plugins):void 0;if($?.validateCondition?.(f),!y||h.length!==1||Object.keys(f).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[E,A]=y;if(!$)throw new Error(`Query Operator disappeared: ${E}`);n[u.canonicalName]={[E]:await $.normalize(A,{schema:u.schema,property:u.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(g,w,L)=>wa(g,w,L,r)})};continue}}const p=await un(c,r),l=await wa(p,u.schema,u.property,r),m=qo(l);if(dn(m)){s(await $a(u.canonicalName,m,e,r));continue}n[u.canonicalName]=m}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},Ea=async(t,e,r)=>{if(!t)return;const n=await xo(t,e,r);return Object.keys(n).length===0?void 0:n},_a=(t,e,r)=>Promise.all((t??[]).map(n=>$r(n,e,r,Ea))),Gl=(t,e,r)=>_a(t??[],e,r),Kt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},zl=t=>{"skip"in t&&Kt("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)&&Kt("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&&Kt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Kt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Kt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Kt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},Wl=t=>t.property.name,Ia=(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(c=>c.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 c=r?.(a.ref);if(!c)continue;const u=Ia(c,e,r,n,i);if(u)return`${a.name}_${u}`}},Sa=(t,e,r,n)=>{try{const o=oe(t,e,n);return Ia(r,Wl(o),n,o.property.type)}catch{return}},Bo=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Bo(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Bo(e)):[]],ba=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>ba(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)?Bo(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 c=r.resolveSchema?.(s),u={};for(const[p,l]of Object.entries(a))try{const m=oe(e,p,r.resolveSchema),f=c?oe(c,l,r.resolveSchema):void 0;u[m.canonicalName]=f?.canonicalName??l}catch{u[p]=l}o[s]=u}const i=[...(t.groupby??[]).map(s=>s.pred),...ba(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=oe(e,s,r.resolveSchema)}catch{continue}for(const c of n){const u=r.resolveSchema?.(c),p=u&&Sa(e,s,u,r.resolveSchema);p&&p!==a.canonicalName&&(o[c]={...o[c]??{},[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=ua(t,e,r);return pt(t,n,r)},pt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:qr([...Se(r.plugins).flatMap(y=>y.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Qe(r.plugins)}},Uo(t),Jl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!Vn(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=ae(t),i={...r,normalizeNestedLogicform:async y=>{const $=ua(y,e,r);return pt(y,$,r)}};zl(o);const s=await Xl(o.from,e,i),a=s&&r.resolveFromSchema?await r.resolveFromSchema(s,e):e,c=await Ea(pa(o.query,o.entity_id,a,r.plugins),a,i),u=o.preds===void 0&&o.groupby===void 0?a.properties.filter(y=>r.canProjectProperty?.(a,y)??!0).map(y=>({pred:y.name,name:y.name})):o.preds,p={...i,...c?{autoCaseQuery:c}:{}};let l=await _a(u,a,p),m=await Gl(o.groupby,a,p);const f=m.filter(y=>Ui(y,m,a,r.resolveSchema));if(f.length>0){const y=new Set(f.map(({name:$})=>$));m=m.filter(({name:$})=>!y.has($)),l=[...l,...f]}return o.preds=l,m.length>0?o.groupby=m:delete o.groupby,s?o.from=s:delete o.from,c?o.query=c:delete o.query,Kl(o,a,i)},Ra=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),it=(t,e)=>{if(t){if(!Ra(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},Rt=(t,e,r)=>{const n=it(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},wr=(t,e,r)=>{if(!Rt(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})},Vo=(t,e,r,n)=>{const o=oe(e,t,n);for(const i of o.relations)it(r,i.targetSchema.id),wr(r,i.sourceSchema,i.property);wr(r,o.schema,o.property)},Na=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),ln=(t,e,r,n)=>{if(De(t)){mn(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)ln(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))ln(o,e,r,n)};function Er(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&it(r,t.schema),typeof t.pred=="string"?Vo(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"?Vo(s,i,r,n):Er(s,i,r,n,o);fn(t.query,i,r,n,o)}const fn=(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 c of s)fn(c,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const c=s.pred;typeof c=="object"&&c!==null&&!Array.isArray(c)&&Er(c,e,r,n,o),ln(s.condition,r,n,o)}continue}const a=oe(e,i,n);if(Vo(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[c,u]of Object.entries(s))qt(c,o)?.authorize?.(u,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{it(r,p)},assertPropertyAllowed:(p,l)=>wr(r,p,l),hasRowPermissions:p=>it(r,p)?.rowPermissions!==void 0});if(Na(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);it(r,c.id),Qn(s.entity_id)&&wr(r,c,Hn(c,o)),fn(s.query,c,r,n,o);continue}ln(s,r,n,o)}},mn=(t,e,r,n=[])=>{if(!t.schema){if(t.from){mn(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(it(e,o.id),Qn(t.entity_id)&&wr(e,o,Hn(o,n)),t.from){mn(t.from,e,r,n);return}fn(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)},yn=(t,e)=>{if(Array.isArray(t))return t.map(o=>yn(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,yn(i,e)]),n=Object.fromEntries(r);return Na(t)&&!Ra(t,"version")&&(n.version=e),n},Zl=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[c,u]of Object.entries(s))if((c==="$and"||c==="$or")&&Array.isArray(u))for(const p of u)o(p,a);else if(c==="$expr"&&typeof u=="object"&&u!==null&&!Array.isArray(u)){const p=u.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else c.startsWith("$")||n.push(oe(a,c,r))},i=(s,a)=>{const c=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(oe(c,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,c);for(const u of Array.isArray(s.pred)?s.pred:[])typeof u=="string"?n.push(oe(c,u,r)):i(u,c);o(s.query,c)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},ef=(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},m)=>{e[l.id]?.rowPermissions!==void 0&&(a=m)}),a<0)continue;const c=s.relations.slice(0,a+1),u=c.map(({property:l})=>l.name).join("_");if(o.has(u))continue;o.add(u);let p={};for(const l of[...c].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Jt=(t,e,r,n,o,i)=>De(t)?Nt(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Jt(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Jt(a,e,r,n,o,i)])),Yo=(t,e,r,n,o,i)=>({...t,...t.query?{query:Jt(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))}:{}}),Nt=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return ae(t);if(!t.schema){const f=ae(t);return f.from&&(f.from=Nt(f.from,e,r,n,new Set,i)),f}n&&mn(t,e,r,i);const s=it(e,t.schema),a=o.has(t.schema),c=new Set(o).add(t.schema),u=ae(t);u.query&&(u.query=Jt(u.query,e,r,n,new Set,i)),u.preds&&(u.preds=u.preds.map(f=>Yo(f,e,r,n,new Set,i))),u.from&&(u.from=Nt(u.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:ef(t,e,r)).map(f=>Jt(yn(f,t.version),e,r,!1,c,i));p&&l.push(Jt(yn(ae(p),t.version),e,r,!1,c,i));const m=[u.query,...l].filter(f=>f!==void 0&&Object.keys(f).length>0);return m.length===1?u.query=m[0]:m.length>1?u.query={$and:m}:delete u.query,u},tf=(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:c})=>a===s||c===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},Oa=(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")}},Ta=(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=Oa(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)},rf=(t,e)=>{const r=ls(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=Oa(e,t.timeZone);let o=Ta({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Ta({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},nf=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[rf(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},Fo=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(Fo):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Fo(r)])):t,Pa=t=>lc("sha256").update(JSON.stringify(Fo(t))).digest("hex"),of=t=>Pa({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),sf=(t,e)=>Pa({namespace:t,source:e}),Qo=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(Qo)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Qo(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)]))}},af=t=>JSON.stringify(Qo(t)),cf=t=>{const e=Ho(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},uf=Number.MAX_SAFE_INTEGER;class df{#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:${of(e)}`}#o(e,r){return`${this.#t}:source:${sf(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return cf(r)}async set(e,r,n){const o=this.#n(e),i=af(r),s=n.expiresAt?.getTime(),a=s??uf,c=this.#e.multi();s===void 0?c.set(o,i):c.set(o,i,{PXAT:s});for(const u of new Set(n.sources)){const p=this.#o(e.namespace,u);c.zRemRangeByScore(p,0,Date.now()),c.zAdd(p,{score:a,value:o})}await c.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 pf=async(t={})=>{const e=fc(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new df(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function lf(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 ff=({namespace:t,...e})=>e,mf=async t=>pf({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class yf{create;#e=new Map;constructor(e=mf){this.create=e}async get(e){lf(e);const r=ff(e),n=this.#e.get(r.id);if(n){if(!pi(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 La=new yf,Ca=t=>La.get(t),hf=()=>La.close(),gf=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 Ca(t);await r.store.invalidateSource(r.namespace,e)},Af=Object.freeze({invalidateSource:gf}),$f=()=>{},_r=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),Ir=(t,e,r)=>{if(jt(t)){e.push(t.plan);return}if(cs(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)Ir(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))Ir(n,e,r)},Sr=(t,e,r)=>{if(t.kind==="window"){Sr(t.input,e,r);for(const n of t.partitionBy)Sr(n,e,r);return}if(t.kind==="operator"){Ir(t.query,e,r),t.input&&Sr(t.input,e,r);for(const n of t.inputs??[])Sr(n,e,r)}},Te=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 Te(o))r(i);else if(t.sourcePlan)for(const o of Te(t.sourcePlan))r(o);else if(t.mappingSourcePlan)for(const o of Te(t.mappingSourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])if(r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}}),o.targetMappingSourcePlan)for(const i of Te(o.targetMappingSourcePlan))r(i);for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];Ir(t.query,n,e),Ir(t.having,n,e);for(const o of t.projections)Sr(o.expression,n,e);for(const o of n)for(const i of Te(o))r(i);return[...e.values()]},Xt=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()]},Da=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})}},wf=(t,e)=>{const r=[];for(const n of t){const o=_r(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},vo=async(t,e,r,n=$f)=>{t=Ma(t),r.signal?.throwIfAborted();const o=r.cache?wf(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),Da(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 Da(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=nf(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:c})=>c))],...a?{expiresAt:a}:{}})}catch{}return s},Ma=t=>({...t,sql:$l(t.sql)}),Ef=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")},_f=(t,e,r)=>{const n=Ef(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}},Ua=async(t,e)=>{if(!Rt(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(E=>Rt(e.permissions,t.schema.id,E)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:E})=>E===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:_f(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(E=>({pred:E.name,name:E.name}))},a=Nt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),c=await pt(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}),u=Le(c,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(E,A)=>Rt(e.permissions,E.id,A)}),p=new Set(Te(u).map(E=>e.schemaMappings.findSource(E.schemaId,E.source,E.connectionId)?.connectionId).filter(E=>!!E));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,m=l&&e.providerForConnection?e.providerForConnection(l):i,f=$e(u,m,e.operators),h=Te(u),y=e.onCompiled?.(f,c,m,l,h),$=await vo(f,h,{provider:m,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return Po($,u.rowIdentity)},qa=t=>String(t),If=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${qa(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=qa(r),o},ka=(t,e)=>`${t}:${String(e)}`,Sf=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 bf{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=ka(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(Fn(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=Sf(s);let c,u;const p=new Promise((m,f)=>{c=m,u=f}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:m=>c?.(m),reject:m=>u?.(m)}),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),c=i._id===a?i:{...i,_id:a};o.set(ka(e.schema.id,s),c)}}for(const[i,s]of e.loads){const a=o.get(i)??If(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 Rf=(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})}},Nf=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=r.get(i.type),a=Rf(o[i.name],i),c={property:i,requestEntity:n},u=s.normalizeResult?await s.normalizeResult(a,c):a,p=s.hydrateResult;if(!p){o[i.name]=u;return}o[i.name]=i.isArray&&Array.isArray(u)?await Promise.all(u.map(l=>p(l,c))):await p(u,c)}))}))},ja=5,Of=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Tf=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Pf=(t,e)=>{const r=mc(e);t._title=t[r.name]??t._id},Lf=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Tf(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Cf=(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})},Df=async(t,e,r)=>{const n=new bf(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 c=a.expandEntities&&i<ja;return Nf(a.rows,a.properties,r.semanticTypes,c?n.load:(u,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const c of a.rows)Pf(c,a.schema);if(i>=ja)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const c of a.properties){if(c.primal_type!=="entity"&&c.primal_type!=="object"||!c.ref)continue;const u=r.resolveSchema(c.ref);for(const p of a.rows){if(!(c.name in p))continue;const l=p[c.name],m=c.isArray?Array.isArray(l)?l:[l]:[l];for(const[f,h]of m.entries()){if(!Of(h))continue;const y=Lf(h,u);c.isArray?m[f]=y:p[c.name]=y,Cf(s,u,y,!c.isArray)}c.isArray&&(p[c.name]=m)}}o=[...s.values()]}},xa=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Df(n,e,r),n},Go=t=>`'${t.replaceAll("'","''")}'`,Ba=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}'`},br=(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():Go(t.toString());if(typeof t=="string")return e==="mysql"?Ba(t):Go(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Ba(r):Go(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}`)},Mf=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?br(e[o],"clickhouse"):r}),Uf=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?br(e[o],"oracle"):r}),qf=(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 c=Number(a)-1;if(c in e){r+=br(e[c],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},zo=(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+=br(e[o],r),o+=1;continue}n+=a}}return n},kf=(t,e)=>zo(t,e,"mysql"),Wo=(t,e)=>zo(t,e,"snowflake"),jf=(t,e)=>zo(t,e,"dameng"),xf=(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 c=Number(a);if(c in e){r+=br(e[c],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},lt=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),Rr=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`)},Be=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},Je=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],je=(t,e)=>{const r=Je(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},Va=t=>{const e=je(t,"table_name"),r=Je(t,"table_database"),n=Je(t,"table_schema"),o=je(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"}},Bf=t=>t.map(Va),Ot=async(t,e)=>{e.signal?.throwIfAborted(),Rr(e);const r=[],n=c=>{const u=t.parameter(r.length,c);return r.push(c),u},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Be(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&&Be(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&&Be(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&&Be(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(),Bf(a)},Ko=t=>{if(Rr(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},hn=(t,e)=>{const r=Je(t,e);return typeof r=="string"?r:""},Vf=t=>{const e=je(t,"column_type"),r=Je(t,"type_length"),n=Je(t,"type_precision"),o=Je(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},Ya=t=>{const e=Je(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:je(t,"column_name"),type:Vf(t),comment:hn(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},Yf=(t,e)=>{const r=[],n=u=>{const p=t.parameter(r.length,u);return r.push(u),p},o=n(e.table),{database:i,schema:s}=e;let a,c;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Be(t,"schema");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&Be(t,"database");const u=`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 ${u} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,c=`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 ${u} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const u=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${u}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${u}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 ${u}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${u}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}`,c=`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 ${u}sys.indexes i JOIN ${u}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 ${u}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${u}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${u}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 u=`${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 ${u}.TABLES c WHERE ${p}`,c=`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 ${u}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Be(t,"database");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&Be(t,"schema");const u=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 = ${u}`,c=`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 = ${u} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:c,parameters:r}},Fa=(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(".")},Zt=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},Jo=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=Fa(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 Zt(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},Ff=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Zt(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??=je(l,"table_database"),n??=je(l,"table_schema")}const o=Fa(t,{name:e.table,database:r,schema:n}),i=await Zt(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,c=!1,u="",p="table";for(const l of i){const m=Je(l,"col_name"),f=Je(l,"data_type"),h=(m==="# Partition Information"||m==="# Detailed Table Information")&&!f;(m===""||h)&&(a=!1),h&&m==="# Detailed Table Information"&&(c=!0),a?s.push({name:je(l,"col_name"),type:je(l,"data_type"),comment:hn(l,"comment")}):c&&m==="Comment"?u=hn(l,"data_type"):c&&m==="Type"&&f==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return Jo(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:u}})},Qf=async(t,e)=>{e.database!==void 0&&Be(t,"database"),e.schema!==void 0&&Be(t,"schema");const n=(await Zt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(Ya);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return Jo(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},st=async(t,e)=>{if(e.signal?.throwIfAborted(),Ko(e),t.kind==="databricks")return Ff(t,e);if(t.kind==="maxcompute")return Qf(t,e);const{tableSql:r,columnSql:n,parameters:o}=Yf(t,e),i=await Zt(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={...Va(s),comment:hn(s,"table_comment")},c=(await Zt(t,e,n,o)).map(Ya);return Jo(t,e,{columns:c,tableInfo:a})},Hf=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}`},vf=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Qa=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Gf{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 lt("@clickhouse/client",r)});return e({url:Hf(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}:${vf(r)}}`}displayQuery(e,r){return Mf(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}`,Qa(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return Ot(this,e)}describeTable(e){return st(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,c)=>[`p${c}`,Qa(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 c=JSON.parse(a);if(typeof c!="object"||c===null||Array.isArray(c))throw new Error("ClickHouse provider expected object rows");return c}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const zf=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Wf=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??(zf(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)}`)},Kf=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 Jf{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 lt("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Wf(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 Wo(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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(Kf)}),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 st(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),Rr(e);const r=u=>this.execute({sql:u,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[u]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!u)throw new Error("Databricks current namespace was not returned");n??=je(u,"table_database"),o??=je(u,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),c=new Map;for(const u of s){const p=je(u,"tableName");c.set(p,{name:p,database:n,schema:o,type:"table"})}for(const u of a){const p=je(u,"viewName");c.set(p,{name:p,database:n,schema:o,type:"view"})}return[...c.values()].sort((u,p)=>u.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const Ha=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}`)},Xf=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class Zf{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={...Xf(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${di()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw lt("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 jf(e,r.map(Ha))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 Ot(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return st(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(Ha),{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 ie={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 kf(t,e)},dateBucket(t,e){const r={second:"%Y-%m-%d %H:%i:%s",minute:"%Y-%m-%d %H:%i:00",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,n){const o=this.quoteIdentifier(e),i=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${i} ${n==="string"?"VARCHAR(4000)":"JSON"} PATH '$')) AS ${o}`,valueExpression:`${o}.${i}`}}},em={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class gn{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 lt("mysql2",r)});return e({...em,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return ie.quoteIdentifier(e)}tableAlias(e,r){return ie.tableAlias(e,r)}paginate(e,r,n){return ie.paginate(e,r,n)}parameter(e,r){return ie.parameter(e,r)}displayQuery(e,r){return ie.displayQuery(e,r)}dateBucket(e,r){return ie.dateBucket(e,r)}datePart(e,r){return ie.datePart(e,r)}dateShift(e,r,n){return ie.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=ie.datePeriodBoundary?.bind(ie);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return ie.aggregateFunction(e,r)}stringify(e){return ie.stringify(e)}concat(e){return ie.concat(e)}substring(e,r,n){return ie.substring(e,r,n)}stringLength(e){return ie.stringLength(e)}regex(e,r,n){return ie.regex(e,r,n)}arrayContains(e,r){const n=ie.arrayContains?.bind(ie);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n,o){const i=ie.expandArray?.bind(ie);if(!i)throw new Error("MySQL-compatible array expansion is unavailable");return i(e,r,n,o)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return Ot(this,e)}describeTable(e){return st(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 tm extends gn{kind="doris";constructor(e={}){super(e)}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}`}}}class rm extends gn{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class nm{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return ie.quoteIdentifier(e)}tableAlias(e,r){return ie.tableAlias(e,r)}paginate(e,r,n){return ie.paginate(e,r,n)}parameter(e,r){return ie.parameter(e,r)}displayQuery(e,r){return ie.displayQuery(e,r)}dateBucket(e,r){return ie.dateBucket(e,r)}datePart(e,r){return ie.datePart(e,r)}dateShift(e,r,n){return ie.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=ie.datePeriodBoundary?.bind(ie);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return ie.aggregateFunction(e,r)}stringify(e){return ie.stringify(e)}concat(e){return ie.concat(e)}substring(e,r,n){return ie.substring(e,r,n)}stringLength(e){return ie.stringLength(e)}regex(e,r,n){return ie.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(),Rr(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Be(this,"database"),e.schema!==void 0&&Be(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:je(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Ko(e),!this.#e.describeTable)return st(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class om extends gn{kind="mysql";constructor(e={}){super(e)}}const va=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}`)},im=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class sm{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 Uf(e,r.map(va))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 lt("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 Ot(this,e)}describeTable(e){return st(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(va),{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?im(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 am{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{default:e}=await import("pg").catch(r=>{throw lt("pg",r)});return new e.Pool(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 qf(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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})`}normalizeStringArray(e){const r=`to_jsonb(${e})`;return`(CASE WHEN ${e} IS NULL THEN ARRAY[]::text[] WHEN jsonb_typeof(${r}) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(${r})) ELSE ARRAY[${r} #>> '{}'] END)`}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 Ot(this,e)}describeTable(e){return st(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 Ga=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}`)},cm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class um{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 lt("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 Wo(e,r.map(Ga))}dateBucket(e,r){if(!new Set(["second","minute","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 Ot(this,e)}describeTable(e){return st(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(Ga);return new Promise((i,s)=>{const a=e.signal,c={};let u=!1;const p=m=>{u||(u=!0,a?.removeEventListener("abort",l),m())},l=()=>{c.current?.cancel(),a&&p(()=>s(cm(a)))};a?.addEventListener("abort",l,{once:!0}),c.current=n.execute({sqlText:e.sql,binds:o,complete:(m,f,h)=>{if(m){p(()=>s(m));return}if(!(r&&h===void 0)&&!Array.isArray(h)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const y=r?f.getNumUpdatedRows?.():void 0;p(()=>i({rows:h??[],...typeof y=="number"&&y>=0?{affectedRows:y}:{}}))}}),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 dm=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}}},pm=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}`)},lm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),fm=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),mm=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 ym{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 lt("mssql",n)}),r=new e.ConnectionPool(dm(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`${mm(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 xf(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 Ot(this,e)}describeTable(e){return st(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}`,pm(i))),new Promise((i,s)=>{const a=e.signal;let c=!1;const u=l=>{c||(c=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&u(()=>s(lm(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){u(()=>s(new Error("SQL Server provider expected an array result")));return}u(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((m,f)=>m+f,0)}:{}}))},l=>u(()=>s(fm(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class hm extends gn{kind="starrocks";constructor(e={}){super(e)}arrayContains(e,r){return`array_contains(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`, UNNEST(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}}const Ve=t=>{const{id:e,kind:r,...n}=t;return n},gm=Object.freeze([{kind:"mysql",create:t=>new om({connection:Ve(t)})},{kind:"doris",create:t=>new tm({connection:Ve(t)})},{kind:"gbase",create:t=>new rm({connection:Ve(t)})},{kind:"starrocks",create:t=>new hm({connection:Ve(t)})},{kind:"maxcompute",create:t=>new nm(Ve(t))},{kind:"postgresql",create:t=>new am({connection:Ve(t)})},{kind:"clickhouse",create:t=>new Gf(Ve(t))},{kind:"databricks",create:t=>new Jf({connection:Ve(t)})},{kind:"dameng",create:t=>new Zf({connection:Ve(t)})},{kind:"snowflake",create:t=>new um({connection:Ve(t)})},{kind:"sqlserver",create:t=>new ym({connection:Ve(t)})},{kind:"oracle",create:t=>new sm({connection:Ve(t)})}]);class za{#e=new Map;constructor(e=gm){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 Wa=new za,Ka=(t,e=Wa)=>e.create(t);class Am{create;#e=new Map;#t=new Set;#r=[];constructor(e=Ka){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&pi(r.connection,e))return r.provider;const n=this.create(e);return this.#e.set(e.id,{connection:{...e},provider:n}),r&&r.provider!==n&&this.#n(r.provider),n}#n(e){const r=Promise.resolve().then(()=>e.close()).then(()=>{this.#t.delete(r)},n=>{this.#t.delete(r),this.#r.push(n)});this.#t.add(r)}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()),...this.#t]),n=this.#r.splice(0);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 An=new Map,$m=t=>{const e=An.get(t);if(e)return e;const r=new Am(n=>Ka(n,t));return An.set(t,r),r},$n=(t,e=Wa)=>$m(e).get(t),wm=async()=>{const t=[...An.values()];An.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")},Ja=async()=>{const e=(await Promise.allSettled([wm(),hf()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},Em=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=$n(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},_m=async t=>{t.signal?.throwIfAborted(),Rr(t);const e=$n(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},Im=async t=>{t.signal?.throwIfAborted(),Ko(t);const e=$n(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},Sm=Object.freeze({runSQL:Em,getTableList:_m,describeTable:Im,close:Ja}),bm=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:fi,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:Nn,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:li,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:Lt,sqlType:"VARCHAR"}}},Rm=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Nm=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return et(Rm(t),fi);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:et(r,Nn)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?et(r,li):null}case"string":return typeof t=="string"?et(t,Lt):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?et(t.toString(),Lt):typeof t=="symbol"?et(t.description??"",Lt):typeof t=="function"?et(t.name,Lt):et(JSON.stringify(t),Lt)}},Om=t=>{if(t==null)return null;if(t instanceof Date)return et(t,Nn);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return hc(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class bn{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await yc.create(":memory:"),r=await e.connect();return new bn(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 Wo(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(bm),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 c of o){const u=Nm(a[c.name],c);u===null?s.appendNull():s.appendValue(u,c.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(Om));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Xo="__sdb_total__",Tm="__sdb_total_source__",Zo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Pm=t=>{const e={...t};return delete e.limit,delete e.page,e},ei=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(Xo)} FROM ${e.tableAlias(`(${t.sql})`,Tm)}`,parameters:t.parameters}),wn=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[Xo]??e[Xo.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},Nr="__semanticdb_coordinator__",Xa=(t,e)=>{const r=new Set;for(const n of Te(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]},Or=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>Xa(r,e))).size>1||!!(t.sourcePlan&&Or(t.sourcePlan,e)),Lm=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Cm=(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"},Za=(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"?Cm(e,n):"string";return{name:n,kind:i}})},Dm=(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=>Lm(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Mm=(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",on(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")},ec=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:sn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},En=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&&Or(t.sourcePlan,e.schemaMappings)){const s=await En(t.sourcePlan,e),a=await bn.create();try{const c="__federated_source";await a.materialize(c,Za(t.sourcePlan,s.rows),s.rows);const u={...t,source:c};delete u.sourcePlan,delete u.sourceLogicform,delete u.connectionId;const p=$e(u,a,e.operators),l=ei($e(Zo(u),a,e.operators),a),m=e.onCompiled({compiled:p,sources:[],connectionId:Nr,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:l,sources:[],connectionId:Nr,provider:a,type:"total",logicform:e.logicform})("database");const h=await a.execute({...l,...e.signal?{signal:e.signal}:{}});m("database");const y=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:ec(y,t),total:wn(h),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=Xa(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 c=a[0],u=e.providerForConnection(c);r.set(c,u.kind);const p=$e(s,u,e.operators),l=Te(s),m=e.onCompiled({compiled:p,sources:l,connectionId:c,provider:u,type:"computation",logicform:e.logicform}),f=await vo(p,l,{provider:u,connectionId:c,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},m),h=await bt(f,s.projections,e.operators);return{child:s,rows:Mm(h,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 bn.create();try{const s=n.flatMap(({rows:y})=>y),a=[];for(const[y,{child:$,rows:E}]of n.entries()){const A=`__federated_branch_${y}`;await i.materialize(A,Za($,s),E),a.push(Dm($,A))}const c={...t,subplans:a},u=$e(c,i,e.operators),p=ei($e(Zo(c),i,e.operators),i),l=e.onCompiled({compiled:u,sources:[],connectionId:Nr,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,sources:[],connectionId:Nr,provider:i,type:"total",logicform:e.logicform})("database");const f=await i.execute({...p,...e.signal?{signal:e.signal}:{}});l("database");const h=await i.execute({...u,...e.signal?{signal:e.signal}:{}});return{rows:ec(h,t),total:wn(f),connections:[...r].map(([y,$])=>({connectionId:y,provider:$}))}}finally{await i.close()}},tc=t=>{const e={...t};return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},Um=new Set(["$gt","$gte","$lt","$lte"]),ti=t=>Object.entries(t).flatMap(([e,r])=>e==="$and"&&Array.isArray(r)?r.flatMap(n=>ti(n)):[{[e]:r}]),qm=(t,e)=>{if(!t||!e||typeof t!="object"||typeof e!="object"||Array.isArray(t)||Array.isArray(e))return;const r=[t,e];if(r.some(o=>Object.keys(o).some(i=>!Um.has(i))))return;const n={};for(const o of["lower","upper"]){const i=o==="lower"?["$gt","$gte"]:["$lt","$lte"],s=r.flatMap(u=>i.flatMap(p=>u[p]===void 0?[]:[{key:p,value:u[p]}]));if(s.some(({value:u})=>typeof u!="string"&&!(u instanceof Date)))return;const c=s.reduce((u,p)=>{if(!u)return p;const l=u.value instanceof Date?u.value.toISOString():u.value,m=p.value instanceof Date?p.value.toISOString():p.value;return l===m?p.key===(o==="lower"?"$gt":"$lt")?p:u:o==="lower"?m>l?p:u:m<l?p:u},void 0);c&&(n[c.key]=c.value)}return n},rc=(t,e)=>{const r=[...t?ti(t):[],...ti(e)],n=[];for(const i of r){const[s]=Object.entries(i);if(!s)continue;const[a,c]=s,u=n.findIndex(p=>Object.keys(p).length===1&&a in p);if(u>=0){const p=n[u],l=qm(p[a],c);if(l){n[u]={[a]:l};continue}}n.push(i)}if(n.length===1)return n[0];const o=n.map(i=>Object.keys(i)[0]);return new Set(o).size===o.length&&o.every(i=>i&&!i.startsWith("$"))?Object.assign({},...n):{$and:n}},nc=(t,e,r)=>{if(e.length===0)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition returned no shards`);for(const[n,o]of e.entries()){const i=o,s=i?.query,a=i?.mappingCandidates;if(!i||typeof i!="object"||!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).length===0||!Array.isArray(a)||a.length===0)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} requires a query and mappingCandidates`);for(const c of o.mappingCandidates)if(typeof c!="string"||!r.findById(t.id,c))throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} references unknown mapping ${c}`)}},oc=t=>{if(!t.preds?.length||t.preds.some(e=>e.operator!=="$sum"))throw new d("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition currently supports only $sum PredItems")},ri=(t,e,r,n,o,i,s)=>{if(oc(t),s&&oc(s.logicform),t.limitBy!==void 0||s?.logicform.limitBy!==void 0)throw new d("UNSUPPORTED_SCHEMA_PARTITION_LIMIT_BY","Schema partition does not support limitBy");nc(e,r,o);const a=[],c=[],u=[];let p,l;for(const[y,$]of r.entries()){const E=rc(t.query,$.query),A={...t,query:E},g=s?{...s.logicform,query:s.queryForCurrentShard(E)}:void 0;let w;const L=[],I=[];for(const R of $.mappingCandidates){const N={...i,mappingCandidates:[R]};try{const D=Le(tc(A),e,n,o,N),F=g?Le(tc(g),e,n,o,N):void 0;w={mappingId:R,current:D,...F?{comparison:F}:{}};break}catch(D){if(!(D instanceof d)||D.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw D;L.push(`${R}: ${JSON.stringify(D.details?.rejectedMappings??[])}`);const F=D.details?.uncoveredDimensions;I.push(Array.isArray(F)?F.filter(V=>typeof V=="string"):[])}}if(!w){const R=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,N=I.length===$.mappingCandidates.length&&I.every(D=>D.length>0)?[...new Set(I.flat())]:[];throw new d("SCHEMA_PARTITION_MAPPING_NOT_FOUND",N.length>0?s?`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u6240\u9700\u7EF4\u5EA6\u3010${N.join("\u3001")}\u3011\u3002`:`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u7EF4\u5EA6\u3010${N.join("\u3001")}\u3011\u3002`:s?`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`:`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:R,shardIndex:y,...s?{comparison:!0}:{},...N.length>0?{uncoveredDimensions:N}:{},reasons:L})}const S={...i,mappingCandidates:[w.mappingId]};p??=Le(A,e,n,o,S),g&&(l??=Le(g,e,n,o,S)),a.push(w.current),w.comparison&&c.push(w.comparison),u.push(w.mappingId)}const m=p,f=a.length===1?m:{...m,subplans:a,sumPartition:!0},h=l?c.length===1?l:{...l,subplans:c,sumPartition:!0}:void 0;return{current:f,...h?{comparison:h}:{},mappingIds:u}},ic=(t,e)=>[...Se(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],_n=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{},...t.partitionQuery?{partitionQuery:t.partitionQuery}:{}}),sc=t=>t instanceof Error?t:new Error(String(t)),km=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,jm=(t,e,r={},n="zh-CN",o)=>{const i=sc(t);return{errorCode:"100",error:km(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.lineage?{lineage:r.lineage}:{}}},xm=(t,e,r)=>{const n=e.projections.map(({name:u})=>u),o=new Map((e.columnProperties??[]).map(u=>[u.name,u])),i=[],s=(u,p)=>{const l=r.parameter(i.length,p);i.push(p);const m=o.get(u)?.type;return m&&(m==="date"||m==="timestamp")&&r.castValue?r.castValue(l,m):l},a=u=>`SELECT ${n.map(p=>`${s(p,u[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(u=>`NULL AS ${r.quoteIdentifier(u)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Bm=(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),...Te(r)];for(const i of o){const s=_r(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Vm=async(t,e,r)=>{await t?.({...e,partialResult:r})},Ym=(t,e,r,n,o,i,s=r,a,c=[])=>({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,schemaMappings:c,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),ni=(t,e)=>{if(e.connectionId)for(const r of Te(t)){const n=_r(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})}},ac=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 oi(o))e.add(i)};return r(t),[...e]},oi=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...oi(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:oi(r))]:e},ii=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??qr(ic(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&&Cp(t);const c=a?_s(t,e.schemas):t,u=e.schemaMappings.definitions(),p=ac(c),l=[...new Set(u.filter(({schemaId:_})=>p.includes(_)).map(({connectionId:_})=>_))],m=e.connectionId??(l.length===1?l[0]:void 0)??e.provider.kind,f=a?Rs(e.schemas,u,m,p):u,h=f.length===u.length?e.schemaMappings:new gt(f,e.schemaMappings.plugins),y={...e,locale:r,localeRegistry:n,schemaMappings:h,schemas:Is(e.schemas,o,a)},$=Lr.now(),E=y.semanticTypes===void 0?Xr(o):y.semanticTypesResolved?y.semanticTypes:Cs(y.semanticTypes,o);let A=y.operators??Qe(o);if(y.operators&&!y.operatorsResolved)for(const _ of o)for(const T of _.operators??[])if(A.has(T.name)){if(A.get(T.name)!==T)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${T.name}`,{operator:T.name,plugin:_.name})}else A.register(T);const g=y.schemaMappings,w=_=>Te(_).some(T=>bs(_r(T,g))),L=new Date,I=new Map,S=new Map;let R={};const N=[],D=new WeakMap,F=_=>{const T=new Map;for(const k of _){const U=_r(k,g);if(!U)continue;const B=U.id??U.source;T.set(JSON.stringify([U.schemaId,U.connectionId,B]),{schemaId:U.schemaId,mappingId:B,connectionId:U.connectionId,source:U.source})}return[...T.values()]},V=(_,T,k,U=T,B=y.provider,Y=y.connectionId,v)=>{const G=N.length;N.push(Ym(Ma(_),B,T,k,y.locale??"zh-CN",n,U,Y,F(v))),R={...R,sqls:[...N]};const z=W=>{N[G]={...N[G],executionSource:W},R={...R,sqls:[...N]}};return D.set(_,z),z},x=(_,T)=>vo(_,T,y,D.get(_)),M=async(_,T={})=>{R={...R,...T},await Vm(y.onProgress,_,R)},j=_=>mo(Di(_,y.schemas),E,o),K=new Map,Q=_=>{const T=K.get(_);return T||(it(y.permissions,_),j(_))},re=_=>{if(_.schema)return Q(_.schema);if(_.from)return re(_.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},ye=_=>{if(_.schema)return j(_.schema);if(_.from)return ye(_.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},Me=async()=>{const _=Object.values(y.schemas).filter(W=>W.is_calendar===!0);if(_.length!==1)return Object.freeze({});const T=_[0];if(!T)return Object.freeze({});const k=g.list(T.id),U=k.find(({connectionId:W})=>W===y.connectionId)??k[0];if(!U)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${T.id}`,{schemaId:T.id});if(bs(U))return Object.freeze({calendar:Object.freeze([])});const B=y.providerForConnection?.(U.connectionId)??y.provider,{onProgress:Y,executionContext:v,...G}=y,z=await ii({version:"2.0",schema:T.id,limit:-1},{...G,provider:B,connectionId:U.connectionId,operators:A,operatorsResolved:!0,executionContext:Object.freeze({})});return N.push(...z.sqls.map(W=>({...W,type:"semantic-resolution",explain:n.translate(y.locale??"zh-CN","sql.semanticResolution")}))),Object.freeze({calendar:Object.freeze(z.result.map(({_id:W,...ee})=>Object.freeze(ee)))})},fe=e.executionContext??await Me();A=A.withExecutionContext(fe);const be=new Map,se={plugins:o,preplannedPartitions:be,resolveSchema:Q,...y.connectionId?{preferredConnectionId:y.connectionId}:{},canUsePropertyRowIdentity:(_,T)=>Rt(y.permissions,_.id,T)},Re=async(_,T)=>{const k=await q(_,re(_));return be.set(JSON.stringify(_),k),Qs(k,T)},b=async(_,T,k)=>{const U=`${_.id}:${T.id}:${k.toISOString()}`,B=I.get(U);if(B)return B;const Y=(async()=>{const v=Se(o).find(Ee=>Ee.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!v)return;const G=v({logicform:c,rootSchema:_,rootProperty:T,requestedUpperBound:k,now:L,...y.timeWatermark?{defaultPolicy:y.timeWatermark}:{},resolveSchema:Q,inferPropertyPath:(Ee,me,_e)=>Sa(Ee,me,_e,Q)}),z=Nt(G,y.permissions,Q,!1,new Set,o),W=await pt(z,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re}),ee=Le(W,_,A,g,se);if(w(ee))return;let de;if(Or(ee,g)){const Ee=y.providerForConnection;if(!Ee)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");de=(await En(ee,{logicform:W,operators:A,schemaMappings:g,providerForConnection:Ee,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:_e,sources:Ne,logicform:he,provider:xe,connectionId:ve})=>V(_e,"semantic-resolution",he,"time-watermark",xe,ve,Ne)})).rows}else{ni(ee,y);const Ee=$e(ee,y.provider,A),me=Te(ee);V(Ee,"semantic-resolution",W,"time-watermark",y.provider,y.connectionId,me),de=await x(Ee,me)}const ge=de[0]?.__timeWatermark__??Object.values(de[0]??{})[0];if(ge==null||!(ge instanceof Date)&&typeof ge!="string"&&typeof ge!="number")return;const we=ge instanceof Date?ge:new Date(ge);return Number.isNaN(we.getTime())?void 0:we})();return I.set(U,Y),Y},O=async(_,T,k)=>{const U=JSON.stringify([_.id,T,k??null]),B=S.get(U);if(B)return B;const Y=(async()=>{const v={version:"2.0",schema:_.id,...k?{query:k}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:T},{name:"__autoCaseMax__",operator:"$max",pred:T},{name:"__autoCaseCount__",operator:"$count",pred:T}]},G=await pt(v,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re}),z=Le(G,_,A,g,se);if(w(z))return{empty:!0};let W;if(Or(z,g)){const Ne=y.providerForConnection;if(!Ne)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");W=(await En(z,{logicform:G,operators:A,schemaMappings:g,providerForConnection:Ne,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:xe,sources:ve,logicform:Tt,provider:Ye,connectionId:Fe})=>V(xe,"semantic-resolution",Tt,"auto-case",Ye,Fe,ve)})).rows}else{ni(z,y);const Ne=$e(z,y.provider,A),he=Te(z);V(Ne,"semantic-resolution",G,"auto-case",y.provider,y.connectionId,he),W=await x(Ne,he)}const ee=W[0],de=ee?.__autoCaseMin__,ge=ee?.__autoCaseMax__,we=ee?.__autoCaseCount__;if(de==null||ge===null||ge===void 0||we===null||we===void 0||Number(we)===0)return{empty:!0};const Ee=Number(de),me=Number(ge),_e=Number(we);if(!Number.isFinite(Ee)||!Number.isFinite(me)||!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:de,max:ge,count:we});return{min:Ee,max:me,count:_e}})();return S.set(U,Y),Y},C=async(_,T)=>{if(!T.partition||y.partitionDisabledSchemaIds?.includes(T.id)||!_.schema||_.from)return;if(y.partitionStack?.includes(T.id))throw new d("RECURSIVE_SCHEMA_PARTITION",`Schema ${T.id} partition called itself without a pinned mapping`);const k=[...y.partitionStack??[],T.id],U=await T.partition(_,{dayjs:le,moment:le,schemas:Object.fromEntries(Object.keys(y.schemas).map(Y=>[Y,j(Y)])),schemaMappings:g.definitions(),execute:async(Y,v)=>{const G=Y.schema,z=v?.mappingId;if(z&&!G)throw new d("PARTITION_MAPPING_SCHEMA_REQUIRED","A pinned partition query requires a physical Schema");const W=z&&G?g.findById(G,z):void 0;if(z&&!W)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${G}:${z}`);const ee=W?new gt([...g.definitions().filter(({schemaId:_e})=>_e!==G),W],o):g,de=W?.connectionId??y.connectionId,ge=W?y.providerForConnection?.(W.connectionId)??(W.connectionId===y.connectionId?y.provider:void 0):y.provider;if(!ge)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED",`Pinned mapping ${z} requires a provider for ${de}`);const{onProgress:we,...Ee}=y,me=await ii(Y,{...Ee,schemaMappings:ee,provider:ge,...de?{connectionId:de}:{},partitionStack:k,...G&&W?{partitionDisabledSchemaIds:[...y.partitionDisabledSchemaIds??[],G]}:{},operators:A,operatorsResolved:!0,semanticTypes:E,semanticTypesResolved:!0});return N.push(...me.sqls.map(_e=>({..._e,type:"semantic-resolution",explain:n.translate(r,"sql.semanticResolution")}))),R={...R,sqls:[...N]},me}}),B=U;if(typeof B!="object"||B===null||!Array.isArray(B.shards))throw new d("INVALID_SCHEMA_PARTITION",`Schema ${T.id} partition must return shards`);return nc(T,U.shards,g),Promise.all(U.shards.map(async Y=>{const v=await pt({version:_.version,schema:T.id,query:Y.query,preds:[]},T,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re,requestTimeWatermark:b,requestAutoCaseBounds:O});if(!v.query)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${T.id} partition shard query normalized to empty`);return{...Y,query:v.query}}))},q=async(_,T,k)=>{const U=await C(_,T);if(!U)return Le(_,T,A,g,se);if(_.preds?.every(({operator:v})=>v==="$sum"))return ri(_,T,U,A,g,se).current;if(!_.preds?.some(({operator:v})=>v&&A.get(v).kind==="component"))throw new d("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition currently supports only $sum PredItems");for(const v of U)for(const G of v.mappingCandidates){const z={..._,query:rc(_.query,v.query)};try{return Le(z,T,A,g,{...se,mappingCandidates:[G]})}catch(W){if(!(W instanceof d)||W.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw W;const ee=g.findById(T.id,G);if(!ee)continue;const de={...ee,...ee.mappings?{mappings:ee.mappings.map(({granularity:we,...Ee})=>Ee)}:{}},ge=new gt([...g.definitions().filter(({schemaId:we})=>we!==T.id),de],o);return Le(z,T,A,ge,{...se,mappingCandidates:[G]})}}const Y=T.name&&T.name!==T.id?`${T.name}(${T.id})`:T.id;throw new d("SCHEMA_PARTITION_MAPPING_NOT_FOUND",`Schema\u300C${Y}\u300D\u7684\u7EC4\u4EF6\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:T.id,schemaLabel:Y,component:!0})};try{y.signal?.throwIfAborted(),Uo(c),await M({stage:"started",logicform:c}),tf(y.permissions,j);const _=re(c);await M({stage:"validated",schema:_});const T=Nt(c,y.permissions,Q,!0,new Set,o),k=await pt(T,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re,canProjectProperty:(P,H)=>Rt(y.permissions,P.id,H),requestTimeWatermark:b,requestAutoCaseBounds:O});await M({stage:"normalized",normedLogicform:k},{normedLogicform:k});const U=async P=>{if(De(P)){await U(P.from),await U(P.query),await U(P.preds);const H=JSON.stringify(P);!be.has(H)&&P.schema&&!P.from&&Q(P.schema).partition&&be.set(H,await q(P,Q(P.schema)));return}if(Array.isArray(P)){for(const H of P)await U(H);return}if(!(typeof P!="object"||P===null||P instanceof Date))for(const H of Object.values(P))await U(H)};await U(k.from),await U(k.query),await U(k.preds);const B=await q(k,_),Y=Or(B,g);Y||ni(B,y);const v=B.columnProperties??[],G=Fs(B,_);K.set(G.id,G),await M({stage:"planned",plan:B},{schema:G});const z=ps(B,_,y.provider,A,y.providerForConnection);if(await M({stage:"lineage",lineage:z},{lineage:z}),a&&w(B)){const P=[];await M({stage:"compiled",sqls:[]},{sqls:[]}),await M({stage:"result",result:P},{result:P,total:0}),await M({stage:"completed",durationMs:Lr.now()-$});const H=k.output?Vn(k.output.type,o):void 0;return{result:P,total:0,schema:G,normedLogicform:k,sqls:[],lineage:z,...H?{output:await H.handle({rows:P,logicform:k,schema:G})}:{}}}if(Y){const P=y.providerForConnection;if(!P)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const H=await En(B,{logicform:k,operators:A,schemaMappings:g,providerForConnection:P,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:Ie,sources:pe,type:ce,logicform:Ce,provider:Ae,connectionId:Ge})=>V(Ie,ce,Ce,ce,Ae,Ge,pe)});await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:"duckdb",connectionId:Nr}),await M({stage:"hydrating"});const X=H.connections.length===1?H.connections[0]?.connectionId:void 0,J=await xa(H.rows,v,{semanticTypes:E,plugins:o,resolveSchema:Q,fetchEntities:Ie=>Ua(Ie,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,...y.permissions?{permissions:y.permissions}:{},provider:y.provider,providerForConnection:P,...X?{preferredConnectionId:X}:{},...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:(pe,ce,Ce,Ae,Ge)=>V(pe,"semantic-resolution",ce,"entity-expansion",Ce,Ae,Ge)})}),ne=Po(J,B.rowIdentity);return await M({stage:"result",result:ne},{result:ne,total:H.total,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.now()-$}),{result:ne,total:H.total,schema:G,normedLogicform:k,sqls:[...N],lineage:z}}const W=an(k,B,_,A,Q,void 0,r,n.translator(r)),ee=new WeakMap;for(const P of W??[]){if("logicform"in P&&P.partitionQuery&&P.partitionCurrentLogicform){const H=re(P.partitionCurrentLogicform),X=await C(P.partitionCurrentLogicform,H);if(X){const J=ri(P.partitionCurrentLogicform,H,X,A,g,se,{logicform:P.logicform,queryForCurrentShard:P.partitionQuery});ee.set(P.logicform,J.comparison)}}if("components"in P)for(const H of P.components){if(!H.comparisonOf||!H.partitionQuery)continue;const X=P.components.find(({name:pe})=>pe===H.comparisonOf);if(!X)throw new d("INVALID_COMPONENT_COMPARISON",`Comparison component ${H.name} has no current component ${H.comparisonOf}`);const J=re(X.logicform),ne=await C(X.logicform,J);if(!ne)continue;const Ie=ri(X.logicform,J,ne,A,g,se,{logicform:H.logicform,queryForCurrentShard:H.partitionQuery});ee.set(X.logicform,Ie.current),ee.set(H.logicform,Ie.comparison)}}const de=async(P,H)=>{const X=H&&P.logicform.schema===H.id?H:re(P.logicform),J=P.prepare?await pt(Nt(P.logicform,y.permissions,Q,!0,new Set,o),X,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re,canProjectProperty:(pe,ce)=>Rt(y.permissions,pe.id,ce),requestTimeWatermark:b}):P.logicform,ne=ee.get(P.logicform)??await q(J,X),Ie=an(J,ne,X,A,Q,P.logicform,r,n.translator(r));if(Ie){if(Ie.length!==1)throw new Error("A generated component must produce exactly one execution unit");const pe=Ie[0];if("logicform"in pe){const Ae=await de(pe,X),Ge=Ae.component.mapResult,Xe=P.mapResult;return{...Ae,component:{...P,logicform:Ae.component.logicform,...Ge||Xe?{mapResult:Ze=>{const ft=Ge?.(Ze)??[...Ze];return Xe?.(ft)??[...ft]}}:{}}}}if("mergeRow"in pe)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const ce=await Promise.all(pe.components.map(async Ae=>({name:Ae.name,prepared:await de(_n(Ae)),...Ae.groupKeyShifts?{groupKeyShifts:Ae.groupKeyShifts}:{},...Ae.joinKeys?{joinKeys:Ae.joinKeys}:{}}))),Ce=nn(pe,ce.map(({name:Ae,prepared:Ge,...Xe})=>({name:Ae,plan:Ge.plan,...Xe})),ne,pe.outputName,y.provider,A);return{component:{...P,logicform:J},plan:ne,compiled:Ce,sources:Xt(ce.map(({prepared:Ae})=>Ae.sources))}}return{component:{...P,logicform:J},plan:ne,compiled:$e(ne,y.provider,A),sources:Te(ne)}},ge=async(P,H)=>{const X=an(P,H,re(P),A,Q,void 0,r,n.translator(r));if(!X)return{compiled:$e(H,y.provider,A),sources:Te(H)};const J=await Promise.all(X.map(async ne=>{if("logicform"in ne){const ce=await de(ne);return{plan:ce.plan,compiled:ce.compiled,outputs:ce.plan.projections.map(({name:Ce})=>Ce).filter(Ce=>!H.groupBy.some(Ae=>Ae.name===Ce))}}if("mergeRow"in ne)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ie=await Promise.all(ne.components.map(async ce=>{const Ce=await de(_n(ce));return{name:ce.name,plan:Ce.plan,...ce.joinKeys?{joinKeys:ce.joinKeys}:{},...ce.groupKeyShifts?{groupKeyShifts:ce.groupKeyShifts}:{}}})),pe=nn(ne,Ie,H,ne.outputName,y.provider,A);return{plan:H,compiled:pe,outputs:[ne.outputName,...ne.components.map(ce=>ce.name)]}}));return{compiled:No(J,H,y.provider,A),sources:Xt(J.map(({plan:ne})=>Te(ne)))}},we=new WeakMap,Ee=async P=>{if(!P.sourcePlan||!P.sourceLogicform)return $e(P,y.provider,A);const H=ye(P.sourceLogicform),X=an(P.sourceLogicform,P.sourcePlan,H,A,Q,void 0,r,n.translator(r));if(X?.some(ce=>"mergeRow"in ce)){const ce=we.get(P.sourcePlan);if(ce){const ue={...P};delete ue.sourcePlan,delete ue.sourceLogicform;const at=$e({...ue,sourceSql:ce.sql,source:P.source},y.provider,A,ce.parameters.length);return{sql:at.sql,parameters:[...ce.parameters,...at.parameters]}}const Ce=await Promise.all(X.map(async ue=>{if("logicform"in ue)return{kind:"query",unit:ue,prepared:await de(ue,H)};const at=await Promise.all(ue.components.map(async Oe=>({input:Oe,prepared:await de(_n(Oe),H)})));return"mergeRow"in ue?{kind:"js",unit:ue,components:at}:{kind:"component",unit:ue,components:at,compiled:nn(ue,at.map(({input:Oe,prepared:qe})=>({name:Oe.name,plan:qe.plan,...Oe.joinKeys?{joinKeys:Oe.joinKeys}:{},...Oe.groupKeyShifts?{groupKeyShifts:Oe.groupKeyShifts}:{}})),P.sourcePlan,ue.outputName,y.provider,A)}})),Ae=P.sourcePlan.groupBy.map(({name:ue})=>ue),Ge=await Promise.all(Ce.map(async ue=>{if(ue.kind==="query"){V(ue.prepared.compiled,"computation",ue.prepared.component.logicform,"computation",y.provider,y.connectionId,ue.prepared.sources);const Oe=await x(ue.prepared.compiled,ue.prepared.sources),qe=await bt(Oe,ue.prepared.plan.projections,A);return ue.unit.mapResult?.(qe)??qe}if(ue.kind==="component"){const Oe=Xt(ue.components.map(({prepared:qe})=>qe.sources));return V(ue.compiled,"computation",P.sourceLogicform,"computation",y.provider,y.connectionId,Oe),x(ue.compiled,Oe)}const at=await Promise.all(ue.components.map(async({input:Oe,prepared:qe})=>{V(qe.compiled,"computation",qe.component.logicform,"computation",y.provider,y.connectionId,qe.sources);const pc=await x(qe.compiled,qe.sources),ci=await bt(pc,qe.plan.projections,A);return Oe.mapResult?.(ci)??ci}));return Promise.all(Do(at,Ae).map(async Oe=>({...Oe,[ue.unit.outputName]:await ue.unit.mergeRow(Oe)})))})),Xe=Mo(Ge,P.sourcePlan),Ze=y.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(Ze)||Ze<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:Ze});if(Xe.length>Ze)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Xe.length} rows; maximum is ${Ze}`,{materializedRowCount:Xe.length,maxMaterializedRows:Ze});const ft=xm(Xe,P.sourcePlan,y.provider);we.set(P.sourcePlan,ft);const Rn={...P};delete Rn.sourcePlan,delete Rn.sourceLogicform;const ai=$e({...Rn,sourceSql:ft.sql,source:P.source},y.provider,A,ft.parameters.length);return{sql:ai.sql,parameters:[...ft.parameters,...ai.parameters]}}const J=await ge(P.sourceLogicform,P.sourcePlan),ne={...P};delete ne.sourcePlan,delete ne.sourceLogicform;const Ie={...ne,sourceSql:J.compiled.sql,source:P.source},pe=$e(Ie,y.provider,A,J.compiled.parameters.length);return{sql:pe.sql,parameters:[...J.compiled.parameters,...pe.parameters]}},me=W?await Promise.all(W.map(async P=>{if("logicform"in P)return{kind:"query",unit:P,...await de(P)};const H=await Promise.all(P.components.map(async J=>({name:J.name,prepared:await de(_n(J)),...J.groupKeyShifts?{groupKeyShifts:J.groupKeyShifts}:{},...J.joinKeys?{joinKeys:J.joinKeys}:{}})));if("mergeRow"in P)return{kind:"js",unit:P,components:H.map(({prepared:J})=>J)};const X=H.map(({name:J,prepared:ne,...Ie})=>({name:J,plan:ne.plan,...Ie}));return{kind:"component",unit:P,plan:B,compiled:nn(P,X,B,P.outputName,y.provider,A),sources:Xt(H.map(({prepared:J})=>J.sources))}})):void 0,_e=me&&Bm(me,g,B)?me.map(P=>{const H=new Set(B.groupBy.map(({name:J})=>J));if(P.kind==="query")return{plan:P.plan,compiled:P.compiled,outputs:P.plan.projections.map(({name:J})=>J).filter(J=>!H.has(J))};const X=P.unit.outputName;if(!X)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:P.plan,compiled:P.compiled,outputs:[X,...P.unit.components.map(J=>J.name)]}}):void 0,Ne=_e?No(_e,B,y.provider,A):void 0,he=me?void 0:await Ee(B),xe=Te(B),ve=B.sourcePlan&&we.has(B.sourcePlan)?[]:xe,Tt=Ne?Xt([...me.map(P=>P.sources),xe]):void 0,Ye=Ne?Xt([...me.map(P=>P.sources),ve]):void 0,Fe=Zo(B),Pt=B.pagination&&(Ne||he)?ei(_e?No(_e,Fe,y.provider,A):await Ee(Fe),y.provider):void 0;if(Ne)V(Ne,"computation",k,"computation",y.provider,y.connectionId,Ye);else if(me)for(const P of me)if(P.kind==="js")for(const H of P.components)V(H.compiled,"computation",H.component.logicform,"computation",y.provider,y.connectionId,H.sources);else V(P.compiled,"computation",k,"computation",y.provider,y.connectionId,P.sources);else V(he,"computation",k,"computation",y.provider,y.connectionId,ve);Pt&&V(Pt,"total",Pm(k),"total",y.provider,y.connectionId,Ye??ve),await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:y.provider.kind});const cc=Ne?await(async()=>{const P=Tt,[H,X]=await Promise.all([x(Ne,P),Pt?x(Pt,P):Promise.resolve(void 0)]),J=await bt(H,B.projections,A);return{rows:J,total:X?wn(X):J.length}})():me?await(async()=>{const P=await Promise.all(me.map(async X=>{if(X.kind==="js"){const Ie=await Promise.all(X.components.map(async pe=>{const ce=await x(pe.compiled,pe.sources),Ce=await bt(ce,pe.plan.projections,A);return pe.component.mapResult?.(Ce)??Ce}));return Promise.all(Do(Ie,B.groupBy.map(({name:pe})=>pe)).map(async pe=>{const ce=await X.unit.mergeRow(pe);return{...pe,[X.unit.outputName]:ce}}))}const J=await x(X.compiled,X.sources),ne=X.kind==="query"?await bt(J,X.plan.projections,A):J;return X.kind==="query"?X.unit.mapResult?.(ne)??ne:ne})),H=Mo(P,B);return{rows:H,total:B.pagination?Mo(P,Fe).length:H.length}})():await(async()=>{const P=xe,[H,X]=await Promise.all([x(he,P),Pt?x(Pt,P):Promise.resolve(void 0)]),J=await bt(H,B.projections,A);return{rows:J,total:X?wn(X):J.length}})(),{rows:uc,total:si}=cc;await M({stage:"hydrating"});const dc=await xa(uc,v,{semanticTypes:E,plugins:o,resolveSchema:Q,fetchEntities:P=>Ua(P,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,...y.permissions?{permissions:y.permissions}:{},provider:y.provider,...y.connectionId?{preferredConnectionId:y.connectionId}:{},...y.providerForConnection?{providerForConnection:y.providerForConnection}:{},...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:(H,X,J,ne,Ie)=>V(H,"semantic-resolution",X,"entity-expansion",J,ne,Ie)})}),Pr=Po(dc,B.rowIdentity);return await M({stage:"result",result:Pr},{result:Pr,total:si,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.now()-$}),{result:Pr,total:si,schema:G,normedLogicform:k,sqls:[...N],lineage:z,...k.output?await(async()=>{const P=Vn(k.output?.type??"",o);return P?{output:await P.handle({rows:Pr,logicform:k,schema:G})}:{}})():{}}}catch(_){const T=sc(_);try{await M({stage:"failed",error:T})}catch{}throw T}},Fm=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=qr(ic(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 N of e.connections){if(N.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(N.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${N.id}`,{connectionId:N.id});i.set(N.id,N)}const s=ac(t),a=t.version,c=a===void 0||typeof a=="string"&&/^1\./.test(a),u=[...new Set(e.schemaMappings.filter(({schemaId:N})=>s.includes(N)).map(({connectionId:N})=>N))],p=e.connections.length===1?e.connections[0]?.id:u.length===1?u[0]:void 0,l=c?Rs(e.schemas,e.schemaMappings,p,s,e.connections.map(({id:N})=>N)):e.schemaMappings,m=new gt(l,e.plugins),f=s.flatMap(N=>m.list(N)).map(({connectionId:N})=>N)[0];if(!f)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const h=N=>{const D=i.get(N);if(!D)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${N}`,{connectionId:N});return $n(D,e.providerRegistry)},y=h(f),$=Qe(e.plugins),E=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],A=new er(E),g=new Set(A.definitions().map(({name:N})=>N)),w=E.length===0?$:new er([...$.definitions().filter(({name:N})=>!g.has(N)),...A.definitions()]),L=e.semanticTypes===void 0?Xr(e.plugins):Cs(e.semanticTypes,e.plugins??[]),{cache:I,...S}=e,R=I?await Ca(I):void 0;return await ii(t,{...S,schemaMappings:m,locale:n,localeRegistry:o,provider:y,providerForConnection:h,operators:w,operatorsResolved:!0,semanticTypes:L,semanticTypesResolved:!0,connectionId:f,...R?{cache:R}:{},onProgress:async N=>{r=N.partialResult,await e.onProgress?.(N)}})}catch(i){return jm(i,t,r,n,o)}},Qm=Object.freeze({execute:Fm,close:Ja});export{Sm as DBConnector,Cn as LocaleRegistry,Qm as Logicform,er as OperatorRegistry,Us as PlannerSemanticRegistry,za as ProviderRegistry,Af as QueryCacheManager,gt as SchemaMappingRegistry,d as SemanticDBError,fo as SemanticTypeRegistry,Ap as builtinOperators,ao as builtinSemanticTypes,qr as createLocaleRegistry,Qe as createOperatorRegistry,qs as createPlannerSemanticRegistry,Xr as createSemanticTypeRegistry,kr as defaultLocaleRegistry,Li as enUS,Jp as fromYiAskSchemaMapping,dr as getLogicformPropertyReferences,Wp as getSupportedDimensions,jp as isDimensionInLogicform,as as resolveOperator,mo as resolveSchema,Ns as validateResolvedSchema,Ci as zhCN};
|