@dcupl/bundle 2.0.0-beta.7 → 2.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- (function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function xi(r){return r&&DataView.prototype.isPrototypeOf(r)}if(O.arrayBuffer)var Ei=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],ji=ArrayBuffer.isView||function(r){return r&&Ei.indexOf(Object.prototype.toString.call(r))>-1};function De(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function Lt(r){return typeof r!="string"&&(r=String(r)),r}function Wt(r){var e={next:function(){var t=r.shift();return{done:t===void 0,value:t}}};return O.iterable&&(e[Symbol.iterator]=function(){return e}),e}function x(r){this.map={},r instanceof x?r.forEach(function(e,t){this.append(t,e)},this):Array.isArray(r)?r.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(e){this.append(e,r[e])},this)}x.prototype.append=function(r,e){r=De(r),e=Lt(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[De(r)]},x.prototype.get=function(r){return r=De(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(De(r))},x.prototype.set=function(r,e){this.map[De(r)]=Lt(e)},x.prototype.forEach=function(r,e){for(var t in this.map)this.map.hasOwnProperty(t)&&r.call(e,this.map[t],t,this)},x.prototype.keys=function(){var r=[];return this.forEach(function(e,t){r.push(t)}),Wt(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Wt(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Wt(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Ht(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function es(r){return new Promise(function(e,t){r.onload=function(){e(r.result)},r.onerror=function(){t(r.error)}})}function Si(r){var e=new FileReader,t=es(e);return e.readAsArrayBuffer(r),t}function Mi(r){var e=new FileReader,t=es(e),s=/charset=([A-Za-z0-9_-]+)/.exec(r.type),o=s?s[1]:"utf-8";return e.readAsText(r,o),t}function Ri(r){for(var e=new Uint8Array(r),t=new Array(e.length),s=0;s<e.length;s++)t[s]=String.fromCharCode(e[s]);return t.join("")}function ts(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function rs(){return this.bodyUsed=!1,this._initBody=function(r){this.bodyUsed=this.bodyUsed,this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:O.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:O.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():O.arrayBuffer&&O.blob&&xi(r)?(this._bodyArrayBuffer=ts(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||ji(r))?this._bodyArrayBuffer=ts(r):this._bodyText=r=Object.prototype.toString.call(r):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof r=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},O.blob&&(this.blob=function(){var r=Ht(this);if(r)return r;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var r=Ht(this);return r||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(O.blob)return this.blob().then(Si);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Ht(this);if(r)return r;if(this._bodyBlob)return Mi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Ri(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},O.formData&&(this.formData=function(){return this.text().then(Oi)}),this.json=function(){return this.text().then(JSON.parse)},this}var Ti=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ii(r){var e=r.toUpperCase();return Ti.indexOf(e)>-1?e:r}function le(r,e){if(!(this instanceof le))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var t=e.body;if(r instanceof le){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,e.headers||(this.headers=new x(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!t&&r._bodyInit!=null&&(t=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new x(e.headers)),this.method=Ii(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||(function(){if("AbortController"in R){var n=new AbortController;return n.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&t)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(t),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var s=/([?&])_=[^&]*/;if(s.test(this.url))this.url=this.url.replace(s,"$1_="+new Date().getTime());else{var o=/\?/;this.url+=(o.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}le.prototype.clone=function(){return new le(this,{body:this._bodyInit})};function Oi(r){var e=new FormData;return r.trim().split("&").forEach(function(t){if(t){var s=t.split("="),o=s.shift().replace(/\+/g," "),n=s.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}}),e}function Ki(r){var e=new x,t=r.replace(/\r?\n[\t ]+/g," ");return t.split("\r").map(function(s){return s.indexOf(`
2
- `)===0?s.substr(1,s.length):s}).forEach(function(s){var o=s.split(":"),n=o.shift().trim();if(n){var i=o.join(":").trim();try{e.append(n,i)}catch(a){console.warn("Response "+a.message)}}}),e}rs.call(le.prototype);function H(r,e){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new x(e.headers),this.url=e.url||"",this._initBody(r)}rs.call(H.prototype),H.prototype.clone=function(){return new H(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new x(this.headers),url:this.url})},H.error=function(){var r=new H(null,{status:200,statusText:""});return r.ok=!1,r.status=0,r.type="error",r};var Fi=[301,302,303,307,308];H.redirect=function(r,e){if(Fi.indexOf(e)===-1)throw new RangeError("Invalid status code");return new H(null,{status:e,headers:{location:r}})};var de=R.DOMException;try{new de}catch{de=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},de.prototype=Object.create(Error.prototype),de.prototype.constructor=de}function ss(r,e){return new Promise(function(t,s){var o=new le(r,e);if(o.signal&&o.signal.aborted)return s(new de("Aborted","AbortError"));var n=new XMLHttpRequest;function i(){n.abort()}n.onload=function(){var c={statusText:n.statusText,headers:Ki(n.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(n.status<200||n.status>599)?c.status=200:c.status=n.status,c.url="responseURL"in n?n.responseURL:c.headers.get("X-Request-URL");var l="response"in n?n.response:n.responseText;setTimeout(function(){t(new H(l,c))},0)},n.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},n.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},n.onabort=function(){setTimeout(function(){s(new de("Aborted","AbortError"))},0)};function a(c){try{return c===""&&R.location.href?R.location.href:c}catch{return c}}if(n.open(o.method,a(o.url),!0),o.credentials==="include"?n.withCredentials=!0:o.credentials==="omit"&&(n.withCredentials=!1),"responseType"in n&&(O.blob?n.responseType="blob":O.arrayBuffer&&(n.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof x||R.Headers&&e.headers instanceof R.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){u.push(De(c)),n.setRequestHeader(c,Lt(e.headers[c]))}),o.headers.forEach(function(c,l){u.indexOf(l)===-1&&n.setRequestHeader(l,c)})}else o.headers.forEach(function(c,l){n.setRequestHeader(l,c)});o.signal&&(o.signal.addEventListener("abort",i),n.onreadystatechange=function(){n.readyState===4&&o.signal.removeEventListener("abort",i)}),n.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}ss.polyfill=!0,R.fetch||(R.fetch=ss,R.Headers=x,R.Request=le,R.Response=H);var os=typeof global=="object"&&global&&global.Object===Object&&global,qi=typeof self=="object"&&self&&self.Object===Object&&self,J=os||qi||Function("return this")(),G=J.Symbol,ns=Object.prototype,Qi=ns.hasOwnProperty,Bi=ns.toString,Ge=G?G.toStringTag:void 0;function Vi(r){var e=Qi.call(r,Ge),t=r[Ge];try{r[Ge]=void 0;var s=!0}catch{}var o=Bi.call(r);return s&&(e?r[Ge]=t:delete r[Ge]),o}var Gi=Object.prototype,Ui=Gi.toString;function Ni(r){return Ui.call(r)}var zi="[object Null]",Li="[object Undefined]",is=G?G.toStringTag:void 0;function Y(r){return r==null?r===void 0?Li:zi:is&&is in Object(r)?Vi(r):Ni(r)}function K(r){return r!=null&&typeof r=="object"}var Wi="[object Symbol]";function _e(r){return typeof r=="symbol"||K(r)&&Y(r)==Wi}function Pe(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,as=G?G.prototype:void 0,us=as?as.toString:void 0;function vt(r){if(typeof r=="string")return r;if(E(r))return Pe(r,vt)+"";if(_e(r))return us?us.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Hi=/\s/;function Ji(r){for(var e=r.length;e--&&Hi.test(r.charAt(e)););return e}var Zi=/^\s+/;function Xi(r){return r&&r.slice(0,Ji(r)+1).replace(Zi,"")}function z(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var cs=NaN,Yi=/^[-+]0x[0-9a-f]+$/i,ea=/^0b[01]+$/i,ta=/^0o[0-7]+$/i,ra=parseInt;function sa(r){if(typeof r=="number")return r;if(_e(r))return cs;if(z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Xi(r);var t=ea.test(r);return t||ta.test(r)?ra(r.slice(2),t?2:8):Yi.test(r)?cs:+r}var ls=1/0,oa=17976931348623157e292;function na(r){if(!r)return r===0?r:0;if(r=sa(r),r===ls||r===-ls){var e=r<0?-1:1;return e*oa}return r===r?r:0}function bt(r){var e=na(r),t=e%1;return e===e?t?e-t:e:0}function kt(r){return r}var ia="[object AsyncFunction]",aa="[object Function]",ua="[object GeneratorFunction]",ca="[object Proxy]";function Jt(r){if(!z(r))return!1;var e=Y(r);return e==aa||e==ua||e==ia||e==ca}var Zt=J["__core-js_shared__"],ds=(function(){var r=/[^.]+$/.exec(Zt&&Zt.keys&&Zt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function la(r){return!!ds&&ds in r}var da=Function.prototype,fa=da.toString;function fe(r){if(r!=null){try{return fa.call(r)}catch{}try{return r+""}catch{}}return""}var pa=/[\\^$.*+?()[\]{}|]/g,ha=/^\[object .+?Constructor\]$/,ya=Function.prototype,ga=Object.prototype,ma=ya.toString,va=ga.hasOwnProperty,ba=RegExp("^"+ma.call(va).replace(pa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ka(r){if(!z(r)||la(r))return!1;var e=Jt(r)?ba:ha;return e.test(fe(r))}function wa(r,e){return r?.[e]}function pe(r,e){var t=wa(r,e);return ka(t)?t:void 0}var Xt=pe(J,"WeakMap"),fs=Object.create,Aa=(function(){function r(){}return function(e){if(!z(e))return{};if(fs)return fs(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ca(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var $a=800,Da=16,_a=Date.now;function Pa(r){var e=0,t=0;return function(){var s=_a(),o=Da-(s-t);if(t=s,o>0){if(++e>=$a)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function xa(r){return function(){return r}}var wt=(function(){try{var r=pe(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Ea=wt?function(r,e){return wt(r,"toString",{configurable:!0,enumerable:!1,value:xa(e),writable:!0})}:kt,ja=Pa(Ea);function Sa(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function ps(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Ma(r){return r!==r}function Ra(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function hs(r,e,t){return e===e?Ra(r,e,t):ps(r,Ma,t)}function Ta(r,e){var t=r==null?0:r.length;return!!t&&hs(r,e,0)>-1}var Ia=9007199254740991,Oa=/^(?:0|[1-9]\d*)$/;function Yt(r,e){var t=typeof r;return e=e??Ia,!!e&&(t=="number"||t!="symbol"&&Oa.test(r))&&r>-1&&r%1==0&&r<e}function At(r,e,t){e=="__proto__"&&wt?wt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Ue(r,e){return r===e||r!==r&&e!==e}var Ka=Object.prototype,Fa=Ka.hasOwnProperty;function ys(r,e,t){var s=r[e];(!(Fa.call(r,e)&&Ue(s,t))||t===void 0&&!(e in r))&&At(r,e,t)}var gs=Math.max;function qa(r,e,t){return e=gs(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=gs(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Ca(r,this,a)}}function er(r,e){return ja(qa(r,e,kt),r+"")}var Qa=9007199254740991;function tr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Qa}function ee(r){return r!=null&&tr(r.length)&&!Jt(r)}var Ba=Object.prototype;function rr(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ba;return r===t}function Va(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Ga="[object Arguments]";function ms(r){return K(r)&&Y(r)==Ga}var vs=Object.prototype,Ua=vs.hasOwnProperty,Na=vs.propertyIsEnumerable,Ne=ms((function(){return arguments})())?ms:function(r){return K(r)&&Ua.call(r,"callee")&&!Na.call(r,"callee")};function za(){return!1}var bs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ks=bs&&typeof module=="object"&&module&&!module.nodeType&&module,La=ks&&ks.exports===bs,ws=La?J.Buffer:void 0,Wa=ws?ws.isBuffer:void 0,ze=Wa||za,Ha="[object Arguments]",Ja="[object Array]",Za="[object Boolean]",Xa="[object Date]",Ya="[object Error]",eu="[object Function]",tu="[object Map]",ru="[object Number]",su="[object Object]",ou="[object RegExp]",nu="[object Set]",iu="[object String]",au="[object WeakMap]",uu="[object ArrayBuffer]",cu="[object DataView]",lu="[object Float32Array]",du="[object Float64Array]",fu="[object Int8Array]",pu="[object Int16Array]",hu="[object Int32Array]",yu="[object Uint8Array]",gu="[object Uint8ClampedArray]",mu="[object Uint16Array]",vu="[object Uint32Array]",$={};$[lu]=$[du]=$[fu]=$[pu]=$[hu]=$[yu]=$[gu]=$[mu]=$[vu]=!0,$[Ha]=$[Ja]=$[uu]=$[Za]=$[cu]=$[Xa]=$[Ya]=$[eu]=$[tu]=$[ru]=$[su]=$[ou]=$[nu]=$[iu]=$[au]=!1;function bu(r){return K(r)&&tr(r.length)&&!!$[Y(r)]}function Le(r){return function(e){return r(e)}}var As=typeof exports=="object"&&exports&&!exports.nodeType&&exports,We=As&&typeof module=="object"&&module&&!module.nodeType&&module,ku=We&&We.exports===As,sr=ku&&os.process,xe=(function(){try{var r=We&&We.require&&We.require("util").types;return r||sr&&sr.binding&&sr.binding("util")}catch{}})(),Cs=xe&&xe.isTypedArray,or=Cs?Le(Cs):bu,wu=Object.prototype,Au=wu.hasOwnProperty;function $s(r,e){var t=E(r),s=!t&&Ne(r),o=!t&&!s&&ze(r),n=!t&&!s&&!o&&or(r),i=t||s||o||n,a=i?Va(r.length,String):[],u=a.length;for(var c in r)(e||Au.call(r,c))&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Yt(c,u)))&&a.push(c);return a}function Ds(r,e){return function(t){return r(e(t))}}var Cu=Ds(Object.keys,Object),$u=Object.prototype,Du=$u.hasOwnProperty;function _s(r){if(!rr(r))return Cu(r);var e=[];for(var t in Object(r))Du.call(r,t)&&t!="constructor"&&e.push(t);return e}function He(r){return ee(r)?$s(r):_s(r)}var _u=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Pu=/^\w*$/;function nr(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||_e(r)?!0:Pu.test(r)||!_u.test(r)||e!=null&&r in Object(e)}var Je=pe(Object,"create");function xu(){this.__data__=Je?Je(null):{},this.size=0}function Eu(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var ju="__lodash_hash_undefined__",Su=Object.prototype,Mu=Su.hasOwnProperty;function Ru(r){var e=this.__data__;if(Je){var t=e[r];return t===ju?void 0:t}return Mu.call(e,r)?e[r]:void 0}var Tu=Object.prototype,Iu=Tu.hasOwnProperty;function Ou(r){var e=this.__data__;return Je?e[r]!==void 0:Iu.call(e,r)}var Ku="__lodash_hash_undefined__";function Fu(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Je&&e===void 0?Ku:e,this}function he(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}he.prototype.clear=xu,he.prototype.delete=Eu,he.prototype.get=Ru,he.prototype.has=Ou,he.prototype.set=Fu;function qu(){this.__data__=[],this.size=0}function Ct(r,e){for(var t=r.length;t--;)if(Ue(r[t][0],e))return t;return-1}var Qu=Array.prototype,Bu=Qu.splice;function Vu(r){var e=this.__data__,t=Ct(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Bu.call(e,t,1),--this.size,!0}function Gu(r){var e=this.__data__,t=Ct(e,r);return t<0?void 0:e[t][1]}function Uu(r){return Ct(this.__data__,r)>-1}function Nu(r,e){var t=this.__data__,s=Ct(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function te(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}te.prototype.clear=qu,te.prototype.delete=Vu,te.prototype.get=Gu,te.prototype.has=Uu,te.prototype.set=Nu;var Ze=pe(J,"Map");function zu(){this.size=0,this.__data__={hash:new he,map:new(Ze||te),string:new he}}function Lu(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function $t(r,e){var t=r.__data__;return Lu(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Wu(r){var e=$t(this,r).delete(r);return this.size-=e?1:0,e}function Hu(r){return $t(this,r).get(r)}function Ju(r){return $t(this,r).has(r)}function Zu(r,e){var t=$t(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=zu,re.prototype.delete=Wu,re.prototype.get=Hu,re.prototype.has=Ju,re.prototype.set=Zu;var Xu="Expected a function";function ir(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Xu);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(ir.Cache||re),t}ir.Cache=re;var Yu=500;function ec(r){var e=ir(r,function(s){return t.size===Yu&&t.clear(),s}),t=e.cache;return e}var tc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rc=/\\(\\)?/g,sc=ec(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(tc,function(t,s,o,n){e.push(o?n.replace(rc,"$1"):s||t)}),e});function ar(r){return r==null?"":vt(r)}function Ps(r,e){return E(r)?r:nr(r,e)?[r]:sc(ar(r))}function Dt(r){if(typeof r=="string"||_e(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ur(r,e){e=Ps(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[Dt(e[t++])];return t&&t==s?r:void 0}function Xe(r,e,t){var s=r==null?void 0:ur(r,e);return s===void 0?t:s}function xs(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Es=G?G.isConcatSpreadable:void 0;function oc(r){return E(r)||Ne(r)||!!(Es&&r&&r[Es])}function js(r,e,t,s,o){var n=-1,i=r.length;for(t||(t=oc),o||(o=[]);++n<i;){var a=r[n];t(a)&&xs(o,a)}return o}var Ss=Ds(Object.getPrototypeOf,Object),nc="\\ud800-\\udfff",ic="\\u0300-\\u036f",ac="\\ufe20-\\ufe2f",uc="\\u20d0-\\u20ff",cc=ic+ac+uc,lc="\\ufe0e\\ufe0f",dc="\\u200d",fc=RegExp("["+dc+nc+cc+lc+"]");function pc(r){return fc.test(r)}function Ms(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function hc(){this.__data__=new te,this.size=0}function yc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function gc(r){return this.__data__.get(r)}function mc(r){return this.__data__.has(r)}var vc=200;function bc(r,e){var t=this.__data__;if(t instanceof te){var s=t.__data__;if(!Ze||s.length<vc-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new re(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new te(r);this.size=e.size}L.prototype.clear=hc,L.prototype.delete=yc,L.prototype.get=gc,L.prototype.has=mc,L.prototype.set=bc;var Rs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ts=Rs&&typeof module=="object"&&module&&!module.nodeType&&module,kc=Ts&&Ts.exports===Rs,Is=kc?J.Buffer:void 0,Os=Is?Is.allocUnsafe:void 0;function Ks(r,e){if(e)return r.slice();var t=r.length,s=Os?Os(t):new r.constructor(t);return r.copy(s),s}function wc(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Ac(){return[]}var Cc=Object.prototype,$c=Cc.propertyIsEnumerable,Fs=Object.getOwnPropertySymbols,Dc=Fs?function(r){return r==null?[]:(r=Object(r),wc(Fs(r),function(e){return $c.call(r,e)}))}:Ac;function _c(r,e,t){var s=e(r);return E(r)?s:xs(s,t(r))}function cr(r){return _c(r,He,Dc)}var lr=pe(J,"DataView"),dr=pe(J,"Promise"),fr=pe(J,"Set"),qs="[object Map]",Pc="[object Object]",Qs="[object Promise]",Bs="[object Set]",Vs="[object WeakMap]",Gs="[object DataView]",xc=fe(lr),Ec=fe(Ze),jc=fe(dr),Sc=fe(fr),Mc=fe(Xt),U=Y;(lr&&U(new lr(new ArrayBuffer(1)))!=Gs||Ze&&U(new Ze)!=qs||dr&&U(dr.resolve())!=Qs||fr&&U(new fr)!=Bs||Xt&&U(new Xt)!=Vs)&&(U=function(r){var e=Y(r),t=e==Pc?r.constructor:void 0,s=t?fe(t):"";if(s)switch(s){case xc:return Gs;case Ec:return qs;case jc:return Qs;case Sc:return Bs;case Mc:return Vs}return e});var Rc=Object.prototype,Tc=Rc.hasOwnProperty;function Ic(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Tc.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var _t=J.Uint8Array;function pr(r){var e=new r.constructor(r.byteLength);return new _t(e).set(new _t(r)),e}function Oc(r,e){var t=pr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Kc=/\w*$/;function Fc(r){var e=new r.constructor(r.source,Kc.exec(r));return e.lastIndex=r.lastIndex,e}var Us=G?G.prototype:void 0,Ns=Us?Us.valueOf:void 0;function qc(r){return Ns?Object(Ns.call(r)):{}}function zs(r,e){var t=e?pr(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var Qc="[object Boolean]",Bc="[object Date]",Vc="[object Map]",Gc="[object Number]",Uc="[object RegExp]",Nc="[object Set]",zc="[object String]",Lc="[object Symbol]",Wc="[object ArrayBuffer]",Hc="[object DataView]",Jc="[object Float32Array]",Zc="[object Float64Array]",Xc="[object Int8Array]",Yc="[object Int16Array]",el="[object Int32Array]",tl="[object Uint8Array]",rl="[object Uint8ClampedArray]",sl="[object Uint16Array]",ol="[object Uint32Array]";function nl(r,e,t){var s=r.constructor;switch(e){case Wc:return pr(r);case Qc:case Bc:return new s(+r);case Hc:return Oc(r);case Jc:case Zc:case Xc:case Yc:case el:case tl:case rl:case sl:case ol:return zs(r,t);case Vc:return new s;case Gc:case zc:return new s(r);case Uc:return Fc(r);case Nc:return new s;case Lc:return qc(r)}}function Ls(r){return typeof r.constructor=="function"&&!rr(r)?Aa(Ss(r)):{}}var il="[object Map]";function al(r){return K(r)&&U(r)==il}var Ws=xe&&xe.isMap,ul=Ws?Le(Ws):al,cl="[object Set]";function ll(r){return K(r)&&U(r)==cl}var Hs=xe&&xe.isSet,dl=Hs?Le(Hs):ll,fl=1,Js="[object Arguments]",pl="[object Array]",hl="[object Boolean]",yl="[object Date]",gl="[object Error]",Zs="[object Function]",ml="[object GeneratorFunction]",vl="[object Map]",bl="[object Number]",Xs="[object Object]",kl="[object RegExp]",wl="[object Set]",Al="[object String]",Cl="[object Symbol]",$l="[object WeakMap]",Dl="[object ArrayBuffer]",_l="[object DataView]",Pl="[object Float32Array]",xl="[object Float64Array]",El="[object Int8Array]",jl="[object Int16Array]",Sl="[object Int32Array]",Ml="[object Uint8Array]",Rl="[object Uint8ClampedArray]",Tl="[object Uint16Array]",Il="[object Uint32Array]",w={};w[Js]=w[pl]=w[Dl]=w[_l]=w[hl]=w[yl]=w[Pl]=w[xl]=w[El]=w[jl]=w[Sl]=w[vl]=w[bl]=w[Xs]=w[kl]=w[wl]=w[Al]=w[Cl]=w[Ml]=w[Rl]=w[Tl]=w[Il]=!0,w[gl]=w[Zs]=w[$l]=!1;function Pt(r,e,t,s,o,n){var i,a=e&fl;if(i!==void 0)return i;if(!z(r))return r;var u=E(r);if(u)i=Ic(r);else{var c=U(r),l=c==Zs||c==ml;if(ze(r))return Ks(r,a);if(c==Xs||c==Js||l&&!o)i=l?{}:Ls(r);else{if(!w[c])return o?r:{};i=nl(r,c,a)}}n||(n=new L);var d=n.get(r);if(d)return d;n.set(r,i),dl(r)?r.forEach(function(p){i.add(Pt(p,e,t,p,r,n))}):ul(r)&&r.forEach(function(p,y){i.set(y,Pt(p,e,t,y,r,n))});var f=cr,h=u?void 0:f(r);return Sa(h||r,function(p,y){h&&(y=p,p=r[y]),ys(i,y,Pt(p,e,t,y,r,n))}),i}var Ol=1,Kl=4;function se(r){return Pt(r,Ol|Kl)}var Fl="__lodash_hash_undefined__";function ql(r){return this.__data__.set(r,Fl),this}function Ql(r){return this.__data__.has(r)}function Ye(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new re;++e<t;)this.add(r[e])}Ye.prototype.add=Ye.prototype.push=ql,Ye.prototype.has=Ql;function Bl(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(e(r[t],t,r))return!0;return!1}function Ys(r,e){return r.has(e)}var Vl=1,Gl=2;function eo(r,e,t,s,o,n){var i=t&Vl,a=r.length,u=e.length;if(a!=u&&!(i&&u>a))return!1;var c=n.get(r),l=n.get(e);if(c&&l)return c==e&&l==r;var d=-1,f=!0,h=t&Gl?new Ye:void 0;for(n.set(r,e),n.set(e,r);++d<a;){var p=r[d],y=e[d];if(s)var v=i?s(y,p,d,e,r,n):s(p,y,d,r,e,n);if(v!==void 0){if(v)continue;f=!1;break}if(h){if(!Bl(e,function(g,k){if(!Ys(h,k)&&(p===g||o(p,g,t,s,n)))return h.push(k)})){f=!1;break}}else if(!(p===y||o(p,y,t,s,n))){f=!1;break}}return n.delete(r),n.delete(e),f}function Ul(r){var e=-1,t=Array(r.size);return r.forEach(function(s,o){t[++e]=[o,s]}),t}function Nl(r){var e=-1,t=Array(r.size);return r.forEach(function(s){t[++e]=s}),t}var zl=1,Ll=2,Wl="[object Boolean]",Hl="[object Date]",Jl="[object Error]",Zl="[object Map]",Xl="[object Number]",Yl="[object RegExp]",ed="[object Set]",td="[object String]",rd="[object Symbol]",sd="[object ArrayBuffer]",od="[object DataView]",to=G?G.prototype:void 0,hr=to?to.valueOf:void 0;function nd(r,e,t,s,o,n,i){switch(t){case od:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case sd:return!(r.byteLength!=e.byteLength||!n(new _t(r),new _t(e)));case Wl:case Hl:case Xl:return Ue(+r,+e);case Jl:return r.name==e.name&&r.message==e.message;case Yl:case td:return r==e+"";case Zl:var a=Ul;case ed:var u=s&zl;if(a||(a=Nl),r.size!=e.size&&!u)return!1;var c=i.get(r);if(c)return c==e;s|=Ll,i.set(r,e);var l=eo(a(r),a(e),s,o,n,i);return i.delete(r),l;case rd:if(hr)return hr.call(r)==hr.call(e)}return!1}var id=1,ad=Object.prototype,ud=ad.hasOwnProperty;function cd(r,e,t,s,o,n){var i=t&id,a=cr(r),u=a.length,c=cr(e),l=c.length;if(u!=l&&!i)return!1;for(var d=u;d--;){var f=a[d];if(!(i?f in e:ud.call(e,f)))return!1}var h=n.get(r),p=n.get(e);if(h&&p)return h==e&&p==r;var y=!0;n.set(r,e),n.set(e,r);for(var v=i;++d<u;){f=a[d];var g=r[f],k=e[f];if(s)var m=i?s(k,g,f,e,r,n):s(g,k,f,r,e,n);if(!(m===void 0?g===k||o(g,k,t,s,n):m)){y=!1;break}v||(v=f=="constructor")}if(y&&!v){var M=r.constructor,N=e.constructor;M!=N&&"constructor"in r&&"constructor"in e&&!(typeof M=="function"&&M instanceof M&&typeof N=="function"&&N instanceof N)&&(y=!1)}return n.delete(r),n.delete(e),y}var ld=1,ro="[object Arguments]",so="[object Array]",xt="[object Object]",dd=Object.prototype,oo=dd.hasOwnProperty;function fd(r,e,t,s,o,n){var i=E(r),a=E(e),u=i?so:U(r),c=a?so:U(e);u=u==ro?xt:u,c=c==ro?xt:c;var l=u==xt,d=c==xt,f=u==c;if(f&&ze(r)){if(!ze(e))return!1;i=!0,l=!1}if(f&&!l)return n||(n=new L),i||or(r)?eo(r,e,t,s,o,n):nd(r,e,u,t,s,o,n);if(!(t&ld)){var h=l&&oo.call(r,"__wrapped__"),p=d&&oo.call(e,"__wrapped__");if(h||p){var y=h?r.value():r,v=p?e.value():e;return n||(n=new L),o(y,v,t,s,n)}}return f?(n||(n=new L),cd(r,e,t,s,o,n)):!1}function et(r,e,t,s,o){return r===e?!0:r==null||e==null||!K(r)&&!K(e)?r!==r&&e!==e:fd(r,e,t,s,et,o)}var pd=1,hd=2;function no(r,e,t,s){var o=t.length,n=o;if(r==null)return!n;for(r=Object(r);o--;){var i=t[o];if(i[2]?i[1]!==r[i[0]]:!(i[0]in r))return!1}for(;++o<n;){i=t[o];var a=i[0],u=r[a],c=i[1];if(i[2]){if(u===void 0&&!(a in r))return!1}else{var l=new L,d;if(!(d===void 0?et(c,u,pd|hd,s,l):d))return!1}}return!0}function io(r){return r===r&&!z(r)}function ao(r){for(var e=He(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,io(o)]}return e}function uo(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function yd(r){var e=ao(r);return e.length==1&&e[0][2]?uo(e[0][0],e[0][1]):function(t){return t===r||no(t,r,e)}}function gd(r,e){return r!=null&&e in Object(r)}function md(r,e,t){e=Ps(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=Dt(e[s]);if(!(n=r!=null&&t(r,i)))break;r=r[i]}return n||++s!=o?n:(o=r==null?0:r.length,!!o&&tr(o)&&Yt(i,o)&&(E(r)||Ne(r)))}function vd(r,e){return r!=null&&md(r,e,gd)}var bd=1,kd=2;function wd(r,e){return nr(r)&&io(e)?uo(Dt(r),e):function(t){var s=Xe(t,r);return s===void 0&&s===e?vd(t,r):et(e,s,bd|kd)}}function co(r){return function(e){return e?.[r]}}function Ad(r){return function(e){return ur(e,r)}}function Cd(r){return nr(r)?co(Dt(r)):Ad(r)}function Ee(r){return typeof r=="function"?r:r==null?kt:typeof r=="object"?E(r)?wd(r[0],r[1]):yd(r):Cd(r)}function $d(r){return function(e,t,s){for(var o=-1,n=Object(e),i=s(e),a=i.length;a--;){var u=i[++o];if(t(n[u],u,n)===!1)break}return e}}var lo=$d();function Dd(r,e){return r&&lo(r,e,He)}function _d(r,e){return function(t,s){if(t==null)return t;if(!ee(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var yr=_d(Dd);function je(r){return K(r)&&ee(r)}var Pd=200;function fo(r,e,t,s){var o=-1,n=Ta,i=!0,a=r.length,u=[],c=e.length;if(!a)return u;t&&(e=Pe(e,Le(t))),e.length>=Pd&&(n=Ys,i=!1,e=new Ye(e));e:for(;++o<a;){var l=r[o],d=t==null?l:t(l);if(l=l!==0?l:0,i&&d===d){for(var f=c;f--;)if(e[f]===d)continue e;u.push(l)}else n(e,d,s)||u.push(l)}return u}function xd(r){var e=r==null?0:r.length;return e?r[e-1]:void 0}var po=er(function(r,e){var t=xd(e);return je(t)&&(t=void 0),je(r)?fo(r,js(e,1,je),Ee(t)):[]});function ho(r,e,t){r=ar(r),e=vt(e);var s=r.length;t=t===void 0?s:Ms(bt(t),0,s);var o=t;return t-=e.length,t>=0&&r.slice(t,o)==e}function Ed(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(!e(r[t],t,r))return!1;return!0}function jd(r,e){var t=!0;return yr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function yo(r,e,t){var s=E(r)?Ed:jd;return s(r,Ee(e))}function Sd(r){return function(e,t,s){var o=Object(e);if(!ee(e)){var n=Ee(t);e=He(e),t=function(a){return n(o[a],a,o)}}var i=r(e,t,s);return i>-1?o[n?e[i]:i]:void 0}}var Md=Math.max;function gr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:bt(t);return o<0&&(o=Md(s+o,0)),ps(r,Ee(e),o)}var Rd=Sd(gr);function Td(r,e){var t=-1,s=ee(r)?Array(r.length):[];return yr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var Id="[object String]";function Et(r){return typeof r=="string"||!E(r)&&K(r)&&Y(r)==Id}function go(r,e){return et(r,e)}function jt(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?et(r,e,void 0,t):!!s}function Od(r,e){return r===e||no(r,e,ao(e))}function Kd(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Fd(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=_e(r),i=e!==void 0,a=e===null,u=e===e,c=_e(e);if(!a&&!c&&!n&&r>e||n&&i&&u&&!a&&!c||s&&i&&u||!t&&u||!o)return 1;if(!s&&!n&&!c&&r<e||c&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!u)return-1}return 0}function qd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var u=Fd(o[s],n[s]);if(u){if(s>=a)return u;var c=t[s];return u*(c=="desc"?-1:1)}}return r.index-e.index}function Qd(r,e,t){e.length?e=Pe(e,function(n){return E(n)?function(i){return ur(i,n.length===1?n[0]:n)}:n}):e=[kt];var s=-1;e=Pe(e,Le(Ee));var o=Td(r,function(n,i,a){var u=Pe(e,function(c){return c(n)});return{criteria:u,index:++s,value:n}});return Kd(o,function(n,i){return qd(n,i,t)})}function mo(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Qd(r,e,t))}var Bd=co("length"),vo="\\ud800-\\udfff",Vd="\\u0300-\\u036f",Gd="\\ufe20-\\ufe2f",Ud="\\u20d0-\\u20ff",Nd=Vd+Gd+Ud,zd="\\ufe0e\\ufe0f",Ld="["+vo+"]",mr="["+Nd+"]",vr="\\ud83c[\\udffb-\\udfff]",Wd="(?:"+mr+"|"+vr+")",bo="[^"+vo+"]",ko="(?:\\ud83c[\\udde6-\\uddff]){2}",wo="[\\ud800-\\udbff][\\udc00-\\udfff]",Hd="\\u200d",Ao=Wd+"?",Co="["+zd+"]?",Jd="(?:"+Hd+"(?:"+[bo,ko,wo].join("|")+")"+Co+Ao+")*",Zd=Co+Ao+Jd,Xd="(?:"+[bo+mr+"?",mr,ko,wo,Ld].join("|")+")",$o=RegExp(vr+"(?="+vr+")|"+Xd+Zd,"g");function Yd(r){for(var e=$o.lastIndex=0;$o.test(r);)++e;return e}function ef(r){return pc(r)?Yd(r):Bd(r)}var tf="[object Map]",rf="[object Set]";function sf(r){if(r==null)return 0;if(ee(r))return Et(r)?ef(r):r.length;var e=U(r);return e==tf||e==rf?r.size:_s(r).length}function of(r,e,t){return r=ar(r),t=t==null?0:Ms(bt(t),0,r.length),e=vt(e),r.slice(t,t+e.length)==e}function br(r){const e=kr(r);return nf(e)}function kr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(kr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+kr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function nf(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const ye={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}};class af{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s={name:e.name,type:"mark",value:ye.now(),createdAt:Date.now()};return this.data.set(t,s),s}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s=this.data.get(this.getKey(e.start,e.context)),o=this.data.get(this.getKey(e.end,e.context));if(!s||!o)return;const n=o.value-s.value,i=Math.round(n*100)/100,a=this.data.get(t);if(a&&e.sum){const c=a.value+i,l={...a,value:c};return this.data.set(t,l),l}const u={name:e.name,type:"measure",value:i,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),s=this.data.get(t);if(s){const o={...s,...e.value};this.data.set(t,o)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:ye.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const s=br(t);return e+"_"+s}}let Do=class Pi{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const u=o(a);if(u)return u}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const u=this.edges.get(a);if(u)for(let c of u)i(c);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const u=this.edges.get(a);if(u)for(const c of u)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&o.push(c)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(u=>i.has(this.nodeKinds.get(u))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=c=>!s||s.length===0||s.includes(this.nodeKinds.get(c)??void 0),i=()=>{const c=new Set,l=Array.from(o);for(;l.length;){const d=l.shift();for(const[f,h]of this.edges)h.has(d)&&!c.has(f)&&(c.add(f),l.push(f))}return c},a=()=>{const c=new Set,l=Array.from(o);for(;l.length;){const d=l.shift(),f=this.edges.get(d);if(f)for(const h of f)c.has(h)||(c.add(h),l.push(h))}return c};let u;return t==="both"?u=new Set([...i(),...a()]):t==="upstream"?u=a():u=i(),Array.from(u).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Pi;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),u=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),c=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),l=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&l.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:u,removedEdges:c,kindChanges:l}}};class uf{graph;nodeIndex;constructor(){this.graph=new Do,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const u=t.get(n);u.has(a)||u.set(a,new Set),u.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const u=t(a,new Set(o));i=Math.max(i,u)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,attributeKey:n})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const _o={silent:0,error:1,warn:2,info:3,debug:4};let cf=class I{config;static globalConfig={};constructor(e={}){this.config={level:e.level??I.globalConfig.level??this.getDefaultLevel(),format:e.format??I.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??I.globalConfig.onLog,onTrackError:e.onTrackError??I.globalConfig.onTrackError}}static setGlobalConfig(e){I.globalConfig={...I.globalConfig,...e}}static getGlobalConfig(){return{...I.globalConfig}}static setModuleLevel(e,t){I.globalConfig.onLog||(I.globalConfig.onLog=void 0),I._moduleOverrides||(I._moduleOverrides=new Map),I._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!I._moduleOverrides))return I._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=I.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return _o[e]<=_o[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new I(t)}configure(e){Object.assign(this.config,e)}};const Se=new cf;class Po{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=Se.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const u=o.modelAttributes.get(i);for(const c of a)if(u.has(c)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return se(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=br(t);return e+"_"+s}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class wr{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=ye.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const xo=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):se(r):r,Eo=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=xo(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=ye.now(),c=u-s,l=Math.round(c*1e3)/1e3;t.duration=l,t.start=s,t.end=u;const d={duration:t.duration};return t.modelKey&&(d.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(d.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},b=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=ye.now(),a=this.cdRef,u=xo(r,!0);u.key||(a.increaseCounter(),u.key=a.getCounter());const c=W();a.analyticsController.mark({name:`${u.type}:start`,context:c});const l=this.model?.key;!u.originCdRefKey&&a.key&&(u.originCdRefKey=a.key),l&&(u.modelKey=l);const d=o.apply(this,n);return u.method=t,u.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Eo(this,a,u,i,c,f)):Eo(this,a,u,i,c,d)},s};function lf(r,e,t,s){t.max||(t.max=20);const o=[],n=t.transform?s.transformValue(t.value,t.transform):t.value;for(const[i,a]of e.entries()){const u=Array.from(a).some(l=>r.has(l)),c=t.transform?s.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(u&&(n===""||n==="//")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}else if(u&&typeof n=="string"&&n.startsWith("/")&&n.endsWith("/")){if(s.queryFind(c,n,"some")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}}else if(u&&typeof n=="string"){const l=String(c??""),d=n;if(l.toLowerCase().startsWith(d.toLowerCase())){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(f)}}else if(u&&s.queryFind(c,n,"some")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}if(o.length===t.max)break}}return o}function df(r){return r instanceof Date}function jo(r){return r instanceof Date&&!isNaN(r.getTime())}const ff={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function pf(r){let e="^";const t=[];let s=r;const o=Object.entries(ff).sort((n,i)=>i[0].length-n[0].length);for(;s.length>0;){let n=!1;for(const[i,a]of o)if(s.startsWith(i)){e+=a.regex,t.push({type:a.type,pattern:i}),s=s.slice(i.length),n=!0;break}if(!n){const i=s[0];if(!i)break;e+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=s.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function hf(r,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let s=0;s<e.length;s++){const o=r[s+1];if(!o)continue;const n=parseInt(o,10),i=e[s];i&&(i.type==="year"&&i.pattern==="yy"?t.year=2e3+n:t[i.type]=n)}return t}function yf(r){if(r.month<1||r.month>12)return new Date(NaN);if(r.day<1||r.day>31)return new Date(NaN);if(r.hour<0||r.hour>23)return new Date(NaN);if(r.minute<0||r.minute>59)return new Date(NaN);if(r.second<0||r.second>59)return new Date(NaN);if(r.millisecond<0||r.millisecond>999)return new Date(NaN);const e=new Date(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return jo(e)?e.getFullYear()!==r.year||e.getMonth()!==r.month-1||e.getDate()!==r.day?new Date(NaN):e:new Date(NaN)}function gf(r,e,t){if(r=r.trim(),e==="t"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:s,tokenOrder:o}=pf(e),n=r.match(s);if(!n)return new Date(NaN);const i=hf(n,o);return yf(i)}class mf{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const s=this.accessOrder.shift();s!==void 0&&this.cache.delete(s)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class vf{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,s=new Set,o=n=>{t.add(n),s.add(n);const i=this.graph.get(n);if(i){for(const a of i)if(t.has(a)){if(s.has(a))return!0}else if(o(a))return!0}return s.delete(n),!1};for(let n=0;n<e.length-1;n++){const i=e[n],a=e[n+1];i&&a&&this.addDependency(i,a)}for(const n of e)if(!t.has(n)&&o(n))return!0;return!1}clear(){this.graph.clear()}}class bf{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new mf(e),this.circularRefDetector=new vf}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,s;const o=e.includes("."),n=e.includes("["),i=o||n;if(i)if(s=e.split(/[.[]/)[0],n){const u=e.indexOf("]");if(u>-1){const c=e.indexOf(".",u+1);c>-1?t=e.substring(c+1):t=void 0}else o&&(t=e.substring(e.indexOf(".")+1))}else o&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:i};return s&&(a.reference=s),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const s=[];if(!e||e.trim().length===0)return s.push("Attribute path cannot be empty"),{valid:!1,errors:s};(e.startsWith(".")||e.endsWith("."))&&s.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&s.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const o=(e.match(/\[/g)||[]).length,n=(e.match(/]/g)||[]).length;o!==n&&s.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&s.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const i=/\[([^\]]+)\]/g;let a;for(;(a=i.exec(e))!==null;){const l=a[1];l&&l!=="*"&&!/^\d+$/.test(l)&&s.push(`Invalid bracket content: Must be a number or '*', got '${l}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&s.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&s.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:s.length===0,errors:s.length>0?s:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,s=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:s}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(t=>t.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const P=new bf;function ge(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),u=i?Xe(r,i):r;if(!Array.isArray(u))return[];const c=[];for(const l of u)!a||a===""?l!==void 0&&c.push(l):a.startsWith(".")&&c.push(...ge(l,a.slice(1)));return c}const t=e.split(".");let s=[r];for(const n of t){const i=[];for(const a of s)if(a!=null)if(Array.isArray(a))for(const u of a){if(u==null)continue;const c=u[n];c!==void 0&&i.push(c)}else{const u=a[n];u!==void 0&&i.push(u)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function Ar(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function So(r,e,t){return(r*t+e*t)/t}function kf(r,e,t){return r*t/(e*t)}const tt=(r,e,t,s)=>{if(!s)throw new Error("Attribute not found");const o={attribute:s,types:r.types};let n;(o.types.includes("sum")||o.types.includes("avg"))&&(n=$f(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Af(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=wf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Df(r,e,t):a==="group"&&(o.group=Cf(r,e))}),o},wf=(r,e)=>{const t=P.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=ge(o,r).filter(n=>n!=null).length;else{const n=o[r];if(n==null)continue;Array.isArray(n)?s+=n.filter(i=>i!=null).length:s++}return s},Af=(r,e)=>{let t,s;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ge(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a.filter(u=>u!==void 0):i=[a]}for(const a of i)a==null||typeof a=="object"||((t===void 0||a<t)&&(t=a),(s===void 0||a>s)&&(s=a))}if(!(t===void 0||s===void 0))return[t,s]},Cf=(r,e)=>{const t=[];r.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const s={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=P.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=ge(n,r.attribute):i=[n[r.attribute]];let a=!1;for(const u of i)for(const c of t)(typeof c.option.value<"u"&&c.option.value.includes(u)||typeof c.option.from<"u"&&c.option.from<u&&typeof c.option.to<"u"&&c.option.to>u)&&(c.keys.includes(n.key)||(c.count++,c.keys.push(n.key)),a=!0);!a&&r?.groupOptions?.calculateNotFound&&(s.count++,s.keys.push(n.key))}return r?.groupOptions?.calculateNotFound&&t.push(s),t},$f=(r,e)=>{let t=0,s=0;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ge(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a:i=[a]}for(const a of i)if(Array.isArray(a))for(const u of a)typeof u=="number"&&(t=So(t,u,Ar([t,u])),s++);else typeof a=="number"&&(t=So(t,a,Ar([t,a])),s++)}return s===0?void 0:{average:kf(t,s,Ar([t,s])),count:s,sum:t}},Df=(r,e,t)=>{const s=[];for(const[o,n]of t)if(!(r.excludeUndefineds&&typeof o>"u")&&Array.from(n).find(i=>e.has(i))){const i={value:o,count:n.size};if(r.distinctOptions?.skipKeys||(i.keys=Array.from(n)),s.push(i),r.distinctOptions?.limit&&s.length>=r.distinctOptions.limit)break}return s};let rt=class extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}},me=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=se(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||P}init(e){this._initOptions=se(e),this.currentQuery=se(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=se(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return se(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(s=>this.isQuery(s)&&s.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:yo(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.groupKey);if(o>-1){const n=s.queries[o];e.groupType&&(n.groupType=e.groupType),t?.mode==="set"?s.queries[o]=e:n.queries=[...n.queries,...e.queries]}else s.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return s}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.attribute);if(s>-1){const o=t.queries[s],n=gr(o.queries,e);n>-1&&o.queries.splice(n,1),o.queries.length===0&&t.queries.splice(s,1)}}else if(this.isQueryGroup(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(s>-1)if(!e.queries)t.queries.splice(s,1);else{const o=t.queries[s];for(const n of e.queries){const i=gr(o.queries,n);i>-1&&o.queries.splice(i,1)}o.queries.length===0&&t.queries.splice(s,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new rt("Missing attribute",e)),e.operator||t.push(new rt("Missing operator",e)),typeof e.value>"u"&&t.push(new rt("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new rt("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const s=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return s.length>0?{valid:!1,errors:s}:{valid:!0}}return t.push(new rt("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(e=>e.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const Cr=new me;function _f(r,e,t,s,o,n,i){const a=Cr.removeQuery({groupKey:o},se(s)),u=i.queryData(r,a,!1,n),c=e?[...e.keys()]:[],l=new Set(c),d=n.get(o);if(!t.excludeUnresolved)for(const h of d.keys())l.add(h);if(t.excludeUndefineds?l.delete(void 0):l.add(void 0),t.sort){const h=[];for(const y of l.values())h.push(Mo(y,d,u,e,o,s,!0));const p=t.excludeZeros?h.filter(y=>y.size>0):h;return p.sort(Pf(t.sort)),t.count?p.slice(0,t.count):p}const f=[];for(const h of l.values()){const p=Mo(h,d,u,e,o,s,!!t?.calculateFacets);if(!(t?.excludeZeros&&p.size===0)){if(t?.count&&f.length===t?.count)return f;f.push(p)}}return f}function Mo(r,e,t,s,o,n,i){const a=new Map,u=e.get(r)||new Set;for(const c of u){const l=t.get(c);if(l&&(a.set(c,l),!i))break}return{key:String(r),value:r,selected:xf(o,r,n),enabled:a.size>0,size:a.size,entry:s.get(r),resultKeys:Array.from(a.keys())}}function St(r,e){if(r===void 0&&e===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;const t=typeof r,s=typeof e;if(t!==s)return t<s?-1:1;if(t==="number")return r-e;if(t==="string")return r.localeCompare(e);const o=String(r),n=String(e);return o<n?-1:o>n?1:0}function Pf(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||St(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||St(e.value,t.value);case"value-asc":return(e,t)=>St(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-St(e.value,t.value)}}const xf=(r,e,t)=>{const s=t.queries.findIndex(o=>Cr.isQueryGroup(o)&&o.groupKey===r);return s>-1?!!t.queries[s].queries.find(o=>{if(Cr.isQuery(o)){const n=o.value?.key||o.value;return o.attribute===r&&n===e}return!1}):!1};class Mt{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const u of n)this.fillInverseIndex(e,t,[u]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=P.parse(e).isDeepQuery??!1;this.indexMetadata.set(o,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:s,type:a?"deep":"shallow"})}if(!n){this.reset(o),this.indexMap.set(o,new Map);const a=P.parse(e).isDeepQuery;for(const u of t.values()){let c;a?(c=ge(u,e),c.length===0&&(c=[void 0])):c=[u[e]],this.fillInverseIndex(o,u.key,c),this.fillDataMap(o,c)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+br(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const u of n)this.removeFromInverseIndex(e,t,[u]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return P.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const s of this.indexMap.keys())this.isDeepQueryIndex(s)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let s=0;for(const[o,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(o),s++);return s}getStats(){const e=this.getIndexCount(),t=Date.now();let s=0,o=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;s+=a,a>o&&(o=a)}const n=this.indexMetadata.size>0?s/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:o,avgAge:n}}}const Me="__";function $r(r,e,t={key:"root"},s="root",o=new Mt,n){const i=n||r;for(const a of e.columns)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Ef(r,e.rows[0],e,o,s,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=Ro(r,e.columns[0],e,o,s,n);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],s==="root"&&e.options?.calculateTotals===!1)continue;const u=tt(a,r,o.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function Ef(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const l={key:u,value:u},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(l.values=l.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=tt(f,d,s.getIndex(f.attribute),f.attribute);l.values.push(h)}if(i.rows=i.rows||[],i.rows.push(l),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};$r(d,f,l,o+Me+e.attribute+Me+u,s,n)}else if(t.columns)for(const f of t.columns){l.columns=l.columns||[];const h=Ro(d,f,t,s,o+Me+e.attribute+Me+u,n);l.columns.push(h)}}}return i}function Ro(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const l={key:u,value:u},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(l.values=l.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=tt(f,d,s.getIndex(f.attribute),f.attribute);l.values.push(h)}if(i.columns=i.columns||[],i.columns.push(l),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};$r(d,f,l,o+Me+e.attribute+Me+u,s,n)}}}return i}const jf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Sf=/^-?\d+$/,Mf=/^-?\d+\.\d+$/,Rf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Tf=r=>r==="true"||r==="false"?"boolean":Sf.test(r)?"int":Mf.test(r)?"float":jf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",If=r=>Rf.test(r),Of=r=>r==null||r==="",Kf=r=>{const e=[...r];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},Ff=(r,e={})=>{const t=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,o=new Map,n=[],i=Math.min(r.length,t);for(let c=0;c<i;c++){const l=r[c];if(l)for(const[d,f]of Object.entries(l)){let h=o.get(d);if(h||(h={observed:new Set,empty:0,scanned:0},o.set(d,h),n.push(d)),h.scanned++,Of(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Tf(f),p==="string"&&!h.hint&&If(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=qf(f),h.observed.add(p)}}const a=[],u=[];for(const c of n){const l=o.get(c),{type:d,conflict:f}=Kf(l.observed.size?l.observed:new Set(["string"]));a.push({key:c,type:d}),u.push({column:c,inferredType:d,observedTypes:[...l.observed].sort(),emptyRate:l.scanned===0?0:l.empty/l.scanned,conflict:f,hint:l.hint})}return{properties:a,diagnostics:u}},To=(r,e=!1)=>Ff(r,typeof e=="boolean"?{deep:e}:e).properties,Io=r=>Number(r)===r&&r%1===0,Oo=r=>Number(r)===r&&r%1!==0,qf=r=>{switch(typeof r){case"string":return"string";case"number":return Io(r)?"int":Oo(r)?"float":"any";case"boolean":return"boolean";case"object":return df(r)?"date":"json";default:return"any"}};class Qf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}registeredCustomOperator=new Map;queryBuilder=new me;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s,o=e.value;const n=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(o=this.transformValue(o,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?s=Xe(t,e.attribute):s=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),(typeof s>"u"||s===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!go(s,o):go(s,o);case"find":return e.options?.invert?!this.queryFind(s,o,n):this.queryFind(s,o,n);case"lt":return Array.isArray(s)?n==="some"?s.some(i=>i<o):s.every(i=>i<o):s<o;case"gt":return Array.isArray(s)?n==="some"?s.some(i=>i>o):s.every(i=>i>o):s>o;case"lte":return Array.isArray(s)?n==="some"?s.some(i=>i<=o):s.every(i=>i<=o):s<=o;case"gte":return Array.isArray(s)?n==="some"?s.some(i=>i>=o):s.every(i=>i>=o):s>=o;case"typeof":return e.options?.invert?typeof s!==o:Array.isArray(s)?n==="some"?s.some(i=>typeof i===o):s.every(i=>typeof i===o):typeof s===o;case"isTruthy":return o===!0?Array.isArray(s)?n==="some"?s.some(i=>typeof!!i):s.every(i=>typeof!!i):!!s:!s;case"size":return typeof s=="string"?s.length===o:sf(s)===o;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const i=this.registeredCustomOperator.get(e.operator);if(typeof i=="function")return i(e,t)}}return!1}evaluateEqOperator(e,t,s,o){const n=new Map,i=o.get(t.attribute);if(i){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=i.get(a);if(u)if(u.forEach(c=>{s.has(c)&&n.set(c,s.get(c))}),t.options?.invert){const c=po(Array.from(s.values()),Array.from(n.values()),"key"),l=new Map;return c.forEach(d=>{l.set(d.key,d)}),l}else return n}}for(let[a,u]of s){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(l=>l.isDeepQuery)){const l=this.queryBuilder.getProjectionForAttributeEntries(c.filter(d=>d.isDeepQuery));u=this.globalItemService.getProjectedData(l,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&n.set(a,u)}return n}equalRegexFn(e,t){if(typeof t=="string"&&of(t,"/")&&ho(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(s=>jt(s,t,this.equalRegexFn)):typeof t=="object"?Od(e,t):e===t}queryFind(e,t,s){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?s==="some"?e.some(o=>jt(o,t,this.equalRegexFn)):e.every(o=>jt(o,t,this.equalRegexFn)):!!Rd(e,t):jt(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return yo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let u of s.values()){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(c.filter(h=>h.isDeepQuery));u=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),u)}const l=this.handleArrayStarQuery(t,u);let d=!1;for(const f of l.queries){const h={...f,options:{...f.options,invert:!1}};if(this.evaluateQuery(h,u)){d=!0;break}}d&&(a.add(u.key),i||n.set(u.key,u))}if(i)for(const[u,c]of s)a.has(u)||n.set(u,c)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,s,o);for(let[i,a]of s){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(l=>l.isDeepQuery));a=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&n.set(i,a)}}return n}handleArrayStarQuery(e,t){const s=e.attribute.indexOf("[*]"),o={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(s!==-1){const n=e.attribute.substring(0,s),i=n.includes(".")?Xe(t,n):t[n];if(Array.isArray(i))for(let a=0;a<i.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);o.queries.push({attribute:u,operator:e.operator,value:e.value,options:e.options})}}return o}evaluateQueryGroup(e,t,s,o,n){let i=new Map,a=s;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,n):c=this.evaluateQueryGroup(e,u,a,o,n),i.size===0&&(i=c),t.groupType==="or")c.forEach(l=>{i.set(l.key,l)});else{const l=po(Array.from(i.values()),Array.from(c.values()),"key");for(const d of l)i.delete(d.key)}t.groupType==="and"?a=i:a=s}return i}queryData(e,t,s,o){const n=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,s,o))}}class Bf{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
1
+ (function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function Ki(r){return r&&DataView.prototype.isPrototypeOf(r)}if(O.arrayBuffer)var Fi=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],qi=ArrayBuffer.isView||function(r){return r&&Fi.indexOf(Object.prototype.toString.call(r))>-1};function Pe(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function Wt(r){return typeof r!="string"&&(r=String(r)),r}function Ht(r){var e={next:function(){var t=r.shift();return{done:t===void 0,value:t}}};return O.iterable&&(e[Symbol.iterator]=function(){return e}),e}function x(r){this.map={},r instanceof x?r.forEach(function(e,t){this.append(t,e)},this):Array.isArray(r)?r.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(e){this.append(e,r[e])},this)}x.prototype.append=function(r,e){r=Pe(r),e=Wt(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[Pe(r)]},x.prototype.get=function(r){return r=Pe(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(Pe(r))},x.prototype.set=function(r,e){this.map[Pe(r)]=Wt(e)},x.prototype.forEach=function(r,e){for(var t in this.map)this.map.hasOwnProperty(t)&&r.call(e,this.map[t],t,this)},x.prototype.keys=function(){var r=[];return this.forEach(function(e,t){r.push(t)}),Ht(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Ht(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Ht(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Jt(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function os(r){return new Promise(function(e,t){r.onload=function(){e(r.result)},r.onerror=function(){t(r.error)}})}function Qi(r){var e=new FileReader,t=os(e);return e.readAsArrayBuffer(r),t}function Bi(r){var e=new FileReader,t=os(e),s=/charset=([A-Za-z0-9_-]+)/.exec(r.type),o=s?s[1]:"utf-8";return e.readAsText(r,o),t}function Vi(r){for(var e=new Uint8Array(r),t=new Array(e.length),s=0;s<e.length;s++)t[s]=String.fromCharCode(e[s]);return t.join("")}function ns(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function is(){return this.bodyUsed=!1,this._initBody=function(r){this.bodyUsed=this.bodyUsed,this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:O.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:O.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():O.arrayBuffer&&O.blob&&Ki(r)?(this._bodyArrayBuffer=ns(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||qi(r))?this._bodyArrayBuffer=ns(r):this._bodyText=r=Object.prototype.toString.call(r):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof r=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},O.blob&&(this.blob=function(){var r=Jt(this);if(r)return r;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var r=Jt(this);return r||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(O.blob)return this.blob().then(Qi);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Jt(this);if(r)return r;if(this._bodyBlob)return Bi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Vi(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},O.formData&&(this.formData=function(){return this.text().then(Ni)}),this.json=function(){return this.text().then(JSON.parse)},this}var Gi=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ui(r){var e=r.toUpperCase();return Gi.indexOf(e)>-1?e:r}function fe(r,e){if(!(this instanceof fe))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var t=e.body;if(r instanceof fe){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,e.headers||(this.headers=new x(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!t&&r._bodyInit!=null&&(t=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new x(e.headers)),this.method=Ui(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||(function(){if("AbortController"in R){var n=new AbortController;return n.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&t)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(t),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var s=/([?&])_=[^&]*/;if(s.test(this.url))this.url=this.url.replace(s,"$1_="+new Date().getTime());else{var o=/\?/;this.url+=(o.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}fe.prototype.clone=function(){return new fe(this,{body:this._bodyInit})};function Ni(r){var e=new FormData;return r.trim().split("&").forEach(function(t){if(t){var s=t.split("="),o=s.shift().replace(/\+/g," "),n=s.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}}),e}function zi(r){var e=new x,t=r.replace(/\r?\n[\t ]+/g," ");return t.split("\r").map(function(s){return s.indexOf(`
2
+ `)===0?s.substr(1,s.length):s}).forEach(function(s){var o=s.split(":"),n=o.shift().trim();if(n){var i=o.join(":").trim();try{e.append(n,i)}catch(a){console.warn("Response "+a.message)}}}),e}is.call(fe.prototype);function H(r,e){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new x(e.headers),this.url=e.url||"",this._initBody(r)}is.call(H.prototype),H.prototype.clone=function(){return new H(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new x(this.headers),url:this.url})},H.error=function(){var r=new H(null,{status:200,statusText:""});return r.ok=!1,r.status=0,r.type="error",r};var Li=[301,302,303,307,308];H.redirect=function(r,e){if(Li.indexOf(e)===-1)throw new RangeError("Invalid status code");return new H(null,{status:e,headers:{location:r}})};var pe=R.DOMException;try{new pe}catch{pe=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},pe.prototype=Object.create(Error.prototype),pe.prototype.constructor=pe}function as(r,e){return new Promise(function(t,s){var o=new fe(r,e);if(o.signal&&o.signal.aborted)return s(new pe("Aborted","AbortError"));var n=new XMLHttpRequest;function i(){n.abort()}n.onload=function(){var c={statusText:n.statusText,headers:zi(n.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(n.status<200||n.status>599)?c.status=200:c.status=n.status,c.url="responseURL"in n?n.responseURL:c.headers.get("X-Request-URL");var l="response"in n?n.response:n.responseText;setTimeout(function(){t(new H(l,c))},0)},n.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},n.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},n.onabort=function(){setTimeout(function(){s(new pe("Aborted","AbortError"))},0)};function a(c){try{return c===""&&R.location.href?R.location.href:c}catch{return c}}if(n.open(o.method,a(o.url),!0),o.credentials==="include"?n.withCredentials=!0:o.credentials==="omit"&&(n.withCredentials=!1),"responseType"in n&&(O.blob?n.responseType="blob":O.arrayBuffer&&(n.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof x||R.Headers&&e.headers instanceof R.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){u.push(Pe(c)),n.setRequestHeader(c,Wt(e.headers[c]))}),o.headers.forEach(function(c,l){u.indexOf(l)===-1&&n.setRequestHeader(l,c)})}else o.headers.forEach(function(c,l){n.setRequestHeader(l,c)});o.signal&&(o.signal.addEventListener("abort",i),n.onreadystatechange=function(){n.readyState===4&&o.signal.removeEventListener("abort",i)}),n.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}as.polyfill=!0,R.fetch||(R.fetch=as,R.Headers=x,R.Request=fe,R.Response=H);var us=typeof global=="object"&&global&&global.Object===Object&&global,Wi=typeof self=="object"&&self&&self.Object===Object&&self,J=us||Wi||Function("return this")(),G=J.Symbol,cs=Object.prototype,Hi=cs.hasOwnProperty,Ji=cs.toString,Ne=G?G.toStringTag:void 0;function Zi(r){var e=Hi.call(r,Ne),t=r[Ne];try{r[Ne]=void 0;var s=!0}catch{}var o=Ji.call(r);return s&&(e?r[Ne]=t:delete r[Ne]),o}var Yi=Object.prototype,Xi=Yi.toString;function ea(r){return Xi.call(r)}var ta="[object Null]",ra="[object Undefined]",ls=G?G.toStringTag:void 0;function X(r){return r==null?r===void 0?ra:ta:ls&&ls in Object(r)?Zi(r):ea(r)}function K(r){return r!=null&&typeof r=="object"}var sa="[object Symbol]";function xe(r){return typeof r=="symbol"||K(r)&&X(r)==sa}function Ee(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,ds=G?G.prototype:void 0,fs=ds?ds.toString:void 0;function bt(r){if(typeof r=="string")return r;if(E(r))return Ee(r,bt)+"";if(xe(r))return fs?fs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var oa=/\s/;function na(r){for(var e=r.length;e--&&oa.test(r.charAt(e)););return e}var ia=/^\s+/;function aa(r){return r&&r.slice(0,na(r)+1).replace(ia,"")}function z(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ps=NaN,ua=/^[-+]0x[0-9a-f]+$/i,ca=/^0b[01]+$/i,la=/^0o[0-7]+$/i,da=parseInt;function fa(r){if(typeof r=="number")return r;if(xe(r))return ps;if(z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=aa(r);var t=ca.test(r);return t||la.test(r)?da(r.slice(2),t?2:8):ua.test(r)?ps:+r}var hs=1/0,pa=17976931348623157e292;function ha(r){if(!r)return r===0?r:0;if(r=fa(r),r===hs||r===-hs){var e=r<0?-1:1;return e*pa}return r===r?r:0}function kt(r){var e=ha(r),t=e%1;return e===e?t?e-t:e:0}function wt(r){return r}var ya="[object AsyncFunction]",ga="[object Function]",ma="[object GeneratorFunction]",va="[object Proxy]";function Zt(r){if(!z(r))return!1;var e=X(r);return e==ga||e==ma||e==ya||e==va}var Yt=J["__core-js_shared__"],ys=(function(){var r=/[^.]+$/.exec(Yt&&Yt.keys&&Yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ba(r){return!!ys&&ys in r}var ka=Function.prototype,wa=ka.toString;function he(r){if(r!=null){try{return wa.call(r)}catch{}try{return r+""}catch{}}return""}var Aa=/[\\^$.*+?()[\]{}|]/g,$a=/^\[object .+?Constructor\]$/,Ca=Function.prototype,Da=Object.prototype,_a=Ca.toString,Pa=Da.hasOwnProperty,xa=RegExp("^"+_a.call(Pa).replace(Aa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ea(r){if(!z(r)||ba(r))return!1;var e=Zt(r)?xa:$a;return e.test(he(r))}function ja(r,e){return r?.[e]}function ye(r,e){var t=ja(r,e);return Ea(t)?t:void 0}var Xt=ye(J,"WeakMap"),gs=Object.create,Sa=(function(){function r(){}return function(e){if(!z(e))return{};if(gs)return gs(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ma(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Ra=800,Ta=16,Ia=Date.now;function Oa(r){var e=0,t=0;return function(){var s=Ia(),o=Ta-(s-t);if(t=s,o>0){if(++e>=Ra)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Ka(r){return function(){return r}}var At=(function(){try{var r=ye(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Fa=At?function(r,e){return At(r,"toString",{configurable:!0,enumerable:!1,value:Ka(e),writable:!0})}:wt,qa=Oa(Fa);function Qa(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function ms(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Ba(r){return r!==r}function Va(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function vs(r,e,t){return e===e?Va(r,e,t):ms(r,Ba,t)}function Ga(r,e){var t=r==null?0:r.length;return!!t&&vs(r,e,0)>-1}var Ua=9007199254740991,Na=/^(?:0|[1-9]\d*)$/;function er(r,e){var t=typeof r;return e=e??Ua,!!e&&(t=="number"||t!="symbol"&&Na.test(r))&&r>-1&&r%1==0&&r<e}function $t(r,e,t){e=="__proto__"&&At?At(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function ze(r,e){return r===e||r!==r&&e!==e}var za=Object.prototype,La=za.hasOwnProperty;function bs(r,e,t){var s=r[e];(!(La.call(r,e)&&ze(s,t))||t===void 0&&!(e in r))&&$t(r,e,t)}var ks=Math.max;function Wa(r,e,t){return e=ks(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=ks(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Ma(r,this,a)}}function tr(r,e){return qa(Wa(r,e,wt),r+"")}var Ha=9007199254740991;function rr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ha}function ee(r){return r!=null&&rr(r.length)&&!Zt(r)}var Ja=Object.prototype;function sr(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ja;return r===t}function Za(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Ya="[object Arguments]";function ws(r){return K(r)&&X(r)==Ya}var As=Object.prototype,Xa=As.hasOwnProperty,eu=As.propertyIsEnumerable,Le=ws((function(){return arguments})())?ws:function(r){return K(r)&&Xa.call(r,"callee")&&!eu.call(r,"callee")};function tu(){return!1}var $s=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Cs=$s&&typeof module=="object"&&module&&!module.nodeType&&module,ru=Cs&&Cs.exports===$s,Ds=ru?J.Buffer:void 0,su=Ds?Ds.isBuffer:void 0,We=su||tu,ou="[object Arguments]",nu="[object Array]",iu="[object Boolean]",au="[object Date]",uu="[object Error]",cu="[object Function]",lu="[object Map]",du="[object Number]",fu="[object Object]",pu="[object RegExp]",hu="[object Set]",yu="[object String]",gu="[object WeakMap]",mu="[object ArrayBuffer]",vu="[object DataView]",bu="[object Float32Array]",ku="[object Float64Array]",wu="[object Int8Array]",Au="[object Int16Array]",$u="[object Int32Array]",Cu="[object Uint8Array]",Du="[object Uint8ClampedArray]",_u="[object Uint16Array]",Pu="[object Uint32Array]",C={};C[bu]=C[ku]=C[wu]=C[Au]=C[$u]=C[Cu]=C[Du]=C[_u]=C[Pu]=!0,C[ou]=C[nu]=C[mu]=C[iu]=C[vu]=C[au]=C[uu]=C[cu]=C[lu]=C[du]=C[fu]=C[pu]=C[hu]=C[yu]=C[gu]=!1;function xu(r){return K(r)&&rr(r.length)&&!!C[X(r)]}function He(r){return function(e){return r(e)}}var _s=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Je=_s&&typeof module=="object"&&module&&!module.nodeType&&module,Eu=Je&&Je.exports===_s,or=Eu&&us.process,je=(function(){try{var r=Je&&Je.require&&Je.require("util").types;return r||or&&or.binding&&or.binding("util")}catch{}})(),Ps=je&&je.isTypedArray,nr=Ps?He(Ps):xu,ju=Object.prototype,Su=ju.hasOwnProperty;function xs(r,e){var t=E(r),s=!t&&Le(r),o=!t&&!s&&We(r),n=!t&&!s&&!o&&nr(r),i=t||s||o||n,a=i?Za(r.length,String):[],u=a.length;for(var c in r)(e||Su.call(r,c))&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||er(c,u)))&&a.push(c);return a}function Es(r,e){return function(t){return r(e(t))}}var Mu=Es(Object.keys,Object),Ru=Object.prototype,Tu=Ru.hasOwnProperty;function js(r){if(!sr(r))return Mu(r);var e=[];for(var t in Object(r))Tu.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ze(r){return ee(r)?xs(r):js(r)}var Iu=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ou=/^\w*$/;function ir(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||xe(r)?!0:Ou.test(r)||!Iu.test(r)||e!=null&&r in Object(e)}var Ye=ye(Object,"create");function Ku(){this.__data__=Ye?Ye(null):{},this.size=0}function Fu(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var qu="__lodash_hash_undefined__",Qu=Object.prototype,Bu=Qu.hasOwnProperty;function Vu(r){var e=this.__data__;if(Ye){var t=e[r];return t===qu?void 0:t}return Bu.call(e,r)?e[r]:void 0}var Gu=Object.prototype,Uu=Gu.hasOwnProperty;function Nu(r){var e=this.__data__;return Ye?e[r]!==void 0:Uu.call(e,r)}var zu="__lodash_hash_undefined__";function Lu(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ye&&e===void 0?zu:e,this}function ge(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ge.prototype.clear=Ku,ge.prototype.delete=Fu,ge.prototype.get=Vu,ge.prototype.has=Nu,ge.prototype.set=Lu;function Wu(){this.__data__=[],this.size=0}function Ct(r,e){for(var t=r.length;t--;)if(ze(r[t][0],e))return t;return-1}var Hu=Array.prototype,Ju=Hu.splice;function Zu(r){var e=this.__data__,t=Ct(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Ju.call(e,t,1),--this.size,!0}function Yu(r){var e=this.__data__,t=Ct(e,r);return t<0?void 0:e[t][1]}function Xu(r){return Ct(this.__data__,r)>-1}function ec(r,e){var t=this.__data__,s=Ct(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function te(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}te.prototype.clear=Wu,te.prototype.delete=Zu,te.prototype.get=Yu,te.prototype.has=Xu,te.prototype.set=ec;var Xe=ye(J,"Map");function tc(){this.size=0,this.__data__={hash:new ge,map:new(Xe||te),string:new ge}}function rc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Dt(r,e){var t=r.__data__;return rc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function sc(r){var e=Dt(this,r).delete(r);return this.size-=e?1:0,e}function oc(r){return Dt(this,r).get(r)}function nc(r){return Dt(this,r).has(r)}function ic(r,e){var t=Dt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=tc,re.prototype.delete=sc,re.prototype.get=oc,re.prototype.has=nc,re.prototype.set=ic;var ac="Expected a function";function ar(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ac);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(ar.Cache||re),t}ar.Cache=re;var uc=500;function cc(r){var e=ar(r,function(s){return t.size===uc&&t.clear(),s}),t=e.cache;return e}var lc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,dc=/\\(\\)?/g,fc=cc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(lc,function(t,s,o,n){e.push(o?n.replace(dc,"$1"):s||t)}),e});function ur(r){return r==null?"":bt(r)}function Ss(r,e){return E(r)?r:ir(r,e)?[r]:fc(ur(r))}function _t(r){if(typeof r=="string"||xe(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function cr(r,e){e=Ss(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[_t(e[t++])];return t&&t==s?r:void 0}function et(r,e,t){var s=r==null?void 0:cr(r,e);return s===void 0?t:s}function Ms(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Rs=G?G.isConcatSpreadable:void 0;function pc(r){return E(r)||Le(r)||!!(Rs&&r&&r[Rs])}function Ts(r,e,t,s,o){var n=-1,i=r.length;for(t||(t=pc),o||(o=[]);++n<i;){var a=r[n];t(a)&&Ms(o,a)}return o}var Is=Es(Object.getPrototypeOf,Object),hc="\\ud800-\\udfff",yc="\\u0300-\\u036f",gc="\\ufe20-\\ufe2f",mc="\\u20d0-\\u20ff",vc=yc+gc+mc,bc="\\ufe0e\\ufe0f",kc="\\u200d",wc=RegExp("["+kc+hc+vc+bc+"]");function Ac(r){return wc.test(r)}function Os(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function $c(){this.__data__=new te,this.size=0}function Cc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Dc(r){return this.__data__.get(r)}function _c(r){return this.__data__.has(r)}var Pc=200;function xc(r,e){var t=this.__data__;if(t instanceof te){var s=t.__data__;if(!Xe||s.length<Pc-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new re(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new te(r);this.size=e.size}L.prototype.clear=$c,L.prototype.delete=Cc,L.prototype.get=Dc,L.prototype.has=_c,L.prototype.set=xc;var Ks=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Fs=Ks&&typeof module=="object"&&module&&!module.nodeType&&module,Ec=Fs&&Fs.exports===Ks,qs=Ec?J.Buffer:void 0,Qs=qs?qs.allocUnsafe:void 0;function Bs(r,e){if(e)return r.slice();var t=r.length,s=Qs?Qs(t):new r.constructor(t);return r.copy(s),s}function jc(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Sc(){return[]}var Mc=Object.prototype,Rc=Mc.propertyIsEnumerable,Vs=Object.getOwnPropertySymbols,Tc=Vs?function(r){return r==null?[]:(r=Object(r),jc(Vs(r),function(e){return Rc.call(r,e)}))}:Sc;function Ic(r,e,t){var s=e(r);return E(r)?s:Ms(s,t(r))}function lr(r){return Ic(r,Ze,Tc)}var dr=ye(J,"DataView"),fr=ye(J,"Promise"),pr=ye(J,"Set"),Gs="[object Map]",Oc="[object Object]",Us="[object Promise]",Ns="[object Set]",zs="[object WeakMap]",Ls="[object DataView]",Kc=he(dr),Fc=he(Xe),qc=he(fr),Qc=he(pr),Bc=he(Xt),U=X;(dr&&U(new dr(new ArrayBuffer(1)))!=Ls||Xe&&U(new Xe)!=Gs||fr&&U(fr.resolve())!=Us||pr&&U(new pr)!=Ns||Xt&&U(new Xt)!=zs)&&(U=function(r){var e=X(r),t=e==Oc?r.constructor:void 0,s=t?he(t):"";if(s)switch(s){case Kc:return Ls;case Fc:return Gs;case qc:return Us;case Qc:return Ns;case Bc:return zs}return e});var Vc=Object.prototype,Gc=Vc.hasOwnProperty;function Uc(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Gc.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Pt=J.Uint8Array;function hr(r){var e=new r.constructor(r.byteLength);return new Pt(e).set(new Pt(r)),e}function Nc(r,e){var t=hr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var zc=/\w*$/;function Lc(r){var e=new r.constructor(r.source,zc.exec(r));return e.lastIndex=r.lastIndex,e}var Ws=G?G.prototype:void 0,Hs=Ws?Ws.valueOf:void 0;function Wc(r){return Hs?Object(Hs.call(r)):{}}function Js(r,e){var t=e?hr(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var Hc="[object Boolean]",Jc="[object Date]",Zc="[object Map]",Yc="[object Number]",Xc="[object RegExp]",el="[object Set]",tl="[object String]",rl="[object Symbol]",sl="[object ArrayBuffer]",ol="[object DataView]",nl="[object Float32Array]",il="[object Float64Array]",al="[object Int8Array]",ul="[object Int16Array]",cl="[object Int32Array]",ll="[object Uint8Array]",dl="[object Uint8ClampedArray]",fl="[object Uint16Array]",pl="[object Uint32Array]";function hl(r,e,t){var s=r.constructor;switch(e){case sl:return hr(r);case Hc:case Jc:return new s(+r);case ol:return Nc(r);case nl:case il:case al:case ul:case cl:case ll:case dl:case fl:case pl:return Js(r,t);case Zc:return new s;case Yc:case tl:return new s(r);case Xc:return Lc(r);case el:return new s;case rl:return Wc(r)}}function Zs(r){return typeof r.constructor=="function"&&!sr(r)?Sa(Is(r)):{}}var yl="[object Map]";function gl(r){return K(r)&&U(r)==yl}var Ys=je&&je.isMap,ml=Ys?He(Ys):gl,vl="[object Set]";function bl(r){return K(r)&&U(r)==vl}var Xs=je&&je.isSet,kl=Xs?He(Xs):bl,wl=1,eo="[object Arguments]",Al="[object Array]",$l="[object Boolean]",Cl="[object Date]",Dl="[object Error]",to="[object Function]",_l="[object GeneratorFunction]",Pl="[object Map]",xl="[object Number]",ro="[object Object]",El="[object RegExp]",jl="[object Set]",Sl="[object String]",Ml="[object Symbol]",Rl="[object WeakMap]",Tl="[object ArrayBuffer]",Il="[object DataView]",Ol="[object Float32Array]",Kl="[object Float64Array]",Fl="[object Int8Array]",ql="[object Int16Array]",Ql="[object Int32Array]",Bl="[object Uint8Array]",Vl="[object Uint8ClampedArray]",Gl="[object Uint16Array]",Ul="[object Uint32Array]",w={};w[eo]=w[Al]=w[Tl]=w[Il]=w[$l]=w[Cl]=w[Ol]=w[Kl]=w[Fl]=w[ql]=w[Ql]=w[Pl]=w[xl]=w[ro]=w[El]=w[jl]=w[Sl]=w[Ml]=w[Bl]=w[Vl]=w[Gl]=w[Ul]=!0,w[Dl]=w[to]=w[Rl]=!1;function xt(r,e,t,s,o,n){var i,a=e&wl;if(i!==void 0)return i;if(!z(r))return r;var u=E(r);if(u)i=Uc(r);else{var c=U(r),l=c==to||c==_l;if(We(r))return Bs(r,a);if(c==ro||c==eo||l&&!o)i=l?{}:Zs(r);else{if(!w[c])return o?r:{};i=hl(r,c,a)}}n||(n=new L);var d=n.get(r);if(d)return d;n.set(r,i),kl(r)?r.forEach(function(p){i.add(xt(p,e,t,p,r,n))}):ml(r)&&r.forEach(function(p,y){i.set(y,xt(p,e,t,y,r,n))});var f=lr,h=u?void 0:f(r);return Qa(h||r,function(p,y){h&&(y=p,p=r[y]),bs(i,y,xt(p,e,t,y,r,n))}),i}var Nl=1,zl=4;function se(r){return xt(r,Nl|zl)}var Ll="__lodash_hash_undefined__";function Wl(r){return this.__data__.set(r,Ll),this}function Hl(r){return this.__data__.has(r)}function tt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new re;++e<t;)this.add(r[e])}tt.prototype.add=tt.prototype.push=Wl,tt.prototype.has=Hl;function Jl(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(e(r[t],t,r))return!0;return!1}function so(r,e){return r.has(e)}var Zl=1,Yl=2;function oo(r,e,t,s,o,n){var i=t&Zl,a=r.length,u=e.length;if(a!=u&&!(i&&u>a))return!1;var c=n.get(r),l=n.get(e);if(c&&l)return c==e&&l==r;var d=-1,f=!0,h=t&Yl?new tt:void 0;for(n.set(r,e),n.set(e,r);++d<a;){var p=r[d],y=e[d];if(s)var v=i?s(y,p,d,e,r,n):s(p,y,d,r,e,n);if(v!==void 0){if(v)continue;f=!1;break}if(h){if(!Jl(e,function(g,k){if(!so(h,k)&&(p===g||o(p,g,t,s,n)))return h.push(k)})){f=!1;break}}else if(!(p===y||o(p,y,t,s,n))){f=!1;break}}return n.delete(r),n.delete(e),f}function Xl(r){var e=-1,t=Array(r.size);return r.forEach(function(s,o){t[++e]=[o,s]}),t}function ed(r){var e=-1,t=Array(r.size);return r.forEach(function(s){t[++e]=s}),t}var td=1,rd=2,sd="[object Boolean]",od="[object Date]",nd="[object Error]",id="[object Map]",ad="[object Number]",ud="[object RegExp]",cd="[object Set]",ld="[object String]",dd="[object Symbol]",fd="[object ArrayBuffer]",pd="[object DataView]",no=G?G.prototype:void 0,yr=no?no.valueOf:void 0;function hd(r,e,t,s,o,n,i){switch(t){case pd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case fd:return!(r.byteLength!=e.byteLength||!n(new Pt(r),new Pt(e)));case sd:case od:case ad:return ze(+r,+e);case nd:return r.name==e.name&&r.message==e.message;case ud:case ld:return r==e+"";case id:var a=Xl;case cd:var u=s&td;if(a||(a=ed),r.size!=e.size&&!u)return!1;var c=i.get(r);if(c)return c==e;s|=rd,i.set(r,e);var l=oo(a(r),a(e),s,o,n,i);return i.delete(r),l;case dd:if(yr)return yr.call(r)==yr.call(e)}return!1}var yd=1,gd=Object.prototype,md=gd.hasOwnProperty;function vd(r,e,t,s,o,n){var i=t&yd,a=lr(r),u=a.length,c=lr(e),l=c.length;if(u!=l&&!i)return!1;for(var d=u;d--;){var f=a[d];if(!(i?f in e:md.call(e,f)))return!1}var h=n.get(r),p=n.get(e);if(h&&p)return h==e&&p==r;var y=!0;n.set(r,e),n.set(e,r);for(var v=i;++d<u;){f=a[d];var g=r[f],k=e[f];if(s)var m=i?s(k,g,f,e,r,n):s(g,k,f,r,e,n);if(!(m===void 0?g===k||o(g,k,t,s,n):m)){y=!1;break}v||(v=f=="constructor")}if(y&&!v){var M=r.constructor,N=e.constructor;M!=N&&"constructor"in r&&"constructor"in e&&!(typeof M=="function"&&M instanceof M&&typeof N=="function"&&N instanceof N)&&(y=!1)}return n.delete(r),n.delete(e),y}var bd=1,io="[object Arguments]",ao="[object Array]",Et="[object Object]",kd=Object.prototype,uo=kd.hasOwnProperty;function wd(r,e,t,s,o,n){var i=E(r),a=E(e),u=i?ao:U(r),c=a?ao:U(e);u=u==io?Et:u,c=c==io?Et:c;var l=u==Et,d=c==Et,f=u==c;if(f&&We(r)){if(!We(e))return!1;i=!0,l=!1}if(f&&!l)return n||(n=new L),i||nr(r)?oo(r,e,t,s,o,n):hd(r,e,u,t,s,o,n);if(!(t&bd)){var h=l&&uo.call(r,"__wrapped__"),p=d&&uo.call(e,"__wrapped__");if(h||p){var y=h?r.value():r,v=p?e.value():e;return n||(n=new L),o(y,v,t,s,n)}}return f?(n||(n=new L),vd(r,e,t,s,o,n)):!1}function rt(r,e,t,s,o){return r===e?!0:r==null||e==null||!K(r)&&!K(e)?r!==r&&e!==e:wd(r,e,t,s,rt,o)}var Ad=1,$d=2;function co(r,e,t,s){var o=t.length,n=o;if(r==null)return!n;for(r=Object(r);o--;){var i=t[o];if(i[2]?i[1]!==r[i[0]]:!(i[0]in r))return!1}for(;++o<n;){i=t[o];var a=i[0],u=r[a],c=i[1];if(i[2]){if(u===void 0&&!(a in r))return!1}else{var l=new L,d;if(!(d===void 0?rt(c,u,Ad|$d,s,l):d))return!1}}return!0}function lo(r){return r===r&&!z(r)}function fo(r){for(var e=Ze(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,lo(o)]}return e}function po(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Cd(r){var e=fo(r);return e.length==1&&e[0][2]?po(e[0][0],e[0][1]):function(t){return t===r||co(t,r,e)}}function Dd(r,e){return r!=null&&e in Object(r)}function _d(r,e,t){e=Ss(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=_t(e[s]);if(!(n=r!=null&&t(r,i)))break;r=r[i]}return n||++s!=o?n:(o=r==null?0:r.length,!!o&&rr(o)&&er(i,o)&&(E(r)||Le(r)))}function Pd(r,e){return r!=null&&_d(r,e,Dd)}var xd=1,Ed=2;function jd(r,e){return ir(r)&&lo(e)?po(_t(r),e):function(t){var s=et(t,r);return s===void 0&&s===e?Pd(t,r):rt(e,s,xd|Ed)}}function ho(r){return function(e){return e?.[r]}}function Sd(r){return function(e){return cr(e,r)}}function Md(r){return ir(r)?ho(_t(r)):Sd(r)}function Se(r){return typeof r=="function"?r:r==null?wt:typeof r=="object"?E(r)?jd(r[0],r[1]):Cd(r):Md(r)}function Rd(r){return function(e,t,s){for(var o=-1,n=Object(e),i=s(e),a=i.length;a--;){var u=i[++o];if(t(n[u],u,n)===!1)break}return e}}var yo=Rd();function Td(r,e){return r&&yo(r,e,Ze)}function Id(r,e){return function(t,s){if(t==null)return t;if(!ee(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var gr=Id(Td);function Me(r){return K(r)&&ee(r)}var Od=200;function go(r,e,t,s){var o=-1,n=Ga,i=!0,a=r.length,u=[],c=e.length;if(!a)return u;t&&(e=Ee(e,He(t))),e.length>=Od&&(n=so,i=!1,e=new tt(e));e:for(;++o<a;){var l=r[o],d=t==null?l:t(l);if(l=l!==0?l:0,i&&d===d){for(var f=c;f--;)if(e[f]===d)continue e;u.push(l)}else n(e,d,s)||u.push(l)}return u}function Kd(r){var e=r==null?0:r.length;return e?r[e-1]:void 0}var mo=tr(function(r,e){var t=Kd(e);return Me(t)&&(t=void 0),Me(r)?go(r,Ts(e,1,Me),Se(t)):[]});function vo(r,e,t){r=ur(r),e=bt(e);var s=r.length;t=t===void 0?s:Os(kt(t),0,s);var o=t;return t-=e.length,t>=0&&r.slice(t,o)==e}function Fd(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(!e(r[t],t,r))return!1;return!0}function qd(r,e){var t=!0;return gr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function bo(r,e,t){var s=E(r)?Fd:qd;return s(r,Se(e))}function Qd(r){return function(e,t,s){var o=Object(e);if(!ee(e)){var n=Se(t);e=Ze(e),t=function(a){return n(o[a],a,o)}}var i=r(e,t,s);return i>-1?o[n?e[i]:i]:void 0}}var Bd=Math.max;function mr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:kt(t);return o<0&&(o=Bd(s+o,0)),ms(r,Se(e),o)}var Vd=Qd(mr);function Gd(r,e){var t=-1,s=ee(r)?Array(r.length):[];return gr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var Ud="[object String]";function jt(r){return typeof r=="string"||!E(r)&&K(r)&&X(r)==Ud}function ko(r,e){return rt(r,e)}function St(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?rt(r,e,void 0,t):!!s}function Nd(r,e){return r===e||co(r,e,fo(e))}function zd(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Ld(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=xe(r),i=e!==void 0,a=e===null,u=e===e,c=xe(e);if(!a&&!c&&!n&&r>e||n&&i&&u&&!a&&!c||s&&i&&u||!t&&u||!o)return 1;if(!s&&!n&&!c&&r<e||c&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!u)return-1}return 0}function Wd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var u=Ld(o[s],n[s]);if(u){if(s>=a)return u;var c=t[s];return u*(c=="desc"?-1:1)}}return r.index-e.index}function Hd(r,e,t){e.length?e=Ee(e,function(n){return E(n)?function(i){return cr(i,n.length===1?n[0]:n)}:n}):e=[wt];var s=-1;e=Ee(e,He(Se));var o=Gd(r,function(n,i,a){var u=Ee(e,function(c){return c(n)});return{criteria:u,index:++s,value:n}});return zd(o,function(n,i){return Wd(n,i,t)})}function wo(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Hd(r,e,t))}var Jd=ho("length"),Ao="\\ud800-\\udfff",Zd="\\u0300-\\u036f",Yd="\\ufe20-\\ufe2f",Xd="\\u20d0-\\u20ff",ef=Zd+Yd+Xd,tf="\\ufe0e\\ufe0f",rf="["+Ao+"]",vr="["+ef+"]",br="\\ud83c[\\udffb-\\udfff]",sf="(?:"+vr+"|"+br+")",$o="[^"+Ao+"]",Co="(?:\\ud83c[\\udde6-\\uddff]){2}",Do="[\\ud800-\\udbff][\\udc00-\\udfff]",of="\\u200d",_o=sf+"?",Po="["+tf+"]?",nf="(?:"+of+"(?:"+[$o,Co,Do].join("|")+")"+Po+_o+")*",af=Po+_o+nf,uf="(?:"+[$o+vr+"?",vr,Co,Do,rf].join("|")+")",xo=RegExp(br+"(?="+br+")|"+uf+af,"g");function cf(r){for(var e=xo.lastIndex=0;xo.test(r);)++e;return e}function lf(r){return Ac(r)?cf(r):Jd(r)}var df="[object Map]",ff="[object Set]";function pf(r){if(r==null)return 0;if(ee(r))return jt(r)?lf(r):r.length;var e=U(r);return e==df||e==ff?r.size:js(r).length}function hf(r,e,t){return r=ur(r),t=t==null?0:Os(kt(t),0,r.length),e=bt(e),r.slice(t,t+e.length)==e}function kr(r){const e=wr(r);return yf(e)}function wr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(wr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+wr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function yf(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const me={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}};class gf{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s={name:e.name,type:"mark",value:me.now(),createdAt:Date.now()};return this.data.set(t,s),s}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s=this.data.get(this.getKey(e.start,e.context)),o=this.data.get(this.getKey(e.end,e.context));if(!s||!o)return;const n=o.value-s.value,i=Math.round(n*100)/100,a=this.data.get(t);if(a&&e.sum){const c=a.value+i,l={...a,value:c};return this.data.set(t,l),l}const u={name:e.name,type:"measure",value:i,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),s=this.data.get(t);if(s){const o={...s,...e.value};this.data.set(t,o)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:me.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const s=kr(t);return e+"_"+s}}let Eo=class Oi{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const u=o(a);if(u)return u}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const u=this.edges.get(a);if(u)for(let c of u)i(c);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const u=this.edges.get(a);if(u)for(const c of u)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&o.push(c)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(u=>i.has(this.nodeKinds.get(u))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=c=>!s||s.length===0||s.includes(this.nodeKinds.get(c)??void 0),i=()=>{const c=new Set,l=Array.from(o);for(;l.length;){const d=l.shift();for(const[f,h]of this.edges)h.has(d)&&!c.has(f)&&(c.add(f),l.push(f))}return c},a=()=>{const c=new Set,l=Array.from(o);for(;l.length;){const d=l.shift(),f=this.edges.get(d);if(f)for(const h of f)c.has(h)||(c.add(h),l.push(h))}return c};let u;return t==="both"?u=new Set([...i(),...a()]):t==="upstream"?u=a():u=i(),Array.from(u).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Oi;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),u=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),c=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),l=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&l.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:u,removedEdges:c,kindChanges:l}}};class mf{graph;nodeIndex;constructor(){this.graph=new Eo,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const u=t.get(n);u.has(a)||u.set(a,new Set),u.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const u=t(a,new Set(o));i=Math.max(i,u)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,attributeKey:n})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const jo={silent:0,error:1,warn:2,info:3,debug:4};let vf=class I{config;static globalConfig={};constructor(e={}){this.config={level:e.level??I.globalConfig.level??this.getDefaultLevel(),format:e.format??I.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??I.globalConfig.onLog,onTrackError:e.onTrackError??I.globalConfig.onTrackError}}static setGlobalConfig(e){I.globalConfig={...I.globalConfig,...e}}static getGlobalConfig(){return{...I.globalConfig}}static setModuleLevel(e,t){I.globalConfig.onLog||(I.globalConfig.onLog=void 0),I._moduleOverrides||(I._moduleOverrides=new Map),I._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!I._moduleOverrides))return I._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=I.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return jo[e]<=jo[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new I(t)}configure(e){Object.assign(this.config,e)}};const Re=new vf;class So{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=Re.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const u=o.modelAttributes.get(i);for(const c of a)if(u.has(c)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return se(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=kr(t);return e+"_"+s}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class Ar{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=me.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const Mo=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):se(r):r,Ro=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Mo(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=me.now(),c=u-s,l=Math.round(c*1e3)/1e3;t.duration=l,t.start=s,t.end=u;const d={duration:t.duration};return t.modelKey&&(d.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(d.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},b=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=me.now(),a=this.cdRef,u=Mo(r,!0);u.key||(a.increaseCounter(),u.key=a.getCounter());const c=W();a.analyticsController.mark({name:`${u.type}:start`,context:c});const l=this.model?.key;!u.originCdRefKey&&a.key&&(u.originCdRefKey=a.key),l&&(u.modelKey=l);const d=o.apply(this,n);return u.method=t,u.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Ro(this,a,u,i,c,f)):Ro(this,a,u,i,c,d)},s};function bf(r,e,t,s){t.max||(t.max=20);const o=[],n=t.transform?s.transformValue(t.value,t.transform):t.value;for(const[i,a]of e.entries()){const u=Array.from(a).some(l=>r.has(l)),c=t.transform?s.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(u&&(n===""||n==="//")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}else if(u&&typeof n=="string"&&n.startsWith("/")&&n.endsWith("/")){if(s.queryFind(c,n,"some")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}}else if(u&&typeof n=="string"){const l=String(c??""),d=n;if(l.toLowerCase().startsWith(d.toLowerCase())){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(f)}}else if(u&&s.queryFind(c,n,"some")){const l={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(l)}if(o.length===t.max)break}}return o}function kf(r){return r instanceof Date}function To(r){return r instanceof Date&&!isNaN(r.getTime())}const wf={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function Af(r){let e="^";const t=[];let s=r;const o=Object.entries(wf).sort((n,i)=>i[0].length-n[0].length);for(;s.length>0;){let n=!1;for(const[i,a]of o)if(s.startsWith(i)){e+=a.regex,t.push({type:a.type,pattern:i}),s=s.slice(i.length),n=!0;break}if(!n){const i=s[0];if(!i)break;e+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=s.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function $f(r,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let s=0;s<e.length;s++){const o=r[s+1];if(!o)continue;const n=parseInt(o,10),i=e[s];i&&(i.type==="year"&&i.pattern==="yy"?t.year=2e3+n:t[i.type]=n)}return t}function Cf(r){if(r.month<1||r.month>12)return new Date(NaN);if(r.day<1||r.day>31)return new Date(NaN);if(r.hour<0||r.hour>23)return new Date(NaN);if(r.minute<0||r.minute>59)return new Date(NaN);if(r.second<0||r.second>59)return new Date(NaN);if(r.millisecond<0||r.millisecond>999)return new Date(NaN);const e=new Date(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return To(e)?e.getFullYear()!==r.year||e.getMonth()!==r.month-1||e.getDate()!==r.day?new Date(NaN):e:new Date(NaN)}function Df(r,e,t){if(r=r.trim(),e==="t"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:s,tokenOrder:o}=Af(e),n=r.match(s);if(!n)return new Date(NaN);const i=$f(n,o);return Cf(i)}class _f{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const s=this.accessOrder.shift();s!==void 0&&this.cache.delete(s)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class Pf{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,s=new Set,o=n=>{t.add(n),s.add(n);const i=this.graph.get(n);if(i){for(const a of i)if(t.has(a)){if(s.has(a))return!0}else if(o(a))return!0}return s.delete(n),!1};for(let n=0;n<e.length-1;n++){const i=e[n],a=e[n+1];i&&a&&this.addDependency(i,a)}for(const n of e)if(!t.has(n)&&o(n))return!0;return!1}clear(){this.graph.clear()}}class xf{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new _f(e),this.circularRefDetector=new Pf}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,s;const o=e.includes("."),n=e.includes("["),i=o||n;if(i)if(s=e.split(/[.[]/)[0],n){const u=e.indexOf("]");if(u>-1){const c=e.indexOf(".",u+1);c>-1?t=e.substring(c+1):t=void 0}else o&&(t=e.substring(e.indexOf(".")+1))}else o&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:i};return s&&(a.reference=s),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const s=[];if(!e||e.trim().length===0)return s.push("Attribute path cannot be empty"),{valid:!1,errors:s};(e.startsWith(".")||e.endsWith("."))&&s.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&s.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const o=(e.match(/\[/g)||[]).length,n=(e.match(/]/g)||[]).length;o!==n&&s.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&s.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const i=/\[([^\]]+)\]/g;let a;for(;(a=i.exec(e))!==null;){const l=a[1];l&&l!=="*"&&!/^\d+$/.test(l)&&s.push(`Invalid bracket content: Must be a number or '*', got '${l}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&s.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&s.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:s.length===0,errors:s.length>0?s:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,s=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:s}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(t=>t.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const P=new xf;function ve(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),u=i?et(r,i):r;if(!Array.isArray(u))return[];const c=[];for(const l of u)!a||a===""?l!==void 0&&c.push(l):a.startsWith(".")&&c.push(...ve(l,a.slice(1)));return c}const t=e.split(".");let s=[r];for(const n of t){const i=[];for(const a of s)if(a!=null)if(Array.isArray(a))for(const u of a){if(u==null)continue;const c=u[n];c!==void 0&&i.push(c)}else{const u=a[n];u!==void 0&&i.push(u)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function $r(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function Io(r,e,t){return(r*t+e*t)/t}function Ef(r,e,t){return r*t/(e*t)}const st=(r,e,t,s)=>{if(!s)throw new Error("Attribute not found");const o={attribute:s,types:r.types};let n;(o.types.includes("sum")||o.types.includes("avg"))&&(n=Rf(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Sf(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=jf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Tf(r,e,t):a==="group"&&(o.group=Mf(r,e))}),o},jf=(r,e)=>{const t=P.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=ve(o,r).filter(n=>n!=null).length;else{const n=o[r];if(n==null)continue;Array.isArray(n)?s+=n.filter(i=>i!=null).length:s++}return s},Sf=(r,e)=>{let t,s;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ve(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a.filter(u=>u!==void 0):i=[a]}for(const a of i)a==null||typeof a=="object"||((t===void 0||a<t)&&(t=a),(s===void 0||a>s)&&(s=a))}if(!(t===void 0||s===void 0))return[t,s]},Mf=(r,e)=>{const t=[];r.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const s={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=P.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=ve(n,r.attribute):i=[n[r.attribute]];let a=!1;for(const u of i)for(const c of t)(typeof c.option.value<"u"&&c.option.value.includes(u)||typeof c.option.from<"u"&&c.option.from<u&&typeof c.option.to<"u"&&c.option.to>u)&&(c.keys.includes(n.key)||(c.count++,c.keys.push(n.key)),a=!0);!a&&r?.groupOptions?.calculateNotFound&&(s.count++,s.keys.push(n.key))}return r?.groupOptions?.calculateNotFound&&t.push(s),t},Rf=(r,e)=>{let t=0,s=0;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ve(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a:i=[a]}for(const a of i)if(Array.isArray(a))for(const u of a)typeof u=="number"&&(t=Io(t,u,$r([t,u])),s++);else typeof a=="number"&&(t=Io(t,a,$r([t,a])),s++)}return s===0?void 0:{average:Ef(t,s,$r([t,s])),count:s,sum:t}},Tf=(r,e,t)=>{const s=[];for(const[o,n]of t)if(!(r.excludeUndefineds&&typeof o>"u")&&Array.from(n).find(i=>e.has(i))){const i={value:o,count:n.size};if(r.distinctOptions?.skipKeys||(i.keys=Array.from(n)),s.push(i),r.distinctOptions?.limit&&s.length>=r.distinctOptions.limit)break}return s};let ot=class extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}},be=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=se(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||P}init(e){this._initOptions=se(e),this.currentQuery=se(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=se(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return se(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(s=>this.isQuery(s)&&s.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:bo(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.groupKey);if(o>-1){const n=s.queries[o];e.groupType&&(n.groupType=e.groupType),t?.mode==="set"?s.queries[o]=e:n.queries=[...n.queries,...e.queries]}else s.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return s}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.attribute);if(s>-1){const o=t.queries[s],n=mr(o.queries,e);n>-1&&o.queries.splice(n,1),o.queries.length===0&&t.queries.splice(s,1)}}else if(this.isQueryGroup(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(s>-1)if(!e.queries)t.queries.splice(s,1);else{const o=t.queries[s];for(const n of e.queries){const i=mr(o.queries,n);i>-1&&o.queries.splice(i,1)}o.queries.length===0&&t.queries.splice(s,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new ot("Missing attribute",e)),e.operator||t.push(new ot("Missing operator",e)),typeof e.value>"u"&&t.push(new ot("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new ot("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const s=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return s.length>0?{valid:!1,errors:s}:{valid:!0}}return t.push(new ot("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(e=>e.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const Cr=new be;function If(r,e,t,s,o,n,i){const a=Cr.removeQuery({groupKey:o},se(s)),u=i.queryData(r,a,!1,n),c=e?[...e.keys()]:[],l=new Set(c),d=n.get(o);if(!t.excludeUnresolved)for(const h of d.keys())l.add(h);if(t.excludeUndefineds?l.delete(void 0):l.add(void 0),t.sort){const h=[];for(const y of l.values())h.push(Oo(y,d,u,e,o,s,!0));const p=t.excludeZeros?h.filter(y=>y.size>0):h;return p.sort(Of(t.sort)),t.count?p.slice(0,t.count):p}const f=[];for(const h of l.values()){const p=Oo(h,d,u,e,o,s,!!t?.calculateFacets);if(!(t?.excludeZeros&&p.size===0)){if(t?.count&&f.length===t?.count)return f;f.push(p)}}return f}function Oo(r,e,t,s,o,n,i){const a=new Map,u=e.get(r)||new Set;for(const c of u){const l=t.get(c);if(l&&(a.set(c,l),!i))break}return{key:String(r),value:r,selected:Kf(o,r,n),enabled:a.size>0,size:a.size,entry:s.get(r),resultKeys:Array.from(a.keys())}}function Mt(r,e){if(r===void 0&&e===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;const t=typeof r,s=typeof e;if(t!==s)return t<s?-1:1;if(t==="number")return r-e;if(t==="string")return r.localeCompare(e);const o=String(r),n=String(e);return o<n?-1:o>n?1:0}function Of(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||Mt(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||Mt(e.value,t.value);case"value-asc":return(e,t)=>Mt(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-Mt(e.value,t.value)}}const Kf=(r,e,t)=>{const s=t.queries.findIndex(o=>Cr.isQueryGroup(o)&&o.groupKey===r);return s>-1?!!t.queries[s].queries.find(o=>{if(Cr.isQuery(o)){const n=o.value?.key||o.value;return o.attribute===r&&n===e}return!1}):!1};class Rt{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const u of n)this.fillInverseIndex(e,t,[u]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=P.parse(e).isDeepQuery??!1;this.indexMetadata.set(o,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:s,type:a?"deep":"shallow"})}if(!n){this.reset(o),this.indexMap.set(o,new Map);const a=P.parse(e).isDeepQuery;for(const u of t.values()){let c;a?(c=ve(u,e),c.length===0&&(c=[void 0])):c=[u[e]],this.fillInverseIndex(o,u.key,c),this.fillDataMap(o,c)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+kr(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const u of n)this.removeFromInverseIndex(e,t,[u]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return P.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const s of this.indexMap.keys())this.isDeepQueryIndex(s)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let s=0;for(const[o,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(o),s++);return s}getStats(){const e=this.getIndexCount(),t=Date.now();let s=0,o=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;s+=a,a>o&&(o=a)}const n=this.indexMetadata.size>0?s/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:o,avgAge:n}}}const Te="__";function Dr(r,e,t={key:"root"},s="root",o=new Rt,n){const i=n||r;for(const a of e.columns)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Ff(r,e.rows[0],e,o,s,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=Ko(r,e.columns[0],e,o,s,n);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],s==="root"&&e.options?.calculateTotals===!1)continue;const u=st(a,r,o.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function Ff(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const l={key:u,value:u},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(l.values=l.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=st(f,d,s.getIndex(f.attribute),f.attribute);l.values.push(h)}if(i.rows=i.rows||[],i.rows.push(l),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};Dr(d,f,l,o+Te+e.attribute+Te+u,s,n)}else if(t.columns)for(const f of t.columns){l.columns=l.columns||[];const h=Ko(d,f,t,s,o+Te+e.attribute+Te+u,n);l.columns.push(h)}}}return i}function Ko(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[u,c]of a.entries()){const l={key:u,value:u},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(l.values=l.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=st(f,d,s.getIndex(f.attribute),f.attribute);l.values.push(h)}if(i.columns=i.columns||[],i.columns.push(l),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};Dr(d,f,l,o+Te+e.attribute+Te+u,s,n)}}}return i}const qf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Qf=/^-?\d+$/,Bf=/^-?\d+\.\d+$/,Vf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Gf=r=>r==="true"||r==="false"?"boolean":Qf.test(r)?"int":Bf.test(r)?"float":qf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",Uf=r=>Vf.test(r),Nf=r=>r==null||r==="",zf=r=>{const e=[...r];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},Lf=(r,e={})=>{const t=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,o=new Map,n=[],i=Math.min(r.length,t);for(let c=0;c<i;c++){const l=r[c];if(l)for(const[d,f]of Object.entries(l)){let h=o.get(d);if(h||(h={observed:new Set,empty:0,scanned:0},o.set(d,h),n.push(d)),h.scanned++,Nf(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Gf(f),p==="string"&&!h.hint&&Uf(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=Wf(f),h.observed.add(p)}}const a=[],u=[];for(const c of n){const l=o.get(c),{type:d,conflict:f}=zf(l.observed.size?l.observed:new Set(["string"]));a.push({key:c,type:d}),u.push({column:c,inferredType:d,observedTypes:[...l.observed].sort(),emptyRate:l.scanned===0?0:l.empty/l.scanned,conflict:f,hint:l.hint})}return{properties:a,diagnostics:u}},Fo=(r,e=!1)=>Lf(r,typeof e=="boolean"?{deep:e}:e).properties,qo=r=>Number(r)===r&&r%1===0,Qo=r=>Number(r)===r&&r%1!==0,Wf=r=>{switch(typeof r){case"string":return"string";case"number":return qo(r)?"int":Qo(r)?"float":"any";case"boolean":return"boolean";case"object":return kf(r)?"date":"json";default:return"any"}};class Hf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}registeredCustomOperator=new Map;queryBuilder=new be;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s,o=e.value;const n=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(o=this.transformValue(o,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?s=et(t,e.attribute):s=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),(typeof s>"u"||s===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!ko(s,o):ko(s,o);case"find":return e.options?.invert?!this.queryFind(s,o,n):this.queryFind(s,o,n);case"lt":return Array.isArray(s)?n==="some"?s.some(i=>i<o):s.every(i=>i<o):s<o;case"gt":return Array.isArray(s)?n==="some"?s.some(i=>i>o):s.every(i=>i>o):s>o;case"lte":return Array.isArray(s)?n==="some"?s.some(i=>i<=o):s.every(i=>i<=o):s<=o;case"gte":return Array.isArray(s)?n==="some"?s.some(i=>i>=o):s.every(i=>i>=o):s>=o;case"typeof":return e.options?.invert?typeof s!==o:Array.isArray(s)?n==="some"?s.some(i=>typeof i===o):s.every(i=>typeof i===o):typeof s===o;case"isTruthy":return o===!0?Array.isArray(s)?n==="some"?s.some(i=>typeof!!i):s.every(i=>typeof!!i):!!s:!s;case"size":return typeof s=="string"?s.length===o:pf(s)===o;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const i=this.registeredCustomOperator.get(e.operator);if(typeof i=="function")return i(e,t)}}return!1}evaluateEqOperator(e,t,s,o){const n=new Map,i=o.get(t.attribute);if(i){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=i.get(a);if(u)if(u.forEach(c=>{s.has(c)&&n.set(c,s.get(c))}),t.options?.invert){const c=mo(Array.from(s.values()),Array.from(n.values()),"key"),l=new Map;return c.forEach(d=>{l.set(d.key,d)}),l}else return n}}for(let[a,u]of s){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(l=>l.isDeepQuery)){const l=this.queryBuilder.getProjectionForAttributeEntries(c.filter(d=>d.isDeepQuery));u=this.globalItemService.getProjectedData(l,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&n.set(a,u)}return n}equalRegexFn(e,t){if(typeof t=="string"&&hf(t,"/")&&vo(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(s=>St(s,t,this.equalRegexFn)):typeof t=="object"?Nd(e,t):e===t}queryFind(e,t,s){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?s==="some"?e.some(o=>St(o,t,this.equalRegexFn)):e.every(o=>St(o,t,this.equalRegexFn)):!!Vd(e,t):St(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return bo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let u of s.values()){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(c.filter(h=>h.isDeepQuery));u=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),u)}const l=this.handleArrayStarQuery(t,u);let d=!1;for(const f of l.queries){const h={...f,options:{...f.options,invert:!1}};if(this.evaluateQuery(h,u)){d=!0;break}}d&&(a.add(u.key),i||n.set(u.key,u))}if(i)for(const[u,c]of s)a.has(u)||n.set(u,c)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,s,o);for(let[i,a]of s){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(l=>l.isDeepQuery));a=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&n.set(i,a)}}return n}handleArrayStarQuery(e,t){const s=e.attribute.indexOf("[*]"),o={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(s!==-1){const n=e.attribute.substring(0,s),i=n.includes(".")?et(t,n):t[n];if(Array.isArray(i))for(let a=0;a<i.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);o.queries.push({attribute:u,operator:e.operator,value:e.value,options:e.options})}}return o}evaluateQueryGroup(e,t,s,o,n){let i=new Map,a=s;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,n):c=this.evaluateQueryGroup(e,u,a,o,n),i.size===0&&(i=c),t.groupType==="or")c.forEach(l=>{i.set(l.key,l)});else{const l=mo(Array.from(i.values()),Array.from(c.values()),"key");for(const d of l)i.delete(d.key)}t.groupType==="and"?a=i:a=s}return i}queryData(e,t,s,o){const n=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,s,o))}}class Jf{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
3
3
  "use strict";
4
4
  ${e}
5
- `}executeScript(e,t,s){if(!this.getScript(e))throw new Error(`Script ${e} not found`);s.context||(s.context=s.options||{});const o=Object.keys(s),n=Object.values(s);return this.getScriptAsFn(e,o)(t,...n)}}const Rt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>Xe(e,s.trim(),""))):"",Dr=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};var Vf=er(function(r,e){return je(r)?fo(r,js(e,1,je)):[]});let Gf=class{constructor(e,t,s,o,n){this.modelParser=e,this.cdRef=t,this.item=s,this.indicesController=o,this.queryManager=n,this.cacheCtrl=new Po(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}initialData;filteredData;model;filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new me,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=P.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches()}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&P.parse(o.attribute).isDeepQuery&&t.add(o.attribute);return Array.from(t)}getProjectionForQuery(e){const t=this.getDeepQueryAttributes(e);if(t.length===0)return null;const s=t.map(o=>P.parse(o));return this.queryBuilder.getProjectionForAttributeEntries(s)}getProjectionCacheKey(e){const t=this.getDeepQueryAttributes(e);return t.length===0?"":t.sort().join("|")}getProjectedData(e,t,s){if(s&&this.projectionCache.has(s))return this.projectionCache.get(s);const o=new Map;for(const[n,i]of e){const a=this.item.getProjectedData(t,this.model,i);o.set(n,a)}return s&&this.projectionCache.set(s,o),o}initFilterItems(e){[...this.model.properties.values(),...this.model.references.values()].forEach(t=>{t.filter&&(Array.isArray(e?.filterKeys)?e?.filterKeys.includes(t.key)&&this.updateFilterItem(t.key,e):this.updateFilterItem(t.key,e))})}getAggregate(e,t,s){if(P.parse(e.attribute).isDeepQuery)return tt(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return tt(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=P.parse(e.attribute),o=s.isDeepQuery;let n;if(!o&&(n=this.model.getAttribute(e.attribute),!n))throw new Error("Attribute not found");let i=new Map,a;!o&&n&&(n.type==="singleValued"||n.type==="multiValued")&&(a=this.modelParser.models.get(n.model));const u={},c=this.getSortingProjectionForModel(e,this.model);u.sort=c;let l=this.item.getItemsAsMap(this.filteredData,this.model,u);if(o){const p=this.queryBuilder.getProjectionForAttributeEntries([s]),y=new Map;for(const[v,g]of l){const k=this.item.getProjectedData(p,this.model,g);y.set(v,k)}l=y}const d=this.indicesController.getOrCreateIndex(`${e.attribute}`,l,{childLevelSorting:c,query:this.queryBuilder.getQuery()}),f=this.getAggregate({attribute:e.attribute,types:["distinct"],excludeUndefineds:!0},l,d);if(f.distinct)for(const p of f.distinct){let y={key:p.value,value:p.value};const v=p.keys.filter(k=>l.has(k));if(a){const k=a.data.get(p.value);k&&(y=k)}const g={...y,key:p.value,_items:[],_aggregates:[],_meta:{size:v.length}};i.set(p.value,g)}const h={count:e.count,start:e.start,projection:e.projection};if(a){const p=this.getSortingProjectionForModel(e,a);h.sort=p}if(t._meta.currentSize=i.size,t._meta.initialSize=f.distinct.length,i=this.item.getItemsAsMap(i,a,h),Array.isArray(e?.aggregates)&&i.forEach(p=>{const y=f.distinct.find(g=>g.value===p.key),v=this.getDataByKeys(l,y.keys);p._aggregates=e.aggregates.map(g=>this.getAggregate(g,v,d))}),e?.items){const p=e.items?.find(y=>y.key==="*");p?i.forEach(y=>{const v=f.distinct.find(m=>m.value===y.key),g=this.getDataByKeys(l,v.keys),k=this.item.getItems(g,this.model,p);y._items=k}):i.forEach(y=>{const v=e.items?.find(g=>g.key===y.key);if(v){const g=f.distinct.find(M=>M.value===y.key),k=this.getDataByKeys(l,g.keys),m=this.item.getItems(k,this.model,v);y._items=m}})}return t.items=Array.from(i.values()),t}getSortingProjectionForModel(e,t){const s={attributes:[],order:[]};return e?.sort?.attributes.forEach((o,n)=>{if(t.properties.has(o)){s.attributes.push(o);const i=e.sort?.order;s.order.push(i[n])}}),s}getReferenceKeyForFilterKey(e){const t=this.filterItems.get(e);return t?.attributeKey||t?.key||e}updateFilterItem(e,t={}){const s={calculateFacets:!1,excludeZeros:!0,excludeUndefineds:!0,excludeUnresolved:!0,skipProcessing:!1},o=this.getReferenceKeyForFilterKey(e);if(!o)return;const n=this.model.references.get(o);let i={};if(typeof n?.filter=="object"?i=Object.assign(s,n.filter,t):i=Object.assign(s,t),n){this.updateFilterItemReference(n.key,n.key,i);return}const a=this.model.properties.get(o);if(a)if(Array.isArray(a.filter)){a.filter.forEach(u=>{const c=u?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(u.key,a.key,a.type,c,i)});return}else{const u=a.filter?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(a.key,a.key,a.type,u,i);return}if(e==="key"){this.updateFilterItemProperty("key","key","string","containsIgnoreCase",i);return}}updateFilterItemReference(e,t,s){let o=[];const n=this.model.references.get(t);if(n&&!s.skipProcessing){const a=this.modelParser.models.get(n.model);o=this.getFacets(n.key,a,s)}const i={key:e,attributeKey:t,enabled:!!o.find(a=>a.enabled),selected:!!o.find(a=>a.selected),type:"reference",entries:o};this.filterItems.set(i.key,i)}updateFilterItemProperty(e,t,s,o,n){const i=this.getFilterTypeForPropertyType(s),a=this.queryBuilder.hasQueryGroup(e),u={key:e,attributeKey:t,enabled:!0,selected:!!a,type:i};if(u.type==="text"&&(u.comparisonType=o),u.type==="boolean"){const c=this.getFacets(u.attributeKey,void 0,n);u.entries=c}n.skipProcessing||(u.type==="number"&&(u.range=this.getNumberRangesForFilterItem(u)),u.type==="date"&&(u.range=this.getDateRangesForFilterItem(u))),this.filterItems.set(u.key,u)}getNumberRange(e,t=e){let s=1/0,o=-1/0;for(const a of this.filteredData.values()){const u=a[e];if(!(typeof u>"u"||u===null))if(Array.isArray(u))for(const c of u)typeof c=="number"&&(c<s&&(s=c),c>o&&(o=c));else typeof u=="number"&&(u<s&&(s=u),u>o&&(o=u))}let n=1/0,i=-1/0;for(const a of this.initialData.values()){const u=a[e];if(!(typeof u>"u"||u===null))if(Array.isArray(u))for(const c of u)typeof c=="number"&&(c<n&&(n=c),c>i&&(i=c));else typeof u=="number"&&(u<n&&(n=u),u>i&&(i=u))}return s===1/0&&(s=0),o===-1/0&&(o=0),n===1/0&&(n=0),i===-1/0&&(i=0),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getNumberRangesForFilterItem(e){return this.getNumberRange(e.attributeKey,e.key)}getDateRangesForFilterItem(e){return this.getDateRange(e.attributeKey,e.key)}getDateRange(e,t=e){let s=null,o=null;for(const u of this.filteredData.values()){const c=u[e];if(typeof c>"u"||c===null)continue;const l=Array.isArray(c)?c:[c];for(const d of l)d instanceof Date&&((!s||d<s)&&(s=d),(!o||d>o)&&(o=d))}let n=null,i=null;for(const u of this.initialData.values()){const c=u[e];if(typeof c>"u"||c===null)continue;const l=Array.isArray(c)?c:[c];for(const d of l)d instanceof Date&&((!n||d<n)&&(n=d),(!i||d>i)&&(i=d))}const a=new Date;return s||(s=a),o||(o=a),n||(n=a),i||(i=a),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getFacets(e,t,s,o){let n;const i=this.cacheCtrl.generateContext({attributeKey:e,query:this.queryBuilder.getQuery(),options:s}),a=this.cacheCtrl.get("facets",i);if(a)return a;let u=new Map;n=this.indicesController.getIndex(e),t?u=t.getData():u=this.indicesController.getData(e);let c=o||this.initialData;if(!o){const d=this.queryBuilder.getQueryAttributeForString(e);if(d.isDeepQuery){const f=this.queryBuilder.getProjectionForAttributeEntries([d]);c=this.item.getItemsAsMap(c,this.model,{projection:f})}}if(!n||!u){this.indicesController.reset(e);const d=P.parse(e),f=d.isDeepQuery;let h=c;if(f){const p=this.queryBuilder.getProjectionForAttributeEntries([d]);h=new Map;for(const[y,v]of c){const g=this.item.getProjectedData(p,this.model,v);h.set(y,g)}}h.forEach(p=>{let y;f?(y=ge(p,e),y.length===0&&(y=[void 0])):y=[p[e]],this.indicesController.fillInverseIndex(e,p.key,y),this.indicesController.fillDataMap(e,y)}),n=this.indicesController.getIndex(e),u=this.indicesController.getData(e)}const l=_f(c,u,s,this.queryBuilder.getQuery(),e,this.indicesController.indexMap,this.queryManager);return this.cacheCtrl.set("facets",i,l,{models:new Set([this.model.key]),modelAttributes:new Map([[this.model.key,new Set([e])]])}),l}getDataByKeys(e,t){if(t){const s=new Map;return t.forEach(o=>{const n=e.get(o);n&&s.set(n.key,n)}),s}return e}getFilterTypeForPropertyType(e){switch(e){case"string":return"text";case"int":return"number";case"float":return"number";case"date":return"date";case"boolean":return"boolean";case"json":return"text";case"any":return"text";case"Array<string>":return"text";case"Array<int>":return"number";case"Array<float>":return"number";case"Array<date>":return"date"}}updateFilteredData(e){const t=ye.now();e?.skipProcessing||(this.filteredData=this.getFilteredData(this.initialData,!1),this.cdRef.trigger({scope:"list",type:"result_updated",action:"update",connectMessage:!0,listKey:this.cdRef.key,modelKey:this.model.key,start:t}))}getFilteredData(e,t){const s=this.cacheCtrl.generateContext({query:this.queryBuilder.getQuery(),earlyReturn:t}),o=this.cacheCtrl.get("data",s);if(o)return o;const n=this.queryBuilder.getQuery(),i=this.getProjectionForQuery(n);let a;if(i){const u=this.getProjectionCacheKey(n),c=this.getProjectedData(e,i,u),l=this.queryManager.queryData(c,n,t,this.indicesController.indexMap);a=new Map;for(const d of l.keys())e.has(d)&&a.set(d,e.get(d))}else a=this.queryManager.queryData(e,n,t,this.indicesController.indexMap);return this.cacheCtrl.set("data",s,a,{models:new Set([this.model.key]),modelAttributes:new Map}),a}getFilterItems(e){if(Array.isArray(e?.filterKeys)){const t=[];return e?.filterKeys.forEach(s=>{const o=this.getFilterItem(s,e);o&&t.push(o)}),t}else return e?.skipProcessing||this.initFilterItems(e),Array.from(this.filterItems.values())}getFilterItem(e,t){return this.filterItems.has(e)&&(t?.skipProcessing||this.updateFilterItem(e,t)),this.filterItems.get(e)}},Ko=class{constructor(e,t){this.modelParser=e,this.scriptController=t}getItem(e,t,s,o){const n=o?.projection||{$:!0},i=t.get(e);return i?this.getProjectedData(n,s,i):null}getManyItems(e,t,s,o){const n=[];for(const i of e){const a=o?.projection||{$:!0},u=t.get(i);if(!u)continue;const c=this.getProjectedData(a,s,u);n.push(c)}return n}getItems(e,t,s){const o=this.getItemsAsMap(e,t,s);return Array.from(o.values())}getItemsAsMap(e,t,s){const o=s?.start||0,n=s?.count||e.size,i=s?.projection||{$:!0};return this.isValidSortProjection(s?.sort)&&(e=this.getSortedItems(e,s,t)),this.isValidScriptSorting(s?.sort)&&(e=this.getSortedItemsBasedOnScript(e,s)),this.getPagedData(e,o,n,i,t)}getSortedItemsBasedOnScript(e,t){const s=Array.from(e.values()),o=t?.sort?.script?.key||"",n=t?.sort?.script?.options||void 0;if(!this.scriptController.hasScript(o))return e;const i=this.scriptController.executeScript(o,"sort",{options:n,items:s});return new Map(i.map(a=>[a.key,a]))}getSortedItems(e,t,s){const o=[...t.sort.attributes],n=Array.from(e.values()),i=(l,d,f)=>{const h=l[d];return typeof h>"u"||h===null?f:typeof h=="string"?h.toLowerCase():typeof h=="object"&&typeof h?.key=="string"?h.key.toLowerCase():h},a=o.map((l,d)=>f=>{const h=t.sort.order.at(d),p=this.getUndefinedValueForSorting(l,h,s);return i(f,l,p)}),u=[...t.sort.order].map(l=>l.toLowerCase()),c=mo(n,[...a],u);return new Map(c.map(l=>[l.key,l]))}getUndefinedValueForSorting(e,t,s){const o=s?.properties.get(e);if(o){if(o.type==="string"){if(t=="ASC")return;if(t=="DESC")return""}if(o.type==="int"||o.type==="float"||o.type==="date"||o.type==="boolean"){if(t=="ASC")return 1/0;if(t=="DESC")return-1/0}}}isValidProjection(e){return!(!e||e.$===!0&&Object.keys(e).length===1)}getPagedData(e,t,s,o,n){const i=e.entries(),a=new Map;if(t===0&&s===e.size&&o?.$===!0&&Object.keys(o).length===1)return e;for(let u=0;u<t+s;u++){if(u<t){i.next();continue}if(u>t+s)break;const c=i.next().value;if(c)if(n&&o&&this.isValidProjection(o)){const l=this.getProjectedData(o,n,c[1]);a.set(c[0],l)}else a.set(c[0],c[1])}return a}isValidScriptSorting(e){return!(!e||!e.script)}isValidSortProjection(e){const t=["ASC","DESC"];return!(!e||!Array.isArray(e.attributes)||e.attributes.length===0||!Array.isArray(e.order)||e.attributes.length!==e.order.length||Vf(e.order,t).length>0)}getProjectedData(e,t,s){let o={key:s.key};return e.$===!0&&(o=Object.assign({},s)),e.$$===!0&&(o=Object.assign({},s),t.references.forEach(n=>{e[n.key]||(e[n.key]={$:!0})})),Object.keys(e).filter(n=>n!=="$"&&n!=="$$").forEach(n=>{const i=e[n];if(i===!1){delete o[n];return}if(i===!0){o[n]=s[n];return}if(typeof i=="object"){const a=t.references.get(n);if(a){const u=this.modelParser.models.get(a.model);if(u){if(a.type==="multiValued"){const c=s[n]||[];o[n]=c.map(l=>{const d=typeof l=="string"?l:l.key,f=u.getEntry(d);return f?this.getProjectedData(i,u,f):this.modelParser.initOptions.referenceMetadata?.enabled?{key:d,_dcupl_ref_:"miss"}:null}).filter(Boolean)}else if(a.type==="singleValued"){const c=s[n];if(c){const l=typeof c=="string"?c:c.key,d=u?.getEntry(l);d?o[n]=this.getProjectedData(i,u,d):this.modelParser.initOptions.referenceMetadata?.enabled?o[n]={key:l,_dcupl_ref_:"miss"}:delete o[n]}}}}}}),o}};var Uf=Object.defineProperty,Nf=Object.getOwnPropertyDescriptor,T=(r,e,t,s)=>{for(var o=Nf(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Uf(e,t,o),o};let j=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Ko(this.dcuplApi.modelParser,this.dcuplApi.scriptController),this.filter=new Gf(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}metadata;model;filter;itemService;log=Se.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e});if(this.filter.cacheCtrl.has("query",t))return this.filter.cacheCtrl.get("query",t);const s=Object.assign({},e,{modelKey:this.model.key}),o=this.dcuplApi.queryManager.queryData(this.filter.filteredData,s,!1,this.filter.indicesController.indexMap),n=this.itemService.getItems(o,this.model,e);return this.filter.cacheCtrl.set("query",t,n),n}_getSections(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("sections",t))return this.filter.cacheCtrl.get("sections",t);const s=this.filter.getSections(e);return this.filter.cacheCtrl.set("sections",t,s),s}_getItem(e){return this.itemService.getItem(e.itemKey,this.filter.filteredData,this.model,e)}_getManyItems(e){return this.itemService.getManyItems(e.itemKeys,this.filter.filteredData,this.model,e)}_getSuggestions(e){typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeNulls>"u"&&(e.excludeNulls=!0),typeof e.calculateResultKeys>"u"&&(e.calculateResultKeys=!0);const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("suggestions",t))return this.filter.cacheCtrl.get("suggestions",t);const s=P.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);if(typeof e.value=="string"&&e.value.startsWith("/")&&e.value.endsWith("/"))try{new RegExp(e.value.slice(1,-1))}catch{return[]}let o,n;if(e.relevantData==="all")o=this.filter.initialData,n={modelKey:this.model.key,queries:[]};else if(e.relevantData==="filtered")o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();else if(e.relevantData==="excludeQuery"&&e.excludeQuery){const c=new me;c.init(this.filter.queryBuilder.getQuery()),c.removeQuery(e.excludeQuery),n=c.getQuery(),o=this.dcuplApi.queryManager.queryData(this.filter.initialData,n,!1,this.filter.indicesController.indexMap)}else o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();let i=o;if(s){const c=P.parse(e.attribute),l=this.filter.queryBuilder.getProjectionForAttributeEntries([c]),d=new Map;for(const[f,h]of o){const p=this.filter.item.getProjectedData(l,this.model,h);d.set(f,p)}i=d}const a=this.filter.indicesController.getOrCreateIndex(e.attribute,i,{query:n}),u=lf(i,a,e,this.dcuplApi.queryManager);return this.filter.cacheCtrl.set("suggestions",t,u),u}_getFacets(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("facets",t))return this.filter.cacheCtrl.get("facets",t);const s=P.parse(e.attribute).isDeepQuery;let o;if(!s){const i=this.model.references.get(e.attribute);i&&(o=this.filter.modelParser.models.get(i.model))}let n;if(s){const i=P.parse(e.attribute),a=this.filter.queryBuilder.getProjectionForAttributeEntries([i]);n=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(a,this.model,c);n.set(u,l)}}return this.computeFacetsInternal(e,o,t,n)}computeFacetsInternal(e,t,s,o){typeof e.excludeZeros>"u"&&(e.excludeZeros=!0),typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeUnresolved>"u"&&(e.excludeUnresolved=!0),typeof e.calculateResults>"u"&&(e.calculateResults=!0);const n=this.filter.getFacets(e.attribute,t,{calculateFacets:e.calculateResults,count:e.count,excludeZeros:e.excludeZeros,excludeUndefineds:e.excludeUndefineds,excludeUnresolved:e.excludeUnresolved,sort:e.sort,skipProcessing:!1},o);return this.filter.cacheCtrl.set("facets",s,n),n}getAggregate(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("aggregation",t))return this.filter.cacheCtrl.get("aggregation",t);const s=P.parse(e.attribute);let o=this.filter.filteredData;if(s.isDeepQuery){const i=this.filter.queryBuilder.getProjectionForAttributeEntries([s]),a=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(i,this.model,c);a.set(u,l)}o=a}const n=this.filter.getAggregate(e,o,this.filter.indicesController.getOrCreateIndex(e.attribute,o,this.filter.queryBuilder.getQuery()));return this.filter.cacheCtrl.set("aggregation",t,n),n}_getPivot(e){if(!e||!Array.isArray(e.columns)||!Array.isArray(e.rows)||!e.values||!e.values.length)return this.log.error("Invalid pivot options",void 0,{model:this.model.key}),{key:"invalid_options"};const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("pivot",t))return this.filter.cacheCtrl.get("pivot",t);let s=new Mt;this.filter.filteredData.size===this.filter.initialData.size&&(s=this.filter.indicesController);const o=[...e.rows.map(a=>a.attribute),...e.columns.map(a=>a.attribute),...e.values.map(a=>a.attribute)].map(a=>P.parse(a)).filter(a=>a.isDeepQuery);let n;if(o.length>0){const a=this.filter.queryBuilder.getProjectionForAttributeEntries(o);n=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(a,this.model,c);n.set(u,l)}}const i=$r(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};T([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getMetadata"),T([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilters"),T([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilter"),T([b({scope:"list",type:"query_get",cloneResult:!0})],j.prototype,"getQuery"),T([b({scope:"list",type:"query_has"})],j.prototype,"hasGroupOrQueryKey"),T([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyQuery"),T([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyOptions"),T([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"removeQuery"),T([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"resetQuery"),T([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"executeQuery"),T([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSections"),T([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getItem"),T([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getManyItems"),T([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSuggestions"),T([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFacets"),T([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"getAggregate"),T([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getPivot");let zf=class extends j{constructor(e,t,s){super(e,t,s),this.dcuplApi=e,this.cdRef=t,this.indicesController=s}listKey;init(e,t,s){this.listKey=e,this.model=t,this.filter.init(t,s),super.initListeners()}update(e,t,s){this.model=e,this.filter.update(e,t,s)}};function Lf(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function Wf(r,e,t,s){var o=!t;t||(t={});for(var n=-1,i=e.length;++n<i;){var a=e[n],u=void 0;u===void 0&&(u=r[a]),o?At(t,a,u):ys(t,a,u)}return t}function Hf(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?ee(t)&&Yt(e,t.length):s=="string"&&e in t)?Ue(t[e],r):!1}function Jf(r){return er(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&Hf(t[0],t[1],i)&&(n=o<3?void 0:n,o=1),e=Object(e);++s<o;){var a=t[s];a&&r(e,a,s,n)}return e})}function Zf(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var Xf=Object.prototype,Yf=Xf.hasOwnProperty;function ep(r){if(!z(r))return Zf(r);var e=rr(r),t=[];for(var s in r)s=="constructor"&&(e||!Yf.call(r,s))||t.push(s);return t}function Fo(r){return ee(r)?$s(r,!0):ep(r)}var tp="[object Object]",rp=Function.prototype,sp=Object.prototype,qo=rp.toString,op=sp.hasOwnProperty,np=qo.call(Object);function ip(r){if(!K(r)||Y(r)!=tp)return!1;var e=Ss(r);if(e===null)return!0;var t=op.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&qo.call(t)==np}function ap(r,e,t,s){for(var o=-1,n=r==null?0:r.length;++o<n;){var i=r[o];e(s,i,t(i),r)}return s}function up(r,e,t,s){return yr(r,function(o,n,i){e(s,o,t(o),i)}),s}function cp(r,e){return function(t,s){var o=E(t)?ap:up,n={};return o(t,r,Ee(s),n)}}function _r(r,e,t){(t!==void 0&&!Ue(r[e],t)||t===void 0&&!(e in r))&&At(r,e,t)}function Pr(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function lp(r){return Wf(r,Fo(r))}function dp(r,e,t,s,o,n,i){var a=Pr(r,t),u=Pr(e,t),c=i.get(u);if(c){_r(r,t,c);return}var l=n?n(a,u,t+"",r,e,i):void 0,d=l===void 0;if(d){var f=E(u),h=!f&&ze(u),p=!f&&!h&&or(u);l=u,f||h||p?E(a)?l=a:je(a)?l=Lf(a):h?(d=!1,l=Ks(u,!0)):p?(d=!1,l=zs(u,!0)):l=[]:ip(u)||Ne(u)?(l=a,Ne(a)?l=lp(a):(!z(a)||Jt(a))&&(l=Ls(u))):d=!1}d&&(i.set(u,l),o(l,u,s,n,i),i.delete(u)),_r(r,t,l)}function Qo(r,e,t,s,o){r!==e&&lo(e,function(n,i){if(o||(o=new L),z(n))dp(r,e,i,t,Qo,s,o);else{var a=s?s(Pr(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),_r(r,i,a)}},Fo)}var fp=Object.prototype,pp=fp.hasOwnProperty,xr=cp(function(r,e,t){pp.call(r,t)?r[t].push(e):At(r,t,[e])}),hp="[object Boolean]";function yp(r){return r===!0||r===!1||K(r)&&Y(r)==hp}var st=Jf(function(r,e,t){Qo(r,e,t)});const B=(r,e,t)=>({title:r,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",attribute:e,description:t}),gp=r=>{const e=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"];if(!r.key)return B("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return B("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return B("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return B("Invalid Property",r.key,"Expression is invalid")},mp=r=>{const e=["multiValued","singleValued"];if(!r.key)return B("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return B("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return B("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return B("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return B("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return B("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return B("Invalid Reference",r.key,"Grouped Reference reference is missing")},vp=r=>{if(typeof r.key!="string"||r.key.length===0)throw new Error("Invalid Model: key must be a non-empty string");if(typeof r.keyProperty<"u"){const e=r.keyProperty,t=typeof e=="string"&&e.length>0,s=Array.isArray(e)&&e.length>0&&e.every(o=>typeof o=="string"&&o.length>0);if(!t&&!s)throw new Error("Invalid Model: keyProperty must be a non-empty string or a non-empty array of non-empty strings")}if(typeof r.keyPropertySeparator<"u"&&(typeof r.keyPropertySeparator!="string"||r.keyPropertySeparator.length===0))throw new Error("Invalid Model: keyPropertySeparator must be a non-empty string");if(typeof r.autoGenerateKey<"u"&&typeof r.autoGenerateKey!="boolean")throw new Error("Invalid Model: autoGenerateKey must be a boolean");if(typeof r.autoGenerateProperties<"u"){const e=r.autoGenerateProperties;if(typeof e!="boolean"){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid Model: autoGenerateProperties must be a boolean or an options object");if(typeof e.deep<"u"&&typeof e.deep!="boolean")throw new Error("Invalid Model: autoGenerateProperties.deep must be a boolean");if(typeof e.sampleSize<"u"&&(typeof e.sampleSize!="number"||!Number.isFinite(e.sampleSize)||e.sampleSize<1))throw new Error("Invalid Model: autoGenerateProperties.sampleSize must be a positive number")}}if(r.properties&&!Array.isArray(r.properties))throw new Error("Invalid Model: properties must be an array");if(r.references&&!Array.isArray(r.references))throw new Error("Invalid Model: references must be an array");return!0},bp=(r,e)=>{const t=[];return r.references.forEach(s=>{e.has(s.model)||t.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:s.key,model:r.key,description:`Referenced model ${s.model} does not exist`}),"derive"in s&&t.push(...kp(s,r,e)),"resolve"in s&&t.push(...wp(s,r,e)),"groupBy"in s&&t.push(...Ap(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Cp(s,r,e)),"expression"in s&&t.push(...$p(s,r))}),t},kp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},wp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Ap=(r,e)=>{const t=[];return e.references.get(r.groupBy.reference)||t.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.groupBy.reference} does not exist in model ${e.key}`}),t},Cp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);if(n){if(r.derive.remoteProperty==="key")return s;n.properties.get(r.derive.remoteProperty)||s.push({title:"Missing Property",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingProperty",attribute:r.key,model:e.key,description:`Remote Property ${r.derive.remoteProperty} does not exist in model ${n.key}`})}return s},$p=(r,e)=>{const t=[];return Dr(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},ot="::";function Dp(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Bo(r,e,t=ot){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function _p(r,e=ot){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Pp={REF_VALUE:"_dcupl_ref_"},Vo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Go={enabled:!0,attributes:Vo};let xp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Se.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Go;indicesController=new Mt;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=st({},Go,e.quality))}applyPropertiesAndReferences(e){e.properties?.map(t=>{const s=gp(t);s?(s.model=this.key,this.setError(s)):(this.setAttributeQualityConfig(t),this.properties.set(t.key,t))}),e.references?.map(t=>{const s=mp(t);s?(s.model=this.key,this.setError(s)):(t.validity=t.validity||"loose",this.setAttributeQualityConfig(t),this.references.set(t.key,t))}),this.supportsAutoCreation=!!e.supportsAutoCreation,this.keyProperty=e.keyProperty||"key",this.keyPropertySeparator=e.keyPropertySeparator,this.autoGenerateKey=!!e.autoGenerateKey,this.autoGenerateProperties=!!e.autoGenerateProperties,this.autoGeneratePropertiesOption=e.autoGenerateProperties??!1,this.valueMappings=e.valueMappings||[],this.meta=e.meta}setAttributeQualityConfig(e){const t=this.qualityConfig.attributes,s=st({},Vo,t,e.quality);this.attributeQualityConfigs.set(e.key,s)}getModelDefinition(){return this.autoGenerateProperties?{key:this.key,keyProperty:this.keyProperty,keyPropertySeparator:this.keyPropertySeparator,references:Array.from(this.references.values()),properties:Array.from(this.properties.values()),autoGenerateKey:this.autoGenerateKey,supportsAutoCreation:this.supportsAutoCreation,valueMappings:this.valueMappings,meta:this.meta,autoGenerateProperties:this.autoGeneratePropertiesOption,quality:this.qualityConfig}:this.initialDefinition}generatePropertiesFromContainer(e){const t=this.autoGeneratePropertiesOption;(typeof t=="object"&&t!==null?To(e.data,t):To(e.data,!1)).map(s=>{if(!this.properties.has(s.key)){if(s.key==="key")return;const o=e.keyProperty??this.keyProperty;Dp(o).some(n=>n&&n!=="key"&&n===s.key)&&(s.type="string"),s.filter=!0,this.properties.set(s.key,s)}})}getReferenceKeys(e){return e.map(t=>{if(typeof t=="string")return String(t.trim());if(typeof t=="number")return String(t);if(t===null)return"null";if(typeof t=="object"&&t&&t.key)return t.key})}setError(e){this.modelParser.qualityController.enabled&&this.qualityConfig.enabled===!0&&(e.model=this.key,this.modelParser.qualityController.setError(e))}emitUnknownColumnErrors(e,t,s,o,n){const i=new Set;for(const u of s)i.add(u.key);for(const u of o)i.add(u.key);const a=e.keyProperty??this.keyProperty;if(typeof a=="string")i.add(a);else if(Array.isArray(a))for(const u of a)i.add(u);i.add("key");for(const u of t)i.has(u)||this.setError({title:"Unknown Column",type:"model",errorGroup:"DataContainerError",errorType:"UnknownColumn",description:`Column "${u}" in the source for model "${e.model}" is not declared on the model; its values are dropped during ingest`,attribute:u,model:e.model,meta:{column:u,origin:n}})}processBasicProperty(e,t,s,o="inline"){const n=t[e.key],i=this.attributeQualityConfigs.get(e.key);let a;if(typeof n>"u"){if(i?.required){const u=e.type;this.setError({title:"Undefined Value",type:"model",errorGroup:"PropertyDataError",errorType:"UndefinedValue",description:`The required ${u??""} property "${e.key}" in the "${this.key}" model is undefined (no value)`.replace(/\s+/g," "),itemKey:t.key,attribute:e.key,model:this.key,meta:{rawValue:n,declaredType:u,origin:o}})}return}else{if(n===null)i?.nullable||this.setError({title:"Null Value",description:`The value of the property "${e.key}" in the "${this.key}" model should not be null`,type:"model",errorGroup:"PropertyDataError",errorType:"NullValue",itemKey:t.key,attribute:e.key,model:this.key}),a=n;else if(e.type==="string"){if(a=this.processStringProperty(e,n,t),typeof a>"u")return}else if(e.type==="int"){if(a=this.processIntProperty(e,n,t),typeof a>"u")return}else if(e.type==="float"){if(a=this.processFloatProperty(e,n,t),typeof a>"u")return}else if(e.type==="date"){if(a=this.processDateProperty(e,n,t),typeof a>"u")return}else if(e.type==="json"){if(a=this.processJSONProperty(e,n,t),typeof a>"u")return}else if(e.type==="boolean"){if(a=this.processBooleanProperty(e,n,t),typeof a>"u")return}else if(e.type==="any")a=n;else if(e.type==="Array<string>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processStringProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<int>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processIntProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<float>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processFloatProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<date>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processDateProperty(e,c,t);typeof l<"u"&&a.push(l)}))}s[e.key]=a}e.index&&(this.indicesController.fillInverseIndex(e.key,s.key,[a]),this.indicesController.fillDataMap(e.key,[a]))}handleValidators(e,t,s){if(!this.modelParser.qualityController.enabled||this.qualityConfig.enabled!==!0)return!0;let o=!0;try{if(t.quality?.validators){const n=this.modelParser.qualityController.validateAttribute(e,t.quality.validators,t.key);for(const i of n)o=!1,i.attribute=t.key,i.itemKey=s.key,i.model=this.key,this.setError(i)}}catch(n){this.log.error("Validator definition error",n)}return o}getWrongDataTypeError(e,t,s){return{title:"Wrong Data Type",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:s.key,attribute:e.key,model:this.key,description:`Expect ${e.type} but got ${typeof t} with value ${t}`,meta:{expected:e.type,rawValue:t,typeof:typeof t}}}isLossyNumericCoercion(e,t,s){const o=Number(typeof e=="string"?e.trim():e);return isNaN(o)?!0:s?o!==t:!1}getLossyCoercionError(e,t,s,o){return{title:"Lossy Data Coercion",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:o.key,attribute:e.key,model:this.key,description:`Lossy coercion to ${e.type}: raw value "${t}" was coerced to ${s}`,meta:{expected:e.type,rawValue:t,coercedValue:s,typeof:typeof t,lossy:!0}}}getValueAsArray(e,t=","){if(e)return Array.isArray(e)?e:e&&typeof e=="string"?e.split(t).map(s=>s.trim()):[]}processStringProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);let n=t;if(o?.forceStrictDataType){if(!Et(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!Et(n)&&n!=t){this.setError(this.getWrongDataTypeError(e,t,s));return}if(!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processIntProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Io(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Oo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}let n;const i=e.fractionDigits;if(typeof i>"u"?n=parseFloat(t):n=parseFloat(parseFloat(t).toFixed(i)),isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!1)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processJSONProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!K(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}if(K(t))return t;if(!K(t)&&typeof t=="string")try{return JSON.parse(t)}catch{this.setError(this.getWrongDataTypeError(e,t,s));return}}processBooleanProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!yp(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}return!!t}processDateProperty(e,t,s){if(t===""){this.setError(this.getWrongDataTypeError(e,t,s));return}const o=e.inputFormat;let n;try{if(o&&typeof o=="string"){let i=t;typeof i!="string"&&(i=String(i)),n=gf(i,o,new Date)}else n=new Date(t)}catch(i){this.log.error("Property extraction error",i,{property:e.key,model:this.key}),this.setError(this.getWrongDataTypeError(e,t,s));return}if(!jo(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}return e.UTC&&(n=new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))),n}processSingleValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;let n="";typeof t=="string"?n=t:typeof t=="object"&&t&&t.key&&(n=t.key);const i=o.getEntry(String(n));if(!i){if(o.supportsAutoCreation){const u=this.handleAutoCreationAndReturnKey(o,t);this.indicesController.fillInverseIndex(e.key,s.key,[t]),s[e.key]=u,this.setRefValue(u,"auto_hit");return}else if(this.indicesController.fillInverseIndex(e.key,s.key,[n]),this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${t}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:t}}),e.validity==="strict")return}this.indicesController.fillInverseIndex(e.key,s.key,[n]);const a={key:String(n)};s[e.key]=a,!i&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(a,"miss"):this.setRefValue(a,"hit")}processMultiValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;const n=this.getReferenceKeys(t),i=[];n.forEach((a,u)=>{const c=o.getEntry(String(a));if(!c){if(o.supportsAutoCreation){const d=this.handleAutoCreationAndReturnKey(o,t[u]);this.setRefValue(d,"auto_hit"),i.push(d);return}else if(this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${a}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:a}}),e.validity==="strict")return}const l={key:a};!c&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(l,"miss"):this.setRefValue(l,"hit"),i.push(l)}),this.indicesController.fillInverseIndex(e.key,s.key,i.map(a=>a.key)),s[e.key]=i}getViewKeys(){return this.modelParser._getViewKeys({modelKey:this.key})}addBasicPropertiesAndReferences(e){const t=this.getBasicProperties(),s=this.getBasicReferences(),o=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e),n=o?.origin??"inline";o&&o.sourceColumns.length>0&&this.emitUnknownColumnErrors(e,o.sourceColumns,t,s,n);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const c=e.keyProperty??this.keyProperty,l=e.keyPropertySeparator??this.keyPropertySeparator??ot,d=_p(c,l),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const c of t){c.origin&&(i[c.key]=i[c.origin]);const l=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(l)&&(i=this.mapRawValueUsingValueMapping(i,c.key,l)),this.processBasicProperty(c,i,a,n)}for(const c of s){const l=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),l?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(c,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const h=this.getValueAsArray(f,c?.separator);Array.isArray(h)?this.processMultiValuedReference(c,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}})}}const u=String(a.key);a.key=u,this.data.set(u,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=Rt(o,{...n}),u=JSON.parse(a),c=new me;c.init({modelKey:s.model}),c.applyQuery(u,{mode:"set"}),u.projection||c.applyOptions({projection:{$:!1}});const l=c.getQuery();if(l.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(l);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>!o.to);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??ot;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=Bo(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return setTimeout(()=>{e.addContainer(i)},0),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};setTimeout(()=>{e.addContainer(s)},0)}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const u=a.reference.key;let c;if(a.inverseKeys){if(a.reference.type==="multiValued"){const l=a.inverseKeys.get(n.key)||new Set;c=Array.from(l).map(d=>({key:d}))}else{const l=a.inverseKeys.get(n.key),d=l&&Array.from(l)[0]||null;d?c={key:d}:c=null}n[u]=c,this.indicesController.fillInverseIndex(u,o,n[u])}}const i=String(n.key);n.key=i,this.data.set(i,n)}}rebuildResolvedReferencesForAllItems(e){let t=this.getResolvedReferences();if(t.length===0||e&&(t=t.filter(o=>e.has(o.key)),t.length===0))return;const s=t.map(o=>{const n=this.modelParser.models.get(o.resolve.model);if(!n)return;const i=n.indicesController.getIndex(o.resolve.reference);return{reference:o,model:n,remoteData:[],inverseKeys:i}}).filter(o=>!!o);for(const o of this.data.values())for(const n of s){const i=n.reference.key;let a;if(n.inverseKeys){if(n.reference.type==="multiValued"){const u=n.inverseKeys.get(o.key)||new Set;a=Array.from(u).map(c=>({key:c}))}else{const u=n.inverseKeys.get(o.key),c=u?Array.from(u)[0]:null;c?a={key:c}:a=null}o[i]=a,this.indicesController.fillInverseIndex(i,o.key,o[i])}}}addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e){const t=this.getDerivedPropertiesForBasicAndDerivedReferences(),s=this.getExpressionProperties(),o=this.getDerivedReferences(),n=this.getGroupedReferences();for(const i of e.data){const a=this.data.get(String(i.key));o.length>0&&o.forEach(c=>{this.handleDerivedReferences(c,a)}),n.length>0&&n.forEach(c=>{this.handleGroupedReferences(c,a)}),t.length>0&&t.forEach(c=>{this.handleDerivedProperties(c,a)}),s.length>0&&s.forEach(c=>{const l=this.createExpressionContext(a),d=Rt(c.expression,l);a[c.key]=d});const u=String(a.key);a.key=u,this.data.set(u,a)}}handleDerivedProperties(e,t){const s=this.references.get(e.derive.localReference);if(s){const o=this.modelParser.models.get(s.model);o&&(s.type==="singleValued"?this.handleSingleValuedDerivedProperties(o,t,s,e):s.type==="multiValued"&&this.handleMultiValuedDerivedProperties(o,t,s,e))}}reRunDerivedPropertiesBasedOnResolves(e){const t=this.getDerivedProperties(),s=this.getDerivedReferences();for(const o of e.data){const n=this.data.get(String(o.key));s.forEach(a=>{this.handleDerivedReferences(a,n)}),t.forEach(a=>{const u=this.references.get(a.derive.localReference);if(u){const c=this.modelParser.models.get(u.model);c&&(u.type==="singleValued"?this.handleSingleValuedDerivedProperties(c,n,u,a):u.type==="multiValued"&&this.handleMultiValuedDerivedProperties(c,n,u,a))}});const i=String(n.key);n.key=i,this.data.set(i,n)}}handleSingleValuedDerivedProperties(e,t,s,o){const n=t[s.key];if(!n){delete t[o.key];return}const i=e?.getData().get(n.key);if(i){const a=i[o.derive.remoteProperty];typeof a<"u"&&(t[o.key]=a),o.index&&this.indicesController.fillInverseIndex(o.key,t.key,[a])}else delete t[o.key]}handleMultiValuedDerivedProperties(e,t,s,o){const n=t[s.key];let i;n?Array.isArray(n)?i=[...n]:n&&typeof n.key=="string"?i=[{key:n.key}]:i=[]:i=[];const a=o.derive?.separator||", ",u=i.map(l=>{const d=e?.getData().get(l.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let c;o.type.includes("Array<")?c=u:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?c=u.join(a):(o.type,c=u),t[o.key]=c}handleDerivedReferences(e,t){const s=this.references.get(e.derive.localReference);if(!s)return;const o=this.modelParser.models.get(s.model);if(!o)return;const n=t[s.key];if(!n)return;let i=[];if(Array.isArray(n)){const u=new Set;n.forEach(c=>{const l=o?.data.get(c.key);if(l){const d=l[e.derive.remoteReference];d&&(Array.isArray(d)?d.forEach(f=>{u.add(f.key)}):u.add(d.key))}}),i=Array.from(u.values())}else{const u=o?.data.get(n.key);if(u){const c=u[e.derive.remoteReference];c?Array.isArray(c)?i=c.map(l=>l.key):"key"in c&&(i=[c.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(u=>({key:u})),this.indicesController.fillInverseIndex(e.key,t.key,i),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const u of n){const c=i.get(u);c&&c.forEach(l=>a.add(l))}for(const u of a)e.groupBy.includeSelfInGroup?s.push({key:u}):t.key!==u&&s.push({key:u})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Pp.REF_VALUE,{value:t,enumerable:!0,writable:!1,configurable:!1})}addBasicPropertiesAndReferencesPartial(e,t){const s=this.getBasicProperties().filter(i=>t.has(i.key)),o=this.getBasicReferences().filter(i=>t.has(i.key)),n=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e)?.origin??"inline";for(let i of e.data){let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const c of s){c.origin&&(i[c.key]=i[c.origin]);const l=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(l)&&(i=this.mapRawValueUsingValueMapping(i,c.key,l)),this.processBasicProperty(c,i,a,n)}for(const c of o){const l=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];typeof f=="number"&&(f=String(f));const h=a[c.key];if(!f){h&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),delete a[c.key],l?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.processSingleValuedReference(c,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const p=this.getValueAsArray(f,c?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(c.key,a.key,h),this.processMultiValuedReference(c,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}})}}const u=String(a.key);a.key=u,this.data.set(u,a)}}addQueryAndResolvedReferencesPartial(e,t){if(this.hasQueryReferences()){const s=this.getQueryReferences().filter(o=>t.has(o.key));for(let o of s){const n=JSON.stringify(o.query);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)continue;const u=Rt(n,{...i}),c=JSON.parse(u),l=new me;l.init({modelKey:o.model}),l.applyQuery(c,{mode:"set"}),c.projection||l.applyOptions({projection:{$:!1}});const d=l.getQuery();if(d.queries.length>0){const h=this.modelParser.dcuplInstance.query.execute(d);o.type==="singleValued"?h[0]&&(a[o.key]={key:h[0].key,_dcupl_ref_:"hit"}):o.type==="multiValued"&&(h.forEach(p=>{p._dcupl_ref_="hit"}),a[o.key]=h)}else o.type==="singleValued"?a[o.key]=null:o.type==="multiValued"&&(a[o.key]=[]);const f=String(a.key);a.key=f,this.data.set(f,a)}}}this.hasResolvedReferences()&&this.getResolvedReferences().filter(s=>t.has(s.key)).length>0&&this.rebuildResolvedReferencesForAllItems()}createExpressionContext(e){const t={...e};return this.references.forEach((s,o)=>{const n=e[o];if(!n)return;const i=this.modelParser.models.get(s.model);if(i)if(s.type==="singleValued"&&typeof n=="object"&&"key"in n){const a=i.getData().get(n.key);a&&(t[o]=this.createNestedContext(a,i))}else s.type==="multiValued"&&Array.isArray(n)&&(t[o]=n.map(a=>{const u=i.getData().get(a.key);return u?this.createNestedContext(u,i):null}).filter(Boolean))}),t}createNestedContext(e,t){const s={...e};return t.references.forEach((o,n)=>{const i=e[n];if(!i)return;const a=this.modelParser.models.get(o.model);if(a&&o.type==="singleValued"&&typeof i=="object"&&"key"in i){const u=a.getData().get(i.key);u&&(s[n]={...u})}}),s}addDerivedAndExpressionAttributesPartial(e,t){const s=this.getDerivedPropertiesForBasicAndDerivedReferences().filter(a=>t.has(a.key)),o=this.getDerivedReferences().filter(a=>t.has(a.key)),n=this.getGroupedReferences().filter(a=>t.has(a.key)),i=this.getExpressionProperties().filter(a=>t.has(a.key));for(const a of e.data){const u=this.data.get(String(a.key));if(!u)continue;o.forEach(l=>{this.handleDerivedReferences(l,u)}),n.forEach(l=>{this.handleGroupedReferences(l,u)}),s.forEach(l=>{this.handleDerivedProperties(l,u)}),i.forEach(l=>{const d=this.createExpressionContext(u),f=Rt(l.expression,d);u[l.key]=f});const c=String(u.key);u.key=c,this.data.set(c,u)}}reRunDerivedPropertiesBasedOnResolvesPartial(e,t){const s=this.getDerivedProperties().filter(n=>t.has(n.key)),o=this.getDerivedReferences().filter(n=>t.has(n.key));for(const n of e.data){const i=this.data.get(String(n.key));if(!i)continue;o.forEach(u=>{this.handleDerivedReferences(u,i)}),s.forEach(u=>{this.handleDerivedProperties(u,i)});const a=String(i.key);i.key=a,this.data.set(a,i)}}};class Ep{changedAttributes;changedItems;deletedItems;modelFullReset;state="clean";constructor(){this.changedAttributes=new Map,this.changedItems=new Map,this.deletedItems=new Map,this.modelFullReset=new Set}recordDataChange(e){const t=e.model;if(!(!e.data||e.data.length===0))if(e.type==="set")this.state==="clean"?this.state="full-reset":this.state==="tracking"&&(this.state="full-reset",this.changedAttributes.delete(t),this.changedItems.delete(t),this.deletedItems.delete(t)),this.modelFullReset.add(t);else{if(this.modelFullReset.has(t))return;this.state==="clean"?this.state="tracking":this.state==="full-reset"&&(this.state="tracking"),e.type==="remove"?this.recordDeletedItems(t,e.data):this.recordChangedData(t,e.data)}}recordAttributeChange(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedAttributes.get(e).add(t)}recordChangedData(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedItems.has(e)||this.changedItems.set(e,new Set);const s=this.changedAttributes.get(e),o=this.changedItems.get(e);for(const n of t){n.key&&o.add(String(n.key));for(const i in n)i!=="key"&&s.add(i)}}recordDeletedItems(e,t){this.deletedItems.has(e)||this.deletedItems.set(e,new Set);const s=this.deletedItems.get(e);for(const o of t)o.key&&s.add(String(o.key))}getChangedAttributes(){return this.changedAttributes}getChangedAttributesForModel(e){return this.changedAttributes.get(e)}getChangedItems(e){return this.changedItems.get(e)||new Set}getDeletedItems(e){return this.deletedItems.get(e)||new Set}getModelsWithChanges(){const e=new Set;for(const t of this.changedAttributes.keys())e.add(t);for(const t of this.changedItems.keys())e.add(t);for(const t of this.deletedItems.keys())e.add(t);return Array.from(e)}getModelsWithFullReset(){return this.modelFullReset}hasFullReset(e){return this.modelFullReset.has(e)}hasChanges(){return this.changedAttributes.size>0||this.changedItems.size>0||this.deletedItems.size>0||this.modelFullReset.size>0}getTotalChangedItemCount(){let e=0;for(const t of this.changedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}}let jp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(u=>u.type==="partial"),t=this.metrics.filter(u=>u.type==="full"),s=e.length>0?e.reduce((u,c)=>u+c.durationMs,0)/e.length:0,o=t.length>0?t.reduce((u,c)=>u+c.durationMs,0)/t.length:0,n=e.length>0?e.reduce((u,c)=>u+(c.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((u,c)=>u+(c.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((u,c)=>u+(o-c.durationMs),0):0;return{totalUpdates:this.metrics.length,partialUpdates:e.length,fullUpdates:t.length,avgPartialUpdateTime:s,avgFullUpdateTime:o,avgAttributesProcessed:n,avgModelsAffected:i,totalTimeSaved:a}}getLastUpdates(e=10){return this.metrics.slice(-e)}clear(){this.metrics=[]}getMetricsInRange(e,t){return this.metrics.filter(s=>s.timestamp>=e&&s.timestamp<=t)}};function Sp(r){return"query"in r}function Er(r){return"resolve"in r}function Mp(r){return"derive"in r}function Rp(r){return"groupBy"in r}var Tp=Object.defineProperty,Ip=Object.getOwnPropertyDescriptor,Tt=(r,e,t,s)=>{for(var o=Ip(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Tp(e,t,o),o};let nt=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new Ep;partialUpdateMetrics=new jp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Se.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear()}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new xp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&bp(e,this.models).forEach(t=>{this.setError(t,e)})})}initDependencyGraph(){this.dependencyGraph=new Do,this.models.forEach(t=>{this.dependencyGraph.addNode(t.key)}),this.models.forEach(t=>{t.getReferencesRelevantForDependencyGraph().forEach(s=>{t.key!==s.model&&(this.dependencyGraph.addNode(s.model),this.dependencyGraph.addDependency(t.key,s.model))})});const e=this.dependencyGraph.validateNoCycles();if(e.hasCycle){const t=e.path.join(" → ");throw this.log.error(`Circular dependency detected in model references: ${t}
5
+ `}executeScript(e,t,s){if(!this.getScript(e))throw new Error(`Script ${e} not found`);s.context||(s.context=s.options||{});const o=Object.keys(s),n=Object.values(s);return this.getScriptAsFn(e,o)(t,...n)}}const Tt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>et(e,s.trim(),""))):"",_r=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};var Zf=tr(function(r,e){return Me(r)?go(r,Ts(e,1,Me)):[]});let Yf=class{constructor(e,t,s,o,n){this.modelParser=e,this.cdRef=t,this.item=s,this.indicesController=o,this.queryManager=n,this.cacheCtrl=new So(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}initialData;filteredData;model;filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new be,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=P.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches()}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&P.parse(o.attribute).isDeepQuery&&t.add(o.attribute);return Array.from(t)}getProjectionForQuery(e){const t=this.getDeepQueryAttributes(e);if(t.length===0)return null;const s=t.map(o=>P.parse(o));return this.queryBuilder.getProjectionForAttributeEntries(s)}getProjectionCacheKey(e){const t=this.getDeepQueryAttributes(e);return t.length===0?"":t.sort().join("|")}getProjectedData(e,t,s){if(s&&this.projectionCache.has(s))return this.projectionCache.get(s);const o=new Map;for(const[n,i]of e){const a=this.item.getProjectedData(t,this.model,i);o.set(n,a)}return s&&this.projectionCache.set(s,o),o}initFilterItems(e){[...this.model.properties.values(),...this.model.references.values()].forEach(t=>{t.filter&&(Array.isArray(e?.filterKeys)?e?.filterKeys.includes(t.key)&&this.updateFilterItem(t.key,e):this.updateFilterItem(t.key,e))})}getAggregate(e,t,s){if(P.parse(e.attribute).isDeepQuery)return st(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return st(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=P.parse(e.attribute),o=s.isDeepQuery;let n;if(!o&&(n=this.model.getAttribute(e.attribute),!n))throw new Error("Attribute not found");let i=new Map,a;!o&&n&&(n.type==="singleValued"||n.type==="multiValued")&&(a=this.modelParser.models.get(n.model));const u={},c=this.getSortingProjectionForModel(e,this.model);u.sort=c;let l=this.item.getItemsAsMap(this.filteredData,this.model,u);if(o){const p=this.queryBuilder.getProjectionForAttributeEntries([s]),y=new Map;for(const[v,g]of l){const k=this.item.getProjectedData(p,this.model,g);y.set(v,k)}l=y}const d=this.indicesController.getOrCreateIndex(`${e.attribute}`,l,{childLevelSorting:c,query:this.queryBuilder.getQuery()}),f=this.getAggregate({attribute:e.attribute,types:["distinct"],excludeUndefineds:!0},l,d);if(f.distinct)for(const p of f.distinct){let y={key:p.value,value:p.value};const v=p.keys.filter(k=>l.has(k));if(a){const k=a.data.get(p.value);k&&(y=k)}const g={...y,key:p.value,_items:[],_aggregates:[],_meta:{size:v.length}};i.set(p.value,g)}const h={count:e.count,start:e.start,projection:e.projection};if(a){const p=this.getSortingProjectionForModel(e,a);h.sort=p}if(t._meta.currentSize=i.size,t._meta.initialSize=f.distinct.length,i=this.item.getItemsAsMap(i,a,h),Array.isArray(e?.aggregates)&&i.forEach(p=>{const y=f.distinct.find(g=>g.value===p.key),v=this.getDataByKeys(l,y.keys);p._aggregates=e.aggregates.map(g=>this.getAggregate(g,v,d))}),e?.items){const p=e.items?.find(y=>y.key==="*");p?i.forEach(y=>{const v=f.distinct.find(m=>m.value===y.key),g=this.getDataByKeys(l,v.keys),k=this.item.getItems(g,this.model,p);y._items=k}):i.forEach(y=>{const v=e.items?.find(g=>g.key===y.key);if(v){const g=f.distinct.find(M=>M.value===y.key),k=this.getDataByKeys(l,g.keys),m=this.item.getItems(k,this.model,v);y._items=m}})}return t.items=Array.from(i.values()),t}getSortingProjectionForModel(e,t){const s={attributes:[],order:[]};return e?.sort?.attributes.forEach((o,n)=>{if(t.properties.has(o)){s.attributes.push(o);const i=e.sort?.order;s.order.push(i[n])}}),s}getReferenceKeyForFilterKey(e){const t=this.filterItems.get(e);return t?.attributeKey||t?.key||e}updateFilterItem(e,t={}){const s={calculateFacets:!1,excludeZeros:!0,excludeUndefineds:!0,excludeUnresolved:!0,skipProcessing:!1},o=this.getReferenceKeyForFilterKey(e);if(!o)return;const n=this.model.references.get(o);let i={};if(typeof n?.filter=="object"?i=Object.assign(s,n.filter,t):i=Object.assign(s,t),n){this.updateFilterItemReference(n.key,n.key,i);return}const a=this.model.properties.get(o);if(a)if(Array.isArray(a.filter)){a.filter.forEach(u=>{const c=u?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(u.key,a.key,a.type,c,i)});return}else{const u=a.filter?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(a.key,a.key,a.type,u,i);return}if(e==="key"){this.updateFilterItemProperty("key","key","string","containsIgnoreCase",i);return}}updateFilterItemReference(e,t,s){let o=[];const n=this.model.references.get(t);if(n&&!s.skipProcessing){const a=this.modelParser.models.get(n.model);o=this.getFacets(n.key,a,s)}const i={key:e,attributeKey:t,enabled:!!o.find(a=>a.enabled),selected:!!o.find(a=>a.selected),type:"reference",entries:o};this.filterItems.set(i.key,i)}updateFilterItemProperty(e,t,s,o,n){const i=this.getFilterTypeForPropertyType(s),a=this.queryBuilder.hasQueryGroup(e),u={key:e,attributeKey:t,enabled:!0,selected:!!a,type:i};if(u.type==="text"&&(u.comparisonType=o),u.type==="boolean"){const c=this.getFacets(u.attributeKey,void 0,n);u.entries=c}n.skipProcessing||(u.type==="number"&&(u.range=this.getNumberRangesForFilterItem(u)),u.type==="date"&&(u.range=this.getDateRangesForFilterItem(u))),this.filterItems.set(u.key,u)}getNumberRange(e,t=e){let s=1/0,o=-1/0;for(const a of this.filteredData.values()){const u=a[e];if(!(typeof u>"u"||u===null))if(Array.isArray(u))for(const c of u)typeof c=="number"&&(c<s&&(s=c),c>o&&(o=c));else typeof u=="number"&&(u<s&&(s=u),u>o&&(o=u))}let n=1/0,i=-1/0;for(const a of this.initialData.values()){const u=a[e];if(!(typeof u>"u"||u===null))if(Array.isArray(u))for(const c of u)typeof c=="number"&&(c<n&&(n=c),c>i&&(i=c));else typeof u=="number"&&(u<n&&(n=u),u>i&&(i=u))}return s===1/0&&(s=0),o===-1/0&&(o=0),n===1/0&&(n=0),i===-1/0&&(i=0),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getNumberRangesForFilterItem(e){return this.getNumberRange(e.attributeKey,e.key)}getDateRangesForFilterItem(e){return this.getDateRange(e.attributeKey,e.key)}getDateRange(e,t=e){let s=null,o=null;for(const u of this.filteredData.values()){const c=u[e];if(typeof c>"u"||c===null)continue;const l=Array.isArray(c)?c:[c];for(const d of l)d instanceof Date&&((!s||d<s)&&(s=d),(!o||d>o)&&(o=d))}let n=null,i=null;for(const u of this.initialData.values()){const c=u[e];if(typeof c>"u"||c===null)continue;const l=Array.isArray(c)?c:[c];for(const d of l)d instanceof Date&&((!n||d<n)&&(n=d),(!i||d>i)&&(i=d))}const a=new Date;return s||(s=a),o||(o=a),n||(n=a),i||(i=a),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getFacets(e,t,s,o){let n;const i=this.cacheCtrl.generateContext({attributeKey:e,query:this.queryBuilder.getQuery(),options:s}),a=this.cacheCtrl.get("facets",i);if(a)return a;let u=new Map;n=this.indicesController.getIndex(e),t?u=t.getData():u=this.indicesController.getData(e);let c=o||this.initialData;if(!o){const d=this.queryBuilder.getQueryAttributeForString(e);if(d.isDeepQuery){const f=this.queryBuilder.getProjectionForAttributeEntries([d]);c=this.item.getItemsAsMap(c,this.model,{projection:f})}}if(!n||!u){this.indicesController.reset(e);const d=P.parse(e),f=d.isDeepQuery;let h=c;if(f){const p=this.queryBuilder.getProjectionForAttributeEntries([d]);h=new Map;for(const[y,v]of c){const g=this.item.getProjectedData(p,this.model,v);h.set(y,g)}}h.forEach(p=>{let y;f?(y=ve(p,e),y.length===0&&(y=[void 0])):y=[p[e]],this.indicesController.fillInverseIndex(e,p.key,y),this.indicesController.fillDataMap(e,y)}),n=this.indicesController.getIndex(e),u=this.indicesController.getData(e)}const l=If(c,u,s,this.queryBuilder.getQuery(),e,this.indicesController.indexMap,this.queryManager);return this.cacheCtrl.set("facets",i,l,{models:new Set([this.model.key]),modelAttributes:new Map([[this.model.key,new Set([e])]])}),l}getDataByKeys(e,t){if(t){const s=new Map;return t.forEach(o=>{const n=e.get(o);n&&s.set(n.key,n)}),s}return e}getFilterTypeForPropertyType(e){switch(e){case"string":return"text";case"int":return"number";case"float":return"number";case"date":return"date";case"boolean":return"boolean";case"json":return"text";case"any":return"text";case"Array<string>":return"text";case"Array<int>":return"number";case"Array<float>":return"number";case"Array<date>":return"date"}}updateFilteredData(e){const t=me.now();e?.skipProcessing||(this.filteredData=this.getFilteredData(this.initialData,!1),this.cdRef.trigger({scope:"list",type:"result_updated",action:"update",connectMessage:!0,listKey:this.cdRef.key,modelKey:this.model.key,start:t}))}getFilteredData(e,t){const s=this.cacheCtrl.generateContext({query:this.queryBuilder.getQuery(),earlyReturn:t}),o=this.cacheCtrl.get("data",s);if(o)return o;const n=this.queryBuilder.getQuery(),i=this.getProjectionForQuery(n);let a;if(i){const u=this.getProjectionCacheKey(n),c=this.getProjectedData(e,i,u),l=this.queryManager.queryData(c,n,t,this.indicesController.indexMap);a=new Map;for(const d of l.keys())e.has(d)&&a.set(d,e.get(d))}else a=this.queryManager.queryData(e,n,t,this.indicesController.indexMap);return this.cacheCtrl.set("data",s,a,{models:new Set([this.model.key]),modelAttributes:new Map}),a}getFilterItems(e){if(Array.isArray(e?.filterKeys)){const t=[];return e?.filterKeys.forEach(s=>{const o=this.getFilterItem(s,e);o&&t.push(o)}),t}else return e?.skipProcessing||this.initFilterItems(e),Array.from(this.filterItems.values())}getFilterItem(e,t){return this.filterItems.has(e)&&(t?.skipProcessing||this.updateFilterItem(e,t)),this.filterItems.get(e)}},Bo=class{constructor(e,t){this.modelParser=e,this.scriptController=t}getItem(e,t,s,o){const n=o?.projection||{$:!0},i=t.get(e);return i?this.getProjectedData(n,s,i):null}getManyItems(e,t,s,o){const n=[];for(const i of e){const a=o?.projection||{$:!0},u=t.get(i);if(!u)continue;const c=this.getProjectedData(a,s,u);n.push(c)}return n}getItems(e,t,s){const o=this.getItemsAsMap(e,t,s);return Array.from(o.values())}getItemsAsMap(e,t,s){const o=s?.start||0,n=s?.count||e.size,i=s?.projection||{$:!0};return this.isValidSortProjection(s?.sort)&&(e=this.getSortedItems(e,s,t)),this.isValidScriptSorting(s?.sort)&&(e=this.getSortedItemsBasedOnScript(e,s)),this.getPagedData(e,o,n,i,t)}getSortedItemsBasedOnScript(e,t){const s=Array.from(e.values()),o=t?.sort?.script?.key||"",n=t?.sort?.script?.options||void 0;if(!this.scriptController.hasScript(o))return e;const i=this.scriptController.executeScript(o,"sort",{options:n,items:s});return new Map(i.map(a=>[a.key,a]))}getSortedItems(e,t,s){const o=[...t.sort.attributes],n=Array.from(e.values()),i=(l,d,f)=>{const h=l[d];return typeof h>"u"||h===null?f:typeof h=="string"?h.toLowerCase():typeof h=="object"&&typeof h?.key=="string"?h.key.toLowerCase():h},a=o.map((l,d)=>f=>{const h=t.sort.order.at(d),p=this.getUndefinedValueForSorting(l,h,s);return i(f,l,p)}),u=[...t.sort.order].map(l=>l.toLowerCase()),c=wo(n,[...a],u);return new Map(c.map(l=>[l.key,l]))}getUndefinedValueForSorting(e,t,s){const o=s?.properties.get(e);if(o){if(o.type==="string"){if(t=="ASC")return;if(t=="DESC")return""}if(o.type==="int"||o.type==="float"||o.type==="date"||o.type==="boolean"){if(t=="ASC")return 1/0;if(t=="DESC")return-1/0}}}isValidProjection(e){return!(!e||e.$===!0&&Object.keys(e).length===1)}getPagedData(e,t,s,o,n){const i=e.entries(),a=new Map;if(t===0&&s===e.size&&o?.$===!0&&Object.keys(o).length===1)return e;for(let u=0;u<t+s;u++){if(u<t){i.next();continue}if(u>t+s)break;const c=i.next().value;if(c)if(n&&o&&this.isValidProjection(o)){const l=this.getProjectedData(o,n,c[1]);a.set(c[0],l)}else a.set(c[0],c[1])}return a}isValidScriptSorting(e){return!(!e||!e.script)}isValidSortProjection(e){const t=["ASC","DESC"];return!(!e||!Array.isArray(e.attributes)||e.attributes.length===0||!Array.isArray(e.order)||e.attributes.length!==e.order.length||Zf(e.order,t).length>0)}getProjectedData(e,t,s){let o={key:s.key};return e.$===!0&&(o=Object.assign({},s)),e.$$===!0&&(o=Object.assign({},s),t.references.forEach(n=>{e[n.key]||(e[n.key]={$:!0})})),Object.keys(e).filter(n=>n!=="$"&&n!=="$$").forEach(n=>{const i=e[n];if(i===!1){delete o[n];return}if(i===!0){o[n]=s[n];return}if(typeof i=="object"){const a=t.references.get(n);if(a){const u=this.modelParser.models.get(a.model);if(u){if(a.type==="multiValued"){const c=s[n]||[];o[n]=c.map(l=>{const d=typeof l=="string"?l:l.key,f=u.getEntry(d);return f?this.getProjectedData(i,u,f):this.modelParser.initOptions.referenceMetadata?.enabled?{key:d,_dcupl_ref_:"miss"}:null}).filter(Boolean)}else if(a.type==="singleValued"){const c=s[n];if(c){const l=typeof c=="string"?c:c.key,d=u?.getEntry(l);d?o[n]=this.getProjectedData(i,u,d):this.modelParser.initOptions.referenceMetadata?.enabled?o[n]={key:l,_dcupl_ref_:"miss"}:delete o[n]}}}}}}),o}};var Xf=Object.defineProperty,ep=Object.getOwnPropertyDescriptor,T=(r,e,t,s)=>{for(var o=ep(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Xf(e,t,o),o};let j=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Bo(this.dcuplApi.modelParser,this.dcuplApi.scriptController),this.filter=new Yf(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}metadata;model;filter;itemService;log=Re.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e});if(this.filter.cacheCtrl.has("query",t))return this.filter.cacheCtrl.get("query",t);const s=Object.assign({},e,{modelKey:this.model.key}),o=this.dcuplApi.queryManager.queryData(this.filter.filteredData,s,!1,this.filter.indicesController.indexMap),n=this.itemService.getItems(o,this.model,e);return this.filter.cacheCtrl.set("query",t,n),n}_getSections(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("sections",t))return this.filter.cacheCtrl.get("sections",t);const s=this.filter.getSections(e);return this.filter.cacheCtrl.set("sections",t,s),s}_getItem(e){return this.itemService.getItem(e.itemKey,this.filter.filteredData,this.model,e)}_getManyItems(e){return this.itemService.getManyItems(e.itemKeys,this.filter.filteredData,this.model,e)}_getSuggestions(e){typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeNulls>"u"&&(e.excludeNulls=!0),typeof e.calculateResultKeys>"u"&&(e.calculateResultKeys=!0);const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("suggestions",t))return this.filter.cacheCtrl.get("suggestions",t);const s=P.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);if(typeof e.value=="string"&&e.value.startsWith("/")&&e.value.endsWith("/"))try{new RegExp(e.value.slice(1,-1))}catch{return[]}let o,n;if(e.relevantData==="all")o=this.filter.initialData,n={modelKey:this.model.key,queries:[]};else if(e.relevantData==="filtered")o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();else if(e.relevantData==="excludeQuery"&&e.excludeQuery){const c=new be;c.init(this.filter.queryBuilder.getQuery()),c.removeQuery(e.excludeQuery),n=c.getQuery(),o=this.dcuplApi.queryManager.queryData(this.filter.initialData,n,!1,this.filter.indicesController.indexMap)}else o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();let i=o;if(s){const c=P.parse(e.attribute),l=this.filter.queryBuilder.getProjectionForAttributeEntries([c]),d=new Map;for(const[f,h]of o){const p=this.filter.item.getProjectedData(l,this.model,h);d.set(f,p)}i=d}const a=this.filter.indicesController.getOrCreateIndex(e.attribute,i,{query:n}),u=bf(i,a,e,this.dcuplApi.queryManager);return this.filter.cacheCtrl.set("suggestions",t,u),u}_getFacets(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("facets",t))return this.filter.cacheCtrl.get("facets",t);const s=P.parse(e.attribute).isDeepQuery;let o;if(!s){const i=this.model.references.get(e.attribute);i&&(o=this.filter.modelParser.models.get(i.model))}let n;if(s){const i=P.parse(e.attribute),a=this.filter.queryBuilder.getProjectionForAttributeEntries([i]);n=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(a,this.model,c);n.set(u,l)}}return this.computeFacetsInternal(e,o,t,n)}computeFacetsInternal(e,t,s,o){typeof e.excludeZeros>"u"&&(e.excludeZeros=!0),typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeUnresolved>"u"&&(e.excludeUnresolved=!0),typeof e.calculateResults>"u"&&(e.calculateResults=!0);const n=this.filter.getFacets(e.attribute,t,{calculateFacets:e.calculateResults,count:e.count,excludeZeros:e.excludeZeros,excludeUndefineds:e.excludeUndefineds,excludeUnresolved:e.excludeUnresolved,sort:e.sort,skipProcessing:!1},o);return this.filter.cacheCtrl.set("facets",s,n),n}getAggregate(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("aggregation",t))return this.filter.cacheCtrl.get("aggregation",t);const s=P.parse(e.attribute);let o=this.filter.filteredData;if(s.isDeepQuery){const i=this.filter.queryBuilder.getProjectionForAttributeEntries([s]),a=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(i,this.model,c);a.set(u,l)}o=a}const n=this.filter.getAggregate(e,o,this.filter.indicesController.getOrCreateIndex(e.attribute,o,this.filter.queryBuilder.getQuery()));return this.filter.cacheCtrl.set("aggregation",t,n),n}_getPivot(e){if(!e||!Array.isArray(e.columns)||!Array.isArray(e.rows)||!e.values||!e.values.length)return this.log.error("Invalid pivot options",void 0,{model:this.model.key}),{key:"invalid_options"};const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("pivot",t))return this.filter.cacheCtrl.get("pivot",t);let s=new Rt;this.filter.filteredData.size===this.filter.initialData.size&&(s=this.filter.indicesController);const o=[...e.rows.map(a=>a.attribute),...e.columns.map(a=>a.attribute),...e.values.map(a=>a.attribute)].map(a=>P.parse(a)).filter(a=>a.isDeepQuery);let n;if(o.length>0){const a=this.filter.queryBuilder.getProjectionForAttributeEntries(o);n=new Map;for(const[u,c]of this.filter.filteredData){const l=this.filter.item.getProjectedData(a,this.model,c);n.set(u,l)}}const i=Dr(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};T([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getMetadata"),T([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilters"),T([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilter"),T([b({scope:"list",type:"query_get",cloneResult:!0})],j.prototype,"getQuery"),T([b({scope:"list",type:"query_has"})],j.prototype,"hasGroupOrQueryKey"),T([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyQuery"),T([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyOptions"),T([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"removeQuery"),T([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"resetQuery"),T([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"executeQuery"),T([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSections"),T([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getItem"),T([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getManyItems"),T([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSuggestions"),T([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFacets"),T([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"getAggregate"),T([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getPivot");let tp=class extends j{constructor(e,t,s){super(e,t,s),this.dcuplApi=e,this.cdRef=t,this.indicesController=s}listKey;init(e,t,s){this.listKey=e,this.model=t,this.filter.init(t,s),super.initListeners()}update(e,t,s){this.model=e,this.filter.update(e,t,s)}};function rp(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function sp(r,e,t,s){var o=!t;t||(t={});for(var n=-1,i=e.length;++n<i;){var a=e[n],u=void 0;u===void 0&&(u=r[a]),o?$t(t,a,u):bs(t,a,u)}return t}function op(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?ee(t)&&er(e,t.length):s=="string"&&e in t)?ze(t[e],r):!1}function np(r){return tr(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&op(t[0],t[1],i)&&(n=o<3?void 0:n,o=1),e=Object(e);++s<o;){var a=t[s];a&&r(e,a,s,n)}return e})}function ip(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var ap=Object.prototype,up=ap.hasOwnProperty;function cp(r){if(!z(r))return ip(r);var e=sr(r),t=[];for(var s in r)s=="constructor"&&(e||!up.call(r,s))||t.push(s);return t}function Vo(r){return ee(r)?xs(r,!0):cp(r)}var lp="[object Object]",dp=Function.prototype,fp=Object.prototype,Go=dp.toString,pp=fp.hasOwnProperty,hp=Go.call(Object);function yp(r){if(!K(r)||X(r)!=lp)return!1;var e=Is(r);if(e===null)return!0;var t=pp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Go.call(t)==hp}function gp(r,e,t,s){for(var o=-1,n=r==null?0:r.length;++o<n;){var i=r[o];e(s,i,t(i),r)}return s}function mp(r,e,t,s){return gr(r,function(o,n,i){e(s,o,t(o),i)}),s}function vp(r,e){return function(t,s){var o=E(t)?gp:mp,n={};return o(t,r,Se(s),n)}}function Pr(r,e,t){(t!==void 0&&!ze(r[e],t)||t===void 0&&!(e in r))&&$t(r,e,t)}function xr(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function bp(r){return sp(r,Vo(r))}function kp(r,e,t,s,o,n,i){var a=xr(r,t),u=xr(e,t),c=i.get(u);if(c){Pr(r,t,c);return}var l=n?n(a,u,t+"",r,e,i):void 0,d=l===void 0;if(d){var f=E(u),h=!f&&We(u),p=!f&&!h&&nr(u);l=u,f||h||p?E(a)?l=a:Me(a)?l=rp(a):h?(d=!1,l=Bs(u,!0)):p?(d=!1,l=Js(u,!0)):l=[]:yp(u)||Le(u)?(l=a,Le(a)?l=bp(a):(!z(a)||Zt(a))&&(l=Zs(u))):d=!1}d&&(i.set(u,l),o(l,u,s,n,i),i.delete(u)),Pr(r,t,l)}function Uo(r,e,t,s,o){r!==e&&yo(e,function(n,i){if(o||(o=new L),z(n))kp(r,e,i,t,Uo,s,o);else{var a=s?s(xr(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),Pr(r,i,a)}},Vo)}var wp=Object.prototype,Ap=wp.hasOwnProperty,Er=vp(function(r,e,t){Ap.call(r,t)?r[t].push(e):$t(r,t,[e])}),$p="[object Boolean]";function Cp(r){return r===!0||r===!1||K(r)&&X(r)==$p}var nt=np(function(r,e,t){Uo(r,e,t)});const B=(r,e,t)=>({title:r,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",attribute:e,description:t}),Dp=r=>{const e=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"];if(!r.key)return B("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return B("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return B("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return B("Invalid Property",r.key,"Expression is invalid")},_p=r=>{const e=["multiValued","singleValued"];if(!r.key)return B("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return B("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return B("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return B("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return B("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return B("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return B("Invalid Reference",r.key,"Grouped Reference reference is missing")},Pp=r=>{if(typeof r.key!="string"||r.key.length===0)throw new Error("Invalid Model: key must be a non-empty string");if(typeof r.keyProperty<"u"){const e=r.keyProperty,t=typeof e=="string"&&e.length>0,s=Array.isArray(e)&&e.length>0&&e.every(o=>typeof o=="string"&&o.length>0);if(!t&&!s)throw new Error("Invalid Model: keyProperty must be a non-empty string or a non-empty array of non-empty strings")}if(typeof r.keyPropertySeparator<"u"&&(typeof r.keyPropertySeparator!="string"||r.keyPropertySeparator.length===0))throw new Error("Invalid Model: keyPropertySeparator must be a non-empty string");if(typeof r.autoGenerateKey<"u"&&typeof r.autoGenerateKey!="boolean")throw new Error("Invalid Model: autoGenerateKey must be a boolean");if(typeof r.autoGenerateProperties<"u"){const e=r.autoGenerateProperties;if(typeof e!="boolean"){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid Model: autoGenerateProperties must be a boolean or an options object");if(typeof e.deep<"u"&&typeof e.deep!="boolean")throw new Error("Invalid Model: autoGenerateProperties.deep must be a boolean");if(typeof e.sampleSize<"u"&&(typeof e.sampleSize!="number"||!Number.isFinite(e.sampleSize)||e.sampleSize<1))throw new Error("Invalid Model: autoGenerateProperties.sampleSize must be a positive number")}}if(r.properties&&!Array.isArray(r.properties))throw new Error("Invalid Model: properties must be an array");if(r.references&&!Array.isArray(r.references))throw new Error("Invalid Model: references must be an array");return!0},xp=(r,e)=>{const t=[];return r.references.forEach(s=>{e.has(s.model)||t.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:s.key,model:r.key,description:`Referenced model ${s.model} does not exist`}),"derive"in s&&t.push(...Ep(s,r,e)),"resolve"in s&&t.push(...jp(s,r,e)),"groupBy"in s&&t.push(...Sp(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Mp(s,r,e)),"expression"in s&&t.push(...Rp(s,r))}),t},Ep=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},jp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Sp=(r,e)=>{const t=[];return e.references.get(r.groupBy.reference)||t.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.groupBy.reference} does not exist in model ${e.key}`}),t},Mp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);if(n){if(r.derive.remoteProperty==="key")return s;n.properties.get(r.derive.remoteProperty)||s.push({title:"Missing Property",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingProperty",attribute:r.key,model:e.key,description:`Remote Property ${r.derive.remoteProperty} does not exist in model ${n.key}`})}return s},Rp=(r,e)=>{const t=[];return _r(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},it="::";function Tp(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function No(r,e,t=it){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function Ip(r,e=it){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Op={REF_VALUE:"_dcupl_ref_"},zo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Lo={enabled:!0,attributes:zo};let Kp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Re.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Lo;indicesController=new Rt;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=nt({},Lo,e.quality))}applyPropertiesAndReferences(e){e.properties?.map(t=>{const s=Dp(t);s?(s.model=this.key,this.setError(s)):(this.setAttributeQualityConfig(t),this.properties.set(t.key,t))}),e.references?.map(t=>{const s=_p(t);s?(s.model=this.key,this.setError(s)):(t.validity=t.validity||"loose",this.setAttributeQualityConfig(t),this.references.set(t.key,t))}),this.supportsAutoCreation=!!e.supportsAutoCreation,this.keyProperty=e.keyProperty||"key",this.keyPropertySeparator=e.keyPropertySeparator,this.autoGenerateKey=!!e.autoGenerateKey,this.autoGenerateProperties=!!e.autoGenerateProperties,this.autoGeneratePropertiesOption=e.autoGenerateProperties??!1,this.valueMappings=e.valueMappings||[],this.meta=e.meta}setAttributeQualityConfig(e){const t=this.qualityConfig.attributes,s=nt({},zo,t,e.quality);this.attributeQualityConfigs.set(e.key,s)}getModelDefinition(){return this.autoGenerateProperties?{key:this.key,keyProperty:this.keyProperty,keyPropertySeparator:this.keyPropertySeparator,references:Array.from(this.references.values()),properties:Array.from(this.properties.values()),autoGenerateKey:this.autoGenerateKey,supportsAutoCreation:this.supportsAutoCreation,valueMappings:this.valueMappings,meta:this.meta,autoGenerateProperties:this.autoGeneratePropertiesOption,quality:this.qualityConfig}:this.initialDefinition}generatePropertiesFromContainer(e){const t=this.autoGeneratePropertiesOption;(typeof t=="object"&&t!==null?Fo(e.data,t):Fo(e.data,!1)).map(s=>{if(!this.properties.has(s.key)){if(s.key==="key")return;const o=e.keyProperty??this.keyProperty;Tp(o).some(n=>n&&n!=="key"&&n===s.key)&&(s.type="string"),s.filter=!0,this.properties.set(s.key,s)}})}getReferenceKeys(e){return e.map(t=>{if(typeof t=="string")return String(t.trim());if(typeof t=="number")return String(t);if(t===null)return"null";if(typeof t=="object"&&t&&t.key)return t.key})}setError(e){this.modelParser.qualityController.enabled&&this.qualityConfig.enabled===!0&&(e.model=this.key,this.modelParser.qualityController.setError(e))}emitUnknownColumnErrors(e,t,s,o,n){const i=new Set;for(const u of s)i.add(u.key);for(const u of o)i.add(u.key);const a=e.keyProperty??this.keyProperty;if(typeof a=="string")i.add(a);else if(Array.isArray(a))for(const u of a)i.add(u);i.add("key");for(const u of t)i.has(u)||this.setError({title:"Unknown Column",type:"model",errorGroup:"DataContainerError",errorType:"UnknownColumn",description:`Column "${u}" in the source for model "${e.model}" is not declared on the model; its values are dropped during ingest`,attribute:u,model:e.model,meta:{column:u,origin:n}})}processBasicProperty(e,t,s,o="inline"){const n=t[e.key],i=this.attributeQualityConfigs.get(e.key);let a;if(typeof n>"u"){if(i?.required){const u=e.type;this.setError({title:"Undefined Value",type:"model",errorGroup:"PropertyDataError",errorType:"UndefinedValue",description:`The required ${u??""} property "${e.key}" in the "${this.key}" model is undefined (no value)`.replace(/\s+/g," "),itemKey:t.key,attribute:e.key,model:this.key,meta:{rawValue:n,declaredType:u,origin:o}})}return}else{if(n===null)i?.nullable||this.setError({title:"Null Value",description:`The value of the property "${e.key}" in the "${this.key}" model should not be null`,type:"model",errorGroup:"PropertyDataError",errorType:"NullValue",itemKey:t.key,attribute:e.key,model:this.key}),a=n;else if(e.type==="string"){if(a=this.processStringProperty(e,n,t),typeof a>"u")return}else if(e.type==="int"){if(a=this.processIntProperty(e,n,t),typeof a>"u")return}else if(e.type==="float"){if(a=this.processFloatProperty(e,n,t),typeof a>"u")return}else if(e.type==="date"){if(a=this.processDateProperty(e,n,t),typeof a>"u")return}else if(e.type==="json"){if(a=this.processJSONProperty(e,n,t),typeof a>"u")return}else if(e.type==="boolean"){if(a=this.processBooleanProperty(e,n,t),typeof a>"u")return}else if(e.type==="any")a=n;else if(e.type==="Array<string>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processStringProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<int>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processIntProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<float>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processFloatProperty(e,c,t);typeof l<"u"&&a.push(l)}))}else if(e.type==="Array<date>"){const u=this.getValueAsArray(n,e?.separator);Array.isArray(u)&&(a=[],u.forEach(c=>{const l=this.processDateProperty(e,c,t);typeof l<"u"&&a.push(l)}))}s[e.key]=a}e.index&&(this.indicesController.fillInverseIndex(e.key,s.key,[a]),this.indicesController.fillDataMap(e.key,[a]))}handleValidators(e,t,s){if(!this.modelParser.qualityController.enabled||this.qualityConfig.enabled!==!0)return!0;let o=!0;try{if(t.quality?.validators){const n=this.modelParser.qualityController.validateAttribute(e,t.quality.validators,t.key);for(const i of n)o=!1,i.attribute=t.key,i.itemKey=s.key,i.model=this.key,this.setError(i)}}catch(n){this.log.error("Validator definition error",n)}return o}getWrongDataTypeError(e,t,s){return{title:"Wrong Data Type",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:s.key,attribute:e.key,model:this.key,description:`Expect ${e.type} but got ${typeof t} with value ${t}`,meta:{expected:e.type,rawValue:t,typeof:typeof t}}}isLossyNumericCoercion(e,t,s){const o=Number(typeof e=="string"?e.trim():e);return isNaN(o)?!0:s?o!==t:!1}getLossyCoercionError(e,t,s,o){return{title:"Lossy Data Coercion",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:o.key,attribute:e.key,model:this.key,description:`Lossy coercion to ${e.type}: raw value "${t}" was coerced to ${s}`,meta:{expected:e.type,rawValue:t,coercedValue:s,typeof:typeof t,lossy:!0}}}getValueAsArray(e,t=","){if(e)return Array.isArray(e)?e:e&&typeof e=="string"?e.split(t).map(s=>s.trim()):[]}processStringProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);let n=t;if(o?.forceStrictDataType){if(!jt(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!jt(n)&&n!=t){this.setError(this.getWrongDataTypeError(e,t,s));return}if(!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processIntProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!qo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Qo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}let n;const i=e.fractionDigits;if(typeof i>"u"?n=parseFloat(t):n=parseFloat(parseFloat(t).toFixed(i)),isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!1)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processJSONProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!K(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}if(K(t))return t;if(!K(t)&&typeof t=="string")try{return JSON.parse(t)}catch{this.setError(this.getWrongDataTypeError(e,t,s));return}}processBooleanProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!Cp(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}return!!t}processDateProperty(e,t,s){if(t===""){this.setError(this.getWrongDataTypeError(e,t,s));return}const o=e.inputFormat;let n;try{if(o&&typeof o=="string"){let i=t;typeof i!="string"&&(i=String(i)),n=Df(i,o,new Date)}else n=new Date(t)}catch(i){this.log.error("Property extraction error",i,{property:e.key,model:this.key}),this.setError(this.getWrongDataTypeError(e,t,s));return}if(!To(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}return e.UTC&&(n=new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))),n}processSingleValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;let n="";typeof t=="string"?n=t:typeof t=="object"&&t&&t.key&&(n=t.key);const i=o.getEntry(String(n));if(!i){if(o.supportsAutoCreation){const u=this.handleAutoCreationAndReturnKey(o,t);this.indicesController.fillInverseIndex(e.key,s.key,[t]),s[e.key]=u,this.setRefValue(u,"auto_hit");return}else if(this.indicesController.fillInverseIndex(e.key,s.key,[n]),this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${t}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:t}}),e.validity==="strict")return}this.indicesController.fillInverseIndex(e.key,s.key,[n]);const a={key:String(n)};s[e.key]=a,!i&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(a,"miss"):this.setRefValue(a,"hit")}processMultiValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;const n=this.getReferenceKeys(t),i=[];n.forEach((a,u)=>{const c=o.getEntry(String(a));if(!c){if(o.supportsAutoCreation){const d=this.handleAutoCreationAndReturnKey(o,t[u]);this.setRefValue(d,"auto_hit"),i.push(d);return}else if(this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${a}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:a}}),e.validity==="strict")return}const l={key:a};!c&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(l,"miss"):this.setRefValue(l,"hit"),i.push(l)}),this.indicesController.fillInverseIndex(e.key,s.key,i.map(a=>a.key)),s[e.key]=i}getViewKeys(){return this.modelParser._getViewKeys({modelKey:this.key})}addBasicPropertiesAndReferences(e){const t=this.getBasicProperties(),s=this.getBasicReferences(),o=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e),n=o?.origin??"inline";o&&o.sourceColumns.length>0&&this.emitUnknownColumnErrors(e,o.sourceColumns,t,s,n);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const c=e.keyProperty??this.keyProperty,l=e.keyPropertySeparator??this.keyPropertySeparator??it,d=Ip(c,l),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const c of t){c.origin&&(i[c.key]=i[c.origin]);const l=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(l)&&(i=this.mapRawValueUsingValueMapping(i,c.key,l)),this.processBasicProperty(c,i,a,n)}for(const c of s){const l=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),l?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(c,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const h=this.getValueAsArray(f,c?.separator);Array.isArray(h)?this.processMultiValuedReference(c,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}})}}const u=String(a.key);a.key=u,this.data.set(u,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=Tt(o,{...n}),u=JSON.parse(a),c=new be;c.init({modelKey:s.model}),c.applyQuery(u,{mode:"set"}),u.projection||c.applyOptions({projection:{$:!1}});const l=c.getQuery();if(l.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(l);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>!o.to);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??it;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=No(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return setTimeout(()=>{e.addContainer(i)},0),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};setTimeout(()=>{e.addContainer(s)},0)}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const u=a.reference.key;let c;if(a.inverseKeys){if(a.reference.type==="multiValued"){const l=a.inverseKeys.get(n.key)||new Set;c=Array.from(l).map(d=>({key:d}))}else{const l=a.inverseKeys.get(n.key),d=l&&Array.from(l)[0]||null;d?c={key:d}:c=null}n[u]=c,this.indicesController.fillInverseIndex(u,o,n[u])}}const i=String(n.key);n.key=i,this.data.set(i,n)}}rebuildResolvedReferencesForAllItems(e){let t=this.getResolvedReferences();if(t.length===0||e&&(t=t.filter(o=>e.has(o.key)),t.length===0))return;const s=t.map(o=>{const n=this.modelParser.models.get(o.resolve.model);if(!n)return;const i=n.indicesController.getIndex(o.resolve.reference);return{reference:o,model:n,remoteData:[],inverseKeys:i}}).filter(o=>!!o);for(const o of this.data.values())for(const n of s){const i=n.reference.key;let a;if(n.inverseKeys){if(n.reference.type==="multiValued"){const u=n.inverseKeys.get(o.key)||new Set;a=Array.from(u).map(c=>({key:c}))}else{const u=n.inverseKeys.get(o.key),c=u?Array.from(u)[0]:null;c?a={key:c}:a=null}o[i]=a,this.indicesController.fillInverseIndex(i,o.key,o[i])}}}addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e){const t=this.getDerivedPropertiesForBasicAndDerivedReferences(),s=this.getExpressionProperties(),o=this.getDerivedReferences(),n=this.getGroupedReferences();for(const i of e.data){const a=this.data.get(String(i.key));o.length>0&&o.forEach(c=>{this.handleDerivedReferences(c,a)}),n.length>0&&n.forEach(c=>{this.handleGroupedReferences(c,a)}),t.length>0&&t.forEach(c=>{this.handleDerivedProperties(c,a)}),s.length>0&&s.forEach(c=>{const l=this.createExpressionContext(a),d=Tt(c.expression,l);a[c.key]=d});const u=String(a.key);a.key=u,this.data.set(u,a)}}handleDerivedProperties(e,t){const s=this.references.get(e.derive.localReference);if(s){const o=this.modelParser.models.get(s.model);o&&(s.type==="singleValued"?this.handleSingleValuedDerivedProperties(o,t,s,e):s.type==="multiValued"&&this.handleMultiValuedDerivedProperties(o,t,s,e))}}reRunDerivedPropertiesBasedOnResolves(e){const t=this.getDerivedProperties(),s=this.getDerivedReferences();for(const o of e.data){const n=this.data.get(String(o.key));s.forEach(a=>{this.handleDerivedReferences(a,n)}),t.forEach(a=>{const u=this.references.get(a.derive.localReference);if(u){const c=this.modelParser.models.get(u.model);c&&(u.type==="singleValued"?this.handleSingleValuedDerivedProperties(c,n,u,a):u.type==="multiValued"&&this.handleMultiValuedDerivedProperties(c,n,u,a))}});const i=String(n.key);n.key=i,this.data.set(i,n)}}handleSingleValuedDerivedProperties(e,t,s,o){const n=t[s.key];if(!n){delete t[o.key];return}const i=e?.getData().get(n.key);if(i){const a=i[o.derive.remoteProperty];typeof a<"u"&&(t[o.key]=a),o.index&&this.indicesController.fillInverseIndex(o.key,t.key,[a])}else delete t[o.key]}handleMultiValuedDerivedProperties(e,t,s,o){const n=t[s.key];let i;n?Array.isArray(n)?i=[...n]:n&&typeof n.key=="string"?i=[{key:n.key}]:i=[]:i=[];const a=o.derive?.separator||", ",u=i.map(l=>{const d=e?.getData().get(l.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let c;o.type.includes("Array<")?c=u:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?c=u.join(a):(o.type,c=u),t[o.key]=c}handleDerivedReferences(e,t){const s=this.references.get(e.derive.localReference);if(!s)return;const o=this.modelParser.models.get(s.model);if(!o)return;const n=t[s.key];if(!n)return;let i=[];if(Array.isArray(n)){const u=new Set;n.forEach(c=>{const l=o?.data.get(c.key);if(l){const d=l[e.derive.remoteReference];d&&(Array.isArray(d)?d.forEach(f=>{u.add(f.key)}):u.add(d.key))}}),i=Array.from(u.values())}else{const u=o?.data.get(n.key);if(u){const c=u[e.derive.remoteReference];c?Array.isArray(c)?i=c.map(l=>l.key):"key"in c&&(i=[c.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(u=>({key:u})),this.indicesController.fillInverseIndex(e.key,t.key,i),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const u of n){const c=i.get(u);c&&c.forEach(l=>a.add(l))}for(const u of a)e.groupBy.includeSelfInGroup?s.push({key:u}):t.key!==u&&s.push({key:u})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Op.REF_VALUE,{value:t,enumerable:!0,writable:!1,configurable:!1})}addBasicPropertiesAndReferencesPartial(e,t){const s=this.getBasicProperties().filter(i=>t.has(i.key)),o=this.getBasicReferences().filter(i=>t.has(i.key)),n=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e)?.origin??"inline";for(let i of e.data){let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const c of s){c.origin&&(i[c.key]=i[c.origin]);const l=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(l)&&(i=this.mapRawValueUsingValueMapping(i,c.key,l)),this.processBasicProperty(c,i,a,n)}for(const c of o){const l=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];typeof f=="number"&&(f=String(f));const h=a[c.key];if(!f){h&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),delete a[c.key],l?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.processSingleValuedReference(c,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const p=this.getValueAsArray(f,c?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(c.key,a.key,h),this.processMultiValuedReference(c,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}})}}const u=String(a.key);a.key=u,this.data.set(u,a)}}addQueryAndResolvedReferencesPartial(e,t){if(this.hasQueryReferences()){const s=this.getQueryReferences().filter(o=>t.has(o.key));for(let o of s){const n=JSON.stringify(o.query);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)continue;const u=Tt(n,{...i}),c=JSON.parse(u),l=new be;l.init({modelKey:o.model}),l.applyQuery(c,{mode:"set"}),c.projection||l.applyOptions({projection:{$:!1}});const d=l.getQuery();if(d.queries.length>0){const h=this.modelParser.dcuplInstance.query.execute(d);o.type==="singleValued"?h[0]&&(a[o.key]={key:h[0].key,_dcupl_ref_:"hit"}):o.type==="multiValued"&&(h.forEach(p=>{p._dcupl_ref_="hit"}),a[o.key]=h)}else o.type==="singleValued"?a[o.key]=null:o.type==="multiValued"&&(a[o.key]=[]);const f=String(a.key);a.key=f,this.data.set(f,a)}}}this.hasResolvedReferences()&&this.getResolvedReferences().filter(s=>t.has(s.key)).length>0&&this.rebuildResolvedReferencesForAllItems()}createExpressionContext(e){const t={...e};return this.references.forEach((s,o)=>{const n=e[o];if(!n)return;const i=this.modelParser.models.get(s.model);if(i)if(s.type==="singleValued"&&typeof n=="object"&&"key"in n){const a=i.getData().get(n.key);a&&(t[o]=this.createNestedContext(a,i))}else s.type==="multiValued"&&Array.isArray(n)&&(t[o]=n.map(a=>{const u=i.getData().get(a.key);return u?this.createNestedContext(u,i):null}).filter(Boolean))}),t}createNestedContext(e,t){const s={...e};return t.references.forEach((o,n)=>{const i=e[n];if(!i)return;const a=this.modelParser.models.get(o.model);if(a&&o.type==="singleValued"&&typeof i=="object"&&"key"in i){const u=a.getData().get(i.key);u&&(s[n]={...u})}}),s}addDerivedAndExpressionAttributesPartial(e,t){const s=this.getDerivedPropertiesForBasicAndDerivedReferences().filter(a=>t.has(a.key)),o=this.getDerivedReferences().filter(a=>t.has(a.key)),n=this.getGroupedReferences().filter(a=>t.has(a.key)),i=this.getExpressionProperties().filter(a=>t.has(a.key));for(const a of e.data){const u=this.data.get(String(a.key));if(!u)continue;o.forEach(l=>{this.handleDerivedReferences(l,u)}),n.forEach(l=>{this.handleGroupedReferences(l,u)}),s.forEach(l=>{this.handleDerivedProperties(l,u)}),i.forEach(l=>{const d=this.createExpressionContext(u),f=Tt(l.expression,d);u[l.key]=f});const c=String(u.key);u.key=c,this.data.set(c,u)}}reRunDerivedPropertiesBasedOnResolvesPartial(e,t){const s=this.getDerivedProperties().filter(n=>t.has(n.key)),o=this.getDerivedReferences().filter(n=>t.has(n.key));for(const n of e.data){const i=this.data.get(String(n.key));if(!i)continue;o.forEach(u=>{this.handleDerivedReferences(u,i)}),s.forEach(u=>{this.handleDerivedProperties(u,i)});const a=String(i.key);i.key=a,this.data.set(a,i)}}},Fp=class{changedAttributes;changedItems;deletedItems;modelFullReset;state="clean";constructor(){this.changedAttributes=new Map,this.changedItems=new Map,this.deletedItems=new Map,this.modelFullReset=new Set}recordDataChange(e){const t=e.model;if(!(!e.data||e.data.length===0))if(e.type==="set")this.state==="clean"?this.state="full-reset":this.state==="tracking"&&(this.state="full-reset",this.changedAttributes.delete(t),this.changedItems.delete(t),this.deletedItems.delete(t)),this.modelFullReset.add(t);else{if(this.modelFullReset.has(t))return;this.state==="clean"?this.state="tracking":this.state==="full-reset"&&(this.state="tracking"),e.type==="remove"?this.recordDeletedItems(t,e.data):this.recordChangedData(t,e.data)}}recordAttributeChange(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedAttributes.get(e).add(t)}recordChangedData(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedItems.has(e)||this.changedItems.set(e,new Set);const s=this.changedAttributes.get(e),o=this.changedItems.get(e);for(const n of t){n.key&&o.add(String(n.key));for(const i in n)i!=="key"&&s.add(i)}}recordDeletedItems(e,t){this.deletedItems.has(e)||this.deletedItems.set(e,new Set);const s=this.deletedItems.get(e);for(const o of t)o.key&&s.add(String(o.key))}getChangedAttributes(){return this.changedAttributes}getChangedAttributesForModel(e){return this.changedAttributes.get(e)}getChangedItems(e){return this.changedItems.get(e)||new Set}getDeletedItems(e){return this.deletedItems.get(e)||new Set}getModelsWithChanges(){const e=new Set;for(const t of this.changedAttributes.keys())e.add(t);for(const t of this.changedItems.keys())e.add(t);for(const t of this.deletedItems.keys())e.add(t);return Array.from(e)}getModelsWithFullReset(){return this.modelFullReset}hasFullReset(e){return this.modelFullReset.has(e)}hasChanges(){return this.changedAttributes.size>0||this.changedItems.size>0||this.deletedItems.size>0||this.modelFullReset.size>0}getTotalChangedItemCount(){let e=0;for(const t of this.changedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}},qp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(u=>u.type==="partial"),t=this.metrics.filter(u=>u.type==="full"),s=e.length>0?e.reduce((u,c)=>u+c.durationMs,0)/e.length:0,o=t.length>0?t.reduce((u,c)=>u+c.durationMs,0)/t.length:0,n=e.length>0?e.reduce((u,c)=>u+(c.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((u,c)=>u+(c.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((u,c)=>u+(o-c.durationMs),0):0;return{totalUpdates:this.metrics.length,partialUpdates:e.length,fullUpdates:t.length,avgPartialUpdateTime:s,avgFullUpdateTime:o,avgAttributesProcessed:n,avgModelsAffected:i,totalTimeSaved:a}}getLastUpdates(e=10){return this.metrics.slice(-e)}clear(){this.metrics=[]}getMetricsInRange(e,t){return this.metrics.filter(s=>s.timestamp>=e&&s.timestamp<=t)}};function Qp(r){return"query"in r}function jr(r){return"resolve"in r}function Bp(r){return"derive"in r}function Vp(r){return"groupBy"in r}var Gp=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,It=(r,e,t,s)=>{for(var o=Up(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Gp(e,t,o),o};let at=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new Fp;partialUpdateMetrics=new qp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Re.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear()}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new Kp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&xp(e,this.models).forEach(t=>{this.setError(t,e)})})}initDependencyGraph(){this.dependencyGraph=new Eo,this.models.forEach(t=>{this.dependencyGraph.addNode(t.key)}),this.models.forEach(t=>{t.getReferencesRelevantForDependencyGraph().forEach(s=>{t.key!==s.model&&(this.dependencyGraph.addNode(s.model),this.dependencyGraph.addDependency(t.key,s.model))})});const e=this.dependencyGraph.validateNoCycles();if(e.hasCycle){const t=e.path.join(" → ");throw this.log.error(`Circular dependency detected in model references: ${t}
6
6
  This will cause unpredictable update ordering. Please restructure your models to remove the circular dependency.`),new Error(`Circular dependency detected: ${t}
7
- Models cannot have circular references as this leads to unpredictable behavior during updates.`)}}buildAttributeDependencyGraph(){this.attributeDependencyGraph=new uf,this.models.forEach(e=>{const t=e.key;e.properties.forEach((s,o)=>{if(s.expression)this.processExpressionProperty(t,o,s.expression);else if(s.derive)this.processDerivedProperty(t,o,s.derive);else{const n={modelKey:t,attributeKey:o,type:"property",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}}),e.references.forEach((s,o)=>{if(Sp(s))this.processQueryReference(t,o,s.query);else if(Er(s))this.processResolvedReference(t,o,s.resolve);else if(Mp(s))this.processDerivedReference(t,o,s.derive);else if(Rp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
8
- These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=Dr(s);n.forEach(i=>{const a=i.name.split("."),u=this.models.get(e);if(!u)return;const c=a[0];if(u.properties.has(c)){const l={modelKey:e,attributeKey:c,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}else if(u.references.has(c)){const l={modelKey:e,attributeKey:c,type:"reference",processingStep:1};if(this.attributeDependencyGraph.addAttributeDependency(o,l),a.length>1){let d=u,f=e;for(let h=0;h<a.length-1;h++){const p=a[h],y=d.references.get(p);if(y){const v=this.models.get(y.model);if(v&&(d=v,f=y.model,h===a.length-2)){const g=a[a.length-1],k={modelKey:f,attributeKey:g,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,k)}}}}}})}processDerivedProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const u={modelKey:a.model,attributeKey:s.remoteProperty,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}}}processQueryReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);try{const n=JSON.stringify(s),{variables:i}=Dr(n);i.forEach(a=>{const u=a.name,c=this.models.get(e);if(c){if(c.properties.has(u)){const l={modelKey:e,attributeKey:u,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}else if(c.references.has(u)){const l={modelKey:e,attributeKey:u,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}})}catch{}}processResolvedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:s.model,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}processDerivedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const u={modelKey:a.model,attributeKey:s.remoteReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}}}processGroupedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}async update(){const e=performance.now(),t=this.shouldUsePartialUpdate();if(t.decision){const s=this.changeTracker.getModelsWithChanges().length,o=Array.from(this.changeTracker.getChangedAttributes().values()).reduce((a,u)=>a+u.size,0),n=this.changeTracker.getTotalChangedItemCount();await this.partialUpdate();const i=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"partial",durationMs:i,modelsAffected:s,attributesProcessed:o,itemsChanged:n,decisionReason:t.reason,timestamp:Date.now()})}else{await this.init();const s=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"full",durationMs:s,decisionReason:t.reason,timestamp:Date.now()})}}shouldUsePartialUpdate(){const e=this.dcuplInstance.initOptions.performance?.partialUpdates,t=e?.modelRatioThreshold??.5,s=e?.itemRatioThreshold??.5,o=e?.enableDetailedLogging??!1;if(!this.changeTracker.hasChanges())return o&&this.log.debug("Partial update decision: SKIP",{reason:"no_changes_detected"}),{decision:!1,reason:"no_changes_detected"};if(this.changeTracker.getModelsWithFullReset().size>0)return o&&this.log.debug("Partial update decision: FULL",{reason:"full_reset_detected"}),{decision:!1,reason:"full_reset_detected"};const n=Array.from(this.models.keys()).filter(l=>!l.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,u=0;for(const l of this.changeTracker.getModelsWithChanges()){const d=this.models.get(l);if(d){const f=d.getData().size;a+=f,u+=this.changeTracker.getChangedItems(l).size,u+=this.changeTracker.getDeletedItems(l).size}}const c=a>0?u/a:0;return i>t&&c>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:c.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${c.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:c.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${c.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(s=>!s.placeholderUid);for(const s of e)if(s.type==="remove"){const o=this.models.get(s.model);if(o){o.deleteDataEntries(s);for(const n of o.properties.values())this.changeTracker.recordAttributeChange(s.model,n.key);for(const n of o.references.values())this.changeTracker.recordAttributeChange(s.model,n.key)}}const t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(t)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return mo(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{vp(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=xr(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),u=this.mergeContainerSourceMetadata(i);u&&this.dcuplInstance.setContainerSourceMetadata(a,u),s.push(a)}else s.push(i[0])}return s}mergeContainers(e){let t;return e?.forEach(s=>{if(!t){if(s.type==="remove")return;t=new Map(s.data.map(o=>[o.key,o]));return}switch(s.type){case"upsert":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=st(n,o),t.set(o.key,n)}else t.set(o.key,o)});break;case"update":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=st(n,o),t.set(o.key,n)}});break;case"remove":s.data.forEach(o=>{t.delete(o.key)});break;case"set":t=new Map(s.data.map(o=>[o.key,o]));break;default:t=new Map(s.data.map(o=>[o.key,o]));break}}),{model:e[0].model,data:Array.from(t.values()),type:"set"}}mergeContainerSourceMetadata(e){let t;for(const s of e){const o=this.dcuplInstance.getContainerSourceMetadata(s),n=s.type??"set";if(n==="set")t=o?{columns:new Set(o.sourceColumns),samples:this.cloneCoercionSamples(o.coercionFailureSamples),origin:o.origin}:void 0;else if((n==="upsert"||n==="update")&&o){t||(t={columns:new Set,samples:{},origin:o.origin}),o.sourceColumns.forEach(i=>t.columns.add(i));for(const i of Object.keys(o.coercionFailureSamples)){const a=o.coercionFailureSamples[i],u=t.samples[i];u?u.count+=a.count:t.samples[i]={...a}}}}if(t)return{sourceColumns:Array.from(t.columns),coercionFailureSamples:t.samples,origin:t.origin}}cloneCoercionSamples(e){const t={};for(const s of Object.keys(e))t[s]={...e[s]};return t}async connectDataWithModels(e){try{this.dependencyGraph.order()}catch(s){this.log.warn("Your models have circular dependencies which might lead to errors. Please consider changing your models"),this.log.error("Dependency graph error",s)}const t=this.dependencyGraph.order({allowCycles:!0});e.sort((s,o)=>t.indexOf(s.model)-t.indexOf(o.model)),await this.handleDataContainer(e)}async connectDataWithModelsPartial(e){const t=this.dependencyGraph.order({allowCycles:!0});e.sort((i,a)=>t.indexOf(i.model)-t.indexOf(a.model));const s=[];for(const[i,a]of this.changeTracker.getChangedAttributes())for(const u of a){const c=this.attributeDependencyGraph.getAttributesForModel(i).find(l=>l.attributeKey===u);if(c)s.push(c);else{const l=this.models.get(i);if(l){const d=l.properties.get(u),f=l.references.get(u);(d||f)&&s.push({modelKey:i,attributeKey:u,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const u=this.changeTracker.getChangedItems(a.key),c=this.changeTracker.getChangedAttributes().get(a.key);u.size>0&&c&&(this.qualityController.cleanUpErrorsForItems(a,u,c),this.qualityController.validateItemsPartial(a,u,c).forEach(l=>{this.setError(l,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[u,c]of e.entries()){const l=c.get(2);l&&l.size>0&&(s.add(u),t.set(u,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const u of s){const c=this.models.get(u);if(!c)continue;const l=e.get(u)?.get(2);if(l)for(const d of l){const f=c.references.get(d);if(f&&Er(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Er(v)&&t.get(u).add(h)}}}}const o=[],n=new Set,i=new Set,a=u=>{if(i.has(u)||n.has(u))return;n.add(u);const c=t.get(u);if(c)for(const l of c)a(l);n.delete(u),i.add(u),o.push(u)};for(const u of s)a(u);return o}async processAttributesForStep(e,t,s){let o=this.dependencyGraph.order({allowCycles:!0});e===2&&(o=this.getResolvedReferenceProcessingOrder(t));for(const n of o){const i=t.get(n);if(!i)continue;const a=i.get(e);if(!a||a.size===0)continue;const u=this.models.get(n);if(!u)continue;const c=W(),l=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${l}:start`,context:c}),e===2)u.rebuildResolvedReferencesForAllItems(a);else{const d=s.find(f=>f.model===n);if(!d)continue;switch(e){case 1:u.addBasicPropertiesAndReferencesPartial(d,a);break;case 3:u.addDerivedAndExpressionAttributesPartial(d,a);break;case 4:u.reRunDerivedPropertiesBasedOnResolvesPartial(d,a);break}}this.cdRef.analyticsController.mark({name:`${l}:end`,context:c}),this.cdRef.analyticsController.measure({name:l,start:`${l}:start`,end:`${l}:end`,context:c,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??ot,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=Bo(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(u=>{this.setError(u,i)}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};Tt([b({scope:"global",type:"model_add",connectMessage:!0})],nt.prototype,"addModel"),Tt([b({scope:"global",type:"data_change",connectMessage:!0})],nt.prototype,"addData"),Tt([b({scope:"global",type:"view_add",connectMessage:!0})],nt.prototype,"addView"),Tt([b({scope:"global",type:"dcupl_handle_datacontainer"})],nt.prototype,"handleDataContainer");function Op(r,e){return Pe(e,function(t){return r[t]})}function Kp(r){return r==null?[]:Op(r,He(r))}var Fp=Math.max;function qp(r,e,t,s){r=ee(r)?r:Kp(r),t=t?bt(t):0;var o=r.length;return t<0&&(t=Fp(o+t,0)),Et(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&hs(r,e,t)>-1}var Qp=Object.defineProperty,Bp=Object.getOwnPropertyDescriptor,Uo=(r,e,t,s)=>{for(var o=Bp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Qp(e,t,o),o};let jr=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}options;key;modelKey;catalog;setup(e){const t=this.dcuplApi.modelParser.models.get(e.modelKey);if(!t)throw new Error(`Model with key ${e.modelKey} not found`);const s=this.getListItemKeys(e),o=this.getRelevantData(t,s),n=this.initIndicesController(s,t,o);this.catalog?this.catalog.filter.update(t,o,n):(this.catalog=new zf(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new Mt;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s)}else o=t.indicesController;return o}getListItemKeys(e){let t;return e.listItemKeys?t=e.listItemKeys:e.query&&(t=this.dcuplApi.query.execute(e.query).map(s=>s.key)),t}getRelevantData(e,t){const s=e.getData();return t?this.initFromItemKeys(s,t):s}init(e){this.options=se(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}on(e){return this.cdRef.on(e)}};Uo([b({scope:"list",type:"list_destroyed",connectMessage:!0})],jr.prototype,"_destroy"),Uo([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],jr.prototype,"update");var Vp=Object.defineProperty,Gp=Object.getOwnPropertyDescriptor,Up=(r,e,t,s)=>{for(var o=Gp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Vp(e,t,o),o};class No{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new wr;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new jr(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}}Up([b({scope:"global",type:"list_created",connectMessage:!0})],No.prototype,"create");let Np=class{constructor(e){this.scriptsController=e}enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Se.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const c of this.getModelErrors(o))c.attribute===i&&c.itemKey!=null&&(c.errorType==="UndefinedValue"||c.errorType==="WrongDataType")&&this.removeError(c.key);const u=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,u,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&u.errorType==="UndefinedValue"&&this.removeError(u.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(u=>u.errorType==="UndefinedValue"&&u.attribute!=null).map(u=>u.attribute));for(const u of n){const c=this.getGroupCount(o,u,"UndefinedValue");if(c>0&&c===t.data.length){for(const l of this.getModelErrors(o))l.attribute===u&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,u))}}const i=this.getModelErrors(o).filter(u=>u.errorType==="WrongDataType"&&u.errorGroup==="PropertyDataError"&&u.title==="Wrong Data Type"&&u.itemKey!=null),a=xr(i,"attribute");for(const u in a){const c=a[u];if(!c?.length)continue;const l=c[0].meta,d=e.properties.get(u)?.type??l?.expected??"unknown";for(const f of c)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,u,String(l?.rawValue??""),d,c.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),u=i?a.filter(c=>c.errorType===i):a;for(const c of u)if(c.itemKey&&t.has(c.itemKey)){if(n&&c.attribute&&!n.has(c.attribute))continue;this.removeError(c.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const u=a.quality?.validators;if(u)for(const c of t){const l=n.get(c);if(!l)continue;const d=l[a.key],f=this.validateAttribute(d,u,a.key);for(const h of f)h.model=e.key,h.itemKey=l.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(s=>s.model!=="$DcuplErrorTrackingErrors");const e=this.modelParser.models.get("$DcuplErrorTrackingErrors");e?.resetData(),e?.resetIndexMap(),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"});const t=this.modelParser.unprocessedData.find(s=>s.model==="$DcuplErrorTrackingErrors");t&&await this.modelParser.handleDataContainer([t])}initErrorTrackingModels(){this.modelParser?.addModel({key:"$DcuplErrorTrackingErrors",autoGenerateKey:!0,supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"title",type:"string",filter:!0},{key:"itemKey",type:"string",filter:!0},{key:"attribute",type:"string",filter:!0},{key:"description",type:"string"},{key:"meta",type:"json"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingType",data:[{key:"UndefinedAttribute"},{key:"InvalidValidator"},{key:"UndefinedValue"},{key:"NullValue"},{key:"WrongDataType"},{key:"MissingModel"},{key:"NonUniqueKey"},{key:"RemoteReferenceKeyNotFound"},{key:"InvalidModelDescription"},{key:"InvalidResource"},{key:"InvalidModelDefinition"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingGroup",data:[{key:"ReferenceDataError"},{key:"PropertyDataError"},{key:"DataContainerError"},{key:"ModelDescriptionError"},{key:"LoaderError"},{key:"ResourceError"},{key:"ModelDefinitionError"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingModel",supportsAutoCreation:!0,quality:{enabled:!1}})}initAnalyticsValues(){this.calculateTiming(),this.calculateSizes(),this.calculateErrorTrackingFacet(),this.calculateCounts(),this.calculateUnusedAttributes()}calculateUnusedAttributes(){this.values.unusedAttributes=[];const e=this.dcupl.models.keys();for(const t of e){const s=this.getUnusedAttributesFromModel(this.dcupl,t);for(const o of s)this.values.unusedAttributes?.push({model:t,attribute:o})}}calculateCounts(){this.values.counts={},this.values.counts.modelFiles=this.dcupl.modelParser.unprocessedModelDescriptions.size,this.values.counts.dataFiles=this.dcupl.modelParser.unprocessedData.length,this.values.counts.models=this.dcupl.models.keys().length;let e=0,t=0,s=0;this.dcupl.models.keys().forEach(o=>{const n=this.dcupl.modelParser.models.get(o);if(!n)return;const i=n?.getBasicProperties()||[],a=n?.getBasicReferences()||[],u=i.length+a.length;t+=u;const c=n.data?.size||0;e+=c,s+=u*c}),this.values.counts.rows=e,this.values.counts.attributes=t,this.values.counts.dataEntries=s}calculateTiming(){const e=this.dcupl.analyticsController.getByName("loader_processed");e&&e[0]&&(this.values.loading=e[0].value);const t=this.dcupl.analyticsController.getByName("dcupl_initialized");t&&t[0]&&(this.values.processing=t[0].value),this.values.startup=this.values.loading+this.values.processing}calculateSizes(){const e=this.calculateSizesForModels();this.values.sizes={},this.values.sizes.totalEncoded=e.reduce((t,s)=>t+s.encodedBodySize,0),this.values.sizes.totalDecoded=e.reduce((t,s)=>t+s.decodedBodySize,0),this.values.sizes.unusedDecoded=this.calculateUnusedData(),this.values.sizes.models=e.map(t=>({model:t.model,decodedBodySize:t.decodedBodySize,encodedBodySize:t.encodedBodySize})),this.values.sizes.models?.sort((t,s)=>(s.encodedBodySize||0)-(t.encodedBodySize||0))}calculateErrorTrackingFacet(){try{if(!this.enabled)return;const e=this.dcupl.lists.create({modelKey:"$DcuplErrorTrackingErrors"}),t=e.catalog.fn.facets({attribute:"errorType",calculateResults:!0,excludeUndefineds:!1,excludeUnresolved:!1,excludeZeros:!1});this.values.errors={},t&&(this.values.errors.size=e.catalog.fn.metadata().currentSize,this.values.errors.UndefinedValue=t.find(s=>s.key==="UndefinedValue")?.size||0,this.values.errors.UndefinedAttribute=t.find(s=>s.key==="UndefinedAttribute")?.size||0,this.values.errors.WrongDataType=t.find(s=>s.key==="WrongDataType")?.size||0,this.values.errors.MissingModel=t.find(s=>s.key==="MissingModel")?.size||0,this.values.errors.InvalidModelDescription=t.find(s=>s.key==="InvalidModelDescription")?.size||0,this.values.errors.RemoteReferenceKeyNotFound=t.find(s=>s.key==="RemoteReferenceKeyNotFound")?.size||0)}catch(e){this.log.error("Error calculating error tracking facet",e)}}calculateSizesForModels(){const e=this.dcupl.analyticsController.getByType("resource").filter(s=>s.value?.type==="data"),t=xr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const u=a.value.encodedBodySize;return i+u},0),n=t[s]?.reduce((i,a)=>{const u=a.value.decodedBodySize;return i+u},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(c=>c.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const u=e.modelParser.unprocessedData.find(c=>c.model===t)?.data||[];return this.getUnusedAttributes(u,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const u=a[t];if(n.has(u)){const c={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${u}" is not unique`};o.push(c),i&&delete a[t]}else n.add(u)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!ho(e,t.value))return{title:"Validator Error - EndsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not end with "${t.value}"`}}validateIncludes(e,t,s){if(e!=null&&!qp(e,t.value))return{title:"Validator Error - Includes",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not include "${t.value}"`}}validateMinLength(e,t,s){if(e!=null&&e.length<t.value)return{title:"Validator Error - Min Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is shorter than the minimum length of "${t.value}"`}}validateMaxLength(e,t,s){if(e!=null&&e.length>t.value)return{title:"Validator Error - Max Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is longer than the maximum length of "${t.value}"`}}validateEnum(e,t,s){if(!t.value.includes(e))return{title:"Validator Error - Enum",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is not in the enum values`}}validatePattern(e,t,s){if(e!=null)try{if(!new RegExp(t.value).test(e))return{title:"Validator Error - Pattern",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not match the pattern "${t.value}"`}}catch(o){this.log.error("Invalid pattern validation",o)}}};var zp=Object.defineProperty,Lp=Object.getOwnPropertyDescriptor,V=(r,e,t,s)=>{for(var o=Lp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&zp(e,t,o),o};let Q=class{cdRef=new wr;analyticsController=new af;containerSourceMetadata=new WeakMap;scriptController=new Bf;qualityController=new Np(this.scriptController);log=Se.child({prefix:"Dcupl"});modelParser=new nt(this.cdRef,this.qualityController,this);globalItemService=new Ko(this.modelParser,this.scriptController);cacheCtrl=new Po(!1);queryManager=new Qf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new me;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,cacheInvalidationThreshold:.7,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new No(this,this.cdRef);busy=!1;updateQueue=[];constructor(e){this.analyticsController.init(!!e?.analytics?.enabled),this.qualityController.dcupl=this,this.analyticsController.mark({name:"dcupl:constructor"}),this.initOptions=st({},this._defaultInitOptions,e),this.qualityController.enabled=this.initOptions.errorTracking?.enabled||this.initOptions.quality?.enabled||!1,this.qualityController.maxErrorsPerGroup=this.initOptions.quality?.maxErrorsPerGroup??1e3,this.modelParser.initOptions=Object.assign({},this.initOptions),this.cdRef._init({cdRefKey:"root",dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),this.cacheCtrl.enabled=!!this.initOptions.performance?.cache?.enabled}models={get:e=>this.modelParser.models.get(e)?.getModelDefinition(),set:e=>(this.modelParser.models.delete(e.key),this.modelParser.addModel(e)),update:e=>this.modelParser.addModel(e),remove:e=>{this.modelParser.models.delete(e)},keys:()=>this.modelParser._getModelKeys()};views={get:e=>this.modelParser.views.get(e),keys:e=>this.modelParser._getViewKeys(e),set:e=>this.modelParser.addView(e)};data={update:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"update",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},upsert:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"upsert",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},set:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"set",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},remove:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"remove",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},reset:e=>{e.model&&(this.modelParser.models.get(e.model)?.resetData(),this.modelParser.models.get(e.model)?.resetIndexMap())},apply:e=>this.modelParser.addData(e)};loaders={add:(e,t)=>{this.addLoader(e,t)},remove:e=>{this.removeLoader(e)},get:e=>this._loaders.get(e)};scripts={set:(e,t)=>{this.scriptController.setScript(e,t)},remove:e=>{this.scriptController.removeScript(e)},get:e=>{this.scriptController.getScript(e)},keys:()=>this.scriptController.keys(),execute:(e,t)=>{const s={dcupl:this,options:t};return this.scriptController.executeScript(e,"script",s)},executeAsync:(e,t)=>new Promise((s,o)=>{const n={dcupl:this,options:t,resolve:s,reject:o};return this.scriptController.executeScript(e,"async_script",n)})};fn={pivot:e=>this._pivot(e),aggregate:e=>this._aggregate(e),suggest:e=>this._suggest(e),groupBy:e=>this._groupBy(e),facets:e=>this._facets(e),metadata:e=>this._metadata(e)};_pivot(e){return this.getFnList(e).catalog.fn.pivot(e.options)}_aggregate(e){return this.getFnList(e).catalog.fn.aggregate(e.options)}_suggest(e){return this.getFnList(e).catalog.fn.suggest(e.options)}_groupBy(e){return this.getFnList(e).catalog.fn.groupBy(e.options)}_facets(e){return this.getFnList(e).catalog.fn.facets(e.options)}_metadata(e){return this.getFnList(e).catalog.fn.metadata()}registerContainer(e){this.modelParser.addData(e)}updateRegisteredContainer(e,t){const s=this.modelParser.unprocessedData.findIndex(o=>o.placeholderUid===e.placeholderUid);s>-1&&(delete e.placeholderUid,this.modelParser.unprocessedData[s]=e,t&&this.containerSourceMetadata.set(e,t))}removeRegisteredContainer(e){const t=this.modelParser.unprocessedData.findIndex(s=>s.placeholderUid===e.placeholderUid);t>-1&&this.modelParser.unprocessedData.splice(t,1)}getContainerSourceMetadata(e){return this.containerSourceMetadata.get(e)}setContainerSourceMetadata(e,t){this.containerSourceMetadata.set(e,t)}getFnList(e){let t=this.lists.get(`__global_list__${e.modelKey}`);return t||(t=this.lists.create({modelKey:e.modelKey,listKey:`__global_list__${e.modelKey}`})),e.query?t.catalog.query.apply(e.query,{mode:"set"}):t.catalog.query.reset(),t}getAffectedModels(e){const t=new Set;for(const o of e.keys())t.add(o);const s=this.modelParser.dependencyGraph;if(s)for(const o of e.keys())this.getDownstreamDependencies(o,s).forEach(n=>t.add(n));return Array.from(t)}getDownstreamDependencies(e,t){const s=new Set,o=new Set,n=i=>{if(!o.has(i)){o.add(i);for(const[a,u]of Object.entries(t.dependencies||{}))Array.isArray(u)&&u.includes(i)&&(s.add(a),n(a))}};return n(e),s}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;for(const o of this.lists.getAll()){if(!this.shouldAutoUpdateList(o,t)){s&&this.log.debug("List skipped (auto-update disabled)",{listKey:o.key,modelKey:o.modelKey});continue}e?this.isListAffectedByChanges(o,e.affectedModels)?(s&&this.log.debug("List auto-updating (affected by changes)",{listKey:o.key,modelKey:o.modelKey,affectedModels:e.affectedModels}),o.update()):s&&this.log.debug("List skipped (not affected)",{listKey:o.key,modelKey:o.modelKey}):(s&&this.log.debug("List auto-updating (full update)",{listKey:o.key,modelKey:o.modelKey}),o.update())}}isListAffectedByChanges(e,t){const s=e.modelKey;return t.includes(s)}shouldAutoUpdateList(e,t){return e.key.startsWith("__global_list__")?!0:t!==void 0?t:e.options.autoUpdate!==void 0?e.options.autoUpdate:this.initOptions.performance?.autoUpdateLists?.enabled??!1}query={one:e=>this.getItem(e),many:e=>this._getManyItems(e),execute:e=>this.executeQuery(e),generate:(e,t)=>(this.rootQueryBuilder.init({modelKey:e}),this.rootQueryBuilder.applyQuery(t)),registerCustomOperator:(e,t)=>{this.queryManager.registerCustomOperator(e,t)}};on(e){return this.cdRef.on(e)}async init(){try{return await this.performUpdate(()=>this.modelParser.init()),this.cacheCtrl.clear(),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=this.modelParser.changeTracker,s=t.hasChanges(),o=s?new Map(t.getChangedAttributes()):null,n=s?new Set(t.getModelsWithFullReset()):null,i=this.cacheCtrl.getStats();if(await this.performUpdate(()=>this.modelParser.update()),s&&this.cacheCtrl.enabled&&o){const a=this.modelParser.getTotalItemCount(),u=t.getTotalChangedItemCount(),c=a>0?u/a:0,l=this.initOptions.performance?.partialUpdates?.cacheInvalidationThreshold??.7,d=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;n&&n.size>0?(d&&this.log.debug("Cache invalidation: Full clear",{reason:"full_reset_detected"}),this.cacheCtrl.clear()):c>l?(d&&this.log.debug("Cache invalidation: Full clear",{reason:"high_item_ratio",ratio:c.toFixed(2),threshold:l,changedItems:u,totalItems:a}),this.cacheCtrl.clear()):(d&&this.log.debug("Cache invalidation: Selective",{changedItems:u,totalItems:a,ratio:c.toFixed(2)}),this.cacheCtrl.invalidateByDependencies(o))}else(this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1)&&this.log.debug("Cache invalidation: Full clear",{reason:"full_update"}),this.cacheCtrl.clear();if(this.cacheCtrl.getStats){const a=this.cacheCtrl.getStats(),u=this.modelParser.partialUpdateMetrics.getLastUpdates(1);if(u.length>0&&u[0]){const c=u[0];c.cacheStats={entriesInvalidated:i.totalEntries-a.totalEntries,totalEntries:i.totalEntries}}}if(s&&o){const a={isPartialUpdate:!0,changedModels:Array.from(o.keys()),changedAttributes:o,affectedModels:this.getAffectedModels(o)};this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[a]}),this.updateFnLists(a,e?.autoUpdateLists)}else this.updateFnLists(null,e?.autoUpdateLists);return!0}catch(t){return this.log.error("Update failed",t),!1}}destroy(){try{this.lists.destroy(),this._loaders.forEach(e=>{e.destroy()})}catch{}}getItem(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getItem(e.itemKey,t.data,t,e)}_getManyItems(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getManyItems(e.itemKeys,t.data,t,e)}executeQuery(e){if(!e?.modelKey)throw new Error("No modelKey provided");return this.getFnList({modelKey:e?.modelKey}).catalog.query.execute(e)}addLoader(e,t){const s=ye.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new wr;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}async performUpdate(e){if(this.busy)return new Promise(t=>{this.updateQueue.push(()=>e().then(t))});try{this.busy=!0,await e()}finally{this.busy=!1,this.processQueue()}}async processQueue(){if(this.updateQueue.length>0){const e=this.updateQueue.shift();e&&(await e(),this.processQueue())}}};V([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),V([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),V([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),V([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),V([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),V([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),V([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),V([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),V([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),V([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),V([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),V([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),V([b({scope:"global",type:"loader_removed",connectMessage:!0})],Q.prototype,"removeLoader");let Wp=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var zo=typeof global=="object"&&global&&global.Object===Object&&global,Hp=typeof self=="object"&&self&&self.Object===Object&&self,Z=zo||Hp||Function("return this")(),ue=Z.Symbol,Lo=Object.prototype,Jp=Lo.hasOwnProperty,Zp=Lo.toString,it=ue?ue.toStringTag:void 0;function Xp(r){var e=Jp.call(r,it),t=r[it];try{r[it]=void 0;var s=!0}catch{}var o=Zp.call(r);return s&&(e?r[it]=t:delete r[it]),o}var Yp=Object.prototype,eh=Yp.toString;function th(r){return eh.call(r)}var rh="[object Null]",sh="[object Undefined]",Wo=ue?ue.toStringTag:void 0;function Re(r){return r==null?r===void 0?sh:rh:Wo&&Wo in Object(r)?Xp(r):th(r)}function Te(r){return r!=null&&typeof r=="object"}var oh="[object Symbol]";function Sr(r){return typeof r=="symbol"||Te(r)&&Re(r)==oh}function nh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Ie=Array.isArray,Ho=ue?ue.prototype:void 0,Jo=Ho?Ho.toString:void 0;function Zo(r){if(typeof r=="string")return r;if(Ie(r))return nh(r,Zo)+"";if(Sr(r))return Jo?Jo.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function It(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ih="[object AsyncFunction]",ah="[object Function]",uh="[object GeneratorFunction]",ch="[object Proxy]";function Xo(r){if(!It(r))return!1;var e=Re(r);return e==ah||e==uh||e==ih||e==ch}var Mr=Z["__core-js_shared__"],Yo=(function(){var r=/[^.]+$/.exec(Mr&&Mr.keys&&Mr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function lh(r){return!!Yo&&Yo in r}var dh=Function.prototype,fh=dh.toString;function ve(r){if(r!=null){try{return fh.call(r)}catch{}try{return r+""}catch{}}return""}var ph=/[\\^$.*+?()[\]{}|]/g,hh=/^\[object .+?Constructor\]$/,yh=Function.prototype,gh=Object.prototype,mh=yh.toString,vh=gh.hasOwnProperty,bh=RegExp("^"+mh.call(vh).replace(ph,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function kh(r){if(!It(r)||lh(r))return!1;var e=Xo(r)?bh:hh;return e.test(ve(r))}function wh(r,e){return r?.[e]}function be(r,e){var t=wh(r,e);return kh(t)?t:void 0}var Rr=be(Z,"WeakMap"),en=Object.create,Ah=(function(){function r(){}return function(e){if(!It(e))return{};if(en)return en(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),tn=(function(){try{var r=be(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Ch(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var $h=9007199254740991,Dh=/^(?:0|[1-9]\d*)$/;function _h(r,e){var t=typeof r;return e=e??$h,!!e&&(t=="number"||t!="symbol"&&Dh.test(r))&&r>-1&&r%1==0&&r<e}function Ph(r,e,t){e=="__proto__"&&tn?tn(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function rn(r,e){return r===e||r!==r&&e!==e}var xh=Object.prototype,Eh=xh.hasOwnProperty;function jh(r,e,t){var s=r[e];(!(Eh.call(r,e)&&rn(s,t))||t===void 0&&!(e in r))&&Ph(r,e,t)}var Sh=9007199254740991;function sn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Sh}function Mh(r){return r!=null&&sn(r.length)&&!Xo(r)}var Rh=Object.prototype;function on(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Rh;return r===t}function Th(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Ih="[object Arguments]";function nn(r){return Te(r)&&Re(r)==Ih}var an=Object.prototype,Oh=an.hasOwnProperty,Kh=an.propertyIsEnumerable,Fh=nn((function(){return arguments})())?nn:function(r){return Te(r)&&Oh.call(r,"callee")&&!Kh.call(r,"callee")};function qh(){return!1}var un=typeof exports=="object"&&exports&&!exports.nodeType&&exports,cn=un&&typeof module=="object"&&module&&!module.nodeType&&module,Qh=cn&&cn.exports===un,ln=Qh?Z.Buffer:void 0,Bh=ln?ln.isBuffer:void 0,dn=Bh||qh,Vh="[object Arguments]",Gh="[object Array]",Uh="[object Boolean]",Nh="[object Date]",zh="[object Error]",Lh="[object Function]",Wh="[object Map]",Hh="[object Number]",Jh="[object Object]",Zh="[object RegExp]",Xh="[object Set]",Yh="[object String]",ey="[object WeakMap]",ty="[object ArrayBuffer]",ry="[object DataView]",sy="[object Float32Array]",oy="[object Float64Array]",ny="[object Int8Array]",iy="[object Int16Array]",ay="[object Int32Array]",uy="[object Uint8Array]",cy="[object Uint8ClampedArray]",ly="[object Uint16Array]",dy="[object Uint32Array]",D={};D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[uy]=D[cy]=D[ly]=D[dy]=!0,D[Vh]=D[Gh]=D[ty]=D[Uh]=D[ry]=D[Nh]=D[zh]=D[Lh]=D[Wh]=D[Hh]=D[Jh]=D[Zh]=D[Xh]=D[Yh]=D[ey]=!1;function fy(r){return Te(r)&&sn(r.length)&&!!D[Re(r)]}function Tr(r){return function(e){return r(e)}}var fn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,at=fn&&typeof module=="object"&&module&&!module.nodeType&&module,py=at&&at.exports===fn,Ir=py&&zo.process,Oe=(function(){try{var r=at&&at.require&&at.require("util").types;return r||Ir&&Ir.binding&&Ir.binding("util")}catch{}})(),pn=Oe&&Oe.isTypedArray,hy=pn?Tr(pn):fy,yy=Object.prototype,gy=yy.hasOwnProperty;function my(r,e){var t=Ie(r),s=!t&&Fh(r),o=!t&&!s&&dn(r),n=!t&&!s&&!o&&hy(r),i=t||s||o||n,a=i?Th(r.length,String):[],u=a.length;for(var c in r)gy.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||_h(c,u)))&&a.push(c);return a}function hn(r,e){return function(t){return r(e(t))}}var vy=hn(Object.keys,Object),by=Object.prototype,ky=by.hasOwnProperty;function wy(r){if(!on(r))return vy(r);var e=[];for(var t in Object(r))ky.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ay(r){return Mh(r)?my(r):wy(r)}var Cy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$y=/^\w*$/;function Dy(r,e){if(Ie(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Sr(r)?!0:$y.test(r)||!Cy.test(r)||e!=null&&r in Object(e)}var ut=be(Object,"create");function _y(){this.__data__=ut?ut(null):{},this.size=0}function Py(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var xy="__lodash_hash_undefined__",Ey=Object.prototype,jy=Ey.hasOwnProperty;function Sy(r){var e=this.__data__;if(ut){var t=e[r];return t===xy?void 0:t}return jy.call(e,r)?e[r]:void 0}var My=Object.prototype,Ry=My.hasOwnProperty;function Ty(r){var e=this.__data__;return ut?e[r]!==void 0:Ry.call(e,r)}var Iy="__lodash_hash_undefined__";function Oy(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=ut&&e===void 0?Iy:e,this}function ke(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ke.prototype.clear=_y,ke.prototype.delete=Py,ke.prototype.get=Sy,ke.prototype.has=Ty,ke.prototype.set=Oy;function Ky(){this.__data__=[],this.size=0}function Ot(r,e){for(var t=r.length;t--;)if(rn(r[t][0],e))return t;return-1}var Fy=Array.prototype,qy=Fy.splice;function Qy(r){var e=this.__data__,t=Ot(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():qy.call(e,t,1),--this.size,!0}function By(r){var e=this.__data__,t=Ot(e,r);return t<0?void 0:e[t][1]}function Vy(r){return Ot(this.__data__,r)>-1}function Gy(r,e){var t=this.__data__,s=Ot(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function oe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}oe.prototype.clear=Ky,oe.prototype.delete=Qy,oe.prototype.get=By,oe.prototype.has=Vy,oe.prototype.set=Gy;var ct=be(Z,"Map");function Uy(){this.size=0,this.__data__={hash:new ke,map:new(ct||oe),string:new ke}}function Ny(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Kt(r,e){var t=r.__data__;return Ny(e)?t[typeof e=="string"?"string":"hash"]:t.map}function zy(r){var e=Kt(this,r).delete(r);return this.size-=e?1:0,e}function Ly(r){return Kt(this,r).get(r)}function Wy(r){return Kt(this,r).has(r)}function Hy(r,e){var t=Kt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ce.prototype.clear=Uy,ce.prototype.delete=zy,ce.prototype.get=Ly,ce.prototype.has=Wy,ce.prototype.set=Hy;var Jy="Expected a function";function Or(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Jy);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(Or.Cache||ce),t}Or.Cache=ce;var Zy=500;function Xy(r){var e=Or(r,function(s){return t.size===Zy&&t.clear(),s}),t=e.cache;return e}var Yy=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,eg=/\\(\\)?/g,tg=Xy(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Yy,function(t,s,o,n){e.push(o?n.replace(eg,"$1"):s||t)}),e});function rg(r){return r==null?"":Zo(r)}function sg(r,e){return Ie(r)?r:Dy(r,e)?[r]:tg(rg(r))}function og(r){if(typeof r=="string"||Sr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ng(r,e){e=sg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[og(e[t++])];return t&&t==s?r:void 0}function ig(r,e,t){var s=r==null?void 0:ng(r,e);return s===void 0?t:s}function ag(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var ug=hn(Object.getPrototypeOf,Object);function cg(){this.__data__=new oe,this.size=0}function lg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function dg(r){return this.__data__.get(r)}function fg(r){return this.__data__.has(r)}var pg=200;function hg(r,e){var t=this.__data__;if(t instanceof oe){var s=t.__data__;if(!ct||s.length<pg-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new ce(s)}return t.set(r,e),this.size=t.size,this}function Ke(r){var e=this.__data__=new oe(r);this.size=e.size}Ke.prototype.clear=cg,Ke.prototype.delete=lg,Ke.prototype.get=dg,Ke.prototype.has=fg,Ke.prototype.set=hg;var yn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gn=yn&&typeof module=="object"&&module&&!module.nodeType&&module,yg=gn&&gn.exports===yn,mn=yg?Z.Buffer:void 0;mn&&mn.allocUnsafe;function gg(r,e){return r.slice()}function mg(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function vg(){return[]}var bg=Object.prototype,kg=bg.propertyIsEnumerable,vn=Object.getOwnPropertySymbols,wg=vn?function(r){return r==null?[]:(r=Object(r),mg(vn(r),function(e){return kg.call(r,e)}))}:vg;function Ag(r,e,t){var s=e(r);return Ie(r)?s:ag(s,t(r))}function Cg(r){return Ag(r,Ay,wg)}var Kr=be(Z,"DataView"),Fr=be(Z,"Promise"),qr=be(Z,"Set"),bn="[object Map]",$g="[object Object]",kn="[object Promise]",wn="[object Set]",An="[object WeakMap]",Cn="[object DataView]",Dg=ve(Kr),_g=ve(ct),Pg=ve(Fr),xg=ve(qr),Eg=ve(Rr),ne=Re;(Kr&&ne(new Kr(new ArrayBuffer(1)))!=Cn||ct&&ne(new ct)!=bn||Fr&&ne(Fr.resolve())!=kn||qr&&ne(new qr)!=wn||Rr&&ne(new Rr)!=An)&&(ne=function(r){var e=Re(r),t=e==$g?r.constructor:void 0,s=t?ve(t):"";if(s)switch(s){case Dg:return Cn;case _g:return bn;case Pg:return kn;case xg:return wn;case Eg:return An}return e});var jg=Object.prototype,Sg=jg.hasOwnProperty;function Mg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Sg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var $n=Z.Uint8Array;function Qr(r){var e=new r.constructor(r.byteLength);return new $n(e).set(new $n(r)),e}function Rg(r,e){var t=Qr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Tg=/\w*$/;function Ig(r){var e=new r.constructor(r.source,Tg.exec(r));return e.lastIndex=r.lastIndex,e}var Dn=ue?ue.prototype:void 0,_n=Dn?Dn.valueOf:void 0;function Og(r){return _n?Object(_n.call(r)):{}}function Kg(r,e){var t=Qr(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Fg="[object Boolean]",qg="[object Date]",Qg="[object Map]",Bg="[object Number]",Vg="[object RegExp]",Gg="[object Set]",Ug="[object String]",Ng="[object Symbol]",zg="[object ArrayBuffer]",Lg="[object DataView]",Wg="[object Float32Array]",Hg="[object Float64Array]",Jg="[object Int8Array]",Zg="[object Int16Array]",Xg="[object Int32Array]",Yg="[object Uint8Array]",em="[object Uint8ClampedArray]",tm="[object Uint16Array]",rm="[object Uint32Array]";function sm(r,e,t){var s=r.constructor;switch(e){case zg:return Qr(r);case Fg:case qg:return new s(+r);case Lg:return Rg(r);case Wg:case Hg:case Jg:case Zg:case Xg:case Yg:case em:case tm:case rm:return Kg(r);case Qg:return new s;case Bg:case Ug:return new s(r);case Vg:return Ig(r);case Gg:return new s;case Ng:return Og(r)}}function om(r){return typeof r.constructor=="function"&&!on(r)?Ah(ug(r)):{}}var nm="[object Map]";function im(r){return Te(r)&&ne(r)==nm}var Pn=Oe&&Oe.isMap,am=Pn?Tr(Pn):im,um="[object Set]";function cm(r){return Te(r)&&ne(r)==um}var xn=Oe&&Oe.isSet,lm=xn?Tr(xn):cm,En="[object Arguments]",dm="[object Array]",fm="[object Boolean]",pm="[object Date]",hm="[object Error]",jn="[object Function]",ym="[object GeneratorFunction]",gm="[object Map]",mm="[object Number]",Sn="[object Object]",vm="[object RegExp]",bm="[object Set]",km="[object String]",wm="[object Symbol]",Am="[object WeakMap]",Cm="[object ArrayBuffer]",$m="[object DataView]",Dm="[object Float32Array]",_m="[object Float64Array]",Pm="[object Int8Array]",xm="[object Int16Array]",Em="[object Int32Array]",jm="[object Uint8Array]",Sm="[object Uint8ClampedArray]",Mm="[object Uint16Array]",Rm="[object Uint32Array]",A={};A[En]=A[dm]=A[Cm]=A[$m]=A[fm]=A[pm]=A[Dm]=A[_m]=A[Pm]=A[xm]=A[Em]=A[gm]=A[mm]=A[Sn]=A[vm]=A[bm]=A[km]=A[wm]=A[jm]=A[Sm]=A[Mm]=A[Rm]=!0,A[hm]=A[jn]=A[Am]=!1;function Ft(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!It(r))return r;var a=Ie(r);if(a)i=Mg(r);else{var u=ne(r),c=u==jn||u==ym;if(dn(r))return gg(r);if(u==Sn||u==En||c&&!o)i=c?{}:om(r);else{if(!A[u])return o?r:{};i=sm(r,u)}}n||(n=new Ke);var l=n.get(r);if(l)return l;n.set(r,i),lm(r)?r.forEach(function(h){i.add(Ft(h,e,t,h,r,n))}):am(r)&&r.forEach(function(h,p){i.set(p,Ft(h,e,t,p,r,n))});var d=Cg,f=a?void 0:d(r);return Ch(f||r,function(h,p){f&&(p=h,h=r[p]),jh(i,p,Ft(h,e,t,p,r,n))}),i}var Tm=1,Im=4;function Om(r){return Ft(r,Tm|Im)}const F={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}},Mn={silent:0,error:1,warn:2,info:3,debug:4};class S{config;static globalConfig={};constructor(e={}){this.config={level:e.level??S.globalConfig.level??this.getDefaultLevel(),format:e.format??S.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??S.globalConfig.onLog,onTrackError:e.onTrackError??S.globalConfig.onTrackError}}static setGlobalConfig(e){S.globalConfig={...S.globalConfig,...e}}static getGlobalConfig(){return{...S.globalConfig}}static setModuleLevel(e,t){S.globalConfig.onLog||(S.globalConfig.onLog=void 0),S._moduleOverrides||(S._moduleOverrides=new Map),S._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!S._moduleOverrides))return S._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=S.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Mn[e]<=Mn[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new S(t)}configure(e){Object.assign(this.config,e)}}const Br=new S;function Vr(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}let Km=class{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=F.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}};const Rn=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):Om(r):r,Tn=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Rn(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=F.now(),c=u-s,l=Math.round(c*1e3)/1e3;t.duration=l,t.start=s,t.end=u;const d={duration:t.duration};return t.modelKey&&(d.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(d.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},In=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=F.now(),a=this.cdRef,u=Rn(r,!0);u.key||(a.increaseCounter(),u.key=a.getCounter());const c=Vr();a.analyticsController.mark({name:`${u.type}:start`,context:c});const l=this.model?.key;!u.originCdRefKey&&a.key&&(u.originCdRefKey=a.key),l&&(u.modelKey=l);const d=o.apply(this,n);return u.method=t,u.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Tn(this,a,u,i,c,f)):Tn(this,a,u,i,c,d)},s},qt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>ig(e,s.trim(),""))):"";let Fm=class{log=Br.child({prefix:"DcuplCsvParser"});parse(r,e={}){const{quoteChar:t=e.quoteChar||'"',escapeChar:s=e.escapeChar||'"',comments:o=e.comments||void 0,dynamicTyping:n=!1,header:i=!0,skipEmptyLines:a=!0,transformHeader:u,transform:c}=e,l=[],d=i?[]:null;let f=r.length,h=[],p="",y=!1,v=!0,g=0;if(a){for(;g<f&&(r[g]===`
7
+ Models cannot have circular references as this leads to unpredictable behavior during updates.`)}}buildAttributeDependencyGraph(){this.attributeDependencyGraph=new mf,this.models.forEach(e=>{const t=e.key;e.properties.forEach((s,o)=>{if(s.expression)this.processExpressionProperty(t,o,s.expression);else if(s.derive)this.processDerivedProperty(t,o,s.derive);else{const n={modelKey:t,attributeKey:o,type:"property",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}}),e.references.forEach((s,o)=>{if(Qp(s))this.processQueryReference(t,o,s.query);else if(jr(s))this.processResolvedReference(t,o,s.resolve);else if(Bp(s))this.processDerivedReference(t,o,s.derive);else if(Vp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
8
+ These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=_r(s);n.forEach(i=>{const a=i.name.split("."),u=this.models.get(e);if(!u)return;const c=a[0];if(u.properties.has(c)){const l={modelKey:e,attributeKey:c,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}else if(u.references.has(c)){const l={modelKey:e,attributeKey:c,type:"reference",processingStep:1};if(this.attributeDependencyGraph.addAttributeDependency(o,l),a.length>1){let d=u,f=e;for(let h=0;h<a.length-1;h++){const p=a[h],y=d.references.get(p);if(y){const v=this.models.get(y.model);if(v&&(d=v,f=y.model,h===a.length-2)){const g=a[a.length-1],k={modelKey:f,attributeKey:g,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,k)}}}}}})}processDerivedProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const u={modelKey:a.model,attributeKey:s.remoteProperty,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}}}processQueryReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);try{const n=JSON.stringify(s),{variables:i}=_r(n);i.forEach(a=>{const u=a.name,c=this.models.get(e);if(c){if(c.properties.has(u)){const l={modelKey:e,attributeKey:u,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}else if(c.references.has(u)){const l={modelKey:e,attributeKey:u,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}})}catch{}}processResolvedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:s.model,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}processDerivedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const u={modelKey:a.model,attributeKey:s.remoteReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}}}processGroupedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}async update(){const e=performance.now(),t=this.shouldUsePartialUpdate();if(t.decision){const s=this.changeTracker.getModelsWithChanges().length,o=Array.from(this.changeTracker.getChangedAttributes().values()).reduce((a,u)=>a+u.size,0),n=this.changeTracker.getTotalChangedItemCount();await this.partialUpdate();const i=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"partial",durationMs:i,modelsAffected:s,attributesProcessed:o,itemsChanged:n,decisionReason:t.reason,timestamp:Date.now()})}else{await this.init();const s=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"full",durationMs:s,decisionReason:t.reason,timestamp:Date.now()})}}shouldUsePartialUpdate(){const e=this.dcuplInstance.initOptions.performance?.partialUpdates,t=e?.modelRatioThreshold??.5,s=e?.itemRatioThreshold??.5,o=e?.enableDetailedLogging??!1;if(!this.changeTracker.hasChanges())return o&&this.log.debug("Partial update decision: SKIP",{reason:"no_changes_detected"}),{decision:!1,reason:"no_changes_detected"};if(this.changeTracker.getModelsWithFullReset().size>0)return o&&this.log.debug("Partial update decision: FULL",{reason:"full_reset_detected"}),{decision:!1,reason:"full_reset_detected"};const n=Array.from(this.models.keys()).filter(l=>!l.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,u=0;for(const l of this.changeTracker.getModelsWithChanges()){const d=this.models.get(l);if(d){const f=d.getData().size;a+=f,u+=this.changeTracker.getChangedItems(l).size,u+=this.changeTracker.getDeletedItems(l).size}}const c=a>0?u/a:0;return i>t&&c>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:c.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${c.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:c.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${c.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(s=>!s.placeholderUid);for(const s of e)if(s.type==="remove"){const o=this.models.get(s.model);if(o){o.deleteDataEntries(s);for(const n of o.properties.values())this.changeTracker.recordAttributeChange(s.model,n.key);for(const n of o.references.values())this.changeTracker.recordAttributeChange(s.model,n.key)}}const t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(t)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return wo(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{Pp(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=Er(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),u=this.mergeContainerSourceMetadata(i);u&&this.dcuplInstance.setContainerSourceMetadata(a,u),s.push(a)}else s.push(i[0])}return s}mergeContainers(e){let t;return e?.forEach(s=>{if(!t){if(s.type==="remove")return;t=new Map(s.data.map(o=>[o.key,o]));return}switch(s.type){case"upsert":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=nt(n,o),t.set(o.key,n)}else t.set(o.key,o)});break;case"update":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=nt(n,o),t.set(o.key,n)}});break;case"remove":s.data.forEach(o=>{t.delete(o.key)});break;case"set":t=new Map(s.data.map(o=>[o.key,o]));break;default:t=new Map(s.data.map(o=>[o.key,o]));break}}),{model:e[0].model,data:Array.from(t.values()),type:"set"}}mergeContainerSourceMetadata(e){let t;for(const s of e){const o=this.dcuplInstance.getContainerSourceMetadata(s),n=s.type??"set";if(n==="set")t=o?{columns:new Set(o.sourceColumns),samples:this.cloneCoercionSamples(o.coercionFailureSamples),origin:o.origin}:void 0;else if((n==="upsert"||n==="update")&&o){t||(t={columns:new Set,samples:{},origin:o.origin}),o.sourceColumns.forEach(i=>t.columns.add(i));for(const i of Object.keys(o.coercionFailureSamples)){const a=o.coercionFailureSamples[i],u=t.samples[i];u?u.count+=a.count:t.samples[i]={...a}}}}if(t)return{sourceColumns:Array.from(t.columns),coercionFailureSamples:t.samples,origin:t.origin}}cloneCoercionSamples(e){const t={};for(const s of Object.keys(e))t[s]={...e[s]};return t}async connectDataWithModels(e){try{this.dependencyGraph.order()}catch(s){this.log.warn("Your models have circular dependencies which might lead to errors. Please consider changing your models"),this.log.error("Dependency graph error",s)}const t=this.dependencyGraph.order({allowCycles:!0});e.sort((s,o)=>t.indexOf(s.model)-t.indexOf(o.model)),await this.handleDataContainer(e)}async connectDataWithModelsPartial(e){const t=this.dependencyGraph.order({allowCycles:!0});e.sort((i,a)=>t.indexOf(i.model)-t.indexOf(a.model));const s=[];for(const[i,a]of this.changeTracker.getChangedAttributes())for(const u of a){const c=this.attributeDependencyGraph.getAttributesForModel(i).find(l=>l.attributeKey===u);if(c)s.push(c);else{const l=this.models.get(i);if(l){const d=l.properties.get(u),f=l.references.get(u);(d||f)&&s.push({modelKey:i,attributeKey:u,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const u=this.changeTracker.getChangedItems(a.key),c=this.changeTracker.getChangedAttributes().get(a.key);u.size>0&&c&&(this.qualityController.cleanUpErrorsForItems(a,u,c),this.qualityController.validateItemsPartial(a,u,c).forEach(l=>{this.setError(l,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[u,c]of e.entries()){const l=c.get(2);l&&l.size>0&&(s.add(u),t.set(u,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const u of s){const c=this.models.get(u);if(!c)continue;const l=e.get(u)?.get(2);if(l)for(const d of l){const f=c.references.get(d);if(f&&jr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&jr(v)&&t.get(u).add(h)}}}}const o=[],n=new Set,i=new Set,a=u=>{if(i.has(u)||n.has(u))return;n.add(u);const c=t.get(u);if(c)for(const l of c)a(l);n.delete(u),i.add(u),o.push(u)};for(const u of s)a(u);return o}async processAttributesForStep(e,t,s){let o=this.dependencyGraph.order({allowCycles:!0});e===2&&(o=this.getResolvedReferenceProcessingOrder(t));for(const n of o){const i=t.get(n);if(!i)continue;const a=i.get(e);if(!a||a.size===0)continue;const u=this.models.get(n);if(!u)continue;const c=W(),l=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${l}:start`,context:c}),e===2)u.rebuildResolvedReferencesForAllItems(a);else{const d=s.find(f=>f.model===n);if(!d)continue;switch(e){case 1:u.addBasicPropertiesAndReferencesPartial(d,a);break;case 3:u.addDerivedAndExpressionAttributesPartial(d,a);break;case 4:u.reRunDerivedPropertiesBasedOnResolvesPartial(d,a);break}}this.cdRef.analyticsController.mark({name:`${l}:end`,context:c}),this.cdRef.analyticsController.measure({name:l,start:`${l}:start`,end:`${l}:end`,context:c,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??it,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=No(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(u=>{this.setError(u,i)}),s?t>0&&o>0&&o%t===0&&await new Promise(u=>setTimeout(u,0)):await new Promise(u=>setTimeout(u,0))}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};It([b({scope:"global",type:"model_add",connectMessage:!0})],at.prototype,"addModel"),It([b({scope:"global",type:"data_change",connectMessage:!0})],at.prototype,"addData"),It([b({scope:"global",type:"view_add",connectMessage:!0})],at.prototype,"addView"),It([b({scope:"global",type:"dcupl_handle_datacontainer"})],at.prototype,"handleDataContainer");function Np(r,e){return Ee(e,function(t){return r[t]})}function zp(r){return r==null?[]:Np(r,Ze(r))}var Lp=Math.max;function Wp(r,e,t,s){r=ee(r)?r:zp(r),t=t?kt(t):0;var o=r.length;return t<0&&(t=Lp(o+t,0)),jt(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&vs(r,e,t)>-1}var Hp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,Wo=(r,e,t,s)=>{for(var o=Jp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Hp(e,t,o),o};let Sr=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}options;key;modelKey;catalog;setup(e){const t=this.dcuplApi.modelParser.models.get(e.modelKey);if(!t)throw new Error(`Model with key ${e.modelKey} not found`);const s=this.getListItemKeys(e),o=this.getRelevantData(t,s),n=this.initIndicesController(s,t,o);this.catalog?this.catalog.filter.update(t,o,n):(this.catalog=new tp(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new Rt;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s)}else o=t.indicesController;return o}getListItemKeys(e){let t;return e.listItemKeys?t=e.listItemKeys:e.query&&(t=this.dcuplApi.query.execute(e.query).map(s=>s.key)),t}getRelevantData(e,t){const s=e.getData();return t?this.initFromItemKeys(s,t):s}init(e){this.options=se(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}on(e){return this.cdRef.on(e)}};Wo([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Sr.prototype,"_destroy"),Wo([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Sr.prototype,"update");var Zp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,Xp=(r,e,t,s)=>{for(var o=Yp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Zp(e,t,o),o};class Ho{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new Ar;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Sr(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}}Xp([b({scope:"global",type:"list_created",connectMessage:!0})],Ho.prototype,"create");let eh=class{constructor(e){this.scriptsController=e}enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Re.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const c of this.getModelErrors(o))c.attribute===i&&c.itemKey!=null&&(c.errorType==="UndefinedValue"||c.errorType==="WrongDataType")&&this.removeError(c.key);const u=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,u,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&u.errorType==="UndefinedValue"&&this.removeError(u.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(u=>u.errorType==="UndefinedValue"&&u.attribute!=null).map(u=>u.attribute));for(const u of n){const c=this.getGroupCount(o,u,"UndefinedValue");if(c>0&&c===t.data.length){for(const l of this.getModelErrors(o))l.attribute===u&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,u))}}const i=this.getModelErrors(o).filter(u=>u.errorType==="WrongDataType"&&u.errorGroup==="PropertyDataError"&&u.title==="Wrong Data Type"&&u.itemKey!=null),a=Er(i,"attribute");for(const u in a){const c=a[u];if(!c?.length)continue;const l=c[0].meta,d=e.properties.get(u)?.type??l?.expected??"unknown";for(const f of c)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,u,String(l?.rawValue??""),d,c.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),u=i?a.filter(c=>c.errorType===i):a;for(const c of u)if(c.itemKey&&t.has(c.itemKey)){if(n&&c.attribute&&!n.has(c.attribute))continue;this.removeError(c.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const u=a.quality?.validators;if(u)for(const c of t){const l=n.get(c);if(!l)continue;const d=l[a.key],f=this.validateAttribute(d,u,a.key);for(const h of f)h.model=e.key,h.itemKey=l.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(s=>s.model!=="$DcuplErrorTrackingErrors");const e=this.modelParser.models.get("$DcuplErrorTrackingErrors");e?.resetData(),e?.resetIndexMap(),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"});const t=this.modelParser.unprocessedData.find(s=>s.model==="$DcuplErrorTrackingErrors");t&&await this.modelParser.handleDataContainer([t])}initErrorTrackingModels(){this.modelParser?.addModel({key:"$DcuplErrorTrackingErrors",autoGenerateKey:!0,supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"title",type:"string",filter:!0},{key:"itemKey",type:"string",filter:!0},{key:"attribute",type:"string",filter:!0},{key:"description",type:"string"},{key:"meta",type:"json"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingType",data:[{key:"UndefinedAttribute"},{key:"InvalidValidator"},{key:"UndefinedValue"},{key:"NullValue"},{key:"WrongDataType"},{key:"MissingModel"},{key:"NonUniqueKey"},{key:"RemoteReferenceKeyNotFound"},{key:"InvalidModelDescription"},{key:"InvalidResource"},{key:"InvalidModelDefinition"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingGroup",data:[{key:"ReferenceDataError"},{key:"PropertyDataError"},{key:"DataContainerError"},{key:"ModelDescriptionError"},{key:"LoaderError"},{key:"ResourceError"},{key:"ModelDefinitionError"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingModel",supportsAutoCreation:!0,quality:{enabled:!1}})}initAnalyticsValues(){this.calculateTiming(),this.calculateSizes(),this.calculateErrorTrackingFacet(),this.calculateCounts(),this.calculateUnusedAttributes()}calculateUnusedAttributes(){this.values.unusedAttributes=[];const e=this.dcupl.models.keys();for(const t of e){const s=this.getUnusedAttributesFromModel(this.dcupl,t);for(const o of s)this.values.unusedAttributes?.push({model:t,attribute:o})}}calculateCounts(){this.values.counts={},this.values.counts.modelFiles=this.dcupl.modelParser.unprocessedModelDescriptions.size,this.values.counts.dataFiles=this.dcupl.modelParser.unprocessedData.length,this.values.counts.models=this.dcupl.models.keys().length;let e=0,t=0,s=0;this.dcupl.models.keys().forEach(o=>{const n=this.dcupl.modelParser.models.get(o);if(!n)return;const i=n?.getBasicProperties()||[],a=n?.getBasicReferences()||[],u=i.length+a.length;t+=u;const c=n.data?.size||0;e+=c,s+=u*c}),this.values.counts.rows=e,this.values.counts.attributes=t,this.values.counts.dataEntries=s}calculateTiming(){const e=this.dcupl.analyticsController.getByName("loader_processed");e&&e[0]&&(this.values.loading=e[0].value);const t=this.dcupl.analyticsController.getByName("dcupl_initialized");t&&t[0]&&(this.values.processing=t[0].value),this.values.startup=this.values.loading+this.values.processing}calculateSizes(){const e=this.calculateSizesForModels();this.values.sizes={},this.values.sizes.totalEncoded=e.reduce((t,s)=>t+s.encodedBodySize,0),this.values.sizes.totalDecoded=e.reduce((t,s)=>t+s.decodedBodySize,0),this.values.sizes.unusedDecoded=this.calculateUnusedData(),this.values.sizes.models=e.map(t=>({model:t.model,decodedBodySize:t.decodedBodySize,encodedBodySize:t.encodedBodySize})),this.values.sizes.models?.sort((t,s)=>(s.encodedBodySize||0)-(t.encodedBodySize||0))}calculateErrorTrackingFacet(){try{if(!this.enabled)return;const e=this.dcupl.lists.create({modelKey:"$DcuplErrorTrackingErrors"}),t=e.catalog.fn.facets({attribute:"errorType",calculateResults:!0,excludeUndefineds:!1,excludeUnresolved:!1,excludeZeros:!1});this.values.errors={},t&&(this.values.errors.size=e.catalog.fn.metadata().currentSize,this.values.errors.UndefinedValue=t.find(s=>s.key==="UndefinedValue")?.size||0,this.values.errors.UndefinedAttribute=t.find(s=>s.key==="UndefinedAttribute")?.size||0,this.values.errors.WrongDataType=t.find(s=>s.key==="WrongDataType")?.size||0,this.values.errors.MissingModel=t.find(s=>s.key==="MissingModel")?.size||0,this.values.errors.InvalidModelDescription=t.find(s=>s.key==="InvalidModelDescription")?.size||0,this.values.errors.RemoteReferenceKeyNotFound=t.find(s=>s.key==="RemoteReferenceKeyNotFound")?.size||0)}catch(e){this.log.error("Error calculating error tracking facet",e)}}calculateSizesForModels(){const e=this.dcupl.analyticsController.getByType("resource").filter(s=>s.value?.type==="data"),t=Er(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const u=a.value.encodedBodySize;return i+u},0),n=t[s]?.reduce((i,a)=>{const u=a.value.decodedBodySize;return i+u},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(c=>c.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const u=e.modelParser.unprocessedData.find(c=>c.model===t)?.data||[];return this.getUnusedAttributes(u,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const u=a[t];if(n.has(u)){const c={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${u}" is not unique`};o.push(c),i&&delete a[t]}else n.add(u)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!vo(e,t.value))return{title:"Validator Error - EndsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not end with "${t.value}"`}}validateIncludes(e,t,s){if(e!=null&&!Wp(e,t.value))return{title:"Validator Error - Includes",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not include "${t.value}"`}}validateMinLength(e,t,s){if(e!=null&&e.length<t.value)return{title:"Validator Error - Min Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is shorter than the minimum length of "${t.value}"`}}validateMaxLength(e,t,s){if(e!=null&&e.length>t.value)return{title:"Validator Error - Max Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is longer than the maximum length of "${t.value}"`}}validateEnum(e,t,s){if(!t.value.includes(e))return{title:"Validator Error - Enum",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is not in the enum values`}}validatePattern(e,t,s){if(e!=null)try{if(!new RegExp(t.value).test(e))return{title:"Validator Error - Pattern",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not match the pattern "${t.value}"`}}catch(o){this.log.error("Invalid pattern validation",o)}}};var th=Object.defineProperty,rh=Object.getOwnPropertyDescriptor,V=(r,e,t,s)=>{for(var o=rh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&th(e,t,o),o};let Q=class{cdRef=new Ar;analyticsController=new gf;containerSourceMetadata=new WeakMap;scriptController=new Jf;qualityController=new eh(this.scriptController);log=Re.child({prefix:"Dcupl"});modelParser=new at(this.cdRef,this.qualityController,this);globalItemService=new Bo(this.modelParser,this.scriptController);cacheCtrl=new So(!1);queryManager=new Hf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new be;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,cacheInvalidationThreshold:.7,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new Ho(this,this.cdRef);busy=!1;updateQueue=[];constructor(e){this.analyticsController.init(!!e?.analytics?.enabled),this.qualityController.dcupl=this,this.analyticsController.mark({name:"dcupl:constructor"}),this.initOptions=nt({},this._defaultInitOptions,e),this.qualityController.enabled=this.initOptions.errorTracking?.enabled||this.initOptions.quality?.enabled||!1,this.qualityController.maxErrorsPerGroup=this.initOptions.quality?.maxErrorsPerGroup??1e3,this.modelParser.initOptions=Object.assign({},this.initOptions),this.cdRef._init({cdRefKey:"root",dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),this.cacheCtrl.enabled=!!this.initOptions.performance?.cache?.enabled}models={get:e=>this.modelParser.models.get(e)?.getModelDefinition(),set:e=>(this.modelParser.models.delete(e.key),this.modelParser.addModel(e)),update:e=>this.modelParser.addModel(e),remove:e=>{this.modelParser.models.delete(e)},keys:()=>this.modelParser._getModelKeys()};views={get:e=>this.modelParser.views.get(e),keys:e=>this.modelParser._getViewKeys(e),set:e=>this.modelParser.addView(e)};data={update:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"update",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},upsert:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"upsert",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},set:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"set",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},remove:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"remove",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},reset:e=>{e.model&&(this.modelParser.models.get(e.model)?.resetData(),this.modelParser.models.get(e.model)?.resetIndexMap())},apply:e=>this.modelParser.addData(e)};loaders={add:(e,t)=>{this.addLoader(e,t)},remove:e=>{this.removeLoader(e)},get:e=>this._loaders.get(e)};scripts={set:(e,t)=>{this.scriptController.setScript(e,t)},remove:e=>{this.scriptController.removeScript(e)},get:e=>{this.scriptController.getScript(e)},keys:()=>this.scriptController.keys(),execute:(e,t)=>{const s={dcupl:this,options:t};return this.scriptController.executeScript(e,"script",s)},executeAsync:(e,t)=>new Promise((s,o)=>{const n={dcupl:this,options:t,resolve:s,reject:o};return this.scriptController.executeScript(e,"async_script",n)})};fn={pivot:e=>this._pivot(e),aggregate:e=>this._aggregate(e),suggest:e=>this._suggest(e),groupBy:e=>this._groupBy(e),facets:e=>this._facets(e),metadata:e=>this._metadata(e)};_pivot(e){return this.getFnList(e).catalog.fn.pivot(e.options)}_aggregate(e){return this.getFnList(e).catalog.fn.aggregate(e.options)}_suggest(e){return this.getFnList(e).catalog.fn.suggest(e.options)}_groupBy(e){return this.getFnList(e).catalog.fn.groupBy(e.options)}_facets(e){return this.getFnList(e).catalog.fn.facets(e.options)}_metadata(e){return this.getFnList(e).catalog.fn.metadata()}registerContainer(e){this.modelParser.addData(e)}updateRegisteredContainer(e,t){const s=this.modelParser.unprocessedData.findIndex(o=>o.placeholderUid===e.placeholderUid);s>-1&&(delete e.placeholderUid,this.modelParser.unprocessedData[s]=e,t&&this.containerSourceMetadata.set(e,t))}removeRegisteredContainer(e){const t=this.modelParser.unprocessedData.findIndex(s=>s.placeholderUid===e.placeholderUid);t>-1&&this.modelParser.unprocessedData.splice(t,1)}getContainerSourceMetadata(e){return this.containerSourceMetadata.get(e)}setContainerSourceMetadata(e,t){this.containerSourceMetadata.set(e,t)}getFnList(e){let t=this.lists.get(`__global_list__${e.modelKey}`);return t||(t=this.lists.create({modelKey:e.modelKey,listKey:`__global_list__${e.modelKey}`})),e.query?t.catalog.query.apply(e.query,{mode:"set"}):t.catalog.query.reset(),t}getAffectedModels(e){const t=new Set;for(const o of e.keys())t.add(o);const s=this.modelParser.dependencyGraph;if(s)for(const o of e.keys())this.getDownstreamDependencies(o,s).forEach(n=>t.add(n));return Array.from(t)}getDownstreamDependencies(e,t){const s=new Set,o=new Set,n=i=>{if(!o.has(i)){o.add(i);for(const[a,u]of Object.entries(t.dependencies||{}))Array.isArray(u)&&u.includes(i)&&(s.add(a),n(a))}};return n(e),s}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;for(const o of this.lists.getAll()){if(!this.shouldAutoUpdateList(o,t)){s&&this.log.debug("List skipped (auto-update disabled)",{listKey:o.key,modelKey:o.modelKey});continue}e?this.isListAffectedByChanges(o,e.affectedModels)?(s&&this.log.debug("List auto-updating (affected by changes)",{listKey:o.key,modelKey:o.modelKey,affectedModels:e.affectedModels}),o.update()):s&&this.log.debug("List skipped (not affected)",{listKey:o.key,modelKey:o.modelKey}):(s&&this.log.debug("List auto-updating (full update)",{listKey:o.key,modelKey:o.modelKey}),o.update())}}isListAffectedByChanges(e,t){const s=e.modelKey;return t.includes(s)}shouldAutoUpdateList(e,t){return e.key.startsWith("__global_list__")?!0:t!==void 0?t:e.options.autoUpdate!==void 0?e.options.autoUpdate:this.initOptions.performance?.autoUpdateLists?.enabled??!1}query={one:e=>this.getItem(e),many:e=>this._getManyItems(e),execute:e=>this.executeQuery(e),generate:(e,t)=>(this.rootQueryBuilder.init({modelKey:e}),this.rootQueryBuilder.applyQuery(t)),registerCustomOperator:(e,t)=>{this.queryManager.registerCustomOperator(e,t)}};on(e){return this.cdRef.on(e)}async init(){try{return await this.performUpdate(()=>this.modelParser.init()),this.cacheCtrl.clear(),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=this.modelParser.changeTracker,s=t.hasChanges(),o=s?new Map(t.getChangedAttributes()):null,n=s?new Set(t.getModelsWithFullReset()):null,i=this.cacheCtrl.getStats();if(await this.performUpdate(()=>this.modelParser.update()),s&&this.cacheCtrl.enabled&&o){const a=this.modelParser.getTotalItemCount(),u=t.getTotalChangedItemCount(),c=a>0?u/a:0,l=this.initOptions.performance?.partialUpdates?.cacheInvalidationThreshold??.7,d=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;n&&n.size>0?(d&&this.log.debug("Cache invalidation: Full clear",{reason:"full_reset_detected"}),this.cacheCtrl.clear()):c>l?(d&&this.log.debug("Cache invalidation: Full clear",{reason:"high_item_ratio",ratio:c.toFixed(2),threshold:l,changedItems:u,totalItems:a}),this.cacheCtrl.clear()):(d&&this.log.debug("Cache invalidation: Selective",{changedItems:u,totalItems:a,ratio:c.toFixed(2)}),this.cacheCtrl.invalidateByDependencies(o))}else(this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1)&&this.log.debug("Cache invalidation: Full clear",{reason:"full_update"}),this.cacheCtrl.clear();if(this.cacheCtrl.getStats){const a=this.cacheCtrl.getStats(),u=this.modelParser.partialUpdateMetrics.getLastUpdates(1);if(u.length>0&&u[0]){const c=u[0];c.cacheStats={entriesInvalidated:i.totalEntries-a.totalEntries,totalEntries:i.totalEntries}}}if(s&&o){const a={isPartialUpdate:!0,changedModels:Array.from(o.keys()),changedAttributes:o,affectedModels:this.getAffectedModels(o)};this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[a]}),this.updateFnLists(a,e?.autoUpdateLists)}else this.updateFnLists(null,e?.autoUpdateLists);return!0}catch(t){return this.log.error("Update failed",t),!1}}destroy(){try{this.lists.destroy(),this._loaders.forEach(e=>{e.destroy()})}catch{}}getItem(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getItem(e.itemKey,t.data,t,e)}_getManyItems(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getManyItems(e.itemKeys,t.data,t,e)}executeQuery(e){if(!e?.modelKey)throw new Error("No modelKey provided");return this.getFnList({modelKey:e?.modelKey}).catalog.query.execute(e)}addLoader(e,t){const s=me.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new Ar;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}async performUpdate(e){if(this.busy)return new Promise(t=>{this.updateQueue.push(()=>e().then(t))});try{this.busy=!0,await e()}finally{this.busy=!1,this.processQueue()}}async processQueue(){if(this.updateQueue.length>0){const e=this.updateQueue.shift();e&&(await e(),this.processQueue())}}};V([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),V([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),V([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),V([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),V([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),V([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),V([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),V([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),V([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),V([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),V([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),V([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),V([b({scope:"global",type:"loader_removed",connectMessage:!0})],Q.prototype,"removeLoader");let sh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Jo=typeof global=="object"&&global&&global.Object===Object&&global,oh=typeof self=="object"&&self&&self.Object===Object&&self,Z=Jo||oh||Function("return this")(),ce=Z.Symbol,Zo=Object.prototype,nh=Zo.hasOwnProperty,ih=Zo.toString,ut=ce?ce.toStringTag:void 0;function ah(r){var e=nh.call(r,ut),t=r[ut];try{r[ut]=void 0;var s=!0}catch{}var o=ih.call(r);return s&&(e?r[ut]=t:delete r[ut]),o}var uh=Object.prototype,ch=uh.toString;function lh(r){return ch.call(r)}var dh="[object Null]",fh="[object Undefined]",Yo=ce?ce.toStringTag:void 0;function Ie(r){return r==null?r===void 0?fh:dh:Yo&&Yo in Object(r)?ah(r):lh(r)}function Oe(r){return r!=null&&typeof r=="object"}var ph="[object Symbol]";function Mr(r){return typeof r=="symbol"||Oe(r)&&Ie(r)==ph}function hh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Ke=Array.isArray,Xo=ce?ce.prototype:void 0,en=Xo?Xo.toString:void 0;function tn(r){if(typeof r=="string")return r;if(Ke(r))return hh(r,tn)+"";if(Mr(r))return en?en.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Ot(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var yh="[object AsyncFunction]",gh="[object Function]",mh="[object GeneratorFunction]",vh="[object Proxy]";function rn(r){if(!Ot(r))return!1;var e=Ie(r);return e==gh||e==mh||e==yh||e==vh}var Rr=Z["__core-js_shared__"],sn=(function(){var r=/[^.]+$/.exec(Rr&&Rr.keys&&Rr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function bh(r){return!!sn&&sn in r}var kh=Function.prototype,wh=kh.toString;function ke(r){if(r!=null){try{return wh.call(r)}catch{}try{return r+""}catch{}}return""}var Ah=/[\\^$.*+?()[\]{}|]/g,$h=/^\[object .+?Constructor\]$/,Ch=Function.prototype,Dh=Object.prototype,_h=Ch.toString,Ph=Dh.hasOwnProperty,xh=RegExp("^"+_h.call(Ph).replace(Ah,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Eh(r){if(!Ot(r)||bh(r))return!1;var e=rn(r)?xh:$h;return e.test(ke(r))}function jh(r,e){return r?.[e]}function we(r,e){var t=jh(r,e);return Eh(t)?t:void 0}var Tr=we(Z,"WeakMap"),on=Object.create,Sh=(function(){function r(){}return function(e){if(!Ot(e))return{};if(on)return on(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),nn=(function(){try{var r=we(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Mh(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Rh=9007199254740991,Th=/^(?:0|[1-9]\d*)$/;function Ih(r,e){var t=typeof r;return e=e??Rh,!!e&&(t=="number"||t!="symbol"&&Th.test(r))&&r>-1&&r%1==0&&r<e}function Oh(r,e,t){e=="__proto__"&&nn?nn(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function an(r,e){return r===e||r!==r&&e!==e}var Kh=Object.prototype,Fh=Kh.hasOwnProperty;function qh(r,e,t){var s=r[e];(!(Fh.call(r,e)&&an(s,t))||t===void 0&&!(e in r))&&Oh(r,e,t)}var Qh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Qh}function Bh(r){return r!=null&&un(r.length)&&!rn(r)}var Vh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Vh;return r===t}function Gh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Uh="[object Arguments]";function ln(r){return Oe(r)&&Ie(r)==Uh}var dn=Object.prototype,Nh=dn.hasOwnProperty,zh=dn.propertyIsEnumerable,Lh=ln((function(){return arguments})())?ln:function(r){return Oe(r)&&Nh.call(r,"callee")&&!zh.call(r,"callee")};function Wh(){return!1}var fn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,pn=fn&&typeof module=="object"&&module&&!module.nodeType&&module,Hh=pn&&pn.exports===fn,hn=Hh?Z.Buffer:void 0,Jh=hn?hn.isBuffer:void 0,yn=Jh||Wh,Zh="[object Arguments]",Yh="[object Array]",Xh="[object Boolean]",ey="[object Date]",ty="[object Error]",ry="[object Function]",sy="[object Map]",oy="[object Number]",ny="[object Object]",iy="[object RegExp]",ay="[object Set]",uy="[object String]",cy="[object WeakMap]",ly="[object ArrayBuffer]",dy="[object DataView]",fy="[object Float32Array]",py="[object Float64Array]",hy="[object Int8Array]",yy="[object Int16Array]",gy="[object Int32Array]",my="[object Uint8Array]",vy="[object Uint8ClampedArray]",by="[object Uint16Array]",ky="[object Uint32Array]",D={};D[fy]=D[py]=D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=!0,D[Zh]=D[Yh]=D[ly]=D[Xh]=D[dy]=D[ey]=D[ty]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[uy]=D[cy]=!1;function wy(r){return Oe(r)&&un(r.length)&&!!D[Ie(r)]}function Ir(r){return function(e){return r(e)}}var gn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ct=gn&&typeof module=="object"&&module&&!module.nodeType&&module,Ay=ct&&ct.exports===gn,Or=Ay&&Jo.process,Fe=(function(){try{var r=ct&&ct.require&&ct.require("util").types;return r||Or&&Or.binding&&Or.binding("util")}catch{}})(),mn=Fe&&Fe.isTypedArray,$y=mn?Ir(mn):wy,Cy=Object.prototype,Dy=Cy.hasOwnProperty;function _y(r,e){var t=Ke(r),s=!t&&Lh(r),o=!t&&!s&&yn(r),n=!t&&!s&&!o&&$y(r),i=t||s||o||n,a=i?Gh(r.length,String):[],u=a.length;for(var c in r)Dy.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ih(c,u)))&&a.push(c);return a}function vn(r,e){return function(t){return r(e(t))}}var Py=vn(Object.keys,Object),xy=Object.prototype,Ey=xy.hasOwnProperty;function jy(r){if(!cn(r))return Py(r);var e=[];for(var t in Object(r))Ey.call(r,t)&&t!="constructor"&&e.push(t);return e}function Sy(r){return Bh(r)?_y(r):jy(r)}var My=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ry=/^\w*$/;function Ty(r,e){if(Ke(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Mr(r)?!0:Ry.test(r)||!My.test(r)||e!=null&&r in Object(e)}var lt=we(Object,"create");function Iy(){this.__data__=lt?lt(null):{},this.size=0}function Oy(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ky="__lodash_hash_undefined__",Fy=Object.prototype,qy=Fy.hasOwnProperty;function Qy(r){var e=this.__data__;if(lt){var t=e[r];return t===Ky?void 0:t}return qy.call(e,r)?e[r]:void 0}var By=Object.prototype,Vy=By.hasOwnProperty;function Gy(r){var e=this.__data__;return lt?e[r]!==void 0:Vy.call(e,r)}var Uy="__lodash_hash_undefined__";function Ny(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=lt&&e===void 0?Uy:e,this}function Ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ae.prototype.clear=Iy,Ae.prototype.delete=Oy,Ae.prototype.get=Qy,Ae.prototype.has=Gy,Ae.prototype.set=Ny;function zy(){this.__data__=[],this.size=0}function Kt(r,e){for(var t=r.length;t--;)if(an(r[t][0],e))return t;return-1}var Ly=Array.prototype,Wy=Ly.splice;function Hy(r){var e=this.__data__,t=Kt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Wy.call(e,t,1),--this.size,!0}function Jy(r){var e=this.__data__,t=Kt(e,r);return t<0?void 0:e[t][1]}function Zy(r){return Kt(this.__data__,r)>-1}function Yy(r,e){var t=this.__data__,s=Kt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function oe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}oe.prototype.clear=zy,oe.prototype.delete=Hy,oe.prototype.get=Jy,oe.prototype.has=Zy,oe.prototype.set=Yy;var dt=we(Z,"Map");function Xy(){this.size=0,this.__data__={hash:new Ae,map:new(dt||oe),string:new Ae}}function eg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ft(r,e){var t=r.__data__;return eg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function tg(r){var e=Ft(this,r).delete(r);return this.size-=e?1:0,e}function rg(r){return Ft(this,r).get(r)}function sg(r){return Ft(this,r).has(r)}function og(r,e){var t=Ft(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function le(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}le.prototype.clear=Xy,le.prototype.delete=tg,le.prototype.get=rg,le.prototype.has=sg,le.prototype.set=og;var ng="Expected a function";function Kr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ng);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(Kr.Cache||le),t}Kr.Cache=le;var ig=500;function ag(r){var e=Kr(r,function(s){return t.size===ig&&t.clear(),s}),t=e.cache;return e}var ug=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,cg=/\\(\\)?/g,lg=ag(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(ug,function(t,s,o,n){e.push(o?n.replace(cg,"$1"):s||t)}),e});function dg(r){return r==null?"":tn(r)}function fg(r,e){return Ke(r)?r:Ty(r,e)?[r]:lg(dg(r))}function pg(r){if(typeof r=="string"||Mr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function hg(r,e){e=fg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[pg(e[t++])];return t&&t==s?r:void 0}function yg(r,e,t){var s=r==null?void 0:hg(r,e);return s===void 0?t:s}function gg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var mg=vn(Object.getPrototypeOf,Object);function vg(){this.__data__=new oe,this.size=0}function bg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function kg(r){return this.__data__.get(r)}function wg(r){return this.__data__.has(r)}var Ag=200;function $g(r,e){var t=this.__data__;if(t instanceof oe){var s=t.__data__;if(!dt||s.length<Ag-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new le(s)}return t.set(r,e),this.size=t.size,this}function qe(r){var e=this.__data__=new oe(r);this.size=e.size}qe.prototype.clear=vg,qe.prototype.delete=bg,qe.prototype.get=kg,qe.prototype.has=wg,qe.prototype.set=$g;var bn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,kn=bn&&typeof module=="object"&&module&&!module.nodeType&&module,Cg=kn&&kn.exports===bn,wn=Cg?Z.Buffer:void 0;wn&&wn.allocUnsafe;function Dg(r,e){return r.slice()}function _g(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Pg(){return[]}var xg=Object.prototype,Eg=xg.propertyIsEnumerable,An=Object.getOwnPropertySymbols,jg=An?function(r){return r==null?[]:(r=Object(r),_g(An(r),function(e){return Eg.call(r,e)}))}:Pg;function Sg(r,e,t){var s=e(r);return Ke(r)?s:gg(s,t(r))}function Mg(r){return Sg(r,Sy,jg)}var Fr=we(Z,"DataView"),qr=we(Z,"Promise"),Qr=we(Z,"Set"),$n="[object Map]",Rg="[object Object]",Cn="[object Promise]",Dn="[object Set]",_n="[object WeakMap]",Pn="[object DataView]",Tg=ke(Fr),Ig=ke(dt),Og=ke(qr),Kg=ke(Qr),Fg=ke(Tr),ne=Ie;(Fr&&ne(new Fr(new ArrayBuffer(1)))!=Pn||dt&&ne(new dt)!=$n||qr&&ne(qr.resolve())!=Cn||Qr&&ne(new Qr)!=Dn||Tr&&ne(new Tr)!=_n)&&(ne=function(r){var e=Ie(r),t=e==Rg?r.constructor:void 0,s=t?ke(t):"";if(s)switch(s){case Tg:return Pn;case Ig:return $n;case Og:return Cn;case Kg:return Dn;case Fg:return _n}return e});var qg=Object.prototype,Qg=qg.hasOwnProperty;function Bg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Qg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var xn=Z.Uint8Array;function Br(r){var e=new r.constructor(r.byteLength);return new xn(e).set(new xn(r)),e}function Vg(r,e){var t=Br(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Gg=/\w*$/;function Ug(r){var e=new r.constructor(r.source,Gg.exec(r));return e.lastIndex=r.lastIndex,e}var En=ce?ce.prototype:void 0,jn=En?En.valueOf:void 0;function Ng(r){return jn?Object(jn.call(r)):{}}function zg(r,e){var t=Br(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Lg="[object Boolean]",Wg="[object Date]",Hg="[object Map]",Jg="[object Number]",Zg="[object RegExp]",Yg="[object Set]",Xg="[object String]",em="[object Symbol]",tm="[object ArrayBuffer]",rm="[object DataView]",sm="[object Float32Array]",om="[object Float64Array]",nm="[object Int8Array]",im="[object Int16Array]",am="[object Int32Array]",um="[object Uint8Array]",cm="[object Uint8ClampedArray]",lm="[object Uint16Array]",dm="[object Uint32Array]";function fm(r,e,t){var s=r.constructor;switch(e){case tm:return Br(r);case Lg:case Wg:return new s(+r);case rm:return Vg(r);case sm:case om:case nm:case im:case am:case um:case cm:case lm:case dm:return zg(r);case Hg:return new s;case Jg:case Xg:return new s(r);case Zg:return Ug(r);case Yg:return new s;case em:return Ng(r)}}function pm(r){return typeof r.constructor=="function"&&!cn(r)?Sh(mg(r)):{}}var hm="[object Map]";function ym(r){return Oe(r)&&ne(r)==hm}var Sn=Fe&&Fe.isMap,gm=Sn?Ir(Sn):ym,mm="[object Set]";function vm(r){return Oe(r)&&ne(r)==mm}var Mn=Fe&&Fe.isSet,bm=Mn?Ir(Mn):vm,Rn="[object Arguments]",km="[object Array]",wm="[object Boolean]",Am="[object Date]",$m="[object Error]",Tn="[object Function]",Cm="[object GeneratorFunction]",Dm="[object Map]",_m="[object Number]",In="[object Object]",Pm="[object RegExp]",xm="[object Set]",Em="[object String]",jm="[object Symbol]",Sm="[object WeakMap]",Mm="[object ArrayBuffer]",Rm="[object DataView]",Tm="[object Float32Array]",Im="[object Float64Array]",Om="[object Int8Array]",Km="[object Int16Array]",Fm="[object Int32Array]",qm="[object Uint8Array]",Qm="[object Uint8ClampedArray]",Bm="[object Uint16Array]",Vm="[object Uint32Array]",A={};A[Rn]=A[km]=A[Mm]=A[Rm]=A[wm]=A[Am]=A[Tm]=A[Im]=A[Om]=A[Km]=A[Fm]=A[Dm]=A[_m]=A[In]=A[Pm]=A[xm]=A[Em]=A[jm]=A[qm]=A[Qm]=A[Bm]=A[Vm]=!0,A[$m]=A[Tn]=A[Sm]=!1;function qt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Ot(r))return r;var a=Ke(r);if(a)i=Bg(r);else{var u=ne(r),c=u==Tn||u==Cm;if(yn(r))return Dg(r);if(u==In||u==Rn||c&&!o)i=c?{}:pm(r);else{if(!A[u])return o?r:{};i=fm(r,u)}}n||(n=new qe);var l=n.get(r);if(l)return l;n.set(r,i),bm(r)?r.forEach(function(h){i.add(qt(h,e,t,h,r,n))}):gm(r)&&r.forEach(function(h,p){i.set(p,qt(h,e,t,p,r,n))});var d=Mg,f=a?void 0:d(r);return Mh(f||r,function(h,p){f&&(p=h,h=r[p]),qh(i,p,qt(h,e,t,p,r,n))}),i}var Gm=1,Um=4;function Nm(r){return qt(r,Gm|Um)}function zm(r){const e=Vr(r);return Lm(e)}function Vr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Vr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Vr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Lm(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const F={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}},On={silent:0,error:1,warn:2,info:3,debug:4};class S{config;static globalConfig={};constructor(e={}){this.config={level:e.level??S.globalConfig.level??this.getDefaultLevel(),format:e.format??S.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??S.globalConfig.onLog,onTrackError:e.onTrackError??S.globalConfig.onTrackError}}static setGlobalConfig(e){S.globalConfig={...S.globalConfig,...e}}static getGlobalConfig(){return{...S.globalConfig}}static setModuleLevel(e,t){S.globalConfig.onLog||(S.globalConfig.onLog=void 0),S._moduleOverrides||(S._moduleOverrides=new Map),S._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!S._moduleOverrides))return S._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=S.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return On[e]<=On[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new S(t)}configure(e){Object.assign(this.config,e)}}const Gr=new S;function Ur(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}let Wm=class{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=F.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}};const Kn=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):Nm(r):r,Fn=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Kn(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=F.now(),c=u-s,l=Math.round(c*1e3)/1e3;t.duration=l,t.start=s,t.end=u;const d={duration:t.duration};return t.modelKey&&(d.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(d.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},qn=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=F.now(),a=this.cdRef,u=Kn(r,!0);u.key||(a.increaseCounter(),u.key=a.getCounter());const c=Ur();a.analyticsController.mark({name:`${u.type}:start`,context:c});const l=this.model?.key;!u.originCdRefKey&&a.key&&(u.originCdRefKey=a.key),l&&(u.modelKey=l);const d=o.apply(this,n);return u.method=t,u.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Fn(this,a,u,i,c,f)):Fn(this,a,u,i,c,d)},s},Hm="k:",Jm="h:";function Nr(r,e=0){if(r.key)return`${Hm}${r.key}`;const t=zm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Jm}${t}`}function Zm(r){const e=new Map,t=new Set;return r.map(s=>{const o=`${s.key??""}|${s.type}|${s.rawUrl??s.url}|${s.model??""}`;let n=e.get(o)??0,i=Nr(s,n);for(;t.has(i);)n+=1,i=s.key?`${Nr(s)}#${n}`:Nr(s,n);return e.set(o,n+1),t.add(i),i})}const Qt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>yg(e,s.trim(),""))):"",Ym=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let Xm=class{log=Gr.child({prefix:"DcuplCsvParser"});parse(r,e={}){const{quoteChar:t=e.quoteChar||'"',escapeChar:s=e.escapeChar||'"',comments:o=e.comments||void 0,dynamicTyping:n=!1,header:i=!0,skipEmptyLines:a=!0,transformHeader:u,transform:c}=e,l=[],d=i?[]:null;let f=r.length,h=[],p="",y=!1,v=!0,g=0;if(a){for(;g<f&&(r[g]===`
9
9
  `||r[g]==="\r"||r[g]===""||r[g]==="'"||r[g]==='"');)g++;r=r.slice(g),f=r.length,g=0}const k=e.delimiter||this.detectDelimiter(r);for(;g<f;g++){const m=r[g],M=r[g+1];if(o&&m===o&&!y&&p.length===0){for(;g<f&&r[g]!==`
10
10
  `;)g++;continue}if(m===`
11
11
  `||m==="\r"&&M===`
12
12
  `)if(y)p+=m;else{(p.length>0||!a)&&h.push(p),v&&d?h.forEach(N=>d.push(u?u(N):N)):d?l.push(this.buildObjectRow(d,h,n,c)):l.push([...h]),h=[],p="",v=!1,g+=m==="\r"&&M===`
13
13
  `?1:0;continue}else if(m===k&&!y)h.push(p),p="";else if(m===t)y?M===s?(p+=t,g++):y=!1:p.length===0?y=!0:p+=m;else if((y||p.length===0)&&(m==="{"||m==="[")){const N=this.extractJson(r,g,k);p+=N.value,g+=N.length-1}else p+=m}return(p.length>0||!a)&&h.push(p),h.length&&(v&&d?h.forEach(m=>d.push(u?u(m):m)):d?l.push(this.buildObjectRow(d,h,n,c)):l.push([...h])),l}buildObjectRow(r,e,t,s){const o={};for(let n=0;n<r.length;n++){const i=r[n];let a=e[n];t&&(a=this.dynamicType(a)),o[i]=s?s(a,i):a}return o}detectDelimiter(r){const e=r.slice(0,r.indexOf(`
14
14
  `)),t=[",",";"," ","|"],s=t.map(o=>{const n=new RegExp(`\\${o}`,"g");return(e.match(n)||[]).length});return t[s.indexOf(Math.max(...s))]||","}dynamicType(r){if(r==="true")return!0;if(r==="false")return!1;if(!isNaN(Number(r)))return Number(r);try{return JSON.parse(r)}catch{return r}}extractJson(r,e,t){const s=[];let o=e,n=!1,i="";for(;o<r.length;){const a=r[o];if(!n&&a===t)break;if(!n&&(a===`
15
- `||a==="\r")){this.log.error("JSON block spans multiple lines",void 0,{startIndex:e,endIndex:o});break}if(a==='"'&&i!=="\\"&&(n=!n),n||(a==="{"||a==="["?s.push(a):(a==="}"&&s[s.length-1]==="{"||a==="]"&&s[s.length-1]==="[")&&s.pop()),o++,i=a,s.length===0&&!n)break}return{value:r.slice(e,o),length:o-e}}};function On(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class qm{loader;log=Br.child({prefix:"CsvParser"});constructor(e){this.loader=e}getParserConfig(e,t,s,o){const n=this.loader.config.get()?.options,i=this.loader.options,a=this.log,u={};typeof t?.csvParserOptions?.quoteChar<"u"?u.quoteChar=t?.csvParserOptions?.quoteChar:typeof n?.csvParserOptions?.quoteChar<"u"?u.quoteChar=n?.csvParserOptions?.quoteChar:u.quoteChar=i.csvParserOptions?.quoteChar,typeof t?.csvParserOptions?.delimiter<"u"?u.delimiter=t?.csvParserOptions?.delimiter:typeof n?.csvParserOptions?.delimiter<"u"?u.delimiter=n?.csvParserOptions?.delimiter:u.delimiter=i.csvParserOptions?.delimiter,typeof t?.csvParserOptions?.escapeChar<"u"?u.escapeChar=t?.csvParserOptions?.escapeChar:typeof n?.csvParserOptions?.escapeChar<"u"?u.escapeChar=n?.csvParserOptions?.escapeChar:u.escapeChar=i.csvParserOptions?.escapeChar,typeof t?.csvParserOptions?.commentChar<"u"?u.commentChar=t?.csvParserOptions?.commentChar:typeof n?.csvParserOptions?.commentChar<"u"?u.commentChar=n?.csvParserOptions?.commentChar:u.commentChar=i.csvParserOptions?.commentChar;const c=new Map,l=new Map;if(e.references)for(const p of e.references)c.set(p.key,p),p.origin&&c.set(p.origin,p);if(e.properties)for(const p of e.properties)l.set(p.key,p),p.origin&&l.set(p.origin,p);const d=t?.keyProperty??e.keyProperty??"key",f=Array.isArray(d)?d:[d],h=new Set(f);return{delimiter:u?.delimiter,quoteChar:u?.quoteChar,escapeChar:u?.escapeChar,comments:u.commentChar,dynamicTyping:!1,header:!0,skipEmptyLines:!0,transformHeader:p=>{const y=p?.trim().replace(/"/g,"");return s&&y&&s.push(y),y},transform:function(p,y){if(typeof y>"u"||h.has(y))return p;if(p==="null")return null;if(p===""||typeof p>"u")return;const v=m=>{if(!o)return;const M=o[y];M?M.count+=1:o[y]={rawValue:p,expected:m,count:1}},g=c.get(y);if(g)if(p[0]==="{"||p[0]==="[")try{return JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV reference field",m,{header:y,value:p});return}else return g.type==="singleValued"?p:p?.length>0&&g.type==="multiValued"?On(p,g?.separator):p;const k=l.get(y);if(!(!e.autoGenerateProperties&&!k))switch(k?.type){case"string":return p;case"int":{const m=parseInt(p,10);if(isNaN(m)){v("int");return}return m}case"float":{const m=parseFloat(p);if(isNaN(m)){v("float");return}return m}case"boolean":if(p==="true")return!0;if(p==="false")return!1;v("boolean");return;case"json":try{return p=p.replace(/[\x00-\x1F\x7F-\x9F]/g,""),JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV property field",m,{header:y,value:p}),v("json");return}case"Array<string>":case"Array<int>":case"Array<float>":case"Array<date>":if(p&&typeof p=="string"&&p[0]==="[")try{return JSON.parse(p)}catch{v(k.type);return}if(p&&typeof p=="string")return On(p,k?.separator);v(k.type);return;default:return p}}}}getJsonFromCSVString(e,t,s){return this.getJsonFromCSVStringWithMetadata(e,t,s).data}getJsonFromCSVStringWithMetadata(e,t,s){const o=[],n={},i=this.getParserConfig(t,s.options,o,n);return{data:new Fm().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Kn=typeof global=="object"&&global&&global.Object===Object&&global,Qm=typeof self=="object"&&self&&self.Object===Object&&self,X=Kn||Qm||Function("return this")(),Fe=X.Symbol,Fn=Object.prototype,Bm=Fn.hasOwnProperty,Vm=Fn.toString,lt=Fe?Fe.toStringTag:void 0;function Gm(r){var e=Bm.call(r,lt),t=r[lt];try{r[lt]=void 0;var s=!0}catch{}var o=Vm.call(r);return s&&(e?r[lt]=t:delete r[lt]),o}var Um=Object.prototype,Nm=Um.toString;function zm(r){return Nm.call(r)}var Lm="[object Null]",Wm="[object Undefined]",qn=Fe?Fe.toStringTag:void 0;function dt(r){return r==null?r===void 0?Wm:Lm:qn&&qn in Object(r)?Gm(r):zm(r)}function qe(r){return r!=null&&typeof r=="object"}function Hm(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Gr=Array.isArray;function Qt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Qn(r){return r}var Jm="[object AsyncFunction]",Zm="[object Function]",Xm="[object GeneratorFunction]",Ym="[object Proxy]";function Bn(r){if(!Qt(r))return!1;var e=dt(r);return e==Zm||e==Xm||e==Jm||e==Ym}var Ur=X["__core-js_shared__"],Vn=(function(){var r=/[^.]+$/.exec(Ur&&Ur.keys&&Ur.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ev(r){return!!Vn&&Vn in r}var tv=Function.prototype,rv=tv.toString;function we(r){if(r!=null){try{return rv.call(r)}catch{}try{return r+""}catch{}}return""}var sv=/[\\^$.*+?()[\]{}|]/g,ov=/^\[object .+?Constructor\]$/,nv=Function.prototype,iv=Object.prototype,av=nv.toString,uv=iv.hasOwnProperty,cv=RegExp("^"+av.call(uv).replace(sv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function lv(r){if(!Qt(r)||ev(r))return!1;var e=Bn(r)?cv:ov;return e.test(we(r))}function dv(r,e){return r?.[e]}function Ae(r,e){var t=dv(r,e);return lv(t)?t:void 0}var Nr=Ae(X,"WeakMap"),Gn=Object.create,fv=(function(){function r(){}return function(e){if(!Qt(e))return{};if(Gn)return Gn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function pv(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var hv=800,yv=16,gv=Date.now;function mv(r){var e=0,t=0;return function(){var s=gv(),o=yv-(s-t);if(t=s,o>0){if(++e>=hv)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function vv(r){return function(){return r}}var Bt=(function(){try{var r=Ae(Object,"defineProperty");return r({},"",{}),r}catch{}})(),bv=Bt?function(r,e){return Bt(r,"toString",{configurable:!0,enumerable:!1,value:vv(e),writable:!0})}:Qn,kv=mv(bv);function wv(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Av(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Cv(r){return r!==r}function $v(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function Dv(r,e,t){return e===e?$v(r,e,t):Av(r,Cv,t)}function _v(r,e){var t=r==null?0:r.length;return!!t&&Dv(r,e,0)>-1}var Pv=9007199254740991,xv=/^(?:0|[1-9]\d*)$/;function Ev(r,e){var t=typeof r;return e=e??Pv,!!e&&(t=="number"||t!="symbol"&&xv.test(r))&&r>-1&&r%1==0&&r<e}function jv(r,e,t){e=="__proto__"&&Bt?Bt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Un(r,e){return r===e||r!==r&&e!==e}var Sv=Object.prototype,Mv=Sv.hasOwnProperty;function Rv(r,e,t){var s=r[e];(!(Mv.call(r,e)&&Un(s,t))||t===void 0&&!(e in r))&&jv(r,e,t)}var Nn=Math.max;function Tv(r,e,t){return e=Nn(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=Nn(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),pv(r,this,a)}}function Iv(r,e){return kv(Tv(r,e,Qn),r+"")}var Ov=9007199254740991;function zn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ov}function Ln(r){return r!=null&&zn(r.length)&&!Bn(r)}var Kv=Object.prototype;function Wn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Kv;return r===t}function Fv(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var qv="[object Arguments]";function Hn(r){return qe(r)&&dt(r)==qv}var Jn=Object.prototype,Qv=Jn.hasOwnProperty,Bv=Jn.propertyIsEnumerable,Vv=Hn((function(){return arguments})())?Hn:function(r){return qe(r)&&Qv.call(r,"callee")&&!Bv.call(r,"callee")};function Gv(){return!1}var Zn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xn=Zn&&typeof module=="object"&&module&&!module.nodeType&&module,Uv=Xn&&Xn.exports===Zn,Yn=Uv?X.Buffer:void 0,Nv=Yn?Yn.isBuffer:void 0,ei=Nv||Gv,zv="[object Arguments]",Lv="[object Array]",Wv="[object Boolean]",Hv="[object Date]",Jv="[object Error]",Zv="[object Function]",Xv="[object Map]",Yv="[object Number]",eb="[object Object]",tb="[object RegExp]",rb="[object Set]",sb="[object String]",ob="[object WeakMap]",nb="[object ArrayBuffer]",ib="[object DataView]",ab="[object Float32Array]",ub="[object Float64Array]",cb="[object Int8Array]",lb="[object Int16Array]",db="[object Int32Array]",fb="[object Uint8Array]",pb="[object Uint8ClampedArray]",hb="[object Uint16Array]",yb="[object Uint32Array]",_={};_[ab]=_[ub]=_[cb]=_[lb]=_[db]=_[fb]=_[pb]=_[hb]=_[yb]=!0,_[zv]=_[Lv]=_[nb]=_[Wv]=_[ib]=_[Hv]=_[Jv]=_[Zv]=_[Xv]=_[Yv]=_[eb]=_[tb]=_[rb]=_[sb]=_[ob]=!1;function gb(r){return qe(r)&&zn(r.length)&&!!_[dt(r)]}function zr(r){return function(e){return r(e)}}var ti=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ft=ti&&typeof module=="object"&&module&&!module.nodeType&&module,mb=ft&&ft.exports===ti,Lr=mb&&Kn.process,Qe=(function(){try{var r=ft&&ft.require&&ft.require("util").types;return r||Lr&&Lr.binding&&Lr.binding("util")}catch{}})(),ri=Qe&&Qe.isTypedArray,vb=ri?zr(ri):gb,bb=Object.prototype,kb=bb.hasOwnProperty;function wb(r,e){var t=Gr(r),s=!t&&Vv(r),o=!t&&!s&&ei(r),n=!t&&!s&&!o&&vb(r),i=t||s||o||n,a=i?Fv(r.length,String):[],u=a.length;for(var c in r)kb.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ev(c,u)))&&a.push(c);return a}function si(r,e){return function(t){return r(e(t))}}var Ab=si(Object.keys,Object),Cb=Object.prototype,$b=Cb.hasOwnProperty;function Db(r){if(!Wn(r))return Ab(r);var e=[];for(var t in Object(r))$b.call(r,t)&&t!="constructor"&&e.push(t);return e}function _b(r){return Ln(r)?wb(r):Db(r)}var pt=Ae(Object,"create");function Pb(){this.__data__=pt?pt(null):{},this.size=0}function xb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Eb="__lodash_hash_undefined__",jb=Object.prototype,Sb=jb.hasOwnProperty;function Mb(r){var e=this.__data__;if(pt){var t=e[r];return t===Eb?void 0:t}return Sb.call(e,r)?e[r]:void 0}var Rb=Object.prototype,Tb=Rb.hasOwnProperty;function Ib(r){var e=this.__data__;return pt?e[r]!==void 0:Tb.call(e,r)}var Ob="__lodash_hash_undefined__";function Kb(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=pt&&e===void 0?Ob:e,this}function Ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ce.prototype.clear=Pb,Ce.prototype.delete=xb,Ce.prototype.get=Mb,Ce.prototype.has=Ib,Ce.prototype.set=Kb;function Fb(){this.__data__=[],this.size=0}function Vt(r,e){for(var t=r.length;t--;)if(Un(r[t][0],e))return t;return-1}var qb=Array.prototype,Qb=qb.splice;function Bb(r){var e=this.__data__,t=Vt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Qb.call(e,t,1),--this.size,!0}function Vb(r){var e=this.__data__,t=Vt(e,r);return t<0?void 0:e[t][1]}function Gb(r){return Vt(this.__data__,r)>-1}function Ub(r,e){var t=this.__data__,s=Vt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ie(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ie.prototype.clear=Fb,ie.prototype.delete=Bb,ie.prototype.get=Vb,ie.prototype.has=Gb,ie.prototype.set=Ub;var ht=Ae(X,"Map");function Nb(){this.size=0,this.__data__={hash:new Ce,map:new(ht||ie),string:new Ce}}function zb(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Gt(r,e){var t=r.__data__;return zb(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Lb(r){var e=Gt(this,r).delete(r);return this.size-=e?1:0,e}function Wb(r){return Gt(this,r).get(r)}function Hb(r){return Gt(this,r).has(r)}function Jb(r,e){var t=Gt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function $e(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}$e.prototype.clear=Nb,$e.prototype.delete=Lb,$e.prototype.get=Wb,$e.prototype.has=Hb,$e.prototype.set=Jb;function Zb(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Xb=si(Object.getPrototypeOf,Object);function Yb(){this.__data__=new ie,this.size=0}function ek(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function tk(r){return this.__data__.get(r)}function rk(r){return this.__data__.has(r)}var sk=200;function ok(r,e){var t=this.__data__;if(t instanceof ie){var s=t.__data__;if(!ht||s.length<sk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new $e(s)}return t.set(r,e),this.size=t.size,this}function Be(r){var e=this.__data__=new ie(r);this.size=e.size}Be.prototype.clear=Yb,Be.prototype.delete=ek,Be.prototype.get=tk,Be.prototype.has=rk,Be.prototype.set=ok;var oi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ni=oi&&typeof module=="object"&&module&&!module.nodeType&&module,nk=ni&&ni.exports===oi,ii=nk?X.Buffer:void 0;ii&&ii.allocUnsafe;function ik(r,e){return r.slice()}function ak(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function uk(){return[]}var ck=Object.prototype,lk=ck.propertyIsEnumerable,ai=Object.getOwnPropertySymbols,dk=ai?function(r){return r==null?[]:(r=Object(r),ak(ai(r),function(e){return lk.call(r,e)}))}:uk;function fk(r,e,t){var s=e(r);return Gr(r)?s:Zb(s,t(r))}function pk(r){return fk(r,_b,dk)}var Wr=Ae(X,"DataView"),Hr=Ae(X,"Promise"),Jr=Ae(X,"Set"),ui="[object Map]",hk="[object Object]",ci="[object Promise]",li="[object Set]",di="[object WeakMap]",fi="[object DataView]",yk=we(Wr),gk=we(ht),mk=we(Hr),vk=we(Jr),bk=we(Nr),ae=dt;(Wr&&ae(new Wr(new ArrayBuffer(1)))!=fi||ht&&ae(new ht)!=ui||Hr&&ae(Hr.resolve())!=ci||Jr&&ae(new Jr)!=li||Nr&&ae(new Nr)!=di)&&(ae=function(r){var e=dt(r),t=e==hk?r.constructor:void 0,s=t?we(t):"";if(s)switch(s){case yk:return fi;case gk:return ui;case mk:return ci;case vk:return li;case bk:return di}return e});var kk=Object.prototype,wk=kk.hasOwnProperty;function Ak(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&wk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var pi=X.Uint8Array;function Zr(r){var e=new r.constructor(r.byteLength);return new pi(e).set(new pi(r)),e}function Ck(r,e){var t=Zr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var $k=/\w*$/;function Dk(r){var e=new r.constructor(r.source,$k.exec(r));return e.lastIndex=r.lastIndex,e}var hi=Fe?Fe.prototype:void 0,yi=hi?hi.valueOf:void 0;function _k(r){return yi?Object(yi.call(r)):{}}function Pk(r,e){var t=Zr(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var xk="[object Boolean]",Ek="[object Date]",jk="[object Map]",Sk="[object Number]",Mk="[object RegExp]",Rk="[object Set]",Tk="[object String]",Ik="[object Symbol]",Ok="[object ArrayBuffer]",Kk="[object DataView]",Fk="[object Float32Array]",qk="[object Float64Array]",Qk="[object Int8Array]",Bk="[object Int16Array]",Vk="[object Int32Array]",Gk="[object Uint8Array]",Uk="[object Uint8ClampedArray]",Nk="[object Uint16Array]",zk="[object Uint32Array]";function Lk(r,e,t){var s=r.constructor;switch(e){case Ok:return Zr(r);case xk:case Ek:return new s(+r);case Kk:return Ck(r);case Fk:case qk:case Qk:case Bk:case Vk:case Gk:case Uk:case Nk:case zk:return Pk(r);case jk:return new s;case Sk:case Tk:return new s(r);case Mk:return Dk(r);case Rk:return new s;case Ik:return _k(r)}}function Wk(r){return typeof r.constructor=="function"&&!Wn(r)?fv(Xb(r)):{}}var Hk="[object Map]";function Jk(r){return qe(r)&&ae(r)==Hk}var gi=Qe&&Qe.isMap,Zk=gi?zr(gi):Jk,Xk="[object Set]";function Yk(r){return qe(r)&&ae(r)==Xk}var mi=Qe&&Qe.isSet,ew=mi?zr(mi):Yk,vi="[object Arguments]",tw="[object Array]",rw="[object Boolean]",sw="[object Date]",ow="[object Error]",bi="[object Function]",nw="[object GeneratorFunction]",iw="[object Map]",aw="[object Number]",ki="[object Object]",uw="[object RegExp]",cw="[object Set]",lw="[object String]",dw="[object Symbol]",fw="[object WeakMap]",pw="[object ArrayBuffer]",hw="[object DataView]",yw="[object Float32Array]",gw="[object Float64Array]",mw="[object Int8Array]",vw="[object Int16Array]",bw="[object Int32Array]",kw="[object Uint8Array]",ww="[object Uint8ClampedArray]",Aw="[object Uint16Array]",Cw="[object Uint32Array]",C={};C[vi]=C[tw]=C[pw]=C[hw]=C[rw]=C[sw]=C[yw]=C[gw]=C[mw]=C[vw]=C[bw]=C[iw]=C[aw]=C[ki]=C[uw]=C[cw]=C[lw]=C[dw]=C[kw]=C[ww]=C[Aw]=C[Cw]=!0,C[ow]=C[bi]=C[fw]=!1;function Ut(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Qt(r))return r;var a=Gr(r);if(a)i=Ak(r);else{var u=ae(r),c=u==bi||u==nw;if(ei(r))return ik(r);if(u==ki||u==vi||c&&!o)i=c?{}:Wk(r);else{if(!C[u])return o?r:{};i=Lk(r,u)}}n||(n=new Be);var l=n.get(r);if(l)return l;n.set(r,i),ew(r)?r.forEach(function(h){i.add(Ut(h,e,t,h,r,n))}):Zk(r)&&r.forEach(function(h,p){i.set(p,Ut(h,e,t,p,r,n))});var d=pk,f=a?void 0:d(r);return wv(f||r,function(h,p){f&&(p=h,h=r[p]),Rv(i,p,Ut(h,e,t,p,r,n))}),i}var $w=1,Dw=4;function yt(r){return Ut(r,$w|Dw)}var _w="__lodash_hash_undefined__";function Pw(r){return this.__data__.set(r,_w),this}function xw(r){return this.__data__.has(r)}function Nt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new $e;++e<t;)this.add(r[e])}Nt.prototype.add=Nt.prototype.push=Pw,Nt.prototype.has=xw;function wi(r,e){return r.has(e)}function Ew(r){return qe(r)&&Ln(r)}var jw=Math.min;function Sw(r,e,t){for(var s=_v,o=r[0].length,n=r.length,i=n,a=Array(n),u=1/0,c=[];i--;){var l=r[i];u=jw(l.length,u),a[i]=o>=120&&l.length>=120?new Nt(i&&l):void 0}l=r[0];var d=-1,f=a[0];e:for(;++d<o&&c.length<u;){var h=l[d],p=h;if(h=h!==0?h:0,!(f?wi(f,p):s(c,p))){for(i=n;--i;){var y=a[i];if(!(y?wi(y,p):s(r[i],p)))continue e}f&&f.push(p),c.push(h)}}return c}function Mw(r){return Ew(r)?r:[]}var Ai=Iv(function(r){var e=Hm(r,Mw);return e.length&&e[0]===r[0]?Sw(e):[]});class Ci{context="";total=0;totalItems=[];processedItems=new Set;downloadedItems=new Set;failedItems=new Set;remainingItems=new Set;processed=0;remaining=0;progress=0;currentItem;constructor(){}init(e){return this.total=e.length,this.totalItems=[...e],this.remaining=e.length,this.remainingItems=new Set(e),this.getProgress()}update(e,t,s,o){const n=yt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values())}}}var Rw=Object.defineProperty,Tw=Object.getOwnPropertyDescriptor,$i=(r,e,t,s)=>{for(var o=Tw(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Rw(e,t,o),o};const Iw={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let Xr=class{key;core;cdRef=new Km;log=Br.child({prefix:"AppLoader"});registeredTransformers=[];options=Iw;csvParser=new qm(this);currentConfig;globalVariables=new Map;defaultVariables=new Map;progressListeners=new Set;currentProcessOptions;currentContext="";progressHandler=new Ci;constructor(){this.initDefaultVariables()}destroy(){this.core=null,this.cdRef=null,this.csvParser=null,this.progressListeners=null,this.progressHandler=null}initDefaultVariables(){this.defaultVariables.set("projectId",{key:"projectId",value:void 0,description:"Your dcupl console project id"}),this.defaultVariables.set("apiKey",{key:"apiKey",value:void 0,description:"Your dcupl console project API key"}),this.defaultVariables.set("version",{key:"version",value:"draft",description:"The version of uploaded files to the dcupl CDN - draft/published/..."}),this.defaultVariables.set("cdnBaseUrl",{key:"cdnBaseUrl",value:"https://cdn.dcupl.com/files/projects",description:"The url to your dcupl folder - might be the dcupl CDN or any other "}),this.defaultVariables.set("baseUrl",{key:"baseUrl",value:"${cdnBaseUrl}/${projectId}/${version}",description:"The base url to your hosted models and data files"}),this.defaultVariables.set("modelUrl",{key:"modelUrl",value:"${baseUrl}/models",description:"The url to the your model files"}),this.defaultVariables.set("dataUrl",{key:"dataUrl",value:"${baseUrl}/data",description:"The url to the your data files"}),this.defaultVariables.set("transformerUrl",{key:"transformerUrl",value:"${baseUrl}/transformers",description:"The url to the your data files"}),this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:"dcupl.lc.json",description:"The file name of the loader json"}),this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:void 0,description:"The file-version of the CDN data"}),this.defaultVariables.set("consoleApiUrl",{key:"consoleApiUrl",value:"https://api.dcupl.com",description:"The dcupl console API Url"})}resources={get:r=>this.currentConfig?.resources.find(e=>e.key===r),getAll:()=>this.currentConfig?.resources||[],getWithTag:r=>this.currentConfig?.resources.filter(e=>e.tags?.includes(r))||[],set:r=>{this.currentConfig.resources=r},add:r=>{this.currentConfig.resources.push(r)},delete:r=>{const e=this.currentConfig.resources.findIndex(t=>t.key===r);e>-1&&this.currentConfig.resources.splice(e,1)}};variables={get:(r,e)=>{const t=this.currentConfig?.environments?.filter(s=>s.key===e);return this.evaluateVariables(t,this.currentProcessOptions).find(s=>s.key===r)},getAll:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.evaluateVariables(e,this.currentProcessOptions)},getAllAsObject:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.getEvaluatedVariablesAsRecord(e,this.currentProcessOptions)},default:{get:r=>this.defaultVariables.get(r),getAll:()=>Array.from(this.defaultVariables.values())},environment:{get:(r,e)=>{if(!r)return;const t=this.currentConfig?.environments?.find(s=>s.key===r);if(t)return t.variables?.find(s=>s.key===e)},getAll:r=>this.currentConfig?.environments?.find(e=>e.key===r)?.variables||[]},process:{get:r=>this.currentProcessOptions?.variables?.find(e=>e.key===r),getAll:()=>this.currentProcessOptions?.variables||[]},global:{get:r=>this.globalVariables.get(r),getAll:()=>Array.from(this.globalVariables.values()),set:(r,e)=>{this.globalVariables.set(r,{key:r,value:e})},delete:r=>{this.globalVariables.delete(r)}}};transformers={get:r=>this.registeredTransformers.filter(e=>Ai(e.applyTo,r.appyTo).length>0),getAll:()=>this.registeredTransformers,set:r=>{this.transformers.remove(r.key),this.registeredTransformers.push(r)},remove:r=>{const e=this.registeredTransformers.findIndex(t=>t.key===r);e>-1&&this.registeredTransformers.splice(e,1)}};config={get:()=>yt(this.currentConfig),set:r=>{this.currentConfig=yt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${r}`);return s.json()}catch(t){this.log.error("Could not fetch loader configuration",t,{url:r});return}}async loadConfigFromApi(){const r=this.variables.get("baseUrl")?.value,e=this.variables.get("loaderFileName")?.value,t=this.variables.get("cdnVersion")?.value,s=this.variables.get("apiKey")?.value;try{let o=`${r}/${e}`;this.isDcuplCdn(o)&&(t&&(o=this.appendSearchParamToUrl(o,"v",String(t))),s&&(o=this.appendSearchParamToUrl(o,"api-key",s)));const n=await fetch(o);if(!n.ok)throw new Error(`Failed to fetch loader configuration from ${o}`);return n.json()}catch(o){this.log.error("Could not fetch loader configuration. Are you sure your projectId + apiKey are correct?",o,{baseUrl:r,loaderFileName:e});return}}appendSearchParamToUrl(r,e,t){const s=r.includes("?")?"&":"?";return`${r}${s}${e}=${t}`}async setCdnVersion(){let r;try{const e=this.variables.get("consoleApiUrl")?.value,t=this.variables.get("projectId")?.value,s=this.variables.get("version")?.value;r=`${e}/projects/${t}/files/versions/${s}/status`;const o=await(await fetch(r)).json();o&&o.changedAt&&this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:String(o.changedAt)})}catch(e){this.log.error("Could not fetch version status",e,{url:r})}}async process(r){if(!this.config)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");this.currentContext=Vr();const e=yt(r),t=yt(this.currentConfig);if(e?.applicationKey){const l=this.getAppPreset(t,e);if(!l)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||l?.resourceTags,e.variables=e.variables||l?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=this.getResourcesForConfigOptions(t,o,e),u=this.getLoaderOptions(t,e),c=await this.fetchResources(a,o,u,n,i);return this.currentProcessOptions=e,c}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}getResourcesForConfigOptions(r,e,t){const s=[];if(!r.resources)return[];if(!Array.isArray(t?.resourceTags)||!t?.resourceTags.length)s.push(...r.resources);else for(const o of r.resources)!Array.isArray(o.tags)||!o.tags.length||this.isValidResourceForTags(o.tags,t.resourceTags)&&s.push(o);return s.map(o=>{if(e){const n=qt(o.url,{...e});return o.url=n,o}else return o})}isValidResourceForTags(r,e){for(const t of e)if(Array.isArray(t)){if(t.every(s=>r.includes(s)))return!0}else if(r.includes(t))return!0;return!1}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=qt(n.value,o);return s}getEvaluatedVariablesAsRecord(r,e){const t=this.evaluateVariables(r,e),s={};for(const o of t)s[o.key]=o.value||"";return s}getEnvironments(r,e){if(!(!r.environments||!r.environments[0])&&e&&e.environmentKeys&&e.environmentKeys.length>0)return r.environments.filter(t=>e.environmentKeys.indexOf(t.key)>-1)}getAppPreset(r,e){if(!(!r.applications||!r.applications[0])&&e?.applicationKey)return r.applications?.find(t=>t.key===e.applicationKey)}getHeaderForUrl(r,e,t){if(!t||!t.length||!r.tags?.length)return;const s=[];t?.forEach(n=>{if(!n.tags?.length){this.isValidCondition(n,e)&&s.push(n);return}n.tags.find(i=>r.tags?.includes(i))&&this.isValidCondition(n,e)&&s.push(n)});const o={};if(s.forEach(n=>{const i=qt(n.value,{...e});o[n.key]=i}),Object.keys(o).length!==0)return o}getQueryParamsForUrl(r,e,t){const s=[];if(t?.forEach(o=>{if(!o.tags?.length){this.isValidCondition(o,e)&&s.push(o);return}o.tags.find(n=>r.tags?.includes(n))&&this.isValidCondition(o,e)&&s.push(o)}),this.isDcuplCdn(r.url)){const o=e.cdnVersion;o&&s.push({key:"v",value:o}),e.apiKey&&s?.push({key:"api-key",value:e.apiKey})}return s.map(o=>(o.value=qt(o.value,{...e}),o))}isDcuplCdn(r){return r.includes("cdn.dcupl.com")}isValidCondition(r,e){return r.condition?.applyIfVariableHasValue?typeof e[r.condition?.applyIfVariableHasValue]<"u"&&e[r.condition?.applyIfVariableHasValue]!=="":!0}async handleScriptResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.scriptKey;if(this.core.scriptController.hasScript(n)){const u=this.progressHandler.update(o,!0,"script");return this.updateProgressListeners(u),null}const i=await this.fetchScript(o,e,t,s);this.core.scriptController.setScript(n,i);const a=this.progressHandler.update(o,!0,"script");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load script resource",n,{url:o.url,scriptKey:o.scriptKey});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"script");this.updateProgressListeners(a);return}})),!0}async handleOperatorResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.operator;if(this.core.queryManager.registeredCustomOperator.has(n)){const u=this.progressHandler.update(o,!0,"operator");return this.updateProgressListeners(u),null}const i=await this.fetchJavascriptFile(o,e,t,s);this.core.query.registerCustomOperator(n,i);const a=this.progressHandler.update(o,!0,"operator");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load operator resource",n,{url:o.url,operator:o.operator});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"operator");this.updateProgressListeners(a);return}})),!0}async handleTransformerResources(r,e,t,s){const o=[];return await Promise.all(r.map(async n=>{try{const i=this.registeredTransformers.find(l=>l.key===n.url);if(i){o.push(i);const l=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(l);return}const a=await this.fetchJavascriptFile(n,e,t,s),u={key:n.url,applyTo:n.applyTo||[],type:n.transformerType||"parsedFileTransformer",transformer:a};this.registeredTransformers.push(u),o.push(u);const c=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(c)}catch(i){this.log.error("Failed to load transformer resource",i,{url:n.url,transformerType:n.transformerType});const a={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:i?.message};this.setError(a);const u=this.progressHandler.update(n,!1,"transformer");this.updateProgressListeners(u)}})),o}getRequestOptions(r,e,t,s){const o=this.getHeaderForUrl(r,e,t),n=this.getQueryParamsForUrl(r,e,s);return{url:this.appendQueryParamsToUrl(r.url,n),headers:o}}async fetchScript(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${o}`);return await i.text()}async fetchJavascriptFile(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${o}`);const a=await i.text();return new Function(a)()}isValidModelDefinitionShape(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;const e=r;return!(typeof e.key!="string"||e.key.length===0||typeof e.properties<"u"&&!Array.isArray(e.properties))}emitInvalidModelDefinitionError(r,e,t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:t??"",meta:r,description:e};this.setError(s)}async handleModelResources(r,e,t,s){const o=r.map(async n=>{const i=new Date().getTime();let a;try{const{url:u,headers:c}=this.getRequestOptions(n,e,t,s),l=await fetch(u,{headers:c});if(a=l.status,!l.ok)throw new Error(`Failed to fetch data from ${u}`);const d=F.now(),f=await l.json(),h=F.now(),p=Array.isArray(f)?f:[f],y=[];for(const m of p)this.isValidModelDefinitionShape(m)?y.push(m):this.emitInvalidModelDefinitionError(n,"Resource body is not a valid ModelDefinition (missing or invalid `key`/`properties`)",typeof m?.key=="string"?m.key:void 0);if(y.length===0){const m=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(m),Promise.resolve(null)}const v=y.map(m=>m.key).join("__"),g=F.getEntriesByName(u.toString());if(Array.isArray(g)&&g[0]){const m=g[0],M={name:n.url,type:"resource",createdAt:new Date().getTime(),value:{model:v,type:"model",start:i,startTime:m.startTime,requestStart:m.requestStart,responseEnd:m.responseEnd,responseStart:m.responseStart,duration:m.duration,parseEnd:h,parseStart:d,decodedBodySize:m.decodedBodySize,encodedBodySize:m.encodedBodySize,end:h}};this.core.analyticsController.set({value:M,context:this.currentContext})}for(const m of y)this.addModelOrView(n,m);const k=this.progressHandler.update(n,!0,"model");return this.updateProgressListeners(k),Promise.resolve(f)}catch(u){this.log.error("Failed to load model resource",u,{url:n.url});const c={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:u?.message};this.setError(c);const l=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(l),Promise.resolve(null)}});return await Promise.all(o),!0}appendQueryParamsToUrl(r,e){const t=r.includes("?");let s=r;return e&&e.forEach((o,n)=>{s+=`${n===0&&!t?"?":"&"}${encodeURIComponent(o.key)}=${encodeURIComponent(o.value)}`}),s}async handleDataResources(r,e,t,s,o,n){const i=r.map(async a=>{const u=Vr(),c={placeholderUid:u,data:[],model:a.model};this.core.registerContainer(c);const l=new Date().getTime();let d;try{const{url:f,headers:h}=this.getRequestOptions(a,e,s,o),p=await fetch(f,{headers:h});if(d=p.status,!p.ok)throw new Error(`Failed to fetch data from ${f}`);const y=p.headers.get("content-type"),v=F.now();let g;a.url.endsWith(".csv")||y?.includes("text/csv")?g=await p.text():g=await p.json();const k=F.now(),m=F.now(),M=this.handleTransformerLogic(g,a,"rawFileTransformer",n||[]),N=F.now();let mt=[],zt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!zt&&(t?.missingModelHandling?.autoGenerateProperties||a.options?.autoGenerateProperties)){const q=a.options?.autoGenerateProperties??t?.missingModelHandling?.autoGenerateProperties??!0;this.addModelOrView(a,{key:a.model,autoGenerateProperties:q,autoGenerateKey:a.options?.autoGenerateKey||!1,keyProperty:a?.options?.keyProperty||"key",keyPropertySeparator:a?.options?.keyPropertySeparator}),zt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const Fw=F.now();let Di={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(zt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,zt,a);mt=q.data,Di={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else mt=M;const qw=F.now(),Qw=F.now();try{mt=this.handleTransformerLogic(mt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const Bw=F.now(),_i={placeholderUid:u,model:a.model,data:mt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},Yr=F.getEntriesByName(f.toString());if(Array.isArray(Yr)&&Yr[0]){const q=Yr[0],Gw={name:a.url,type:"resource",createdAt:new Date().getTime(),value:{model:a.model,type:"data",start:l,startTime:q.startTime,requestStart:q.requestStart,responseEnd:q.responseEnd,responseStart:q.responseStart,duration:q.duration,parseEnd:k,rawTransformStart:m,rawTransformEnd:N,parseStart:v,csvToJsonStart:Fw,csvToJsonEnd:qw,parsedTransformStart:Qw,parsedTransformEnd:Bw,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:Gw,context:this.currentContext})}this.core.updateRegisteredContainer(_i,Di);const Vw=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(Vw),Promise.resolve(_i)}catch(f){this.log.error("Failed to load data resource",f,{url:a.url,model:a.model});const h={title:a.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:a,model:a.model,description:f?.message};this.setError(h),this.core.removeRegisteredContainer(c);const p=this.progressHandler.update(a,!1,"data",d);return this.updateProgressListeners(p),Promise.resolve()}});return await Promise.all(i),!0}async fetchResources(r,e,t,s,o){this.progressHandler=new Ci,this.progressHandler.init(r),this.updateProgressListeners(this.progressHandler.getProgress());try{if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;const n=r.filter(d=>d.type==="script");await this.handleScriptResources(n,e,s,o);const i=r.filter(d=>d.type==="operator");await this.handleOperatorResources(i,e,s,o);const a=r.filter(d=>d.type==="transformer"),u=await this.handleTransformerResources(a,e,s,o),c=r.filter(d=>d.type==="model");await this.handleModelResources(c,e,s,o);const l=r.filter(d=>d.type==="data");return await this.handleDataResources(l,e,t,s,o,u),!0}catch(n){return this.log.error("Failed to fetch resources",n),!1}}addModelOrView(r,e){try{"model"in e?this.core.views.set(e):this.core.models.set(e)}catch(t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,meta:r,description:t?.message};this.setError(s)}}handleTransformerLogic(r,e,t,s){for(const o of s)o.type===t&&o.transformer&&(!o.applyTo.length&&!e.tags?.length&&(r=o.transformer(e,r)),Ai(o.applyTo,e.tags||[]).length&&(r=o.transformer(e,r)));return r}updateProgressListeners(r){this.progressListeners.forEach(e=>e(r))}on(r){return this.progressListeners.add(r),()=>{this.progressListeners.delete(r)}}setError(r){this.core.modelParser.qualityController.enabled&&this.core.modelParser.qualityController.setError(r)}};$i([In({scope:"global",origin:"loader",type:"loader_config_fetched",connectMessage:!0,connectMessageResult:!0})],Xr.prototype,"fetchConfig"),$i([In({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],Xr.prototype,"process");const Ow=Xr;let gt,Ve;async function Kw(r){return gt=new Wp(r.options),Ve=new Ow,gt.loaders.add(Ve,"default"),r.appLoaderConfig?await Ve.config.fetch(r.appLoaderConfig):await Ve.config.fetch(),await Ve.process(r.processOptions),await gt.init(),globalThis.dcupl=gt,{dcupl:gt,loader:Ve}}globalThis.initDcupl=Kw})();
15
+ `||a==="\r")){this.log.error("JSON block spans multiple lines",void 0,{startIndex:e,endIndex:o});break}if(a==='"'&&i!=="\\"&&(n=!n),n||(a==="{"||a==="["?s.push(a):(a==="}"&&s[s.length-1]==="{"||a==="]"&&s[s.length-1]==="[")&&s.pop()),o++,i=a,s.length===0&&!n)break}return{value:r.slice(e,o),length:o-e}}};function Qn(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class ev{loader;log=Gr.child({prefix:"CsvParser"});constructor(e){this.loader=e}getParserConfig(e,t,s,o){const n=this.loader.config.get()?.options,i=this.loader.options,a=this.log,u={};typeof t?.csvParserOptions?.quoteChar<"u"?u.quoteChar=t?.csvParserOptions?.quoteChar:typeof n?.csvParserOptions?.quoteChar<"u"?u.quoteChar=n?.csvParserOptions?.quoteChar:u.quoteChar=i.csvParserOptions?.quoteChar,typeof t?.csvParserOptions?.delimiter<"u"?u.delimiter=t?.csvParserOptions?.delimiter:typeof n?.csvParserOptions?.delimiter<"u"?u.delimiter=n?.csvParserOptions?.delimiter:u.delimiter=i.csvParserOptions?.delimiter,typeof t?.csvParserOptions?.escapeChar<"u"?u.escapeChar=t?.csvParserOptions?.escapeChar:typeof n?.csvParserOptions?.escapeChar<"u"?u.escapeChar=n?.csvParserOptions?.escapeChar:u.escapeChar=i.csvParserOptions?.escapeChar,typeof t?.csvParserOptions?.commentChar<"u"?u.commentChar=t?.csvParserOptions?.commentChar:typeof n?.csvParserOptions?.commentChar<"u"?u.commentChar=n?.csvParserOptions?.commentChar:u.commentChar=i.csvParserOptions?.commentChar;const c=new Map,l=new Map;if(e.references)for(const p of e.references)c.set(p.key,p),p.origin&&c.set(p.origin,p);if(e.properties)for(const p of e.properties)l.set(p.key,p),p.origin&&l.set(p.origin,p);const d=t?.keyProperty??e.keyProperty??"key",f=Array.isArray(d)?d:[d],h=new Set(f);return{delimiter:u?.delimiter,quoteChar:u?.quoteChar,escapeChar:u?.escapeChar,comments:u.commentChar,dynamicTyping:!1,header:!0,skipEmptyLines:!0,transformHeader:p=>{const y=p?.trim().replace(/"/g,"");return s&&y&&s.push(y),y},transform:function(p,y){if(typeof y>"u"||h.has(y))return p;if(p==="null")return null;if(p===""||typeof p>"u")return;const v=m=>{if(!o)return;const M=o[y];M?M.count+=1:o[y]={rawValue:p,expected:m,count:1}},g=c.get(y);if(g)if(p[0]==="{"||p[0]==="[")try{return JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV reference field",m,{header:y,value:p});return}else return g.type==="singleValued"?p:p?.length>0&&g.type==="multiValued"?Qn(p,g?.separator):p;const k=l.get(y);if(!(!e.autoGenerateProperties&&!k))switch(k?.type){case"string":return p;case"int":{const m=parseInt(p,10);if(isNaN(m)){v("int");return}return m}case"float":{const m=parseFloat(p);if(isNaN(m)){v("float");return}return m}case"boolean":if(p==="true")return!0;if(p==="false")return!1;v("boolean");return;case"json":try{return p=p.replace(/[\x00-\x1F\x7F-\x9F]/g,""),JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV property field",m,{header:y,value:p}),v("json");return}case"Array<string>":case"Array<int>":case"Array<float>":case"Array<date>":if(p&&typeof p=="string"&&p[0]==="[")try{return JSON.parse(p)}catch{v(k.type);return}if(p&&typeof p=="string")return Qn(p,k?.separator);v(k.type);return;default:return p}}}}getJsonFromCSVString(e,t,s){return this.getJsonFromCSVStringWithMetadata(e,t,s).data}getJsonFromCSVStringWithMetadata(e,t,s){const o=[],n={},i=this.getParserConfig(t,s.options,o,n);return{data:new Xm().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Bn=typeof global=="object"&&global&&global.Object===Object&&global,tv=typeof self=="object"&&self&&self.Object===Object&&self,Y=Bn||tv||Function("return this")(),de=Y.Symbol,Vn=Object.prototype,rv=Vn.hasOwnProperty,sv=Vn.toString,ft=de?de.toStringTag:void 0;function ov(r){var e=rv.call(r,ft),t=r[ft];try{r[ft]=void 0;var s=!0}catch{}var o=sv.call(r);return s&&(e?r[ft]=t:delete r[ft]),o}var nv=Object.prototype,iv=nv.toString;function av(r){return iv.call(r)}var uv="[object Null]",cv="[object Undefined]",Gn=de?de.toStringTag:void 0;function Qe(r){return r==null?r===void 0?cv:uv:Gn&&Gn in Object(r)?ov(r):av(r)}function $e(r){return r!=null&&typeof r=="object"}var lv="[object Symbol]";function zr(r){return typeof r=="symbol"||$e(r)&&Qe(r)==lv}function Un(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Be=Array.isArray,Nn=de?de.prototype:void 0,zn=Nn?Nn.toString:void 0;function Ln(r){if(typeof r=="string")return r;if(Be(r))return Un(r,Ln)+"";if(zr(r))return zn?zn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Bt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Wn(r){return r}var dv="[object AsyncFunction]",fv="[object Function]",pv="[object GeneratorFunction]",hv="[object Proxy]";function Hn(r){if(!Bt(r))return!1;var e=Qe(r);return e==fv||e==pv||e==dv||e==hv}var Lr=Y["__core-js_shared__"],Jn=(function(){var r=/[^.]+$/.exec(Lr&&Lr.keys&&Lr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function yv(r){return!!Jn&&Jn in r}var gv=Function.prototype,mv=gv.toString;function Ce(r){if(r!=null){try{return mv.call(r)}catch{}try{return r+""}catch{}}return""}var vv=/[\\^$.*+?()[\]{}|]/g,bv=/^\[object .+?Constructor\]$/,kv=Function.prototype,wv=Object.prototype,Av=kv.toString,$v=wv.hasOwnProperty,Cv=RegExp("^"+Av.call($v).replace(vv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Dv(r){if(!Bt(r)||yv(r))return!1;var e=Hn(r)?Cv:bv;return e.test(Ce(r))}function _v(r,e){return r?.[e]}function De(r,e){var t=_v(r,e);return Dv(t)?t:void 0}var Wr=De(Y,"WeakMap"),Zn=Object.create,Pv=(function(){function r(){}return function(e){if(!Bt(e))return{};if(Zn)return Zn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function xv(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Ev=800,jv=16,Sv=Date.now;function Mv(r){var e=0,t=0;return function(){var s=Sv(),o=jv-(s-t);if(t=s,o>0){if(++e>=Ev)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Rv(r){return function(){return r}}var Vt=(function(){try{var r=De(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Tv=Vt?function(r,e){return Vt(r,"toString",{configurable:!0,enumerable:!1,value:Rv(e),writable:!0})}:Wn,Iv=Mv(Tv);function Ov(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Kv(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Fv(r){return r!==r}function qv(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function Qv(r,e,t){return e===e?qv(r,e,t):Kv(r,Fv,t)}function Bv(r,e){var t=r==null?0:r.length;return!!t&&Qv(r,e,0)>-1}var Vv=9007199254740991,Gv=/^(?:0|[1-9]\d*)$/;function Uv(r,e){var t=typeof r;return e=e??Vv,!!e&&(t=="number"||t!="symbol"&&Gv.test(r))&&r>-1&&r%1==0&&r<e}function Nv(r,e,t){e=="__proto__"&&Vt?Vt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Yn(r,e){return r===e||r!==r&&e!==e}var zv=Object.prototype,Lv=zv.hasOwnProperty;function Wv(r,e,t){var s=r[e];(!(Lv.call(r,e)&&Yn(s,t))||t===void 0&&!(e in r))&&Nv(r,e,t)}var Xn=Math.max;function Hv(r,e,t){return e=Xn(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=Xn(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),xv(r,this,a)}}function Jv(r,e){return Iv(Hv(r,e,Wn),r+"")}var Zv=9007199254740991;function ei(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Zv}function ti(r){return r!=null&&ei(r.length)&&!Hn(r)}var Yv=Object.prototype;function ri(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Yv;return r===t}function Xv(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var eb="[object Arguments]";function si(r){return $e(r)&&Qe(r)==eb}var oi=Object.prototype,tb=oi.hasOwnProperty,rb=oi.propertyIsEnumerable,sb=si((function(){return arguments})())?si:function(r){return $e(r)&&tb.call(r,"callee")&&!rb.call(r,"callee")};function ob(){return!1}var ni=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ii=ni&&typeof module=="object"&&module&&!module.nodeType&&module,nb=ii&&ii.exports===ni,ai=nb?Y.Buffer:void 0,ib=ai?ai.isBuffer:void 0,ui=ib||ob,ab="[object Arguments]",ub="[object Array]",cb="[object Boolean]",lb="[object Date]",db="[object Error]",fb="[object Function]",pb="[object Map]",hb="[object Number]",yb="[object Object]",gb="[object RegExp]",mb="[object Set]",vb="[object String]",bb="[object WeakMap]",kb="[object ArrayBuffer]",wb="[object DataView]",Ab="[object Float32Array]",$b="[object Float64Array]",Cb="[object Int8Array]",Db="[object Int16Array]",_b="[object Int32Array]",Pb="[object Uint8Array]",xb="[object Uint8ClampedArray]",Eb="[object Uint16Array]",jb="[object Uint32Array]",_={};_[Ab]=_[$b]=_[Cb]=_[Db]=_[_b]=_[Pb]=_[xb]=_[Eb]=_[jb]=!0,_[ab]=_[ub]=_[kb]=_[cb]=_[wb]=_[lb]=_[db]=_[fb]=_[pb]=_[hb]=_[yb]=_[gb]=_[mb]=_[vb]=_[bb]=!1;function Sb(r){return $e(r)&&ei(r.length)&&!!_[Qe(r)]}function Hr(r){return function(e){return r(e)}}var ci=typeof exports=="object"&&exports&&!exports.nodeType&&exports,pt=ci&&typeof module=="object"&&module&&!module.nodeType&&module,Mb=pt&&pt.exports===ci,Jr=Mb&&Bn.process,Ve=(function(){try{var r=pt&&pt.require&&pt.require("util").types;return r||Jr&&Jr.binding&&Jr.binding("util")}catch{}})(),li=Ve&&Ve.isTypedArray,Rb=li?Hr(li):Sb,Tb=Object.prototype,Ib=Tb.hasOwnProperty;function Ob(r,e){var t=Be(r),s=!t&&sb(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Rb(r),i=t||s||o||n,a=i?Xv(r.length,String):[],u=a.length;for(var c in r)Ib.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Uv(c,u)))&&a.push(c);return a}function di(r,e){return function(t){return r(e(t))}}var Kb=di(Object.keys,Object),Fb=Object.prototype,qb=Fb.hasOwnProperty;function Qb(r){if(!ri(r))return Kb(r);var e=[];for(var t in Object(r))qb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Bb(r){return ti(r)?Ob(r):Qb(r)}var Vb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Gb=/^\w*$/;function Ub(r,e){if(Be(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||zr(r)?!0:Gb.test(r)||!Vb.test(r)||e!=null&&r in Object(e)}var ht=De(Object,"create");function Nb(){this.__data__=ht?ht(null):{},this.size=0}function zb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Lb="__lodash_hash_undefined__",Wb=Object.prototype,Hb=Wb.hasOwnProperty;function Jb(r){var e=this.__data__;if(ht){var t=e[r];return t===Lb?void 0:t}return Hb.call(e,r)?e[r]:void 0}var Zb=Object.prototype,Yb=Zb.hasOwnProperty;function Xb(r){var e=this.__data__;return ht?e[r]!==void 0:Yb.call(e,r)}var ek="__lodash_hash_undefined__";function tk(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=ht&&e===void 0?ek:e,this}function _e(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}_e.prototype.clear=Nb,_e.prototype.delete=zb,_e.prototype.get=Jb,_e.prototype.has=Xb,_e.prototype.set=tk;function rk(){this.__data__=[],this.size=0}function Gt(r,e){for(var t=r.length;t--;)if(Yn(r[t][0],e))return t;return-1}var sk=Array.prototype,ok=sk.splice;function nk(r){var e=this.__data__,t=Gt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():ok.call(e,t,1),--this.size,!0}function ik(r){var e=this.__data__,t=Gt(e,r);return t<0?void 0:e[t][1]}function ak(r){return Gt(this.__data__,r)>-1}function uk(r,e){var t=this.__data__,s=Gt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ie(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ie.prototype.clear=rk,ie.prototype.delete=nk,ie.prototype.get=ik,ie.prototype.has=ak,ie.prototype.set=uk;var yt=De(Y,"Map");function ck(){this.size=0,this.__data__={hash:new _e,map:new(yt||ie),string:new _e}}function lk(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ut(r,e){var t=r.__data__;return lk(e)?t[typeof e=="string"?"string":"hash"]:t.map}function dk(r){var e=Ut(this,r).delete(r);return this.size-=e?1:0,e}function fk(r){return Ut(this,r).get(r)}function pk(r){return Ut(this,r).has(r)}function hk(r,e){var t=Ut(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ae.prototype.clear=ck,ae.prototype.delete=dk,ae.prototype.get=fk,ae.prototype.has=pk,ae.prototype.set=hk;var yk="Expected a function";function Zr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(yk);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(Zr.Cache||ae),t}Zr.Cache=ae;var gk=500;function mk(r){var e=Zr(r,function(s){return t.size===gk&&t.clear(),s}),t=e.cache;return e}var vk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bk=/\\(\\)?/g,kk=mk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(vk,function(t,s,o,n){e.push(o?n.replace(bk,"$1"):s||t)}),e});function wk(r){return r==null?"":Ln(r)}function Ak(r,e){return Be(r)?r:Ub(r,e)?[r]:kk(wk(r))}function $k(r){if(typeof r=="string"||zr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Ck(r,e){e=Ak(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[$k(e[t++])];return t&&t==s?r:void 0}function Dk(r,e,t){var s=r==null?void 0:Ck(r,e);return s===void 0?t:s}function _k(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Pk=di(Object.getPrototypeOf,Object);function xk(){this.__data__=new ie,this.size=0}function Ek(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function jk(r){return this.__data__.get(r)}function Sk(r){return this.__data__.has(r)}var Mk=200;function Rk(r,e){var t=this.__data__;if(t instanceof ie){var s=t.__data__;if(!yt||s.length<Mk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new ae(s)}return t.set(r,e),this.size=t.size,this}function Ge(r){var e=this.__data__=new ie(r);this.size=e.size}Ge.prototype.clear=xk,Ge.prototype.delete=Ek,Ge.prototype.get=jk,Ge.prototype.has=Sk,Ge.prototype.set=Rk;var fi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,pi=fi&&typeof module=="object"&&module&&!module.nodeType&&module,Tk=pi&&pi.exports===fi,hi=Tk?Y.Buffer:void 0;hi&&hi.allocUnsafe;function Ik(r,e){return r.slice()}function Ok(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Kk(){return[]}var Fk=Object.prototype,qk=Fk.propertyIsEnumerable,yi=Object.getOwnPropertySymbols,Qk=yi?function(r){return r==null?[]:(r=Object(r),Ok(yi(r),function(e){return qk.call(r,e)}))}:Kk;function Bk(r,e,t){var s=e(r);return Be(r)?s:_k(s,t(r))}function Vk(r){return Bk(r,Bb,Qk)}var Yr=De(Y,"DataView"),Xr=De(Y,"Promise"),es=De(Y,"Set"),gi="[object Map]",Gk="[object Object]",mi="[object Promise]",vi="[object Set]",bi="[object WeakMap]",ki="[object DataView]",Uk=Ce(Yr),Nk=Ce(yt),zk=Ce(Xr),Lk=Ce(es),Wk=Ce(Wr),ue=Qe;(Yr&&ue(new Yr(new ArrayBuffer(1)))!=ki||yt&&ue(new yt)!=gi||Xr&&ue(Xr.resolve())!=mi||es&&ue(new es)!=vi||Wr&&ue(new Wr)!=bi)&&(ue=function(r){var e=Qe(r),t=e==Gk?r.constructor:void 0,s=t?Ce(t):"";if(s)switch(s){case Uk:return ki;case Nk:return gi;case zk:return mi;case Lk:return vi;case Wk:return bi}return e});var Hk=Object.prototype,Jk=Hk.hasOwnProperty;function Zk(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Jk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var wi=Y.Uint8Array;function ts(r){var e=new r.constructor(r.byteLength);return new wi(e).set(new wi(r)),e}function Yk(r,e){var t=ts(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Xk=/\w*$/;function ew(r){var e=new r.constructor(r.source,Xk.exec(r));return e.lastIndex=r.lastIndex,e}var Ai=de?de.prototype:void 0,$i=Ai?Ai.valueOf:void 0;function tw(r){return $i?Object($i.call(r)):{}}function rw(r,e){var t=ts(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var sw="[object Boolean]",ow="[object Date]",nw="[object Map]",iw="[object Number]",aw="[object RegExp]",uw="[object Set]",cw="[object String]",lw="[object Symbol]",dw="[object ArrayBuffer]",fw="[object DataView]",pw="[object Float32Array]",hw="[object Float64Array]",yw="[object Int8Array]",gw="[object Int16Array]",mw="[object Int32Array]",vw="[object Uint8Array]",bw="[object Uint8ClampedArray]",kw="[object Uint16Array]",ww="[object Uint32Array]";function Aw(r,e,t){var s=r.constructor;switch(e){case dw:return ts(r);case sw:case ow:return new s(+r);case fw:return Yk(r);case pw:case hw:case yw:case gw:case mw:case vw:case bw:case kw:case ww:return rw(r);case nw:return new s;case iw:case cw:return new s(r);case aw:return ew(r);case uw:return new s;case lw:return tw(r)}}function $w(r){return typeof r.constructor=="function"&&!ri(r)?Pv(Pk(r)):{}}var Cw="[object Map]";function Dw(r){return $e(r)&&ue(r)==Cw}var Ci=Ve&&Ve.isMap,_w=Ci?Hr(Ci):Dw,Pw="[object Set]";function xw(r){return $e(r)&&ue(r)==Pw}var Di=Ve&&Ve.isSet,Ew=Di?Hr(Di):xw,_i="[object Arguments]",jw="[object Array]",Sw="[object Boolean]",Mw="[object Date]",Rw="[object Error]",Pi="[object Function]",Tw="[object GeneratorFunction]",Iw="[object Map]",Ow="[object Number]",xi="[object Object]",Kw="[object RegExp]",Fw="[object Set]",qw="[object String]",Qw="[object Symbol]",Bw="[object WeakMap]",Vw="[object ArrayBuffer]",Gw="[object DataView]",Uw="[object Float32Array]",Nw="[object Float64Array]",zw="[object Int8Array]",Lw="[object Int16Array]",Ww="[object Int32Array]",Hw="[object Uint8Array]",Jw="[object Uint8ClampedArray]",Zw="[object Uint16Array]",Yw="[object Uint32Array]",$={};$[_i]=$[jw]=$[Vw]=$[Gw]=$[Sw]=$[Mw]=$[Uw]=$[Nw]=$[zw]=$[Lw]=$[Ww]=$[Iw]=$[Ow]=$[xi]=$[Kw]=$[Fw]=$[qw]=$[Qw]=$[Hw]=$[Jw]=$[Zw]=$[Yw]=!0,$[Rw]=$[Pi]=$[Bw]=!1;function Nt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Bt(r))return r;var a=Be(r);if(a)i=Zk(r);else{var u=ue(r),c=u==Pi||u==Tw;if(ui(r))return Ik(r);if(u==xi||u==_i||c&&!o)i=c?{}:$w(r);else{if(!$[u])return o?r:{};i=Aw(r,u)}}n||(n=new Ge);var l=n.get(r);if(l)return l;n.set(r,i),Ew(r)?r.forEach(function(h){i.add(Nt(h,e,t,h,r,n))}):_w(r)&&r.forEach(function(h,p){i.set(p,Nt(h,e,t,p,r,n))});var d=Vk,f=a?void 0:d(r);return Ov(f||r,function(h,p){f&&(p=h,h=r[p]),Wv(i,p,Nt(h,e,t,p,r,n))}),i}var Xw=1,eA=4;function gt(r){return Nt(r,Xw|eA)}var tA="__lodash_hash_undefined__";function rA(r){return this.__data__.set(r,tA),this}function sA(r){return this.__data__.has(r)}function zt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new ae;++e<t;)this.add(r[e])}zt.prototype.add=zt.prototype.push=rA,zt.prototype.has=sA;function Ei(r,e){return r.has(e)}function oA(r){return $e(r)&&ti(r)}var nA=Math.min;function iA(r,e,t){for(var s=Bv,o=r[0].length,n=r.length,i=n,a=Array(n),u=1/0,c=[];i--;){var l=r[i];u=nA(l.length,u),a[i]=o>=120&&l.length>=120?new zt(i&&l):void 0}l=r[0];var d=-1,f=a[0];e:for(;++d<o&&c.length<u;){var h=l[d],p=h;if(h=h!==0?h:0,!(f?Ei(f,p):s(c,p))){for(i=n;--i;){var y=a[i];if(!(y?Ei(y,p):s(r[i],p)))continue e}f&&f.push(p),c.push(h)}}return c}function aA(r){return oA(r)?r:[]}var ji=Jv(function(r){var e=Un(r,aA);return e.length&&e[0]===r[0]?iA(e):[]});class Si{context="";total=0;totalItems=[];processedItems=new Set;downloadedItems=new Set;failedItems=new Set;remainingItems=new Set;skippedItems=[];run;processed=0;remaining=0;progress=0;currentItem;constructor(){}init(e,t){return this.total=e.length,this.totalItems=[...e],this.remaining=e.length,this.remainingItems=new Set(e),this.skippedItems=t?.skipped??[],this.run=t?.run,this.getProgress()}update(e,t,s,o){const n=gt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values()),skippedItems:this.skippedItems,run:this.run}}}function uA(r,e){for(const t of e)if(Array.isArray(t)){if(t.every(s=>r.includes(s)))return!0}else if(r.includes(t))return!0;return!1}function cA(r,e){return Ym(r).variables.map(t=>t.name).filter(t=>Dk(e,t)===void 0)}function Mi(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=Zm(o),i=[],a=[],u=Array.isArray(t?.resourceTags)&&t.resourceTags.length>0;return o.forEach((c,l)=>{if(u){if(!Array.isArray(c.tags)||!c.tags.length){a.push({resource:c,reason:"no-tags",id:n[l]});return}if(!uA(c.tags,t.resourceTags)){a.push({resource:c,reason:"tag-mismatch",id:n[l]});return}}const d=c.url??"",f=cA(d,e),h={...c,id:n[l],rawUrl:d,url:Qt(d,{...e})};f.length&&(h.unresolvedVariables=f),i.push(h)}),{scheduled:i,skipped:a,variables:e,run:s}}var lA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,Ri=(r,e,t,s)=>{for(var o=dA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&lA(e,t,o),o};const fA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let rs=class{key;core;cdRef=new Wm;log=Gr.child({prefix:"AppLoader"});registeredTransformers=[];options=fA;csvParser=new ev(this);currentConfig;globalVariables=new Map;defaultVariables=new Map;progressListeners=new Set;currentProcessOptions;currentContext="";progressHandler=new Si;constructor(){this.initDefaultVariables()}destroy(){this.core=null,this.cdRef=null,this.csvParser=null,this.progressListeners=null,this.progressHandler=null}initDefaultVariables(){this.defaultVariables.set("projectId",{key:"projectId",value:void 0,description:"Your dcupl console project id"}),this.defaultVariables.set("apiKey",{key:"apiKey",value:void 0,description:"Your dcupl console project API key"}),this.defaultVariables.set("version",{key:"version",value:"draft",description:"The version of uploaded files to the dcupl CDN - draft/published/..."}),this.defaultVariables.set("cdnBaseUrl",{key:"cdnBaseUrl",value:"https://cdn.dcupl.com/files/projects",description:"The url to your dcupl folder - might be the dcupl CDN or any other "}),this.defaultVariables.set("baseUrl",{key:"baseUrl",value:"${cdnBaseUrl}/${projectId}/${version}",description:"The base url to your hosted models and data files"}),this.defaultVariables.set("modelUrl",{key:"modelUrl",value:"${baseUrl}/models",description:"The url to the your model files"}),this.defaultVariables.set("dataUrl",{key:"dataUrl",value:"${baseUrl}/data",description:"The url to the your data files"}),this.defaultVariables.set("transformerUrl",{key:"transformerUrl",value:"${baseUrl}/transformers",description:"The url to the your data files"}),this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:"dcupl.lc.json",description:"The file name of the loader json"}),this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:void 0,description:"The file-version of the CDN data"}),this.defaultVariables.set("consoleApiUrl",{key:"consoleApiUrl",value:"https://api.dcupl.com",description:"The dcupl console API Url"})}resources={get:r=>this.currentConfig?.resources.find(e=>e.key===r),getAll:()=>this.currentConfig?.resources||[],getWithTag:r=>this.currentConfig?.resources.filter(e=>e.tags?.includes(r))||[],set:r=>{this.currentConfig.resources=r},add:r=>{this.currentConfig.resources.push(r)},delete:r=>{const e=this.currentConfig.resources.findIndex(t=>t.key===r);e>-1&&this.currentConfig.resources.splice(e,1)},plan:r=>{const{config:e,options:t,variables:s}=this.resolveRunContext(r);return Mi(e,s,t)}};variables={get:(r,e)=>{const t=this.currentConfig?.environments?.filter(s=>s.key===e);return this.evaluateVariables(t,this.currentProcessOptions).find(s=>s.key===r)},getAll:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.evaluateVariables(e,this.currentProcessOptions)},getAllAsObject:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.getEvaluatedVariablesAsRecord(e,this.currentProcessOptions)},default:{get:r=>this.defaultVariables.get(r),getAll:()=>Array.from(this.defaultVariables.values())},environment:{get:(r,e)=>{if(!r)return;const t=this.currentConfig?.environments?.find(s=>s.key===r);if(t)return t.variables?.find(s=>s.key===e)},getAll:r=>this.currentConfig?.environments?.find(e=>e.key===r)?.variables||[]},process:{get:r=>this.currentProcessOptions?.variables?.find(e=>e.key===r),getAll:()=>this.currentProcessOptions?.variables||[]},global:{get:r=>this.globalVariables.get(r),getAll:()=>Array.from(this.globalVariables.values()),set:(r,e)=>{this.globalVariables.set(r,{key:r,value:e})},delete:r=>{this.globalVariables.delete(r)}}};transformers={get:r=>this.registeredTransformers.filter(e=>ji(e.applyTo,r.appyTo).length>0),getAll:()=>this.registeredTransformers,set:r=>{this.transformers.remove(r.key),this.registeredTransformers.push(r)},remove:r=>{const e=this.registeredTransformers.findIndex(t=>t.key===r);e>-1&&this.registeredTransformers.splice(e,1)}};config={get:()=>gt(this.currentConfig),set:r=>{this.currentConfig=gt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${r}`);return s.json()}catch(t){this.log.error("Could not fetch loader configuration",t,{url:r});return}}async loadConfigFromApi(){const r=this.variables.get("baseUrl")?.value,e=this.variables.get("loaderFileName")?.value,t=this.variables.get("cdnVersion")?.value,s=this.variables.get("apiKey")?.value;try{let o=`${r}/${e}`;this.isDcuplCdn(o)&&(t&&(o=this.appendSearchParamToUrl(o,"v",String(t))),s&&(o=this.appendSearchParamToUrl(o,"api-key",s)));const n=await fetch(o);if(!n.ok)throw new Error(`Failed to fetch loader configuration from ${o}`);return n.json()}catch(o){this.log.error("Could not fetch loader configuration. Are you sure your projectId + apiKey are correct?",o,{baseUrl:r,loaderFileName:e});return}}appendSearchParamToUrl(r,e,t){const s=r.includes("?")?"&":"?";return`${r}${s}${e}=${t}`}async setCdnVersion(){let r;try{const e=this.variables.get("consoleApiUrl")?.value,t=this.variables.get("projectId")?.value,s=this.variables.get("version")?.value;r=`${e}/projects/${t}/files/versions/${s}/status`;const o=await(await fetch(r)).json();o&&o.changedAt&&this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:String(o.changedAt)})}catch(e){this.log.error("Could not fetch version status",e,{url:r})}}async process(r){if(!this.config)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");this.currentContext=Ur();const{config:e,options:t,environments:s,variables:o}=this.resolveRunContext(r),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=Mi(e,o,t),u=this.getLoaderOptions(e,t),c=await this.fetchResources(a,o,u,n,i);return this.currentProcessOptions=t,c}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}resolveRunContext(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");const e=gt(r),t=gt(this.currentConfig);if(e?.applicationKey){const n=this.getAppPreset(t,e);if(!n)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||n?.resourceTags,e.variables=e.variables||n?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e);return{config:t,options:e,environments:s,variables:o}}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()).map(n=>({...n})),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=Qt(n.value,o);return s}getEvaluatedVariablesAsRecord(r,e){const t=this.evaluateVariables(r,e),s={};for(const o of t)s[o.key]=o.value||"";return s}getEnvironments(r,e){if(!(!r.environments||!r.environments[0])&&e&&e.environmentKeys&&e.environmentKeys.length>0)return r.environments.filter(t=>e.environmentKeys.indexOf(t.key)>-1)}getAppPreset(r,e){if(!(!r.applications||!r.applications[0])&&e?.applicationKey)return r.applications?.find(t=>t.key===e.applicationKey)}getHeaderForUrl(r,e,t){if(!t||!t.length||!r.tags?.length)return;const s=[];t?.forEach(n=>{if(!n.tags?.length){this.isValidCondition(n,e)&&s.push(n);return}n.tags.find(i=>r.tags?.includes(i))&&this.isValidCondition(n,e)&&s.push(n)});const o={};if(s.forEach(n=>{const i=Qt(n.value,{...e});o[n.key]=i}),Object.keys(o).length!==0)return o}getQueryParamsForUrl(r,e,t){const s=[];if(t?.forEach(o=>{if(!o.tags?.length){this.isValidCondition(o,e)&&s.push(o);return}o.tags.find(n=>r.tags?.includes(n))&&this.isValidCondition(o,e)&&s.push(o)}),this.isDcuplCdn(r.url)){const o=e.cdnVersion;o&&s.push({key:"v",value:o}),e.apiKey&&s?.push({key:"api-key",value:e.apiKey})}return s.map(o=>(o.value=Qt(o.value,{...e}),o))}isDcuplCdn(r){return r.includes("cdn.dcupl.com")}isValidCondition(r,e){return r.condition?.applyIfVariableHasValue?typeof e[r.condition?.applyIfVariableHasValue]<"u"&&e[r.condition?.applyIfVariableHasValue]!=="":!0}async handleScriptResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.scriptKey;if(this.core.scriptController.hasScript(n)){const u=this.progressHandler.update(o,!0,"script");return this.updateProgressListeners(u),null}const i=await this.fetchScript(o,e,t,s);this.core.scriptController.setScript(n,i);const a=this.progressHandler.update(o,!0,"script");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load script resource",n,{url:o.url,scriptKey:o.scriptKey});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"script");this.updateProgressListeners(a);return}})),!0}async handleOperatorResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.operator;if(this.core.queryManager.registeredCustomOperator.has(n)){const u=this.progressHandler.update(o,!0,"operator");return this.updateProgressListeners(u),null}const i=await this.fetchJavascriptFile(o,e,t,s);this.core.query.registerCustomOperator(n,i);const a=this.progressHandler.update(o,!0,"operator");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load operator resource",n,{url:o.url,operator:o.operator});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"operator");this.updateProgressListeners(a);return}})),!0}async handleTransformerResources(r,e,t,s){const o=[];return await Promise.all(r.map(async n=>{try{const i=this.registeredTransformers.find(l=>l.key===n.url);if(i){o.push(i);const l=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(l);return}const a=await this.fetchJavascriptFile(n,e,t,s),u={key:n.url,applyTo:n.applyTo||[],type:n.transformerType||"parsedFileTransformer",transformer:a};this.registeredTransformers.push(u),o.push(u);const c=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(c)}catch(i){this.log.error("Failed to load transformer resource",i,{url:n.url,transformerType:n.transformerType});const a={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:i?.message};this.setError(a);const u=this.progressHandler.update(n,!1,"transformer");this.updateProgressListeners(u)}})),o}getRequestOptions(r,e,t,s){const o=this.getHeaderForUrl(r,e,t),n=this.getQueryParamsForUrl(r,e,s);return{url:this.appendQueryParamsToUrl(r.url,n),headers:o}}async fetchScript(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${o}`);return await i.text()}async fetchJavascriptFile(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${o}`);const a=await i.text();return new Function(a)()}isValidModelDefinitionShape(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;const e=r;return!(typeof e.key!="string"||e.key.length===0||typeof e.properties<"u"&&!Array.isArray(e.properties))}emitInvalidModelDefinitionError(r,e,t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:t??"",meta:r,description:e};this.setError(s)}async handleModelResources(r,e,t,s){const o=r.map(async n=>{const i=new Date().getTime();let a;try{const{url:u,headers:c}=this.getRequestOptions(n,e,t,s),l=await fetch(u,{headers:c});if(a=l.status,!l.ok)throw new Error(`Failed to fetch data from ${u}`);const d=F.now(),f=await l.json(),h=F.now(),p=Array.isArray(f)?f:[f],y=[];for(const m of p)this.isValidModelDefinitionShape(m)?y.push(m):this.emitInvalidModelDefinitionError(n,"Resource body is not a valid ModelDefinition (missing or invalid `key`/`properties`)",typeof m?.key=="string"?m.key:void 0);if(y.length===0){const m=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(m),Promise.resolve(null)}const v=y.map(m=>m.key).join("__"),g=F.getEntriesByName(u.toString());if(Array.isArray(g)&&g[0]){const m=g[0],M={name:n.url,type:"resource",createdAt:new Date().getTime(),value:{model:v,type:"model",start:i,startTime:m.startTime,requestStart:m.requestStart,responseEnd:m.responseEnd,responseStart:m.responseStart,duration:m.duration,parseEnd:h,parseStart:d,decodedBodySize:m.decodedBodySize,encodedBodySize:m.encodedBodySize,end:h}};this.core.analyticsController.set({value:M,context:this.currentContext})}for(const m of y)this.addModelOrView(n,m);const k=this.progressHandler.update(n,!0,"model");return this.updateProgressListeners(k),Promise.resolve(f)}catch(u){this.log.error("Failed to load model resource",u,{url:n.url});const c={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:u?.message};this.setError(c);const l=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(l),Promise.resolve(null)}});return await Promise.all(o),!0}appendQueryParamsToUrl(r,e){const t=r.includes("?");let s=r;return e&&e.forEach((o,n)=>{s+=`${n===0&&!t?"?":"&"}${encodeURIComponent(o.key)}=${encodeURIComponent(o.value)}`}),s}async handleDataResources(r,e,t,s,o,n){const i=r.map(async a=>{const u=Ur(),c={placeholderUid:u,data:[],model:a.model};this.core.registerContainer(c);const l=new Date().getTime();let d;try{const{url:f,headers:h}=this.getRequestOptions(a,e,s,o),p=await fetch(f,{headers:h});if(d=p.status,!p.ok)throw new Error(`Failed to fetch data from ${f}`);const y=p.headers.get("content-type"),v=F.now();let g;a.url.endsWith(".csv")||y?.includes("text/csv")?g=await p.text():g=await p.json();const k=F.now(),m=F.now(),M=this.handleTransformerLogic(g,a,"rawFileTransformer",n||[]),N=F.now();let vt=[],Lt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!Lt&&(t?.missingModelHandling?.autoGenerateProperties||a.options?.autoGenerateProperties)){const q=a.options?.autoGenerateProperties??t?.missingModelHandling?.autoGenerateProperties??!0;this.addModelOrView(a,{key:a.model,autoGenerateProperties:q,autoGenerateKey:a.options?.autoGenerateKey||!1,keyProperty:a?.options?.keyProperty||"key",keyPropertySeparator:a?.options?.keyPropertySeparator}),Lt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const yA=F.now();let Ti={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(Lt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,Lt,a);vt=q.data,Ti={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else vt=M;const gA=F.now(),mA=F.now();try{vt=this.handleTransformerLogic(vt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const vA=F.now(),Ii={placeholderUid:u,model:a.model,data:vt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},ss=F.getEntriesByName(f.toString());if(Array.isArray(ss)&&ss[0]){const q=ss[0],kA={name:a.url,type:"resource",createdAt:new Date().getTime(),value:{model:a.model,type:"data",start:l,startTime:q.startTime,requestStart:q.requestStart,responseEnd:q.responseEnd,responseStart:q.responseStart,duration:q.duration,parseEnd:k,rawTransformStart:m,rawTransformEnd:N,parseStart:v,csvToJsonStart:yA,csvToJsonEnd:gA,parsedTransformStart:mA,parsedTransformEnd:vA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:kA,context:this.currentContext})}this.core.updateRegisteredContainer(Ii,Ti);const bA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(bA),Promise.resolve(Ii)}catch(f){this.log.error("Failed to load data resource",f,{url:a.url,model:a.model});const h={title:a.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:a,model:a.model,description:f?.message};this.setError(h),this.core.removeRegisteredContainer(c);const p=this.progressHandler.update(a,!1,"data",d);return this.updateProgressListeners(p),Promise.resolve()}});return await Promise.all(i),!0}async fetchResources(r,e,t,s,o){const n=r.scheduled;this.progressHandler=new Si,this.progressHandler.init(n,{skipped:r.skipped,run:r.run}),this.updateProgressListeners(this.progressHandler.getProgress());try{if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;const i=n.filter(f=>f.type==="script");await this.handleScriptResources(i,e,s,o);const a=n.filter(f=>f.type==="operator");await this.handleOperatorResources(a,e,s,o);const u=n.filter(f=>f.type==="transformer"),c=await this.handleTransformerResources(u,e,s,o),l=n.filter(f=>f.type==="model");await this.handleModelResources(l,e,s,o);const d=n.filter(f=>f.type==="data");return await this.handleDataResources(d,e,t,s,o,c),!0}catch(i){return this.log.error("Failed to fetch resources",i),!1}}addModelOrView(r,e){try{"model"in e?this.core.views.set(e):this.core.models.set(e)}catch(t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,meta:r,description:t?.message};this.setError(s)}}handleTransformerLogic(r,e,t,s){for(const o of s)o.type===t&&o.transformer&&(!o.applyTo.length&&!e.tags?.length&&(r=o.transformer(e,r)),ji(o.applyTo,e.tags||[]).length&&(r=o.transformer(e,r)));return r}updateProgressListeners(r){this.progressListeners.forEach(e=>e(r))}on(r){return this.progressListeners.add(r),()=>{this.progressListeners.delete(r)}}setError(r){this.core.modelParser.qualityController.enabled&&this.core.modelParser.qualityController.setError(r)}};Ri([qn({scope:"global",origin:"loader",type:"loader_config_fetched",connectMessage:!0,connectMessageResult:!0})],rs.prototype,"fetchConfig"),Ri([qn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],rs.prototype,"process");const pA=rs;let mt,Ue;async function hA(r){return mt=new sh(r.options),Ue=new pA,mt.loaders.add(Ue,"default"),r.appLoaderConfig?await Ue.config.fetch(r.appLoaderConfig):await Ue.config.fetch(),await Ue.process(r.processOptions),await mt.init(),globalThis.dcupl=mt,{dcupl:mt,loader:Ue}}globalThis.initDcupl=hA})();
16
16
  //# sourceMappingURL=dcupl.bundle.min.js.map