From 35c071e0c5fb0e98c9f80e99f6501d01e0bcc6f8 Mon Sep 17 00:00:00 2001 From: Felix Razykov Date: Tue, 25 Oct 2022 13:32:30 +0300 Subject: [PATCH] [semver:patch] Expect getting message that is not string --- dist/development/strigo.sdk.js | 6 +++--- dist/production/strigo.sdk.min.js | 4 ++-- src/modules/document/document.ts | 4 ++-- src/modules/listeners/listeners.ts | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dist/development/strigo.sdk.js b/dist/development/strigo.sdk.js index 4995174..71a9156 100644 --- a/dist/development/strigo.sdk.js +++ b/dist/development/strigo.sdk.js @@ -11470,9 +11470,9 @@ ${JSON.stringify(parsedContext)}` : ""); } function removeLoader() { const loader = document.getElementById("loader"); - loader.remove(); + loader?.remove(); const academyHatIcon = document.getElementById("strigo-academy-hat-icon"); - academyHatIcon.classList.remove("loader"); + academyHatIcon?.classList.remove("loader"); } function openWidget() { const widget = document.getElementById("strigo-widget"); @@ -13363,7 +13363,7 @@ ${JSON.stringify(parsedContext)}` : ""); if (!message) { return; } - if (message.startsWith("url-triggered" /* URL_TRIGGERED */)) { + if (message.startsWith?.("url-triggered" /* URL_TRIGGERED */)) { const urlTriggeredCourses = getSessionValue("urlTriggeredCourses") || []; const selectedCourseId = message.split("/")[1]; LoggerInstance.info("URL trigger message received", { selectedCourseId, urlTriggeredCourses }); diff --git a/dist/production/strigo.sdk.min.js b/dist/production/strigo.sdk.min.js index 0b16c9e..7d316db 100644 --- a/dist/production/strigo.sdk.min.js +++ b/dist/production/strigo.sdk.min.js @@ -12,7 +12,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho `,Wt="https://cdn.statically.io/gh/strigo/strigo-sdk";var rl="https://assessment-recorder.web.app",Ho="http://local.strigo.io:3000",nl="http://local-preview.strigo.io:3000";var ol="v1.1.40";var Yi="strigoAssessmentUuid",il="strigoAssessmentRecorder";var Ka="strigoChildIframe";function Pg(h){let B={};for(let[Q,y]of h)B[Q]=y;return B}function Ng(h){let Q=new URLSearchParams(h).entries();return Pg(Q)}function al(){let{host:h,pathname:B,href:Q,origin:y,search:b}=window.location;return{host:h,pathName:B,href:Q,origin:y,search:b,params:Ng(b)}}function ji(h,B){let{subDomain:Q,user:y,webApiKey:b}=h,U=B?nl:Ho,K=B?`https://academy-preview.${Da}`:`https://${Q}.${Da}`,W=window.Strigo.isDevelopment()?U:K,$=new URL(`${W}/academy/courses`);return $.searchParams.set("token",y.token.token),$.searchParams.set("webApiKey",b),$.toString()}function cl(h){let B=new URL(h);return B.searchParams.set(Ka,"true"),B.toString()}function ll(){return window.location.search.includes(Ka)}function ul(){let h=new URL(window.location.href),B=new URLSearchParams(h.search);B.delete(Ka),h.search=B.toString(),window.history.replaceState(window.history.state,"",h)}function fl(){let h=document.getElementById(Al);return{webApiKey:h?.getAttribute("data-web-api-key")||"",subDomain:h?.getAttribute("data-subdomain")||"",selectedWidgetFlavor:h?.getAttribute("data-layout-flavor")||"dynamic"}}function gl(h){return window.Strigo.isDevelopment()?`${SDK_LOCAL_URL}/styles/strigo.css`:h?`${Wt}@${h}/dist/production/styles/strigo.min.css`:`${Wt}@master/dist/production/styles/strigo.min.css`}function dl(h){return window.Strigo.isDevelopment()?`${SDK_LOCAL_URL}/styles/strigo-widget.css`:h?`${Wt}@${h}/dist/production/styles/strigo-widget.min.css`:`${Wt}@master/dist/production/styles/strigo-widget.min.css`}function zi(h){return window.Strigo.isDevelopment()?`${SDK_LOCAL_URL}/styles/strigo-academy-hat.css`:h?`${Wt}@${h}/dist/production/styles/strigo-academy-hat.min.css`:`${Wt}@master/dist/production/styles/strigo-academy-hat.min.css`}function Bl(h){return window.Strigo.isDevelopment()?`${SDK_LOCAL_URL}/styles/strigo-assessment-recorder.css`:h?`${Wt}@${h}/dist/production/styles/strigo-assessment-recorder.min.css`:`${Wt}@${ol}/dist/production/styles/strigo-assessment-recorder.min.css`}function pl(){return window.Strigo.isDevelopment()?RECORDER_LOCAL_URL:rl}function Zi(h){let B=new URL(h),Q=new URLSearchParams(B.search);return Q.delete(Yi),Q.delete(il),B.search=Q.toString(),B.toString()}var hl=class{constructor(B){this.url=B?.url}setup(B){this.url=B.url}logToRemote(B,Q,y){return fetch(this.url,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({level:B,message:Q,context:y})}).then(b=>{b.ok||console.warn("Logging to Strigo failed",{result:b})}).catch(b=>{console.warn("Logging to Strigo failed",{err:b})})}logToConsole(B,Q,y){let b=`${new Date().toISOString()} - ${Q}`,U=y.err instanceof Error?{...y,err:{message:y.err.message,name:y.err.name,stack:y.err.stack}}:y;console[B](b,y?` ${JSON.stringify(U)}`:"")}getDefaultContext(){let B=te();if(!B)return{};let{user:Q,subDomain:y,initSite:b,version:U,selectedWidgetFlavor:K}=B;return{token:Q?.token.token,initSite:b?.href,subDomain:y,development:window.Strigo.isDevelopment(),version:U,selectedWidgetFlavor:K}}log(B,Q,y){let b={...this.getDefaultContext(),...y};try{this.url&&window.Strigo.isDevelopment()&&this.logToRemote(B,Q,b),this.logToConsole(B,`Academy - ${Q}`,b)}catch(U){console.log("Logging error:",{err:U})}}debug(B,Q={}){this.log("debug",B,Q)}info(B,Q={}){this.log("info",B,Q)}warn(B,Q={}){this.log("warn",B,Q)}error(B,Q={}){this.log("error",B,Q)}},T=new hl;function xo(h,B){try{return JSON.parse(window[h].getItem(B))}catch(Q){return T.error("get storage data error",{err:Q}),null}}function To(h,B,Q){try{return window[h].setItem(B,JSON.stringify(Q)),Q}catch(y){return T.error("setup storage error",{err:y}),null}}function qi(h,B,Q,y){try{let b=xo(h,B);if(!b)throw new Error("Can't find initial state");let U={...b,[Q]:y};return window[h].setItem(B,JSON.stringify(U)),U}catch(b){return T.error("set storage value error",{err:b}),null}}function $i(h,B){try{window[h].removeItem(B)}catch(Q){T.error("clear storage error",{err:Q})}}function te(){return xo("localStorage","strigoConfig")}function wl(h){let B=te();return To("localStorage","strigoConfig",{...B,...h})}function vl(h){let B=te();return To("localStorage","strigoConfig",{...B,...h})}function ml(h,B){return qi("localStorage","strigoConfig",h,B)}function pr(h){return te()?.[h]}function Ql(){$i("localStorage","strigoConfig")}async function Cl(h){try{let B=window.Strigo.isDevelopment()?Ho:"https://app.strigo.io",Q=await fetch(`${B}/api/internal/academy/v1/config?domain=${window.location.hostname}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.token}`}});if(!Q.ok)throw new Error(`Failed to fetch remote configuration: ${Q.statusText}`);return(await Q.json()).data}catch(B){return T.warn("Error fetching configuration from Strigo",{err:B}),null}}async function Ul(h,B){try{T.info("Sending success event to strigo",{eventName:B});let Q=window.Strigo.isDevelopment()?Ho:"https://app.strigo.io",y=await fetch(`${Q}/api/internal/academy/v1/success-event`,{method:"POST",body:JSON.stringify({eventName:B}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.token}`}});if(!y.ok)throw new Error(`Failed sending success event to Strigo: ${y.statusText}`);let b=await y.json();T.info("Success event Response",{successEventResponse:b})}catch(Q){return T.warn("Error sending success event to Strigo",{err:Q}),null}}function yl(h){return To("sessionStorage","strigoSession",h)}function As(){return xo("sessionStorage","strigoSession")}function Pn(){return As()?As().shouldPanelBeOpen:!0}function Nn(){return As()?.widgetFlavor}function Jt(h,B){return qi("sessionStorage","strigoSession",h,B)}function Zr(h){return As()?.[h]}function Fl(){$i("sessionStorage","strigoSession")}function Pa(){try{return JSON.parse(window["localStorage"].getItem("strigoAssessments"))}catch(h){return T.error("Get assessments storage error",{error:h}),null}}function El(){try{let h=Pa();if(h)return T.debug("Assessments storage already exists"),h;let B={assessments:[]};return window["localStorage"].setItem("strigoAssessments",JSON.stringify(B)),B}catch(h){return T.error("Init assessments storage error",{error:h}),null}}function bl(h){try{let B=h?{assessments:[...h]}:{assessments:[]};return window["localStorage"].setItem("strigoAssessments",JSON.stringify(B)),B}catch(B){return T.error("Assessments storage setup error",{error:B}),null}}function Il(){try{window["localStorage"].removeItem("strigoAssessments")}catch(h){T.error("Clear assessments storage error",{error:h})}}var Xl=So(Sl(),1);function Lo(){return window.top}function hr(){return document.getElementsByTagName("head")[0]}function Hl(){document.open(),document.close()}function xl(){let h=document.createElement("div");return h.className="strigo-main",document.body.appendChild(h),h}function wr(h){let{url:B,parentElement:Q}=h,y=document.createElement("link");y.rel="stylesheet",y.href=B,Q.appendChild(y)}function Oo(h){let{url:B,parentElement:Q,classNames:y,id:b}=h,U=document.createElement("iframe");return U.classList.add(...y),U.id=b,U.src=B,Q.appendChild(U),U}function Tl(){location.reload()}function Ll(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function ts(){return Ll()?[window.screen.width,window.screen.width]:[window.screen.width/2,window.screen.width]}function Ol(){return Ll()?[0,0]:[window.screen.width*.25,0]}function Dl(){let h=new XMLHttpRequest;h.open("GET",window.document.location.href,!1),h.send(null);let Q=h.getAllResponseHeaders().toLowerCase().split(`\r -`);for(let y of Q)if(y.includes("x-frame-options")){let b=y.split(":");if(b&&b.length>1)return b[1].trim()!=="deny"}return!0}function Kl(){let h=document.getElementById("strigo-widget"),B=document.getElementById("strigo-collapse-div"),Q=document.getElementById("strigo-academy-hat");h.classList.toggle("align-left"),B.classList.toggle("align-left"),Q.classList.toggle("align-left");let y=h.classList.contains("align-left")?"left":"right",b=document.getElementById("strigo-exercises");ml("dockingSide",y),b.contentWindow.postMessage({dockingSide:y},"*")}function Ml(h){h.document.getElementById("strigo-widget").remove()}function Rl(){document.getElementById("loader").remove(),document.getElementById("strigo-academy-hat-icon").classList.remove("loader")}function Gn(){let h=document.getElementById("strigo-widget");h.classList.add("slide-in"),h.classList.add("loaded"),document.getElementById("strigo-collapse-div").classList.remove("slide-in"),document.getElementById("strigo-academy-hat").classList.remove("slide-in")}function ka(){let h=document.getElementById("strigo-widget");h.classList.remove("slide-in"),h.classList.remove("loaded"),document.getElementById("strigo-collapse-div").classList.add("slide-in"),document.getElementById("strigo-academy-hat").classList.add("slide-in")}function _l(){Jt("shouldPanelBeOpen",!1),ka()}var Vg=function(h){if(h.filter(Q=>["HTML","BODY"].includes(Q.target.nodeName)).length>0){if(window.document.getElementById("strigo-widget")){T.info("*** Strigo widget already exist on the DOM.");return}T.info("*** Reloading widget in navigation observer"),setTimeout(window.Strigo.open.bind(window.Strigo),0)}};function Xg(){let B=!Pn();Jt("shouldPanelBeOpen",B),B?Gn():ka()}function Pl(h){let B=Pn(),Q=pr("dockingSide"),y=document.createElement("div");y.className="strigo-academy-hat",y.id="strigo-academy-hat",y.onclick=()=>{Xg()};let b=document.createElement("div");b.className="strigo-academy-hat-icon loader",b.id="strigo-academy-hat-icon",b.innerHTML=Ji,y.appendChild(b);let U=document.createElement("div");U.className="loader",U.id="loader",y.appendChild(U);let K=document.createElement("div");K.className="strigo-collapse-div",K.id="strigo-collapse-div";let W=document.createElement("iframe");W.className="strigo-iframe",W.id="strigo-exercises",W.src=h;let $=document.createElement("div");return $.id="strigo-widget",$.appendChild(K),$.appendChild(W),Q==="left"&&($.classList.add("align-left"),K.classList.add("align-left"),y.classList.add("align-left")),document.body.appendChild($),document.body.appendChild(y),B?Gn():ka(),W}function Nl(h){h.strigoNavigationObserver={observer:new MutationObserver(Vg)};let B={childList:!0,subtree:!0};h?.strigoNavigationObserver?.observer?.observe(h.document,B)}function Gl(h){let{primaryColor:B,primaryHoverColor:Q,primaryTextAccent:y}=h,b=document.querySelector(":root");b.style.setProperty("--customizable-hat-bg-color",B),b.style.setProperty("--customizable-hat-bg-hover-color",Q),b.style.setProperty("--customizable-hat-text-color",y==="dark"?"#000000":"#FFFFFF")}function Va(){var h;(function(M){M[M.All=0]="All",M[M.Two=1]="Two",M[M.One=2]="One"})(h||(h={}));let B,Q;function y(M,tA){if(M.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(M.tagName.toLowerCase()==="html")return"html";let Y={root:document.body,idName:V=>!0,className:V=>!0,tagName:V=>!0,attr:(V,FA)=>!1,seedMinLength:1,buildNodeTreeUpToRoot:!1,maxNumberOfTries:2e3};B=Object.assign(Object.assign({},Y),tA),Q=yA(B.root,Y);let aA=CA(M),UA=AA(M);return{nodeTree:aA,recordedElementInfo:UA}}function b(M){let tA=M[0],Y=tA.name;for(let aA=1;aA ${Y}`:Y=`${M[aA].name} ${Y}`,tA=M[aA];return Y}function U(M,tA){let Y=M.parent,aA=[];for(aA.push(tA),M.path&&aA.push(M.path);Y?.path;)aA.push(Y.path),Y=Y.parent;return b(aA)}function K(M,tA){let Y=M.sort((JA,vA)=>vA.level-JA.level),aA={path:null,children:[],parent:null,level:-1},UA=[],V=new Set,FA=null,wA=0;for(UA.push(aA),V.add(aA);UA.length>0&&Y[wA];){let JA=UA.pop(),{nodeIdentifiers:vA}=Y[wA],VA=$(vA,wA),k=[];for(let D of VA){let X=U(JA,D),iA=document.querySelectorAll(X).length;if(iA!==0){if(iA===1){k.splice(0,k.length),k.push({path:D,children:[],parent:JA,level:wA}),FA=X;break}k.push({path:D,children:[],parent:JA,level:wA})}}if(k.length===0)return;JA.children.push(...k),JA.children.filter(D=>!V.has(D)).forEach(D=>{V.add(D),UA.push(D)}),wA=wA+1}return FA}function W(M,tA){let Y={root:document.body,idName:aA=>!0,className:aA=>!0,tagName:aA=>!0,attr:(aA,UA)=>!1,optimizedMinLength:6,maxNumberOfTries:2e3,fallbackNodeTree:M};return B=Object.assign(Object.assign({},Y),tA),Q=yA(B.root,Y),K(M,Q)}function $(M,tA){let Y=G(M.find(vA=>vA.identifier==="id")),aA=G(...M.filter(vA=>vA.identifier==="attribute")),UA=G(...M.filter(vA=>vA.identifier==="className")),V=G(...M.filter(vA=>vA.identifier==="tagName")),FA=M.filter(vA=>vA.identifier==="index"&&vA.identifier.outOf!=="1")?.[0]?.index,wA=[...Y||[],...aA||[],...UA||[],...V||[]];return FA&&(wA=wA.concat(wA.filter(Ue).map(vA=>OA(vA,FA)))),(wA?ye(WA([wA])):null).map(([vA])=>({...vA,level:tA}))}function yA(M,tA){return M.nodeType===Node.DOCUMENT_NODE?M:M===tA.root?M.ownerDocument:M}function AA(M){let tA=Array.from(M.childNodes).reduce((FA,wA)=>(wA.nodeType===3&&FA.push(wA.nodeValue),FA),[]).join(""),Y=Array.from(M.childNodes).map(FA=>{let wA=FA.nodeName.toLowerCase();return{classes:FA.classList?Array.from(FA.classList):[],nodeName:wA}}),aA=M.classList?Array.from(M.classList):[],UA=M.tagName.toLowerCase(),V=Zi(window.location.href);return{tagName:UA,classes:aA,internalStructure:Y,directInnerText:tA,url:V}}function CA(M){let tA=[],Y=M,aA=0;for(;Y&&Y!==B.root.parentElement;){let UA=[G(ce(Y)),G(ue(Y)),G(...fA(Y)),G(...NA(Y)),G(GA(Y))].filter(zA).flat().sort((V,FA)=>V.penalty-FA.penalty);tA.push({nodeIdentifiers:UA,level:aA}),Y=Y.parentElement,aA++}return tA}function TA(M){return M.map(tA=>tA.penalty).reduce((tA,Y)=>tA+Y,0)}function BA(M){switch(Q.querySelectorAll(b(M)).length){case 0:throw new Error(`Can't select any node with this selector: ${b(M)}`);case 1:return!0;default:return!1}}function ce(M){M?.getAttribute||alert(JSON.stringify(M));let tA=M.getAttribute("id");return tA&&B.idName(tA)?{name:"#"+_e(tA,{isIdentifier:!0}),penalty:0,identifier:"id"}:null}function fA(M){return Array.from(M.attributes).filter(Y=>B.attr(Y.name,Y.value)).map(Y=>({name:"["+_e(Y.name,{isIdentifier:!0})+'="'+_e(Y.value)+'"]',penalty:.5,identifier:"attribute"}))}function NA(M){return Array.from(M.classList).filter(B.className).map(Y=>({name:"."+_e(Y,{isIdentifier:!0}),penalty:1,identifier:"className"}))}function ue(M){let tA=M.tagName.toLowerCase();return B.tagName(tA)?{name:tA,penalty:2,identifier:"tagName"}:null}function Ut(){return{name:"*",penalty:3,identifier:"any"}}function GA(M){let tA=M.parentNode;if(!tA)return null;let Y=tA.firstChild;if(!Y)return null;let aA=0;for(;Y&&(Y.nodeType===Node.ELEMENT_NODE&&aA++,Y!==M);)Y=Y.nextSibling;return{index:aA,outOf:tA.childElementCount,penalty:4,identifier:"index"}}function OA(M,tA){return{name:M.name+`:nth-child(${tA})`,penalty:M.penalty+1}}function Ue(M){return M.name!=="html"&&!M.name.startsWith("#")&&!B.allowDuplicates}function G(...M){let tA=M.filter(zA);return tA.length>0?tA:null}function zA(M){return M!=null}function*WA(M,tA=[]){if(M.length>0)for(let Y of M[0])yield*WA(M.slice(1,M.length),tA.concat(Y));else yield tA}function ye(M){return Array.from(M).sort((tA,Y)=>TA(tA)-TA(Y))}function*ut(M,tA,Y={counter:0,visited:new Map}){if(M.length>2&&M.length>B.optimizedMinLength)for(let aA=1;aAB.maxNumberOfTries){console.log(`*** Selector optimization exhausted. Exceeded max number of tries - ${B.maxNumberOfTries}`);return}Y.counter+=1;let UA=[...M];UA.splice(aA,1);let V=b(UA);if(Y.visited.has(V))return;BA(UA)&&yt(UA,tA)&&(yield UA,Y.visited.set(V,!0),yield*ut(UA,tA,Y))}}function yt(M,tA){return Q.querySelector(b(M))===tA}let jt=/[ -,\.\/:-@\[-\^`\{-~]/,eA=/[ -,\.\/:-@\[\]\^`\{-~]/,HA=/(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g,Re={escapeEverything:!1,isIdentifier:!1,quotes:"single",wrap:!1};function _e(M,tA={}){let Y=Object.assign(Object.assign({},Re),tA);Y.quotes!="single"&&Y.quotes!="double"&&(Y.quotes="single");let aA=Y.quotes=="double"?'"':"'",UA=Y.isIdentifier,V=M.charAt(0),FA="",wA=0,JA=M.length;for(;wA126){if(VA>=55296&&VA<=56319&&wAK===B},{nodeTree:b,recordedElementInfo:U}=Q.getElementProfileNodeTree(h.target,y);return console.log("*** Just FYI - this is how it can generate css selector:",Q.generateSelectorFromNodeTree(b,y)),{nodeTree:b,recordedElementInfo:U}}function Do(h,B){let Q=Va(),b={...{allowDuplicates:!1,optimizedMinLength:10,threshold:1e3,attr:K=>K===dataAttribute,fallbackNodeTree:h},...B};return Q.generateSelectorFromNodeTree(h,b)}function Vl(h,B){this.removeOverlayElement=()=>{console.log("Removing mouse over event listener from the selected element."),h.removeEventListener("mouseover",this.mouseOverEvent);let b=h.getElementById("element-selector-overlay");b&&h?.body?.removeChild(b)},this.saveSelectedSelector=b=>{b.preventDefault(),b.stopPropagation(),this.removeOverlayElement();let U=Wg(b,{dataAttribute:"some-custom-strigo-attribute"});U=U||{},console.log("Selected element with elementProfile:",U),B.onElementProfileCreated(U)};function Q(b,U){for(let K in U)b.style[K]=U[K]}let y=(b,U,K=[])=>{if(U===b.target)return;let W=b.target;if(K.includes(W.id))return;let $=W.offsetWidth+2,yA=W.offsetHeight+2;function AA(BA){let ce=0,fA=0;for(;BA&&!isNaN(BA.offsetLeft)&&!isNaN(BA.offsetTop);)ce+=BA.offsetLeft-BA.scrollLeft,fA+=BA.offsetTop-BA.scrollTop,BA=BA.offsetParent;return{top:fA-window.scrollY,left:ce-window.scrollX}}let CA=AA(W),TA={top:CA.top-2+"px",left:CA.left-2+"px",width:$+"px",height:yA+"px"};Q(U,TA)};return this.mouseOverEvent=b=>{let U=window.document.getElementById("element-selector-overlay");y(b,U,["element-selector-overlay","strigo-assessment-recorder-iframe"]),b.target.addEventListener("click",this.saveSelectedSelector)},this.removeClickListenerFromHoveredElement=b=>{b.target.removeEventListener("click",this.saveSelectedSelector)},this.startElementSelector=()=>{let b=h.createElement("div");b.setAttribute("id","element-selector-overlay"),b.setAttribute("id","element-selector-overlay"),b.setAttribute("style",` +`);for(let y of Q)if(y.includes("x-frame-options")){let b=y.split(":");if(b&&b.length>1)return b[1].trim()!=="deny"}return!0}function Kl(){let h=document.getElementById("strigo-widget"),B=document.getElementById("strigo-collapse-div"),Q=document.getElementById("strigo-academy-hat");h.classList.toggle("align-left"),B.classList.toggle("align-left"),Q.classList.toggle("align-left");let y=h.classList.contains("align-left")?"left":"right",b=document.getElementById("strigo-exercises");ml("dockingSide",y),b.contentWindow.postMessage({dockingSide:y},"*")}function Ml(h){h.document.getElementById("strigo-widget").remove()}function Rl(){document.getElementById("loader")?.remove(),document.getElementById("strigo-academy-hat-icon")?.classList.remove("loader")}function Gn(){let h=document.getElementById("strigo-widget");h.classList.add("slide-in"),h.classList.add("loaded"),document.getElementById("strigo-collapse-div").classList.remove("slide-in"),document.getElementById("strigo-academy-hat").classList.remove("slide-in")}function ka(){let h=document.getElementById("strigo-widget");h.classList.remove("slide-in"),h.classList.remove("loaded"),document.getElementById("strigo-collapse-div").classList.add("slide-in"),document.getElementById("strigo-academy-hat").classList.add("slide-in")}function _l(){Jt("shouldPanelBeOpen",!1),ka()}var Vg=function(h){if(h.filter(Q=>["HTML","BODY"].includes(Q.target.nodeName)).length>0){if(window.document.getElementById("strigo-widget")){T.info("*** Strigo widget already exist on the DOM.");return}T.info("*** Reloading widget in navigation observer"),setTimeout(window.Strigo.open.bind(window.Strigo),0)}};function Xg(){let B=!Pn();Jt("shouldPanelBeOpen",B),B?Gn():ka()}function Pl(h){let B=Pn(),Q=pr("dockingSide"),y=document.createElement("div");y.className="strigo-academy-hat",y.id="strigo-academy-hat",y.onclick=()=>{Xg()};let b=document.createElement("div");b.className="strigo-academy-hat-icon loader",b.id="strigo-academy-hat-icon",b.innerHTML=Ji,y.appendChild(b);let U=document.createElement("div");U.className="loader",U.id="loader",y.appendChild(U);let K=document.createElement("div");K.className="strigo-collapse-div",K.id="strigo-collapse-div";let W=document.createElement("iframe");W.className="strigo-iframe",W.id="strigo-exercises",W.src=h;let $=document.createElement("div");return $.id="strigo-widget",$.appendChild(K),$.appendChild(W),Q==="left"&&($.classList.add("align-left"),K.classList.add("align-left"),y.classList.add("align-left")),document.body.appendChild($),document.body.appendChild(y),B?Gn():ka(),W}function Nl(h){h.strigoNavigationObserver={observer:new MutationObserver(Vg)};let B={childList:!0,subtree:!0};h?.strigoNavigationObserver?.observer?.observe(h.document,B)}function Gl(h){let{primaryColor:B,primaryHoverColor:Q,primaryTextAccent:y}=h,b=document.querySelector(":root");b.style.setProperty("--customizable-hat-bg-color",B),b.style.setProperty("--customizable-hat-bg-hover-color",Q),b.style.setProperty("--customizable-hat-text-color",y==="dark"?"#000000":"#FFFFFF")}function Va(){var h;(function(M){M[M.All=0]="All",M[M.Two=1]="Two",M[M.One=2]="One"})(h||(h={}));let B,Q;function y(M,tA){if(M.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(M.tagName.toLowerCase()==="html")return"html";let Y={root:document.body,idName:V=>!0,className:V=>!0,tagName:V=>!0,attr:(V,FA)=>!1,seedMinLength:1,buildNodeTreeUpToRoot:!1,maxNumberOfTries:2e3};B=Object.assign(Object.assign({},Y),tA),Q=yA(B.root,Y);let aA=CA(M),UA=AA(M);return{nodeTree:aA,recordedElementInfo:UA}}function b(M){let tA=M[0],Y=tA.name;for(let aA=1;aA ${Y}`:Y=`${M[aA].name} ${Y}`,tA=M[aA];return Y}function U(M,tA){let Y=M.parent,aA=[];for(aA.push(tA),M.path&&aA.push(M.path);Y?.path;)aA.push(Y.path),Y=Y.parent;return b(aA)}function K(M,tA){let Y=M.sort((JA,vA)=>vA.level-JA.level),aA={path:null,children:[],parent:null,level:-1},UA=[],V=new Set,FA=null,wA=0;for(UA.push(aA),V.add(aA);UA.length>0&&Y[wA];){let JA=UA.pop(),{nodeIdentifiers:vA}=Y[wA],VA=$(vA,wA),k=[];for(let D of VA){let X=U(JA,D),iA=document.querySelectorAll(X).length;if(iA!==0){if(iA===1){k.splice(0,k.length),k.push({path:D,children:[],parent:JA,level:wA}),FA=X;break}k.push({path:D,children:[],parent:JA,level:wA})}}if(k.length===0)return;JA.children.push(...k),JA.children.filter(D=>!V.has(D)).forEach(D=>{V.add(D),UA.push(D)}),wA=wA+1}return FA}function W(M,tA){let Y={root:document.body,idName:aA=>!0,className:aA=>!0,tagName:aA=>!0,attr:(aA,UA)=>!1,optimizedMinLength:6,maxNumberOfTries:2e3,fallbackNodeTree:M};return B=Object.assign(Object.assign({},Y),tA),Q=yA(B.root,Y),K(M,Q)}function $(M,tA){let Y=G(M.find(vA=>vA.identifier==="id")),aA=G(...M.filter(vA=>vA.identifier==="attribute")),UA=G(...M.filter(vA=>vA.identifier==="className")),V=G(...M.filter(vA=>vA.identifier==="tagName")),FA=M.filter(vA=>vA.identifier==="index"&&vA.identifier.outOf!=="1")?.[0]?.index,wA=[...Y||[],...aA||[],...UA||[],...V||[]];return FA&&(wA=wA.concat(wA.filter(Ue).map(vA=>OA(vA,FA)))),(wA?ye(WA([wA])):null).map(([vA])=>({...vA,level:tA}))}function yA(M,tA){return M.nodeType===Node.DOCUMENT_NODE?M:M===tA.root?M.ownerDocument:M}function AA(M){let tA=Array.from(M.childNodes).reduce((FA,wA)=>(wA.nodeType===3&&FA.push(wA.nodeValue),FA),[]).join(""),Y=Array.from(M.childNodes).map(FA=>{let wA=FA.nodeName.toLowerCase();return{classes:FA.classList?Array.from(FA.classList):[],nodeName:wA}}),aA=M.classList?Array.from(M.classList):[],UA=M.tagName.toLowerCase(),V=Zi(window.location.href);return{tagName:UA,classes:aA,internalStructure:Y,directInnerText:tA,url:V}}function CA(M){let tA=[],Y=M,aA=0;for(;Y&&Y!==B.root.parentElement;){let UA=[G(ce(Y)),G(ue(Y)),G(...fA(Y)),G(...NA(Y)),G(GA(Y))].filter(zA).flat().sort((V,FA)=>V.penalty-FA.penalty);tA.push({nodeIdentifiers:UA,level:aA}),Y=Y.parentElement,aA++}return tA}function TA(M){return M.map(tA=>tA.penalty).reduce((tA,Y)=>tA+Y,0)}function BA(M){switch(Q.querySelectorAll(b(M)).length){case 0:throw new Error(`Can't select any node with this selector: ${b(M)}`);case 1:return!0;default:return!1}}function ce(M){M?.getAttribute||alert(JSON.stringify(M));let tA=M.getAttribute("id");return tA&&B.idName(tA)?{name:"#"+_e(tA,{isIdentifier:!0}),penalty:0,identifier:"id"}:null}function fA(M){return Array.from(M.attributes).filter(Y=>B.attr(Y.name,Y.value)).map(Y=>({name:"["+_e(Y.name,{isIdentifier:!0})+'="'+_e(Y.value)+'"]',penalty:.5,identifier:"attribute"}))}function NA(M){return Array.from(M.classList).filter(B.className).map(Y=>({name:"."+_e(Y,{isIdentifier:!0}),penalty:1,identifier:"className"}))}function ue(M){let tA=M.tagName.toLowerCase();return B.tagName(tA)?{name:tA,penalty:2,identifier:"tagName"}:null}function Ut(){return{name:"*",penalty:3,identifier:"any"}}function GA(M){let tA=M.parentNode;if(!tA)return null;let Y=tA.firstChild;if(!Y)return null;let aA=0;for(;Y&&(Y.nodeType===Node.ELEMENT_NODE&&aA++,Y!==M);)Y=Y.nextSibling;return{index:aA,outOf:tA.childElementCount,penalty:4,identifier:"index"}}function OA(M,tA){return{name:M.name+`:nth-child(${tA})`,penalty:M.penalty+1}}function Ue(M){return M.name!=="html"&&!M.name.startsWith("#")&&!B.allowDuplicates}function G(...M){let tA=M.filter(zA);return tA.length>0?tA:null}function zA(M){return M!=null}function*WA(M,tA=[]){if(M.length>0)for(let Y of M[0])yield*WA(M.slice(1,M.length),tA.concat(Y));else yield tA}function ye(M){return Array.from(M).sort((tA,Y)=>TA(tA)-TA(Y))}function*ut(M,tA,Y={counter:0,visited:new Map}){if(M.length>2&&M.length>B.optimizedMinLength)for(let aA=1;aAB.maxNumberOfTries){console.log(`*** Selector optimization exhausted. Exceeded max number of tries - ${B.maxNumberOfTries}`);return}Y.counter+=1;let UA=[...M];UA.splice(aA,1);let V=b(UA);if(Y.visited.has(V))return;BA(UA)&&yt(UA,tA)&&(yield UA,Y.visited.set(V,!0),yield*ut(UA,tA,Y))}}function yt(M,tA){return Q.querySelector(b(M))===tA}let jt=/[ -,\.\/:-@\[-\^`\{-~]/,eA=/[ -,\.\/:-@\[\]\^`\{-~]/,HA=/(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g,Re={escapeEverything:!1,isIdentifier:!1,quotes:"single",wrap:!1};function _e(M,tA={}){let Y=Object.assign(Object.assign({},Re),tA);Y.quotes!="single"&&Y.quotes!="double"&&(Y.quotes="single");let aA=Y.quotes=="double"?'"':"'",UA=Y.isIdentifier,V=M.charAt(0),FA="",wA=0,JA=M.length;for(;wA126){if(VA>=55296&&VA<=56319&&wAK===B},{nodeTree:b,recordedElementInfo:U}=Q.getElementProfileNodeTree(h.target,y);return console.log("*** Just FYI - this is how it can generate css selector:",Q.generateSelectorFromNodeTree(b,y)),{nodeTree:b,recordedElementInfo:U}}function Do(h,B){let Q=Va(),b={...{allowDuplicates:!1,optimizedMinLength:10,threshold:1e3,attr:K=>K===dataAttribute,fallbackNodeTree:h},...B};return Q.generateSelectorFromNodeTree(h,b)}function Vl(h,B){this.removeOverlayElement=()=>{console.log("Removing mouse over event listener from the selected element."),h.removeEventListener("mouseover",this.mouseOverEvent);let b=h.getElementById("element-selector-overlay");b&&h?.body?.removeChild(b)},this.saveSelectedSelector=b=>{b.preventDefault(),b.stopPropagation(),this.removeOverlayElement();let U=Wg(b,{dataAttribute:"some-custom-strigo-attribute"});U=U||{},console.log("Selected element with elementProfile:",U),B.onElementProfileCreated(U)};function Q(b,U){for(let K in U)b.style[K]=U[K]}let y=(b,U,K=[])=>{if(U===b.target)return;let W=b.target;if(K.includes(W.id))return;let $=W.offsetWidth+2,yA=W.offsetHeight+2;function AA(BA){let ce=0,fA=0;for(;BA&&!isNaN(BA.offsetLeft)&&!isNaN(BA.offsetTop);)ce+=BA.offsetLeft-BA.scrollLeft,fA+=BA.offsetTop-BA.scrollTop,BA=BA.offsetParent;return{top:fA-window.scrollY,left:ce-window.scrollX}}let CA=AA(W),TA={top:CA.top-2+"px",left:CA.left-2+"px",width:$+"px",height:yA+"px"};Q(U,TA)};return this.mouseOverEvent=b=>{let U=window.document.getElementById("element-selector-overlay");y(b,U,["element-selector-overlay","strigo-assessment-recorder-iframe"]),b.target.addEventListener("click",this.saveSelectedSelector)},this.removeClickListenerFromHoveredElement=b=>{b.target.removeEventListener("click",this.saveSelectedSelector)},this.startElementSelector=()=>{let b=h.createElement("div");b.setAttribute("id","element-selector-overlay"),b.setAttribute("id","element-selector-overlay"),b.setAttribute("style",` position: fixed; top: 0; left: 0; @@ -65,7 +65,7 @@ ${JSON.stringify(U)}`:"")}getDefaultContext(){let B=te();if(!B)return{};let{user
Expected text: ${Q?.recordedAssessment?.expectedText}
Selector used: ${B}
- `,b.children[0].children[1].appendChild(K),T.info("*** Appending assessment debug context element.");let $=window.document.querySelectorAll(`[data-${au}="${B}"]`)?.[0];$?$.appendChild(b):Sd(h,B).appendChild(b)},lu=function(){T.info("*** Evaluating Assessments...",{bodyTextDuringAssessment:window.document.body.innerText.slice(0,50)}),fu.filter(({recordedAssessment:B})=>{let Q=B?.locationElement?.profile?.recordedElementInfo?.url;if(!Q)return!1;let y=window.location.href;return su(Q,y)}).forEach(B=>{let{recordedAssessment:Q,challengeSuccessEvent:y,_id:b}=B,{actionType:U,expectedText:K}=Q,W=Q?.locationElement?.profile;if(!W){T.info("*** missing location element profile. Aborting...");return}if(kn?.[b]?.status==="SUCCESS"){T.info('*** Assessment already in "success" status. Aborting...');return}Ac(b,{status:"pending"});let $;try{$=Id(b,W)}catch{T.info("*** Failed to find location element. Aborting assessment evaluation...");return}let yA=te()?.isAcademyAssessmentDebug,{locationElement:AA,locationElementSelector:CA}=$;switch(yA&&Hd(AA,CA,B),U){case"added-item":{let TA=bd.bind({assessment:B,locationElement:AA,window});if(Ct[b]?.observer&&AA===Ct[b].element){Ct[b].element=AA;try{TA([]),Ct[b].observer.observe(AA,qa),T.info("Same reference - no need to observe again"),T.info(" *** Same reference - no need to observe again",{locationElement:AA})}catch(BA){T.error("*** Got an error in item count",{err:BA});break}break}if(Ct[b]?.observer){try{TA([]),Ct[b].observer.observe(AA,qa),T.info("DOM Reference have changed - observing again"),T.info(" *** DOM Reference have changed - observing again",{locationElement:AA})}catch(BA){T.error("*** Got an error in item count",{err:BA});break}break}Ct[b]={element:AA,observer:new MutationObserver(TA)};try{TA([]),Ct[b].observer.observe(AA,qa)}catch(BA){T.info("*** Got an error in item count",BA);break}break}case"text-change":{if(T.info("*** Assessing text changes in location element...",{locationElement:AA,locationElementType:AA instanceof HTMLInputElement?"input":"non-input",innerTextValue:AA instanceof HTMLInputElement?AA?.value:AA?.innerText,expectedText:K}),AA instanceof HTMLInputElement&&AA?.value?.includes(K)){$a(B,{locationElement:AA});break}if(AA?.innerText?.includes(K)){$a(B,{locationElement:AA});break}break}default:break}})},xd=function(h){let B=h.some(y=>y.addedNodes?.length>0),Q=h.some(y=>y.type=="characterData");if(T.info("#####",{isAddedNodes:B,isCharacterDataChanged:Q}),!B&&!Q){T.info("*** No added nodes and no character data change were detected after url change.",{previousLocation:Ro||"",newLocation:document.location.href});return}Ro===document.location.href?T.info("*** No URL change and no nodes were added."):(T.info("*** Detected URL change!",{previousLocation:Ro||"",newLocation:document.location.href}),Ro=document.location.href),ec(window)},ec=(0,uu.default)(h=>{if(T.info("*** Initializing document observer"),fu=Pa().assessments.filter(({assessmentType:B})=>B==="recorded-flow"),!window?.strigoObserver?.observer){T.info("*** Adding Strigo observer to document body"),window.strigoObserver={observer:new MutationObserver(xd),observedBodyElement:window.document.body},lu(),T.info("*** Starting to observe document body"),window?.strigoObserver?.observer?.observe(window.document,cu);return}lu(),window.document.contains(window.strigoObserver.observedBodyElement)||(T.info('*** Detected a "body" element change. Re-initializing the document observer...'),window.strigoObserver.observedBodyElement=window.document.body,window.strigoObserver.observer.observe(window.document,cu))},500);var pu=So(Za(),1);var du={subtree:!0,childList:!0},is;function hu(h){try{window["localStorage"].setItem("strigoUrlTriggers",JSON.stringify(h))}catch(B){return T.error("Url triggers setup error",{error:B}),null}}function Ld(){try{let h=window["localStorage"].getItem("strigoUrlTriggers");if(h)return JSON.parse(h)}catch(h){return T.error("Get url triggers error",{error:h}),null}}function Bu(h){let B=document.getElementById("strigo-exercises"),Q=h.document.location.href,y=Ld();if(!y)return;let b=Zr("urlTriggeredCourses")||[];for(let U of y){let{publishmentId:K,urlTriggerMatchType:W,urlTriggerUrl:$}=U;if(T.info("Detect URL trigger invoked",{publishmentId:K,urlTriggeredCourses:b}),!K){T.info("URL trigger detected without course id");continue}if(b.includes(K)){T.info("Detected URL trigger for a course that was already opened, doing nothing");continue}switch(W){case"exact":{$.trim()===Q.trim()&&B.contentWindow.postMessage({selectedCourseId:K},"*");break}case"starts_with":{Q.trim().startsWith($.trim())&&B.contentWindow.postMessage({selectedCourseId:K},"*");break}default:break}}}var Od=function(h){let B=h.some(Q=>Q.addedNodes?.length>0);if(T.info("#####",{isAddedNodes:B}),!B){T.info("*** No added nodes and no character data change were detected after url change.",{previousLocation:is||"",newLocation:document.location.href});return}is===document.location.href?T.info("*** No URL change and no nodes were added."):(T.info("*** Detected URL change!",{previousLocation:is||"",newLocation:document.location.href}),is=document.location.href),tc(window)},tc=(0,pu.default)(h=>{if(T.info("*** Initializing url trigger observer"),!h?.strigoUrlTriggerObserver?.observer){T.info("*** Adding Strigo url trigger observer to document body"),h.strigoUrlTriggerObserver={observer:new MutationObserver(Od),observedBodyElement:h.document.body},Bu(h),T.info("*** Starting to observe document body - url trigger observer"),h?.strigoUrlTriggerObserver?.observer?.observe(h.document,du);return}Bu(h),h.document.contains(h.strigoUrlTriggerObserver.observedBodyElement)||(T.info('*** Detected a "body" element change. Re-initializing the document observer - url trigger observer...'),h.strigoUrlTriggerObserver.observedBodyElement=h.document.body,h.strigoUrlTriggerObserver.observer.observe(h.document,du))},500);var wu=342;function vu(){T.info("Posting dockable state to Strigo",{});let h=pr("dockingSide");document.getElementById("strigo-exercises").contentWindow.postMessage({dockable:!0,dockingSide:h},"*")}function Kd(){let[h]=ts();(0,rc.default)("#strigo-widget").resizable({edges:{left:"#strigo-collapse-div",right:"#strigo-collapse-div.align-left",bottom:!1,top:!1},listeners:{move(B){let Q=B.target;Q.style.width=`${B.rect.widthh?h:B.rect.width}px`},start(){let B=document.getElementById("strigo-exercises");B.style.pointerEvents="none"},end(){let B=document.getElementById("strigo-exercises");B.style.pointerEvents="auto"}},modifiers:[rc.default.modifiers.restrictEdges({outer:"parent"})]})}var Qu=class{init(){return T.info("overlay init called"),"OVERLAY"}setup({version:B}){T.info("overlay setup called"),wr({parentElement:hr(),url:dl(B)}),wr({parentElement:hr(),url:zi(B)});let Q=te(),y=sessionStorage.getItem("strigoPreviewUserToken"),b=!!y,U=Pl(ji({...Q,user:{token:{token:y||Q.user.token.token,expiration:Q.user.token.expiration},email:Q.user.email}},b)),K=Lo();this.initEventListeners(K,U),T.info("adding assessment document observer"),ec(K),tc(K),Nl(K),T.info("assessment document observer added"),Kd()}shutdown(){T.info("overlay shutdown called");let B=Lo();this.removeEventListeners(B),B?.strigoObserver?.observer?.disconnect(),Ml(B)}collapse(){T.info("overlay collapse called"),_l()}open(){Gn(),vu()}move(){Kl()}initEventListeners(B,Q){as(Q,vu),ss(B)}removeEventListeners(B){Cu()}},_o=new Qu;function yu(h){let B=h?.data;if(!!B){if(B.startsWith("url-triggered")){let Q=Zr("urlTriggeredCourses")||[],y=B.split("/")[1];if(T.info("URL trigger message received",{selectedCourseId:y,urlTriggeredCourses:Q}),!y){T.info("URL trigger message received without course id");return}if(Q.includes(y)){T.info("URL trigger message received for a course that was already opened, doing nothing");return}T.info("URL trigger message received for a new course, opening it"),Q.push(y),Jt("urlTriggeredCourses",Q),Nn()==="overlay"&&Gn();return}switch(h.data){case"move":{T.info("Panel move message received"),Nn()==="overlay"&&_o.move();break}case"close":{T.info("Shutdown message received - will collapse panel"),window.Strigo?.collapse();break}case"destroy":{T.info("Destroy message received"),window.Strigo?.destroy();break}case"challenge-success":{T.info("Challenge event success message received"),Nn()==="overlay"&&_o.open();break}case"rendered":{T.info("Panel rendered message received"),Jt("isRendered",!0),window.Strigo?.expandPanel();break}default:break}}}function ss(h){h.addEventListener("message",yu,!1)}function Cu(){window.removeEventListener("message",yu)}function as(h,B){h.addEventListener("load",async()=>{Zr("isLoading")&&(B&&await B(),Jt("isLoading",!1))})}function Fu(h){let B=pr("initSite")?.host;h.addEventListener("load",function(){try{this.contentWindow.location.host!==B&&window.Strigo.shutdown()}catch(Q){T.error(Q),window.Strigo.shutdown()}})}function Eu(){return Ja(["#strigo-exercises","#original-site"],{sizes:[25,75],maxSize:ts(),minSize:Ol(),gutterSize:2})}async function Rd(){await zl(),document.getElementById("strigo-exercises").contentWindow.postMessage({dockable:!1},"*")}var bu=class{init(){let B;return ll()?(T.info("Child SDK window"),B="CHILD",window.dispatchEvent(new Event("strigo-opened")),ul()):(T.info("Parent SDK window"),B="PARENT"),B}setup({version:B}){T.info("iframe setup started"),Hl(),wr({parentElement:hr(),url:gl(B)}),wr({parentElement:hr(),url:zi(B)}),jl();let Q=te(),y=xl(),b=Oo({parentElement:y,url:ji(Q,!1),classNames:el,id:"strigo-exercises"}),U=Oo({parentElement:y,url:cl(Q.initSite.href),classNames:tl,id:"original-site"}),K=document.createElement("div");K.className="strigo-academy-hat align-left",K.id="strigo-academy-hat",K.onclick=()=>{document.getElementById("strigo-academy-hat").classList.toggle("slide-in"),this.splitInstance=Eu()};let W=document.createElement("div");W.className="strigo-academy-hat-icon",W.id="strigo-academy-hat-icon",W.innerHTML=Ji,K.appendChild(W),y.appendChild(K),this.splitInstance=Eu();let $=Lo();this.initEventListeners($,b,U)}collapse(){this.splitInstance&&(this.splitInstance.destroy(),this.splitInstance=Ja(["#strigo-exercises","#original-site"],{sizes:[25,75],minSize:0,gutterSize:0}),this.splitInstance.collapse(0),document.getElementById("strigo-academy-hat").classList.toggle("slide-in"))}open(){}shutdown(){T.info("iframe shutdown called"),Tl()}initEventListeners(B,Q,y){as(Q,Rd),Fu(y),ss(y.contentWindow)}},Iu=new bu;function Su(h){return h&&h==="dynamic"?Dl()?"iframe":"overlay":h}function Vn(h){let B=null;switch(h){case"iframe":{B=Iu;break}case"overlay":{B=_o;break}default:throw T.error("Widget flavor is not supported",{widgetFlavor:h}),new Error(`Widget flavor ${h} is not supported`)}return B}var Hu=class{constructor(){this.config={}}isDevelopment(){return!1}init(){try{if(T.info("Initializing SDK..."),this.config.initialized){T.info("SDK was already initialized");return}El();let{webApiKey:B,subDomain:Q,selectedWidgetFlavor:y}=fl();if(!B||!Q||!y)throw new Error("Init data is missing");let b=Su(y);wl({webApiKey:B,subDomain:Q,selectedWidgetFlavor:b});let U=Vn(b);if(this.config.sdkType=U.init(),this.config.initialized=!0,T.info("Initialized SDK."),this.config.sdkType!=="CHILD"&&Pn()){let K=te()?.user?.token,W=sessionStorage.getItem("strigoPreviewUserToken"),$=W?{token:{token:W,expiration:`${Date.now()+1e3*60*60*24}`},isPreview:!0}:{token:K};this.setup($)}}catch(B){T.error("Could not initialize SDK",{err:B})}}async setup(B){try{T.info("Starting to setup SDK...");let Q=document.getElementById("strigo-widget");if(this.config.isOpen&&Q||this.config.sdkType==="CHILD"){T.info('panel is already opened. Aborting "setup" action...');return}if(!this.config.initialized)throw new Error("SDK was not initialized");let b=te(),{email:U,token:K,version:W,openWidget:$=!0,dockingSide:yA="right",isPreview:AA}={...b?.user,...b,...B};if(!U||!K)throw new Error("Setup data is missing");let CA=await Cl(K);if(!CA?.allowedAcademyDomains?.includes(window.location.host.replace(/^www\./i,""))){T.warn("Running on an unrelated domain. Aborting...",{allowedDomains:CA?.allowedAcademyDomains,currentHost:window.location.host});return}if(CA){let{loggingConfig:TA,userAssessments:BA}=CA;T.debug("Configuration fetched from Strigo"),T.setup(TA),bl(BA),CA.academyColors&&Gl(CA.academyColors),CA.urlTriggers&&hu(CA.urlTriggers)}AA||vl({user:{email:U,token:K},initSite:al(),version:W,loggingConfig:CA?.loggingConfig,assessmentThresholds:CA?.assessmentThresholds,isAcademyAssessmentDebug:CA?.isAcademyAssessmentDebug,dockingSide:yA}),this.config.configured=!0,T.info("Finished SDK setup."),$&&(this.open(),Jt("shouldPanelBeOpen",!1),this.collapse())}catch(Q){T.error("Could not setup SDK",{err:Q})}}open(){try{if(T.info("Opening academy panel..."),!this.config.configured)throw new Error("SDK was not set up");let B=document.getElementById("strigo-widget");if(this.config.isOpen&&B||this.config.sdkType==="CHILD"){T.info('Panel is already opened. Aborting "open" action...');return}let y=te();yl({currentUrl:y.initSite.href,shouldPanelBeOpen:Pn(),isLoading:!0,isRendered:!1,widgetFlavor:y.selectedWidgetFlavor}),Vn(y.selectedWidgetFlavor).setup({version:y.version}),this.config.isOpen=!0,T.info("Opened academy panel.")}catch(B){T.error("Could not open academy panel",{err:B})}}expandPanel(){T.info("Expanding academy panel");let B=te();Vn(B.selectedWidgetFlavor).open(),Zr("isRendered")&&Rl()}collapse(){T.info("Collapsing academy panel");let{selectedWidgetFlavor:B}=te();Vn(B).collapse()}shutdown(){try{if(T.info("Closing academy panel..."),this.config.sdkType==="CHILD"){window.parent.postMessage(JSON.stringify({messageType:"close"}),"*"),T.info("Notified parent frame to close academy panel.");return}if(!this.config.isOpen){T.info("Tried to close unopened academy panel");return}let B=Vn(Nn());Fl(),B.collapse(),B.shutdown(),this.config.isOpen=!1,T.info("Closed academy panel.")}catch(B){T.error("Could not close academy panel",{err:B})}}destroy(){try{if(T.info("Destroying SDK..."),this.config.sdkType==="CHILD"){window.parent.postMessage(JSON.stringify({messageType:"destroy"}),"*"),T.info("Notified parent frame to destroy SDK.");return}Ql(),Il(),this.shutdown(),this.config={},T.info("Destroyed SDK.")}catch(B){T.error("Could not destroy SDK",{err:B})}}async sendEvent(B){let Q=pr("user"),{token:y}=Q;await Ul(y,B),T.debug("sendEvent called",{eventName:B})}startElementSelector(B,Q,y){T.debug("startElementSelector called");let b=y?window.document.querySelector(y):window.document.body,{startElementSelector:U,stopElementSelection:K}=Vl(window.document,{onElementProfileCreated:B,onElementSelectionCancel:Q,zIndex:2147483645,rootElement:b});this.stopElementSelector=K,U()}stopElementSelector(){}assessmentRecorder(){Wl()}},xu=new Hu;window.Strigo=xu;window.Strigo.init();})(); + `,b.children[0].children[1].appendChild(K),T.info("*** Appending assessment debug context element.");let $=window.document.querySelectorAll(`[data-${au}="${B}"]`)?.[0];$?$.appendChild(b):Sd(h,B).appendChild(b)},lu=function(){T.info("*** Evaluating Assessments...",{bodyTextDuringAssessment:window.document.body.innerText.slice(0,50)}),fu.filter(({recordedAssessment:B})=>{let Q=B?.locationElement?.profile?.recordedElementInfo?.url;if(!Q)return!1;let y=window.location.href;return su(Q,y)}).forEach(B=>{let{recordedAssessment:Q,challengeSuccessEvent:y,_id:b}=B,{actionType:U,expectedText:K}=Q,W=Q?.locationElement?.profile;if(!W){T.info("*** missing location element profile. Aborting...");return}if(kn?.[b]?.status==="SUCCESS"){T.info('*** Assessment already in "success" status. Aborting...');return}Ac(b,{status:"pending"});let $;try{$=Id(b,W)}catch{T.info("*** Failed to find location element. Aborting assessment evaluation...");return}let yA=te()?.isAcademyAssessmentDebug,{locationElement:AA,locationElementSelector:CA}=$;switch(yA&&Hd(AA,CA,B),U){case"added-item":{let TA=bd.bind({assessment:B,locationElement:AA,window});if(Ct[b]?.observer&&AA===Ct[b].element){Ct[b].element=AA;try{TA([]),Ct[b].observer.observe(AA,qa),T.info("Same reference - no need to observe again"),T.info(" *** Same reference - no need to observe again",{locationElement:AA})}catch(BA){T.error("*** Got an error in item count",{err:BA});break}break}if(Ct[b]?.observer){try{TA([]),Ct[b].observer.observe(AA,qa),T.info("DOM Reference have changed - observing again"),T.info(" *** DOM Reference have changed - observing again",{locationElement:AA})}catch(BA){T.error("*** Got an error in item count",{err:BA});break}break}Ct[b]={element:AA,observer:new MutationObserver(TA)};try{TA([]),Ct[b].observer.observe(AA,qa)}catch(BA){T.info("*** Got an error in item count",BA);break}break}case"text-change":{if(T.info("*** Assessing text changes in location element...",{locationElement:AA,locationElementType:AA instanceof HTMLInputElement?"input":"non-input",innerTextValue:AA instanceof HTMLInputElement?AA?.value:AA?.innerText,expectedText:K}),AA instanceof HTMLInputElement&&AA?.value?.includes(K)){$a(B,{locationElement:AA});break}if(AA?.innerText?.includes(K)){$a(B,{locationElement:AA});break}break}default:break}})},xd=function(h){let B=h.some(y=>y.addedNodes?.length>0),Q=h.some(y=>y.type=="characterData");if(T.info("#####",{isAddedNodes:B,isCharacterDataChanged:Q}),!B&&!Q){T.info("*** No added nodes and no character data change were detected after url change.",{previousLocation:Ro||"",newLocation:document.location.href});return}Ro===document.location.href?T.info("*** No URL change and no nodes were added."):(T.info("*** Detected URL change!",{previousLocation:Ro||"",newLocation:document.location.href}),Ro=document.location.href),ec(window)},ec=(0,uu.default)(h=>{if(T.info("*** Initializing document observer"),fu=Pa().assessments.filter(({assessmentType:B})=>B==="recorded-flow"),!window?.strigoObserver?.observer){T.info("*** Adding Strigo observer to document body"),window.strigoObserver={observer:new MutationObserver(xd),observedBodyElement:window.document.body},lu(),T.info("*** Starting to observe document body"),window?.strigoObserver?.observer?.observe(window.document,cu);return}lu(),window.document.contains(window.strigoObserver.observedBodyElement)||(T.info('*** Detected a "body" element change. Re-initializing the document observer...'),window.strigoObserver.observedBodyElement=window.document.body,window.strigoObserver.observer.observe(window.document,cu))},500);var pu=So(Za(),1);var du={subtree:!0,childList:!0},is;function hu(h){try{window["localStorage"].setItem("strigoUrlTriggers",JSON.stringify(h))}catch(B){return T.error("Url triggers setup error",{error:B}),null}}function Ld(){try{let h=window["localStorage"].getItem("strigoUrlTriggers");if(h)return JSON.parse(h)}catch(h){return T.error("Get url triggers error",{error:h}),null}}function Bu(h){let B=document.getElementById("strigo-exercises"),Q=h.document.location.href,y=Ld();if(!y)return;let b=Zr("urlTriggeredCourses")||[];for(let U of y){let{publishmentId:K,urlTriggerMatchType:W,urlTriggerUrl:$}=U;if(T.info("Detect URL trigger invoked",{publishmentId:K,urlTriggeredCourses:b}),!K){T.info("URL trigger detected without course id");continue}if(b.includes(K)){T.info("Detected URL trigger for a course that was already opened, doing nothing");continue}switch(W){case"exact":{$.trim()===Q.trim()&&B.contentWindow.postMessage({selectedCourseId:K},"*");break}case"starts_with":{Q.trim().startsWith($.trim())&&B.contentWindow.postMessage({selectedCourseId:K},"*");break}default:break}}}var Od=function(h){let B=h.some(Q=>Q.addedNodes?.length>0);if(T.info("#####",{isAddedNodes:B}),!B){T.info("*** No added nodes and no character data change were detected after url change.",{previousLocation:is||"",newLocation:document.location.href});return}is===document.location.href?T.info("*** No URL change and no nodes were added."):(T.info("*** Detected URL change!",{previousLocation:is||"",newLocation:document.location.href}),is=document.location.href),tc(window)},tc=(0,pu.default)(h=>{if(T.info("*** Initializing url trigger observer"),!h?.strigoUrlTriggerObserver?.observer){T.info("*** Adding Strigo url trigger observer to document body"),h.strigoUrlTriggerObserver={observer:new MutationObserver(Od),observedBodyElement:h.document.body},Bu(h),T.info("*** Starting to observe document body - url trigger observer"),h?.strigoUrlTriggerObserver?.observer?.observe(h.document,du);return}Bu(h),h.document.contains(h.strigoUrlTriggerObserver.observedBodyElement)||(T.info('*** Detected a "body" element change. Re-initializing the document observer - url trigger observer...'),h.strigoUrlTriggerObserver.observedBodyElement=h.document.body,h.strigoUrlTriggerObserver.observer.observe(h.document,du))},500);var wu=342;function vu(){T.info("Posting dockable state to Strigo",{});let h=pr("dockingSide");document.getElementById("strigo-exercises").contentWindow.postMessage({dockable:!0,dockingSide:h},"*")}function Kd(){let[h]=ts();(0,rc.default)("#strigo-widget").resizable({edges:{left:"#strigo-collapse-div",right:"#strigo-collapse-div.align-left",bottom:!1,top:!1},listeners:{move(B){let Q=B.target;Q.style.width=`${B.rect.widthh?h:B.rect.width}px`},start(){let B=document.getElementById("strigo-exercises");B.style.pointerEvents="none"},end(){let B=document.getElementById("strigo-exercises");B.style.pointerEvents="auto"}},modifiers:[rc.default.modifiers.restrictEdges({outer:"parent"})]})}var Qu=class{init(){return T.info("overlay init called"),"OVERLAY"}setup({version:B}){T.info("overlay setup called"),wr({parentElement:hr(),url:dl(B)}),wr({parentElement:hr(),url:zi(B)});let Q=te(),y=sessionStorage.getItem("strigoPreviewUserToken"),b=!!y,U=Pl(ji({...Q,user:{token:{token:y||Q.user.token.token,expiration:Q.user.token.expiration},email:Q.user.email}},b)),K=Lo();this.initEventListeners(K,U),T.info("adding assessment document observer"),ec(K),tc(K),Nl(K),T.info("assessment document observer added"),Kd()}shutdown(){T.info("overlay shutdown called");let B=Lo();this.removeEventListeners(B),B?.strigoObserver?.observer?.disconnect(),Ml(B)}collapse(){T.info("overlay collapse called"),_l()}open(){Gn(),vu()}move(){Kl()}initEventListeners(B,Q){as(Q,vu),ss(B)}removeEventListeners(B){Cu()}},_o=new Qu;function yu(h){let B=h?.data;if(!!B){if(B.startsWith?.("url-triggered")){let Q=Zr("urlTriggeredCourses")||[],y=B.split("/")[1];if(T.info("URL trigger message received",{selectedCourseId:y,urlTriggeredCourses:Q}),!y){T.info("URL trigger message received without course id");return}if(Q.includes(y)){T.info("URL trigger message received for a course that was already opened, doing nothing");return}T.info("URL trigger message received for a new course, opening it"),Q.push(y),Jt("urlTriggeredCourses",Q),Nn()==="overlay"&&Gn();return}switch(h.data){case"move":{T.info("Panel move message received"),Nn()==="overlay"&&_o.move();break}case"close":{T.info("Shutdown message received - will collapse panel"),window.Strigo?.collapse();break}case"destroy":{T.info("Destroy message received"),window.Strigo?.destroy();break}case"challenge-success":{T.info("Challenge event success message received"),Nn()==="overlay"&&_o.open();break}case"rendered":{T.info("Panel rendered message received"),Jt("isRendered",!0),window.Strigo?.expandPanel();break}default:break}}}function ss(h){h.addEventListener("message",yu,!1)}function Cu(){window.removeEventListener("message",yu)}function as(h,B){h.addEventListener("load",async()=>{Zr("isLoading")&&(B&&await B(),Jt("isLoading",!1))})}function Fu(h){let B=pr("initSite")?.host;h.addEventListener("load",function(){try{this.contentWindow.location.host!==B&&window.Strigo.shutdown()}catch(Q){T.error(Q),window.Strigo.shutdown()}})}function Eu(){return Ja(["#strigo-exercises","#original-site"],{sizes:[25,75],maxSize:ts(),minSize:Ol(),gutterSize:2})}async function Rd(){await zl(),document.getElementById("strigo-exercises").contentWindow.postMessage({dockable:!1},"*")}var bu=class{init(){let B;return ll()?(T.info("Child SDK window"),B="CHILD",window.dispatchEvent(new Event("strigo-opened")),ul()):(T.info("Parent SDK window"),B="PARENT"),B}setup({version:B}){T.info("iframe setup started"),Hl(),wr({parentElement:hr(),url:gl(B)}),wr({parentElement:hr(),url:zi(B)}),jl();let Q=te(),y=xl(),b=Oo({parentElement:y,url:ji(Q,!1),classNames:el,id:"strigo-exercises"}),U=Oo({parentElement:y,url:cl(Q.initSite.href),classNames:tl,id:"original-site"}),K=document.createElement("div");K.className="strigo-academy-hat align-left",K.id="strigo-academy-hat",K.onclick=()=>{document.getElementById("strigo-academy-hat").classList.toggle("slide-in"),this.splitInstance=Eu()};let W=document.createElement("div");W.className="strigo-academy-hat-icon",W.id="strigo-academy-hat-icon",W.innerHTML=Ji,K.appendChild(W),y.appendChild(K),this.splitInstance=Eu();let $=Lo();this.initEventListeners($,b,U)}collapse(){this.splitInstance&&(this.splitInstance.destroy(),this.splitInstance=Ja(["#strigo-exercises","#original-site"],{sizes:[25,75],minSize:0,gutterSize:0}),this.splitInstance.collapse(0),document.getElementById("strigo-academy-hat").classList.toggle("slide-in"))}open(){}shutdown(){T.info("iframe shutdown called"),Tl()}initEventListeners(B,Q,y){as(Q,Rd),Fu(y),ss(y.contentWindow)}},Iu=new bu;function Su(h){return h&&h==="dynamic"?Dl()?"iframe":"overlay":h}function Vn(h){let B=null;switch(h){case"iframe":{B=Iu;break}case"overlay":{B=_o;break}default:throw T.error("Widget flavor is not supported",{widgetFlavor:h}),new Error(`Widget flavor ${h} is not supported`)}return B}var Hu=class{constructor(){this.config={}}isDevelopment(){return!1}init(){try{if(T.info("Initializing SDK..."),this.config.initialized){T.info("SDK was already initialized");return}El();let{webApiKey:B,subDomain:Q,selectedWidgetFlavor:y}=fl();if(!B||!Q||!y)throw new Error("Init data is missing");let b=Su(y);wl({webApiKey:B,subDomain:Q,selectedWidgetFlavor:b});let U=Vn(b);if(this.config.sdkType=U.init(),this.config.initialized=!0,T.info("Initialized SDK."),this.config.sdkType!=="CHILD"&&Pn()){let K=te()?.user?.token,W=sessionStorage.getItem("strigoPreviewUserToken"),$=W?{token:{token:W,expiration:`${Date.now()+1e3*60*60*24}`},isPreview:!0}:{token:K};this.setup($)}}catch(B){T.error("Could not initialize SDK",{err:B})}}async setup(B){try{T.info("Starting to setup SDK...");let Q=document.getElementById("strigo-widget");if(this.config.isOpen&&Q||this.config.sdkType==="CHILD"){T.info('panel is already opened. Aborting "setup" action...');return}if(!this.config.initialized)throw new Error("SDK was not initialized");let b=te(),{email:U,token:K,version:W,openWidget:$=!0,dockingSide:yA="right",isPreview:AA}={...b?.user,...b,...B};if(!U||!K)throw new Error("Setup data is missing");let CA=await Cl(K);if(!CA?.allowedAcademyDomains?.includes(window.location.host.replace(/^www\./i,""))){T.warn("Running on an unrelated domain. Aborting...",{allowedDomains:CA?.allowedAcademyDomains,currentHost:window.location.host});return}if(CA){let{loggingConfig:TA,userAssessments:BA}=CA;T.debug("Configuration fetched from Strigo"),T.setup(TA),bl(BA),CA.academyColors&&Gl(CA.academyColors),CA.urlTriggers&&hu(CA.urlTriggers)}AA||vl({user:{email:U,token:K},initSite:al(),version:W,loggingConfig:CA?.loggingConfig,assessmentThresholds:CA?.assessmentThresholds,isAcademyAssessmentDebug:CA?.isAcademyAssessmentDebug,dockingSide:yA}),this.config.configured=!0,T.info("Finished SDK setup."),$&&(this.open(),Jt("shouldPanelBeOpen",!1),this.collapse())}catch(Q){T.error("Could not setup SDK",{err:Q})}}open(){try{if(T.info("Opening academy panel..."),!this.config.configured)throw new Error("SDK was not set up");let B=document.getElementById("strigo-widget");if(this.config.isOpen&&B||this.config.sdkType==="CHILD"){T.info('Panel is already opened. Aborting "open" action...');return}let y=te();yl({currentUrl:y.initSite.href,shouldPanelBeOpen:Pn(),isLoading:!0,isRendered:!1,widgetFlavor:y.selectedWidgetFlavor}),Vn(y.selectedWidgetFlavor).setup({version:y.version}),this.config.isOpen=!0,T.info("Opened academy panel.")}catch(B){T.error("Could not open academy panel",{err:B})}}expandPanel(){T.info("Expanding academy panel");let B=te();Vn(B.selectedWidgetFlavor).open(),Zr("isRendered")&&Rl()}collapse(){T.info("Collapsing academy panel");let{selectedWidgetFlavor:B}=te();Vn(B).collapse()}shutdown(){try{if(T.info("Closing academy panel..."),this.config.sdkType==="CHILD"){window.parent.postMessage(JSON.stringify({messageType:"close"}),"*"),T.info("Notified parent frame to close academy panel.");return}if(!this.config.isOpen){T.info("Tried to close unopened academy panel");return}let B=Vn(Nn());Fl(),B.collapse(),B.shutdown(),this.config.isOpen=!1,T.info("Closed academy panel.")}catch(B){T.error("Could not close academy panel",{err:B})}}destroy(){try{if(T.info("Destroying SDK..."),this.config.sdkType==="CHILD"){window.parent.postMessage(JSON.stringify({messageType:"destroy"}),"*"),T.info("Notified parent frame to destroy SDK.");return}Ql(),Il(),this.shutdown(),this.config={},T.info("Destroyed SDK.")}catch(B){T.error("Could not destroy SDK",{err:B})}}async sendEvent(B){let Q=pr("user"),{token:y}=Q;await Ul(y,B),T.debug("sendEvent called",{eventName:B})}startElementSelector(B,Q,y){T.debug("startElementSelector called");let b=y?window.document.querySelector(y):window.document.body,{startElementSelector:U,stopElementSelection:K}=Vl(window.document,{onElementProfileCreated:B,onElementSelectionCancel:Q,zIndex:2147483645,rootElement:b});this.stopElementSelector=K,U()}stopElementSelector(){}assessmentRecorder(){Wl()}},xu=new Hu;window.Strigo=xu;window.Strigo.init();})(); /*! * html2canvas 1.4.1 * Copyright (c) 2022 Niklas von Hertzen diff --git a/src/modules/document/document.ts b/src/modules/document/document.ts index 44f94f4..5cc9263 100644 --- a/src/modules/document/document.ts +++ b/src/modules/document/document.ts @@ -117,10 +117,10 @@ export function removeWidget(hostingAppWindow: Window): void { export function removeLoader(): void { const loader = document.getElementById('loader'); - loader.remove(); + loader?.remove(); const academyHatIcon = document.getElementById('strigo-academy-hat-icon'); - academyHatIcon.classList.remove('loader'); + academyHatIcon?.classList.remove('loader'); } export function openWidget(): void { diff --git a/src/modules/listeners/listeners.ts b/src/modules/listeners/listeners.ts index bddfed1..c5245f0 100644 --- a/src/modules/listeners/listeners.ts +++ b/src/modules/listeners/listeners.ts @@ -14,7 +14,7 @@ function onHostEventHandler(ev: MessageEvent): void { return; } - if (message.startsWith(MessageTypes.URL_TRIGGERED)) { + if (message.startsWith?.(MessageTypes.URL_TRIGGERED)) { const urlTriggeredCourses = (sessionManager.getSessionValue('urlTriggeredCourses') as string[]) || []; const selectedCourseId = message.split('/')[1];