deepspotscreen-sdk 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,546 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class A{constructor(e,t){this.tokenCache=new Map,this.baseUrl=e.replace(/\/$/,""),this.apiKey=t}async getEmbedToken(e){var i,a,d,o;const t=[e.dashboardId,e.embedType,(i=e.embedLevel)!=null?i:"",(a=e.componentId)!=null?a:"",(d=e.userId)!=null?d:""].join(":"),r=this.tokenCache.get(t);if(r&&r.expiresAt>Date.now()+6e4)return r.token;const s=await this.post("/dashboard-builder/embed-token",{dashboardId:e.dashboardId,embedType:e.embedType,embedLevel:(o=e.embedLevel)!=null?o:"dashboard",componentId:e.componentId,userId:e.userId,tenantId:e.tenantId,expiresIn:3600},{"x-deepspot-api-key":this.apiKey});return this.tokenCache.set(t,{token:s.token,expiresAt:new Date(s.expiresAt).getTime()}),s.token}async getDashboardRender(e,t,r={}){var i;const s=new URLSearchParams({embedType:"dashboard",embedLevel:(i=r.embedLevel)!=null?i:"dashboard"});return r.pageId&&s.set("pageId",r.pageId),r.tabId&&s.set("tabId",r.tabId),r.filters&&Object.entries(r.filters).forEach(([a,d])=>{d!=null&&d!==""&&s.set(`filter[${a}]`,Array.isArray(d)?d.join(","):String(d))}),this.get(`/dashboard-builder/embed/${e}/render?${s}`,{"x-embed-token":t})}async getReportRender(e,t,r,s={}){const i=new URLSearchParams({embedType:"report",embedLevel:"report",componentId:t});return s.filters&&Object.entries(s.filters).forEach(([a,d])=>{d!=null&&d!==""&&i.set(`filter[${a}]`,Array.isArray(d)?d.join(","):String(d))}),this.get(`/dashboard-builder/embed/${e}/render?${i}`,{"x-embed-token":r})}async createApiKey(e,t){return this.post("/dashboard-builder/api-keys",e,{Authorization:`Bearer ${t}`})}async listApiKeys(e){return this.get("/dashboard-builder/api-keys",{Authorization:`Bearer ${e}`})}async deleteApiKey(e,t){await this.delete(`/dashboard-builder/api-keys/${e}`,{Authorization:`Bearer ${t}`})}async getFilterOptions(e,t,r){try{const s=await this.get(`/dashboard-builder/embed/${e}/filters/${t}/options`,{"x-embed-token":r});return Array.isArray(s)?s:Array.isArray(s==null?void 0:s.options)?s.options:Array.isArray(s==null?void 0:s.data)?s.data:[]}catch(s){return[]}}clearTokenCache(){this.tokenCache.clear()}async get(e,t={}){const r=await fetch(`${this.baseUrl}${e}`,{method:"GET",headers:{"Content-Type":"application/json",...t}});return this.handleResponse(r)}async post(e,t,r={}){const s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(t)});return this.handleResponse(s)}async delete(e,t={}){const r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",...t}});if(!r.ok)throw new Error(`Deepspot SDK: DELETE ${e} failed (${r.status})`)}async handleResponse(e){if(!e.ok){let r=`HTTP ${e.status}`;try{const s=await e.json();r=(s==null?void 0:s.message)||(s==null?void 0:s.error)||r}catch(s){}throw new Error(`Deepspot SDK: ${r}`)}const t=await e.json();return(t==null?void 0:t.data)!==void 0?t.data:t}}class ${constructor(e){var t,r;this.destroyed=!1,this.refreshTimer=null,this.opts=e,this.filters={...e.activeFilters},this.activePageId=(t=e.activePageId)!=null?t:"",this.activeTabId=(r=e.activeTabId)!=null?r:""}getActiveFilters(){return{...this.filters}}setFilter(e,t){this.filters[e]=t,this.scheduleRefresh()}setFilters(e){Object.assign(this.filters,e),this.scheduleRefresh()}goToPage(e){this.opts.embedType==="dashboard"&&(this.activePageId=e,this.opts.renderer.goToPage(e))}goToTab(e,t){this.opts.embedType==="dashboard"&&(this.activePageId=e,this.activeTabId=t,this.opts.renderer.goToTab(e,t))}async refresh(){if(!this.destroyed)try{const e=await this.fetchData();this.opts.renderer.update(e)}catch(e){console.error("Deepspot SDK: refresh failed",e)}}exportPDF(){this.opts.embedType==="dashboard"&&this.opts.renderer.exportPDF()}destroy(){this.destroyed=!0,this.refreshTimer&&clearTimeout(this.refreshTimer),this.opts.renderer.destroy(),this.opts.apiClient.clearTokenCache()}scheduleRefresh(){this.refreshTimer&&clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(()=>this.refresh(),300)}async fetchData(){const{apiClient:e,dashboardId:t,componentId:r,token:s,embedType:i,embedLevel:a}=this.opts;return i==="report"&&r?e.getReportRender(t,r,s,{filters:this.filters}):e.getDashboardRender(t,s,{embedLevel:a,pageId:this.activePageId||void 0,tabId:this.activeTabId||void 0,filters:this.filters})}}const D=24,x=10,w=12;class I{constructor(e,t=0){this.containerWidth=e,this.minY=t}get colWidth(){return this.containerWidth/D}toPx(e){const t=this.colWidth,r=w/2;return{left:e.x*t+r,top:(e.y-this.minY)*x+r,width:e.w*t-w,height:e.h*x-w}}static totalHeight(e){if(!e.length)return 400;const t=Math.min(...e.map(s=>s.y));return(Math.max(...e.map(s=>s.y+s.h))-t)*x+40}applyStyles(e,t){const r=this.toPx(t);e.style.position="absolute",e.style.left=`${r.left}px`,e.style.top=`${r.top}px`,e.style.width=`${r.width}px`,e.style.height=`${r.height}px`}}let T=null;function E(){return T||(T=Promise.resolve().then(()=>require("./apexcharts.common-DGzslxI3.cjs")).then(p=>p.apexcharts_common)),T}class L{constructor(e){this.chart=null,this.container=e}async render(e,t,r,s){if(!t||t.length===0){this.renderEmpty(e.title);return}const i=this.buildOptions(e,t,r,s);if(!i){this.renderEmpty(e.title);return}this.container.innerHTML=`
2
- <div class="ds-chart-card">
3
- <div class="ds-chart-title">${e.title||""}</div>
4
- <div class="ds-chart-body" id="ds-chart-body-${e.id}"></div>
5
- </div>
6
- `;const a=this.container.querySelector(`#ds-chart-body-${e.id}`);if(a)try{this.chart&&this.chart.destroy();const{default:d}=await E();this.chart=new d(a,i),this.chart.render()}catch(d){console.error("[Deepspot SDK] ChartRenderer error:",d),a.innerHTML='<div class="ds-chart-empty">Chart render error</div>'}}async update(e,t,r){if(!this.chart||!t||t.length===0){await this.render(e,t,r);return}const{series:s,categories:i}=this.extractSeriesAndCategories(e,t);try{this.chart.updateOptions({series:s,xaxis:{categories:i},theme:{mode:r}})}catch(a){this.render(e,t,r)}}destroy(){var e;try{(e=this.chart)==null||e.destroy()}catch(t){}this.chart=null}buildOptions(e,t,r,s){const i=e.type;return i==="pie"||i==="donut"?this.buildPieOptions(e,t,r,s):i==="bar"||i==="line"||i==="area"?this.buildCartesianOptions(e,t,r,s):null}buildCartesianOptions(e,t,r,s){var n;const{series:i,categories:a,xAxisLabel:d,yAxisLabel:o}=this.extractSeriesAndCategories(e,t),l=e.properties||{},b=l.colors?Object.values(l.colors):["#6366f1","#8b5cf6","#ec4899","#f59e0b","#10b981","#3b82f6"],c=r==="dark";return{chart:{type:e.type==="area"?"area":e.type==="line"?"line":"bar",toolbar:{show:!1},background:"transparent",animations:{enabled:!0,speed:400},fontFamily:"inherit",height:s!=null?s:"100%"},theme:{mode:r},series:i,xaxis:{categories:a,title:{text:d},labels:{rotate:a.length>8?-45:0,style:{colors:c?"#94a3b8":"#6b7280",fontSize:"11px"}},axisBorder:{color:c?"#334155":"#e5e7eb"},axisTicks:{color:c?"#334155":"#e5e7eb"}},yaxis:{title:{text:o},labels:{style:{colors:c?"#94a3b8":"#6b7280",fontSize:"11px"}}},colors:b,legend:{show:i.length>1||((n=l.showLegend)!=null?n:!1),position:"bottom",labels:{colors:c?"#94a3b8":"#6b7280"}},grid:{borderColor:c?"#1e293b":"#f3f4f6",strokeDashArray:4,padding:{bottom:a.length>8?60:10}},tooltip:{theme:r},stroke:{curve:"smooth",width:e.type==="bar"?0:2},fill:e.type==="area"?{type:"gradient",gradient:{shadeIntensity:.5,opacityFrom:.4,opacityTo:0}}:{},dataLabels:{enabled:!1},plotOptions:{bar:{borderRadius:4,distributed:i.length===1}}}}buildPieOptions(e,t,r,s){const i=e.properties||{},a=t.length>0?Object.keys(t[0]):[],d=a[0]||"label",o=a[1]||"value",l=t.map(h=>{var f;return String((f=h[d])!=null?f:"")}),b=t.map(h=>Number(h[o])||0),c=r==="dark",n=i.colors?Object.values(i.colors):["#6366f1","#8b5cf6","#ec4899","#f59e0b","#10b981","#3b82f6"];return{chart:{type:e.type,toolbar:{show:!1},background:"transparent",fontFamily:"inherit",height:s!=null?s:"100%"},theme:{mode:r},series:b,labels:l,colors:n,legend:{position:"bottom",labels:{colors:c?"#94a3b8":"#6b7280"}},tooltip:{theme:r},dataLabels:{enabled:l.length<=8},plotOptions:{pie:{donut:{size:e.type==="donut"?"65%":"0%"}}}}}extractSeriesAndCategories(e,t){const r=e.properties||{},s=t.length>0?Object.keys(t[0]):[],i=r.xAxis||s[0]||"x";let a=[];if(r.selectedYAxisColumn)try{const n=typeof r.selectedYAxisColumn=="string"?JSON.parse(r.selectedYAxisColumn):r.selectedYAxisColumn;Array.isArray(n)&&(a=n.map(h=>typeof h=="string"?{column:h}:h))}catch(n){}if(!a.length&&r.yAxis){const n=r.yAxis;a=(Array.isArray(n)?n:[n]).map(f=>({column:String(f)}))}!a.length&&s.length>1&&(a=s.slice(1).map(n=>({column:n})));const d=t.map(n=>{var h;return String((h=n[i])!=null?h:"")}),o=t.length>0?Object.keys(t[0]):[],l=a.map(n=>{const h=o.includes(n.column)?n.column:null,f=h?null:o.find(u=>u.includes(n.column)||n.column.includes(u)),g=!h&&!f?o.find(u=>{var y;return u!==i&&!isNaN(Number((y=t[0])==null?void 0:y[u]))}):null,m=h||f||g||n.column;return{name:n.label||n.column.replace(/_/g," "),data:t.map(u=>{const y=u[m];return y!=null?Number(y):null})}}),b=r.xAxisLabel||i.replace(/_/g," "),c=r.yAxisLabel||(l.length===1?l[0].name:"Values");return{series:l,categories:d,xAxisLabel:b,yAxisLabel:c}}renderEmpty(e){this.container.innerHTML=`
7
- <div class="ds-chart-card">
8
- ${e?`<div class="ds-chart-title">${e}</div>`:""}
9
- <div class="ds-chart-empty">No data available</div>
10
- </div>
11
- `}}class R{render(e,t,r){var l;if(!r||r.length===0){e.innerHTML=`
12
- <div class="ds-table-card">
13
- <div class="ds-table-title">${t.title||""}</div>
14
- <div class="ds-chart-empty">No data available</div>
15
- </div>
16
- `;return}const s=Object.keys(r[0]),i=((l=t.properties)==null?void 0:l.columns)||[],a=i.length?i.filter(b=>s.includes(b)):s,d=a.map(b=>`<th>${this.formatHeader(b)}</th>`).join(""),o=r.map(b=>`<tr>${a.map(n=>{const h=b[n];return`<td title="${this.escape(String(h!=null?h:""))}">${this.escape(this.formatValue(h))}</td>`}).join("")}</tr>`).join("");e.innerHTML=`
17
- <div class="ds-table-card">
18
- <div class="ds-table-title">${t.title||""}</div>
19
- <div class="ds-table-scroll">
20
- <table class="ds-table">
21
- <thead><tr>${d}</tr></thead>
22
- <tbody>${o}</tbody>
23
- </table>
24
- </div>
25
- </div>
26
- `}formatHeader(e){return e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}formatValue(e){return e==null?"—":typeof e=="number"?e%1===0?e.toLocaleString():e.toFixed(2):String(e)}escape(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}}class F{render(e,t,r){const s=t.properties||{};let i=null;if(r&&r.length>0){const h=r[0],f=s.metric||Object.keys(h)[0],g=h[f];if(g!==void 0)i=g;else{const m=Object.keys(h).find(u=>u.includes(f)||f.includes(u));i=h[m!=null?m:Object.keys(h)[0]]}}const a=this.formatValue(i,s),d=s.backgroundColor||"",o=s.textColor||"",l=t.title||"",b=d?`background:${d};border-color:${d};`:"",c=o?`color:${o};`:"",n=o?`color:${o};opacity:0.7;`:"";e.innerHTML=`
27
- <div class="ds-card"${b?` style="${b}"`:""}>
28
- <div class="ds-card-label"${n?` style="${n}"`:""}>${l}</div>
29
- <div class="ds-card-value"${c?` style="${c}"`:""}>${a}</div>
30
- </div>
31
- `}formatValue(e,t){if(e==null)return"—";const r=Number(e);if(isNaN(r))return String(e);const s=(t==null?void 0:t.prefix)||(t==null?void 0:t.currencySymbol)||"",i=(t==null?void 0:t.suffix)||"";let a;return Math.abs(r)>=1e6?a=(r/1e6).toFixed(1)+"M":Math.abs(r)>=1e3?a=(r/1e3).toFixed(1)+"K":a=r%1===0?r.toLocaleString():r.toFixed(2),`${s}${a}${i}`}}class P{constructor(e,t){this.currentValues={},this.container=e,this.onFilterChange=t}render(e,t={}){if(!e||e.length===0){this.container.style.display="none";return}this.container.style.display="",this.currentValues={...t},this.container.innerHTML=`<div class="ds-filter-bar">${e.map(r=>this.renderFilter(r,t[r.applyToField||r.filterId])).join("")}</div>`,this.attachListeners(e)}updateOptions(e,t){const r=this.container.querySelector(`select[data-filter-id="${e}"]`);if(!r)return;const s=r.value;r.innerHTML='<option value="">All</option>'+t.map(i=>`<option value="${this.escAttr(i)}">${this.escText(i)}</option>`).join(""),s&&t.includes(s)&&(r.value=s)}updateValues(e){Object.assign(this.currentValues,e),Object.entries(e).forEach(([t,r])=>{const s=this.container.querySelector(`[data-filter-id="${t}"]`);s&&r!==void 0&&(s.value=String(r))})}renderFilter(e,t){const r=`ds-filter-${e.filterId}`,s=`<label class="ds-filter-label" for="${r}">${e.label}</label>`;switch(e.type){case"dropdown":return`
32
- <div class="ds-filter-item">
33
- ${s}
34
- <select class="ds-filter-select" id="${r}" data-filter-id="${e.filterId}">
35
- <option value="">All</option>
36
- ${(e.options||[]).map(d=>`
37
- <option value="${this.escAttr(d)}" ${t===d?"selected":""}>
38
- ${this.escText(d)}
39
- </option>
40
- `).join("")}
41
- </select>
42
- </div>`;case"multi-select":return`
43
- <div class="ds-filter-item">
44
- ${s}
45
- <select class="ds-filter-select" id="${r}" data-filter-id="${e.filterId}" multiple size="1">
46
- ${(e.options||[]).map(d=>`
47
- <option value="${this.escAttr(d)}">${this.escText(d)}</option>
48
- `).join("")}
49
- </select>
50
- </div>`;case"date-range":const i=(t==null?void 0:t.from)||"",a=(t==null?void 0:t.to)||"";return`
51
- <div class="ds-filter-item">
52
- ${s}
53
- <div class="ds-date-range-inputs">
54
- <input type="date" class="ds-filter-input"
55
- data-filter-id="${e.filterId}" data-date-part="from"
56
- value="${i}" />
57
- <span>–</span>
58
- <input type="date" class="ds-filter-input"
59
- data-filter-id="${e.filterId}" data-date-part="to"
60
- value="${a}" />
61
- </div>
62
- </div>`;case"text-input":return`
63
- <div class="ds-filter-item">
64
- ${s}
65
- <input type="text" class="ds-filter-input" id="${r}"
66
- data-filter-id="${e.filterId}"
67
- value="${this.escAttr(String(t!=null?t:""))}"
68
- placeholder="Search..." />
69
- </div>`;case"number-input":return`
70
- <div class="ds-filter-item">
71
- ${s}
72
- <input type="number" class="ds-filter-input" id="${r}"
73
- data-filter-id="${e.filterId}"
74
- value="${this.escAttr(String(t!=null?t:""))}" />
75
- </div>`;default:return""}}attachListeners(e){const t={};this.container.querySelectorAll("[data-filter-id]").forEach(r=>{const s=r.dataset.filterId,i=r.dataset.datePart,a=e.find(o=>o.filterId===s),d=()=>{let o;if((a==null?void 0:a.type)==="date-range"&&i)t[s]=t[s]||{},t[s][i]=r.value,o={...t[s]};else if((a==null?void 0:a.type)==="multi-select"){const l=r;o=Array.from(l.selectedOptions).map(b=>b.value).filter(Boolean)}else o=r.value;this.currentValues[s]=o,this.onFilterChange(s,o)};r.addEventListener((a==null?void 0:a.type)==="text-input"?"input":"change",d)})}escAttr(e){return e.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}escText(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}}class O{constructor(e,t){this.activePageId="",this.activeTabId="",this.activeFilters={},this.chartRenderers=new Map,this.tableRenderer=new R,this.cardRenderer=new F,this.isLoadingTab=!1,this.root=e,this.opts=t,this.activeFilters={...t.initialFilters}}render(e){var t,r;this.renderData=e,this.activePageId=e.activePage,this.activeTabId=e.activeTab,this.buildShell(),this.renderNavigation(),this.renderFilterBar(),this.renderGrid(),(r=(t=this.opts).onReady)==null||r.call(t)}update(e){this.renderData=e,this.activePageId=e.activePage,this.activeTabId=e.activeTab,this.isLoadingTab=!1,this.syncNavHighlight(),this.updateFilterBar(),this.renderGrid()}goToPage(e){const t=this.getTabsForPage(e)[0];t&&this.triggerTabSwitch(e,t.id)}goToTab(e,t){this.triggerTabSwitch(e,t)}destroy(){this.chartRenderers.forEach(e=>e.destroy()),this.chartRenderers.clear(),this.root.innerHTML=""}exportPDF(){const e=this.root.querySelector("#ds-canvas");e&&Promise.resolve().then(()=>require("./html2canvas.esm-EoNFmhrp.cjs")).then(({default:t})=>t(e,{scale:2,useCORS:!0}).then(r=>Promise.resolve().then(()=>require("./jspdf.es.min-D6GjoB2T.cjs")).then(s=>s.jspdf_es_min).then(({jsPDF:s})=>{const i=new s({orientation:"landscape",unit:"px"});i.addImage(r.toDataURL("image/png"),"PNG",0,0,i.internal.pageSize.width,0),i.save(`${this.renderData.dashboard.name||"dashboard"}.pdf`)})))}exportCSV(){this.renderData.components.forEach(e=>{const t=this.renderData.data[e.id];if(!(t!=null&&t.length)||!["table","bar","line","area"].includes(e.type))return;const r=Object.keys(t[0]),s=[r.join(","),...t.map(a=>r.map(d=>{var o;return JSON.stringify((o=a[d])!=null?o:"")}).join(","))].join(`
76
- `);Object.assign(document.createElement("a"),{href:URL.createObjectURL(new Blob([s],{type:"text/csv"})),download:`${e.title||e.id}.csv`}).click()})}updateFilterValues(e){var t;Object.assign(this.activeFilters,e),(t=this.filterRenderer)==null||t.updateValues(e)}buildShell(){const e=this.opts.embedLevel,t=this.renderData.dashboard.pages,r=e==="dashboard"&&t.length>1,s=e==="page"||e==="dashboard";this.root.innerHTML=`
77
- ${this.opts.hideExport?"":'<div class="ds-toolbar" id="ds-toolbar"></div>'}
78
- ${r?'<nav class="ds-page-nav" id="ds-page-nav"></nav>':""}
79
- ${s?'<nav class="ds-page-nav" id="ds-tab-nav"></nav>':""}
80
- <div id="ds-filter-container"></div>
81
- <div class="ds-canvas" id="ds-canvas">
82
- <div class="ds-grid" id="ds-grid"></div>
83
- </div>
84
- <div id="ds-tab-loading" style="display:none;position:absolute;inset:0;
85
- background:rgba(255,255,255,0.5);align-items:center;justify-content:center;">
86
- <div class="ds-embed-spinner"></div>
87
- </div>
88
- `,this.root.style.position="relative",this.opts.hideExport||this.buildExportToolbar();const i=this.root.querySelector("#ds-filter-container");this.filterRenderer=new P(i,(a,d)=>{var b,c;const o=this.renderData.filters.find(n=>n.filterId===a),l=(o==null?void 0:o.applyToField)||a;this.activeFilters[l]=d,(c=(b=this.opts).onFilterChange)==null||c.call(b,this.activeFilters),this.opts.onTabSwitch(this.activePageId,this.activeTabId)})}buildExportToolbar(){var t,r;const e=this.root.querySelector("#ds-toolbar");e&&(e.innerHTML=`
89
- <button class="ds-toolbar-btn" id="ds-btn-pdf">⬇ PDF</button>
90
- <button class="ds-toolbar-btn" id="ds-btn-csv">⬇ CSV</button>
91
- `,(t=e.querySelector("#ds-btn-pdf"))==null||t.addEventListener("click",()=>this.exportPDF()),(r=e.querySelector("#ds-btn-csv"))==null||r.addEventListener("click",()=>this.exportCSV()))}renderNavigation(){this.renderPageNav(),this.renderTabNav(this.activePageId)}renderPageNav(){const e=this.root.querySelector("#ds-page-nav");e&&(e.innerHTML=this.renderData.dashboard.pages.map(t=>`
92
- <button class="ds-page-tab ${t.pageId===this.activePageId?"ds-active":""}"
93
- data-page-id="${t.pageId}">${t.title}</button>
94
- `).join(""),e.querySelectorAll(".ds-page-tab").forEach(t=>{t.addEventListener("click",()=>{var s,i;const r=t.dataset.pageId;r===this.activePageId&&!this.isLoadingTab||this.triggerTabSwitch(r,(i=(s=this.getTabsForPage(r)[0])==null?void 0:s.id)!=null?i:"")})}))}renderTabNav(e){const t=this.root.querySelector("#ds-tab-nav");t&&this.buildTabButtons(t,e)}buildTabButtons(e,t){const r=this.getTabsForPage(t);if(r.length<=1){e.style.display="none";return}e.style.display="",e.innerHTML=r.map(s=>`
95
- <button class="ds-page-tab ${s.id===this.activeTabId?"ds-active":""}"
96
- data-tab-id="${s.id}" data-page-id="${t}">${s.title}</button>
97
- `).join(""),e.querySelectorAll(".ds-page-tab").forEach(s=>{s.addEventListener("click",()=>{const i=s.dataset.tabId,a=s.dataset.pageId;i===this.activeTabId&&a===this.activePageId&&!this.isLoadingTab||this.triggerTabSwitch(a,i)})})}triggerTabSwitch(e,t){this.isLoadingTab||!e||!t||(this.isLoadingTab=!0,this.activePageId=e,this.activeTabId=t,this.syncNavHighlight(),this.showTabSpinner(),this.opts.onTabSwitch(e,t))}syncNavHighlight(){this.root.querySelectorAll("#ds-page-nav .ds-page-tab").forEach(t=>{t.classList.toggle("ds-active",t.dataset.pageId===this.activePageId)});const e=this.root.querySelector("#ds-tab-nav");e&&this.buildTabButtons(e,this.activePageId)}renderFilterBar(){this.opts.hideFilters||(this.filterRenderer.render(this.renderData.filters,this.activeFilters),this.fetchFilterOptions())}updateFilterBar(){this.opts.hideFilters||(this.filterRenderer.render(this.renderData.filters,this.activeFilters),this.fetchFilterOptions())}async fetchFilterOptions(){if(this.opts.onFetchFilterOptions)for(const e of this.renderData.filters){if(e.type!=="dropdown"&&e.type!=="multi-select"||e.options&&e.options.length>0)continue;const t=await this.opts.onFetchFilterOptions(e.filterId);t.length>0&&this.filterRenderer.updateOptions(e.filterId,t)}}renderGrid(){this.hideTabSpinner();const e=this.root.querySelector("#ds-grid");if(!e)return;this.chartRenderers.forEach(l=>l.destroy()),this.chartRenderers.clear();const t=this.renderData.components;if(!t.length){e.style.height="200px",e.innerHTML='<div class="ds-chart-empty" style="padding-top:80px;">No components on this tab.</div>';return}const r=e.clientWidth||this.root.clientWidth||800,s=t.map(l=>l.position),i=s.length?Math.min(...s.map(l=>l.y)):0,a=new I(r,i);e.style.height=`${I.totalHeight(s)}px`,e.innerHTML="";const d=36,o=[];t.forEach(l=>{const b=document.createElement("div");b.className="ds-component-wrapper",b.dataset.componentId=l.id,a.applyStyles(b,l.position),e.appendChild(b);const c=a.toPx(l.position),n=Math.max(50,c.height-d);o.push(this.renderComponent(b,l,n))}),Promise.all(o).catch(()=>{})}async renderComponent(e,t,r){var a,d;const s=this.renderData.data[t.id]||[],i=this.opts.theme;switch(t.type){case"bar":case"line":case"pie":case"donut":case"area":{const o=new L(e);await o.render(t,s,i,r),this.chartRenderers.set(t.id,o);break}case"table":this.tableRenderer.render(e,t,s);break;case"number-card":this.cardRenderer.render(e,t,s);break;case"text":{const o=Object.entries(((a=t.properties)==null?void 0:a.style)||{}).map(([l,b])=>`${l}:${b}`).join(";");e.innerHTML=`<div style="${o};padding:8px;">${((d=t.properties)==null?void 0:d.content)||""}</div>`;break}}}showTabSpinner(){const e=this.root.querySelector("#ds-tab-loading"),t=this.root.querySelector("#ds-grid");e&&(e.style.display="flex"),t&&(t.style.opacity="0.35")}hideTabSpinner(){const e=this.root.querySelector("#ds-tab-loading"),t=this.root.querySelector("#ds-grid");e&&(e.style.display="none"),t&&(t.style.opacity="1")}getTabsForPage(e){var t,r;return(r=(t=this.renderData.dashboard.pages.find(s=>s.pageId===e))==null?void 0:t.tabs)!=null?r:[]}}class j{constructor(e,t){this.chartRenderer=null,this.tableRenderer=new R,this.cardRenderer=new F,this.root=e,this.theme=t}render(e,t){const r=e.components[0];if(!r){this.root.innerHTML=`<div class="ds-embed-error">
98
- <div class="ds-embed-error-icon">⚠</div>
99
- <div>Component not found.</div>
100
- </div>`;return}const s=e.data[r.id]||[];this.renderComponent(r,s),t==null||t()}update(e){const t=e.components[0];if(!t)return;const r=e.data[t.id]||[];switch(t.type){case"bar":case"line":case"pie":case"donut":case"area":this.chartRenderer?this.chartRenderer.update(t,r,this.theme):this.renderComponent(t,r);break;case"table":this.tableRenderer.render(this.root,t,r);break;case"number-card":this.cardRenderer.render(this.root,t,r);break}}destroy(){var e;(e=this.chartRenderer)==null||e.destroy(),this.chartRenderer=null,this.root.innerHTML=""}renderComponent(e,t){var r;switch(e.type){case"bar":case"line":case"pie":case"donut":case"area":(r=this.chartRenderer)==null||r.destroy(),this.chartRenderer=new L(this.root),this.chartRenderer.render(e,t,this.theme);break;case"table":this.tableRenderer.render(this.root,e,t);break;case"number-card":this.cardRenderer.render(this.root,e,t);break;default:this.root.innerHTML=`<div class="ds-chart-empty">Unsupported component type: ${e.type}</div>`}}}let S=!1;function M(){if(!(S||typeof document=="undefined")){S=!0;try{const p=`/* ─────────────────────────────────────────────────────────────────────────────
101
- Deepspot SDK — Base Embed Styles
102
- Injected once into the host page's <head> by the SDK.
103
- All selectors are scoped under .ds-embed-* to avoid leaking into host styles.
104
- ───────────────────────────────────────────────────────────────────────────── */
105
-
106
- /* ── Reset inside SDK containers ──────────────────────────────────────────── */
107
- .ds-embed-root *,
108
- .ds-embed-root *::before,
109
- .ds-embed-root *::after {
110
- box-sizing: border-box;
111
- margin: 0;
112
- padding: 0;
113
- }
114
-
115
- /* ── Root container ────────────────────────────────────────────────────────── */
116
- .ds-embed-root {
117
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
118
- Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
119
- font-size: 14px;
120
- line-height: 1.5;
121
- width: 100%;
122
- height: 100%;
123
- overflow: auto;
124
- position: relative;
125
- }
126
-
127
- .ds-embed-root.ds-theme-light {
128
- background: #ffffff;
129
- color: #111827;
130
- }
131
-
132
- .ds-embed-root.ds-theme-dark {
133
- background: #0f172a;
134
- color: #f1f5f9;
135
- }
136
-
137
- /* ── Loading state ─────────────────────────────────────────────────────────── */
138
- .ds-embed-loading {
139
- display: flex;
140
- flex-direction: column;
141
- align-items: center;
142
- justify-content: center;
143
- height: 100%;
144
- min-height: 200px;
145
- gap: 12px;
146
- color: #6b7280;
147
- }
148
-
149
- .ds-embed-spinner {
150
- width: 36px;
151
- height: 36px;
152
- border: 3px solid #e5e7eb;
153
- border-top-color: #6366f1;
154
- border-radius: 50%;
155
- animation: ds-spin 0.8s linear infinite;
156
- }
157
-
158
- @keyframes ds-spin {
159
- to { transform: rotate(360deg); }
160
- }
161
-
162
- .ds-embed-loading-text {
163
- font-size: 13px;
164
- }
165
-
166
- /* ── Error state ───────────────────────────────────────────────────────────── */
167
- .ds-embed-error {
168
- display: flex;
169
- flex-direction: column;
170
- align-items: center;
171
- justify-content: center;
172
- height: 100%;
173
- min-height: 200px;
174
- gap: 8px;
175
- padding: 24px;
176
- text-align: center;
177
- color: #ef4444;
178
- }
179
-
180
- .ds-embed-error-icon {
181
- font-size: 32px;
182
- }
183
-
184
- .ds-embed-error-message {
185
- font-size: 13px;
186
- color: #6b7280;
187
- }
188
-
189
- /* ── Filter bar ────────────────────────────────────────────────────────────── */
190
- .ds-filter-bar {
191
- display: flex;
192
- flex-wrap: wrap;
193
- align-items: center;
194
- gap: 10px;
195
- padding: 10px 16px;
196
- border-bottom: 1px solid #e5e7eb;
197
- background: inherit;
198
- }
199
-
200
- .ds-theme-dark .ds-filter-bar {
201
- border-bottom-color: #1e293b;
202
- }
203
-
204
- .ds-filter-item {
205
- display: flex;
206
- flex-direction: column;
207
- gap: 4px;
208
- }
209
-
210
- .ds-filter-label {
211
- font-size: 11px;
212
- font-weight: 600;
213
- text-transform: uppercase;
214
- letter-spacing: 0.05em;
215
- color: #6b7280;
216
- }
217
-
218
- .ds-filter-select,
219
- .ds-filter-input {
220
- height: 32px;
221
- padding: 0 10px;
222
- border: 1px solid #d1d5db;
223
- border-radius: 6px;
224
- font-size: 13px;
225
- background: #ffffff;
226
- color: #111827;
227
- cursor: pointer;
228
- min-width: 130px;
229
- }
230
-
231
- .ds-theme-dark .ds-filter-select,
232
- .ds-theme-dark .ds-filter-input {
233
- background: #1e293b;
234
- border-color: #334155;
235
- color: #f1f5f9;
236
- }
237
-
238
- .ds-filter-select:focus,
239
- .ds-filter-input:focus {
240
- outline: none;
241
- border-color: #6366f1;
242
- box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
243
- }
244
-
245
- .ds-date-range-inputs {
246
- display: flex;
247
- gap: 6px;
248
- align-items: center;
249
- }
250
-
251
- .ds-date-range-inputs input[type="date"] {
252
- height: 32px;
253
- padding: 0 8px;
254
- border: 1px solid #d1d5db;
255
- border-radius: 6px;
256
- font-size: 13px;
257
- background: #ffffff;
258
- color: #111827;
259
- }
260
-
261
- .ds-theme-dark .ds-date-range-inputs input[type="date"] {
262
- background: #1e293b;
263
- border-color: #334155;
264
- color: #f1f5f9;
265
- }
266
-
267
- /* ── Page / Tab navigation ─────────────────────────────────────────────────── */
268
- .ds-page-nav {
269
- display: flex;
270
- gap: 4px;
271
- padding: 8px 16px 0;
272
- border-bottom: 1px solid #e5e7eb;
273
- overflow-x: auto;
274
- }
275
-
276
- .ds-theme-dark .ds-page-nav {
277
- border-bottom-color: #1e293b;
278
- }
279
-
280
- .ds-page-tab {
281
- padding: 6px 16px;
282
- font-size: 13px;
283
- font-weight: 500;
284
- border: none;
285
- border-bottom: 2px solid transparent;
286
- background: transparent;
287
- color: #6b7280;
288
- cursor: pointer;
289
- white-space: nowrap;
290
- transition: color 0.15s, border-color 0.15s;
291
- }
292
-
293
- .ds-page-tab:hover {
294
- color: #111827;
295
- }
296
-
297
- .ds-theme-dark .ds-page-tab:hover {
298
- color: #f1f5f9;
299
- }
300
-
301
- .ds-page-tab.ds-active {
302
- color: #6366f1;
303
- border-bottom-color: #6366f1;
304
- }
305
-
306
- /* ── Grid canvas ───────────────────────────────────────────────────────────── */
307
- .ds-canvas {
308
- position: relative;
309
- width: 100%;
310
- /* No horizontal padding — grid.clientWidth must equal container width so
311
- GridLayout.colWidth = containerWidth/24 matches the dashboard builder.
312
- 16px on each side was shrinking the grid by 32px and misaligning positions. */
313
- padding: 8px 0 16px;
314
- overflow-x: hidden;
315
- }
316
-
317
- .ds-grid {
318
- position: relative;
319
- width: 100%;
320
- /* Clip absolutely-positioned children to the grid boundary so rounding
321
- errors or miscalculated widths don't create a horizontal scrollbar. */
322
- overflow: hidden;
323
- }
324
-
325
- .ds-component-wrapper {
326
- position: absolute;
327
- overflow: hidden;
328
- }
329
-
330
- /* ── Chart component ───────────────────────────────────────────────────────── */
331
- .ds-chart-card {
332
- width: 100%;
333
- height: 100%;
334
- background: #ffffff;
335
- border: 1px solid #e5e7eb;
336
- border-radius: 10px;
337
- overflow: hidden;
338
- display: flex;
339
- flex-direction: column;
340
- }
341
-
342
- .ds-theme-dark .ds-chart-card {
343
- background: #1e293b;
344
- border-color: #334155;
345
- }
346
-
347
- .ds-chart-title {
348
- padding: 10px 14px 4px;
349
- font-size: 13px;
350
- font-weight: 600;
351
- color: #374151;
352
- flex-shrink: 0;
353
- }
354
-
355
- .ds-theme-dark .ds-chart-title {
356
- color: #e2e8f0;
357
- }
358
-
359
- .ds-chart-body {
360
- flex: 1;
361
- min-height: 0;
362
- }
363
-
364
- .ds-chart-empty {
365
- display: flex;
366
- align-items: center;
367
- justify-content: center;
368
- height: 100%;
369
- color: #9ca3af;
370
- font-size: 13px;
371
- }
372
-
373
- /* ── Table component ───────────────────────────────────────────────────────── */
374
- .ds-table-card {
375
- width: 100%;
376
- height: 100%;
377
- background: #ffffff;
378
- border: 1px solid #e5e7eb;
379
- border-radius: 10px;
380
- overflow: hidden;
381
- display: flex;
382
- flex-direction: column;
383
- }
384
-
385
- .ds-theme-dark .ds-table-card {
386
- background: #1e293b;
387
- border-color: #334155;
388
- }
389
-
390
- .ds-table-title {
391
- padding: 10px 14px 4px;
392
- font-size: 13px;
393
- font-weight: 600;
394
- color: #374151;
395
- flex-shrink: 0;
396
- }
397
-
398
- .ds-theme-dark .ds-table-title {
399
- color: #e2e8f0;
400
- }
401
-
402
- .ds-table-scroll {
403
- flex: 1;
404
- overflow: auto;
405
- }
406
-
407
- .ds-table {
408
- width: 100%;
409
- border-collapse: collapse;
410
- font-size: 12px;
411
- }
412
-
413
- .ds-table th {
414
- position: sticky;
415
- top: 0;
416
- padding: 8px 12px;
417
- text-align: left;
418
- font-weight: 600;
419
- font-size: 11px;
420
- text-transform: uppercase;
421
- letter-spacing: 0.05em;
422
- background: #f9fafb;
423
- color: #6b7280;
424
- border-bottom: 1px solid #e5e7eb;
425
- white-space: nowrap;
426
- }
427
-
428
- .ds-theme-dark .ds-table th {
429
- background: #0f172a;
430
- color: #94a3b8;
431
- border-bottom-color: #334155;
432
- }
433
-
434
- .ds-table td {
435
- padding: 8px 12px;
436
- border-bottom: 1px solid #f3f4f6;
437
- color: #374151;
438
- max-width: 200px;
439
- overflow: hidden;
440
- text-overflow: ellipsis;
441
- white-space: nowrap;
442
- }
443
-
444
- .ds-theme-dark .ds-table td {
445
- color: #cbd5e1;
446
- border-bottom-color: #1e293b;
447
- }
448
-
449
- .ds-table tr:hover td {
450
- background: #f9fafb;
451
- }
452
-
453
- .ds-theme-dark .ds-table tr:hover td {
454
- background: #1e293b;
455
- }
456
-
457
- /* ── KPI Number Card ───────────────────────────────────────────────────────── */
458
- .ds-card {
459
- width: 100%;
460
- height: 100%;
461
- border: 1px solid #e5e7eb;
462
- border-radius: 10px;
463
- display: flex;
464
- flex-direction: column;
465
- align-items: center;
466
- justify-content: center;
467
- padding: 16px;
468
- text-align: center;
469
- background: #ffffff;
470
- }
471
-
472
- .ds-theme-dark .ds-card {
473
- background: #1e293b;
474
- border-color: #334155;
475
- }
476
-
477
- .ds-card-label {
478
- font-size: 12px;
479
- font-weight: 500;
480
- color: #6b7280;
481
- margin-bottom: 6px;
482
- text-transform: uppercase;
483
- letter-spacing: 0.05em;
484
- }
485
-
486
- .ds-card-value {
487
- font-size: 32px;
488
- font-weight: 700;
489
- color: #111827;
490
- line-height: 1.1;
491
- }
492
-
493
- .ds-theme-dark .ds-card-value {
494
- color: #f1f5f9;
495
- }
496
-
497
- /* ── Export toolbar ────────────────────────────────────────────────────────── */
498
- .ds-toolbar {
499
- display: flex;
500
- justify-content: flex-end;
501
- padding: 8px 16px 0;
502
- gap: 8px;
503
- }
504
-
505
- .ds-toolbar-btn {
506
- height: 30px;
507
- padding: 0 12px;
508
- border: 1px solid #d1d5db;
509
- border-radius: 6px;
510
- font-size: 12px;
511
- font-weight: 500;
512
- background: #ffffff;
513
- color: #374151;
514
- cursor: pointer;
515
- display: flex;
516
- align-items: center;
517
- gap: 5px;
518
- transition: background 0.15s, border-color 0.15s;
519
- }
520
-
521
- .ds-toolbar-btn:hover {
522
- background: #f9fafb;
523
- border-color: #9ca3af;
524
- }
525
-
526
- .ds-theme-dark .ds-toolbar-btn {
527
- background: #1e293b;
528
- border-color: #334155;
529
- color: #e2e8f0;
530
- }
531
-
532
- .ds-theme-dark .ds-toolbar-btn:hover {
533
- background: #0f172a;
534
- }
535
- `,e=document.createElement("style");e.id="deepspot-sdk-styles",e.textContent=p,document.head.appendChild(e)}catch(p){}}}function C(p){if(typeof p=="string"){const e=document.querySelector(p);if(!e)throw new Error(`Deepspot SDK: container "${p}" not found in DOM`);return e}return p}class K{constructor(e){if(!e.apiKey)throw new Error("Deepspot SDK: apiKey is required");if(!e.baseUrl)throw new Error("Deepspot SDK: baseUrl is required");this.apiClient=new A(e.baseUrl,e.apiKey),M()}async embedDashboard(e){var a,d,o,l,b;const t=C(e.container),r=(a=e.embedLevel)!=null?a:"dashboard",s=(d=e.theme)!=null?d:"light";t.style.height=e.height||"600px",t.style.display="block";const i=this.createRoot(t,s);this.showLoading(i);try{const c=await this.apiClient.getEmbedToken({dashboardId:e.dashboardId,embedType:"dashboard",embedLevel:r,userId:e.userId,tenantId:e.tenantId}),n=await this.apiClient.getDashboardRender(e.dashboardId,c,{embedLevel:r,pageId:e.pageId,tabId:e.tabId,filters:e.filters||{}});let h;const f=new O(i,{embedLevel:r,theme:s,hideFilters:(o=e.hideFilters)!=null?o:!1,hideExport:(l=e.hideExport)!=null?l:!1,initialFilters:e.filters||{},onFilterChange:e.onFilterChange,onReady:e.onReady,onFetchFilterOptions:g=>this.apiClient.getFilterOptions(e.dashboardId,g,c),onTabSwitch:async(g,m)=>{var u,y,k;(u=e.onTabSwitch)==null||u.call(e,g,m);try{const v=await this.apiClient.getDashboardRender(e.dashboardId,c,{embedLevel:r,pageId:g,tabId:m,filters:(k=(y=h==null?void 0:h.getActiveFilters())!=null?y:e.filters)!=null?k:{}});f.update(v)}catch(v){console.error("Deepspot SDK: tab fetch failed",v)}}});return f.render(n),h=new $({dashboardId:e.dashboardId,token:c,embedType:"dashboard",embedLevel:r,activePageId:n.activePage,activeTabId:n.activeTab,activeFilters:e.filters||{},apiClient:this.apiClient,renderer:f,onFilterChange:e.onFilterChange}),h}catch(c){throw this.showError(i,(c==null?void 0:c.message)||"Failed to load dashboard"),(b=e.onError)==null||b.call(e,(c==null?void 0:c.message)||"Failed to load dashboard"),c}}async embedReport(e){var s;const t=C(e.container);t.style.height=e.height||"400px",t.style.display="block";const r=this.createRoot(t,e.theme||"light");this.showLoading(r);try{const i=await this.apiClient.getEmbedToken({dashboardId:e.dashboardId,embedType:"report",componentId:e.componentId,userId:e.userId,tenantId:e.tenantId}),a=await this.apiClient.getReportRender(e.dashboardId,e.componentId,i,{filters:e.filters||{}}),d=new j(r,e.theme||"light");return d.render(a,e.onReady),new $({dashboardId:e.dashboardId,componentId:e.componentId,token:i,embedType:"report",activeFilters:e.filters||{},apiClient:this.apiClient,renderer:d})}catch(i){throw this.showError(r,(i==null?void 0:i.message)||"Failed to load report"),(s=e.onError)==null||s.call(e,(i==null?void 0:i.message)||"Failed to load report"),i}}createRoot(e,t){e.innerHTML="";const r=document.createElement("div");return r.className=`ds-embed-root ds-theme-${t}`,r.style.width="100%",r.style.height="100%",e.appendChild(r),r}showLoading(e){e.innerHTML=`
536
- <div class="ds-embed-loading">
537
- <div class="ds-embed-spinner"></div>
538
- <div class="ds-embed-loading-text">Loading…</div>
539
- </div>
540
- `}showError(e,t){e.innerHTML=`
541
- <div class="ds-embed-error">
542
- <div class="ds-embed-error-icon">⚠</div>
543
- <div>${t}</div>
544
- <div class="ds-embed-error-message">Check your SDK configuration.</div>
545
- </div>
546
- `}}exports.DeepspotSDK=K;