UNPKG

@iblai/iblai-web-mentor

Version:

IBL AI Mentor

3 lines (2 loc) 15.2 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const t=t=>{const e=document.createElement("div");return["script","noscript","style","nav","footer",".ads",".sidebar",".popup",".cookie-banner","#ibl-chat-widget-container",".ibl-chat-bubble","mentor-ai"].forEach((n=>{e.innerHTML=t;e.querySelectorAll(n).forEach((t=>t.remove()))})),e.innerHTML.replace(/\n/g,"")},e=new Blob(['\n const cleanElement = (htmlString) => {\n const selectorsToRemove = [\n "script",\n "noscript",\n "style",\n "nav",\n "footer",\n ".ads",\n ".sidebar",\n ".popup",\n ".cookie-banner",\n "#ibl-chat-widget-container",\n ".ibl-chat-bubble",\n "mentor-ai",\n "link",\n "meta",\n "iframe",\n ];\n\n let cleanedHTML = htmlString;\n \n // Remove HTML comments\n cleanedHTML = cleanedHTML.replace(/\x3c!--.*?--\x3e/gs, "");\n cleanedHTML = cleanedHTML.replace("\\n", "");\n // Remove elements by tag name\n selectorsToRemove\n .filter((selector) => !selector.startsWith(".") && !selector.startsWith("#"))\n .forEach((tag) => {\n const regex = new RegExp(`<${tag}[^>]*>.*?</${tag}>`, "gs");\n cleanedHTML = cleanedHTML.replace(regex, "");\n });\n\n // Remove elements by class or ID\n selectorsToRemove\n .filter((selector) => selector.startsWith(".") || selector.startsWith("#"))\n .forEach((attr) => {\n const attrType = attr.startsWith(".") ? "class" : "id";\n const attrName = attr.slice(1);\n\n // Remove elements with matching class or ID\n const regex = new RegExp(`<[^>]*\\s${attrType}=["\'][^"\']*\\b${attrName}\\b[^"\']*["\'][^>]*>.*?</[^>]+>`, "gs");\n cleanedHTML = cleanedHTML.replace(regex, "");\n\n // Remove attributes inside tags (e.g., `<div class="ads">` → `<div>`)\n const attrRegex = new RegExp(`\\s${attrType}=["\'][^"\']*\\b${attrName}\\b[^"\']*["\']`, "gs");\n cleanedHTML = cleanedHTML.replace(attrRegex, "");\n });\n\n // Remove newline characters and extra spaces\n return cleanedHTML.replace(/\\n/g, "").trim();\n };\n onmessage = function (event) {\n const htmlContent = event.data; // Get the HTML content from the main thread\n const cleanedContent = cleanElement(htmlContent); // Clean the content\n postMessage(cleanedContent); // Send the cleaned content back to the main thread\n }\n '],{type:"application/javascript"}),n=URL.createObjectURL(e);async function s(t){const e=await fetch(`${t}/api/ibl/users/manage/platform/`,{credentials:"include"});if(!e.ok)throw new Error("Network response was not ok");return await e.json()}async function o(t,e){const n=new FormData;n.append("platform_key",e);const s=await fetch(`${t}/api/ibl/manager/consolidated-token/proxy/`,{method:"POST",credentials:"include",body:n});if(!s.ok)throw new Error("Network response was not ok");return(await s.json()).data}class i extends HTMLElement{constructor(){super(),this.isEmbeddedMentorReady=!1,this.iblData="",this.lastUrl="",this.iframeContexts={};const t=new URL(window.location.href).searchParams.get("ibl-data");t&&(this.iblData=t),this.attachShadow({mode:"open"});this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n iframe {\n border: 0px white;\n height: 100%;\n width: 100%;\n border-radius: 0;\n }\n #ibl-chat-widget-container {\n /* border: 1px solid #dfdfdf; */\n height: 100%;\n position: relative;\n }\n @media screen and (max-width: 768px) {\n #ibl-chat-widget-container {\n\n }\n img.ibl-chat-bubble {\n right: 20px !important;\n }\n }\n .spinner {\n border: 3px solid #f3f3f3; /* Light grey */\n border-top: 3px solid #6cafe1; /* Blue */\n border-radius: 50%;\n width: 40px;\n height: 40px;\n animation: spin 1s linear infinite;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n display: block; /* Initially hidden */\n }\n\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div id="ibl-chat-widget-container">\n <div class="spinner" id="loading-spinner"></div>\n <iframe\n allow="clipboard-read; clipboard-write"\n onload="this.parentNode.querySelector(\'#loading-spinner\').style.display=\'none\';"\n onloadstart="this.parentNode.querySelector(\'#loading-spinner\').style.display=\'block\';"\n ></iframe>\n </div>\n ')}async onPostMessage(t){var e;let n=t.data;if("string"==typeof n)try{n=JSON.parse(n)}catch(t){return}if("context"===(null==n?void 0:n.type)){const e=t.origin;this.contextOrigins.includes(e)&&(this.iframeContexts[e]=n.data)}if((null==n?void 0:n.closeEmbed)&&window.parent.postMessage(JSON.stringify(n),"*"),null==n?void 0:n.height){const t=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("#ibl-chat-widget-container");t&&(t.style.height=`${n.height}px`)}if(!this.isAnonymous){if((null==n?void 0:n.loaded)&&(!n.auth.axd_token||!n.auth.dm_token||n.auth.tenant!==this.tenant||this.isTokenExpired(n.auth.dm_token_expires)||this.isTokenExpired(n.auth.axd_token_expires))){try{const t=await s(this.lmsUrl),e=t.find((t=>t.key===this.tenant));if(e){const n=await o(this.lmsUrl,e.key),s={axd_token:n.axd_token.token,axd_token_expires:n.axd_token.expires,userData:JSON.stringify(n.user),dm_token_expires:n.dm_token.expires,tenant:e.key,tenants:JSON.stringify(t),dm_token:n.dm_token.token};this.sendAuthDataToIframe(s)}}catch(t){}!this.iblData&&this.redirectToAuthSPA()}if((null==n?void 0:n.loaded)&&n.auth.userData)try{if(this.edxUserId&&this.edxUserId!=JSON.parse(n.auth.userData).user_id.toString())if(this.iblData)this.sendAuthDataToIframe(this.iblData);else try{const t=await s(this.lmsUrl),e=t.find((t=>t.key===this.tenant));if(e){const n=await o(this.lmsUrl,e.key),s={axd_token:n.axd_token.token,axd_token_expires:n.axd_token.expires,userData:JSON.stringify(n.user),dm_token_expires:n.dm_token.expires,tenant:e.key,tenants:JSON.stringify(t),dm_token:n.dm_token.token};this.sendAuthDataToIframe(s)}}catch(t){}}catch(t){console.error("Error parsing userData from auth:",t)}}(null==n?void 0:n.authExpired)?this.isAnonymous||(this.iblData?this.sendAuthDataToIframe(this.iblData):this.redirectToAuthSPA(!0)):(null==n?void 0:n.ready)&&(this.isEmbeddedMentorReady=!0,this.iblData?this.sendAuthDataToIframe(this.iblData):this.authRelyOnHost||this.isAnonymous||this.redirectToAuthSPA()),(null==n?void 0:n.loaded)&&(this.isEmbeddedMentorReady=!0,this.isContextAware&&this.sendHostInfoToIframe(),this.theme&&this.switchTheme(this.theme),this.documentFilter&&this.sendDocumentFilterToIframe(),this.edxUsageId&&this.sendDataToIframe({type:"MENTOR:EDX_USAGE_ID",data:{edxUsageId:this.edxUsageId}}),this.edxCourseId&&this.sendDataToIframe({type:"MENTOR:EDX_COURSE_ID",data:{edxCourseId:this.edxCourseId}}))}connectedCallback(){var t;if(this.iblData){const t=new URL(window.location.href);t.searchParams.delete("ibl-data"),window.history.replaceState({},document.title,t);const e=JSON.parse(this.iblData).userData;document.cookie=`userData=${e}; domain=${document.domain}; path=/;`}window.addEventListener("message",(t=>this.onPostMessage(t)));const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("iframe");e&&(e.onloadstart=()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("#loading-spinner");e&&(e.style.display="block")},e.onload=()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("#loading-spinner");e&&(e.style.display="none")})}disconnectedCallback(){window.removeEventListener("message",this.onPostMessage)}get mentorUrl(){return this.getAttribute("mentorurl")||"https://mentor.iblai.app"}set mentorUrl(t){this.setAttribute("mentorurl",t)}get authUrl(){return this.getAttribute("authurl")||"https://auth.iblai.app"}set authUrl(t){this.setAttribute("authurl",t)}get lmsUrl(){return this.getAttribute("lmsurl")||"https://learn.iblai.app"}set lmsUrl(t){this.setAttribute("lmsurl",t)}get theme(){return this.getAttribute("theme")||"light"}set theme(t){this.setAttribute("theme",t)}get tenant(){return this.getAttribute("tenant")}set tenant(t){this.setAttribute("tenant",t)}get extraParams(){return this.getAttribute("extraparams")}set extraParams(t){this.setAttribute("extraparams",t)}get contextOrigins(){var t;return(null===(t=this.getAttribute("contextorigins"))||void 0===t?void 0:t.split(","))||[]}set contextOrigins(t){this.setAttribute("contextorigins",t)}get mentor(){return this.getAttribute("mentor")}set mentor(t){this.setAttribute("mentor",t)}get edxUsageId(){return this.getAttribute("edxusageid")}set edxUsageId(t){this.setAttribute("edxusageid",t)}get edxCourseId(){return this.getAttribute("edxcourseid")}set edxCourseId(t){this.setAttribute("edxcourseid",t)}get edxUserId(){return this.getAttribute("edxuserid")}set edxUserId(t){this.setAttribute("edxuserid",t)}get authRelyOnHost(){return this.hasAttribute("authrelyonhost")}set authRelyOnHost(t){t?this.setAttribute("authrelyonhost",""):this.removeAttribute("authrelyonhost")}get isAnonymous(){return this.hasAttribute("isanonymous")}set isAnonymous(t){t?this.setAttribute("isanonymous",""):this.removeAttribute("isanonymous")}get isAdvanced(){return this.hasAttribute("isadvanced")}set isAdvanced(t){t?this.setAttribute("isadvanced",""):this.removeAttribute("isadvanced")}get isContextAware(){return this.hasAttribute("iscontextaware")}set isContextAware(t){t?this.setAttribute("iscontextaware",""):this.removeAttribute("iscontextaware")}get redirectToken(){return this.getAttribute("redirecttoken")}set redirectToken(t){this.setAttribute("redirecttoken",t)}get component(){return this.getAttribute("component")}set component(t){this.setAttribute("component",t)}get modal(){return this.getAttribute("modal")}set modal(t){this.setAttribute("modal",t)}get documentFilter(){return this.getAttribute("documentfilter")}set documentFilter(t){this.setAttribute("documentfilter",t)}static get observedAttributes(){return["mentorUrl","tenant","mentor","isadvanced","iscontextaware","contextOrigins","component","modal","extraparams","documentfilter"]}attributeChangedCallback(t,e,n){var s,o;if(["mentorUrl","tenant","mentor","isadvanced","component","modal","extraparams"].includes(t)){const t=null===(s=this.shadowRoot)||void 0===s?void 0:s.querySelector("iframe");this.shadowRoot&&t&&(t.src=`${this.mentorUrl}/platform/${this.tenant}${((t,e)=>{switch(t){case"analytics-overview":return`/${e}/analytics`;case"analytics-users":return`/${e}/analytics/users`;case"analytics-topics":return`/${e}/analytics/topics`;case"prompt-gallery":return`/${e}/prompt-gallery`;case"explore":return"/explore";default:return`/${e}`}})(this.component,this.mentor)}/${this.modal?this.modal:""}?embed=true&mode=anonymous&extra-body-classes=iframed-externally${this.isAdvanced?"&chat=advanced":""}${this.modal?"&modal="+this.modal:""}${o=this.component,o?["analytics-overview","analytics-users","analytics-topics","prompt-gallery","explore"].includes(null!=o?o:"")?`&hide_side_nav=true&hide_header=true&component=${o}`:"recent-messages"===o?`&hide_header=true&component=${o}`:`&component=${o}`:""}${this.extraParams?"&"+this.extraParams:""}`)}this.isContextAware&&(this.lastUrl=window.location.href,setInterval((()=>{this.isContextAware&&this.sendHostInfoToIframe()}),1e3)),this.documentFilter&&this.sendDocumentFilterToIframe(),"contextOrigins"===t&&(this.contextOrigins=(null==n?void 0:n.split(","))||[]),"theme"===t&&this.switchTheme(n)}getCleanBodyContent(){const e=document.body.cloneNode(!0);t(e.outerHTML);const n=t=>{for(let e=0;e<t.childNodes.length;e++){const s=t.childNodes[e];8===s.nodeType?(t.removeChild(s),e--):1===s.nodeType&&n(s)}};n(e);const s=Object.values(this.iframeContexts).map((e=>t(e)));return e.innerHTML+s.join("")}sendHostInfoToIframe(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("#ibl-chat-widget-container iframe");if(e&&e.contentWindow){const t=this.getCleanBodyContent(),n={type:"MENTOR:CONTEXT_UPDATE",hostInfo:{title:document.title,href:window.location.href},pageContent:t};e.contentWindow.postMessage(n,"*")}}sendDocumentFilterToIframe(){this.sendDataToIframe({type:"MENTOR:DOCUMENTFILTER",data:this.documentFilter})}sendDataToIframe(t){var e;const n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("#ibl-chat-widget-container iframe");n&&n.contentWindow&&n.contentWindow.postMessage(t,"*")}switchTheme(t){var e;const n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("#ibl-chat-widget-container iframe");n&&n.contentWindow&&n.contentWindow.postMessage(JSON.stringify({theme:t}),"*")}sendAuthDataToIframe(t){var e;const n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("#ibl-chat-widget-container iframe");n&&n.contentWindow&&n.contentWindow.postMessage(t,"*")}isTokenExpired(t){const e=new Date(t);return new Date>=e}redirectToAuthSPA(t){var e;if(this.authRelyOnHost){const t=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector("#ibl-chat-widget-container iframe");return void(t&&t.contentWindow&&t.contentWindow.postMessage(Object.assign({},localStorage),"*"))}const n=window.location.pathname+window.location.search;window.location.href=`${this.authUrl}/login?redirect-path=${n}&tenant=${this.tenant}${t?"&logout=true":""}&redirect-token=${this.redirectToken}`}toggleWidget(){const t=document.getElementById("ibl-chat-widget-container");t&&("none"===t.style.display?t.style.display="":t.style.display="none")}}"undefined"==typeof window||customElements.get("mentor-ai")||customElements.define("mentor-ai",i),exports.default=i,exports.proxyContextPostMessage=function(t,e){window.addEventListener("message",(n=>{if("context"===n.data.type)if(window.self!==window.top)window.parent.postMessage(n.data,t);else{const s=document.getElementById(t);if(s&&s.contentWindow){const t=e||"*";s.contentWindow.postMessage(n.data,t)}else console.log("Iframe not found or contentWindow is not accessible.")}}))},exports.sendHTMLContentToHost=function(t,e=5e3){const s=new Worker(n);s.onmessage=e=>{const n=e.data;window.parent.postMessage({type:"context",data:n},t)},setInterval((()=>{if(window.self!==window.top){const t=document.documentElement.outerHTML;s.postMessage(t)}}),e)},exports.sendHTMLContentToIframe=function(t,e,s=5e3){let o;const i=new Worker(n);let a=document.documentElement.outerHTML;i.onmessage=t=>{var e;const n=t.data;null===(e=null==o?void 0:o.contentWindow)||void 0===e||e.postMessage({type:"context",data:n},"*")},setInterval((()=>{o=t instanceof HTMLIFrameElement?t:document.getElementById(t),a=document.documentElement.outerHTML,o&&o.contentWindow?i.postMessage(a):console.log("Iframe not found or contentWindow is not accessible.")}),s)}; //# sourceMappingURL=iblai-web-mentor.cjs.js.map