react-semaphor 0.1.226 → 0.1.227
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-controls-WfvdR-3x.js → dashboard-controls-CD8QDWP8.js} +1 -1
- package/dist/chunks/{dashboard-controls-CJwFENq_.js → dashboard-controls-CuhYK1eE.js} +5 -5
- package/dist/chunks/{dashboard-json-0FgkPBOf.js → dashboard-json--PxGe-sz.js} +1 -1
- package/dist/chunks/{dashboard-json-BMMl4vZv.js → dashboard-json-BVzVl07t.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-7w6MgsZa.js → dashboard-summary-settings-dialog-BSwM7ZET.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CLk_W4NO.js → dashboard-summary-settings-dialog-BWJp5oq2.js} +1 -1
- package/dist/chunks/edit-dashboard-visual-BBs3ADo3.js +182 -0
- package/dist/chunks/{edit-dashboard-visual-uziE-2Vl.js → edit-dashboard-visual-Dg73XwQP.js} +4418 -4371
- package/dist/chunks/{editor-action-buttons-NWIn7xZ4.js → editor-action-buttons-DbNBN70-.js} +1 -1
- package/dist/chunks/{editor-action-buttons-CICb1HLY.js → editor-action-buttons-E_EgfoLz.js} +2 -2
- package/dist/chunks/{index-BiMLZ1zZ.js → index-BDupICe6.js} +7 -7
- package/dist/chunks/{index-buJawQQ7.js → index-BW9Wx7y1.js} +2 -2
- package/dist/chunks/{notification-bell-6MhrczIG.js → notification-bell-CClk_EcU.js} +1 -1
- package/dist/chunks/{notification-bell-S-eySEPf.js → notification-bell-bTY51lWO.js} +3 -3
- package/dist/chunks/{resource-management-panel-DN4YQNga.js → resource-management-panel-D5niXqb5.js} +1 -1
- package/dist/chunks/{resource-management-panel-B1vRjfy8.js → resource-management-panel-D7cts-3B.js} +3 -3
- package/dist/chunks/{use-role-aware-display-preferences-D5Ybe0jJ.js → use-role-aware-display-preferences-BnHxHVL1.js} +1 -1
- package/dist/chunks/{use-role-aware-display-preferences-DOG-ac3T.js → use-role-aware-display-preferences-C0M8EODv.js} +1 -1
- package/dist/chunks/{use-visual-utils-B6rg3-pY.js → use-visual-utils-BgbrOsFH.js} +1 -1
- package/dist/chunks/{use-visual-utils-BRYLN4eh.js → use-visual-utils-wID9j0pU.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/edit-dashboard-visual-DSuO96w0.js +0 -177
|
@@ -1085,7 +1085,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1085
1085
|
|
|
1086
1086
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
1087
1087
|
|
|
1088
|
-
`)}})}});var Vtt=Pet(()=>yre(Bi([wr({type:rn("text-start"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("text-delta"),id:kt(),delta:kt(),providerMetadata:zr.optional()}),wr({type:rn("text-end"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("error"),errorText:kt()}),wr({type:rn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:Do().optional(),dynamic:Do().optional()}),wr({type:rn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),wr({type:rn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:Fa(),providerExecuted:Do().optional(),providerMetadata:zr.optional(),dynamic:Do().optional()}),wr({type:rn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:Fa(),providerExecuted:Do().optional(),providerMetadata:zr.optional(),dynamic:Do().optional(),errorText:kt()}),wr({type:rn("tool-output-available"),toolCallId:kt(),output:Fa(),providerExecuted:Do().optional(),dynamic:Do().optional(),preliminary:Do().optional()}),wr({type:rn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:Do().optional(),dynamic:Do().optional()}),wr({type:rn("reasoning-start"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:zr.optional()}),wr({type:rn("reasoning-end"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:zr.optional()}),wr({type:rn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:zr.optional()}),wr({type:rn("file"),url:kt(),mediaType:kt(),providerMetadata:zr.optional()}),wr({type:mre(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:Fa(),transient:Do().optional()}),wr({type:rn("start-step")}),wr({type:rn("finish-step")}),wr({type:rn("start"),messageId:kt().optional(),messageMetadata:Fa().optional()}),wr({type:rn("finish"),finishReason:dre(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Fa().optional()}),wr({type:rn("abort")}),wr({type:rn("message-metadata"),messageMetadata:Fa()})])));function Utt(e){return e.type.startsWith("data-")}function Ere(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]=Ere(o,s):n[r]=s}return n}function Htt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function _re(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await vS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await vS({text:Htt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ew(e){return e.type.startsWith("tool-")}function Wtt(e){return e.type==="dynamic-tool"}function bM(e){return Ew(e)||Wtt(e)}function c8(e){return e.type.split("-").slice(1).join("-")}function qtt({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 Ytt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(S){const N=u.message.parts.filter(Ew).find(k=>k.toolCallId===S);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(S){const N=u.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===S);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(S){var C;const N=u.message.parts.find(M=>Ew(M)&&M.toolCallId===S.toolCallId),k=S,E=N;N!=null?(N.state=S.state,E.input=k.input,E.output=k.output,E.errorText=k.errorText,E.rawInput=k.rawInput,E.preliminary=k.preliminary,E.providerExecuted=(C=k.providerExecuted)!=null?C:N.providerExecuted,k.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:`tool-${S.toolName}`,toolCallId:S.toolCallId,state:S.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function y(S){var C,N;const k=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===S.toolCallId),E=S,M=k;k!=null?(k.state=S.state,M.toolName=S.toolName,M.input=E.input,M.output=E.output,M.errorText=E.errorText,M.rawInput=(C=E.rawInput)!=null?C:M.rawInput,M.preliminary=E.preliminary,M.providerExecuted=(N=E.providerExecuted)!=null?N:k.providerExecuted,E.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:S.toolName,toolCallId:S.toolCallId,state:S.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(S){if(S!=null){const C=u.message.metadata!=null?Ere(u.message.metadata,S):S;t!=null&&await s8({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const S={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=S,u.message.parts.push(S),d();break}case"text-delta":{const S=u.activeTextParts[a.id];S.text+=a.delta,S.providerMetadata=(f=a.providerMetadata)!=null?f:S.providerMetadata,d();break}case"text-end":{const S=u.activeTextParts[a.id];S.state="done",S.providerMetadata=(h=a.providerMetadata)!=null?h:S.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const S={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=S,u.message.parts.push(S),d();break}case"reasoning-delta":{const S=u.activeReasoningParts[a.id];S.text+=a.delta,S.providerMetadata=(m=a.providerMetadata)!=null?m:S.providerMetadata,d();break}case"reasoning-end":{const S=u.activeReasoningParts[a.id];S.providerMetadata=(p=a.providerMetadata)!=null?p:S.providerMetadata,S.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 S=u.message.parts.filter(Ew);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:S.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const S=u.partialToolCalls[a.toolCallId];S.text+=a.inputTextDelta;const{value:C}=await _re(S.text);S.dynamic?y({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:C}):b({toolCallId:a.toolCallId,toolName:S.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,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):b({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,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):b({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 S=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-available",input:S.input,output:a.output,preliminary:a.preliminary})}else{const S=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:c8(S),state:"output-available",input:S.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const S=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-error",input:S.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const S=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:c8(S),state:"output-error",input:S.input,rawInput:S.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),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(Utt(a)){(n==null?void 0:n[a.type])!=null&&await s8({value:a.data,schema:n[a.type]});const S=a;if(S.transient){i==null||i(S);break}const C=S.id!=null?u.message.parts.find(N=>S.type===N.type&&S.id===N.id):void 0;C!=null?C.data=S.data:u.message.parts.push(S),i==null||i(S),d()}}c.enqueue(a)})}}))}async function Gtt({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()}}g0({prefix:"aitxt",size:24});g0({prefix:"aiobj",size:24});var Ktt=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()})}};g0({prefix:"aiobj",size:24});var Ztt={};Dtt(Ztt,{object:()=>Qtt,text:()=>Xtt});var Xtt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Qtt=({schema:e})=>{const t=Mtt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await _re(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 vS({text:n});if(!s.success)throw new a8({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 fO({value:s.value,schema:t});if(!o.success)throw new a8({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Jtt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var ent=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 Th(this.body),c=await Th(this.headers),u=await Th(this.credentials),d={...Td(c),...Td(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?Td(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:n8({"Content-Type":"application/json",...m},`ai-sdk/${l8}`,t8()),body:JSON.stringify(p),credentials:g,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 Th(this.body),a=await Th(this.headers),c=await Th(this.credentials),u={...Td(a),...Td(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?Td(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:n8(h,`ai-sdk/${l8}`,t8()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},mO=class extends ent{constructor(e={}){super(e)}processResponseStream(e){return $et({stream:e,schema:Vtt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},tnt=class{constructor({generateId:e=_et,id:t=e(),transport:n=new mO,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Ktt,this.sendMessage=async(f,h)=>{var m,p,g,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let b;if("text"in f||"files"in f?b={parts:[...Array.isArray(f.files)?f.files:await Jtt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:b=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,{...b,id:f.messageId,role:(p=b.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...b,id:(g=b.id)!=null?g:this.generateId(),role:(x=b.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(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.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var x,b;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(S=>bM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(S=>bM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(b=this.lastMessage)==null?void 0:b.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:qtt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}p=x}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=x=>this.jobExecutor.run(()=>x({state:m.state,write:()=>{var b;this.setStatus({status:"streaming"}),m.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Gtt({stream:Ytt({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function Tre({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(bM).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function nnt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var rnt=nnt;const snt=Uf(rnt);var Mre=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},ar=(e,t,n)=>(Mre(e,t,"read from private field"),n?n.call(e):t.get(e)),Da=(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)},Vc=(e,t,n,r)=>(Mre(e,t,"write to private field"),t.set(e,n),n);function ont(e,t){return t!=null?snt(e,t):e}var bi,_w,Tw,lx,cx,ux,Ph,yM,vM,int=class{constructor(e=[]){Da(this,bi,void 0),Da(this,_w,"ready"),Da(this,Tw,void 0),Da(this,lx,new Set),Da(this,cx,new Set),Da(this,ux,new Set),this.pushMessage=t=>{Vc(this,bi,ar(this,bi).concat(t)),ar(this,Ph).call(this)},this.popMessage=()=>{Vc(this,bi,ar(this,bi).slice(0,-1)),ar(this,Ph).call(this)},this.replaceMessage=(t,n)=>{Vc(this,bi,[...ar(this,bi).slice(0,t),this.snapshot(n),...ar(this,bi).slice(t+1)]),ar(this,Ph).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ont(t,n):t;return ar(this,lx).add(r),()=>{ar(this,lx).delete(r)}},this["~registerStatusCallback"]=t=>(ar(this,cx).add(t),()=>{ar(this,cx).delete(t)}),this["~registerErrorCallback"]=t=>(ar(this,ux).add(t),()=>{ar(this,ux).delete(t)}),Da(this,Ph,()=>{ar(this,lx).forEach(t=>t())}),Da(this,yM,()=>{ar(this,cx).forEach(t=>t())}),Da(this,vM,()=>{ar(this,ux).forEach(t=>t())}),Vc(this,bi,e)}get status(){return ar(this,_w)}set status(e){Vc(this,_w,e),ar(this,yM).call(this)}get error(){return ar(this,Tw)}set error(e){Vc(this,Tw,e),ar(this,vM).call(this)}get messages(){return ar(this,bi)}set messages(e){Vc(this,bi,[...e]),ar(this,Ph).call(this)}};bi=new WeakMap;_w=new WeakMap;Tw=new WeakMap;lx=new WeakMap;cx=new WeakMap;ux=new WeakMap;Ph=new WeakMap;yM=new WeakMap;vM=new WeakMap;var Oh,u8=class extends tnt{constructor({messages:e,...t}){const n=new int(e);super({...t,state:n}),Da(this,Oh,void 0),this["~registerMessagesCallback"]=(r,s)=>ar(this,Oh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>ar(this,Oh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>ar(this,Oh)["~registerErrorCallback"](r),Vc(this,Oh,n)}};Oh=new WeakMap;function Ire({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new u8(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new u8(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function ant(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function lnt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function cnt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function unt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Dre(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:unt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Are(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 dnt(){var x;const{authToken:e,tokenProps:t}=tt(),n=Q(b=>b.dashboard.aiScopeTables),r=(x=RS().data)==null?void 0:x.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:c,addToolResult:u,error:d,stop:f,clearError:h}=Ire({transport:new mO({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const b=_c.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:b.currentAIContext,reasoningEffort:b.reasoningEffort,showReasoning:b.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:b,body:y})=>({body:{...y,messages:ZG(b)}})}),onToolCall:m,sendAutomaticallyWhen:Tre,onFinish({isAbort:b,isDisconnect:y,isError:v}){console.log(b?"[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(b){var y;if(b.name==="AbortError"||(y=b.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",b)}});async function m({toolCall:b}){if(b.toolName==="getCurrentTableScope"&&u({tool:b.toolName,toolCallId:b.toolCallId,output:{tables:Dre(n||[])}}),b.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:b.toolName,toolCallId:b.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(c),g=Are(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:c,stop:f,errorMessage:g,clearError:h}}function Rre(){var u;const{authToken:e,tokenProps:t}=tt(),n=(u=RS().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=en({queryKey:["assistant-profile",n],queryFn:()=>xr(`${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 Pre({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(l7,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(te,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function fnt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=Ll-n;if(c.length>u){We.error(`You can only attach ${Ll} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=wne(c);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>sO(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ll}),l.jsx(te,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ll,title:n>=Ll?`Maximum ${Ll} files allowed`:"Attach files",children:l.jsx(gI,{className:"h-4 w-4 text-muted-foreground"})})]})}function hnt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.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=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.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=Ll-r;if(h.length>m){We.error(`You can only attach ${Ll} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=wne(h);if(g.forEach(({file:x,error:b})=>{We.error(`${x.name}: ${b}`)}),p.length>0)try{const x=await Promise.all(p.map(b=>sO(b)));t(x),We.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),We.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:Z("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(jI,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ll-r," slot(s) available"]})]})})]})}function Ore(e){return e.type==="dataset"&&e.label||e.name}function mnt(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 pnt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(st,{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:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),Ore(n),l.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:l.jsx(Vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function gnt(e){const{tokenProps:t}=tt(),n=Q(c=>c.authToken)||e;$e(c=>c.selectedConnectionId),$e(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=en({queryKey:["semantic-domains"],queryFn:()=>xr(`${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 xnt(e,t){const{tokenProps:n}=tt(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=en({queryKey:["datasets",e],queryFn:()=>xr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function bnt(e){var g,x;const{tokenProps:t}=tt(),n=Q(b=>b.authToken)||e,{connections:r}=pi(e),s=$e(b=>{var y,v;return(v=(y=b==null?void 0:b.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(b=>b.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(b){var y;return!s||!b?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=en({queryKey:["databases",s],queryFn:()=>xr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(x=d==null?void 0:d.databases)==null?void 0:x.map(b=>({id:b.database_name,name:b.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function ynt(e){var g;const{tokenProps:t}=tt(),n=Q(x=>x.authToken)||e,{connections:r}=pi(e),s=$e(x=>{var b,y;return(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.connectionId}),o=$e(x=>{var b,y,v;return(v=(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(x=>x.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var x;return!(!s||!((x=i==null?void 0:i.capabilities)!=null&&x.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=en({queryKey:["schemas",s,o],queryFn:()=>xr(`${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(x=>({id:x.schema_name,name:x.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function Fre(e){const{tokenProps:t}=tt(),n=Q(h=>h.authToken)||e,{connections:r}=pi(e),s=$e(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:c,error:u,refetch:d}=en({queryKey:["dataModels",s],queryFn:()=>xr(`${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:c,error:u,dataModels:f||[],refetch:d}}function vnt(){var C,N,k;const e=$e(E=>E.card.dataSource);$e(E=>E.actions.updateDirectSource);const t=$e(E=>E.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=pi(),{databases:i,isPending:a,error:c,label:u}=bnt(),{schemas:d,isPending:f,error:h,label:m}=ynt(),{error:p}=Fre(),g=s==null?void 0:s.capabilities.path.includes("schema"),x=s==null?void 0:s.capabilities.path.includes("database"),b=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},S=E=>{var j;if(!((j=e==null?void 0:e.dbSelection)!=null&&j.database))return;const M=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...M,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(te,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[x&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:u}),l.jsxs(bt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(Nn,{className:"h-4 w-4 animate-spin"}),l.jsx(wt,{placeholder:c?`Error loading ${b}`:a?`Loading ${b}...`:`Select ${b}...`})]})}),l.jsx(gt,{children:i.map(E=>l.jsx(Ee,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:m}),l.jsxs(bt,{value:((k=e==null?void 0:e.dbSelection)==null?void 0:k.schema)||"",onValueChange:S,disabled:f,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(Nn,{className:"h-4 w-4 animate-spin"}),l.jsx(wt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(gt,{children:d.map(E=>l.jsx(Ee,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function wnt(){const e=$e(c=>c.card.dataSource),t=$e(c=>c.actions.updateDataSource),[n,r]=w.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).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=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),l.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:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(jI,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(te,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pa,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},c.id))})]})]})}function Snt(){const e=$e(f=>f.card.dataSource),t=$e(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),c=()=>{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 l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(sn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(sn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),l.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:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(te,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(Ar,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(oy,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function Cnt(e,t){var y,v;const{tokenProps:n}=tt(),r=Q(S=>S.authToken)||t,{connections:s}=pi(t),o=$e(S=>{var C,N;return(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.connectionId}),i=$e(S=>{var C,N,k;return(k=(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.dbSelection)==null?void 0:k.database}),a=$e(S=>{var C,N,k;return(k=(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.dbSelection)==null?void 0:k.schema}),c=s==null?void 0:s.find(S=>S.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const S=(u==null?void 0:u.path)||[];return!(S.includes("database")&&!i||S.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:x}=en({queryKey:[e,o,i,a],queryFn:()=>xr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),b=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(S=>{var C;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(C=S==null?void 0:S.table_type)==null?void 0:C.toLowerCase(),id:S[`${e}_name`],database:i,schema:a,name:S[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:b||[],refetch:x,label:d}}function wS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx(xc,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function Nnt({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=pi(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=br(),{entities:p,isLoading:g,error:x}=Cnt("table"),{dataModels:b,isPending:y,error:v}=Fre(),S=j=>{const _=s.find(P=>P.id===j);if(!_)return;const T=_.type==="upload"?"upload":_.type==="url"?"url":"database";h({...e,connectionId:j,connectionType:_.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(j)},C=j=>{var F,R;const _=n||[],T=_.some($=>$.name===j.name&&$.type===j.type);let P;if(T)P=_.filter($=>!($.name===j.name&&$.type===j.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:j.type,dbObjectType:j.dbObjectType,database:((F=e.dbSelection)==null?void 0:F.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:j.name,dialect:j.dialect};P=[..._,$]}t==null||t(P)},N=j=>{const _=n||[],T=_.some(F=>F.type==="model"&&F.name===j.name);let P;T?P=_.filter(F=>!(F.type==="model"&&F.name===j.name)):P=[..._,j],t==null||t(P)},k=p.filter(j=>j.name.toLowerCase().includes(i.toLowerCase())),E=b.filter(j=>j.name.toLowerCase().includes(c.toLowerCase())),M=w.useCallback(()=>{if(!t)return;const j=n||[];let _=[...j];if(d==="tables"){const P=k.filter(F=>!j.some(R=>R.name===F.name&&R.type==="table")).map(F=>{var R,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:F.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:F.name,dialect:F.dialect}});_=[...j,...P]}else if(d==="datamodels"){const T=E.filter(P=>!j.some(F=>F.name===P.name&&F.type==="model"));_=[...j,...T]}t(_)},[d,k,E,n,e,t]);return w.useEffect(()=>{r&&r(M)},[r,M]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(bt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:S,disabled:o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(wt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(gt,{children:s.map(j=>l.jsx(Ee,{className:"hover:bg-muted",value:j.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(Ja,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:j.name}),l.jsx(st,{variant:"secondary",className:"flex-shrink-0 text-xs",children:j.type})]})},j.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(wnt,{}),e.connectionType==="url"&&l.jsx(Snt,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(vnt,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(Fs,{defaultValue:"tables",value:d,onValueChange:j=>f(j),className:"w-full",children:[l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsxs(cn,{value:"tables",children:["Tables & Views (",k.length,")"]}),l.jsxs(cn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),l.jsxs(cr,{value:"tables",className:"space-y-2",children:[l.jsx($n,{placeholder:"Search tables and views...",value:i,onChange:j=>a(j.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):x?l.jsx(wS,{title:"Error loading tables",message:x.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):k.map(j=>{const _=n.some(T=>T.name===j.name&&T.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(j),children:[l.jsx(yn,{id:`table-${j.name}`,checked:_,onCheckedChange:()=>C(j),onClick:T=>T.stopPropagation(),disabled:g}),l.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[j.name,j.dbObjectType==="view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),j.dbObjectType==="materialized view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},j.name)})})]}),l.jsxs(cr,{value:"datamodels",className:"space-y-2",children:[l.jsx($n,{placeholder:"Search data models...",value:c,onChange:j=>u(j.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(wS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(j=>{const _=n.some(T=>T.name===j.name&&T.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(j),children:[l.jsx(yn,{id:`dataModel-${j.name}`,checked:_,onCheckedChange:()=>N(j),onClick:T=>T.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer",children:j.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:j.description})]})]},j.name)})})]})]})})})]})]})]})}function jnt({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=B8.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var S;const[a,c]=w.useState(""),u=w.useCallback(C=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...N})},[e,t]);w.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=gnt(),m=d.filter(C=>{var N,k;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(C.id))??!1;case"exclude":return!(((k=s.domainIds)==null?void 0:k.includes(C.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:x}=xnt(e==null?void 0:e.semanticDomainId),b=C=>{const N=r||[],k=N.some(M=>M.id===C.id&&M.type==="dataset");let E;if(k)E=N.filter(M=>!(M.id===C.id&&M.type==="dataset"));else{const M={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};E=[...N,M]}n==null||n(E)},y=p.filter(C=>C.name.toLowerCase().includes(a.toLowerCase())),v=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],k=y.filter(M=>!C.some(j=>j.id===M.id&&j.type==="dataset")).map(M=>({id:M.id,datasetType:M.type,name:M.name||M.table,label:M.label,domainId:M.domainId,description:M.description,database:M.database,schema:M.schema,type:"dataset",connectionId:M.connectionId,connectionType:M.connectionType,dialect:M.dialect,datamodelId:M.datamodelId,sql:M.sql})),E=[...C,...k];n(E)},[y,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(bt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(wt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),l.jsx(gt,{children:m.map(C=>l.jsx(Ee,{className:"hover:bg-muted",value:C.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:C.label}),l.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),h&&l.jsx(wS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx($n,{placeholder:"Search datasets...",value:a,onChange:C=>c(C.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?l.jsx(wS,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(C=>{const N=r.some(k=>k.id===C.id&&k.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>b(C),children:[l.jsx(yn,{id:`dataset-${C.id}`,checked:N,onCheckedChange:()=>b(C),onClick:k=>k.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer font-medium",children:C.label||C.name}),l.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function knt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Ent({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!knt(e,t,n):r}function _nt(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function pO({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o}){var A,L;const{tokenProps:i}=tt(),a=i.semanticDomainAccess||B8.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[c,u]=w.useState([]),[d,f]=w.useState(void 0),{updateDataSource:h}=br(),m=Q(O=>O.isVisualEditing),p=Q(O=>O.dashboard.aiContext),{setAiContext:g}=un(),x=w.useRef(null),[b,y]=w.useState(!1),v=a.mode,S=v==="include"||v==="exclude",C=v!=="all",N=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,E=v==="include"&&(((A=a.domainIds)==null?void 0:A.length)||0)===1?(L=a.domainIds)==null?void 0:L[0]:void 0,M=w.useCallback(O=>{const I=O;h({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:I,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...I!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,h]),j=w.useCallback(O=>{h({...n,...O})},[n,h]),_=w.useCallback(O=>{if(r==="aiContext"){"semanticDomainId"in O&&f(O.semanticDomainId);return}j(O)},[r,j]),T=r==="aiContext"?d:n.semanticDomainId,P=r==="aiContext"?{...n,mode:k,semanticDomainId:d}:n;w.useEffect(()=>{if(!C||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){M("semanticDomain");return}if(k!=="semanticDomain")return;const O=T,I=a.domainIds??[],V=r==="aiContext"?c:n.selectedEntities,Y=((V==null?void 0:V.length)??0)>0,G=((c==null?void 0:c.length)??0)>0;Ent({mode:v,currentDomainId:O,scopedDomainIds:I,hasSelectedEntities:Y})&&(r==="dataSource"?j({semanticDomainId:void 0,selectedEntities:[]}):f(void 0),G&&u([]))},[S,C,k,n.mode,T,n.selectedEntities,r,d,c,e,a.domainIds,v,j,M]),w.useEffect(()=>{E&&!T&&_({semanticDomainId:E})},[E,T,_]),w.useEffect(()=>{if(e){u(s||[]);const O=r==="aiContext"?_nt(s):void 0;f(n.semanticDomainId||O)}else x.current=null,y(!1)},[e,n==null?void 0:n.selectedEntities,r,h,s,n]);const F=O=>{const I=c.filter(V=>!(V.name===O.name&&V.type===O.type));u(I)},R=()=>{u([])},$=w.useCallback(O=>{u(O)},[]),q=w.useCallback(()=>{x.current&&x.current()},[]),U=w.useCallback(O=>{x.current=O,y(!0)},[]);function W(){var O,I;if(r==="aiContext")m&&h(n),g({...p,selectedEntities:c}),o==null||o(c),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const V=(O=c==null?void 0:c[0])==null?void 0:O.connectionId,Y=(I=c==null?void 0:c[0])==null?void 0:I.connectionType;h({...n,connectionId:V,connectionType:Y,selectedEntities:c})}else h({...n,selectedEntities:c});t(!1)}}return l.jsx(Wr,{open:e,onOpenChange:t,children:l.jsx(Rr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Pr,{className:"flex-shrink-0",children:[l.jsx(Or,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(Xr,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[N&&l.jsx("div",{className:"space-y-2",children:l.jsx(Fs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:M,className:"w-full",children:l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsx(cn,{value:"database",children:"Direct Source"}),l.jsx(cn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(jnt,{dataSource:P,onDataSourceUpdate:_,selectedEntities:c,onSelectionChange:$,domainAccess:a,autoSelectedDomainId:E,onRegisterSelectAll:U}),k==="database"&&N&&l.jsx(Nnt,{dataSource:n,onDataSourceUpdate:j,selectedEntities:c,onSelectionChange:$,onRegisterSelectAll:U})]})}),l.jsx(pnt,{selectedEntities:c,onDeselectEntity:F}),l.jsx(Ns,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(te,{variant:"outline",onClick:q,disabled:!b,children:"Select All"}),l.jsx(te,{variant:"outline",onClick:R,disabled:c.length===0,children:"Clear All"}),l.jsxs(te,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Vt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(te,{onClick:W,children:[l.jsx(Ur,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function Va(e,t){if("id"in e&&"id"in t&&e.id&&t.id)return e.id===t.id;const n=e.database||"",r=t.database||"",s=e.schema||"",o=t.schema||"",i=e.connectionType||"",a=t.connectionType||"",c=e.dbObjectType||"",u=t.dbObjectType||"";return e.type===t.type&&e.connectionId===t.connectionId&&i===a&&n===r&&s===o&&e.name===t.name&&c===u}function d8(e){return e||[]}function Tnt(){const e=zp(),t=Q(p=>{var g;return(g=p.dashboard.aiContext)==null?void 0:g.selectedEntities}),{setCurrentAIContext:n}=YC(),r=d8(e.selectedEntities),s=d8(t),o=w.useCallback(p=>{n({...e,selectedEntities:p})},[e,n]),i=w.useCallback(p=>r.some(g=>Va(g,p)),[r]),a=w.useCallback(p=>{if(r.some(x=>Va(x,p))){o(r.filter(x=>!Va(x,p)));return}o([...r,p])},[r,o]),c=w.useCallback(p=>{r.some(g=>Va(g,p))||o([...r,p])},[r,o]),u=w.useCallback(p=>{o(r.filter(g=>!Va(g,p)))},[r,o]),d=w.useCallback(p=>{p.length!==0&&o(r.filter(g=>!p.some(x=>Va(g,x))))},[r,o]),f=w.useCallback(()=>{o(s)},[s,o]),h=w.useCallback(()=>{o([])},[o]),m=w.useCallback(()=>{r.length===0&&o(s)},[s,r.length,o]);return{selectedEntities:r,availableEntities:s,setSelectedEntities:o,isEntitySelected:i,toggleEntity:a,addEntityIfMissing:c,removeEntity:u,removeEntities:d,selectAllEntities:f,clearAllEntities:h,syncWithGlobalContext:m}}function SS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(wI,{className:r});case"view":return l.jsx(ku,{className:r});case"materialized view":return l.jsx(Fle,{className:r});case"model":return l.jsx(BS,{className:r});case"file":return l.jsx(pa,{className:r});case"dataset":return l.jsx(Ja,{className:r});case"upload":return l.jsx(jI,{className:r});case"url":return l.jsx(m7,{className:r});default:return l.jsx(oy,{className:r})}}const wM=e=>e.name||e.name,Mnt=e=>{const t=wM(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Int({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=w.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(nr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsxs(st,{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:[SS(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:wM(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(Mn,{side:"top",className:"max-w-xs",children:Mnt(f)})]},m)}),d&&l.jsxs(jn,{open:o,onOpenChange:i,children:[l.jsx(kn,{asChild:!0,children:l.jsxs(st,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(d7,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(Mn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:SS(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:wM(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Vt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const $re=D.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Uo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(io.Input,{ref:n,className:Z("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})]}));$re.displayName=io.Input.displayName;const Zv=e=>e.label||(e==null?void 0:e.name),f8=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Dnt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=tt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),x=s.filter(N=>{if(!h)return!0;const k=Zv(N).toLowerCase(),E=f8(N).toLowerCase(),M=h.toLowerCase();return k.includes(M)||E.includes(M)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{x.length>0&&!p&&g(Zv(x[0]))},[x,p]);const b=()=>{if(!p)return;const N=x.find(k=>Zv(k)===p);N&&(o.some(E=>"id"in N&&"id"in E?N.id===E.id:N.name===E.name&&N.connectionId===E.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),b())};if(!e)return null;const v=N=>o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId),S=o.length===s.length,C=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Rp,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx($re,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(Ar,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:S,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Pp,{className:"min-h-60",children:[l.jsx(Op,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(Ar,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(Fp,{children:x.map((N,k)=>{const E=v(N),M="id"in N?N.id:`${N.connectionId}-${N.name}`,j=Zv(N);return l.jsxs($p,{value:j,onSelect:()=>{E?n==null||n(N):t(N)},onMouseDown:_=>{_.preventDefault(),_.stopPropagation()},className:Z("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:SS(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:f8(N)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(Ur,{className:"h-3 w-3 text-background"})})]},M)})})]})]})})}function SM({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0}){const[x,b]=w.useState(!1),[y,v]=w.useState(!1),S=o??x,C=o!==void 0,N=w.useRef(!1),E=$e(z=>z.card.dataSource)??KN,{selectedEntities:M,availableEntities:j,syncWithGlobalContext:_,setSelectedEntities:T,isEntitySelected:P}=Tnt(),F=e==="full"||e==="display",R=e==="full"||e==="trigger",$=w.useMemo(()=>g&&M.length>0?`Add entity (${M.length})`:p,[M.length,g,p]);w.useEffect(()=>{S&&!N.current&&s&&_(),N.current=S},[S,s,_]);const q=w.useCallback(z=>{C||b(z),i==null||i(z)},[C,i]),U=w.useCallback(z=>{const B=M.filter(H=>!Va(H,z));T(B),c==null||c(z),d==null||d(B)},[c,d,M,T]),W=w.useCallback(z=>{if(z.length===0)return;const B=M.filter(H=>!z.some(K=>Va(H,K)));T(B),u==null||u(z),d==null||d(B)},[u,d,M,T]),A=w.useCallback(z=>{const B=P(z)?M.filter(H=>!Va(H,z)):[...M,z];T(B),d==null||d(B)},[P,d,M,T]),L=w.useCallback(()=>{T(j),d==null||d(j)},[j,d,T]),O=w.useCallback(()=>{T([]),d==null||d([])},[d,T]),I=w.useCallback(z=>{T(z),d==null||d(z)},[d,T]),V=w.useCallback(z=>{const B=M.some(H=>Va(H,z))?M:[...M,z];T(B),a==null||a(z),d==null||d(B),q(!1)},[a,d,M,q,T]),Y=F?l.jsx(Int,{className:Z(n?"contents":"space-y-2"),entities:M,availableEntities:j,onRemoveEntity:U,onRemoveEntities:W}):null,G=R?l.jsxs(l.Fragment,{children:[l.jsxs(vs,{open:S,onOpenChange:q,children:[l.jsx(ws,{asChild:!0,children:l.jsxs(te,{variant:m,size:"sm",className:Z(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx(Rle,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:$})]})}),l.jsx(Ss,{className:Z("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:l.jsx(Dnt,{isOpen:!0,onSelect:A,onDeselect:A,onClose:()=>q(!1),availableEntities:j,selectedEntities:M,onTabComplete:V,onSelectAll:L,onRemoveAll:O,onAddContext:()=>{q(!1),v(!0)}})})]}),l.jsx(pO,{incomingSelectedEntities:M,open:y,onOpenChange:v,dataSource:E,dialogMode:"aiContext",onSaveSelectedEntities:I})]}):null;return l.jsx("div",{className:Z(n?"flex flex-wrap items-center gap-1":"",!n&&F?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[G,Y]}):l.jsxs(l.Fragment,{children:[Y,G]})})}const gO=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),h=w.useRef(null),{queueMessage:m}=Bp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:x}=SA(),b=wA(c);w.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=w.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const _=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${_}px`}},[e]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{const j=setTimeout(()=>{y()},0);return()=>clearTimeout(j)},[y]);const v=()=>{const j=e.trim();!j&&b.length===0||(a!=="ready"?(m(c,j,b),t(""),x(c)):r({preventDefault:()=>{}}))},S=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),v()),j.key==="@"&&f(!0)},C=w.useCallback(j=>{const _=XKe(j.nativeEvent);_.length>0&&(j.preventDefault(),_.forEach(async T=>{const P=await sO(T);p(c,P)}))},[p,c]),N=w.useCallback(j=>{j.forEach(_=>{p(c,_)})},[p,c]),k=w.useCallback(j=>{j.forEach(_=>{p(c,_)})},[p,c]),E=w.useCallback(j=>{g(c,j)},[g,c]),M=w.useCallback(j=>{const _=`@${j}`;e.includes(_)&&t(e.replace(_,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(hnt,{onFilesDropped:N,currentFileCount:b.length,disabled:s,className:"space-y-4",children:[l.jsx(SM,{mode:"display",onEntityRemoved:j=>{const _="label"in j?j.label:j.name;M(_)},onEntitiesRemoved:j=>{let _=e;j.forEach(T=>{const P="label"in T?T.label:T.name;_=_.replace(`@${P}`,"")}),_!==e&&t(_.replace(/\s{2,}/g," ").trim())}}),b.length>0&&l.jsx(QKe,{files:b,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:S,onPaste:C,onFocus:()=>{y(),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"}}),l.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(SM,{mode:"trigger",syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const _="label"in j?j.label:j.name;t(`${e}@${_} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(fnt,{onFilesSelected:k,disabled:s,currentFileCount:b.length})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[s&&l.jsx(te,{className:"rounded-full",size:"sm",onClick:o,children:l.jsx(Yle,{className:"size-3.5 bg-background"})}),!s&&l.jsx(te,{disabled:!e.trim()&&b.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(yI,{className:"size-4"})})]})]})]})]})});gO.displayName="ChatInputWithContext";function Lre({assistantType:e,className:t}){const n=XG(e),{removeFromQueue:r}=Bp();return n.length===0?null:l.jsxs("div",{className:Z("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(ju,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(Vt,{className:"h-3 w-3"})})]})},s.id))})]})}function zre({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=XG(e),{dequeueMessage:o}=Bp();w.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 Ant(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Rnt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ant(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Bre(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!0),[d,f]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(0),x=w.useRef(!0),b=w.useRef(!0),y=w.useRef(!1),v=w.useRef(!1),S=w.useRef(0),C=w.useRef({count:0,signature:"none"}),N=w.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const $=R.closest("[data-radix-scroll-area-viewport]");if($)return i.current=$,$;const q=R.parentElement;return q?(i.current=q,q):null},[]),k=w.useCallback(()=>{const R=N();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[N]),E=w.useCallback(()=>k()<=n,[k,n]),M=w.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=w.useCallback(R=>{b.current!==R&&(b.current=R,f(R))},[]),_=w.useCallback(()=>{m(R=>R&&!1),g(R=>R===0?R:0)},[]),T=w.useCallback((R={})=>{const $=N();if(!$)return;const{force:q=!1,instant:U=!1}=R;if(!q&&y.current)return;const W=U||r==="auto"||r==="instant"?"auto":r;v.current=!0,W==="smooth"&&"scrollTo"in $?$.scrollTo({top:$.scrollHeight,behavior:"smooth"}):$.scrollTop=$.scrollHeight,S.current=$.scrollTop,y.current=!1,M(!0),j(!0),_(),requestAnimationFrame(()=>{v.current=!1})},[r,_,N,M,j]),P=w.useCallback(()=>{g(0),m(!1)},[]),F=w.useCallback(()=>{const R=N();if(!R)return;const $=S.current,q=R.scrollTop,U=q-$;S.current=q;const W=E();if(v.current){j(W),W&&(y.current=!1,M(!0));return}if(U<-1&&!W){y.current=!0,M(!1),j(!1);return}if(W){y.current=!1,M(!0),j(!0),_();return}j(!1),y.current&&M(!1)},[_,N,E,M,j]);return w.useEffect(()=>{const R=N();if(!e||e.length===0){C.current={count:0,signature:"none"},R&&(S.current=R.scrollTop),_();return}const $=e[e.length-1],q=Rnt($),U=C.current,W=e.length>U.count,A=q!==U.signature;C.current={count:e.length,signature:q};const L=o||s&&($==null?void 0:$.role)==="assistant"&&A;if(!y.current){M(!0),R&&E()&&j(!0),(W||A||L)&&T({force:!1,instant:L});return}if(W){const O=e.length-U.count;O>0&&(m(!0),g(I=>I+O))}else A&&(m(!0),g(O=>O>0?O:1))},[_,o,s,N,E,e,T,M,j]),w.useEffect(()=>{T({force:!0,instant:!0})},[T]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const $=new ResizeObserver(()=>{y.current||T({force:!1,instant:!0})});return $.observe(R),()=>{$.disconnect()}},[T]),w.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:T,handleScroll:F,resetNewMessageCount:P}}function Vre(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Ure(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:Sne(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pnt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Ont({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(OM),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:x,isConsoleMode:b}=yp(),y=w.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:S}=br(),{addFrame:C,setSelectedFrameId:N,setIsDashboardEditing:k}=un(),E=zp(),{setCurrentAIContext:M,updateSelectedEntities:j,setReasoningEffort:_,setShowReasoning:T}=YC(),{clearQueue:P}=Bp(),{clearFileAttachments:F,getFileAttachments:R}=SA(),$=wA("dashboard"),q=Q(Be=>Be.dashboard.aiContext),U=$e(Be=>Be.card.dataSource),{assistantProfile:W}=Rre(),A=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:L,isLoading:O,messages:I,setMessages:V,status:Y,stop:G,errorMessage:z,clearError:B}=dnt(),H=w.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=w.useCallback(()=>{H(!g)},[g,H]);w.useEffect(()=>{if(!g)return;function Be(ye){ye.key==="Escape"&&H(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,H]);const[ee,X]=w.useState(""),re=Be=>{X(Be.target.value)};function le({sql:Be,cardTitle:ye,connectionId:it,cardType:Ve,python:et,cardConfig:Rt,dataSource:Fe,customVisualPreferences:je}){if(!v)return;const Le={id:gr(),title:ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ve==="horizontalBar"?"y":"x"}},type:Ve,sql:Be,python:et,dataSource:Fe,config:Rt,connectionId:it,customCardPreferences:je?{url:je.url,componentName:je.componentName,pluginChartType:je.pluginChartType,settings:je.settings,type:"component"}:void 0},ut={id:gr(),cards:[Le],activeCardId:Le.id};k(!0),C(v,ut,"end"),N(ut.id)}const ue=Be=>{Be.preventDefault();const ye=ee.trim();if(!ye&&$.length===0)return;const it=[];ye&&it.push({type:"text",text:ye}),$.forEach(Ve=>{Ve.data&&it.push({type:"file",mediaType:Ve.type,filename:Ve.name,url:`data:${Ve.type};base64,${Ve.data}`})}),L({role:"user",parts:it}),X(""),F("dashboard"),oe({force:!0})};w.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),zre({assistantType:"dashboard",status:Y,isLoading:O,sendMessage:L});const{hasActiveTools:ce}=Ure(I),{visibleMessages:Se,hasMoreMessages:se,totalMessageCount:ke,loadMoreMessages:pe,resetMessageWindow:De}=Vre(I,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Pe,contentRef:ge,isAtBottom:ve,hasNewMessages:ie,newMessageCount:J,scrollToBottom:oe,handleScroll:we,resetNewMessageCount:Ne}=Bre(Se,{threshold:40,behavior:"smooth",isStreaming:O});function _e(Be){Qe();const ye={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};L(ye)}function me(Be){Qe(),L({role:"user",parts:[{type:"text",text:Be}]})}function Ie(Be){Qe(),L({role:"user",parts:[{type:"text",text:Be}]}),oe({force:!0})}const ze=w.useCallback(async()=>{const Be=JSON.stringify(I??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),We.success("Conversation copied")}catch(ye){console.error("Failed to copy conversation",ye),We.error("Unable to copy conversation")}},[I]);function Qe(){E.selectedEntities.length===0&&M({selectedEntities:(q==null?void 0:q.selectedEntities)||[]})}const Te=(ee==null?void 0:ee.length)===0&&(I==null?void 0:I.filter(Be=>Be.role==="user").length)===0;function Ye(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function rt(){return l.jsxs(Qf,{children:[l.jsx(Jf,{asChild:!0,children:l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(dp,{className:"size-3.5"})})}),l.jsxs(Vu,{align:"end",children:[l.jsx(Jh,{children:"Options"}),l.jsx(jf,{}),l.jsx(fx,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(fx,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(fx,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Je=l.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ye(),A&&l.jsx(te,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:A,children:(W==null?void 0:W.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[b&&rt(),a&&l.jsx(te,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ze,children:"Copy Conversation"}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?l.jsx(pI,{className:"size-4"}):l.jsx(VS,{className:"size-4"})}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{V([]),P("dashboard"),B(),De()},children:l.jsx(HS,{className:"size-4"})}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Vt,{className:"size-4"})})]})]}),l.jsxs(wl,{"data-role":"dashboard-assistant-scroll-area",ref:Pe,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:we,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[se&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(te,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ke-Se.length)," ","more messages (",ke-Se.length," ","hidden)"]})}),l.jsx(Nne,{showTools:a,showSystemMessage:u,messages:Se,onAddToDashboard:le,onQuickReply:Ie,disableQuickReplies:O}),!ce&&l.jsx(Cne,{status:Y,errorMessage:z})]}),l.jsx(Fi,{orientation:"horizontal"})]}),e&&!ve&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(te,{onClick:()=>{oe({force:!0}),Ne()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(dr,{className:"h-4 w-4"}),ie&&J>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:J>9?"9+":J})]})}),l.jsxs("div",{className:"space-y-3",children:[!W&&Te&&l.jsx(jne,{onClick:_e,placeholders:Pnt}),l.jsx("div",{children:Te&&W&&l.jsx(Pre,{seedQuestions:W.seedQuestions||[],handleSeedQuestionClick:me})}),l.jsx(Lre,{assistantType:"dashboard",className:"mb-3"}),l.jsx(gO,{ref:y,setInput:X,stop:G,input:ee,handleInputChange:re,handleSubmit:Be=>{Qe(),ue(Be),oe({force:!0})},isLoading:O,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(pO,{incomingSelectedEntities:(q==null?void 0:q.selectedEntities)||[],open:f,onOpenChange:h,dataSource:U||KN,dialogMode:"aiContext"})]});return g&&s?ur.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:Je})}),s):Je}function Fnt(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=un(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.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=XQ(p),x=g.cards.findIndex(b=>b.id===g.activeCardId);x!==-1&&(g.cards[x].title=`${g.cards[x].title} (Copy)`),r(a,g),s(g.id),We.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,c,u,t])}function $nt(e,t){switch(e.interactionMode){case"drillToDetail":Lnt(e,t);break;case"drillThrough":znt(e,t);break;case"drillToURL":Bnt(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 Lnt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function znt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Bnt(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 Vnt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Wr,{open:e,onOpenChange:t,children:l.jsxs(Rr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Pr,{children:[l.jsx(Or,{children:i||"Insight Detail"}),l.jsx(Xr,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(WJ,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(ZJ,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Unt(){const e=Qt(S=>S.interactionStates),t=Qt(S=>S.setInteractionState),n=Qt(S=>S.clearLastInteractionEvent),r=Qt(S=>S.replaceCardWithInsight),s=Qt(S=>S.setPendingDrillThrough),o=Qt(S=>S.pendingDrillThrough),i=Qt(S=>S.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=un(),{selectDashboard:u}=up(),d=Q(S=>S.dashboard),f=Q(S=>S.filterValues),{data:h,isLoading:m}=AV((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),x=XJ(p.insightId,{enabled:p.open&&!!p.insightId}),b=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:S,filters:C,contextMode:N})=>{g({open:!0,insightId:S,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:S,insightId:C,filters:N,contextMode:k})=>{r(S,C,N,k)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:S,contextMode:C,sourceDashboardId:N,sourceDashboardTitle:k,targetDashboardId:E})=>{const j={sourceCardId:Za,interactionMode:"clickFilter",filterGroups:[{filters:S}]},_={...ki(),appliedClickFilters:[j],contextMode:C,sourceDashboardId:N,sourceDashboardTitle:k,targetDashboardId:E};t(Za,_)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([S,C])=>{if(C!=null&&C.lastInteractionEvent){const N=C.lastInteractionEvent,k=`${S}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(b.current.has(k))return;b.current.add(k);try{$nt(N,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(S),setTimeout(()=>{b.current.delete(k)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(S){console.error("[DrillThrough] Error during automatic navigation:",S),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Vnt,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(Nn,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Hnt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Wnt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Wnt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function qnt(e){return e?`Back to ${e}`:"Back"}function Ynt(){var b,y,v,S,C;const e=Qt(N=>N.interactionStates[Za]),t=Q(N=>N.actions.goBackFromDrill),n=Q(N=>N.actions.clearDrillContext),{selectDashboard:r}=up(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const N=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},k=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",k),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",k)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((S=(v=(y=(b=e==null?void 0:e.appliedClickFilters)==null?void 0:b[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:S.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(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};Hnt(f);const x=qnt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,k)=>{const E=N.field.label||N.field.name,M=String(N.value);return l.jsxs(st,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",M]},k)})})]}),l.jsx(te,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Vt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(te,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(J9,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Hre(){var ke;const{showAssistant:e,tokenProps:t}=tt(),{preferences:n,isConsoleMode:r}=yp(),s=((ke=n==null?void 0:n.cardDisplay)==null?void 0:ke.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,c]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=HBe({initialPosition:"bottom-right"}),m=hf(pe=>pe.setFullscreen),p=hf(pe=>pe.setPanelOpen),g=hf(pe=>pe.setContainer),x=YG("dashboard"),b=GG(),y=KG("dashboard"),v=x.isOpen,S=b==="dashboard",C=Q(pe=>pe.isVisualEditing),N=Q(pe=>pe.themeStyle),k=Q(pe=>{var De;return(De=pe.dashboard)==null?void 0:De.sheets}),E=Q(pe=>pe.showFilters),M=Q(pe=>pe.isDashboardEditing),j=Q(pe=>pe.selectedSheetId),_=Q(pe=>{var De,Pe;return((Pe=(De=pe.dashboard)==null?void 0:De.summary)==null?void 0:Pe.position)||"top"}),T=Q(pe=>{var De;return(De=pe.dashboard)==null?void 0:De.id}),P=Q(pe=>pe.isDashboardPanelOpen),F=Q(pe=>pe.actions.setIsDashboardPanelOpen),{getDefaultSheetId:R,setDefaultSheetId:$,clearDefaultSheetId:q}=G9(T),[U,W]=w.useState(null);sC(vn.DASHBOARD);const{setSelectedSheetId:A,setSheetTitle:L,addSheet:O,setSheets:I}=un();Fnt(i);const{setActiveAssistantType:V}=YC();w.useEffect(()=>{if(T){const pe=R();W(pe)}},[T,R]),w.useEffect(()=>{v?V("dashboard"):b==="dashboard"&&m(null)},[v,V,b,m]),w.useEffect(()=>{var pe;v||(pe=o.current)==null||pe.resize(0)},[v]);function Y(pe){var De,Pe;pe?((De=o.current)==null||De.resize(40),p("dashboard",!0),V("dashboard")):(p("dashboard",!1),m(null),(Pe=o.current)==null||Pe.resize(0),V(null))}function G(){const pe={id:gr(),title:"New Sheet"};O(pe),A(pe.id)}function z(pe,De){if(!T)return;U===pe?(q(),W(null),We.success("Default sheet cleared")):($(pe),W(pe),We.success(`"${De}" set as default sheet`))}function B(pe){var De;pe<1?(p("dashboard",!1),m(null),V(null),(De=o.current)==null||De.resize(0)):(v||p("dashboard",!0),V("dashboard"))}function H(){return(N==null?void 0:N.canvasTheme)==="muted"||!(N!=null&&N.canvasTheme)?"hsl(var(--semaphor-muted))":(N==null?void 0:N.canvasTheme)==="clear"?"":N==null?void 0:N.canvasTheme}const K=(pe,De)=>{pe.dataTransfer.setData("tabIndex",De.toString())},ee=pe=>{pe.preventDefault()},X=(pe,De)=>{const Pe=pe.dataTransfer.getData("tabIndex");if(Pe===De.toString())return;const ge=Array.from(k||[]),[ve]=ge.splice(parseInt(Pe),1);ge.splice(De,0,ve),I(ge)},re=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,le=e===!0&&!s&&!v&&!C&&!E;function ue(){var pe,De;if(k&&k.length>1||M)return l.jsxs(js,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&re&&!P&&l.jsx(te,{style:{borderRadius:N==null?void 0:N.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{F(!P)},className:"h-8 shrink-0 p-2",children:P?l.jsx(i7,{className:"h-4 w-4"}):l.jsx(a7,{className:"h-4 w-4"})}),k==null?void 0:k.map((Pe,ge)=>{const ve=j===Pe.id,ie=U===Pe.id;return l.jsxs(cn,{draggable:!0,onDragStart:J=>K(J,ge),onDragOver:ee,onDrop:J=>X(J,ge),style:{borderRadius:N==null?void 0:N.controlInputRadius},onClick:()=>A(Pe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:Pe.id,children:[l.jsx(K1,{enabled:M&&ve,text:Pe.title,onSave:J=>L(Pe.id,J),children:Pe.title},Pe.id),!M&&ve&&l.jsx("div",{title:ie?"Clear default sheet":"Set as default sheet",children:l.jsx(vI,{className:Z("ml-1 size-3 cursor-pointer transition-all",ie?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:J=>{J.stopPropagation(),z(Pe.id,Pe.title||"Sheet")}})}),M&&ve&&k.length>1&&l.jsx(Vt,{className:"ml-1 size-3",onClick:()=>c(!0)})]},Pe.id)}),M&&l.jsx("div",{style:{borderRadius:(De=(pe=N==null?void 0:N.chart)==null?void 0:pe.options)==null?void 0:De.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:G,children:l.jsx(Ar,{className:"size-3"})})]})}function ce(){return l.jsx("div",{ref:i,style:{},className:"grow",children:k==null?void 0:k.map(pe=>l.jsx(cr,{style:{backgroundColor:H()},className:Z("mt-0",{}),value:pe.id,children:l.jsx(mBe,{sheet:pe})},pe.id))})}function Se(){var pe;return l.jsxs(Fs,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",N==null?void 0:N.dashboardTabsContainer),onValueChange:De=>{A(De)},value:j||((pe=k==null?void 0:k[0])==null?void 0:pe.id),children:[ue(),_==="top"&&l.jsx(BT,{}),l.jsx(wl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:ce()}),_==="bottom"&&l.jsx(BT,{}),l.jsx(WBe,{open:a,setOpen:c})]})}const se=w.useCallback(pe=>{g("dashboard",pe)},[g]);return k?l.jsxs(l.Fragment,{children:[l.jsx(Unt,{}),l.jsx(Ynt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(ote,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(XT,{children:Se()}),e===!0&&l.jsxs(l.Fragment,{children:[l.jsx(UBe,{open:v,onTabClick:Y,withHandle:!0,disabled:!v}),l.jsx(XT,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:v?40:0,ref:o,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Ont,{open:v,setOpen:Y,isFullscreen:S,onFullscreenChange:pe=>m(pe?"dashboard":null),fullscreenContainer:y})})})]})]}),l.jsx("div",{ref:se,className:Z("absolute inset-0",!S&&"pointer-events-none")}),le&&l.jsx("div",{className:Z("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:l.jsx(te,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||Y(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:l.jsx(iy,{className:"h-5 w-5"})})})]})]}):null}function xO({children:e}){return l.jsx(Ca,{style:{height:"100%",width:"100%"},children:l.jsx(Gae,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(nr,{delayDuration:0,children:e})})})}function Wre({children:e,preferences:t}){const{currentUser:n}=so(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(uV.Provider,{value:r,children:l.jsx(bP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Gnt(e=2e3,t=500){const n=Cle(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function bO({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Gnt(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qre(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(ya,{FallbackComponent:vN,children:l.jsxs(nI,{dashboardProps:e,children:[l.jsx(bO,{componentType:"dashboard",componentId:e.id}),l.jsx(xO,{children:l.jsx(Wre,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(CA,{...e,type:"dashboard",children:l.jsx(Hre,{})})})})})]})})}function h8(e,t){return e.map(n=>({...n,fieldScope:t}))}function Knt(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function m8(e){if(Ec(e)||ky(e))return e.expression}function yO(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=YD(),i=$e(g=>g.frame.calculatedFields),a=$e(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?h8(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(x=>{const b=`${x.name}-${x.role||"unknown"}`;g.set(b,x)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(Ec),x=((a==null?void 0:a.groupByColumns)||[]).filter(ky),y=Knt([...g,...x]).filter(v=>{const S=`${v.name}-${v.role||"unknown"}`,C=f.get(S);if(!C)return!0;const N=m8(v),k=m8(C);return N&&k?N!==k:!0});return h8(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==p9),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function vO(e){const{tokenProps:t,authToken:n}=tt(),r=t==null?void 0:t.apiServiceUrl;return en({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return xr(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 Yre(e,t,n){if(t==="source")return{isValid:!0};const r=Nr(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};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 Gre(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=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function Znt(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const Kre=e=>{var F;const t=(F=e==null?void 0:e.dataSource)==null?void 0:F.semanticDomainId,{data:n}=vO(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=br(),h=$e(R=>R.card.type),m=e==null?void 0:e.id,p=(R,$)=>{if(R.id)return R.id;const q=R.qualifiedEntityName||R.entityName||$;return`${$}-${q}-${R.name}`},g=w.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return Znt(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),x=w.useCallback((R,$)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),b=w.useCallback((R,$,q)=>{if(!m)return;const U=g(R),W=U[$];if(W)switch(R){case"groupBy":s(m,W.id,{label:q});break;case"metrics":o(m,W.id,{label:q});break;case"pivotBy":i(m,W.id,{label:q});break;case"sortBy":a(m,W.id,{label:q});break;case"detailColumns":{const A=U.map((L,O)=>O===$?{...L,label:q}:L);r(m,{detailColumns:A});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{aggregate:$,label:_q(U.name,$)})},[m,g,o]),v=w.useCallback((R,$,q,U="groupBy")=>{if(!m)return;const W=g(U),A=W[R];if(!A)return;const L={dateFormat:$,customFormat:$==="custom"&&q?q:void 0};if(U==="detailColumns"){const O=W.map((I,V)=>V===R?{...I,...L}:I);r(m,{detailColumns:O});return}s(m,A.id,L)},[m,g,r,s]),S=w.useCallback((R,$)=>{if(!m)return;const U=g("groupBy")[R];U&&s(m,U.id,{granularity:$})},[m,g,s]),C=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{aliasTemplate:$})},[m,g,o]),N=w.useCallback((R,$)=>{if(console.log("handleValueAliasesChange",R,$),!m)return;console.log("handleValueAliasesChange",R,$);const U=g("metrics")[R];U&&(console.log("handleValueAliasesChange",$),o(m,U.id,{valueAliases:$}))},[m,g,o]),k=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),E=w.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),M=w.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),j=w.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),_=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async R=>{var I;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],q=R,U=$Ne(q,$,{joinPlan:(I=e==null?void 0:e.config)==null?void 0:I.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!U.isValid){U.showError&&jq();return}const W=BNe(q,$,h);if(!W){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const A=Yre(q,W,h);if(!A.isValid){We.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3});return}const L=g(W);if(kq(q,L))return;const O=Tq(q,W,L);if(O){const V=[...L,O];x(W,V),W==="metrics"&&Gre(h,e==null?void 0:e.config,r,m,V)}},[m,e==null?void 0:e.config,g,x,t,n,h,r]),P=w.useCallback((R,$)=>{if(!m)return;const U=g(R)[$];if(U){if(R!=="sortBy"){const W=g("sortBy"),A=W.filter(L=>!(L.name===U.name&&L.qualifiedEntityName===U.qualifiedEntityName));A.length!==W.length&&r(m,{sortByColumns:A})}switch(R){case"groupBy":c(m,U.id);break;case"metrics":u(m,U.id);break;case"pivotBy":d(m,U.id);break;case"sortBy":f(m,U.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((W,A)=>A!==$)});break}}}},[m,g,c,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:x,updateLabel:b,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:C,handleValueAliasesChange:N,removeField:P,handleFieldClick:T,handleMetricComparisonChange:k,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:M,handleKpiTrendlineGranularityChange:j,handleMetricTargetValueChange:_,cardType:h}};function JN(e,t){var Ie,ze,Qe,Te,Ye,rt,Je,Be;const{tokenProps:n}=tt(),r=us(),s=tt().authToken||e,o=$e(ye=>ye.selectedConnectionId),i=$e(ye=>ye.card),{queryKey:a}=oge(i),c=$e(ye=>ye.selectedDatamodelId),u=$e(ye=>ye.isDevMode),d=$e(ye=>ye.selectedDatabaseName),f=$e(ye=>ye.selectedSchemaName),h=$e(ye=>ye.selectedTableName),m=$e(ye=>ye.actions.setSelectedConnectionId),p=$e(ye=>ye.actions.setSelectedDatamodelId),g=$e(ye=>ye.actions.setSelectedDatabaseName),x=$e(ye=>ye.actions.setSelectedSchemaName),b=$e(ye=>ye.actions.setSelectedTableName);$e(ye=>ye.actions.setCardSql);const{setQueryConfig:y}=br();function v(ye){var Fe;if(!o||!ye)return!1;const it=((Fe=M==null?void 0:M.capabilities)==null?void 0:Fe.path)||[],Ve=it.includes("database"),et=it.includes("schema");return!(!it.includes("table")||Ve&&(!d||d==="NA")||et&&!f)}function S(ye){var it;return!o||!ye?!1:!!((it=M==null?void 0:M.capabilities)!=null&&it.path.includes("database"))}const{refetchConnections:C,connectionsData:N,isConnectionsLoading:k,isConnectionsError:E,selectedConnection:M}=pi(e),{refetch:j,data:_,isLoading:T,isError:P}=en({queryKey:["models",o],queryFn:()=>xr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),F=M==null?void 0:M.type,R=((Ie=M==null?void 0:M.capabilities)==null?void 0:Ie.path.includes("schema"))??!1,$=((ze=M==null?void 0:M.capabilities)==null?void 0:ze.path.length)===1&&((Qe=M==null?void 0:M.capabilities)==null?void 0:Qe.path[0])==="table",q=$,{data:U,isLoading:W,isFetching:A,isError:L,refetch:O}=en({queryKey:["databases",o],queryFn:()=>xr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:S(F)}),{data:I,isLoading:V,isFetching:Y,isError:G,refetch:z}=en({queryKey:["schemas",o,d],queryFn:()=>xr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:B,isLoading:H,isFetching:K,isError:ee,refetch:X}=en({queryKey:["tables",o,d,f],queryFn:()=>xr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(F)}),{columns:re,isColumnsLoading:le,isColumnsFetching:ue,isColumnsError:ce,refetchColumns:Se}=Mq(e);w.useEffect(()=>{$&&(g(""),x(""),p(""),F==="API"&&b("api"))},[F,b,g,x,p,$]);const se=(M==null?void 0:M.type)==="API"?(Te=M==null?void 0:M.type)==null?void 0:Te.toLowerCase():h||"",ke=R&&f||"";function pe(ye){b(ye),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function De(ye){x(ye),b("")}function Pe(ye){g(ye==="none"?"":ye),x(""),b(""),ye!=="none"&&ye!==""&&p("")}function ge(ye){m(ye)}function ve(ye){p(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}U&&((Ye=U==null?void 0:U.databases)==null?void 0:Ye.length)>0,I&&((rt=I==null?void 0:I.schemas)==null?void 0:rt.length)>0;const ie=N==null?void 0:N.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),J=(Je=_==null?void 0:_.datamodels)==null?void 0:Je.map(ye=>({id:ye.id,name:ye.name})),oe=U==null?void 0:U.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),we=I==null?void 0:I.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),Ne=B==null?void 0:B.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),_e=(Be=_==null?void 0:_.datamodels.find(ye=>ye.id===c))==null?void 0:Be.name,me=M!=null&&M.capabilities?Pw({schemaName:ke,tableName:se,modelName:_e,databaseName:d||"",capabilities:M.capabilities}):se;return{connectionItems:ie,selectedConnectionId:o,selectedConnection:M,isConnectionsLoading:k,isConnectionsError:E,modelItems:J,selectedDatamodelId:c,selectedDatamodelName:_e,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:oe,isDatabasesLoadingOrFetching:W||A,isDatabaseError:L,schemaItems:we,selectedSchemaName:f,isSchemaLoadingOrFetching:V||Y,isSchemaError:G,tableItems:Ne,selectedTableName:h,isTableLoadingOrFetching:H||K,isTableError:ee,columns:re,isColumnsLoadingOrFetching:le||ue,isColumnsError:ce,isNonDbConnection:q,connectionType:F,tableName:se,formattedTableName:me,schemaName:ke,refetchConnections:C,refetchModels:j,refetchDatabases:O,refetchSchemas:z,refetchTables:X,refetchColumns:Se,handleConnectionChange:ge,handleDatamodelChange:ve,handleDatabaseChange:Pe,handleSchemaChange:De,handleTableChange:pe}}function Xv(e){return`${e}-${gr()}`}function p8(e,t){const n=ui(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 Xnt(e,t){const n=ui(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function wO(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 Zre(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Xre(){const e=$e(k=>k.sqlGen),t=$e(k=>k.isDevMode),n=$e(k=>k.card.dataSource),r=$e(k=>{var E,M;return(M=(E=k.card)==null?void 0:E.queryConfig)==null?void 0:M.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=wO(n),a=Zre(n),c=$e(k=>k.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=br(),{modelItems:g,selectedDatamodelName:x}=JN(),{selectedConnection:b}=pi(),y=b==null?void 0:b.capabilities,v=k=>({column_name:k.name,data_type:k.dataType,label:k.label,description:k.description});return{handleDevModeFieldClick:k=>{var M;if(!t)return;const E=v(k);if(t&&a&&s&&y){const j=VM(E,e);m(j);const _=(M=g==null?void 0:g.find(P=>P.id===c))==null?void 0:M.name,T=BM(j,o||"",s,_||"",i||"",y,k.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(ty(E.data_type))if(r&&r.length>0){const j={...E,role:"groupby",id:Xv(E.column_name),name:E.column_name,type:E.data_type};d(j)}else{const j={...E,role:"metric",id:Xv(E.column_name),name:E.column_name,label:p8(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(j)}if(ha(E.data_type)){const j={...E,role:"groupby",id:Xv(E.column_name),name:E.column_name,type:E.data_type,label:Xnt(E.column_name,"month"),granularity:"month"};d(j)}if(fa(E.data_type)){const j={...E,role:"metric",id:Xv(E.column_name),name:E.column_name,label:p8(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(j)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const k=Pw({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});p(!1);const M=(b==null?void 0:b.type)==="MSSQL"?`SELECT top 10 * FROM ${k}`:`SELECT * FROM ${k} LIMIT 10`;f(M),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const k=Pw({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${k}`),h(!0)},isNumberField:k=>fa(k.dataType)}}function Qnt(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>Hx(o)).join("."),s=Hx(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Qre(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Jre(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function ese(e){var t,n;return e?!!(e.entityName===Sc||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function tse(){const e=Q(c=>c.dashboard.filters)||[],t=Q(c=>c.selectedSheetId),n=Q(c=>c.actions.addFilter),r=Q(c=>c.actions.removeFilter),{removeFilterValues:s}=un(),o=$e(c=>c.card.dataSource),{selectedConnection:i}=pi();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Qnt(c);let m;if(u==="sheet"&&t?m=uTe(e,d,f,t):m=e==null?void 0:e.find(p=>Zm(p.column)===Zm(d)),m)s(m.id),r(m.id);else{const p=gr(),g=Qre(c),x=Jre(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),b=ese(g),y=u==="sheet"&&t?[t]:void 0,v=Nr(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:b?"":HX(c.dataType,f,h),fieldMeta:g,semanticContext:x}),p}}return{assignFilter:a}}function Jnt({column:e}){const[t,n]=w.useState(!1),r=$e(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=wO(r),a=$e(y=>y.selectedDatamodelId),c=$e(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=JN(),f=d==null?void 0:d.capabilities,h=$e(y=>y.actions.setSqlGen),m=$e(y=>y.actions.setCardSql),p=$e(y=>y.actions.setRunSql),g=Zre(r);function x(y,v){var E,M;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=VM(y,c,v),C=(E=u==null?void 0:u.find(j=>j.id===a))==null?void 0:E.name;if(h(S),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const N=(M=y.qualifiedFieldName)==null?void 0:M.split(".").slice(0,-1).join("."),k=BM(S,o||"",s,C||"",i||"",f,N);k&&(m(k),p(!0)),n(!1)}function b(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>x(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>x(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>x(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>x(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>x(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?l.jsxs(vp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(wp,{asChild:!0,children:l.jsx(dp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Sp,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function ert({field:e,fieldState:t}){return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function g8({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=$e(X=>X.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=Q(X=>X.dashboard.filters),d=Q(X=>X.selectedSheetId),f=Q(X=>X.actions.removeFilter),{removeFilterValues:h}=un(),{assignFilter:m}=tse(),p=t==="filter"?Tc(u,d):u,g=t==="filter"?p==null?void 0:p.find(X=>{if(X.title===e.name)return!0;const re=Zm(X.column||""),le=Zm(e.name);return re.endsWith(`.${le}`)||re===le}):void 0,x=!!g,b=t==="inline-filter"&&(s==null?void 0:s.some(X=>X.column===e.qualifiedFieldName||X.column===e.name)),y=x||b,v=g&&a?u==null?void 0:u.find(X=>X.id===g.id):void 0,S=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:S,selectedSheetId:d});const[C,N]=w.useState(!1),[k,E]=w.useState(null),{attributes:M,listeners:j,setNodeRef:_,transform:T,transition:P,isDragging:F}=c0({id:e.id,disabled:c}),[R,$]=w.useState(!1),q=$e(X=>X.card),{handleFieldClick:U}=Kre(q),{handleDevModeFieldClick:W,isNumberField:A}=Xre(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),N(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&S?(E(e),N(!0)):m(e,"sheet"):i?W(e):U(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},V={transform:zi.Transform.toString(T),transition:P},Y=()=>{if(!n||a)return{};const re={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",...re},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...re},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...re}}[n.state]||re};function G(X){return X==="domain"?{label:"Domain",Icon:oy,className:"border-border bg-muted text-foreground"}:X==="dashboard"?{label:"Dashboard",Icon:fI,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:y7,className:"border-border bg-muted/40 text-foreground"}}const z=Y(),B=e.fieldScope,H=B?G(B):null,K=C1(e),ee=K&&Ec(e);return l.jsxs("div",{ref:_,style:V,...c?{}:M,...c?{}:j,className:Z("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",F&&"scale-95 opacity-50",!F&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,x&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[l.jsxs("div",{className:"relative shrink-0",children:[sp(e.dataType),K&&l.jsx("span",{className:Z("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",ee?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx(nr,{children:l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.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})})}),l.jsx(Mn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(ert,{field:e,fieldState:n})})]})}),t==="editor"&&H&&l.jsx("span",{title:H.label,className:Z("shrink-0 rounded-full border p-1",H.className),children:l.jsx(H.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&A(e)&&l.jsx("div",{onClick:X=>X.stopPropagation(),children:l.jsx(Jnt,{column:I})}),o&&l.jsx("div",{className:"ml-auto flex items-center",onClick:X=>X.stopPropagation(),onPointerDown:X=>X.stopPropagation(),children:o})]}),R&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Vo,{className:"",children:l.jsxs(Pi,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(v7,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Jle,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(st,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(eh,{open:C,onOpenChange:N,children:l.jsxs(Uu,{children:[l.jsxs(Hu,{children:[l.jsx(qu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Yu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Wu,{children:[l.jsx(Ku,{children:"Cancel"}),l.jsx(Gu,{onClick:L,children:"Remove Filter"})]})]})})]})}let nse=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Ub=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],Pl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Gl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function x8(e,t,n,r,s,o,i,a,c,u){const d=Ub.find(b=>b.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=Pl(e);return{id:i||`calc_${nse(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:Sc,entityType:"table",description:`Calculated field: ${e}`}}function trt(e){var r,s;const t=Ub.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function nrt(e,t,n,r,s,o){const i=Pl(e);return{id:o||`calc_dim_${nse(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Sc,entityType:"table",description:`Calculated field: ${e.trim()}`}}function rrt(){const{domainCalculatedFields:e}=yO(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function srt({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(Fs,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(js,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(cn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function ort({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const x of g){const b=u(p,x);if(b!==p)return b}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx($n,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:l.jsx(Vt,{className:"size-3.5"})})]}),l.jsx(wl,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(_b,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(vu,{value:f.id,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",x=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:Z("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[sp(h.dataType),h.isCalculated&&l.jsx("span",{className:Z("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:Z("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:x})}),m&&l.jsx(st,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function irt({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Ub.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Ub.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(bt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(pt,{children:l.jsx(wt,{})}),l.jsx(gt,{children:l.jsxs(pA,{children:[l.jsx(UC,{children:"OPERATIONS"}),i.map(c=>l.jsx(Ee,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const art={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function lrt({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Nr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(bt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(pt,{className:"h-9",children:l.jsx(wt,{})}),l.jsx(gt,{children:c.map(u=>l.jsx(Ee,{value:u,children:art[u]},u))})]})}const crt=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function b8({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return l.jsxs("div",{className:Z("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(bt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(pt,{className:"h-9 flex-1",children:l.jsx(wt,{placeholder:"Select field"})}),l.jsx(gt,{children:f.map(h=>l.jsx(Ee,{value:h.id,children:crt(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(lrt,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:c})})]}),t&&l.jsx(te,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Vt,{className:"h-3.5 w-3.5"})})]})}const y8=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&l.jsxs(te,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[l.jsx(iy,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),l.jsx(np,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function urt({result:e}){const t=e.errors.length>0;return l.jsxs("div",{className:Z("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[l.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>l.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>l.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>l.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&l.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function v8({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(te,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&l.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&l.jsx(urt,{result:n||r})]})}function drt({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[l.jsx(de,{children:"Availability"}),l.jsxs(As,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-card",value:"card"}),l.jsx(de,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(de,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-domain",value:"domain"}),l.jsx(de,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function frt({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-description",children:"Description"}),l.jsx(ja,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:Z("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(sn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function hrt({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=tt(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await ls(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function mrt({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=hrt({endpoint:o,availableFields:n,fieldType:r,dialect:i}),x=w.useMemo(()=>{const N=f.trim().toLowerCase();return N?n.filter(k=>[k.label,k.baseLabel,k.name,k.tokenLabel,k.entityName,k.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(N)):n},[n,f]),b=N=>{const E=(N.name||N.baseLabel||N.label||N.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=N=>{const k=N.entityName||N.qualifiedEntityName||"";return k?k==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":k.includes(".")&&k.split(".").pop()||k:"—"},v=async()=>{const N=await m(a.trim());N&&d(N)},S=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},C=()=>{c(""),d(""),h(""),t(!1)};return l.jsx(Wr,{open:e,onOpenChange:N=>{N?t(!0):C()},children:l.jsxs(Rr,{className:"max-w-3xl",children:[l.jsxs(Pr,{children:[l.jsx(Or,{children:"Generate Expression with AI"}),l.jsx(Xr,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(np,{id:"ai-prompt",value:a,onChange:N=>c(N.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(te,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&l.jsx("p",{className:"text-xs text-destructive",children:g})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(sn,{value:f,onChange:N=>h(N.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx("div",{className:"max-h-48 overflow-y-auto",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:l.jsxs("tr",{children:[l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),l.jsx("tbody",{className:"divide-y",children:x.length===0?l.jsx("tr",{children:l.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):x.map(N=>l.jsxs("tr",{className:"hover:bg-muted/30",children:[l.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:b(N)}),l.jsx("td",{className:"px-3 py-1.5",children:l.jsx(st,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:N.dataType})}),l.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(N)})]},N.id))})]})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Generated expression"}),l.jsx(np,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),l.jsxs(Ns,{className:"gap-2",children:[l.jsx(te,{variant:"ghost",onClick:C,children:"Cancel"}),l.jsx(te,{onClick:S,disabled:!u.trim(),children:"Use Expression"})]})]})})}const prt=/\{([^}]+)\}/g;function ej(e){return e.trim().toLowerCase()}function CS(e){return Array.from(e.matchAll(prt)).map(t=>t[1]).filter(Boolean)}function grt(e){const t=new Set,n=[];return e.forEach(r=>{const s=ej(r);t.has(s)||(t.add(s),n.push(r))}),n}function SO(e){const t=new Map,n=(r,s)=>{const o=ej(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function Og(e,t){const n=CS(e),r=grt(n),s=SO(t),o=r.map(a=>{const c=s.get(ej(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function w8(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${xrt(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function xrt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const brt=e=>e.entityName===km||e.entityName===Sc?"Calculated Fields":e.qualifiedEntityName?qx(e.entityName||e.qualifiedEntityName):qx(e.entityName||"Other"),yrt=e=>Nr(e.dataType||"")==="number";function vrt(e,t,n){const r=new Set((n||[]).map(s=>Gl(s)));return e.filter(s=>{const o=Gl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function wrt(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Sc?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function Srt(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||yrt(o);return{...o,isCompatible:i}}).filter(o=>r)}function Crt(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function Nrt(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:brt(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function jrt({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>vrt(e,t,r),[e,t,r]),a=w.useMemo(()=>wrt(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Ec(m)||m.role==="groupby"&&ky(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>SO(c),[c]),d=w.useMemo(()=>Srt(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>Crt(d,n),[d,n]),h=w.useMemo(()=>Nrt(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const krt=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},Ert=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},_rt=(e,t)=>t.map(r=>({candidate:r,distance:Ert(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),Trt=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},Mrt=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function Irt({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=tt(),[a,c]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>SO(t),[t]),p=w.useMemo(()=>{const b=[],y=[],v=e.trim();v||b.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!krt(v)&&b.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const C=CS(e).map(k=>{const E=m.get(ej(k))||[];if(!E.length){const _=Array.from(m.keys()),T=_rt(k,_),P=T.length?`Did you mean {${T[0]}}?`:void 0;return b.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${k}}`,suggestion:P}),{token:k,field:null,error:"Unknown token"}}if(E.length>1)return b.push({code:"UNKNOWN_TOKEN",message:`Token {${k}} matches multiple fields. Use a disambiguated label.`}),{token:k,field:null,error:"Ambiguous token"};const M=E[0];return(n||[]).map(Gl).includes(Gl(M.id))?(b.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:k,field:null,error:"Self reference"}):{token:k,field:M}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const N=C.map(k=>k.field).filter(Boolean);return{isValid:b.length===0,tokens:C,errors:b,warnings:y,inferredDataType:Trt(e,N)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return c(p),p;const b=r,y={type:"calculated-field-expression",value:e,context:{availableFields:Mrt(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const S=await ls(b,(i==null?void 0:i.accessToken)||"",y),C=S.errors||[],N=S.warnings||[],k={...p,isValid:S.valid&&C.length===0,errors:C,warnings:N,inferredDataType:((v=S.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return c(k),k}catch(S){return h((S==null?void 0:S.error)||"Validation failed"),c(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),x=w.useCallback(()=>{c(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:x}}const S8=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],rE=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},rse=e=>Nr(e.dataType||"")==="number",Fh=e=>rse(e)?"SUM":"COUNT",sE=(e,t)=>rse(e)||t==="COUNT"||t==="DISTINCT"?t:Fh(e);function oE(e,t){if(e.role==="metric"){const n=e;return Ec(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function Mh(e,t){const n=e.role==="metric"&&Ec(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function sse({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var He;const{tokenProps:m}=tt(),{selectedConnection:p}=Cq(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[x,b]=w.useState(f),[y,v]=w.useState(""),[S,C]=w.useState("ratio"),[N,k]=w.useState(null),[E,M]=w.useState(null),[j,_]=w.useState(1),[T,P]=w.useState(""),[F,R]=w.useState(null),[$,q]=w.useState("card"),[U,W]=w.useState(""),[A,L]=w.useState(""),[O,I]=w.useState({}),[V,Y]=w.useState("A"),[G,z]=w.useState(""),[B,H]=w.useState(!1),[K,ee]=w.useState(null),[X,re]=w.useState(!1),[le,ue]=w.useState(!1),[ce,Se]=w.useState(!1),se=w.useRef(null),ke=w.useRef(!1),pe=w.useRef(null),{userContext:De}=so(),{metrics:Pe,dimensions:ge}=rrt(),ve=(De==null?void 0:De.type)==="organization",ie=!ve,J=!!d&&ve,oe=J&&!!a,we=J&&!!c,Ne=!!(i||oe||we),_e=!!i,me=x==="metric"?oe:we,Ie=(He=m==null?void 0:m.apiServiceUrl)==null?void 0:He.replace(/\/$/,""),ze=Ie?`${Ie}/v1/validate`:"/v1/validate",Qe=Ie?`${Ie}/v1/ai/generate`:"/v1/ai/generate",Te=w.useMemo(()=>{var yt;const xe=[...n];return(((yt=r==null?void 0:r.calculatedFormula)==null?void 0:yt.inputFields)||[]).forEach(Ce=>{xe.some(ft=>ft.id===Ce.id||ft.qualifiedFieldName===Ce.qualifiedFieldName||ft.name===Ce.name)||xe.push(Ce)}),xe},[n,r]),Ye=V==="A"?N:E,rt=x==="metric"&&S!=="custom"?Ye==null?void 0:Ye.aggregate:void 0,{allFields:Je,groups:Be}=jrt({fields:Te,mode:x,searchTerm:G,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:rt,showIncompatible:!0}),ye=Je,{clientResult:it,validationResult:Ve,validateExpression:et,isValidating:Rt,serverError:Fe,resetValidation:je}=Irt({expression:T,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:ze,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),Le=(Ve==null?void 0:Ve.inferredDataType)||it.inferredDataType,ut=F||Le||"string",ct=Ub.find(xe=>xe.id===S),fe=w.useMemo(()=>{if(!y.trim())return!1;const xe=Pl(y),nt=s==="domain"&&(r!=null&&r.name)?Pl(r.name):null;return(x==="metric"?Pe:ge).some(Ce=>{const Ge=Pl(Ce.name);return nt&&Ge===nt?!1:Ge===xe})},[ge,Pe,r,s,x,y]),qe=w.useMemo(()=>{if(x==="metric"&&S==="custom"){const{orderedFields:nt}=Og(T,ye);return nt.filter(yt=>!!yt).map(yt=>yt.id)}const xe=[];return N!=null&&N.field.id&&xe.push(N.field.id),E!=null&&E.field.id&&xe.push(E.field.id),xe},[ye,T,x,N,E,S]),lt=xe=>{ie||(b(xe),xe==="dimension"&&$==="domain"&&!we&&q("card"),xe==="metric"&&$==="domain"&&!oe&&q("card"))},Pt=xe=>{ie||(C(xe),xe==="scale"&&M(null),xe==="custom"&&(k(null),M(null)))},$t=()=>{v(""),C("ratio"),k(null),M(null),_(1),P(""),R(null),q("card"),W(""),L(""),I({}),z(""),H(!1),ee(null),re(!1),Se(!1),je(),t(!1)},_n=w.useCallback(xe=>Te.find(nt=>nt.qualifiedFieldName===xe.qualifiedFieldName||nt.name===xe.name)||xe,[Te]),or=w.useCallback(xe=>{if(!xe.calculatedFormula)return;const nt=xe.calculatedFormula;if(C(nt.operation),P(""),nt.operation==="scale"){const Ge=nt.inputFields[0];Ge&&k(Mh(_n(Ge),Ge.aggregate||"SUM")),_(nt.constant===void 0?1:nt.constant);return}if(nt.operation==="custom"){P(ns(xe.expression||"",nt.inputFields||[])),k(null),M(null);return}const[yt,Ce]=nt.inputFields;yt&&k(Mh(_n(yt),yt.aggregate||"SUM")),Ce&&M(Mh(_n(Ce),Ce.aggregate||"SUM"))},[_n]),ns=w.useCallback((xe,nt)=>xe.replace(/\{field_(\d+)\}/g,(yt,Ce)=>{var mt;const Ge=nt[Number(Ce)];return Ge?`{${((mt=ye.find(Ct=>Ct.id===Ge.id))==null?void 0:mt.tokenLabel)||Ge.label||Ge.name}}`:yt}),[ye]);w.useEffect(()=>{var yt;if(!e){ke.current=!1,pe.current=null;return}const xe=r?`${r.role}-${r.id||r.name}`:"new";if(ke.current&&pe.current===xe)return;if(ke.current=!0,pe.current=xe,I({}),z(""),Se(!1),je(),r){const Ce=r.tags||[];if(r.role==="metric"){b("metric"),v(r.label||r.name),q(s||"card"),W(r.description||""),L(Ce.join(", ")),or(r);return}b("dimension");const Ge=r;v(Ge.label||Ge.name),q(s||"card"),P(ns(Ge.expression||"",((yt=Ge.calculatedFormula)==null?void 0:yt.inputFields)||[]));const ft=S8.some(mt=>mt.value===Ge.dataType)?Ge.dataType:"string";R(ft),W(Ge.description||""),L(Ce.join(", "));return}const nt=h&&h.length>0?h.includes(f)?f:h[0]:f;b(nt),v(""),C("ratio"),k(null),M(null),_(1),P(""),R(null),q("card"),W(""),L("")},[e,r,s,f,h,or,ns,je]);const $s=xe=>{const nt=`{${xe}}`,yt=se.current;if(!yt){P(mt=>mt+nt);return}const Ce=yt.selectionStart||0,Ge=yt.selectionEnd||0,ft=`${T.slice(0,Ce)}${nt}${T.slice(Ge)}`;P(ft),requestAnimationFrame(()=>{yt.focus();const mt=Ce+nt.length;yt.setSelectionRange(mt,mt)})},qi=xe=>{if(ie)return;if(x==="dimension"||S==="custom"){$s(xe.tokenLabel||xe.label||xe.name);return}const nt=sE(xe,V==="A"?(N==null?void 0:N.aggregate)||Fh(xe):(E==null?void 0:E.aggregate)||Fh(xe)),yt=Mh(xe,nt);if(V==="A"){k(yt),E||Y("B");return}M(yt),N||Y("A")},ks=(xe,nt)=>{if(!ie){if(xe==="A"&&N){k({...N,aggregate:nt});return}xe==="B"&&E&&M({...E,aggregate:nt})}},_o=async()=>{const xe={};if(y.trim()||(xe.name="Name is required"),S==="custom")T.trim()||(xe.expression="Expression is required"),CS(T).length===0&&(xe.expression=xe.expression||"Expression must include field tokens"),Og(T,ye).unresolvedTokens.length>0&&(xe.expression=xe.expression||"Expression contains unknown or ambiguous tokens"),xe.expression||(await et()).isValid||(xe.expression="Fix validation errors before saving");else if(S==="scale")N||(xe.inputA="Please select a metric for input A"),Number.isNaN(j)&&(xe.constant="Please enter a valid multiplication factor");else{if(N||(xe.inputA="Please select a metric for input A"),E||(xe.inputB="Please select a metric for input B"),N&&E){const nt=N.field.id===E.field.id,yt=N.aggregate===E.aggregate;nt&&yt&&(xe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const nt=Gl(r.id);(Gl(N==null?void 0:N.field.id)===nt||Gl(E==null?void 0:E.field.id)===nt)&&(xe.inputs="Cannot reference the field being edited")}}return Ne&&($==="domain"&&!oe&&(xe.scope="You do not have permission to save to domain"),$==="domain"&&!U.trim()&&(xe.description="Description is required for domain fields"),$==="domain"&&fe&&(xe.name="A domain field with this name already exists")),I(xe),Object.keys(xe).length===0},Nl=async()=>{const xe={};return y.trim()||(xe.name="Name is required"),T.trim()||(xe.expression="Expression is required"),CS(T).length===0&&(xe.expression=xe.expression||"Expression must include field tokens"),Og(T,ye).unresolvedTokens.length>0&&(xe.expression=xe.expression||"Expression contains unknown or ambiguous tokens"),xe.expression||(await et()).isValid||(xe.expression="Fix validation errors before saving"),Ne&&($==="domain"&&!we&&(xe.scope="You do not have permission to save to domain"),$==="domain"&&!U.trim()&&(xe.description="Description is required for domain fields"),$==="domain"&&fe&&(xe.name="A domain field with this name already exists")),I(xe),Object.keys(xe).length===0},jl=()=>{const{orderedTokens:xe,orderedFields:nt}=Og(T,ye),yt=nt.filter(ft=>!!ft),Ce=w8(T,xe),Ge=nrt(y,Ce,yt,ut,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Ge}:Ge},kl=()=>{var Ce;if(S==="custom"){const{orderedTokens:Ge,orderedFields:ft}=Og(T,ye),mt=ft.filter(Ft=>!!Ft),Ct=(r==null?void 0:r.role)==="metric"?((Ce=r.calculatedFormula)==null?void 0:Ce.inputFields)||[]:[],Tt=new Map;Ct.forEach(Ft=>{const Rn=Gl(Ft.id);Rn&&Tt.set(Rn,Ft),Ft.qualifiedFieldName&&Tt.set(Ft.qualifiedFieldName,Ft),Ft.name&&Tt.set(Ft.name,Ft)});const Lr=mt.map(Ft=>{const Rn=Gl(Ft.id),qo=Rn&&Tt.get(Rn)||Ft.qualifiedFieldName&&Tt.get(Ft.qualifiedFieldName)||Tt.get(Ft.name),hh=((qo==null?void 0:qo.role)==="metric"?qo.aggregate:void 0)||(Ft.role==="metric"?Ft.aggregate:void 0)||Fh(Ft);return oE(Ft,hh)}),Bt=w8(T,Ge),Ot=x8(y,S,null,null,{},u,r==null?void 0:r.id,Bt,void 0,Lr);return r&&r.role==="metric"?{...r,...Ot}:Ot}const xe=N?oE(N.field,N.aggregate):null,nt=E?oE(E.field,E.aggregate):null,yt=x8(y,S,xe,nt,{},u,r==null?void 0:r.id,void 0,S==="scale"?j:void 0);return r&&r.role==="metric"?{...r,...yt}:yt},El=async xe=>{var yt,Ce,Ge;if(x==="dimension"){const ft=jl();if(xe==="dashboard"){if(!i){I(mt=>({...mt,scope:"Dashboard scope is not available"}));return}i(ft),$t();return}if(xe==="domain"){if(!c){I(Ot=>({...Ot,scope:"Domain scope is not available"}));return}const mt=((yt=ft.calculatedFormula)==null?void 0:yt.inputFields)||[],Ct=new Map,Tt=mt.map(Ot=>{const Ft=Pl(Ot.label||Ot.name),Rn=Ct.get(Ft)||0;return Ct.set(Ft,Rn+1),Rn===0?Ft:`${Ft}_${Rn+1}`}),Lr=((Ce=ft.expression)==null?void 0:Ce.replace(/\{field_(\d+)\}/g,(Ot,Ft)=>`{${Tt[Number(Ft)]||Ft}}`))||"",Bt=Tt.reduce((Ot,Ft,Rn)=>{const qo=mt[Rn];return ky(qo)?Ot[Ft]={dimension:qo.name}:Ot[Ft]={dataset:qo.entityName,field:qo.name},Ot},{});try{await c({name:Pl(y),label:y.trim(),description:U.trim(),expression:Lr,inputs:Bt,dataType:ut,tags:A.split(",").map(Ot=>Ot.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Ot){I(Ft=>({...Ft,scope:(Ot==null?void 0:Ot.message)||"Failed to save to domain"}));return}$t();return}o(ft),$t();return}const nt=kl();if(xe==="dashboard"){if(!i){I(ft=>({...ft,scope:"Dashboard scope is not available"}));return}i(nt),$t();return}if(xe==="domain"){if(!a){I(Bt=>({...Bt,scope:"Domain scope is not available"}));return}if(!nt.calculatedFormula){I(Bt=>({...Bt,scope:"Calculated formula missing"}));return}const ft=nt.calculatedFormula.inputFields,mt=new Map,Ct=ft.map(Bt=>{const Ot=Pl(Bt.label||Bt.name),Ft=mt.get(Ot)||0;return mt.set(Ot,Ft+1),Ft===0?Ot:`${Ot}_${Ft+1}`}),Tt=((Ge=nt.expression)==null?void 0:Ge.replace(/\{field_(\d+)\}/g,(Bt,Ot)=>`{${Ct[Number(Ot)]||Ot}}`))||"",Lr=Ct.reduce((Bt,Ot,Ft)=>{const Rn=ft[Ft];return Rn.role==="metric"?Ec(Rn)?Bt[Ot]={metric:Rn.name}:Bt[Ot]={dataset:Rn.entityName,field:Rn.name,aggregate:Rn.aggregate}:Bt[Ot]={dataset:Rn.entityName,field:Rn.name},Bt},{});try{await a({name:Pl(y),label:y.trim(),description:U.trim(),expression:Tt,inputs:Lr,tags:A.split(",").map(Bt=>Bt.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Bt){I(Ot=>({...Ot,scope:(Bt==null?void 0:Bt.message)||"Failed to save to domain"}));return}$t();return}o(nt),$t()},xt=async()=>{if(ie)return;if(I({}),x==="metric"){if(!await _o())return}else if(!await Nl())return;const xe=Ne?$:s||"card";if(x==="metric"&&xe!=="domain"&&fe&&!r){ee(xe),re(!0);return}ue(!0);try{await El(xe)}finally{ue(!1)}},he=w.useMemo(()=>{if(!ct||S==="custom")return"";if(S==="scale"){const xe=Number.isFinite(j)?j:1;return`${rE(N)} x ${xe}`}return`${rE(N)||"A"} ${ct.symbol} ${rE(E)||"B"}`},[ct,S,N,E,j]);return l.jsxs(l.Fragment,{children:[l.jsxs(Wr,{modal:!1,open:e,onOpenChange:xe=>{xe?t(!0):$t()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Rr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:xe=>{xe.preventDefault()},children:[l.jsxs(Pr,{children:[l.jsxs(Or,{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xr,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(ort,{groups:Be,searchTerm:G,onSearchTermChange:z,onFieldClick:qi,selectedFieldIds:qe,disabled:ie}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Field Type"}),l.jsx(srt,{value:x,onChange:lt,disabled:ie||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"calculated-name",children:"Name"}),l.jsx(sn,{id:"calculated-name",value:y,onChange:xe=>v(xe.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":"",disabled:ie}),O.name&&l.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),x==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Operation"}),l.jsx(irt,{value:S,onChange:Pt,allowCustom:!0,disabled:ie}),O.operation&&l.jsx("p",{className:"text-xs text-red-500",children:O.operation})]}),S==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(y8,{ref:se,value:T,onChange:xe=>{P(xe),Se(!1)},onGenerate:()=>H(!0),showGenerate:!!Qe&&!ie,disabled:ie}),l.jsx(v8,{onValidate:async()=>{Se(!0),await et()},isValidating:Rt,validationResult:Ve,fallbackResult:it,error:Fe,showFallback:ce,disabled:ie}),O.expression&&l.jsx("p",{className:"text-xs text-red-500",children:O.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(de,{children:"Inputs"}),l.jsx(b8,{label:"A",input:N,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:xe=>{const nt=sE(xe,(N==null?void 0:N.aggregate)||Fh(xe));k(Mh(xe,nt))},onAggregateChange:xe=>ks("A",xe),onRemove:()=>k(null),onActivate:()=>Y("A"),allowMedian:g,disabled:ie}),O.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:O.inputA}),S!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(b8,{label:"B",input:E,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:xe=>{const nt=sE(xe,(E==null?void 0:E.aggregate)||Fh(xe));M(Mh(xe,nt))},onAggregateChange:xe=>ks("B",xe),onRemove:()=>M(null),onActivate:()=>Y("B"),allowMedian:g,disabled:ie}),O.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),S==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(sn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(j)?"":j,onChange:xe=>_(xe.target.value===""?Number.NaN:Number(xe.target.value)),className:O.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ie}),O.constant&&l.jsx("p",{className:"text-xs text-red-500",children:O.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:he||"Select inputs to preview formula"}),O.inputs&&l.jsxs(aN,{variant:"destructive",children:[l.jsx(xc,{className:"h-4 w-4"}),l.jsx(lN,{children:O.inputs})]})]})]}),x==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(y8,{ref:se,value:T,onChange:xe=>{P(xe),Se(!1)},onGenerate:()=>H(!0),showGenerate:!!Qe&&!ie,disabled:ie}),l.jsx(v8,{onValidate:async()=>{Se(!0),await et()},isValidating:Rt,validationResult:Ve,fallbackResult:it,error:Fe,showFallback:ce,disabled:ie}),O.expression&&l.jsx("p",{className:"text-xs text-red-500",children:O.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Output Type"}),l.jsxs(bt,{value:ut,onValueChange:xe=>R(xe),disabled:ie,children:[l.jsx(pt,{className:"h-9 w-full",children:l.jsx(wt,{placeholder:"Select output type"})}),l.jsx(gt,{children:S8.map(xe=>l.jsx(Ee,{value:xe.value,children:xe.label},xe.value))})]}),Le&&!F&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",Le]})]})]}),Ne&&(_e||me)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(drt,{scope:$,onChange:q,showDashboardScope:_e,showDomainScope:me,error:O.scope,disabled:ie}),$==="domain"&&l.jsx(frt,{description:U,tags:A,onDescriptionChange:W,onTagsChange:L,descriptionError:O.description,disabled:ie})]})]})]}),l.jsxs(Ns,{children:[l.jsx(te,{variant:"outline",onClick:$t,children:"Cancel"}),l.jsxs(te,{onClick:xt,disabled:le||ie,children:[r?"Update":"Create"," ",x==="metric"?"Metric":"Dimension"]})]})]})]}),l.jsx(mrt,{open:B,onOpenChange:H,availableFields:ye,fieldType:x,onExpressionGenerated:async xe=>{P(xe),Se(!1),je()},endpoint:Qe,dialect:p==null?void 0:p.dialect}),l.jsx(eh,{open:X,onOpenChange:re,children:l.jsxs(Uu,{children:[l.jsxs(Hu,{children:[l.jsx(qu,{children:"Name Conflict"}),l.jsxs(Yu,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",K==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Wu,{children:[l.jsx(Ku,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Gu,{onClick:async()=>{if(K){re(!1),ue(!0);try{await El(K)}finally{ue(!1),ee(null)}}},children:"Continue"})]})]})})]})}function ose({domainId:e}){const{authToken:t,tokenProps:n}=tt(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!c){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(c,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const ise=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var je,Le,ut,ct;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");$e(fe=>fe.isDevMode);const x=$e(fe=>fe.card.dataSource),b=$e(fe=>fe.card.config),y=$e(fe=>fe.card),v=$e(fe=>fe.frame),S=$e(fe=>fe.actions.updateCardConfig),C=$e(fe=>fe.actions.updateFrame),{userContext:N}=so(),{autoJoinMetadata:k}=ul(y),{columns:E,rawColumnGroups:M,scopedFields:j,dashboardCalculatedFields:_,cardCalculatedFields:T,isLoading:P,error:F,refetch:R}=yO(),$=(x==null?void 0:x.mode)==="semanticDomain"?x.semanticDomainId:void 0,{data:q}=vO($),{promoteMetric:U,promoteDimension:W}=ose({domainId:$}),A=w.useMemo(()=>[...(b==null?void 0:b.groupByColumns)||[],...(b==null?void 0:b.metricColumns)||[],...(b==null?void 0:b.detailColumns)||[]],[b==null?void 0:b.groupByColumns,b==null?void 0:b.metricColumns,b==null?void 0:b.detailColumns]);(Le=(je=b==null?void 0:b.joinPlan)==null?void 0:je.baseEntity)==null||Le.name,(ct=(ut=k==null?void 0:k.resolvedJoinPlan)==null?void 0:ut.baseEntity)==null||ct.name,Xre();const L=t==="editor",O=(N==null?void 0:N.type)==="organization",I=L?j:E,V=M,Y=s.toLowerCase(),G=(b==null?void 0:b.metricColumns)||[],z=(b==null?void 0:b.groupByColumns)||[],B=w.useCallback(async fe=>{await U(fe),R()},[U,R]),H=w.useCallback(async fe=>{await W(fe),R()},[W,R]),K=fe=>fe.name.toLowerCase().includes(Y)||fe.dataType.toLowerCase().includes(Y)||fe.label&&fe.label.toLowerCase().includes(Y)||fe.qualifiedEntityName&&fe.qualifiedEntityName.toLowerCase().includes(Y),ee=fe=>(fe.label||fe.name).toLowerCase().trim(),X=(fe,qe)=>ee(fe).localeCompare(ee(qe),void 0,{numeric:!0,sensitivity:"base"}),re=I.filter(K).sort(X),le=fe=>{if(fe.role==="metric"&&Ec(fe)||fe.role==="groupby"&&fe.expression)return"calculated";if(fe.dataType==="number"||fe.dataType==="integer"||fe.dataType==="float"||fe.dataType==="decimal"||fe.dataType==="currency")return"metrics";const qe=Nr(fe.dataType);return["date","string","boolean"].includes(qe)?"dimensions":qe==="number"?"metrics":"dimensions"},ue=fe=>{const qe=fe.filter(K);return i==="all"?qe:qe.filter(lt=>le(lt)===i)},ce=i==="all"?re:re.filter(fe=>le(fe)===i),Se=L?[..._,...T]:[],se=L?ue(Se).sort(X):[],pe=ue(E).sort(X).reduce((fe,qe)=>{const lt=qe.qualifiedEntityName||"Other Fields";return fe[lt]||(fe[lt]={label:qx(qe.entityName),fields:[]}),fe[lt].fields.push(qe),fe},{}),De=w.useMemo(()=>Object.entries(pe).map(([fe,qe])=>{const lt=V.find($t=>$t.entityName===fe)||{entityName:fe,label:qe.label},Pt=fe===km?"Domain Calculated Fields":lt.label||lt.entityName;return{groupName:fe,groupLabel:Pt,fields:[...qe.fields].sort(X)}}).sort((fe,qe)=>fe.groupLabel.localeCompare(qe.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[pe,V]),Pe=fe=>fe.id||`${fe.entityName}-${fe.qualifiedEntityName}-${fe.name}-${fe.role||"field"}`,ge=w.useMemo(()=>{const fe=new Map;return(L?j:E).forEach(lt=>{fe.set(Pe(lt),GD(lt,{joinabilityMap:(q==null?void 0:q.joinabilityMap)||null,selectedFields:A,cardConfig:b,autoJoinMetadata:k}))}),fe},[L,j,E,q==null?void 0:q.joinabilityMap,A,b,k]),ve=L?[{key:"scope-calculated",label:"Calculated Fields",fields:se}].filter(fe=>fe.fields.length>0):[],J=[...ve.map(fe=>fe.key),...De.map(fe=>fe.groupName)],oe=re.filter(fe=>le(fe)==="dimensions").length,we=re.filter(fe=>le(fe)==="metrics").length,Ne=re.filter(fe=>le(fe)==="calculated").length,_e=re.length>0&&t!=="inline-filter",me=t==="inline-filter"?"w-full":"w-[290px]";if(P)return l.jsx("div",{className:Z("flex h-full flex-col items-center justify-center py-8",me),children:l.jsx(Cc,{size:"md",color:"muted","aria-label":"Loading data"})});if(F)return l.jsxs("div",{className:Z("flex h-full flex-col items-center justify-center py-8",me),children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:F.message||"Failed to load column data"})]});if(!x||!x.selectedEntities||x.selectedEntities.length===0)return l.jsxs("div",{className:Z("flex flex-col items-center justify-center py-8 text-center",me),children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="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 Ie=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",ze=t==="inline-filter"?"overflow-hidden":"",Qe=fe=>fe!=null&&fe.startsWith("card-source-")?fe.replace("card-source-",""):fe,Te=(fe,qe,lt)=>{const Pt=Qe(fe.id),$t=Qe(qe.id);return Pt&&$t&&Pt===$t?!0:!Pt||!$t||lt!=null&<.allowNameFallback?fe.name===qe.name&&fe.role===qe.role:!1},Ye=(fe,qe,lt)=>fe.findIndex(Pt=>Te(Pt,qe,lt)),rt=fe=>{if(!v)return fe;const qe=v.calculatedFields||[],lt=Ye(qe,fe),Pt=lt>=0&&qe[lt].id!==fe.id?{...fe,id:qe[lt].id}:fe,$t=lt>=0?qe.map((_n,or)=>or===lt?Pt:_n):[...qe,Pt];return C({calculatedFields:$t}),Pt},Je=(fe,qe,lt,Pt)=>{var _n;const $t=Ye(fe,lt||qe,Pt);if($t>=0){const or=(_n=fe[$t])==null?void 0:_n.id,ns=or&&or!==qe.id?{...qe,id:or}:qe;return fe.map(($s,qi)=>qi===$t?ns:$s)}return[...fe,qe]},Be=fe=>{if(fe.role==="metric")return G.find(qe=>Te(qe,fe));if(fe.role==="groupby")return z.find(qe=>Te(qe,fe))},ye=fe=>{var qe;return(qe=v==null?void 0:v.calculatedFields)==null?void 0:qe.find(lt=>Te(lt,fe))},it=fe=>{if(fe.role==="metric"){S(y.id,{metricColumns:G.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))});return}fe.role==="groupby"&&S(y.id,{groupByColumns:z.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))})},Ve=fe=>{if(!v)return;const qe=(v.calculatedFields||[]).filter(lt=>!Te(lt,fe));C({calculatedFields:qe})},et=fe=>{if(!O)return;if(fe.fieldScope==="domain"){f(fe),m("domain"),g(fe.role==="metric"?"metric":"dimension"),u(!0);return}if(fe.fieldScope==="dashboard"){const lt=ye(fe);if(!lt)return;f(lt),m("dashboard"),g(lt.role==="metric"?"metric":"dimension"),u(!0);return}const qe=Be(fe);qe&&(f(qe),m("card"),g(qe.role==="metric"?"metric":"dimension"),u(!0))},Rt=fe=>{if(O&&fe.fieldScope!=="domain"){if(fe.fieldScope==="dashboard"){Ve(fe),it(fe);return}it(fe)}},Fe=fe=>{if(!O)return null;const qe=fe.fieldScope==="domain";return l.jsxs(Qf,{children:[l.jsx(Jf,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:l.jsx(d7,{className:"h-4 w-4"})})}),l.jsxs(Vu,{align:"end",className:"w-40",children:[l.jsx($o,{onClick:()=>et(fe),children:"Edit"}),l.jsx($o,{disabled:qe,onClick:()=>Rt(fe),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Z("mt-2 flex h-full w-full grow flex-col gap-2",Ie,ze),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[I.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx($n,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:fe=>o(fe.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Vt,{className:"size-3.5"})})]}),_e&&l.jsx(Fs,{defaultValue:"all",value:i,onValueChange:fe=>a(fe),className:"mb-4",children:l.jsxs(js,{className:"grid h-9 w-full grid-cols-4",children:[l.jsxs(cn,{value:"all",className:"text-xs",children:["All",l.jsx("span",{className:"ml-2 text-xs font-semibold",children:re.length})]}),l.jsxs(cn,{value:"dimensions",className:"text-xs",children:[l.jsx(BS,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:oe})]}),l.jsxs(cn,{value:"metrics",className:"text-xs",children:[l.jsx(OS,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:we})]}),l.jsxs(cn,{value:"calculated",className:"text-xs",children:[l.jsx(rI,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:Ne})]})]})}),t==="editor"&&i==="calculated"&&O&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(te,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Ar,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(wl,{className:"min-h-0 flex-1",children:[l.jsxs(_b,{type:"multiple",defaultValue:J,className:"space-y-2",children:[ve.map(fe=>l.jsxs(vu,{value:fe.key,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:fe.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:fe.fields.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:fe.fields.map(qe=>{const lt=ge.get(Pe(qe)),Pt=t==="editor"&&i==="calculated";return l.jsx(g8,{field:qe,context:t,fieldState:lt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Pt?Fe(qe):void 0},qe.id)})})})]},fe.key)),De.map(({groupName:fe,groupLabel:qe,fields:lt})=>l.jsxs(vu,{value:fe,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:qe,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:qe}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:lt.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:lt.map(Pt=>{const $t=ge.get(Pe(Pt));return l.jsx(g8,{field:Pt,context:t,fieldState:$t,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Pt.id)})})})]},fe))]}),I.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),I.length>0&&ce.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Fi,{orientation:"horizontal"}),l.jsx(Fi,{orientation:"vertical"})]})]}),l.jsx(sse,{open:c,onOpenChange:fe=>{u(fe),fe||(f(null),m("card"))},availableFields:j,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:fe=>{if(fe.role==="metric"){if(d&&h==="card"){S(y.id,{metricColumns:Je(G,fe,d)});return}S(y.id,{metricColumns:Je(G,fe)});return}if(d&&h==="card"){S(y.id,{groupByColumns:Je(z,fe,d)});return}S(y.id,{groupByColumns:Je(z,fe)})},onSaveToDashboard:fe=>{const qe=!!(d&&h==="dashboard"),lt=qe?d:void 0;if(fe.role==="metric"){const $t=rt(fe);S(y.id,{metricColumns:Je(G,$t,lt,{allowNameFallback:qe})});return}const Pt=rt(fe);S(y.id,{groupByColumns:Je(z,Pt,lt,{allowNameFallback:qe})})},cardId:y.id,onPromoteMetricToDomain:$?B:void 0,onPromoteDimensionToDomain:$?H:void 0,domainId:$})]})}),ase=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(ise,{context:t})," "]})});function lse(){const e=$e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=br();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=wO(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(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Drt(){lse();const e=Q(c=>c.selectedSheetId),t=Q(c=>c.selectedFrameId),n=Q(c=>c.dashboard),r=Q(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=un(),{setCard:o}=br(),i=$e(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){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),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Art(){const e=Q(o=>o.dashboard.filterLayout),{setFilterLayout:t}=un(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(vs,{children:[l.jsx(ws,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(cc,{className:"h-4 w-4"})})}),l.jsx(Ss,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(As,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Sn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Sn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(yn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(de,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(yn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(de,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Rrt(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=Drt();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Art,{}),l.jsx(te,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(JJ,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(a0,{collisionDetection:s0,children:l.jsx(l0,{items:[],strategy:TP,children:l.jsx(ase,{context:"filter"})})})})]})}function Prt(){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?l.jsx("div",{className:Z("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(SP,{filter:r}),l.jsx(Qp,{filter:r})]},r.id))}):null}function Ort(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Z("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Prt,{}),l.jsx(Hre,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Rrt,{})})]})}const Frt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-WfvdR-3x.js"))),$rt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DSuO96w0.js"))),Lrt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BMMl4vZv.js"))),zrt=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DN4YQNga.js")).then(e=>({default:e.ResourceManagementPanel})));function Brt({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(c=>c.isDashboardPanelOpen),s=Q(c=>c.isVisualEditing),o=Q(c=>c.showDashboardJSON),i=Q(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(ya,{FallbackComponent:vN,children:l.jsxs(nI,{dashboardProps:n,children:[l.jsx(Khe,{}),l.jsx(bO,{componentType:"surfboard",componentId:n.id}),l.jsx(xO,{children:l.jsxs(Wre,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Lrt,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Frt,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(zrt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(CA,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx($rt,{})}),l.jsx(Ort,{})]})})]})]})]})})]})})}const cse=D.forwardRef(({className:e,...t},n)=>l.jsx(u0,{className:Z("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(IP,{className:Z("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));cse.displayName=u0.displayName;var Vrt=Object.defineProperty,Urt=(e,t,n)=>t in e?Vrt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Qv=(e,t,n)=>Urt(e,typeof t!="symbol"?t+"":t,n);const Hrt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Wrt={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}},qrt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Yrt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function use(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Grt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=use(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Krt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Zrt={stringify:e=>e,parse:e=>e},iE={string:Zrt,number:Krt,boolean:Hrt,function:Wrt,method:Grt,json:qrt},Fg=Symbol.for("r2wc.render"),Jv=Symbol.for("r2wc.connected"),Cd=Symbol.for("r2wc.context"),Zo=Symbol.for("r2wc.props");function Xrt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Yrt(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(),Qv(this,o,!0),Qv(this,s),Qv(this,r,{}),Qv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Zo].container=this.container;for(const p of i){const g=d[p],x=this.getAttribute(g),b=c[p],y=b?iE[b]:null;if(b==="method"){const v=use(g);Object.defineProperty(this[Zo].container,v,{enumerable:!0,configurable:!0,get(){return this[Zo][v]},set(S){this[Zo][v]=S,this[Fg]()}}),this[Zo][p]=y.parse(x,g,this)}y!=null&&y.parse&&x&&(this[Zo][p]=y.parse(x,g,this))}for(const p of a)this[Zo][p]=g=>{const x=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Jv]=!0,this[Fg]()}disconnectedCallback(){this[Jv]=!1,this[Cd]&&n.unmount(this[Cd]),delete this[Cd]}attributeChangedCallback(p,g,x){const b=f[p],y=c[b],v=y?iE[y]:null;b in c&&v!=null&&v.parse&&x&&(this[Zo][b]=v.parse(x,p,this),this[Fg]())}[(o=Jv,s=Cd,r=Zo,Fg)](){this[Jv]&&(this[Cd]?n.update(this[Cd],this[Zo]):this[Cd]=n.mount(this.container,e,this[Zo]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Zo][m]},set(x){this[Zo][m]=x;const b=g?iE[g]:null;if(b!=null&&b.stringify){const y=b.stringify(x,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Fg]()}})}return h}function Qrt(e,t,n){const r=loe.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Jrt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function est({root:e}){e.unmount()}function tst(e,t={}){return Xrt(e,t,{mount:Qrt,update:Jrt,unmount:est})}const nst={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"},rst=tst(qre,{props:nst});function C8(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function sst(e){if(Array.isArray(e))return e}function ost(e,t,n){return(t=fst(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ist(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function ast(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1088
|
+
`)}})}});var Vtt=Pet(()=>yre(Bi([wr({type:rn("text-start"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("text-delta"),id:kt(),delta:kt(),providerMetadata:zr.optional()}),wr({type:rn("text-end"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("error"),errorText:kt()}),wr({type:rn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:Do().optional(),dynamic:Do().optional()}),wr({type:rn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),wr({type:rn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:Fa(),providerExecuted:Do().optional(),providerMetadata:zr.optional(),dynamic:Do().optional()}),wr({type:rn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:Fa(),providerExecuted:Do().optional(),providerMetadata:zr.optional(),dynamic:Do().optional(),errorText:kt()}),wr({type:rn("tool-output-available"),toolCallId:kt(),output:Fa(),providerExecuted:Do().optional(),dynamic:Do().optional(),preliminary:Do().optional()}),wr({type:rn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:Do().optional(),dynamic:Do().optional()}),wr({type:rn("reasoning-start"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:zr.optional()}),wr({type:rn("reasoning-end"),id:kt(),providerMetadata:zr.optional()}),wr({type:rn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:zr.optional()}),wr({type:rn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:zr.optional()}),wr({type:rn("file"),url:kt(),mediaType:kt(),providerMetadata:zr.optional()}),wr({type:mre(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:Fa(),transient:Do().optional()}),wr({type:rn("start-step")}),wr({type:rn("finish-step")}),wr({type:rn("start"),messageId:kt().optional(),messageMetadata:Fa().optional()}),wr({type:rn("finish"),finishReason:dre(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Fa().optional()}),wr({type:rn("abort")}),wr({type:rn("message-metadata"),messageMetadata:Fa()})])));function Utt(e){return e.type.startsWith("data-")}function Ere(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]=Ere(o,s):n[r]=s}return n}function Htt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function _re(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await vS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await vS({text:Htt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ew(e){return e.type.startsWith("tool-")}function Wtt(e){return e.type==="dynamic-tool"}function bM(e){return Ew(e)||Wtt(e)}function c8(e){return e.type.split("-").slice(1).join("-")}function qtt({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 Ytt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(S){const N=u.message.parts.filter(Ew).find(k=>k.toolCallId===S);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(S){const N=u.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===S);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(S){var C;const N=u.message.parts.find(M=>Ew(M)&&M.toolCallId===S.toolCallId),k=S,E=N;N!=null?(N.state=S.state,E.input=k.input,E.output=k.output,E.errorText=k.errorText,E.rawInput=k.rawInput,E.preliminary=k.preliminary,E.providerExecuted=(C=k.providerExecuted)!=null?C:N.providerExecuted,k.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:`tool-${S.toolName}`,toolCallId:S.toolCallId,state:S.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function y(S){var C,N;const k=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===S.toolCallId),E=S,M=k;k!=null?(k.state=S.state,M.toolName=S.toolName,M.input=E.input,M.output=E.output,M.errorText=E.errorText,M.rawInput=(C=E.rawInput)!=null?C:M.rawInput,M.preliminary=E.preliminary,M.providerExecuted=(N=E.providerExecuted)!=null?N:k.providerExecuted,E.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:S.toolName,toolCallId:S.toolCallId,state:S.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(S){if(S!=null){const C=u.message.metadata!=null?Ere(u.message.metadata,S):S;t!=null&&await s8({value:C,schema:t}),u.message.metadata=C}}switch(a.type){case"text-start":{const S={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=S,u.message.parts.push(S),d();break}case"text-delta":{const S=u.activeTextParts[a.id];S.text+=a.delta,S.providerMetadata=(f=a.providerMetadata)!=null?f:S.providerMetadata,d();break}case"text-end":{const S=u.activeTextParts[a.id];S.state="done",S.providerMetadata=(h=a.providerMetadata)!=null?h:S.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const S={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=S,u.message.parts.push(S),d();break}case"reasoning-delta":{const S=u.activeReasoningParts[a.id];S.text+=a.delta,S.providerMetadata=(m=a.providerMetadata)!=null?m:S.providerMetadata,d();break}case"reasoning-end":{const S=u.activeReasoningParts[a.id];S.providerMetadata=(p=a.providerMetadata)!=null?p:S.providerMetadata,S.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 S=u.message.parts.filter(Ew);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:S.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const S=u.partialToolCalls[a.toolCallId];S.text+=a.inputTextDelta;const{value:C}=await _re(S.text);S.dynamic?y({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:C}):b({toolCallId:a.toolCallId,toolName:S.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,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):b({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,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):b({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 S=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-available",input:S.input,output:a.output,preliminary:a.preliminary})}else{const S=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:c8(S),state:"output-available",input:S.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const S=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-error",input:S.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const S=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:c8(S),state:"output-error",input:S.input,rawInput:S.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),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(Utt(a)){(n==null?void 0:n[a.type])!=null&&await s8({value:a.data,schema:n[a.type]});const S=a;if(S.transient){i==null||i(S);break}const C=S.id!=null?u.message.parts.find(N=>S.type===N.type&&S.id===N.id):void 0;C!=null?C.data=S.data:u.message.parts.push(S),i==null||i(S),d()}}c.enqueue(a)})}}))}async function Gtt({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()}}g0({prefix:"aitxt",size:24});g0({prefix:"aiobj",size:24});var Ktt=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()})}};g0({prefix:"aiobj",size:24});var Ztt={};Dtt(Ztt,{object:()=>Qtt,text:()=>Xtt});var Xtt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Qtt=({schema:e})=>{const t=Mtt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await _re(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 vS({text:n});if(!s.success)throw new a8({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 fO({value:s.value,schema:t});if(!o.success)throw new a8({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Jtt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var ent=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 Th(this.body),c=await Th(this.headers),u=await Th(this.credentials),d={...Td(c),...Td(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?Td(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:n8({"Content-Type":"application/json",...m},`ai-sdk/${l8}`,t8()),body:JSON.stringify(p),credentials:g,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 Th(this.body),a=await Th(this.headers),c=await Th(this.credentials),u={...Td(a),...Td(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?Td(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:n8(h,`ai-sdk/${l8}`,t8()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},mO=class extends ent{constructor(e={}){super(e)}processResponseStream(e){return $et({stream:e,schema:Vtt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},tnt=class{constructor({generateId:e=_et,id:t=e(),transport:n=new mO,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Ktt,this.sendMessage=async(f,h)=>{var m,p,g,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let b;if("text"in f||"files"in f?b={parts:[...Array.isArray(f.files)?f.files:await Jtt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:b=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,{...b,id:f.messageId,role:(p=b.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...b,id:(g=b.id)!=null?g:this.generateId(),role:(x=b.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(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.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var x,b;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(S=>bM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(S=>bM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(b=this.lastMessage)==null?void 0:b.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:qtt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}p=x}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=x=>this.jobExecutor.run(()=>x({state:m.state,write:()=>{var b;this.setStatus({status:"streaming"}),m.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Gtt({stream:Ytt({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function Tre({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(bM).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function nnt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var rnt=nnt;const snt=Uf(rnt);var Mre=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},ar=(e,t,n)=>(Mre(e,t,"read from private field"),n?n.call(e):t.get(e)),Da=(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)},Vc=(e,t,n,r)=>(Mre(e,t,"write to private field"),t.set(e,n),n);function ont(e,t){return t!=null?snt(e,t):e}var bi,_w,Tw,lx,cx,ux,Ph,yM,vM,int=class{constructor(e=[]){Da(this,bi,void 0),Da(this,_w,"ready"),Da(this,Tw,void 0),Da(this,lx,new Set),Da(this,cx,new Set),Da(this,ux,new Set),this.pushMessage=t=>{Vc(this,bi,ar(this,bi).concat(t)),ar(this,Ph).call(this)},this.popMessage=()=>{Vc(this,bi,ar(this,bi).slice(0,-1)),ar(this,Ph).call(this)},this.replaceMessage=(t,n)=>{Vc(this,bi,[...ar(this,bi).slice(0,t),this.snapshot(n),...ar(this,bi).slice(t+1)]),ar(this,Ph).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ont(t,n):t;return ar(this,lx).add(r),()=>{ar(this,lx).delete(r)}},this["~registerStatusCallback"]=t=>(ar(this,cx).add(t),()=>{ar(this,cx).delete(t)}),this["~registerErrorCallback"]=t=>(ar(this,ux).add(t),()=>{ar(this,ux).delete(t)}),Da(this,Ph,()=>{ar(this,lx).forEach(t=>t())}),Da(this,yM,()=>{ar(this,cx).forEach(t=>t())}),Da(this,vM,()=>{ar(this,ux).forEach(t=>t())}),Vc(this,bi,e)}get status(){return ar(this,_w)}set status(e){Vc(this,_w,e),ar(this,yM).call(this)}get error(){return ar(this,Tw)}set error(e){Vc(this,Tw,e),ar(this,vM).call(this)}get messages(){return ar(this,bi)}set messages(e){Vc(this,bi,[...e]),ar(this,Ph).call(this)}};bi=new WeakMap;_w=new WeakMap;Tw=new WeakMap;lx=new WeakMap;cx=new WeakMap;ux=new WeakMap;Ph=new WeakMap;yM=new WeakMap;vM=new WeakMap;var Oh,u8=class extends tnt{constructor({messages:e,...t}){const n=new int(e);super({...t,state:n}),Da(this,Oh,void 0),this["~registerMessagesCallback"]=(r,s)=>ar(this,Oh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>ar(this,Oh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>ar(this,Oh)["~registerErrorCallback"](r),Vc(this,Oh,n)}};Oh=new WeakMap;function Ire({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new u8(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new u8(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function ant(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function lnt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function cnt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function unt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Dre(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:unt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Are(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 dnt(){var x;const{authToken:e,tokenProps:t}=tt(),n=Q(b=>b.dashboard.aiScopeTables),r=(x=RS().data)==null?void 0:x.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:c,addToolResult:u,error:d,stop:f,clearError:h}=Ire({transport:new mO({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const b=_c.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:b.currentAIContext,reasoningEffort:b.reasoningEffort,showReasoning:b.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:b,body:y})=>({body:{...y,messages:ZG(b)}})}),onToolCall:m,sendAutomaticallyWhen:Tre,onFinish({isAbort:b,isDisconnect:y,isError:v}){console.log(b?"[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(b){var y;if(b.name==="AbortError"||(y=b.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",b)}});async function m({toolCall:b}){if(b.toolName==="getCurrentTableScope"&&u({tool:b.toolName,toolCallId:b.toolCallId,output:{tables:Dre(n||[])}}),b.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:b.toolName,toolCallId:b.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(c),g=Are(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:c,stop:f,errorMessage:g,clearError:h}}function Rre(){var u;const{authToken:e,tokenProps:t}=tt(),n=(u=RS().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=en({queryKey:["assistant-profile",n],queryFn:()=>xr(`${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 Pre({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(l7,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(te,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function fnt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=Ll-n;if(c.length>u){We.error(`You can only attach ${Ll} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=wne(c);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>sO(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ll}),l.jsx(te,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ll,title:n>=Ll?`Maximum ${Ll} files allowed`:"Attach files",children:l.jsx(gI,{className:"h-4 w-4 text-muted-foreground"})})]})}function hnt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.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=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.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=Ll-r;if(h.length>m){We.error(`You can only attach ${Ll} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=wne(h);if(g.forEach(({file:x,error:b})=>{We.error(`${x.name}: ${b}`)}),p.length>0)try{const x=await Promise.all(p.map(b=>sO(b)));t(x),We.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),We.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:Z("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(jI,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ll-r," slot(s) available"]})]})})]})}function Ore(e){return e.type==="dataset"&&e.label||e.name}function mnt(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 pnt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(de,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(st,{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:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),Ore(n),l.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:l.jsx(Vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function gnt(e){const{tokenProps:t}=tt(),n=Q(c=>c.authToken)||e;$e(c=>c.selectedConnectionId),$e(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=en({queryKey:["semantic-domains"],queryFn:()=>xr(`${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 xnt(e,t){const{tokenProps:n}=tt(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=en({queryKey:["datasets",e],queryFn:()=>xr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function bnt(e){var g,x;const{tokenProps:t}=tt(),n=Q(b=>b.authToken)||e,{connections:r}=pi(e),s=$e(b=>{var y,v;return(v=(y=b==null?void 0:b.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(b=>b.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(b){var y;return!s||!b?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=en({queryKey:["databases",s],queryFn:()=>xr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(x=d==null?void 0:d.databases)==null?void 0:x.map(b=>({id:b.database_name,name:b.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function ynt(e){var g;const{tokenProps:t}=tt(),n=Q(x=>x.authToken)||e,{connections:r}=pi(e),s=$e(x=>{var b,y;return(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.connectionId}),o=$e(x=>{var b,y,v;return(v=(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(x=>x.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var x;return!(!s||!((x=i==null?void 0:i.capabilities)!=null&&x.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=en({queryKey:["schemas",s,o],queryFn:()=>xr(`${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(x=>({id:x.schema_name,name:x.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function Fre(e){const{tokenProps:t}=tt(),n=Q(h=>h.authToken)||e,{connections:r}=pi(e),s=$e(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:c,error:u,refetch:d}=en({queryKey:["dataModels",s],queryFn:()=>xr(`${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:c,error:u,dataModels:f||[],refetch:d}}function vnt(){var C,N,k;const e=$e(E=>E.card.dataSource);$e(E=>E.actions.updateDirectSource);const t=$e(E=>E.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=pi(),{databases:i,isPending:a,error:c,label:u}=bnt(),{schemas:d,isPending:f,error:h,label:m}=ynt(),{error:p}=Fre(),g=s==null?void 0:s.capabilities.path.includes("schema"),x=s==null?void 0:s.capabilities.path.includes("database"),b=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},S=E=>{var j;if(!((j=e==null?void 0:e.dbSelection)!=null&&j.database))return;const M=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...M,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(te,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[x&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:u}),l.jsxs(bt,{value:((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)||"",onValueChange:v,disabled:a,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(Nn,{className:"h-4 w-4 animate-spin"}),l.jsx(wt,{placeholder:c?`Error loading ${b}`:a?`Loading ${b}...`:`Select ${b}...`})]})}),l.jsx(gt,{children:i.map(E=>l.jsx(Ee,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:m}),l.jsxs(bt,{value:((k=e==null?void 0:e.dbSelection)==null?void 0:k.schema)||"",onValueChange:S,disabled:f,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(Nn,{className:"h-4 w-4 animate-spin"}),l.jsx(wt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(gt,{children:d.map(E=>l.jsx(Ee,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function wnt(){const e=$e(c=>c.card.dataSource),t=$e(c=>c.actions.updateDataSource),[n,r]=w.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).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=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Upload Files"}),l.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:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(jI,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(te,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pa,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},c.id))})]})]})}function Snt(){const e=$e(f=>f.card.dataSource),t=$e(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),c=()=>{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 l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(sn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(sn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-xs text-gray-600",children:"Type"}),l.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:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(te,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(Ar,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(oy,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function Cnt(e,t){var y,v;const{tokenProps:n}=tt(),r=Q(S=>S.authToken)||t,{connections:s}=pi(t),o=$e(S=>{var C,N;return(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.connectionId}),i=$e(S=>{var C,N,k;return(k=(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.dbSelection)==null?void 0:k.database}),a=$e(S=>{var C,N,k;return(k=(N=(C=S==null?void 0:S.card)==null?void 0:C.dataSource)==null?void 0:N.dbSelection)==null?void 0:k.schema}),c=s==null?void 0:s.find(S=>S.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const S=(u==null?void 0:u.path)||[];return!(S.includes("database")&&!i||S.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:x}=en({queryKey:[e,o,i,a],queryFn:()=>xr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),b=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(S=>{var C;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(C=S==null?void 0:S.table_type)==null?void 0:C.toLowerCase(),id:S[`${e}_name`],database:i,schema:a,name:S[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:b||[],refetch:x,label:d}}function wS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx(xc,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function Nnt({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=pi(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=br(),{entities:p,isLoading:g,error:x}=Cnt("table"),{dataModels:b,isPending:y,error:v}=Fre(),S=j=>{const _=s.find(P=>P.id===j);if(!_)return;const T=_.type==="upload"?"upload":_.type==="url"?"url":"database";h({...e,connectionId:j,connectionType:_.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(j)},C=j=>{var F,R;const _=n||[],T=_.some($=>$.name===j.name&&$.type===j.type);let P;if(T)P=_.filter($=>!($.name===j.name&&$.type===j.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:j.type,dbObjectType:j.dbObjectType,database:((F=e.dbSelection)==null?void 0:F.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:j.name,dialect:j.dialect};P=[..._,$]}t==null||t(P)},N=j=>{const _=n||[],T=_.some(F=>F.type==="model"&&F.name===j.name);let P;T?P=_.filter(F=>!(F.type==="model"&&F.name===j.name)):P=[..._,j],t==null||t(P)},k=p.filter(j=>j.name.toLowerCase().includes(i.toLowerCase())),E=b.filter(j=>j.name.toLowerCase().includes(c.toLowerCase())),M=w.useCallback(()=>{if(!t)return;const j=n||[];let _=[...j];if(d==="tables"){const P=k.filter(F=>!j.some(R=>R.name===F.name&&R.type==="table")).map(F=>{var R,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:F.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:F.name,dialect:F.dialect}});_=[...j,...P]}else if(d==="datamodels"){const T=E.filter(P=>!j.some(F=>F.name===P.name&&F.type==="model"));_=[...j,...T]}t(_)},[d,k,E,n,e,t]);return w.useEffect(()=>{r&&r(M)},[r,M]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(bt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:S,disabled:o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(wt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(gt,{children:s.map(j=>l.jsx(Ee,{className:"hover:bg-muted",value:j.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(Ja,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:j.name}),l.jsx(st,{variant:"secondary",className:"flex-shrink-0 text-xs",children:j.type})]})},j.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(wnt,{}),e.connectionType==="url"&&l.jsx(Snt,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(vnt,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(Fs,{defaultValue:"tables",value:d,onValueChange:j=>f(j),className:"w-full",children:[l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsxs(cn,{value:"tables",children:["Tables & Views (",k.length,")"]}),l.jsxs(cn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),l.jsxs(cr,{value:"tables",className:"space-y-2",children:[l.jsx($n,{placeholder:"Search tables and views...",value:i,onChange:j=>a(j.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):x?l.jsx(wS,{title:"Error loading tables",message:x.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):k.map(j=>{const _=n.some(T=>T.name===j.name&&T.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(j),children:[l.jsx(yn,{id:`table-${j.name}`,checked:_,onCheckedChange:()=>C(j),onClick:T=>T.stopPropagation(),disabled:g}),l.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[j.name,j.dbObjectType==="view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),j.dbObjectType==="materialized view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},j.name)})})]}),l.jsxs(cr,{value:"datamodels",className:"space-y-2",children:[l.jsx($n,{placeholder:"Search data models...",value:c,onChange:j=>u(j.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(wS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(j=>{const _=n.some(T=>T.name===j.name&&T.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(j),children:[l.jsx(yn,{id:`dataModel-${j.name}`,checked:_,onCheckedChange:()=>N(j),onClick:T=>T.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer",children:j.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:j.description})]})]},j.name)})})]})]})})})]})]})]})}function jnt({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=B8.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var S;const[a,c]=w.useState(""),u=w.useCallback(C=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...N})},[e,t]);w.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=gnt(),m=d.filter(C=>{var N,k;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(C.id))??!1;case"exclude":return!(((k=s.domainIds)==null?void 0:k.includes(C.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:x}=xnt(e==null?void 0:e.semanticDomainId),b=C=>{const N=r||[],k=N.some(M=>M.id===C.id&&M.type==="dataset");let E;if(k)E=N.filter(M=>!(M.id===C.id&&M.type==="dataset"));else{const M={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};E=[...N,M]}n==null||n(E)},y=p.filter(C=>C.name.toLowerCase().includes(a.toLowerCase())),v=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],k=y.filter(M=>!C.some(j=>j.id===M.id&&j.type==="dataset")).map(M=>({id:M.id,datasetType:M.type,name:M.name||M.table,label:M.label,domainId:M.domainId,description:M.description,database:M.database,schema:M.schema,type:"dataset",connectionId:M.connectionId,connectionType:M.connectionType,dialect:M.dialect,datamodelId:M.datamodelId,sql:M.sql})),E=[...C,...k];n(E)},[y,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(bt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(wt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),l.jsx(gt,{children:m.map(C=>l.jsx(Ee,{className:"hover:bg-muted",value:C.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:C.label}),l.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),h&&l.jsx(wS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx($n,{placeholder:"Search datasets...",value:a,onChange:C=>c(C.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?l.jsx(wS,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(C=>{const N=r.some(k=>k.id===C.id&&k.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>b(C),children:[l.jsx(yn,{id:`dataset-${C.id}`,checked:N,onCheckedChange:()=>b(C),onClick:k=>k.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer font-medium",children:C.label||C.name}),l.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function knt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Ent({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!knt(e,t,n):r}function _nt(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function pO({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o}){var A,L;const{tokenProps:i}=tt(),a=i.semanticDomainAccess||B8.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[c,u]=w.useState([]),[d,f]=w.useState(void 0),{updateDataSource:h}=br(),m=Q(O=>O.isVisualEditing),p=Q(O=>O.dashboard.aiContext),{setAiContext:g}=un(),x=w.useRef(null),[b,y]=w.useState(!1),v=a.mode,S=v==="include"||v==="exclude",C=v!=="all",N=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,E=v==="include"&&(((A=a.domainIds)==null?void 0:A.length)||0)===1?(L=a.domainIds)==null?void 0:L[0]:void 0,M=w.useCallback(O=>{const I=O;h({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:I,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...I!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,h]),j=w.useCallback(O=>{h({...n,...O})},[n,h]),_=w.useCallback(O=>{if(r==="aiContext"){"semanticDomainId"in O&&f(O.semanticDomainId);return}j(O)},[r,j]),T=r==="aiContext"?d:n.semanticDomainId,P=r==="aiContext"?{...n,mode:k,semanticDomainId:d}:n;w.useEffect(()=>{if(!C||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){M("semanticDomain");return}if(k!=="semanticDomain")return;const O=T,I=a.domainIds??[],V=r==="aiContext"?c:n.selectedEntities,Y=((V==null?void 0:V.length)??0)>0,G=((c==null?void 0:c.length)??0)>0;Ent({mode:v,currentDomainId:O,scopedDomainIds:I,hasSelectedEntities:Y})&&(r==="dataSource"?j({semanticDomainId:void 0,selectedEntities:[]}):f(void 0),G&&u([]))},[S,C,k,n.mode,T,n.selectedEntities,r,d,c,e,a.domainIds,v,j,M]),w.useEffect(()=>{E&&!T&&_({semanticDomainId:E})},[E,T,_]),w.useEffect(()=>{if(e){u(s||[]);const O=r==="aiContext"?_nt(s):void 0;f(n.semanticDomainId||O)}else x.current=null,y(!1)},[e,n==null?void 0:n.selectedEntities,r,h,s,n]);const F=O=>{const I=c.filter(V=>!(V.name===O.name&&V.type===O.type));u(I)},R=()=>{u([])},$=w.useCallback(O=>{u(O)},[]),q=w.useCallback(()=>{x.current&&x.current()},[]),U=w.useCallback(O=>{x.current=O,y(!0)},[]);function W(){var O,I;if(r==="aiContext")m&&h(n),g({...p,selectedEntities:c}),o==null||o(c),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const V=(O=c==null?void 0:c[0])==null?void 0:O.connectionId,Y=(I=c==null?void 0:c[0])==null?void 0:I.connectionType;h({...n,connectionId:V,connectionType:Y,selectedEntities:c})}else h({...n,selectedEntities:c});t(!1)}}return l.jsx(Wr,{open:e,onOpenChange:t,children:l.jsx(Rr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Pr,{className:"flex-shrink-0",children:[l.jsx(Or,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(Xr,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[N&&l.jsx("div",{className:"space-y-2",children:l.jsx(Fs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:M,className:"w-full",children:l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsx(cn,{value:"database",children:"Direct Source"}),l.jsx(cn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(jnt,{dataSource:P,onDataSourceUpdate:_,selectedEntities:c,onSelectionChange:$,domainAccess:a,autoSelectedDomainId:E,onRegisterSelectAll:U}),k==="database"&&N&&l.jsx(Nnt,{dataSource:n,onDataSourceUpdate:j,selectedEntities:c,onSelectionChange:$,onRegisterSelectAll:U})]})}),l.jsx(pnt,{selectedEntities:c,onDeselectEntity:F}),l.jsx(Ns,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(te,{variant:"outline",onClick:q,disabled:!b,children:"Select All"}),l.jsx(te,{variant:"outline",onClick:R,disabled:c.length===0,children:"Clear All"}),l.jsxs(te,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Vt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(te,{onClick:W,children:[l.jsx(Ur,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function Va(e,t){if("id"in e&&"id"in t&&e.id&&t.id)return e.id===t.id;const n=e.database||"",r=t.database||"",s=e.schema||"",o=t.schema||"",i=e.connectionType||"",a=t.connectionType||"",c=e.dbObjectType||"",u=t.dbObjectType||"";return e.type===t.type&&e.connectionId===t.connectionId&&i===a&&n===r&&s===o&&e.name===t.name&&c===u}function d8(e){return e||[]}function Tnt(){const e=zp(),t=Q(p=>{var g;return(g=p.dashboard.aiContext)==null?void 0:g.selectedEntities}),{setCurrentAIContext:n}=YC(),r=d8(e.selectedEntities),s=d8(t),o=w.useCallback(p=>{n({...e,selectedEntities:p})},[e,n]),i=w.useCallback(p=>r.some(g=>Va(g,p)),[r]),a=w.useCallback(p=>{if(r.some(x=>Va(x,p))){o(r.filter(x=>!Va(x,p)));return}o([...r,p])},[r,o]),c=w.useCallback(p=>{r.some(g=>Va(g,p))||o([...r,p])},[r,o]),u=w.useCallback(p=>{o(r.filter(g=>!Va(g,p)))},[r,o]),d=w.useCallback(p=>{p.length!==0&&o(r.filter(g=>!p.some(x=>Va(g,x))))},[r,o]),f=w.useCallback(()=>{o(s)},[s,o]),h=w.useCallback(()=>{o([])},[o]),m=w.useCallback(()=>{r.length===0&&o(s)},[s,r.length,o]);return{selectedEntities:r,availableEntities:s,setSelectedEntities:o,isEntitySelected:i,toggleEntity:a,addEntityIfMissing:c,removeEntity:u,removeEntities:d,selectAllEntities:f,clearAllEntities:h,syncWithGlobalContext:m}}function SS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(wI,{className:r});case"view":return l.jsx(ku,{className:r});case"materialized view":return l.jsx(Fle,{className:r});case"model":return l.jsx(BS,{className:r});case"file":return l.jsx(pa,{className:r});case"dataset":return l.jsx(Ja,{className:r});case"upload":return l.jsx(jI,{className:r});case"url":return l.jsx(m7,{className:r});default:return l.jsx(oy,{className:r})}}const wM=e=>e.name||e.name,Mnt=e=>{const t=wM(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Int({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=w.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(nr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsxs(st,{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:[SS(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:wM(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(Mn,{side:"top",className:"max-w-xs",children:Mnt(f)})]},m)}),d&&l.jsxs(jn,{open:o,onOpenChange:i,children:[l.jsx(kn,{asChild:!0,children:l.jsxs(st,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(d7,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(Mn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:SS(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:wM(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Vt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const $re=D.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Uo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(io.Input,{ref:n,className:Z("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})]}));$re.displayName=io.Input.displayName;const Zv=e=>e.label||(e==null?void 0:e.name),f8=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Dnt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=tt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),x=s.filter(N=>{if(!h)return!0;const k=Zv(N).toLowerCase(),E=f8(N).toLowerCase(),M=h.toLowerCase();return k.includes(M)||E.includes(M)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{x.length>0&&!p&&g(Zv(x[0]))},[x,p]);const b=()=>{if(!p)return;const N=x.find(k=>Zv(k)===p);N&&(o.some(E=>"id"in N&&"id"in E?N.id===E.id:N.name===E.name&&N.connectionId===E.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),b())};if(!e)return null;const v=N=>o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId),S=o.length===s.length,C=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Rp,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx($re,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(Ar,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:S,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),C&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Pp,{className:"min-h-60",children:[l.jsx(Op,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(te,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(Ar,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(Fp,{children:x.map((N,k)=>{const E=v(N),M="id"in N?N.id:`${N.connectionId}-${N.name}`,j=Zv(N);return l.jsxs($p,{value:j,onSelect:()=>{E?n==null||n(N):t(N)},onMouseDown:_=>{_.preventDefault(),_.stopPropagation()},className:Z("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:SS(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:f8(N)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(Ur,{className:"h-3 w-3 text-background"})})]},M)})})]})]})})}function SM({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0}){const[x,b]=w.useState(!1),[y,v]=w.useState(!1),S=o??x,C=o!==void 0,N=w.useRef(!1),E=$e(z=>z.card.dataSource)??KN,{selectedEntities:M,availableEntities:j,syncWithGlobalContext:_,setSelectedEntities:T,isEntitySelected:P}=Tnt(),F=e==="full"||e==="display",R=e==="full"||e==="trigger",$=w.useMemo(()=>g&&M.length>0?`Add entity (${M.length})`:p,[M.length,g,p]);w.useEffect(()=>{S&&!N.current&&s&&_(),N.current=S},[S,s,_]);const q=w.useCallback(z=>{C||b(z),i==null||i(z)},[C,i]),U=w.useCallback(z=>{const B=M.filter(H=>!Va(H,z));T(B),c==null||c(z),d==null||d(B)},[c,d,M,T]),W=w.useCallback(z=>{if(z.length===0)return;const B=M.filter(H=>!z.some(K=>Va(H,K)));T(B),u==null||u(z),d==null||d(B)},[u,d,M,T]),A=w.useCallback(z=>{const B=P(z)?M.filter(H=>!Va(H,z)):[...M,z];T(B),d==null||d(B)},[P,d,M,T]),L=w.useCallback(()=>{T(j),d==null||d(j)},[j,d,T]),O=w.useCallback(()=>{T([]),d==null||d([])},[d,T]),I=w.useCallback(z=>{T(z),d==null||d(z)},[d,T]),V=w.useCallback(z=>{const B=M.some(H=>Va(H,z))?M:[...M,z];T(B),a==null||a(z),d==null||d(B),q(!1)},[a,d,M,q,T]),Y=F?l.jsx(Int,{className:Z(n?"contents":"space-y-2"),entities:M,availableEntities:j,onRemoveEntity:U,onRemoveEntities:W}):null,G=R?l.jsxs(l.Fragment,{children:[l.jsxs(vs,{open:S,onOpenChange:q,children:[l.jsx(ws,{asChild:!0,children:l.jsxs(te,{variant:m,size:"sm",className:Z(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx(Rle,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:$})]})}),l.jsx(Ss,{className:Z("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:l.jsx(Dnt,{isOpen:!0,onSelect:A,onDeselect:A,onClose:()=>q(!1),availableEntities:j,selectedEntities:M,onTabComplete:V,onSelectAll:L,onRemoveAll:O,onAddContext:()=>{q(!1),v(!0)}})})]}),l.jsx(pO,{incomingSelectedEntities:M,open:y,onOpenChange:v,dataSource:E,dialogMode:"aiContext",onSaveSelectedEntities:I})]}):null;return l.jsx("div",{className:Z(n?"flex flex-wrap items-center gap-1":"",!n&&F?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[G,Y]}):l.jsxs(l.Fragment,{children:[Y,G]})})}const gO=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),h=w.useRef(null),{queueMessage:m}=Bp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:x}=SA(),b=wA(c);w.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=w.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const _=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${_}px`}},[e]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{const j=setTimeout(()=>{y()},0);return()=>clearTimeout(j)},[y]);const v=()=>{const j=e.trim();!j&&b.length===0||(a!=="ready"?(m(c,j,b),t(""),x(c)):r({preventDefault:()=>{}}))},S=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),v()),j.key==="@"&&f(!0)},C=w.useCallback(j=>{const _=XKe(j.nativeEvent);_.length>0&&(j.preventDefault(),_.forEach(async T=>{const P=await sO(T);p(c,P)}))},[p,c]),N=w.useCallback(j=>{j.forEach(_=>{p(c,_)})},[p,c]),k=w.useCallback(j=>{j.forEach(_=>{p(c,_)})},[p,c]),E=w.useCallback(j=>{g(c,j)},[g,c]),M=w.useCallback(j=>{const _=`@${j}`;e.includes(_)&&t(e.replace(_,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(hnt,{onFilesDropped:N,currentFileCount:b.length,disabled:s,className:"space-y-4",children:[l.jsx(SM,{mode:"display",onEntityRemoved:j=>{const _="label"in j?j.label:j.name;M(_)},onEntitiesRemoved:j=>{let _=e;j.forEach(T=>{const P="label"in T?T.label:T.name;_=_.replace(`@${P}`,"")}),_!==e&&t(_.replace(/\s{2,}/g," ").trim())}}),b.length>0&&l.jsx(QKe,{files:b,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:S,onPaste:C,onFocus:()=>{y(),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"}}),l.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(SM,{mode:"trigger",syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const _="label"in j?j.label:j.name;t(`${e}@${_} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(fnt,{onFilesSelected:k,disabled:s,currentFileCount:b.length})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[s&&l.jsx(te,{className:"rounded-full",size:"sm",onClick:o,children:l.jsx(Yle,{className:"size-3.5 bg-background"})}),!s&&l.jsx(te,{disabled:!e.trim()&&b.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(yI,{className:"size-4"})})]})]})]})]})});gO.displayName="ChatInputWithContext";function Lre({assistantType:e,className:t}){const n=XG(e),{removeFromQueue:r}=Bp();return n.length===0?null:l.jsxs("div",{className:Z("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(ju,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(te,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(Vt,{className:"h-3 w-3"})})]})},s.id))})]})}function zre({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=XG(e),{dequeueMessage:o}=Bp();w.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 Ant(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Rnt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ant(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Bre(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!0),[d,f]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(0),x=w.useRef(!0),b=w.useRef(!0),y=w.useRef(!1),v=w.useRef(!1),S=w.useRef(0),C=w.useRef({count:0,signature:"none"}),N=w.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const $=R.closest("[data-radix-scroll-area-viewport]");if($)return i.current=$,$;const q=R.parentElement;return q?(i.current=q,q):null},[]),k=w.useCallback(()=>{const R=N();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[N]),E=w.useCallback(()=>k()<=n,[k,n]),M=w.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=w.useCallback(R=>{b.current!==R&&(b.current=R,f(R))},[]),_=w.useCallback(()=>{m(R=>R&&!1),g(R=>R===0?R:0)},[]),T=w.useCallback((R={})=>{const $=N();if(!$)return;const{force:q=!1,instant:U=!1}=R;if(!q&&y.current)return;const W=U||r==="auto"||r==="instant"?"auto":r;v.current=!0,W==="smooth"&&"scrollTo"in $?$.scrollTo({top:$.scrollHeight,behavior:"smooth"}):$.scrollTop=$.scrollHeight,S.current=$.scrollTop,y.current=!1,M(!0),j(!0),_(),requestAnimationFrame(()=>{v.current=!1})},[r,_,N,M,j]),P=w.useCallback(()=>{g(0),m(!1)},[]),F=w.useCallback(()=>{const R=N();if(!R)return;const $=S.current,q=R.scrollTop,U=q-$;S.current=q;const W=E();if(v.current){j(W),W&&(y.current=!1,M(!0));return}if(U<-1&&!W){y.current=!0,M(!1),j(!1);return}if(W){y.current=!1,M(!0),j(!0),_();return}j(!1),y.current&&M(!1)},[_,N,E,M,j]);return w.useEffect(()=>{const R=N();if(!e||e.length===0){C.current={count:0,signature:"none"},R&&(S.current=R.scrollTop),_();return}const $=e[e.length-1],q=Rnt($),U=C.current,W=e.length>U.count,A=q!==U.signature;C.current={count:e.length,signature:q};const L=o||s&&($==null?void 0:$.role)==="assistant"&&A;if(!y.current){M(!0),R&&E()&&j(!0),(W||A||L)&&T({force:!1,instant:L});return}if(W){const O=e.length-U.count;O>0&&(m(!0),g(I=>I+O))}else A&&(m(!0),g(O=>O>0?O:1))},[_,o,s,N,E,e,T,M,j]),w.useEffect(()=>{T({force:!0,instant:!0})},[T]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const $=new ResizeObserver(()=>{y.current||T({force:!1,instant:!0})});return $.observe(R),()=>{$.disconnect()}},[T]),w.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:T,handleScroll:F,resetNewMessageCount:P}}function Vre(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Ure(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:Sne(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pnt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Ont({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(OM),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:x,isConsoleMode:b}=yp(),y=w.useRef(null);Q(Be=>Be.dashboard.aiScopeTables),Q(Be=>Be.isDashboardEditing);const v=Q(Be=>Be.selectedSheetId),{setDataSource:S}=br(),{addFrame:C,setSelectedFrameId:N,setIsDashboardEditing:k}=un(),E=zp(),{setCurrentAIContext:M,updateSelectedEntities:j,setReasoningEffort:_,setShowReasoning:T}=YC(),{clearQueue:P}=Bp(),{clearFileAttachments:F,getFileAttachments:R}=SA(),$=wA("dashboard"),q=Q(Be=>Be.dashboard.aiContext),U=$e(Be=>Be.card.dataSource),{assistantProfile:W}=Rre(),A=Q(Be=>Be.handleOpenAssistantProfile),{sendMessage:L,isLoading:O,messages:I,setMessages:V,status:Y,stop:G,errorMessage:z,clearError:B}=dnt(),H=w.useCallback(Be=>{r==null||r(Be),n===void 0&&p(Be)},[n,r]),K=w.useCallback(()=>{H(!g)},[g,H]);w.useEffect(()=>{if(!g)return;function Be(ye){ye.key==="Escape"&&H(!1)}return window.addEventListener("keydown",Be),()=>{window.removeEventListener("keydown",Be)}},[g,H]);const[ee,X]=w.useState(""),re=Be=>{X(Be.target.value)};function le({sql:Be,cardTitle:ye,connectionId:it,cardType:Ve,python:et,cardConfig:Rt,dataSource:Fe,customVisualPreferences:je}){if(!v)return;const Le={id:gr(),title:ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ve==="horizontalBar"?"y":"x"}},type:Ve,sql:Be,python:et,dataSource:Fe,config:Rt,connectionId:it,customCardPreferences:je?{url:je.url,componentName:je.componentName,pluginChartType:je.pluginChartType,settings:je.settings,type:"component"}:void 0},ut={id:gr(),cards:[Le],activeCardId:Le.id};k(!0),C(v,ut,"end"),N(ut.id)}const ue=Be=>{Be.preventDefault();const ye=ee.trim();if(!ye&&$.length===0)return;const it=[];ye&&it.push({type:"text",text:ye}),$.forEach(Ve=>{Ve.data&&it.push({type:"file",mediaType:Ve.type,filename:Ve.name,url:`data:${Ve.type};base64,${Ve.data}`})}),L({role:"user",parts:it}),X(""),F("dashboard"),oe({force:!0})};w.useEffect(()=>{var Be;e&&((Be=y.current)==null||Be.focus())},[e]),zre({assistantType:"dashboard",status:Y,isLoading:O,sendMessage:L});const{hasActiveTools:ce}=Ure(I),{visibleMessages:Se,hasMoreMessages:se,totalMessageCount:ke,loadMoreMessages:pe,resetMessageWindow:De}=Vre(I,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Pe,contentRef:ge,isAtBottom:ve,hasNewMessages:ie,newMessageCount:J,scrollToBottom:oe,handleScroll:we,resetNewMessageCount:Ne}=Bre(Se,{threshold:40,behavior:"smooth",isStreaming:O});function _e(Be){Qe();const ye={role:"user",parts:[{type:"text",text:Be.title+" "+Be.subtitle}]};L(ye)}function me(Be){Qe(),L({role:"user",parts:[{type:"text",text:Be}]})}function Ie(Be){Qe(),L({role:"user",parts:[{type:"text",text:Be}]}),oe({force:!0})}const ze=w.useCallback(async()=>{const Be=JSON.stringify(I??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Be),We.success("Conversation copied")}catch(ye){console.error("Failed to copy conversation",ye),We.error("Unable to copy conversation")}},[I]);function Qe(){E.selectedEntities.length===0&&M({selectedEntities:(q==null?void 0:q.selectedEntities)||[]})}const Te=(ee==null?void 0:ee.length)===0&&(I==null?void 0:I.filter(Be=>Be.role==="user").length)===0;function Ye(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function rt(){return l.jsxs(Qf,{children:[l.jsx(Jf,{asChild:!0,children:l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(dp,{className:"size-3.5"})})}),l.jsxs(Vu,{align:"end",children:[l.jsx(Jh,{children:"Options"}),l.jsx(jf,{}),l.jsx(fx,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(fx,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(fx,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Je=l.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ye(),A&&l.jsx(te,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:A,children:(W==null?void 0:W.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[b&&rt(),a&&l.jsx(te,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ze,children:"Copy Conversation"}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?l.jsx(pI,{className:"size-4"}):l.jsx(VS,{className:"size-4"})}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{V([]),P("dashboard"),B(),De()},children:l.jsx(HS,{className:"size-4"})}),l.jsx(hu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Vt,{className:"size-4"})})]})]}),l.jsxs(wl,{"data-role":"dashboard-assistant-scroll-area",ref:Pe,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:we,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[se&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(te,{variant:"outline",size:"sm",onClick:pe,className:"text-xs",children:["Load ",Math.min(5,ke-Se.length)," ","more messages (",ke-Se.length," ","hidden)"]})}),l.jsx(Nne,{showTools:a,showSystemMessage:u,messages:Se,onAddToDashboard:le,onQuickReply:Ie,disableQuickReplies:O}),!ce&&l.jsx(Cne,{status:Y,errorMessage:z})]}),l.jsx(Fi,{orientation:"horizontal"})]}),e&&!ve&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(te,{onClick:()=>{oe({force:!0}),Ne()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(dr,{className:"h-4 w-4"}),ie&&J>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:J>9?"9+":J})]})}),l.jsxs("div",{className:"space-y-3",children:[!W&&Te&&l.jsx(jne,{onClick:_e,placeholders:Pnt}),l.jsx("div",{children:Te&&W&&l.jsx(Pre,{seedQuestions:W.seedQuestions||[],handleSeedQuestionClick:me})}),l.jsx(Lre,{assistantType:"dashboard",className:"mb-3"}),l.jsx(gO,{ref:y,setInput:X,stop:G,input:ee,handleInputChange:re,handleSubmit:Be=>{Qe(),ue(Be),oe({force:!0})},isLoading:O,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(pO,{incomingSelectedEntities:(q==null?void 0:q.selectedEntities)||[],open:f,onOpenChange:h,dataSource:U||KN,dialogMode:"aiContext"})]});return g&&s?ur.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:Je})}),s):Je}function Fnt(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=un(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.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=XQ(p),x=g.cards.findIndex(b=>b.id===g.activeCardId);x!==-1&&(g.cards[x].title=`${g.cards[x].title} (Copy)`),r(a,g),s(g.id),We.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,c,u,t])}function $nt(e,t){switch(e.interactionMode){case"drillToDetail":Lnt(e,t);break;case"drillThrough":znt(e,t);break;case"drillToURL":Bnt(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 Lnt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function znt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Bnt(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 Vnt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Wr,{open:e,onOpenChange:t,children:l.jsxs(Rr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Pr,{children:[l.jsx(Or,{children:i||"Insight Detail"}),l.jsx(Xr,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(WJ,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(ZJ,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Unt(){const e=Qt(S=>S.interactionStates),t=Qt(S=>S.setInteractionState),n=Qt(S=>S.clearLastInteractionEvent),r=Qt(S=>S.replaceCardWithInsight),s=Qt(S=>S.setPendingDrillThrough),o=Qt(S=>S.pendingDrillThrough),i=Qt(S=>S.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=un(),{selectDashboard:u}=up(),d=Q(S=>S.dashboard),f=Q(S=>S.filterValues),{data:h,isLoading:m}=AV((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),x=XJ(p.insightId,{enabled:p.open&&!!p.insightId}),b=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:S,filters:C,contextMode:N})=>{g({open:!0,insightId:S,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:S,insightId:C,filters:N,contextMode:k})=>{r(S,C,N,k)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:S,contextMode:C,sourceDashboardId:N,sourceDashboardTitle:k,targetDashboardId:E})=>{const j={sourceCardId:Za,interactionMode:"clickFilter",filterGroups:[{filters:S}]},_={...ki(),appliedClickFilters:[j],contextMode:C,sourceDashboardId:N,sourceDashboardTitle:k,targetDashboardId:E};t(Za,_)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([S,C])=>{if(C!=null&&C.lastInteractionEvent){const N=C.lastInteractionEvent,k=`${S}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(b.current.has(k))return;b.current.add(k);try{$nt(N,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(S),setTimeout(()=>{b.current.delete(k)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(S){console.error("[DrillThrough] Error during automatic navigation:",S),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Vnt,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(Nn,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Hnt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Wnt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Wnt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function qnt(e){return e?`Back to ${e}`:"Back"}function Ynt(){var b,y,v,S,C;const e=Qt(N=>N.interactionStates[Za]),t=Q(N=>N.actions.goBackFromDrill),n=Q(N=>N.actions.clearDrillContext),{selectDashboard:r}=up(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const N=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},k=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",k),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",k)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((S=(v=(y=(b=e==null?void 0:e.appliedClickFilters)==null?void 0:b[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:S.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(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};Hnt(f);const x=qnt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,k)=>{const E=N.field.label||N.field.name,M=String(N.value);return l.jsxs(st,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",M]},k)})})]}),l.jsx(te,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Vt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(te,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(J9,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Hre(){var ke;const{showAssistant:e,tokenProps:t}=tt(),{preferences:n,isConsoleMode:r}=yp(),s=((ke=n==null?void 0:n.cardDisplay)==null?void 0:ke.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,c]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=HBe({initialPosition:"bottom-right"}),m=hf(pe=>pe.setFullscreen),p=hf(pe=>pe.setPanelOpen),g=hf(pe=>pe.setContainer),x=YG("dashboard"),b=GG(),y=KG("dashboard"),v=x.isOpen,S=b==="dashboard",C=Q(pe=>pe.isVisualEditing),N=Q(pe=>pe.themeStyle),k=Q(pe=>{var De;return(De=pe.dashboard)==null?void 0:De.sheets}),E=Q(pe=>pe.showFilters),M=Q(pe=>pe.isDashboardEditing),j=Q(pe=>pe.selectedSheetId),_=Q(pe=>{var De,Pe;return((Pe=(De=pe.dashboard)==null?void 0:De.summary)==null?void 0:Pe.position)||"top"}),T=Q(pe=>{var De;return(De=pe.dashboard)==null?void 0:De.id}),P=Q(pe=>pe.isDashboardPanelOpen),F=Q(pe=>pe.actions.setIsDashboardPanelOpen),{getDefaultSheetId:R,setDefaultSheetId:$,clearDefaultSheetId:q}=G9(T),[U,W]=w.useState(null);sC(vn.DASHBOARD);const{setSelectedSheetId:A,setSheetTitle:L,addSheet:O,setSheets:I}=un();Fnt(i);const{setActiveAssistantType:V}=YC();w.useEffect(()=>{if(T){const pe=R();W(pe)}},[T,R]),w.useEffect(()=>{v?V("dashboard"):b==="dashboard"&&m(null)},[v,V,b,m]),w.useEffect(()=>{var pe;v||(pe=o.current)==null||pe.resize(0)},[v]);function Y(pe){var De,Pe;pe?((De=o.current)==null||De.resize(40),p("dashboard",!0),V("dashboard")):(p("dashboard",!1),m(null),(Pe=o.current)==null||Pe.resize(0),V(null))}function G(){const pe={id:gr(),title:"New Sheet"};O(pe),A(pe.id)}function z(pe,De){if(!T)return;U===pe?(q(),W(null),We.success("Default sheet cleared")):($(pe),W(pe),We.success(`"${De}" set as default sheet`))}function B(pe){var De;pe<1?(p("dashboard",!1),m(null),V(null),(De=o.current)==null||De.resize(0)):(v||p("dashboard",!0),V("dashboard"))}function H(){return(N==null?void 0:N.canvasTheme)==="muted"||!(N!=null&&N.canvasTheme)?"hsl(var(--semaphor-muted))":(N==null?void 0:N.canvasTheme)==="clear"?"":N==null?void 0:N.canvasTheme}const K=(pe,De)=>{pe.dataTransfer.setData("tabIndex",De.toString())},ee=pe=>{pe.preventDefault()},X=(pe,De)=>{const Pe=pe.dataTransfer.getData("tabIndex");if(Pe===De.toString())return;const ge=Array.from(k||[]),[ve]=ge.splice(parseInt(Pe),1);ge.splice(De,0,ve),I(ge)},re=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,le=e===!0&&!s&&!v&&!C&&!E;function ue(){var pe,De;if(k&&k.length>1||M)return l.jsxs(js,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&re&&!P&&l.jsx(te,{style:{borderRadius:N==null?void 0:N.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{F(!P)},className:"h-8 shrink-0 p-2",children:P?l.jsx(i7,{className:"h-4 w-4"}):l.jsx(a7,{className:"h-4 w-4"})}),k==null?void 0:k.map((Pe,ge)=>{const ve=j===Pe.id,ie=U===Pe.id;return l.jsxs(cn,{draggable:!0,onDragStart:J=>K(J,ge),onDragOver:ee,onDrop:J=>X(J,ge),style:{borderRadius:N==null?void 0:N.controlInputRadius},onClick:()=>A(Pe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:Pe.id,children:[l.jsx(K1,{enabled:M&&ve,text:Pe.title,onSave:J=>L(Pe.id,J),children:Pe.title},Pe.id),!M&&ve&&l.jsx("div",{title:ie?"Clear default sheet":"Set as default sheet",children:l.jsx(vI,{className:Z("ml-1 size-3 cursor-pointer transition-all",ie?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:J=>{J.stopPropagation(),z(Pe.id,Pe.title||"Sheet")}})}),M&&ve&&k.length>1&&l.jsx(Vt,{className:"ml-1 size-3",onClick:()=>c(!0)})]},Pe.id)}),M&&l.jsx("div",{style:{borderRadius:(De=(pe=N==null?void 0:N.chart)==null?void 0:pe.options)==null?void 0:De.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:G,children:l.jsx(Ar,{className:"size-3"})})]})}function ce(){return l.jsx("div",{ref:i,style:{},className:"grow",children:k==null?void 0:k.map(pe=>l.jsx(cr,{style:{backgroundColor:H()},className:Z("mt-0",{}),value:pe.id,children:l.jsx(mBe,{sheet:pe})},pe.id))})}function Se(){var pe;return l.jsxs(Fs,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",N==null?void 0:N.dashboardTabsContainer),onValueChange:De=>{A(De)},value:j||((pe=k==null?void 0:k[0])==null?void 0:pe.id),children:[ue(),_==="top"&&l.jsx(BT,{}),l.jsx(wl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:ce()}),_==="bottom"&&l.jsx(BT,{}),l.jsx(WBe,{open:a,setOpen:c})]})}const se=w.useCallback(pe=>{g("dashboard",pe)},[g]);return k?l.jsxs(l.Fragment,{children:[l.jsx(Unt,{}),l.jsx(Ynt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(ote,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(XT,{children:Se()}),e===!0&&l.jsxs(l.Fragment,{children:[l.jsx(UBe,{open:v,onTabClick:Y,withHandle:!0,disabled:!v}),l.jsx(XT,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:v?40:0,ref:o,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Ont,{open:v,setOpen:Y,isFullscreen:S,onFullscreenChange:pe=>m(pe?"dashboard":null),fullscreenContainer:y})})})]})]}),l.jsx("div",{ref:se,className:Z("absolute inset-0",!S&&"pointer-events-none")}),le&&l.jsx("div",{className:Z("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:l.jsx(te,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||Y(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:l.jsx(iy,{className:"h-5 w-5"})})})]})]}):null}function xO({children:e}){return l.jsx(Ca,{style:{height:"100%",width:"100%"},children:l.jsx(Gae,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(nr,{delayDuration:0,children:e})})})}function Wre({children:e,preferences:t}){const{currentUser:n}=so(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(uV.Provider,{value:r,children:l.jsx(bP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Gnt(e=2e3,t=500){const n=Cle(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function bO({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Gnt(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qre(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(ya,{FallbackComponent:vN,children:l.jsxs(nI,{dashboardProps:e,children:[l.jsx(bO,{componentType:"dashboard",componentId:e.id}),l.jsx(xO,{children:l.jsx(Wre,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(CA,{...e,type:"dashboard",children:l.jsx(Hre,{})})})})})]})})}function h8(e,t){return e.map(n=>({...n,fieldScope:t}))}function Knt(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function m8(e){if(Ec(e)||ky(e))return e.expression}function yO(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=YD(),i=$e(g=>g.frame.calculatedFields),a=$e(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?h8(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(x=>{const b=`${x.name}-${x.role||"unknown"}`;g.set(b,x)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(Ec),x=((a==null?void 0:a.groupByColumns)||[]).filter(ky),y=Knt([...g,...x]).filter(v=>{const S=`${v.name}-${v.role||"unknown"}`,C=f.get(S);if(!C)return!0;const N=m8(v),k=m8(C);return N&&k?N!==k:!0});return h8(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==p9),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function vO(e){const{tokenProps:t,authToken:n}=tt(),r=t==null?void 0:t.apiServiceUrl;return en({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return xr(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 Yre(e,t,n){if(t==="source")return{isValid:!0};const r=Nr(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};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 Gre(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=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function Znt(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const Kre=e=>{var F;const t=(F=e==null?void 0:e.dataSource)==null?void 0:F.semanticDomainId,{data:n}=vO(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=br(),h=$e(R=>R.card.type),m=e==null?void 0:e.id,p=(R,$)=>{if(R.id)return R.id;const q=R.qualifiedEntityName||R.entityName||$;return`${$}-${q}-${R.name}`},g=w.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return Znt(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),x=w.useCallback((R,$)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),b=w.useCallback((R,$,q)=>{if(!m)return;const U=g(R),W=U[$];if(W)switch(R){case"groupBy":s(m,W.id,{label:q});break;case"metrics":o(m,W.id,{label:q});break;case"pivotBy":i(m,W.id,{label:q});break;case"sortBy":a(m,W.id,{label:q});break;case"detailColumns":{const A=U.map((L,O)=>O===$?{...L,label:q}:L);r(m,{detailColumns:A});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{aggregate:$,label:_q(U.name,$)})},[m,g,o]),v=w.useCallback((R,$,q,U="groupBy")=>{if(!m)return;const W=g(U),A=W[R];if(!A)return;const L={dateFormat:$,customFormat:$==="custom"&&q?q:void 0};if(U==="detailColumns"){const O=W.map((I,V)=>V===R?{...I,...L}:I);r(m,{detailColumns:O});return}s(m,A.id,L)},[m,g,r,s]),S=w.useCallback((R,$)=>{if(!m)return;const U=g("groupBy")[R];U&&s(m,U.id,{granularity:$})},[m,g,s]),C=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{aliasTemplate:$})},[m,g,o]),N=w.useCallback((R,$)=>{if(console.log("handleValueAliasesChange",R,$),!m)return;console.log("handleValueAliasesChange",R,$);const U=g("metrics")[R];U&&(console.log("handleValueAliasesChange",$),o(m,U.id,{valueAliases:$}))},[m,g,o]),k=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),E=w.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),M=w.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),j=w.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),_=w.useCallback((R,$)=>{if(!m)return;const U=g("metrics")[R];U&&o(m,U.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async R=>{var I;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],q=R,U=$Ne(q,$,{joinPlan:(I=e==null?void 0:e.config)==null?void 0:I.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!U.isValid){U.showError&&jq();return}const W=BNe(q,$,h);if(!W){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const A=Yre(q,W,h);if(!A.isValid){We.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3});return}const L=g(W);if(kq(q,L))return;const O=Tq(q,W,L);if(O){const V=[...L,O];x(W,V),W==="metrics"&&Gre(h,e==null?void 0:e.config,r,m,V)}},[m,e==null?void 0:e.config,g,x,t,n,h,r]),P=w.useCallback((R,$)=>{if(!m)return;const U=g(R)[$];if(U){if(R!=="sortBy"){const W=g("sortBy"),A=W.filter(L=>!(L.name===U.name&&L.qualifiedEntityName===U.qualifiedEntityName));A.length!==W.length&&r(m,{sortByColumns:A})}switch(R){case"groupBy":c(m,U.id);break;case"metrics":u(m,U.id);break;case"pivotBy":d(m,U.id);break;case"sortBy":f(m,U.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((W,A)=>A!==$)});break}}}},[m,g,c,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:x,updateLabel:b,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:C,handleValueAliasesChange:N,removeField:P,handleFieldClick:T,handleMetricComparisonChange:k,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:M,handleKpiTrendlineGranularityChange:j,handleMetricTargetValueChange:_,cardType:h}};function JN(e,t){var Ie,ze,Qe,Te,Ye,rt,Je,Be;const{tokenProps:n}=tt(),r=us(),s=tt().authToken||e,o=$e(ye=>ye.selectedConnectionId),i=$e(ye=>ye.card),{queryKey:a}=oge(i),c=$e(ye=>ye.selectedDatamodelId),u=$e(ye=>ye.isDevMode),d=$e(ye=>ye.selectedDatabaseName),f=$e(ye=>ye.selectedSchemaName),h=$e(ye=>ye.selectedTableName),m=$e(ye=>ye.actions.setSelectedConnectionId),p=$e(ye=>ye.actions.setSelectedDatamodelId),g=$e(ye=>ye.actions.setSelectedDatabaseName),x=$e(ye=>ye.actions.setSelectedSchemaName),b=$e(ye=>ye.actions.setSelectedTableName);$e(ye=>ye.actions.setCardSql);const{setQueryConfig:y}=br();function v(ye){var Fe;if(!o||!ye)return!1;const it=((Fe=M==null?void 0:M.capabilities)==null?void 0:Fe.path)||[],Ve=it.includes("database"),et=it.includes("schema");return!(!it.includes("table")||Ve&&(!d||d==="NA")||et&&!f)}function S(ye){var it;return!o||!ye?!1:!!((it=M==null?void 0:M.capabilities)!=null&&it.path.includes("database"))}const{refetchConnections:C,connectionsData:N,isConnectionsLoading:k,isConnectionsError:E,selectedConnection:M}=pi(e),{refetch:j,data:_,isLoading:T,isError:P}=en({queryKey:["models",o],queryFn:()=>xr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),F=M==null?void 0:M.type,R=((Ie=M==null?void 0:M.capabilities)==null?void 0:Ie.path.includes("schema"))??!1,$=((ze=M==null?void 0:M.capabilities)==null?void 0:ze.path.length)===1&&((Qe=M==null?void 0:M.capabilities)==null?void 0:Qe.path[0])==="table",q=$,{data:U,isLoading:W,isFetching:A,isError:L,refetch:O}=en({queryKey:["databases",o],queryFn:()=>xr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:S(F)}),{data:I,isLoading:V,isFetching:Y,isError:G,refetch:z}=en({queryKey:["schemas",o,d],queryFn:()=>xr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:B,isLoading:H,isFetching:K,isError:ee,refetch:X}=en({queryKey:["tables",o,d,f],queryFn:()=>xr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(F)}),{columns:re,isColumnsLoading:le,isColumnsFetching:ue,isColumnsError:ce,refetchColumns:Se}=Mq(e);w.useEffect(()=>{$&&(g(""),x(""),p(""),F==="API"&&b("api"))},[F,b,g,x,p,$]);const se=(M==null?void 0:M.type)==="API"?(Te=M==null?void 0:M.type)==null?void 0:Te.toLowerCase():h||"",ke=R&&f||"";function pe(ye){b(ye),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function De(ye){x(ye),b("")}function Pe(ye){g(ye==="none"?"":ye),x(""),b(""),ye!=="none"&&ye!==""&&p("")}function ge(ye){m(ye)}function ve(ye){p(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}U&&((Ye=U==null?void 0:U.databases)==null?void 0:Ye.length)>0,I&&((rt=I==null?void 0:I.schemas)==null?void 0:rt.length)>0;const ie=N==null?void 0:N.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),J=(Je=_==null?void 0:_.datamodels)==null?void 0:Je.map(ye=>({id:ye.id,name:ye.name})),oe=U==null?void 0:U.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),we=I==null?void 0:I.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),Ne=B==null?void 0:B.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),_e=(Be=_==null?void 0:_.datamodels.find(ye=>ye.id===c))==null?void 0:Be.name,me=M!=null&&M.capabilities?Pw({schemaName:ke,tableName:se,modelName:_e,databaseName:d||"",capabilities:M.capabilities}):se;return{connectionItems:ie,selectedConnectionId:o,selectedConnection:M,isConnectionsLoading:k,isConnectionsError:E,modelItems:J,selectedDatamodelId:c,selectedDatamodelName:_e,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:oe,isDatabasesLoadingOrFetching:W||A,isDatabaseError:L,schemaItems:we,selectedSchemaName:f,isSchemaLoadingOrFetching:V||Y,isSchemaError:G,tableItems:Ne,selectedTableName:h,isTableLoadingOrFetching:H||K,isTableError:ee,columns:re,isColumnsLoadingOrFetching:le||ue,isColumnsError:ce,isNonDbConnection:q,connectionType:F,tableName:se,formattedTableName:me,schemaName:ke,refetchConnections:C,refetchModels:j,refetchDatabases:O,refetchSchemas:z,refetchTables:X,refetchColumns:Se,handleConnectionChange:ge,handleDatamodelChange:ve,handleDatabaseChange:Pe,handleSchemaChange:De,handleTableChange:pe}}function Xv(e){return`${e}-${gr()}`}function p8(e,t){const n=ui(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 Xnt(e,t){const n=ui(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function wO(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 Zre(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Xre(){const e=$e(k=>k.sqlGen),t=$e(k=>k.isDevMode),n=$e(k=>k.card.dataSource),r=$e(k=>{var E,M;return(M=(E=k.card)==null?void 0:E.queryConfig)==null?void 0:M.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=wO(n),a=Zre(n),c=$e(k=>k.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=br(),{modelItems:g,selectedDatamodelName:x}=JN(),{selectedConnection:b}=pi(),y=b==null?void 0:b.capabilities,v=k=>({column_name:k.name,data_type:k.dataType,label:k.label,description:k.description});return{handleDevModeFieldClick:k=>{var M;if(!t)return;const E=v(k);if(t&&a&&s&&y){const j=VM(E,e);m(j);const _=(M=g==null?void 0:g.find(P=>P.id===c))==null?void 0:M.name,T=BM(j,o||"",s,_||"",i||"",y,k.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(ty(E.data_type))if(r&&r.length>0){const j={...E,role:"groupby",id:Xv(E.column_name),name:E.column_name,type:E.data_type};d(j)}else{const j={...E,role:"metric",id:Xv(E.column_name),name:E.column_name,label:p8(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(j)}if(ha(E.data_type)){const j={...E,role:"groupby",id:Xv(E.column_name),name:E.column_name,type:E.data_type,label:Xnt(E.column_name,"month"),granularity:"month"};d(j)}if(fa(E.data_type)){const j={...E,role:"metric",id:Xv(E.column_name),name:E.column_name,label:p8(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(j)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const k=Pw({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});p(!1);const M=(b==null?void 0:b.type)==="MSSQL"?`SELECT top 10 * FROM ${k}`:`SELECT * FROM ${k} LIMIT 10`;f(M),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const k=Pw({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${k}`),h(!0)},isNumberField:k=>fa(k.dataType)}}function Qnt(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>Hx(o)).join("."),s=Hx(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Qre(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Jre(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function ese(e){var t,n;return e?!!(e.entityName===Sc||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function tse(){const e=Q(c=>c.dashboard.filters)||[],t=Q(c=>c.selectedSheetId),n=Q(c=>c.actions.addFilter),r=Q(c=>c.actions.removeFilter),{removeFilterValues:s}=un(),o=$e(c=>c.card.dataSource),{selectedConnection:i}=pi();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Qnt(c);let m;if(u==="sheet"&&t?m=uTe(e,d,f,t):m=e==null?void 0:e.find(p=>Zm(p.column)===Zm(d)),m)s(m.id),r(m.id);else{const p=gr(),g=Qre(c),x=Jre(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),b=ese(g),y=u==="sheet"&&t?[t]:void 0,v=Nr(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:b?"":HX(c.dataType,f,h),fieldMeta:g,semanticContext:x}),p}}return{assignFilter:a}}function Jnt({column:e}){const[t,n]=w.useState(!1),r=$e(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=wO(r),a=$e(y=>y.selectedDatamodelId),c=$e(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=JN(),f=d==null?void 0:d.capabilities,h=$e(y=>y.actions.setSqlGen),m=$e(y=>y.actions.setCardSql),p=$e(y=>y.actions.setRunSql),g=Zre(r);function x(y,v){var E,M;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=VM(y,c,v),C=(E=u==null?void 0:u.find(j=>j.id===a))==null?void 0:E.name;if(h(S),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const N=(M=y.qualifiedFieldName)==null?void 0:M.split(".").slice(0,-1).join("."),k=BM(S,o||"",s,C||"",i||"",f,N);k&&(m(k),p(!0)),n(!1)}function b(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>x(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>x(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>x(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>x(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>x(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?l.jsxs(vp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(wp,{asChild:!0,children:l.jsx(dp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Sp,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function ert({field:e,fieldState:t}){return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function g8({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=$e(X=>X.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=Q(X=>X.dashboard.filters),d=Q(X=>X.selectedSheetId),f=Q(X=>X.actions.removeFilter),{removeFilterValues:h}=un(),{assignFilter:m}=tse(),p=t==="filter"?Tc(u,d):u,g=t==="filter"?p==null?void 0:p.find(X=>{if(X.title===e.name)return!0;const re=Zm(X.column||""),le=Zm(e.name);return re.endsWith(`.${le}`)||re===le}):void 0,x=!!g,b=t==="inline-filter"&&(s==null?void 0:s.some(X=>X.column===e.qualifiedFieldName||X.column===e.name)),y=x||b,v=g&&a?u==null?void 0:u.find(X=>X.id===g.id):void 0,S=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:S,selectedSheetId:d});const[C,N]=w.useState(!1),[k,E]=w.useState(null),{attributes:M,listeners:j,setNodeRef:_,transform:T,transition:P,isDragging:F}=c0({id:e.id,disabled:c}),[R,$]=w.useState(!1),q=$e(X=>X.card),{handleFieldClick:U}=Kre(q),{handleDevModeFieldClick:W,isNumberField:A}=Xre(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),N(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&S?(E(e),N(!0)):m(e,"sheet"):i?W(e):U(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},V={transform:zi.Transform.toString(T),transition:P},Y=()=>{if(!n||a)return{};const re={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",...re},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...re},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...re}}[n.state]||re};function G(X){return X==="domain"?{label:"Domain",Icon:oy,className:"border-border bg-muted text-foreground"}:X==="dashboard"?{label:"Dashboard",Icon:fI,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:y7,className:"border-border bg-muted/40 text-foreground"}}const z=Y(),B=e.fieldScope,H=B?G(B):null,K=C1(e),ee=K&&Ec(e);return l.jsxs("div",{ref:_,style:V,...c?{}:M,...c?{}:j,className:Z("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",F&&"scale-95 opacity-50",!F&&"border",z.borderColor||"border-transparent",z.bgColor||"",z.hoverBorderColor,z.hoverBgColor||"hover:bg-muted",z.opacity,z.cursor,x&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[l.jsxs("div",{className:"relative shrink-0",children:[sp(e.dataType),K&&l.jsx("span",{className:Z("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",ee?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx(nr,{children:l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.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})})}),l.jsx(Mn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(ert,{field:e,fieldState:n})})]})}),t==="editor"&&H&&l.jsx("span",{title:H.label,className:Z("shrink-0 rounded-full border p-1",H.className),children:l.jsx(H.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&A(e)&&l.jsx("div",{onClick:X=>X.stopPropagation(),children:l.jsx(Jnt,{column:I})}),o&&l.jsx("div",{className:"ml-auto flex items-center",onClick:X=>X.stopPropagation(),onPointerDown:X=>X.stopPropagation(),children:o})]}),R&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Vo,{className:"",children:l.jsxs(Pi,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(v7,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Jle,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(st,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(eh,{open:C,onOpenChange:N,children:l.jsxs(Uu,{children:[l.jsxs(Hu,{children:[l.jsx(qu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Yu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Wu,{children:[l.jsx(Ku,{children:"Cancel"}),l.jsx(Gu,{onClick:L,children:"Remove Filter"})]})]})})]})}let nse=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Ub=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],Pl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Gl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function x8(e,t,n,r,s,o,i,a,c,u){const d=Ub.find(b=>b.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=Pl(e);return{id:i||`calc_${nse(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:Sc,entityType:"table",description:`Calculated field: ${e}`}}function trt(e){var r,s;const t=Ub.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function nrt(e,t,n,r,s,o){const i=Pl(e);return{id:o||`calc_dim_${nse(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Sc,entityType:"table",description:`Calculated field: ${e.trim()}`}}function rrt(){const{domainCalculatedFields:e}=yO(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function srt({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(Fs,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(js,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(cn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function ort({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const x of g){const b=u(p,x);if(b!==p)return b}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx($n,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:l.jsx(Vt,{className:"size-3.5"})})]}),l.jsx(wl,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(_b,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(vu,{value:f.id,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",x=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:Z("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[sp(h.dataType),h.isCalculated&&l.jsx("span",{className:Z("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:Z("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:x})}),m&&l.jsx(st,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function irt({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Ub.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Ub.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(bt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(pt,{children:l.jsx(wt,{})}),l.jsx(gt,{children:l.jsxs(pA,{children:[l.jsx(UC,{children:"OPERATIONS"}),i.map(c=>l.jsx(Ee,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const art={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function lrt({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Nr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(bt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(pt,{className:"h-9",children:l.jsx(wt,{})}),l.jsx(gt,{children:c.map(u=>l.jsx(Ee,{value:u,children:art[u]},u))})]})}const crt=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function b8({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return l.jsxs("div",{className:Z("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(bt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(pt,{className:"h-9 flex-1",children:l.jsx(wt,{placeholder:"Select field"})}),l.jsx(gt,{children:f.map(h=>l.jsx(Ee,{value:h.id,children:crt(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(lrt,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:c})})]}),t&&l.jsx(te,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Vt,{className:"h-3.5 w-3.5"})})]})}const y8=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&l.jsxs(te,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[l.jsx(iy,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),l.jsx(np,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function urt({result:e}){const t=e.errors.length>0;return l.jsxs("div",{className:Z("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[l.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>l.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>l.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>l.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&l.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function v8({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(te,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&l.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&l.jsx(urt,{result:n||r})]})}function drt({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[l.jsx(de,{children:"Availability"}),l.jsxs(As,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-card",value:"card"}),l.jsx(de,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(de,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Sn,{id:"scope-domain",value:"domain"}),l.jsx(de,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function frt({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-description",children:"Description"}),l.jsx(ja,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:Z("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(sn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function hrt({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=tt(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await ls(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function mrt({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=hrt({endpoint:o,availableFields:n,fieldType:r,dialect:i}),x=w.useMemo(()=>{const N=f.trim().toLowerCase();return N?n.filter(k=>[k.label,k.baseLabel,k.name,k.tokenLabel,k.entityName,k.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(N)):n},[n,f]),b=N=>{const E=(N.name||N.baseLabel||N.label||N.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=N=>{const k=N.entityName||N.qualifiedEntityName||"";return k?k==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":k.includes(".")&&k.split(".").pop()||k:"—"},v=async()=>{const N=await m(a.trim());N&&d(N)},S=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},C=()=>{c(""),d(""),h(""),t(!1)};return l.jsx(Wr,{open:e,onOpenChange:N=>{N?t(!0):C()},children:l.jsxs(Rr,{className:"max-w-3xl",children:[l.jsxs(Pr,{children:[l.jsx(Or,{children:"Generate Expression with AI"}),l.jsx(Xr,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(np,{id:"ai-prompt",value:a,onChange:N=>c(N.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(te,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&l.jsx("p",{className:"text-xs text-destructive",children:g})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(sn,{value:f,onChange:N=>h(N.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx("div",{className:"max-h-48 overflow-y-auto",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:l.jsxs("tr",{children:[l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),l.jsx("tbody",{className:"divide-y",children:x.length===0?l.jsx("tr",{children:l.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):x.map(N=>l.jsxs("tr",{className:"hover:bg-muted/30",children:[l.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:b(N)}),l.jsx("td",{className:"px-3 py-1.5",children:l.jsx(st,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:N.dataType})}),l.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(N)})]},N.id))})]})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Generated expression"}),l.jsx(np,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),l.jsxs(Ns,{className:"gap-2",children:[l.jsx(te,{variant:"ghost",onClick:C,children:"Cancel"}),l.jsx(te,{onClick:S,disabled:!u.trim(),children:"Use Expression"})]})]})})}const prt=/\{([^}]+)\}/g;function ej(e){return e.trim().toLowerCase()}function CS(e){return Array.from(e.matchAll(prt)).map(t=>t[1]).filter(Boolean)}function grt(e){const t=new Set,n=[];return e.forEach(r=>{const s=ej(r);t.has(s)||(t.add(s),n.push(r))}),n}function SO(e){const t=new Map,n=(r,s)=>{const o=ej(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function Og(e,t){const n=CS(e),r=grt(n),s=SO(t),o=r.map(a=>{const c=s.get(ej(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function w8(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${xrt(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function xrt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const brt=e=>e.entityName===km||e.entityName===Sc?"Calculated Fields":e.qualifiedEntityName?qx(e.entityName||e.qualifiedEntityName):qx(e.entityName||"Other"),yrt=e=>Nr(e.dataType||"")==="number";function vrt(e,t,n){const r=new Set((n||[]).map(s=>Gl(s)));return e.filter(s=>{const o=Gl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function wrt(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Sc?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function Srt(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||yrt(o);return{...o,isCompatible:i}}).filter(o=>r)}function Crt(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function Nrt(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:brt(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function jrt({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>vrt(e,t,r),[e,t,r]),a=w.useMemo(()=>wrt(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Ec(m)||m.role==="groupby"&&ky(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>SO(c),[c]),d=w.useMemo(()=>Srt(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>Crt(d,n),[d,n]),h=w.useMemo(()=>Nrt(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const krt=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},Ert=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},_rt=(e,t)=>t.map(r=>({candidate:r,distance:Ert(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),Trt=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},Mrt=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function Irt({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=tt(),[a,c]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>SO(t),[t]),p=w.useMemo(()=>{const b=[],y=[],v=e.trim();v||b.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!krt(v)&&b.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const C=CS(e).map(k=>{const E=m.get(ej(k))||[];if(!E.length){const _=Array.from(m.keys()),T=_rt(k,_),P=T.length?`Did you mean {${T[0]}}?`:void 0;return b.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${k}}`,suggestion:P}),{token:k,field:null,error:"Unknown token"}}if(E.length>1)return b.push({code:"UNKNOWN_TOKEN",message:`Token {${k}} matches multiple fields. Use a disambiguated label.`}),{token:k,field:null,error:"Ambiguous token"};const M=E[0];return(n||[]).map(Gl).includes(Gl(M.id))?(b.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:k,field:null,error:"Self reference"}):{token:k,field:M}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const N=C.map(k=>k.field).filter(Boolean);return{isValid:b.length===0,tokens:C,errors:b,warnings:y,inferredDataType:Trt(e,N)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return c(p),p;const b=r,y={type:"calculated-field-expression",value:e,context:{availableFields:Mrt(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const S=await ls(b,(i==null?void 0:i.accessToken)||"",y),C=S.errors||[],N=S.warnings||[],k={...p,isValid:S.valid&&C.length===0,errors:C,warnings:N,inferredDataType:((v=S.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return c(k),k}catch(S){return h((S==null?void 0:S.error)||"Validation failed"),c(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),x=w.useCallback(()=>{c(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:x}}const S8=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],rE=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},rse=e=>Nr(e.dataType||"")==="number",Fh=e=>rse(e)?"SUM":"COUNT",sE=(e,t)=>rse(e)||t==="COUNT"||t==="DISTINCT"?t:Fh(e);function oE(e,t){if(e.role==="metric"){const n=e;return Ec(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function Mh(e,t){const n=e.role==="metric"&&Ec(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function sse({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var He;const{tokenProps:m}=tt(),{selectedConnection:p}=Cq(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[x,b]=w.useState(f),[y,v]=w.useState(""),[S,C]=w.useState("ratio"),[N,k]=w.useState(null),[E,M]=w.useState(null),[j,_]=w.useState(1),[T,P]=w.useState(""),[F,R]=w.useState(null),[$,q]=w.useState("card"),[U,W]=w.useState(""),[A,L]=w.useState(""),[O,I]=w.useState({}),[V,Y]=w.useState("A"),[G,z]=w.useState(""),[B,H]=w.useState(!1),[K,ee]=w.useState(null),[X,re]=w.useState(!1),[le,ue]=w.useState(!1),[ce,Se]=w.useState(!1),se=w.useRef(null),ke=w.useRef(!1),pe=w.useRef(null),{userContext:De}=so(),{metrics:Pe,dimensions:ge}=rrt(),ve=(De==null?void 0:De.type)==="organization",ie=!ve,J=!!d&&ve,oe=J&&!!a,we=J&&!!c,Ne=!!(i||oe||we),_e=!!i,me=x==="metric"?oe:we,Ie=(He=m==null?void 0:m.apiServiceUrl)==null?void 0:He.replace(/\/$/,""),ze=Ie?`${Ie}/v1/validate`:"/v1/validate",Qe=Ie?`${Ie}/v1/ai/generate`:"/v1/ai/generate",Te=w.useMemo(()=>{var yt;const xe=[...n];return(((yt=r==null?void 0:r.calculatedFormula)==null?void 0:yt.inputFields)||[]).forEach(Ce=>{xe.some(ft=>ft.id===Ce.id||ft.qualifiedFieldName===Ce.qualifiedFieldName||ft.name===Ce.name)||xe.push(Ce)}),xe},[n,r]),Ye=V==="A"?N:E,rt=x==="metric"&&S!=="custom"?Ye==null?void 0:Ye.aggregate:void 0,{allFields:Je,groups:Be}=jrt({fields:Te,mode:x,searchTerm:G,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:rt,showIncompatible:!0}),ye=Je,{clientResult:it,validationResult:Ve,validateExpression:et,isValidating:Rt,serverError:Fe,resetValidation:je}=Irt({expression:T,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:ze,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),Le=(Ve==null?void 0:Ve.inferredDataType)||it.inferredDataType,ut=F||Le||"string",ct=Ub.find(xe=>xe.id===S),fe=w.useMemo(()=>{if(!y.trim())return!1;const xe=Pl(y),nt=s==="domain"&&(r!=null&&r.name)?Pl(r.name):null;return(x==="metric"?Pe:ge).some(Ce=>{const Ge=Pl(Ce.name);return nt&&Ge===nt?!1:Ge===xe})},[ge,Pe,r,s,x,y]),qe=w.useMemo(()=>{if(x==="metric"&&S==="custom"){const{orderedFields:nt}=Og(T,ye);return nt.filter(yt=>!!yt).map(yt=>yt.id)}const xe=[];return N!=null&&N.field.id&&xe.push(N.field.id),E!=null&&E.field.id&&xe.push(E.field.id),xe},[ye,T,x,N,E,S]),lt=xe=>{ie||(b(xe),xe==="dimension"&&$==="domain"&&!we&&q("card"),xe==="metric"&&$==="domain"&&!oe&&q("card"))},Pt=xe=>{ie||(C(xe),xe==="scale"&&M(null),xe==="custom"&&(k(null),M(null)))},$t=()=>{v(""),C("ratio"),k(null),M(null),_(1),P(""),R(null),q("card"),W(""),L(""),I({}),z(""),H(!1),ee(null),re(!1),Se(!1),je(),t(!1)},_n=w.useCallback(xe=>Te.find(nt=>nt.qualifiedFieldName===xe.qualifiedFieldName||nt.name===xe.name)||xe,[Te]),or=w.useCallback(xe=>{if(!xe.calculatedFormula)return;const nt=xe.calculatedFormula;if(C(nt.operation),P(""),nt.operation==="scale"){const Ge=nt.inputFields[0];Ge&&k(Mh(_n(Ge),Ge.aggregate||"SUM")),_(nt.constant===void 0?1:nt.constant);return}if(nt.operation==="custom"){P(ns(xe.expression||"",nt.inputFields||[])),k(null),M(null);return}const[yt,Ce]=nt.inputFields;yt&&k(Mh(_n(yt),yt.aggregate||"SUM")),Ce&&M(Mh(_n(Ce),Ce.aggregate||"SUM"))},[_n]),ns=w.useCallback((xe,nt)=>xe.replace(/\{field_(\d+)\}/g,(yt,Ce)=>{var mt;const Ge=nt[Number(Ce)];return Ge?`{${((mt=ye.find(Ct=>Ct.id===Ge.id))==null?void 0:mt.tokenLabel)||Ge.label||Ge.name}}`:yt}),[ye]);w.useEffect(()=>{var yt;if(!e){ke.current=!1,pe.current=null;return}const xe=r?`${r.role}-${r.id||r.name}`:"new";if(ke.current&&pe.current===xe)return;if(ke.current=!0,pe.current=xe,I({}),z(""),Se(!1),je(),r){const Ce=r.tags||[];if(r.role==="metric"){b("metric"),v(r.label||r.name),q(s||"card"),W(r.description||""),L(Ce.join(", ")),or(r);return}b("dimension");const Ge=r;v(Ge.label||Ge.name),q(s||"card"),P(ns(Ge.expression||"",((yt=Ge.calculatedFormula)==null?void 0:yt.inputFields)||[]));const ft=S8.some(mt=>mt.value===Ge.dataType)?Ge.dataType:"string";R(ft),W(Ge.description||""),L(Ce.join(", "));return}const nt=h&&h.length>0?h.includes(f)?f:h[0]:f;b(nt),v(""),C("ratio"),k(null),M(null),_(1),P(""),R(null),q("card"),W(""),L("")},[e,r,s,f,h,or,ns,je]);const $s=xe=>{const nt=`{${xe}}`,yt=se.current;if(!yt){P(mt=>mt+nt);return}const Ce=yt.selectionStart||0,Ge=yt.selectionEnd||0,ft=`${T.slice(0,Ce)}${nt}${T.slice(Ge)}`;P(ft),requestAnimationFrame(()=>{yt.focus();const mt=Ce+nt.length;yt.setSelectionRange(mt,mt)})},qi=xe=>{if(ie)return;if(x==="dimension"||S==="custom"){$s(xe.tokenLabel||xe.label||xe.name);return}const nt=sE(xe,V==="A"?(N==null?void 0:N.aggregate)||Fh(xe):(E==null?void 0:E.aggregate)||Fh(xe)),yt=Mh(xe,nt);if(V==="A"){k(yt),E||Y("B");return}M(yt),N||Y("A")},ks=(xe,nt)=>{if(!ie){if(xe==="A"&&N){k({...N,aggregate:nt});return}xe==="B"&&E&&M({...E,aggregate:nt})}},_o=async()=>{const xe={};if(y.trim()||(xe.name="Name is required"),S==="custom")T.trim()||(xe.expression="Expression is required"),CS(T).length===0&&(xe.expression=xe.expression||"Expression must include field tokens"),Og(T,ye).unresolvedTokens.length>0&&(xe.expression=xe.expression||"Expression contains unknown or ambiguous tokens"),xe.expression||(await et()).isValid||(xe.expression="Fix validation errors before saving");else if(S==="scale")N||(xe.inputA="Please select a metric for input A"),Number.isNaN(j)&&(xe.constant="Please enter a valid multiplication factor");else{if(N||(xe.inputA="Please select a metric for input A"),E||(xe.inputB="Please select a metric for input B"),N&&E){const nt=N.field.id===E.field.id,yt=N.aggregate===E.aggregate;nt&&yt&&(xe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const nt=Gl(r.id);(Gl(N==null?void 0:N.field.id)===nt||Gl(E==null?void 0:E.field.id)===nt)&&(xe.inputs="Cannot reference the field being edited")}}return Ne&&($==="domain"&&!oe&&(xe.scope="You do not have permission to save to domain"),$==="domain"&&!U.trim()&&(xe.description="Description is required for domain fields"),$==="domain"&&fe&&(xe.name="A domain field with this name already exists")),I(xe),Object.keys(xe).length===0},Nl=async()=>{const xe={};return y.trim()||(xe.name="Name is required"),T.trim()||(xe.expression="Expression is required"),CS(T).length===0&&(xe.expression=xe.expression||"Expression must include field tokens"),Og(T,ye).unresolvedTokens.length>0&&(xe.expression=xe.expression||"Expression contains unknown or ambiguous tokens"),xe.expression||(await et()).isValid||(xe.expression="Fix validation errors before saving"),Ne&&($==="domain"&&!we&&(xe.scope="You do not have permission to save to domain"),$==="domain"&&!U.trim()&&(xe.description="Description is required for domain fields"),$==="domain"&&fe&&(xe.name="A domain field with this name already exists")),I(xe),Object.keys(xe).length===0},jl=()=>{const{orderedTokens:xe,orderedFields:nt}=Og(T,ye),yt=nt.filter(ft=>!!ft),Ce=w8(T,xe),Ge=nrt(y,Ce,yt,ut,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Ge}:Ge},kl=()=>{var Ce;if(S==="custom"){const{orderedTokens:Ge,orderedFields:ft}=Og(T,ye),mt=ft.filter(Ft=>!!Ft),Ct=(r==null?void 0:r.role)==="metric"?((Ce=r.calculatedFormula)==null?void 0:Ce.inputFields)||[]:[],Tt=new Map;Ct.forEach(Ft=>{const Rn=Gl(Ft.id);Rn&&Tt.set(Rn,Ft),Ft.qualifiedFieldName&&Tt.set(Ft.qualifiedFieldName,Ft),Ft.name&&Tt.set(Ft.name,Ft)});const Lr=mt.map(Ft=>{const Rn=Gl(Ft.id),qo=Rn&&Tt.get(Rn)||Ft.qualifiedFieldName&&Tt.get(Ft.qualifiedFieldName)||Tt.get(Ft.name),hh=((qo==null?void 0:qo.role)==="metric"?qo.aggregate:void 0)||(Ft.role==="metric"?Ft.aggregate:void 0)||Fh(Ft);return oE(Ft,hh)}),Bt=w8(T,Ge),Ot=x8(y,S,null,null,{},u,r==null?void 0:r.id,Bt,void 0,Lr);return r&&r.role==="metric"?{...r,...Ot}:Ot}const xe=N?oE(N.field,N.aggregate):null,nt=E?oE(E.field,E.aggregate):null,yt=x8(y,S,xe,nt,{},u,r==null?void 0:r.id,void 0,S==="scale"?j:void 0);return r&&r.role==="metric"?{...r,...yt}:yt},El=async xe=>{var yt,Ce,Ge;if(x==="dimension"){const ft=jl();if(xe==="dashboard"){if(!i){I(mt=>({...mt,scope:"Dashboard scope is not available"}));return}i(ft),$t();return}if(xe==="domain"){if(!c){I(Ot=>({...Ot,scope:"Domain scope is not available"}));return}const mt=((yt=ft.calculatedFormula)==null?void 0:yt.inputFields)||[],Ct=new Map,Tt=mt.map(Ot=>{const Ft=Pl(Ot.label||Ot.name),Rn=Ct.get(Ft)||0;return Ct.set(Ft,Rn+1),Rn===0?Ft:`${Ft}_${Rn+1}`}),Lr=((Ce=ft.expression)==null?void 0:Ce.replace(/\{field_(\d+)\}/g,(Ot,Ft)=>`{${Tt[Number(Ft)]||Ft}}`))||"",Bt=Tt.reduce((Ot,Ft,Rn)=>{const qo=mt[Rn];return ky(qo)?Ot[Ft]={dimension:qo.name}:Ot[Ft]={dataset:qo.entityName,field:qo.name},Ot},{});try{await c({name:Pl(y),label:y.trim(),description:U.trim(),expression:Lr,inputs:Bt,dataType:ut,tags:A.split(",").map(Ot=>Ot.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Ot){I(Ft=>({...Ft,scope:(Ot==null?void 0:Ot.message)||"Failed to save to domain"}));return}$t();return}o(ft),$t();return}const nt=kl();if(xe==="dashboard"){if(!i){I(ft=>({...ft,scope:"Dashboard scope is not available"}));return}i(nt),$t();return}if(xe==="domain"){if(!a){I(Bt=>({...Bt,scope:"Domain scope is not available"}));return}if(!nt.calculatedFormula){I(Bt=>({...Bt,scope:"Calculated formula missing"}));return}const ft=nt.calculatedFormula.inputFields,mt=new Map,Ct=ft.map(Bt=>{const Ot=Pl(Bt.label||Bt.name),Ft=mt.get(Ot)||0;return mt.set(Ot,Ft+1),Ft===0?Ot:`${Ot}_${Ft+1}`}),Tt=((Ge=nt.expression)==null?void 0:Ge.replace(/\{field_(\d+)\}/g,(Bt,Ot)=>`{${Ct[Number(Ot)]||Ot}}`))||"",Lr=Ct.reduce((Bt,Ot,Ft)=>{const Rn=ft[Ft];return Rn.role==="metric"?Ec(Rn)?Bt[Ot]={metric:Rn.name}:Bt[Ot]={dataset:Rn.entityName,field:Rn.name,aggregate:Rn.aggregate}:Bt[Ot]={dataset:Rn.entityName,field:Rn.name},Bt},{});try{await a({name:Pl(y),label:y.trim(),description:U.trim(),expression:Tt,inputs:Lr,tags:A.split(",").map(Bt=>Bt.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Bt){I(Ot=>({...Ot,scope:(Bt==null?void 0:Bt.message)||"Failed to save to domain"}));return}$t();return}o(nt),$t()},xt=async()=>{if(ie)return;if(I({}),x==="metric"){if(!await _o())return}else if(!await Nl())return;const xe=Ne?$:s||"card";if(x==="metric"&&xe!=="domain"&&fe&&!r){ee(xe),re(!0);return}ue(!0);try{await El(xe)}finally{ue(!1)}},he=w.useMemo(()=>{if(!ct||S==="custom")return"";if(S==="scale"){const xe=Number.isFinite(j)?j:1;return`${rE(N)} x ${xe}`}return`${rE(N)||"A"} ${ct.symbol} ${rE(E)||"B"}`},[ct,S,N,E,j]);return l.jsxs(l.Fragment,{children:[l.jsxs(Wr,{modal:!1,open:e,onOpenChange:xe=>{xe?t(!0):$t()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Rr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:xe=>{xe.preventDefault()},children:[l.jsxs(Pr,{children:[l.jsxs(Or,{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xr,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(ort,{groups:Be,searchTerm:G,onSearchTermChange:z,onFieldClick:qi,selectedFieldIds:qe,disabled:ie}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Field Type"}),l.jsx(srt,{value:x,onChange:lt,disabled:ie||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"calculated-name",children:"Name"}),l.jsx(sn,{id:"calculated-name",value:y,onChange:xe=>v(xe.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":"",disabled:ie}),O.name&&l.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),x==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Operation"}),l.jsx(irt,{value:S,onChange:Pt,allowCustom:!0,disabled:ie}),O.operation&&l.jsx("p",{className:"text-xs text-red-500",children:O.operation})]}),S==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(y8,{ref:se,value:T,onChange:xe=>{P(xe),Se(!1)},onGenerate:()=>H(!0),showGenerate:!!Qe&&!ie,disabled:ie}),l.jsx(v8,{onValidate:async()=>{Se(!0),await et()},isValidating:Rt,validationResult:Ve,fallbackResult:it,error:Fe,showFallback:ce,disabled:ie}),O.expression&&l.jsx("p",{className:"text-xs text-red-500",children:O.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(de,{children:"Inputs"}),l.jsx(b8,{label:"A",input:N,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:xe=>{const nt=sE(xe,(N==null?void 0:N.aggregate)||Fh(xe));k(Mh(xe,nt))},onAggregateChange:xe=>ks("A",xe),onRemove:()=>k(null),onActivate:()=>Y("A"),allowMedian:g,disabled:ie}),O.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:O.inputA}),S!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(b8,{label:"B",input:E,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:xe=>{const nt=sE(xe,(E==null?void 0:E.aggregate)||Fh(xe));M(Mh(xe,nt))},onAggregateChange:xe=>ks("B",xe),onRemove:()=>M(null),onActivate:()=>Y("B"),allowMedian:g,disabled:ie}),O.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),S==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(sn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(j)?"":j,onChange:xe=>_(xe.target.value===""?Number.NaN:Number(xe.target.value)),className:O.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ie}),O.constant&&l.jsx("p",{className:"text-xs text-red-500",children:O.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:he||"Select inputs to preview formula"}),O.inputs&&l.jsxs(aN,{variant:"destructive",children:[l.jsx(xc,{className:"h-4 w-4"}),l.jsx(lN,{children:O.inputs})]})]})]}),x==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(y8,{ref:se,value:T,onChange:xe=>{P(xe),Se(!1)},onGenerate:()=>H(!0),showGenerate:!!Qe&&!ie,disabled:ie}),l.jsx(v8,{onValidate:async()=>{Se(!0),await et()},isValidating:Rt,validationResult:Ve,fallbackResult:it,error:Fe,showFallback:ce,disabled:ie}),O.expression&&l.jsx("p",{className:"text-xs text-red-500",children:O.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Output Type"}),l.jsxs(bt,{value:ut,onValueChange:xe=>R(xe),disabled:ie,children:[l.jsx(pt,{className:"h-9 w-full",children:l.jsx(wt,{placeholder:"Select output type"})}),l.jsx(gt,{children:S8.map(xe=>l.jsx(Ee,{value:xe.value,children:xe.label},xe.value))})]}),Le&&!F&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",Le]})]})]}),Ne&&(_e||me)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(drt,{scope:$,onChange:q,showDashboardScope:_e,showDomainScope:me,error:O.scope,disabled:ie}),$==="domain"&&l.jsx(frt,{description:U,tags:A,onDescriptionChange:W,onTagsChange:L,descriptionError:O.description,disabled:ie})]})]})]}),l.jsxs(Ns,{children:[l.jsx(te,{variant:"outline",onClick:$t,children:"Cancel"}),l.jsxs(te,{onClick:xt,disabled:le||ie,children:[r?"Update":"Create"," ",x==="metric"?"Metric":"Dimension"]})]})]})]}),l.jsx(mrt,{open:B,onOpenChange:H,availableFields:ye,fieldType:x,onExpressionGenerated:async xe=>{P(xe),Se(!1),je()},endpoint:Qe,dialect:p==null?void 0:p.dialect}),l.jsx(eh,{open:X,onOpenChange:re,children:l.jsxs(Uu,{children:[l.jsxs(Hu,{children:[l.jsx(qu,{children:"Name Conflict"}),l.jsxs(Yu,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",K==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Wu,{children:[l.jsx(Ku,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Gu,{onClick:async()=>{if(K){re(!1),ue(!0);try{await El(K)}finally{ue(!1),ee(null)}}},children:"Continue"})]})]})})]})}function ose({domainId:e}){const{authToken:t,tokenProps:n}=tt(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!c){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(c,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const ise=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var je,Le,ut,ct;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");$e(fe=>fe.isDevMode);const x=$e(fe=>fe.card.dataSource),b=$e(fe=>fe.card.config),y=$e(fe=>fe.card),v=$e(fe=>fe.frame),S=$e(fe=>fe.actions.updateCardConfig),C=$e(fe=>fe.actions.updateFrame),{userContext:N}=so(),{autoJoinMetadata:k}=ul(y),{columns:E,rawColumnGroups:M,scopedFields:j,dashboardCalculatedFields:_,cardCalculatedFields:T,isLoading:P,error:F,refetch:R}=yO(),$=(x==null?void 0:x.mode)==="semanticDomain"?x.semanticDomainId:void 0,{data:q}=vO($),{promoteMetric:U,promoteDimension:W}=ose({domainId:$}),A=w.useMemo(()=>[...(b==null?void 0:b.groupByColumns)||[],...(b==null?void 0:b.metricColumns)||[],...(b==null?void 0:b.detailColumns)||[]],[b==null?void 0:b.groupByColumns,b==null?void 0:b.metricColumns,b==null?void 0:b.detailColumns]);(Le=(je=b==null?void 0:b.joinPlan)==null?void 0:je.baseEntity)==null||Le.name,(ct=(ut=k==null?void 0:k.resolvedJoinPlan)==null?void 0:ut.baseEntity)==null||ct.name,Xre();const L=t==="editor",O=(N==null?void 0:N.type)==="organization",I=L?j:E,V=M,Y=s.toLowerCase(),G=(b==null?void 0:b.metricColumns)||[],z=(b==null?void 0:b.groupByColumns)||[],B=w.useCallback(async fe=>{await U(fe),R()},[U,R]),H=w.useCallback(async fe=>{await W(fe),R()},[W,R]),K=fe=>fe.name.toLowerCase().includes(Y)||fe.dataType.toLowerCase().includes(Y)||fe.label&&fe.label.toLowerCase().includes(Y)||fe.qualifiedEntityName&&fe.qualifiedEntityName.toLowerCase().includes(Y),ee=fe=>(fe.label||fe.name).toLowerCase().trim(),X=(fe,qe)=>ee(fe).localeCompare(ee(qe),void 0,{numeric:!0,sensitivity:"base"}),re=I.filter(K).sort(X),le=fe=>{if(fe.role==="metric"&&Ec(fe)||fe.role==="groupby"&&fe.expression)return"calculated";if(fe.dataType==="number"||fe.dataType==="integer"||fe.dataType==="float"||fe.dataType==="decimal"||fe.dataType==="currency")return"metrics";const qe=Nr(fe.dataType);return["date","string","boolean"].includes(qe)?"dimensions":qe==="number"?"metrics":"dimensions"},ue=fe=>{const qe=fe.filter(K);return i==="all"?qe:qe.filter(lt=>le(lt)===i)},ce=i==="all"?re:re.filter(fe=>le(fe)===i),Se=L?[..._,...T]:[],se=L?ue(Se).sort(X):[],pe=ue(E).sort(X).reduce((fe,qe)=>{const lt=qe.qualifiedEntityName||"Other Fields";return fe[lt]||(fe[lt]={label:qx(qe.entityName),fields:[]}),fe[lt].fields.push(qe),fe},{}),De=w.useMemo(()=>Object.entries(pe).map(([fe,qe])=>{const lt=V.find($t=>$t.entityName===fe)||{entityName:fe,label:qe.label},Pt=fe===km?"Domain Calculated Fields":lt.label||lt.entityName;return{groupName:fe,groupLabel:Pt,fields:[...qe.fields].sort(X)}}).sort((fe,qe)=>fe.groupLabel.localeCompare(qe.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[pe,V]),Pe=fe=>fe.id||`${fe.entityName}-${fe.qualifiedEntityName}-${fe.name}-${fe.role||"field"}`,ge=w.useMemo(()=>{const fe=new Map;return(L?j:E).forEach(lt=>{fe.set(Pe(lt),GD(lt,{joinabilityMap:(q==null?void 0:q.joinabilityMap)||null,selectedFields:A,cardConfig:b,autoJoinMetadata:k}))}),fe},[L,j,E,q==null?void 0:q.joinabilityMap,A,b,k]),ve=L?[{key:"scope-calculated",label:"Calculated Fields",fields:se}].filter(fe=>fe.fields.length>0):[],J=[...ve.map(fe=>fe.key),...De.map(fe=>fe.groupName)],oe=re.filter(fe=>le(fe)==="dimensions").length,we=re.filter(fe=>le(fe)==="metrics").length,Ne=re.filter(fe=>le(fe)==="calculated").length,_e=re.length>0&&t!=="inline-filter",me=t==="inline-filter"?"w-full":"w-[290px]";if(P)return l.jsx("div",{className:Z("flex h-full flex-col items-center justify-center py-8",me),children:l.jsx(Cc,{size:"md",color:"muted","aria-label":"Loading data"})});if(F)return l.jsxs("div",{className:Z("flex h-full flex-col items-center justify-center py-8",me),children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:F.message||"Failed to load column data"})]});if(!x||!x.selectedEntities||x.selectedEntities.length===0)return l.jsxs("div",{className:Z("flex flex-col items-center justify-center py-8 text-center",me),children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="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 Ie=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",ze=t==="inline-filter"?"overflow-hidden":"",Qe=fe=>fe!=null&&fe.startsWith("card-source-")?fe.replace("card-source-",""):fe,Te=(fe,qe,lt)=>{const Pt=Qe(fe.id),$t=Qe(qe.id);return Pt&&$t&&Pt===$t?!0:!Pt||!$t||lt!=null&<.allowNameFallback?fe.name===qe.name&&fe.role===qe.role:!1},Ye=(fe,qe,lt)=>fe.findIndex(Pt=>Te(Pt,qe,lt)),rt=fe=>{if(!v)return fe;const qe=v.calculatedFields||[],lt=Ye(qe,fe),Pt=lt>=0&&qe[lt].id!==fe.id?{...fe,id:qe[lt].id}:fe,$t=lt>=0?qe.map((_n,or)=>or===lt?Pt:_n):[...qe,Pt];return C({calculatedFields:$t}),Pt},Je=(fe,qe,lt,Pt)=>{var _n;const $t=Ye(fe,lt||qe,Pt);if($t>=0){const or=(_n=fe[$t])==null?void 0:_n.id,ns=or&&or!==qe.id?{...qe,id:or}:qe;return fe.map(($s,qi)=>qi===$t?ns:$s)}return[...fe,qe]},Be=fe=>{if(fe.role==="metric")return G.find(qe=>Te(qe,fe));if(fe.role==="groupby")return z.find(qe=>Te(qe,fe))},ye=fe=>{var qe;return(qe=v==null?void 0:v.calculatedFields)==null?void 0:qe.find(lt=>Te(lt,fe))},it=fe=>{if(fe.role==="metric"){S(y.id,{metricColumns:G.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))});return}fe.role==="groupby"&&S(y.id,{groupByColumns:z.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))})},Ve=fe=>{if(!v)return;const qe=(v.calculatedFields||[]).filter(lt=>!Te(lt,fe));C({calculatedFields:qe})},et=fe=>{if(!O)return;if(fe.fieldScope==="domain"){f(fe),m("domain"),g(fe.role==="metric"?"metric":"dimension"),u(!0);return}if(fe.fieldScope==="dashboard"){const lt=ye(fe);if(!lt)return;f(lt),m("dashboard"),g(lt.role==="metric"?"metric":"dimension"),u(!0);return}const qe=Be(fe);qe&&(f(qe),m("card"),g(qe.role==="metric"?"metric":"dimension"),u(!0))},Rt=fe=>{if(O&&fe.fieldScope!=="domain"){if(fe.fieldScope==="dashboard"){Ve(fe),it(fe);return}it(fe)}},Fe=fe=>{if(!O)return null;const qe=fe.fieldScope==="domain";return l.jsxs(Qf,{children:[l.jsx(Jf,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:l.jsx(d7,{className:"h-4 w-4"})})}),l.jsxs(Vu,{align:"end",className:"w-40",children:[l.jsx($o,{onClick:()=>et(fe),children:"Edit"}),l.jsx($o,{disabled:qe,onClick:()=>Rt(fe),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Z("mt-2 flex h-full w-full grow flex-col gap-2",Ie,ze),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[I.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Uo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx($n,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:fe=>o(fe.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Vt,{className:"size-3.5"})})]}),_e&&l.jsx(Fs,{defaultValue:"all",value:i,onValueChange:fe=>a(fe),className:"mb-4",children:l.jsxs(js,{className:"grid h-9 w-full grid-cols-4",children:[l.jsxs(cn,{value:"all",className:"text-xs",children:["All",l.jsx("span",{className:"ml-2 text-xs font-semibold",children:re.length})]}),l.jsxs(cn,{value:"dimensions",className:"text-xs",children:[l.jsx(BS,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:oe})]}),l.jsxs(cn,{value:"metrics",className:"text-xs",children:[l.jsx(OS,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:we})]}),l.jsxs(cn,{value:"calculated",className:"text-xs",children:[l.jsx(rI,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:Ne})]})]})}),t==="editor"&&i==="calculated"&&O&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(te,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Ar,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(wl,{className:"min-h-0 flex-1",children:[l.jsxs(_b,{type:"multiple",defaultValue:J,className:"space-y-2",children:[ve.map(fe=>l.jsxs(vu,{value:fe.key,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:fe.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:fe.fields.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:fe.fields.map(qe=>{const lt=ge.get(Pe(qe)),Pt=t==="editor"&&i==="calculated";return l.jsx(g8,{field:qe,context:t,fieldState:lt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Pt?Fe(qe):void 0},qe.id)})})})]},fe.key)),De.map(({groupName:fe,groupLabel:qe,fields:lt})=>l.jsxs(vu,{value:fe,className:"border-none",children:[l.jsx(wu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:qe,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:qe}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:lt.length})]})}),l.jsx(Su,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:lt.map(Pt=>{const $t=ge.get(Pe(Pt));return l.jsx(g8,{field:Pt,context:t,fieldState:$t,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Pt.id)})})})]},fe))]}),I.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),I.length>0&&ce.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Fi,{orientation:"horizontal"}),l.jsx(Fi,{orientation:"vertical"})]})]}),l.jsx(sse,{open:c,onOpenChange:fe=>{u(fe),fe||(f(null),m("card"))},availableFields:j,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:fe=>{if(fe.role==="metric"){if(d&&h==="card"){S(y.id,{metricColumns:Je(G,fe,d)});return}S(y.id,{metricColumns:Je(G,fe)});return}if(d&&h==="card"){S(y.id,{groupByColumns:Je(z,fe,d)});return}S(y.id,{groupByColumns:Je(z,fe)})},onSaveToDashboard:fe=>{const qe=!!(d&&h==="dashboard"),lt=qe?d:void 0;if(fe.role==="metric"){const $t=rt(fe);S(y.id,{metricColumns:Je(G,$t,lt,{allowNameFallback:qe})});return}const Pt=rt(fe);S(y.id,{groupByColumns:Je(z,Pt,lt,{allowNameFallback:qe})})},cardId:y.id,onPromoteMetricToDomain:$?B:void 0,onPromoteDimensionToDomain:$?H:void 0,domainId:$})]})}),ase=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(ise,{context:t})," "]})});function lse(){const e=$e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=br();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=wO(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(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Drt(){lse();const e=Q(c=>c.selectedSheetId),t=Q(c=>c.selectedFrameId),n=Q(c=>c.dashboard),r=Q(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=un(),{setCard:o}=br(),i=$e(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){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),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Art(){const e=Q(o=>o.dashboard.filterLayout),{setFilterLayout:t}=un(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(vs,{children:[l.jsx(ws,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(cc,{className:"h-4 w-4"})})}),l.jsx(Ss,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(As,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Sn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Sn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(yn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(de,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(yn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(de,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Rrt(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=Drt();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(de,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Art,{}),l.jsx(te,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(JJ,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(Ja,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(a0,{collisionDetection:s0,children:l.jsx(l0,{items:[],strategy:TP,children:l.jsx(ase,{context:"filter"})})})})]})}function Prt(){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?l.jsx("div",{className:Z("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(SP,{filter:r}),l.jsx(Qp,{filter:r})]},r.id))}):null}function Ort(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Z("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Prt,{}),l.jsx(Hre,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Rrt,{})})]})}const Frt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CD8QDWP8.js"))),$rt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BBs3ADo3.js"))),Lrt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BVzVl07t.js"))),zrt=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-D5niXqb5.js")).then(e=>({default:e.ResourceManagementPanel})));function Brt({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(c=>c.isDashboardPanelOpen),s=Q(c=>c.isVisualEditing),o=Q(c=>c.showDashboardJSON),i=Q(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(ya,{FallbackComponent:vN,children:l.jsxs(nI,{dashboardProps:n,children:[l.jsx(Khe,{}),l.jsx(bO,{componentType:"surfboard",componentId:n.id}),l.jsx(xO,{children:l.jsxs(Wre,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Lrt,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Frt,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(zrt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(CA,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx($rt,{})}),l.jsx(Ort,{})]})})]})]})]})})]})})}const cse=D.forwardRef(({className:e,...t},n)=>l.jsx(u0,{className:Z("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(IP,{className:Z("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));cse.displayName=u0.displayName;var Vrt=Object.defineProperty,Urt=(e,t,n)=>t in e?Vrt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Qv=(e,t,n)=>Urt(e,typeof t!="symbol"?t+"":t,n);const Hrt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Wrt={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}},qrt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Yrt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function use(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Grt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=use(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Krt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Zrt={stringify:e=>e,parse:e=>e},iE={string:Zrt,number:Krt,boolean:Hrt,function:Wrt,method:Grt,json:qrt},Fg=Symbol.for("r2wc.render"),Jv=Symbol.for("r2wc.connected"),Cd=Symbol.for("r2wc.context"),Zo=Symbol.for("r2wc.props");function Xrt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Yrt(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(),Qv(this,o,!0),Qv(this,s),Qv(this,r,{}),Qv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Zo].container=this.container;for(const p of i){const g=d[p],x=this.getAttribute(g),b=c[p],y=b?iE[b]:null;if(b==="method"){const v=use(g);Object.defineProperty(this[Zo].container,v,{enumerable:!0,configurable:!0,get(){return this[Zo][v]},set(S){this[Zo][v]=S,this[Fg]()}}),this[Zo][p]=y.parse(x,g,this)}y!=null&&y.parse&&x&&(this[Zo][p]=y.parse(x,g,this))}for(const p of a)this[Zo][p]=g=>{const x=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Jv]=!0,this[Fg]()}disconnectedCallback(){this[Jv]=!1,this[Cd]&&n.unmount(this[Cd]),delete this[Cd]}attributeChangedCallback(p,g,x){const b=f[p],y=c[b],v=y?iE[y]:null;b in c&&v!=null&&v.parse&&x&&(this[Zo][b]=v.parse(x,p,this),this[Fg]())}[(o=Jv,s=Cd,r=Zo,Fg)](){this[Jv]&&(this[Cd]?n.update(this[Cd],this[Zo]):this[Cd]=n.mount(this.container,e,this[Zo]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Zo][m]},set(x){this[Zo][m]=x;const b=g?iE[g]:null;if(b!=null&&b.stringify){const y=b.stringify(x,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Fg]()}})}return h}function Qrt(e,t,n){const r=loe.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Jrt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function est({root:e}){e.unmount()}function tst(e,t={}){return Xrt(e,t,{mount:Qrt,update:Jrt,unmount:est})}const nst={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"},rst=tst(qre,{props:nst});function C8(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function sst(e){if(Array.isArray(e))return e}function ost(e,t,n){return(t=fst(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ist(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function ast(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1089
1089
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N8(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 j8(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?N8(Object(n),!0).forEach(function(r){ost(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N8(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function lst(e,t){if(e==null)return{};var n,r,s=cst(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function cst(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function ust(e,t){return sst(e)||ist(e,t)||hst(e,t)||ast()}function dst(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function fst(e){var t=dst(e,"string");return typeof t=="symbol"?t:t+""}function hst(e,t){if(e){if(typeof e=="string")return C8(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?C8(e,t):void 0}}function mst(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k8(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 E8(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?k8(Object(n),!0).forEach(function(r){mst(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):k8(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function pst(){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 dx(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),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function NS(e){return{}.toString.call(e).includes("Object")}function gst(e){return!Object.keys(e).length}function Hb(e){return typeof e=="function"}function xst(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function bst(e,t){return NS(t)||Nu("changeType"),Object.keys(t).some(function(n){return!xst(e,n)})&&Nu("changeField"),t}function yst(e){Hb(e)||Nu("selectorType")}function vst(e){Hb(e)||NS(e)||Nu("handlerType"),NS(e)&&Object.values(e).some(function(t){return!Hb(t)})&&Nu("handlersType")}function wst(e){e||Nu("initialIsRequired"),NS(e)||Nu("initialType"),gst(e)&&Nu("initialContent")}function Sst(e,t){throw new Error(e[t]||e.default)}var Cst={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"},Nu=dx(Sst)(Cst),ew={changes:bst,selector:yst,handler:vst,initial:wst};function Nst(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};ew.initial(e),ew.handler(t);var n={current:e},r=dx(Est)(n,t),s=dx(kst)(n),o=dx(ew.changes)(e),i=dx(jst)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return ew.selector(u),u(n.current)}function c(u){pst(r,s,o,i)(u)}return[a,c]}function jst(e,t){return Hb(t)?t(e.current):t}function kst(e,t){return e.current=E8(E8({},e.current),t),t}function Est(e,t,n){return Hb(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 _st={create:Nst},Tst={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function Mst(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),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function Ist(e){return{}.toString.call(e).includes("Object")}function Dst(e){return e||_8("configIsRequired"),Ist(e)||_8("configType"),e.urls?(Ast(),{paths:{vs:e.urls.monacoBase}}):e}function Ast(){console.warn(dse.deprecation)}function Rst(e,t){throw new Error(e[t]||e.default)}var dse={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!
|
|
1090
1090
|
You are using deprecated way of configuration.
|
|
1091
1091
|
|
|
@@ -1095,4 +1095,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1095
1095
|
monaco.config({ paths: { vs: '...' } })
|
|
1096
1096
|
|
|
1097
1097
|
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
1098
|
-
`},_8=Mst(Rst)(dse),Pst={config:Dst},Ost=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(s){return n.reduceRight(function(o,i){return i(o)},s)}};function fse(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],fse(e[n],t[n]))}),j8(j8({},e),t)}var Fst={type:"cancelation",msg:"operation is manually canceled"};function aE(e){var t=!1,n=new Promise(function(r,s){e.then(function(o){return t?s(Fst):r(o)}),e.catch(s)});return n.cancel=function(){return t=!0},n}var $st=["monaco"],Lst=_st.create({config:Tst,isInitialized:!1,resolve:null,reject:null,monaco:null}),hse=ust(Lst,2),x0=hse[0],tj=hse[1];function zst(e){var t=Pst.config(e),n=t.monaco,r=lst(t,$st);tj(function(s){return{config:fse(s.config,r),monaco:n}})}function Bst(){var e=x0(function(t){var n=t.monaco,r=t.isInitialized,s=t.resolve;return{monaco:n,isInitialized:r,resolve:s}});if(!e.isInitialized){if(tj({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),aE(lE);if(window.monaco&&window.monaco.editor)return mse(window.monaco),e.resolve(window.monaco),aE(lE);Ost(Vst,Hst)(Wst)}return aE(lE)}function Vst(e){return document.body.appendChild(e)}function Ust(e){var t=document.createElement("script");return e&&(t.src=e),t}function Hst(e){var t=x0(function(r){var s=r.config,o=r.reject;return{config:s,reject:o}}),n=Ust("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function Wst(){var e=x0(function(n){var r=n.config,s=n.resolve,o=n.reject;return{config:r,resolve:s,reject:o}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){var r=n.m||n;mse(r),e.resolve(r)},function(n){e.reject(n)})}function mse(e){x0().monaco||tj({monaco:e})}function qst(){return x0(function(e){var t=e.monaco;return t})}var lE=new Promise(function(e,t){return tj({resolve:e,reject:t})}),jS={config:zst,init:Bst,__getMonacoInstance:qst},Yst={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},cE=Yst,Gst={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Kst=Gst;function Zst({children:e}){return w.createElement("div",{style:Kst.container},e)}var Xst=Zst,Qst=Xst;function Jst({width:e,height:t,isEditorReady:n,loading:r,_ref:s,className:o,wrapperProps:i}){return w.createElement("section",{style:{...cE.wrapper,width:e,height:t},...i},!n&&w.createElement(Qst,null,r),w.createElement("div",{ref:s,style:{...cE.fullWidth,...!n&&cE.hide},className:o}))}var eot=Jst,pse=w.memo(eot);function tot(e){w.useEffect(e,[])}var CO=tot;function not(e,t,n=!0){let r=w.useRef(!0);w.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var si=not;function Fx(){}function qh(e,t,n,r){return rot(e,r)||sot(e,t,n,r)}function rot(e,t){return e.editor.getModel(gse(e,t))}function sot(e,t,n,r){return e.editor.createModel(t,n,r?gse(e,r):void 0)}function gse(e,t){return e.Uri.parse(t)}function oot({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:s,originalModelPath:o,modifiedModelPath:i,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:c=!1,theme:u="light",loading:d="Loading...",options:f={},height:h="100%",width:m="100%",className:p,wrapperProps:g={},beforeMount:x=Fx,onMount:b=Fx}){let[y,v]=w.useState(!1),[S,C]=w.useState(!0),N=w.useRef(null),k=w.useRef(null),E=w.useRef(null),M=w.useRef(b),j=w.useRef(x),_=w.useRef(!1);CO(()=>{let R=jS.init();return R.then($=>(k.current=$)&&C(!1)).catch($=>($==null?void 0:$.type)!=="cancelation"&&console.error("Monaco initialization: error:",$)),()=>N.current?F():R.cancel()}),si(()=>{if(N.current&&k.current){let R=N.current.getOriginalEditor(),$=qh(k.current,e||"",r||n||"text",o||"");$!==R.getModel()&&R.setModel($)}},[o],y),si(()=>{if(N.current&&k.current){let R=N.current.getModifiedEditor(),$=qh(k.current,t||"",s||n||"text",i||"");$!==R.getModel()&&R.setModel($)}},[i],y),si(()=>{let R=N.current.getModifiedEditor();R.getOption(k.current.editor.EditorOption.readOnly)?R.setValue(t||""):t!==R.getValue()&&(R.executeEdits("",[{range:R.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),R.pushUndoStop())},[t],y),si(()=>{var R,$;($=(R=N.current)==null?void 0:R.getModel())==null||$.original.setValue(e||"")},[e],y),si(()=>{let{original:R,modified:$}=N.current.getModel();k.current.editor.setModelLanguage(R,r||n||"text"),k.current.editor.setModelLanguage($,s||n||"text")},[n,r,s],y),si(()=>{var R;(R=k.current)==null||R.editor.setTheme(u)},[u],y),si(()=>{var R;(R=N.current)==null||R.updateOptions(f)},[f],y);let T=w.useCallback(()=>{var q;if(!k.current)return;j.current(k.current);let R=qh(k.current,e||"",r||n||"text",o||""),$=qh(k.current,t||"",s||n||"text",i||"");(q=N.current)==null||q.setModel({original:R,modified:$})},[n,t,s,e,r,o,i]),P=w.useCallback(()=>{var R;!_.current&&E.current&&(N.current=k.current.editor.createDiffEditor(E.current,{automaticLayout:!0,...f}),T(),(R=k.current)==null||R.editor.setTheme(u),v(!0),_.current=!0)},[f,u,T]);w.useEffect(()=>{y&&M.current(N.current,k.current)},[y]),w.useEffect(()=>{!S&&!y&&P()},[S,y,P]);function F(){var $,q,U,W;let R=($=N.current)==null?void 0:$.getModel();a||((q=R==null?void 0:R.original)==null||q.dispose()),c||((U=R==null?void 0:R.modified)==null||U.dispose()),(W=N.current)==null||W.dispose()}return w.createElement(pse,{width:m,height:h,isEditorReady:y,loading:d,_ref:E,className:p,wrapperProps:g})}var iot=oot;w.memo(iot);function aot(){let[e,t]=w.useState(jS.__getMonacoInstance());return CO(()=>{let n;return e||(n=jS.init(),n.then(r=>{t(r)})),()=>n==null?void 0:n.cancel()}),e}var lot=aot;function cot(e){let t=w.useRef();return w.useEffect(()=>{t.current=e},[e]),t.current}var uot=cot,tw=new Map;function dot({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:s,path:o,theme:i="light",line:a,loading:c="Loading...",options:u={},overrideServices:d={},saveViewState:f=!0,keepCurrentModel:h=!1,width:m="100%",height:p="100%",className:g,wrapperProps:x={},beforeMount:b=Fx,onMount:y=Fx,onChange:v,onValidate:S=Fx}){let[C,N]=w.useState(!1),[k,E]=w.useState(!0),M=w.useRef(null),j=w.useRef(null),_=w.useRef(null),T=w.useRef(y),P=w.useRef(b),F=w.useRef(),R=w.useRef(r),$=uot(o),q=w.useRef(!1),U=w.useRef(!1);CO(()=>{let L=jS.init();return L.then(O=>(M.current=O)&&E(!1)).catch(O=>(O==null?void 0:O.type)!=="cancelation"&&console.error("Monaco initialization: error:",O)),()=>j.current?A():L.cancel()}),si(()=>{var O,I,V,Y;let L=qh(M.current,e||r||"",t||s||"",o||n||"");L!==((O=j.current)==null?void 0:O.getModel())&&(f&&tw.set($,(I=j.current)==null?void 0:I.saveViewState()),(V=j.current)==null||V.setModel(L),f&&((Y=j.current)==null||Y.restoreViewState(tw.get(o))))},[o],C),si(()=>{var L;(L=j.current)==null||L.updateOptions(u)},[u],C),si(()=>{!j.current||r===void 0||(j.current.getOption(M.current.editor.EditorOption.readOnly)?j.current.setValue(r):r!==j.current.getValue()&&(U.current=!0,j.current.executeEdits("",[{range:j.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),j.current.pushUndoStop(),U.current=!1))},[r],C),si(()=>{var O,I;let L=(O=j.current)==null?void 0:O.getModel();L&&s&&((I=M.current)==null||I.editor.setModelLanguage(L,s))},[s],C),si(()=>{var L;a!==void 0&&((L=j.current)==null||L.revealLine(a))},[a],C),si(()=>{var L;(L=M.current)==null||L.editor.setTheme(i)},[i],C);let W=w.useCallback(()=>{var L;if(!(!_.current||!M.current)&&!q.current){P.current(M.current);let O=o||n,I=qh(M.current,r||e||"",t||s||"",O||"");j.current=(L=M.current)==null?void 0:L.editor.create(_.current,{model:I,automaticLayout:!0,...u},d),f&&j.current.restoreViewState(tw.get(O)),M.current.editor.setTheme(i),a!==void 0&&j.current.revealLine(a),N(!0),q.current=!0}},[e,t,n,r,s,o,u,d,f,i,a]);w.useEffect(()=>{C&&T.current(j.current,M.current)},[C]),w.useEffect(()=>{!k&&!C&&W()},[k,C,W]),R.current=r,w.useEffect(()=>{var L,O;C&&v&&((L=F.current)==null||L.dispose(),F.current=(O=j.current)==null?void 0:O.onDidChangeModelContent(I=>{U.current||v(j.current.getValue(),I)}))},[C,v]),w.useEffect(()=>{if(C){let L=M.current.editor.onDidChangeMarkers(O=>{var V;let I=(V=j.current.getModel())==null?void 0:V.uri;if(I&&O.find(Y=>Y.path===I.path)){let Y=M.current.editor.getModelMarkers({resource:I});S==null||S(Y)}});return()=>{L==null||L.dispose()}}return()=>{}},[C,S]);function A(){var L,O;(L=F.current)==null||L.dispose(),h?f&&tw.set(o,j.current.saveViewState()):(O=j.current.getModel())==null||O.dispose(),j.current.dispose()}return w.createElement(pse,{width:m,height:p,isEditorReady:C,loading:c,_ref:_,className:g,wrapperProps:x})}var fot=dot,xse=w.memo(fot),hot=xse;const bse=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),mot=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),pot=Array.from(bse).join(", "),got=3,xot="Self-heal",bot=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function yot({card:e}){var U,W,A,L,O,I,V;const[t,n]=w.useState({}),{authToken:r}=tt(),{theme:s}=cp(),o=KM(r==null?void 0:r.accessToken),i=Q(Y=>Y.themeStyle),a={mode:s||"system",colors:((W=(U=i==null?void 0:i.chart)==null?void 0:U.dataset)==null?void 0:W.backgroundColor)||[]},c=$e(Y=>Y.frame),u=e,{getCard:d,manifest:f}=ih(((A=u.customCardPreferences)==null?void 0:A.url)||""),h=(L=f==null?void 0:f.visuals)==null?void 0:L.find(Y=>{var G;return Y.name===((G=u.customCardPreferences)==null?void 0:G.componentName)}),m=Qy(u,h)??"single",p=w.useMemo(()=>XR({frame:c,configCard:u,isMultiInputVisual:m==="multiple"}),[c,u,m]),g=w.useMemo(()=>{const Y=p.findIndex(G=>(G==null?void 0:G.id)===e.id);return Y<0?-1:jb(e,Y)},[p,e]),x=w.useMemo(()=>m!=="multiple"||g<0?e.type:am(e,g,h==null?void 0:h.slots)??e.type,[m,g,e,h==null?void 0:h.slots]),b=w.useMemo(()=>m==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:x!==e.type?{...e,type:x}:e,[e,x,m]),{data:y}=ul(b),v=Qt(Y=>Y.interactionStates),S=Q(Y=>{var G;return(G=Y.dashboard)==null?void 0:G.id}),C=Q(Y=>Y.dashboard.filters),N=Q(Y=>Y.filterValues),k=Q(Y=>Y.selectedSheetId),E=Q(Y=>Y.inlineFilterValuesMap[e.id]),M=w.useMemo(()=>GR({card:e,sheetId:k||"",inlineFilterValues:E}),[e,k,E]),{cardFilters:j,cardFilterValues:_}=w.useMemo(()=>gC({card:e,interactionStates:v,currentDashboardId:S,filters:C,filterValues:N,selectedSheetId:k}),[e,v,S,C,N,k]),T=w.useCallback((Y,G)=>{const z=JR(G);n(B=>({...B,[Y]:z}))},[]),P=(O=u.customCardPreferences)==null?void 0:O.componentName,F=P?d(P):null,R=H1((I=u.customCardPreferences)==null?void 0:I.settings,u),$=w.useMemo(()=>ZR(p),[p]),q=w.useMemo(()=>$.map((Y,G)=>am(Y,G,h==null?void 0:h.slots)),[$,h==null?void 0:h.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(w.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[F&&m==="single"&&l.jsx(F,{editing:!0,params:o,theme:a,settings:R,cardMetadata:ZQ({card:e,dataMetadata:y==null?void 0:y.metadata}),onDataChange:T,data:(y==null?void 0:y.records)||[],filters:j,filterValues:[..._||[],...E||[]],inlineFilters:M}),F&&m==="multiple"&&l.jsxs(l.Fragment,{children:[p.map((Y,G)=>{if(!Y)return null;const z=jb(Y,G),B=am(Y,z,h==null?void 0:h.slots);return l.jsx(kR,{onDataChange:T,card:Y,effectiveCardType:B},`${Y.id}-${z}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(F,{editing:!0,onDataChange:T,...eP({configCard:u,slotOrderedCards:$,slotTypes:q,multiInputData:t,params:o,theme:a,chartSettings:R,filters:j,filterValues:[..._||[],...E||[]],inlineFilters:M})})})]})]},(V=u.customCardPreferences)==null?void 0:V.componentName)}):null}const vot=w.memo(yot,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)});function wot(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return`hsl(${Math.abs(t%360)}, 65%, 45%)`}function Sot(e){const t=e.trim().split(/\s+/);return t.length>1?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}function yse({chartType:e,chartName:t,isCustom:n=!1,className:r="h-6 w-6"}){if(!n&&e)return rP(e,r);const s=oJ(t);if(s)return w.cloneElement(s,{className:r});const o=Sot(t),i=wot(t);return l.jsx("div",{className:Z("flex items-center justify-center rounded text-white font-semibold text-xs",r),style:{backgroundColor:i},children:o})}const vse=Vi()(e9((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var wse=["PageUp","PageDown"],Sse=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Cse={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ag="Slider",[CM,Cot,Not]=cy(ag),[Nse]=ts(ag,[Not]),[jot,nj]=Nse(ag),jse=D.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:p,...g}=e,x=D.useRef(new Set),b=D.useRef(0),v=i==="horizontal"?kot:Eot,[S=[],C]=Cs({prop:d,defaultProp:u,onChange:_=>{var P;(P=[...x.current][b.current])==null||P.focus(),f(_)}}),N=D.useRef(S);function k(_){const T=Dot(S,_);j(_,T)}function E(_){j(_,b.current)}function M(){const _=N.current[b.current];S[b.current]!==_&&h(S)}function j(_,T,{commit:P}={commit:!1}){const F=Oot(o),R=Fot(Math.round((_-r)/o)*o+r,F),$=gb(R,[r,s]);C((q=[])=>{const U=Mot(q,$,T);if(Pot(U,c*o)){b.current=U.indexOf($);const W=String(U)!==String(q);return W&&P&&h(U),W?U:q}else return q})}return l.jsx(jot,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:b,thumbs:x.current,values:S,orientation:i,form:p,children:l.jsx(CM.Provider,{scope:e.__scopeSlider,children:l.jsx(CM.Slot,{scope:e.__scopeSlider,children:l.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Ue(g.onPointerDown,()=>{a||(N.current=S)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:k,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:M,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,S.length-1,{commit:!0}),onStepKeyDown:({event:_,direction:T})=>{if(!a){const R=wse.includes(_.key)||_.shiftKey&&Sse.includes(_.key)?10:1,$=b.current,q=S[$],U=o*R*T;j(q+U,$,{commit:!0})}}})})})})});jse.displayName=ag;var[kse,Ese]=Nse(ag,{startEdge:"left",endEdge:"right",size:"width",direction:1}),kot=D.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=D.useState(null),m=jt(t,v=>h(v)),p=D.useRef(void 0),g=zu(s),x=g==="ltr",b=x&&!o||!x&&o;function y(v){const S=p.current||f.getBoundingClientRect(),C=[0,S.width],k=NO(C,b?[n,r]:[r,n]);return p.current=S,k(v-S.left)}return l.jsx(kse,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:l.jsx(_se,{dir:g,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const S=y(v.clientX);i==null||i(S)},onSlideMove:v=>{const S=y(v.clientX);a==null||a(S)},onSlideEnd:()=>{p.current=void 0,c==null||c()},onStepKeyDown:v=>{const C=Cse[b?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:C?-1:1})}})})}),Eot=D.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=D.useRef(null),f=jt(t,d),h=D.useRef(void 0),m=!s;function p(g){const x=h.current||d.current.getBoundingClientRect(),b=[0,x.height],v=NO(b,m?[r,n]:[n,r]);return h.current=x,v(g-x.top)}return l.jsx(kse,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:l.jsx(_se,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const x=p(g.clientY);o==null||o(x)},onSlideMove:g=>{const x=p(g.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=Cse[m?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:b?-1:1})}})})}),_se=D.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=nj(ag,n);return l.jsx(at.span,{...u,ref:t,onKeyDown:Ue(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):wse.concat(Sse).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:Ue(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Ue(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:Ue(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),Tse="SliderTrack",Mse=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=nj(Tse,n);return l.jsx(at.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});Mse.displayName=Tse;var NM="SliderRange",Ise=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=nj(NM,n),o=Ese(NM,n),i=D.useRef(null),a=jt(t,i),c=s.values.length,u=s.values.map(h=>Rse(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(at.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Ise.displayName=NM;var jM="SliderThumb",Dse=D.forwardRef((e,t)=>{const n=Cot(e.__scopeSlider),[r,s]=D.useState(null),o=jt(t,a=>s(a)),i=D.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(_ot,{...e,ref:o,index:i})}),_ot=D.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=nj(jM,n),a=Ese(jM,n),[c,u]=D.useState(null),d=jt(t,y=>u(y)),f=c?i.form||!!c.closest("form"):!0,h=dy(c),m=i.values[r],p=m===void 0?0:Rse(m,i.min,i.max),g=Iot(r,i.values.length),x=h==null?void 0:h[a.size],b=x?Aot(x,p,a.direction):0;return D.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${p}% + ${b}px)`},children:[l.jsx(CM.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(at.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:Ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(Ase,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});Dse.displayName=jM;var Tot="RadioBubbleInput",Ase=D.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=D.useRef(null),o=jt(s,r),i=vy(t);return D.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(at.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});Ase.displayName=Tot;function Mot(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Rse(e,t,n){const o=100/(n-t)*(e-t);return gb(o,[0,100])}function Iot(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Dot(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function Aot(e,t,n){const r=e/2,o=NO([0,50],[0,r]);return(r-o(t)*n)*n}function Rot(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Pot(e,t){if(t>0){const n=Rot(e);return Math.min(...n)>=t}return!0}function NO(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Oot(e){return(String(e).split(".")[1]||"").length}function Fot(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Pse=jse,$ot=Mse,Lot=Ise,zot=Dse;const Ose=D.forwardRef(({className:e,...t},n)=>l.jsxs(Pse,{ref:n,className:Z("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx($ot,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(Lot,{className:"absolute h-full bg-primary"})}),l.jsx(zot,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Ose.displayName=Pse.displayName;const Bot={table:Zh,bar:PS,line:sy,stackedBar:sI,stackedLine:sJ,scatter:aI,bubble:rJ,pie:iI,doughnut:dI,kpi:nP,treemap:wN,bullet:SN,funnel:tP,tornado:SI,heatmap:LS,range:oI,radar:x7,polarArea:nJ,text:n7,map:g7},Fse=[{id:"table",icon:Zh,label:"Table"},{id:"bar",icon:PS,label:"Bar Chart"},{id:"line",icon:sy,label:"Line Chart"},{id:"stackedBar",icon:sI,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:iI,label:"Pie Chart"},{id:"doughnut",icon:dI,label:"Donut Chart"},{id:"kpi",icon:nP,label:"KPI"},{id:"treemap",icon:wN,label:"Treemap"},{id:"bullet",icon:SN,label:"Bullet Chart"},{id:"funnel",icon:tP,label:"Funnel Chart"},{id:"tornado",icon:SI,label:"Tornado Chart"},{id:"heatmap",icon:LS,label:"Heatmap"},{id:"range",icon:oI,label:"Range Chart"}],Vot=14;Fse.map(e=>e.id);function Uot({selectedChart:e,onChartChange:t,isDropdownExpanded:n,onToggleDropdown:r}){var S,C;const s=$e(N=>N.card),{setCardType:o,setCardPreferences:i}=$e(N=>N.actions),{setCardCustomCfg:a,setCustomCardPreferences:c,setQueryConfig:u,replaceFrameCards:d,clearModeDrafts:f,initializeModeDrafts:h}=br(),m=((S=s==null?void 0:s.config)==null?void 0:S.pivotByColumns)&&s.config.pivotByColumns.length>0,{starredCharts:p,isStarred:g}=vse(),{data:x=[]}=vP(),b=w.useMemo(()=>{const N=Fse.filter(_=>!(_.requiresPivot&&!m)),k=p.filter(_=>_.type==="default"?!0:x.some(T=>T.name===_.id)),E=new Set(k.map(_=>_.id)),M=N.filter(_=>!E.has(_.id));return[...k.map(_=>({id:_.id,label:_.name,icon:_.type==="default"?Bot[_.id]:void 0,isCustom:_.type==="custom",isStarred:!0,url:_.url})),...M.map(_=>({id:_.id,label:_.label,icon:_.icon,isCustom:!1,isStarred:!1}))].slice(0,Vot-1)},[p,x,m]),y=N=>{if(N.isCustom){const k=x.find(E=>E.name===N.id);if(k){a(null),i({}),u(void 0);const E=GQ(k);if(E==="multiple"&&k.slots&&k.slots.length>0){f();const j=YQ(k.slots,k,s);d(j),j[0]&&h(j[0]);return}o("custom"),c({type:"component",visualType:E,url:k.url,componentName:k.name,icon:k.icon,pluginChartType:k.chartType,minInputs:k.minInputs,maxInputs:k.maxInputs}),t("custom")}}else t(N.id)},v=e==="custom"&&((C=s==null?void 0:s.customCardPreferences)==null?void 0:C.componentName);return l.jsxs("div",{className:"grid grid-cols-7 gap-1.5",children:[b.map(N=>{var M;const k=N.icon,E=N.isCustom?v&&((M=s==null?void 0:s.customCardPreferences)==null?void 0:M.componentName)===N.id:e===N.id;return l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsxs(te,{variant:"ghost",size:"sm",onClick:()=>y(N),className:Z("h-8 w-8 rounded-md p-0 text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground",E&&"bg-accent/80 text-foreground shadow-sm ring-1 ring-border"),children:[k?l.jsx(k,{className:"h-4 w-4"}):l.jsx(yse,{chartName:N.label,isCustom:!0,className:"h-4 w-4"}),l.jsx("span",{className:"sr-only",children:N.label})]})}),l.jsxs(Mn,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[l.jsx("p",{children:N.label}),l.jsx(Am,{className:"fill-foreground"})]})]},`${N.isCustom?"custom":"default"}-${N.id}`)}),r&&l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 rounded-md p-0 text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground","aria-label":n?"Hide all charts":"Show all charts",children:n?l.jsx(af,{className:"h-4 w-4"}):l.jsx(dr,{className:"h-4 w-4"})})}),l.jsxs(Mn,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[l.jsx("p",{children:n?"Hide dropdown":"Show all charts"}),l.jsx(Am,{className:"fill-foreground"})]})]})]})}const $se=D.forwardRef(({className:e,icon:t,tooltip:n,...r},s)=>{const o=l.jsx(u0,{className:Z("peer inline-flex h-8 w-12 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...r,ref:s,children:l.jsx(IP,{className:Z("pointer-events-none block h-7 w-7 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),children:t&&l.jsx("span",{className:"flex h-full items-center justify-center text-primary",children:t})})});return n?l.jsx(nr,{children:l.jsxs(jn,{delayDuration:0,children:[l.jsx(kn,{asChild:!0,children:l.jsx("span",{className:"inline-flex",children:o})}),l.jsxs(Mn,{side:"bottom",className:"border-0 bg-foreground text-background shadow-md",children:[l.jsx(Am,{className:"fill-foreground"}),l.jsx("p",{children:n})]})]})}):o});$se.displayName="DevModeSwitch";exports.Accordion=_b;exports.AccordionContent=Su;exports.AccordionItem=vu;exports.AccordionTrigger=wu;exports.AggregateTable=uN;exports.Alert=aN;exports.AlertCreationDialog=cP;exports.AlertDescription=lN;exports.AlertDialog=eh;exports.AlertDialogAction=Gu;exports.AlertDialogCancel=Ku;exports.AlertDialogContent=Uu;exports.AlertDialogDescription=Yu;exports.AlertDialogFooter=Wu;exports.AlertDialogHeader=Hu;exports.AlertDialogTitle=qu;exports.AlertManagementPage=jJ;exports.AlertsApiError=KD;exports.ArrowDown=qa;exports.ArrowRight=e7;exports.ArrowUp=Ei;exports.ArrowUpDown=qc;exports.AssistantContextEntityControls=SM;exports.AssistantStatus=Cne;exports.AxisConfigurator=jp;exports.Badge=st;exports.Bell=Gh;exports.BulletChartIcon=SN;exports.Button=te;exports.CALCULATED_FIELDS_GROUP_NAME=km;exports.CALCULATED_FIELD_ENTITY_MARKER=Sc;exports.COMPARISON_SUPPORTED_CHART_TYPES=i9;exports.CSS=zi;exports.CalculatedFieldEditor=sse;exports.Calculator=rI;exports.Calendar=ps;exports.Card=Vo;exports.CardAlertIndicator=GJ;exports.CardContent=Pi;exports.CardHeader=Ri;exports.CardSummary=HT;exports.CardTitle=ma;exports.CaretSortIcon=y8e;exports.ChartArea=VE;exports.ChartColumn=OS;exports.ChartColumnIncreasing=PS;exports.ChartIcon=yse;exports.ChartJsVisual=Uy;exports.ChartLine=sy;exports.ChartQuickSelector=Uot;exports.ChartScatter=aI;exports.ChatInputWithContext=gO;exports.Check=Ur;exports.CheckIcon=QJ;exports.Checkbox=yn;exports.ChevronDown=dr;exports.ChevronLeft=FS;exports.ChevronRight=bs;exports.ChevronUp=af;exports.ChevronsUpDown=lI;exports.Circle=uI;exports.CircleAlert=xc;exports.CircleCheck=cI;exports.CircleHelp=l7;exports.Clock=ju;exports.Code=c7;exports.CodeHighlighter=Cu;exports.CodeXml=HE;exports.Collapsible=Qs;exports.CollapsibleContent=eo;exports.CollapsibleTrigger=Js;exports.Command=Rp;exports.CommandEmpty=Op;exports.CommandGroup=Fp;exports.CommandInput=Oy;exports.CommandItem=$p;exports.CommandList=Pp;exports.CommandSeparator=NY;exports.ComparisonMetadataBadge=yZ;exports.Container=CA;exports.Copy=_m;exports.CopyButton=rp;exports.CopyPlus=u7;exports.CreateDashboardDialog=sU;exports.Cross2Icon=JJ;exports.CustomFilterPopover=wP;exports.CustomScrollArea=wl;exports.DATE_FORMAT_VALUES=DNe;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=bq;exports.Dashboard=qre;exports.DashboardActionsMenu=dV;exports.DashboardCard=KJ;exports.DashboardExportDialog=Oee;exports.DashboardPlus=Brt;exports.DashboardWC=rst;exports.DataSourceDialog=pO;exports.Database=Ja;exports.DateRangePicker=DR;exports.DefaultChatTransport=mO;exports.DevModeSwitch=$se;exports.Dialog=Wr;exports.DialogContent=Rr;exports.DialogDescription=Xr;exports.DialogFooter=Ns;exports.DialogHeader=Pr;exports.DialogTitle=Or;exports.DialogTrigger=Kme;exports.DisplayPreferencesProvider=bP;exports.DndContext=a0;exports.Download=Yf;exports.DownloadPdf=Fee;exports.DragOverlay=Nee;exports.DropdownMenu=Qf;exports.DropdownMenuCheckboxItem=fx;exports.DropdownMenuContent=Vu;exports.DropdownMenuItem=$o;exports.DropdownMenuLabel=Jh;exports.DropdownMenuRadioGroup=She;exports.DropdownMenuRadioItem=cV;exports.DropdownMenuSeparator=jf;exports.DropdownMenuSub=lV;exports.DropdownMenuSubContent=qI;exports.DropdownMenuSubTrigger=WI;exports.DropdownMenuTrigger=Jf;exports.EMPTY_DATA_SOURCE=KN;exports.Editable=K1;exports.EditableText=Ai;exports.EditorCustomVisual=vot;exports.EllipsisVertical=dp;exports.EmailScheduleDialog=aJ;exports.ErrorBoundary=ya;exports.ExportError=Ip;exports.ExternalLink=Kx;exports.Eye=ku;exports.EyeOff=$S;exports.Fallback=vN;exports.FallbackVisual=kb;exports.FeedbackCategory=Ou;exports.FeedbackDialog=$b;exports.FieldsList=ise;exports.FieldsSection=ase;exports.FileText=pa;exports.Filter=lc;exports.FilterComponent=Qp;exports.FilterHeader=SP;exports.FilterInfo=VT;exports.Ft=hot;exports.GenIcon=ch;exports.Grid3x3=LS;exports.GripVertical=zS;exports.HEATMAP_PRESET_PALETTES=V_;exports.Hash=h7;exports.House=Zx;exports.HoverCard=vp;exports.HoverCardContent=Sp;exports.HoverCardTrigger=wp;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=bse;exports.INLINE_ALLOWED_TOOL_LIST=pot;exports.INLINE_BLOCKED_MUTATING_TOOLS=mot;exports.IconButton=hu;exports.Info=tr;exports.InfoHover=xP;exports.InlineFilterBar=YJ;exports.Input=sn;exports.Input$1=$n;exports.KPICard=Mb;exports.KeyboardSensor=o0;exports.LOCALE_CURRENCY_PAIRS=qie;exports.Label=de;exports.Layers=BS;exports.Le=lot;exports.Link=m7;exports.List=hI;exports.LoaderCircle=Nn;exports.LoadingDots=Cc;exports.MAX_SELF_HEAL_ATTEMPTS=got;exports.METADATA_KEYS=$M;exports.Markdown=Vte;exports.Maximize2=VS;exports.MessageSquareWarning=mI;exports.Minimize2=pI;exports.MultiInputEmptyRenderer=kR;exports.PYTHON_DEFAULT_CODE=FM;exports.PenLine=YE;exports.Pencil=xI;exports.PendingMessagesDisplay=Lre;exports.PivotMarkerEnum=Sq;exports.PivotTableTanstack=Jy;exports.Placeholders=jne;exports.Play=US;exports.Plus=Ar;exports.PointerSensor=ng;exports.Popover=vs;exports.PopoverContent=Ss;exports.PopoverTrigger=ws;exports.PortalTooltipContent=uP;exports.PrintMessages=Nne;exports.Progress=EN;exports.RECOVERABLE_SQL_ERROR_CODES=bot;exports.RadioGroup=As;exports.RadioGroupItem=Sn;exports.RefreshCcw=b7;exports.RefreshCw=Vw;exports.ResizableHandle=VBe;exports.ResizablePanel=XT;exports.ResizablePanelGroup=ote;exports.ResourceEditDialog=qG;exports.ResourceType=vn;exports.SELF_HEAL_TIMELINE_STEP=xot;exports.ScrollArea=No;exports.ScrollBar=Fi;exports.Search=Uo;exports.SeedQuestions=Pre;exports.Select=bt;exports.SelectContent=gt;exports.SelectGroup=pA;exports.SelectItem=Ee;exports.SelectLabel=UC;exports.SelectTrigger=pt;exports.SelectValue=wt;exports.SemaphorContext=ry;exports.SemaphorContextProvider=nI;exports.SemaphorQueryClient=q9;exports.SemaphorReadyIndicator=bO;exports.Separator=Ds;exports.Settings=fp;exports.Settings2=cc;exports.Share2=Kh;exports.ShareDialog=WG;exports.Skeleton=wo;exports.Slider=Ose;exports.SmallSwitch=cse;exports.SortableContext=l0;exports.Sparkles=iy;exports.Square=y7;exports.SquarePen=HS;exports.Star=vI;exports.SummaryCard=BT;exports.Table2=Zh;exports.TableSkeleton=UJ;exports.TableVisual=Ff;exports.Tabs=Fs;exports.TabsContent=cr;exports.TabsList=js;exports.TabsTrigger=cn;exports.Tag=v7;exports.TbChartTreemap=wN;exports.TextCard=Qm;exports.Textarea=ja;exports.Toggle=e0;exports.Tooltip=jn;exports.TooltipArrow=Am;exports.TooltipContent=Mn;exports.TooltipProvider=nr;exports.TooltipTrigger=kn;exports.Trash2=Sa;exports.TreePalm=CI;exports.TrendingUp=Tm;exports.TriangleAlert=Gf;exports.Type=GE;exports.UXProvider=xO;exports.Undo2=Xx;exports.User=bc;exports.UserPlus=w7;exports.Users=is;exports.X=Vt;exports.areEntitiesJoined=Nq;exports.arrayMove=rg;exports.backtestAlert=Hq;exports.buildFilterFieldMeta=Qre;exports.buildFilterSemanticContext=Jre;exports.buildInlineFilterNodes=GR;exports.buildMultiInputCustomVisualProps=eP;exports.buildSlotOrderedCards=ZR;exports.calculateContextAwareFilters=gC;exports.calculateFieldState=GD;exports.canUserAccessVisuals=i8e;exports.canUserCreateDashboards=o8e;exports.canUserEdit=n8e;exports.canUserManageDashboards=s8e;exports.canUserManageGroups=a8e;exports.canUserUseFilters=r8e;exports.cancelExport=XNe;exports.chartSupportsDataLabels=pW;exports.chartSupportsLegend=hW;exports.chartTypes=CN;exports.cleanupIncompleteMessages=ZG;exports.cleanupKpiMetricComparisonMode=Gre;exports.cloneDeep=Cf;exports.cloneLinkedFrameWithSourceMapping=pLe;exports.closestCenter=s0;exports.cn=Z;exports.colors=Zn;exports.createAlert=Oq;exports.createCardsFromSlots=YQ;exports.createChartConfig=qD;exports.createEmptyKpiConfig=rge;exports.createExport=Rq;exports.createLucideIcon=Ae;exports.createSlot=ay;exports.createSqlGenConfig=VM;exports.de=xse;exports.dedup=lnt;exports.deleteAlert=$q;exports.downloadPdf=VK;exports.emitDashboardLoad=uie;exports.emitDashboardUnload=die;exports.endOfDayInTimezone=Gs;exports.fieldAlreadyExists=kq;exports.findCustomVisualConfigCard=QR;exports.fmt=Hx;exports.formatDisplayFormula=trt;exports.formatFileSize=eje;exports.getAlert=Pq;exports.getAlertContextSources=oje;exports.getAlertHistory=Vq;exports.getAlertQuotaUsage=Gq;exports.getAlertRunDeliveries=Uq;exports.getAlertRunSteps=sje;exports.getAlertRuns=Bq;exports.getAlertState=zq;exports.getAutoDetectedChartIcon=oJ;exports.getCacheConfig=IS;exports.getCanvasBackgroundColor=aa;exports.getChartGridStyle=Sge;exports.getChartIconByType=rP;exports.getColorForValue=o_;exports.getColumnDataType=Qie;exports.getConfigSlotExpectedType=$$e;exports.getContrastColor=vo;exports.getCustomVisualInputCards=XR;exports.getDataType=Nr;exports.getDateFormatOptionsForGranularity=Mee;exports.getDefaultAxisConfig=a_;exports.getDefaultChartColors=th;exports.getDefaultDataLabelsConfig=Ny;exports.getDefaultFilterSql=HX;exports.getDefaultLegendConfig=TD;exports.getDisplayName=Ore;exports.getDownloadUrl=ZNe;exports.getEffectiveCardTypeForSlot=am;exports.getEntityDetails=mnt;exports.getEntityIcon=SS;exports.getErrorMessage=Are;exports.getExportStatus=KNe;exports.getExports=GNe;exports.getFieldIconComponent=sp;exports.getFilterCount=Q1;exports.getFilterValueType=Fo;exports.getFormattedTableNameForQuery=Pw;exports.getKeys=Xn;exports.getMetricDisplayLabel=LNe;exports.getNewField=Tq;exports.getObjectDiff=Y9;exports.getQualifiedTableName=UM;exports.getRoleBasedDisplayOverrides=qJ;exports.getSelectedDateFilterColumn=VX;exports.getSlotDefinitionForIndex=KR;exports.getSlotExpectedChartType=yN;exports.getSlotIndexForCard=jb;exports.getSql=BM;exports.getTokenParams=KM;exports.handleAggregationChange=UT;exports.handleAggregationLabelChange=HJ;exports.hasValidCardConfig=cl;exports.horizontalListSortingStrategy=_P;exports.hslStringToHex=Cge;exports.interpretAlertContext=Wq;exports.invalidateToken=Uae;exports.isBooleanDataType=zM;exports.isCalculatedDimension=ky;exports.isCalculatedField=C1;exports.isCalculatedFilterField=ese;exports.isCalculatedMetric=Ec;exports.isCardSummaryVisibleOnCard=hP;exports.isColumnInSqlGen=Jie;exports.isCustomVisualConfigCard=RT;exports.isDateDataType=ha;exports.isDefaultColor=dge;exports.isDevEnv=OM;exports.isExportComplete=JNe;exports.isExportInProgress=QNe;exports.isInAiScopeArray=ant;exports.isNumberDataType=fa;exports.isObjectEmpty=Lae;exports.isTextDataType=ty;exports.lastAssistantMessageIsCompleteWithToolCalls=Tre;exports.listAlertQuotas=Yq;exports.listAlerts=ZD;exports.merge=Em;exports.mergeAxisConfig=l_;exports.normalizeMultiInputPayload=JR;exports.pivotData=wy;exports.postRequest=k9;exports.postRequestRegular=ls;exports.prepareFeedbackData=GN;exports.previewAlertDeliverable=qq;exports.reindexSlotCards=F$e;exports.remarkGfm=gne;exports.removeFromScopeArray=cnt;exports.removeRing=Wc;exports.resolveDataType=HM;exports.resolveDatamodelName=g9;exports.resolveMultiInputType=Qy;exports.resolveMultiInputTypeFromVisual=GQ;exports.sanitizeAIScope=Dre;exports.setupEditorWithCard=YA;exports.showJoinRequiredNotification=jq;exports.sortByColumnsToSortState=CZ;exports.sortStateToSortByColumns=NZ;exports.sortableKeyboardCoordinates=MP;exports.startOfDayInTimezone=Ys;exports.titleCase=Wx;exports.toTitleCase=ui;exports.triggerAlertNow=Lq;exports.ue=We;exports.updateAlert=Fq;exports.updateAlertContextSources=ije;exports.updateAlertQuota=Kq;exports.useAIActions=YC;exports.useAIInteractionStore=_c;exports.useActiveExports=qNe;exports.useActiveToolStatus=Ure;exports.useAddNewFrame=Iq;exports.useAlertActions=XD;exports.useAlertBacktest=eY;exports.useAlertContextBuilder=Jq;exports.useAlertDeliveries=gje;exports.useAlertDetail=fje;exports.useAlertDraft=uje;exports.useAlertFilters=Xq;exports.useAlertHistory=pje;exports.useAlertQuotas=xje;exports.useAlertRuns=mje;exports.useAlertState=hje;exports.useAlertStore=td;exports.useAlerts=JD;exports.useAlertsBootstrap=Qq;exports.useAlertsById=lje;exports.useAlertsForCard=QD;exports.useAssignFilter=tse;exports.useAssistantContainer=KG;exports.useAssistantLayoutStore=hf;exports.useAssistantPanel=YG;exports.useAssistantProfile=Rre;exports.useAutoScroll=Bre;exports.useAutoSubmitQueue=zre;exports.useCallbackRef=os;exports.useCard=UNe;exports.useCardAlertMap=cje;exports.useCardFilterValues=pC;exports.useCardSummary=mP;exports.useChat=Ire;exports.useColumns=YD;exports.useCreateVisualWithFrame=Ime;exports.useCurrentAIContext=zp;exports.useCurrentActiveCard=C9;exports.useCurrentCardConfig=Fae;exports.useCurrentSheetActiveCards=N9;exports.useCurrentUserInfo=so;exports.useCustomVisual=ih;exports.useCustomVisualsQuery=vP;exports.useDashboardActions=un;exports.useDashboardById=AV;exports.useDashboardCardQuery=ul;exports.useDashboardCreation=OV;exports.useDashboardManagement=PV;exports.useDashboardPreferences=yp;exports.useDashboardQuery=RS;exports.useDashboardStore=Q;exports.useDashboardSummary=zJ;exports.useDataColumns=Mq;exports.useDateFilterHook=JFe;exports.useDebounce=sm;exports.useDefaultDashboardMutation=fV;exports.useDisplayPreferences=Zu;exports.useDroppable=Cee;exports.useEditorActions=br;exports.useEditorAside=JN;exports.useEditorStore=$e;exports.useEnsureReactGlobals=xX;exports.useExportActions=Aq;exports.useExportStore=DC;exports.useFieldManagement=Kre;exports.useFileActions=SA;exports.useFileAttachments=wA;exports.useFullscreenAssistant=GG;exports.useGroupMembers=v2e;exports.useGroups=hA;exports.useHasDashboardId=QG;exports.useInProgressExportsCount=YNe;exports.useInteractionStore=Qt;exports.useIsDashboardSelected=Ele;exports.useIsVisualSelected=_le;exports.useJoinabilityMap=vO;exports.useLayoutEffect2=cs;exports.useManagementActions=up;exports.useManagementStore=as;exports.useMessageWindow=Vre;exports.useMutation=Zr;exports.usePivotTableConfig=Vp;exports.usePluginQuery=eee;exports.usePromoteCalculatedMetricToDomain=ose;exports.useQuery=en;exports.useQueryClient=us;exports.useQueueActions=Bp;exports.useResourceManagement=sC;exports.useResourceUpdateState=RV;exports.useScopedFields=yO;exports.useSelectedAlertId=Zq;exports.useSelectedVisual=kle;exports.useSemaphorContext=tt;exports.useSensor=op;exports.useSensors=IN;exports.useSortable=c0;exports.useStarredChartsStore=vse;exports.useSyncLegacyEditorState=lse;exports.useTextFilterHook=c5e;exports.useTheme=cp;exports.useTopoJson=wq;exports.useUnifiedUsers=fA;exports.useUpdateResource=TV;exports.useUpdateVisualMutation=Dme;exports.useUserPreferences=oU;exports.useVisualById=rC;exports.useVisualManagement=Mme;exports.v4=gr;exports.validateFieldForChartType=Yre;exports.verticalListSortingStrategy=TP;
|
|
1098
|
+
`},_8=Mst(Rst)(dse),Pst={config:Dst},Ost=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(s){return n.reduceRight(function(o,i){return i(o)},s)}};function fse(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],fse(e[n],t[n]))}),j8(j8({},e),t)}var Fst={type:"cancelation",msg:"operation is manually canceled"};function aE(e){var t=!1,n=new Promise(function(r,s){e.then(function(o){return t?s(Fst):r(o)}),e.catch(s)});return n.cancel=function(){return t=!0},n}var $st=["monaco"],Lst=_st.create({config:Tst,isInitialized:!1,resolve:null,reject:null,monaco:null}),hse=ust(Lst,2),x0=hse[0],tj=hse[1];function zst(e){var t=Pst.config(e),n=t.monaco,r=lst(t,$st);tj(function(s){return{config:fse(s.config,r),monaco:n}})}function Bst(){var e=x0(function(t){var n=t.monaco,r=t.isInitialized,s=t.resolve;return{monaco:n,isInitialized:r,resolve:s}});if(!e.isInitialized){if(tj({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),aE(lE);if(window.monaco&&window.monaco.editor)return mse(window.monaco),e.resolve(window.monaco),aE(lE);Ost(Vst,Hst)(Wst)}return aE(lE)}function Vst(e){return document.body.appendChild(e)}function Ust(e){var t=document.createElement("script");return e&&(t.src=e),t}function Hst(e){var t=x0(function(r){var s=r.config,o=r.reject;return{config:s,reject:o}}),n=Ust("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function Wst(){var e=x0(function(n){var r=n.config,s=n.resolve,o=n.reject;return{config:r,resolve:s,reject:o}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){var r=n.m||n;mse(r),e.resolve(r)},function(n){e.reject(n)})}function mse(e){x0().monaco||tj({monaco:e})}function qst(){return x0(function(e){var t=e.monaco;return t})}var lE=new Promise(function(e,t){return tj({resolve:e,reject:t})}),jS={config:zst,init:Bst,__getMonacoInstance:qst},Yst={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},cE=Yst,Gst={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Kst=Gst;function Zst({children:e}){return w.createElement("div",{style:Kst.container},e)}var Xst=Zst,Qst=Xst;function Jst({width:e,height:t,isEditorReady:n,loading:r,_ref:s,className:o,wrapperProps:i}){return w.createElement("section",{style:{...cE.wrapper,width:e,height:t},...i},!n&&w.createElement(Qst,null,r),w.createElement("div",{ref:s,style:{...cE.fullWidth,...!n&&cE.hide},className:o}))}var eot=Jst,pse=w.memo(eot);function tot(e){w.useEffect(e,[])}var CO=tot;function not(e,t,n=!0){let r=w.useRef(!0);w.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var si=not;function Fx(){}function qh(e,t,n,r){return rot(e,r)||sot(e,t,n,r)}function rot(e,t){return e.editor.getModel(gse(e,t))}function sot(e,t,n,r){return e.editor.createModel(t,n,r?gse(e,r):void 0)}function gse(e,t){return e.Uri.parse(t)}function oot({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:s,originalModelPath:o,modifiedModelPath:i,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:c=!1,theme:u="light",loading:d="Loading...",options:f={},height:h="100%",width:m="100%",className:p,wrapperProps:g={},beforeMount:x=Fx,onMount:b=Fx}){let[y,v]=w.useState(!1),[S,C]=w.useState(!0),N=w.useRef(null),k=w.useRef(null),E=w.useRef(null),M=w.useRef(b),j=w.useRef(x),_=w.useRef(!1);CO(()=>{let R=jS.init();return R.then($=>(k.current=$)&&C(!1)).catch($=>($==null?void 0:$.type)!=="cancelation"&&console.error("Monaco initialization: error:",$)),()=>N.current?F():R.cancel()}),si(()=>{if(N.current&&k.current){let R=N.current.getOriginalEditor(),$=qh(k.current,e||"",r||n||"text",o||"");$!==R.getModel()&&R.setModel($)}},[o],y),si(()=>{if(N.current&&k.current){let R=N.current.getModifiedEditor(),$=qh(k.current,t||"",s||n||"text",i||"");$!==R.getModel()&&R.setModel($)}},[i],y),si(()=>{let R=N.current.getModifiedEditor();R.getOption(k.current.editor.EditorOption.readOnly)?R.setValue(t||""):t!==R.getValue()&&(R.executeEdits("",[{range:R.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),R.pushUndoStop())},[t],y),si(()=>{var R,$;($=(R=N.current)==null?void 0:R.getModel())==null||$.original.setValue(e||"")},[e],y),si(()=>{let{original:R,modified:$}=N.current.getModel();k.current.editor.setModelLanguage(R,r||n||"text"),k.current.editor.setModelLanguage($,s||n||"text")},[n,r,s],y),si(()=>{var R;(R=k.current)==null||R.editor.setTheme(u)},[u],y),si(()=>{var R;(R=N.current)==null||R.updateOptions(f)},[f],y);let T=w.useCallback(()=>{var q;if(!k.current)return;j.current(k.current);let R=qh(k.current,e||"",r||n||"text",o||""),$=qh(k.current,t||"",s||n||"text",i||"");(q=N.current)==null||q.setModel({original:R,modified:$})},[n,t,s,e,r,o,i]),P=w.useCallback(()=>{var R;!_.current&&E.current&&(N.current=k.current.editor.createDiffEditor(E.current,{automaticLayout:!0,...f}),T(),(R=k.current)==null||R.editor.setTheme(u),v(!0),_.current=!0)},[f,u,T]);w.useEffect(()=>{y&&M.current(N.current,k.current)},[y]),w.useEffect(()=>{!S&&!y&&P()},[S,y,P]);function F(){var $,q,U,W;let R=($=N.current)==null?void 0:$.getModel();a||((q=R==null?void 0:R.original)==null||q.dispose()),c||((U=R==null?void 0:R.modified)==null||U.dispose()),(W=N.current)==null||W.dispose()}return w.createElement(pse,{width:m,height:h,isEditorReady:y,loading:d,_ref:E,className:p,wrapperProps:g})}var iot=oot;w.memo(iot);function aot(){let[e,t]=w.useState(jS.__getMonacoInstance());return CO(()=>{let n;return e||(n=jS.init(),n.then(r=>{t(r)})),()=>n==null?void 0:n.cancel()}),e}var lot=aot;function cot(e){let t=w.useRef();return w.useEffect(()=>{t.current=e},[e]),t.current}var uot=cot,tw=new Map;function dot({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:s,path:o,theme:i="light",line:a,loading:c="Loading...",options:u={},overrideServices:d={},saveViewState:f=!0,keepCurrentModel:h=!1,width:m="100%",height:p="100%",className:g,wrapperProps:x={},beforeMount:b=Fx,onMount:y=Fx,onChange:v,onValidate:S=Fx}){let[C,N]=w.useState(!1),[k,E]=w.useState(!0),M=w.useRef(null),j=w.useRef(null),_=w.useRef(null),T=w.useRef(y),P=w.useRef(b),F=w.useRef(),R=w.useRef(r),$=uot(o),q=w.useRef(!1),U=w.useRef(!1);CO(()=>{let L=jS.init();return L.then(O=>(M.current=O)&&E(!1)).catch(O=>(O==null?void 0:O.type)!=="cancelation"&&console.error("Monaco initialization: error:",O)),()=>j.current?A():L.cancel()}),si(()=>{var O,I,V,Y;let L=qh(M.current,e||r||"",t||s||"",o||n||"");L!==((O=j.current)==null?void 0:O.getModel())&&(f&&tw.set($,(I=j.current)==null?void 0:I.saveViewState()),(V=j.current)==null||V.setModel(L),f&&((Y=j.current)==null||Y.restoreViewState(tw.get(o))))},[o],C),si(()=>{var L;(L=j.current)==null||L.updateOptions(u)},[u],C),si(()=>{!j.current||r===void 0||(j.current.getOption(M.current.editor.EditorOption.readOnly)?j.current.setValue(r):r!==j.current.getValue()&&(U.current=!0,j.current.executeEdits("",[{range:j.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),j.current.pushUndoStop(),U.current=!1))},[r],C),si(()=>{var O,I;let L=(O=j.current)==null?void 0:O.getModel();L&&s&&((I=M.current)==null||I.editor.setModelLanguage(L,s))},[s],C),si(()=>{var L;a!==void 0&&((L=j.current)==null||L.revealLine(a))},[a],C),si(()=>{var L;(L=M.current)==null||L.editor.setTheme(i)},[i],C);let W=w.useCallback(()=>{var L;if(!(!_.current||!M.current)&&!q.current){P.current(M.current);let O=o||n,I=qh(M.current,r||e||"",t||s||"",O||"");j.current=(L=M.current)==null?void 0:L.editor.create(_.current,{model:I,automaticLayout:!0,...u},d),f&&j.current.restoreViewState(tw.get(O)),M.current.editor.setTheme(i),a!==void 0&&j.current.revealLine(a),N(!0),q.current=!0}},[e,t,n,r,s,o,u,d,f,i,a]);w.useEffect(()=>{C&&T.current(j.current,M.current)},[C]),w.useEffect(()=>{!k&&!C&&W()},[k,C,W]),R.current=r,w.useEffect(()=>{var L,O;C&&v&&((L=F.current)==null||L.dispose(),F.current=(O=j.current)==null?void 0:O.onDidChangeModelContent(I=>{U.current||v(j.current.getValue(),I)}))},[C,v]),w.useEffect(()=>{if(C){let L=M.current.editor.onDidChangeMarkers(O=>{var V;let I=(V=j.current.getModel())==null?void 0:V.uri;if(I&&O.find(Y=>Y.path===I.path)){let Y=M.current.editor.getModelMarkers({resource:I});S==null||S(Y)}});return()=>{L==null||L.dispose()}}return()=>{}},[C,S]);function A(){var L,O;(L=F.current)==null||L.dispose(),h?f&&tw.set(o,j.current.saveViewState()):(O=j.current.getModel())==null||O.dispose(),j.current.dispose()}return w.createElement(pse,{width:m,height:p,isEditorReady:C,loading:c,_ref:_,className:g,wrapperProps:x})}var fot=dot,xse=w.memo(fot),hot=xse;const bse=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),mot=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),pot=Array.from(bse).join(", "),got=3,xot="Self-heal",bot=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function yot({card:e}){var U,W,A,L,O,I,V;const[t,n]=w.useState({}),{authToken:r}=tt(),{theme:s}=cp(),o=KM(r==null?void 0:r.accessToken),i=Q(Y=>Y.themeStyle),a={mode:s||"system",colors:((W=(U=i==null?void 0:i.chart)==null?void 0:U.dataset)==null?void 0:W.backgroundColor)||[]},c=$e(Y=>Y.frame),u=e,{getCard:d,manifest:f}=ih(((A=u.customCardPreferences)==null?void 0:A.url)||""),h=(L=f==null?void 0:f.visuals)==null?void 0:L.find(Y=>{var G;return Y.name===((G=u.customCardPreferences)==null?void 0:G.componentName)}),m=Qy(u,h)??"single",p=w.useMemo(()=>XR({frame:c,configCard:u,isMultiInputVisual:m==="multiple"}),[c,u,m]),g=w.useMemo(()=>{const Y=p.findIndex(G=>(G==null?void 0:G.id)===e.id);return Y<0?-1:jb(e,Y)},[p,e]),x=w.useMemo(()=>m!=="multiple"||g<0?e.type:am(e,g,h==null?void 0:h.slots)??e.type,[m,g,e,h==null?void 0:h.slots]),b=w.useMemo(()=>m==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:x!==e.type?{...e,type:x}:e,[e,x,m]),{data:y}=ul(b),v=Qt(Y=>Y.interactionStates),S=Q(Y=>{var G;return(G=Y.dashboard)==null?void 0:G.id}),C=Q(Y=>Y.dashboard.filters),N=Q(Y=>Y.filterValues),k=Q(Y=>Y.selectedSheetId),E=Q(Y=>Y.inlineFilterValuesMap[e.id]),M=w.useMemo(()=>GR({card:e,sheetId:k||"",inlineFilterValues:E}),[e,k,E]),{cardFilters:j,cardFilterValues:_}=w.useMemo(()=>gC({card:e,interactionStates:v,currentDashboardId:S,filters:C,filterValues:N,selectedSheetId:k}),[e,v,S,C,N,k]),T=w.useCallback((Y,G)=>{const z=JR(G);n(B=>({...B,[Y]:z}))},[]),P=(O=u.customCardPreferences)==null?void 0:O.componentName,F=P?d(P):null,R=H1((I=u.customCardPreferences)==null?void 0:I.settings,u),$=w.useMemo(()=>ZR(p),[p]),q=w.useMemo(()=>$.map((Y,G)=>am(Y,G,h==null?void 0:h.slots)),[$,h==null?void 0:h.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(w.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[F&&m==="single"&&l.jsx(F,{editing:!0,params:o,theme:a,settings:R,cardMetadata:ZQ({card:e,dataMetadata:y==null?void 0:y.metadata}),onDataChange:T,data:(y==null?void 0:y.records)||[],filters:j,filterValues:[..._||[],...E||[]],inlineFilters:M}),F&&m==="multiple"&&l.jsxs(l.Fragment,{children:[p.map((Y,G)=>{if(!Y)return null;const z=jb(Y,G),B=am(Y,z,h==null?void 0:h.slots);return l.jsx(kR,{onDataChange:T,card:Y,effectiveCardType:B},`${Y.id}-${z}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(F,{editing:!0,onDataChange:T,...eP({configCard:u,slotOrderedCards:$,slotTypes:q,multiInputData:t,params:o,theme:a,chartSettings:R,filters:j,filterValues:[..._||[],...E||[]],inlineFilters:M})})})]})]},(V=u.customCardPreferences)==null?void 0:V.componentName)}):null}const vot=w.memo(yot,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)});function wot(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return`hsl(${Math.abs(t%360)}, 65%, 45%)`}function Sot(e){const t=e.trim().split(/\s+/);return t.length>1?(t[0][0]+t[1][0]).toUpperCase():e.slice(0,2).toUpperCase()}function yse({chartType:e,chartName:t,isCustom:n=!1,className:r="h-6 w-6"}){if(!n&&e)return rP(e,r);const s=oJ(t);if(s)return w.cloneElement(s,{className:r});const o=Sot(t),i=wot(t);return l.jsx("div",{className:Z("flex items-center justify-center rounded text-white font-semibold text-xs",r),style:{backgroundColor:i},children:o})}const vse=Vi()(e9((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var wse=["PageUp","PageDown"],Sse=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Cse={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ag="Slider",[CM,Cot,Not]=cy(ag),[Nse]=ts(ag,[Not]),[jot,nj]=Nse(ag),jse=D.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:p,...g}=e,x=D.useRef(new Set),b=D.useRef(0),v=i==="horizontal"?kot:Eot,[S=[],C]=Cs({prop:d,defaultProp:u,onChange:_=>{var P;(P=[...x.current][b.current])==null||P.focus(),f(_)}}),N=D.useRef(S);function k(_){const T=Dot(S,_);j(_,T)}function E(_){j(_,b.current)}function M(){const _=N.current[b.current];S[b.current]!==_&&h(S)}function j(_,T,{commit:P}={commit:!1}){const F=Oot(o),R=Fot(Math.round((_-r)/o)*o+r,F),$=gb(R,[r,s]);C((q=[])=>{const U=Mot(q,$,T);if(Pot(U,c*o)){b.current=U.indexOf($);const W=String(U)!==String(q);return W&&P&&h(U),W?U:q}else return q})}return l.jsx(jot,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:b,thumbs:x.current,values:S,orientation:i,form:p,children:l.jsx(CM.Provider,{scope:e.__scopeSlider,children:l.jsx(CM.Slot,{scope:e.__scopeSlider,children:l.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:t,onPointerDown:Ue(g.onPointerDown,()=>{a||(N.current=S)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:k,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:M,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,S.length-1,{commit:!0}),onStepKeyDown:({event:_,direction:T})=>{if(!a){const R=wse.includes(_.key)||_.shiftKey&&Sse.includes(_.key)?10:1,$=b.current,q=S[$],U=o*R*T;j(q+U,$,{commit:!0})}}})})})})});jse.displayName=ag;var[kse,Ese]=Nse(ag,{startEdge:"left",endEdge:"right",size:"width",direction:1}),kot=D.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=D.useState(null),m=jt(t,v=>h(v)),p=D.useRef(void 0),g=zu(s),x=g==="ltr",b=x&&!o||!x&&o;function y(v){const S=p.current||f.getBoundingClientRect(),C=[0,S.width],k=NO(C,b?[n,r]:[r,n]);return p.current=S,k(v-S.left)}return l.jsx(kse,{scope:e.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:l.jsx(_se,{dir:g,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const S=y(v.clientX);i==null||i(S)},onSlideMove:v=>{const S=y(v.clientX);a==null||a(S)},onSlideEnd:()=>{p.current=void 0,c==null||c()},onStepKeyDown:v=>{const C=Cse[b?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:C?-1:1})}})})}),Eot=D.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=D.useRef(null),f=jt(t,d),h=D.useRef(void 0),m=!s;function p(g){const x=h.current||d.current.getBoundingClientRect(),b=[0,x.height],v=NO(b,m?[r,n]:[n,r]);return h.current=x,v(g-x.top)}return l.jsx(kse,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:l.jsx(_se,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const x=p(g.clientY);o==null||o(x)},onSlideMove:g=>{const x=p(g.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=Cse[m?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:b?-1:1})}})})}),_se=D.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=nj(ag,n);return l.jsx(at.span,{...u,ref:t,onKeyDown:Ue(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):wse.concat(Sse).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:Ue(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:Ue(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:Ue(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),Tse="SliderTrack",Mse=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=nj(Tse,n);return l.jsx(at.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});Mse.displayName=Tse;var NM="SliderRange",Ise=D.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=nj(NM,n),o=Ese(NM,n),i=D.useRef(null),a=jt(t,i),c=s.values.length,u=s.values.map(h=>Rse(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(at.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Ise.displayName=NM;var jM="SliderThumb",Dse=D.forwardRef((e,t)=>{const n=Cot(e.__scopeSlider),[r,s]=D.useState(null),o=jt(t,a=>s(a)),i=D.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(_ot,{...e,ref:o,index:i})}),_ot=D.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=nj(jM,n),a=Ese(jM,n),[c,u]=D.useState(null),d=jt(t,y=>u(y)),f=c?i.form||!!c.closest("form"):!0,h=dy(c),m=i.values[r],p=m===void 0?0:Rse(m,i.min,i.max),g=Iot(r,i.values.length),x=h==null?void 0:h[a.size],b=x?Aot(x,p,a.direction):0;return D.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${p}% + ${b}px)`},children:[l.jsx(CM.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(at.span,{role:"slider","aria-label":e["aria-label"]||g,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:Ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(Ase,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});Dse.displayName=jM;var Tot="RadioBubbleInput",Ase=D.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=D.useRef(null),o=jt(s,r),i=vy(t);return D.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(at.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});Ase.displayName=Tot;function Mot(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Rse(e,t,n){const o=100/(n-t)*(e-t);return gb(o,[0,100])}function Iot(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Dot(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function Aot(e,t,n){const r=e/2,o=NO([0,50],[0,r]);return(r-o(t)*n)*n}function Rot(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Pot(e,t){if(t>0){const n=Rot(e);return Math.min(...n)>=t}return!0}function NO(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Oot(e){return(String(e).split(".")[1]||"").length}function Fot(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Pse=jse,$ot=Mse,Lot=Ise,zot=Dse;const Ose=D.forwardRef(({className:e,...t},n)=>l.jsxs(Pse,{ref:n,className:Z("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx($ot,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(Lot,{className:"absolute h-full bg-primary"})}),l.jsx(zot,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Ose.displayName=Pse.displayName;const Bot={table:Zh,bar:PS,line:sy,stackedBar:sI,stackedLine:sJ,scatter:aI,bubble:rJ,pie:iI,doughnut:dI,kpi:nP,treemap:wN,bullet:SN,funnel:tP,tornado:SI,heatmap:LS,range:oI,radar:x7,polarArea:nJ,text:n7,map:g7},Fse=[{id:"table",icon:Zh,label:"Table"},{id:"bar",icon:PS,label:"Bar Chart"},{id:"line",icon:sy,label:"Line Chart"},{id:"stackedBar",icon:sI,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:iI,label:"Pie Chart"},{id:"doughnut",icon:dI,label:"Donut Chart"},{id:"kpi",icon:nP,label:"KPI"},{id:"treemap",icon:wN,label:"Treemap"},{id:"bullet",icon:SN,label:"Bullet Chart"},{id:"funnel",icon:tP,label:"Funnel Chart"},{id:"tornado",icon:SI,label:"Tornado Chart"},{id:"heatmap",icon:LS,label:"Heatmap"},{id:"range",icon:oI,label:"Range Chart"}],Vot=14;Fse.map(e=>e.id);function Uot({selectedChart:e,onChartChange:t,isDropdownExpanded:n,onToggleDropdown:r}){var S,C;const s=$e(N=>N.card),{setCardType:o,setCardPreferences:i}=$e(N=>N.actions),{setCardCustomCfg:a,setCustomCardPreferences:c,setQueryConfig:u,replaceFrameCards:d,clearModeDrafts:f,initializeModeDrafts:h}=br(),m=((S=s==null?void 0:s.config)==null?void 0:S.pivotByColumns)&&s.config.pivotByColumns.length>0,{starredCharts:p,isStarred:g}=vse(),{data:x=[]}=vP(),b=w.useMemo(()=>{const N=Fse.filter(_=>!(_.requiresPivot&&!m)),k=p.filter(_=>_.type==="default"?!0:x.some(T=>T.name===_.id)),E=new Set(k.map(_=>_.id)),M=N.filter(_=>!E.has(_.id));return[...k.map(_=>({id:_.id,label:_.name,icon:_.type==="default"?Bot[_.id]:void 0,isCustom:_.type==="custom",isStarred:!0,url:_.url})),...M.map(_=>({id:_.id,label:_.label,icon:_.icon,isCustom:!1,isStarred:!1}))].slice(0,Vot-1)},[p,x,m]),y=N=>{if(N.isCustom){const k=x.find(E=>E.name===N.id);if(k){a(null),i({}),u(void 0);const E=GQ(k);if(E==="multiple"&&k.slots&&k.slots.length>0){f();const j=YQ(k.slots,k,s);d(j),j[0]&&h(j[0]);return}o("custom"),c({type:"component",visualType:E,url:k.url,componentName:k.name,icon:k.icon,pluginChartType:k.chartType,minInputs:k.minInputs,maxInputs:k.maxInputs}),t("custom")}}else t(N.id)},v=e==="custom"&&((C=s==null?void 0:s.customCardPreferences)==null?void 0:C.componentName);return l.jsxs("div",{className:"grid grid-cols-7 gap-1.5",children:[b.map(N=>{var M;const k=N.icon,E=N.isCustom?v&&((M=s==null?void 0:s.customCardPreferences)==null?void 0:M.componentName)===N.id:e===N.id;return l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsxs(te,{variant:"ghost",size:"sm",onClick:()=>y(N),className:Z("h-8 w-8 rounded-md p-0 text-foreground/65 transition-colors hover:bg-muted/70 hover:text-foreground",E&&"bg-accent text-foreground shadow-sm ring-1 ring-border/80"),children:[k?l.jsx(k,{className:"h-4 w-4"}):l.jsx(yse,{chartName:N.label,isCustom:!0,className:"h-4 w-4"}),l.jsx("span",{className:"sr-only",children:N.label})]})}),l.jsxs(Mn,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[l.jsx("p",{children:N.label}),l.jsx(Am,{className:"fill-foreground"})]})]},`${N.isCustom?"custom":"default"}-${N.id}`)}),r&&l.jsxs(jn,{children:[l.jsx(kn,{asChild:!0,children:l.jsx(te,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 rounded-md p-0 text-foreground/65 transition-colors hover:bg-muted/70 hover:text-foreground","aria-label":n?"Hide all charts":"Show all charts",children:n?l.jsx(af,{className:"h-4 w-4"}):l.jsx(dr,{className:"h-4 w-4"})})}),l.jsxs(Mn,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[l.jsx("p",{children:n?"Hide dropdown":"Show all charts"}),l.jsx(Am,{className:"fill-foreground"})]})]})]})}const $se=D.forwardRef(({className:e,icon:t,tooltip:n,...r},s)=>{const o=l.jsx(u0,{className:Z("peer inline-flex h-8 w-12 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...r,ref:s,children:l.jsx(IP,{className:Z("pointer-events-none block h-7 w-7 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),children:t&&l.jsx("span",{className:"flex h-full items-center justify-center text-primary",children:t})})});return n?l.jsx(nr,{children:l.jsxs(jn,{delayDuration:0,children:[l.jsx(kn,{asChild:!0,children:l.jsx("span",{className:"inline-flex",children:o})}),l.jsxs(Mn,{side:"bottom",className:"border-0 bg-foreground text-background shadow-md",children:[l.jsx(Am,{className:"fill-foreground"}),l.jsx("p",{children:n})]})]})}):o});$se.displayName="DevModeSwitch";exports.Accordion=_b;exports.AccordionContent=Su;exports.AccordionItem=vu;exports.AccordionTrigger=wu;exports.AggregateTable=uN;exports.Alert=aN;exports.AlertCreationDialog=cP;exports.AlertDescription=lN;exports.AlertDialog=eh;exports.AlertDialogAction=Gu;exports.AlertDialogCancel=Ku;exports.AlertDialogContent=Uu;exports.AlertDialogDescription=Yu;exports.AlertDialogFooter=Wu;exports.AlertDialogHeader=Hu;exports.AlertDialogTitle=qu;exports.AlertManagementPage=jJ;exports.AlertsApiError=KD;exports.ArrowDown=qa;exports.ArrowRight=e7;exports.ArrowUp=Ei;exports.ArrowUpDown=qc;exports.AssistantContextEntityControls=SM;exports.AssistantStatus=Cne;exports.AxisConfigurator=jp;exports.Badge=st;exports.Bell=Gh;exports.BulletChartIcon=SN;exports.Button=te;exports.CALCULATED_FIELDS_GROUP_NAME=km;exports.CALCULATED_FIELD_ENTITY_MARKER=Sc;exports.COMPARISON_SUPPORTED_CHART_TYPES=i9;exports.CSS=zi;exports.CalculatedFieldEditor=sse;exports.Calculator=rI;exports.Calendar=ps;exports.Card=Vo;exports.CardAlertIndicator=GJ;exports.CardContent=Pi;exports.CardHeader=Ri;exports.CardSummary=HT;exports.CardTitle=ma;exports.CaretSortIcon=y8e;exports.ChartArea=VE;exports.ChartColumn=OS;exports.ChartColumnIncreasing=PS;exports.ChartIcon=yse;exports.ChartJsVisual=Uy;exports.ChartLine=sy;exports.ChartQuickSelector=Uot;exports.ChartScatter=aI;exports.ChatInputWithContext=gO;exports.Check=Ur;exports.CheckIcon=QJ;exports.Checkbox=yn;exports.ChevronDown=dr;exports.ChevronLeft=FS;exports.ChevronRight=bs;exports.ChevronUp=af;exports.ChevronsUpDown=lI;exports.Circle=uI;exports.CircleAlert=xc;exports.CircleCheck=cI;exports.CircleHelp=l7;exports.Clock=ju;exports.Code=c7;exports.CodeHighlighter=Cu;exports.CodeXml=HE;exports.Collapsible=Qs;exports.CollapsibleContent=eo;exports.CollapsibleTrigger=Js;exports.Command=Rp;exports.CommandEmpty=Op;exports.CommandGroup=Fp;exports.CommandInput=Oy;exports.CommandItem=$p;exports.CommandList=Pp;exports.CommandSeparator=NY;exports.ComparisonMetadataBadge=yZ;exports.Container=CA;exports.Copy=_m;exports.CopyButton=rp;exports.CopyPlus=u7;exports.CreateDashboardDialog=sU;exports.Cross2Icon=JJ;exports.CustomFilterPopover=wP;exports.CustomScrollArea=wl;exports.DATE_FORMAT_VALUES=DNe;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=bq;exports.Dashboard=qre;exports.DashboardActionsMenu=dV;exports.DashboardCard=KJ;exports.DashboardExportDialog=Oee;exports.DashboardPlus=Brt;exports.DashboardWC=rst;exports.DataSourceDialog=pO;exports.Database=Ja;exports.DateRangePicker=DR;exports.DefaultChatTransport=mO;exports.DevModeSwitch=$se;exports.Dialog=Wr;exports.DialogContent=Rr;exports.DialogDescription=Xr;exports.DialogFooter=Ns;exports.DialogHeader=Pr;exports.DialogTitle=Or;exports.DialogTrigger=Kme;exports.DisplayPreferencesProvider=bP;exports.DndContext=a0;exports.Download=Yf;exports.DownloadPdf=Fee;exports.DragOverlay=Nee;exports.DropdownMenu=Qf;exports.DropdownMenuCheckboxItem=fx;exports.DropdownMenuContent=Vu;exports.DropdownMenuItem=$o;exports.DropdownMenuLabel=Jh;exports.DropdownMenuRadioGroup=She;exports.DropdownMenuRadioItem=cV;exports.DropdownMenuSeparator=jf;exports.DropdownMenuSub=lV;exports.DropdownMenuSubContent=qI;exports.DropdownMenuSubTrigger=WI;exports.DropdownMenuTrigger=Jf;exports.EMPTY_DATA_SOURCE=KN;exports.Editable=K1;exports.EditableText=Ai;exports.EditorCustomVisual=vot;exports.EllipsisVertical=dp;exports.EmailScheduleDialog=aJ;exports.ErrorBoundary=ya;exports.ExportError=Ip;exports.ExternalLink=Kx;exports.Eye=ku;exports.EyeOff=$S;exports.Fallback=vN;exports.FallbackVisual=kb;exports.FeedbackCategory=Ou;exports.FeedbackDialog=$b;exports.FieldsList=ise;exports.FieldsSection=ase;exports.FileText=pa;exports.Filter=lc;exports.FilterComponent=Qp;exports.FilterHeader=SP;exports.FilterInfo=VT;exports.Ft=hot;exports.GenIcon=ch;exports.Grid3x3=LS;exports.GripVertical=zS;exports.HEATMAP_PRESET_PALETTES=V_;exports.Hash=h7;exports.House=Zx;exports.HoverCard=vp;exports.HoverCardContent=Sp;exports.HoverCardTrigger=wp;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=bse;exports.INLINE_ALLOWED_TOOL_LIST=pot;exports.INLINE_BLOCKED_MUTATING_TOOLS=mot;exports.IconButton=hu;exports.Info=tr;exports.InfoHover=xP;exports.InlineFilterBar=YJ;exports.Input=sn;exports.Input$1=$n;exports.KPICard=Mb;exports.KeyboardSensor=o0;exports.LOCALE_CURRENCY_PAIRS=qie;exports.Label=de;exports.Layers=BS;exports.Le=lot;exports.Link=m7;exports.List=hI;exports.LoaderCircle=Nn;exports.LoadingDots=Cc;exports.MAX_SELF_HEAL_ATTEMPTS=got;exports.METADATA_KEYS=$M;exports.Markdown=Vte;exports.Maximize2=VS;exports.MessageSquareWarning=mI;exports.Minimize2=pI;exports.MultiInputEmptyRenderer=kR;exports.PYTHON_DEFAULT_CODE=FM;exports.PenLine=YE;exports.Pencil=xI;exports.PendingMessagesDisplay=Lre;exports.PivotMarkerEnum=Sq;exports.PivotTableTanstack=Jy;exports.Placeholders=jne;exports.Play=US;exports.Plus=Ar;exports.PointerSensor=ng;exports.Popover=vs;exports.PopoverContent=Ss;exports.PopoverTrigger=ws;exports.PortalTooltipContent=uP;exports.PrintMessages=Nne;exports.Progress=EN;exports.RECOVERABLE_SQL_ERROR_CODES=bot;exports.RadioGroup=As;exports.RadioGroupItem=Sn;exports.RefreshCcw=b7;exports.RefreshCw=Vw;exports.ResizableHandle=VBe;exports.ResizablePanel=XT;exports.ResizablePanelGroup=ote;exports.ResourceEditDialog=qG;exports.ResourceType=vn;exports.SELF_HEAL_TIMELINE_STEP=xot;exports.ScrollArea=No;exports.ScrollBar=Fi;exports.Search=Uo;exports.SeedQuestions=Pre;exports.Select=bt;exports.SelectContent=gt;exports.SelectGroup=pA;exports.SelectItem=Ee;exports.SelectLabel=UC;exports.SelectTrigger=pt;exports.SelectValue=wt;exports.SemaphorContext=ry;exports.SemaphorContextProvider=nI;exports.SemaphorQueryClient=q9;exports.SemaphorReadyIndicator=bO;exports.Separator=Ds;exports.Settings=fp;exports.Settings2=cc;exports.Share2=Kh;exports.ShareDialog=WG;exports.Skeleton=wo;exports.Slider=Ose;exports.SmallSwitch=cse;exports.SortableContext=l0;exports.Sparkles=iy;exports.Square=y7;exports.SquarePen=HS;exports.Star=vI;exports.SummaryCard=BT;exports.Table2=Zh;exports.TableSkeleton=UJ;exports.TableVisual=Ff;exports.Tabs=Fs;exports.TabsContent=cr;exports.TabsList=js;exports.TabsTrigger=cn;exports.Tag=v7;exports.TbChartTreemap=wN;exports.TextCard=Qm;exports.Textarea=ja;exports.Toggle=e0;exports.Tooltip=jn;exports.TooltipArrow=Am;exports.TooltipContent=Mn;exports.TooltipProvider=nr;exports.TooltipTrigger=kn;exports.Trash2=Sa;exports.TreePalm=CI;exports.TrendingUp=Tm;exports.TriangleAlert=Gf;exports.Type=GE;exports.UXProvider=xO;exports.Undo2=Xx;exports.User=bc;exports.UserPlus=w7;exports.Users=is;exports.X=Vt;exports.areEntitiesJoined=Nq;exports.arrayMove=rg;exports.backtestAlert=Hq;exports.buildFilterFieldMeta=Qre;exports.buildFilterSemanticContext=Jre;exports.buildInlineFilterNodes=GR;exports.buildMultiInputCustomVisualProps=eP;exports.buildSlotOrderedCards=ZR;exports.calculateContextAwareFilters=gC;exports.calculateFieldState=GD;exports.canUserAccessVisuals=i8e;exports.canUserCreateDashboards=o8e;exports.canUserEdit=n8e;exports.canUserManageDashboards=s8e;exports.canUserManageGroups=a8e;exports.canUserUseFilters=r8e;exports.cancelExport=XNe;exports.chartSupportsDataLabels=pW;exports.chartSupportsLegend=hW;exports.chartTypes=CN;exports.cleanupIncompleteMessages=ZG;exports.cleanupKpiMetricComparisonMode=Gre;exports.cloneDeep=Cf;exports.cloneLinkedFrameWithSourceMapping=pLe;exports.closestCenter=s0;exports.cn=Z;exports.colors=Zn;exports.createAlert=Oq;exports.createCardsFromSlots=YQ;exports.createChartConfig=qD;exports.createEmptyKpiConfig=rge;exports.createExport=Rq;exports.createLucideIcon=Ae;exports.createSlot=ay;exports.createSqlGenConfig=VM;exports.de=xse;exports.dedup=lnt;exports.deleteAlert=$q;exports.downloadPdf=VK;exports.emitDashboardLoad=uie;exports.emitDashboardUnload=die;exports.endOfDayInTimezone=Gs;exports.fieldAlreadyExists=kq;exports.findCustomVisualConfigCard=QR;exports.fmt=Hx;exports.formatDisplayFormula=trt;exports.formatFileSize=eje;exports.getAlert=Pq;exports.getAlertContextSources=oje;exports.getAlertHistory=Vq;exports.getAlertQuotaUsage=Gq;exports.getAlertRunDeliveries=Uq;exports.getAlertRunSteps=sje;exports.getAlertRuns=Bq;exports.getAlertState=zq;exports.getAutoDetectedChartIcon=oJ;exports.getCacheConfig=IS;exports.getCanvasBackgroundColor=aa;exports.getChartGridStyle=Sge;exports.getChartIconByType=rP;exports.getColorForValue=o_;exports.getColumnDataType=Qie;exports.getConfigSlotExpectedType=$$e;exports.getContrastColor=vo;exports.getCustomVisualInputCards=XR;exports.getDataType=Nr;exports.getDateFormatOptionsForGranularity=Mee;exports.getDefaultAxisConfig=a_;exports.getDefaultChartColors=th;exports.getDefaultDataLabelsConfig=Ny;exports.getDefaultFilterSql=HX;exports.getDefaultLegendConfig=TD;exports.getDisplayName=Ore;exports.getDownloadUrl=ZNe;exports.getEffectiveCardTypeForSlot=am;exports.getEntityDetails=mnt;exports.getEntityIcon=SS;exports.getErrorMessage=Are;exports.getExportStatus=KNe;exports.getExports=GNe;exports.getFieldIconComponent=sp;exports.getFilterCount=Q1;exports.getFilterValueType=Fo;exports.getFormattedTableNameForQuery=Pw;exports.getKeys=Xn;exports.getMetricDisplayLabel=LNe;exports.getNewField=Tq;exports.getObjectDiff=Y9;exports.getQualifiedTableName=UM;exports.getRoleBasedDisplayOverrides=qJ;exports.getSelectedDateFilterColumn=VX;exports.getSlotDefinitionForIndex=KR;exports.getSlotExpectedChartType=yN;exports.getSlotIndexForCard=jb;exports.getSql=BM;exports.getTokenParams=KM;exports.handleAggregationChange=UT;exports.handleAggregationLabelChange=HJ;exports.hasValidCardConfig=cl;exports.horizontalListSortingStrategy=_P;exports.hslStringToHex=Cge;exports.interpretAlertContext=Wq;exports.invalidateToken=Uae;exports.isBooleanDataType=zM;exports.isCalculatedDimension=ky;exports.isCalculatedField=C1;exports.isCalculatedFilterField=ese;exports.isCalculatedMetric=Ec;exports.isCardSummaryVisibleOnCard=hP;exports.isColumnInSqlGen=Jie;exports.isCustomVisualConfigCard=RT;exports.isDateDataType=ha;exports.isDefaultColor=dge;exports.isDevEnv=OM;exports.isExportComplete=JNe;exports.isExportInProgress=QNe;exports.isInAiScopeArray=ant;exports.isNumberDataType=fa;exports.isObjectEmpty=Lae;exports.isTextDataType=ty;exports.lastAssistantMessageIsCompleteWithToolCalls=Tre;exports.listAlertQuotas=Yq;exports.listAlerts=ZD;exports.merge=Em;exports.mergeAxisConfig=l_;exports.normalizeMultiInputPayload=JR;exports.pivotData=wy;exports.postRequest=k9;exports.postRequestRegular=ls;exports.prepareFeedbackData=GN;exports.previewAlertDeliverable=qq;exports.reindexSlotCards=F$e;exports.remarkGfm=gne;exports.removeFromScopeArray=cnt;exports.removeRing=Wc;exports.resolveDataType=HM;exports.resolveDatamodelName=g9;exports.resolveMultiInputType=Qy;exports.resolveMultiInputTypeFromVisual=GQ;exports.sanitizeAIScope=Dre;exports.setupEditorWithCard=YA;exports.showJoinRequiredNotification=jq;exports.sortByColumnsToSortState=CZ;exports.sortStateToSortByColumns=NZ;exports.sortableKeyboardCoordinates=MP;exports.startOfDayInTimezone=Ys;exports.titleCase=Wx;exports.toTitleCase=ui;exports.triggerAlertNow=Lq;exports.ue=We;exports.updateAlert=Fq;exports.updateAlertContextSources=ije;exports.updateAlertQuota=Kq;exports.useAIActions=YC;exports.useAIInteractionStore=_c;exports.useActiveExports=qNe;exports.useActiveToolStatus=Ure;exports.useAddNewFrame=Iq;exports.useAlertActions=XD;exports.useAlertBacktest=eY;exports.useAlertContextBuilder=Jq;exports.useAlertDeliveries=gje;exports.useAlertDetail=fje;exports.useAlertDraft=uje;exports.useAlertFilters=Xq;exports.useAlertHistory=pje;exports.useAlertQuotas=xje;exports.useAlertRuns=mje;exports.useAlertState=hje;exports.useAlertStore=td;exports.useAlerts=JD;exports.useAlertsBootstrap=Qq;exports.useAlertsById=lje;exports.useAlertsForCard=QD;exports.useAssignFilter=tse;exports.useAssistantContainer=KG;exports.useAssistantLayoutStore=hf;exports.useAssistantPanel=YG;exports.useAssistantProfile=Rre;exports.useAutoScroll=Bre;exports.useAutoSubmitQueue=zre;exports.useCallbackRef=os;exports.useCard=UNe;exports.useCardAlertMap=cje;exports.useCardFilterValues=pC;exports.useCardSummary=mP;exports.useChat=Ire;exports.useColumns=YD;exports.useCreateVisualWithFrame=Ime;exports.useCurrentAIContext=zp;exports.useCurrentActiveCard=C9;exports.useCurrentCardConfig=Fae;exports.useCurrentSheetActiveCards=N9;exports.useCurrentUserInfo=so;exports.useCustomVisual=ih;exports.useCustomVisualsQuery=vP;exports.useDashboardActions=un;exports.useDashboardById=AV;exports.useDashboardCardQuery=ul;exports.useDashboardCreation=OV;exports.useDashboardManagement=PV;exports.useDashboardPreferences=yp;exports.useDashboardQuery=RS;exports.useDashboardStore=Q;exports.useDashboardSummary=zJ;exports.useDataColumns=Mq;exports.useDateFilterHook=JFe;exports.useDebounce=sm;exports.useDefaultDashboardMutation=fV;exports.useDisplayPreferences=Zu;exports.useDroppable=Cee;exports.useEditorActions=br;exports.useEditorAside=JN;exports.useEditorStore=$e;exports.useEnsureReactGlobals=xX;exports.useExportActions=Aq;exports.useExportStore=DC;exports.useFieldManagement=Kre;exports.useFileActions=SA;exports.useFileAttachments=wA;exports.useFullscreenAssistant=GG;exports.useGroupMembers=v2e;exports.useGroups=hA;exports.useHasDashboardId=QG;exports.useInProgressExportsCount=YNe;exports.useInteractionStore=Qt;exports.useIsDashboardSelected=Ele;exports.useIsVisualSelected=_le;exports.useJoinabilityMap=vO;exports.useLayoutEffect2=cs;exports.useManagementActions=up;exports.useManagementStore=as;exports.useMessageWindow=Vre;exports.useMutation=Zr;exports.usePivotTableConfig=Vp;exports.usePluginQuery=eee;exports.usePromoteCalculatedMetricToDomain=ose;exports.useQuery=en;exports.useQueryClient=us;exports.useQueueActions=Bp;exports.useResourceManagement=sC;exports.useResourceUpdateState=RV;exports.useScopedFields=yO;exports.useSelectedAlertId=Zq;exports.useSelectedVisual=kle;exports.useSemaphorContext=tt;exports.useSensor=op;exports.useSensors=IN;exports.useSortable=c0;exports.useStarredChartsStore=vse;exports.useSyncLegacyEditorState=lse;exports.useTextFilterHook=c5e;exports.useTheme=cp;exports.useTopoJson=wq;exports.useUnifiedUsers=fA;exports.useUpdateResource=TV;exports.useUpdateVisualMutation=Dme;exports.useUserPreferences=oU;exports.useVisualById=rC;exports.useVisualManagement=Mme;exports.v4=gr;exports.validateFieldForChartType=Yre;exports.verticalListSortingStrategy=TP;
|