react-semaphor 0.1.137 → 0.1.139

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 (24) hide show
  1. package/dist/chunks/{dashboard-controls-hLb7d4n_.js → dashboard-controls-CycUpkzN.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-CxQYnkax.js → dashboard-controls-FAtMQrth.js} +3 -3
  3. package/dist/chunks/{dashboard-export-dialog-XQQow9XX.js → dashboard-export-dialog-BOeaIkB4.js} +3 -3
  4. package/dist/chunks/{dashboard-export-dialog-JVjnwTLv.js → dashboard-export-dialog-BkGfu2Ur.js} +1 -1
  5. package/dist/chunks/{dashboard-json-CSK4231d.js → dashboard-json-CUnn97AA.js} +1 -1
  6. package/dist/chunks/{dashboard-json-W8a-T1U3.js → dashboard-json-vWf6j3ir.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-C8ZQJfdk.js → edit-dashboard-visual-QX1EfVIC.js} +2 -2
  8. package/dist/chunks/{edit-dashboard-visual-BGH8yv2A.js → edit-dashboard-visual-WvBAW290.js} +9 -6
  9. package/dist/chunks/{editor-action-buttons-BmBNyNxY.js → editor-action-buttons-BaYDKpMq.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-zUsKxZMu.js → editor-action-buttons-hyOjCHRm.js} +2 -2
  11. package/dist/chunks/{index-MdpD3qo9.js → index-BAZxSdVh.js} +1 -1
  12. package/dist/chunks/{index-NjRBKdZ2.js → index-C0aUsTJw.js} +4 -4
  13. package/dist/chunks/{resource-management-panel-C_q7Ilyi.js → resource-management-panel-B2XgOmvv.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-Di5Mg69T.js → resource-management-panel-Chg6-H5n.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-oliZ5xcR.js → use-visual-utils-DIuorLLH.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-CmKlc7fo.js → use-visual-utils-DyjCJ47j.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/style.css +1 -1
  22. package/dist/surfboard/index.cjs +1 -1
  23. package/dist/surfboard/index.js +1 -1
  24. package/package.json +1 -1
@@ -1068,7 +1068,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1068
1068
 
1069
1069
  `)},flush(e){e.enqueue(`data: [DONE]
1070
1070
 
1071
- `)}})}});var YXe=zZe(()=>aee(Ar([qn({type:mt("text-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("error"),errorText:ze()}),qn({type:mt("tool-input-start"),toolCallId:ze(),toolName:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-delta"),toolCallId:ze(),inputTextDelta:ze()}),qn({type:mt("tool-input-available"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-error"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional(),errorText:ze()}),qn({type:mt("tool-output-available"),toolCallId:ze(),output:fo(),providerExecuted:Cr().optional(),dynamic:Cr().optional(),preliminary:Cr().optional()}),qn({type:mt("tool-output-error"),toolCallId:ze(),errorText:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("reasoning-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("source-url"),sourceId:ze(),url:ze(),title:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("source-document"),sourceId:ze(),mediaType:ze(),title:ze(),filename:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("file"),url:ze(),mediaType:ze(),providerMetadata:ur.optional()}),qn({type:nee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ze().optional(),data:fo(),transient:Cr().optional()}),qn({type:mt("start-step")}),qn({type:mt("finish-step")}),qn({type:mt("start"),messageId:ze().optional(),messageMetadata:fo().optional()}),qn({type:mt("finish"),messageMetadata:fo().optional()}),qn({type:mt("abort")}),qn({type:mt("message-metadata"),messageMetadata:fo()})])));function GXe(e){return e.type.startsWith("data-")}function pee(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=pee(o,s):n[r]=s}return n}function KXe(e){const t=["ROOT"];let n=-1,r=null;function s(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 o(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":s(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":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(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,s(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":{s(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"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(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"?o(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 gee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Bw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Bw({text:KXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ky(e){return e.type.startsWith("tool-")}function ZXe(e){return e.type==="dynamic-tool"}function f_(e){return Ky(e)||ZXe(e)}function _L(e){return e.type.split("-").slice(1).join("-")}function XXe({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 QXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(Ky).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var C;const S=u.message.parts.find(E=>Ky(E)&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=N.rawInput,_.preliminary=N.preliminary,_.providerExecuted=(C=N.providerExecuted)!=null?C:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var C;const S=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.toolName=w.toolName,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=(C=N.rawInput)!=null?C:_.rawInput,_.preliminary=N.preliminary,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,errorText:N.errorText,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}async function v(w){if(w!=null){const C=u.message.metadata!=null?pee(u.message.metadata,w):w;t!=null&&await CL({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.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 w=u.message.parts.filter(Ky);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:C}=await gee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}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 v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(GXe(a)){(n==null?void 0:n[a.type])!=null&&await CL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const C=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;C!=null?C.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function JXe({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()}}Bx({prefix:"aitxt",size:24});Bx({prefix:"aiobj",size:24});var eQe=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()})}};Bx({prefix:"aiobj",size:24});var tQe={};FXe(tQe,{object:()=>rQe,text:()=>nQe});var nQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rQe=({schema:e})=>{const t=PXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await gee(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Bw({text:n});if(!s.success)throw new kL({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await AI({value:s.value,schema:t});if(!o.success)throw new kL({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},sQe=Yf({name:ze(),version:ze()}),OI=Yf({_meta:xr(Wt({}).loose())}),Cb=OI,oQe=Wt({method:ze(),params:xr(OI)}),iQe=Yf({experimental:xr(Wt({}).loose()),logging:xr(Wt({}).loose()),prompts:xr(Yf({listChanged:xr(Cr())})),resources:xr(Yf({subscribe:xr(Cr()),listChanged:xr(Cr())})),tools:xr(Yf({listChanged:xr(Cr())}))});Cb.extend({protocolVersion:ze(),capabilities:iQe,serverInfo:sQe,instructions:xr(ze())});var aQe=Cb.extend({nextCursor:xr(ze())}),lQe=Wt({name:ze(),description:xr(ze()),inputSchema:Wt({type:mt("object"),properties:xr(Wt({}).loose())}).loose()}).loose();aQe.extend({tools:ou(lQe)});var cQe=Wt({type:mt("text"),text:ze()}).loose(),uQe=Wt({type:mt("image"),data:ZJ(),mimeType:ze()}).loose(),bee=Wt({uri:ze(),mimeType:xr(ze())}).loose(),dQe=bee.extend({text:ze()}),fQe=bee.extend({blob:ZJ()}),hQe=Wt({type:mt("resource"),resource:Ar([dQe,fQe])}).loose();Cb.extend({content:ou(Ar([cQe,uQe,hQe])),isError:Cr().default(!1).optional()}).or(Cb.extend({toolResult:fo()}));var sC="2.0",mQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()])}).merge(oQe).strict(),pQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),result:Cb}).strict(),gQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),error:Wt({code:wb().int(),message:ze(),data:xr(fo())})}).strict(),bQe=Wt({jsonrpc:mt(sC)}).merge(Wt({method:ze(),params:xr(OI)})).strict();Ar([mQe,bQe,pQe,gQe]);async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Mf(this.body),l=await Mf(this.headers),u=await Mf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},m=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},p=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:SL({"Content-Type":"application/json",...h},`ai-sdk/${EL}`,wL()),body:JSON.stringify(m),credentials:p,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Mf(this.body),a=await Mf(this.headers),l=await Mf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,p=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:SL(f,`ai-sdk/${EL}`,wL()),credentials:h});if(p.status===204)return null;if(!p.ok)throw new Error((o=await p.text())!=null?o:"Failed to fetch the chat response.");if(!p.body)throw new Error("The response body is empty.");return this.processResponseStream(p.body)}},FI=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return HZe({stream:e,schema:YXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=TZe,id:t=e(),transport:n=new FI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new eQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"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(p=>p.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.addToolResult=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=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:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:XXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let m;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}m=g}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const p=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await JXe({stream:QXe({stream:m,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:p,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(f_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function SQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var CQe=SQe;const NQe=Vc(CQe);var xee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},In=(e,t,n)=>(xee(e,t,"read from private field"),n?n.call(e):t.get(e)),Vi=(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)},Ll=(e,t,n,r)=>(xee(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var ko,Zy,Xy,Yp,Gp,Kp,Of,h_,m_,kQe=class{constructor(e=[]){Vi(this,ko,void 0),Vi(this,Zy,"ready"),Vi(this,Xy,void 0),Vi(this,Yp,new Set),Vi(this,Gp,new Set),Vi(this,Kp,new Set),this.pushMessage=t=>{Ll(this,ko,In(this,ko).concat(t)),In(this,Of).call(this)},this.popMessage=()=>{Ll(this,ko,In(this,ko).slice(0,-1)),In(this,Of).call(this)},this.replaceMessage=(t,n)=>{Ll(this,ko,[...In(this,ko).slice(0,t),this.snapshot(n),...In(this,ko).slice(t+1)]),In(this,Of).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return In(this,Yp).add(r),()=>{In(this,Yp).delete(r)}},this["~registerStatusCallback"]=t=>(In(this,Gp).add(t),()=>{In(this,Gp).delete(t)}),this["~registerErrorCallback"]=t=>(In(this,Kp).add(t),()=>{In(this,Kp).delete(t)}),Vi(this,Of,()=>{In(this,Yp).forEach(t=>t())}),Vi(this,h_,()=>{In(this,Gp).forEach(t=>t())}),Vi(this,m_,()=>{In(this,Kp).forEach(t=>t())}),Ll(this,ko,e)}get status(){return In(this,Zy)}set status(e){Ll(this,Zy,e),In(this,h_).call(this)}get error(){return In(this,Xy)}set error(e){Ll(this,Xy,e),In(this,m_).call(this)}get messages(){return In(this,ko)}set messages(e){Ll(this,ko,[...e]),In(this,Of).call(this)}};ko=new WeakMap;Zy=new WeakMap;Xy=new WeakMap;Yp=new WeakMap;Gp=new WeakMap;Kp=new WeakMap;Of=new WeakMap;h_=new WeakMap;m_=new WeakMap;var Ff,DL=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),Vi(this,Ff,void 0),this["~registerMessagesCallback"]=(r,s)=>In(this,Ff)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>In(this,Ff)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>In(this,Ff)["~registerErrorCallback"](r),Ll(this,Ff,n)}};Ff=new WeakMap;function yee({experimental_throttle:e,resume:t=!1,...n}={}){const r=j.useRef("chat"in n?n.chat:new DL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DL(n));const o="id"in n?n.id:null,i=j.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=j.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=j.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=j.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=j.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return j.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.addToolResult}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function DQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function vee(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function wee(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function TQe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=s1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=yee({transport:new FI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Oi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:$W(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:vee(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=wee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function See(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=s1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=cn({queryKey:["assistant-profile",n],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Cee({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(M8,{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(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Vw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(fD,{className:r});case"view":return c.jsx(vd,{className:r});case"materialized view":return c.jsx(Iae,{className:r});case"model":return c.jsx(a1,{className:r});case"file":return c.jsx(ki,{className:r});case"dataset":return c.jsx(al,{className:r});case"upload":return c.jsx(pD,{className:r});case"url":return c.jsx(L8,{className:r});default:return c.jsx(i1,{className:r})}}const Nee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(va,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:X("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})]}));Nee.displayName=ds.Input.displayName;const vy=e=>e.label||(e==null?void 0:e.name),ML=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function RQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=j.useState(""),[p,g]=j.useState(""),b=s.filter(S=>{if(!h)return!0;const N=vy(S).toLowerCase(),_=ML(S).toLowerCase(),E=h.toLowerCase();return N.includes(E)||_.includes(E)});j.useEffect(()=>{e||(m(""),g(""))},[e]),j.useEffect(()=>{b.length>0&&!p&&g(vy(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>vy(N)===p);S&&(o.some(_=>"id"in S&&"id"in _?S.id===_.id:S.name===_.name&&S.connectionId===_.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,C=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(FS,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Nee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.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:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs($S,{className:"min-h-60",children:[c.jsx(LS,{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(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(zS,{children:b.map((S,N)=>{const _=v(S),E="id"in S?S.id:`${S.connectionId}-${S.name}`,k=vy(S);return c.jsxs(BS,{value:k,onSelect:()=>{_?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("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:Vw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:ML(S)})]}),_&&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($r,{className:"h-3 w-3 text-background"})})]},E)})})]})]})})}const p_=e=>e.name||e.name,IQe=e=>{const t=p_(e),n="description"in e?e.description:"",r=e.database||"",s=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}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=j.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(On,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Vw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:p_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-w-xs",children:IQe(d)})]},h)}),u&&c.jsxs(un,{open:s,onOpenChange:o,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Aae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{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:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.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:Vw(d.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:p_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function jee(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function OQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),jee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQe(e){const{tokenProps:t}=Ge(),n=Q(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(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:s,data:o,isLoading:i,isError:a}=cn({queryKey:["semantic-domains"],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Ge(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=cn({queryKey:["datasets",e],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Ge(),n=Q(x=>x.authToken)||e,{connections:r}=Pi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["databases",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Ge(),n=Q(b=>b.authToken)||e,{connections:r}=Pi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["schemas",s,o],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function kee(e){const{tokenProps:t}=Ge(),n=Q(h=>h.authToken)||e,{connections:r}=Pi(e),s=Ee(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=cn({queryKey:["dataModels",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var C,S,N;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=j.useState(""),{selectedConnection:s,error:o}=Pi(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=kee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const E=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...E,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(nt,{children:i.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:m}),c.jsxs(rt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(nt,{children:d.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function VQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=j.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(ki,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=j.useState(""),[s,o]=j.useState(""),[i,a]=j.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(jn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(jn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",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(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(i1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Ge(),r=Q(w=>w.authToken)||t,{connections:s}=Pi(t),o=Ee(w=>{var C,S;return(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.connectionId}),i=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=cn({queryKey:[e,o,i,a],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var C;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(C=w==null?void 0:w.table_type)==null?void 0:C.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function Hw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(yd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pi(),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=kee(),w=k=>{const M=s.find(O=>O.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},C=k=>{var R,I;const M=n||[],T=M.some(L=>L.name===k.name&&L.type===k.type);let O;if(T)O=M.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};O=[...M,L]}t==null||t(O)},S=k=>{const M=n||[],T=M.some(R=>R.type==="model"&&R.name===k.name);let O;T?O=M.filter(R=>!(R.type==="model"&&R.name===k.name)):O=[...M,k],t==null||t(O)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),E=j.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const O=N.filter(R=>!k.some(I=>I.name===R.name&&I.type==="table")).map(R=>{var I,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:R.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:R.name,dialect:R.dialect}});M=[...k,...O]}else if(d==="datamodels"){const T=_.filter(O=>!k.some(R=>R.name===O.name&&R.type==="model"));M=[...k,...T]}t(M)},[d,N,_,n,e,t]);return j.useEffect(()=>{r&&r(E)},[r,E]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(nt,{children:s.map(k=>c.jsx(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(al,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Oe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(As,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(qt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(qt,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(nr,{value:"tables",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Hw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[c.jsx(nn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(nr,{value:"datamodels",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Hw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(nn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var C;const[l,u]=j.useState(""),d=j.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);j.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=FQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],_=N.some(k=>k.id===S.id&&k.type==="dataset");let E;if(_)E=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};E=[...N,k]}n==null||n(E)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=j.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],_=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),E=[...S,..._];n(E)},[v,r,e==null?void 0:e.semanticDomainId,n]);return j.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((C=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),c.jsx(nt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(Hw,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Hw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(_=>_.id===S.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(nn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function $I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=j.useState([]),{updateDataSource:u}=lr(),d=Q(M=>M.isVisualEditing),f=Q(M=>M.dashboard.aiContext),{setAiContext:h}=Gt(),m=j.useRef(null),[p,g]=j.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=j.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=j.useCallback(M=>{u({...n,...M})},[n,u]);j.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),j.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),j.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const C=M=>{const T=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(T)},S=()=>{l([])},N=j.useCallback(M=>{l(M)},[]),_=j.useCallback(()=>{m.current&&m.current()},[]),E=j.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,R=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:O,connectionType:R,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Ur,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Wr,{className:"flex-shrink-0",children:[c.jsx(qr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(As,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsx(qt,{value:"database",children:"Direct Source"}),c.jsx(qt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:E}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:E})]})}),c.jsx(OQe,{selectedEntities:a,onDeselectEntity:C}),c.jsx(Rs,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:k,children:[c.jsx($r,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=j.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ba-n;if(l.length>u){Fe.error(`You can only attach ${Ba} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=lJ(l);if(f.forEach(({file:h,error:m})=>{Fe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>jI(m)));e(h)}catch(h){console.error("Failed to process files:",h),Fe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ba}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ba,title:n>=Ba?`Maximum ${Ba} files allowed`:"Attach files",children:c.jsx(aD,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=j.useState(!1),a=j.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=j.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=j.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=j.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=Ba-r;if(h.length>m){Fe.error(`You can only attach ${Ba} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=lJ(h);if(g.forEach(({file:b,error:x})=>{Fe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>jI(x)));t(b),Fe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Fe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg 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(pD,{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:[Ba-r," slot(s) available"]})]})})]})}const LI=j.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=j.useState(!1),[h,m]=j.useState(!1),[p,g]=j.useState(!1),b=j.useRef(null),x=$m();YNe(),qNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:C}=G1(),{queueMessage:S}=Lm(),{addFileAttachment:N,removeFileAttachment:_,clearFileAttachments:E,getFileAttachments:k}=rT(),M=nT(l),T=Ee(H=>H.card.dataSource),O=Q(H=>H.dashboard.aiContext),R=Q(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});j.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=j.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);j.useEffect(()=>{I()},[I]),j.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const L=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(S(l,H,M),t(""),E(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},V=j.useCallback(H=>{const G=lqe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async K=>{const te=await jI(K);N(l,te)}))},[N,l]),$=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),P=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),U=j.useCallback(H=>{_(l,H)},[_,l]),B=H=>{if(x.selectedEntities.some(K=>K.id&&K.id===H.id||K.name===H.name)){const K=x.selectedEntities.filter(te=>!(te.id&&te.id===H.id||te.name===H.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,H];y({selectedEntities:K})}},A=H=>{B(H)},Y=H=>{var te;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const K="label"in H?H.label:H.name;t(e+`@${K} `),f(!1),(te=b.current)==null||te.focus()},z=H=>{const G=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:G});const te=`@${"label"in H?H.label:H.name}`;e.includes(te)&&t(e.replace(te,"").trim())},q=H=>{const G=new Set(H.map(Z=>Z.id||Z.name)),K=x.selectedEntities.filter(Z=>!G.has(Z.id||Z.name));y({selectedEntities:K});let te=e;H.forEach(Z=>{const se=`@${"label"in Z?Z.label:Z.name}`;te=te.replace(se,"").trim()}),t(te)},W=j.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:R||[],onRemoveEntity:z,onRemoveEntities:q}),M.length>0&&c.jsx(cqe,{files:M,onRemove:U,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:V,onFocus:()=>{I(),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 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ks,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Es,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Eae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(_s,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(RQe,{isOpen:!0,onSelect:B,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:R||[],selectedEntities:x.selectedEntities,onTabComplete:Y,onSelectAll:()=>{R&&y({selectedEntities:R})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Wae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(q8,{className:"size-4"})})]})]})]}),c.jsx($I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||tC,dialogMode:"aiContext"})]})});LI.displayName="ChatInputWithContext";function Eee({assistantType:e,className:t}){const n=LW(e),{removeFromQueue:r}=Lm();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>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:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function _ee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=LW(e),{dequeueMessage:o}=Lm();j.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Dee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=j.useRef(null),[a,l]=j.useState(!0),[u,d]=j.useState(!0),[f,h]=j.useState(!1),[m,p]=j.useState(0),g=j.useRef(0),b=j.useRef(!1),x=j.useRef(0),y=j.useRef(a),v=j.useRef(),w=j.useRef({key:null,count:0,length:0}),C=j.useCallback(()=>{const E=i.current;return E?E.scrollHeight-E.scrollTop-E.clientHeight:0},[]),S=j.useCallback((E={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=E;if(!M&&!y.current||!a&&!M)return;const O=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const R=i.current;if(!R){b.current=!1,v.current=void 0;return}const I=R.scrollHeight;O==="smooth"&&"scrollTo"in R?R.scrollTo({top:I,behavior:O}):R.scrollTop=I,g.current=R.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=j.useCallback(()=>{const E=i.current;if(!E)return;const k=g.current,M=E.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=C()<=n;d(O),l(O),y.current=O,O&&(h(!1),p(0))},[C,n]),_=j.useCallback(()=>{p(0),h(!1)},[]);return j.useEffect(()=>{y.current=a},[a]),j.useEffect(()=>{const E=i.current;if(!E||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=E?E.scrollTop:0,x.current=E?E.scrollHeight:0;return}g.current=E.scrollTop,x.current=E.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,R=e.length>k.count,I=T!==k.key,L=O>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!R&&(I||L),V=o||F;if(w.current={key:T,count:e.length,length:O},a&&(R||I||L||V)){S({force:!1,instant:V});return}if(!a&&R){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>0?$:1))},[e,S,a,s,o]),j.useEffect(()=>{S({instant:!0})},[S]),j.useEffect(()=>{if(typeof ResizeObserver>"u")return;const E=i.current;if(!E)return;x.current=E.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>T&&S({force:!1,instant:!0})});return k.observe(E),()=>{k.disconnect()}},[S]),j.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:_}}function Mee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=j.useState(r),a=j.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=j.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=j.useCallback(()=>{i(r)},[r]);return j.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Tee(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:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:cJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=j.useState(!1),[a,l]=j.useState(T_),[u,d]=j.useState(!1),[f,h]=j.useState(!1),[m,p]=j.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=gm(),y=j.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:w}=lr(),{addFrame:C,setSelectedFrameId:S,setIsDashboardEditing:N}=Gt(),_=$m(),{setCurrentAIContext:E,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=G1(),{clearQueue:O}=Lm(),{clearFileAttachments:R,getFileAttachments:I}=rT(),L=nT("dashboard"),F=Q(Be=>Be.dashboard.aiContext),V=Ee(Be=>Be.card.dataSource),{assistantProfile:$}=See(),P=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:U,isLoading:B,messages:A,setMessages:Y,status:z,stop:q,errorMessage:W,clearError:H}=TQe(),G=j.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=j.useCallback(()=>{G(!g)},[g,G]);j.useEffect(()=>{if(!g)return;function Be(We){We.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,G]);const[te,Z]=j.useState(""),ee=Be=>{Z(Be.target.value)};function se({sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}){if(console.log("handleAddNewFrame",{sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}),!v)return;const Ve={id:jr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Je==="horizontalBar"?"y":"x"}},type:Je,sql:Be,python:Ne,dataSource:Re,config:_e,connectionId:qe},it={id:jr(),cards:[Ve],activeCardId:Ve.id};N(!0),C(v,it,"end"),S(it.id)}const ce=Be=>{Be.preventDefault();const We=te.trim();if(!We&&L.length===0)return;const ht=[];We&&ht.push({type:"text",text:We}),L.forEach(qe=>{qe.data&&ht.push({type:"file",mediaType:qe.type,filename:qe.name,url:`data:${qe.type};base64,${qe.data}`})}),U({role:"user",parts:ht}),Z(""),R("dashboard"),le({force:!0})};j.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),_ee({assistantType:"dashboard",status:z,isLoading:B,sendMessage:U});const{hasActiveTools:re}=Tee(A),{visibleMessages:fe,hasMoreMessages:Ce,totalMessageCount:ie,loadMoreMessages:pe,resetMessageWindow:ue}=Mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,isAtBottom:Se,hasNewMessages:Qe,newMessageCount:Ke,scrollToBottom:le,handleScroll:xe,resetNewMessageCount:Le}=Dee(fe,{threshold:50,behavior:"smooth",isStreaming:B});function me(Be){Ie();const We={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};U(We)}function ke(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]})}function $e(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]}),le({force:!0})}const He=j.useCallback(async()=>{const Be=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),Fe.success("Conversation copied")}catch(We){console.error("Failed to copy conversation",We),Fe.error("Unable to copy conversation")}},[A]);function Ie(){_.selectedEntities.length===0&&E({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const st=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Be=>Be.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function pt(){return c.jsxs(mm,{children:[c.jsx(pm,{asChild:!0,children:c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(om,{className:"size-3.5"})})}),c.jsxs(Zd,{align:"end",children:[c.jsx(eh,{children:"Options"}),c.jsx(Cd,{}),c.jsx(Qp,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Qp,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Qp,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const It=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl 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:[je(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&pt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(iD,{className:"size-4"}):c.jsx(l1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{Y([]),O("dashboard"),H(),ue()},children:c.jsx(c1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Cl,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[Ce&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ie-fe.length)," ","more messages (",ie-fe.length," ","hidden)"]})}),c.jsx(dJ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:se,onQuickReply:$e,disableQuickReplies:B}),!re&&c.jsx(uJ,{status:z,errorMessage:W})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Se&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{le({force:!0}),Le()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ks,{className:"h-4 w-4"}),Qe&&Ke>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:Ke>9?"9+":Ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&st&&c.jsx(fJ,{onClick:me,placeholders:KQe}),c.jsx("div",{children:st&&$&&c.jsx(Cee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:ke})}),c.jsx(Eee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(LI,{ref:y,setInput:Z,stop:q,input:te,handleInputChange:ee,handleSubmit:Be=>{Ie(),ce(Be),le({force:!0})},isLoading:B,status:z,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx($I,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||tC,dialogMode:"aiContext"})]});return g&&s?Pn.createPortal(c.jsx("div",{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:It})}),s):It}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);j.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Fe.success("Card copied to clipboard"),m.preventDefault()):p&&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();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=_R(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Fe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}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)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(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 JQe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function eJe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",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 tJe(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 nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:i||"Insight Detail"}),c.jsx(Is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(xZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(wZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function rJe(){const e=Pt(w=>w.interactionStates),t=Pt(w=>w.setInteractionState),n=Pt(w=>w.clearLastInteractionEvent),r=Pt(w=>w.replaceCardWithInsight),s=Pt(w=>w.setPendingDrillThrough),o=Pt(w=>w.pendingDrillThrough),i=Pt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=$b(),d=Q(w=>w.dashboard),f=Q(w=>w.filterValues),{data:h,isLoading:m}=ahe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=j.useState({open:!1,insightId:""}),b=SZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=j.useRef(new Set),y=j.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:C,contextMode:S})=>{g({open:!0,insightId:w,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:C,filters:S,contextMode:N})=>{r(w,C,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_})=>{const k={sourceCardId:oa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Po(),appliedClickFilters:[k],contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_};t(oa,M)}}),[a,r,f,l,d,s,t]);j.useEffect(()=>{Object.entries(e).forEach(([w,C])=>{if(C!=null&&C.lastInteractionEvent){const S=C.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{QQe(S,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),j.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&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-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(Mn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,w,C;const e=Pt(S=>S.interactionStates[oa]),t=Q(S=>S.actions.goBackFromDrill),n=Q(S=>S.actions.clearDrillContext),{selectDashboard:r}=$b(),[s,o]=j.useState({x:16,y:16}),[i,a]=j.useState(!1),l=j.useRef({x:0,y:0});j.useEffect(()=>{if(!i)return;const S=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.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||!((C=e.appliedClickFilters)!=null&&C.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,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((S,N)=>{const _=S.field.label||S.field.name,E=String(S.value);return c.jsxs(Oe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",E]},N)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(g8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Ree(){var Z;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=gm(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=j.useRef(null),i=j.useRef(null),[a,l]=j.useState(!1),u=id(ee=>ee.setFullscreen),d=id(ee=>ee.setPanelOpen),f=id(ee=>ee.setContainer),h=PW("dashboard"),m=OW(),p=FW("dashboard"),g=h.isOpen,b=m==="dashboard",x=Q(ee=>ee.isVisualEditing),y=Q(ee=>ee.themeStyle),v=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.sheets}),w=Q(ee=>ee.isDashboardEditing),C=Q(ee=>ee.selectedSheetId),S=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.id}),N=Q(ee=>ee.isDashboardPanelOpen),_=Q(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:E,setDefaultSheetId:k,clearDefaultSheetId:M}=d8(S),[T,O]=j.useState(null);j1(Ft.DASHBOARD);const{setSelectedSheetId:R,setSheetTitle:I,addSheet:L,setSheets:F}=Gt();XQe(i);const{setActiveAssistantType:V}=G1();j.useEffect(()=>{if(S){const ee=E();O(ee)}},[S,E]),j.useEffect(()=>{g?V("dashboard"):m==="dashboard"&&u(null)},[g,V,m,u]);function $(ee){var se,ce;ee?((se=o.current)==null||se.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(ce=o.current)==null||ce.resize(0),V(null))}function P(){const ee={id:jr(),title:"New Sheet"};L(ee),R(ee.id)}function U(ee,se){if(!S)return;T===ee?(M(),O(null),Fe.success("Default sheet cleared")):(k(ee),O(ee),Fe.success(`"${se}" set as default sheet`))}function B(ee){ee<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const Y=(ee,se)=>{ee.dataTransfer.setData("tabIndex",se.toString())},z=ee=>{ee.preventDefault()},q=(ee,se)=>{const ce=ee.dataTransfer.getData("tabIndex");if(ce===se.toString())return;const re=Array.from(v||[]),[fe]=re.splice(parseInt(ce),1);re.splice(se,0,fe),F(re)},W=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var ee,se;if(v&&v.length>1||w)return c.jsxs(cs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&W&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!N)},className:"h-8 p-2",children:N?c.jsx(_8,{className:"h-4 w-4"}):c.jsx(D8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ce,re)=>{const fe=C===ce.id,Ce=T===ce.id;return c.jsxs(qt,{draggable:!0,onDragStart:ie=>Y(ie,re),onDragOver:z,onDrop:ie=>q(ie,re),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>R(ce.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ce.id,children:[c.jsx(ib,{enabled:w&&fe,text:ce.title,onSave:ie=>I(ce.id,ie),children:ce.title},ce.id),!w&&fe&&c.jsx("div",{title:Ce?"Clear default sheet":"Set as default sheet",children:c.jsx(dD,{className:X("ml-1 size-3 cursor-pointer transition-all",Ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ie=>{ie.stopPropagation(),U(ce.id,ce.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ce.id)}),w&&c.jsx("div",{style:{borderRadius:(se=(ee=y==null?void 0:y.chart)==null?void 0:ee.options)==null?void 0:se.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(ee=>c.jsx(nr,{style:{backgroundColor:A()},className:X("mt-0",{}),value:ee.id,children:c.jsx(C8e,{sheet:ee})},ee.id))})}function K(){var ee;return c.jsxs(As,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:se=>{R(se)},value:C||((ee=v==null?void 0:v[0])==null?void 0:ee.id),children:[H(),c.jsx(Cl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(nze,{open:a,setOpen:l})]})}const te=j.useCallback(ee=>{f("dashboard",ee)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(YX,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(qE,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(tze,{open:g,onTabClick:$,withHandle:!0}),c.jsx(qE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:ee=>u(ee?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:te,className:X("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(uD,{className:"h-5 w-5"})})})]})]}):null}function zI({children:e}){return c.jsx(Ca,{style:{height:"100%",width:"100%"},children:c.jsx(qie,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(On,{delayDuration:0,children:e})})})}function Iee({children:e,preferences:t}){const{currentUser:n}=Ts(),r=j.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx($9.Provider,{value:r,children:c.jsx(RR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Aee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Da,{FallbackComponent:SS,children:c.jsx(J_,{dashboardProps:e,children:c.jsx(zI,{children:c.jsx(Iee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(sT,{...e,type:"dashboard",children:c.jsx(Ree,{})})})})})})})}function BI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return cn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Hn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Pee(e,t,n){if(t==="source")return{isValid:!0};const r=Ir(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Oee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Fee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=BI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=lr(),h=Ee(R=>R.card.type),m=e==null?void 0:e.id,p=j.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=j.useCallback((R,I)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:I});break}case"metrics":{r(m,{metricColumns:I});break}case"pivotBy":{r(m,{pivotByColumns:I});break}case"sortBy":{r(m,{sortByColumns:I});break}}},[m,r]),b=j.useCallback((R,I,L)=>{if(!m)return;const V=p(R)[I];if(V)switch(R){case"groupBy":s(m,V.id,{label:L});break;case"metrics":o(m,V.id,{label:L});break;case"pivotBy":i(m,V.id,{label:L});break;case"sortBy":a(m,V.id,{label:L});break}},[m,p,s,o,i,a]),x=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aggregate:I,label:hU(F.name,I)})},[m,p,o]),y=j.useCallback((R,I,L)=>{if(!m)return;const V=p("groupBy")[R];if(!V)return;const $={dateFormat:I};I==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,V.id,$)},[m,p,s]),v=j.useCallback((R,I)=>{if(!m)return;const F=p("groupBy")[R];F&&s(m,F.id,{granularity:I})},[m,p,s]),w=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aliasTemplate:I})},[m,p,o]),C=j.useCallback((R,I)=>{if(console.log("handleValueAliasesChange",R,I),!m)return;console.log("handleValueAliasesChange",R,I);const F=p("metrics")[R];F&&(console.log("handleValueAliasesChange",I),o(m,F.id,{valueAliases:I}))},[m,p,o]),S=j.useCallback(R=>{if(!m)return;if(p("metrics").length===0){Fe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:R})},[m,r,p]),N=j.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),_=j.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),E=j.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),k=j.useCallback(R=>{m&&r(m,{targetValue:R})},[m,r]),M=j.useCallback(R=>{var U;if(!m)return;const I=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=bCe(R,I,{joinPlan:(U=e==null?void 0:e.config)==null?void 0:U.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&uU();return}const F=vCe(R,I,h);if(!F){Fe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=Pee(R,F,h);if(!V.isValid){Fe.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=p(F);if(dU(R,$))return;const P=mU(R,F,$);if(P){const B=[...$,P];g(F,B),F==="metrics"&&Oee(h,e==null?void 0:e.config,r,m,B)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),T=j.useCallback((R,I)=>{if(!m)return;const F=p(R)[I];if(F){if(R!=="sortBy"){const V=p("sortBy"),$=V.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==V.length&&r(m,{sortByColumns:$})}switch(R){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:C,removeField:T,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:k,cardType:h}};function Vx(e,t){var ke,$e,He,Ie,st;const{tokenProps:n}=Ge(),r=Qs(),s=Ge().authToken||e,o=Ee(je=>je.selectedConnectionId),i=Ee(je=>je.card),{queryKey:a}=upe(i),l=Ee(je=>je.selectedDatamodelId),u=Ee(je=>je.isDevMode),d=Ee(je=>je.selectedDatabaseName),f=Ee(je=>je.selectedSchemaName),h=Ee(je=>je.selectedTableName),m=Ee(je=>je.actions.setSelectedConnectionId),p=Ee(je=>je.actions.setSelectedDatamodelId),g=Ee(je=>je.actions.setSelectedDatabaseName),b=Ee(je=>je.actions.setSelectedSchemaName),x=Ee(je=>je.actions.setSelectedTableName);Ee(je=>je.actions.setCardSql);const{setQueryConfig:y}=lr();function v(je){var It;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((It=E==null?void 0:E.capabilities)==null?void 0:It.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:C,connectionsData:S,isConnectionsLoading:N,isConnectionsError:_,selectedConnection:E}=Pi(e),{refetch:k,data:M,isLoading:T,isError:O}=cn({queryKey:["models",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),R=E==null?void 0:E.type,I=(E==null?void 0:E.type)==="API"||(E==null?void 0:E.type)==="S3",{data:L,isLoading:F,isFetching:V,isError:$,refetch:P}=cn({queryKey:["databases",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(R)}),{data:U,isLoading:B,isFetching:A,isError:Y,refetch:z}=cn({queryKey:["schemas",o,d],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:q,isLoading:W,isFetching:H,isError:G,refetch:K}=cn({queryKey:["tables",o,d,f],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(R)}),{columns:te,isColumnsLoading:Z,isColumnsFetching:ee,isColumnsError:se,refetchColumns:ce}=pU(e);j.useEffect(()=>{(R==="S3"||R==="API")&&(g(""),b(""),p(""),R==="API"&&x("api"))},[R,x,g,b,p]);const re=(E==null?void 0:E.type)==="API"?(ke=E==null?void 0:E.type)==null?void 0:ke.toLowerCase():h||"",fe=I?"":f||"";function Ce(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ie(je){b(je),x("")}function pe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function ue(je){m(je)}function ve(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&(($e=L==null?void 0:L.databases)==null?void 0:$e.length)>0,U&&((He=U==null?void 0:U.schemas)==null?void 0:He.length)>0;const Se=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Qe=(Ie=M==null?void 0:M.datamodels)==null?void 0:Ie.map(je=>({id:je.id,name:je.name})),Ke=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),le=U==null?void 0:U.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=q==null?void 0:q.tables.map(je=>({id:je.table_name,name:je.table_name})),Le=(st=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:st.name,me=nv({schemaName:fe,tableName:re,modelName:Le,connectionType:R,databaseName:d||""});return{connectionItems:Se,selectedConnectionId:o,selectedConnection:E,isConnectionsLoading:N,isConnectionsError:_,modelItems:Qe,selectedDatamodelId:l,selectedDatamodelName:Le,isModelsLoading:T,isModelsError:O,selectedDatabaseName:d,databaseItems:Ke,isDatabasesLoadingOrFetching:F||V,isDatabaseError:$,schemaItems:le,selectedSchemaName:f,isSchemaLoadingOrFetching:B||A,isSchemaError:Y,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:te,isColumnsLoadingOrFetching:Z||ee,isColumnsError:se,isNonDbConnection:I,connectionType:R,tableName:re,formattedTableName:me,schemaName:fe,refetchConnections:C,refetchModels:k,refetchDatabases:P,refetchSchemas:z,refetchTables:K,refetchColumns:ce,handleConnectionChange:ue,handleDatamodelChange:ve,handleDatabaseChange:pe,handleSchemaChange:ie,handleTableChange:Ce}}function wy(e){return`${e}-${jr()}`}function TL(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function lJe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function VI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function $ee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lee(){const e=Ee(S=>S.sqlGen),t=Ee(S=>S.isDevMode),n=Ee(S=>S.card.dataSource),r=Ee(S=>{var N,_;return(_=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=VI(n),a=$ee(n),l=Ee(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Vx(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var _;if(!t)return;const N=y(S);if(t&&a&&s){const E=O_(N,e);m(E);const k=(_=b==null?void 0:b.find(T=>T.id===l))==null?void 0:_.name,M=P_(E,fi(o||""),fi(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Ab(N.data_type))if(r&&r.length>0){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type};d(E)}else{const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(E)}if(Si(N.data_type)){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type,label:lJe(N.column_name,"month"),granularity:"month"};d(E)}if(wi(N.data_type)){const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>wi(S.dataType)}}function cJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=fi(e),u=fi(t||""),d=fi(n||""),f=fi(r);let h=Jw({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Eg}.${i}.${l}`,h=`${Eg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function zee(){const e=Ee(p=>p.selectedConnectionId),t=Ee(p=>p.selectedDatamodelId),n=Ee(p=>p.selectedDatabaseName),r=Ee(p=>p.selectedSchemaName),s=Ee(p=>p.selectedTableName),o=Q(p=>p.dashboard.filters)||[],i=Q(p=>p.selectedSheetId),a=Q(p=>p.actions.addFilter),l=Q(p=>p.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Vx();function m(p,g="sheet",b){var _;const x=(_=d==null?void 0:d.find(E=>E.id===t))==null?void 0:_.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:C,formattedDatabase:S}=cJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=Kke(o,y,C,n||"",S,i):N=o==null?void 0:o.find(E=>E.column===y&&E.table===C&&(E.database===S||E.database===n)),N)u(N.id),l(N.id);else{const E=jr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,w)}),E):(a({id:E,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),E)}}return{assignFilter:m}}function uJe({column:e}){const[t,n]=j.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=VI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Vx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),m=Ee(x=>x.actions.setRunSql),p=$ee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=O_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const C=P_(v,fi(o||""),fi(s),w||"",d,i||"");C&&(h(C),m(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return p?c.jsxs(Pm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Om,{asChild:!0,children:c.jsx(om,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(rf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function dJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function fJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Ee(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=Q(q=>q.dashboard.filters),u=Q(q=>q.selectedSheetId),d=Q(q=>q.actions.removeFilter),{removeFilterValues:f}=Gt(),{assignFilter:h}=zee(),m=t==="filter"?Jc(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var W;return q.title===e.name||((W=q.column)==null?void 0:W.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,C]=j.useState(!1),[S,N]=j.useState(null),{attributes:_,listeners:E,setNodeRef:k,transform:M,transition:T,isDragging:O}=PS({id:e.id,disabled:a}),[R,I]=j.useState(!1),L=Ee(q=>q.card),{handleFieldClick:F}=Fee(L),{handleDevModeFieldClick:V,isNumberField:$}=Lee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),C(!1)},U=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:q,field:e}),C(!0)):h(q,"sheet",e)}else o?V(e):F(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},A={transform:Mi.Transform.toString(M),transition:T},z=(()=>{if(!n||i)return{};const W={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:A,...a?{}:_,...a?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:U,children:[lb(e.dataType),c.jsx(On,{children:c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${R?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(pn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(dJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(uJe,{column:B})})]}),R&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(vo,{className:"",children:c.jsxs(ji,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Y8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Oe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Gb,{open:w,onOpenChange:C,children:c.jsxs(bm,{children:[c.jsxs(xm,{children:[c.jsx(vm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(wm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(ym,{children:[c.jsx(Cm,{children:"Cancel"}),c.jsx(Sm,{onClick:P,children:"Remove Filter"})]})]})})]})}const hJe="SEMAPHOR_CALCULATED_FIELD",mJe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Bee(e){return!!e.expression}function pJe(e){return!!e.expression}function gJe(e){return!!e.expression}var Vee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Vee||{}),_l="Accordion",bJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[HI,xJe,yJe]=d1(_l),[oC]=_r(_l,[yJe,MZ]),UI=MZ(),Hee=j.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(HI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(CJe,{...o,ref:t}):c.jsx(SJe,{...s,ref:t})})});Hee.displayName=_l;var[Uee,vJe]=oC(_l),[Wee,wJe]=oC(_l,{collapsible:!1}),SJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=zr({prop:n,defaultProp:r,onChange:s});return c.jsx(Uee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:j.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(qee,{...i,ref:t})})})}),CJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=zr({prop:n,defaultProp:r,onChange:s}),l=j.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=j.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Uee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(qee,{...o,ref:t})})})}),[NJe,iC]=oC(_l),qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=j.useRef(null),l=bt(a,t),u=xJe(n),f=qd(s)==="ltr",h=De(e.onKeyDown,m=>{var _;if(!bJe.includes(m.key))return;const p=m.target,g=u().filter(E=>{var k;return!((k=E.ref.current)!=null&&k.disabled)}),b=g.findIndex(E=>E.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,C=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?C():S());break;case"ArrowDown":o==="vertical"&&C();break;case"ArrowLeft":o==="horizontal"&&(f?S():C());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(_=g[N].ref.current)==null||_.focus()});return c.jsx(NJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(HI.Slot,{scope:n,children:c.jsx(Ue.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Uw="AccordionItem",[jJe,WI]=oC(Uw),Yee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=iC(Uw,n),i=vJe(Uw,n),a=UI(n),l=or(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(jJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(IZ,{"data-orientation":o.orientation,"data-state":Jee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Yee.displayName=Uw;var Gee="AccordionHeader",Kee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Gee,n);return c.jsx(Ue.h3,{"data-orientation":s.orientation,"data-state":Jee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Kee.displayName=Gee;var g_="AccordionTrigger",Zee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(g_,n),i=wJe(g_,n),a=UI(n);return c.jsx(HI.ItemSlot,{scope:n,children:c.jsx(E$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Zee.displayName=g_;var Xee="AccordionContent",Qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Xee,n),i=UI(n);return c.jsx(_$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Qee.displayName=Xee;function Jee(e){return e?"open":"closed"}var kJe=Hee,EJe=Yee,_Je=Kee,ete=Zee,tte=Qee;const nte=kJe,qI=D.forwardRef(({className:e,...t},n)=>c.jsx(EJe,{ref:n,className:X("border-b",e),...t}));qI.displayName="AccordionItem";const YI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(_Je,{className:"flex",children:c.jsxs(ete,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ks,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));YI.displayName=ete.displayName;const GI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));GI.displayName=tte.displayName;function rte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var I,L,F,V;const[r,s]=j.useState(""),[o,i]=j.useState("all");Ee($=>$.isDevMode);const a=Ee($=>$.card.dataSource),l=Ee($=>$.card.config),u=Ee($=>$.card),{autoJoinMetadata:d}=pa(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=zM(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=BI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(I=l==null?void 0:l.joinPlan)==null?void 0:I.baseEntity)==null||L.name,(V=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||V.name,Lee();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&Bee($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Ir($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},C=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const U=P.qualifiedEntityName||"Other Fields";return $[U]||($[U]={label:q_(P.entityName),fields:[]}),$[U].fields.push(P),$},{}),N=Object.keys(C),_=y.filter($=>v($)==="dimensions").length,E=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",T=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:c.jsx(Rc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const O=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",R=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",O,R),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Nn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(yt,{className:"size-3.5"})})]}),M&&c.jsx(As,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(qt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(qt,{value:"dimensions",className:"text-xs",children:[c.jsx(a1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(qt,{value:"metrics",className:"text-xs",children:[c.jsx(sm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(qt,{value:"calculated",className:"text-xs",children:[c.jsx(eD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Cl,{className:"min-h-0 overflow-auto",children:[c.jsx(nte,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(C).map(([$,P])=>{const U=h.find(B=>B.entityName===$)||{entityName:$,label:P.label};return c.jsxs(qI,{value:$,className:"border-none",children:[c.jsx(YI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:U.label||U.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:U.label||U.entityName}),c.jsx(Oe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(GI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(B=>{const A=BM(B,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(fJe,{field:B,context:e,fieldState:A,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},B.id)})})})]},$)})}),Object.keys(C).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(C).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function ste({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(rte,{context:e})," "]})}function ote(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();j.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=VI(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function DJe(){ote();const e=Q(l=>l.selectedSheetId),t=Q(l=>l.selectedFrameId),n=Q(l=>l.dashboard),r=Q(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=lr(),i=Ee(l=>l.card.dataSource);return j.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function MJe(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=DJe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(NZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(IS,{collisionDetection:DS,children:c.jsx(AS,{items:[],strategy:YR,children:c.jsx(ste,{context:"filter"})})})})]})}function TJe(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("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(AR,{filter:r}),c.jsx(Cx,{filter:r})]},r.id))}):null}function RJe(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(TJe,{}),c.jsx(Ree,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(MJe,{})})]})}const IJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-hLb7d4n_.js"))),AJe=j.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-C8ZQJfdk.js"))),PJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CSK4231d.js"))),OJe=j.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Di5Mg69T.js")).then(e=>({default:e.ResourceManagementPanel})));function FJe({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(l=>l.isDashboardPanelOpen),s=Q(l=>l.isVisualEditing),o=Q(l=>l.showDashboardJSON),i=Q(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Da,{FallbackComponent:SS,children:c.jsxs(J_,{dashboardProps:n,children:[c.jsx(Cfe,{}),c.jsx(zI,{children:c.jsxs(Iee,{preferences:a,children:[o&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(PJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(IJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(OJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(sT,{...n,type:"dashboard",children:[s&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(AJe,{})}),c.jsx(RJe,{})]})})]})]})]})})]})})}var $Je=Object.defineProperty,LJe=(e,t,n)=>t in e?$Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Sy=(e,t,n)=>LJe(e,typeof t!="symbol"?t+"":t,n);const zJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},BJe={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}},VJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},HJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},UJe={stringify:e=>e,parse:e=>e},n2={string:UJe,number:HJe,boolean:zJe,function:BJe,json:VJe};function WJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const Cy=Symbol.for("r2wc.render"),Ny=Symbol.for("r2wc.connected"),yu=Symbol.for("r2wc.context"),Aa=Symbol.for("r2wc.props");function qJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WJe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Sy(this,o,!0),Sy(this,s),Sy(this,r,{}),Sy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Aa].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?n2[x]:null;y!=null&&y.parse&&b&&(this[Aa][p]=y.parse(b,g,this))}for(const p of a)this[Aa][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Ny]=!0,this[Cy]()}disconnectedCallback(){this[Ny]=!1,this[yu]&&n.unmount(this[yu]),delete this[yu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?n2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Aa][x]=v.parse(b,p,this),this[Cy]())}[(o=Ny,s=yu,r=Aa,Cy)](){this[Ny]&&(this[yu]?n.update(this[yu],this[Aa]):this[yu]=n.mount(this.container,e,this[Aa]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Aa][m]},set(b){this[Aa][m]=b;const x=g?n2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Cy]()}})}return h}function YJe(e,t,n){const r=p2(e),s=j.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function GJe({root:e,ReactComponent:t},n){const r=j.createElement(t,n);e.render(r)}function KJe({root:e}){e.unmount()}function ZJe(e,t={}){return qJe(e,t,{mount:YJe,update:GJe,unmount:KJe})}const XJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},QJe=ZJe(Aee,{props:XJe});function JJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function IL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?RL(Object(n),!0).forEach(function(r){JJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function eet(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function tet(e,t){if(e==null)return{};var n=eet(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function net(e,t){return ret(e)||set(e,t)||oet(e,t)||iet()}function ret(e){if(Array.isArray(e))return e}function set(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function oet(e,t){if(e){if(typeof e=="string")return AL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return AL(e,t)}}function AL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function iet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1071
+ `)}})}});var YXe=zZe(()=>aee(Ar([qn({type:mt("text-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("text-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("error"),errorText:ze()}),qn({type:mt("tool-input-start"),toolCallId:ze(),toolName:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-delta"),toolCallId:ze(),inputTextDelta:ze()}),qn({type:mt("tool-input-available"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional()}),qn({type:mt("tool-input-error"),toolCallId:ze(),toolName:ze(),input:fo(),providerExecuted:Cr().optional(),providerMetadata:ur.optional(),dynamic:Cr().optional(),errorText:ze()}),qn({type:mt("tool-output-available"),toolCallId:ze(),output:fo(),providerExecuted:Cr().optional(),dynamic:Cr().optional(),preliminary:Cr().optional()}),qn({type:mt("tool-output-error"),toolCallId:ze(),errorText:ze(),providerExecuted:Cr().optional(),dynamic:Cr().optional()}),qn({type:mt("reasoning-start"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-delta"),id:ze(),delta:ze(),providerMetadata:ur.optional()}),qn({type:mt("reasoning-end"),id:ze(),providerMetadata:ur.optional()}),qn({type:mt("source-url"),sourceId:ze(),url:ze(),title:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("source-document"),sourceId:ze(),mediaType:ze(),title:ze(),filename:ze().optional(),providerMetadata:ur.optional()}),qn({type:mt("file"),url:ze(),mediaType:ze(),providerMetadata:ur.optional()}),qn({type:nee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ze().optional(),data:fo(),transient:Cr().optional()}),qn({type:mt("start-step")}),qn({type:mt("finish-step")}),qn({type:mt("start"),messageId:ze().optional(),messageMetadata:fo().optional()}),qn({type:mt("finish"),messageMetadata:fo().optional()}),qn({type:mt("abort")}),qn({type:mt("message-metadata"),messageMetadata:fo()})])));function GXe(e){return e.type.startsWith("data-")}function pee(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=pee(o,s):n[r]=s}return n}function KXe(e){const t=["ROOT"];let n=-1,r=null;function s(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 o(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":s(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":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(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,s(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":{s(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"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(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"?o(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 gee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Bw({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Bw({text:KXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ky(e){return e.type.startsWith("tool-")}function ZXe(e){return e.type==="dynamic-tool"}function f_(e){return Ky(e)||ZXe(e)}function _L(e){return e.type.split("-").slice(1).join("-")}function XXe({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 QXe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(Ky).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var C;const S=u.message.parts.find(E=>Ky(E)&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=N.rawInput,_.preliminary=N.preliminary,_.providerExecuted=(C=N.providerExecuted)!=null?C:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var C;const S=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===w.toolCallId),N=w,_=S;S!=null?(S.state=w.state,_.toolName=w.toolName,_.input=N.input,_.output=N.output,_.errorText=N.errorText,_.rawInput=(C=N.rawInput)!=null?C:_.rawInput,_.preliminary=N.preliminary,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,errorText:N.errorText,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}async function v(w){if(w!=null){const C=u.message.metadata!=null?pee(u.message.metadata,w):w;t!=null&&await CL({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.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 w=u.message.parts.filter(Ky);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:C}=await gee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:C}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:_L(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}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 v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(GXe(a)){(n==null?void 0:n[a.type])!=null&&await CL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const C=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;C!=null?C.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function JXe({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()}}Bx({prefix:"aitxt",size:24});Bx({prefix:"aiobj",size:24});var eQe=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()})}};Bx({prefix:"aiobj",size:24});var tQe={};FXe(tQe,{object:()=>rQe,text:()=>nQe});var nQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),rQe=({schema:e})=>{const t=PXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await gee(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await Bw({text:n});if(!s.success)throw new kL({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await AI({value:s.value,schema:t});if(!o.success)throw new kL({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},sQe=Yf({name:ze(),version:ze()}),OI=Yf({_meta:xr(Wt({}).loose())}),Cb=OI,oQe=Wt({method:ze(),params:xr(OI)}),iQe=Yf({experimental:xr(Wt({}).loose()),logging:xr(Wt({}).loose()),prompts:xr(Yf({listChanged:xr(Cr())})),resources:xr(Yf({subscribe:xr(Cr()),listChanged:xr(Cr())})),tools:xr(Yf({listChanged:xr(Cr())}))});Cb.extend({protocolVersion:ze(),capabilities:iQe,serverInfo:sQe,instructions:xr(ze())});var aQe=Cb.extend({nextCursor:xr(ze())}),lQe=Wt({name:ze(),description:xr(ze()),inputSchema:Wt({type:mt("object"),properties:xr(Wt({}).loose())}).loose()}).loose();aQe.extend({tools:ou(lQe)});var cQe=Wt({type:mt("text"),text:ze()}).loose(),uQe=Wt({type:mt("image"),data:ZJ(),mimeType:ze()}).loose(),bee=Wt({uri:ze(),mimeType:xr(ze())}).loose(),dQe=bee.extend({text:ze()}),fQe=bee.extend({blob:ZJ()}),hQe=Wt({type:mt("resource"),resource:Ar([dQe,fQe])}).loose();Cb.extend({content:ou(Ar([cQe,uQe,hQe])),isError:Cr().default(!1).optional()}).or(Cb.extend({toolResult:fo()}));var sC="2.0",mQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()])}).merge(oQe).strict(),pQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),result:Cb}).strict(),gQe=Wt({jsonrpc:mt(sC),id:Ar([ze(),wb().int()]),error:Wt({code:wb().int(),message:ze(),data:xr(fo())})}).strict(),bQe=Wt({jsonrpc:mt(sC)}).merge(Wt({method:ze(),params:xr(OI)})).strict();Ar([mQe,bQe,pQe,gQe]);async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Mf(this.body),l=await Mf(this.headers),u=await Mf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},m=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},p=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:SL({"Content-Type":"application/json",...h},`ai-sdk/${EL}`,wL()),body:JSON.stringify(m),credentials:p,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Mf(this.body),a=await Mf(this.headers),l=await Mf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,p=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:SL(f,`ai-sdk/${EL}`,wL()),credentials:h});if(p.status===204)return null;if(!p.ok)throw new Error((o=await p.text())!=null?o:"Failed to fetch the chat response.");if(!p.body)throw new Error("The response body is empty.");return this.processResponseStream(p.body)}},FI=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return HZe({stream:e,schema:YXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=TZe,id:t=e(),transport:n=new FI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new eQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"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(p=>p.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.addToolResult=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>f_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=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:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:XXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let m;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}m=g}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const p=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await JXe({stream:QXe({stream:m,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:p,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(f_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function SQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var CQe=SQe;const NQe=Vc(CQe);var xee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},In=(e,t,n)=>(xee(e,t,"read from private field"),n?n.call(e):t.get(e)),Vi=(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)},Ll=(e,t,n,r)=>(xee(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var ko,Zy,Xy,Yp,Gp,Kp,Of,h_,m_,kQe=class{constructor(e=[]){Vi(this,ko,void 0),Vi(this,Zy,"ready"),Vi(this,Xy,void 0),Vi(this,Yp,new Set),Vi(this,Gp,new Set),Vi(this,Kp,new Set),this.pushMessage=t=>{Ll(this,ko,In(this,ko).concat(t)),In(this,Of).call(this)},this.popMessage=()=>{Ll(this,ko,In(this,ko).slice(0,-1)),In(this,Of).call(this)},this.replaceMessage=(t,n)=>{Ll(this,ko,[...In(this,ko).slice(0,t),this.snapshot(n),...In(this,ko).slice(t+1)]),In(this,Of).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return In(this,Yp).add(r),()=>{In(this,Yp).delete(r)}},this["~registerStatusCallback"]=t=>(In(this,Gp).add(t),()=>{In(this,Gp).delete(t)}),this["~registerErrorCallback"]=t=>(In(this,Kp).add(t),()=>{In(this,Kp).delete(t)}),Vi(this,Of,()=>{In(this,Yp).forEach(t=>t())}),Vi(this,h_,()=>{In(this,Gp).forEach(t=>t())}),Vi(this,m_,()=>{In(this,Kp).forEach(t=>t())}),Ll(this,ko,e)}get status(){return In(this,Zy)}set status(e){Ll(this,Zy,e),In(this,h_).call(this)}get error(){return In(this,Xy)}set error(e){Ll(this,Xy,e),In(this,m_).call(this)}get messages(){return In(this,ko)}set messages(e){Ll(this,ko,[...e]),In(this,Of).call(this)}};ko=new WeakMap;Zy=new WeakMap;Xy=new WeakMap;Yp=new WeakMap;Gp=new WeakMap;Kp=new WeakMap;Of=new WeakMap;h_=new WeakMap;m_=new WeakMap;var Ff,DL=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),Vi(this,Ff,void 0),this["~registerMessagesCallback"]=(r,s)=>In(this,Ff)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>In(this,Ff)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>In(this,Ff)["~registerErrorCallback"](r),Ll(this,Ff,n)}};Ff=new WeakMap;function yee({experimental_throttle:e,resume:t=!1,...n}={}){const r=j.useRef("chat"in n?n.chat:new DL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DL(n));const o="id"in n?n.id:null,i=j.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=j.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=j.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=j.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=j.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return j.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.addToolResult}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function DQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function vee(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function wee(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function TQe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=s1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=yee({transport:new FI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Oi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:$W(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:vee(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=wee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function See(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=s1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=cn({queryKey:["assistant-profile",n],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Cee({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(M8,{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(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Vw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(fD,{className:r});case"view":return c.jsx(vd,{className:r});case"materialized view":return c.jsx(Iae,{className:r});case"model":return c.jsx(a1,{className:r});case"file":return c.jsx(ki,{className:r});case"dataset":return c.jsx(al,{className:r});case"upload":return c.jsx(pD,{className:r});case"url":return c.jsx(L8,{className:r});default:return c.jsx(i1,{className:r})}}const Nee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(va,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:X("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})]}));Nee.displayName=ds.Input.displayName;const vy=e=>e.label||(e==null?void 0:e.name),ML=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function RQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=j.useState(""),[p,g]=j.useState(""),b=s.filter(S=>{if(!h)return!0;const N=vy(S).toLowerCase(),_=ML(S).toLowerCase(),E=h.toLowerCase();return N.includes(E)||_.includes(E)});j.useEffect(()=>{e||(m(""),g(""))},[e]),j.useEffect(()=>{b.length>0&&!p&&g(vy(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>vy(N)===p);S&&(o.some(_=>"id"in S&&"id"in _?S.id===_.id:S.name===_.name&&S.connectionId===_.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,C=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(FS,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Nee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.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:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs($S,{className:"min-h-60",children:[c.jsx(LS,{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(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(zS,{children:b.map((S,N)=>{const _=v(S),E="id"in S?S.id:`${S.connectionId}-${S.name}`,k=vy(S);return c.jsxs(BS,{value:k,onSelect:()=>{_?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("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:Vw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:ML(S)})]}),_&&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($r,{className:"h-3 w-3 text-background"})})]},E)})})]})]})})}const p_=e=>e.name||e.name,IQe=e=>{const t=p_(e),n="description"in e?e.description:"",r=e.database||"",s=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}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=j.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(On,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Vw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:p_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{side:"top",className:"max-w-xs",children:IQe(d)})]},h)}),u&&c.jsxs(un,{open:s,onOpenChange:o,children:[c.jsx(dn,{asChild:!0,children:c.jsxs(Oe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Aae,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(yt,{className:"h-3 w-3"})})]})}),c.jsx(pn,{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:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.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:Vw(d.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:p_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function jee(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function OQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Oe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),jee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function FQe(e){const{tokenProps:t}=Ge(),n=Q(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(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:s,data:o,isLoading:i,isError:a}=cn({queryKey:["semantic-domains"],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Ge(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=cn({queryKey:["datasets",e],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Ge(),n=Q(x=>x.authToken)||e,{connections:r}=Pi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["databases",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Ge(),n=Q(b=>b.authToken)||e,{connections:r}=Pi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=cn({queryKey:["schemas",s,o],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function kee(e){const{tokenProps:t}=Ge(),n=Q(h=>h.authToken)||e,{connections:r}=Pi(e),s=Ee(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=cn({queryKey:["dataModels",s],queryFn:()=>Hn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var C,S,N;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=j.useState(""),{selectedConnection:s,error:o}=Pi(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=kee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const E=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...E,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(nt,{children:i.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:m}),c.jsxs(rt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(tt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(Mn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(nt,{children:d.map(_=>c.jsx(ge,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function VQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=j.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pD,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(ki,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=j.useState(""),[s,o]=j.useState(""),[i,a]=j.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(jn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(jn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",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(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(i1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Ge(),r=Q(w=>w.authToken)||t,{connections:s}=Pi(t),o=Ee(w=>{var C,S;return(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.connectionId}),i=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ee(w=>{var C,S,N;return(N=(S=(C=w==null?void 0:w.card)==null?void 0:C.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=cn({queryKey:[e,o,i,a],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var C;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(C=w==null?void 0:w.table_type)==null?void 0:C.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function Hw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(yd,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pi(),[i,a]=j.useState(""),[l,u]=j.useState(""),[d,f]=j.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=kee(),w=k=>{const M=s.find(O=>O.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},C=k=>{var R,I;const M=n||[],T=M.some(L=>L.name===k.name&&L.type===k.type);let O;if(T)O=M.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};O=[...M,L]}t==null||t(O)},S=k=>{const M=n||[],T=M.some(R=>R.type==="model"&&R.name===k.name);let O;T?O=M.filter(R=>!(R.type==="model"&&R.name===k.name)):O=[...M,k],t==null||t(O)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),E=j.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const O=N.filter(R=>!k.some(I=>I.name===R.name&&I.type==="table")).map(R=>{var I,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:R.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:R.name,dialect:R.dialect}});M=[...k,...O]}else if(d==="datamodels"){const T=_.filter(O=>!k.some(R=>R.name===O.name&&R.type==="model"));M=[...k,...T]}t(M)},[d,N,_,n,e,t]);return j.useEffect(()=>{r&&r(E)},[r,E]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(nt,{children:s.map(k=>c.jsx(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(al,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Oe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(As,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(qt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(qt,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(nr,{value:"tables",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Hw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[c.jsx(nn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Oe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(nr,{value:"datamodels",className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Hw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(nn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var C;const[l,u]=j.useState(""),d=j.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);j.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=FQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],_=N.some(k=>k.id===S.id&&k.type==="dataset");let E;if(_)E=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};E=[...N,k]}n==null||n(E)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=j.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],_=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),E=[...S,..._];n(E)},[v,r,e==null?void 0:e.semanticDomainId,n]);return j.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(tt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((C=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),c.jsx(nt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(Hw,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Nn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Hw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(_=>_.id===S.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(nn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(de,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function $I({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=j.useState([]),{updateDataSource:u}=lr(),d=Q(M=>M.isVisualEditing),f=Q(M=>M.dashboard.aiContext),{setAiContext:h}=Gt(),m=j.useRef(null),[p,g]=j.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=j.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=j.useCallback(M=>{u({...n,...M})},[n,u]);j.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),j.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),j.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const C=M=>{const T=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(T)},S=()=>{l([])},N=j.useCallback(M=>{l(M)},[]),_=j.useCallback(()=>{m.current&&m.current()},[]),E=j.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,R=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:O,connectionType:R,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Ur,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Wr,{className:"flex-shrink-0",children:[c.jsx(qr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(As,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(cs,{className:"grid w-full grid-cols-2",children:[c.jsx(qt,{value:"database",children:"Direct Source"}),c.jsx(qt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:E}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:E})]})}),c.jsx(OQe,{selectedEntities:a,onDeselectEntity:C}),c.jsx(Rs,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:k,children:[c.jsx($r,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=j.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ba-n;if(l.length>u){Fe.error(`You can only attach ${Ba} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=lJ(l);if(f.forEach(({file:h,error:m})=>{Fe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>jI(m)));e(h)}catch(h){console.error("Failed to process files:",h),Fe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ba}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ba,title:n>=Ba?`Maximum ${Ba} files allowed`:"Attach files",children:c.jsx(aD,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=j.useState(!1),a=j.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=j.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=j.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=j.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=Ba-r;if(h.length>m){Fe.error(`You can only attach ${Ba} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=lJ(h);if(g.forEach(({file:b,error:x})=>{Fe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>jI(x)));t(b),Fe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Fe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg 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(pD,{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:[Ba-r," slot(s) available"]})]})})]})}const LI=j.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=j.useState(!1),[h,m]=j.useState(!1),[p,g]=j.useState(!1),b=j.useRef(null),x=$m();YNe(),qNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:C}=G1(),{queueMessage:S}=Lm(),{addFileAttachment:N,removeFileAttachment:_,clearFileAttachments:E,getFileAttachments:k}=rT(),M=nT(l),T=Ee(H=>H.card.dataSource),O=Q(H=>H.dashboard.aiContext),R=Q(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});j.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=j.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);j.useEffect(()=>{I()},[I]),j.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const L=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(S(l,H,M),t(""),E(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},V=j.useCallback(H=>{const G=lqe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async K=>{const te=await jI(K);N(l,te)}))},[N,l]),$=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),P=j.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),U=j.useCallback(H=>{_(l,H)},[_,l]),B=H=>{if(x.selectedEntities.some(K=>K.id&&K.id===H.id||K.name===H.name)){const K=x.selectedEntities.filter(te=>!(te.id&&te.id===H.id||te.name===H.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,H];y({selectedEntities:K})}},A=H=>{B(H)},Y=H=>{var te;if(!x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}const K="label"in H?H.label:H.name;t(e+`@${K} `),f(!1),(te=b.current)==null||te.focus()},z=H=>{const G=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:G});const te=`@${"label"in H?H.label:H.name}`;e.includes(te)&&t(e.replace(te,"").trim())},q=H=>{const G=new Set(H.map(Z=>Z.id||Z.name)),K=x.selectedEntities.filter(Z=>!G.has(Z.id||Z.name));y({selectedEntities:K});let te=e;H.forEach(Z=>{const se=`@${"label"in Z?Z.label:Z.name}`;te=te.replace(se,"").trim()}),t(te)},W=j.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:R||[],onRemoveEntity:z,onRemoveEntities:q}),M.length>0&&c.jsx(cqe,{files:M,onRemove:U,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:V,onFocus:()=>{I(),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 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ks,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Es,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Eae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(_s,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(RQe,{isOpen:!0,onSelect:B,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:R||[],selectedEntities:x.selectedEntities,onTabComplete:Y,onSelectAll:()=>{R&&y({selectedEntities:R})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Wae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(q8,{className:"size-4"})})]})]})]}),c.jsx($I,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||tC,dialogMode:"aiContext"})]})});LI.displayName="ChatInputWithContext";function Eee({assistantType:e,className:t}){const n=LW(e),{removeFromQueue:r}=Lm();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>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:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function _ee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=LW(e),{dequeueMessage:o}=Lm();j.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Dee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=j.useRef(null),[a,l]=j.useState(!0),[u,d]=j.useState(!0),[f,h]=j.useState(!1),[m,p]=j.useState(0),g=j.useRef(0),b=j.useRef(!1),x=j.useRef(0),y=j.useRef(a),v=j.useRef(),w=j.useRef({key:null,count:0,length:0}),C=j.useCallback(()=>{const E=i.current;return E?E.scrollHeight-E.scrollTop-E.clientHeight:0},[]),S=j.useCallback((E={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=E;if(!M&&!y.current||!a&&!M)return;const O=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const R=i.current;if(!R){b.current=!1,v.current=void 0;return}const I=R.scrollHeight;O==="smooth"&&"scrollTo"in R?R.scrollTo({top:I,behavior:O}):R.scrollTop=I,g.current=R.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=j.useCallback(()=>{const E=i.current;if(!E)return;const k=g.current,M=E.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=C()<=n;d(O),l(O),y.current=O,O&&(h(!1),p(0))},[C,n]),_=j.useCallback(()=>{p(0),h(!1)},[]);return j.useEffect(()=>{y.current=a},[a]),j.useEffect(()=>{const E=i.current;if(!E||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=E?E.scrollTop:0,x.current=E?E.scrollHeight:0;return}g.current=E.scrollTop,x.current=E.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,R=e.length>k.count,I=T!==k.key,L=O>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!R&&(I||L),V=o||F;if(w.current={key:T,count:e.length,length:O},a&&(R||I||L||V)){S({force:!1,instant:V});return}if(!a&&R){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>0?$:1))},[e,S,a,s,o]),j.useEffect(()=>{S({instant:!0})},[S]),j.useEffect(()=>{if(typeof ResizeObserver>"u")return;const E=i.current;if(!E)return;x.current=E.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>T&&S({force:!1,instant:!0})});return k.observe(E),()=>{k.disconnect()}},[S]),j.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:_}}function Mee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=j.useState(r),a=j.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=j.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=j.useCallback(()=>{i(r)},[r]);return j.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Tee(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:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:cJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=j.useState(!1),[a,l]=j.useState(T_),[u,d]=j.useState(!1),[f,h]=j.useState(!1),[m,p]=j.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=gm(),y=j.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:w}=lr(),{addFrame:C,setSelectedFrameId:S,setIsDashboardEditing:N}=Gt(),_=$m(),{setCurrentAIContext:E,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=G1(),{clearQueue:O}=Lm(),{clearFileAttachments:R,getFileAttachments:I}=rT(),L=nT("dashboard"),F=Q(Be=>Be.dashboard.aiContext),V=Ee(Be=>Be.card.dataSource),{assistantProfile:$}=See(),P=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:U,isLoading:B,messages:A,setMessages:Y,status:z,stop:q,errorMessage:W,clearError:H}=TQe(),G=j.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=j.useCallback(()=>{G(!g)},[g,G]);j.useEffect(()=>{if(!g)return;function Be(We){We.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,G]);const[te,Z]=j.useState(""),ee=Be=>{Z(Be.target.value)};function se({sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}){if(console.log("handleAddNewFrame",{sql:Be,data:We,cardTitle:ht,connectionId:qe,cardType:Je,python:Ne,cardConfig:_e,dataSource:Re}),!v)return;const Ve={id:jr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Je==="horizontalBar"?"y":"x"}},type:Je,sql:Be,python:Ne,dataSource:Re,config:_e,connectionId:qe},it={id:jr(),cards:[Ve],activeCardId:Ve.id};N(!0),C(v,it,"end"),S(it.id)}const ce=Be=>{Be.preventDefault();const We=te.trim();if(!We&&L.length===0)return;const ht=[];We&&ht.push({type:"text",text:We}),L.forEach(qe=>{qe.data&&ht.push({type:"file",mediaType:qe.type,filename:qe.name,url:`data:${qe.type};base64,${qe.data}`})}),U({role:"user",parts:ht}),Z(""),R("dashboard"),le({force:!0})};j.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),_ee({assistantType:"dashboard",status:z,isLoading:B,sendMessage:U});const{hasActiveTools:re}=Tee(A),{visibleMessages:fe,hasMoreMessages:Ce,totalMessageCount:ie,loadMoreMessages:pe,resetMessageWindow:ue}=Mee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ve,isAtBottom:Se,hasNewMessages:Qe,newMessageCount:Ke,scrollToBottom:le,handleScroll:xe,resetNewMessageCount:Le}=Dee(fe,{threshold:50,behavior:"smooth",isStreaming:B});function me(Be){Ie();const We={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};U(We)}function ke(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]})}function $e(Be){Ie(),U({role:"user",parts:[{type:"text",text:Be}]}),le({force:!0})}const He=j.useCallback(async()=>{const Be=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),Fe.success("Conversation copied")}catch(We){console.error("Failed to copy conversation",We),Fe.error("Unable to copy conversation")}},[A]);function Ie(){_.selectedEntities.length===0&&E({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const st=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Be=>Be.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function pt(){return c.jsxs(mm,{children:[c.jsx(pm,{asChild:!0,children:c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(om,{className:"size-3.5"})})}),c.jsxs(Zd,{align:"end",children:[c.jsx(eh,{children:"Options"}),c.jsx(Cd,{}),c.jsx(Qp,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Qp,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Qp,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const It=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl 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:[je(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&pt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(iD,{className:"size-4"}):c.jsx(l1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{Y([]),O("dashboard"),H(),ue()},children:c.jsx(c1,{className:"size-4"})}),c.jsx(dc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Cl,{"data-role":"dashboard-assistant-scroll-area",ref:ve,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[Ce&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ie-fe.length)," ","more messages (",ie-fe.length," ","hidden)"]})}),c.jsx(dJ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:se,onQuickReply:$e,disableQuickReplies:B}),!re&&c.jsx(uJ,{status:z,errorMessage:W})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Se&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{le({force:!0}),Le()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ks,{className:"h-4 w-4"}),Qe&&Ke>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:Ke>9?"9+":Ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&st&&c.jsx(fJ,{onClick:me,placeholders:KQe}),c.jsx("div",{children:st&&$&&c.jsx(Cee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:ke})}),c.jsx(Eee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(LI,{ref:y,setInput:Z,stop:q,input:te,handleInputChange:ee,handleSubmit:Be=>{Ie(),ce(Be),le({force:!0})},isLoading:B,status:z,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx($I,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||tC,dialogMode:"aiContext"})]});return g&&s?Pn.createPortal(c.jsx("div",{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:It})}),s):It}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);j.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Fe.success("Card copied to clipboard"),m.preventDefault()):p&&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();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=_R(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Fe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}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)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(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 JQe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function eJe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",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 tJe(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 nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Ur,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Wr,{children:[c.jsx(qr,{children:i||"Insight Detail"}),c.jsx(Is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(xZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(wZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function rJe(){const e=Pt(w=>w.interactionStates),t=Pt(w=>w.setInteractionState),n=Pt(w=>w.clearLastInteractionEvent),r=Pt(w=>w.replaceCardWithInsight),s=Pt(w=>w.setPendingDrillThrough),o=Pt(w=>w.pendingDrillThrough),i=Pt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=$b(),d=Q(w=>w.dashboard),f=Q(w=>w.filterValues),{data:h,isLoading:m}=ahe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=j.useState({open:!1,insightId:""}),b=SZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=j.useRef(new Set),y=j.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:C,contextMode:S})=>{g({open:!0,insightId:w,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:C,filters:S,contextMode:N})=>{r(w,C,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_})=>{const k={sourceCardId:oa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Po(),appliedClickFilters:[k],contextMode:C,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:_};t(oa,M)}}),[a,r,f,l,d,s,t]);j.useEffect(()=>{Object.entries(e).forEach(([w,C])=>{if(C!=null&&C.lastInteractionEvent){const S=C.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{QQe(S,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),j.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&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-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(Mn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,w,C;const e=Pt(S=>S.interactionStates[oa]),t=Q(S=>S.actions.goBackFromDrill),n=Q(S=>S.actions.clearDrillContext),{selectDashboard:r}=$b(),[s,o]=j.useState({x:16,y:16}),[i,a]=j.useState(!1),l=j.useRef({x:0,y:0});j.useEffect(()=>{if(!i)return;const S=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.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||!((C=e.appliedClickFilters)!=null&&C.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,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((S,N)=>{const _=S.field.label||S.field.name,E=String(S.value);return c.jsxs(Oe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",E]},N)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(g8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Ree(){var Z;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=gm(),s=((Z=n==null?void 0:n.cardDisplay)==null?void 0:Z.mode)==="print",o=j.useRef(null),i=j.useRef(null),[a,l]=j.useState(!1),u=id(ee=>ee.setFullscreen),d=id(ee=>ee.setPanelOpen),f=id(ee=>ee.setContainer),h=PW("dashboard"),m=OW(),p=FW("dashboard"),g=h.isOpen,b=m==="dashboard",x=Q(ee=>ee.isVisualEditing),y=Q(ee=>ee.themeStyle),v=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.sheets}),w=Q(ee=>ee.isDashboardEditing),C=Q(ee=>ee.selectedSheetId),S=Q(ee=>{var se;return(se=ee.dashboard)==null?void 0:se.id}),N=Q(ee=>ee.isDashboardPanelOpen),_=Q(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:E,setDefaultSheetId:k,clearDefaultSheetId:M}=d8(S),[T,O]=j.useState(null);j1(Ft.DASHBOARD);const{setSelectedSheetId:R,setSheetTitle:I,addSheet:L,setSheets:F}=Gt();XQe(i);const{setActiveAssistantType:V}=G1();j.useEffect(()=>{if(S){const ee=E();O(ee)}},[S,E]),j.useEffect(()=>{g?V("dashboard"):m==="dashboard"&&u(null)},[g,V,m,u]);function $(ee){var se,ce;ee?((se=o.current)==null||se.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(ce=o.current)==null||ce.resize(0),V(null))}function P(){const ee={id:jr(),title:"New Sheet"};L(ee),R(ee.id)}function U(ee,se){if(!S)return;T===ee?(M(),O(null),Fe.success("Default sheet cleared")):(k(ee),O(ee),Fe.success(`"${se}" set as default sheet`))}function B(ee){ee<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const Y=(ee,se)=>{ee.dataTransfer.setData("tabIndex",se.toString())},z=ee=>{ee.preventDefault()},q=(ee,se)=>{const ce=ee.dataTransfer.getData("tabIndex");if(ce===se.toString())return;const re=Array.from(v||[]),[fe]=re.splice(parseInt(ce),1);re.splice(se,0,fe),F(re)},W=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var ee,se;if(v&&v.length>1||w)return c.jsxs(cs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&W&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!N)},className:"h-8 p-2",children:N?c.jsx(_8,{className:"h-4 w-4"}):c.jsx(D8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ce,re)=>{const fe=C===ce.id,Ce=T===ce.id;return c.jsxs(qt,{draggable:!0,onDragStart:ie=>Y(ie,re),onDragOver:z,onDrop:ie=>q(ie,re),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>R(ce.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ce.id,children:[c.jsx(ib,{enabled:w&&fe,text:ce.title,onSave:ie=>I(ce.id,ie),children:ce.title},ce.id),!w&&fe&&c.jsx("div",{title:Ce?"Clear default sheet":"Set as default sheet",children:c.jsx(dD,{className:X("ml-1 size-3 cursor-pointer transition-all",Ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ie=>{ie.stopPropagation(),U(ce.id,ce.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ce.id)}),w&&c.jsx("div",{style:{borderRadius:(se=(ee=y==null?void 0:y.chart)==null?void 0:ee.options)==null?void 0:se.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(ee=>c.jsx(nr,{style:{backgroundColor:A()},className:X("mt-0",{}),value:ee.id,children:c.jsx(C8e,{sheet:ee})},ee.id))})}function K(){var ee;return c.jsxs(As,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:se=>{R(se)},value:C||((ee=v==null?void 0:v[0])==null?void 0:ee.id),children:[H(),c.jsx(Cl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(nze,{open:a,setOpen:l})]})}const te=j.useCallback(ee=>{f("dashboard",ee)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(YX,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(qE,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(tze,{open:g,onTabClick:$,withHandle:!0}),c.jsx(qE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:ee=>u(ee?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:te,className:X("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(uD,{className:"h-5 w-5"})})})]})]}):null}function zI({children:e}){return c.jsx(Ca,{style:{height:"100%",width:"100%"},children:c.jsx(qie,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(On,{delayDuration:0,children:e})})})}function Iee({children:e,preferences:t}){const{currentUser:n}=Ts(),r=j.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx($9.Provider,{value:r,children:c.jsx(RR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Aee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Da,{FallbackComponent:SS,children:c.jsx(J_,{dashboardProps:e,children:c.jsx(zI,{children:c.jsx(Iee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(sT,{...e,type:"dashboard",children:c.jsx(Ree,{})})})})})})})}function BI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return cn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Hn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Pee(e,t,n){if(t==="source")return{isValid:!0};const r=Ir(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Oee(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Fee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=BI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=lr(),h=Ee(R=>R.card.type),m=e==null?void 0:e.id,p=j.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=j.useCallback((R,I)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:I});break}case"metrics":{r(m,{metricColumns:I});break}case"pivotBy":{r(m,{pivotByColumns:I});break}case"sortBy":{r(m,{sortByColumns:I});break}}},[m,r]),b=j.useCallback((R,I,L)=>{if(!m)return;const V=p(R)[I];if(V)switch(R){case"groupBy":s(m,V.id,{label:L});break;case"metrics":o(m,V.id,{label:L});break;case"pivotBy":i(m,V.id,{label:L});break;case"sortBy":a(m,V.id,{label:L});break}},[m,p,s,o,i,a]),x=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aggregate:I,label:hU(F.name,I)})},[m,p,o]),y=j.useCallback((R,I,L)=>{if(!m)return;const V=p("groupBy")[R];if(!V)return;const $={dateFormat:I};I==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,V.id,$)},[m,p,s]),v=j.useCallback((R,I)=>{if(!m)return;const F=p("groupBy")[R];F&&s(m,F.id,{granularity:I})},[m,p,s]),w=j.useCallback((R,I)=>{if(!m)return;const F=p("metrics")[R];F&&o(m,F.id,{aliasTemplate:I})},[m,p,o]),C=j.useCallback((R,I)=>{if(console.log("handleValueAliasesChange",R,I),!m)return;console.log("handleValueAliasesChange",R,I);const F=p("metrics")[R];F&&(console.log("handleValueAliasesChange",I),o(m,F.id,{valueAliases:I}))},[m,p,o]),S=j.useCallback(R=>{if(!m)return;if(p("metrics").length===0){Fe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:R})},[m,r,p]),N=j.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),_=j.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),E=j.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),k=j.useCallback(R=>{m&&r(m,{targetValue:R})},[m,r]),M=j.useCallback(R=>{var U;if(!m)return;const I=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=bCe(R,I,{joinPlan:(U=e==null?void 0:e.config)==null?void 0:U.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&uU();return}const F=vCe(R,I,h);if(!F){Fe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=Pee(R,F,h);if(!V.isValid){Fe.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=p(F);if(dU(R,$))return;const P=mU(R,F,$);if(P){const B=[...$,P];g(F,B),F==="metrics"&&Oee(h,e==null?void 0:e.config,r,m,B)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),T=j.useCallback((R,I)=>{if(!m)return;const F=p(R)[I];if(F){if(R!=="sortBy"){const V=p("sortBy"),$=V.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==V.length&&r(m,{sortByColumns:$})}switch(R){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:C,removeField:T,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleKpiTargetValueChange:k,cardType:h}};function Vx(e,t){var ke,$e,He,Ie,st;const{tokenProps:n}=Ge(),r=Qs(),s=Ge().authToken||e,o=Ee(je=>je.selectedConnectionId),i=Ee(je=>je.card),{queryKey:a}=upe(i),l=Ee(je=>je.selectedDatamodelId),u=Ee(je=>je.isDevMode),d=Ee(je=>je.selectedDatabaseName),f=Ee(je=>je.selectedSchemaName),h=Ee(je=>je.selectedTableName),m=Ee(je=>je.actions.setSelectedConnectionId),p=Ee(je=>je.actions.setSelectedDatamodelId),g=Ee(je=>je.actions.setSelectedDatabaseName),b=Ee(je=>je.actions.setSelectedSchemaName),x=Ee(je=>je.actions.setSelectedTableName);Ee(je=>je.actions.setCardSql);const{setQueryConfig:y}=lr();function v(je){var It;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((It=E==null?void 0:E.capabilities)==null?void 0:It.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:C,connectionsData:S,isConnectionsLoading:N,isConnectionsError:_,selectedConnection:E}=Pi(e),{refetch:k,data:M,isLoading:T,isError:O}=cn({queryKey:["models",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),R=E==null?void 0:E.type,I=(E==null?void 0:E.type)==="API"||(E==null?void 0:E.type)==="S3",{data:L,isLoading:F,isFetching:V,isError:$,refetch:P}=cn({queryKey:["databases",o],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(R)}),{data:U,isLoading:B,isFetching:A,isError:Y,refetch:z}=cn({queryKey:["schemas",o,d],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:q,isLoading:W,isFetching:H,isError:G,refetch:K}=cn({queryKey:["tables",o,d,f],queryFn:()=>Hn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(R)}),{columns:te,isColumnsLoading:Z,isColumnsFetching:ee,isColumnsError:se,refetchColumns:ce}=pU(e);j.useEffect(()=>{(R==="S3"||R==="API")&&(g(""),b(""),p(""),R==="API"&&x("api"))},[R,x,g,b,p]);const re=(E==null?void 0:E.type)==="API"?(ke=E==null?void 0:E.type)==null?void 0:ke.toLowerCase():h||"",fe=I?"":f||"";function Ce(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ie(je){b(je),x("")}function pe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function ue(je){m(je)}function ve(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&(($e=L==null?void 0:L.databases)==null?void 0:$e.length)>0,U&&((He=U==null?void 0:U.schemas)==null?void 0:He.length)>0;const Se=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Qe=(Ie=M==null?void 0:M.datamodels)==null?void 0:Ie.map(je=>({id:je.id,name:je.name})),Ke=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),le=U==null?void 0:U.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=q==null?void 0:q.tables.map(je=>({id:je.table_name,name:je.table_name})),Le=(st=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:st.name,me=nv({schemaName:fe,tableName:re,modelName:Le,connectionType:R,databaseName:d||""});return{connectionItems:Se,selectedConnectionId:o,selectedConnection:E,isConnectionsLoading:N,isConnectionsError:_,modelItems:Qe,selectedDatamodelId:l,selectedDatamodelName:Le,isModelsLoading:T,isModelsError:O,selectedDatabaseName:d,databaseItems:Ke,isDatabasesLoadingOrFetching:F||V,isDatabaseError:$,schemaItems:le,selectedSchemaName:f,isSchemaLoadingOrFetching:B||A,isSchemaError:Y,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:te,isColumnsLoadingOrFetching:Z||ee,isColumnsError:se,isNonDbConnection:I,connectionType:R,tableName:re,formattedTableName:me,schemaName:fe,refetchConnections:C,refetchModels:k,refetchDatabases:P,refetchSchemas:z,refetchTables:K,refetchColumns:ce,handleConnectionChange:ue,handleDatamodelChange:ve,handleDatabaseChange:pe,handleSchemaChange:ie,handleTableChange:Ce}}function wy(e){return`${e}-${jr()}`}function TL(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function lJe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function VI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function $ee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lee(){const e=Ee(S=>S.sqlGen),t=Ee(S=>S.isDevMode),n=Ee(S=>S.card.dataSource),r=Ee(S=>{var N,_;return(_=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=VI(n),a=$ee(n),l=Ee(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Vx(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var _;if(!t)return;const N=y(S);if(t&&a&&s){const E=O_(N,e);m(E);const k=(_=b==null?void 0:b.find(T=>T.id===l))==null?void 0:_.name,M=P_(E,fi(o||""),fi(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Ab(N.data_type))if(r&&r.length>0){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type};d(E)}else{const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(E)}if(Si(N.data_type)){const E={...N,role:"groupby",id:wy(N.column_name),name:N.column_name,type:N.data_type,label:lJe(N.column_name,"month"),granularity:"month"};d(E)}if(wi(N.data_type)){const E={...N,role:"metric",id:wy(N.column_name),name:N.column_name,label:TL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=nv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>wi(S.dataType)}}function cJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=fi(e),u=fi(t||""),d=fi(n||""),f=fi(r);let h=Jw({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Eg}.${i}.${l}`,h=`${Eg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function zee(){const e=Ee(p=>p.selectedConnectionId),t=Ee(p=>p.selectedDatamodelId),n=Ee(p=>p.selectedDatabaseName),r=Ee(p=>p.selectedSchemaName),s=Ee(p=>p.selectedTableName),o=Q(p=>p.dashboard.filters)||[],i=Q(p=>p.selectedSheetId),a=Q(p=>p.actions.addFilter),l=Q(p=>p.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Vx();function m(p,g="sheet",b){var _;const x=(_=d==null?void 0:d.find(E=>E.id===t))==null?void 0:_.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:C,formattedDatabase:S}=cJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=Kke(o,y,C,n||"",S,i):N=o==null?void 0:o.find(E=>E.column===y&&E.table===C&&(E.database===S||E.database===n)),N)u(N.id),l(N.id);else{const E=jr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,w)}),E):(a({id:E,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:NE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),E)}}return{assignFilter:m}}function uJe({column:e}){const[t,n]=j.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=VI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Vx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),m=Ee(x=>x.actions.setRunSql),p=$ee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=O_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const C=P_(v,fi(o||""),fi(s),w||"",d,i||"");C&&(h(C),m(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return p?c.jsxs(Pm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Om,{asChild:!0,children:c.jsx(om,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(rf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function dJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function fJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Ee(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=Q(q=>q.dashboard.filters),u=Q(q=>q.selectedSheetId),d=Q(q=>q.actions.removeFilter),{removeFilterValues:f}=Gt(),{assignFilter:h}=zee(),m=t==="filter"?Jc(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var W;return q.title===e.name||((W=q.column)==null?void 0:W.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,C]=j.useState(!1),[S,N]=j.useState(null),{attributes:_,listeners:E,setNodeRef:k,transform:M,transition:T,isDragging:O}=PS({id:e.id,disabled:a}),[R,I]=j.useState(!1),L=Ee(q=>q.card),{handleFieldClick:F}=Fee(L),{handleDevModeFieldClick:V,isNumberField:$}=Lee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),C(!1)},U=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:q,field:e}),C(!0)):h(q,"sheet",e)}else o?V(e):F(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},A={transform:Mi.Transform.toString(M),transition:T},z=(()=>{if(!n||i)return{};const W={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:A,...a?{}:_,...a?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:U,children:[lb(e.dataType),c.jsx(On,{children:c.jsxs(un,{children:[c.jsx(dn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${R?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(pn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(dJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(uJe,{column:B})})]}),R&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(vo,{className:"",children:c.jsxs(ji,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Y8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Oe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Gb,{open:w,onOpenChange:C,children:c.jsxs(bm,{children:[c.jsxs(xm,{children:[c.jsx(vm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(wm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(ym,{children:[c.jsx(Cm,{children:"Cancel"}),c.jsx(Sm,{onClick:P,children:"Remove Filter"})]})]})})]})}const hJe="SEMAPHOR_CALCULATED_FIELD",mJe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function Bee(e){return!!e.expression}function pJe(e){return!!e.expression}function gJe(e){return!!e.expression}var Vee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(Vee||{}),_l="Accordion",bJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[HI,xJe,yJe]=d1(_l),[oC]=_r(_l,[yJe,MZ]),UI=MZ(),Hee=j.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(HI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(CJe,{...o,ref:t}):c.jsx(SJe,{...s,ref:t})})});Hee.displayName=_l;var[Uee,vJe]=oC(_l),[Wee,wJe]=oC(_l,{collapsible:!1}),SJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=zr({prop:n,defaultProp:r,onChange:s});return c.jsx(Uee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:j.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(qee,{...i,ref:t})})})}),CJe=j.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=zr({prop:n,defaultProp:r,onChange:s}),l=j.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=j.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Uee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Wee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(qee,{...o,ref:t})})})}),[NJe,iC]=oC(_l),qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=j.useRef(null),l=bt(a,t),u=xJe(n),f=qd(s)==="ltr",h=De(e.onKeyDown,m=>{var _;if(!bJe.includes(m.key))return;const p=m.target,g=u().filter(E=>{var k;return!((k=E.ref.current)!=null&&k.disabled)}),b=g.findIndex(E=>E.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,C=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?C():S());break;case"ArrowDown":o==="vertical"&&C();break;case"ArrowLeft":o==="horizontal"&&(f?S():C());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(_=g[N].ref.current)==null||_.focus()});return c.jsx(NJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(HI.Slot,{scope:n,children:c.jsx(Ue.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Uw="AccordionItem",[jJe,WI]=oC(Uw),Yee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=iC(Uw,n),i=vJe(Uw,n),a=UI(n),l=or(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(jJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(IZ,{"data-orientation":o.orientation,"data-state":Jee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Yee.displayName=Uw;var Gee="AccordionHeader",Kee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Gee,n);return c.jsx(Ue.h3,{"data-orientation":s.orientation,"data-state":Jee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Kee.displayName=Gee;var g_="AccordionTrigger",Zee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(g_,n),i=wJe(g_,n),a=UI(n);return c.jsx(HI.ItemSlot,{scope:n,children:c.jsx(E$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Zee.displayName=g_;var Xee="AccordionContent",Qee=j.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=iC(_l,n),o=WI(Xee,n),i=UI(n);return c.jsx(_$e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Qee.displayName=Xee;function Jee(e){return e?"open":"closed"}var kJe=Hee,EJe=Yee,_Je=Kee,ete=Zee,tte=Qee;const nte=kJe,qI=D.forwardRef(({className:e,...t},n)=>c.jsx(EJe,{ref:n,className:X("border-b",e),...t}));qI.displayName="AccordionItem";const YI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(_Je,{className:"flex",children:c.jsxs(ete,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ks,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));YI.displayName=ete.displayName;const GI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));GI.displayName=tte.displayName;function rte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var I,L,F,V;const[r,s]=j.useState(""),[o,i]=j.useState("all");Ee($=>$.isDevMode);const a=Ee($=>$.card.dataSource),l=Ee($=>$.card.config),u=Ee($=>$.card),{autoJoinMetadata:d}=pa(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=zM(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=BI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(I=l==null?void 0:l.joinPlan)==null?void 0:I.baseEntity)==null||L.name,(V=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||V.name,Lee();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&Bee($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Ir($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},C=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const U=P.qualifiedEntityName||"Other Fields";return $[U]||($[U]={label:q_(P.entityName),fields:[]}),$[U].fields.push(P),$},{}),N=Object.keys(C),_=y.filter($=>v($)==="dimensions").length,E=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",T=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:c.jsx(Rc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",T),children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const O=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",R=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",O,R),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(va,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Nn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(yt,{className:"size-3.5"})})]}),M&&c.jsx(As,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(qt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(qt,{value:"dimensions",className:"text-xs",children:[c.jsx(a1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(qt,{value:"metrics",className:"text-xs",children:[c.jsx(sm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(qt,{value:"calculated",className:"text-xs",children:[c.jsx(eD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Cl,{className:"min-h-0 overflow-auto",children:[c.jsx(nte,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(C).map(([$,P])=>{const U=h.find(B=>B.entityName===$)||{entityName:$,label:P.label};return c.jsxs(qI,{value:$,className:"border-none",children:[c.jsx(YI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:U.label||U.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:U.label||U.entityName}),c.jsx(Oe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(GI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(B=>{const A=BM(B,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(fJe,{field:B,context:e,fieldState:A,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},B.id)})})})]},$)})}),Object.keys(C).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(C).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function ste({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(rte,{context:e})," "]})}function ote(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();j.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=VI(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function DJe(){ote();const e=Q(l=>l.selectedSheetId),t=Q(l=>l.selectedFrameId),n=Q(l=>l.dashboard),r=Q(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=lr(),i=Ee(l=>l.card.dataSource);return j.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function MJe(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=DJe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(NZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(al,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(IS,{collisionDetection:DS,children:c.jsx(AS,{items:[],strategy:YR,children:c.jsx(ste,{context:"filter"})})})})]})}function TJe(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("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(AR,{filter:r}),c.jsx(Cx,{filter:r})]},r.id))}):null}function RJe(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(TJe,{}),c.jsx(Ree,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(MJe,{})})]})}const IJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CycUpkzN.js"))),AJe=j.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-QX1EfVIC.js"))),PJe=j.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CUnn97AA.js"))),OJe=j.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Chg6-H5n.js")).then(e=>({default:e.ResourceManagementPanel})));function FJe({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(l=>l.isDashboardPanelOpen),s=Q(l=>l.isVisualEditing),o=Q(l=>l.showDashboardJSON),i=Q(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Da,{FallbackComponent:SS,children:c.jsxs(J_,{dashboardProps:n,children:[c.jsx(Cfe,{}),c.jsx(zI,{children:c.jsxs(Iee,{preferences:a,children:[o&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(PJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(IJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(OJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(sT,{...n,type:"dashboard",children:[s&&c.jsx(j.Suspense,{fallback:null,children:c.jsx(AJe,{})}),c.jsx(RJe,{})]})})]})]})]})})]})})}var $Je=Object.defineProperty,LJe=(e,t,n)=>t in e?$Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Sy=(e,t,n)=>LJe(e,typeof t!="symbol"?t+"":t,n);const zJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},BJe={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}},VJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},HJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},UJe={stringify:e=>e,parse:e=>e},n2={string:UJe,number:HJe,boolean:zJe,function:BJe,json:VJe};function WJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const Cy=Symbol.for("r2wc.render"),Ny=Symbol.for("r2wc.connected"),yu=Symbol.for("r2wc.context"),Aa=Symbol.for("r2wc.props");function qJe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WJe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Sy(this,o,!0),Sy(this,s),Sy(this,r,{}),Sy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Aa].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?n2[x]:null;y!=null&&y.parse&&b&&(this[Aa][p]=y.parse(b,g,this))}for(const p of a)this[Aa][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Ny]=!0,this[Cy]()}disconnectedCallback(){this[Ny]=!1,this[yu]&&n.unmount(this[yu]),delete this[yu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?n2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Aa][x]=v.parse(b,p,this),this[Cy]())}[(o=Ny,s=yu,r=Aa,Cy)](){this[Ny]&&(this[yu]?n.update(this[yu],this[Aa]):this[yu]=n.mount(this.container,e,this[Aa]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Aa][m]},set(b){this[Aa][m]=b;const x=g?n2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Cy]()}})}return h}function YJe(e,t,n){const r=p2(e),s=j.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function GJe({root:e,ReactComponent:t},n){const r=j.createElement(t,n);e.render(r)}function KJe({root:e}){e.unmount()}function ZJe(e,t={}){return qJe(e,t,{mount:YJe,update:GJe,unmount:KJe})}const XJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},QJe=ZJe(Aee,{props:XJe});function JJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function IL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?RL(Object(n),!0).forEach(function(r){JJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function eet(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function tet(e,t){if(e==null)return{};var n=eet(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function net(e,t){return ret(e)||set(e,t)||oet(e,t)||iet()}function ret(e){if(Array.isArray(e))return e}function set(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function oet(e,t){if(e){if(typeof e=="string")return AL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return AL(e,t)}}function AL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function iet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1072
1072
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aet(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function OL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?PL(Object(n),!0).forEach(function(r){aet(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):PL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function cet(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function Zp(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function Ww(e){return{}.toString.call(e).includes("Object")}function uet(e){return!Object.keys(e).length}function Nb(e){return typeof e=="function"}function det(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function fet(e,t){return Ww(t)||vc("changeType"),Object.keys(t).some(function(n){return!det(e,n)})&&vc("changeField"),t}function het(e){Nb(e)||vc("selectorType")}function met(e){Nb(e)||Ww(e)||vc("handlerType"),Ww(e)&&Object.values(e).some(function(t){return!Nb(t)})&&vc("handlersType")}function pet(e){e||vc("initialIsRequired"),Ww(e)||vc("initialType"),uet(e)&&vc("initialContent")}function get(e,t){throw new Error(e[t]||e.default)}var bet={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},vc=Zp(get)(bet),jy={changes:fet,selector:het,handler:met,initial:pet};function xet(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};jy.initial(e),jy.handler(t);var n={current:e},r=Zp(wet)(n,t),s=Zp(vet)(n),o=Zp(jy.changes)(e),i=Zp(yet)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return jy.selector(u),u(n.current)}function l(u){cet(r,s,o,i)(u)}return[a,l]}function yet(e,t){return Nb(t)?t(e.current):t}function vet(e,t){return e.current=OL(OL({},e.current),t),t}function wet(e,t,n){return Nb(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var Cet={create:xet},Net={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function jet(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function ket(e){return{}.toString.call(e).includes("Object")}function Eet(e){return e||FL("configIsRequired"),ket(e)||FL("configType"),e.urls?(_et(),{paths:{vs:e.urls.monacoBase}}):e}function _et(){console.warn(ite.deprecation)}function Det(e,t){throw new Error(e[t]||e.default)}var ite={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1073
1073
  You are using deprecated way of configuration.
1074
1074