@preset-sdk/embedded
Version:
Frontend SDK for embedding Preset data analytics into your own application
2 lines • 5.89 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.presetSdk=t():e.presetSdk=t()}(globalThis,(function(){return(()=>{"use strict";var e={d:(t,o)=>{for(var s in o)e.o(o,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:o[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{_initComms:()=>d,embedDashboard:()=>a});var o=function(e){return e.GET="get",e.REPLY="reply",e.EMIT="emit",e.ERROR="error",e}(o||{});class s{constructor(e){this.port=void 0,this.name="",this.methods={},this.incrementor=1,this.debugMode=void 0,this.isInitialised=void 0,e&&this.init(e)}init(e){if(this.isInitialised)return void this.logError("already initialized");const{port:t,name:s="switchboard",debug:i=!1}=e;this.port=t,this.name=s,this.debugMode=i,t.addEventListener("message",(async e=>{this.log("message received",e);const t=e.data;if(function(e){return e.switchboardAction===o.GET}(t))this.port.postMessage(await this.getMethodResult(t));else if(function(e){return e.switchboardAction===o.EMIT}(t)){const{method:e,args:o}=t,s=this.methods[e];s&&s(o)}})),this.isInitialised=!0}async getMethodResult({messageId:e,method:t,args:s}){const i=this.methods[t];if(null==i)return{switchboardAction:o.ERROR,messageId:e,error:`[${this.name}] Method "${t}" is not defined`};try{const t=await i(s);return{switchboardAction:o.REPLY,messageId:e,result:t}}catch(s){return this.logError(s),{switchboardAction:o.ERROR,messageId:e,error:`[${this.name}] Method "${t}" threw an error`}}}defineMethod(e,t){this.methods[e]=t}get(e,t){return new Promise(((s,i)=>{if(!this.isInitialised)return void i(new Error("Switchboard not initialised"));const r=this.getNewMessageId(),n=e=>{const t=e.data;if(t.messageId===r)if(this.port.removeEventListener("message",n),function(e){return e.switchboardAction===o.REPLY}(t))s(t.result);else{const e=function(e){return e.switchboardAction===o.ERROR}(t)?t.error:"Unexpected response message";i(new Error(e))}};this.port.addEventListener("message",n),this.port.start();const a={switchboardAction:o.GET,method:e,messageId:r,args:t};this.port.postMessage(a)}))}emit(e,t){if(!this.isInitialised)return void this.logError("Switchboard not initialised");const s={switchboardAction:o.EMIT,method:e,args:t};this.port.postMessage(s)}start(){this.isInitialised?this.port.start():this.logError("Switchboard not initialised")}log(...e){this.debugMode&&console.debug(`[${this.name}]`,...e)}logError(...e){console.error(`[${this.name}]`,...e)}getNewMessageId(){return`m_${this.name}_${this.incrementor++}`}}new s;const i="__embedded_comms__",r={visible:"show_filters",expanded:"expand_filters"};function n(e){const t=JSON.parse(atob(e.split(".")[1]).toString()),o=new Date(/[^0-9\.]/g.test(t.exp)?t.exp:1e3*parseFloat(t.exp));return("Invalid Date"!==o.toString()?Math.max(1e4,o.getTime()-Date.now()):3e5)-5e3}async function a(e){let{id:t,supersetDomain:o,mountPoint:s,fetchGuestToken:i,dashboardUiConfig:a,debug:h=!1,iframeTitle:c="Embedded Dashboard",iframeSandboxExtras:l=[],referrerPolicy:m}=e;function g(){if(h){for(var e=arguments.length,o=new Array(e),s=0;s<e;s++)o[s]=arguments[s];console.debug(`[preset-frontend-sdk][dashboard ${t}]`,...o)}}var u;function f(){let e=0;return a&&(a.hideTitle&&(e+=1),a.hideTab&&(e+=2),a.hideChartControls&&(e+=8),a.emitDataMasks&&(e+=16),a.showRowLimitWarning&&(e+=32)),e}g("embedding"),(u=Element.prototype).hasOwnProperty("replaceChildren")||Object.defineProperty(u,"replaceChildren",{configurable:!0,enumerable:!0,value:function(){for(;this.firstChild;)this.removeChild(this.firstChild);for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];t.forEach((e=>{this.appendChild("string"==typeof e?document.createTextNode(e):e)}))}}),o.endsWith("/")&&(o=o.slice(0,-1));const[p,b]=await Promise.all([i(),async function(){return new Promise((e=>{const i=document.createElement("iframe"),n=a?{uiConfig:`${f()}`}:void 0,u=a?.filters||{},p=Object.keys(u),b={...n,...Object.fromEntries(p.map((e=>[r[e],u[e]]))),...a?.urlParams},w=Object.keys(b).length?"?"+new URLSearchParams(b).toString():"";i.sandbox.add("allow-same-origin"),i.sandbox.add("allow-scripts"),i.sandbox.add("allow-presentation"),i.sandbox.add("allow-downloads"),i.sandbox.add("allow-top-navigation"),i.sandbox.add("allow-forms"),i.sandbox.add("allow-popups"),l.forEach((e=>{i.sandbox.add(e)})),m&&(i.referrerPolicy=m),i.addEventListener("load",(()=>{const t=d(i.contentWindow,o,h);g("sent message channel to the iframe"),e(t)})),i.src=`${o}/embedded/${t}${w}`,i.title=c,s?.replaceChildren(i),g("placed the iframe")}))}()]);let w;return b.emit("guestToken",{guestToken:p}),g("sent guest token"),w=setTimeout((async function e(){const t=await i();b.emit("guestToken",{guestToken:t}),w=setTimeout(e,n(t))}),n(p)),{getScrollSize:()=>b.get("getScrollSize"),unmount:function(){g("unmounting"),s?.replaceChildren(),clearTimeout(w)},getDashboardPermalink:e=>b.get("getDashboardPermalink",{anchor:e}),getActiveTabs:()=>b.get("getActiveTabs"),observeDataMask:e=>{b.start(),b.defineMethod("observeDataMask",e)},getDataMask:()=>b.get("getDataMask"),setThemeConfig:async e=>{try{b.emit("setThemeConfig",{themeConfig:e}),g("Theme config sent successfully (or at least message dispatched)")}catch(e){throw g('Error sending theme config. Ensure the iframe side implements the "setThemeConfig" method.'),e}}}}function d(e,t){let o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=new MessageChannel,n=r.port1,a=r.port2;return e.postMessage({type:i,handshake:"port transfer"},t,[a]),new s({port:n,name:"preset-frontend-sdk",debug:o})}return t})()}));
//# sourceMappingURL=index.js.map