react-semaphor 0.1.338 → 0.1.339

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.
Files changed (59) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +58 -57
  3. package/dist/brand-studio/index.cjs +1 -1
  4. package/dist/brand-studio/index.js +3 -3
  5. package/dist/chunks/{braces-Q86XHDaD.js → braces-Ccvdip75.js} +1 -1
  6. package/dist/chunks/{braces-BLa_lORs.js → braces-DDHkbW1c.js} +1 -1
  7. package/dist/chunks/{calendar-preferences-dialog-Cocogo9H.js → calendar-preferences-dialog-2IbYrrP1.js} +3 -3
  8. package/dist/chunks/{calendar-preferences-dialog-Bm7ji3k9.js → calendar-preferences-dialog-8-KE5sVX.js} +1 -1
  9. package/dist/chunks/catalog-field-grounding-DoEBOXQd.js +100 -0
  10. package/dist/chunks/catalog-field-grounding-Du6mKDcF.js +1 -0
  11. package/dist/chunks/{chevrons-up-down-BBTZ5pAY.js → chevrons-up-down-B9fTSds9.js} +1 -1
  12. package/dist/chunks/{chevrons-up-down-CYuWasy_.js → chevrons-up-down-pV0i9ptS.js} +1 -1
  13. package/dist/chunks/{dashboard-briefing-launcher-BtqtLx1-.js → dashboard-briefing-launcher-CcqDPVke.js} +1 -1
  14. package/dist/chunks/{dashboard-briefing-launcher-DF4CoaRn.js → dashboard-briefing-launcher-DtxDRAiu.js} +4 -4
  15. package/dist/chunks/{dashboard-controls-B5U-VUxs.js → dashboard-controls-Bi98DhYD.js} +6 -6
  16. package/dist/chunks/{dashboard-controls-0VMAeMoa.js → dashboard-controls-By7aKmDj.js} +1 -1
  17. package/dist/chunks/{dashboard-json-CqbLOfnr.js → dashboard-json-BOyLuhS6.js} +1 -1
  18. package/dist/chunks/{dashboard-json-Hmc0Ri5z.js → dashboard-json-CGxIsTEP.js} +2 -2
  19. package/dist/chunks/{edit-dashboard-visual-D4VVu-QQ.js → edit-dashboard-visual-Ba8LenNc.js} +6 -6
  20. package/dist/chunks/{edit-dashboard-visual-C0EDM0QB.js → edit-dashboard-visual-BuXlHmJH.js} +1 -1
  21. package/dist/chunks/{index-DE0vIuYG.js → index-DT9osgRT.js} +2 -2
  22. package/dist/chunks/{index-DzyUhzV3.js → index-DVPvpd8u.js} +5 -5
  23. package/dist/chunks/{palette-DalASD28.js → palette-BMXS-AcI.js} +1 -1
  24. package/dist/chunks/{palette-B9AbDw0n.js → palette-DKecBucs.js} +1 -1
  25. package/dist/chunks/{resource-management-panel-C4YydU9I.js → resource-management-panel-98Hy6SYB.js} +3 -3
  26. package/dist/chunks/{resource-management-panel-P9iNqBM1.js → resource-management-panel-ByR-FD3h.js} +1 -1
  27. package/dist/chunks/{switch-BAYfpAEb.js → switch-CP7SmEIZ.js} +1 -1
  28. package/dist/chunks/{switch-CyRoZr5T.js → switch-DYRgERrC.js} +1 -1
  29. package/dist/chunks/{use-create-flow-overlay-state-P1LMwQ89.js → use-create-flow-overlay-state-D5uvjbwY.js} +3 -3
  30. package/dist/chunks/{use-create-flow-overlay-state-CbhjxI3W.js → use-create-flow-overlay-state-uNxArZdj.js} +1 -1
  31. package/dist/chunks/{use-visual-utils-lB-3Zk0b.js → use-visual-utils-BLh9mKic.js} +2 -2
  32. package/dist/chunks/{use-visual-utils-CV6_-y4p.js → use-visual-utils-CpaqIHoc.js} +1 -1
  33. package/dist/chunks/{validators-BOqiGymD.js → validators-CPEQojnV.js} +325 -250
  34. package/dist/chunks/validators-CfP-49k9.js +1 -0
  35. package/dist/dashboard/index.cjs +1 -1
  36. package/dist/dashboard/index.js +1 -1
  37. package/dist/dashboard-authoring/index.cjs +3 -3
  38. package/dist/dashboard-authoring/index.js +424 -561
  39. package/dist/data-app-builder/index.cjs +1 -1
  40. package/dist/data-app-builder/index.js +1 -1
  41. package/dist/data-app-sdk/index.cjs +1 -1
  42. package/dist/data-app-sdk/index.js +313 -308
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.js +7 -7
  45. package/dist/surfboard/index.cjs +1 -1
  46. package/dist/surfboard/index.js +2 -2
  47. package/dist/types/analytics-protocol.d.ts +74 -48
  48. package/dist/types/dashboard-authoring.d.ts +26 -52
  49. package/dist/types/dashboard.d.ts +1 -2
  50. package/dist/types/data-app-builder.d.ts +23 -13
  51. package/dist/types/data-app-sdk.d.ts +33 -46
  52. package/dist/types/main.d.ts +29 -50
  53. package/dist/types/shared.d.ts +1 -2
  54. package/dist/types/surfboard.d.ts +1 -2
  55. package/dist/types/types.d.ts +1 -2
  56. package/package.json +1 -1
  57. package/dist/chunks/catalog-field-grounding-DmT7aGUA.js +0 -191
  58. package/dist/chunks/catalog-field-grounding-VgVzDd25.js +0 -1
  59. package/dist/chunks/validators-BtFXY3S_.js +0 -2
@@ -1,4 +1,4 @@
1
- "use strict";var phe=Object.defineProperty;var b$=e=>{throw TypeError(e)};var mhe=(e,t,n)=>t in e?phe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ne=(e,t,n)=>mhe(e,typeof t!="symbol"?t+"":t,n),vE=(e,t,n)=>t.has(e)||b$("Cannot "+n);var he=(e,t,n)=>(vE(e,t,"read from private field"),n?n.call(e):t.get(e)),Mt=(e,t,n)=>t.has(e)?b$("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),vt=(e,t,n,r)=>(vE(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Gt=(e,t,n)=>(vE(e,t,"access private method"),n);var _w=(e,t,n,r)=>({set _(s){vt(e,t,s,n)},get _(){return he(e,t,r)}});const l=require("react/jsx-runtime"),v=require("react"),Sr=require("react-dom"),m=require("./switch-CyRoZr5T.js"),ghe=require("./index-BxM99sFL.js"),Wc=require("./index-DRlMUglg.js"),CW=require("react-dom/client"),Bn=require("./date-formatter-B4EBSe9C.js"),bhe=require("../types/index.cjs"),xn=require("./index-D7KJindZ.js"),Mo=require("./normalize-dashboard-for-dirty-check-BXRUMVb2.js"),Cr=require("./common-types-C73-Ud1-.js"),xhe=require("../layouts/index.cjs"),jw=require("../data-app-builder-browser-runtime/index.cjs");function yk(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const x$=yk(l),Q=yk(v),f2=yk(Sr),yhe=yk(CW),tF=`import pandas as pd
1
+ "use strict";var phe=Object.defineProperty;var b$=e=>{throw TypeError(e)};var mhe=(e,t,n)=>t in e?phe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ne=(e,t,n)=>mhe(e,typeof t!="symbol"?t+"":t,n),vE=(e,t,n)=>t.has(e)||b$("Cannot "+n);var he=(e,t,n)=>(vE(e,t,"read from private field"),n?n.call(e):t.get(e)),Mt=(e,t,n)=>t.has(e)?b$("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),vt=(e,t,n,r)=>(vE(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Gt=(e,t,n)=>(vE(e,t,"access private method"),n);var _w=(e,t,n,r)=>({set _(s){vt(e,t,s,n)},get _(){return he(e,t,r)}});const l=require("react/jsx-runtime"),v=require("react"),Sr=require("react-dom"),m=require("./switch-DYRgERrC.js"),ghe=require("./index-BxM99sFL.js"),Wc=require("./index-DRlMUglg.js"),CW=require("react-dom/client"),Bn=require("./date-formatter-B4EBSe9C.js"),bhe=require("../types/index.cjs"),xn=require("./index-D7KJindZ.js"),Mo=require("./normalize-dashboard-for-dirty-check-BXRUMVb2.js"),Cr=require("./common-types-C73-Ud1-.js"),xhe=require("../layouts/index.cjs"),jw=require("../data-app-builder-browser-runtime/index.cjs");function yk(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const x$=yk(l),Q=yk(v),f2=yk(Sr),yhe=yk(CW),tF=`import pandas as pd
2
2
  df = pd.DataFrame(data) # 'data' contains the query result
3
3
  result = df.to_dict('records') # must return 'result' as [dict] type
4
4
  `;function vhe(e,t){const n=+xn.toDate(e);return xn.constructFrom(e,n+t)}function uC(e,t){return vhe(e,t*xn.millisecondsInHour)}function whe(e){return xn.toDate(e).getMonth()}function She(e){return xn.toDate(e).getFullYear()}function dC(e,t){const r=_he(e);let s;if(r.date){const c=jhe(r.date,2);s=Ehe(c.restDateString,c.year)}if(!s||isNaN(s.getTime()))return new Date(NaN);const o=s.getTime();let i=0,a;if(r.time&&(i=Dhe(r.time),isNaN(i)))return new Date(NaN);if(r.timezone){if(a=Ihe(r.timezone),isNaN(a))return new Date(NaN)}else{const c=new Date(o+i),u=new Date(0);return u.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),u.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),u}return new Date(o+i+a)}const Ew={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Che=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Nhe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,khe=/^([+-])(\d{2})(?::?(\d{2}))?$/;function _he(e){const t={},n=e.split(Ew.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Ew.timeZoneDelimiter.test(t.date)&&(t.date=e.split(Ew.timeZoneDelimiter)[0],r=e.substr(t.date.length,e.length))),r){const s=Ew.timezone.exec(r);s?(t.time=r.replace(s[1],""),t.timezone=s[1]):t.time=r}return t}function jhe(e,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=e.match(n);if(!r)return{year:NaN,restDateString:""};const s=r[1]?parseInt(r[1]):null,o=r[2]?parseInt(r[2]):null;return{year:o===null?s:o*100,restDateString:e.slice((r[1]||r[2]).length)}}function Ehe(e,t){if(t===null)return new Date(NaN);const n=e.match(Che);if(!n)return new Date(NaN);const r=!!n[4],s=kb(n[1]),o=kb(n[2])-1,i=kb(n[3]),a=kb(n[4]),c=kb(n[5])-1;if(r)return Fhe(t,a,c)?The(t,a,c):new Date(NaN);{const u=new Date(0);return!Ahe(t,o,i)||!Rhe(t,s)?new Date(NaN):(u.setUTCFullYear(t,o,Math.max(s,i)),u)}}function kb(e){return e?parseInt(e):1}function Dhe(e){const t=e.match(Nhe);if(!t)return NaN;const n=wE(t[1]),r=wE(t[2]),s=wE(t[3]);return Phe(n,r,s)?n*xn.millisecondsInHour+r*xn.millisecondsInMinute+s*1e3:NaN}function wE(e){return e&&parseFloat(e.replace(",","."))||0}function Ihe(e){if(e==="Z")return 0;const t=e.match(khe);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),s=t[3]&&parseInt(t[3])||0;return Ohe(r,s)?n*(r*xn.millisecondsInHour+s*xn.millisecondsInMinute):NaN}function The(e,t,n){const r=new Date(0);r.setUTCFullYear(e,0,4);const s=r.getUTCDay()||7,o=(t-1)*7+n+1-s;return r.setUTCDate(r.getUTCDate()+o),r}const Mhe=[31,null,31,30,31,30,31,31,30,31,30,31];function NW(e){return e%400===0||e%4===0&&e%100!==0}function Ahe(e,t,n){return t>=0&&t<=11&&n>=1&&n<=(Mhe[t]||(NW(e)?29:28))}function Rhe(e,t){return t>=1&&t<=(NW(e)?366:365)}function Fhe(e,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function Phe(e,t,n){return e===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&e>=0&&e<25}function Ohe(e,t){return t>=0&&t<=59}var fC={exports:{}};fC.exports;(function(e,t){var n=200,r="__lodash_hash_undefined__",s=800,o=16,i=9007199254740991,a="[object Arguments]",c="[object Array]",u="[object AsyncFunction]",d="[object Boolean]",f="[object Date]",h="[object Error]",p="[object Function]",g="[object GeneratorFunction]",b="[object Map]",x="[object Number]",y="[object Null]",S="[object Object]",w="[object Proxy]",C="[object RegExp]",N="[object Set]",k="[object String]",_="[object Undefined]",E="[object WeakMap]",D="[object ArrayBuffer]",j="[object DataView]",I="[object Float32Array]",T="[object Float64Array]",F="[object Int8Array]",P="[object Int16Array]",R="[object Int32Array]",B="[object Uint8Array]",z="[object Uint8ClampedArray]",U="[object Uint16Array]",Y="[object Uint32Array]",O=/[\\^$.*+?()[\]{}|]/g,K=/^\[object .+?Constructor\]$/,q=/^(?:0|[1-9]\d*)$/,M={};M[I]=M[T]=M[F]=M[P]=M[R]=M[B]=M[z]=M[U]=M[Y]=!0,M[a]=M[c]=M[D]=M[d]=M[j]=M[f]=M[h]=M[p]=M[b]=M[x]=M[S]=M[C]=M[N]=M[k]=M[E]=!1;var G=typeof m.commonjsGlobal=="object"&&m.commonjsGlobal&&m.commonjsGlobal.Object===Object&&m.commonjsGlobal,L=typeof self=="object"&&self&&self.Object===Object&&self,$=G||L||Function("return this")(),V=t&&!t.nodeType&&t,H=V&&!0&&e&&!e.nodeType&&e,A=H&&H.exports===V,W=A&&G.process,X=function(){try{var ie=H&&H.require&&H.require("util").types;return ie||W&&W.binding&&W.binding("util")}catch{}}(),Z=X&&X.isTypedArray;function J(ie,De,Le){switch(Le.length){case 0:return ie.call(De);case 1:return ie.call(De,Le[0]);case 2:return ie.call(De,Le[0],Le[1]);case 3:return ie.call(De,Le[0],Le[1],Le[2])}return ie.apply(De,Le)}function re(ie,De){for(var Le=-1,At=Array(ie);++Le<ie;)At[Le]=De(Le);return At}function fe(ie){return function(De){return ie(De)}}function de(ie,De){return ie==null?void 0:ie[De]}function Se(ie,De){return function(Le){return ie(De(Le))}}var ue=Array.prototype,ve=Function.prototype,xe=Object.prototype,ke=$["__core-js_shared__"],se=ve.toString,be=xe.hasOwnProperty,Ce=function(){var ie=/[^.]+$/.exec(ke&&ke.keys&&ke.keys.IE_PROTO||"");return ie?"Symbol(src)_1."+ie:""}(),ge=xe.toString,ee=se.call(Object),te=RegExp("^"+se.call(be).replace(O,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ce=A?$.Buffer:void 0,le=$.Symbol,Ee=$.Uint8Array;ce&&ce.allocUnsafe;var ye=Se(Object.getPrototypeOf,Object),ne=Object.create,je=xe.propertyIsEnumerable,Ue=ue.splice,Be=le?le.toStringTag:void 0,rt=function(){try{var ie=Pt(Object,"defineProperty");return ie({},"",{}),ie}catch{}}(),Xe=ce?ce.isBuffer:void 0,et=Math.max,tt=Date.now,me=Pt($,"Map"),Ye=Pt(Object,"create"),Ve=function(){function ie(){}return function(De){if(!ia(De))return{};if(ne)return ne(De);ie.prototype=De;var Le=new ie;return ie.prototype=void 0,Le}}();function $e(ie){var De=-1,Le=ie==null?0:ie.length;for(this.clear();++De<Le;){var At=ie[De];this.set(At[0],At[1])}}function Ae(){this.__data__=Ye?Ye(null):{},this.size=0}function Re(ie){var De=this.has(ie)&&delete this.__data__[ie];return this.size-=De?1:0,De}function He(ie){var De=this.__data__;if(Ye){var Le=De[ie];return Le===r?void 0:Le}return be.call(De,ie)?De[ie]:void 0}function Ge(ie){var De=this.__data__;return Ye?De[ie]!==void 0:be.call(De,ie)}function ht(ie,De){var Le=this.__data__;return this.size+=this.has(ie)?0:1,Le[ie]=Ye&&De===void 0?r:De,this}$e.prototype.clear=Ae,$e.prototype.delete=Re,$e.prototype.get=He,$e.prototype.has=Ge,$e.prototype.set=ht;function lt(ie){var De=-1,Le=ie==null?0:ie.length;for(this.clear();++De<Le;){var At=ie[De];this.set(At[0],At[1])}}function st(){this.__data__=[],this.size=0}function Fe(ie){var De=this.__data__,Le=wt(De,ie);if(Le<0)return!1;var At=De.length-1;return Le==At?De.pop():Ue.call(De,Le,1),--this.size,!0}function Ke(ie){var De=this.__data__,Le=wt(De,ie);return Le<0?void 0:De[Le][1]}function _t(ie){return wt(this.__data__,ie)>-1}function Te(ie,De){var Le=this.__data__,At=wt(Le,ie);return At<0?(++this.size,Le.push([ie,De])):Le[At][1]=De,this}lt.prototype.clear=st,lt.prototype.delete=Fe,lt.prototype.get=Ke,lt.prototype.has=_t,lt.prototype.set=Te;function Ze(ie){var De=-1,Le=ie==null?0:ie.length;for(this.clear();++De<Le;){var At=ie[De];this.set(At[0],At[1])}}function at(){this.size=0,this.__data__={hash:new $e,map:new(me||lt),string:new $e}}function bt(ie){var De=jt(this,ie).delete(ie);return this.size-=De?1:0,De}function ft(ie){return jt(this,ie).get(ie)}function Et(ie){return jt(this,ie).has(ie)}function Wt(ie,De){var Le=jt(this,ie),At=Le.size;return Le.set(ie,De),this.size+=Le.size==At?0:1,this}Ze.prototype.clear=at,Ze.prototype.delete=bt,Ze.prototype.get=ft,Ze.prototype.has=Et,Ze.prototype.set=Wt;function En(ie){var De=this.__data__=new lt(ie);this.size=De.size}function zn(){this.__data__=new lt,this.size=0}function xt(ie){var De=this.__data__,Le=De.delete(ie);return this.size=De.size,Le}function Dt(ie){return this.__data__.get(ie)}function Lt(ie){return this.__data__.has(ie)}function Ft(ie,De){var Le=this.__data__;if(Le instanceof lt){var At=Le.__data__;if(!me||At.length<n-1)return At.push([ie,De]),this.size=++Le.size,this;Le=this.__data__=new Ze(At)}return Le.set(ie,De),this.size=Le.size,this}En.prototype.clear=zn,En.prototype.delete=xt,En.prototype.get=Dt,En.prototype.has=Lt,En.prototype.set=Ft;function pt(ie,De){var Le=ap(ie),At=!Le&&ip(ie),oe=!Le&&!At&&yw(ie),_e=!Le&&!At&&!oe&&vb(ie),Me=Le||At||oe||_e,Ie=Me?re(ie.length,String):[],ct=Ie.length;for(var $t in ie)Me&&($t=="length"||oe&&($t=="offset"||$t=="parent")||_e&&($t=="buffer"||$t=="byteLength"||$t=="byteOffset")||ir($t,ct))||Ie.push($t);return Ie}function ae(ie,De,Le){(Le!==void 0&&!op(ie[De],Le)||Le===void 0&&!(De in ie))&&Pe(ie,De,Le)}function qe(ie,De,Le){var At=ie[De];(!(be.call(ie,De)&&op(At,Le))||Le===void 0&&!(De in ie))&&Pe(ie,De,Le)}function wt(ie,De){for(var Le=ie.length;Le--;)if(op(ie[Le][0],De))return Le;return-1}function Pe(ie,De,Le){De=="__proto__"&&rt?rt(ie,De,{configurable:!0,enumerable:!0,value:Le,writable:!0}):ie[De]=Le}var St=mt();function pe(ie){return ie==null?ie===void 0?_:y:Be&&Be in Object(ie)?An(ie):hE(ie)}function Oe(ie){return Pd(ie)&&pe(ie)==a}function Je(ie){if(!ia(ie)||iu(ie))return!1;var De=yb(ie)?te:K;return De.test(bE(ie))}function It(ie){return Pd(ie)&&vw(ie.length)&&!!M[pe(ie)]}function nn(ie){if(!ia(ie))return Ul(ie);var De=sp(ie),Le=[];for(var At in ie)At=="constructor"&&(De||!be.call(ie,At))||Le.push(At);return Le}function Rt(ie,De,Le,At,oe){ie!==De&&St(De,function(_e,Me){if(oe||(oe=new En),ia(_e))_r(ie,De,Me,Le,Rt,At,oe);else{var Ie=At?At(xb(ie,Me),_e,Me+"",ie,De,oe):void 0;Ie===void 0&&(Ie=_e),ae(ie,Me,Ie)}},Sw)}function _r(ie,De,Le,At,oe,_e,Me){var Ie=xb(ie,Le),ct=xb(De,Le),$t=Me.get(ct);if($t){ae(ie,Le,$t);return}var Qt=_e?_e(Ie,ct,Le+"",ie,De,Me):void 0,rn=Qt===void 0;if(rn){var tr=ap(ct),Bt=!tr&&yw(ct),Jt=!tr&&!Bt&&vb(ct);Qt=ct,tr||Bt||Jt?ap(Ie)?Qt=Ie:xE(Ie)?Qt=We(Ie):Bt?(rn=!1,Qt=Ts(ct)):Jt?(rn=!1,Qt=yo(ct)):Qt=[]:ww(ct)||ip(ct)?(Qt=Ie,ip(Ie)?Qt=wb(Ie):(!ia(Ie)||yb(Ie))&&(Qt=zt(ct))):rn=!1}rn&&(Me.set(ct,Qt),oe(Qt,ct,At,_e,Me),Me.delete(ct)),ae(ie,Le,Qt)}function Cn(ie,De){return mE(pE(ie,De,kw),ie+"")}var yr=rt?function(ie,De){return rt(ie,"toString",{configurable:!0,enumerable:!1,value:Nw(De),writable:!0})}:kw;function Ts(ie,De){return ie.slice()}function ds(ie){var De=new ie.constructor(ie.byteLength);return new Ee(De).set(new Ee(ie)),De}function yo(ie,De){var Le=ds(ie.buffer);return new ie.constructor(Le,ie.byteOffset,ie.length)}function We(ie,De){var Le=-1,At=ie.length;for(De||(De=Array(At));++Le<At;)De[Le]=ie[Le];return De}function we(ie,De,Le,At){var oe=!Le;Le||(Le={});for(var _e=-1,Me=De.length;++_e<Me;){var Ie=De[_e],ct=void 0;ct===void 0&&(ct=ie[Ie]),oe?Pe(Le,Ie,ct):qe(Le,Ie,ct)}return Le}function ot(ie){return Cn(function(De,Le){var At=-1,oe=Le.length,_e=oe>1?Le[oe-1]:void 0,Me=oe>2?Le[2]:void 0;for(_e=ie.length>3&&typeof _e=="function"?(oe--,_e):void 0,Me&&er(Le[0],Le[1],Me)&&(_e=oe<3?void 0:_e,oe=1),De=Object(De);++At<oe;){var Ie=Le[At];Ie&&ie(De,Ie,At,_e)}return De})}function mt(ie){return function(De,Le,At){for(var oe=-1,_e=Object(De),Me=At(De),Ie=Me.length;Ie--;){var ct=Me[++oe];if(Le(_e[ct],ct,_e)===!1)break}return De}}function jt(ie,De){var Le=ie.__data__;return Ar(De)?Le[typeof De=="string"?"string":"hash"]:Le.map}function Pt(ie,De){var Le=de(ie,De);return Je(Le)?Le:void 0}function An(ie){var De=be.call(ie,Be),Le=ie[Be];try{ie[Be]=void 0;var At=!0}catch{}var oe=ge.call(ie);return At&&(De?ie[Be]=Le:delete ie[Be]),oe}function zt(ie){return typeof ie.constructor=="function"&&!sp(ie)?Ve(ye(ie)):{}}function ir(ie,De){var Le=typeof ie;return De=De??i,!!De&&(Le=="number"||Le!="symbol"&&q.test(ie))&&ie>-1&&ie%1==0&&ie<De}function er(ie,De,Le){if(!ia(Le))return!1;var At=typeof De;return(At=="number"?qs(Le)&&ir(De,Le.length):At=="string"&&De in Le)?op(Le[De],ie):!1}function Ar(ie){var De=typeof ie;return De=="string"||De=="number"||De=="symbol"||De=="boolean"?ie!=="__proto__":ie===null}function iu(ie){return!!Ce&&Ce in ie}function sp(ie){var De=ie&&ie.constructor,Le=typeof De=="function"&&De.prototype||xe;return ie===Le}function Ul(ie){var De=[];if(ie!=null)for(var Le in Object(ie))De.push(Le);return De}function hE(ie){return ge.call(ie)}function pE(ie,De,Le){return De=et(De===void 0?ie.length-1:De,0),function(){for(var At=arguments,oe=-1,_e=et(At.length-De,0),Me=Array(_e);++oe<_e;)Me[oe]=At[De+oe];oe=-1;for(var Ie=Array(De+1);++oe<De;)Ie[oe]=At[oe];return Ie[De]=Le(Me),J(ie,this,Ie)}}function xb(ie,De){if(!(De==="constructor"&&typeof ie[De]=="function")&&De!="__proto__")return ie[De]}var mE=gE(yr);function gE(ie){var De=0,Le=0;return function(){var At=tt(),oe=o-(At-Le);if(Le=At,oe>0){if(++De>=s)return arguments[0]}else De=0;return ie.apply(void 0,arguments)}}function bE(ie){if(ie!=null){try{return se.call(ie)}catch{}try{return ie+""}catch{}}return""}function op(ie,De){return ie===De||ie!==ie&&De!==De}var ip=Oe(function(){return arguments}())?Oe:function(ie){return Pd(ie)&&be.call(ie,"callee")&&!je.call(ie,"callee")},ap=Array.isArray;function qs(ie){return ie!=null&&vw(ie.length)&&!yb(ie)}function xE(ie){return Pd(ie)&&qs(ie)}var yw=Xe||yE;function yb(ie){if(!ia(ie))return!1;var De=pe(ie);return De==p||De==g||De==u||De==w}function vw(ie){return typeof ie=="number"&&ie>-1&&ie%1==0&&ie<=i}function ia(ie){var De=typeof ie;return ie!=null&&(De=="object"||De=="function")}function Pd(ie){return ie!=null&&typeof ie=="object"}function ww(ie){if(!Pd(ie)||pe(ie)!=S)return!1;var De=ye(ie);if(De===null)return!0;var Le=be.call(De,"constructor")&&De.constructor;return typeof Le=="function"&&Le instanceof Le&&se.call(Le)==ee}var vb=Z?fe(Z):It;function wb(ie){return we(ie,Sw(ie))}function Sw(ie){return qs(ie)?pt(ie):nn(ie)}var Cw=ot(function(ie,De,Le){Rt(ie,De,Le)});function Nw(ie){return function(){return ie}}function kw(ie){return ie}function yE(){return!1}e.exports=Cw})(fC,fC.exports);var Lhe=fC.exports;const xl=m.getDefaultExportFromCjs(Lhe),$he={theme:"system",setTheme:()=>null},kW=v.createContext($he);function hC(e,t="system"){return zhe(e)?e:t}function zhe(e){return e==="light"||e==="dark"||e==="system"}const nF=()=>{const e=v.useContext(kW);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e},_W=(e,t)=>{const n={};if(e===null||t===null)return t;const r=new Set([...Object.keys(e),...Object.keys(t)]);for(const s of r){if(!(s in e)&&s in t){n[s]=t[s];continue}if(s in e&&!(s in t)){n[s]=void 0;continue}const o=e[s],i=t[s];if(!h2(o,i))if(Array.isArray(o)&&Array.isArray(i))n[s]=i;else if(y$(o)&&y$(i)){const a=_W(o,i);Object.keys(a).length>0&&(n[s]=a)}else n[s]=i}return n},h2=(e,t)=>{if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((s,o)=>h2(s,t[o]));const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>h2(e[s],t[s]))}return!1},y$=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Zo=e=>{if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(Array.isArray(e))return e.map(n=>Zo(n));const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Zo(e[n]));return t},jW="__semaphorAuthoredFontFamily";var cW,uW;const Bhe=(uW=(cW=m.DEFAULT_STYLE.default.chart)==null?void 0:cW.font)==null?void 0:uW.family,Vhe=new Set([Bhe,"Open Sans, Arial, sans-serif",'"Open Sans", Arial, sans-serif'].filter(Boolean));function Hhe(e,t){if(!e)return t?{family:t}:void 0;const{[jW]:n,...r}=e,s=Uhe(r.family,t,!!n);return{...r,...s?{family:s}:void 0}}function Uhe(e,t,n=!1){return n&&e||e&&!Whe(e)?e:t||e}function Whe(e){return Vhe.has(e.trim())}function qhe(e,t){if(!t)return e;const n={...e,font:Pi(e.font,t)},r=Khe(e.plugins,t);r&&(n.plugins=r);const s=Zhe(e.scales,t);return s&&(n.scales=s),n}function Yhe(e,t){return!e||!t?e:e.map(n=>{if(!n||typeof n!="object")return n;const r=n,s=r.datalabels;return!s||typeof s!="object"?n:{...r,datalabels:{...s,font:Pi(s.font,t)}}})}function Ghe(e,t){if(!e||typeof e!="object"||!t)return e;const n=e.datasets;return Array.isArray(n)?{...e,datasets:Yhe(n,t)}:e}function Khe(e,t){var n;return e&&{...e,title:e.title?{...e.title,font:Pi(e.title.font,t)}:e.title,subtitle:e.subtitle?{...e.subtitle,font:Pi(e.subtitle.font,t)}:e.subtitle,legend:e.legend?{...e.legend,labels:e.legend.labels?{...e.legend.labels,font:Pi(e.legend.labels.font,t)}:e.legend.labels}:e.legend,tooltip:e.tooltip?{...e.tooltip,titleFont:Pi(e.tooltip.titleFont,t),bodyFont:Pi(e.tooltip.bodyFont,t),footerFont:Pi(e.tooltip.footerFont,t)}:e.tooltip,datalabels:e.datalabels?{...e.datalabels,font:Pi((n=e.datalabels)==null?void 0:n.font,t)}:e.datalabels}}function Zhe(e,t){return e&&Object.entries(e).reduce((n,[r,s])=>{if(!s||typeof s!="object")return n[r]=s,n;const o=s;return n[r]={...o,ticks:o.ticks?{...o.ticks,font:Pi(o.ticks.font,t)}:o.ticks,title:o.title?{...o.title,font:Pi(o.title.font,t)}:o.title,pointLabels:o.pointLabels?{...o.pointLabels,font:Pi(o.pointLabels.font,t)}:o.pointLabels},n},{})}function Pi(e,t){return typeof e=="function"?e:{...t,...e&&typeof e=="object"?e:{}}}function Xhe(e,t){const n=Zo(e??{}),r=Qhe(t);if(!r)return n;const s=xl(n,r);return tpe(s,r),s}function Qhe(e){var h,p,g,b;const t=(h=e.scheme.components)==null?void 0:h.chart,n=Wc.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode],r=(p=n.components)==null?void 0:p.chart,s=(g=n.tokens)==null?void 0:g.typography,o={};epe(t==null?void 0:t.palette,r==null?void 0:r.palette)&&(o.dataset={backgroundColor:[...t.palette],borderColor:[...t.palette]});const i=(b=e.scheme.tokens)==null?void 0:b.typography,a=up(i==null?void 0:i.fontFamily,s==null?void 0:s.fontFamily),c=up(i==null?void 0:i.baseFontSize,s==null?void 0:s.baseFontSize);if(a||c!==void 0){const x={...a?{family:a}:void 0,...c!==void 0?{size:c}:void 0};a&&(x[jW]=!0),o.font=x}const u=up(t==null?void 0:t.gridColor,r==null?void 0:r.gridColor),d=up(t==null?void 0:t.axisColor,r==null?void 0:r.axisColor)??up(t==null?void 0:t.foreground,r==null?void 0:r.foreground);(u||d)&&(o.options={scales:{x:SE({gridColor:u,axisColor:d}),y:SE({gridColor:u,axisColor:d}),y2:SE({gridColor:u,axisColor:d}),r:Jhe({gridColor:u,axisColor:d})}});const f=up(t==null?void 0:t.foreground,r==null?void 0:r.foreground);return f&&(o.options=xl(o.options??{},{plugins:{legend:{labels:{color:f}}}})),Object.keys(o).length>0?{chart:o}:void 0}function SE({gridColor:e,axisColor:t}){return{...e?{grid:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t}}:void 0}}function Jhe({gridColor:e,axisColor:t}){return{...e?{grid:{color:e},angleLines:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t},pointLabels:{color:t}}:void 0}}function epe(e,t){return e!=null&&e.length?!(t!=null&&t.length)||e.length!==t.length?!0:e.some((n,r)=>n!==t[r]):!1}function up(e,t){return e!==void 0&&e!==t?e:void 0}function tpe(e,t){var r;const n=(r=t.chart)==null?void 0:r.dataset;n&&(e.chart=e.chart??{},e.chart.dataset=e.chart.dataset??{},Array.isArray(n.backgroundColor)&&(e.chart.dataset.backgroundColor=[...n.backgroundColor]),Array.isArray(n.borderColor)&&(e.chart.dataset.borderColor=[...n.borderColor]))}var Fh=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},npe={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ja,If,dW,rpe=(dW=class{constructor(){Mt(this,Ja,npe);Mt(this,If,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&he(this,If)&&e!==he(this,Ja)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:he(this,Ja),provider:e}),vt(this,Ja,e),process.env.NODE_ENV!=="production"&&vt(this,If,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&vt(this,If,!0),he(this,Ja).setTimeout(e,t)}clearTimeout(e){he(this,Ja).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&vt(this,If,!0),he(this,Ja).setInterval(e,t)}clearInterval(e){he(this,Ja).clearInterval(e)}},Ja=new WeakMap,If=new WeakMap,dW),xf=new rpe;function spe(e){setTimeout(e,0)}var sh=typeof window>"u"||"Deno"in globalThis;function Qs(){}function ope(e,t){return typeof e=="function"?e(t):e}function p2(e){return typeof e=="number"&&e>=0&&e!==1/0}function EW(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Hu(e,t){return typeof e=="function"?e(t):e}function Oi(e,t){return typeof e=="function"?e(t):e}function v$(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:i,stale:a}=e;if(i){if(r){if(t.queryHash!==rF(i,t.options))return!1}else if(!jy(t.queryKey,i))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||o&&!o(t))}function w$(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(oh(t.options.mutationKey)!==oh(o))return!1}else if(!jy(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rF(e,t){return((t==null?void 0:t.queryKeyHashFn)||oh)(e)}function oh(e){return JSON.stringify(e,(t,n)=>m2(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function jy(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>jy(e[n],t[n])):!1}var ipe=Object.prototype.hasOwnProperty;function pC(e,t){if(e===t)return e;const n=S$(e)&&S$(t);if(!n&&!(m2(e)&&m2(t)))return t;const s=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),i=o.length,a=n?new Array(i):{};let c=0;for(let u=0;u<i;u++){const d=n?u:o[u],f=e[d],h=t[d];if(f===h){a[d]=f,(n?u<s:ipe.call(e,d))&&c++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){a[d]=h;continue}const p=pC(f,h);a[d]=p,p===f&&c++}return s===i&&c===s?e:a}function Ey(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function S$(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function m2(e){if(!C$(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!C$(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function C$(e){return Object.prototype.toString.call(e)==="[object Object]"}function ape(e){return new Promise(t=>{xf.setTimeout(t,e)})}function g2(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return pC(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${r}`),r}return pC(e,t)}return t}function lpe(e){return e}function cpe(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function upe(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var mC=Symbol();function DW(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===mC&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===mC?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function IW(e,t){return typeof e=="function"?e(...t):!!e}var Tf,wu,bm,fW,dpe=(fW=class extends Fh{constructor(){super();Mt(this,Tf);Mt(this,wu);Mt(this,bm);vt(this,bm,t=>{if(!sh&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){he(this,wu)||this.setEventListener(he(this,bm))}onUnsubscribe(){var t;this.hasListeners()||((t=he(this,wu))==null||t.call(this),vt(this,wu,void 0))}setEventListener(t){var n;vt(this,bm,t),(n=he(this,wu))==null||n.call(this),vt(this,wu,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){he(this,Tf)!==t&&(vt(this,Tf,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof he(this,Tf)=="boolean"?he(this,Tf):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Tf=new WeakMap,wu=new WeakMap,bm=new WeakMap,fW),sF=new dpe;function b2(){let e,t;const n=new Promise((s,o)=>{e=s,t=o});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var fpe=spe;function hpe(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=fpe;const o=a=>{t?e.push(a):s(()=>{n(a)})},i=()=>{const a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||i()}return c},batchCalls:a=>(...c)=>{o(()=>{a(...c)})},schedule:o,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var $r=hpe(),xm,Su,ym,hW,ppe=(hW=class extends Fh{constructor(){super();Mt(this,xm,!0);Mt(this,Su);Mt(this,ym);vt(this,ym,t=>{if(!sh&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){he(this,Su)||this.setEventListener(he(this,ym))}onUnsubscribe(){var t;this.hasListeners()||((t=he(this,Su))==null||t.call(this),vt(this,Su,void 0))}setEventListener(t){var n;vt(this,ym,t),(n=he(this,Su))==null||n.call(this),vt(this,Su,t(this.setOnline.bind(this)))}setOnline(t){he(this,xm)!==t&&(vt(this,xm,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return he(this,xm)}},xm=new WeakMap,Su=new WeakMap,ym=new WeakMap,hW),gC=new ppe;function mpe(e){return Math.min(1e3*2**e,3e4)}function TW(e){return(e??"online")==="online"?gC.isOnline():!0}var x2=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function MW(e){let t=!1,n=0,r;const s=b2(),o=()=>s.status!=="pending",i=b=>{var x;if(!o()){const y=new x2(b);h(y),(x=e.onCancel)==null||x.call(e,y)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>sF.isFocused()&&(e.networkMode==="always"||gC.isOnline())&&e.canRun(),d=()=>TW(e.networkMode)&&e.canRun(),f=b=>{o()||(r==null||r(),s.resolve(b))},h=b=>{o()||(r==null||r(),s.reject(b))},p=()=>new Promise(b=>{var x;r=y=>{(o()||u())&&b(y)},(x=e.onPause)==null||x.call(e)}).then(()=>{var b;r=void 0,o()||(b=e.onContinue)==null||b.call(e)}),g=()=>{if(o())return;let b;const x=n===0?e.initialPromise:void 0;try{b=x??e.fn()}catch(y){b=Promise.reject(y)}Promise.resolve(b).then(f).catch(y=>{var k;if(o())return;const S=e.retry??(sh?0:3),w=e.retryDelay??mpe,C=typeof w=="function"?w(n,y):w,N=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,y);if(t||!N){h(y);return}n++,(k=e.onFail)==null||k.call(e,n,y),ape(C).then(()=>u()?void 0:p()).then(()=>{t?h(y):g()})})};return{promise:s,status:()=>s.status,cancel:i,continue:()=>(r==null||r(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?g():p().then(g),s)}}var Mf,pW,AW=(pW=class{constructor(){Mt(this,Mf)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),p2(this.gcTime)&&vt(this,Mf,xf.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(sh?1/0:5*60*1e3))}clearGcTimeout(){he(this,Mf)&&(xf.clearTimeout(he(this,Mf)),vt(this,Mf,void 0))}},Mf=new WeakMap,pW),Af,vm,Ri,Rf,ys,U0,Ff,da,Xl,mW,gpe=(mW=class extends AW{constructor(t){super();Mt(this,da);Mt(this,Af);Mt(this,vm);Mt(this,Ri);Mt(this,Rf);Mt(this,ys);Mt(this,U0);Mt(this,Ff);vt(this,Ff,!1),vt(this,U0,t.defaultOptions),this.setOptions(t.options),this.observers=[],vt(this,Rf,t.client),vt(this,Ri,he(this,Rf).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,vt(this,Af,k$(this.options)),this.state=t.state??he(this,Af),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=he(this,ys))==null?void 0:t.promise}setOptions(t){if(this.options={...he(this,U0),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=k$(this.options);n.data!==void 0&&(this.setState(N$(n.data,n.dataUpdatedAt)),vt(this,Af,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&he(this,Ri).remove(this)}setData(t,n){const r=g2(this.state.data,t,this.options);return Gt(this,da,Xl).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Gt(this,da,Xl).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=he(this,ys))==null?void 0:r.promise;return(s=he(this,ys))==null||s.cancel(t),n?n.then(Qs).catch(Qs):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(he(this,Af))}isActive(){return this.observers.some(t=>Oi(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===mC||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Hu(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!EW(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=he(this,ys))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=he(this,ys))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),he(this,Ri).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(he(this,ys)&&(he(this,Ff)?he(this,ys).cancel({revert:!0}):he(this,ys).cancelRetry()),this.scheduleGc()),he(this,Ri).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Gt(this,da,Xl).call(this,{type:"invalidate"})}async fetch(t,n){var c,u,d,f,h,p,g,b,x,y,S,w;if(this.state.fetchStatus!=="idle"&&((c=he(this,ys))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(he(this,ys))return he(this,ys).continueRetry(),he(this,ys).promise}if(t&&this.setOptions(t),!this.options.queryFn){const C=this.observers.find(N=>N.options.queryFn);C&&this.setOptions(C.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const r=new AbortController,s=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(vt(this,Ff,!0),r.signal)})},o=()=>{const C=DW(this.options,n),k=(()=>{const _={client:he(this,Rf),queryKey:this.queryKey,meta:this.meta};return s(_),_})();return vt(this,Ff,!1),this.options.persister?this.options.persister(C,k,this):C(k)},a=(()=>{const C={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:he(this,Rf),state:this.state,fetchFn:o};return s(C),C})();(u=this.options.behavior)==null||u.onFetch(a,this),vt(this,vm,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=a.fetchOptions)==null?void 0:d.meta))&&Gt(this,da,Xl).call(this,{type:"fetch",meta:(f=a.fetchOptions)==null?void 0:f.meta}),vt(this,ys,MW({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:C=>{C instanceof x2&&C.revert&&this.setState({...he(this,vm),fetchStatus:"idle"}),r.abort()},onFail:(C,N)=>{Gt(this,da,Xl).call(this,{type:"failed",failureCount:C,error:N})},onPause:()=>{Gt(this,da,Xl).call(this,{type:"pause"})},onContinue:()=>{Gt(this,da,Xl).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const C=await he(this,ys).start();if(C===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(C),(p=(h=he(this,Ri).config).onSuccess)==null||p.call(h,C,this),(b=(g=he(this,Ri).config).onSettled)==null||b.call(g,C,this.state.error,this),C}catch(C){if(C instanceof x2){if(C.silent)return he(this,ys).promise;if(C.revert){if(this.state.data===void 0)throw C;return this.state.data}}throw Gt(this,da,Xl).call(this,{type:"error",error:C}),(y=(x=he(this,Ri).config).onError)==null||y.call(x,C,this),(w=(S=he(this,Ri).config).onSettled)==null||w.call(S,this.state.data,C,this),C}finally{this.scheduleGc()}}},Af=new WeakMap,vm=new WeakMap,Ri=new WeakMap,Rf=new WeakMap,ys=new WeakMap,U0=new WeakMap,Ff=new WeakMap,da=new WeakSet,Xl=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...RW(r.data,this.options),fetchMeta:t.meta??null};case"success":const s={...r,...N$(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return vt(this,vm,t.manual?s:void 0),s;case"error":const o=t.error;return{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),$r.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),he(this,Ri).notify({query:this,type:"updated",action:t})})},mW);function RW(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:TW(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function N$(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function k$(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var qo,Dn,W0,jo,Pf,wm,ac,Cu,q0,Sm,Cm,Of,Lf,Nu,Nm,Jn,fx,y2,v2,w2,S2,C2,N2,k2,FW,gW,oF=(gW=class extends Fh{constructor(t,n){super();Mt(this,Jn);Mt(this,qo);Mt(this,Dn);Mt(this,W0);Mt(this,jo);Mt(this,Pf);Mt(this,wm);Mt(this,ac);Mt(this,Cu);Mt(this,q0);Mt(this,Sm);Mt(this,Cm);Mt(this,Of);Mt(this,Lf);Mt(this,Nu);Mt(this,Nm,new Set);this.options=n,vt(this,qo,t),vt(this,Cu,null),vt(this,ac,b2()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(he(this,Dn).addObserver(this),_$(he(this,Dn),this.options)?Gt(this,Jn,fx).call(this):this.updateResult(),Gt(this,Jn,S2).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _2(he(this,Dn),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _2(he(this,Dn),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Gt(this,Jn,C2).call(this),Gt(this,Jn,N2).call(this),he(this,Dn).removeObserver(this)}setOptions(t){const n=this.options,r=he(this,Dn);if(this.options=he(this,qo).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Oi(this.options.enabled,he(this,Dn))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Gt(this,Jn,k2).call(this),he(this,Dn).setOptions(this.options),n._defaulted&&!Ey(this.options,n)&&he(this,qo).getQueryCache().notify({type:"observerOptionsUpdated",query:he(this,Dn),observer:this});const s=this.hasListeners();s&&j$(he(this,Dn),r,this.options,n)&&Gt(this,Jn,fx).call(this),this.updateResult(),s&&(he(this,Dn)!==r||Oi(this.options.enabled,he(this,Dn))!==Oi(n.enabled,he(this,Dn))||Hu(this.options.staleTime,he(this,Dn))!==Hu(n.staleTime,he(this,Dn)))&&Gt(this,Jn,y2).call(this);const o=Gt(this,Jn,v2).call(this);s&&(he(this,Dn)!==r||Oi(this.options.enabled,he(this,Dn))!==Oi(n.enabled,he(this,Dn))||o!==he(this,Nu))&&Gt(this,Jn,w2).call(this,o)}getOptimisticResult(t){const n=he(this,qo).getQueryCache().build(he(this,qo),t),r=this.createResult(n,t);return xpe(this,r)&&(vt(this,jo,r),vt(this,wm,this.options),vt(this,Pf,he(this,Dn).state)),r}getCurrentResult(){return he(this,jo)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n==null||n(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&he(this,ac).status==="pending"&&he(this,ac).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){he(this,Nm).add(t)}getCurrentQuery(){return he(this,Dn)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=he(this,qo).defaultQueryOptions(t),r=he(this,qo).getQueryCache().build(he(this,qo),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Gt(this,Jn,fx).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),he(this,jo)))}createResult(t,n){var D;const r=he(this,Dn),s=this.options,o=he(this,jo),i=he(this,Pf),a=he(this,wm),u=t!==r?t.state:he(this,W0),{state:d}=t;let f={...d},h=!1,p;if(n._optimisticResults){const j=this.hasListeners(),I=!j&&_$(t,n),T=j&&j$(t,r,n,s);(I||T)&&(f={...f,...RW(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:g,errorUpdatedAt:b,status:x}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&x==="pending"){let j;o!=null&&o.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(j=o.data,y=!0):j=typeof n.placeholderData=="function"?n.placeholderData((D=he(this,Cm))==null?void 0:D.state.data,he(this,Cm)):n.placeholderData,j!==void 0&&(x="success",p=g2(o==null?void 0:o.data,j,n),h=!0)}if(n.select&&p!==void 0&&!y)if(o&&p===(i==null?void 0:i.data)&&n.select===he(this,q0))p=he(this,Sm);else try{vt(this,q0,n.select),p=n.select(p),p=g2(o==null?void 0:o.data,p,n),vt(this,Sm,p),vt(this,Cu,null)}catch(j){vt(this,Cu,j)}he(this,Cu)&&(g=he(this,Cu),p=he(this,Sm),b=Date.now(),x="error");const S=f.fetchStatus==="fetching",w=x==="pending",C=x==="error",N=w&&S,k=p!==void 0,E={status:x,fetchStatus:f.fetchStatus,isPending:w,isSuccess:x==="success",isError:C,isInitialLoading:N,isLoading:N,data:p,dataUpdatedAt:f.dataUpdatedAt,error:g,errorUpdatedAt:b,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:f.dataUpdateCount>0||f.errorUpdateCount>0,isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!w,isLoadingError:C&&!k,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&k,isStale:iF(t,n),refetch:this.refetch,promise:he(this,ac),isEnabled:Oi(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const j=F=>{E.status==="error"?F.reject(E.error):E.data!==void 0&&F.resolve(E.data)},I=()=>{const F=vt(this,ac,E.promise=b2());j(F)},T=he(this,ac);switch(T.status){case"pending":t.queryHash===r.queryHash&&j(T);break;case"fulfilled":(E.status==="error"||E.data!==T.value)&&I();break;case"rejected":(E.status!=="error"||E.error!==T.reason)&&I();break}}return E}updateResult(){const t=he(this,jo),n=this.createResult(he(this,Dn),this.options);if(vt(this,Pf,he(this,Dn).state),vt(this,wm,this.options),he(this,Pf).data!==void 0&&vt(this,Cm,he(this,Dn)),Ey(n,t))return;vt(this,jo,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:s}=this.options,o=typeof s=="function"?s():s;if(o==="all"||!o&&!he(this,Nm).size)return!0;const i=new Set(o??he(this,Nm));return this.options.throwOnError&&i.add("error"),Object.keys(he(this,jo)).some(a=>{const c=a;return he(this,jo)[c]!==t[c]&&i.has(c)})};Gt(this,Jn,FW).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Gt(this,Jn,S2).call(this)}},qo=new WeakMap,Dn=new WeakMap,W0=new WeakMap,jo=new WeakMap,Pf=new WeakMap,wm=new WeakMap,ac=new WeakMap,Cu=new WeakMap,q0=new WeakMap,Sm=new WeakMap,Cm=new WeakMap,Of=new WeakMap,Lf=new WeakMap,Nu=new WeakMap,Nm=new WeakMap,Jn=new WeakSet,fx=function(t){Gt(this,Jn,k2).call(this);let n=he(this,Dn).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Qs)),n},y2=function(){Gt(this,Jn,C2).call(this);const t=Hu(this.options.staleTime,he(this,Dn));if(sh||he(this,jo).isStale||!p2(t))return;const r=EW(he(this,jo).dataUpdatedAt,t)+1;vt(this,Of,xf.setTimeout(()=>{he(this,jo).isStale||this.updateResult()},r))},v2=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(he(this,Dn)):this.options.refetchInterval)??!1},w2=function(t){Gt(this,Jn,N2).call(this),vt(this,Nu,t),!(sh||Oi(this.options.enabled,he(this,Dn))===!1||!p2(he(this,Nu))||he(this,Nu)===0)&&vt(this,Lf,xf.setInterval(()=>{(this.options.refetchIntervalInBackground||sF.isFocused())&&Gt(this,Jn,fx).call(this)},he(this,Nu)))},S2=function(){Gt(this,Jn,y2).call(this),Gt(this,Jn,w2).call(this,Gt(this,Jn,v2).call(this))},C2=function(){he(this,Of)&&(xf.clearTimeout(he(this,Of)),vt(this,Of,void 0))},N2=function(){he(this,Lf)&&(xf.clearInterval(he(this,Lf)),vt(this,Lf,void 0))},k2=function(){const t=he(this,qo).getQueryCache().build(he(this,qo),this.options);if(t===he(this,Dn))return;const n=he(this,Dn);vt(this,Dn,t),vt(this,W0,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},FW=function(t){$r.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(he(this,jo))}),he(this,qo).getQueryCache().notify({query:he(this,Dn),type:"observerResultsUpdated"})})},gW);function bpe(e,t){return Oi(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _$(e,t){return bpe(e,t)||e.state.data!==void 0&&_2(e,t,t.refetchOnMount)}function _2(e,t,n){if(Oi(t.enabled,e)!==!1&&Hu(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&iF(e,t)}return!1}function j$(e,t,n,r){return(e!==t||Oi(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&iF(e,n)}function iF(e,t){return Oi(t.enabled,e)!==!1&&e.isStaleByTime(Hu(t.staleTime,e))}function xpe(e,t){return!Ey(e.getCurrentResult(),t)}function E$(e){return{onFetch:(t,n)=>{var d,f,h,p,g;const r=t.options,s=(h=(f=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:f.fetchMore)==null?void 0:h.direction,o=((p=t.state.data)==null?void 0:p.pages)||[],i=((g=t.state.data)==null?void 0:g.pageParams)||[];let a={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const x=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?b=!0:t.signal.addEventListener("abort",()=>{b=!0}),t.signal)})},y=DW(t.options,t.fetchOptions),S=async(w,C,N)=>{if(b)return Promise.reject();if(C==null&&w.pages.length)return Promise.resolve(w);const _=(()=>{const I={client:t.client,queryKey:t.queryKey,pageParam:C,direction:N?"backward":"forward",meta:t.options.meta};return x(I),I})(),E=await y(_),{maxPages:D}=t.options,j=N?upe:cpe;return{pages:j(w.pages,E,D),pageParams:j(w.pageParams,C,D)}};if(s&&o.length){const w=s==="backward",C=w?ype:D$,N={pages:o,pageParams:i},k=C(r,N);a=await S(N,k,w)}else{const w=e??o.length;do{const C=c===0?i[0]??r.initialPageParam:D$(r,a);if(c>0&&C==null)break;a=await S(a,C),c++}while(c<w)}return a};t.options.persister?t.fetchFn=()=>{var b,x;return(x=(b=t.options).persister)==null?void 0:x.call(b,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function D$(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function ype(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Y0,el,Eo,$f,tl,mu,bW,vpe=(bW=class extends AW{constructor(t){super();Mt(this,tl);Mt(this,Y0);Mt(this,el);Mt(this,Eo);Mt(this,$f);vt(this,Y0,t.client),this.mutationId=t.mutationId,vt(this,Eo,t.mutationCache),vt(this,el,[]),this.state=t.state||PW(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){he(this,el).includes(t)||(he(this,el).push(t),this.clearGcTimeout(),he(this,Eo).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){vt(this,el,he(this,el).filter(n=>n!==t)),this.scheduleGc(),he(this,Eo).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){he(this,el).length||(this.state.status==="pending"?this.scheduleGc():he(this,Eo).remove(this))}continue(){var t;return((t=he(this,$f))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,a,c,u,d,f,h,p,g,b,x,y,S,w,C,N,k,_,E,D;const n=()=>{Gt(this,tl,mu).call(this,{type:"continue"})},r={client:he(this,Y0),meta:this.options.meta,mutationKey:this.options.mutationKey};vt(this,$f,MW({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(j,I)=>{Gt(this,tl,mu).call(this,{type:"failed",failureCount:j,error:I})},onPause:()=>{Gt(this,tl,mu).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>he(this,Eo).canRun(this)}));const s=this.state.status==="pending",o=!he(this,$f).canStart();try{if(s)n();else{Gt(this,tl,mu).call(this,{type:"pending",variables:t,isPaused:o}),await((a=(i=he(this,Eo).config).onMutate)==null?void 0:a.call(i,t,this,r));const I=await((u=(c=this.options).onMutate)==null?void 0:u.call(c,t,r));I!==this.state.context&&Gt(this,tl,mu).call(this,{type:"pending",context:I,variables:t,isPaused:o})}const j=await he(this,$f).start();return await((f=(d=he(this,Eo).config).onSuccess)==null?void 0:f.call(d,j,t,this.state.context,this,r)),await((p=(h=this.options).onSuccess)==null?void 0:p.call(h,j,t,this.state.context,r)),await((b=(g=he(this,Eo).config).onSettled)==null?void 0:b.call(g,j,null,this.state.variables,this.state.context,this,r)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,j,null,t,this.state.context,r)),Gt(this,tl,mu).call(this,{type:"success",data:j}),j}catch(j){try{throw await((w=(S=he(this,Eo).config).onError)==null?void 0:w.call(S,j,t,this.state.context,this,r)),await((N=(C=this.options).onError)==null?void 0:N.call(C,j,t,this.state.context,r)),await((_=(k=he(this,Eo).config).onSettled)==null?void 0:_.call(k,void 0,j,this.state.variables,this.state.context,this,r)),await((D=(E=this.options).onSettled)==null?void 0:D.call(E,void 0,j,t,this.state.context,r)),j}finally{Gt(this,tl,mu).call(this,{type:"error",error:j})}}finally{he(this,Eo).runNext(this)}}},Y0=new WeakMap,el=new WeakMap,Eo=new WeakMap,$f=new WeakMap,tl=new WeakSet,mu=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),$r.batch(()=>{he(this,el).forEach(r=>{r.onMutationUpdate(t)}),he(this,Eo).notify({mutation:this,type:"updated",action:t})})},bW);function PW(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lc,fa,G0,xW,wpe=(xW=class extends Fh{constructor(t={}){super();Mt(this,lc);Mt(this,fa);Mt(this,G0);this.config=t,vt(this,lc,new Set),vt(this,fa,new Map),vt(this,G0,0)}build(t,n,r){const s=new vpe({client:t,mutationCache:this,mutationId:++_w(this,G0)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){he(this,lc).add(t);const n=Dw(t);if(typeof n=="string"){const r=he(this,fa).get(n);r?r.push(t):he(this,fa).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(he(this,lc).delete(t)){const n=Dw(t);if(typeof n=="string"){const r=he(this,fa).get(n);if(r)if(r.length>1){const s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&he(this,fa).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Dw(t);if(typeof n=="string"){const r=he(this,fa).get(n),s=r==null?void 0:r.find(o=>o.state.status==="pending");return!s||s===t}else return!0}runNext(t){var r;const n=Dw(t);if(typeof n=="string"){const s=(r=he(this,fa).get(n))==null?void 0:r.find(o=>o!==t&&o.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){$r.batch(()=>{he(this,lc).forEach(t=>{this.notify({type:"removed",mutation:t})}),he(this,lc).clear(),he(this,fa).clear()})}getAll(){return Array.from(he(this,lc))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>w$(n,r))}findAll(t={}){return this.getAll().filter(n=>w$(t,n))}notify(t){$r.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return $r.batch(()=>Promise.all(t.map(n=>n.continue().catch(Qs))))}},lc=new WeakMap,fa=new WeakMap,G0=new WeakMap,xW);function Dw(e){var t;return(t=e.options.scope)==null?void 0:t.id}var cc,ku,Yo,uc,Fc,wS,j2,yW,Spe=(yW=class extends Fh{constructor(n,r){super();Mt(this,Fc);Mt(this,cc);Mt(this,ku);Mt(this,Yo);Mt(this,uc);vt(this,cc,n),this.setOptions(r),this.bindMethods(),Gt(this,Fc,wS).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var s;const r=this.options;this.options=he(this,cc).defaultMutationOptions(n),Ey(this.options,r)||he(this,cc).getMutationCache().notify({type:"observerOptionsUpdated",mutation:he(this,Yo),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&oh(r.mutationKey)!==oh(this.options.mutationKey)?this.reset():((s=he(this,Yo))==null?void 0:s.state.status)==="pending"&&he(this,Yo).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=he(this,Yo))==null||n.removeObserver(this)}onMutationUpdate(n){Gt(this,Fc,wS).call(this),Gt(this,Fc,j2).call(this,n)}getCurrentResult(){return he(this,ku)}reset(){var n;(n=he(this,Yo))==null||n.removeObserver(this),vt(this,Yo,void 0),Gt(this,Fc,wS).call(this),Gt(this,Fc,j2).call(this)}mutate(n,r){var s;return vt(this,uc,r),(s=he(this,Yo))==null||s.removeObserver(this),vt(this,Yo,he(this,cc).getMutationCache().build(he(this,cc),this.options)),he(this,Yo).addObserver(this),he(this,Yo).execute(n)}},cc=new WeakMap,ku=new WeakMap,Yo=new WeakMap,uc=new WeakMap,Fc=new WeakSet,wS=function(){var r;const n=((r=he(this,Yo))==null?void 0:r.state)??PW();vt(this,ku,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},j2=function(n){$r.batch(()=>{var r,s,o,i,a,c,u,d;if(he(this,uc)&&this.hasListeners()){const f=he(this,ku).variables,h=he(this,ku).context,p={client:he(this,cc),meta:this.options.meta,mutationKey:this.options.mutationKey};(n==null?void 0:n.type)==="success"?((s=(r=he(this,uc)).onSuccess)==null||s.call(r,n.data,f,h,p),(i=(o=he(this,uc)).onSettled)==null||i.call(o,n.data,null,f,h,p)):(n==null?void 0:n.type)==="error"&&((c=(a=he(this,uc)).onError)==null||c.call(a,n.error,f,h,p),(d=(u=he(this,uc)).onSettled)==null||d.call(u,void 0,n.error,f,h,p))}this.listeners.forEach(f=>{f(he(this,ku))})})},yW);function I$(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Cpe(e,t,n){const r=e.slice(0);return r[t]=n,r}var zf,fi,km,_m,Fi,_u,K0,Z0,X0,Us,E2,D2,I2,T2,M2,vW,Npe=(vW=class extends Fh{constructor(t,n,r){super();Mt(this,Us);Mt(this,zf);Mt(this,fi);Mt(this,km);Mt(this,_m);Mt(this,Fi);Mt(this,_u);Mt(this,K0);Mt(this,Z0);Mt(this,X0,[]);vt(this,zf,t),vt(this,_m,r),vt(this,km,[]),vt(this,Fi,[]),vt(this,fi,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&he(this,Fi).forEach(t=>{t.subscribe(n=>{Gt(this,Us,T2).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,he(this,Fi).forEach(t=>{t.destroy()})}setQueries(t,n){if(vt(this,km,t),vt(this,_m,n),process.env.NODE_ENV!=="production"){const r=t.map(s=>he(this,zf).defaultQueryOptions(s).queryHash);new Set(r).size!==r.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}$r.batch(()=>{const r=he(this,Fi),s=Gt(this,Us,I2).call(this,he(this,km));vt(this,X0,s),s.forEach(f=>f.observer.setOptions(f.defaultedQueryOptions));const o=s.map(f=>f.observer),i=o.map(f=>f.getCurrentResult()),a=r.length!==o.length,c=o.some((f,h)=>f!==r[h]),u=a||c,d=u?!0:i.some((f,h)=>{const p=he(this,fi)[h];return!p||!Ey(f,p)});!u&&!d||(u&&vt(this,Fi,o),vt(this,fi,i),this.hasListeners()&&(u&&(I$(r,o).forEach(f=>{f.destroy()}),I$(o,r).forEach(f=>{f.subscribe(h=>{Gt(this,Us,T2).call(this,f,h)})})),Gt(this,Us,M2).call(this)))})}getCurrentResult(){return he(this,fi)}getQueries(){return he(this,Fi).map(t=>t.getCurrentQuery())}getObservers(){return he(this,Fi)}getOptimisticResult(t,n){const r=Gt(this,Us,I2).call(this,t),s=r.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions));return[s,o=>Gt(this,Us,D2).call(this,o??s,n),()=>Gt(this,Us,E2).call(this,s,r)]}},zf=new WeakMap,fi=new WeakMap,km=new WeakMap,_m=new WeakMap,Fi=new WeakMap,_u=new WeakMap,K0=new WeakMap,Z0=new WeakMap,X0=new WeakMap,Us=new WeakSet,E2=function(t,n){return n.map((r,s)=>{const o=t[s];return r.defaultedQueryOptions.notifyOnChangeProps?o:r.observer.trackResult(o,i=>{n.forEach(a=>{a.observer.trackProp(i)})})})},D2=function(t,n){return n?((!he(this,_u)||he(this,fi)!==he(this,Z0)||n!==he(this,K0))&&(vt(this,K0,n),vt(this,Z0,he(this,fi)),vt(this,_u,pC(he(this,_u),n(t)))),he(this,_u)):t},I2=function(t){const n=new Map;he(this,Fi).forEach(s=>{const o=s.options.queryHash;if(!o)return;const i=n.get(o);i?i.push(s):n.set(o,[s])});const r=[];return t.forEach(s=>{var c;const o=he(this,zf).defaultQueryOptions(s),a=((c=n.get(o.queryHash))==null?void 0:c.shift())??new oF(he(this,zf),o);r.push({defaultedQueryOptions:o,observer:a})}),r},T2=function(t,n){const r=he(this,Fi).indexOf(t);r!==-1&&(vt(this,fi,Cpe(he(this,fi),r,n)),Gt(this,Us,M2).call(this))},M2=function(){var t;if(this.hasListeners()){const n=he(this,_u),r=Gt(this,Us,E2).call(this,he(this,fi),he(this,X0)),s=Gt(this,Us,D2).call(this,r,(t=he(this,_m))==null?void 0:t.combine);n!==s&&$r.batch(()=>{this.listeners.forEach(o=>{o(he(this,fi))})})}},vW),nl,wW,OW=(wW=class extends Fh{constructor(t={}){super();Mt(this,nl);this.config=t,vt(this,nl,new Map)}build(t,n,r){const s=n.queryKey,o=n.queryHash??rF(s,n);let i=this.get(o);return i||(i=new gpe({client:t,queryKey:s,queryHash:o,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(i)),i}add(t){he(this,nl).has(t.queryHash)||(he(this,nl).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=he(this,nl).get(t.queryHash);n&&(t.destroy(),n===t&&he(this,nl).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){$r.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return he(this,nl).get(t)}getAll(){return[...he(this,nl).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>v$(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>v$(t,r)):n}notify(t){$r.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){$r.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){$r.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},nl=new WeakMap,wW),Ur,ju,Eu,jm,Em,Du,Dm,Im,SW,kpe=(SW=class{constructor(e={}){Mt(this,Ur);Mt(this,ju);Mt(this,Eu);Mt(this,jm);Mt(this,Em);Mt(this,Du);Mt(this,Dm);Mt(this,Im);vt(this,Ur,e.queryCache||new OW),vt(this,ju,e.mutationCache||new wpe),vt(this,Eu,e.defaultOptions||{}),vt(this,jm,new Map),vt(this,Em,new Map),vt(this,Du,0)}mount(){_w(this,Du)._++,he(this,Du)===1&&(vt(this,Dm,sF.subscribe(async e=>{e&&(await this.resumePausedMutations(),he(this,Ur).onFocus())})),vt(this,Im,gC.subscribe(async e=>{e&&(await this.resumePausedMutations(),he(this,Ur).onOnline())})))}unmount(){var e,t;_w(this,Du)._--,he(this,Du)===0&&((e=he(this,Dm))==null||e.call(this),vt(this,Dm,void 0),(t=he(this,Im))==null||t.call(this),vt(this,Im,void 0))}isFetching(e){return he(this,Ur).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return he(this,ju).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=he(this,Ur).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=he(this,Ur).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Hu(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return he(this,Ur).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=he(this,Ur).get(r.queryHash),o=s==null?void 0:s.state.data,i=ope(t,o);if(i!==void 0)return he(this,Ur).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return $r.batch(()=>he(this,Ur).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=he(this,Ur).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=he(this,Ur);$r.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=he(this,Ur);return $r.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=$r.batch(()=>he(this,Ur).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Qs).catch(Qs)}invalidateQueries(e,t={}){return $r.batch(()=>(he(this,Ur).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=$r.batch(()=>he(this,Ur).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Qs)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Qs)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=he(this,Ur).build(this,t);return n.isStaleByTime(Hu(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Qs).catch(Qs)}fetchInfiniteQuery(e){return e.behavior=E$(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Qs).catch(Qs)}ensureInfiniteQueryData(e){return e.behavior=E$(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return gC.isOnline()?he(this,ju).resumePausedMutations():Promise.resolve()}getQueryCache(){return he(this,Ur)}getMutationCache(){return he(this,ju)}getDefaultOptions(){return he(this,Eu)}setDefaultOptions(e){vt(this,Eu,e)}setQueryDefaults(e,t){he(this,jm).set(oh(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...he(this,jm).values()],n={};return t.forEach(r=>{jy(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){he(this,Em).set(oh(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...he(this,Em).values()],n={};return t.forEach(r=>{jy(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...he(this,Eu).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=rF(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===mC&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...he(this,Eu).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){he(this,Ur).clear(),he(this,ju).clear()}},Ur=new WeakMap,ju=new WeakMap,Eu=new WeakMap,jm=new WeakMap,Em=new WeakMap,Du=new WeakMap,Dm=new WeakMap,Im=new WeakMap,SW),aF=Q.createContext(void 0),ns=e=>{const t=Q.useContext(aF);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},_pe=({client:e,children:t})=>(Q.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(aF.Provider,{value:e,children:t})),LW=Q.createContext(!1),$W=()=>Q.useContext(LW);LW.Provider;function jpe(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Epe=Q.createContext(jpe()),zW=()=>Q.useContext(Epe),BW=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},VW=e=>{Q.useEffect(()=>{e.clearReset()},[e])},HW=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||IW(n,[e.error,r])),UW=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},WW=(e,t)=>e.isLoading&&e.isFetching&&!t,A2=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,bC=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function hg({queries:e,...t},n){const r=ns(),s=$W(),o=zW(),i=Q.useMemo(()=>e.map(b=>{const x=r.defaultQueryOptions(b);return x._optimisticResults=s?"isRestoring":"optimistic",x}),[e,r,s]);i.forEach(b=>{UW(b),BW(b,o)}),VW(o);const[a]=Q.useState(()=>new Npe(r,i,t)),[c,u,d]=a.getOptimisticResult(i,t.combine),f=!s&&t.subscribed!==!1;Q.useSyncExternalStore(Q.useCallback(b=>f?a.subscribe($r.batchCalls(b)):Qs,[a,f]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),Q.useEffect(()=>{a.setQueries(i,t)},[i,t,a]);const p=c.some((b,x)=>A2(i[x],b))?c.flatMap((b,x)=>{const y=i[x];if(y){const S=new oF(r,y);if(A2(y,b))return bC(y,S,o);WW(b,s)&&bC(y,S,o)}return[]}):[];if(p.length>0)throw Promise.all(p);const g=c.find((b,x)=>{const y=i[x];return y&&HW({result:b,errorResetBoundary:o,throwOnError:y.throwOnError,query:r.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(g!=null&&g.error)throw g.error;return u(d())}function Dpe(e,t,n){var f,h,p,g,b;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=$W(),s=zW(),o=ns(),i=o.defaultQueryOptions(e);(h=(f=o.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||h.call(f,i),process.env.NODE_ENV!=="production"&&(i.queryFn||console.error(`[${i.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),i._optimisticResults=r?"isRestoring":"optimistic",UW(i),BW(i,s),VW(s);const a=!o.getQueryCache().get(i.queryHash),[c]=Q.useState(()=>new t(o,i)),u=c.getOptimisticResult(i),d=!r&&e.subscribed!==!1;if(Q.useSyncExternalStore(Q.useCallback(x=>{const y=d?c.subscribe($r.batchCalls(x)):Qs;return c.updateResult(),y},[c,d]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),Q.useEffect(()=>{c.setOptions(i)},[i,c]),A2(i,u))throw bC(i,c,s);if(HW({result:u,errorResetBoundary:s,throwOnError:i.throwOnError,query:o.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw u.error;if((g=(p=o.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||g.call(p,i,u),i.experimental_prefetchInRender&&!sh&&WW(u,r)){const x=a?bC(i,c,s):(b=o.getQueryCache().get(i.queryHash))==null?void 0:b.promise;x==null||x.catch(Qs).finally(()=>{c.updateResult()})}return i.notifyOnChangeProps?u:c.trackResult(u)}function On(e,t){return Dpe(e,oF)}function Ipe(e,t){const n=ns(),r=n.getQueryCache();return Q.useSyncExternalStore(Q.useCallback(s=>r.subscribe($r.batchCalls(s)),[r]),()=>n.isFetching(e),()=>n.isFetching(e))}function co(e,t){const n=ns(),[r]=Q.useState(()=>new Spe(n,e));Q.useEffect(()=>{r.setOptions(e)},[r,e]);const s=Q.useSyncExternalStore(Q.useCallback(i=>r.subscribe($r.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=Q.useCallback((i,a)=>{r.mutate(i,a).catch(Qs)},[r]);if(s.error&&IW(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}function Tpe(){const e=v.useContext(aF);if(e&&e.isSemaphorClient)return e}function qW({children:e}){const{setIsSessionExpired:t}=m.useDashboardActions(),n=Tpe(),[r]=v.useState(()=>{const s=new kpe({queryCache:new OW({onError:o=>{o instanceof Error?(console.error(`Something went wrong: ${o.message}`),o.message==="invalid token"&&t(!0)):console.error("Something went wrong:",o)}}),defaultOptions:{queries:{gcTime:36e5,staleTime:3e5,refetchOnWindowFocus:!1,retry:!1}}});return s.isSemaphorClient=!0,s});return n?l.jsx(l.Fragment,{children:e}):l.jsx(_pe,{client:r,children:e})}const Mpe={id:"",authToken:void 0,tokenProps:{}},pg=v.createContext(Mpe),lF=({children:e,dashboardProps:t})=>{const n=v.useMemo(()=>{let r={};const s=t.authToken;return s&&(r=ghe.jwtDecode(s.accessToken)),{...t,tokenProps:r}},[t]);return l.jsx(qW,{children:l.jsx(pg.Provider,{value:n,children:e})})};function Ct(){const e=v.useContext(pg);if(e===void 0)throw new Error("useApplicationContext must be used within a ApplicationContextProvider");return e}const is=m.create()(m.immer(e=>({initialDashboard:null,selectedDashboard:null,selectedVisual:null,lastSelectedDashboard:null,lastSelectedVisual:null,showHub:!1,actions:{setInitialDashboard:t=>{e(n=>{n.initialDashboard=t})},selectDashboard:t=>{e(n=>{var r;((r=n.selectedDashboard)==null?void 0:r.id)!==t.id&&(n.lastSelectedDashboard=n.selectedDashboard,n.selectedDashboard=t),n.showHub=!1})},updateSelectedDashboard:t=>{e(n=>{n.selectedDashboard=t})},selectVisual:t=>{e(n=>{n.lastSelectedVisual=n.selectedVisual,n.selectedVisual=t})},clearSelectedDashboard:()=>{e(t=>{t.lastSelectedDashboard=t.selectedDashboard,t.selectedDashboard=null,t.showHub=!0})},clearSelectedVisual:()=>{e(t=>{t.lastSelectedVisual=t.selectedVisual,t.selectedVisual=null})},setShowHub:t=>{e(n=>{n.showHub=t})}}}))),Ape=()=>is(e=>e.selectedVisual),Ph=()=>is(e=>e.actions),Rpe=e=>{const t=is(o=>o.selectedDashboard),n=is(o=>o.lastSelectedDashboard),r=m.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.id});return t===null&&n!==null?!1:((t==null?void 0:t.id)||r)===e},Fpe=e=>is(t=>{var n;return((n=t.selectedVisual)==null?void 0:n.id)===e});function Q0(){const{authToken:e,version:t,tokenProps:n,id:r}=Ct(),s=is(g=>g.selectedDashboard),o=is(g=>g.showHub),i=m.useDashboardStore(g=>g.selectedLensId),a=Ppe({showHub:o,selectedDashboardId:s==null?void 0:s.id,dashboardId:r,tokenDashboardId:n==null?void 0:n.dashboard_id});function c(){return!(!(e!=null&&e.accessToken)||!a)}const{data:u,isLoading:d,isFetching:f,isError:h,refetch:p}=On({queryKey:["dashboard",i,e==null?void 0:e.accessToken,a],queryFn:()=>m.getDashboard(n.apiServiceUrl,e==null?void 0:e.accessToken,{lensId:i,version:t,dashboardId:a}),enabled:c()});return{data:u,isLoading:d,isFetching:f,isError:h,refetch:p,dashboardIdToFetch:a}}function Ppe({showHub:e,selectedDashboardId:t,dashboardId:n,tokenDashboardId:r}){return e?null:t||n||r||null}function Ope(){const{authToken:e}=Ct(),t=m.useDashboardStore(r=>r.authToken),{setAuthToken:n}=m.useDashboardActions();return v.useEffect(()=>{const r=e==null?void 0:e.accessToken,s=t==null?void 0:t.accessToken;e&&r!==s&&n(e)},[e,t,n]),e}function YW(e){const t=v.useCallback(o=>`semaphor-default-sheet-${o}`,[]),n=v.useCallback(()=>{if(!e)return null;try{const o=t(e);return localStorage.getItem(o)}catch(o){return console.error("Error reading default sheet preference:",o),null}},[e,t]),r=v.useCallback(o=>{if(!(!e||!o))try{const i=t(e);localStorage.setItem(i,o)}catch(i){console.error("Error saving default sheet preference:",i)}},[e,t]),s=v.useCallback(()=>{if(e)try{const o=t(e);localStorage.removeItem(o)}catch(o){console.error("Error clearing default sheet preference:",o)}},[e,t]);return{getDefaultSheetId:n,setDefaultSheetId:r,clearDefaultSheetId:s}}function Lpe(e,t){if(!e||typeof e!="object"||!("kind"in e))return e;switch(e.kind){case"manual":return{kind:"manual",...t!=null&&t.includePresentation?{options:e.options.map(n=>({value:n.value,label:n.label,presentation:n.presentation}))}:{optionValues:e.options.map(n=>n.value).sort()}};case"dataset_values":return{kind:"dataset_values",fieldId:e.fieldId,connectionId:e.connectionId||""};case"field_allowlist":return{kind:"field_allowlist",fieldIds:[...e.fieldIds].sort()};case"metric_allowlist":return{kind:"metric_allowlist",metricIds:[...e.metricIds].sort()};case"sql_query":return{kind:"sql_query",connectionId:e.connectionId,sql:e.sql,valueColumn:e.valueColumn,labelColumn:e.labelColumn};default:return e}}function $pe(e,t){return{id:e.id,scope:e.scope,type:e.type,source:Lpe(e.source,t),initialValueStrategy:e.initialValueStrategy,defaultValue:e.defaultValue,requiredAtExecution:e.requiredAtExecution,...t!=null&&t.includePresentation?{label:e.label,helpText:e.helpText,hidden:e.hidden,locked:e.locked,placement:e.placement,showLabel:e.showLabel,toolbarWidth:e.toolbarWidth}:{}}}function zpe(e){return e.target==="sql_param"?e:{...e,mapping:Object.fromEntries(Object.entries(e.mapping).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([r],[s])=>r.localeCompare(s))):n]))}}function T$(e=[],t){return[...e].map(n=>$pe(n,t)).sort((n,r)=>n.id.localeCompare(r.id)||n.scope.localeCompare(r.scope)||n.type.localeCompare(r.type))}function Bpe(e=[]){return[...e].map(zpe).sort((t,n)=>Mo.stableSerialize(t).localeCompare(Mo.stableSerialize(n)))}function R2(e,t){return e?Mo.stableSerialize({controlDefinitions:T$(e.controlDefinitions,t),cardControlDefinitions:T$(e.cardControlDefinitions,t),controlBindings:Bpe(e.controlBindings)}):"__none__"}function CE(e,t){return e&&t.has(e)?e:null}function Vpe({selectedSheetId:e,preservedSelectedSheetId:t,defaultSheetId:n,sheets:r}){var o;const s=new Set((r||[]).map(i=>i.id).filter(i=>typeof i=="string"));return CE(e,s)||CE(t,s)||CE(n,s)||((o=r==null?void 0:r[0])==null?void 0:o.id)||null}function GW(e){const t=e.trim().split(/[^A-Za-z0-9]+/).filter(Boolean).map(r=>r.toLowerCase());if(!t.length)return"input";const n=t.map((r,s)=>s===0?r:A$(r)).join("");return/^[A-Za-z]/.test(n)?n:`input${A$(n)}`}function cF(e,t){const n=GW(e);return KW(n,t)}function J0(e){const n=e.trim().replace(/^\{\{\s*/,"").replace(/\s*\}\}$/,"").replace(/[^A-Za-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"");return n?/^[A-Za-z]/.test(n)?n:`input_${n}`:"input"}function Ju(e,t){return KW(J0(e),t)}function KW(e,t){const n=new Set(t.map(s=>s.variableName).filter(s=>!!s));if(!n.has(e))return e;let r=2;for(;n.has(`${e}${r}`);)r+=1;return`${e}${r}`}function uF(e){return m.getDataType(e.dataType)==="date"?["label","start","end","range"]:["label","value"]}function dF(e){return Upe(e)?["label","value"]:["value"]}function M$(e){return e.kind==="filter"?`filter:${e.filter.id}`:`control:${e.control.id}`}function Hpe(e){return{placement:e.hide||e.displayMode==="canvas"?"hidden":"toolbar",...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function ZW(e){return{placement:e.hidden?"hidden":e.placement||(e.scope==="card"?"card_header":"toolbar"),...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function xC(e){return!!e.compatibility}function Upe(e){return e.type==="enum"||e.type==="multi_enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function A$(e){return e&&e[0].toUpperCase()+e.slice(1)}function Wpe(e){var i,a;const t=[...e.inputs||[]],n=new Set(t.map(c=>c.id)),r=new Set((e.sheets||[]).filter(c=>c.kind==="document").map(c=>c.id));let s=!1;for(const c of e.sheets||[])if(!(c.kind!=="document"||!((a=(i=c.document)==null?void 0:i.inputs)!=null&&a.length)))for(const u of c.document.inputs)n.has(u.id)||(t.push(qpe(u,c.id)),n.add(u.id),s=!0);const o=t.map(c=>{if(c.kind==="filter"&&R$(c,r)&&c.filter.variableName!==c.variableName)return s=!0,{...c,filter:{...c.filter,variableName:c.variableName}};if(c.kind!=="control"||!R$(c,r))return c;const u=Ju(c.control.id||c.variableName,t.filter(d=>d.id!==c.id));return c.variableName===u&&c.control.id===u?c:(s=!0,{...c,variableName:u,control:{...c.control,id:u}})});return s?{...e,inputs:o}:e}function qpe(e,t){const n={id:e.id,label:e.label,variableName:e.variableName,description:e.description,requiredAtExecution:e.requiredAtExecution,scope:{kind:"sheets",sheetIds:[t]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},exports:e.exports,compatibility:{source:"documentInput",sheetId:t,inputId:e.id}};return e.kind==="filter"?{...n,kind:"filter",filter:e.filter}:{...n,kind:"control",control:e.control}}function R$(e,t){var n;switch(e.scope.kind){case"allSheets":return!((n=e.scope.sheetKinds)!=null&&n.length)||e.scope.sheetKinds.includes("document");case"sheets":return e.scope.sheetIds.some(r=>t.has(r));case"documentSections":return t.has(e.scope.sheetId);default:return!1}}function Ype(e){return e==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function Gpe(e,t){const n=Ype(e);return n==="dark"?xl({...t==null?void 0:t.default},{...t==null?void 0:t.dark}):t==null?void 0:t.default}function F$(e,t,n){return Xhe(Gpe(e,t),n)}function Kpe(e){return Mo.stableSerialize({hasExplicitDefaultControlValues:e!==void 0,values:e??null})}function Zpe(e,t){const{controlContractOverrides:n,cardId:r}=t;if(!n||(n.controlDefinitions!==void 0&&(e.controls=n.controlDefinitions),typeof r!="string"||r.trim().length===0))return e;const s=m.findCardById(e,r);return s&&(n.cardControlDefinitions!==void 0&&(s.controls=n.cardControlDefinitions),n.controlBindings!==void 0&&(s.controlBindings=n.controlBindings)),e}function Xpe(e,t){const n=v.useRef({key:t,value:e});return n.current.key!==t&&(n.current={key:t,value:e}),n.current.value}function Qpe({customStyle:e,currentTheme:t,onSave:n,onEvent:r,defaultFilterValues:s,defaultControlValues:o,controlContractOverrides:i,dashboardInputExecutionSnapshot:a,type:c,cardId:u,selectedSheetId:d,onFilterValuesChange:f}){var ve,xe,ke,se,be;const{authToken:h,tokenProps:p}=Ct();Ope();const g=m.useDashboardStore(Ce=>Ce.selectedLensId),b=m.useDashboardStore(Ce=>Ce.relaodToken),{data:x,isLoading:y,isFetching:S,isError:w,refetch:C,dashboardIdToFetch:N}=Q0(),k=((xe=(ve=p==null?void 0:p.params)==null?void 0:ve.calendarContext)==null?void 0:xe.tz)||((ke=p==null?void 0:p.params)==null?void 0:ke.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,_=(se=x==null?void 0:x.dashboard)==null?void 0:se.id,{getDefaultSheetId:E,clearDefaultSheetId:D}=YW(_),[j,I]=v.useState(s||[]),T=v.useRef(null),F=v.useRef(null),P=Kpe(o),R=R2(i),B=R2(i,{includePresentation:!0}),z=v.useRef(o);z.current=o;const U=v.useRef(P);U.current=P;const Y=Xpe(i,B),O=v.useRef(null),K=v.useRef(!1),q=v.useRef({dashboardId:null,defaultControlValuesKey:P,controlContractOverridesKey:R}),{setTheme:M}=nF(),{compiledAppearance:G}=m.useAppearance(),L=m.useDashboardStore(Ce=>Ce.dashboard.globalStyle),$=v.useMemo(()=>x!=null&&x.dashboard?Wpe(Zpe(Zo(x.dashboard),{controlContractOverrides:Y,cardId:u})):void 0,[x==null?void 0:x.dashboard,Y,c,u]),{setDashboardWithFilterValues:V,hydrateRuntimeControlValues:H,setStyle:A,setOnSaveFunction:W,setLenses:X,setSelectedLensId:Z,setInlineFilterValuesMap:J}=m.useDashboardActions();m.useDashboardStore(Ce=>Ce.actions.setCustomCards);const re=m.useDashboardStore(Ce=>Ce.filterValues),fe=m.useDashboardStore(Ce=>Ce.actions.setThemeStyle),de=m.useDashboardStore(Ce=>Ce.actions.setDashboardTheme),Se=m.useDashboardStore(Ce=>Ce.actions.setOnEvent);v.useEffect(()=>{const Ce=F.current;Ce&&Ce!==N&&m.storeEvents.emit("dashboard:unload"),F.current=N},[N]),v.useEffect(()=>{b&&C()},[C,b]),v.useEffect(()=>{var ee;const Ce=((ee=x==null?void 0:x.dashboard)==null?void 0:ee.id)||null,ge=T.current;Ce&&Ce!==ge&&m.storeEvents.emit("dashboard:load"),T.current=Ce},[(be=x==null?void 0:x.dashboard)==null?void 0:be.id]),v.useEffect(()=>{de(G.mode)},[G.mode,de]),v.useEffect(()=>{t&&M(t)},[t,M]);const ue=v.useCallback(()=>{const Ce=Zo(m.DEFAULT_STYLE),ge=xl(Ce,L);if(e){const ee=xl(ge,e),te=F$(G.mode,ee,G);fe(te),A(ee)}else{const ee=F$(G.mode,ge,G);fe(ee),A(m.DEFAULT_STYLE)}},[G,e,L,fe,A]);return v.useEffect(()=>{x&&x.dashboard&&ue()},[G.mode,e,L,ue,x]),v.useEffect(()=>{var Ve,$e,Ae,Re;function Ce(He,Ge){const ht=He.filters||[],lt=[];for(const st of Ge){const Fe=ht.find(Ke=>Ke.id===st.filterId);Fe&&lt.push({filterId:st.filterId,name:Fe.column,operation:st.operation,valueType:m.getFilterValueType(Fe),values:st.values,dataType:Fe.dataType,fieldMeta:Fe.fieldMeta,semanticContext:Fe.semanticContext})}return lt}if(!x||!$)return;const ge=$,{filterValues:ee,defaultLensId:te,lenses:ce}=x;function le(){if(ee&&(ee==null?void 0:ee.length)>0)return ee;const Ge=[...m.buildFilterValuesFromDefaults(ge.filters,k)];if(ge.defaultFilterValues&&ge.defaultFilterValues.length>0)for(const st of ge.defaultFilterValues){const Fe=Ge.findIndex(Ke=>Ke.filterId===st.filterId);Fe>=0?Ge[Fe]=st:Ge.push(st)}const ht=Ce(ge,j||[]),lt=[...Ge];for(const st of ht){const Fe=lt.findIndex(Ke=>Ke.filterId===st.filterId);Fe>=0?lt[Fe]=st:lt.push(st)}return lt}const Ee=m.useDashboardStore.getState(),ye=O.current===$.id&&((Ve=Ee.dashboard)==null?void 0:Ve.id)===$.id,ne=le(),je=ye?m.resolveSameDashboardFilterValues({previousFilters:($e=Ee.dashboard)==null?void 0:$e.filters,nextFilters:ge.filters,currentFilterValues:Ee.filterValues,defaultFilterValues:ne}):ne,Ue=m.computeInlineFilterDefaults(ge,k),Be=ye&&q.current.controlContractOverridesKey===R?m.flattenRuntimeControlValues({dashboardValues:Ee.controlValues,cardValuesMap:Ee.cardControlValuesMap}):z.current,rt=Ee.selectedSheetId;let Xe=E(),et=rt;et&&((Ae=$==null?void 0:$.sheets)!=null&&Ae.some(Ge=>Ge.id===et)||(et=null)),Xe&&((Re=$==null?void 0:$.sheets)!=null&&Re.some(Ge=>Ge.id===Xe)||(D(),Xe=null));const tt=Vpe({selectedSheetId:d,preservedSelectedSheetId:et,defaultSheetId:Xe,sheets:$==null?void 0:$.sheets}),me=!!a,Ye=!me&&K.current;V(ge,je||[],Be,{selectedSheetId:tt,...x!=null&&x.semanticExecutionPayload?{semanticExecutionPayload:x.semanticExecutionPayload}:{},...a?{dashboardInputValues:a.dashboardInputValues,dashboardInputValuesAreAuthoritative:!0}:Ye?{dashboardInputValues:{},dashboardInputValuesAreAuthoritative:!1}:{}}),K.current=me,O.current=$.id,q.current.dashboardId!==$.id&&(q.current={dashboardId:$.id,defaultControlValuesKey:U.current,controlContractOverridesKey:R}),J(Ue),ce&&X(ce),te&&Z(te)},[x,k,g,X,V,Z,J,j,d,E,D,R,a,$]),v.useEffect(()=>{if(!($!=null&&$.id))return;const Ce=q.current;if(Ce.dashboardId!==$.id){q.current={dashboardId:$.id,defaultControlValuesKey:P,controlContractOverridesKey:R};return}Ce.defaultControlValuesKey===P&&Ce.controlContractOverridesKey===R||(H($,z.current),q.current={dashboardId:$.id,defaultControlValuesKey:P,controlContractOverridesKey:R})},[$,P,R,H]),v.useEffect(()=>{f&&re&&f(re)},[re,f]),v.useEffect(()=>{n&&W(n),r&&Se(r)},[n,W,r,Se]),{isFetching:S,isLoading:y,isError:w}}function uo({className:e,...t}){return l.jsx("div",{className:m.cn("animate-pulse rounded-md bg-muted",e),...t})}const Tm=Q.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:m.cn("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Tm.displayName="Card";const vk=Q.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:m.cn("flex flex-col space-y-1.5 p-6",e),...t}));vk.displayName="CardHeader";const mg=Q.forwardRef(({className:e,...t},n)=>l.jsx("h3",{ref:n,className:m.cn("text-2xl font-semibold leading-none tracking-tight",e),...t}));mg.displayName="CardTitle";const Jpe=Q.forwardRef(({className:e,...t},n)=>l.jsx("p",{ref:n,className:m.cn("text-sm text-muted-foreground",e),...t}));Jpe.displayName="CardDescription";const wk=Q.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:m.cn("px-6 pt-0",e),...t}));wk.displayName="CardContent";const XW=Q.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:m.cn("flex items-center p-6 pt-0",e),...t}));XW.displayName="CardFooter";/**
@@ -1422,4 +1422,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1422
1422
 
1423
1423
  `)},flush(e){e.enqueue(`data: [DONE]
1424
1424
 
1425
- `)}})}});var Axt=_bt(()=>sfe(ea([Or({type:yn("text-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("error"),errorText:Ut()}),Or({type:yn("tool-input-start"),toolCallId:Ut(),toolName:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-delta"),toolCallId:Ut(),inputTextDelta:Ut()}),Or({type:yn("tool-input-available"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-error"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional(),errorText:Ut()}),Or({type:yn("tool-output-available"),toolCallId:Ut(),output:Qa(),providerExecuted:Uo().optional(),dynamic:Uo().optional(),preliminary:Uo().optional()}),Or({type:yn("tool-output-error"),toolCallId:Ut(),errorText:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("reasoning-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("source-url"),sourceId:Ut(),url:Ut(),title:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("source-document"),sourceId:Ut(),mediaType:Ut(),title:Ut(),filename:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("file"),url:Ut(),mediaType:Ut(),providerMetadata:Jr.optional()}),Or({type:Jde(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Ut().optional(),data:Qa(),transient:Uo().optional()}),Or({type:yn("start-step")}),Or({type:yn("finish-step")}),Or({type:yn("start"),messageId:Ut().optional(),messageMetadata:Qa().optional()}),Or({type:yn("finish"),finishReason:Zde(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Qa().optional()}),Or({type:yn("abort")}),Or({type:yn("message-metadata"),messageMetadata:Qa()})])));function Rxt(e){return e.type.startsWith("data-")}function ffe(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=ffe(o,s):n[r]=s}return n}function Fxt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function hfe(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await bk({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await bk({text:Fxt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function aC(e){return e.type.startsWith("tool-")}function Pxt(e){return e.type==="dynamic-tool"}function qR(e){return aC(e)||Pxt(e)}function XU(e){return e.type.split("-").slice(1).join("-")}function Oxt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Lxt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,p,g;function b(C){const k=u.message.parts.filter(aC).find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function x(C){const k=u.message.parts.filter(_=>_.type==="dynamic-tool").find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function y(C){var N;const k=u.message.parts.find(D=>aC(D)&&D.toolCallId===C.toolCallId),_=C,E=k;k!=null?(k.state=C.state,E.input=_.input,E.output=_.output,E.errorText=_.errorText,E.rawInput=_.rawInput,E.preliminary=_.preliminary,E.providerExecuted=(N=_.providerExecuted)!=null?N:k.providerExecuted,_.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=_.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null?{callProviderMetadata:_.providerMetadata}:{}})}function S(C){var N,k;const _=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===C.toolCallId),E=C,D=_;_!=null?(_.state=C.state,D.toolName=C.toolName,D.input=E.input,D.output=E.output,D.errorText=E.errorText,D.rawInput=(N=E.rawInput)!=null?N:D.rawInput,D.preliminary=E.preliminary,D.providerExecuted=(k=E.providerExecuted)!=null?k:_.providerExecuted,E.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?ffe(u.message.metadata,C):C;t!=null&&await qU({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(g=a.providerMetadata)!=null?g:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(aC);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await hfe(C.text);C.dynamic?S({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await w(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Rxt(a)){(n==null?void 0:n[a.type])!=null&&await qU({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(k=>C.type===k.type&&C.id===k.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function $xt({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}xw({prefix:"aitxt",size:24});xw({prefix:"aiobj",size:24});var zxt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};xw({prefix:"aiobj",size:24});var Bxt={};Cxt(Bxt,{object:()=>Hxt,text:()=>Vxt});var Vxt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Hxt=({schema:e})=>{const t=wxt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await hfe(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await bk({text:n});if(!s.success)throw new KU({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await a$({value:s.value,schema:t});if(!o.success)throw new KU({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Uxt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Wxt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Ip(this.body),c=await Ip(this.headers),u=await Ip(this.credentials),d={...cf(c),...cf(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,p=(f==null?void 0:f.headers)!==void 0?cf(f.headers):d,g=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},b=(s=f==null?void 0:f.credentials)!=null?s:u,y=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:UU({"Content-Type":"application/json",...p},`ai-sdk/${ZU}`,HU()),body:JSON.stringify(g),credentials:b,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Ip(this.body),a=await Ip(this.headers),c=await Ip(this.credentials),u={...cf(a),...cf(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?cf(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:c,b=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:UU(h,`ai-sdk/${ZU}`,HU()),credentials:p});if(b.status===204)return null;if(!b.ok)throw new Error((o=await b.text())!=null?o:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},c$=class extends Wxt{constructor(e={}){super(e)}processResponseStream(e){return Dbt({stream:e,schema:Axt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},qxt=class{constructor({generateId:e=ybt,id:t=e(),transport:n=new c$,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new zxt,this.sendMessage=async(f,h)=>{var p,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await Uxt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const S=this.state.messages.findIndex(w=>w.id===f.messageId);if(S===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[S].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,S+1),this.state.replaceMessage(S,{...y,id:f.messageId,role:(g=y.role)!=null?g:"user",metadata:f.metadata})}else this.state.pushMessage({...y,id:(b=y.id)!=null?b:this.generateId(),role:(x=y.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:p,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const S=this.state.messages,w=S[S.length-1];this.state.replaceMessage(S.length-1,{...w,parts:w.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:Oxt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}g=x}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const b=x=>this.jobExecutor.run(()=>x({state:p.state,write:()=>{var y;this.setStatus({status:"streaming"}),p.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $xt({stream:Lxt({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:b,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function pfe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(qR).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Yxt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Gxt=Yxt;const Kxt=m.getDefaultExportFromCjs(Gxt);var mfe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},jr=(e,t,n)=>(mfe(e,t,"read from private field"),n?n.call(e):t.get(e)),qa=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},gu=(e,t,n,r)=>(mfe(e,t,"write to private field"),t.set(e,n),n);function Zxt(e,t){return t!=null?Kxt(e,t):e}var Ai,lC,cC,Hx,Ux,Wx,Up,YR,GR,Xxt=class{constructor(e=[]){qa(this,Ai,void 0),qa(this,lC,"ready"),qa(this,cC,void 0),qa(this,Hx,new Set),qa(this,Ux,new Set),qa(this,Wx,new Set),this.pushMessage=t=>{gu(this,Ai,jr(this,Ai).concat(t)),jr(this,Up).call(this)},this.popMessage=()=>{gu(this,Ai,jr(this,Ai).slice(0,-1)),jr(this,Up).call(this)},this.replaceMessage=(t,n)=>{gu(this,Ai,[...jr(this,Ai).slice(0,t),this.snapshot(n),...jr(this,Ai).slice(t+1)]),jr(this,Up).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Zxt(t,n):t;return jr(this,Hx).add(r),()=>{jr(this,Hx).delete(r)}},this["~registerStatusCallback"]=t=>(jr(this,Ux).add(t),()=>{jr(this,Ux).delete(t)}),this["~registerErrorCallback"]=t=>(jr(this,Wx).add(t),()=>{jr(this,Wx).delete(t)}),qa(this,Up,()=>{jr(this,Hx).forEach(t=>t())}),qa(this,YR,()=>{jr(this,Ux).forEach(t=>t())}),qa(this,GR,()=>{jr(this,Wx).forEach(t=>t())}),gu(this,Ai,e)}get status(){return jr(this,lC)}set status(e){gu(this,lC,e),jr(this,YR).call(this)}get error(){return jr(this,cC)}set error(e){gu(this,cC,e),jr(this,GR).call(this)}get messages(){return jr(this,Ai)}set messages(e){gu(this,Ai,[...e]),jr(this,Up).call(this)}};Ai=new WeakMap;lC=new WeakMap;cC=new WeakMap;Hx=new WeakMap;Ux=new WeakMap;Wx=new WeakMap;Up=new WeakMap;YR=new WeakMap;GR=new WeakMap;var Wp,QU=class extends qxt{constructor({messages:e,...t}){const n=new Xxt(e);super({...t,state:n}),qa(this,Wp,void 0),this["~registerMessagesCallback"]=(r,s)=>jr(this,Wp)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>jr(this,Wp)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>jr(this,Wp)["~registerErrorCallback"](r),gu(this,Wp,n)}};Wp=new WeakMap;function gfe({experimental_throttle:e,resume:t=!1,...n}={}){const r=v.useRef("chat"in n?n.chat:new QU(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new QU(n));const o="id"in n?n.id:null,i=v.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=v.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=v.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=v.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=v.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return v.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Qxt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Jxt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eyt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tyt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function bfe(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:tyt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function xfe(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function uE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function yfe(e,t,n){const r=uE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>_j(o)).filter(o=>o!==void 0).map(s)}function vfe(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function nyt(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function nm(e){return(e||[]).map(nyt)}function wfe(e){return nm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function u$(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function ryt(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...u$(s)}})}function syt(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...u$(t)}))}function Sfe(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function l2(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>Sfe(s,`${t}:${r}:${o}`)))}function oyt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function iyt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function ayt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(iyt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...u$(r)})),n=e.filter(oyt).map((r,s)=>Sfe(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function lyt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=m.getClickFiltersForCardFromStates(e.id,t),s=t[m.DRILL_CONTEXT_CARD_ID],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>l2(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>l2(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>l2(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Cfe(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>Cfe(t)).filter(Boolean)}:null}function Nfe(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==tF.trim()}function cyt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":Nfe(e)?"custom-python":"config"}function kfe({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=uE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=fv({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=dv({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=ayt(n==null?void 0:n.filters),p=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:p?h.dashboardFilterValues:ryt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:syt(a==null?void 0:a[t.id]),interactionFilterValues:p?h.interactionFilterValues:lyt({card:t,interactionStates:i,currentDashboardId:r.id})}}function uyt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=kfe({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:nm(c.metricColumns),dimensions:wfe(c),selectedEntities:vfe(t)}}function dyt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function JU({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=uE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:Ly(e.filters,n,r)}}function fyt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=uE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=yfe(e,t.selectedSheetId,s),c=Nd(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>uyt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:dyt({activeFilters:t.activeFilters})}}function hyt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var w,C;const c=yfe(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:p,inlineFilterValues:g,interactionFilterValues:b}=kfe({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:x,targetValue:y}=_Ye(h,d.type),S=cyt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:S,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...Nfe(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:vfe(d),metrics:nm(h.metricColumns),dimensions:wfe(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Cfe(h.filters),effectiveDashboardFilters:p,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:nm(h.groupByColumns),pivotBy:nm(h.pivotByColumns),sortBy:nm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...S==="custom-sql"?["This card runs custom SQL."]:S==="custom-python"?["This card runs custom Python."]:[]]}}function qp(){return crypto.randomUUID()}function _fe(){return crypto.randomUUID()}function KR(e){return typeof(e==null?void 0:e.then)=="function"}async function pyt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Xr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>m.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=Yie(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function myt({dynamicVisualMode:e="auto"}={}){var R;const{compiledAppearance:t}=m.useAppearance(),n=v.useMemo(()=>PL(t),[t]),r=v.useRef(n);v.useEffect(()=>{r.current=n},[n]);const{authToken:s,tokenProps:o}=Ct(),i=ns(),a=m.useDashboardStore(B=>B.dashboard.aiScopeTables),c=(R=Q0().data)==null?void 0:R.assistantProfileId,u=v.useRef(null),d=v.useRef(qp()),f=v.useRef(!1),h=v.useRef(!1),p=v.useRef(e);p.current=e;function g(){const B=m.useAIInteractionStore.getState(),z=m.useDashboardStore.getState(),U=Jie({overrides:B.dashboardEntitySelectionOverrides,dashboardId:z.dashboard.id,draftScopeKey:z.dashboardAssistantDraftScopeKey});return m.appendQualifiedEntityNameToAIContext(BKe({currentAIContext:B.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:z.dashboard.aiContext,derivedSelectedSheetEntities:Qie(z.dashboard,z.selectedSheetId)}))}function b(){const B=m.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:JU({dashboard:B.dashboard,selectedSheetId:B.selectedSheetId,activeFilters:B.filterValues})}}const{sendMessage:x,messages:y,setMessages:S,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:E}=gfe({transport:new c$({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${s==null?void 0:s.accessToken}`}),body:()=>{const B=m.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:z,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:c,conversationId:d.current,assistantRequestId:_fe(),aiContext:z,dashboardViewState:U,dynamicVisualMode:p.current,dynamicVisualTheme:r.current,reasoningEffort:B.reasoningEffort,showReasoning:B.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:B,body:z})=>({body:{...z,messages:m.cleanupIncompleteMessages(B)}})}),onToolCall:T,sendAutomaticallyWhen:pfe,onFinish({message:B,isAbort:z,isDisconnect:U,isError:Y}){var O;h.current=!1,B!=null&&B.id&&((O=u.current)!=null&&O.aiContext)&&m.useAIInteractionStore.getState().actions.setAssistantMessageContext(B.id,u.current.aiContext),console.log(z?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":Y?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))},onError(B){var z;if(h.current=!1,B.name==="AbortError"||(z=B.message)!=null&&z.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]));return}console.error("[Dashboard Assistant] Stream error:",B),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))}}),D=v.useCallback((...B)=>{h.current=!0;try{const z=x(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[x]),j=v.useCallback((...B)=>{h.current=!0;try{const z=w(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[w]),I=B=>{let z=!1;S(U=>{const Y=typeof B=="function"?B(U):B;if(Y.length===0){if(h.current)return f.current=!0,z=!0,U;f.current=!1,d.current=qp()}return Y}),z&&_()};async function T({toolCall:B}){var M,G;if(B.toolName==="getCurrentTableScope"){N({tool:B.toolName,toolCallId:B.toolCallId,output:{tables:bfe(a||[])}});return}const z=m.useDashboardStore.getState().dashboard,U=m.useDashboardStore.getState().inlineFilterValuesMap,Y=m.useInteractionStore.getState(),O=Y.interactionStates,K=await pyt({replacedCards:Y.replacedCards,apiServiceUrl:o.apiServiceUrl,accessToken:(s==null?void 0:s.accessToken)||"",queryClient:i}),q=JU({dashboard:z,selectedSheetId:m.useDashboardStore.getState().selectedSheetId,activeFilters:m.useDashboardStore.getState().filterValues});if(B.toolName==="getDashboardSynopsis"){N({tool:B.toolName,toolCallId:B.toolCallId,output:fyt({dashboard:z,viewState:q,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})});return}if(B.toolName==="getCardContext"){const L=((M=B.input)==null?void 0:M.cardId)||((G=B.args)==null?void 0:G.cardId)||"";N({tool:B.toolName,toolCallId:B.toolCallId,output:hyt({dashboard:z,viewState:q,cardId:L,runtimeFilterValues:m.useDashboardStore.getState().filterValues,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),P=xfe(k);return{sendMessage:D,regenerate:j,isLoading:F,messages:y,setMessages:I,status:C,stop:_,errorMessage:P,clearError:E}}function jfe(){var u;const{authToken:e,tokenProps:t}=Ct(),n=(u=Q0().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=On({queryKey:["assistant-profile",n],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Efe({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(pq,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function gyt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=v.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ic-n;if(c.length>u){ut.error(`You can only attach ${ic} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=que(c);if(f.forEach(({file:h,error:p})=>{ut.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>Z3(p)));e(h)}catch(h){console.error("Failed to process files:",h),ut.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ic}),l.jsx(m.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ic,title:n>=ic?`Maximum ${ic} files allowed`:"Attach files",children:l.jsx(Nq,{className:"h-4 w-4 text-muted-foreground"})})]})}function byt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=v.useState(!1),a=v.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=v.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,g=f.clientY;(p<h.left||p>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=v.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=v.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=ic-r;if(h.length>p){ut.error(`You can only attach ${ic} files per message. You have ${p} slot(s) remaining.`);return}const{valid:g,errors:b}=que(h);if(b.forEach(({file:x,error:y})=>{ut.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>Z3(y)));t(x),ut.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),ut.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:m.cn("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-control border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(m.Upload,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ic-r," slot(s) available"]})]})})]})}function xyt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function yyt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!xyt(e,t,n):r}function Dfe(e){const{tokenProps:t}=Ct(),n=m.useDashboardStore(c=>c.authToken)||e;m.useEditorStore(c=>c.selectedConnectionId),m.useEditorStore(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=On({queryKey:["semantic-domains"],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function vyt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:s}){const{semanticDomains:o,isSemanticDomainsLoading:i}=Dfe(),a=v.useMemo(()=>Syt(o,e),[o,e]),c=v.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&c.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(c.length===0)return null;const u=!!n;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Semantic Domains"}),c.map(d=>l.jsx(wyt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:s},d.id))]})}function wyt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){const[o,i]=v.useState(!1),a=o||t.length>0||!!n,{datasets:c,isPending:u}=nNe(a?e.id:void 0),d=v.useMemo(()=>{if(!t)return c;const x=t.trim().toLowerCase();return c.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[c,t]),f=t.length>0&&d.length>0,h=o||f||!!n,p=c.length,g=v.useMemo(()=>d.filter(x=>r.some(y=>zr(y,c2(x)))).length,[d,r]),b=x=>{const y=c2(x),S=r.some(w=>zr(w,y));s(S?r.filter(w=>!zr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"flex w-full items-center gap-1.5 rounded-[4px] px-3 py-1.5 text-left transition-colors hover:bg-muted/50",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),p>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",p," dataset",p===1?"":"s"," · curated"]}),l.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&l.jsx("ul",{className:"space-y-px pb-1",children:u&&c.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=c2(x),S=r.some(w=>zr(w,y));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:S,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),l.jsx(ei,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:x.type==="virtual"?"virtual":"dataset"})]}),x.description&&l.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ife({label:e}){return l.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function Syt(e,t){if(!t||t.mode==="all")return e;const n=new Set(t.domainIds??[]);return t.mode==="include"?e.filter(r=>n.has(r.id)):t.mode==="exclude"?e.filter(r=>!n.has(r.id)):[]}function c2(e){return{id:e.id,datasetType:e.type,name:e.name||e.table,label:e.label,domainId:e.domainId,description:e.description,database:e.database,schema:e.schema,table:e.table,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function Cyt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:s,isConnectionsLoading:o}=Xc(),i=v.useMemo(()=>t?s.filter(c=>c.id===t):s,[s,t]);if(o&&i.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading connections…"});if(i.length===0)return null;const a=!!t;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Direct Sources"}),i.map(c=>l.jsx(Nyt,{connection:c,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},c.id))]})}function Nyt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){var g;const[o,i]=v.useState(!1),a=o||t.length>0||!!n,c=((g=e.capabilities)==null?void 0:g.path)??[],u=c.includes("database"),d=c.includes("schema"),f=e.type==="upload",h=e.type==="url",p=v.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return l.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>i(b=>!b),className:"flex w-full items-center gap-2 px-4 py-1.5 text-left transition-colors hover:bg-muted/40",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),l.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),l.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:p>0?p:""})]}),a&&l.jsxs(l.Fragment,{children:[f?l.jsx(kyt,{connection:e,selectedEntities:r,onSelectionChange:s}):h?l.jsx(_yt,{connection:e,selectedEntities:r,onSelectionChange:s}):u?l.jsx(jyt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:s}):d?l.jsx(Tfe,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:s}),!f&&!h&&l.jsx(Eyt,{connection:e,search:t,selectedEntities:r,onSelectionChange:s})]})]})}function kyt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,s=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),o=a=>{if(!(a!=null&&a.length))return;const c=Array.from(a).map(u=>({id:`file-${Date.now()}-${Math.random()}`,name:u.name,type:"upload",connectionId:e.id,connectionType:e.type,label:u.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:u.name,file:u}));n([...t,...c])},i=a=>{n(t.filter(c=>!("id"in c&&c.id===a&&c.connectionId===e.id&&(c.type==="upload"||c.type==="file"))))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[l.jsx(m.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),l.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>o(a.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(m.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2 h-7 text-[12px]",onClick:()=>{var a;return(a=document.getElementById(r))==null?void 0:a.click()},children:"Select files"})]}),s.length>0&&l.jsx("ul",{className:"space-y-1",children:s.map(a=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(vi,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),l.jsx("button",{type:"button","aria-label":`Remove ${a.originalName||a.name}`,onClick:()=>i(a.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},a.id))})]})}function _yt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,s]=v.useState(""),[o,i]=v.useState(""),[a,c]=v.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),p=o.trim();if(!h||!p)return;const g={id:`url-${Date.now()}-${Math.random()}`,name:h,type:"url",connectionId:e.id,connectionType:e.type,label:h,description:`URL source of type ${a}`,originalName:h,url:p,sourceType:a};n([...t,g]),s(""),i(""),c("api")},f=h=>{n(t.filter(p=>!("id"in p&&p.id===h&&p.connectionId===e.id&&p.type==="url")))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[l.jsx(m.Input,{value:r,onChange:h=>s(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),l.jsx(m.Input,{value:o,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("select",{value:a,onChange:h=>c(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[l.jsx("option",{value:"api",children:"API endpoint"}),l.jsx("option",{value:"csv",children:"CSV file"}),l.jsx("option",{value:"json",children:"JSON file"})]}),l.jsxs(m.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!o.trim(),onClick:d,children:[l.jsx(dr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&l.jsx("ul",{className:"space-y-1",children:u.map(h=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(gg,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"truncate text-[12px]",children:h.name}),l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),l.jsx("button",{type:"button","aria-label":`Remove ${h.name}`,onClick:()=>f(h.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},h.id))})]})}function jyt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/databases",{connection_id:e.id},["databases",e.id]);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=o.data)==null?void 0:a.databases)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?l.jsx(Tfe,{connection:e,databaseName:c.database_name,search:n,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:c.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:s}))},c.database_name))})}function Tfe({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=o.data)==null?void 0:a.schemas)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&l.jsx(d$,{connection:e,databaseName:t,schemaName:c.schema_name,search:n,selectedEntities:r,onSelectionChange:s})},c.schema_name))})}function d$({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:s,onSelectionChange:o}){const i=dE("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=v.useMemo(()=>{var f;const u=((f=i.data)==null?void 0:f.tables)??[];if(!r)return u;const d=r.trim().toLowerCase();return u.filter(h=>h.table_name.toLowerCase().includes(d))},[i.data,r]);if(i.isLoading)return l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const c=(u,d)=>{const f={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u,dbObjectType:d==null?void 0:d.toLowerCase()},h=s.some(p=>zr(p,f));o(h?s.filter(p=>!zr(p,f)):[...s,f])};return l.jsx("ul",{children:a.map(u=>{var h;const d={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u.table_name,dbObjectType:(h=u.table_type)==null?void 0:h.toLowerCase()},f=s.some(p=>zr(p,d));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:f,onCheckedChange:()=>c(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),l.jsx(m.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:u.table_type??"table"})]})]})},u.table_name)})})}function Eyt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const s=dE("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),o=v.useMemo(()=>{var u;const a=((u=s.data)==null?void 0:u.datamodels)??[];if(!t)return a;const c=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(c))},[s.data,t]);if(s.isLoading||o.length===0)return null;const i=a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));r(u?n.filter(d=>!zr(d,c)):[...n,c])};return l.jsxs("div",{children:[l.jsx("div",{className:"px-8 pb-1 pt-2",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),l.jsx("ul",{children:o.map(a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),l.jsx(sme,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&l.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Mfe({label:e,indentLevel:t,search:n,renderChildren:r}){const[s,o]=v.useState(!1),i=s||n.length>0,a=t===1?"pl-8":"pl-10";return l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:m.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[l.jsx(Mr,{className:m.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function dE(e,t,n,r=!0){const{tokenProps:s}=Ct(),o=m.useDashboardStore(a=>a.authToken),i=v.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return On({queryKey:n,queryFn:()=>m.getRequest(`${s.apiServiceUrl}${e}`,(o==null?void 0:o.accessToken)||"",i),enabled:r&&!!(o!=null&&o.accessToken)&&Object.values(i).every(a=>a.length>0)})}function eW(e){return e.type==="dataset"&&e.label||e.name}function Dyt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-input bg-muted/50 py-0.5 pl-1.5 pr-0.5 text-[11px] text-foreground/80",children:[l.jsx("span",{className:"max-w-[180px] truncate",children:eW(n)}),l.jsx("button",{type:"button",onClick:s=>{s.stopPropagation(),t(n)},"aria-label":`Remove ${eW(n)}`,className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function tW(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function u2(e){if(e!=null&&e.length)return e.every(t=>t.type==="dataset")?"semanticDomain":e.every(t=>t.type==="url")?"url":e.every(t=>t.type==="upload"||t.type==="file")?"upload":"database"}function f$({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var ue,ve;const{tokenProps:a}=Ct(),c=a.config,u=a.semanticDomainAccess||bhe.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=v.useState([]),[h,p]=v.useState(void 0),[g,b]=v.useState(""),[x,y]=v.useState("all"),[S,w]=v.useState(void 0),C=v.useRef(!1),{updateDataSource:N}=m.useEditorActions(),k=m.useDashboardStore(xe=>xe.isVisualEditing),_=m.useDashboardStore(xe=>xe.dashboard.aiContext),{setAiContext:E}=m.useDashboardActions(),D=u.mode,j=(c==null?void 0:c.showDirectSource)!==!1,I=D==="include"||D==="exclude"||!j,T=D!=="all",F=j&&!I,P=I?"semanticDomain":n.mode,R=r==="dataSource"&&!j,B=D==="include"&&(((ue=u.domainIds)==null?void 0:ue.length)||0)===1?(ve=u.domainIds)==null?void 0:ve[0]:void 0,z=v.useCallback(xe=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:xe,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...xe!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=v.useCallback(xe=>{N({...n,...xe})},[n,N]),Y=v.useCallback(xe=>{if(r==="aiContext"){"semanticDomainId"in xe&&p(xe.semanticDomainId);return}U(xe)},[r,U]),O=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},v.useEffect(()=>{if(r==="aiContext"&&!e)return;if(I&&n.mode!=="semanticDomain"&&r==="dataSource"){z("semanticDomain");return}if(!T||P!=="semanticDomain")return;const xe=O,ke=u.domainIds??[],se=r==="aiContext"?d:n.selectedEntities,be=((se==null?void 0:se.length)??0)>0,Ce=((d==null?void 0:d.length)??0)>0;yyt({mode:D,currentDomainId:xe,scopedDomainIds:ke,hasSelectedEntities:be})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):p(void 0),Ce&&f([]))},[I,T,P,n.mode,O,n.selectedEntities,r,h,d,e,u.domainIds,D,j,U,z]),v.useEffect(()=>{B&&!O&&Y({semanticDomainId:B})},[B,O,Y]),v.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(I?"semantic":"all");return}if(C.current)return;f([...s||[]]);const xe=r==="aiContext"?tW(s):void 0;p(n.semanticDomainId||xe),w(u2(s))},[e,r,s,n.semanticDomainId,I]);const K=xe=>{C.current=!0,f(d.filter(ke=>!zr(ke,xe)))},q=v.useCallback((xe,ke)=>{C.current=!0,f(xe),w(ke??u2(xe))},[]),M=()=>{var ke,se;if(r==="aiContext"){if(k&&N(n),i){const be={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};E(be)}o==null||o(d),t(!1);return}const xe=u2(d)??S??P;if(xe==="semanticDomain"){const be=tW(d)||h||n.semanticDomainId,Ce=((ke=d==null?void 0:d[0])==null?void 0:ke.connectionId)||n.connectionId,ge=((se=d==null?void 0:d[0])==null?void 0:se.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:be,connectionId:Ce,connectionType:ge,selectedEntities:d})}else if(xe==="upload"||xe==="url"){const be=d==null?void 0:d[0];N({...n,mode:xe,semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}else{const be=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Dfe(),{connections:L}=Xc(),$=xe=>{y(xe),xe==="semantic"||xe.startsWith("domain:")?n.mode!=="semanticDomain"&&z("semanticDomain"):(xe==="direct"||xe.startsWith("conn:"))&&n.mode==="semanticDomain"&&z("database")},V=x.startsWith("domain:"),H=x.startsWith("conn:"),A=V?x.slice(7):void 0,W=H?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||V,Z=j&&!I&&(x==="all"||x==="direct"||H),J=((s==null?void 0:s.length)??0)>0,re=d.length===0&&!J,fe=d.length===0&&J?"Clear":"Add",de=r==="aiContext"?"Data context":R?"Select dataset":"Add data",Se=r==="aiContext"?"Set the overall data scope for the dashboard":R?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{showCloseButton:!1,className:"flex h-[560px] w-[620px] max-w-[620px] flex-col gap-0 overflow-hidden rounded-[6px] border border-border bg-popover p-0",children:[l.jsx(m.VisuallyHidden,{children:l.jsx(go,{children:de})}),l.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:de}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:Se})]}),l.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Close",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]}),l.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:g,onChange:xe=>b(xe.target.value),placeholder:"Search datasets, tables, views, models",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"}),g&&l.jsx("button",{type:"button",onClick:()=>b(""),"aria-label":"Clear search",className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),F&&l.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:l.jsxs("div",{className:"flex w-max items-center gap-1",children:[l.jsx(ux,{label:"All",active:x==="all",onClick:()=>$("all")}),(G.length>0||L.length>0)&&l.jsxs(l.Fragment,{children:[l.jsx(ux,{label:"Semantic",active:x==="semantic",onClick:()=>$("semantic")}),l.jsx(ux,{label:"Direct",active:x==="direct",onClick:()=>$("direct")}),l.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(xe=>l.jsx(ux,{label:xe.label||xe.name,active:x===`domain:${xe.id}`,onClick:()=>$(`domain:${xe.id}`)},`domain:${xe.id}`)),L.map(xe=>l.jsx(ux,{label:xe.name,active:x===`conn:${xe.id}`,onClick:()=>$(`conn:${xe.id}`)},`conn:${xe.id}`))]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&l.jsx(vyt,{domainAccess:u,search:g,scopeDomainId:A,selectedEntities:d,onSelectionChange:xe=>q(xe,"semanticDomain")}),Z&&l.jsx(Cyt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:xe=>q(xe)})]}),l.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:"Selected"}),l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:()=>t(!1),className:"inline-flex h-7 items-center rounded-control px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Cancel"}),l.jsxs("button",{type:"button",onClick:M,disabled:re,className:m.cn("inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",re&&"cursor-not-allowed opacity-50 hover:bg-primary"),children:[l.jsx("span",{children:fe}),d.length>0&&l.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&l.jsx(Dyt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function ux({label:e,active:t,onClick:n}){return l.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:m.cn("inline-flex h-6 shrink-0 items-center whitespace-nowrap rounded-control px-2 text-[11px] font-medium transition-colors",t?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:e})}function xk(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(vF,{className:r});case"view":return l.jsx(tv,{className:r});case"materialized view":return l.jsx(ume,{className:r});case"model":return l.jsx(nv,{className:r});case"file":return l.jsx(vi,{className:r});case"dataset":return l.jsx(ei,{className:r});case"upload":return l.jsx(m.Upload,{className:r});case"url":return l.jsx(hF,{className:r});default:return l.jsx(gg,{className:r})}}const ZR=e=>e.name||e.name,Iyt=e=>{const t=ZR(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Tyt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=v.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(m.TooltipProvider,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const p="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[xk(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate",children:ZR(f)}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-xs",children:Iyt(f)})]},p)}),d&&l.jsxs(m.Tooltip,{open:o,onOpenChange:i,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"flex h-6 cursor-pointer items-center gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(ja,{className:"h-3 w-3"}),l.jsxs("span",{children:[u.length," more"]}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:xk(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:ZR(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(m.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Afe=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Afe.displayName=bo.Input.displayName;const bS=e=>e.label||(e==null?void 0:e.name),nW=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Myt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Ct(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=v.useState(""),[g,b]=v.useState(""),x=s.filter(k=>{if(!h)return!0;const _=bS(k).toLowerCase(),E=(nW(k)||"").toLowerCase(),D=h.toLowerCase();return _.includes(D)||E.includes(D)});v.useEffect(()=>{e||(p(""),b(""))},[e]),v.useEffect(()=>{x.length>0&&!g&&b(bS(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>bS(_)===g);k&&(o.some(E=>"id"in k&&"id"in E?k.id===E.id:k.name===E.name&&k.connectionId===E.connectionId)||t(k),i(k),r())},S=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>o.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Pj,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:S,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Afe,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),a==null||a()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),c==null||c()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Oj,{className:"min-h-60",children:[l.jsx(Lj,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(dr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx($j,{children:x.map((k,_)=>{const E=w(k),D="id"in k?k.id:`${k.connectionId}-${k.name}`,j=bS(k);return l.jsxs(zj,{value:j,onSelect:()=>{E?n==null||n(k):t(k)},onMouseDown:I=>{I.preventDefault(),I.stopPropagation()},className:m.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:xk(k.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nW(k)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(m.Check,{className:"h-3 w-3 text-background"})})]},D)})})]})]})})}function XR({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:p="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,S]=v.useState(!1),[w,C]=v.useState(!1),N=o??y,k=o!==void 0,_=v.useRef(!1),D=m.useEditorStore(A=>A.card.dataSource)??z0,{selectedEntities:j,availableEntities:I,syncWithGlobalContext:T,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:R}=jj(x),B=e==="full"||e==="display",z=e==="full"||e==="trigger",U=v.useMemo(()=>b&&j.length>0?`Add entity (${j.length})`:g,[j.length,b,g]);v.useEffect(()=>{N&&!_.current&&s&&T(),_.current=N},[N,s,T]);const Y=v.useCallback(A=>{k||S(A),i==null||i(A)},[k,i]),O=v.useCallback(A=>{const W=j.filter(X=>!zr(X,A));F(W),c==null||c(A),d==null||d(W)},[c,d,j,F]),K=v.useCallback(A=>{if(A.length===0)return;const W=j.filter(X=>!A.some(Z=>zr(X,Z)));F(W),u==null||u(A),d==null||d(W)},[u,d,j,F]),q=v.useCallback(A=>{const W=R(A)?j.filter(X=>!zr(X,A)):[...j,A];F(W),d==null||d(W)},[R,d,j,F]),M=v.useCallback(()=>{F(I),d==null||d(I)},[I,d,F]),G=v.useCallback(()=>{F([]),d==null||d([])},[d,F]),L=v.useCallback(A=>{x==="dashboard"?P():F(A),d==null||d(A)},[P,x,d,F]),$=v.useCallback(A=>{const W=j.some(X=>zr(X,A))?j:[...j,A];F(W),a==null||a(A),d==null||d(W),Y(!1)},[a,d,j,Y,F]),V=B?l.jsx(Tyt,{className:m.cn(n?"contents":"space-y-2"),entities:j,availableEntities:I,onRemoveEntity:O,onRemoveEntities:K}):null,H=z?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:N,onOpenChange:Y,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:p,size:"xs",className:m.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[l.jsx(QW,{className:"h-3 w-3 text-muted-foreground"}),!b&&l.jsx("span",{children:U})]})}),l.jsx(m.PopoverContent,{className:m.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:A=>A.preventDefault(),children:l.jsx(Myt,{isOpen:!0,onSelect:q,onDeselect:q,onClose:()=>Y(!1),availableEntities:I,selectedEntities:j,onTabComplete:$,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{Y(!1),C(!0)}})})]}),l.jsx(f$,{incomingSelectedEntities:j,open:w,onOpenChange:C,dataSource:D,dialogMode:"aiContext",onSaveSelectedEntities:L,saveAsDashboardDefault:x==="dashboard"})]}):null;return l.jsx("div",{className:m.cn(n?"flex flex-wrap items-center gap-1":"",!n&&B?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[H,V]}):l.jsxs(l.Fragment,{children:[V,H]})})}const h$=v.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=v.useState(!1),h=v.useRef(null),{queueMessage:p}=m.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=m.useFileActions(),y=m.useFileAttachments(c);v.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const S=v.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const I=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${I}px`}},[e]);v.useEffect(()=>{S()},[S]),v.useEffect(()=>{const j=setTimeout(()=>{S()},0);return()=>clearTimeout(j)},[S]);const w=()=>{const j=e.trim();!j&&y.length===0||(a!=="ready"?(p(c,j,y),t(""),x(c)):r({preventDefault:()=>{}}))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),w()),j.key==="@"&&f(!0)},N=v.useCallback(j=>{const I=Cft(j.nativeEvent);I.length>0&&(j.preventDefault(),I.forEach(async T=>{const F=await Z3(T);g(c,F)}))},[g,c]),k=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),_=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),E=v.useCallback(j=>{b(c,j)},[b,c]),D=v.useCallback(j=>{const I=`@${j}`;e.includes(I)&&t(e.replace(I,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(byt,{onFilesDropped:k,currentFileCount:y.length,disabled:s,className:"space-y-4",children:[l.jsx(XR,{mode:"display",assistantType:c,onEntityRemoved:j=>{const I="label"in j?j.label:j.name;D(I)},onEntitiesRemoved:j=>{let I=e;j.forEach(T=>{const F="label"in T?T.label:T.name;I=I.replace(`@${F}`,"")}),I!==e&&t(I.replace(/\s{2,}/g," ").trim())}}),y.length>0&&l.jsx(Rft,{files:y,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{S(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pb-1 pt-3 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(XR,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const I="label"in j?j.label:j.name;t(`${e}@${I} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(gyt,{onFilesSelected:_,disabled:s,currentFileCount:y.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(m.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(_me,{className:"size-3.5"})}),!s&&l.jsx(m.Button,{disabled:!e.trim()&&y.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:w,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(bF,{className:"size-3.5"})})]})]})]})]})});h$.displayName="ChatInputWithContext";function Rfe({assistantType:e,className:t}){const n=m.useMessageQueue(e),{removeFromQueue:r}=m.useQueueActions();return n.length===0?null:l.jsxs("div",{className:m.cn("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(fF,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(m.X,{className:"h-3 w-3"})})]})},s.id))})]})}function Ffe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=m.useMessageQueue(e),{dequeueMessage:o}=m.useQueueActions();v.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Ayt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Ryt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ayt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Pfe(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=v.useRef(null),a=v.useRef(null),[c,u]=v.useState(!0),[d,f]=v.useState(!0),[h,p]=v.useState(!1),[g,b]=v.useState(0),x=v.useRef(!0),y=v.useRef(!0),S=v.useRef(!1),w=v.useRef(!1),C=v.useRef(0),N=v.useRef({count:0,signature:"none"}),k=v.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const B=R.closest("[data-radix-scroll-area-viewport]");if(B)return i.current=B,B;const z=R.parentElement;return z?(i.current=z,z):null},[]),_=v.useCallback(()=>{const R=k();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[k]),E=v.useCallback(()=>_()<=n,[_,n]),D=v.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=v.useCallback(R=>{y.current!==R&&(y.current=R,f(R))},[]),I=v.useCallback(()=>{p(R=>R&&!1),b(R=>R===0?R:0)},[]),T=v.useCallback((R={})=>{const B=k();if(!B)return;const{force:z=!1,instant:U=!1}=R;if(!z&&S.current)return;const Y=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,Y==="smooth"&&"scrollTo"in B?B.scrollTo({top:B.scrollHeight,behavior:"smooth"}):B.scrollTop=B.scrollHeight,C.current=B.scrollTop,S.current=!1,D(!0),j(!0),I(),requestAnimationFrame(()=>{w.current=!1})},[r,I,k,D,j]),F=v.useCallback(()=>{b(0),p(!1)},[]),P=v.useCallback(()=>{const R=k();if(!R)return;const B=C.current,z=R.scrollTop,U=z-B;C.current=z;const Y=E();if(w.current){j(Y),Y&&(S.current=!1,D(!0));return}if(U<-1&&!Y){S.current=!0,D(!1),j(!1);return}if(Y){S.current=!1,D(!0),j(!0),I();return}j(!1),S.current&&D(!1)},[I,k,E,D,j]);return v.useEffect(()=>{const R=k();if(!e||e.length===0){N.current={count:0,signature:"none"},R&&(C.current=R.scrollTop),I();return}const B=e[e.length-1],z=Ryt(B),U=N.current,Y=e.length>U.count,O=z!==U.signature;N.current={count:e.length,signature:z};const K=o||s&&(B==null?void 0:B.role)==="assistant"&&O;if(!S.current){D(!0),R&&E()&&j(!0),(Y||O||K)&&T({force:!1,instant:K});return}if(Y){const q=e.length-U.count;q>0&&(p(!0),b(M=>M+q))}else O&&(p(!0),b(q=>q>0?q:1))},[I,o,s,k,E,e,T,D,j]),v.useEffect(()=>{T({force:!0,instant:!0})},[T]),v.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const B=new ResizeObserver(()=>{S.current||T({force:!1,instant:!0})});return B.observe(R),()=>{B.disconnect()}},[T]),v.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:T,handleScroll:P,resetNewMessageCount:F}}function Ofe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=v.useState(r),a=v.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=v.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=v.useCallback(()=>{i(r)},[r]);return v.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const rW={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Fyt(e,t){var r;if((r=rW[e])!=null&&r[t])return rW[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function Lfe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Fyt(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pyt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Oyt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=v.useState(!1),[a,c]=v.useState(m.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[p,g]=v.useState(!1),[b,x]=v.useState(!1),y=n??b,{isLocalDev:S,isConsoleMode:w}=xg(),C=v.useRef(null);m.useDashboardStore(me=>me.dashboard.aiScopeTables),m.useDashboardStore(me=>me.isDashboardEditing);const N=m.useDashboardStore(me=>me.selectedSheetId),{setDataSource:k}=m.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:E}=m.useDashboardActions(),D=OL(),{setReasoningEffort:j,setShowReasoning:I,clearAssistantMessageContexts:T}=m.useAIActions(),{clearQueue:F}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:R}=m.useFileActions(),B=m.useFileAttachments("dashboard"),z=m.useEditorStore(me=>me.card.dataSource),{assistantProfile:U}=jfe(),Y=m.useDashboardStore(me=>me.handleOpenAssistantProfile),{selectedEntities:O,applyDashboardDefaultEntities:K}=jj("dashboard"),{sendMessage:q,isLoading:M,messages:G,setMessages:L,status:$,stop:V,errorMessage:H,clearError:A}=myt({dynamicVisualMode:f}),W=v.useCallback(me=>{r==null||r(me),n===void 0&&x(me)},[n,r]),X=v.useCallback(()=>{W(!y)},[y,W]);v.useEffect(()=>{if(!y)return;function me(Ye){Ye.key==="Escape"&&W(!1)}return window.addEventListener("keydown",me),()=>{window.removeEventListener("keydown",me)}},[y,W]);const[Z,J]=v.useState(""),re=me=>{J(me.target.value)};async function fe({sql:me,cardTitle:Ye,connectionId:Ve,cardType:$e,python:Ae,cardConfig:Re,dataSource:He,customVisualPreferences:Ge,visualizationMode:ht,dynamicCardPreferences:lt}){if(!N)return;const st=ht==="dynamic",Fe=m.hasValidCardConfig(Re),Ke=Ve||(He==null?void 0:He.connectionId)||"",_t=He?{...He,connectionId:Ke||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ke?{connectionId:Ke,connectionType:"",mode:"database",selectedEntities:[]}:z0,Te=!Fe||!st||(lt==null?void 0:lt.provenance)!=="card-config",Ze=Te?me:"",at=Te?Ae:"",bt={id:m.v4(),title:Ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:$e==="horizontalBar"?"y":"x"},...st&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:$e,sql:Ze,python:at,dataSource:_t,config:Re,connectionId:Ke,visualizationMode:ht,dynamicCardPreferences:lt,customCardPreferences:Ge?{url:Ge.url,componentName:Ge.componentName,pluginChartType:Ge.pluginChartType,settings:Ge.settings,type:"component"}:void 0},ft={id:m.v4(),cards:[bt],activeCardId:bt.id};try{await D(N,ft,"end"),E(!0),_(ft.id)}catch(Et){console.error("Failed to add assistant visual to dashboard:",Et),ut.error(Et instanceof Error?Et.message:"Failed to prepare semantic metadata for the new visual")}}const de=me=>{me.preventDefault();const Ye=Z.trim();if(!Ye&&B.length===0)return;const Ve=[];Ye&&Ve.push({type:"text",text:Ye}),B.forEach($e=>{$e.data&&Ve.push({type:"file",mediaType:$e.type,filename:$e.name,url:`data:${$e.type};base64,${$e.data}`})}),q({role:"user",parts:Ve}),J(""),P("dashboard"),le({force:!0})};v.useEffect(()=>{var me;e&&((me=C.current)==null||me.focus())},[e]),Ffe({assistantType:"dashboard",status:$,isLoading:M,sendMessage:q});const{hasActiveTools:Se,activeToolText:ue}=Lfe(G),{visibleMessages:ve,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:se,resetMessageWindow:be}=Ofe(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ce,contentRef:ge,isAtBottom:ee,hasNewMessages:te,newMessageCount:ce,scrollToBottom:le,handleScroll:Ee,resetNewMessageCount:ye}=Pfe(ve,{threshold:40,behavior:"smooth",isStreaming:M});function ne(me){const Ye={role:"user",parts:[{type:"text",text:me.title+" "+me.subtitle}]};q(Ye)}function je(me){q({role:"user",parts:[{type:"text",text:me}]})}function Ue(me){q({role:"user",parts:[{type:"text",text:me}]}),le({force:!0})}const Be=v.useCallback(async()=>{const me=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(me),ut.success("Conversation copied")}catch(Ye){console.error("Failed to copy conversation",Ye),ut.error("Unable to copy conversation")}},[G]),rt=(Z==null?void 0:Z.length)===0&&(G==null?void 0:G.filter(me=>me.role==="user").length)===0;function Xe(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function et(){return l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Lh,{className:"size-3.5"})})}),l.jsxs(fo,{align:"end",children:[l.jsx(kc,{children:"Options"}),l.jsx(Ea,{}),l.jsx(bu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(bu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(bu,{checked:u,onCheckedChange:d,children:"System Message"}),(S||w)&&l.jsxs(l.Fragment,{children:[l.jsx(Ea,{}),l.jsx(kc,{children:"Dynamic Visuals"}),l.jsx(bu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(bu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(bu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const tt=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("flex h-full grow flex-col justify-between break-words px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Xe(),Y&&l.jsx(m.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:Y,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&et(),a&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Be,children:"Copy Conversation"}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?l.jsx(pF,{className:"size-4"}):l.jsx(_k,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const me=G.filter(Ye=>Ye.role==="assistant").map(Ye=>Ye.id).filter(Ye=>!!Ye);L([]),F("dashboard"),A(),T(me),be()},children:l.jsx(jk,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(m.X,{className:"size-4"})})]})]}),l.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:Ce,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:Ee,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[xe&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:se,className:"text-xs",children:["Load ",Math.min(5,ke-ve.length)," ","more messages (",ke-ve.length," ","hidden)"]})}),l.jsx(cde,{showTools:a,showSystemMessage:u,messages:ve,onAddToDashboard:fe,onQuickReply:Ue,disableQuickReplies:M}),l.jsx(lde,{status:$,errorMessage:H,activeToolText:M&&Se?ue:void 0})]}),l.jsx(m.ScrollBar,{orientation:"horizontal"})]}),e&&!ee&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(m.Button,{onClick:()=>{le({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(m.ChevronDown,{className:"h-4 w-4"}),te&&ce>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&rt&&l.jsx(ude,{onClick:ne,placeholders:Pyt}),l.jsx("div",{children:rt&&U&&l.jsx(Efe,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:je})}),l.jsx(Rfe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(h$,{ref:C,setInput:J,stop:V,input:Z,handleInputChange:re,handleSubmit:me=>{de(me),le({force:!0})},isLoading:M,status:$,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(f$,{incomingSelectedEntities:O,open:p,onOpenChange:g,dataSource:z||z0,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:me=>K()})]});return y&&s?Sr.createPortal(l.jsx(sb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:l.jsx("div",{className:"flex h-full w-full",children:tt})}),s):tt}function Lyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=Iie(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(p){if($yt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),ut.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=zyt(p);if(g!=null&&g.id){const b=jie(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),ut.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function $yt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function zyt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function Byt(e,t){switch(e.interactionMode){case"drillToDetail":Vyt(e,t);break;case"drillThrough":Hyt(e,t);break;case"drillToURL":Uyt(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Vyt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Hyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Uyt(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Wyt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(na,{children:[l.jsx(go,{children:i||"Insight Detail"}),l.jsx(si,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Aie,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Gie,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function qyt(){const e=m.useInteractionStore(C=>C.interactionStates),t=m.useInteractionStore(C=>C.setInteractionState),n=m.useInteractionStore(C=>C.clearLastInteractionEvent),r=m.useInteractionStore(C=>C.replaceCardWithInsight),s=m.useInteractionStore(C=>C.setPendingDrillThrough),o=m.useInteractionStore(C=>C.pendingDrillThrough),i=m.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=Ph(),d=m.useDashboardStore(C=>C.dashboard),f=m.useDashboardStore(C=>C.filterValues),{data:h,isLoading:p}=LY((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Kie(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),S=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E})=>{const D={filters:C},j={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[D]},I={...m.createInitialInteractionState(),appliedClickFilters:[j],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E};t(m.DRILL_CONTEXT_CARD_ID,I)}}),[a,r,f,c,d,s,t]);v.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{Byt(k,S)}catch(E){console.error("Error executing interaction event:",E)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,S]),v.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,p,u,c,i]);const w=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Wyt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Yyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Gyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Gyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kyt(e){return e?`Back to ${e}`:"Back"}function Zyt(){var y,S,w,C,N;const e=m.useInteractionStore(k=>k.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(k=>k.actions.goBackFromDrill),n=m.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=Ph(),[s,o]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const k=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(w=(S=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:S.filterGroups)==null?void 0:w[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),c.current={x:k.clientX-s.x,y:k.clientY-s.y})};Yyt(f);const x=Kyt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const E=k.field.label||k.field.name,D=String(k.value);return l.jsxs(Yr,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",D]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(ev,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Xyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Qyt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=db({id:`filter:${e.id}`,disabled:n||!t}),x={transform:_i.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(bL,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const sW="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Jyt=[];function $fe({open:e,onOpenChange:t}){var L,$,V;const[n,r]=v.useState(!1),[s,o]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(H=>{var A;return(A=H.dashboard)==null?void 0:A.sheets}),u=m.useDashboardStore(H=>H.dashboard),d=m.useDashboardStore(H=>H.dashboardInputValues),f=m.useDashboardStore(H=>H.filterValues),h=m.useDashboardStore(H=>H.controlValues),p=m.useDashboardStore(H=>H.inlineFilterValuesMap),g=m.useDashboardStore(H=>H.cardControlValuesMap),b=m.useDashboardStore(H=>H.selectedSheetId),x=m.useDashboardStore(H=>H.selectedSheetId?H.documentInputRuntimeBySheetId[H.selectedSheetId]:void 0),y=m.useDashboardStore(H=>H.isDownloadingPdf),{authToken:S,tokenProps:w}=Ct(),C=c==null?void 0:c.find(H=>H.id===b),N=v.useMemo(()=>m.getDashboardExportSheets(c),[c]),k=m.isDocumentSheet(C),_=k&&C?C.document:void 0,E=v.useMemo(()=>k&&C?dw(u,C.id):[],[C,k,u]),D=E.length>0,j=v.useMemo(()=>k&&C?Tce(u,C.id):!1,[C,k,u]),I=v.useMemo(()=>D?E.map(fw):(_==null?void 0:_.inputs)||Jyt,[_,E,D]),T=(($=(L=w==null?void 0:w.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((V=w==null?void 0:w.params)==null?void 0:V.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=v.useMemo(()=>Tle(I),[I]),P=v.useMemo(()=>Dle(I,T),[I,T]),R=v.useMemo(()=>Ile(I),[I]),B=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=v.useMemo(()=>k?j&&C&&_?VZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(H=>H.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:T}):Rle(I,B,z,F,F):[],[_,I,C,k,u,g,h,f,p,d,z,B,F,T,j]),Y=!!C,O=N.length>0,K=((c==null?void 0:c.length)||0)>1||k,q=i.sheetSelection==="current"&&(!Y||k&&U.length>0)||i.sheetSelection==="all"&&!O;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(H=>({...H,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){ut.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){ut.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!Y){ut.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){ut.error("No dashboard sheets are available to export");return}o(!0);const H=i.sheetSelection==="current"&&k,A=H?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",W=ut.loading(A);try{if(H){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){ut.dismiss(W),ut.error(`Set ${U.join(", ")} before exporting`);return}const Z=new Date().toISOString(),J=j?UZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:Z,timezone:T}).snapshot:void 0;await PP(w.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:T,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:B,controlValuesByInputId:z,generatedAt:Z}}})}else{const Z=xee();await XZ(w.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,Z)}ut.dismiss(W);const X=H?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";ut.success(X,{duration:2e3}),M()}catch(X){ut.dismiss(W),ut.error("Failed to download PDF",{description:m_(X,"Please try again or contact support."),descriptionClassName:p_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{o(!1)}}return l.jsx(Oo,{open:e,onOpenChange:H=>{if(!H){M();return}t(!0)},children:l.jsxs(mo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(na,{children:[l.jsx(go,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),l.jsx(si,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[K&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:sW,children:"Export scope"}),l.jsxs(Ia,{value:i.sheetSelection,onValueChange:H=>a({...i,sheetSelection:H}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!Y&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"current",id:"scope-current",disabled:!Y}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Ln,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:H=>{a({...i,protectPdf:H,password:H?i.password:""}),H||r(!1)}}),l.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:sW,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:H=>a({...i,password:H.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:H=>{H.key==="Enter"&&i.password&&G()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Nk,{className:"h-3.5 w-3.5"}):l.jsx(tv,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:G,disabled:s||y||q,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(qc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function zfe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=v.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(qc,{className:m.cn("size-4",e)})}),l.jsx($fe,{open:i,onOpenChange:a})]})}function oW(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function e0t({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=db({id:`control:${e.id}`,disabled:!n}),d={transform:_i.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Gle,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function iW(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function aW(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function t0t(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return aW(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=aW(t,n).filter(a=>!o.has(a));return[...s,...i]}function n0t(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function r0t(e){return zm(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>zm(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function lW(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function s0t(e){const t={sheetId:e.selectedSheetId},n=m.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=m.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||m.getBackingDefaultSlot(e.dashboardInput)}function o0t(e){return Bfe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function Bfe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=n0t(e.dashboard,t);return lZ(a_({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!r0t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function i0t(e,t){return"toolbar"}function a0t(){const e=Zc("interactive"),t=m.useDashboardStore($=>$.selectedSheetId),n=m.useDashboardStore($=>$.dashboard.filters),r=m.useDashboardStore($=>$.dashboard.filterLayout),s=m.useDashboardStore($=>$.isDashboardEditing),o=m.useDashboardStore($=>$.controlValues),i=m.useDashboardStore($=>$.filterValues);m.useDashboardStore($=>$.filteringCards);const a=m.useDashboardStore($=>$.inlineFilterValuesMap),c=m.useDashboardStore($=>$.dashboardInputValues),u=m.useInteractionStore($=>$.clearAllClickFilters),d=m.useInteractionStore($=>Object.entries($.interactionStates).reduce((V,[H,A])=>{var W;return H===m.DRILL_CONTEXT_CARD_ID?V:V+(((W=A.appliedClickFilters)==null?void 0:W.length)??0)},0)),f=m.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:S,setFilteringCards:w,upsertDashboardInput:C}=m.useDashboardActions(),N=Tj(cg(cb,{activationConstraint:{distance:5}})),k=m.useDashboardStore($=>$.dashboard),_=o0t({dashboard:k,selectedSheetId:t}).filter($=>i0t($.filter)==="toolbar"),E=Bfe({dashboard:k,selectedSheetId:t}),D=_.map($=>$.filter),j=new Map(_.map($=>[`filter:${$.filter.id}`,$])),I=wKe(k),T=I.filter($=>!$.hidden&&C0($)==="toolbar"),F=I.filter($=>!$.hidden&&C0($)==="advanced"),P=t0t(r==null?void 0:r.toolbarItemOrder,D,T),R=new Map(D.map($=>[`filter:${$.id}`,$])),B=new Map(T.map($=>[`control:${$.id}`,$]));function z($){const{active:V,over:H}=$;if(!H||V.id===H.id)return;const A=String(V.id),W=String(H.id),X=P.findIndex(ve=>ve===A),Z=P.findIndex(ve=>ve===W);if(X===-1||Z===-1)return;const J=ub(P,X,Z);y({toolbarItemOrder:J});const re=new Set((n||[]).map(ve=>ve.id)),fe=P.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),de=J.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),Se=P.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:","")),ue=J.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:",""));h(oW(n||[],fe,de)),g(oW(k.controls||[],Se,ue))}const U=(r==null?void 0:r.toolbarWrap)??!1,Y=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>iW($)).length)??0,K=E.filter(lW),q=K.filter($=>{const V=s0t({dashboardInput:$,dashboardInputValues:c,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(V==null?void 0:V.status)==="set"&&V.value.kind==="filter"&&iW(V.value.filterValue)}).length,M=a?Object.values(a).reduce(($,V)=>$+((V==null?void 0:V.length)??0),0):0,G=O+q+M+d,L=()=>{S([]),K.forEach($=>{p($,{sheetId:t})}),w([]),u(),a&&Object.entries(a).forEach(([$,V])=>{V==null||V.forEach(H=>{f($,H.filterId)})})};return!D.length&&!T.length&&!F.length&&!Y&&G===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(ow,{sensors:N,collisionDetection:nw,onDragEnd:z,children:l.jsxs("div",{className:m.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(iw,{items:P,strategy:qL,children:l.jsx(NR,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const V=R.get($);if(V){const A=j.get($),W=A&&lW(A);return l.jsx(Qyt,{filter:V,isEditing:s,storageOptions:W?{storageTarget:"dashboardInput",dashboardInput:A,sheetId:t??void 0}:void 0,inputVariableName:W?A.variableName:void 0,onUpdateFilter:W?(X,Z)=>{C({...A,variableName:(Z==null?void 0:Z.variableName)||A.variableName,filter:X})}:void 0,onRemoveFilter:W?()=>{S((i||[]).filter(X=>X.filterId!==V.id)),b(A.id)}:void 0},$)}const H=B.get($);return H?l.jsx(e0t,{control:H,value:o==null?void 0:o[H.id],isEditing:s,onChange:A=>x(H.id,A)},$):null})})}),F.length>0&&l.jsx(Hie,{title:"",controls:F,values:o,onChange:($,V)=>x($.id,V),immediatePlacement:"toolbar",advancedLabel:"More controls"}),G>0&&l.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(m.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:G})]}),Y&&l.jsx("div",{className:m.cn(G>0?"ml-1.5":"ml-auto"),children:l.jsx(zfe,{})})]})})})}function Vfe(){var te,ce;const{showAssistant:e,tokenProps:t,renderMode:n}=Ct(),r=Xyt((te=t.config)==null?void 0:te.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=xg(),i=(ce=s==null?void 0:s.cardDisplay)==null?void 0:ce.mode,a=Wh(i),c=_Z({displayMode:i,renderMode:n}),u=v.useRef(null),d=v.useRef(null),[f,h]=v.useState(!1),{handleDragStart:p,isDraggingRef:g,getStyle:b,getPositionClasses:x}=Sot({initialPosition:"bottom-right"}),y=Hf(le=>le.setFullscreen),S=Hf(le=>le.setPanelOpen),w=Hf(le=>le.setContainer),C=mK("dashboard"),N=gK(),k=bK("dashboard"),_=C.isOpen,E=N==="dashboard",D=m.useDashboardStore(le=>le.isVisualEditing),j=m.useDashboardStore(le=>le.themeStyle),I=Rl(),T=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.sheets}),F=m.useDashboardStore(le=>le.showFilters),P=m.useDashboardStore(le=>le.isDashboardEditing),R=m.useDashboardStore(le=>le.selectedSheetId),B=T==null?void 0:T.find(le=>le.id===R),z=m.useDashboardStore(le=>{var Ee,ye,ne;return(ne=(ye=(Ee=le.dashboard)==null?void 0:Ee.sheets)==null?void 0:ye.find(je=>je.id===le.selectedSheetId))==null?void 0:ne.kind}),U=m.useDashboardStore(le=>{var Ee,ye;return((ye=(Ee=le.dashboard)==null?void 0:Ee.summary)==null?void 0:ye.position)||"top"}),Y=z==="document",O=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.id}),K=m.useDashboardStore(le=>le.isDashboardPanelOpen),q=m.useDashboardStore(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:L}=YW(O),[$,V]=v.useState(null);Rk(Xr.DASHBOARD);const{setSelectedSheetId:H,setSheetTitle:A,addSheet:W,setSheets:X}=m.useDashboardActions();Lyt(d);const{setActiveAssistantType:Z}=m.useAIActions();v.useEffect(()=>{if(O){const le=M();V(le)}},[O,M]),v.useEffect(()=>{_?Z("dashboard"):N==="dashboard"&&y(null)},[_,Z,N,y]),v.useEffect(()=>{var le;_||(le=u.current)==null||le.resize(0)},[_]);function J(le){var Ee,ye;le?((Ee=u.current)==null||Ee.resize(40),S("dashboard",!0),y("dashboard"),Z("dashboard")):(S("dashboard",!1),y(null),(ye=u.current)==null||ye.resize(0),Z(null))}function re(le="dashboard"){const Ee={id:m.v4(),title:le==="document"?"New Document":"New Sheet",...le==="document"?{kind:le,document:m.createDefaultDocumentDefinition()}:{}};W(Ee),H(Ee.id)}function fe(le,Ee){if(!O)return;$===le?(L(),V(null),ut.success("Default sheet cleared")):(G(le),V(le),ut.success(`"${Ee}" set as default sheet`))}function de(le){var Ee;le<1?(S("dashboard",!1),y(null),Z(null),(Ee=u.current)==null||Ee.resize(0)):(_||S("dashboard",!0),Z("dashboard"))}function Se(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const ue=(le,Ee)=>{le.dataTransfer.setData("tabIndex",Ee.toString())},ve=le=>{le.preventDefault()},xe=(le,Ee)=>{const ye=le.dataTransfer.getData("tabIndex");if(ye===Ee.toString())return;const ne=Array.from(T||[]),[je]=ne.splice(parseInt(ye),1);ne.splice(Ee,0,je),X(ne)},ke=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,se=r===!0&&!a&&!_&&!D&&!F;function be(){if(T&&T.length>1||P)return l.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&ke&&!K&&l.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{q(!K)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:l.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:l.jsx(mF,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[T==null?void 0:T.map((le,Ee)=>{const ye=R===le.id,ne=$===le.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:je=>ue(je,Ee),onDragOver:ve,onDrop:je=>xe(je,Ee),onClick:()=>H(le.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:le.id,children:[le.kind==="document"&&l.jsx(vi,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(ON,{enabled:P&&ye,text:le.title,onSave:je=>A(le.id,je),children:le.title},le.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":ne?"Clear default sheet":"Set as default sheet",title:ne?"Clear default sheet":"Set as default sheet",onClick:je=>{je.stopPropagation(),fe(le.id,le.title||"Sheet")},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),fe(le.id,le.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ye||ne?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(yF,{className:m.cn("h-3 w-3 transition-colors",ne?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ye&&T.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:je=>{je.stopPropagation(),h(!0)},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),h(!0))},children:l.jsx(m.X,{className:"h-3 w-3"})})]},le.id)}),P&&l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(dr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(fo,{align:"start",className:"w-48",children:[l.jsxs(jn,{onSelect:()=>re("dashboard"),children:[l.jsx(Rm,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(jn,{onSelect:()=>re("document"),children:[l.jsx(vi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function Ce(){return l.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:T==null?void 0:T.map(le=>l.jsx(m.TabsContent,{style:{backgroundColor:Se(),...I.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:le.id,children:l.jsx(xH,{sheet:le})},le.id))})}function ge(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:le=>{H(le)},value:R||void 0,children:[be(),U==="top"&&!Y&&l.jsx(sR,{}),R&&!Y&&l.jsx(a0t,{}),Y?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:Ce()}):l.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:Ce()}),U==="bottom"&&!Y&&l.jsx(sR,{}),l.jsx(Cot,{open:f,setOpen:h})]})}const ee=v.useCallback(le=>{w("dashboard",le)},[w]);return T?c&&R&&!Y?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):c&&Y&&B?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(xH,{sheet:B})}):l.jsxs(l.Fragment,{children:[l.jsx(qyt,{}),l.jsx(Zyt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(UF,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",E&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(Ry,{children:ge()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(wot,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),l.jsx(Ry,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:de,defaultSize:_?40:0,ref:u,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Oyt,{open:_,setOpen:J,isFullscreen:E,onFullscreenChange:le=>y(le?"dashboard":null),fullscreenContainer:k})})})]})]}),l.jsx("div",{ref:ee,className:m.cn("absolute inset-0",!E&&"pointer-events-none")}),se&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{g.current||J(!0)},onMouseDown:p,onTouchStart:p,title:"Open Assistant (drag to move)",children:l.jsx(vme,{className:"h-5 w-5"})})})]})]}):null}const Hfe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>l0t(d),[d]),{theme:h}=nF(),p=c0t(h),g=v.useMemo(()=>s??Wc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=v.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=v.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(sb,{...c,ref:u,className:i,style:a,children:o})})});Hfe.displayName="AppearanceProvider";function l0t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function c0t(e){const t=hC(e),[n,r]=v.useState(()=>u0t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function u0t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Ufe=v.createContext({openBrandStudioPreview:()=>{}}),d0t=Ufe.Provider;function f0t(){return v.useContext(Ufe)}function h0t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=hC(t),[o,i]=v.useState(()=>p0t(n)||s),a=v.useCallback(u=>{const d=hC(u);m0t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(kW.Provider,{...r,value:c,children:e})}function p0t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=hC(t,"system");return n===t?n:null}catch{return null}}function m0t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const g0t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function p$({appearance:e,children:t}){var I,T;const{authToken:n,id:r,tokenProps:s}=Ct(),o=Q0(),i=(I=o.data)==null?void 0:I.organizationAppearance,a=(T=s.config)==null?void 0:T.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),S=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=On({queryKey:AY({resourceType:Xr.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:S,appearance:i})},[i,S]),v.useEffect(()=>{w.data!==void 0&&y({scopeKey:S,appearance:w.data})},[w.data,S]);const C=(x==null?void 0:x.scopeKey)===S?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=v.useMemo(()=>Wc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=v.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),E=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const D=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),j=g??h??e;return l.jsx(h0t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(d0t,{value:D,children:l.jsx(Hfe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:j,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(g0t,{appearance:d,onDraftChange:b,onSave:F=>{p(F),b(F),f(F)},onCancel:E})})})]})})})})}function Wfe({children:e,preferences:t}){const{currentUser:n}=ta(),r=v.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(IY.Provider,{value:r,children:l.jsx(kj,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function b0t(e=2e3,t=500){const n=Ipe(),[r,s]=v.useState(!1),[o,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function m$({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=b0t(e,t);return v.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:e,children:[l.jsx(m$,{componentType:"dashboard",componentId:e.id}),l.jsx(p$,{appearance:e.appearance,children:l.jsx(Wfe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(YF,{...e,type:"dashboard",children:l.jsx(Vfe,{})})})})})]})})}function x0t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[s,o]=v.useState(),i=v.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function y0t({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=xg(),r=Wh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=x0t([t,o,r]);return v.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(Zi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(gL,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(m.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function v0t(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(y0t,{filter:r}),l.jsx(gj,{filter:r})]},r.id))}):null}function w0t(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(v0t,{}),l.jsx(Vfe,{})]})})}const S0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-0VMAeMoa.js"))),C0t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-C0EDM0QB.js"))),N0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CqbLOfnr.js"))),k0t=v.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-P9iNqBM1.js")).then(e=>({default:e.ResourceManagementPanel})));function _0t({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(u=>u.isDashboardPanelOpen),s=m.useDashboardStore(u=>u.isVisualEditing),o=m.useDashboardStore(u=>u.showDashboardJSON),i=m.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:c}=n;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:n,children:[l.jsx(m$,{componentType:"surfboard",componentId:n.id}),l.jsxs(p$,{appearance:a,children:[l.jsx(Ebe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(Wfe,{preferences:c,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(N0t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(S0t,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(k0t,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(YF,{...n,type:"dashboard",children:[s&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(C0t,{})}),l.jsx(w0t,{})]})})]})]})]})]})]})})}var j0t=Object.defineProperty,E0t=(e,t,n)=>t in e?j0t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xS=(e,t,n)=>E0t(e,typeof t!="symbol"?t+"":t,n);const D0t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},I0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},T0t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M0t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const A0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Yfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},R0t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},F0t={stringify:e=>e,parse:e=>e},d2={string:F0t,number:R0t,boolean:D0t,function:I0t,method:A0t,json:T0t},dx=Symbol.for("r2wc.render"),yS=Symbol.for("r2wc.connected"),Xd=Symbol.for("r2wc.context"),li=Symbol.for("r2wc.props");function P0t(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const p of i){c[p]=Array.isArray(t.props)?"string":t.props[p];const g=M0t(p);d[p]=g,f[g]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),xS(this,o,!0),xS(this,s),xS(this,r,{}),xS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[li].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],S=y?d2[y]:null;if(y==="method"){const w=Yfe(b);Object.defineProperty(this[li].container,w,{enumerable:!0,configurable:!0,get(){return this[li][w]},set(C){this[li][w]=C,this[dx]()}}),this[li][g]=S.parse(x,b,this)}S!=null&&S.parse&&x&&(this[li][g]=S.parse(x,b,this))}for(const g of a)this[li][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yS]=!0,this[dx]()}disconnectedCallback(){this[yS]=!1,this[Xd]&&n.unmount(this[Xd]),delete this[Xd]}attributeChangedCallback(g,b,x){const y=f[g],S=c[y],w=S?d2[S]:null;y in c&&w!=null&&w.parse&&x&&(this[li][y]=w.parse(x,g,this),this[dx]())}[(o=yS,s=Xd,r=li,dx)](){this[yS]&&(this[Xd]?n.update(this[Xd],this[li]):this[Xd]=n.mount(this.container,e,this[li]))}}for(const p of i){const g=d[p],b=c[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[li][p]},set(x){this[li][p]=x;const y=b?d2[b]:null;if(y!=null&&y.stringify){const S=y.stringify(x,g,this);this.getAttribute(g)!==S&&this.setAttribute(g,S)}else this[dx]()}})}return h}function O0t(e,t,n){const r=CW.createRoot(e),s=v.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function L0t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $0t({root:e}){e.unmount()}function z0t(e,t={}){return P0t(e,t,{mount:O0t,update:L0t,unmount:$0t})}const B0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V0t=z0t(qfe,{props:B0t}),H0t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(g3,{context:t})," "]})}),Gfe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),U0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),W0t=Array.from(Gfe).join(", "),q0t=3,Y0t="Self-heal",G0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function K0t({card:e}){var Y,O,K,q,M;const[t,n]=v.useState({}),{authToken:r}=Ct(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=v.useMemo(()=>Yv(o),[o]),a=m.useEditorStore(G=>G.frame),c=m.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=m.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=m.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=Qh(((Y=f.customCardPreferences)==null?void 0:Y.url)||""),g=(O=p==null?void 0:p.visuals)==null?void 0:O.find(G=>{var L;return G.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=Gv(f,g)??"single",x=v.useMemo(()=>wL({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=v.useMemo(()=>{const G=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return G<0?-1:y0(e,G)},[x,e]),S=v.useMemo(()=>b!=="multiple"||y<0?e.type:pm(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=v.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==e.type?{...e,type:S}:e,[e,S,b]),{data:C}=f_(w),N=m.useInteractionStore(G=>G.interactionStates),k=m.useDashboardStore(G=>{var L;return(L=G.dashboard)==null?void 0:L.id}),_=m.useDashboardStore(G=>G.dashboard.filters),E=m.useDashboardStore(G=>G.filterValues),D=m.useDashboardStore(G=>G.selectedSheetId),j=v.useMemo(()=>xL({card:e,sheetId:D||"",inlineFilterValues:c,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,D,c,u,d]),{cardFilters:I,cardFilterValues:T}=v.useMemo(()=>dv({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:E,selectedSheetId:D}),[e,N,k,_,E,D]),F=v.useCallback((G,L)=>{const $=CL(L);n(V=>({...V,[G]:$}))},[]),P=(K=f.customCardPreferences)==null?void 0:K.componentName,R=P?h(P):null,B=FN((q=f.customCardPreferences)==null?void 0:q.settings,f),z=v.useMemo(()=>vL(x),[x]),U=v.useMemo(()=>z.map((G,L)=>pm(G,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[R&&b==="single"&&l.jsx(R,{editing:!0,params:s,theme:i,settings:B,cardMetadata:oie({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j}),R&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((G,L)=>{if(!G)return null;const $=y0(G,L),V=pm(G,$,g==null?void 0:g.slots);return l.jsx(U5,{onDataChange:F,card:G,effectiveCardType:V},`${G.id}-${$}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(R,{editing:!0,onDataChange:F,...NL({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:B,filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Z0t=v.memo(K0t,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),X0t=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Kfe=["PageUp","PageDown"],Zfe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},bb="Slider",[QR,Q0t,J0t]=m.createCollection(bb),[Qfe]=m.createContextScope(bb,[J0t]),[evt,fE]=Qfe(bb),Jfe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),w=i==="horizontal"?tvt:nvt,[C=[],N]=m.useControllableState({prop:d,defaultProp:u,onChange:I=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(I)}}),k=Q.useRef(C);function _(I){const T=avt(C,I);j(I,T)}function E(I){j(I,y.current)}function D(){const I=k.current[y.current];C[y.current]!==I&&h(C)}function j(I,T,{commit:F}={commit:!1}){const P=dvt(o),R=fvt(Math.round((I-r)/o)*o+r,P),B=m.clamp(R,[r,s]);N((z=[])=>{const U=ovt(z,B,T);if(uvt(U,c*o)){y.current=U.indexOf(B);const Y=String(U)!==String(z);return Y&&F&&h(U),Y?U:z}else return z})}return l.jsx(evt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:l.jsx(QR.Provider,{scope:e.__scopeSlider,children:l.jsx(QR.Slot,{scope:e.__scopeSlider,children:l.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:_,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,C.length-1,{commit:!0}),onStepKeyDown:({event:I,direction:T})=>{if(!a){const R=Kfe.includes(I.key)||I.shiftKey&&Zfe.includes(I.key)?10:1,B=y.current,z=C[B],U=o*R*T;j(z+U,B,{commit:!0})}}})})})})});Jfe.displayName=bb;var[ehe,the]=Qfe(bb,{startEdge:"left",endEdge:"right",size:"width",direction:1}),tvt=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),p=m.useComposedRefs(t,w=>h(w)),g=Q.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function S(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=g$(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(nhe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=S(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=S(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:w=>{const N=Xfe[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),nvt=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=Q.useRef(null),f=m.useComposedRefs(t,d),h=Q.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=g$(y,p?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(nhe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xfe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),nhe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=fE(bb,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kfe.concat(Zfe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),rhe="SliderTrack",she=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(rhe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});she.displayName=rhe;var JR="SliderRange",ohe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(JR,n),o=the(JR,n),i=Q.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>lhe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});ohe.displayName=JR;var eF="SliderThumb",ihe=Q.forwardRef((e,t)=>{const n=Q0t(e.__scopeSlider),[r,s]=Q.useState(null),o=m.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(rvt,{...e,ref:o,index:i})}),rvt=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=fE(eF,n),a=the(eF,n),[c,u]=Q.useState(null),d=m.useComposedRefs(t,S=>u(S)),f=c?i.form||!!c.closest("form"):!0,h=m.useSize(c),p=i.values[r],g=p===void 0?0:lhe(p,i.min,i.max),b=ivt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?lvt(x,g,a.direction):0;return Q.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(QR.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(ahe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});ihe.displayName=eF;var svt="RadioBubbleInput",ahe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=m.useComposedRefs(s,r),i=m.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(m.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});ahe.displayName=svt;function ovt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function lhe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function ivt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function avt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function lvt(e,t,n){const r=e/2,o=g$([0,50],[0,r]);return(r-o(t)*n)*n}function cvt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function uvt(e,t){if(t>0){const n=cvt(e);return Math.min(...n)>=t}return!0}function g$(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function dvt(e){return(String(e).split(".")[1]||"").length}function fvt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var che=Jfe,hvt=she,pvt=ohe,mvt=ihe;const uhe=Q.forwardRef(({className:e,...t},n)=>l.jsxs(che,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(hvt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(pvt,{className:"absolute h-full bg-primary"})}),l.jsx(mvt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));uhe.displayName=che.displayName;const dhe=["SUN","MON","TUE","WED","THU","FRI","SAT"],gvt=dhe.reduce((e,t,n)=>({...e,[t]:n}),{}),tc={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function bvt(e){if(!e||!e.trim())return{...tc};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...tc,isCustom:!0};const[s,o,i,a,c]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...tc,isCustom:!0};if(i==="*"&&(c==="?"||c==="*"))return{...tc,repeats:"daily",hour:d,minute:u};if(i==="?"&&c!=="?"&&c!=="*"){const h=c.split(",").map(p=>p.toUpperCase()).map(p=>gvt[p]).filter(p=>typeof p=="number");if(h.length>0)return{...tc,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(c==="?"||c==="*")?{...tc,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(c==="?"||c==="*")?{...tc,repeats:"monthly",hour:d,minute:u}:{...tc,hour:d,minute:u,isCustom:!0}}function xvt(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>dhe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fhe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function yvt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function vvt(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function wvt(e,t,n,r){const s=fhe(e.hour,e.minute),o=yvt(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${vvt(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const Svt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=l3;exports.AccordionContent=T0;exports.AccordionItem=D0;exports.AccordionTrigger=I0;exports.AddDataPicker=f$;exports.AggregateTable=W_;exports.Alert=zP;exports.AlertDescription=BP;exports.AlertDialog=Lc;exports.AlertDialogAction=kl;exports.AlertDialogCancel=_l;exports.AlertDialogContent=vl;exports.AlertDialogDescription=Nl;exports.AlertDialogFooter=Sl;exports.AlertDialogHeader=wl;exports.AlertDialogTitle=Cl;exports.AlertDialogTrigger=V2;exports.AlertTitle=wX;exports.ArrowDown=Js;exports.ArrowDownIcon=wqe;exports.ArrowLeft=ev;exports.ArrowRight=Sk;exports.ArrowUp=eo;exports.ArrowUpIcon=Cqe;exports.AssistantContextEntityControls=XR;exports.AssistantStatus=lde;exports.AtSign=QW;exports.AxisConfigurator=jg;exports.Badge=Yr;exports.Bell=SS;exports.BookType=eq;exports.BulletChartIcon=ade;exports.COMMON_TIMEZONES=Svt;exports.CSS=_i;exports.CalculatedFieldEditor=yle;exports.Calculator=nq;exports.Calendar=gi;exports.Calendar$1=ZS;exports.CalendarRange=rq;exports.Card=Tm;exports.CardContent=wk;exports.CardHeader=vk;exports.CardSummary=dR;exports.CardTitle=mg;exports.ChartArea=F2;exports.ChartColumnIncreasing=sq;exports.ChartColumnStacked=oq;exports.ChartJsVisual=$v;exports.ChartLine=iq;exports.ChartNoAxesGantt=lq;exports.ChartPie=cq;exports.ChartScatter=uq;exports.ChatInputWithContext=h$;exports.Checkbox=Ln;exports.ChevronLeft=Oh;exports.ChevronRight=Mr;exports.Circle=Ck;exports.CircleAlert=ih;exports.CircleCheck=hq;exports.CircleHelp=pq;exports.Clock=fF;exports.CodeHighlighter=Uu;exports.CodeXml=Bf;exports.Collapsible=Vc;exports.CollapsibleContent=Uc;exports.CollapsibleTrigger=Hc;exports.ColorField=Bi;exports.Command=Pj;exports.CommandEmpty=Lj;exports.CommandGroup=$j;exports.CommandInput=ZL;exports.CommandItem=zj;exports.CommandList=Oj;exports.CommandSeparator=$ae;exports.ComparisonMetadataBadge=Wee;exports.Container=YF;exports.ControlDefaultValueEditor=Ble;exports.ControlDefinitionOptionsEditor=zle;exports.ControlIdInput=Ple;exports.ControlVisibilitySettings=$tt;exports.Copy=Pc;exports.CopyButton=Ac;exports.CopyPlus=O2;exports.Cross2Icon=jqe;exports.CustomFilterPopover=gL;exports.CustomScrollArea=zl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=GJ;exports.DEFAULT_SCHEDULE_VM=tc;exports.Dashboard=qfe;exports.DashboardActionsMenu=TY;exports.DashboardCard=Wie;exports.DashboardCreateDialogBase=aG;exports.DashboardExportDialog=$fe;exports.DashboardPlus=_0t;exports.DashboardWC=V0t;exports.DataAppBuilder=pK;exports.DataTableConditionalFormattingSettings=Dce;exports.DataTablePagination=z_;exports.Database=ei;exports.DateRangePicker=Z5;exports.DefaultChatTransport=c$;exports.Dialog=Oo;exports.DialogContent=mo;exports.DialogDescription=si;exports.DialogFooter=Gc;exports.DialogHeader=na;exports.DialogTitle=go;exports.DialogTrigger=oG;exports.DisplayPreferencesProvider=kj;exports.DndContext=ow;exports.Donut=mq;exports.Download=qc;exports.DownloadPdf=zfe;exports.DragOverlay=kae;exports.DropdownMenu=Ao;exports.DropdownMenuCheckboxItem=bu;exports.DropdownMenuContent=fo;exports.DropdownMenuItem=jn;exports.DropdownMenuLabel=kc;exports.DropdownMenuRadioGroup=tbe;exports.DropdownMenuRadioItem=DY;exports.DropdownMenuSeparator=Ea;exports.DropdownMenuSub=TF;exports.DropdownMenuSubContent=Tk;exports.DropdownMenuSubTrigger=Ik;exports.DropdownMenuTrigger=Ro;exports.EMPTY_DATA_SOURCE=z0;exports.Editable=ON;exports.EditableText=Zi;exports.EditorCustomVisual=Z0t;exports.Ellipsis=ja;exports.EllipsisVertical=Lh;exports.ErrorBoundary=Aa;exports.ExportError=Rg;exports.ExternalLink=Am;exports.Eye=tv;exports.EyeOff=Nk;exports.Fallback=Cj;exports.FallbackVisual=w0;exports.FeedbackCategory=xd;exports.FeedbackDialog=L0;exports.FieldsList=g3;exports.FieldsSection=H0t;exports.FileSpreadsheet=gq;exports.FileText=vi;exports.Filter=ah;exports.FilterComponent=gj;exports.FilterInfo=aR;exports.FilterableFieldsPanel=wle;exports.Globe=gg;exports.Grid3x3=bq;exports.GripVertical=Yc;exports.HEATMAP_PRESET_PALETTES=YM;exports.Hash=xq;exports.House=yq;exports.HoverCard=Pg;exports.HoverCardContent=cd;exports.HoverCardTrigger=Og;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gfe;exports.INLINE_ALLOWED_TOOL_LIST=W0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=U0t;exports.IconButton=Vu;exports.IconForFieldType=rC;exports.InfoHover=LL;exports.InlineFilterBar=Fie;exports.KPICard=Th;exports.KeyboardSensor=rw;exports.Layers=nv;exports.LayoutDashboard=Rm;exports.Link=hF;exports.LoadingDots=dd;exports.Lock=kk;exports.MAX_SELF_HEAL_ATTEMPTS=q0t;exports.Map=Sq;exports.Markdown=bue;exports.Maximize2=_k;exports.MdStackedLineChart=ode;exports.Minimize2=pF;exports.MultiInputEmptyRenderer=U5;exports.PYTHON_DEFAULT_CODE=tF;exports.PanelLeft=mF;exports.PanelResizeHandle=qk;exports.Paperclip=Nq;exports.PenLine=L2;exports.Pencil=$2;exports.PendingMessagesDisplay=Rfe;exports.PersistedDynamicVisual=Nj;exports.PiChartPolar=tde;exports.PivotTableTanstack=rb;exports.Placeholders=ude;exports.Play=kq;exports.Plus=dr;exports.PointerSensor=cb;exports.PrintMessages=cde;exports.Progress=J3;exports.RECOVERABLE_SQL_ERROR_CODES=G0t;exports.Radar=_q;exports.RadioGroup=Ia;exports.RadioGroupItem=js;exports.RefreshCw=Oc;exports.ResizableHandle=uK;exports.ResizablePanel=Ry;exports.ResizablePanelGroup=UF;exports.ResourceEditDialog=LG;exports.ResourceType=Xr;exports.SELF_HEAL_TIMELINE_STEP=Y0t;exports.Search=Ws;exports.SeedQuestions=Efe;exports.SemaphorContext=pg;exports.SemaphorContextProvider=lF;exports.SemaphorQueryClient=qW;exports.SemaphorReadyIndicator=m$;exports.SemaphorStyleWrapper=sb;exports.Send=bF;exports.Settings=xF;exports.Settings2=bg;exports.Share2=jq;exports.ShareDialog=OG;exports.Sheet=Aee;exports.SheetContent=BO;exports.SheetDescription=HO;exports.SheetHeader=Fee;exports.SheetTitle=VO;exports.SheetTrigger=DOe;exports.Slider=uhe;exports.SortableContext=iw;exports.Sparkles=Fm;exports.Square=Eq;exports.SquarePen=jk;exports.Star=yF;exports.StructuralParticipantSelector=Ole;exports.SummaryCard=sR;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ui;exports.TableBody=xh;exports.TableCell=sr;exports.TableColumnVisibilitySettings=bce;exports.TableHead=Ko;exports.TableHeader=Fg;exports.TablePresentationSettings=yce;exports.TableRow=Kr;exports.TableSkeleton=$L;exports.TableVisual=ud;exports.TbChartBubble=nde;exports.TbChartFunnel=rde;exports.TbChartTreemap=sde;exports.TextCard=og;exports.Textarea=Bh;exports.TiSortNumerically=ide;exports.Toggle=wj;exports.Tornado=Dq;exports.Trash2=yl;exports.TreePalm=wF;exports.TrendingUp=Iq;exports.TriangleAlert=ba;exports.TypeGlyph=Qv;exports.UXProvider=p$;exports.User=Mq;exports.UserRound=Tq;exports.Users=SF;exports.applyFilterOverridesToDashboardInputSlots=BZ;exports.areContextEntitiesEqual=zr;exports.areEntitiesJoined=JJ;exports.arrayMove=ub;exports.buildCardControlUsageById=Btt;exports.buildCustomCardTheme=Yv;exports.buildDashboardCardExecutionSnapshot=zZ;exports.buildDashboardControlUsageById=ztt;exports.buildDashboardExecutionSnapshot=RP;exports.buildDashboardInputExecutionSnapshot=Wu;exports.buildDashboardSheetsInputExecutionSnapshot=HZ;exports.buildDashboardStructuralParticipantIdsByControlId=Ule;exports.buildFilterFieldMeta=n3;exports.buildFilterSemanticContext=r3;exports.buildInlineFilterNodes=xL;exports.buildMultiInputCustomVisualProps=NL;exports.buildScheduleExpr=xvt;exports.buildSchedulePreview=wvt;exports.buildSlotOrderedCards=vL;exports.calculateContextAwareFilters=dv;exports.calculateFieldState=MO;exports.canUserAccessVisuals=bKe;exports.canUserCreateDashboards=gKe;exports.canUserEdit=hKe;exports.canUserManageDashboards=mKe;exports.canUserManageGroups=xKe;exports.canUserUseFilters=pKe;exports.cancelExport=bPe;exports.chartSupportsDataLabels=WQ;exports.chartSupportsLegend=HQ;exports.chartTypes=iE;exports.cleanupKpiMetricComparisonMode=Yae;exports.cloneDeep=Zo;exports.cloneLinkedFrameWithSourceMapping=LGe;exports.closestCenter=nw;exports.commitSharedCalculatedFields=af;exports.createAssistantConversationId=qp;exports.createAssistantRequestId=_fe;exports.createCardsFromSlots=eYe;exports.createChartConfig=Ag;exports.createDashboardControlInputFromControl=Pst;exports.createDefaultGlobalDateFilter=ZCe;exports.createExport=yee;exports.createUniqueDashboardInputVariableNameFromName=Ju;exports.dedup=Jxt;exports.doesStoredFilterMatchField=ug;exports.downloadDocumentPdf=PP;exports.downloadPdf=XZ;exports.extractSqlParamReferences=Yse;exports.extractTableMetadata=t3;exports.fieldAlreadyExists=tee;exports.findCustomVisualConfigCard=SL;exports.findDashboardFrameById=BCe;exports.flexRender=Qo;exports.formatDisplayFormula=AJe;exports.formatFileSize=vPe;exports.formatFilterLine=CX;exports.formatTimeLabel=fhe;exports.getAutoDetectedChartIcon=Wft;exports.getChartGridStyle=v_e;exports.getChartIconByType=qft;exports.getColorForValue=uM;exports.getConfigSlotExpectedType=Jqe;exports.getCoreRowModel=O_;exports.getCustomVisualInputCards=wL;exports.getDateFormatOptionsForGranularity=j0;exports.getDefaultAxisConfig=fM;exports.getDefaultChartColors=qh;exports.getDefaultDataLabelsConfig=Cv;exports.getDefaultExportFormat=zX;exports.getDefaultFilterSql=tL;exports.getDefaultLegendConfig=mO;exports.getDefaultRunningTotalPartitionByFieldIds=vy;exports.getDocumentSectionEditorCard=xtt;exports.getDocumentSheetDashboardInputs=dw;exports.getDownloadUrl=gPe;exports.getEffectiveCardTypeForSlot=pm;exports.getEntityIcon=xk;exports.getErrorMessage=xfe;exports.getExportStatus=mPe;exports.getExports=pPe;exports.getExpressionFieldKind=bd;exports.getFieldExpressionAnnotation=s3;exports.getFilterCount=VN;exports.getGlobalDateFilter=wg;exports.getGlobalDateFilterCoverage=XCe;exports.getGranularityOptionsForFieldType=S3;exports.getKeys=pr;exports.getMetricDisplayLabel=PFe;exports.getNewField=iee;exports.getObjectDiff=_W;exports.getPaginationRowModel=L_;exports.getRoleBasedDisplayOverrides=Rie;exports.getRunningTotalOrderByCandidates=nJe;exports.getSelectedDateFilterColumn=Kse;exports.getSheetScopedFilterValues=Ly;exports.getSlotDefinitionForIndex=yL;exports.getSlotExpectedChartType=yj;exports.getSlotIndexForCard=y0;exports.getSortedRowModel=Mee;exports.getSupportedExportFormats=$X;exports.getTableConditionalFormattingColumnOptions=Cce;exports.getTableOutputColumnOptions=Nce;exports.getTablePageSizeOptions=gee;exports.handleAggregationChange=lR;exports.handleAggregationLabelChange=Mie;exports.hasFlatTableTotalsBehavior=WNe;exports.horizontalListSortingStrategy=qL;exports.isCalculatedFilterField=E0;exports.isCardSummaryVisibleOnCard=kL;exports.isCustomVisualConfigCard=nR;exports.isDefaultColor=eke;exports.isEligibleFlatTableTotalsCard=Sg;exports.isExportComplete=yPe;exports.isExportInProgress=xPe;exports.isInAiScopeArray=Qxt;exports.isManagedCalculatedExpressionField=ka;exports.isMetricTransformEnabled=eJe;exports.isPromiseLike=KR;exports.isSubtotalEnabledAggregateTable=e3;exports.isSupportedDocumentTableCardType=ytt;exports.lastAssistantMessageIsCompleteWithToolCalls=pfe;exports.merge=xl;exports.mergeAxisConfig=hM;exports.normalizeConditionalFormatting=jP;exports.normalizeContextFormatMode=DX;exports.normalizeDashboardInputVariableName=J0;exports.normalizeMultiInputPayload=CL;exports.parseScheduleExpr=bvt;exports.pivotData=gv;exports.prepareFeedbackData=oE;exports.purify=PA;exports.reindexSlotCards=Qqe;exports.remarkGfm=Bue;exports.removeFromScopeArray=eyt;exports.resolveDashboardInputContext=$l;exports.resolveDomainCalculatedFieldForEdit=Iet;exports.resolveMultiInputType=Gv;exports.resolveMultiInputTypeFromVisual=tYe;exports.resolveTablePageSize=R_;exports.resolveTablePresentationStyle=JO;exports.sanitizeAIScope=bfe;exports.saveCalculatedFieldToCardScope=vR;exports.saveCalculatedFieldToSharedScope=vle;exports.saveCalculatedFieldToSheetScope=wR;exports.seedSemanticMetricFormatDefaults=Kae;exports.setTableColumnVisibility=See;exports.setupEditorWithCard=h_;exports.showAllTableColumns=NPe;exports.showJoinRequiredNotification=eee;exports.sortByColumnsToSortState=tte;exports.sortStateToSortByColumns=nte;exports.sortableKeyboardCoordinates=GL;exports.supportsMetricTransformForMetric=Gae;exports.supportsTableConditionalFormatting=vce;exports.toEntityArray=Na;exports.ue=ut;exports.useActiveExports=awe;exports.useActiveToolStatus=Lfe;exports.useAddFrameWithFreshSemanticExecutionPayload=OL;exports.useAddNewFrame=tae;exports.useAssistantContainer=bK;exports.useAssistantContextEntities=jj;exports.useAssistantLayoutStore=Hf;exports.useAssistantPanel=mK;exports.useAssistantProfile=jfe;exports.useAutoScroll=Pfe;exports.useAutoSubmitQueue=Ffe;exports.useBrandStudioPreview=f0t;exports.useCard=GFe;exports.useCardFilterValues=lee;exports.useCardSummary=_L;exports.useChat=gfe;exports.useColumns=XL;exports.useCreateVisualWithFrame=Ybe;exports.useCurrentUserInfo=ta;exports.useCustomVisual=Qh;exports.useCustomVisualsQuery=mL;exports.useDashboardAppearance=Rl;exports.useDashboardById=LY;exports.useDashboardCreation=BY;exports.useDashboardManagement=zY;exports.useDashboardPreferences=xg;exports.useDashboardQuery=Q0;exports.useDashboardStructuralParticipants=Wle;exports.useDashboardSummary=pie;exports.useDataColumns=Xae;exports.useDateFilterHook=M7e;exports.useDebounce=py;exports.useDefaultDashboardMutation=MY;exports.useDisplayPreferences=Ll;exports.useDroppable=Nae;exports.useEditorAside=Bj;exports.useEditorCardQuery=f_;exports.useEnsureReactGlobals=Sse;exports.useExportActions=xK;exports.useExportStore=Yk;exports.useFieldManagement=Zae;exports.useFilterableFields=Uae;exports.useFullscreenAssistant=gK;exports.useGroupMembers=Vxe;exports.useGroups=DG;exports.useHasDashboardId=yK;exports.useInProgressExportsCount=lwe;exports.useIsDashboardSelected=Rpe;exports.useIsVisualSelected=Fpe;exports.useJoinabilityMap=JL;exports.useManagementActions=Ph;exports.useManagementStore=is;exports.useMessageWindow=Ofe;exports.useMutation=co;exports.usePivotTableConfig=Gh;exports.usePluginQuery=eie;exports.useQuery=On;exports.useQueryClient=ns;exports.useReactTable=$_;exports.useResolveExistingFrameSemanticExecutionPayload=VGe;exports.useResourceManagement=Rk;exports.useResourceUpdateState=$Y;exports.useScopedFields=Hae;exports.useSelectedVisual=Ape;exports.useSemaphorContext=Ct;exports.useSensor=cg;exports.useSensors=Tj;exports.useSortable=db;exports.useStarredChartsStore=X0t;exports.useSurfaceAppearance=Zc;exports.useTableQueryState=qee;exports.useTextFilterHook=H7e;exports.useTheme=nF;exports.useTopoJson=kv;exports.useUnifiedUsers=OF;exports.useUpdateResource=RY;exports.useUpdateVisualMutation=Gbe;exports.useUserPreferences=lG;exports.useVisualById=Ak;exports.useVisualManagement=qbe;exports.validateFieldForChartType=qae;exports.verticalListSortingStrategy=YL;
1425
+ `)}})}});var Axt=_bt(()=>sfe(ea([Or({type:yn("text-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("error"),errorText:Ut()}),Or({type:yn("tool-input-start"),toolCallId:Ut(),toolName:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-delta"),toolCallId:Ut(),inputTextDelta:Ut()}),Or({type:yn("tool-input-available"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-error"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional(),errorText:Ut()}),Or({type:yn("tool-output-available"),toolCallId:Ut(),output:Qa(),providerExecuted:Uo().optional(),dynamic:Uo().optional(),preliminary:Uo().optional()}),Or({type:yn("tool-output-error"),toolCallId:Ut(),errorText:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("reasoning-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("source-url"),sourceId:Ut(),url:Ut(),title:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("source-document"),sourceId:Ut(),mediaType:Ut(),title:Ut(),filename:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("file"),url:Ut(),mediaType:Ut(),providerMetadata:Jr.optional()}),Or({type:Jde(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Ut().optional(),data:Qa(),transient:Uo().optional()}),Or({type:yn("start-step")}),Or({type:yn("finish-step")}),Or({type:yn("start"),messageId:Ut().optional(),messageMetadata:Qa().optional()}),Or({type:yn("finish"),finishReason:Zde(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Qa().optional()}),Or({type:yn("abort")}),Or({type:yn("message-metadata"),messageMetadata:Qa()})])));function Rxt(e){return e.type.startsWith("data-")}function ffe(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=ffe(o,s):n[r]=s}return n}function Fxt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function hfe(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await bk({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await bk({text:Fxt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function aC(e){return e.type.startsWith("tool-")}function Pxt(e){return e.type==="dynamic-tool"}function qR(e){return aC(e)||Pxt(e)}function XU(e){return e.type.split("-").slice(1).join("-")}function Oxt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Lxt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,p,g;function b(C){const k=u.message.parts.filter(aC).find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function x(C){const k=u.message.parts.filter(_=>_.type==="dynamic-tool").find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function y(C){var N;const k=u.message.parts.find(D=>aC(D)&&D.toolCallId===C.toolCallId),_=C,E=k;k!=null?(k.state=C.state,E.input=_.input,E.output=_.output,E.errorText=_.errorText,E.rawInput=_.rawInput,E.preliminary=_.preliminary,E.providerExecuted=(N=_.providerExecuted)!=null?N:k.providerExecuted,_.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=_.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null?{callProviderMetadata:_.providerMetadata}:{}})}function S(C){var N,k;const _=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===C.toolCallId),E=C,D=_;_!=null?(_.state=C.state,D.toolName=C.toolName,D.input=E.input,D.output=E.output,D.errorText=E.errorText,D.rawInput=(N=E.rawInput)!=null?N:D.rawInput,D.preliminary=E.preliminary,D.providerExecuted=(k=E.providerExecuted)!=null?k:_.providerExecuted,E.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?ffe(u.message.metadata,C):C;t!=null&&await qU({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(g=a.providerMetadata)!=null?g:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(aC);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await hfe(C.text);C.dynamic?S({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await w(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Rxt(a)){(n==null?void 0:n[a.type])!=null&&await qU({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(k=>C.type===k.type&&C.id===k.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function $xt({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}xw({prefix:"aitxt",size:24});xw({prefix:"aiobj",size:24});var zxt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};xw({prefix:"aiobj",size:24});var Bxt={};Cxt(Bxt,{object:()=>Hxt,text:()=>Vxt});var Vxt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Hxt=({schema:e})=>{const t=wxt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await hfe(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await bk({text:n});if(!s.success)throw new KU({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await a$({value:s.value,schema:t});if(!o.success)throw new KU({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Uxt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Wxt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Ip(this.body),c=await Ip(this.headers),u=await Ip(this.credentials),d={...cf(c),...cf(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,p=(f==null?void 0:f.headers)!==void 0?cf(f.headers):d,g=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},b=(s=f==null?void 0:f.credentials)!=null?s:u,y=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:UU({"Content-Type":"application/json",...p},`ai-sdk/${ZU}`,HU()),body:JSON.stringify(g),credentials:b,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Ip(this.body),a=await Ip(this.headers),c=await Ip(this.credentials),u={...cf(a),...cf(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?cf(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:c,b=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:UU(h,`ai-sdk/${ZU}`,HU()),credentials:p});if(b.status===204)return null;if(!b.ok)throw new Error((o=await b.text())!=null?o:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},c$=class extends Wxt{constructor(e={}){super(e)}processResponseStream(e){return Dbt({stream:e,schema:Axt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},qxt=class{constructor({generateId:e=ybt,id:t=e(),transport:n=new c$,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new zxt,this.sendMessage=async(f,h)=>{var p,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await Uxt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const S=this.state.messages.findIndex(w=>w.id===f.messageId);if(S===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[S].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,S+1),this.state.replaceMessage(S,{...y,id:f.messageId,role:(g=y.role)!=null?g:"user",metadata:f.metadata})}else this.state.pushMessage({...y,id:(b=y.id)!=null?b:this.generateId(),role:(x=y.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:p,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const S=this.state.messages,w=S[S.length-1];this.state.replaceMessage(S.length-1,{...w,parts:w.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:Oxt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}g=x}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const b=x=>this.jobExecutor.run(()=>x({state:p.state,write:()=>{var y;this.setStatus({status:"streaming"}),p.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $xt({stream:Lxt({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:b,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function pfe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(qR).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Yxt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Gxt=Yxt;const Kxt=m.getDefaultExportFromCjs(Gxt);var mfe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},jr=(e,t,n)=>(mfe(e,t,"read from private field"),n?n.call(e):t.get(e)),qa=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},gu=(e,t,n,r)=>(mfe(e,t,"write to private field"),t.set(e,n),n);function Zxt(e,t){return t!=null?Kxt(e,t):e}var Ai,lC,cC,Hx,Ux,Wx,Up,YR,GR,Xxt=class{constructor(e=[]){qa(this,Ai,void 0),qa(this,lC,"ready"),qa(this,cC,void 0),qa(this,Hx,new Set),qa(this,Ux,new Set),qa(this,Wx,new Set),this.pushMessage=t=>{gu(this,Ai,jr(this,Ai).concat(t)),jr(this,Up).call(this)},this.popMessage=()=>{gu(this,Ai,jr(this,Ai).slice(0,-1)),jr(this,Up).call(this)},this.replaceMessage=(t,n)=>{gu(this,Ai,[...jr(this,Ai).slice(0,t),this.snapshot(n),...jr(this,Ai).slice(t+1)]),jr(this,Up).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Zxt(t,n):t;return jr(this,Hx).add(r),()=>{jr(this,Hx).delete(r)}},this["~registerStatusCallback"]=t=>(jr(this,Ux).add(t),()=>{jr(this,Ux).delete(t)}),this["~registerErrorCallback"]=t=>(jr(this,Wx).add(t),()=>{jr(this,Wx).delete(t)}),qa(this,Up,()=>{jr(this,Hx).forEach(t=>t())}),qa(this,YR,()=>{jr(this,Ux).forEach(t=>t())}),qa(this,GR,()=>{jr(this,Wx).forEach(t=>t())}),gu(this,Ai,e)}get status(){return jr(this,lC)}set status(e){gu(this,lC,e),jr(this,YR).call(this)}get error(){return jr(this,cC)}set error(e){gu(this,cC,e),jr(this,GR).call(this)}get messages(){return jr(this,Ai)}set messages(e){gu(this,Ai,[...e]),jr(this,Up).call(this)}};Ai=new WeakMap;lC=new WeakMap;cC=new WeakMap;Hx=new WeakMap;Ux=new WeakMap;Wx=new WeakMap;Up=new WeakMap;YR=new WeakMap;GR=new WeakMap;var Wp,QU=class extends qxt{constructor({messages:e,...t}){const n=new Xxt(e);super({...t,state:n}),qa(this,Wp,void 0),this["~registerMessagesCallback"]=(r,s)=>jr(this,Wp)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>jr(this,Wp)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>jr(this,Wp)["~registerErrorCallback"](r),gu(this,Wp,n)}};Wp=new WeakMap;function gfe({experimental_throttle:e,resume:t=!1,...n}={}){const r=v.useRef("chat"in n?n.chat:new QU(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new QU(n));const o="id"in n?n.id:null,i=v.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=v.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=v.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=v.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=v.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return v.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Qxt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Jxt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eyt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tyt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function bfe(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:tyt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function xfe(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function uE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function yfe(e,t,n){const r=uE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>_j(o)).filter(o=>o!==void 0).map(s)}function vfe(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function nyt(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function nm(e){return(e||[]).map(nyt)}function wfe(e){return nm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function u$(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function ryt(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...u$(s)}})}function syt(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...u$(t)}))}function Sfe(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function l2(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>Sfe(s,`${t}:${r}:${o}`)))}function oyt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function iyt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function ayt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(iyt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...u$(r)})),n=e.filter(oyt).map((r,s)=>Sfe(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function lyt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=m.getClickFiltersForCardFromStates(e.id,t),s=t[m.DRILL_CONTEXT_CARD_ID],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>l2(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>l2(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>l2(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Cfe(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>Cfe(t)).filter(Boolean)}:null}function Nfe(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==tF.trim()}function cyt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":Nfe(e)?"custom-python":"config"}function kfe({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=uE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=fv({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=dv({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=ayt(n==null?void 0:n.filters),p=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:p?h.dashboardFilterValues:ryt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:syt(a==null?void 0:a[t.id]),interactionFilterValues:p?h.interactionFilterValues:lyt({card:t,interactionStates:i,currentDashboardId:r.id})}}function uyt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=kfe({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:nm(c.metricColumns),dimensions:wfe(c),selectedEntities:vfe(t)}}function dyt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function JU({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=uE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:Ly(e.filters,n,r)}}function fyt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=uE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=yfe(e,t.selectedSheetId,s),c=Nd(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>uyt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:dyt({activeFilters:t.activeFilters})}}function hyt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var w,C;const c=yfe(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:p,inlineFilterValues:g,interactionFilterValues:b}=kfe({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:x,targetValue:y}=_Ye(h,d.type),S=cyt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:S,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...Nfe(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:vfe(d),metrics:nm(h.metricColumns),dimensions:wfe(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Cfe(h.filters),effectiveDashboardFilters:p,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:nm(h.groupByColumns),pivotBy:nm(h.pivotByColumns),sortBy:nm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...S==="custom-sql"?["This card runs custom SQL."]:S==="custom-python"?["This card runs custom Python."]:[]]}}function qp(){return crypto.randomUUID()}function _fe(){return crypto.randomUUID()}function KR(e){return typeof(e==null?void 0:e.then)=="function"}async function pyt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Xr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>m.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=Yie(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function myt({dynamicVisualMode:e="auto"}={}){var R;const{compiledAppearance:t}=m.useAppearance(),n=v.useMemo(()=>PL(t),[t]),r=v.useRef(n);v.useEffect(()=>{r.current=n},[n]);const{authToken:s,tokenProps:o}=Ct(),i=ns(),a=m.useDashboardStore(B=>B.dashboard.aiScopeTables),c=(R=Q0().data)==null?void 0:R.assistantProfileId,u=v.useRef(null),d=v.useRef(qp()),f=v.useRef(!1),h=v.useRef(!1),p=v.useRef(e);p.current=e;function g(){const B=m.useAIInteractionStore.getState(),z=m.useDashboardStore.getState(),U=Jie({overrides:B.dashboardEntitySelectionOverrides,dashboardId:z.dashboard.id,draftScopeKey:z.dashboardAssistantDraftScopeKey});return m.appendQualifiedEntityNameToAIContext(BKe({currentAIContext:B.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:z.dashboard.aiContext,derivedSelectedSheetEntities:Qie(z.dashboard,z.selectedSheetId)}))}function b(){const B=m.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:JU({dashboard:B.dashboard,selectedSheetId:B.selectedSheetId,activeFilters:B.filterValues})}}const{sendMessage:x,messages:y,setMessages:S,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:E}=gfe({transport:new c$({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${s==null?void 0:s.accessToken}`}),body:()=>{const B=m.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:z,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:c,conversationId:d.current,assistantRequestId:_fe(),aiContext:z,dashboardViewState:U,dynamicVisualMode:p.current,dynamicVisualTheme:r.current,reasoningEffort:B.reasoningEffort,showReasoning:B.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:B,body:z})=>({body:{...z,messages:m.cleanupIncompleteMessages(B)}})}),onToolCall:T,sendAutomaticallyWhen:pfe,onFinish({message:B,isAbort:z,isDisconnect:U,isError:Y}){var O;h.current=!1,B!=null&&B.id&&((O=u.current)!=null&&O.aiContext)&&m.useAIInteractionStore.getState().actions.setAssistantMessageContext(B.id,u.current.aiContext),console.log(z?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":Y?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))},onError(B){var z;if(h.current=!1,B.name==="AbortError"||(z=B.message)!=null&&z.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]));return}console.error("[Dashboard Assistant] Stream error:",B),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))}}),D=v.useCallback((...B)=>{h.current=!0;try{const z=x(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[x]),j=v.useCallback((...B)=>{h.current=!0;try{const z=w(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[w]),I=B=>{let z=!1;S(U=>{const Y=typeof B=="function"?B(U):B;if(Y.length===0){if(h.current)return f.current=!0,z=!0,U;f.current=!1,d.current=qp()}return Y}),z&&_()};async function T({toolCall:B}){var M,G;if(B.toolName==="getCurrentTableScope"){N({tool:B.toolName,toolCallId:B.toolCallId,output:{tables:bfe(a||[])}});return}const z=m.useDashboardStore.getState().dashboard,U=m.useDashboardStore.getState().inlineFilterValuesMap,Y=m.useInteractionStore.getState(),O=Y.interactionStates,K=await pyt({replacedCards:Y.replacedCards,apiServiceUrl:o.apiServiceUrl,accessToken:(s==null?void 0:s.accessToken)||"",queryClient:i}),q=JU({dashboard:z,selectedSheetId:m.useDashboardStore.getState().selectedSheetId,activeFilters:m.useDashboardStore.getState().filterValues});if(B.toolName==="getDashboardSynopsis"){N({tool:B.toolName,toolCallId:B.toolCallId,output:fyt({dashboard:z,viewState:q,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})});return}if(B.toolName==="getCardContext"){const L=((M=B.input)==null?void 0:M.cardId)||((G=B.args)==null?void 0:G.cardId)||"";N({tool:B.toolName,toolCallId:B.toolCallId,output:hyt({dashboard:z,viewState:q,cardId:L,runtimeFilterValues:m.useDashboardStore.getState().filterValues,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),P=xfe(k);return{sendMessage:D,regenerate:j,isLoading:F,messages:y,setMessages:I,status:C,stop:_,errorMessage:P,clearError:E}}function jfe(){var u;const{authToken:e,tokenProps:t}=Ct(),n=(u=Q0().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=On({queryKey:["assistant-profile",n],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Efe({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(pq,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function gyt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=v.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ic-n;if(c.length>u){ut.error(`You can only attach ${ic} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=que(c);if(f.forEach(({file:h,error:p})=>{ut.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>Z3(p)));e(h)}catch(h){console.error("Failed to process files:",h),ut.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ic}),l.jsx(m.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ic,title:n>=ic?`Maximum ${ic} files allowed`:"Attach files",children:l.jsx(Nq,{className:"h-4 w-4 text-muted-foreground"})})]})}function byt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=v.useState(!1),a=v.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=v.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,g=f.clientY;(p<h.left||p>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=v.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=v.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=ic-r;if(h.length>p){ut.error(`You can only attach ${ic} files per message. You have ${p} slot(s) remaining.`);return}const{valid:g,errors:b}=que(h);if(b.forEach(({file:x,error:y})=>{ut.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>Z3(y)));t(x),ut.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),ut.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:m.cn("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-control border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(m.Upload,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ic-r," slot(s) available"]})]})})]})}function xyt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function yyt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!xyt(e,t,n):r}function Dfe(e){const{tokenProps:t}=Ct(),n=m.useDashboardStore(c=>c.authToken)||e;m.useEditorStore(c=>c.selectedConnectionId),m.useEditorStore(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=On({queryKey:["semantic-domains"],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function vyt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:s}){const{semanticDomains:o,isSemanticDomainsLoading:i}=Dfe(),a=v.useMemo(()=>Syt(o,e),[o,e]),c=v.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&c.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(c.length===0)return null;const u=!!n;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Semantic Domains"}),c.map(d=>l.jsx(wyt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:s},d.id))]})}function wyt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){const[o,i]=v.useState(!1),a=o||t.length>0||!!n,{datasets:c,isPending:u}=nNe(a?e.id:void 0),d=v.useMemo(()=>{if(!t)return c;const x=t.trim().toLowerCase();return c.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[c,t]),f=t.length>0&&d.length>0,h=o||f||!!n,p=c.length,g=v.useMemo(()=>d.filter(x=>r.some(y=>zr(y,c2(x)))).length,[d,r]),b=x=>{const y=c2(x),S=r.some(w=>zr(w,y));s(S?r.filter(w=>!zr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"flex w-full items-center gap-1.5 rounded-[4px] px-3 py-1.5 text-left transition-colors hover:bg-muted/50",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),p>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",p," dataset",p===1?"":"s"," · curated"]}),l.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&l.jsx("ul",{className:"space-y-px pb-1",children:u&&c.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=c2(x),S=r.some(w=>zr(w,y));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:S,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),l.jsx(ei,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:x.type==="virtual"?"virtual":"dataset"})]}),x.description&&l.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ife({label:e}){return l.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function Syt(e,t){if(!t||t.mode==="all")return e;const n=new Set(t.domainIds??[]);return t.mode==="include"?e.filter(r=>n.has(r.id)):t.mode==="exclude"?e.filter(r=>!n.has(r.id)):[]}function c2(e){return{id:e.id,datasetType:e.type,name:e.name||e.table,label:e.label,domainId:e.domainId,description:e.description,database:e.database,schema:e.schema,table:e.table,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function Cyt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:s,isConnectionsLoading:o}=Xc(),i=v.useMemo(()=>t?s.filter(c=>c.id===t):s,[s,t]);if(o&&i.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading connections…"});if(i.length===0)return null;const a=!!t;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Direct Sources"}),i.map(c=>l.jsx(Nyt,{connection:c,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},c.id))]})}function Nyt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){var g;const[o,i]=v.useState(!1),a=o||t.length>0||!!n,c=((g=e.capabilities)==null?void 0:g.path)??[],u=c.includes("database"),d=c.includes("schema"),f=e.type==="upload",h=e.type==="url",p=v.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return l.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>i(b=>!b),className:"flex w-full items-center gap-2 px-4 py-1.5 text-left transition-colors hover:bg-muted/40",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),l.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),l.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:p>0?p:""})]}),a&&l.jsxs(l.Fragment,{children:[f?l.jsx(kyt,{connection:e,selectedEntities:r,onSelectionChange:s}):h?l.jsx(_yt,{connection:e,selectedEntities:r,onSelectionChange:s}):u?l.jsx(jyt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:s}):d?l.jsx(Tfe,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:s}),!f&&!h&&l.jsx(Eyt,{connection:e,search:t,selectedEntities:r,onSelectionChange:s})]})]})}function kyt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,s=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),o=a=>{if(!(a!=null&&a.length))return;const c=Array.from(a).map(u=>({id:`file-${Date.now()}-${Math.random()}`,name:u.name,type:"upload",connectionId:e.id,connectionType:e.type,label:u.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:u.name,file:u}));n([...t,...c])},i=a=>{n(t.filter(c=>!("id"in c&&c.id===a&&c.connectionId===e.id&&(c.type==="upload"||c.type==="file"))))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[l.jsx(m.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),l.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>o(a.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(m.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2 h-7 text-[12px]",onClick:()=>{var a;return(a=document.getElementById(r))==null?void 0:a.click()},children:"Select files"})]}),s.length>0&&l.jsx("ul",{className:"space-y-1",children:s.map(a=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(vi,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),l.jsx("button",{type:"button","aria-label":`Remove ${a.originalName||a.name}`,onClick:()=>i(a.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},a.id))})]})}function _yt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,s]=v.useState(""),[o,i]=v.useState(""),[a,c]=v.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),p=o.trim();if(!h||!p)return;const g={id:`url-${Date.now()}-${Math.random()}`,name:h,type:"url",connectionId:e.id,connectionType:e.type,label:h,description:`URL source of type ${a}`,originalName:h,url:p,sourceType:a};n([...t,g]),s(""),i(""),c("api")},f=h=>{n(t.filter(p=>!("id"in p&&p.id===h&&p.connectionId===e.id&&p.type==="url")))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[l.jsx(m.Input,{value:r,onChange:h=>s(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),l.jsx(m.Input,{value:o,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("select",{value:a,onChange:h=>c(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[l.jsx("option",{value:"api",children:"API endpoint"}),l.jsx("option",{value:"csv",children:"CSV file"}),l.jsx("option",{value:"json",children:"JSON file"})]}),l.jsxs(m.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!o.trim(),onClick:d,children:[l.jsx(dr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&l.jsx("ul",{className:"space-y-1",children:u.map(h=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(gg,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"truncate text-[12px]",children:h.name}),l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),l.jsx("button",{type:"button","aria-label":`Remove ${h.name}`,onClick:()=>f(h.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},h.id))})]})}function jyt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/databases",{connection_id:e.id},["databases",e.id]);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=o.data)==null?void 0:a.databases)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?l.jsx(Tfe,{connection:e,databaseName:c.database_name,search:n,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:c.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:s}))},c.database_name))})}function Tfe({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=o.data)==null?void 0:a.schemas)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&l.jsx(d$,{connection:e,databaseName:t,schemaName:c.schema_name,search:n,selectedEntities:r,onSelectionChange:s})},c.schema_name))})}function d$({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:s,onSelectionChange:o}){const i=dE("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=v.useMemo(()=>{var f;const u=((f=i.data)==null?void 0:f.tables)??[];if(!r)return u;const d=r.trim().toLowerCase();return u.filter(h=>h.table_name.toLowerCase().includes(d))},[i.data,r]);if(i.isLoading)return l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const c=(u,d)=>{const f={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u,dbObjectType:d==null?void 0:d.toLowerCase()},h=s.some(p=>zr(p,f));o(h?s.filter(p=>!zr(p,f)):[...s,f])};return l.jsx("ul",{children:a.map(u=>{var h;const d={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u.table_name,dbObjectType:(h=u.table_type)==null?void 0:h.toLowerCase()},f=s.some(p=>zr(p,d));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:f,onCheckedChange:()=>c(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),l.jsx(m.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:u.table_type??"table"})]})]})},u.table_name)})})}function Eyt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const s=dE("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),o=v.useMemo(()=>{var u;const a=((u=s.data)==null?void 0:u.datamodels)??[];if(!t)return a;const c=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(c))},[s.data,t]);if(s.isLoading||o.length===0)return null;const i=a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));r(u?n.filter(d=>!zr(d,c)):[...n,c])};return l.jsxs("div",{children:[l.jsx("div",{className:"px-8 pb-1 pt-2",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),l.jsx("ul",{children:o.map(a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),l.jsx(sme,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&l.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Mfe({label:e,indentLevel:t,search:n,renderChildren:r}){const[s,o]=v.useState(!1),i=s||n.length>0,a=t===1?"pl-8":"pl-10";return l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:m.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[l.jsx(Mr,{className:m.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function dE(e,t,n,r=!0){const{tokenProps:s}=Ct(),o=m.useDashboardStore(a=>a.authToken),i=v.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return On({queryKey:n,queryFn:()=>m.getRequest(`${s.apiServiceUrl}${e}`,(o==null?void 0:o.accessToken)||"",i),enabled:r&&!!(o!=null&&o.accessToken)&&Object.values(i).every(a=>a.length>0)})}function eW(e){return e.type==="dataset"&&e.label||e.name}function Dyt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-input bg-muted/50 py-0.5 pl-1.5 pr-0.5 text-[11px] text-foreground/80",children:[l.jsx("span",{className:"max-w-[180px] truncate",children:eW(n)}),l.jsx("button",{type:"button",onClick:s=>{s.stopPropagation(),t(n)},"aria-label":`Remove ${eW(n)}`,className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function tW(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function u2(e){if(e!=null&&e.length)return e.every(t=>t.type==="dataset")?"semanticDomain":e.every(t=>t.type==="url")?"url":e.every(t=>t.type==="upload"||t.type==="file")?"upload":"database"}function f$({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var ue,ve;const{tokenProps:a}=Ct(),c=a.config,u=a.semanticDomainAccess||bhe.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=v.useState([]),[h,p]=v.useState(void 0),[g,b]=v.useState(""),[x,y]=v.useState("all"),[S,w]=v.useState(void 0),C=v.useRef(!1),{updateDataSource:N}=m.useEditorActions(),k=m.useDashboardStore(xe=>xe.isVisualEditing),_=m.useDashboardStore(xe=>xe.dashboard.aiContext),{setAiContext:E}=m.useDashboardActions(),D=u.mode,j=(c==null?void 0:c.showDirectSource)!==!1,I=D==="include"||D==="exclude"||!j,T=D!=="all",F=j&&!I,P=I?"semanticDomain":n.mode,R=r==="dataSource"&&!j,B=D==="include"&&(((ue=u.domainIds)==null?void 0:ue.length)||0)===1?(ve=u.domainIds)==null?void 0:ve[0]:void 0,z=v.useCallback(xe=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:xe,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...xe!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=v.useCallback(xe=>{N({...n,...xe})},[n,N]),Y=v.useCallback(xe=>{if(r==="aiContext"){"semanticDomainId"in xe&&p(xe.semanticDomainId);return}U(xe)},[r,U]),O=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},v.useEffect(()=>{if(r==="aiContext"&&!e)return;if(I&&n.mode!=="semanticDomain"&&r==="dataSource"){z("semanticDomain");return}if(!T||P!=="semanticDomain")return;const xe=O,ke=u.domainIds??[],se=r==="aiContext"?d:n.selectedEntities,be=((se==null?void 0:se.length)??0)>0,Ce=((d==null?void 0:d.length)??0)>0;yyt({mode:D,currentDomainId:xe,scopedDomainIds:ke,hasSelectedEntities:be})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):p(void 0),Ce&&f([]))},[I,T,P,n.mode,O,n.selectedEntities,r,h,d,e,u.domainIds,D,j,U,z]),v.useEffect(()=>{B&&!O&&Y({semanticDomainId:B})},[B,O,Y]),v.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(I?"semantic":"all");return}if(C.current)return;f([...s||[]]);const xe=r==="aiContext"?tW(s):void 0;p(n.semanticDomainId||xe),w(u2(s))},[e,r,s,n.semanticDomainId,I]);const K=xe=>{C.current=!0,f(d.filter(ke=>!zr(ke,xe)))},q=v.useCallback((xe,ke)=>{C.current=!0,f(xe),w(ke??u2(xe))},[]),M=()=>{var ke,se;if(r==="aiContext"){if(k&&N(n),i){const be={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};E(be)}o==null||o(d),t(!1);return}const xe=u2(d)??S??P;if(xe==="semanticDomain"){const be=tW(d)||h||n.semanticDomainId,Ce=((ke=d==null?void 0:d[0])==null?void 0:ke.connectionId)||n.connectionId,ge=((se=d==null?void 0:d[0])==null?void 0:se.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:be,connectionId:Ce,connectionType:ge,selectedEntities:d})}else if(xe==="upload"||xe==="url"){const be=d==null?void 0:d[0];N({...n,mode:xe,semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}else{const be=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Dfe(),{connections:L}=Xc(),$=xe=>{y(xe),xe==="semantic"||xe.startsWith("domain:")?n.mode!=="semanticDomain"&&z("semanticDomain"):(xe==="direct"||xe.startsWith("conn:"))&&n.mode==="semanticDomain"&&z("database")},V=x.startsWith("domain:"),H=x.startsWith("conn:"),A=V?x.slice(7):void 0,W=H?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||V,Z=j&&!I&&(x==="all"||x==="direct"||H),J=((s==null?void 0:s.length)??0)>0,re=d.length===0&&!J,fe=d.length===0&&J?"Clear":"Add",de=r==="aiContext"?"Data context":R?"Select dataset":"Add data",Se=r==="aiContext"?"Set the overall data scope for the dashboard":R?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{showCloseButton:!1,className:"flex h-[560px] w-[620px] max-w-[620px] flex-col gap-0 overflow-hidden rounded-[6px] border border-border bg-popover p-0",children:[l.jsx(m.VisuallyHidden,{children:l.jsx(go,{children:de})}),l.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:de}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:Se})]}),l.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Close",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]}),l.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:g,onChange:xe=>b(xe.target.value),placeholder:"Search datasets, tables, views, models",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"}),g&&l.jsx("button",{type:"button",onClick:()=>b(""),"aria-label":"Clear search",className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),F&&l.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:l.jsxs("div",{className:"flex w-max items-center gap-1",children:[l.jsx(ux,{label:"All",active:x==="all",onClick:()=>$("all")}),(G.length>0||L.length>0)&&l.jsxs(l.Fragment,{children:[l.jsx(ux,{label:"Semantic",active:x==="semantic",onClick:()=>$("semantic")}),l.jsx(ux,{label:"Direct",active:x==="direct",onClick:()=>$("direct")}),l.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(xe=>l.jsx(ux,{label:xe.label||xe.name,active:x===`domain:${xe.id}`,onClick:()=>$(`domain:${xe.id}`)},`domain:${xe.id}`)),L.map(xe=>l.jsx(ux,{label:xe.name,active:x===`conn:${xe.id}`,onClick:()=>$(`conn:${xe.id}`)},`conn:${xe.id}`))]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&l.jsx(vyt,{domainAccess:u,search:g,scopeDomainId:A,selectedEntities:d,onSelectionChange:xe=>q(xe,"semanticDomain")}),Z&&l.jsx(Cyt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:xe=>q(xe)})]}),l.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:"Selected"}),l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:()=>t(!1),className:"inline-flex h-7 items-center rounded-control px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Cancel"}),l.jsxs("button",{type:"button",onClick:M,disabled:re,className:m.cn("inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",re&&"cursor-not-allowed opacity-50 hover:bg-primary"),children:[l.jsx("span",{children:fe}),d.length>0&&l.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&l.jsx(Dyt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function ux({label:e,active:t,onClick:n}){return l.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:m.cn("inline-flex h-6 shrink-0 items-center whitespace-nowrap rounded-control px-2 text-[11px] font-medium transition-colors",t?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:e})}function xk(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(vF,{className:r});case"view":return l.jsx(tv,{className:r});case"materialized view":return l.jsx(ume,{className:r});case"model":return l.jsx(nv,{className:r});case"file":return l.jsx(vi,{className:r});case"dataset":return l.jsx(ei,{className:r});case"upload":return l.jsx(m.Upload,{className:r});case"url":return l.jsx(hF,{className:r});default:return l.jsx(gg,{className:r})}}const ZR=e=>e.name||e.name,Iyt=e=>{const t=ZR(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Tyt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=v.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(m.TooltipProvider,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const p="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[xk(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate",children:ZR(f)}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-xs",children:Iyt(f)})]},p)}),d&&l.jsxs(m.Tooltip,{open:o,onOpenChange:i,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"flex h-6 cursor-pointer items-center gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(ja,{className:"h-3 w-3"}),l.jsxs("span",{children:[u.length," more"]}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:xk(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:ZR(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(m.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Afe=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Afe.displayName=bo.Input.displayName;const bS=e=>e.label||(e==null?void 0:e.name),nW=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Myt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Ct(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=v.useState(""),[g,b]=v.useState(""),x=s.filter(k=>{if(!h)return!0;const _=bS(k).toLowerCase(),E=(nW(k)||"").toLowerCase(),D=h.toLowerCase();return _.includes(D)||E.includes(D)});v.useEffect(()=>{e||(p(""),b(""))},[e]),v.useEffect(()=>{x.length>0&&!g&&b(bS(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>bS(_)===g);k&&(o.some(E=>"id"in k&&"id"in E?k.id===E.id:k.name===E.name&&k.connectionId===E.connectionId)||t(k),i(k),r())},S=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>o.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Pj,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:S,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Afe,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),a==null||a()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),c==null||c()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Oj,{className:"min-h-60",children:[l.jsx(Lj,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(dr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx($j,{children:x.map((k,_)=>{const E=w(k),D="id"in k?k.id:`${k.connectionId}-${k.name}`,j=bS(k);return l.jsxs(zj,{value:j,onSelect:()=>{E?n==null||n(k):t(k)},onMouseDown:I=>{I.preventDefault(),I.stopPropagation()},className:m.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:xk(k.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nW(k)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(m.Check,{className:"h-3 w-3 text-background"})})]},D)})})]})]})})}function XR({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:p="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,S]=v.useState(!1),[w,C]=v.useState(!1),N=o??y,k=o!==void 0,_=v.useRef(!1),D=m.useEditorStore(A=>A.card.dataSource)??z0,{selectedEntities:j,availableEntities:I,syncWithGlobalContext:T,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:R}=jj(x),B=e==="full"||e==="display",z=e==="full"||e==="trigger",U=v.useMemo(()=>b&&j.length>0?`Add entity (${j.length})`:g,[j.length,b,g]);v.useEffect(()=>{N&&!_.current&&s&&T(),_.current=N},[N,s,T]);const Y=v.useCallback(A=>{k||S(A),i==null||i(A)},[k,i]),O=v.useCallback(A=>{const W=j.filter(X=>!zr(X,A));F(W),c==null||c(A),d==null||d(W)},[c,d,j,F]),K=v.useCallback(A=>{if(A.length===0)return;const W=j.filter(X=>!A.some(Z=>zr(X,Z)));F(W),u==null||u(A),d==null||d(W)},[u,d,j,F]),q=v.useCallback(A=>{const W=R(A)?j.filter(X=>!zr(X,A)):[...j,A];F(W),d==null||d(W)},[R,d,j,F]),M=v.useCallback(()=>{F(I),d==null||d(I)},[I,d,F]),G=v.useCallback(()=>{F([]),d==null||d([])},[d,F]),L=v.useCallback(A=>{x==="dashboard"?P():F(A),d==null||d(A)},[P,x,d,F]),$=v.useCallback(A=>{const W=j.some(X=>zr(X,A))?j:[...j,A];F(W),a==null||a(A),d==null||d(W),Y(!1)},[a,d,j,Y,F]),V=B?l.jsx(Tyt,{className:m.cn(n?"contents":"space-y-2"),entities:j,availableEntities:I,onRemoveEntity:O,onRemoveEntities:K}):null,H=z?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:N,onOpenChange:Y,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:p,size:"xs",className:m.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[l.jsx(QW,{className:"h-3 w-3 text-muted-foreground"}),!b&&l.jsx("span",{children:U})]})}),l.jsx(m.PopoverContent,{className:m.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:A=>A.preventDefault(),children:l.jsx(Myt,{isOpen:!0,onSelect:q,onDeselect:q,onClose:()=>Y(!1),availableEntities:I,selectedEntities:j,onTabComplete:$,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{Y(!1),C(!0)}})})]}),l.jsx(f$,{incomingSelectedEntities:j,open:w,onOpenChange:C,dataSource:D,dialogMode:"aiContext",onSaveSelectedEntities:L,saveAsDashboardDefault:x==="dashboard"})]}):null;return l.jsx("div",{className:m.cn(n?"flex flex-wrap items-center gap-1":"",!n&&B?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[H,V]}):l.jsxs(l.Fragment,{children:[V,H]})})}const h$=v.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=v.useState(!1),h=v.useRef(null),{queueMessage:p}=m.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=m.useFileActions(),y=m.useFileAttachments(c);v.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const S=v.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const I=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${I}px`}},[e]);v.useEffect(()=>{S()},[S]),v.useEffect(()=>{const j=setTimeout(()=>{S()},0);return()=>clearTimeout(j)},[S]);const w=()=>{const j=e.trim();!j&&y.length===0||(a!=="ready"?(p(c,j,y),t(""),x(c)):r({preventDefault:()=>{}}))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),w()),j.key==="@"&&f(!0)},N=v.useCallback(j=>{const I=Cft(j.nativeEvent);I.length>0&&(j.preventDefault(),I.forEach(async T=>{const F=await Z3(T);g(c,F)}))},[g,c]),k=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),_=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),E=v.useCallback(j=>{b(c,j)},[b,c]),D=v.useCallback(j=>{const I=`@${j}`;e.includes(I)&&t(e.replace(I,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(byt,{onFilesDropped:k,currentFileCount:y.length,disabled:s,className:"space-y-4",children:[l.jsx(XR,{mode:"display",assistantType:c,onEntityRemoved:j=>{const I="label"in j?j.label:j.name;D(I)},onEntitiesRemoved:j=>{let I=e;j.forEach(T=>{const F="label"in T?T.label:T.name;I=I.replace(`@${F}`,"")}),I!==e&&t(I.replace(/\s{2,}/g," ").trim())}}),y.length>0&&l.jsx(Rft,{files:y,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{S(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pb-1 pt-3 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(XR,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const I="label"in j?j.label:j.name;t(`${e}@${I} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(gyt,{onFilesSelected:_,disabled:s,currentFileCount:y.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(m.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(_me,{className:"size-3.5"})}),!s&&l.jsx(m.Button,{disabled:!e.trim()&&y.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:w,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(bF,{className:"size-3.5"})})]})]})]})]})});h$.displayName="ChatInputWithContext";function Rfe({assistantType:e,className:t}){const n=m.useMessageQueue(e),{removeFromQueue:r}=m.useQueueActions();return n.length===0?null:l.jsxs("div",{className:m.cn("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(fF,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(m.X,{className:"h-3 w-3"})})]})},s.id))})]})}function Ffe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=m.useMessageQueue(e),{dequeueMessage:o}=m.useQueueActions();v.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Ayt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Ryt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ayt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Pfe(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=v.useRef(null),a=v.useRef(null),[c,u]=v.useState(!0),[d,f]=v.useState(!0),[h,p]=v.useState(!1),[g,b]=v.useState(0),x=v.useRef(!0),y=v.useRef(!0),S=v.useRef(!1),w=v.useRef(!1),C=v.useRef(0),N=v.useRef({count:0,signature:"none"}),k=v.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const B=R.closest("[data-radix-scroll-area-viewport]");if(B)return i.current=B,B;const z=R.parentElement;return z?(i.current=z,z):null},[]),_=v.useCallback(()=>{const R=k();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[k]),E=v.useCallback(()=>_()<=n,[_,n]),D=v.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=v.useCallback(R=>{y.current!==R&&(y.current=R,f(R))},[]),I=v.useCallback(()=>{p(R=>R&&!1),b(R=>R===0?R:0)},[]),T=v.useCallback((R={})=>{const B=k();if(!B)return;const{force:z=!1,instant:U=!1}=R;if(!z&&S.current)return;const Y=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,Y==="smooth"&&"scrollTo"in B?B.scrollTo({top:B.scrollHeight,behavior:"smooth"}):B.scrollTop=B.scrollHeight,C.current=B.scrollTop,S.current=!1,D(!0),j(!0),I(),requestAnimationFrame(()=>{w.current=!1})},[r,I,k,D,j]),F=v.useCallback(()=>{b(0),p(!1)},[]),P=v.useCallback(()=>{const R=k();if(!R)return;const B=C.current,z=R.scrollTop,U=z-B;C.current=z;const Y=E();if(w.current){j(Y),Y&&(S.current=!1,D(!0));return}if(U<-1&&!Y){S.current=!0,D(!1),j(!1);return}if(Y){S.current=!1,D(!0),j(!0),I();return}j(!1),S.current&&D(!1)},[I,k,E,D,j]);return v.useEffect(()=>{const R=k();if(!e||e.length===0){N.current={count:0,signature:"none"},R&&(C.current=R.scrollTop),I();return}const B=e[e.length-1],z=Ryt(B),U=N.current,Y=e.length>U.count,O=z!==U.signature;N.current={count:e.length,signature:z};const K=o||s&&(B==null?void 0:B.role)==="assistant"&&O;if(!S.current){D(!0),R&&E()&&j(!0),(Y||O||K)&&T({force:!1,instant:K});return}if(Y){const q=e.length-U.count;q>0&&(p(!0),b(M=>M+q))}else O&&(p(!0),b(q=>q>0?q:1))},[I,o,s,k,E,e,T,D,j]),v.useEffect(()=>{T({force:!0,instant:!0})},[T]),v.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const B=new ResizeObserver(()=>{S.current||T({force:!1,instant:!0})});return B.observe(R),()=>{B.disconnect()}},[T]),v.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:T,handleScroll:P,resetNewMessageCount:F}}function Ofe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=v.useState(r),a=v.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=v.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=v.useCallback(()=>{i(r)},[r]);return v.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const rW={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Fyt(e,t){var r;if((r=rW[e])!=null&&r[t])return rW[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function Lfe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Fyt(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pyt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Oyt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=v.useState(!1),[a,c]=v.useState(m.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[p,g]=v.useState(!1),[b,x]=v.useState(!1),y=n??b,{isLocalDev:S,isConsoleMode:w}=xg(),C=v.useRef(null);m.useDashboardStore(me=>me.dashboard.aiScopeTables),m.useDashboardStore(me=>me.isDashboardEditing);const N=m.useDashboardStore(me=>me.selectedSheetId),{setDataSource:k}=m.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:E}=m.useDashboardActions(),D=OL(),{setReasoningEffort:j,setShowReasoning:I,clearAssistantMessageContexts:T}=m.useAIActions(),{clearQueue:F}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:R}=m.useFileActions(),B=m.useFileAttachments("dashboard"),z=m.useEditorStore(me=>me.card.dataSource),{assistantProfile:U}=jfe(),Y=m.useDashboardStore(me=>me.handleOpenAssistantProfile),{selectedEntities:O,applyDashboardDefaultEntities:K}=jj("dashboard"),{sendMessage:q,isLoading:M,messages:G,setMessages:L,status:$,stop:V,errorMessage:H,clearError:A}=myt({dynamicVisualMode:f}),W=v.useCallback(me=>{r==null||r(me),n===void 0&&x(me)},[n,r]),X=v.useCallback(()=>{W(!y)},[y,W]);v.useEffect(()=>{if(!y)return;function me(Ye){Ye.key==="Escape"&&W(!1)}return window.addEventListener("keydown",me),()=>{window.removeEventListener("keydown",me)}},[y,W]);const[Z,J]=v.useState(""),re=me=>{J(me.target.value)};async function fe({sql:me,cardTitle:Ye,connectionId:Ve,cardType:$e,python:Ae,cardConfig:Re,dataSource:He,customVisualPreferences:Ge,visualizationMode:ht,dynamicCardPreferences:lt}){if(!N)return;const st=ht==="dynamic",Fe=m.hasValidCardConfig(Re),Ke=Ve||(He==null?void 0:He.connectionId)||"",_t=He?{...He,connectionId:Ke||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ke?{connectionId:Ke,connectionType:"",mode:"database",selectedEntities:[]}:z0,Te=!Fe||!st||(lt==null?void 0:lt.provenance)!=="card-config",Ze=Te?me:"",at=Te?Ae:"",bt={id:m.v4(),title:Ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:$e==="horizontalBar"?"y":"x"},...st&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:$e,sql:Ze,python:at,dataSource:_t,config:Re,connectionId:Ke,visualizationMode:ht,dynamicCardPreferences:lt,customCardPreferences:Ge?{url:Ge.url,componentName:Ge.componentName,pluginChartType:Ge.pluginChartType,settings:Ge.settings,type:"component"}:void 0},ft={id:m.v4(),cards:[bt],activeCardId:bt.id};try{await D(N,ft,"end"),E(!0),_(ft.id)}catch(Et){console.error("Failed to add assistant visual to dashboard:",Et),ut.error(Et instanceof Error?Et.message:"Failed to prepare semantic metadata for the new visual")}}const de=me=>{me.preventDefault();const Ye=Z.trim();if(!Ye&&B.length===0)return;const Ve=[];Ye&&Ve.push({type:"text",text:Ye}),B.forEach($e=>{$e.data&&Ve.push({type:"file",mediaType:$e.type,filename:$e.name,url:`data:${$e.type};base64,${$e.data}`})}),q({role:"user",parts:Ve}),J(""),P("dashboard"),le({force:!0})};v.useEffect(()=>{var me;e&&((me=C.current)==null||me.focus())},[e]),Ffe({assistantType:"dashboard",status:$,isLoading:M,sendMessage:q});const{hasActiveTools:Se,activeToolText:ue}=Lfe(G),{visibleMessages:ve,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:se,resetMessageWindow:be}=Ofe(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ce,contentRef:ge,isAtBottom:ee,hasNewMessages:te,newMessageCount:ce,scrollToBottom:le,handleScroll:Ee,resetNewMessageCount:ye}=Pfe(ve,{threshold:40,behavior:"smooth",isStreaming:M});function ne(me){const Ye={role:"user",parts:[{type:"text",text:me.title+" "+me.subtitle}]};q(Ye)}function je(me){q({role:"user",parts:[{type:"text",text:me}]})}function Ue(me){q({role:"user",parts:[{type:"text",text:me}]}),le({force:!0})}const Be=v.useCallback(async()=>{const me=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(me),ut.success("Conversation copied")}catch(Ye){console.error("Failed to copy conversation",Ye),ut.error("Unable to copy conversation")}},[G]),rt=(Z==null?void 0:Z.length)===0&&(G==null?void 0:G.filter(me=>me.role==="user").length)===0;function Xe(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function et(){return l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Lh,{className:"size-3.5"})})}),l.jsxs(fo,{align:"end",children:[l.jsx(kc,{children:"Options"}),l.jsx(Ea,{}),l.jsx(bu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(bu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(bu,{checked:u,onCheckedChange:d,children:"System Message"}),(S||w)&&l.jsxs(l.Fragment,{children:[l.jsx(Ea,{}),l.jsx(kc,{children:"Dynamic Visuals"}),l.jsx(bu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(bu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(bu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const tt=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("flex h-full grow flex-col justify-between break-words px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Xe(),Y&&l.jsx(m.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:Y,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&et(),a&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Be,children:"Copy Conversation"}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?l.jsx(pF,{className:"size-4"}):l.jsx(_k,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const me=G.filter(Ye=>Ye.role==="assistant").map(Ye=>Ye.id).filter(Ye=>!!Ye);L([]),F("dashboard"),A(),T(me),be()},children:l.jsx(jk,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(m.X,{className:"size-4"})})]})]}),l.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:Ce,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:Ee,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[xe&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:se,className:"text-xs",children:["Load ",Math.min(5,ke-ve.length)," ","more messages (",ke-ve.length," ","hidden)"]})}),l.jsx(cde,{showTools:a,showSystemMessage:u,messages:ve,onAddToDashboard:fe,onQuickReply:Ue,disableQuickReplies:M}),l.jsx(lde,{status:$,errorMessage:H,activeToolText:M&&Se?ue:void 0})]}),l.jsx(m.ScrollBar,{orientation:"horizontal"})]}),e&&!ee&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(m.Button,{onClick:()=>{le({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(m.ChevronDown,{className:"h-4 w-4"}),te&&ce>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&rt&&l.jsx(ude,{onClick:ne,placeholders:Pyt}),l.jsx("div",{children:rt&&U&&l.jsx(Efe,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:je})}),l.jsx(Rfe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(h$,{ref:C,setInput:J,stop:V,input:Z,handleInputChange:re,handleSubmit:me=>{de(me),le({force:!0})},isLoading:M,status:$,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(f$,{incomingSelectedEntities:O,open:p,onOpenChange:g,dataSource:z||z0,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:me=>K()})]});return y&&s?Sr.createPortal(l.jsx(sb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:l.jsx("div",{className:"flex h-full w-full",children:tt})}),s):tt}function Lyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=Iie(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(p){if($yt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),ut.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=zyt(p);if(g!=null&&g.id){const b=jie(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),ut.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function $yt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function zyt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function Byt(e,t){switch(e.interactionMode){case"drillToDetail":Vyt(e,t);break;case"drillThrough":Hyt(e,t);break;case"drillToURL":Uyt(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Vyt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Hyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Uyt(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Wyt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(na,{children:[l.jsx(go,{children:i||"Insight Detail"}),l.jsx(si,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Aie,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Gie,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function qyt(){const e=m.useInteractionStore(C=>C.interactionStates),t=m.useInteractionStore(C=>C.setInteractionState),n=m.useInteractionStore(C=>C.clearLastInteractionEvent),r=m.useInteractionStore(C=>C.replaceCardWithInsight),s=m.useInteractionStore(C=>C.setPendingDrillThrough),o=m.useInteractionStore(C=>C.pendingDrillThrough),i=m.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=Ph(),d=m.useDashboardStore(C=>C.dashboard),f=m.useDashboardStore(C=>C.filterValues),{data:h,isLoading:p}=LY((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Kie(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),S=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E})=>{const D={filters:C},j={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[D]},I={...m.createInitialInteractionState(),appliedClickFilters:[j],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E};t(m.DRILL_CONTEXT_CARD_ID,I)}}),[a,r,f,c,d,s,t]);v.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{Byt(k,S)}catch(E){console.error("Error executing interaction event:",E)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,S]),v.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,p,u,c,i]);const w=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Wyt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Yyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Gyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Gyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kyt(e){return e?`Back to ${e}`:"Back"}function Zyt(){var y,S,w,C,N;const e=m.useInteractionStore(k=>k.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(k=>k.actions.goBackFromDrill),n=m.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=Ph(),[s,o]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const k=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(w=(S=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:S.filterGroups)==null?void 0:w[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),c.current={x:k.clientX-s.x,y:k.clientY-s.y})};Yyt(f);const x=Kyt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const E=k.field.label||k.field.name,D=String(k.value);return l.jsxs(Yr,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",D]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(ev,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Xyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Qyt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=db({id:`filter:${e.id}`,disabled:n||!t}),x={transform:_i.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(bL,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const sW="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Jyt=[];function $fe({open:e,onOpenChange:t}){var L,$,V;const[n,r]=v.useState(!1),[s,o]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(H=>{var A;return(A=H.dashboard)==null?void 0:A.sheets}),u=m.useDashboardStore(H=>H.dashboard),d=m.useDashboardStore(H=>H.dashboardInputValues),f=m.useDashboardStore(H=>H.filterValues),h=m.useDashboardStore(H=>H.controlValues),p=m.useDashboardStore(H=>H.inlineFilterValuesMap),g=m.useDashboardStore(H=>H.cardControlValuesMap),b=m.useDashboardStore(H=>H.selectedSheetId),x=m.useDashboardStore(H=>H.selectedSheetId?H.documentInputRuntimeBySheetId[H.selectedSheetId]:void 0),y=m.useDashboardStore(H=>H.isDownloadingPdf),{authToken:S,tokenProps:w}=Ct(),C=c==null?void 0:c.find(H=>H.id===b),N=v.useMemo(()=>m.getDashboardExportSheets(c),[c]),k=m.isDocumentSheet(C),_=k&&C?C.document:void 0,E=v.useMemo(()=>k&&C?dw(u,C.id):[],[C,k,u]),D=E.length>0,j=v.useMemo(()=>k&&C?Tce(u,C.id):!1,[C,k,u]),I=v.useMemo(()=>D?E.map(fw):(_==null?void 0:_.inputs)||Jyt,[_,E,D]),T=(($=(L=w==null?void 0:w.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((V=w==null?void 0:w.params)==null?void 0:V.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=v.useMemo(()=>Tle(I),[I]),P=v.useMemo(()=>Dle(I,T),[I,T]),R=v.useMemo(()=>Ile(I),[I]),B=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=v.useMemo(()=>k?j&&C&&_?VZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(H=>H.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:T}):Rle(I,B,z,F,F):[],[_,I,C,k,u,g,h,f,p,d,z,B,F,T,j]),Y=!!C,O=N.length>0,K=((c==null?void 0:c.length)||0)>1||k,q=i.sheetSelection==="current"&&(!Y||k&&U.length>0)||i.sheetSelection==="all"&&!O;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(H=>({...H,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){ut.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){ut.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!Y){ut.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){ut.error("No dashboard sheets are available to export");return}o(!0);const H=i.sheetSelection==="current"&&k,A=H?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",W=ut.loading(A);try{if(H){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){ut.dismiss(W),ut.error(`Set ${U.join(", ")} before exporting`);return}const Z=new Date().toISOString(),J=j?UZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:Z,timezone:T}).snapshot:void 0;await PP(w.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:T,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:B,controlValuesByInputId:z,generatedAt:Z}}})}else{const Z=xee();await XZ(w.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,Z)}ut.dismiss(W);const X=H?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";ut.success(X,{duration:2e3}),M()}catch(X){ut.dismiss(W),ut.error("Failed to download PDF",{description:m_(X,"Please try again or contact support."),descriptionClassName:p_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{o(!1)}}return l.jsx(Oo,{open:e,onOpenChange:H=>{if(!H){M();return}t(!0)},children:l.jsxs(mo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(na,{children:[l.jsx(go,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),l.jsx(si,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[K&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:sW,children:"Export scope"}),l.jsxs(Ia,{value:i.sheetSelection,onValueChange:H=>a({...i,sheetSelection:H}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!Y&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"current",id:"scope-current",disabled:!Y}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Ln,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:H=>{a({...i,protectPdf:H,password:H?i.password:""}),H||r(!1)}}),l.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:sW,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:H=>a({...i,password:H.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:H=>{H.key==="Enter"&&i.password&&G()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Nk,{className:"h-3.5 w-3.5"}):l.jsx(tv,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:G,disabled:s||y||q,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(qc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function zfe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=v.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(qc,{className:m.cn("size-4",e)})}),l.jsx($fe,{open:i,onOpenChange:a})]})}function oW(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function e0t({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=db({id:`control:${e.id}`,disabled:!n}),d={transform:_i.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Gle,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function iW(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function aW(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function t0t(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return aW(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=aW(t,n).filter(a=>!o.has(a));return[...s,...i]}function n0t(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function r0t(e){return zm(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>zm(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function lW(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function s0t(e){const t={sheetId:e.selectedSheetId},n=m.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=m.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||m.getBackingDefaultSlot(e.dashboardInput)}function o0t(e){return Bfe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function Bfe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=n0t(e.dashboard,t);return lZ(a_({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!r0t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function i0t(e,t){return"toolbar"}function a0t(){const e=Zc("interactive"),t=m.useDashboardStore($=>$.selectedSheetId),n=m.useDashboardStore($=>$.dashboard.filters),r=m.useDashboardStore($=>$.dashboard.filterLayout),s=m.useDashboardStore($=>$.isDashboardEditing),o=m.useDashboardStore($=>$.controlValues),i=m.useDashboardStore($=>$.filterValues);m.useDashboardStore($=>$.filteringCards);const a=m.useDashboardStore($=>$.inlineFilterValuesMap),c=m.useDashboardStore($=>$.dashboardInputValues),u=m.useInteractionStore($=>$.clearAllClickFilters),d=m.useInteractionStore($=>Object.entries($.interactionStates).reduce((V,[H,A])=>{var W;return H===m.DRILL_CONTEXT_CARD_ID?V:V+(((W=A.appliedClickFilters)==null?void 0:W.length)??0)},0)),f=m.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:S,setFilteringCards:w,upsertDashboardInput:C}=m.useDashboardActions(),N=Tj(cg(cb,{activationConstraint:{distance:5}})),k=m.useDashboardStore($=>$.dashboard),_=o0t({dashboard:k,selectedSheetId:t}).filter($=>i0t($.filter)==="toolbar"),E=Bfe({dashboard:k,selectedSheetId:t}),D=_.map($=>$.filter),j=new Map(_.map($=>[`filter:${$.filter.id}`,$])),I=wKe(k),T=I.filter($=>!$.hidden&&C0($)==="toolbar"),F=I.filter($=>!$.hidden&&C0($)==="advanced"),P=t0t(r==null?void 0:r.toolbarItemOrder,D,T),R=new Map(D.map($=>[`filter:${$.id}`,$])),B=new Map(T.map($=>[`control:${$.id}`,$]));function z($){const{active:V,over:H}=$;if(!H||V.id===H.id)return;const A=String(V.id),W=String(H.id),X=P.findIndex(ve=>ve===A),Z=P.findIndex(ve=>ve===W);if(X===-1||Z===-1)return;const J=ub(P,X,Z);y({toolbarItemOrder:J});const re=new Set((n||[]).map(ve=>ve.id)),fe=P.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),de=J.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),Se=P.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:","")),ue=J.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:",""));h(oW(n||[],fe,de)),g(oW(k.controls||[],Se,ue))}const U=(r==null?void 0:r.toolbarWrap)??!1,Y=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>iW($)).length)??0,K=E.filter(lW),q=K.filter($=>{const V=s0t({dashboardInput:$,dashboardInputValues:c,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(V==null?void 0:V.status)==="set"&&V.value.kind==="filter"&&iW(V.value.filterValue)}).length,M=a?Object.values(a).reduce(($,V)=>$+((V==null?void 0:V.length)??0),0):0,G=O+q+M+d,L=()=>{S([]),K.forEach($=>{p($,{sheetId:t})}),w([]),u(),a&&Object.entries(a).forEach(([$,V])=>{V==null||V.forEach(H=>{f($,H.filterId)})})};return!D.length&&!T.length&&!F.length&&!Y&&G===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(ow,{sensors:N,collisionDetection:nw,onDragEnd:z,children:l.jsxs("div",{className:m.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(iw,{items:P,strategy:qL,children:l.jsx(NR,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const V=R.get($);if(V){const A=j.get($),W=A&&lW(A);return l.jsx(Qyt,{filter:V,isEditing:s,storageOptions:W?{storageTarget:"dashboardInput",dashboardInput:A,sheetId:t??void 0}:void 0,inputVariableName:W?A.variableName:void 0,onUpdateFilter:W?(X,Z)=>{C({...A,variableName:(Z==null?void 0:Z.variableName)||A.variableName,filter:X})}:void 0,onRemoveFilter:W?()=>{S((i||[]).filter(X=>X.filterId!==V.id)),b(A.id)}:void 0},$)}const H=B.get($);return H?l.jsx(e0t,{control:H,value:o==null?void 0:o[H.id],isEditing:s,onChange:A=>x(H.id,A)},$):null})})}),F.length>0&&l.jsx(Hie,{title:"",controls:F,values:o,onChange:($,V)=>x($.id,V),immediatePlacement:"toolbar",advancedLabel:"More controls"}),G>0&&l.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(m.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:G})]}),Y&&l.jsx("div",{className:m.cn(G>0?"ml-1.5":"ml-auto"),children:l.jsx(zfe,{})})]})})})}function Vfe(){var te,ce;const{showAssistant:e,tokenProps:t,renderMode:n}=Ct(),r=Xyt((te=t.config)==null?void 0:te.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=xg(),i=(ce=s==null?void 0:s.cardDisplay)==null?void 0:ce.mode,a=Wh(i),c=_Z({displayMode:i,renderMode:n}),u=v.useRef(null),d=v.useRef(null),[f,h]=v.useState(!1),{handleDragStart:p,isDraggingRef:g,getStyle:b,getPositionClasses:x}=Sot({initialPosition:"bottom-right"}),y=Hf(le=>le.setFullscreen),S=Hf(le=>le.setPanelOpen),w=Hf(le=>le.setContainer),C=mK("dashboard"),N=gK(),k=bK("dashboard"),_=C.isOpen,E=N==="dashboard",D=m.useDashboardStore(le=>le.isVisualEditing),j=m.useDashboardStore(le=>le.themeStyle),I=Rl(),T=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.sheets}),F=m.useDashboardStore(le=>le.showFilters),P=m.useDashboardStore(le=>le.isDashboardEditing),R=m.useDashboardStore(le=>le.selectedSheetId),B=T==null?void 0:T.find(le=>le.id===R),z=m.useDashboardStore(le=>{var Ee,ye,ne;return(ne=(ye=(Ee=le.dashboard)==null?void 0:Ee.sheets)==null?void 0:ye.find(je=>je.id===le.selectedSheetId))==null?void 0:ne.kind}),U=m.useDashboardStore(le=>{var Ee,ye;return((ye=(Ee=le.dashboard)==null?void 0:Ee.summary)==null?void 0:ye.position)||"top"}),Y=z==="document",O=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.id}),K=m.useDashboardStore(le=>le.isDashboardPanelOpen),q=m.useDashboardStore(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:L}=YW(O),[$,V]=v.useState(null);Rk(Xr.DASHBOARD);const{setSelectedSheetId:H,setSheetTitle:A,addSheet:W,setSheets:X}=m.useDashboardActions();Lyt(d);const{setActiveAssistantType:Z}=m.useAIActions();v.useEffect(()=>{if(O){const le=M();V(le)}},[O,M]),v.useEffect(()=>{_?Z("dashboard"):N==="dashboard"&&y(null)},[_,Z,N,y]),v.useEffect(()=>{var le;_||(le=u.current)==null||le.resize(0)},[_]);function J(le){var Ee,ye;le?((Ee=u.current)==null||Ee.resize(40),S("dashboard",!0),y("dashboard"),Z("dashboard")):(S("dashboard",!1),y(null),(ye=u.current)==null||ye.resize(0),Z(null))}function re(le="dashboard"){const Ee={id:m.v4(),title:le==="document"?"New Document":"New Sheet",...le==="document"?{kind:le,document:m.createDefaultDocumentDefinition()}:{}};W(Ee),H(Ee.id)}function fe(le,Ee){if(!O)return;$===le?(L(),V(null),ut.success("Default sheet cleared")):(G(le),V(le),ut.success(`"${Ee}" set as default sheet`))}function de(le){var Ee;le<1?(S("dashboard",!1),y(null),Z(null),(Ee=u.current)==null||Ee.resize(0)):(_||S("dashboard",!0),Z("dashboard"))}function Se(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const ue=(le,Ee)=>{le.dataTransfer.setData("tabIndex",Ee.toString())},ve=le=>{le.preventDefault()},xe=(le,Ee)=>{const ye=le.dataTransfer.getData("tabIndex");if(ye===Ee.toString())return;const ne=Array.from(T||[]),[je]=ne.splice(parseInt(ye),1);ne.splice(Ee,0,je),X(ne)},ke=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,se=r===!0&&!a&&!_&&!D&&!F;function be(){if(T&&T.length>1||P)return l.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&ke&&!K&&l.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{q(!K)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:l.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:l.jsx(mF,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[T==null?void 0:T.map((le,Ee)=>{const ye=R===le.id,ne=$===le.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:je=>ue(je,Ee),onDragOver:ve,onDrop:je=>xe(je,Ee),onClick:()=>H(le.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:le.id,children:[le.kind==="document"&&l.jsx(vi,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(ON,{enabled:P&&ye,text:le.title,onSave:je=>A(le.id,je),children:le.title},le.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":ne?"Clear default sheet":"Set as default sheet",title:ne?"Clear default sheet":"Set as default sheet",onClick:je=>{je.stopPropagation(),fe(le.id,le.title||"Sheet")},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),fe(le.id,le.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ye||ne?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(yF,{className:m.cn("h-3 w-3 transition-colors",ne?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ye&&T.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:je=>{je.stopPropagation(),h(!0)},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),h(!0))},children:l.jsx(m.X,{className:"h-3 w-3"})})]},le.id)}),P&&l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(dr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(fo,{align:"start",className:"w-48",children:[l.jsxs(jn,{onSelect:()=>re("dashboard"),children:[l.jsx(Rm,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(jn,{onSelect:()=>re("document"),children:[l.jsx(vi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function Ce(){return l.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:T==null?void 0:T.map(le=>l.jsx(m.TabsContent,{style:{backgroundColor:Se(),...I.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:le.id,children:l.jsx(xH,{sheet:le})},le.id))})}function ge(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:le=>{H(le)},value:R||void 0,children:[be(),U==="top"&&!Y&&l.jsx(sR,{}),R&&!Y&&l.jsx(a0t,{}),Y?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:Ce()}):l.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:Ce()}),U==="bottom"&&!Y&&l.jsx(sR,{}),l.jsx(Cot,{open:f,setOpen:h})]})}const ee=v.useCallback(le=>{w("dashboard",le)},[w]);return T?c&&R&&!Y?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):c&&Y&&B?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(xH,{sheet:B})}):l.jsxs(l.Fragment,{children:[l.jsx(qyt,{}),l.jsx(Zyt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(UF,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",E&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(Ry,{children:ge()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(wot,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),l.jsx(Ry,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:de,defaultSize:_?40:0,ref:u,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Oyt,{open:_,setOpen:J,isFullscreen:E,onFullscreenChange:le=>y(le?"dashboard":null),fullscreenContainer:k})})})]})]}),l.jsx("div",{ref:ee,className:m.cn("absolute inset-0",!E&&"pointer-events-none")}),se&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{g.current||J(!0)},onMouseDown:p,onTouchStart:p,title:"Open Assistant (drag to move)",children:l.jsx(vme,{className:"h-5 w-5"})})})]})]}):null}const Hfe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>l0t(d),[d]),{theme:h}=nF(),p=c0t(h),g=v.useMemo(()=>s??Wc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=v.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=v.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(sb,{...c,ref:u,className:i,style:a,children:o})})});Hfe.displayName="AppearanceProvider";function l0t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function c0t(e){const t=hC(e),[n,r]=v.useState(()=>u0t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function u0t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Ufe=v.createContext({openBrandStudioPreview:()=>{}}),d0t=Ufe.Provider;function f0t(){return v.useContext(Ufe)}function h0t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=hC(t),[o,i]=v.useState(()=>p0t(n)||s),a=v.useCallback(u=>{const d=hC(u);m0t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(kW.Provider,{...r,value:c,children:e})}function p0t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=hC(t,"system");return n===t?n:null}catch{return null}}function m0t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const g0t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function p$({appearance:e,children:t}){var I,T;const{authToken:n,id:r,tokenProps:s}=Ct(),o=Q0(),i=(I=o.data)==null?void 0:I.organizationAppearance,a=(T=s.config)==null?void 0:T.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),S=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=On({queryKey:AY({resourceType:Xr.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:S,appearance:i})},[i,S]),v.useEffect(()=>{w.data!==void 0&&y({scopeKey:S,appearance:w.data})},[w.data,S]);const C=(x==null?void 0:x.scopeKey)===S?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=v.useMemo(()=>Wc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=v.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),E=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const D=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),j=g??h??e;return l.jsx(h0t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(d0t,{value:D,children:l.jsx(Hfe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:j,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(g0t,{appearance:d,onDraftChange:b,onSave:F=>{p(F),b(F),f(F)},onCancel:E})})})]})})})})}function Wfe({children:e,preferences:t}){const{currentUser:n}=ta(),r=v.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(IY.Provider,{value:r,children:l.jsx(kj,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function b0t(e=2e3,t=500){const n=Ipe(),[r,s]=v.useState(!1),[o,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function m$({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=b0t(e,t);return v.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:e,children:[l.jsx(m$,{componentType:"dashboard",componentId:e.id}),l.jsx(p$,{appearance:e.appearance,children:l.jsx(Wfe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(YF,{...e,type:"dashboard",children:l.jsx(Vfe,{})})})})})]})})}function x0t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[s,o]=v.useState(),i=v.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function y0t({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=xg(),r=Wh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=x0t([t,o,r]);return v.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(Zi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(gL,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(m.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function v0t(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(y0t,{filter:r}),l.jsx(gj,{filter:r})]},r.id))}):null}function w0t(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(v0t,{}),l.jsx(Vfe,{})]})})}const S0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-By7aKmDj.js"))),C0t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BuXlHmJH.js"))),N0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BOyLuhS6.js"))),k0t=v.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-ByR-FD3h.js")).then(e=>({default:e.ResourceManagementPanel})));function _0t({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(u=>u.isDashboardPanelOpen),s=m.useDashboardStore(u=>u.isVisualEditing),o=m.useDashboardStore(u=>u.showDashboardJSON),i=m.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:c}=n;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:n,children:[l.jsx(m$,{componentType:"surfboard",componentId:n.id}),l.jsxs(p$,{appearance:a,children:[l.jsx(Ebe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(Wfe,{preferences:c,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(N0t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(S0t,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(k0t,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(YF,{...n,type:"dashboard",children:[s&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(C0t,{})}),l.jsx(w0t,{})]})})]})]})]})]})]})})}var j0t=Object.defineProperty,E0t=(e,t,n)=>t in e?j0t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xS=(e,t,n)=>E0t(e,typeof t!="symbol"?t+"":t,n);const D0t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},I0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},T0t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M0t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const A0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Yfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},R0t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},F0t={stringify:e=>e,parse:e=>e},d2={string:F0t,number:R0t,boolean:D0t,function:I0t,method:A0t,json:T0t},dx=Symbol.for("r2wc.render"),yS=Symbol.for("r2wc.connected"),Xd=Symbol.for("r2wc.context"),li=Symbol.for("r2wc.props");function P0t(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const p of i){c[p]=Array.isArray(t.props)?"string":t.props[p];const g=M0t(p);d[p]=g,f[g]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),xS(this,o,!0),xS(this,s),xS(this,r,{}),xS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[li].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],S=y?d2[y]:null;if(y==="method"){const w=Yfe(b);Object.defineProperty(this[li].container,w,{enumerable:!0,configurable:!0,get(){return this[li][w]},set(C){this[li][w]=C,this[dx]()}}),this[li][g]=S.parse(x,b,this)}S!=null&&S.parse&&x&&(this[li][g]=S.parse(x,b,this))}for(const g of a)this[li][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yS]=!0,this[dx]()}disconnectedCallback(){this[yS]=!1,this[Xd]&&n.unmount(this[Xd]),delete this[Xd]}attributeChangedCallback(g,b,x){const y=f[g],S=c[y],w=S?d2[S]:null;y in c&&w!=null&&w.parse&&x&&(this[li][y]=w.parse(x,g,this),this[dx]())}[(o=yS,s=Xd,r=li,dx)](){this[yS]&&(this[Xd]?n.update(this[Xd],this[li]):this[Xd]=n.mount(this.container,e,this[li]))}}for(const p of i){const g=d[p],b=c[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[li][p]},set(x){this[li][p]=x;const y=b?d2[b]:null;if(y!=null&&y.stringify){const S=y.stringify(x,g,this);this.getAttribute(g)!==S&&this.setAttribute(g,S)}else this[dx]()}})}return h}function O0t(e,t,n){const r=CW.createRoot(e),s=v.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function L0t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $0t({root:e}){e.unmount()}function z0t(e,t={}){return P0t(e,t,{mount:O0t,update:L0t,unmount:$0t})}const B0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V0t=z0t(qfe,{props:B0t}),H0t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(g3,{context:t})," "]})}),Gfe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),U0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),W0t=Array.from(Gfe).join(", "),q0t=3,Y0t="Self-heal",G0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function K0t({card:e}){var Y,O,K,q,M;const[t,n]=v.useState({}),{authToken:r}=Ct(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=v.useMemo(()=>Yv(o),[o]),a=m.useEditorStore(G=>G.frame),c=m.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=m.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=m.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=Qh(((Y=f.customCardPreferences)==null?void 0:Y.url)||""),g=(O=p==null?void 0:p.visuals)==null?void 0:O.find(G=>{var L;return G.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=Gv(f,g)??"single",x=v.useMemo(()=>wL({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=v.useMemo(()=>{const G=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return G<0?-1:y0(e,G)},[x,e]),S=v.useMemo(()=>b!=="multiple"||y<0?e.type:pm(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=v.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==e.type?{...e,type:S}:e,[e,S,b]),{data:C}=f_(w),N=m.useInteractionStore(G=>G.interactionStates),k=m.useDashboardStore(G=>{var L;return(L=G.dashboard)==null?void 0:L.id}),_=m.useDashboardStore(G=>G.dashboard.filters),E=m.useDashboardStore(G=>G.filterValues),D=m.useDashboardStore(G=>G.selectedSheetId),j=v.useMemo(()=>xL({card:e,sheetId:D||"",inlineFilterValues:c,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,D,c,u,d]),{cardFilters:I,cardFilterValues:T}=v.useMemo(()=>dv({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:E,selectedSheetId:D}),[e,N,k,_,E,D]),F=v.useCallback((G,L)=>{const $=CL(L);n(V=>({...V,[G]:$}))},[]),P=(K=f.customCardPreferences)==null?void 0:K.componentName,R=P?h(P):null,B=FN((q=f.customCardPreferences)==null?void 0:q.settings,f),z=v.useMemo(()=>vL(x),[x]),U=v.useMemo(()=>z.map((G,L)=>pm(G,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[R&&b==="single"&&l.jsx(R,{editing:!0,params:s,theme:i,settings:B,cardMetadata:oie({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j}),R&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((G,L)=>{if(!G)return null;const $=y0(G,L),V=pm(G,$,g==null?void 0:g.slots);return l.jsx(U5,{onDataChange:F,card:G,effectiveCardType:V},`${G.id}-${$}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(R,{editing:!0,onDataChange:F,...NL({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:B,filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Z0t=v.memo(K0t,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),X0t=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Kfe=["PageUp","PageDown"],Zfe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},bb="Slider",[QR,Q0t,J0t]=m.createCollection(bb),[Qfe]=m.createContextScope(bb,[J0t]),[evt,fE]=Qfe(bb),Jfe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),w=i==="horizontal"?tvt:nvt,[C=[],N]=m.useControllableState({prop:d,defaultProp:u,onChange:I=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(I)}}),k=Q.useRef(C);function _(I){const T=avt(C,I);j(I,T)}function E(I){j(I,y.current)}function D(){const I=k.current[y.current];C[y.current]!==I&&h(C)}function j(I,T,{commit:F}={commit:!1}){const P=dvt(o),R=fvt(Math.round((I-r)/o)*o+r,P),B=m.clamp(R,[r,s]);N((z=[])=>{const U=ovt(z,B,T);if(uvt(U,c*o)){y.current=U.indexOf(B);const Y=String(U)!==String(z);return Y&&F&&h(U),Y?U:z}else return z})}return l.jsx(evt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:l.jsx(QR.Provider,{scope:e.__scopeSlider,children:l.jsx(QR.Slot,{scope:e.__scopeSlider,children:l.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:_,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,C.length-1,{commit:!0}),onStepKeyDown:({event:I,direction:T})=>{if(!a){const R=Kfe.includes(I.key)||I.shiftKey&&Zfe.includes(I.key)?10:1,B=y.current,z=C[B],U=o*R*T;j(z+U,B,{commit:!0})}}})})})})});Jfe.displayName=bb;var[ehe,the]=Qfe(bb,{startEdge:"left",endEdge:"right",size:"width",direction:1}),tvt=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),p=m.useComposedRefs(t,w=>h(w)),g=Q.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function S(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=g$(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(nhe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=S(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=S(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:w=>{const N=Xfe[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),nvt=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=Q.useRef(null),f=m.useComposedRefs(t,d),h=Q.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=g$(y,p?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(nhe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xfe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),nhe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=fE(bb,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kfe.concat(Zfe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),rhe="SliderTrack",she=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(rhe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});she.displayName=rhe;var JR="SliderRange",ohe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(JR,n),o=the(JR,n),i=Q.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>lhe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});ohe.displayName=JR;var eF="SliderThumb",ihe=Q.forwardRef((e,t)=>{const n=Q0t(e.__scopeSlider),[r,s]=Q.useState(null),o=m.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(rvt,{...e,ref:o,index:i})}),rvt=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=fE(eF,n),a=the(eF,n),[c,u]=Q.useState(null),d=m.useComposedRefs(t,S=>u(S)),f=c?i.form||!!c.closest("form"):!0,h=m.useSize(c),p=i.values[r],g=p===void 0?0:lhe(p,i.min,i.max),b=ivt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?lvt(x,g,a.direction):0;return Q.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(QR.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(ahe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});ihe.displayName=eF;var svt="RadioBubbleInput",ahe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=m.useComposedRefs(s,r),i=m.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(m.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});ahe.displayName=svt;function ovt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function lhe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function ivt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function avt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function lvt(e,t,n){const r=e/2,o=g$([0,50],[0,r]);return(r-o(t)*n)*n}function cvt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function uvt(e,t){if(t>0){const n=cvt(e);return Math.min(...n)>=t}return!0}function g$(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function dvt(e){return(String(e).split(".")[1]||"").length}function fvt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var che=Jfe,hvt=she,pvt=ohe,mvt=ihe;const uhe=Q.forwardRef(({className:e,...t},n)=>l.jsxs(che,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(hvt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(pvt,{className:"absolute h-full bg-primary"})}),l.jsx(mvt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));uhe.displayName=che.displayName;const dhe=["SUN","MON","TUE","WED","THU","FRI","SAT"],gvt=dhe.reduce((e,t,n)=>({...e,[t]:n}),{}),tc={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function bvt(e){if(!e||!e.trim())return{...tc};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...tc,isCustom:!0};const[s,o,i,a,c]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...tc,isCustom:!0};if(i==="*"&&(c==="?"||c==="*"))return{...tc,repeats:"daily",hour:d,minute:u};if(i==="?"&&c!=="?"&&c!=="*"){const h=c.split(",").map(p=>p.toUpperCase()).map(p=>gvt[p]).filter(p=>typeof p=="number");if(h.length>0)return{...tc,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(c==="?"||c==="*")?{...tc,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(c==="?"||c==="*")?{...tc,repeats:"monthly",hour:d,minute:u}:{...tc,hour:d,minute:u,isCustom:!0}}function xvt(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>dhe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fhe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function yvt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function vvt(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function wvt(e,t,n,r){const s=fhe(e.hour,e.minute),o=yvt(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${vvt(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const Svt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=l3;exports.AccordionContent=T0;exports.AccordionItem=D0;exports.AccordionTrigger=I0;exports.AddDataPicker=f$;exports.AggregateTable=W_;exports.Alert=zP;exports.AlertDescription=BP;exports.AlertDialog=Lc;exports.AlertDialogAction=kl;exports.AlertDialogCancel=_l;exports.AlertDialogContent=vl;exports.AlertDialogDescription=Nl;exports.AlertDialogFooter=Sl;exports.AlertDialogHeader=wl;exports.AlertDialogTitle=Cl;exports.AlertDialogTrigger=V2;exports.AlertTitle=wX;exports.ArrowDown=Js;exports.ArrowDownIcon=wqe;exports.ArrowLeft=ev;exports.ArrowRight=Sk;exports.ArrowUp=eo;exports.ArrowUpIcon=Cqe;exports.AssistantContextEntityControls=XR;exports.AssistantStatus=lde;exports.AtSign=QW;exports.AxisConfigurator=jg;exports.Badge=Yr;exports.Bell=SS;exports.BookType=eq;exports.BulletChartIcon=ade;exports.COMMON_TIMEZONES=Svt;exports.CSS=_i;exports.CalculatedFieldEditor=yle;exports.Calculator=nq;exports.Calendar=gi;exports.Calendar$1=ZS;exports.CalendarRange=rq;exports.Card=Tm;exports.CardContent=wk;exports.CardHeader=vk;exports.CardSummary=dR;exports.CardTitle=mg;exports.ChartArea=F2;exports.ChartColumnIncreasing=sq;exports.ChartColumnStacked=oq;exports.ChartJsVisual=$v;exports.ChartLine=iq;exports.ChartNoAxesGantt=lq;exports.ChartPie=cq;exports.ChartScatter=uq;exports.ChatInputWithContext=h$;exports.Checkbox=Ln;exports.ChevronLeft=Oh;exports.ChevronRight=Mr;exports.Circle=Ck;exports.CircleAlert=ih;exports.CircleCheck=hq;exports.CircleHelp=pq;exports.Clock=fF;exports.CodeHighlighter=Uu;exports.CodeXml=Bf;exports.Collapsible=Vc;exports.CollapsibleContent=Uc;exports.CollapsibleTrigger=Hc;exports.ColorField=Bi;exports.Command=Pj;exports.CommandEmpty=Lj;exports.CommandGroup=$j;exports.CommandInput=ZL;exports.CommandItem=zj;exports.CommandList=Oj;exports.CommandSeparator=$ae;exports.ComparisonMetadataBadge=Wee;exports.Container=YF;exports.ControlDefaultValueEditor=Ble;exports.ControlDefinitionOptionsEditor=zle;exports.ControlIdInput=Ple;exports.ControlVisibilitySettings=$tt;exports.Copy=Pc;exports.CopyButton=Ac;exports.CopyPlus=O2;exports.Cross2Icon=jqe;exports.CustomFilterPopover=gL;exports.CustomScrollArea=zl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=GJ;exports.DEFAULT_SCHEDULE_VM=tc;exports.Dashboard=qfe;exports.DashboardActionsMenu=TY;exports.DashboardCard=Wie;exports.DashboardCreateDialogBase=aG;exports.DashboardExportDialog=$fe;exports.DashboardPlus=_0t;exports.DashboardWC=V0t;exports.DataAppBuilder=pK;exports.DataTableConditionalFormattingSettings=Dce;exports.DataTablePagination=z_;exports.Database=ei;exports.DateRangePicker=Z5;exports.DefaultChatTransport=c$;exports.Dialog=Oo;exports.DialogContent=mo;exports.DialogDescription=si;exports.DialogFooter=Gc;exports.DialogHeader=na;exports.DialogTitle=go;exports.DialogTrigger=oG;exports.DisplayPreferencesProvider=kj;exports.DndContext=ow;exports.Donut=mq;exports.Download=qc;exports.DownloadPdf=zfe;exports.DragOverlay=kae;exports.DropdownMenu=Ao;exports.DropdownMenuCheckboxItem=bu;exports.DropdownMenuContent=fo;exports.DropdownMenuItem=jn;exports.DropdownMenuLabel=kc;exports.DropdownMenuRadioGroup=tbe;exports.DropdownMenuRadioItem=DY;exports.DropdownMenuSeparator=Ea;exports.DropdownMenuSub=TF;exports.DropdownMenuSubContent=Tk;exports.DropdownMenuSubTrigger=Ik;exports.DropdownMenuTrigger=Ro;exports.EMPTY_DATA_SOURCE=z0;exports.Editable=ON;exports.EditableText=Zi;exports.EditorCustomVisual=Z0t;exports.Ellipsis=ja;exports.EllipsisVertical=Lh;exports.ErrorBoundary=Aa;exports.ExportError=Rg;exports.ExternalLink=Am;exports.Eye=tv;exports.EyeOff=Nk;exports.Fallback=Cj;exports.FallbackVisual=w0;exports.FeedbackCategory=xd;exports.FeedbackDialog=L0;exports.FieldsList=g3;exports.FieldsSection=H0t;exports.FileSpreadsheet=gq;exports.FileText=vi;exports.Filter=ah;exports.FilterComponent=gj;exports.FilterInfo=aR;exports.FilterableFieldsPanel=wle;exports.Globe=gg;exports.Grid3x3=bq;exports.GripVertical=Yc;exports.HEATMAP_PRESET_PALETTES=YM;exports.Hash=xq;exports.House=yq;exports.HoverCard=Pg;exports.HoverCardContent=cd;exports.HoverCardTrigger=Og;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gfe;exports.INLINE_ALLOWED_TOOL_LIST=W0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=U0t;exports.IconButton=Vu;exports.IconForFieldType=rC;exports.InfoHover=LL;exports.InlineFilterBar=Fie;exports.KPICard=Th;exports.KeyboardSensor=rw;exports.Layers=nv;exports.LayoutDashboard=Rm;exports.Link=hF;exports.LoadingDots=dd;exports.Lock=kk;exports.MAX_SELF_HEAL_ATTEMPTS=q0t;exports.Map=Sq;exports.Markdown=bue;exports.Maximize2=_k;exports.MdStackedLineChart=ode;exports.Minimize2=pF;exports.MultiInputEmptyRenderer=U5;exports.PYTHON_DEFAULT_CODE=tF;exports.PanelLeft=mF;exports.PanelResizeHandle=qk;exports.Paperclip=Nq;exports.PenLine=L2;exports.Pencil=$2;exports.PendingMessagesDisplay=Rfe;exports.PersistedDynamicVisual=Nj;exports.PiChartPolar=tde;exports.PivotTableTanstack=rb;exports.Placeholders=ude;exports.Play=kq;exports.Plus=dr;exports.PointerSensor=cb;exports.PrintMessages=cde;exports.Progress=J3;exports.RECOVERABLE_SQL_ERROR_CODES=G0t;exports.Radar=_q;exports.RadioGroup=Ia;exports.RadioGroupItem=js;exports.RefreshCw=Oc;exports.ResizableHandle=uK;exports.ResizablePanel=Ry;exports.ResizablePanelGroup=UF;exports.ResourceEditDialog=LG;exports.ResourceType=Xr;exports.SELF_HEAL_TIMELINE_STEP=Y0t;exports.Search=Ws;exports.SeedQuestions=Efe;exports.SemaphorContext=pg;exports.SemaphorContextProvider=lF;exports.SemaphorQueryClient=qW;exports.SemaphorReadyIndicator=m$;exports.SemaphorStyleWrapper=sb;exports.Send=bF;exports.Settings=xF;exports.Settings2=bg;exports.Share2=jq;exports.ShareDialog=OG;exports.Sheet=Aee;exports.SheetContent=BO;exports.SheetDescription=HO;exports.SheetHeader=Fee;exports.SheetTitle=VO;exports.SheetTrigger=DOe;exports.Slider=uhe;exports.SortableContext=iw;exports.Sparkles=Fm;exports.Square=Eq;exports.SquarePen=jk;exports.Star=yF;exports.StructuralParticipantSelector=Ole;exports.SummaryCard=sR;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ui;exports.TableBody=xh;exports.TableCell=sr;exports.TableColumnVisibilitySettings=bce;exports.TableHead=Ko;exports.TableHeader=Fg;exports.TablePresentationSettings=yce;exports.TableRow=Kr;exports.TableSkeleton=$L;exports.TableVisual=ud;exports.TbChartBubble=nde;exports.TbChartFunnel=rde;exports.TbChartTreemap=sde;exports.TextCard=og;exports.Textarea=Bh;exports.TiSortNumerically=ide;exports.Toggle=wj;exports.Tornado=Dq;exports.Trash2=yl;exports.TreePalm=wF;exports.TrendingUp=Iq;exports.TriangleAlert=ba;exports.TypeGlyph=Qv;exports.UXProvider=p$;exports.User=Mq;exports.UserRound=Tq;exports.Users=SF;exports.applyFilterOverridesToDashboardInputSlots=BZ;exports.areContextEntitiesEqual=zr;exports.areEntitiesJoined=JJ;exports.arrayMove=ub;exports.buildCardControlUsageById=Btt;exports.buildCustomCardTheme=Yv;exports.buildDashboardCardExecutionSnapshot=zZ;exports.buildDashboardControlUsageById=ztt;exports.buildDashboardExecutionSnapshot=RP;exports.buildDashboardInputExecutionSnapshot=Wu;exports.buildDashboardSheetsInputExecutionSnapshot=HZ;exports.buildDashboardStructuralParticipantIdsByControlId=Ule;exports.buildFilterFieldMeta=n3;exports.buildFilterSemanticContext=r3;exports.buildInlineFilterNodes=xL;exports.buildMultiInputCustomVisualProps=NL;exports.buildScheduleExpr=xvt;exports.buildSchedulePreview=wvt;exports.buildSlotOrderedCards=vL;exports.calculateContextAwareFilters=dv;exports.calculateFieldState=MO;exports.canUserAccessVisuals=bKe;exports.canUserCreateDashboards=gKe;exports.canUserEdit=hKe;exports.canUserManageDashboards=mKe;exports.canUserManageGroups=xKe;exports.canUserUseFilters=pKe;exports.cancelExport=bPe;exports.chartSupportsDataLabels=WQ;exports.chartSupportsLegend=HQ;exports.chartTypes=iE;exports.cleanupKpiMetricComparisonMode=Yae;exports.cloneDeep=Zo;exports.cloneLinkedFrameWithSourceMapping=LGe;exports.closestCenter=nw;exports.commitSharedCalculatedFields=af;exports.createAssistantConversationId=qp;exports.createAssistantRequestId=_fe;exports.createCardsFromSlots=eYe;exports.createChartConfig=Ag;exports.createDashboardControlInputFromControl=Pst;exports.createDefaultGlobalDateFilter=ZCe;exports.createExport=yee;exports.createUniqueDashboardInputVariableNameFromName=Ju;exports.dedup=Jxt;exports.doesStoredFilterMatchField=ug;exports.downloadDocumentPdf=PP;exports.downloadPdf=XZ;exports.extractSqlParamReferences=Yse;exports.extractTableMetadata=t3;exports.fieldAlreadyExists=tee;exports.findCustomVisualConfigCard=SL;exports.findDashboardFrameById=BCe;exports.flexRender=Qo;exports.formatDisplayFormula=AJe;exports.formatFileSize=vPe;exports.formatFilterLine=CX;exports.formatTimeLabel=fhe;exports.getAutoDetectedChartIcon=Wft;exports.getChartGridStyle=v_e;exports.getChartIconByType=qft;exports.getColorForValue=uM;exports.getConfigSlotExpectedType=Jqe;exports.getCoreRowModel=O_;exports.getCustomVisualInputCards=wL;exports.getDateFormatOptionsForGranularity=j0;exports.getDefaultAxisConfig=fM;exports.getDefaultChartColors=qh;exports.getDefaultDataLabelsConfig=Cv;exports.getDefaultExportFormat=zX;exports.getDefaultFilterSql=tL;exports.getDefaultLegendConfig=mO;exports.getDefaultRunningTotalPartitionByFieldIds=vy;exports.getDocumentSectionEditorCard=xtt;exports.getDocumentSheetDashboardInputs=dw;exports.getDownloadUrl=gPe;exports.getEffectiveCardTypeForSlot=pm;exports.getEntityIcon=xk;exports.getErrorMessage=xfe;exports.getExportStatus=mPe;exports.getExports=pPe;exports.getExpressionFieldKind=bd;exports.getFieldExpressionAnnotation=s3;exports.getFilterCount=VN;exports.getGlobalDateFilter=wg;exports.getGlobalDateFilterCoverage=XCe;exports.getGranularityOptionsForFieldType=S3;exports.getKeys=pr;exports.getMetricDisplayLabel=PFe;exports.getNewField=iee;exports.getObjectDiff=_W;exports.getPaginationRowModel=L_;exports.getRoleBasedDisplayOverrides=Rie;exports.getRunningTotalOrderByCandidates=nJe;exports.getSelectedDateFilterColumn=Kse;exports.getSheetScopedFilterValues=Ly;exports.getSlotDefinitionForIndex=yL;exports.getSlotExpectedChartType=yj;exports.getSlotIndexForCard=y0;exports.getSortedRowModel=Mee;exports.getSupportedExportFormats=$X;exports.getTableConditionalFormattingColumnOptions=Cce;exports.getTableOutputColumnOptions=Nce;exports.getTablePageSizeOptions=gee;exports.handleAggregationChange=lR;exports.handleAggregationLabelChange=Mie;exports.hasFlatTableTotalsBehavior=WNe;exports.horizontalListSortingStrategy=qL;exports.isCalculatedFilterField=E0;exports.isCardSummaryVisibleOnCard=kL;exports.isCustomVisualConfigCard=nR;exports.isDefaultColor=eke;exports.isEligibleFlatTableTotalsCard=Sg;exports.isExportComplete=yPe;exports.isExportInProgress=xPe;exports.isInAiScopeArray=Qxt;exports.isManagedCalculatedExpressionField=ka;exports.isMetricTransformEnabled=eJe;exports.isPromiseLike=KR;exports.isSubtotalEnabledAggregateTable=e3;exports.isSupportedDocumentTableCardType=ytt;exports.lastAssistantMessageIsCompleteWithToolCalls=pfe;exports.merge=xl;exports.mergeAxisConfig=hM;exports.normalizeConditionalFormatting=jP;exports.normalizeContextFormatMode=DX;exports.normalizeDashboardInputVariableName=J0;exports.normalizeMultiInputPayload=CL;exports.parseScheduleExpr=bvt;exports.pivotData=gv;exports.prepareFeedbackData=oE;exports.purify=PA;exports.reindexSlotCards=Qqe;exports.remarkGfm=Bue;exports.removeFromScopeArray=eyt;exports.resolveDashboardInputContext=$l;exports.resolveDomainCalculatedFieldForEdit=Iet;exports.resolveMultiInputType=Gv;exports.resolveMultiInputTypeFromVisual=tYe;exports.resolveTablePageSize=R_;exports.resolveTablePresentationStyle=JO;exports.sanitizeAIScope=bfe;exports.saveCalculatedFieldToCardScope=vR;exports.saveCalculatedFieldToSharedScope=vle;exports.saveCalculatedFieldToSheetScope=wR;exports.seedSemanticMetricFormatDefaults=Kae;exports.setTableColumnVisibility=See;exports.setupEditorWithCard=h_;exports.showAllTableColumns=NPe;exports.showJoinRequiredNotification=eee;exports.sortByColumnsToSortState=tte;exports.sortStateToSortByColumns=nte;exports.sortableKeyboardCoordinates=GL;exports.supportsMetricTransformForMetric=Gae;exports.supportsTableConditionalFormatting=vce;exports.toEntityArray=Na;exports.ue=ut;exports.useActiveExports=awe;exports.useActiveToolStatus=Lfe;exports.useAddFrameWithFreshSemanticExecutionPayload=OL;exports.useAddNewFrame=tae;exports.useAssistantContainer=bK;exports.useAssistantContextEntities=jj;exports.useAssistantLayoutStore=Hf;exports.useAssistantPanel=mK;exports.useAssistantProfile=jfe;exports.useAutoScroll=Pfe;exports.useAutoSubmitQueue=Ffe;exports.useBrandStudioPreview=f0t;exports.useCard=GFe;exports.useCardFilterValues=lee;exports.useCardSummary=_L;exports.useChat=gfe;exports.useColumns=XL;exports.useCreateVisualWithFrame=Ybe;exports.useCurrentUserInfo=ta;exports.useCustomVisual=Qh;exports.useCustomVisualsQuery=mL;exports.useDashboardAppearance=Rl;exports.useDashboardById=LY;exports.useDashboardCreation=BY;exports.useDashboardManagement=zY;exports.useDashboardPreferences=xg;exports.useDashboardQuery=Q0;exports.useDashboardStructuralParticipants=Wle;exports.useDashboardSummary=pie;exports.useDataColumns=Xae;exports.useDateFilterHook=M7e;exports.useDebounce=py;exports.useDefaultDashboardMutation=MY;exports.useDisplayPreferences=Ll;exports.useDroppable=Nae;exports.useEditorAside=Bj;exports.useEditorCardQuery=f_;exports.useEnsureReactGlobals=Sse;exports.useExportActions=xK;exports.useExportStore=Yk;exports.useFieldManagement=Zae;exports.useFilterableFields=Uae;exports.useFullscreenAssistant=gK;exports.useGroupMembers=Vxe;exports.useGroups=DG;exports.useHasDashboardId=yK;exports.useInProgressExportsCount=lwe;exports.useIsDashboardSelected=Rpe;exports.useIsVisualSelected=Fpe;exports.useJoinabilityMap=JL;exports.useManagementActions=Ph;exports.useManagementStore=is;exports.useMessageWindow=Ofe;exports.useMutation=co;exports.usePivotTableConfig=Gh;exports.usePluginQuery=eie;exports.useQuery=On;exports.useQueryClient=ns;exports.useReactTable=$_;exports.useResolveExistingFrameSemanticExecutionPayload=VGe;exports.useResourceManagement=Rk;exports.useResourceUpdateState=$Y;exports.useScopedFields=Hae;exports.useSelectedVisual=Ape;exports.useSemaphorContext=Ct;exports.useSensor=cg;exports.useSensors=Tj;exports.useSortable=db;exports.useStarredChartsStore=X0t;exports.useSurfaceAppearance=Zc;exports.useTableQueryState=qee;exports.useTextFilterHook=H7e;exports.useTheme=nF;exports.useTopoJson=kv;exports.useUnifiedUsers=OF;exports.useUpdateResource=RY;exports.useUpdateVisualMutation=Gbe;exports.useUserPreferences=lG;exports.useVisualById=Ak;exports.useVisualManagement=qbe;exports.validateFieldForChartType=qae;exports.verticalListSortingStrategy=YL;