react-semaphor 0.1.322 → 0.1.323

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 (26) hide show
  1. package/dist/chunks/{calendar-preferences-dialog-t0OOALVd.js → calendar-preferences-dialog-B9Hz3pTH.js} +1 -1
  2. package/dist/chunks/{calendar-preferences-dialog-CZqePF6B.js → calendar-preferences-dialog-CLXaVo3h.js} +1 -1
  3. package/dist/chunks/{dashboard-briefing-launcher-d1_fm91W.js → dashboard-briefing-launcher-COLpvReF.js} +1 -1
  4. package/dist/chunks/{dashboard-briefing-launcher-BYbnbZ9e.js → dashboard-briefing-launcher-CUEn7cr6.js} +3 -3
  5. package/dist/chunks/{dashboard-controls-BuChCKDm.js → dashboard-controls-CLShFyUq.js} +858 -846
  6. package/dist/chunks/dashboard-controls-DH8gdpOc.js +52 -0
  7. package/dist/chunks/{dashboard-json-DgoYjD0O.js → dashboard-json-Db0DpTMw.js} +1 -1
  8. package/dist/chunks/{dashboard-json-M5-VFCtZ.js → dashboard-json-eGBWfSN1.js} +1 -1
  9. package/dist/chunks/{edit-dashboard-visual-BH8DP1qq.js → edit-dashboard-visual-Cc3xpTNQ.js} +1 -1
  10. package/dist/chunks/{edit-dashboard-visual-DP31ytwJ.js → edit-dashboard-visual-DmMKWtln.js} +3 -3
  11. package/dist/chunks/{index-CodH6sqg.js → index-CMS4bp9G.js} +1 -1
  12. package/dist/chunks/{index-ChmS5nsv.js → index-PTx7430W.js} +4 -4
  13. package/dist/chunks/{resource-management-panel-gt__S0Pb.js → resource-management-panel-C1mbF-2a.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-D3vO68dH.js → resource-management-panel-DR7Ku6sa.js} +1 -1
  15. package/dist/chunks/{use-create-flow-overlay-state-OA3iI54p.js → use-create-flow-overlay-state-B65gg2oB.js} +2 -2
  16. package/dist/chunks/{use-create-flow-overlay-state-BZaSpL-c.js → use-create-flow-overlay-state-CmxTpqeg.js} +1 -1
  17. package/dist/chunks/{use-visual-utils-CMucAqbS.js → use-visual-utils-51Nsy8cj.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-CsXS-Zeh.js → use-visual-utils-Diuguy3D.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/surfboard/index.cjs +1 -1
  24. package/dist/surfboard/index.js +2 -2
  25. package/package.json +1 -1
  26. package/dist/chunks/dashboard-controls-B3HHMRPC.js +0 -52
@@ -1300,4 +1300,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1300
1300
 
1301
1301
  `)},flush(e){e.enqueue(`data: [DONE]
1302
1302
 
1303
- `)}})}});var Dmt=Sht(()=>sce(Ci([vr({type:cn("text-start"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("text-delta"),id:Rt(),delta:Rt(),providerMetadata:$r.optional()}),vr({type:cn("text-end"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("error"),errorText:Rt()}),vr({type:cn("tool-input-start"),toolCallId:Rt(),toolName:Rt(),providerExecuted:hs().optional(),dynamic:hs().optional()}),vr({type:cn("tool-input-delta"),toolCallId:Rt(),inputTextDelta:Rt()}),vr({type:cn("tool-input-available"),toolCallId:Rt(),toolName:Rt(),input:xa(),providerExecuted:hs().optional(),providerMetadata:$r.optional(),dynamic:hs().optional()}),vr({type:cn("tool-input-error"),toolCallId:Rt(),toolName:Rt(),input:xa(),providerExecuted:hs().optional(),providerMetadata:$r.optional(),dynamic:hs().optional(),errorText:Rt()}),vr({type:cn("tool-output-available"),toolCallId:Rt(),output:xa(),providerExecuted:hs().optional(),dynamic:hs().optional(),preliminary:hs().optional()}),vr({type:cn("tool-output-error"),toolCallId:Rt(),errorText:Rt(),providerExecuted:hs().optional(),dynamic:hs().optional()}),vr({type:cn("reasoning-start"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("reasoning-delta"),id:Rt(),delta:Rt(),providerMetadata:$r.optional()}),vr({type:cn("reasoning-end"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("source-url"),sourceId:Rt(),url:Rt(),title:Rt().optional(),providerMetadata:$r.optional()}),vr({type:cn("source-document"),sourceId:Rt(),mediaType:Rt(),title:Rt(),filename:Rt().optional(),providerMetadata:$r.optional()}),vr({type:cn("file"),url:Rt(),mediaType:Rt(),providerMetadata:$r.optional()}),vr({type:ece(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Rt().optional(),data:xa(),transient:hs().optional()}),vr({type:cn("start-step")}),vr({type:cn("finish-step")}),vr({type:cn("start"),messageId:Rt().optional(),messageMetadata:xa().optional()}),vr({type:cn("finish"),finishReason:Xle(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:xa().optional()}),vr({type:cn("abort")}),vr({type:cn("message-metadata"),messageMetadata:xa()})])));function Tmt(e){return e.type.startsWith("data-")}function hce(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 o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?n[r]=hce(s,o):n[r]=o}return n}function Imt(e){const t=["ROOT"];let n=-1,r=null;function o(l,u,d){switch(l){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 s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":o(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,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":{o(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,o(u,l,"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=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;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=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){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 mce(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await HC({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await HC({text:Imt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function R1(e){return e.type.startsWith("tool-")}function Mmt(e){return e.type==="dynamic-tool"}function YM(e){return R1(e)||Mmt(e)}function S7(e){return e.type.split("-").slice(1).join("-")}function Amt({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 Rmt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,g;function b(C){const k=u.message.parts.filter(R1).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(T=>R1(T)&&T.toolCallId===C.toolCallId),_=C,j=k;k!=null?(k.state=C.state,j.input=_.input,j.output=_.output,j.errorText=_.errorText,j.rawInput=_.rawInput,j.preliminary=_.preliminary,j.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 v(C){var N,k;const _=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),j=C,T=_;_!=null?(_.state=C.state,T.toolName=C.toolName,T.input=j.input,T.output=j.output,T.errorText=j.errorText,T.rawInput=(N=j.rawInput)!=null?N:T.rawInput,T.preliminary=j.preliminary,T.providerExecuted=(k=j.providerExecuted)!=null?k:_.providerExecuted,j.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,providerExecuted:j.providerExecuted,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?hce(u.message.metadata,C):C;t!=null&&await b7({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=(m=a.providerMetadata)!=null?m: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(R1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?v({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 mce(C.text);C.dynamic?v({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?v({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(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?v({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);v({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:S7(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);v({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:S7(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":{o==null||o(new Error(a.errorText));break}default:if(Tmt(a)){(n==null?void 0:n[a.type])!=null&&await b7({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()}}l.enqueue(a)})}}))}async function Fmt({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()}}nv({prefix:"aitxt",size:24});nv({prefix:"aiobj",size:24});var Pmt=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()})}};nv({prefix:"aiobj",size:24});var Omt={};ymt(Omt,{object:()=>$mt,text:()=>Lmt});var Lmt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),$mt=({schema:e})=>{const t=bmt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await mce(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await HC({text:n});if(!o.success)throw new v7({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await nL({value:o.value,schema:t});if(!s.success)throw new v7({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}};async function zmt(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,o=await new Promise((s,i)=>{const a=new FileReader;a.onload=l=>{var u;s((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:o}}))}var Bmt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:s,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=s,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,o,s,i;const a=await jh(this.body),l=await jh(this.headers),u=await jh(this.credentials),d={...pd(l),...pd(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,m=(f==null?void 0:f.headers)!==void 0?pd(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=(o=f==null?void 0:f.credentials)!=null?o:u,y=await((s=this.fetch)!=null?s:globalThis.fetch)(h,{method:"POST",headers:p7({"Content-Type":"application/json",...m},`ai-sdk/${w7}`,m7()),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,o,s;const i=await jh(this.body),a=await jh(this.headers),l=await jh(this.credentials),u={...pd(a),...pd(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:l,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?pd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"GET",headers:p7(h,`ai-sdk/${w7}`,m7()),credentials:m});if(b.status===204)return null;if(!b.ok)throw new Error((s=await b.text())!=null?s:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},oL=class extends Bmt{constructor(e={}){super(e)}processResponseStream(e){return kht({stream:e,schema:Dmt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Vmt=class{constructor({generateId:e=pht,id:t=e(),transport:n=new oL,messageMetadataSchema:r,dataPartSchemas:o,state:s,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Pmt,this.sendMessage=async(f,h)=>{var m,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await zmt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const v=this.state.messages.findIndex(w=>w.id===f.messageId);if(v===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[v].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,v+1),this.state.replaceMessage(v,{...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 m=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+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:m,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const v=this.state.messages,w=v[v.length-1];this.state.replaceMessage(v.length-1,{...w,parts:w.parts.map(C=>YM(C)&&C.toolCallId===m?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>YM(C)&&C.toolCallId===m?{...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=o,this.state=s,this.onError=i,this.onToolCall=a,this.onFinish=l,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:o}){var s,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:Amt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;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:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:o});const b=x=>this.jobExecutor.run(()=>x({state:m.state,write:()=>{var y;this.setStatus({status:"streaming"}),m.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Fmt({stream:Rmt({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(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}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:(s=this.activeResponse)==null?void 0:s.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function pce({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((o,s,i)=>s.type==="step-start"?i:o,-1),r=t.parts.slice(n+1).filter(YM).filter(o=>!o.providerExecuted);return r.length>0&&r.every(o=>o.state==="output-available"||o.state==="output-error")}function Hmt(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(...s){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,s)):n=setTimeout(()=>{r=Date.now(),e.apply(this,s)},l)}}var Umt=Hmt;const qmt=p.getDefaultExportFromCjs(Umt);var gce=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},cr=(e,t,n)=>(gce(e,t,"read from private field"),n?n.call(e):t.get(e)),fa=(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)},yc=(e,t,n,r)=>(gce(e,t,"write to private field"),t.set(e,n),n);function Wmt(e,t){return t!=null?qmt(e,t):e}var ni,F1,P1,Tb,Ib,Mb,zh,GM,KM,Ymt=class{constructor(e=[]){fa(this,ni,void 0),fa(this,F1,"ready"),fa(this,P1,void 0),fa(this,Tb,new Set),fa(this,Ib,new Set),fa(this,Mb,new Set),this.pushMessage=t=>{yc(this,ni,cr(this,ni).concat(t)),cr(this,zh).call(this)},this.popMessage=()=>{yc(this,ni,cr(this,ni).slice(0,-1)),cr(this,zh).call(this)},this.replaceMessage=(t,n)=>{yc(this,ni,[...cr(this,ni).slice(0,t),this.snapshot(n),...cr(this,ni).slice(t+1)]),cr(this,zh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Wmt(t,n):t;return cr(this,Tb).add(r),()=>{cr(this,Tb).delete(r)}},this["~registerStatusCallback"]=t=>(cr(this,Ib).add(t),()=>{cr(this,Ib).delete(t)}),this["~registerErrorCallback"]=t=>(cr(this,Mb).add(t),()=>{cr(this,Mb).delete(t)}),fa(this,zh,()=>{cr(this,Tb).forEach(t=>t())}),fa(this,GM,()=>{cr(this,Ib).forEach(t=>t())}),fa(this,KM,()=>{cr(this,Mb).forEach(t=>t())}),yc(this,ni,e)}get status(){return cr(this,F1)}set status(e){yc(this,F1,e),cr(this,GM).call(this)}get error(){return cr(this,P1)}set error(e){yc(this,P1,e),cr(this,KM).call(this)}get messages(){return cr(this,ni)}set messages(e){yc(this,ni,[...e]),cr(this,zh).call(this)}};ni=new WeakMap;F1=new WeakMap;P1=new WeakMap;Tb=new WeakMap;Ib=new WeakMap;Mb=new WeakMap;zh=new WeakMap;GM=new WeakMap;KM=new WeakMap;var Bh,C7=class extends Vmt{constructor({messages:e,...t}){const n=new Ymt(e);super({...t,state:n}),fa(this,Bh,void 0),this["~registerMessagesCallback"]=(r,o)=>cr(this,Bh)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>cr(this,Bh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>cr(this,Bh)["~registerErrorCallback"](r),yc(this,Bh,n)}};Bh=new WeakMap;function bce({experimental_throttle:e,resume:t=!1,...n}={}){const r=S.useRef("chat"in n?n.chat:new C7(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new C7(n));const s="id"in n?n.id:null,i=S.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,s]),a=S.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=S.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=S.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=S.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return S.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:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Gmt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Kmt(e){return e.filter((n,r,o)=>r===o.findIndex(s=>s.tableName===n.tableName&&s.datamodelName===n.datamodelName))}function Zmt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function Xmt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function xce(e){return e.map(r=>{const o=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:o,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:o,tableReferenceFormat:Xmt(o)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function yce(e){var n,r;if(!e)return"";let t="";try{const o=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=o==null?void 0:o.error)==null?void 0:n.lastError)==null?void 0:r.message)||(o==null?void 0:o.error)||e.message}catch{t=e.message}return t}function A_(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function vce(e,t,n){const r=A_(e,t);if(!r)return[];const o=s=>{var i;return{sourceCard:s,visibleCard:((i=n==null?void 0:n[s.id])==null?void 0:i.visibleCard)||s,...n!=null&&n[s.id]?{replacedCard:n[s.id]}:{}}};return(r.frames||[]).map(s=>Dk(s)).filter(s=>s!==void 0).map(o)}function wce(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 Qmt(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 Xh(e){return(e||[]).map(Qmt)}function Sce(e){return Xh([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function sL(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 Jmt(e,t,n){const r=new Map((e||[]).map(o=>[o.id,o]));return(t||[]).map(o=>{const s=r.get(o.filterId);return{filterId:o.filterId,label:(s==null?void 0:s.title)||o.label||o.name||o.filterId,...s!=null&&s.type?{type:s.type}:{},...s!=null&&s.column||o.name?{column:(s==null?void 0:s.column)||o.name}:{},...s!=null&&s.dataType?{dataType:s.dataType}:{},origin:n,...sL(o)}})}function ept(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...sL(t)}))}function Cce(e,t){var n,r,o,s,i,a,l;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(o=e.field)!=null&&o.qualifiedFieldName||(s=e.field)!=null&&s.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(l=e.field)!=null&&l.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function bT(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((o,s)=>Cce(o,`${t}:${r}:${s}`)))}function tpt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function npt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function rpt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(npt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...sL(r)})),n=e.filter(tpt).map((r,o)=>Cce(r,`replaced-insight:${o}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function opt({card:e,interactionStates:t,currentDashboardId:n}){var l;if(!t)return[];const r=p.getClickFiltersForCardFromStates(e.id,t),o=t[p.DRILL_CONTEXT_CARD_ID],i=(o==null?void 0:o.targetDashboardId)===n&&(o==null?void 0:o.contextMode)!=="none"?(o==null?void 0:o.appliedClickFilters)||[]:[],a=((l=t[e.id])==null?void 0:l.breadcrumbs)??[];return[...r.flatMap((u,d)=>bT(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>bT(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>bT(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Nce(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=>Nce(t)).filter(Boolean)}:null}function kce(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==rA.trim()}function spt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":kce(e)?"custom-python":"config"}function _ce({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:o,runtimeFilterValues:s,interactionStates:i,inlineFilterValuesMap:a}){const l=A_(r,o.selectedSheetId),u=(l==null?void 0:l.id)||o.selectedSheetId,{finalConfig:d}=Qy({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:s??o.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=Xy({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:s??o.activeFilters,selectedSheetId:u}),h=rpt(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:Jmt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:ept(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:opt({card:t,interactionStates:i,currentDashboardId:r.id})}}function ipt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:o,inlineFilterValuesMap:s,replacedCard:i,renderOrder:a}){const{finalConfig:l}=_ce({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:o,inlineFilterValuesMap:s});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:Xh(l.metricColumns),dimensions:Sce(l),selectedEntities:wce(t)}}function apt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function N7({dashboard:e,selectedSheetId:t,activeFilters:n}){var o;const r=((o=A_(e,t??null))==null?void 0:o.id)||t||null;return{selectedSheetId:r,activeFilters:Sx(e.filters,n,r)}}function lpt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:o}){const s=A_(e,t.selectedSheetId),i=(s==null?void 0:s.id)||t.selectedSheetId,a=vce(e,t.selectedSheetId,o),l=sc(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(s==null?void 0:s.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>ipt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:l.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:apt({activeFilters:t.activeFilters})}}function cpt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:o,inlineFilterValuesMap:s,replacedCards:i}){var w,C;const l=vce(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!l)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}=l,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:g,interactionFilterValues:b}=_ce({sourceCard:u,card:d,replacedCard:f,interactionStates:o,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:s}),{comparisonType:x,targetValue:y}=XBe(h,d.type),v=spt(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:v,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...kce(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:wce(d),metrics:Xh(h.metricColumns),dimensions:Sce(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Nce(h.filters),effectiveDashboardFilters:m,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:Xh(h.groupByColumns),pivotBy:Xh(h.pivotByColumns),sortBy:Xh(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...v==="custom-sql"?["This card runs custom SQL."]:v==="custom-python"?["This card runs custom Python."]:[]]}}function Vh(){return crypto.randomUUID()}function jce(){return crypto.randomUUID()}function ZM(e){return typeof(e==null?void 0:e.then)=="function"}async function upt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const o=Object.entries(e);if(o.length===0||!n)return{};const s=await Promise.all(o.map(async([i,a])=>{const l=["resource-by-id",Or.VISUAL,a.insightId];let u=r.getQueryData(l);if(!u)try{u=await r.fetchQuery({queryKey:l,queryFn:()=>p.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=wte(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(s.filter(i=>i!==null))}function dpt({dynamicVisualMode:e="auto"}={}){var A;const{compiledAppearance:t}=p.useAppearance(),n=S.useMemo(()=>GP(t),[t]),r=S.useRef(n);S.useEffect(()=>{r.current=n},[n]);const{authToken:o,tokenProps:s}=xt(),i=Vr(),a=p.useDashboardStore(z=>z.dashboard.aiScopeTables),l=(A=Ly().data)==null?void 0:A.assistantProfileId,u=S.useRef(null),d=S.useRef(Vh()),f=S.useRef(!1),h=S.useRef(!1),m=S.useRef(e);m.current=e;function g(){const z=p.useAIInteractionStore.getState(),L=p.useDashboardStore.getState(),U=jte({overrides:z.dashboardEntitySelectionOverrides,dashboardId:L.dashboard.id,draftScopeKey:L.dashboardAssistantDraftScopeKey});return p.appendQualifiedEntityNameToAIContext(s9e({currentAIContext:z.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:L.dashboard.aiContext,derivedSelectedSheetEntities:_te(L.dashboard,L.selectedSheetId)}))}function b(){const z=p.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:N7({dashboard:z.dashboard,selectedSheetId:z.selectedSheetId,activeFilters:z.filterValues})}}const{sendMessage:x,messages:y,setMessages:v,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:j}=bce({transport:new oL({api:`${s.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=p.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:L,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:l,conversationId:d.current,assistantRequestId:jce(),aiContext:L,dashboardViewState:U,dynamicVisualMode:m.current,dynamicVisualTheme:r.current,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:L})=>({body:{...L,messages:p.cleanupIncompleteMessages(z)}})}),onToolCall:I,sendAutomaticallyWhen:pce,onFinish({message:z,isAbort:L,isDisconnect:U,isError:H}){var P;h.current=!1,z!=null&&z.id&&((P=u.current)!=null&&P.aiContext)&&p.useAIInteractionStore.getState().actions.setAssistantMessageContext(z.id,u.current.aiContext),console.log(L?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":H?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]))},onError(z){var L;if(h.current=!1,z.name==="AbortError"||(L=z.message)!=null&&L.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]));return}console.error("[Dashboard Assistant] Stream error:",z),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]))}}),T=S.useCallback((...z)=>{h.current=!0;try{const L=x(...z);return ZM(L)?L.catch(U=>{throw h.current=!1,U}):L}catch(L){throw h.current=!1,L}},[x]),E=S.useCallback((...z)=>{h.current=!0;try{const L=w(...z);return ZM(L)?L.catch(U=>{throw h.current=!1,U}):L}catch(L){throw h.current=!1,L}},[w]),D=z=>{let L=!1;v(U=>{const H=typeof z=="function"?z(U):z;if(H.length===0){if(h.current)return f.current=!0,L=!0,U;f.current=!1,d.current=Vh()}return H}),L&&_()};async function I({toolCall:z}){var M,G;if(z.toolName==="getCurrentTableScope"){N({tool:z.toolName,toolCallId:z.toolCallId,output:{tables:xce(a||[])}});return}const L=p.useDashboardStore.getState().dashboard,U=p.useDashboardStore.getState().inlineFilterValuesMap,H=p.useInteractionStore.getState(),P=H.interactionStates,K=await upt({replacedCards:H.replacedCards,apiServiceUrl:s.apiServiceUrl,accessToken:(o==null?void 0:o.accessToken)||"",queryClient:i}),Y=N7({dashboard:L,selectedSheetId:p.useDashboardStore.getState().selectedSheetId,activeFilters:p.useDashboardStore.getState().filterValues});if(z.toolName==="getDashboardSynopsis"){N({tool:z.toolName,toolCallId:z.toolCallId,output:lpt({dashboard:L,viewState:Y,interactionStates:P,inlineFilterValuesMap:U,replacedCards:K})});return}if(z.toolName==="getCardContext"){const $=((M=z.input)==null?void 0:M.cardId)||((G=z.args)==null?void 0:G.cardId)||"";N({tool:z.toolName,toolCallId:z.toolCallId,output:cpt({dashboard:L,viewState:Y,cardId:$,runtimeFilterValues:p.useDashboardStore.getState().filterValues,interactionStates:P,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),O=yce(k);return{sendMessage:T,regenerate:E,isLoading:F,messages:y,setMessages:D,status:C,stop:_,errorMessage:O,clearError:j}}function Ece(){var u;const{authToken:e,tokenProps:t}=xt(),n=(u=Ly().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:o,isLoading:s,isFetching:i,isError:a}=Dn({queryKey:["assistant-profile",n],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:o==null?void 0:o.assistantProfile,isLoading:s,isFetching:i,isError:a}}function Dce({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(FH,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(p.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function fpt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const o=S.useRef(null),s=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=fl-n;if(l.length>u){Xe.error(`You can only attach ${fl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=Yae(l);if(f.forEach(({file:h,error:m})=>{Xe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>q5(m)));e(h)}catch(h){console.error("Failed to process files:",h),Xe.error("Failed to process one or more files")}o.current&&(o.current.value="")},i=()=>{var a;(a=o.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:o,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:s,className:"hidden",disabled:t||n>=fl}),c.jsx(p.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=fl,title:n>=fl?`Maximum ${fl} files allowed`:"Attach files",children:c.jsx(WH,{className:"h-4 w-4 text-muted-foreground"})})]})}function hpt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:o}){const[s,i]=S.useState(!1),a=S.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=S.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,g=f.clientY;(m<h.left||m>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=S.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=S.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 m=fl-r;if(h.length>m){Xe.error(`You can only attach ${fl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:g,errors:b}=Yae(h);if(b.forEach(({file:x,error:y})=>{Xe.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>q5(y)));t(x),Xe.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),Xe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:p.cn("relative",o),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,s&&!n&&c.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:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(p.Upload,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[fl-r," slot(s) available"]})]})})]})}function mpt(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 ppt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!mpt(e,t,n):r}function Tce(e){const{tokenProps:t}=xt(),n=p.useDashboardStore(l=>l.authToken)||e;p.useEditorStore(l=>l.selectedConnectionId),p.useEditorStore(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:o,data:s,isLoading:i,isError:a}=Dn({queryKey:["semantic-domains"],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:o,error:a,semanticDomainsData:s,semanticDomains:(s==null?void 0:s.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function gpt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:o}){const{semanticDomains:s,isSemanticDomainsLoading:i}=Tce(),a=S.useMemo(()=>xpt(s,e),[s,e]),l=S.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&l.length===0)return c.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(l.length===0)return null;const u=!!n;return c.jsxs("div",{children:[c.jsx(Ice,{label:"Semantic Domains"}),l.map(d=>c.jsx(bpt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:o},d.id))]})}function bpt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:o}){const[s,i]=S.useState(!1),a=s||t.length>0||!!n,{datasets:l,isPending:u}=K0e(a?e.id:void 0),d=S.useMemo(()=>{if(!t)return l;const x=t.trim().toLowerCase();return l.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[l,t]),f=t.length>0&&d.length>0,h=s||f||!!n,m=l.length,g=S.useMemo(()=>d.filter(x=>r.some(y=>Cr(y,xT(x)))).length,[d,r]),b=x=>{const y=xT(x),v=r.some(w=>Cr(w,y));o(v?r.filter(w=>!Cr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:c.jsxs("div",{children:[c.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:[c.jsx(Nr,{className:p.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),m>0&&c.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",m," dataset",m===1?"":"s"," · curated"]}),c.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&c.jsx("ul",{className:"space-y-px pb-1",children:u&&l.length===0?c.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?c.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=xT(x),v=r.some(w=>Cr(w,y));return c.jsx("li",{children:c.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[c.jsx(Cn,{checked:v,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),c.jsx(gi,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),c.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&&c.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ice({label:e}){return c.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function xpt(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 xT(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,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function ypt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:o,isConnectionsLoading:s}=rc(),i=S.useMemo(()=>t?o.filter(l=>l.id===t):o,[o,t]);if(s&&i.length===0)return c.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 c.jsxs("div",{children:[c.jsx(Ice,{label:"Direct Sources"}),i.map(l=>c.jsx(vpt,{connection:l,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},l.id))]})}function vpt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:o}){var g;const[s,i]=S.useState(!1),a=s||t.length>0||!!n,l=((g=e.capabilities)==null?void 0:g.path)??[],u=l.includes("database"),d=l.includes("schema"),f=e.type==="upload",h=e.type==="url",m=S.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return c.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[c.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:[c.jsx(Nr,{className:p.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),c.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),c.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:m>0?m:""})]}),a&&c.jsxs(c.Fragment,{children:[f?c.jsx(wpt,{connection:e,selectedEntities:r,onSelectionChange:o}):h?c.jsx(Spt,{connection:e,selectedEntities:r,onSelectionChange:o}):u?c.jsx(Cpt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:o}):d?c.jsx(Mce,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:o}):c.jsx(iL,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:o}),!f&&!h&&c.jsx(Npt,{connection:e,search:t,selectedEntities:r,onSelectionChange:o})]})]})}function wpt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,o=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),s=a=>{if(!(a!=null&&a.length))return;const l=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,...l])},i=a=>{n(t.filter(l=>!("id"in l&&l.id===a&&l.connectionId===e.id&&(l.type==="upload"||l.type==="file"))))};return c.jsxs("div",{className:"space-y-2 px-8 py-2",children:[c.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[c.jsx(p.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),c.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>s(a.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(p.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"})]}),o.length>0&&c.jsx("ul",{className:"space-y-1",children:o.map(a=>c.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[c.jsx(Ys,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),c.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:c.jsx(p.X,{className:"h-3 w-3"})})]},a.id))})]})}function Spt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,o]=S.useState(""),[s,i]=S.useState(""),[a,l]=S.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),m=s.trim();if(!h||!m)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:m,sourceType:a};n([...t,g]),o(""),i(""),l("api")},f=h=>{n(t.filter(m=>!("id"in m&&m.id===h&&m.connectionId===e.id&&m.type==="url")))};return c.jsxs("div",{className:"space-y-2 px-8 py-2",children:[c.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[c.jsx(p.Input,{value:r,onChange:h=>o(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),c.jsx(p.Input,{value:s,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("select",{value:a,onChange:h=>l(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[c.jsx("option",{value:"api",children:"API endpoint"}),c.jsx("option",{value:"csv",children:"CSV file"}),c.jsx("option",{value:"json",children:"JSON file"})]}),c.jsxs(p.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!s.trim(),onClick:d,children:[c.jsx(pr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&c.jsx("ul",{className:"space-y-1",children:u.map(h=>c.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[c.jsx(hp,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"truncate text-[12px]",children:h.name}),c.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),c.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:c.jsx(p.X,{className:"h-3 w-3"})})]},h.id))})]})}function Cpt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:o}){var a;const s=R_("/v1/databases",{connection_id:e.id},["databases",e.id]);if(s.isLoading)return c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=s.data)==null?void 0:a.databases)??[];return i.length===0?c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):c.jsx("div",{children:i.map(l=>c.jsx(Ace,{label:l.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?c.jsx(Mce,{connection:e,databaseName:l.database_name,search:n,selectedEntities:r,onSelectionChange:o}):c.jsx(iL,{connection:e,databaseName:l.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:o}))},l.database_name))})}function Mce({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:o}){var a;const s=R_("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(s.isLoading)return c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=s.data)==null?void 0:a.schemas)??[];return i.length===0?c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):c.jsx("div",{children:i.map(l=>c.jsx(Ace,{label:l.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&c.jsx(iL,{connection:e,databaseName:t,schemaName:l.schema_name,search:n,selectedEntities:r,onSelectionChange:o})},l.schema_name))})}function iL({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:o,onSelectionChange:s}){const i=R_("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=S.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 c.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:c.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const l=(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=o.some(m=>Cr(m,f));s(h?o.filter(m=>!Cr(m,f)):[...o,f])};return c.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=o.some(m=>Cr(m,d));return c.jsx("li",{children:c.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:[c.jsx(Cn,{checked:f,onCheckedChange:()=>l(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),c.jsx(p.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),c.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 Npt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const o=R_("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),s=S.useMemo(()=>{var u;const a=((u=o.data)==null?void 0:u.datamodels)??[];if(!t)return a;const l=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(l))},[o.data,t]);if(o.isLoading||s.length===0)return null;const i=a=>{const l={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=>Cr(d,l));r(u?n.filter(d=>!Cr(d,l)):[...n,l])};return c.jsxs("div",{children:[c.jsx("div",{className:"px-8 pb-1 pt-2",children:c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),c.jsx("ul",{children:s.map(a=>{const l={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=>Cr(d,l));return c.jsx("li",{children:c.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:[c.jsx(Cn,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),c.jsx(pfe,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),c.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&c.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Ace({label:e,indentLevel:t,search:n,renderChildren:r}){const[o,s]=S.useState(!1),i=o||n.length>0,a=t===1?"pl-8":"pl-10";return c.jsxs("div",{children:[c.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:p.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[c.jsx(Nr,{className:p.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function R_(e,t,n,r=!0){const{tokenProps:o}=xt(),s=p.useDashboardStore(a=>a.authToken),i=S.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return Dn({queryKey:n,queryFn:()=>p.getRequest(`${o.apiServiceUrl}${e}`,(s==null?void 0:s.accessToken)||"",i),enabled:r&&!!(s!=null&&s.accessToken)&&Object.values(i).every(a=>a.length>0)})}function k7(e){return e.type==="dataset"&&e.label||e.name}function kpt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.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:[c.jsx("span",{className:"max-w-[180px] truncate",children:k7(n)}),c.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),t(n)},"aria-label":`Remove ${k7(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:c.jsx(p.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function _7(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 yT(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 aL({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:o,onSaveSelectedEntities:s,saveAsDashboardDefault:i=!1}){var se,Se;const{tokenProps:a}=xt(),l=a.config,u=a.semanticDomainAccess||Due.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=S.useState([]),[h,m]=S.useState(void 0),[g,b]=S.useState(""),[x,y]=S.useState("all"),[v,w]=S.useState(void 0),C=S.useRef(!1),{updateDataSource:N}=p.useEditorActions(),k=p.useDashboardStore(ye=>ye.isVisualEditing),_=p.useDashboardStore(ye=>ye.dashboard.aiContext),{setAiContext:j}=p.useDashboardActions(),T=u.mode,E=(l==null?void 0:l.showDirectSource)!==!1,D=T==="include"||T==="exclude"||!E,I=T!=="all",F=E&&!D,O=D?"semanticDomain":n.mode,A=r==="dataSource"&&!E,z=T==="include"&&(((se=u.domainIds)==null?void 0:se.length)||0)===1?(Se=u.domainIds)==null?void 0:Se[0]:void 0,L=S.useCallback(ye=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:ye,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...ye!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=S.useCallback(ye=>{N({...n,...ye})},[n,N]),H=S.useCallback(ye=>{if(r==="aiContext"){"semanticDomainId"in ye&&m(ye.semanticDomainId);return}U(ye)},[r,U]),P=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},S.useEffect(()=>{if(r==="aiContext"&&!e)return;if(D&&n.mode!=="semanticDomain"&&r==="dataSource"){L("semanticDomain");return}if(!I||O!=="semanticDomain")return;const ye=P,Ae=u.domainIds??[],ae=r==="aiContext"?d:n.selectedEntities,xe=((ae==null?void 0:ae.length)??0)>0,ve=((d==null?void 0:d.length)??0)>0;ppt({mode:T,currentDomainId:ye,scopedDomainIds:Ae,hasSelectedEntities:xe})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):m(void 0),ve&&f([]))},[D,I,O,n.mode,P,n.selectedEntities,r,h,d,e,u.domainIds,T,E,U,L]),S.useEffect(()=>{z&&!P&&H({semanticDomainId:z})},[z,P,H]),S.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(D?"semantic":"all");return}if(C.current)return;f([...o||[]]);const ye=r==="aiContext"?_7(o):void 0;m(n.semanticDomainId||ye),w(yT(o))},[e,r,o,n.semanticDomainId,D]);const K=ye=>{C.current=!0,f(d.filter(Ae=>!Cr(Ae,ye)))},Y=S.useCallback((ye,Ae)=>{C.current=!0,f(ye),w(Ae??yT(ye))},[]),M=()=>{var Ae,ae;if(r==="aiContext"){if(k&&N(n),i){const xe={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};j(xe)}s==null||s(d),t(!1);return}const ye=yT(d)??v??O;if(ye==="semanticDomain"){const xe=_7(d)||h||n.semanticDomainId,ve=((Ae=d==null?void 0:d[0])==null?void 0:Ae.connectionId)||n.connectionId,pe=((ae=d==null?void 0:d[0])==null?void 0:ae.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:xe,connectionId:ve,connectionType:pe,selectedEntities:d})}else if(ye==="upload"||ye==="url"){const xe=d==null?void 0:d[0];N({...n,mode:ye,semanticDomainId:void 0,connectionId:(xe==null?void 0:xe.connectionId)||n.connectionId,connectionType:(xe==null?void 0:xe.connectionType)||n.connectionType,selectedEntities:d})}else{const xe=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(xe==null?void 0:xe.connectionId)||n.connectionId,connectionType:(xe==null?void 0:xe.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Tce(),{connections:$}=rc(),q=ye=>{y(ye),ye==="semantic"||ye.startsWith("domain:")?n.mode!=="semanticDomain"&&L("semanticDomain"):(ye==="direct"||ye.startsWith("conn:"))&&n.mode==="semanticDomain"&&L("database")},B=x.startsWith("domain:"),V=x.startsWith("conn:"),R=B?x.slice(7):void 0,W=V?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||B,Q=E&&!D&&(x==="all"||x==="direct"||V),ee=((o==null?void 0:o.length)??0)>0,re=d.length===0&&!ee,ue=d.length===0&&ee?"Clear":"Add",te=r==="aiContext"?"Data context":A?"Select dataset":"Add data",ce=r==="aiContext"?"Set the overall data scope for the dashboard":A?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Vo,{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:[c.jsx(p.VisuallyHidden,{children:c.jsx(So,{children:te})}),c.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:te}),c.jsx("p",{className:"text-[11px] text-muted-foreground",children:ce})]}),c.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:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]}),c.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[c.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:[c.jsx(zo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),c.jsx("input",{type:"text",value:g,onChange:ye=>b(ye.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&&c.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:c.jsx(p.X,{className:"h-3 w-3"})})]}),F&&c.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:c.jsxs("div",{className:"flex w-max items-center gap-1",children:[c.jsx(Jg,{label:"All",active:x==="all",onClick:()=>q("all")}),(G.length>0||$.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx(Jg,{label:"Semantic",active:x==="semantic",onClick:()=>q("semantic")}),c.jsx(Jg,{label:"Direct",active:x==="direct",onClick:()=>q("direct")}),c.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(ye=>c.jsx(Jg,{label:ye.label||ye.name,active:x===`domain:${ye.id}`,onClick:()=>q(`domain:${ye.id}`)},`domain:${ye.id}`)),$.map(ye=>c.jsx(Jg,{label:ye.name,active:x===`conn:${ye.id}`,onClick:()=>q(`conn:${ye.id}`)},`conn:${ye.id}`))]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&c.jsx(gpt,{domainAccess:u,search:g,scopeDomainId:R,selectedEntities:d,onSelectionChange:ye=>Y(ye,"semanticDomain")}),Q&&c.jsx(ypt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:ye=>Y(ye)})]}),c.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[c.jsx("span",{children:"Selected"}),c.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.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"}),c.jsxs("button",{type:"button",onClick:M,disabled:re,className:p.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:[c.jsx("span",{children:ue}),d.length>0&&c.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&c.jsx(kpt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function Jg({label:e,active:t,onClick:n}){return c.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:p.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 UC(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(wA,{className:r});case"view":return c.jsx(By,{className:r});case"materialized view":return c.jsx(vfe,{className:r});case"model":return c.jsx(KC,{className:r});case"file":return c.jsx(Ys,{className:r});case"dataset":return c.jsx(gi,{className:r});case"upload":return c.jsx(p.Upload,{className:r});case"url":return c.jsx(VH,{className:r});default:return c.jsx(hp,{className:r})}}const XM=e=>e.name||e.name,_pt=e=>{const t=XM(e),n="description"in e?e.description:"",r=e.database||"",o=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,o&&` • Schema: ${o}`]})]})};function jpt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:o}){const[s,i]=S.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const l=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return c.jsx(p.TooltipProvider,{children:c.jsx("div",{className:o,children:a&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[l.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsxs(Ar,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[UC(f.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate",children:XM(f)}),c.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:c.jsx(p.X,{className:"h-3 w-3"})})]})}),c.jsx(p.TooltipContent,{side:"top",className:"max-w-xs",children:_pt(f)})]},m)}),d&&c.jsxs(p.Tooltip,{open:s,onOpenChange:i,children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsxs(Ar,{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:[c.jsx(Oa,{className:"h-3 w-3"}),c.jsxs("span",{children:[u.length," more"]}),c.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:c.jsx(p.X,{className:"h-3 w-3"})})]})}),c.jsx(p.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:UC(f.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:XM(f)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),c.jsx(p.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:c.jsx(p.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Rce=Z.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Ho.Input,{ref:n,className:p.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})]}));Rce.displayName=Ho.Input.displayName;const qw=e=>e.label||(e==null?void 0:e.name),j7=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Ept({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:o,selectedEntities:s,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=xt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=S.useState(""),[g,b]=S.useState(""),x=o.filter(k=>{if(!h)return!0;const _=qw(k).toLowerCase(),j=(j7(k)||"").toLowerCase(),T=h.toLowerCase();return _.includes(T)||j.includes(T)});S.useEffect(()=>{e||(m(""),b(""))},[e]),S.useEffect(()=>{x.length>0&&!g&&b(qw(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>qw(_)===g);k&&(s.some(j=>"id"in k&&"id"in j?k.id===j.id:k.name===j.name&&k.connectionId===j.connectionId)||t(k),i(k),r())},v=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>s.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=s.length===o.length,N=s.length>0;return c.jsx(c.Fragment,{children:c.jsxs($k,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:v,children:[o.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Rce,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(p.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:[c.jsx(pr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),o.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[s.length," ",s.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(p.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&&c.jsxs(p.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),l==null||l()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(p.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(zk,{className:"min-h-60",children:[c.jsx(Bk,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(p.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:[c.jsx(pr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Vk,{children:x.map((k,_)=>{const j=w(k),T="id"in k?k.id:`${k.connectionId}-${k.name}`,E=qw(k);return c.jsxs(Hk,{value:E,onSelect:()=>{j?n==null||n(k):t(k)},onMouseDown:D=>{D.preventDefault(),D.stopPropagation()},className:p.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:UC(k.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:j7(k)})]}),j&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(p.Check,{className:"h-3 w-3 text-background"})})]},T)})})]})]})})}function QM({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:o=!1,open:s,onOpenChange:i,onEntityMention:a,onEntityRemoved:l,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,v]=S.useState(!1),[w,C]=S.useState(!1),N=s??y,k=s!==void 0,_=S.useRef(!1),T=p.useEditorStore(R=>R.card.dataSource)??ky,{selectedEntities:E,availableEntities:D,syncWithGlobalContext:I,setSelectedEntities:F,applyDashboardDefaultEntities:O,isEntitySelected:A}=Tk(x),z=e==="full"||e==="display",L=e==="full"||e==="trigger",U=S.useMemo(()=>b&&E.length>0?`Add entity (${E.length})`:g,[E.length,b,g]);S.useEffect(()=>{N&&!_.current&&o&&I(),_.current=N},[N,o,I]);const H=S.useCallback(R=>{k||v(R),i==null||i(R)},[k,i]),P=S.useCallback(R=>{const W=E.filter(X=>!Cr(X,R));F(W),l==null||l(R),d==null||d(W)},[l,d,E,F]),K=S.useCallback(R=>{if(R.length===0)return;const W=E.filter(X=>!R.some(Q=>Cr(X,Q)));F(W),u==null||u(R),d==null||d(W)},[u,d,E,F]),Y=S.useCallback(R=>{const W=A(R)?E.filter(X=>!Cr(X,R)):[...E,R];F(W),d==null||d(W)},[A,d,E,F]),M=S.useCallback(()=>{F(D),d==null||d(D)},[D,d,F]),G=S.useCallback(()=>{F([]),d==null||d([])},[d,F]),$=S.useCallback(R=>{x==="dashboard"?O():F(R),d==null||d(R)},[O,x,d,F]),q=S.useCallback(R=>{const W=E.some(X=>Cr(X,R))?E:[...E,R];F(W),a==null||a(R),d==null||d(W),H(!1)},[a,d,E,H,F]),B=z?c.jsx(jpt,{className:p.cn(n?"contents":"space-y-2"),entities:E,availableEntities:D,onRemoveEntity:P,onRemoveEntities:K}):null,V=L?c.jsxs(c.Fragment,{children:[c.jsxs(p.Popover,{open:N,onOpenChange:H,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs(p.Button,{variant:m,size:"xs",className:p.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[c.jsx(vH,{className:"h-3 w-3 text-muted-foreground"}),!b&&c.jsx("span",{children:U})]})}),c.jsx(p.PopoverContent,{className:p.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:R=>R.preventDefault(),children:c.jsx(Ept,{isOpen:!0,onSelect:Y,onDeselect:Y,onClose:()=>H(!1),availableEntities:D,selectedEntities:E,onTabComplete:q,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{H(!1),C(!0)}})})]}),c.jsx(aL,{incomingSelectedEntities:E,open:w,onOpenChange:C,dataSource:T,dialogMode:"aiContext",onSaveSelectedEntities:$,saveAsDashboardDefault:x==="dashboard"})]}):null;return c.jsx("div",{className:p.cn(n?"flex flex-wrap items-center gap-1":"",!n&&z?"space-y-2":"",f),children:n&&r?c.jsxs(c.Fragment,{children:[V,B]}):c.jsxs(c.Fragment,{children:[B,V]})})}const lL=S.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:o,stop:s,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=S.useState(!1),h=S.useRef(null),{queueMessage:m}=p.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=p.useFileActions(),y=p.useFileAttachments(l);S.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const v=S.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const D=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${D}px`}},[e]);S.useEffect(()=>{v()},[v]),S.useEffect(()=>{const E=setTimeout(()=>{v()},0);return()=>clearTimeout(E)},[v]);const w=()=>{const E=e.trim();!E&&y.length===0||(a!=="ready"?(m(l,E,y),t(""),x(l)):r({preventDefault:()=>{}}))},C=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),w()),E.key==="@"&&f(!0)},N=S.useCallback(E=>{const D=ylt(E.nativeEvent);D.length>0&&(E.preventDefault(),D.forEach(async I=>{const F=await q5(I);g(l,F)}))},[g,l]),k=S.useCallback(E=>{E.forEach(D=>{g(l,D)})},[g,l]),_=S.useCallback(E=>{E.forEach(D=>{g(l,D)})},[g,l]),j=S.useCallback(E=>{b(l,E)},[b,l]),T=S.useCallback(E=>{const D=`@${E}`;e.includes(D)&&t(e.replace(D,"").replace(/\s{2,}/g," ").trim())},[e,t]);return c.jsxs(hpt,{onFilesDropped:k,currentFileCount:y.length,disabled:o,className:"space-y-4",children:[c.jsx(QM,{mode:"display",assistantType:l,onEntityRemoved:E=>{const D="label"in E?E.label:E.name;T(D)},onEntitiesRemoved:E=>{let D=e;E.forEach(I=>{const F="label"in I?I.label:I.name;D=D.replace(`@${F}`,"")}),D!==e&&t(D.replace(/\s{2,}/g," ").trim())}}),y.length>0&&c.jsx(Tlt,{files:y,onRemove:j,showRemove:!o,className:"mb-2"}),c.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:[c.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{v(),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"}}),c.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[c.jsxs("div",{className:"flex items-center gap-0.5",children:[c.jsx(QM,{mode:"trigger",assistantType:l,syncOnOpen:l==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var I;const D="label"in E?E.label:E.name;t(`${e}@${D} `),(I=h.current)==null||I.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),c.jsx(fpt,{onFilesSelected:_,disabled:o,currentFileCount:y.length})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[o&&c.jsx(p.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:s,children:c.jsx(Ffe,{className:"size-3.5"})}),!o&&c.jsx(p.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:c.jsx(ZH,{className:"size-3.5"})})]})]})]})]})});lL.displayName="ChatInputWithContext";function Fce({assistantType:e,className:t}){const n=p.useMessageQueue(e),{removeFromQueue:r}=p.useQueueActions();return n.length===0?null:c.jsxs("div",{className:p.cn("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(pA,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(o=>c.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:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:o.text})}),c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,o.id),title:"Remove from queue",children:c.jsx(p.X,{className:"h-3 w-3"})})]})},o.id))})]})}function Pce({assistantType:e,status:t,isLoading:n,sendMessage:r}){const o=p.useMessageQueue(e),{dequeueMessage:s}=p.useQueueActions();S.useEffect(()=>{if(t!=="ready"||n||!(o&&o.length>0))return;const a=s(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,o,s,r,e])}function Dpt(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 Tpt(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 o=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",s=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Dpt(r);return`${o}:${s}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Oce(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:o=!0,isStreaming:s=!1}=t,i=S.useRef(null),a=S.useRef(null),[l,u]=S.useState(!0),[d,f]=S.useState(!0),[h,m]=S.useState(!1),[g,b]=S.useState(0),x=S.useRef(!0),y=S.useRef(!0),v=S.useRef(!1),w=S.useRef(!1),C=S.useRef(0),N=S.useRef({count:0,signature:"none"}),k=S.useCallback(()=>{if(i.current)return i.current;const A=a.current;if(!A)return null;const z=A.closest("[data-radix-scroll-area-viewport]");if(z)return i.current=z,z;const L=A.parentElement;return L?(i.current=L,L):null},[]),_=S.useCallback(()=>{const A=k();return A?A.scrollHeight-A.scrollTop-A.clientHeight:0},[k]),j=S.useCallback(()=>_()<=n,[_,n]),T=S.useCallback(A=>{x.current!==A&&(x.current=A,u(A))},[]),E=S.useCallback(A=>{y.current!==A&&(y.current=A,f(A))},[]),D=S.useCallback(()=>{m(A=>A&&!1),b(A=>A===0?A:0)},[]),I=S.useCallback((A={})=>{const z=k();if(!z)return;const{force:L=!1,instant:U=!1}=A;if(!L&&v.current)return;const H=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,H==="smooth"&&"scrollTo"in z?z.scrollTo({top:z.scrollHeight,behavior:"smooth"}):z.scrollTop=z.scrollHeight,C.current=z.scrollTop,v.current=!1,T(!0),E(!0),D(),requestAnimationFrame(()=>{w.current=!1})},[r,D,k,T,E]),F=S.useCallback(()=>{b(0),m(!1)},[]),O=S.useCallback(()=>{const A=k();if(!A)return;const z=C.current,L=A.scrollTop,U=L-z;C.current=L;const H=j();if(w.current){E(H),H&&(v.current=!1,T(!0));return}if(U<-1&&!H){v.current=!0,T(!1),E(!1);return}if(H){v.current=!1,T(!0),E(!0),D();return}E(!1),v.current&&T(!1)},[D,k,j,T,E]);return S.useEffect(()=>{const A=k();if(!e||e.length===0){N.current={count:0,signature:"none"},A&&(C.current=A.scrollTop),D();return}const z=e[e.length-1],L=Tpt(z),U=N.current,H=e.length>U.count,P=L!==U.signature;N.current={count:e.length,signature:L};const K=s||o&&(z==null?void 0:z.role)==="assistant"&&P;if(!v.current){T(!0),A&&j()&&E(!0),(H||P||K)&&I({force:!1,instant:K});return}if(H){const Y=e.length-U.count;Y>0&&(m(!0),b(M=>M+Y))}else P&&(m(!0),b(Y=>Y>0?Y:1))},[D,s,o,k,j,e,I,T,E]),S.useEffect(()=>{I({force:!0,instant:!0})},[I]),S.useEffect(()=>{if(typeof ResizeObserver>"u")return;const A=a.current;if(!A)return;const z=new ResizeObserver(()=>{v.current||I({force:!1,instant:!0})});return z.observe(A),()=>{z.disconnect()}},[I]),S.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:l,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:I,handleScroll:O,resetNewMessageCount:F}}function Lce(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:o=10}=t,[s,i]=S.useState(r),a=S.useMemo(()=>{if(e.length<=s)return e;const h=Math.max(0,e.length-s);return e.slice(h)},[e,s]),l=e.length>s,u=s>=e.length,d=S.useCallback(()=>{i(h=>Math.min(h+o,n))},[o,n]),f=S.useCallback(()=>{i(r)},[r]);return S.useEffect(()=>{u&&e.length>s&&s<n&&i(Math.min(e.length,n))},[e.length,s,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const E7={"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 Ipt(e,t){var r;if((r=E7[e])!=null&&r[t])return E7[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function $ce(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 o=r,s=o.state;return{hasActiveTools:!0,activeToolText:Ipt(o.type,s),toolType:o.type}}}return{hasActiveTools:!1}}const Mpt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Apt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=S.useState(!1),[a,l]=S.useState(p.isDevEnv),[u,d]=S.useState(!1),[f,h]=S.useState("auto"),[m,g]=S.useState(!1),[b,x]=S.useState(!1),y=n??b,{isLocalDev:v,isConsoleMode:w}=mp(),C=S.useRef(null);p.useDashboardStore(he=>he.dashboard.aiScopeTables),p.useDashboardStore(he=>he.isDashboardEditing);const N=p.useDashboardStore(he=>he.selectedSheetId),{setDataSource:k}=p.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:j}=p.useDashboardActions(),T=KP(),{setReasoningEffort:E,setShowReasoning:D,clearAssistantMessageContexts:I}=p.useAIActions(),{clearQueue:F}=p.useQueueActions(),{clearFileAttachments:O,getFileAttachments:A}=p.useFileActions(),z=p.useFileAttachments("dashboard"),L=p.useEditorStore(he=>he.card.dataSource),{assistantProfile:U}=Ece(),H=p.useDashboardStore(he=>he.handleOpenAssistantProfile),{selectedEntities:P,applyDashboardDefaultEntities:K}=Tk("dashboard"),{sendMessage:Y,isLoading:M,messages:G,setMessages:$,status:q,stop:B,errorMessage:V,clearError:R}=dpt({dynamicVisualMode:f}),W=S.useCallback(he=>{r==null||r(he),n===void 0&&x(he)},[n,r]),X=S.useCallback(()=>{W(!y)},[y,W]);S.useEffect(()=>{if(!y)return;function he(ze){ze.key==="Escape"&&W(!1)}return window.addEventListener("keydown",he),()=>{window.removeEventListener("keydown",he)}},[y,W]);const[Q,ee]=S.useState(""),re=he=>{ee(he.target.value)};async function ue({sql:he,cardTitle:ze,connectionId:Ne,cardType:Ee,python:Ze,cardConfig:Re,dataSource:Be,customVisualPreferences:Ve,visualizationMode:ht,dynamicCardPreferences:rt}){if(!N)return;const Je=ht==="dynamic",vt=p.hasValidCardConfig(Re),nt=Ne||(Be==null?void 0:Be.connectionId)||"",_t=Be?{...Be,connectionId:nt||Be.connectionId,connectionType:Be.connectionType||"",mode:Be.mode||"database",selectedEntities:Be.selectedEntities||[]}:nt?{connectionId:nt,connectionType:"",mode:"database",selectedEntities:[]}:ky,je=!vt||!Je||(rt==null?void 0:rt.provenance)!=="card-config",He=je?he:"",et=je?Ze:"",mt={id:p.v4(),title:ze||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ee==="horizontalBar"?"y":"x"},...Je&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Ee,sql:He,python:et,dataSource:_t,config:Re,connectionId:nt,visualizationMode:ht,dynamicCardPreferences:rt,customCardPreferences:Ve?{url:Ve.url,componentName:Ve.componentName,pluginChartType:Ve.pluginChartType,settings:Ve.settings,type:"component"}:void 0},gt={id:p.v4(),cards:[mt],activeCardId:mt.id};try{await T(N,gt,"end"),j(!0),_(gt.id)}catch(Tt){console.error("Failed to add assistant visual to dashboard:",Tt),Xe.error(Tt instanceof Error?Tt.message:"Failed to prepare semantic metadata for the new visual")}}const te=he=>{he.preventDefault();const ze=Q.trim();if(!ze&&z.length===0)return;const Ne=[];ze&&Ne.push({type:"text",text:ze}),z.forEach(Ee=>{Ee.data&&Ne.push({type:"file",mediaType:Ee.type,filename:Ee.name,url:`data:${Ee.type};base64,${Ee.data}`})}),Y({role:"user",parts:Ne}),ee(""),O("dashboard"),fe({force:!0})};S.useEffect(()=>{var he;e&&((he=C.current)==null||he.focus())},[e]),Pce({assistantType:"dashboard",status:q,isLoading:M,sendMessage:Y});const{hasActiveTools:ce,activeToolText:se}=$ce(G),{visibleMessages:Se,hasMoreMessages:ye,totalMessageCount:Ae,loadMoreMessages:ae,resetMessageWindow:xe}=Lce(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,contentRef:pe,isAtBottom:J,hasNewMessages:ne,newMessageCount:ge,scrollToBottom:fe,handleScroll:me,resetNewMessageCount:be}=Oce(Se,{threshold:40,behavior:"smooth",isStreaming:M});function ke(he){const ze={role:"user",parts:[{type:"text",text:he.title+" "+he.subtitle}]};Y(ze)}function De(he){Y({role:"user",parts:[{type:"text",text:he}]})}function Ge(he){Y({role:"user",parts:[{type:"text",text:he}]}),fe({force:!0})}const Ye=S.useCallback(async()=>{const he=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(he),Xe.success("Conversation copied")}catch(ze){console.error("Failed to copy conversation",ze),Xe.error("Unable to copy conversation")}},[G]),it=(Q==null?void 0:Q.length)===0&&(G==null?void 0:G.filter(he=>he.role==="user").length)===0;function We(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Qe(){return c.jsxs(Es,{children:[c.jsx(Ds,{asChild:!0,children:c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Vf,{className:"size-3.5"})})}),c.jsxs(rs,{align:"end",children:[c.jsx(Ml,{children:"Options"}),c.jsx(Zi,{}),c.jsx(vc,{checked:s,onCheckedChange:i,children:"Token Usage"}),c.jsx(vc,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(vc,{checked:u,onCheckedChange:d,children:"System Message"}),(v||w)&&c.jsxs(c.Fragment,{children:[c.jsx(Zi,{}),c.jsx(Ml,{children:"Dynamic Visuals"}),c.jsx(vc,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),c.jsx(vc,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),c.jsx(vc,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const Ke=c.jsxs("div",{"data-role":"dashboard-assistant",className:p.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:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[We(),H&&c.jsx(p.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:H,children:(U==null?void 0:U.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&Qe(),a&&c.jsx(p.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ye,children:"Copy Conversation"}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?c.jsx(gA,{className:"size-4"}):c.jsx(XC,{className:"size-4"})}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const he=G.filter(ze=>ze.role==="assistant").map(ze=>ze.id).filter(ze=>!!ze);$([]),F("dashboard"),R(),I(he),xe()},children:c.jsx(yA,{className:"size-4"})}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(p.X,{className:"size-4"})})]})]}),c.jsxs(Za,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:me,children:[c.jsxs("div",{ref:pe,className:"min-w-0 space-y-3 pb-4",children:[ye&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:ae,className:"text-xs",children:["Load ",Math.min(5,Ae-Se.length)," ","more messages (",Ae-Se.length," ","hidden)"]})}),c.jsx(ule,{showTools:a,showSystemMessage:u,messages:Se,onAddToDashboard:ue,onQuickReply:Ge,disableQuickReplies:M}),c.jsx(cle,{status:q,errorMessage:V,activeToolText:M&&ce?se:void 0})]}),c.jsx(p.ScrollBar,{orientation:"horizontal"})]}),e&&!J&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(p.Button,{onClick:()=>{fe({force:!0}),be()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(p.ChevronDown,{className:"h-4 w-4"}),ne&&ge>0&&c.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:ge>9?"9+":ge})]})}),c.jsxs("div",{className:"space-y-3",children:[!U&&it&&c.jsx(dle,{onClick:ke,placeholders:Mpt}),c.jsx("div",{children:it&&U&&c.jsx(Dce,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:De})}),c.jsx(Fce,{assistantType:"dashboard",className:"mb-3"}),c.jsx(lL,{ref:C,setInput:ee,stop:B,input:Q,handleInputChange:re,handleSubmit:he=>{te(he),fe({force:!0})},isLoading:M,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(aL,{incomingSelectedEntities:P,open:m,onOpenChange:g,dataSource:L||ky,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:he=>K()})]});return y&&o?or.createPortal(c.jsx(Wp,{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:c.jsx("div",{className:"flex h-full w-full",children:Ke})}),o):Ke}function Rpt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),o=rte(),s=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),l=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);S.useEffect(()=>{if(!l||u)return;async function d(m){if(Fpt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),Xe.success("Card copied to clipboard"),m.preventDefault()):g&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText(),g=Ppt(m);if(g!=null&&g.id){const b=ete(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await o(a,b),r(b.id),Xe.success("Card pasted from clipboard")}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[o,n,r,a,l,u,t])}function Fpt(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 Ppt(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 Opt(e,t){switch(e.interactionMode){case"drillToDetail":Lpt(e,t);break;case"drillThrough":$pt(e,t);break;case"drillToURL":zpt(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 Lpt(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:o,filterGroups:s}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=s.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=s.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}o==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function $pt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:o,sourceCardId:s}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=o.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function zpt(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 Bpt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:o,contextMode:s,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Vo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(ki,{children:[c.jsx(So,{children:i||"Insight Detail"}),c.jsx(os,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(ate,{filters:r,filterDefinitions:o,contextMode:s}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(Ste,{insightId:n,filters:r,contextMode:s}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Vpt(){const e=p.useInteractionStore(C=>C.interactionStates),t=p.useInteractionStore(C=>C.setInteractionState),n=p.useInteractionStore(C=>C.clearLastInteractionEvent),r=p.useInteractionStore(C=>C.replaceCardWithInsight),o=p.useInteractionStore(C=>C.setPendingDrillThrough),s=p.useInteractionStore(C=>C.pendingDrillThrough),i=p.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=p.useDashboardActions(),{selectDashboard:u}=zf(),d=p.useDashboardStore(C=>C.dashboard),f=p.useDashboardStore(C=>C.filterValues),{data:h,isLoading:m}=lq((s==null?void 0:s.targetDashboardId)||"",{enabled:!!(s!=null&&s.targetDashboardId)}),[g,b]=S.useState({open:!1,insightId:""}),x=Cte(g.insightId,{enabled:g.open&&!!g.insightId}),y=S.useRef(new Set),v=S.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:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:o,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j})=>{const T={filters:C},E={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[T]},D={...p.createInitialInteractionState(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j};t(p.DRILL_CONTEXT_CARD_ID,D)}}),[a,r,f,l,d,o,t]);S.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{Opt(k,v)}catch(j){console.error("Error executing interaction event:",j)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,v]),S.useEffect(()=>{if(!(!s||!h||m))try{u(h),l(s.targetDashboardId,s.sourceDashboardId,s.sourceDashboardTitle,s.filters,s.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[s,h,m,u,l,i]);const w=()=>{b({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(Bpt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),s&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.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:[c.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),c.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Hpt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,o=Upt(t.value);return r==="="?`${n} = ${o}`:`${n} ${r} ${o}`}).join(", ")}function Upt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function qpt(e){return e?`Back to ${e}`:"Back"}function Wpt(){var y,v,w,C,N;const e=p.useInteractionStore(k=>k.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(k=>k.actions.goBackFromDrill),n=p.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=zf(),[o,s]=S.useState({x:16,y:16}),[i,a]=S.useState(!1),l=S.useRef({x:0,y:0});S.useEffect(()=>{if(!i)return;const k=j=>{s({x:j.clientX-l.current.x,y:j.clientY-l.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=(v=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:v.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 m=()=>{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),l.current={x:k.clientX-o.x,y:k.clientY-o.y})};Hpt(f);const x=qpt(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${o.x}px, ${o.y}px)`,transition:i?"none":void 0},children:c.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:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const j=k.field.label||k.field.name,T=String(k.value);return c.jsxs(Ar,{variant:"secondary",className:"pointer-events-none text-xs",children:[j," = ",T]},_)})})]}),c.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(zy,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Ypt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Gpt({filter:e,isEditing:t=!1,disabled:n=!1}){const{attributes:r,listeners:o,setNodeRef:s,transform:i,transition:a,isDragging:l}=Jp({id:`filter:${e.id}`,disabled:n||!t}),u={transform:Xs.Translate.toString(i),transition:a,opacity:l?.5:1,zIndex:l?10:void 0};return c.jsx("div",{ref:s,style:u,...r,children:c.jsx(DP,{filter:e,isEditing:t,dragListeners:t?o:void 0})})}const D7="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Kpt=[];function zce({open:e,onOpenChange:t}){var $,q,B;const[n,r]=S.useState(!1),[o,s]=S.useState(!1),[i,a]=S.useState({sheetSelection:"current",protectPdf:!1,password:""}),l=p.useDashboardStore(V=>{var R;return(R=V.dashboard)==null?void 0:R.sheets}),u=p.useDashboardStore(V=>V.dashboard),d=p.useDashboardStore(V=>V.dashboardInputValues),f=p.useDashboardStore(V=>V.filterValues),h=p.useDashboardStore(V=>V.controlValues),m=p.useDashboardStore(V=>V.inlineFilterValuesMap),g=p.useDashboardStore(V=>V.cardControlValuesMap),b=p.useDashboardStore(V=>V.selectedSheetId),x=p.useDashboardStore(V=>V.selectedSheetId?V.documentInputRuntimeBySheetId[V.selectedSheetId]:void 0),y=p.useDashboardStore(V=>V.isDownloadingPdf),{authToken:v,tokenProps:w}=xt(),C=l==null?void 0:l.find(V=>V.id===b),N=S.useMemo(()=>p.getDashboardExportSheets(l),[l]),k=p.isDocumentSheet(C),_=k&&C?C.document:void 0,j=S.useMemo(()=>k&&C?K0(u,C.id):[],[C,k,u]),T=j.length>0,E=S.useMemo(()=>k&&C?aie(u,C.id):!1,[C,k,u]),D=S.useMemo(()=>T?j.map(Z0):(_==null?void 0:_.inputs)||Kpt,[_,j,T]),I=((q=($=w==null?void 0:w.params)==null?void 0:$.calendarContext)==null?void 0:q.tz)||((B=w==null?void 0:w.params)==null?void 0:B.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=S.useMemo(()=>sre(D),[D]),O=S.useMemo(()=>rre(D,I),[D,I]),A=S.useMemo(()=>ore(D),[D]),z=x?x.filterValuesByInputId:O,L=x?x.controlValuesByInputId:A,U=S.useMemo(()=>k?E&&C&&_?FY({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(V=>V.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:I}):lre(D,z,L,F,F):[],[_,D,C,k,u,g,h,f,m,d,L,z,F,I,E]),H=!!C,P=N.length>0,K=((l==null?void 0:l.length)||0)>1||k,Y=i.sheetSelection==="current"&&(!H||k&&U.length>0)||i.sheetSelection==="all"&&!P;S.useEffect(()=>{e&&i.sheetSelection==="all"&&!P&&a(V=>({...V,sheetSelection:"current"}))},[P,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){Xe.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){Xe.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!H){Xe.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!P){Xe.error("No dashboard sheets are available to export");return}s(!0);const V=i.sheetSelection==="current"&&k,R=V?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=Xe.loading(R);try{if(V){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){Xe.dismiss(W),Xe.error(`Set ${U.join(", ")} before exporting`);return}const Q=new Date().toISOString(),ee=E?OY({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:Q,timezone:I}).snapshot:void 0;await DR(w.apiServiceUrl,v,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:I,password:i.protectPdf?i.password:void 0,inputSnapshot:ee,...ee?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:z,controlValuesByInputId:L,generatedAt:Q}}})}else{const Q=dX();await UY(w.apiServiceUrl,v,i.protectPdf?i.password:void 0,i.sheetSelection,Q)}Xe.dismiss(W);const X=V?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!";Xe.success(X,{duration:2e3}),M()}catch(X){Xe.dismiss(W),Xe.error("Failed to download PDF",{description:AN(X,"Please try again or contact support."),descriptionClassName:MN,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{s(!1)}}return c.jsx(as,{open:e,onOpenChange:V=>{if(!V){M();return}t(!0)},children:c.jsxs(Vo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[c.jsxs(ki,{children:[c.jsx(So,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),c.jsx(os,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),c.jsxs("div",{className:"space-y-4 py-1",children:[K&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:D7,children:"Export scope"}),c.jsxs(Qi,{value:i.sheetSelection,onValueChange:V=>a({...i,sheetSelection:V}),className:"gap-1.5",children:[c.jsxs(p.Label,{htmlFor:"scope-current",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!H&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(fo,{value:"current",id:"scope-current",disabled:!H}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),c.jsxs(p.Label,{htmlFor:"scope-all",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!P&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(fo,{value:"all",id:"scope-all",disabled:!P}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&c.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.'})]}),c.jsx(p.Separator,{className:"bg-border/60"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[c.jsx(Cn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:V=>{a({...i,protectPdf:V,password:V?i.password:""}),V||r(!1)}}),c.jsx(ZC,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&c.jsxs("div",{className:"ml-6 space-y-1.5",children:[c.jsx(p.Label,{htmlFor:"pdf-password",className:D7,children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:V=>a({...i,password:V.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:V=>{V.key==="Enter"&&i.password&&G()}}),c.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?c.jsx(GC,{className:"h-3.5 w-3.5"}):c.jsx(By,{className:"h-3.5 w-3.5"})})]}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),c.jsxs(ec,{children:[c.jsx(p.Button,{variant:"outline",size:"xs",onClick:M,disabled:o,children:"Cancel"}),c.jsx(p.Button,{size:"xs",onClick:G,disabled:o||y||Y,children:o?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):c.jsxs(c.Fragment,{children:[c.jsx(Xl,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function Bce({iconClassName:e,open:t,onOpenChange:n}){const[r,o]=S.useState(!1),s=t!==void 0,i=s?t:r,a=u=>{s||o(u),n==null||n(u)},l=p.useDashboardStore(u=>u.isDownloadingPdf);return c.jsxs(c.Fragment,{children:[s?null:c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:l,onClick:()=>a(!0),children:c.jsx(Xl,{className:p.cn("size-4",e)})}),c.jsx(zce,{open:i,onOpenChange:a})]})}function T7(e,t,n){const r=new Set(t),o=[...n];return e.map(s=>r.has(s.id)?o.shift()??s.id:s.id)}function Zpt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:o,listeners:s,setNodeRef:i,transform:a,transition:l,isDragging:u}=Jp({id:`control:${e.id}`,disabled:!n}),d={transform:Xs.Translate.toString(a),transition:l,opacity:u?.5:1,zIndex:u?10:void 0};return c.jsx("div",{ref:i,style:d,...o,children:c.jsx(Sre,{control:e,value:t,isEditing:n,dragListeners:n?s:void 0,onChange:r})})}const Xpt=[];function Qpt(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function I7(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function Jpt(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 I7(t,n);const o=e.filter(a=>r.has(a)),s=new Set(o),i=I7(t,n).filter(a=>!s.has(a));return[...o,...i]}function egt(e,t){return"toolbar"}function tgt(){var U;const e=nc("interactive"),t=p.useDashboardStore(H=>H.selectedSheetId),n=p.useDashboardStore(H=>H.dashboard.filters),r=p.useDashboardStore(H=>H.dashboard.filterLayout),o=p.useDashboardStore(H=>H.isDashboardEditing),s=p.useDashboardStore(H=>H.controlValues),i=p.useDashboardStore(H=>H.filterValues);p.useDashboardStore(H=>H.filteringCards);const a=p.useDashboardStore(H=>H.inlineFilterValuesMap),l=p.useInteractionStore(H=>H.clearAllClickFilters),u=p.useInteractionStore(H=>Object.entries(H.interactionStates).reduce((P,[K,Y])=>{var M;return K===p.DRILL_CONTEXT_CARD_ID?P:P+(((M=Y.appliedClickFilters)==null?void 0:M.length)??0)},0)),d=p.useDashboardStore(H=>H.actions.removeCardInlineFilterValue),{reorderFilters:f,reorderDashboardControls:h,setControlValue:m,setFilterLayout:g,setFilterValues:b,setFilteringCards:x}=p.useDashboardActions(),y=Rk(np(Xp,{activationConstraint:{distance:5}})),v=(U=sc(n,t))==null?void 0:U.filter(H=>!H.hide&&H.location!=="frame"),w=(v==null?void 0:v.filter(H=>egt()==="toolbar"))||Xpt,C=p.useDashboardStore(H=>H.dashboard),N=$Ve(C),k=N.filter(H=>!H.hidden&&Xx(H)==="toolbar"),_=N.filter(H=>!H.hidden&&Xx(H)==="advanced"),j=Jpt(r==null?void 0:r.toolbarItemOrder,w,k),T=new Map(w.map(H=>[`filter:${H.id}`,H])),E=new Map(k.map(H=>[`control:${H.id}`,H]));function D(H){const{active:P,over:K}=H;if(!K||P.id===K.id)return;const Y=String(P.id),M=String(K.id),G=j.findIndex(X=>X===Y),$=j.findIndex(X=>X===M);if(G===-1||$===-1)return;const q=Qp(j,G,$);g({toolbarItemOrder:q});const B=j.filter(X=>X.startsWith("filter:")).map(X=>X.replace("filter:","")),V=q.filter(X=>X.startsWith("filter:")).map(X=>X.replace("filter:","")),R=j.filter(X=>X.startsWith("control:")).map(X=>X.replace("control:","")),W=q.filter(X=>X.startsWith("control:")).map(X=>X.replace("control:",""));f(T7(n||[],B,V)),h(T7(C.controls||[],R,W))}const I=(r==null?void 0:r.toolbarWrap)??!1,F=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter(H=>Qpt(H)).length)??0,A=a?Object.values(a).reduce((H,P)=>H+((P==null?void 0:P.length)??0),0):0,z=O+A+u,L=()=>{b([]),x([]),l(),a&&Object.entries(a).forEach(([H,P])=>{P==null||P.forEach(K=>{d(H,K.filterId)})})};return!w.length&&!k.length&&!_.length&&!F?null:c.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:c.jsx(P0,{sensors:y,collisionDetection:A0,onDragEnd:D,children:c.jsxs("div",{className:p.cn("flex items-center",I?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[c.jsx(O0,{items:j,strategy:oO,children:c.jsx(Y2,{className:"gap-3 pr-0",wrap:I,children:j.map(H=>{const P=T.get(H);if(P)return c.jsx(Gpt,{filter:P,isEditing:o},H);const K=E.get(H);return K?c.jsx(Zpt,{control:K,value:s==null?void 0:s[K.id],isEditing:o,onChange:Y=>m(K.id,Y)},H):null})})}),_.length>0&&c.jsx(bte,{title:"",controls:_,values:s,onChange:(H,P)=>m(H.id,P),immediatePlacement:"toolbar",advancedLabel:"More controls"}),z>0&&c.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:[c.jsx(p.X,{className:"h-3 w-3"}),"Clear all",c.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:z})]}),F&&c.jsx("div",{className:p.cn(z>0?"ml-1.5":"ml-auto"),children:c.jsx(Bce,{})})]})})})}function Vce(){var ne,ge;const{showAssistant:e,tokenProps:t,renderMode:n}=xt(),r=Ypt((ne=t.config)==null?void 0:ne.showDashboardAssistant,e),{preferences:o,isConsoleMode:s}=mp(),i=(ge=o==null?void 0:o.cardDisplay)==null?void 0:ge.mode,a=Zf(i),l=yY({displayMode:i,renderMode:n}),u=S.useRef(null),d=S.useRef(null),[f,h]=S.useState(!1),{handleDragStart:m,isDraggingRef:g,getStyle:b,getPositionClasses:x}=det({initialPosition:"bottom-right"}),y=Yd(fe=>fe.setFullscreen),v=Yd(fe=>fe.setPanelOpen),w=Yd(fe=>fe.setContainer),C=uW("dashboard"),N=dW(),k=fW("dashboard"),_=C.isOpen,j=N==="dashboard",T=p.useDashboardStore(fe=>fe.isVisualEditing),E=p.useDashboardStore(fe=>fe.themeStyle),D=qa(),I=p.useDashboardStore(fe=>{var me;return(me=fe.dashboard)==null?void 0:me.sheets}),F=p.useDashboardStore(fe=>fe.showFilters),O=p.useDashboardStore(fe=>fe.isDashboardEditing),A=p.useDashboardStore(fe=>fe.selectedSheetId),z=I==null?void 0:I.find(fe=>fe.id===A),L=p.useDashboardStore(fe=>{var me,be,ke;return(ke=(be=(me=fe.dashboard)==null?void 0:me.sheets)==null?void 0:be.find(De=>De.id===fe.selectedSheetId))==null?void 0:ke.kind}),U=p.useDashboardStore(fe=>{var me,be;return((be=(me=fe.dashboard)==null?void 0:me.summary)==null?void 0:be.position)||"top"}),H=L==="document",P=p.useDashboardStore(fe=>{var me;return(me=fe.dashboard)==null?void 0:me.id}),K=p.useDashboardStore(fe=>fe.isDashboardPanelOpen),Y=p.useDashboardStore(fe=>fe.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:$}=pH(P),[q,B]=S.useState(null);sN(Or.DASHBOARD);const{setSelectedSheetId:V,setSheetTitle:R,addSheet:W,setSheets:X}=p.useDashboardActions();Rpt(d);const{setActiveAssistantType:Q}=p.useAIActions();S.useEffect(()=>{if(P){const fe=M();B(fe)}},[P,M]),S.useEffect(()=>{_?Q("dashboard"):N==="dashboard"&&y(null)},[_,Q,N,y]),S.useEffect(()=>{var fe;_||(fe=u.current)==null||fe.resize(0)},[_]);function ee(fe){var me,be;fe?((me=u.current)==null||me.resize(40),v("dashboard",!0),y("dashboard"),Q("dashboard")):(v("dashboard",!1),y(null),(be=u.current)==null||be.resize(0),Q(null))}function re(fe="dashboard"){const me={id:p.v4(),title:fe==="document"?"New Document":"New Sheet",...fe==="document"?{kind:fe,document:p.createDefaultDocumentDefinition()}:{}};W(me),V(me.id)}function ue(fe,me){if(!P)return;q===fe?($(),B(null),Xe.success("Default sheet cleared")):(G(fe),B(fe),Xe.success(`"${me}" set as default sheet`))}function te(fe){var me;fe<1?(v("dashboard",!1),y(null),Q(null),(me=u.current)==null||me.resize(0)):(_||v("dashboard",!0),Q("dashboard"))}function ce(){return(E==null?void 0:E.canvasTheme)==="muted"||!(E!=null&&E.canvasTheme)?"hsl(var(--semaphor-muted))":(E==null?void 0:E.canvasTheme)==="clear"?"":E==null?void 0:E.canvasTheme}const se=(fe,me)=>{fe.dataTransfer.setData("tabIndex",me.toString())},Se=fe=>{fe.preventDefault()},ye=(fe,me)=>{const be=fe.dataTransfer.getData("tabIndex");if(be===me.toString())return;const ke=Array.from(I||[]),[De]=ke.splice(parseInt(be),1);ke.splice(me,0,De),X(ke)},Ae=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ae=r===!0&&!a&&!_&&!T&&!F;function xe(){if(I&&I.length>1||O)return c.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[s&&Ae&&!K&&c.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{Y(!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:c.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:c.jsx(qH,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),c.jsxs("div",{className:"relative min-w-0 flex-1",children:[c.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"}),c.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"}),c.jsxs(p.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:[I==null?void 0:I.map((fe,me)=>{const be=A===fe.id,ke=q===fe.id;return c.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:De=>se(De,me),onDragOver:Se,onDrop:De=>ye(De,me),onClick:()=>V(fe.id),className:p.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:fe.id,children:[fe.kind==="document"&&c.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"}),c.jsx(HS,{enabled:O&&be,text:fe.title,onSave:De=>R(fe.id,De),children:fe.title},fe.id),c.jsx("span",{role:"button",tabIndex:0,"aria-label":ke?"Clear default sheet":"Set as default sheet",title:ke?"Clear default sheet":"Set as default sheet",onClick:De=>{De.stopPropagation(),ue(fe.id,fe.title||"Sheet")},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),De.stopPropagation(),ue(fe.id,fe.title||"Sheet"))},className:p.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",be||ke?"opacity-100":"opacity-0 group-hover:opacity-100"),children:c.jsx(vA,{className:p.cn("h-3 w-3 transition-colors",ke?"fill-current text-amber-500":"text-muted-foreground")})}),O&&be&&I.length>1&&c.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:De=>{De.stopPropagation(),h(!0)},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),De.stopPropagation(),h(!0))},children:c.jsx(p.X,{className:"h-3 w-3"})})]},fe.id)}),O&&c.jsxs(Es,{children:[c.jsx(Ds,{asChild:!0,children:c.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:[c.jsx(pr,{className:"h-3 w-3"}),"Sheet"]})}),c.jsxs(rs,{align:"start",className:"w-48",children:[c.jsxs(Sn,{onSelect:()=>re("dashboard"),children:[c.jsx(Im,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),c.jsxs(Sn,{onSelect:()=>re("document"),children:[c.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function ve(){return c.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:I==null?void 0:I.map(fe=>c.jsx(p.TabsContent,{style:{backgroundColor:ce(),...D.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:fe.id,children:c.jsx(IV,{sheet:fe})},fe.id))})}function pe(){return c.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",E==null?void 0:E.dashboardTabsContainer),onValueChange:fe=>{V(fe)},value:A||void 0,children:[xe(),U==="top"&&!H&&c.jsx(E2,{}),A&&!H&&c.jsx(tgt,{}),H?c.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:ve()}):c.jsx(Za,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:ve()}),U==="bottom"&&!H&&c.jsx(E2,{}),c.jsx(fet,{open:f,setOpen:h})]})}const J=S.useCallback(fe=>{w("dashboard",fe)},[w]);return I?l&&A&&!H?c.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):l&&H&&z?c.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:c.jsx(IV,{sheet:z})}):c.jsxs(c.Fragment,{children:[c.jsx(Vpt,{}),c.jsx(Wpt,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(Iie,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",j&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(_M,{children:pe()}),r===!0&&c.jsxs(c.Fragment,{children:[c.jsx(uet,{open:_,onTabClick:ee,withHandle:!0,disabled:!_}),c.jsx(_M,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:te,defaultSize:_?40:0,ref:u,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(Apt,{open:_,setOpen:ee,isFullscreen:j,onFullscreenChange:fe=>y(fe?"dashboard":null),fullscreenContainer:k})})})]})]}),c.jsx("div",{ref:J,className:p.cn("absolute inset-0",!j&&"pointer-events-none")}),ae&&c.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:c.jsx(p.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||ee(!0)},onMouseDown:m,onTouchStart:m,title:"Open Assistant (drag to move)",children:c.jsx(Tfe,{className:"h-5 w-5"})})})]})]}):null}const Hce=S.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:o,children:s,className:i,style:a,...l},u)=>{const d=S.useId(),f=S.useMemo(()=>ngt(d),[d]),{theme:h}=oA(),m=rgt(h),g=S.useMemo(()=>o??Zl.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,o,n]),b=S.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=S.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return c.jsx(p.AppearanceContext.Provider,{value:x,children:c.jsx(Wp,{...l,ref:u,className:i,style:a,children:s})})});Hce.displayName="AppearanceProvider";function ngt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function rgt(e){const t=z1(e),[n,r]=S.useState(()=>ogt());return S.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const o=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!o)return;const s=()=>{r(o.matches?"dark":"light")};return s(),typeof o.addEventListener=="function"?(o.addEventListener("change",s),()=>o.removeEventListener("change",s)):((a=o.addListener)==null||a.call(o,s),()=>{var l;return(l=o.removeListener)==null?void 0:l.call(o,s)})},[t]),t==="system"?n:t}function ogt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Uce=S.createContext({openBrandStudioPreview:()=>{}}),sgt=Uce.Provider;function igt(){return S.useContext(Uce)}function agt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const o=z1(t),[s,i]=S.useState(()=>lgt(n)||o),a=S.useCallback(u=>{const d=z1(u);cgt(n,d),i(d)},[n]),l=S.useMemo(()=>({theme:s,setTheme:a}),[s,a]);return c.jsx(Y7.Provider,{...r,value:l,children:e})}function lgt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=z1(t,"system");return n===t?n:null}catch{return null}}function cgt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const ugt=S.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function cL({appearance:e,children:t}){var D,I;const{authToken:n,id:r,tokenProps:o}=xt(),s=Ly(),i=(D=s.data)==null?void 0:D.organizationAppearance,a=(I=o.config)==null?void 0:I.appearance,[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(null),[g,b]=S.useState(null),[x,y]=S.useState(null),v=`${o.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=Dn({queryKey:rq({resourceType:Or.DASHBOARD,apiServiceUrl:o.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${o.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!s.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});S.useEffect(()=>{i!==void 0&&y({scopeKey:v,appearance:i})},[i,v]),S.useEffect(()=>{w.data!==void 0&&y({scopeKey:v,appearance:w.data})},[w.data,v]);const C=(x==null?void 0:x.scopeKey)===v?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=S.useMemo(()=>Zl.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=S.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),j=S.useCallback(()=>{u(!1)},[]);S.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const T=S.useMemo(()=>({openBrandStudioPreview:_}),[_]),E=g??h??e;return c.jsx(agt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(sgt,{value:T,children:c.jsx(Hce,{organizationAppearance:N,tokenAppearance:a,reactAppearance:E,style:{height:"100%",width:"100%"},children:c.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,l&&c.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:c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:c.jsx(ugt,{appearance:d,onDraftChange:b,onSave:F=>{m(F),b(F),f(F)},onCancel:j})})})]})})})})}function qce({children:e,preferences:t}){const{currentUser:n}=Ni(),r=S.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return c.jsx(eq.Provider,{value:r,children:c.jsx(Ek,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function dgt(e=2e3,t=500){const n=Bde(),[r,o]=S.useState(!1),[s,i]=S.useState(!1),a=S.useRef(null);return S.useEffect(()=>{const l=setTimeout(()=>o(!0),e);return()=>clearTimeout(l)},[e]),S.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]),s}function uL({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const o=dgt(e,t);return S.useEffect(()=>(o&&(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()}}),[o,n,r]),c.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:o?"ready":""})}function Wce(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(ea,{FallbackComponent:_k,children:c.jsxs(uA,{dashboardProps:e,children:[c.jsx(uL,{componentType:"dashboard",componentId:e.id}),c.jsx(cL,{appearance:e.appearance,children:c.jsx(qce,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(zA,{...e,type:"dashboard",children:c.jsx(Vce,{})})})})})]})})}function fgt(e=[]){const t=S.useRef(null),n=S.useRef(null),r=S.useRef(null),[o,s]=S.useState(),i=S.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,l=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-l-u-8,h=Math.max(f,0);s(x=>x===h?x:h)},[]);return S.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>i());return l.observe(a),i(),()=>l.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:o,updateAvailableWidth:i}}function hgt({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=mp(),r=Zf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),o=p.useDashboardStore(b=>b.filterValues),s=o==null?void 0:o.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=fgt([t,s,r]);return S.useEffect(()=>{m()},[e.title,m]),c.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[c.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:c.jsx(p.Label,{className:"my-1 block w-full text-sm",children:c.jsx(yi,{value:e.title||e.column,onSave:b=>l({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&c.jsx(EP,{filter:e,isEditing:t}),t&&c.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:c.jsx(p.X,{className:"size-3.5"})})]})]}),c.jsx("div",{className:"hidden",ref:f})]})}function mgt(){const e=p.useDashboardStore(r=>r.dashboard.filters),t=p.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:p.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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(hgt,{filter:r}),c.jsx(vk,{filter:r})]},r.id))}):null}function pgt(){var i;const e=p.useDashboardStore(a=>a.dashboard),t=p.useDashboardStore(a=>a.selectedSheetId),n=p.useDashboardStore(a=>a.isVisualEditing),r=p.useDashboardStore(a=>a.isDashboardEditing),o=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),s=p.isDocumentSheet(o);return c.jsx("div",{role:"dashboard-plus-main",className:p.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:c.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!s&&c.jsx(mgt,{}),c.jsx(Vce,{})]})})}const ggt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-B3HHMRPC.js"))),bgt=S.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BH8DP1qq.js"))),xgt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-M5-VFCtZ.js"))),ygt=S.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-D3vO68dH.js")).then(e=>({default:e.ResourceManagementPanel})));function vgt({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(u=>u.isDashboardPanelOpen),o=p.useDashboardStore(u=>u.isVisualEditing),s=p.useDashboardStore(u=>u.showDashboardJSON),i=p.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:l}=n;return c.jsx(ea,{FallbackComponent:_k,children:c.jsxs(uA,{dashboardProps:n,children:[c.jsx(uL,{componentType:"surfboard",componentId:n.id}),c.jsxs(cL,{appearance:a,children:[c.jsx(Fme,{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"}}}),c.jsxs(qce,{preferences:l,children:[s&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(xgt,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(ggt,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(ygt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(zA,{...n,type:"dashboard",children:[o&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(bgt,{})}),c.jsx(pgt,{})]})})]})]})]})]})]})})}var wgt=Object.defineProperty,Sgt=(e,t,n)=>t in e?wgt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ww=(e,t,n)=>Sgt(e,typeof t!="symbol"?t+"":t,n);const Cgt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Ngt={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}},kgt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function _gt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const jgt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const o=Yce(t);if(typeof n<"u"&&o in n.container)return n.container[o]})();return typeof r=="function"?r.bind(n):void 0}},Egt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Dgt={stringify:e=>e,parse:e=>e},vT={string:Dgt,number:Egt,boolean:Cgt,function:Ngt,method:jgt,json:kgt},eb=Symbol.for("r2wc.render"),Yw=Symbol.for("r2wc.connected"),od=Symbol.for("r2wc.context"),Ps=Symbol.for("r2wc.props");function Tgt(e,t,n){var r,o,s;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),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const g=_gt(m);d[m]=g,f[g]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Ww(this,s,!0),Ww(this,o),Ww(this,r,{}),Ww(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ps].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=l[g],v=y?vT[y]:null;if(y==="method"){const w=Yce(b);Object.defineProperty(this[Ps].container,w,{enumerable:!0,configurable:!0,get(){return this[Ps][w]},set(C){this[Ps][w]=C,this[eb]()}}),this[Ps][g]=v.parse(x,b,this)}v!=null&&v.parse&&x&&(this[Ps][g]=v.parse(x,b,this))}for(const g of a)this[Ps][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[Yw]=!0,this[eb]()}disconnectedCallback(){this[Yw]=!1,this[od]&&n.unmount(this[od]),delete this[od]}attributeChangedCallback(g,b,x){const y=f[g],v=l[y],w=v?vT[v]:null;y in l&&w!=null&&w.parse&&x&&(this[Ps][y]=w.parse(x,g,this),this[eb]())}[(s=Yw,o=od,r=Ps,eb)](){this[Yw]&&(this[od]?n.update(this[od],this[Ps]):this[od]=n.mount(this.container,e,this[Ps]))}}for(const m of i){const g=d[m],b=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Ps][m]},set(x){this[Ps][m]=x;const y=b?vT[b]:null;if(y!=null&&y.stringify){const v=y.stringify(x,g,this);this.getAttribute(g)!==v&&this.setAttribute(g,v)}else this[eb]()}})}return h}function Igt(e,t,n){const r=Eue.createRoot(e),o=S.createElement(t,n);return r.render(o),{root:r,ReactComponent:t}}function Mgt({root:e,ReactComponent:t},n){const r=S.createElement(t,n);e.render(r)}function Agt({root:e}){e.unmount()}function Rgt(e,t={}){return Tgt(e,t,{mount:Igt,update:Mgt,unmount:Agt})}const Fgt={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"},Pgt=Rgt(Wce,{props:Fgt}),Ogt=S.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(EO,{context:t})," "]})}),Gce=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),Lgt=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),$gt=Array.from(Gce).join(", "),zgt=3,Bgt="Self-heal",Vgt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function Hgt({card:e}){var H,P,K,Y,M;const[t,n]=S.useState({}),{authToken:r}=xt(),o=p.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:s}=p.useAppearance(),i=S.useMemo(()=>C0(s),[s]),a=p.useEditorStore(G=>G.frame),l=p.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=p.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=p.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:m}=eh(((H=f.customCardPreferences)==null?void 0:H.url)||""),g=(P=m==null?void 0:m.visuals)==null?void 0:P.find(G=>{var $;return G.name===(($=f.customCardPreferences)==null?void 0:$.componentName)}),b=N0(f,g)??"single",x=S.useMemo(()=>AP({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=S.useMemo(()=>{const G=x.findIndex($=>($==null?void 0:$.id)===e.id);return G<0?-1:Yx(e,G)},[x,e]),v=S.useMemo(()=>b!=="multiple"||y<0?e.type:om(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=S.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:v!==e.type?{...e,type:v}:e,[e,v,b]),{data:C}=TN(w),N=p.useInteractionStore(G=>G.interactionStates),k=p.useDashboardStore(G=>{var $;return($=G.dashboard)==null?void 0:$.id}),_=p.useDashboardStore(G=>G.dashboard.filters),j=p.useDashboardStore(G=>G.filterValues),T=p.useDashboardStore(G=>G.selectedSheetId),E=S.useMemo(()=>TP({card:e,sheetId:T||"",inlineFilterValues:l,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,T,l,u,d]),{cardFilters:D,cardFilterValues:I}=S.useMemo(()=>Xy({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:j,selectedSheetId:T}),[e,N,k,_,j,T]),F=S.useCallback((G,$)=>{const q=FP($);n(B=>({...B,[G]:q}))},[]),O=(K=f.customCardPreferences)==null?void 0:K.componentName,A=O?h(O):null,z=BS((Y=f.customCardPreferences)==null?void 0:Y.settings,f),L=S.useMemo(()=>MP(x),[x]),U=S.useMemo(()=>L.map((G,$)=>om(G,$,g==null?void 0:g.slots)),[L,g==null?void 0:g.slots]);return O?c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(S.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[A&&b==="single"&&c.jsx(A,{editing:!0,params:o,theme:i,settings:z,cardMetadata:Mee({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:D,filterValues:[...I||[],...l||[]],inlineFilters:E}),A&&b==="multiple"&&c.jsxs(c.Fragment,{children:[x.map((G,$)=>{if(!G)return null;const q=Yx(G,$),B=om(G,q,g==null?void 0:g.slots);return c.jsx(rP,{onDataChange:F,card:G,effectiveCardType:B},`${G.id}-${q}`)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(A,{editing:!0,onDataChange:F,...PP({configCard:f,slotOrderedCards:L,slotTypes:U,multiInputData:t,params:o,theme:i,chartSettings:z,filters:D,filterValues:[...I||[],...l||[]],inlineFilters:E})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Ugt=S.memo(Hgt,(e,t)=>{var n,r,o,s,i,a,l,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)&&((o=e.card.customCardPreferences)==null?void 0:o.slotSettings)===((s=t.card.customCardPreferences)==null?void 0:s.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((l=e.card.customCardPreferences)==null?void 0:l.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),qgt=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(o=>o.type===n&&o.id===r),toggleStar:n=>{e(r=>{const o=r.starredCharts.findIndex(s=>s.type===n.type&&s.id===n.id);return o>=0?{starredCharts:r.starredCharts.filter((s,i)=>i!==o)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(o=>o.type===n&&o.id===r)}),{name:"semaphor-starred-charts"}));var Kce=["PageUp","PageDown"],Zce=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xce={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},fg="Slider",[JM,Wgt,Ygt]=p.createCollection(fg),[Qce]=p.createContextScope(fg,[Ygt]),[Ggt,F_]=Qce(fg),Jce=Z.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=Z.useRef(new Set),y=Z.useRef(0),w=i==="horizontal"?Kgt:Zgt,[C=[],N]=p.useControllableState({prop:d,defaultProp:u,onChange:D=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(D)}}),k=Z.useRef(C);function _(D){const I=tbt(C,D);E(D,I)}function j(D){E(D,y.current)}function T(){const D=k.current[y.current];C[y.current]!==D&&h(C)}function E(D,I,{commit:F}={commit:!1}){const O=sbt(s),A=ibt(Math.round((D-r)/s)*s+r,O),z=p.clamp(A,[r,o]);N((L=[])=>{const U=Jgt(L,z,I);if(obt(U,l*s)){y.current=U.indexOf(z);const H=String(U)!==String(L);return H&&F&&h(U),H?U:L}else return L})}return c.jsx(Ggt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:c.jsx(JM.Provider,{scope:e.__scopeSlider,children:c.jsx(JM.Slot,{scope:e.__scopeSlider,children:c.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:o,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:j,onSlideEnd:a?void 0:T,onHomeKeyDown:()=>!a&&E(r,0,{commit:!0}),onEndKeyDown:()=>!a&&E(o,C.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:I})=>{if(!a){const A=Kce.includes(D.key)||D.shiftKey&&Zce.includes(D.key)?10:1,z=y.current,L=C[z],U=s*A*I;E(L+U,z,{commit:!0})}}})})})})});Jce.displayName=fg;var[eue,tue]=Qce(fg,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Kgt=Z.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=Z.useState(null),m=p.useComposedRefs(t,w=>h(w)),g=Z.useRef(void 0),b=p.useDirection(o),x=b==="ltr",y=x&&!s||!x&&s;function v(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=dL(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return c.jsx(eue,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:c.jsx(nue,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=v(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=v(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:w=>{const N=Xce[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),Zgt=Z.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=Z.useRef(null),f=p.useComposedRefs(t,d),h=Z.useRef(void 0),m=!o;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=dL(y,m?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return c.jsx(eue,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(nue,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);s==null||s(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xce[m?"from-bottom":"from-top"].includes(b.key);l==null||l({event:b,direction:y?-1:1})}})})}),nue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=F_(fg,n);return c.jsx(p.Primitive.span,{...u,ref:t,onKeyDown:p.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kce.concat(Zce).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:p.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:p.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),rue="SliderTrack",oue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=F_(rue,n);return c.jsx(p.Primitive.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});oue.displayName=rue;var eA="SliderRange",sue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=F_(eA,n),s=tue(eA,n),i=Z.useRef(null),a=p.useComposedRefs(t,i),l=o.values.length,u=o.values.map(h=>lue(h,o.min,o.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(p.Primitive.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});sue.displayName=eA;var tA="SliderThumb",iue=Z.forwardRef((e,t)=>{const n=Wgt(e.__scopeSlider),[r,o]=Z.useState(null),s=p.useComposedRefs(t,a=>o(a)),i=Z.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(Xgt,{...e,ref:s,index:i})}),Xgt=Z.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=F_(tA,n),a=tue(tA,n),[l,u]=Z.useState(null),d=p.useComposedRefs(t,v=>u(v)),f=l?i.form||!!l.closest("form"):!0,h=p.useSize(l),m=i.values[r],g=m===void 0?0:lue(m,i.min,i.max),b=ebt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?nbt(x,g,a.direction):0;return Z.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),c.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[c.jsx(JM.ItemSlot,{scope:e.__scopeSlider,children:c.jsx(p.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(aue,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});iue.displayName=tA;var Qgt="RadioBubbleInput",aue=Z.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=Z.useRef(null),s=p.useComposedRefs(o,r),i=p.usePrevious(t);return Z.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});aue.displayName=Qgt;function Jgt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function lue(e,t,n){const s=100/(n-t)*(e-t);return p.clamp(s,[0,100])}function ebt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function tbt(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function nbt(e,t,n){const r=e/2,s=dL([0,50],[0,r]);return(r-s(t)*n)*n}function rbt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function obt(e,t){if(t>0){const n=rbt(e);return Math.min(...n)>=t}return!0}function dL(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 sbt(e){return(String(e).split(".")[1]||"").length}function ibt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var cue=Jce,abt=oue,lbt=sue,cbt=iue;const uue=Z.forwardRef(({className:e,...t},n)=>c.jsxs(cue,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(abt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx(lbt,{className:"absolute h-full bg-primary"})}),c.jsx(cbt,{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"})]}));uue.displayName=cue.displayName;const due=["SUN","MON","TUE","WED","THU","FRI","SAT"],ubt=due.reduce((e,t,n)=>({...e,[t]:n}),{}),al={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function dbt(e){if(!e||!e.trim())return{...al};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{...al,isCustom:!0};const[o,s,i,a,l]=r,u=Number(o),d=Number(s);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...al,isCustom:!0};if(i==="*"&&(l==="?"||l==="*"))return{...al,repeats:"daily",hour:d,minute:u};if(i==="?"&&l!=="?"&&l!=="*"){const h=l.split(",").map(m=>m.toUpperCase()).map(m=>ubt[m]).filter(m=>typeof m=="number");if(h.length>0)return{...al,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(l==="?"||l==="*")?{...al,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(l==="?"||l==="*")?{...al,repeats:"monthly",hour:d,minute:u}:{...al,hour:d,minute:u,isCustom:!0}}function fbt(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((o,s)=>o-s).map(o=>due[o]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fue(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,o=t.toString().padStart(2,"0");return`${r}:${o} ${n}`}function hbt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function mbt(e){if(e.length===7)return"every day";const t=e.slice().sort((o,s)=>o-s);if(t.length===5&&t.every(o=>o>=1&&o<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(o=>r[o]).join(", ")}function pbt(e,t,n,r){const o=fue(e.hour,e.minute),s=hbt(t);let i;if(e.isCustom)i=`Custom schedule · ${o} ${s}`;else switch(e.repeats){case"daily":i=`Daily at ${o} ${s}`;break;case"weekly":i=`Weekly · ${mbt(e.weekdays)} at ${o} ${s}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${o} ${s}`;break;case"monthly":i=`Monthly on the 1st at ${o} ${s}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const gbt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=vO;exports.AccordionContent=sy;exports.AccordionItem=ry;exports.AccordionTrigger=oy;exports.AddDataPicker=aL;exports.AggregateTable=ck;exports.Alert=AR;exports.AlertDescription=RR;exports.AlertDialog=Uf;exports.AlertDialogAction=Eu;exports.AlertDialogCancel=Du;exports.AlertDialogContent=Cu;exports.AlertDialogDescription=ju;exports.AlertDialogFooter=ku;exports.AlertDialogHeader=Nu;exports.AlertDialogTitle=_u;exports.AlertDialogTrigger=Kpe;exports.AlertTitle=mG;exports.ArrowDown=vs;exports.ArrowDownIcon=W6e;exports.ArrowLeft=zy;exports.ArrowRight=YC;exports.ArrowUp=ws;exports.ArrowUpIcon=G6e;exports.AssistantContextEntityControls=QM;exports.AssistantStatus=cle;exports.AtSign=vH;exports.AxisConfigurator=Np;exports.Badge=Ar;exports.Bell=Zw;exports.BookType=wH;exports.BulletChartIcon=lle;exports.COMMON_TIMEZONES=gbt;exports.CSS=Xs;exports.CalculatedFieldEditor=Yne;exports.Calculator=CH;exports.Calendar=Hs;exports.Calendar$1=m1;exports.CalendarRange=NH;exports.Card=Em;exports.CardContent=WC;exports.CardHeader=qC;exports.CardSummary=R2;exports.CardTitle=fp;exports.ChartArea=UT;exports.ChartColumnIncreasing=kH;exports.ChartColumnStacked=_H;exports.ChartJsVisual=p0;exports.ChartLine=jH;exports.ChartNoAxesGantt=DH;exports.ChartPie=TH;exports.ChartScatter=IH;exports.ChatInputWithContext=lL;exports.Checkbox=Cn;exports.ChevronLeft=Bf;exports.ChevronRight=Nr;exports.Circle=mA;exports.CircleAlert=px;exports.CircleCheck=RH;exports.CircleHelp=FH;exports.Clock=pA;exports.CodeHighlighter=uf;exports.CodeXml=Xw;exports.Collapsible=Ul;exports.CollapsibleContent=Wl;exports.CollapsibleTrigger=ql;exports.ColorField=ui;exports.Command=$k;exports.CommandEmpty=Bk;exports.CommandGroup=Vk;exports.CommandInput=lO;exports.CommandItem=Hk;exports.CommandList=zk;exports.CommandSeparator=hne;exports.ComparisonMetadataBadge=LX;exports.Container=zA;exports.ControlDefaultValueEditor=pre;exports.ControlDefinitionOptionsEditor=mre;exports.ControlIdInput=ure;exports.ControlVisibilitySettings=tYe;exports.Copy=hf;exports.CopyButton=$l;exports.CopyPlus=PH;exports.Cross2Icon=Q6e;exports.CustomFilterPopover=EP;exports.CustomScrollArea=Za;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=BZ;exports.DEFAULT_SCHEDULE_VM=al;exports.Dashboard=Wce;exports.DashboardActionsMenu=tq;exports.DashboardCard=yte;exports.DashboardCreateDialogBase=Iq;exports.DashboardExportDialog=zce;exports.DashboardPlus=vgt;exports.DashboardWC=Pgt;exports.DataTableConditionalFormattingSettings=sie;exports.DataTablePagination=ok;exports.Database=gi;exports.DateRangePicker=cP;exports.DefaultChatTransport=oL;exports.Dialog=as;exports.DialogContent=Vo;exports.DialogDescription=os;exports.DialogFooter=ec;exports.DialogHeader=ki;exports.DialogTitle=So;exports.DialogTrigger=Dq;exports.DisplayPreferencesProvider=Ek;exports.DndContext=P0;exports.Donut=OH;exports.Download=Xl;exports.DownloadPdf=Bce;exports.DragOverlay=Jte;exports.DropdownMenu=Es;exports.DropdownMenuCheckboxItem=vc;exports.DropdownMenuContent=rs;exports.DropdownMenuItem=Sn;exports.DropdownMenuLabel=Ml;exports.DropdownMenuRadioGroup=lme;exports.DropdownMenuRadioItem=JU;exports.DropdownMenuSeparator=Zi;exports.DropdownMenuSub=MA;exports.DropdownMenuSubContent=nN;exports.DropdownMenuSubTrigger=tN;exports.DropdownMenuTrigger=Ds;exports.EMPTY_DATA_SOURCE=ky;exports.Editable=HS;exports.EditableText=yi;exports.EditorCustomVisual=Ugt;exports.Ellipsis=Oa;exports.EllipsisVertical=Vf;exports.ErrorBoundary=ea;exports.ExportError=Ip;exports.ExternalLink=Tm;exports.Eye=By;exports.EyeOff=GC;exports.Fallback=_k;exports.FallbackVisual=Kx;exports.FeedbackCategory=xu;exports.FeedbackDialog=Cy;exports.FieldsList=EO;exports.FieldsSection=Ogt;exports.FileSpreadsheet=LH;exports.FileText=Ys;exports.Filter=mf;exports.FilterComponent=vk;exports.FilterInfo=T2;exports.FilterableFieldsPanel=Kne;exports.Globe=hp;exports.Grid3x3=$H;exports.GripVertical=Ql;exports.HEATMAP_PRESET_PALETTES=ZI;exports.Hash=zH;exports.House=BH;exports.HoverCard=Ap;exports.HoverCardContent=du;exports.HoverCardTrigger=Rp;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gce;exports.INLINE_ALLOWED_TOOL_LIST=$gt;exports.INLINE_BLOCKED_MUTATING_TOOLS=Lgt;exports.IconButton=Hc;exports.IconForFieldType=w1;exports.InfoHover=ZP;exports.InlineFilterBar=cte;exports.KPICard=_f;exports.KeyboardSensor=R0;exports.Layers=KC;exports.LayoutDashboard=Im;exports.Link=VH;exports.LoadingDots=hu;exports.Lock=ZC;exports.MAX_SELF_HEAL_ATTEMPTS=zgt;exports.Map=HH;exports.Markdown=mae;exports.Maximize2=XC;exports.MdStackedLineChart=ile;exports.Minimize2=gA;exports.MultiInputEmptyRenderer=rP;exports.PYTHON_DEFAULT_CODE=rA;exports.PanelLeft=qH;exports.PanelResizeHandle=y_;exports.Paperclip=WH;exports.PenLine=WT;exports.Pencil=YH;exports.PendingMessagesDisplay=Fce;exports.PersistedDynamicVisual=jk;exports.PiChartPolar=nle;exports.PivotTableTanstack=qp;exports.Placeholders=dle;exports.Play=GH;exports.Plus=pr;exports.PointerSensor=Xp;exports.PrintMessages=ule;exports.Progress=G5;exports.RECOVERABLE_SQL_ERROR_CODES=Vgt;exports.Radar=KH;exports.RadioGroup=Qi;exports.RadioGroupItem=fo;exports.RefreshCw=pf;exports.ResizableHandle=cet;exports.ResizablePanel=_M;exports.ResizablePanelGroup=Iie;exports.ResourceEditDialog=lW;exports.ResourceType=Or;exports.SELF_HEAL_TIMELINE_STEP=Bgt;exports.Search=zo;exports.SeedQuestions=Dce;exports.SemaphorContext=Oy;exports.SemaphorContextProvider=uA;exports.SemaphorQueryClient=mH;exports.SemaphorReadyIndicator=uL;exports.SemaphorStyleWrapper=Wp;exports.Send=ZH;exports.Settings=xA;exports.Settings2=Vy;exports.Share2=XH;exports.ShareDialog=aW;exports.Sheet=_X;exports.SheetContent=RF;exports.SheetDescription=PF;exports.SheetHeader=EX;exports.SheetTitle=FF;exports.SheetTrigger=yMe;exports.Slider=uue;exports.SortableContext=O0;exports.Sparkles=Mm;exports.Square=QH;exports.SquarePen=yA;exports.Star=vA;exports.StructuralParticipantSelector=dre;exports.SummaryCard=E2;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xc;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=hi;exports.TableBody=Nf;exports.TableCell=Hn;exports.TableColumnVisibilitySettings=Yse;exports.TableHead=ys;exports.TableHeader=Mp;exports.TablePresentationSettings=Kse;exports.TableRow=Fr;exports.TableSkeleton=XP;exports.TableVisual=fu;exports.TbChartBubble=rle;exports.TbChartFunnel=ole;exports.TbChartTreemap=sle;exports.TextCard=Qm;exports.Textarea=Wf;exports.TiSortNumerically=ale;exports.Toggle=k0;exports.Tornado=JH;exports.Trash2=Jl;exports.TreePalm=SA;exports.TrendingUp=QC;exports.TriangleAlert=Bi;exports.TypeGlyph=D0;exports.UXProvider=cL;exports.User=nU;exports.UserRound=tU;exports.Users=CA;exports.applyFilterOverridesToDashboardInputSlots=RY;exports.areContextEntitiesEqual=Cr;exports.areEntitiesJoined=WZ;exports.arrayMove=Qp;exports.buildCardControlUsageById=rYe;exports.buildCustomCardTheme=C0;exports.buildDashboardCardExecutionSnapshot=AY;exports.buildDashboardControlUsageById=nYe;exports.buildDashboardExecutionSnapshot=jR;exports.buildDashboardInputExecutionSnapshot=qc;exports.buildDashboardSheetsInputExecutionSnapshot=PY;exports.buildDashboardStructuralParticipantIdsByControlId=xre;exports.buildFilterFieldMeta=mO;exports.buildFilterSemanticContext=pO;exports.buildInlineFilterNodes=TP;exports.buildMultiInputCustomVisualProps=PP;exports.buildScheduleExpr=fbt;exports.buildSchedulePreview=pbt;exports.buildSlotOrderedCards=MP;exports.calculateContextAwareFilters=Xy;exports.calculateFieldState=kF;exports.canUserAccessVisuals=FVe;exports.canUserCreateDashboards=RVe;exports.canUserEdit=IVe;exports.canUserManageDashboards=AVe;exports.canUserManageGroups=PVe;exports.canUserUseFilters=MVe;exports.cancelExport=a2e;exports.chartSupportsDataLabels=LK;exports.chartSupportsLegend=PK;exports.chartTypes=D_;exports.cleanupKpiMetricComparisonMode=wne;exports.cloneDeep=Ss;exports.cloneLinkedFrameWithSourceMapping=cVe;exports.closestCenter=A0;exports.commitSharedCalculatedFields=fd;exports.createAssistantConversationId=Vh;exports.createAssistantRequestId=jce;exports.createCardsFromSlots=kBe;exports.createChartConfig=Tp;exports.createDashboardControlInputFromControl=ZQe;exports.createDefaultGlobalDateFilter=H0e;exports.createExport=fX;exports.createUniqueDashboardInputVariableNameFromName=eu;exports.dedup=Kmt;exports.doesStoredFilterMatchField=rp;exports.downloadDocumentPdf=DR;exports.downloadPdf=UY;exports.extractSqlParamReferences=yJ;exports.extractTableMetadata=hO;exports.fieldAlreadyExists=GZ;exports.findCustomVisualConfigCard=RP;exports.findDashboardFrameById=R0e;exports.flexRender=Ns;exports.formatDisplayFormula=XUe;exports.formatFileSize=u2e;exports.formatFilterLine=gG;exports.formatTimeLabel=fue;exports.getAutoDetectedChartIcon=Blt;exports.getChartGridStyle=f1e;exports.getChartIconByType=Vlt;exports.getColorForValue=hI;exports.getConfigSlotExpectedType=NBe;exports.getCoreRowModel=tk;exports.getCustomVisualInputCards=AP;exports.getDateFormatOptionsForGranularity=ty;exports.getDefaultAxisConfig=pI;exports.getDefaultChartColors=Xf;exports.getDefaultDataLabelsConfig=c0;exports.getDefaultExportFormat=AG;exports.getDefaultFilterSql=mP;exports.getDefaultLegendConfig=lF;exports.getDefaultRunningTotalPartitionByFieldIds=nx;exports.getDocumentSectionEditorCard=RWe;exports.getDocumentSheetDashboardInputs=K0;exports.getDownloadUrl=i2e;exports.getEffectiveCardTypeForSlot=om;exports.getEntityIcon=UC;exports.getErrorMessage=yce;exports.getExportStatus=s2e;exports.getExports=o2e;exports.getExpressionFieldKind=pu;exports.getFieldExpressionAnnotation=gO;exports.getFilterCount=GS;exports.getGlobalDateFilter=xp;exports.getGlobalDateFilterCoverage=U0e;exports.getGranularityOptionsForFieldType=RO;exports.getKeys=Qn;exports.getMetricDisplayLabel=_Ie;exports.getNewField=JZ;exports.getObjectDiff=G7;exports.getPaginationRowModel=nk;exports.getRoleBasedDisplayOverrides=lte;exports.getRunningTotalOrderByCandidates=vUe;exports.getSelectedDateFilterColumn=wJ;exports.getSheetScopedFilterValues=Sx;exports.getSlotDefinitionForIndex=IP;exports.getSlotExpectedChartType=Ck;exports.getSlotIndexForCard=Yx;exports.getSortedRowModel=kX;exports.getSupportedExportFormats=MG;exports.getTableConditionalFormattingColumnOptions=Jse;exports.getTableOutputColumnOptions=eie;exports.getTablePageSizeOptions=cX;exports.handleAggregationChange=I2;exports.handleAggregationLabelChange=ite;exports.hasFlatTableTotalsBehavior=Lve;exports.horizontalListSortingStrategy=oO;exports.isCalculatedFilterField=ny;exports.isCardSummaryVisibleOnCard=OP;exports.isCustomVisualConfigCard=_2;exports.isDefaultColor=Yve;exports.isEligibleFlatTableTotalsCard=yp;exports.isExportComplete=c2e;exports.isExportInProgress=l2e;exports.isInAiScopeArray=Gmt;exports.isManagedCalculatedExpressionField=qi;exports.isMetricTransformEnabled=xUe;exports.isPromiseLike=ZM;exports.isSubtotalEnabledAggregateTable=fO;exports.isSupportedDocumentTableCardType=FWe;exports.lastAssistantMessageIsCompleteWithToolCalls=pce;exports.merge=Pa;exports.mergeAxisConfig=gI;exports.normalizeConditionalFormatting=vR;exports.normalizeContextFormatMode=SG;exports.normalizeDashboardInputVariableName=$y;exports.normalizeMultiInputPayload=FP;exports.parseScheduleExpr=dbt;exports.pivotData=n0;exports.prepareFeedbackData=E_;exports.purify=nQ;exports.reindexSlotCards=CBe;exports.remarkGfm=Vae;exports.removeFromScopeArray=Zmt;exports.resolveDomainCalculatedFieldForEdit=Wqe;exports.resolveMultiInputType=N0;exports.resolveMultiInputTypeFromVisual=_Be;exports.resolveTablePageSize=QN;exports.resolveTablePresentationStyle=WF;exports.sanitizeAIScope=xce;exports.saveCalculatedFieldToCardScope=H2;exports.saveCalculatedFieldToSharedScope=Gne;exports.saveCalculatedFieldToSheetScope=U2;exports.seedSemanticMetricFormatDefaults=Cne;exports.setTableColumnVisibility=pX;exports.setupEditorWithCard=IN;exports.showAllTableColumns=m2e;exports.showJoinRequiredNotification=YZ;exports.sortByColumnsToSortState=GX;exports.sortStateToSortByColumns=KX;exports.sortableKeyboardCoordinates=iO;exports.supportsMetricTransformForMetric=Sne;exports.supportsTableConditionalFormatting=Zse;exports.toEntityArray=Ui;exports.ue=Xe;exports.useActiveExports=Jge;exports.useActiveToolStatus=$ce;exports.useAddFrameWithFreshSemanticExecutionPayload=KP;exports.useAddNewFrame=Dte;exports.useAssistantContainer=fW;exports.useAssistantContextEntities=Tk;exports.useAssistantLayoutStore=Yd;exports.useAssistantPanel=uW;exports.useAssistantProfile=Ece;exports.useAutoScroll=Oce;exports.useAutoSubmitQueue=Pce;exports.useBrandStudioPreview=igt;exports.useCard=LIe;exports.useCardFilterValues=tX;exports.useCardSummary=LP;exports.useChat=bce;exports.useColumns=cO;exports.useCreateVisualWithFrame=epe;exports.useCurrentUserInfo=Ni;exports.useCustomVisual=eh;exports.useCustomVisualsQuery=jP;exports.useDashboardAppearance=qa;exports.useDashboardById=lq;exports.useDashboardCreation=dq;exports.useDashboardManagement=uq;exports.useDashboardPreferences=mp;exports.useDashboardQuery=Ly;exports.useDashboardStructuralParticipants=yre;exports.useDashboardSummary=Bee;exports.useDataColumns=kne;exports.useDateFilterHook=r4e;exports.useDebounce=Zb;exports.useDefaultDashboardMutation=nq;exports.useDisplayPreferences=Ka;exports.useDroppable=Qte;exports.useEditorAside=Uk;exports.useEditorCardQuery=TN;exports.useEnsureReactGlobals=GQ;exports.useExportActions=hW;exports.useExportStore=dN;exports.useFieldManagement=Nne;exports.useFilterableFields=xne;exports.useFullscreenAssistant=dW;exports.useGroupMembers=ege;exports.useGroups=Jq;exports.useHasDashboardId=mW;exports.useInProgressExportsCount=ebe;exports.useIsDashboardSelected=qde;exports.useIsVisualSelected=Wde;exports.useJoinabilityMap=dO;exports.useManagementActions=zf;exports.useManagementStore=Wr;exports.useMessageWindow=Lce;exports.useMutation=Oo;exports.usePivotTableConfig=Jf;exports.usePluginQuery=jee;exports.useQuery=Dn;exports.useQueryClient=Vr;exports.useReactTable=rk;exports.useResolveExistingFrameSemanticExecutionPayload=hVe;exports.useResourceManagement=sN;exports.useResourceUpdateState=cq;exports.useScopedFields=bne;exports.useSelectedVisual=Ude;exports.useSemaphorContext=xt;exports.useSensor=np;exports.useSensors=Rk;exports.useSortable=Jp;exports.useStarredChartsStore=qgt;exports.useSurfaceAppearance=nc;exports.useTableQueryState=$X;exports.useTextFilterHook=m4e;exports.useTheme=oA;exports.useTopoJson=d0;exports.useUnifiedUsers=LA;exports.useUpdateResource=oq;exports.useUpdateVisualMutation=tpe;exports.useUserPreferences=Mq;exports.useVisualById=oN;exports.useVisualManagement=Jme;exports.validateFieldForChartType=vne;exports.verticalListSortingStrategy=sO;
1303
+ `)}})}});var Dmt=Sht(()=>sce(Ci([vr({type:cn("text-start"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("text-delta"),id:Rt(),delta:Rt(),providerMetadata:$r.optional()}),vr({type:cn("text-end"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("error"),errorText:Rt()}),vr({type:cn("tool-input-start"),toolCallId:Rt(),toolName:Rt(),providerExecuted:hs().optional(),dynamic:hs().optional()}),vr({type:cn("tool-input-delta"),toolCallId:Rt(),inputTextDelta:Rt()}),vr({type:cn("tool-input-available"),toolCallId:Rt(),toolName:Rt(),input:xa(),providerExecuted:hs().optional(),providerMetadata:$r.optional(),dynamic:hs().optional()}),vr({type:cn("tool-input-error"),toolCallId:Rt(),toolName:Rt(),input:xa(),providerExecuted:hs().optional(),providerMetadata:$r.optional(),dynamic:hs().optional(),errorText:Rt()}),vr({type:cn("tool-output-available"),toolCallId:Rt(),output:xa(),providerExecuted:hs().optional(),dynamic:hs().optional(),preliminary:hs().optional()}),vr({type:cn("tool-output-error"),toolCallId:Rt(),errorText:Rt(),providerExecuted:hs().optional(),dynamic:hs().optional()}),vr({type:cn("reasoning-start"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("reasoning-delta"),id:Rt(),delta:Rt(),providerMetadata:$r.optional()}),vr({type:cn("reasoning-end"),id:Rt(),providerMetadata:$r.optional()}),vr({type:cn("source-url"),sourceId:Rt(),url:Rt(),title:Rt().optional(),providerMetadata:$r.optional()}),vr({type:cn("source-document"),sourceId:Rt(),mediaType:Rt(),title:Rt(),filename:Rt().optional(),providerMetadata:$r.optional()}),vr({type:cn("file"),url:Rt(),mediaType:Rt(),providerMetadata:$r.optional()}),vr({type:ece(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Rt().optional(),data:xa(),transient:hs().optional()}),vr({type:cn("start-step")}),vr({type:cn("finish-step")}),vr({type:cn("start"),messageId:Rt().optional(),messageMetadata:xa().optional()}),vr({type:cn("finish"),finishReason:Xle(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:xa().optional()}),vr({type:cn("abort")}),vr({type:cn("message-metadata"),messageMetadata:xa()})])));function Tmt(e){return e.type.startsWith("data-")}function hce(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 o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?n[r]=hce(s,o):n[r]=o}return n}function Imt(e){const t=["ROOT"];let n=-1,r=null;function o(l,u,d){switch(l){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 s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":o(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,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":{o(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,o(u,l,"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=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;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=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){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 mce(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await HC({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await HC({text:Imt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function R1(e){return e.type.startsWith("tool-")}function Mmt(e){return e.type==="dynamic-tool"}function YM(e){return R1(e)||Mmt(e)}function S7(e){return e.type.split("-").slice(1).join("-")}function Amt({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 Rmt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,g;function b(C){const k=u.message.parts.filter(R1).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(T=>R1(T)&&T.toolCallId===C.toolCallId),_=C,j=k;k!=null?(k.state=C.state,j.input=_.input,j.output=_.output,j.errorText=_.errorText,j.rawInput=_.rawInput,j.preliminary=_.preliminary,j.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 v(C){var N,k;const _=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),j=C,T=_;_!=null?(_.state=C.state,T.toolName=C.toolName,T.input=j.input,T.output=j.output,T.errorText=j.errorText,T.rawInput=(N=j.rawInput)!=null?N:T.rawInput,T.preliminary=j.preliminary,T.providerExecuted=(k=j.providerExecuted)!=null?k:_.providerExecuted,j.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,providerExecuted:j.providerExecuted,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?hce(u.message.metadata,C):C;t!=null&&await b7({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=(m=a.providerMetadata)!=null?m: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(R1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?v({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 mce(C.text);C.dynamic?v({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?v({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(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?v({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);v({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:S7(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);v({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:S7(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":{o==null||o(new Error(a.errorText));break}default:if(Tmt(a)){(n==null?void 0:n[a.type])!=null&&await b7({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()}}l.enqueue(a)})}}))}async function Fmt({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()}}nv({prefix:"aitxt",size:24});nv({prefix:"aiobj",size:24});var Pmt=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()})}};nv({prefix:"aiobj",size:24});var Omt={};ymt(Omt,{object:()=>$mt,text:()=>Lmt});var Lmt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),$mt=({schema:e})=>{const t=bmt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await mce(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await HC({text:n});if(!o.success)throw new v7({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await nL({value:o.value,schema:t});if(!s.success)throw new v7({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}};async function zmt(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,o=await new Promise((s,i)=>{const a=new FileReader;a.onload=l=>{var u;s((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:o}}))}var Bmt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:s,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=s,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,o,s,i;const a=await jh(this.body),l=await jh(this.headers),u=await jh(this.credentials),d={...pd(l),...pd(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,m=(f==null?void 0:f.headers)!==void 0?pd(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=(o=f==null?void 0:f.credentials)!=null?o:u,y=await((s=this.fetch)!=null?s:globalThis.fetch)(h,{method:"POST",headers:p7({"Content-Type":"application/json",...m},`ai-sdk/${w7}`,m7()),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,o,s;const i=await jh(this.body),a=await jh(this.headers),l=await jh(this.credentials),u={...pd(a),...pd(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:l,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?pd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"GET",headers:p7(h,`ai-sdk/${w7}`,m7()),credentials:m});if(b.status===204)return null;if(!b.ok)throw new Error((s=await b.text())!=null?s:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},oL=class extends Bmt{constructor(e={}){super(e)}processResponseStream(e){return kht({stream:e,schema:Dmt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Vmt=class{constructor({generateId:e=pht,id:t=e(),transport:n=new oL,messageMetadataSchema:r,dataPartSchemas:o,state:s,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Pmt,this.sendMessage=async(f,h)=>{var m,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await zmt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const v=this.state.messages.findIndex(w=>w.id===f.messageId);if(v===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[v].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,v+1),this.state.replaceMessage(v,{...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 m=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+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:m,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const v=this.state.messages,w=v[v.length-1];this.state.replaceMessage(v.length-1,{...w,parts:w.parts.map(C=>YM(C)&&C.toolCallId===m?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>YM(C)&&C.toolCallId===m?{...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=o,this.state=s,this.onError=i,this.onToolCall=a,this.onFinish=l,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:o}){var s,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:Amt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;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:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:o});const b=x=>this.jobExecutor.run(()=>x({state:m.state,write:()=>{var y;this.setStatus({status:"streaming"}),m.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Fmt({stream:Rmt({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(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}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:(s=this.activeResponse)==null?void 0:s.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function pce({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((o,s,i)=>s.type==="step-start"?i:o,-1),r=t.parts.slice(n+1).filter(YM).filter(o=>!o.providerExecuted);return r.length>0&&r.every(o=>o.state==="output-available"||o.state==="output-error")}function Hmt(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(...s){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,s)):n=setTimeout(()=>{r=Date.now(),e.apply(this,s)},l)}}var Umt=Hmt;const qmt=p.getDefaultExportFromCjs(Umt);var gce=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},cr=(e,t,n)=>(gce(e,t,"read from private field"),n?n.call(e):t.get(e)),fa=(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)},yc=(e,t,n,r)=>(gce(e,t,"write to private field"),t.set(e,n),n);function Wmt(e,t){return t!=null?qmt(e,t):e}var ni,F1,P1,Tb,Ib,Mb,zh,GM,KM,Ymt=class{constructor(e=[]){fa(this,ni,void 0),fa(this,F1,"ready"),fa(this,P1,void 0),fa(this,Tb,new Set),fa(this,Ib,new Set),fa(this,Mb,new Set),this.pushMessage=t=>{yc(this,ni,cr(this,ni).concat(t)),cr(this,zh).call(this)},this.popMessage=()=>{yc(this,ni,cr(this,ni).slice(0,-1)),cr(this,zh).call(this)},this.replaceMessage=(t,n)=>{yc(this,ni,[...cr(this,ni).slice(0,t),this.snapshot(n),...cr(this,ni).slice(t+1)]),cr(this,zh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Wmt(t,n):t;return cr(this,Tb).add(r),()=>{cr(this,Tb).delete(r)}},this["~registerStatusCallback"]=t=>(cr(this,Ib).add(t),()=>{cr(this,Ib).delete(t)}),this["~registerErrorCallback"]=t=>(cr(this,Mb).add(t),()=>{cr(this,Mb).delete(t)}),fa(this,zh,()=>{cr(this,Tb).forEach(t=>t())}),fa(this,GM,()=>{cr(this,Ib).forEach(t=>t())}),fa(this,KM,()=>{cr(this,Mb).forEach(t=>t())}),yc(this,ni,e)}get status(){return cr(this,F1)}set status(e){yc(this,F1,e),cr(this,GM).call(this)}get error(){return cr(this,P1)}set error(e){yc(this,P1,e),cr(this,KM).call(this)}get messages(){return cr(this,ni)}set messages(e){yc(this,ni,[...e]),cr(this,zh).call(this)}};ni=new WeakMap;F1=new WeakMap;P1=new WeakMap;Tb=new WeakMap;Ib=new WeakMap;Mb=new WeakMap;zh=new WeakMap;GM=new WeakMap;KM=new WeakMap;var Bh,C7=class extends Vmt{constructor({messages:e,...t}){const n=new Ymt(e);super({...t,state:n}),fa(this,Bh,void 0),this["~registerMessagesCallback"]=(r,o)=>cr(this,Bh)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>cr(this,Bh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>cr(this,Bh)["~registerErrorCallback"](r),yc(this,Bh,n)}};Bh=new WeakMap;function bce({experimental_throttle:e,resume:t=!1,...n}={}){const r=S.useRef("chat"in n?n.chat:new C7(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new C7(n));const s="id"in n?n.id:null,i=S.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,s]),a=S.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=S.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=S.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=S.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return S.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:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Gmt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Kmt(e){return e.filter((n,r,o)=>r===o.findIndex(s=>s.tableName===n.tableName&&s.datamodelName===n.datamodelName))}function Zmt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function Xmt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function xce(e){return e.map(r=>{const o=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:o,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:o,tableReferenceFormat:Xmt(o)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function yce(e){var n,r;if(!e)return"";let t="";try{const o=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=o==null?void 0:o.error)==null?void 0:n.lastError)==null?void 0:r.message)||(o==null?void 0:o.error)||e.message}catch{t=e.message}return t}function A_(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function vce(e,t,n){const r=A_(e,t);if(!r)return[];const o=s=>{var i;return{sourceCard:s,visibleCard:((i=n==null?void 0:n[s.id])==null?void 0:i.visibleCard)||s,...n!=null&&n[s.id]?{replacedCard:n[s.id]}:{}}};return(r.frames||[]).map(s=>Dk(s)).filter(s=>s!==void 0).map(o)}function wce(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 Qmt(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 Xh(e){return(e||[]).map(Qmt)}function Sce(e){return Xh([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function sL(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 Jmt(e,t,n){const r=new Map((e||[]).map(o=>[o.id,o]));return(t||[]).map(o=>{const s=r.get(o.filterId);return{filterId:o.filterId,label:(s==null?void 0:s.title)||o.label||o.name||o.filterId,...s!=null&&s.type?{type:s.type}:{},...s!=null&&s.column||o.name?{column:(s==null?void 0:s.column)||o.name}:{},...s!=null&&s.dataType?{dataType:s.dataType}:{},origin:n,...sL(o)}})}function ept(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...sL(t)}))}function Cce(e,t){var n,r,o,s,i,a,l;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(o=e.field)!=null&&o.qualifiedFieldName||(s=e.field)!=null&&s.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(l=e.field)!=null&&l.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function bT(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((o,s)=>Cce(o,`${t}:${r}:${s}`)))}function tpt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function npt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function rpt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(npt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...sL(r)})),n=e.filter(tpt).map((r,o)=>Cce(r,`replaced-insight:${o}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function opt({card:e,interactionStates:t,currentDashboardId:n}){var l;if(!t)return[];const r=p.getClickFiltersForCardFromStates(e.id,t),o=t[p.DRILL_CONTEXT_CARD_ID],i=(o==null?void 0:o.targetDashboardId)===n&&(o==null?void 0:o.contextMode)!=="none"?(o==null?void 0:o.appliedClickFilters)||[]:[],a=((l=t[e.id])==null?void 0:l.breadcrumbs)??[];return[...r.flatMap((u,d)=>bT(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>bT(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>bT(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Nce(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=>Nce(t)).filter(Boolean)}:null}function kce(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==rA.trim()}function spt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":kce(e)?"custom-python":"config"}function _ce({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:o,runtimeFilterValues:s,interactionStates:i,inlineFilterValuesMap:a}){const l=A_(r,o.selectedSheetId),u=(l==null?void 0:l.id)||o.selectedSheetId,{finalConfig:d}=Qy({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:s??o.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=Xy({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:s??o.activeFilters,selectedSheetId:u}),h=rpt(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:Jmt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:ept(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:opt({card:t,interactionStates:i,currentDashboardId:r.id})}}function ipt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:o,inlineFilterValuesMap:s,replacedCard:i,renderOrder:a}){const{finalConfig:l}=_ce({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:o,inlineFilterValuesMap:s});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:Xh(l.metricColumns),dimensions:Sce(l),selectedEntities:wce(t)}}function apt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function N7({dashboard:e,selectedSheetId:t,activeFilters:n}){var o;const r=((o=A_(e,t??null))==null?void 0:o.id)||t||null;return{selectedSheetId:r,activeFilters:Sx(e.filters,n,r)}}function lpt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:o}){const s=A_(e,t.selectedSheetId),i=(s==null?void 0:s.id)||t.selectedSheetId,a=vce(e,t.selectedSheetId,o),l=sc(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(s==null?void 0:s.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>ipt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:l.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:apt({activeFilters:t.activeFilters})}}function cpt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:o,inlineFilterValuesMap:s,replacedCards:i}){var w,C;const l=vce(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!l)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}=l,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:g,interactionFilterValues:b}=_ce({sourceCard:u,card:d,replacedCard:f,interactionStates:o,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:s}),{comparisonType:x,targetValue:y}=XBe(h,d.type),v=spt(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:v,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...kce(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:wce(d),metrics:Xh(h.metricColumns),dimensions:Sce(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Nce(h.filters),effectiveDashboardFilters:m,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:Xh(h.groupByColumns),pivotBy:Xh(h.pivotByColumns),sortBy:Xh(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...v==="custom-sql"?["This card runs custom SQL."]:v==="custom-python"?["This card runs custom Python."]:[]]}}function Vh(){return crypto.randomUUID()}function jce(){return crypto.randomUUID()}function ZM(e){return typeof(e==null?void 0:e.then)=="function"}async function upt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const o=Object.entries(e);if(o.length===0||!n)return{};const s=await Promise.all(o.map(async([i,a])=>{const l=["resource-by-id",Or.VISUAL,a.insightId];let u=r.getQueryData(l);if(!u)try{u=await r.fetchQuery({queryKey:l,queryFn:()=>p.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=wte(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(s.filter(i=>i!==null))}function dpt({dynamicVisualMode:e="auto"}={}){var A;const{compiledAppearance:t}=p.useAppearance(),n=S.useMemo(()=>GP(t),[t]),r=S.useRef(n);S.useEffect(()=>{r.current=n},[n]);const{authToken:o,tokenProps:s}=xt(),i=Vr(),a=p.useDashboardStore(z=>z.dashboard.aiScopeTables),l=(A=Ly().data)==null?void 0:A.assistantProfileId,u=S.useRef(null),d=S.useRef(Vh()),f=S.useRef(!1),h=S.useRef(!1),m=S.useRef(e);m.current=e;function g(){const z=p.useAIInteractionStore.getState(),L=p.useDashboardStore.getState(),U=jte({overrides:z.dashboardEntitySelectionOverrides,dashboardId:L.dashboard.id,draftScopeKey:L.dashboardAssistantDraftScopeKey});return p.appendQualifiedEntityNameToAIContext(s9e({currentAIContext:z.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:L.dashboard.aiContext,derivedSelectedSheetEntities:_te(L.dashboard,L.selectedSheetId)}))}function b(){const z=p.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:N7({dashboard:z.dashboard,selectedSheetId:z.selectedSheetId,activeFilters:z.filterValues})}}const{sendMessage:x,messages:y,setMessages:v,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:j}=bce({transport:new oL({api:`${s.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${o==null?void 0:o.accessToken}`}),body:()=>{const z=p.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:L,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:l,conversationId:d.current,assistantRequestId:jce(),aiContext:L,dashboardViewState:U,dynamicVisualMode:m.current,dynamicVisualTheme:r.current,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:L})=>({body:{...L,messages:p.cleanupIncompleteMessages(z)}})}),onToolCall:I,sendAutomaticallyWhen:pce,onFinish({message:z,isAbort:L,isDisconnect:U,isError:H}){var P;h.current=!1,z!=null&&z.id&&((P=u.current)!=null&&P.aiContext)&&p.useAIInteractionStore.getState().actions.setAssistantMessageContext(z.id,u.current.aiContext),console.log(L?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":H?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]))},onError(z){var L;if(h.current=!1,z.name==="AbortError"||(L=z.message)!=null&&L.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]));return}console.error("[Dashboard Assistant] Stream error:",z),u.current=null,f.current&&(f.current=!1,d.current=Vh(),v([]))}}),T=S.useCallback((...z)=>{h.current=!0;try{const L=x(...z);return ZM(L)?L.catch(U=>{throw h.current=!1,U}):L}catch(L){throw h.current=!1,L}},[x]),E=S.useCallback((...z)=>{h.current=!0;try{const L=w(...z);return ZM(L)?L.catch(U=>{throw h.current=!1,U}):L}catch(L){throw h.current=!1,L}},[w]),D=z=>{let L=!1;v(U=>{const H=typeof z=="function"?z(U):z;if(H.length===0){if(h.current)return f.current=!0,L=!0,U;f.current=!1,d.current=Vh()}return H}),L&&_()};async function I({toolCall:z}){var M,G;if(z.toolName==="getCurrentTableScope"){N({tool:z.toolName,toolCallId:z.toolCallId,output:{tables:xce(a||[])}});return}const L=p.useDashboardStore.getState().dashboard,U=p.useDashboardStore.getState().inlineFilterValuesMap,H=p.useInteractionStore.getState(),P=H.interactionStates,K=await upt({replacedCards:H.replacedCards,apiServiceUrl:s.apiServiceUrl,accessToken:(o==null?void 0:o.accessToken)||"",queryClient:i}),Y=N7({dashboard:L,selectedSheetId:p.useDashboardStore.getState().selectedSheetId,activeFilters:p.useDashboardStore.getState().filterValues});if(z.toolName==="getDashboardSynopsis"){N({tool:z.toolName,toolCallId:z.toolCallId,output:lpt({dashboard:L,viewState:Y,interactionStates:P,inlineFilterValuesMap:U,replacedCards:K})});return}if(z.toolName==="getCardContext"){const $=((M=z.input)==null?void 0:M.cardId)||((G=z.args)==null?void 0:G.cardId)||"";N({tool:z.toolName,toolCallId:z.toolCallId,output:cpt({dashboard:L,viewState:Y,cardId:$,runtimeFilterValues:p.useDashboardStore.getState().filterValues,interactionStates:P,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),O=yce(k);return{sendMessage:T,regenerate:E,isLoading:F,messages:y,setMessages:D,status:C,stop:_,errorMessage:O,clearError:j}}function Ece(){var u;const{authToken:e,tokenProps:t}=xt(),n=(u=Ly().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:o,isLoading:s,isFetching:i,isError:a}=Dn({queryKey:["assistant-profile",n],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:o==null?void 0:o.assistantProfile,isLoading:s,isFetching:i,isError:a}}function Dce({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(FH,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(p.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function fpt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const o=S.useRef(null),s=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=fl-n;if(l.length>u){Xe.error(`You can only attach ${fl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=Yae(l);if(f.forEach(({file:h,error:m})=>{Xe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>q5(m)));e(h)}catch(h){console.error("Failed to process files:",h),Xe.error("Failed to process one or more files")}o.current&&(o.current.value="")},i=()=>{var a;(a=o.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:o,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:s,className:"hidden",disabled:t||n>=fl}),c.jsx(p.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=fl,title:n>=fl?`Maximum ${fl} files allowed`:"Attach files",children:c.jsx(WH,{className:"h-4 w-4 text-muted-foreground"})})]})}function hpt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:o}){const[s,i]=S.useState(!1),a=S.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=S.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,g=f.clientY;(m<h.left||m>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=S.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=S.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 m=fl-r;if(h.length>m){Xe.error(`You can only attach ${fl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:g,errors:b}=Yae(h);if(b.forEach(({file:x,error:y})=>{Xe.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>q5(y)));t(x),Xe.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),Xe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:p.cn("relative",o),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,s&&!n&&c.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:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(p.Upload,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[fl-r," slot(s) available"]})]})})]})}function mpt(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 ppt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!mpt(e,t,n):r}function Tce(e){const{tokenProps:t}=xt(),n=p.useDashboardStore(l=>l.authToken)||e;p.useEditorStore(l=>l.selectedConnectionId),p.useEditorStore(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:o,data:s,isLoading:i,isError:a}=Dn({queryKey:["semantic-domains"],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:o,error:a,semanticDomainsData:s,semanticDomains:(s==null?void 0:s.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function gpt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:o}){const{semanticDomains:s,isSemanticDomainsLoading:i}=Tce(),a=S.useMemo(()=>xpt(s,e),[s,e]),l=S.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&l.length===0)return c.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(l.length===0)return null;const u=!!n;return c.jsxs("div",{children:[c.jsx(Ice,{label:"Semantic Domains"}),l.map(d=>c.jsx(bpt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:o},d.id))]})}function bpt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:o}){const[s,i]=S.useState(!1),a=s||t.length>0||!!n,{datasets:l,isPending:u}=K0e(a?e.id:void 0),d=S.useMemo(()=>{if(!t)return l;const x=t.trim().toLowerCase();return l.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[l,t]),f=t.length>0&&d.length>0,h=s||f||!!n,m=l.length,g=S.useMemo(()=>d.filter(x=>r.some(y=>Cr(y,xT(x)))).length,[d,r]),b=x=>{const y=xT(x),v=r.some(w=>Cr(w,y));o(v?r.filter(w=>!Cr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:c.jsxs("div",{children:[c.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:[c.jsx(Nr,{className:p.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),m>0&&c.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",m," dataset",m===1?"":"s"," · curated"]}),c.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&c.jsx("ul",{className:"space-y-px pb-1",children:u&&l.length===0?c.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?c.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=xT(x),v=r.some(w=>Cr(w,y));return c.jsx("li",{children:c.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[c.jsx(Cn,{checked:v,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),c.jsx(gi,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),c.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&&c.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ice({label:e}){return c.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function xpt(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 xT(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,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function ypt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:o,isConnectionsLoading:s}=rc(),i=S.useMemo(()=>t?o.filter(l=>l.id===t):o,[o,t]);if(s&&i.length===0)return c.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 c.jsxs("div",{children:[c.jsx(Ice,{label:"Direct Sources"}),i.map(l=>c.jsx(vpt,{connection:l,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},l.id))]})}function vpt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:o}){var g;const[s,i]=S.useState(!1),a=s||t.length>0||!!n,l=((g=e.capabilities)==null?void 0:g.path)??[],u=l.includes("database"),d=l.includes("schema"),f=e.type==="upload",h=e.type==="url",m=S.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return c.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[c.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:[c.jsx(Nr,{className:p.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),c.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),c.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:m>0?m:""})]}),a&&c.jsxs(c.Fragment,{children:[f?c.jsx(wpt,{connection:e,selectedEntities:r,onSelectionChange:o}):h?c.jsx(Spt,{connection:e,selectedEntities:r,onSelectionChange:o}):u?c.jsx(Cpt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:o}):d?c.jsx(Mce,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:o}):c.jsx(iL,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:o}),!f&&!h&&c.jsx(Npt,{connection:e,search:t,selectedEntities:r,onSelectionChange:o})]})]})}function wpt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,o=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),s=a=>{if(!(a!=null&&a.length))return;const l=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,...l])},i=a=>{n(t.filter(l=>!("id"in l&&l.id===a&&l.connectionId===e.id&&(l.type==="upload"||l.type==="file"))))};return c.jsxs("div",{className:"space-y-2 px-8 py-2",children:[c.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[c.jsx(p.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),c.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>s(a.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(p.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"})]}),o.length>0&&c.jsx("ul",{className:"space-y-1",children:o.map(a=>c.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[c.jsx(Ys,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),c.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:c.jsx(p.X,{className:"h-3 w-3"})})]},a.id))})]})}function Spt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,o]=S.useState(""),[s,i]=S.useState(""),[a,l]=S.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),m=s.trim();if(!h||!m)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:m,sourceType:a};n([...t,g]),o(""),i(""),l("api")},f=h=>{n(t.filter(m=>!("id"in m&&m.id===h&&m.connectionId===e.id&&m.type==="url")))};return c.jsxs("div",{className:"space-y-2 px-8 py-2",children:[c.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[c.jsx(p.Input,{value:r,onChange:h=>o(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),c.jsx(p.Input,{value:s,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("select",{value:a,onChange:h=>l(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[c.jsx("option",{value:"api",children:"API endpoint"}),c.jsx("option",{value:"csv",children:"CSV file"}),c.jsx("option",{value:"json",children:"JSON file"})]}),c.jsxs(p.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!s.trim(),onClick:d,children:[c.jsx(pr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&c.jsx("ul",{className:"space-y-1",children:u.map(h=>c.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[c.jsx(hp,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"truncate text-[12px]",children:h.name}),c.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),c.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:c.jsx(p.X,{className:"h-3 w-3"})})]},h.id))})]})}function Cpt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:o}){var a;const s=R_("/v1/databases",{connection_id:e.id},["databases",e.id]);if(s.isLoading)return c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=s.data)==null?void 0:a.databases)??[];return i.length===0?c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):c.jsx("div",{children:i.map(l=>c.jsx(Ace,{label:l.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?c.jsx(Mce,{connection:e,databaseName:l.database_name,search:n,selectedEntities:r,onSelectionChange:o}):c.jsx(iL,{connection:e,databaseName:l.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:o}))},l.database_name))})}function Mce({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:o}){var a;const s=R_("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(s.isLoading)return c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=s.data)==null?void 0:a.schemas)??[];return i.length===0?c.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):c.jsx("div",{children:i.map(l=>c.jsx(Ace,{label:l.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&c.jsx(iL,{connection:e,databaseName:t,schemaName:l.schema_name,search:n,selectedEntities:r,onSelectionChange:o})},l.schema_name))})}function iL({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:o,onSelectionChange:s}){const i=R_("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=S.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 c.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:c.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const l=(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=o.some(m=>Cr(m,f));s(h?o.filter(m=>!Cr(m,f)):[...o,f])};return c.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=o.some(m=>Cr(m,d));return c.jsx("li",{children:c.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:[c.jsx(Cn,{checked:f,onCheckedChange:()=>l(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),c.jsx(p.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),c.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 Npt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const o=R_("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),s=S.useMemo(()=>{var u;const a=((u=o.data)==null?void 0:u.datamodels)??[];if(!t)return a;const l=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(l))},[o.data,t]);if(o.isLoading||s.length===0)return null;const i=a=>{const l={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=>Cr(d,l));r(u?n.filter(d=>!Cr(d,l)):[...n,l])};return c.jsxs("div",{children:[c.jsx("div",{className:"px-8 pb-1 pt-2",children:c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),c.jsx("ul",{children:s.map(a=>{const l={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=>Cr(d,l));return c.jsx("li",{children:c.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:[c.jsx(Cn,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),c.jsx(pfe,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),c.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&c.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Ace({label:e,indentLevel:t,search:n,renderChildren:r}){const[o,s]=S.useState(!1),i=o||n.length>0,a=t===1?"pl-8":"pl-10";return c.jsxs("div",{children:[c.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:p.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[c.jsx(Nr,{className:p.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),c.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function R_(e,t,n,r=!0){const{tokenProps:o}=xt(),s=p.useDashboardStore(a=>a.authToken),i=S.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return Dn({queryKey:n,queryFn:()=>p.getRequest(`${o.apiServiceUrl}${e}`,(s==null?void 0:s.accessToken)||"",i),enabled:r&&!!(s!=null&&s.accessToken)&&Object.values(i).every(a=>a.length>0)})}function k7(e){return e.type==="dataset"&&e.label||e.name}function kpt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.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:[c.jsx("span",{className:"max-w-[180px] truncate",children:k7(n)}),c.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),t(n)},"aria-label":`Remove ${k7(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:c.jsx(p.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function _7(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 yT(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 aL({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:o,onSaveSelectedEntities:s,saveAsDashboardDefault:i=!1}){var se,Se;const{tokenProps:a}=xt(),l=a.config,u=a.semanticDomainAccess||Due.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=S.useState([]),[h,m]=S.useState(void 0),[g,b]=S.useState(""),[x,y]=S.useState("all"),[v,w]=S.useState(void 0),C=S.useRef(!1),{updateDataSource:N}=p.useEditorActions(),k=p.useDashboardStore(ye=>ye.isVisualEditing),_=p.useDashboardStore(ye=>ye.dashboard.aiContext),{setAiContext:j}=p.useDashboardActions(),T=u.mode,E=(l==null?void 0:l.showDirectSource)!==!1,D=T==="include"||T==="exclude"||!E,I=T!=="all",F=E&&!D,O=D?"semanticDomain":n.mode,A=r==="dataSource"&&!E,z=T==="include"&&(((se=u.domainIds)==null?void 0:se.length)||0)===1?(Se=u.domainIds)==null?void 0:Se[0]:void 0,L=S.useCallback(ye=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:ye,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...ye!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=S.useCallback(ye=>{N({...n,...ye})},[n,N]),H=S.useCallback(ye=>{if(r==="aiContext"){"semanticDomainId"in ye&&m(ye.semanticDomainId);return}U(ye)},[r,U]),P=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},S.useEffect(()=>{if(r==="aiContext"&&!e)return;if(D&&n.mode!=="semanticDomain"&&r==="dataSource"){L("semanticDomain");return}if(!I||O!=="semanticDomain")return;const ye=P,Ae=u.domainIds??[],ae=r==="aiContext"?d:n.selectedEntities,xe=((ae==null?void 0:ae.length)??0)>0,ve=((d==null?void 0:d.length)??0)>0;ppt({mode:T,currentDomainId:ye,scopedDomainIds:Ae,hasSelectedEntities:xe})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):m(void 0),ve&&f([]))},[D,I,O,n.mode,P,n.selectedEntities,r,h,d,e,u.domainIds,T,E,U,L]),S.useEffect(()=>{z&&!P&&H({semanticDomainId:z})},[z,P,H]),S.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(D?"semantic":"all");return}if(C.current)return;f([...o||[]]);const ye=r==="aiContext"?_7(o):void 0;m(n.semanticDomainId||ye),w(yT(o))},[e,r,o,n.semanticDomainId,D]);const K=ye=>{C.current=!0,f(d.filter(Ae=>!Cr(Ae,ye)))},Y=S.useCallback((ye,Ae)=>{C.current=!0,f(ye),w(Ae??yT(ye))},[]),M=()=>{var Ae,ae;if(r==="aiContext"){if(k&&N(n),i){const xe={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};j(xe)}s==null||s(d),t(!1);return}const ye=yT(d)??v??O;if(ye==="semanticDomain"){const xe=_7(d)||h||n.semanticDomainId,ve=((Ae=d==null?void 0:d[0])==null?void 0:Ae.connectionId)||n.connectionId,pe=((ae=d==null?void 0:d[0])==null?void 0:ae.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:xe,connectionId:ve,connectionType:pe,selectedEntities:d})}else if(ye==="upload"||ye==="url"){const xe=d==null?void 0:d[0];N({...n,mode:ye,semanticDomainId:void 0,connectionId:(xe==null?void 0:xe.connectionId)||n.connectionId,connectionType:(xe==null?void 0:xe.connectionType)||n.connectionType,selectedEntities:d})}else{const xe=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(xe==null?void 0:xe.connectionId)||n.connectionId,connectionType:(xe==null?void 0:xe.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Tce(),{connections:$}=rc(),q=ye=>{y(ye),ye==="semantic"||ye.startsWith("domain:")?n.mode!=="semanticDomain"&&L("semanticDomain"):(ye==="direct"||ye.startsWith("conn:"))&&n.mode==="semanticDomain"&&L("database")},B=x.startsWith("domain:"),V=x.startsWith("conn:"),R=B?x.slice(7):void 0,W=V?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||B,Q=E&&!D&&(x==="all"||x==="direct"||V),ee=((o==null?void 0:o.length)??0)>0,re=d.length===0&&!ee,ue=d.length===0&&ee?"Clear":"Add",te=r==="aiContext"?"Data context":A?"Select dataset":"Add data",ce=r==="aiContext"?"Set the overall data scope for the dashboard":A?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Vo,{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:[c.jsx(p.VisuallyHidden,{children:c.jsx(So,{children:te})}),c.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:te}),c.jsx("p",{className:"text-[11px] text-muted-foreground",children:ce})]}),c.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:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]}),c.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[c.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:[c.jsx(zo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),c.jsx("input",{type:"text",value:g,onChange:ye=>b(ye.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&&c.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:c.jsx(p.X,{className:"h-3 w-3"})})]}),F&&c.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:c.jsxs("div",{className:"flex w-max items-center gap-1",children:[c.jsx(Jg,{label:"All",active:x==="all",onClick:()=>q("all")}),(G.length>0||$.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx(Jg,{label:"Semantic",active:x==="semantic",onClick:()=>q("semantic")}),c.jsx(Jg,{label:"Direct",active:x==="direct",onClick:()=>q("direct")}),c.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(ye=>c.jsx(Jg,{label:ye.label||ye.name,active:x===`domain:${ye.id}`,onClick:()=>q(`domain:${ye.id}`)},`domain:${ye.id}`)),$.map(ye=>c.jsx(Jg,{label:ye.name,active:x===`conn:${ye.id}`,onClick:()=>q(`conn:${ye.id}`)},`conn:${ye.id}`))]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&c.jsx(gpt,{domainAccess:u,search:g,scopeDomainId:R,selectedEntities:d,onSelectionChange:ye=>Y(ye,"semanticDomain")}),Q&&c.jsx(ypt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:ye=>Y(ye)})]}),c.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[c.jsx("span",{children:"Selected"}),c.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.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"}),c.jsxs("button",{type:"button",onClick:M,disabled:re,className:p.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:[c.jsx("span",{children:ue}),d.length>0&&c.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&c.jsx(kpt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function Jg({label:e,active:t,onClick:n}){return c.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:p.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 UC(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(wA,{className:r});case"view":return c.jsx(By,{className:r});case"materialized view":return c.jsx(vfe,{className:r});case"model":return c.jsx(KC,{className:r});case"file":return c.jsx(Ys,{className:r});case"dataset":return c.jsx(gi,{className:r});case"upload":return c.jsx(p.Upload,{className:r});case"url":return c.jsx(VH,{className:r});default:return c.jsx(hp,{className:r})}}const XM=e=>e.name||e.name,_pt=e=>{const t=XM(e),n="description"in e?e.description:"",r=e.database||"",o=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,o&&` • Schema: ${o}`]})]})};function jpt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:o}){const[s,i]=S.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const l=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return c.jsx(p.TooltipProvider,{children:c.jsx("div",{className:o,children:a&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[l.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsxs(Ar,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[UC(f.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate",children:XM(f)}),c.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:c.jsx(p.X,{className:"h-3 w-3"})})]})}),c.jsx(p.TooltipContent,{side:"top",className:"max-w-xs",children:_pt(f)})]},m)}),d&&c.jsxs(p.Tooltip,{open:s,onOpenChange:i,children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsxs(Ar,{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:[c.jsx(Oa,{className:"h-3 w-3"}),c.jsxs("span",{children:[u.length," more"]}),c.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:c.jsx(p.X,{className:"h-3 w-3"})})]})}),c.jsx(p.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:UC(f.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:XM(f)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),c.jsx(p.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:c.jsx(p.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Rce=Z.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Ho.Input,{ref:n,className:p.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})]}));Rce.displayName=Ho.Input.displayName;const qw=e=>e.label||(e==null?void 0:e.name),j7=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Ept({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:o,selectedEntities:s,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=xt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=S.useState(""),[g,b]=S.useState(""),x=o.filter(k=>{if(!h)return!0;const _=qw(k).toLowerCase(),j=(j7(k)||"").toLowerCase(),T=h.toLowerCase();return _.includes(T)||j.includes(T)});S.useEffect(()=>{e||(m(""),b(""))},[e]),S.useEffect(()=>{x.length>0&&!g&&b(qw(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>qw(_)===g);k&&(s.some(j=>"id"in k&&"id"in j?k.id===j.id:k.name===j.name&&k.connectionId===j.connectionId)||t(k),i(k),r())},v=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>s.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=s.length===o.length,N=s.length>0;return c.jsx(c.Fragment,{children:c.jsxs($k,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:v,children:[o.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Rce,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(p.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:[c.jsx(pr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),o.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[s.length," ",s.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(p.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&&c.jsxs(p.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),l==null||l()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(p.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(zk,{className:"min-h-60",children:[c.jsx(Bk,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(p.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:[c.jsx(pr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Vk,{children:x.map((k,_)=>{const j=w(k),T="id"in k?k.id:`${k.connectionId}-${k.name}`,E=qw(k);return c.jsxs(Hk,{value:E,onSelect:()=>{j?n==null||n(k):t(k)},onMouseDown:D=>{D.preventDefault(),D.stopPropagation()},className:p.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:UC(k.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:j7(k)})]}),j&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(p.Check,{className:"h-3 w-3 text-background"})})]},T)})})]})]})})}function QM({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:o=!1,open:s,onOpenChange:i,onEntityMention:a,onEntityRemoved:l,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,v]=S.useState(!1),[w,C]=S.useState(!1),N=s??y,k=s!==void 0,_=S.useRef(!1),T=p.useEditorStore(R=>R.card.dataSource)??ky,{selectedEntities:E,availableEntities:D,syncWithGlobalContext:I,setSelectedEntities:F,applyDashboardDefaultEntities:O,isEntitySelected:A}=Tk(x),z=e==="full"||e==="display",L=e==="full"||e==="trigger",U=S.useMemo(()=>b&&E.length>0?`Add entity (${E.length})`:g,[E.length,b,g]);S.useEffect(()=>{N&&!_.current&&o&&I(),_.current=N},[N,o,I]);const H=S.useCallback(R=>{k||v(R),i==null||i(R)},[k,i]),P=S.useCallback(R=>{const W=E.filter(X=>!Cr(X,R));F(W),l==null||l(R),d==null||d(W)},[l,d,E,F]),K=S.useCallback(R=>{if(R.length===0)return;const W=E.filter(X=>!R.some(Q=>Cr(X,Q)));F(W),u==null||u(R),d==null||d(W)},[u,d,E,F]),Y=S.useCallback(R=>{const W=A(R)?E.filter(X=>!Cr(X,R)):[...E,R];F(W),d==null||d(W)},[A,d,E,F]),M=S.useCallback(()=>{F(D),d==null||d(D)},[D,d,F]),G=S.useCallback(()=>{F([]),d==null||d([])},[d,F]),$=S.useCallback(R=>{x==="dashboard"?O():F(R),d==null||d(R)},[O,x,d,F]),q=S.useCallback(R=>{const W=E.some(X=>Cr(X,R))?E:[...E,R];F(W),a==null||a(R),d==null||d(W),H(!1)},[a,d,E,H,F]),B=z?c.jsx(jpt,{className:p.cn(n?"contents":"space-y-2"),entities:E,availableEntities:D,onRemoveEntity:P,onRemoveEntities:K}):null,V=L?c.jsxs(c.Fragment,{children:[c.jsxs(p.Popover,{open:N,onOpenChange:H,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs(p.Button,{variant:m,size:"xs",className:p.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[c.jsx(vH,{className:"h-3 w-3 text-muted-foreground"}),!b&&c.jsx("span",{children:U})]})}),c.jsx(p.PopoverContent,{className:p.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:R=>R.preventDefault(),children:c.jsx(Ept,{isOpen:!0,onSelect:Y,onDeselect:Y,onClose:()=>H(!1),availableEntities:D,selectedEntities:E,onTabComplete:q,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{H(!1),C(!0)}})})]}),c.jsx(aL,{incomingSelectedEntities:E,open:w,onOpenChange:C,dataSource:T,dialogMode:"aiContext",onSaveSelectedEntities:$,saveAsDashboardDefault:x==="dashboard"})]}):null;return c.jsx("div",{className:p.cn(n?"flex flex-wrap items-center gap-1":"",!n&&z?"space-y-2":"",f),children:n&&r?c.jsxs(c.Fragment,{children:[V,B]}):c.jsxs(c.Fragment,{children:[B,V]})})}const lL=S.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:o,stop:s,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=S.useState(!1),h=S.useRef(null),{queueMessage:m}=p.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=p.useFileActions(),y=p.useFileAttachments(l);S.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const v=S.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const D=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${D}px`}},[e]);S.useEffect(()=>{v()},[v]),S.useEffect(()=>{const E=setTimeout(()=>{v()},0);return()=>clearTimeout(E)},[v]);const w=()=>{const E=e.trim();!E&&y.length===0||(a!=="ready"?(m(l,E,y),t(""),x(l)):r({preventDefault:()=>{}}))},C=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),w()),E.key==="@"&&f(!0)},N=S.useCallback(E=>{const D=ylt(E.nativeEvent);D.length>0&&(E.preventDefault(),D.forEach(async I=>{const F=await q5(I);g(l,F)}))},[g,l]),k=S.useCallback(E=>{E.forEach(D=>{g(l,D)})},[g,l]),_=S.useCallback(E=>{E.forEach(D=>{g(l,D)})},[g,l]),j=S.useCallback(E=>{b(l,E)},[b,l]),T=S.useCallback(E=>{const D=`@${E}`;e.includes(D)&&t(e.replace(D,"").replace(/\s{2,}/g," ").trim())},[e,t]);return c.jsxs(hpt,{onFilesDropped:k,currentFileCount:y.length,disabled:o,className:"space-y-4",children:[c.jsx(QM,{mode:"display",assistantType:l,onEntityRemoved:E=>{const D="label"in E?E.label:E.name;T(D)},onEntitiesRemoved:E=>{let D=e;E.forEach(I=>{const F="label"in I?I.label:I.name;D=D.replace(`@${F}`,"")}),D!==e&&t(D.replace(/\s{2,}/g," ").trim())}}),y.length>0&&c.jsx(Tlt,{files:y,onRemove:j,showRemove:!o,className:"mb-2"}),c.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:[c.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{v(),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"}}),c.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[c.jsxs("div",{className:"flex items-center gap-0.5",children:[c.jsx(QM,{mode:"trigger",assistantType:l,syncOnOpen:l==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var I;const D="label"in E?E.label:E.name;t(`${e}@${D} `),(I=h.current)==null||I.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),c.jsx(fpt,{onFilesSelected:_,disabled:o,currentFileCount:y.length})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[o&&c.jsx(p.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:s,children:c.jsx(Ffe,{className:"size-3.5"})}),!o&&c.jsx(p.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:c.jsx(ZH,{className:"size-3.5"})})]})]})]})]})});lL.displayName="ChatInputWithContext";function Fce({assistantType:e,className:t}){const n=p.useMessageQueue(e),{removeFromQueue:r}=p.useQueueActions();return n.length===0?null:c.jsxs("div",{className:p.cn("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(pA,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(o=>c.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:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:o.text})}),c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,o.id),title:"Remove from queue",children:c.jsx(p.X,{className:"h-3 w-3"})})]})},o.id))})]})}function Pce({assistantType:e,status:t,isLoading:n,sendMessage:r}){const o=p.useMessageQueue(e),{dequeueMessage:s}=p.useQueueActions();S.useEffect(()=>{if(t!=="ready"||n||!(o&&o.length>0))return;const a=s(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,o,s,r,e])}function Dpt(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 Tpt(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 o=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",s=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Dpt(r);return`${o}:${s}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Oce(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:o=!0,isStreaming:s=!1}=t,i=S.useRef(null),a=S.useRef(null),[l,u]=S.useState(!0),[d,f]=S.useState(!0),[h,m]=S.useState(!1),[g,b]=S.useState(0),x=S.useRef(!0),y=S.useRef(!0),v=S.useRef(!1),w=S.useRef(!1),C=S.useRef(0),N=S.useRef({count:0,signature:"none"}),k=S.useCallback(()=>{if(i.current)return i.current;const A=a.current;if(!A)return null;const z=A.closest("[data-radix-scroll-area-viewport]");if(z)return i.current=z,z;const L=A.parentElement;return L?(i.current=L,L):null},[]),_=S.useCallback(()=>{const A=k();return A?A.scrollHeight-A.scrollTop-A.clientHeight:0},[k]),j=S.useCallback(()=>_()<=n,[_,n]),T=S.useCallback(A=>{x.current!==A&&(x.current=A,u(A))},[]),E=S.useCallback(A=>{y.current!==A&&(y.current=A,f(A))},[]),D=S.useCallback(()=>{m(A=>A&&!1),b(A=>A===0?A:0)},[]),I=S.useCallback((A={})=>{const z=k();if(!z)return;const{force:L=!1,instant:U=!1}=A;if(!L&&v.current)return;const H=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,H==="smooth"&&"scrollTo"in z?z.scrollTo({top:z.scrollHeight,behavior:"smooth"}):z.scrollTop=z.scrollHeight,C.current=z.scrollTop,v.current=!1,T(!0),E(!0),D(),requestAnimationFrame(()=>{w.current=!1})},[r,D,k,T,E]),F=S.useCallback(()=>{b(0),m(!1)},[]),O=S.useCallback(()=>{const A=k();if(!A)return;const z=C.current,L=A.scrollTop,U=L-z;C.current=L;const H=j();if(w.current){E(H),H&&(v.current=!1,T(!0));return}if(U<-1&&!H){v.current=!0,T(!1),E(!1);return}if(H){v.current=!1,T(!0),E(!0),D();return}E(!1),v.current&&T(!1)},[D,k,j,T,E]);return S.useEffect(()=>{const A=k();if(!e||e.length===0){N.current={count:0,signature:"none"},A&&(C.current=A.scrollTop),D();return}const z=e[e.length-1],L=Tpt(z),U=N.current,H=e.length>U.count,P=L!==U.signature;N.current={count:e.length,signature:L};const K=s||o&&(z==null?void 0:z.role)==="assistant"&&P;if(!v.current){T(!0),A&&j()&&E(!0),(H||P||K)&&I({force:!1,instant:K});return}if(H){const Y=e.length-U.count;Y>0&&(m(!0),b(M=>M+Y))}else P&&(m(!0),b(Y=>Y>0?Y:1))},[D,s,o,k,j,e,I,T,E]),S.useEffect(()=>{I({force:!0,instant:!0})},[I]),S.useEffect(()=>{if(typeof ResizeObserver>"u")return;const A=a.current;if(!A)return;const z=new ResizeObserver(()=>{v.current||I({force:!1,instant:!0})});return z.observe(A),()=>{z.disconnect()}},[I]),S.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:l,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:I,handleScroll:O,resetNewMessageCount:F}}function Lce(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:o=10}=t,[s,i]=S.useState(r),a=S.useMemo(()=>{if(e.length<=s)return e;const h=Math.max(0,e.length-s);return e.slice(h)},[e,s]),l=e.length>s,u=s>=e.length,d=S.useCallback(()=>{i(h=>Math.min(h+o,n))},[o,n]),f=S.useCallback(()=>{i(r)},[r]);return S.useEffect(()=>{u&&e.length>s&&s<n&&i(Math.min(e.length,n))},[e.length,s,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const E7={"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 Ipt(e,t){var r;if((r=E7[e])!=null&&r[t])return E7[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function $ce(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 o=r,s=o.state;return{hasActiveTools:!0,activeToolText:Ipt(o.type,s),toolType:o.type}}}return{hasActiveTools:!1}}const Mpt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Apt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=S.useState(!1),[a,l]=S.useState(p.isDevEnv),[u,d]=S.useState(!1),[f,h]=S.useState("auto"),[m,g]=S.useState(!1),[b,x]=S.useState(!1),y=n??b,{isLocalDev:v,isConsoleMode:w}=mp(),C=S.useRef(null);p.useDashboardStore(he=>he.dashboard.aiScopeTables),p.useDashboardStore(he=>he.isDashboardEditing);const N=p.useDashboardStore(he=>he.selectedSheetId),{setDataSource:k}=p.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:j}=p.useDashboardActions(),T=KP(),{setReasoningEffort:E,setShowReasoning:D,clearAssistantMessageContexts:I}=p.useAIActions(),{clearQueue:F}=p.useQueueActions(),{clearFileAttachments:O,getFileAttachments:A}=p.useFileActions(),z=p.useFileAttachments("dashboard"),L=p.useEditorStore(he=>he.card.dataSource),{assistantProfile:U}=Ece(),H=p.useDashboardStore(he=>he.handleOpenAssistantProfile),{selectedEntities:P,applyDashboardDefaultEntities:K}=Tk("dashboard"),{sendMessage:Y,isLoading:M,messages:G,setMessages:$,status:q,stop:B,errorMessage:V,clearError:R}=dpt({dynamicVisualMode:f}),W=S.useCallback(he=>{r==null||r(he),n===void 0&&x(he)},[n,r]),X=S.useCallback(()=>{W(!y)},[y,W]);S.useEffect(()=>{if(!y)return;function he(ze){ze.key==="Escape"&&W(!1)}return window.addEventListener("keydown",he),()=>{window.removeEventListener("keydown",he)}},[y,W]);const[Q,ee]=S.useState(""),re=he=>{ee(he.target.value)};async function ue({sql:he,cardTitle:ze,connectionId:Ne,cardType:Ee,python:Ze,cardConfig:Re,dataSource:Be,customVisualPreferences:Ve,visualizationMode:ht,dynamicCardPreferences:rt}){if(!N)return;const Je=ht==="dynamic",vt=p.hasValidCardConfig(Re),nt=Ne||(Be==null?void 0:Be.connectionId)||"",_t=Be?{...Be,connectionId:nt||Be.connectionId,connectionType:Be.connectionType||"",mode:Be.mode||"database",selectedEntities:Be.selectedEntities||[]}:nt?{connectionId:nt,connectionType:"",mode:"database",selectedEntities:[]}:ky,je=!vt||!Je||(rt==null?void 0:rt.provenance)!=="card-config",He=je?he:"",et=je?Ze:"",mt={id:p.v4(),title:ze||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ee==="horizontalBar"?"y":"x"},...Je&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Ee,sql:He,python:et,dataSource:_t,config:Re,connectionId:nt,visualizationMode:ht,dynamicCardPreferences:rt,customCardPreferences:Ve?{url:Ve.url,componentName:Ve.componentName,pluginChartType:Ve.pluginChartType,settings:Ve.settings,type:"component"}:void 0},gt={id:p.v4(),cards:[mt],activeCardId:mt.id};try{await T(N,gt,"end"),j(!0),_(gt.id)}catch(Tt){console.error("Failed to add assistant visual to dashboard:",Tt),Xe.error(Tt instanceof Error?Tt.message:"Failed to prepare semantic metadata for the new visual")}}const te=he=>{he.preventDefault();const ze=Q.trim();if(!ze&&z.length===0)return;const Ne=[];ze&&Ne.push({type:"text",text:ze}),z.forEach(Ee=>{Ee.data&&Ne.push({type:"file",mediaType:Ee.type,filename:Ee.name,url:`data:${Ee.type};base64,${Ee.data}`})}),Y({role:"user",parts:Ne}),ee(""),O("dashboard"),fe({force:!0})};S.useEffect(()=>{var he;e&&((he=C.current)==null||he.focus())},[e]),Pce({assistantType:"dashboard",status:q,isLoading:M,sendMessage:Y});const{hasActiveTools:ce,activeToolText:se}=$ce(G),{visibleMessages:Se,hasMoreMessages:ye,totalMessageCount:Ae,loadMoreMessages:ae,resetMessageWindow:xe}=Lce(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,contentRef:pe,isAtBottom:J,hasNewMessages:ne,newMessageCount:ge,scrollToBottom:fe,handleScroll:me,resetNewMessageCount:be}=Oce(Se,{threshold:40,behavior:"smooth",isStreaming:M});function ke(he){const ze={role:"user",parts:[{type:"text",text:he.title+" "+he.subtitle}]};Y(ze)}function De(he){Y({role:"user",parts:[{type:"text",text:he}]})}function Ge(he){Y({role:"user",parts:[{type:"text",text:he}]}),fe({force:!0})}const Ye=S.useCallback(async()=>{const he=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(he),Xe.success("Conversation copied")}catch(ze){console.error("Failed to copy conversation",ze),Xe.error("Unable to copy conversation")}},[G]),it=(Q==null?void 0:Q.length)===0&&(G==null?void 0:G.filter(he=>he.role==="user").length)===0;function We(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Qe(){return c.jsxs(Es,{children:[c.jsx(Ds,{asChild:!0,children:c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Vf,{className:"size-3.5"})})}),c.jsxs(rs,{align:"end",children:[c.jsx(Ml,{children:"Options"}),c.jsx(Zi,{}),c.jsx(vc,{checked:s,onCheckedChange:i,children:"Token Usage"}),c.jsx(vc,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(vc,{checked:u,onCheckedChange:d,children:"System Message"}),(v||w)&&c.jsxs(c.Fragment,{children:[c.jsx(Zi,{}),c.jsx(Ml,{children:"Dynamic Visuals"}),c.jsx(vc,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),c.jsx(vc,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),c.jsx(vc,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const Ke=c.jsxs("div",{"data-role":"dashboard-assistant",className:p.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:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[We(),H&&c.jsx(p.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:H,children:(U==null?void 0:U.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&Qe(),a&&c.jsx(p.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ye,children:"Copy Conversation"}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?c.jsx(gA,{className:"size-4"}):c.jsx(XC,{className:"size-4"})}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const he=G.filter(ze=>ze.role==="assistant").map(ze=>ze.id).filter(ze=>!!ze);$([]),F("dashboard"),R(),I(he),xe()},children:c.jsx(yA,{className:"size-4"})}),c.jsx(Hc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(p.X,{className:"size-4"})})]})]}),c.jsxs(Za,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:me,children:[c.jsxs("div",{ref:pe,className:"min-w-0 space-y-3 pb-4",children:[ye&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:ae,className:"text-xs",children:["Load ",Math.min(5,Ae-Se.length)," ","more messages (",Ae-Se.length," ","hidden)"]})}),c.jsx(ule,{showTools:a,showSystemMessage:u,messages:Se,onAddToDashboard:ue,onQuickReply:Ge,disableQuickReplies:M}),c.jsx(cle,{status:q,errorMessage:V,activeToolText:M&&ce?se:void 0})]}),c.jsx(p.ScrollBar,{orientation:"horizontal"})]}),e&&!J&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(p.Button,{onClick:()=>{fe({force:!0}),be()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(p.ChevronDown,{className:"h-4 w-4"}),ne&&ge>0&&c.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:ge>9?"9+":ge})]})}),c.jsxs("div",{className:"space-y-3",children:[!U&&it&&c.jsx(dle,{onClick:ke,placeholders:Mpt}),c.jsx("div",{children:it&&U&&c.jsx(Dce,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:De})}),c.jsx(Fce,{assistantType:"dashboard",className:"mb-3"}),c.jsx(lL,{ref:C,setInput:ee,stop:B,input:Q,handleInputChange:re,handleSubmit:he=>{te(he),fe({force:!0})},isLoading:M,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(aL,{incomingSelectedEntities:P,open:m,onOpenChange:g,dataSource:L||ky,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:he=>K()})]});return y&&o?or.createPortal(c.jsx(Wp,{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:c.jsx("div",{className:"flex h-full w-full",children:Ke})}),o):Ke}function Rpt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),o=rte(),s=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),l=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);S.useEffect(()=>{if(!l||u)return;async function d(m){if(Fpt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),Xe.success("Card copied to clipboard"),m.preventDefault()):g&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText(),g=Ppt(m);if(g!=null&&g.id){const b=ete(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await o(a,b),r(b.id),Xe.success("Card pasted from clipboard")}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[o,n,r,a,l,u,t])}function Fpt(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 Ppt(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 Opt(e,t){switch(e.interactionMode){case"drillToDetail":Lpt(e,t);break;case"drillThrough":$pt(e,t);break;case"drillToURL":zpt(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 Lpt(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:o,filterGroups:s}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=s.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=s.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}o==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function $pt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:o,sourceCardId:s}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=o.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function zpt(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 Bpt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:o,contextMode:s,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Vo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(ki,{children:[c.jsx(So,{children:i||"Insight Detail"}),c.jsx(os,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(ate,{filters:r,filterDefinitions:o,contextMode:s}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(Ste,{insightId:n,filters:r,contextMode:s}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Vpt(){const e=p.useInteractionStore(C=>C.interactionStates),t=p.useInteractionStore(C=>C.setInteractionState),n=p.useInteractionStore(C=>C.clearLastInteractionEvent),r=p.useInteractionStore(C=>C.replaceCardWithInsight),o=p.useInteractionStore(C=>C.setPendingDrillThrough),s=p.useInteractionStore(C=>C.pendingDrillThrough),i=p.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=p.useDashboardActions(),{selectDashboard:u}=zf(),d=p.useDashboardStore(C=>C.dashboard),f=p.useDashboardStore(C=>C.filterValues),{data:h,isLoading:m}=lq((s==null?void 0:s.targetDashboardId)||"",{enabled:!!(s!=null&&s.targetDashboardId)}),[g,b]=S.useState({open:!1,insightId:""}),x=Cte(g.insightId,{enabled:g.open&&!!g.insightId}),y=S.useRef(new Set),v=S.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:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:o,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j})=>{const T={filters:C},E={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[T]},D={...p.createInitialInteractionState(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j};t(p.DRILL_CONTEXT_CARD_ID,D)}}),[a,r,f,l,d,o,t]);S.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{Opt(k,v)}catch(j){console.error("Error executing interaction event:",j)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,v]),S.useEffect(()=>{if(!(!s||!h||m))try{u(h),l(s.targetDashboardId,s.sourceDashboardId,s.sourceDashboardTitle,s.filters,s.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[s,h,m,u,l,i]);const w=()=>{b({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(Bpt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),s&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.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:[c.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),c.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Hpt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,o=Upt(t.value);return r==="="?`${n} = ${o}`:`${n} ${r} ${o}`}).join(", ")}function Upt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function qpt(e){return e?`Back to ${e}`:"Back"}function Wpt(){var y,v,w,C,N;const e=p.useInteractionStore(k=>k.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(k=>k.actions.goBackFromDrill),n=p.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=zf(),[o,s]=S.useState({x:16,y:16}),[i,a]=S.useState(!1),l=S.useRef({x:0,y:0});S.useEffect(()=>{if(!i)return;const k=j=>{s({x:j.clientX-l.current.x,y:j.clientY-l.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=(v=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:v.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 m=()=>{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),l.current={x:k.clientX-o.x,y:k.clientY-o.y})};Hpt(f);const x=qpt(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${o.x}px, ${o.y}px)`,transition:i?"none":void 0},children:c.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:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const j=k.field.label||k.field.name,T=String(k.value);return c.jsxs(Ar,{variant:"secondary",className:"pointer-events-none text-xs",children:[j," = ",T]},_)})})]}),c.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(zy,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Ypt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Gpt({filter:e,isEditing:t=!1,disabled:n=!1}){const{attributes:r,listeners:o,setNodeRef:s,transform:i,transition:a,isDragging:l}=Jp({id:`filter:${e.id}`,disabled:n||!t}),u={transform:Xs.Translate.toString(i),transition:a,opacity:l?.5:1,zIndex:l?10:void 0};return c.jsx("div",{ref:s,style:u,...r,children:c.jsx(DP,{filter:e,isEditing:t,dragListeners:t?o:void 0})})}const D7="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Kpt=[];function zce({open:e,onOpenChange:t}){var $,q,B;const[n,r]=S.useState(!1),[o,s]=S.useState(!1),[i,a]=S.useState({sheetSelection:"current",protectPdf:!1,password:""}),l=p.useDashboardStore(V=>{var R;return(R=V.dashboard)==null?void 0:R.sheets}),u=p.useDashboardStore(V=>V.dashboard),d=p.useDashboardStore(V=>V.dashboardInputValues),f=p.useDashboardStore(V=>V.filterValues),h=p.useDashboardStore(V=>V.controlValues),m=p.useDashboardStore(V=>V.inlineFilterValuesMap),g=p.useDashboardStore(V=>V.cardControlValuesMap),b=p.useDashboardStore(V=>V.selectedSheetId),x=p.useDashboardStore(V=>V.selectedSheetId?V.documentInputRuntimeBySheetId[V.selectedSheetId]:void 0),y=p.useDashboardStore(V=>V.isDownloadingPdf),{authToken:v,tokenProps:w}=xt(),C=l==null?void 0:l.find(V=>V.id===b),N=S.useMemo(()=>p.getDashboardExportSheets(l),[l]),k=p.isDocumentSheet(C),_=k&&C?C.document:void 0,j=S.useMemo(()=>k&&C?K0(u,C.id):[],[C,k,u]),T=j.length>0,E=S.useMemo(()=>k&&C?aie(u,C.id):!1,[C,k,u]),D=S.useMemo(()=>T?j.map(Z0):(_==null?void 0:_.inputs)||Kpt,[_,j,T]),I=((q=($=w==null?void 0:w.params)==null?void 0:$.calendarContext)==null?void 0:q.tz)||((B=w==null?void 0:w.params)==null?void 0:B.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=S.useMemo(()=>sre(D),[D]),O=S.useMemo(()=>rre(D,I),[D,I]),A=S.useMemo(()=>ore(D),[D]),z=x?x.filterValuesByInputId:O,L=x?x.controlValuesByInputId:A,U=S.useMemo(()=>k?E&&C&&_?FY({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(V=>V.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:I}):lre(D,z,L,F,F):[],[_,D,C,k,u,g,h,f,m,d,L,z,F,I,E]),H=!!C,P=N.length>0,K=((l==null?void 0:l.length)||0)>1||k,Y=i.sheetSelection==="current"&&(!H||k&&U.length>0)||i.sheetSelection==="all"&&!P;S.useEffect(()=>{e&&i.sheetSelection==="all"&&!P&&a(V=>({...V,sheetSelection:"current"}))},[P,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){Xe.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){Xe.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!H){Xe.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!P){Xe.error("No dashboard sheets are available to export");return}s(!0);const V=i.sheetSelection==="current"&&k,R=V?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=Xe.loading(R);try{if(V){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){Xe.dismiss(W),Xe.error(`Set ${U.join(", ")} before exporting`);return}const Q=new Date().toISOString(),ee=E?OY({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:Q,timezone:I}).snapshot:void 0;await DR(w.apiServiceUrl,v,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:I,password:i.protectPdf?i.password:void 0,inputSnapshot:ee,...ee?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:z,controlValuesByInputId:L,generatedAt:Q}}})}else{const Q=dX();await UY(w.apiServiceUrl,v,i.protectPdf?i.password:void 0,i.sheetSelection,Q)}Xe.dismiss(W);const X=V?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!";Xe.success(X,{duration:2e3}),M()}catch(X){Xe.dismiss(W),Xe.error("Failed to download PDF",{description:AN(X,"Please try again or contact support."),descriptionClassName:MN,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{s(!1)}}return c.jsx(as,{open:e,onOpenChange:V=>{if(!V){M();return}t(!0)},children:c.jsxs(Vo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[c.jsxs(ki,{children:[c.jsx(So,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),c.jsx(os,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),c.jsxs("div",{className:"space-y-4 py-1",children:[K&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:D7,children:"Export scope"}),c.jsxs(Qi,{value:i.sheetSelection,onValueChange:V=>a({...i,sheetSelection:V}),className:"gap-1.5",children:[c.jsxs(p.Label,{htmlFor:"scope-current",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!H&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(fo,{value:"current",id:"scope-current",disabled:!H}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),c.jsxs(p.Label,{htmlFor:"scope-all",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!P&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(fo,{value:"all",id:"scope-all",disabled:!P}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&c.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.'})]}),c.jsx(p.Separator,{className:"bg-border/60"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[c.jsx(Cn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:V=>{a({...i,protectPdf:V,password:V?i.password:""}),V||r(!1)}}),c.jsx(ZC,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&c.jsxs("div",{className:"ml-6 space-y-1.5",children:[c.jsx(p.Label,{htmlFor:"pdf-password",className:D7,children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:V=>a({...i,password:V.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:V=>{V.key==="Enter"&&i.password&&G()}}),c.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?c.jsx(GC,{className:"h-3.5 w-3.5"}):c.jsx(By,{className:"h-3.5 w-3.5"})})]}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),c.jsxs(ec,{children:[c.jsx(p.Button,{variant:"outline",size:"xs",onClick:M,disabled:o,children:"Cancel"}),c.jsx(p.Button,{size:"xs",onClick:G,disabled:o||y||Y,children:o?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):c.jsxs(c.Fragment,{children:[c.jsx(Xl,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function Bce({iconClassName:e,open:t,onOpenChange:n}){const[r,o]=S.useState(!1),s=t!==void 0,i=s?t:r,a=u=>{s||o(u),n==null||n(u)},l=p.useDashboardStore(u=>u.isDownloadingPdf);return c.jsxs(c.Fragment,{children:[s?null:c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:l,onClick:()=>a(!0),children:c.jsx(Xl,{className:p.cn("size-4",e)})}),c.jsx(zce,{open:i,onOpenChange:a})]})}function T7(e,t,n){const r=new Set(t),o=[...n];return e.map(s=>r.has(s.id)?o.shift()??s.id:s.id)}function Zpt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:o,listeners:s,setNodeRef:i,transform:a,transition:l,isDragging:u}=Jp({id:`control:${e.id}`,disabled:!n}),d={transform:Xs.Translate.toString(a),transition:l,opacity:u?.5:1,zIndex:u?10:void 0};return c.jsx("div",{ref:i,style:d,...o,children:c.jsx(Sre,{control:e,value:t,isEditing:n,dragListeners:n?s:void 0,onChange:r})})}const Xpt=[];function Qpt(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function I7(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function Jpt(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 I7(t,n);const o=e.filter(a=>r.has(a)),s=new Set(o),i=I7(t,n).filter(a=>!s.has(a));return[...o,...i]}function egt(e,t){return"toolbar"}function tgt(){var U;const e=nc("interactive"),t=p.useDashboardStore(H=>H.selectedSheetId),n=p.useDashboardStore(H=>H.dashboard.filters),r=p.useDashboardStore(H=>H.dashboard.filterLayout),o=p.useDashboardStore(H=>H.isDashboardEditing),s=p.useDashboardStore(H=>H.controlValues),i=p.useDashboardStore(H=>H.filterValues);p.useDashboardStore(H=>H.filteringCards);const a=p.useDashboardStore(H=>H.inlineFilterValuesMap),l=p.useInteractionStore(H=>H.clearAllClickFilters),u=p.useInteractionStore(H=>Object.entries(H.interactionStates).reduce((P,[K,Y])=>{var M;return K===p.DRILL_CONTEXT_CARD_ID?P:P+(((M=Y.appliedClickFilters)==null?void 0:M.length)??0)},0)),d=p.useDashboardStore(H=>H.actions.removeCardInlineFilterValue),{reorderFilters:f,reorderDashboardControls:h,setControlValue:m,setFilterLayout:g,setFilterValues:b,setFilteringCards:x}=p.useDashboardActions(),y=Rk(np(Xp,{activationConstraint:{distance:5}})),v=(U=sc(n,t))==null?void 0:U.filter(H=>!H.hide&&H.location!=="frame"),w=(v==null?void 0:v.filter(H=>egt()==="toolbar"))||Xpt,C=p.useDashboardStore(H=>H.dashboard),N=$Ve(C),k=N.filter(H=>!H.hidden&&Xx(H)==="toolbar"),_=N.filter(H=>!H.hidden&&Xx(H)==="advanced"),j=Jpt(r==null?void 0:r.toolbarItemOrder,w,k),T=new Map(w.map(H=>[`filter:${H.id}`,H])),E=new Map(k.map(H=>[`control:${H.id}`,H]));function D(H){const{active:P,over:K}=H;if(!K||P.id===K.id)return;const Y=String(P.id),M=String(K.id),G=j.findIndex(X=>X===Y),$=j.findIndex(X=>X===M);if(G===-1||$===-1)return;const q=Qp(j,G,$);g({toolbarItemOrder:q});const B=j.filter(X=>X.startsWith("filter:")).map(X=>X.replace("filter:","")),V=q.filter(X=>X.startsWith("filter:")).map(X=>X.replace("filter:","")),R=j.filter(X=>X.startsWith("control:")).map(X=>X.replace("control:","")),W=q.filter(X=>X.startsWith("control:")).map(X=>X.replace("control:",""));f(T7(n||[],B,V)),h(T7(C.controls||[],R,W))}const I=(r==null?void 0:r.toolbarWrap)??!1,F=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter(H=>Qpt(H)).length)??0,A=a?Object.values(a).reduce((H,P)=>H+((P==null?void 0:P.length)??0),0):0,z=O+A+u,L=()=>{b([]),x([]),l(),a&&Object.entries(a).forEach(([H,P])=>{P==null||P.forEach(K=>{d(H,K.filterId)})})};return!w.length&&!k.length&&!_.length&&!F?null:c.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:c.jsx(P0,{sensors:y,collisionDetection:A0,onDragEnd:D,children:c.jsxs("div",{className:p.cn("flex items-center",I?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[c.jsx(O0,{items:j,strategy:oO,children:c.jsx(Y2,{className:"gap-3 pr-0",wrap:I,children:j.map(H=>{const P=T.get(H);if(P)return c.jsx(Gpt,{filter:P,isEditing:o},H);const K=E.get(H);return K?c.jsx(Zpt,{control:K,value:s==null?void 0:s[K.id],isEditing:o,onChange:Y=>m(K.id,Y)},H):null})})}),_.length>0&&c.jsx(bte,{title:"",controls:_,values:s,onChange:(H,P)=>m(H.id,P),immediatePlacement:"toolbar",advancedLabel:"More controls"}),z>0&&c.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:[c.jsx(p.X,{className:"h-3 w-3"}),"Clear all",c.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:z})]}),F&&c.jsx("div",{className:p.cn(z>0?"ml-1.5":"ml-auto"),children:c.jsx(Bce,{})})]})})})}function Vce(){var ne,ge;const{showAssistant:e,tokenProps:t,renderMode:n}=xt(),r=Ypt((ne=t.config)==null?void 0:ne.showDashboardAssistant,e),{preferences:o,isConsoleMode:s}=mp(),i=(ge=o==null?void 0:o.cardDisplay)==null?void 0:ge.mode,a=Zf(i),l=yY({displayMode:i,renderMode:n}),u=S.useRef(null),d=S.useRef(null),[f,h]=S.useState(!1),{handleDragStart:m,isDraggingRef:g,getStyle:b,getPositionClasses:x}=det({initialPosition:"bottom-right"}),y=Yd(fe=>fe.setFullscreen),v=Yd(fe=>fe.setPanelOpen),w=Yd(fe=>fe.setContainer),C=uW("dashboard"),N=dW(),k=fW("dashboard"),_=C.isOpen,j=N==="dashboard",T=p.useDashboardStore(fe=>fe.isVisualEditing),E=p.useDashboardStore(fe=>fe.themeStyle),D=qa(),I=p.useDashboardStore(fe=>{var me;return(me=fe.dashboard)==null?void 0:me.sheets}),F=p.useDashboardStore(fe=>fe.showFilters),O=p.useDashboardStore(fe=>fe.isDashboardEditing),A=p.useDashboardStore(fe=>fe.selectedSheetId),z=I==null?void 0:I.find(fe=>fe.id===A),L=p.useDashboardStore(fe=>{var me,be,ke;return(ke=(be=(me=fe.dashboard)==null?void 0:me.sheets)==null?void 0:be.find(De=>De.id===fe.selectedSheetId))==null?void 0:ke.kind}),U=p.useDashboardStore(fe=>{var me,be;return((be=(me=fe.dashboard)==null?void 0:me.summary)==null?void 0:be.position)||"top"}),H=L==="document",P=p.useDashboardStore(fe=>{var me;return(me=fe.dashboard)==null?void 0:me.id}),K=p.useDashboardStore(fe=>fe.isDashboardPanelOpen),Y=p.useDashboardStore(fe=>fe.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:$}=pH(P),[q,B]=S.useState(null);sN(Or.DASHBOARD);const{setSelectedSheetId:V,setSheetTitle:R,addSheet:W,setSheets:X}=p.useDashboardActions();Rpt(d);const{setActiveAssistantType:Q}=p.useAIActions();S.useEffect(()=>{if(P){const fe=M();B(fe)}},[P,M]),S.useEffect(()=>{_?Q("dashboard"):N==="dashboard"&&y(null)},[_,Q,N,y]),S.useEffect(()=>{var fe;_||(fe=u.current)==null||fe.resize(0)},[_]);function ee(fe){var me,be;fe?((me=u.current)==null||me.resize(40),v("dashboard",!0),y("dashboard"),Q("dashboard")):(v("dashboard",!1),y(null),(be=u.current)==null||be.resize(0),Q(null))}function re(fe="dashboard"){const me={id:p.v4(),title:fe==="document"?"New Document":"New Sheet",...fe==="document"?{kind:fe,document:p.createDefaultDocumentDefinition()}:{}};W(me),V(me.id)}function ue(fe,me){if(!P)return;q===fe?($(),B(null),Xe.success("Default sheet cleared")):(G(fe),B(fe),Xe.success(`"${me}" set as default sheet`))}function te(fe){var me;fe<1?(v("dashboard",!1),y(null),Q(null),(me=u.current)==null||me.resize(0)):(_||v("dashboard",!0),Q("dashboard"))}function ce(){return(E==null?void 0:E.canvasTheme)==="muted"||!(E!=null&&E.canvasTheme)?"hsl(var(--semaphor-muted))":(E==null?void 0:E.canvasTheme)==="clear"?"":E==null?void 0:E.canvasTheme}const se=(fe,me)=>{fe.dataTransfer.setData("tabIndex",me.toString())},Se=fe=>{fe.preventDefault()},ye=(fe,me)=>{const be=fe.dataTransfer.getData("tabIndex");if(be===me.toString())return;const ke=Array.from(I||[]),[De]=ke.splice(parseInt(be),1);ke.splice(me,0,De),X(ke)},Ae=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ae=r===!0&&!a&&!_&&!T&&!F;function xe(){if(I&&I.length>1||O)return c.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[s&&Ae&&!K&&c.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{Y(!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:c.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:c.jsx(qH,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),c.jsxs("div",{className:"relative min-w-0 flex-1",children:[c.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"}),c.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"}),c.jsxs(p.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:[I==null?void 0:I.map((fe,me)=>{const be=A===fe.id,ke=q===fe.id;return c.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:De=>se(De,me),onDragOver:Se,onDrop:De=>ye(De,me),onClick:()=>V(fe.id),className:p.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:fe.id,children:[fe.kind==="document"&&c.jsx(Ys,{className:"h-3 w-3 text-muted-foreground"}),c.jsx(HS,{enabled:O&&be,text:fe.title,onSave:De=>R(fe.id,De),children:fe.title},fe.id),c.jsx("span",{role:"button",tabIndex:0,"aria-label":ke?"Clear default sheet":"Set as default sheet",title:ke?"Clear default sheet":"Set as default sheet",onClick:De=>{De.stopPropagation(),ue(fe.id,fe.title||"Sheet")},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),De.stopPropagation(),ue(fe.id,fe.title||"Sheet"))},className:p.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",be||ke?"opacity-100":"opacity-0 group-hover:opacity-100"),children:c.jsx(vA,{className:p.cn("h-3 w-3 transition-colors",ke?"fill-current text-amber-500":"text-muted-foreground")})}),O&&be&&I.length>1&&c.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:De=>{De.stopPropagation(),h(!0)},onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),De.stopPropagation(),h(!0))},children:c.jsx(p.X,{className:"h-3 w-3"})})]},fe.id)}),O&&c.jsxs(Es,{children:[c.jsx(Ds,{asChild:!0,children:c.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:[c.jsx(pr,{className:"h-3 w-3"}),"Sheet"]})}),c.jsxs(rs,{align:"start",className:"w-48",children:[c.jsxs(Sn,{onSelect:()=>re("dashboard"),children:[c.jsx(Im,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),c.jsxs(Sn,{onSelect:()=>re("document"),children:[c.jsx(Ys,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function ve(){return c.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:I==null?void 0:I.map(fe=>c.jsx(p.TabsContent,{style:{backgroundColor:ce(),...D.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:fe.id,children:c.jsx(IV,{sheet:fe})},fe.id))})}function pe(){return c.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",E==null?void 0:E.dashboardTabsContainer),onValueChange:fe=>{V(fe)},value:A||void 0,children:[xe(),U==="top"&&!H&&c.jsx(E2,{}),A&&!H&&c.jsx(tgt,{}),H?c.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:ve()}):c.jsx(Za,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:ve()}),U==="bottom"&&!H&&c.jsx(E2,{}),c.jsx(fet,{open:f,setOpen:h})]})}const J=S.useCallback(fe=>{w("dashboard",fe)},[w]);return I?l&&A&&!H?c.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):l&&H&&z?c.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:c.jsx(IV,{sheet:z})}):c.jsxs(c.Fragment,{children:[c.jsx(Vpt,{}),c.jsx(Wpt,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(Iie,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",j&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(_M,{children:pe()}),r===!0&&c.jsxs(c.Fragment,{children:[c.jsx(uet,{open:_,onTabClick:ee,withHandle:!0,disabled:!_}),c.jsx(_M,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:te,defaultSize:_?40:0,ref:u,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(Apt,{open:_,setOpen:ee,isFullscreen:j,onFullscreenChange:fe=>y(fe?"dashboard":null),fullscreenContainer:k})})})]})]}),c.jsx("div",{ref:J,className:p.cn("absolute inset-0",!j&&"pointer-events-none")}),ae&&c.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:c.jsx(p.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||ee(!0)},onMouseDown:m,onTouchStart:m,title:"Open Assistant (drag to move)",children:c.jsx(Tfe,{className:"h-5 w-5"})})})]})]}):null}const Hce=S.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:o,children:s,className:i,style:a,...l},u)=>{const d=S.useId(),f=S.useMemo(()=>ngt(d),[d]),{theme:h}=oA(),m=rgt(h),g=S.useMemo(()=>o??Zl.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,o,n]),b=S.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=S.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return c.jsx(p.AppearanceContext.Provider,{value:x,children:c.jsx(Wp,{...l,ref:u,className:i,style:a,children:s})})});Hce.displayName="AppearanceProvider";function ngt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function rgt(e){const t=z1(e),[n,r]=S.useState(()=>ogt());return S.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const o=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!o)return;const s=()=>{r(o.matches?"dark":"light")};return s(),typeof o.addEventListener=="function"?(o.addEventListener("change",s),()=>o.removeEventListener("change",s)):((a=o.addListener)==null||a.call(o,s),()=>{var l;return(l=o.removeListener)==null?void 0:l.call(o,s)})},[t]),t==="system"?n:t}function ogt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Uce=S.createContext({openBrandStudioPreview:()=>{}}),sgt=Uce.Provider;function igt(){return S.useContext(Uce)}function agt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const o=z1(t),[s,i]=S.useState(()=>lgt(n)||o),a=S.useCallback(u=>{const d=z1(u);cgt(n,d),i(d)},[n]),l=S.useMemo(()=>({theme:s,setTheme:a}),[s,a]);return c.jsx(Y7.Provider,{...r,value:l,children:e})}function lgt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=z1(t,"system");return n===t?n:null}catch{return null}}function cgt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const ugt=S.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function cL({appearance:e,children:t}){var D,I;const{authToken:n,id:r,tokenProps:o}=xt(),s=Ly(),i=(D=s.data)==null?void 0:D.organizationAppearance,a=(I=o.config)==null?void 0:I.appearance,[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(null),[g,b]=S.useState(null),[x,y]=S.useState(null),v=`${o.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=Dn({queryKey:rq({resourceType:Or.DASHBOARD,apiServiceUrl:o.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${o.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!s.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});S.useEffect(()=>{i!==void 0&&y({scopeKey:v,appearance:i})},[i,v]),S.useEffect(()=>{w.data!==void 0&&y({scopeKey:v,appearance:w.data})},[w.data,v]);const C=(x==null?void 0:x.scopeKey)===v?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=S.useMemo(()=>Zl.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=S.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),j=S.useCallback(()=>{u(!1)},[]);S.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const T=S.useMemo(()=>({openBrandStudioPreview:_}),[_]),E=g??h??e;return c.jsx(agt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(sgt,{value:T,children:c.jsx(Hce,{organizationAppearance:N,tokenAppearance:a,reactAppearance:E,style:{height:"100%",width:"100%"},children:c.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,l&&c.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:c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:c.jsx(ugt,{appearance:d,onDraftChange:b,onSave:F=>{m(F),b(F),f(F)},onCancel:j})})})]})})})})}function qce({children:e,preferences:t}){const{currentUser:n}=Ni(),r=S.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return c.jsx(eq.Provider,{value:r,children:c.jsx(Ek,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function dgt(e=2e3,t=500){const n=Bde(),[r,o]=S.useState(!1),[s,i]=S.useState(!1),a=S.useRef(null);return S.useEffect(()=>{const l=setTimeout(()=>o(!0),e);return()=>clearTimeout(l)},[e]),S.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]),s}function uL({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const o=dgt(e,t);return S.useEffect(()=>(o&&(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()}}),[o,n,r]),c.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:o?"ready":""})}function Wce(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(ea,{FallbackComponent:_k,children:c.jsxs(uA,{dashboardProps:e,children:[c.jsx(uL,{componentType:"dashboard",componentId:e.id}),c.jsx(cL,{appearance:e.appearance,children:c.jsx(qce,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(zA,{...e,type:"dashboard",children:c.jsx(Vce,{})})})})})]})})}function fgt(e=[]){const t=S.useRef(null),n=S.useRef(null),r=S.useRef(null),[o,s]=S.useState(),i=S.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,l=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-l-u-8,h=Math.max(f,0);s(x=>x===h?x:h)},[]);return S.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>i());return l.observe(a),i(),()=>l.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:o,updateAvailableWidth:i}}function hgt({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=mp(),r=Zf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),o=p.useDashboardStore(b=>b.filterValues),s=o==null?void 0:o.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=fgt([t,s,r]);return S.useEffect(()=>{m()},[e.title,m]),c.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[c.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:c.jsx(p.Label,{className:"my-1 block w-full text-sm",children:c.jsx(yi,{value:e.title||e.column,onSave:b=>l({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&c.jsx(EP,{filter:e,isEditing:t}),t&&c.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:c.jsx(p.X,{className:"size-3.5"})})]})]}),c.jsx("div",{className:"hidden",ref:f})]})}function mgt(){const e=p.useDashboardStore(r=>r.dashboard.filters),t=p.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:p.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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(hgt,{filter:r}),c.jsx(vk,{filter:r})]},r.id))}):null}function pgt(){var i;const e=p.useDashboardStore(a=>a.dashboard),t=p.useDashboardStore(a=>a.selectedSheetId),n=p.useDashboardStore(a=>a.isVisualEditing),r=p.useDashboardStore(a=>a.isDashboardEditing),o=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),s=p.isDocumentSheet(o);return c.jsx("div",{role:"dashboard-plus-main",className:p.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:c.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!s&&c.jsx(mgt,{}),c.jsx(Vce,{})]})})}const ggt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DH8gdpOc.js"))),bgt=S.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-Cc3xpTNQ.js"))),xgt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-eGBWfSN1.js"))),ygt=S.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DR7Ku6sa.js")).then(e=>({default:e.ResourceManagementPanel})));function vgt({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(u=>u.isDashboardPanelOpen),o=p.useDashboardStore(u=>u.isVisualEditing),s=p.useDashboardStore(u=>u.showDashboardJSON),i=p.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:l}=n;return c.jsx(ea,{FallbackComponent:_k,children:c.jsxs(uA,{dashboardProps:n,children:[c.jsx(uL,{componentType:"surfboard",componentId:n.id}),c.jsxs(cL,{appearance:a,children:[c.jsx(Fme,{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"}}}),c.jsxs(qce,{preferences:l,children:[s&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(xgt,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(ggt,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(ygt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(zA,{...n,type:"dashboard",children:[o&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(bgt,{})}),c.jsx(pgt,{})]})})]})]})]})]})]})})}var wgt=Object.defineProperty,Sgt=(e,t,n)=>t in e?wgt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ww=(e,t,n)=>Sgt(e,typeof t!="symbol"?t+"":t,n);const Cgt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Ngt={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}},kgt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function _gt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const jgt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const o=Yce(t);if(typeof n<"u"&&o in n.container)return n.container[o]})();return typeof r=="function"?r.bind(n):void 0}},Egt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Dgt={stringify:e=>e,parse:e=>e},vT={string:Dgt,number:Egt,boolean:Cgt,function:Ngt,method:jgt,json:kgt},eb=Symbol.for("r2wc.render"),Yw=Symbol.for("r2wc.connected"),od=Symbol.for("r2wc.context"),Ps=Symbol.for("r2wc.props");function Tgt(e,t,n){var r,o,s;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),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const g=_gt(m);d[m]=g,f[g]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Ww(this,s,!0),Ww(this,o),Ww(this,r,{}),Ww(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ps].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=l[g],v=y?vT[y]:null;if(y==="method"){const w=Yce(b);Object.defineProperty(this[Ps].container,w,{enumerable:!0,configurable:!0,get(){return this[Ps][w]},set(C){this[Ps][w]=C,this[eb]()}}),this[Ps][g]=v.parse(x,b,this)}v!=null&&v.parse&&x&&(this[Ps][g]=v.parse(x,b,this))}for(const g of a)this[Ps][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[Yw]=!0,this[eb]()}disconnectedCallback(){this[Yw]=!1,this[od]&&n.unmount(this[od]),delete this[od]}attributeChangedCallback(g,b,x){const y=f[g],v=l[y],w=v?vT[v]:null;y in l&&w!=null&&w.parse&&x&&(this[Ps][y]=w.parse(x,g,this),this[eb]())}[(s=Yw,o=od,r=Ps,eb)](){this[Yw]&&(this[od]?n.update(this[od],this[Ps]):this[od]=n.mount(this.container,e,this[Ps]))}}for(const m of i){const g=d[m],b=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Ps][m]},set(x){this[Ps][m]=x;const y=b?vT[b]:null;if(y!=null&&y.stringify){const v=y.stringify(x,g,this);this.getAttribute(g)!==v&&this.setAttribute(g,v)}else this[eb]()}})}return h}function Igt(e,t,n){const r=Eue.createRoot(e),o=S.createElement(t,n);return r.render(o),{root:r,ReactComponent:t}}function Mgt({root:e,ReactComponent:t},n){const r=S.createElement(t,n);e.render(r)}function Agt({root:e}){e.unmount()}function Rgt(e,t={}){return Tgt(e,t,{mount:Igt,update:Mgt,unmount:Agt})}const Fgt={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"},Pgt=Rgt(Wce,{props:Fgt}),Ogt=S.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(EO,{context:t})," "]})}),Gce=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),Lgt=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),$gt=Array.from(Gce).join(", "),zgt=3,Bgt="Self-heal",Vgt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function Hgt({card:e}){var H,P,K,Y,M;const[t,n]=S.useState({}),{authToken:r}=xt(),o=p.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:s}=p.useAppearance(),i=S.useMemo(()=>C0(s),[s]),a=p.useEditorStore(G=>G.frame),l=p.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=p.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=p.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:m}=eh(((H=f.customCardPreferences)==null?void 0:H.url)||""),g=(P=m==null?void 0:m.visuals)==null?void 0:P.find(G=>{var $;return G.name===(($=f.customCardPreferences)==null?void 0:$.componentName)}),b=N0(f,g)??"single",x=S.useMemo(()=>AP({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=S.useMemo(()=>{const G=x.findIndex($=>($==null?void 0:$.id)===e.id);return G<0?-1:Yx(e,G)},[x,e]),v=S.useMemo(()=>b!=="multiple"||y<0?e.type:om(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=S.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:v!==e.type?{...e,type:v}:e,[e,v,b]),{data:C}=TN(w),N=p.useInteractionStore(G=>G.interactionStates),k=p.useDashboardStore(G=>{var $;return($=G.dashboard)==null?void 0:$.id}),_=p.useDashboardStore(G=>G.dashboard.filters),j=p.useDashboardStore(G=>G.filterValues),T=p.useDashboardStore(G=>G.selectedSheetId),E=S.useMemo(()=>TP({card:e,sheetId:T||"",inlineFilterValues:l,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,T,l,u,d]),{cardFilters:D,cardFilterValues:I}=S.useMemo(()=>Xy({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:j,selectedSheetId:T}),[e,N,k,_,j,T]),F=S.useCallback((G,$)=>{const q=FP($);n(B=>({...B,[G]:q}))},[]),O=(K=f.customCardPreferences)==null?void 0:K.componentName,A=O?h(O):null,z=BS((Y=f.customCardPreferences)==null?void 0:Y.settings,f),L=S.useMemo(()=>MP(x),[x]),U=S.useMemo(()=>L.map((G,$)=>om(G,$,g==null?void 0:g.slots)),[L,g==null?void 0:g.slots]);return O?c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(S.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[A&&b==="single"&&c.jsx(A,{editing:!0,params:o,theme:i,settings:z,cardMetadata:Mee({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:D,filterValues:[...I||[],...l||[]],inlineFilters:E}),A&&b==="multiple"&&c.jsxs(c.Fragment,{children:[x.map((G,$)=>{if(!G)return null;const q=Yx(G,$),B=om(G,q,g==null?void 0:g.slots);return c.jsx(rP,{onDataChange:F,card:G,effectiveCardType:B},`${G.id}-${q}`)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(A,{editing:!0,onDataChange:F,...PP({configCard:f,slotOrderedCards:L,slotTypes:U,multiInputData:t,params:o,theme:i,chartSettings:z,filters:D,filterValues:[...I||[],...l||[]],inlineFilters:E})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Ugt=S.memo(Hgt,(e,t)=>{var n,r,o,s,i,a,l,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)&&((o=e.card.customCardPreferences)==null?void 0:o.slotSettings)===((s=t.card.customCardPreferences)==null?void 0:s.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((l=e.card.customCardPreferences)==null?void 0:l.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),qgt=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(o=>o.type===n&&o.id===r),toggleStar:n=>{e(r=>{const o=r.starredCharts.findIndex(s=>s.type===n.type&&s.id===n.id);return o>=0?{starredCharts:r.starredCharts.filter((s,i)=>i!==o)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(o=>o.type===n&&o.id===r)}),{name:"semaphor-starred-charts"}));var Kce=["PageUp","PageDown"],Zce=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xce={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},fg="Slider",[JM,Wgt,Ygt]=p.createCollection(fg),[Qce]=p.createContextScope(fg,[Ygt]),[Ggt,F_]=Qce(fg),Jce=Z.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=Z.useRef(new Set),y=Z.useRef(0),w=i==="horizontal"?Kgt:Zgt,[C=[],N]=p.useControllableState({prop:d,defaultProp:u,onChange:D=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(D)}}),k=Z.useRef(C);function _(D){const I=tbt(C,D);E(D,I)}function j(D){E(D,y.current)}function T(){const D=k.current[y.current];C[y.current]!==D&&h(C)}function E(D,I,{commit:F}={commit:!1}){const O=sbt(s),A=ibt(Math.round((D-r)/s)*s+r,O),z=p.clamp(A,[r,o]);N((L=[])=>{const U=Jgt(L,z,I);if(obt(U,l*s)){y.current=U.indexOf(z);const H=String(U)!==String(L);return H&&F&&h(U),H?U:L}else return L})}return c.jsx(Ggt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:c.jsx(JM.Provider,{scope:e.__scopeSlider,children:c.jsx(JM.Slot,{scope:e.__scopeSlider,children:c.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:o,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:j,onSlideEnd:a?void 0:T,onHomeKeyDown:()=>!a&&E(r,0,{commit:!0}),onEndKeyDown:()=>!a&&E(o,C.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:I})=>{if(!a){const A=Kce.includes(D.key)||D.shiftKey&&Zce.includes(D.key)?10:1,z=y.current,L=C[z],U=s*A*I;E(L+U,z,{commit:!0})}}})})})})});Jce.displayName=fg;var[eue,tue]=Qce(fg,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Kgt=Z.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=Z.useState(null),m=p.useComposedRefs(t,w=>h(w)),g=Z.useRef(void 0),b=p.useDirection(o),x=b==="ltr",y=x&&!s||!x&&s;function v(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=dL(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return c.jsx(eue,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:c.jsx(nue,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=v(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=v(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:w=>{const N=Xce[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),Zgt=Z.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=Z.useRef(null),f=p.useComposedRefs(t,d),h=Z.useRef(void 0),m=!o;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=dL(y,m?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return c.jsx(eue,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(nue,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);s==null||s(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xce[m?"from-bottom":"from-top"].includes(b.key);l==null||l({event:b,direction:y?-1:1})}})})}),nue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=F_(fg,n);return c.jsx(p.Primitive.span,{...u,ref:t,onKeyDown:p.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kce.concat(Zce).includes(f.key)&&(l(f),f.preventDefault())}),onPointerDown:p.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:p.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),rue="SliderTrack",oue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=F_(rue,n);return c.jsx(p.Primitive.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});oue.displayName=rue;var eA="SliderRange",sue=Z.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=F_(eA,n),s=tue(eA,n),i=Z.useRef(null),a=p.useComposedRefs(t,i),l=o.values.length,u=o.values.map(h=>lue(h,o.min,o.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(p.Primitive.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});sue.displayName=eA;var tA="SliderThumb",iue=Z.forwardRef((e,t)=>{const n=Wgt(e.__scopeSlider),[r,o]=Z.useState(null),s=p.useComposedRefs(t,a=>o(a)),i=Z.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(Xgt,{...e,ref:s,index:i})}),Xgt=Z.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=F_(tA,n),a=tue(tA,n),[l,u]=Z.useState(null),d=p.useComposedRefs(t,v=>u(v)),f=l?i.form||!!l.closest("form"):!0,h=p.useSize(l),m=i.values[r],g=m===void 0?0:lue(m,i.min,i.max),b=ebt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?nbt(x,g,a.direction):0;return Z.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),c.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[c.jsx(JM.ItemSlot,{scope:e.__scopeSlider,children:c.jsx(p.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(aue,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});iue.displayName=tA;var Qgt="RadioBubbleInput",aue=Z.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=Z.useRef(null),s=p.useComposedRefs(o,r),i=p.usePrevious(t);return Z.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});aue.displayName=Qgt;function Jgt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function lue(e,t,n){const s=100/(n-t)*(e-t);return p.clamp(s,[0,100])}function ebt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function tbt(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function nbt(e,t,n){const r=e/2,s=dL([0,50],[0,r]);return(r-s(t)*n)*n}function rbt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function obt(e,t){if(t>0){const n=rbt(e);return Math.min(...n)>=t}return!0}function dL(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 sbt(e){return(String(e).split(".")[1]||"").length}function ibt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var cue=Jce,abt=oue,lbt=sue,cbt=iue;const uue=Z.forwardRef(({className:e,...t},n)=>c.jsxs(cue,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(abt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx(lbt,{className:"absolute h-full bg-primary"})}),c.jsx(cbt,{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"})]}));uue.displayName=cue.displayName;const due=["SUN","MON","TUE","WED","THU","FRI","SAT"],ubt=due.reduce((e,t,n)=>({...e,[t]:n}),{}),al={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function dbt(e){if(!e||!e.trim())return{...al};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{...al,isCustom:!0};const[o,s,i,a,l]=r,u=Number(o),d=Number(s);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...al,isCustom:!0};if(i==="*"&&(l==="?"||l==="*"))return{...al,repeats:"daily",hour:d,minute:u};if(i==="?"&&l!=="?"&&l!=="*"){const h=l.split(",").map(m=>m.toUpperCase()).map(m=>ubt[m]).filter(m=>typeof m=="number");if(h.length>0)return{...al,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(l==="?"||l==="*")?{...al,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(l==="?"||l==="*")?{...al,repeats:"monthly",hour:d,minute:u}:{...al,hour:d,minute:u,isCustom:!0}}function fbt(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((o,s)=>o-s).map(o=>due[o]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fue(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,o=t.toString().padStart(2,"0");return`${r}:${o} ${n}`}function hbt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function mbt(e){if(e.length===7)return"every day";const t=e.slice().sort((o,s)=>o-s);if(t.length===5&&t.every(o=>o>=1&&o<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(o=>r[o]).join(", ")}function pbt(e,t,n,r){const o=fue(e.hour,e.minute),s=hbt(t);let i;if(e.isCustom)i=`Custom schedule · ${o} ${s}`;else switch(e.repeats){case"daily":i=`Daily at ${o} ${s}`;break;case"weekly":i=`Weekly · ${mbt(e.weekdays)} at ${o} ${s}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${o} ${s}`;break;case"monthly":i=`Monthly on the 1st at ${o} ${s}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const gbt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=vO;exports.AccordionContent=sy;exports.AccordionItem=ry;exports.AccordionTrigger=oy;exports.AddDataPicker=aL;exports.AggregateTable=ck;exports.Alert=AR;exports.AlertDescription=RR;exports.AlertDialog=Uf;exports.AlertDialogAction=Eu;exports.AlertDialogCancel=Du;exports.AlertDialogContent=Cu;exports.AlertDialogDescription=ju;exports.AlertDialogFooter=ku;exports.AlertDialogHeader=Nu;exports.AlertDialogTitle=_u;exports.AlertDialogTrigger=Kpe;exports.AlertTitle=mG;exports.ArrowDown=vs;exports.ArrowDownIcon=W6e;exports.ArrowLeft=zy;exports.ArrowRight=YC;exports.ArrowUp=ws;exports.ArrowUpIcon=G6e;exports.AssistantContextEntityControls=QM;exports.AssistantStatus=cle;exports.AtSign=vH;exports.AxisConfigurator=Np;exports.Badge=Ar;exports.Bell=Zw;exports.BookType=wH;exports.BulletChartIcon=lle;exports.COMMON_TIMEZONES=gbt;exports.CSS=Xs;exports.CalculatedFieldEditor=Yne;exports.Calculator=CH;exports.Calendar=Hs;exports.Calendar$1=m1;exports.CalendarRange=NH;exports.Card=Em;exports.CardContent=WC;exports.CardHeader=qC;exports.CardSummary=R2;exports.CardTitle=fp;exports.ChartArea=UT;exports.ChartColumnIncreasing=kH;exports.ChartColumnStacked=_H;exports.ChartJsVisual=p0;exports.ChartLine=jH;exports.ChartNoAxesGantt=DH;exports.ChartPie=TH;exports.ChartScatter=IH;exports.ChatInputWithContext=lL;exports.Checkbox=Cn;exports.ChevronLeft=Bf;exports.ChevronRight=Nr;exports.Circle=mA;exports.CircleAlert=px;exports.CircleCheck=RH;exports.CircleHelp=FH;exports.Clock=pA;exports.CodeHighlighter=uf;exports.CodeXml=Xw;exports.Collapsible=Ul;exports.CollapsibleContent=Wl;exports.CollapsibleTrigger=ql;exports.ColorField=ui;exports.Command=$k;exports.CommandEmpty=Bk;exports.CommandGroup=Vk;exports.CommandInput=lO;exports.CommandItem=Hk;exports.CommandList=zk;exports.CommandSeparator=hne;exports.ComparisonMetadataBadge=LX;exports.Container=zA;exports.ControlDefaultValueEditor=pre;exports.ControlDefinitionOptionsEditor=mre;exports.ControlIdInput=ure;exports.ControlVisibilitySettings=tYe;exports.Copy=hf;exports.CopyButton=$l;exports.CopyPlus=PH;exports.Cross2Icon=Q6e;exports.CustomFilterPopover=EP;exports.CustomScrollArea=Za;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=BZ;exports.DEFAULT_SCHEDULE_VM=al;exports.Dashboard=Wce;exports.DashboardActionsMenu=tq;exports.DashboardCard=yte;exports.DashboardCreateDialogBase=Iq;exports.DashboardExportDialog=zce;exports.DashboardPlus=vgt;exports.DashboardWC=Pgt;exports.DataTableConditionalFormattingSettings=sie;exports.DataTablePagination=ok;exports.Database=gi;exports.DateRangePicker=cP;exports.DefaultChatTransport=oL;exports.Dialog=as;exports.DialogContent=Vo;exports.DialogDescription=os;exports.DialogFooter=ec;exports.DialogHeader=ki;exports.DialogTitle=So;exports.DialogTrigger=Dq;exports.DisplayPreferencesProvider=Ek;exports.DndContext=P0;exports.Donut=OH;exports.Download=Xl;exports.DownloadPdf=Bce;exports.DragOverlay=Jte;exports.DropdownMenu=Es;exports.DropdownMenuCheckboxItem=vc;exports.DropdownMenuContent=rs;exports.DropdownMenuItem=Sn;exports.DropdownMenuLabel=Ml;exports.DropdownMenuRadioGroup=lme;exports.DropdownMenuRadioItem=JU;exports.DropdownMenuSeparator=Zi;exports.DropdownMenuSub=MA;exports.DropdownMenuSubContent=nN;exports.DropdownMenuSubTrigger=tN;exports.DropdownMenuTrigger=Ds;exports.EMPTY_DATA_SOURCE=ky;exports.Editable=HS;exports.EditableText=yi;exports.EditorCustomVisual=Ugt;exports.Ellipsis=Oa;exports.EllipsisVertical=Vf;exports.ErrorBoundary=ea;exports.ExportError=Ip;exports.ExternalLink=Tm;exports.Eye=By;exports.EyeOff=GC;exports.Fallback=_k;exports.FallbackVisual=Kx;exports.FeedbackCategory=xu;exports.FeedbackDialog=Cy;exports.FieldsList=EO;exports.FieldsSection=Ogt;exports.FileSpreadsheet=LH;exports.FileText=Ys;exports.Filter=mf;exports.FilterComponent=vk;exports.FilterInfo=T2;exports.FilterableFieldsPanel=Kne;exports.Globe=hp;exports.Grid3x3=$H;exports.GripVertical=Ql;exports.HEATMAP_PRESET_PALETTES=ZI;exports.Hash=zH;exports.House=BH;exports.HoverCard=Ap;exports.HoverCardContent=du;exports.HoverCardTrigger=Rp;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gce;exports.INLINE_ALLOWED_TOOL_LIST=$gt;exports.INLINE_BLOCKED_MUTATING_TOOLS=Lgt;exports.IconButton=Hc;exports.IconForFieldType=w1;exports.InfoHover=ZP;exports.InlineFilterBar=cte;exports.KPICard=_f;exports.KeyboardSensor=R0;exports.Layers=KC;exports.LayoutDashboard=Im;exports.Link=VH;exports.LoadingDots=hu;exports.Lock=ZC;exports.MAX_SELF_HEAL_ATTEMPTS=zgt;exports.Map=HH;exports.Markdown=mae;exports.Maximize2=XC;exports.MdStackedLineChart=ile;exports.Minimize2=gA;exports.MultiInputEmptyRenderer=rP;exports.PYTHON_DEFAULT_CODE=rA;exports.PanelLeft=qH;exports.PanelResizeHandle=y_;exports.Paperclip=WH;exports.PenLine=WT;exports.Pencil=YH;exports.PendingMessagesDisplay=Fce;exports.PersistedDynamicVisual=jk;exports.PiChartPolar=nle;exports.PivotTableTanstack=qp;exports.Placeholders=dle;exports.Play=GH;exports.Plus=pr;exports.PointerSensor=Xp;exports.PrintMessages=ule;exports.Progress=G5;exports.RECOVERABLE_SQL_ERROR_CODES=Vgt;exports.Radar=KH;exports.RadioGroup=Qi;exports.RadioGroupItem=fo;exports.RefreshCw=pf;exports.ResizableHandle=cet;exports.ResizablePanel=_M;exports.ResizablePanelGroup=Iie;exports.ResourceEditDialog=lW;exports.ResourceType=Or;exports.SELF_HEAL_TIMELINE_STEP=Bgt;exports.Search=zo;exports.SeedQuestions=Dce;exports.SemaphorContext=Oy;exports.SemaphorContextProvider=uA;exports.SemaphorQueryClient=mH;exports.SemaphorReadyIndicator=uL;exports.SemaphorStyleWrapper=Wp;exports.Send=ZH;exports.Settings=xA;exports.Settings2=Vy;exports.Share2=XH;exports.ShareDialog=aW;exports.Sheet=_X;exports.SheetContent=RF;exports.SheetDescription=PF;exports.SheetHeader=EX;exports.SheetTitle=FF;exports.SheetTrigger=yMe;exports.Slider=uue;exports.SortableContext=O0;exports.Sparkles=Mm;exports.Square=QH;exports.SquarePen=yA;exports.Star=vA;exports.StructuralParticipantSelector=dre;exports.SummaryCard=E2;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xc;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=hi;exports.TableBody=Nf;exports.TableCell=Hn;exports.TableColumnVisibilitySettings=Yse;exports.TableHead=ys;exports.TableHeader=Mp;exports.TablePresentationSettings=Kse;exports.TableRow=Fr;exports.TableSkeleton=XP;exports.TableVisual=fu;exports.TbChartBubble=rle;exports.TbChartFunnel=ole;exports.TbChartTreemap=sle;exports.TextCard=Qm;exports.Textarea=Wf;exports.TiSortNumerically=ale;exports.Toggle=k0;exports.Tornado=JH;exports.Trash2=Jl;exports.TreePalm=SA;exports.TrendingUp=QC;exports.TriangleAlert=Bi;exports.TypeGlyph=D0;exports.UXProvider=cL;exports.User=nU;exports.UserRound=tU;exports.Users=CA;exports.applyFilterOverridesToDashboardInputSlots=RY;exports.areContextEntitiesEqual=Cr;exports.areEntitiesJoined=WZ;exports.arrayMove=Qp;exports.buildCardControlUsageById=rYe;exports.buildCustomCardTheme=C0;exports.buildDashboardCardExecutionSnapshot=AY;exports.buildDashboardControlUsageById=nYe;exports.buildDashboardExecutionSnapshot=jR;exports.buildDashboardInputExecutionSnapshot=qc;exports.buildDashboardSheetsInputExecutionSnapshot=PY;exports.buildDashboardStructuralParticipantIdsByControlId=xre;exports.buildFilterFieldMeta=mO;exports.buildFilterSemanticContext=pO;exports.buildInlineFilterNodes=TP;exports.buildMultiInputCustomVisualProps=PP;exports.buildScheduleExpr=fbt;exports.buildSchedulePreview=pbt;exports.buildSlotOrderedCards=MP;exports.calculateContextAwareFilters=Xy;exports.calculateFieldState=kF;exports.canUserAccessVisuals=FVe;exports.canUserCreateDashboards=RVe;exports.canUserEdit=IVe;exports.canUserManageDashboards=AVe;exports.canUserManageGroups=PVe;exports.canUserUseFilters=MVe;exports.cancelExport=a2e;exports.chartSupportsDataLabels=LK;exports.chartSupportsLegend=PK;exports.chartTypes=D_;exports.cleanupKpiMetricComparisonMode=wne;exports.cloneDeep=Ss;exports.cloneLinkedFrameWithSourceMapping=cVe;exports.closestCenter=A0;exports.commitSharedCalculatedFields=fd;exports.createAssistantConversationId=Vh;exports.createAssistantRequestId=jce;exports.createCardsFromSlots=kBe;exports.createChartConfig=Tp;exports.createDashboardControlInputFromControl=ZQe;exports.createDefaultGlobalDateFilter=H0e;exports.createExport=fX;exports.createUniqueDashboardInputVariableNameFromName=eu;exports.dedup=Kmt;exports.doesStoredFilterMatchField=rp;exports.downloadDocumentPdf=DR;exports.downloadPdf=UY;exports.extractSqlParamReferences=yJ;exports.extractTableMetadata=hO;exports.fieldAlreadyExists=GZ;exports.findCustomVisualConfigCard=RP;exports.findDashboardFrameById=R0e;exports.flexRender=Ns;exports.formatDisplayFormula=XUe;exports.formatFileSize=u2e;exports.formatFilterLine=gG;exports.formatTimeLabel=fue;exports.getAutoDetectedChartIcon=Blt;exports.getChartGridStyle=f1e;exports.getChartIconByType=Vlt;exports.getColorForValue=hI;exports.getConfigSlotExpectedType=NBe;exports.getCoreRowModel=tk;exports.getCustomVisualInputCards=AP;exports.getDateFormatOptionsForGranularity=ty;exports.getDefaultAxisConfig=pI;exports.getDefaultChartColors=Xf;exports.getDefaultDataLabelsConfig=c0;exports.getDefaultExportFormat=AG;exports.getDefaultFilterSql=mP;exports.getDefaultLegendConfig=lF;exports.getDefaultRunningTotalPartitionByFieldIds=nx;exports.getDocumentSectionEditorCard=RWe;exports.getDocumentSheetDashboardInputs=K0;exports.getDownloadUrl=i2e;exports.getEffectiveCardTypeForSlot=om;exports.getEntityIcon=UC;exports.getErrorMessage=yce;exports.getExportStatus=s2e;exports.getExports=o2e;exports.getExpressionFieldKind=pu;exports.getFieldExpressionAnnotation=gO;exports.getFilterCount=GS;exports.getGlobalDateFilter=xp;exports.getGlobalDateFilterCoverage=U0e;exports.getGranularityOptionsForFieldType=RO;exports.getKeys=Qn;exports.getMetricDisplayLabel=_Ie;exports.getNewField=JZ;exports.getObjectDiff=G7;exports.getPaginationRowModel=nk;exports.getRoleBasedDisplayOverrides=lte;exports.getRunningTotalOrderByCandidates=vUe;exports.getSelectedDateFilterColumn=wJ;exports.getSheetScopedFilterValues=Sx;exports.getSlotDefinitionForIndex=IP;exports.getSlotExpectedChartType=Ck;exports.getSlotIndexForCard=Yx;exports.getSortedRowModel=kX;exports.getSupportedExportFormats=MG;exports.getTableConditionalFormattingColumnOptions=Jse;exports.getTableOutputColumnOptions=eie;exports.getTablePageSizeOptions=cX;exports.handleAggregationChange=I2;exports.handleAggregationLabelChange=ite;exports.hasFlatTableTotalsBehavior=Lve;exports.horizontalListSortingStrategy=oO;exports.isCalculatedFilterField=ny;exports.isCardSummaryVisibleOnCard=OP;exports.isCustomVisualConfigCard=_2;exports.isDefaultColor=Yve;exports.isEligibleFlatTableTotalsCard=yp;exports.isExportComplete=c2e;exports.isExportInProgress=l2e;exports.isInAiScopeArray=Gmt;exports.isManagedCalculatedExpressionField=qi;exports.isMetricTransformEnabled=xUe;exports.isPromiseLike=ZM;exports.isSubtotalEnabledAggregateTable=fO;exports.isSupportedDocumentTableCardType=FWe;exports.lastAssistantMessageIsCompleteWithToolCalls=pce;exports.merge=Pa;exports.mergeAxisConfig=gI;exports.normalizeConditionalFormatting=vR;exports.normalizeContextFormatMode=SG;exports.normalizeDashboardInputVariableName=$y;exports.normalizeMultiInputPayload=FP;exports.parseScheduleExpr=dbt;exports.pivotData=n0;exports.prepareFeedbackData=E_;exports.purify=nQ;exports.reindexSlotCards=CBe;exports.remarkGfm=Vae;exports.removeFromScopeArray=Zmt;exports.resolveDomainCalculatedFieldForEdit=Wqe;exports.resolveMultiInputType=N0;exports.resolveMultiInputTypeFromVisual=_Be;exports.resolveTablePageSize=QN;exports.resolveTablePresentationStyle=WF;exports.sanitizeAIScope=xce;exports.saveCalculatedFieldToCardScope=H2;exports.saveCalculatedFieldToSharedScope=Gne;exports.saveCalculatedFieldToSheetScope=U2;exports.seedSemanticMetricFormatDefaults=Cne;exports.setTableColumnVisibility=pX;exports.setupEditorWithCard=IN;exports.showAllTableColumns=m2e;exports.showJoinRequiredNotification=YZ;exports.sortByColumnsToSortState=GX;exports.sortStateToSortByColumns=KX;exports.sortableKeyboardCoordinates=iO;exports.supportsMetricTransformForMetric=Sne;exports.supportsTableConditionalFormatting=Zse;exports.toEntityArray=Ui;exports.ue=Xe;exports.useActiveExports=Jge;exports.useActiveToolStatus=$ce;exports.useAddFrameWithFreshSemanticExecutionPayload=KP;exports.useAddNewFrame=Dte;exports.useAssistantContainer=fW;exports.useAssistantContextEntities=Tk;exports.useAssistantLayoutStore=Yd;exports.useAssistantPanel=uW;exports.useAssistantProfile=Ece;exports.useAutoScroll=Oce;exports.useAutoSubmitQueue=Pce;exports.useBrandStudioPreview=igt;exports.useCard=LIe;exports.useCardFilterValues=tX;exports.useCardSummary=LP;exports.useChat=bce;exports.useColumns=cO;exports.useCreateVisualWithFrame=epe;exports.useCurrentUserInfo=Ni;exports.useCustomVisual=eh;exports.useCustomVisualsQuery=jP;exports.useDashboardAppearance=qa;exports.useDashboardById=lq;exports.useDashboardCreation=dq;exports.useDashboardManagement=uq;exports.useDashboardPreferences=mp;exports.useDashboardQuery=Ly;exports.useDashboardStructuralParticipants=yre;exports.useDashboardSummary=Bee;exports.useDataColumns=kne;exports.useDateFilterHook=r4e;exports.useDebounce=Zb;exports.useDefaultDashboardMutation=nq;exports.useDisplayPreferences=Ka;exports.useDroppable=Qte;exports.useEditorAside=Uk;exports.useEditorCardQuery=TN;exports.useEnsureReactGlobals=GQ;exports.useExportActions=hW;exports.useExportStore=dN;exports.useFieldManagement=Nne;exports.useFilterableFields=xne;exports.useFullscreenAssistant=dW;exports.useGroupMembers=ege;exports.useGroups=Jq;exports.useHasDashboardId=mW;exports.useInProgressExportsCount=ebe;exports.useIsDashboardSelected=qde;exports.useIsVisualSelected=Wde;exports.useJoinabilityMap=dO;exports.useManagementActions=zf;exports.useManagementStore=Wr;exports.useMessageWindow=Lce;exports.useMutation=Oo;exports.usePivotTableConfig=Jf;exports.usePluginQuery=jee;exports.useQuery=Dn;exports.useQueryClient=Vr;exports.useReactTable=rk;exports.useResolveExistingFrameSemanticExecutionPayload=hVe;exports.useResourceManagement=sN;exports.useResourceUpdateState=cq;exports.useScopedFields=bne;exports.useSelectedVisual=Ude;exports.useSemaphorContext=xt;exports.useSensor=np;exports.useSensors=Rk;exports.useSortable=Jp;exports.useStarredChartsStore=qgt;exports.useSurfaceAppearance=nc;exports.useTableQueryState=$X;exports.useTextFilterHook=m4e;exports.useTheme=oA;exports.useTopoJson=d0;exports.useUnifiedUsers=LA;exports.useUpdateResource=oq;exports.useUpdateVisualMutation=tpe;exports.useUserPreferences=Mq;exports.useVisualById=oN;exports.useVisualManagement=Jme;exports.validateFieldForChartType=vne;exports.verticalListSortingStrategy=sO;