customerio-gist-web 3.20.2 → 3.20.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.
package/dist/gist.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Gist=t():e.Gist=t()}(this,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var n in s)e.o(s,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:s[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>Ye});class s{constructor(){this.callbacks={}}on(e,t){const s=this.callbacks[e];s?s.push(t):this.callbacks[e]=[t]}off(e,t){const s=this.callbacks[e];if(!s)return;if(!t)return void delete this.callbacks[e];const n=s.indexOf(t);-1!==n&&s.splice(n,1),0===s.length&&delete this.callbacks[e]}dispatch(e,t){const s=this.callbacks[e];s&&s.forEach(e=>e(t))}}function n(e){Ye.config&&Ye.config.logging&&console.log(`Gist: ${e}`)}const i="gist.web.isPersistingSession";function a(e,t,s=null){let n=s;n||(n=new Date,n.setDate(n.getDate()+365));const i={value:t,expiry:n};u().setItem(e,JSON.stringify(i))}function o(e){return l(e)}function r(e){u().removeItem(e)}function c(){const e=sessionStorage.getItem(i);return null===e?(sessionStorage.setItem(i,"true"),!0):"true"===e}function u(){return c()?localStorage:sessionStorage}function l(e){if(!e)return null;try{const t=u().getItem(e);if(!t)return null;const s=JSON.parse(t);if(!s.expiry)return s.value;const n=new Date,i=new Date(s.expiry),a=e.startsWith("gist.web.message.broadcasts")&&!e.endsWith("shouldShow")&&!e.endsWith("numberOfTimesShown")||e.startsWith("gist.web.message.user")&&!e.endsWith("seen")&&!e.endsWith("state"),o=new Date(n.getTime()+366e4);return a&&i.getTime()>o.getTime()||n.getTime()>i.getTime()?(r(e),null):s.value}catch(t){n(`Error checking key ${e} for expiry: ${t}`)}return null}var d,g=new Uint8Array(16);function m(){if(!d&&!(d="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return d(g)}const p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var f=[],h=0;h<256;++h)f.push((h+256).toString(16).substr(1));const y=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=(f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(s))throw TypeError("Stringified UUID is invalid");return s},w=function(e,t,s){var n=(e=e||{}).random||(e.rng||m)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){s=s||0;for(var i=0;i<16;++i)t[s+i]=n[i];return t}return y(n)},b="gist.web.userQueueUseSSE",v="gist.web.activeSSEConnection";let S,I=30;const x={RENDERER_HOST:"https://code.gist.build",ENGINE_API_ENDPOINT:{prod:"https://engine.api.gist.build",dev:"https://engine.api.dev.gist.build",local:"http://engine.api.local.gist.build:82"},GIST_QUEUE_API_ENDPOINT:{prod:"https://consumer.cloud.gist.build",dev:"https://consumer.cloud.dev.gist.build",local:"http://api.local.gist.build:86"},GIST_QUEUE_REALTIME_API_ENDPOINT:{prod:"https://realtime.cloud.gist.build",dev:"https://realtime.cloud.dev.gist.build",local:"http://api.local.gist.build:3000"},GIST_VIEW_ENDPOINT:{prod:"https://renderer.gist.build/3.0",dev:"https://renderer.gist.build/3.0",local:"http://app.local.gist.build:8080/web"},getSdkId:()=>(S||(S=w()),S),useSSE:()=>o(b)??!1,setUseSSEFlag(e){a(b,e,new Date((new Date).getTime()+6e4)),n(`Set user uses SSE to "${e}"`)},removeActiveSSEConnection(){r(v)},setActiveSSEConnection(){a(v,x.getSdkId(),new Date((new Date).getTime()+x.getSSEHeartbeat()))},hasActiveSSEConnection:()=>o(v)??!1,isSSEConnectionManagedBySDK:()=>o(v)===x.getSdkId(),getSSEHeartbeat:()=>1e3*(I+5),setSSEHeartbeat(e){e&&e>0&&(I=e)}};function $(e){return null!==e&&"object"==typeof e&&"response"in e}function E(e){return $(e)?e.response:void 0}function C(){const e=x.GIST_QUEUE_API_ENDPOINT[Ye.config.env??"prod"],t={"X-CIO-Site-Id":Ye.config.siteId,"X-CIO-Client-Platform":"web"},s=j();async function n(s,n={}){const i=e+s,a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{const e=await fetch(i,{method:n.method||"GET",headers:{...t,...n.headers||{}},body:n.method&&"GET"!==n.method.toUpperCase()?n.body:void 0,signal:a.signal});clearTimeout(o);const s=e.headers.get("content-type")?.includes("application/json"),r=s?await e.json():await e.text(),c=Object.fromEntries(e.headers.entries());if(e.status<200||e.status>=400)throw function(e){return Object.assign(new Error,{response:e})}({status:e.status,data:r,headers:c});return{status:e.status,headers:c,data:r}}catch(e){if(clearTimeout(o),$(e))throw e;if(e instanceof Error)throw Object.assign(e,{response:{status:0,data:e.message||"Unknown error",headers:{}}});throw e}}return null!=s&&(t["X-Gist-Encoded-User-Token"]=s),n.post=(e,t={},s={})=>n(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...s.headers||{}}}),n}const k="gist.web.userLocale";function D(){const e=o(k);return null!==e?e:navigator.language}let T=600,M=!1;const q="gist.web.userQueueNextPullCheck",R="gist.web.sessionId";function P(){let e=o(R);return e||(e=w()),a(R,e,new Date((new Date).getTime()+18e5)),String(e)}const L="gist.web.userToken",N="gist.web.usingGuestUserToken",W="gist.web.guestUserToken";function A(){return null!==o(N)}function O(){return o(L)}function U(){if(null===O()){let e=o(W);null==e&&(e=w(),a(W,e),n(`Set guest user token "${e}" with expiry date set to 1 year from today`)),a(L,e),a(N,!0),n(`Using anonymous session with token: "${e}"`)}}async function _(){const e=O();return null===e?null:await async function(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)}function j(){const e=O();return null===e?null:btoa(e)}async function H(e){try{return await C().post(`/api/v1/logs/queue/${e}`)}catch(e){return E(e)}}function z(e){const t={isEmbedded:!1,elementId:"",hasRouteRule:!1,routeRule:"",position:"",hasPosition:!1,shouldScale:!1,campaignId:null,messageWidth:414,overlayColor:"#00000033",persistent:!1,exitClick:!1,hasCustomWidth:!1},s=e?.properties?.gist;return s?{isEmbedded:!!s.elementId,elementId:s.elementId||"",hasRouteRule:!!s.routeRuleWeb,routeRule:s.routeRuleWeb||"",position:s.position||"",hasPosition:!!s.position,shouldScale:!!s.scale,campaignId:s.campaignId??null,messageWidth:null!=s.messageWidth&&s.messageWidth>0?s.messageWidth:t.messageWidth,hasCustomWidth:(s.messageWidth??0)>0,overlayColor:s.overlayColor||t.overlayColor,persistent:!!s.persistent,exitClick:!!s.exitClick}:t}const G=["x-gist-top","x-gist-floating-top","x-gist-bottom","x-gist-floating-bottom","x-gist-floating-bottom-left","x-gist-floating-bottom-right","x-gist-floating-top-left","x-gist-floating-top-right"];function V(e){if(document.getElementById(e))return;const t=document.createElement("div");t.id=e,"x-gist-top"===e?document.body.insertBefore(t,document.body.firstChild):document.body.insertAdjacentElement("beforeend",t),n("Top & bottom elements injected into page")}const F=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function B(e){return Ye.currentMessages.find(t=>t.instanceId===e)}function J(e){return!!e&&Ye.currentMessages.some(t=>t.queueId===e)}function Q(e){return e?Ye.currentMessages.find(t=>t.elementId===e)??null:null}function X(e){Ye.currentMessages=Ye.currentMessages.filter(t=>t.instanceId!==e)}function K(e,t){X(e),Ye.currentMessages.push(t)}function Y(e){const t={topLeft:"x-gist-floating-top-left",topCenter:"x-gist-floating-top",topRight:"x-gist-floating-top-right",bottomLeft:"x-gist-floating-bottom-left",bottomCenter:"x-gist-floating-bottom",bottomRight:"x-gist-floating-bottom-right"};return e&&t[e]?t[e]:(n(`Invalid overlay position "${e}", defaulting to "topCenter"`),t.topCenter)}function Z(e,t){if(e.properties||(e.properties={}),e.properties.gist||(e.properties.gist={}),"modal"===t.displayType)e.overlay=!0,e.elementId=null,e.properties.gist.elementId=null,e.position=t.modalPosition||"center",e.properties.gist.position=t.modalPosition||"center";else if("overlay"===t.displayType){e.overlay=!1;const s=Y(t.overlayPosition);e.elementId=s,e.properties.gist.elementId=s,e.position=null,e.properties.gist.position=null}else"inline"===t.displayType&&(e.overlay=!1,e.elementId=t.elementSelector,e.properties.gist.elementId=t.elementSelector,e.position=null,e.properties.gist.position=null);e.elementId&&F.includes(e.elementId)?delete e.properties.gist.messageWidth:void 0!==t.maxWidth&&t.maxWidth>0?e.properties.gist.messageWidth=t.maxWidth:delete e.properties.gist.messageWidth,void 0!==t.overlayColor?e.properties.gist.overlayColor=t.overlayColor:delete e.properties.gist.overlayColor,void 0!==t.dismissOutsideClick?e.properties.gist.exitClick=t.dismissOutsideClick:delete e.properties.gist.exitClick}function ee(e){const t=ue(e);t&&(t.classList.remove("gist-visible"),Array.from(t.classList).filter(e=>e.startsWith("gist-")).forEach(e=>t.classList.remove(e)),t.style.removeProperty("height"),t.style.removeProperty("width"),t.innerHTML="")}function te(e){const t=ue(e);if(t)return!(!t.style||!t.style.height||"0px"===t.style.height)}function se(e,t,s=null){const n=document.getElementById(e);n&&(n.onload=()=>{!function(e,t,s=null){const n=document.getElementById(e);if(n?.contentWindow){const e={options:t,capabilities:ne};s&&(t.stepId=s),n.contentWindow.postMessage(e,"*")}}(e,t,s)})}const ne=["MultiStepDisplayTypes"];function ie(e){if(!e.displaySettings)return;const t=re(e.instanceId??""),s=document.getElementById(t);s?.contentWindow&&s.contentWindow.postMessage({action:"updateDisplaySettings",displaySettings:e.displaySettings},"*")}async function ae(){const e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await new Promise(e=>setTimeout(e,300))),oe()}function oe(){const e=document.querySelector("#gist-embed-message");e&&e.parentNode?.removeChild(e)}function re(e){return`gist-${e}`}function ce(){const e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function ue(e){try{const t=document.querySelector(`#${e}`);return t instanceof HTMLElement?t:null}catch{return null}}const le="gist.web.customAttributes";let de=new Map;function ge(){const e=Array.from(de.entries()),t=new Date;t.setDate(t.getDate()+30),a(le,e,t),n(`Saved ${de.size} custom attributes to storage with TTL of 30 days`)}async function me(e){const t=await ye();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e.filter(fe),s)}async function pe(e,t){const s=o(e);return s?.find(e=>e.queueId===t)}function fe(e){return!(!e.properties?.gist||!e.properties.gist.broadcast)}function he(e){if(!fe(e))return!1;const t=e.properties.gist.broadcast;return 0===t.frequency.delay&&0===t.frequency.count}async function ye(){const e=await _();return e?`gist.web.message.broadcasts.${e}`:null}function we(e,t){return`${e}.${t}.numberOfTimesShown`}function be(e,t){return`${e}.${t}.shouldShow`}!function(){const e=o(le);if(e)try{de=new Map(e)}catch{de=new Map}else de=new Map}();const ve="gist.web.message.user";async function Se(e){const t=await Ie();if(!t)return;const s=e.filter(e=>!(e.properties&&e.properties.gist&&e.properties.gist.broadcast)),n=new Date;n.setMinutes(n.getMinutes()+60),a(t,s,n)}async function Ie(){const e=await _();return e?`${ve}.${e}`:null}async function xe(){const e=await _();return e?`${ve}.${e}.seen`:null}async function $e(e){const t=await _();return t?`${ve}.${t}.message.${e}.loading`:null}async function Ee(e){const t=await _();return t?`${ve}.${t}.message.${e}.state`:null}async function Ce(e){const t=await Ee(e);t&&(r(t),n(`Cleared message state for queueId: ${e}`))}async function ke(e){if(Ye.isDocumentVisible){if(J(e.queueId))return n(`Message with queueId ${e.queueId} is already showing.`),null;if(Ye.overlayInstanceId)return n(`Message ${Ye.overlayInstanceId} already showing.`),null;{const t=z(e);return e.instanceId=w(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=(new Date).getTime(),Ye.overlayInstanceId=e.instanceId,Ye.currentMessages.push(e),Le(e,null,e.savedStepName||null)}}return n("Document hidden, not showing message now."),null}function De(e,t){return Ye.isDocumentVisible?J(e.queueId)?(n(`Message with queueId ${e.queueId} is already showing.`),null):Q(t)?(n(`Message with elementId ${t} already has a message.`),null):(e.instanceId=w(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!te(t),e.renderStartTime=(new Date).getTime(),Ye.currentMessages.push(e),Le(e,t,e.savedStepName||null)):(n("Document hidden, not showing message now."),null)}async function Te(e){e?(Ye.messageDismissed(e),await Me(e)):n("Message not found")}async function Me(e){e.overlay?await Pe(!0,e):Re(e)}async function qe(e){e?z(e).persistent&&(n("Persistent message dismissed, logging view"),await Oe(e),await Ne(e),await Ce(e.queueId??"")):n("Message not found")}function Re(e){e.instanceId&&X(e.instanceId),e.elementId&&ee(e.elementId)}async function Pe(e,t){e?await ae():oe(),0===Ye.currentMessages.length&&(window.removeEventListener("message",Ae),window.removeEventListener("touchstart",We)),t.instanceId&&X(t.instanceId),Ye.overlayInstanceId=null}function Le(e,t=null,s=null){const i=Ye.config.env,a={endpoint:x.ENGINE_API_ENDPOINT[i],siteId:Ye.config.siteId,dataCenter:Ye.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId??"",livePreview:!1,properties:e.properties,customAttributes:Object.fromEntries(new Map(de))},o=`${x.GIST_VIEW_ENDPOINT[i]}/index.html`;return window.addEventListener("message",Ae),window.addEventListener("touchstart",We),t?(G.includes(t)&&V(t),function(e,t,s,i,a=null){const o=ue(e);if(o){const n=re(s.instanceId??"");o.classList.add(n);const r=z(s);let c=r.messageWidth+"px";F.includes(e)&&!r.hasCustomWidth&&(c="100%"),G.includes(e)&&(o.style.width=c),te(e)||(o.style.height="0px"),o.innerHTML=function(e,t,s){return function(e,t,s){let n=800;return t.messageWidth>n&&(n=t.messageWidth),`\n <div id="gist-embed">\n <style>\n #x-gist-floating-top, #x-gist-floating-top-left, #x-gist-floating-top-right {\n position: fixed;\n top: 0px;\n z-index: 1000000;\n }\n #x-gist-floating-bottom, #x-gist-floating-bottom-left, #x-gist-floating-bottom-right {\n position: fixed;\n bottom: 0px;\n z-index: 1000000;\n }\n #x-gist-bottom, #x-gist-top, #x-gist-floating-top, #x-gist-floating-bottom {\n left: 50%;\n transform: translate(-50%, 0%);\n }\n #x-gist-floating-top-right, #x-gist-floating-bottom-right {\n right: 0px;\n }\n #gist-embed {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container .gist-frame {\n height: 100%;\n width: 100%;\n border: none;\n }\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n transition: height 0.1s ease-in-out;\n }\n @media (max-width: ${n}px) {\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n width: 100% !important;\n }\n }\n </style>\n <div id="gist-embed-container">\n <iframe id="${e}" class="gist-frame" src="${s}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),s,e)}(t,s,r),se(n,i,a)}else n(`Message could not be embedded, elementId ${e} not found.`)}(t,o,e,a,s)):function(e,t,s,n=null){document.querySelectorAll("#gist-embed-message").forEach(e=>{e.parentNode?.removeChild(e)}),document.body.insertAdjacentHTML("afterbegin",function(e,t){const s=z(t);return function(e,t,s){let n=600;return t.messageWidth>n&&(n=t.messageWidth),`\n <div id="gist-embed-message">\n <style>\n #gist-overlay.gist-background {\n position: fixed;\n z-index: 9999999998;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: ${t.overlayColor};\n visibility: hidden;\n }\n #gist-overlay.gist-background.gist-visible {\n visibility: visible;\n }\n .gist-message {\n width: ${t.messageWidth}px;\n position: absolute;\n border: none;\n opacity: 0;\n transition: opacity 0.3s ease-in-out, height 0.1s ease-in-out;\n z-index: 9999999999;\n left: 50%;\n transform: translateX(-50%);\n }\n .gist-message.gist-visible {\n opacity: 1;\n pointer-events: auto;\n }\n .gist-message.gist-center {\n transform: translate(-50%, -50%);\n top: 50%;\n }\n .gist-message.gist-bottom {\n bottom: 0;\n }\n .gist-message.gist-top {\n top: 0;\n }\n @media (max-width: ${n}px) {\n .gist-message {\n width: 100%;\n }\n }\n </style>\n <div id="gist-overlay" class="gist-background">\n <iframe id="${e}" class="gist-message" src="${s}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),s,e)}(e,t)),se(re(t.instanceId??""),s,n)}(o,e,a,s),e}async function Ne(e){let t;n(`Message shown, logging view for: ${e.messageId}`),null!=e.queueId?(await Oe(e),t=await H(e.queueId)):t=await async function(e){try{return await C().post(`/api/v1/logs/message/${e}`)}catch(e){return E(e)}}(e.messageId),n(200===t?.status?"Message view logged":`Problem logging message: ${t?.status}`)}function We(){}async function Ae(e){const t=e.data;if(t.gist&&e.origin===x.RENDERER_HOST){const e=t.gist.instanceId,s=B(e);if(!s)return;const i=z(s);switch(t.gist.method){case"routeLoaded":{const a=.001*((new Date).getTime()-(s.renderStartTime??0));n(`Engine render for message: ${s.messageId} timer elapsed in ${a.toFixed(3)} seconds`),async function(e){const t=await $e(e);t&&r(t)}(s.queueId??""),s.currentRoute=t.gist.parameters.route,t.gist.parameters.fullDisplaySettings&&!s.displaySettings?s.displaySettings=t.gist.parameters.fullDisplaySettings:s.displaySettings&&(n("SDK already has display settings state, sending it to iframe"),ie(s)),(s.firstLoad||s.isDisplayChange)&&(s.overlay?function(e){const t=z(e),s=document.querySelector("#gist-overlay");if(s){s.classList.add("gist-visible");const n=document.querySelector(".gist-message");n&&(e.position?n.classList.add("gist-"+e.position):n.classList.add("gist-center")),setTimeout(ce,100),t.exitClick&&setTimeout(()=>function(e){const t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",()=>{Ye.dismissMessage(e)})}(e.instanceId??""),1e3)}else oe()}(s):function(e){const t=ue(e);t&&t.classList.add("gist-visible")}(s.elementId),s.firstLoad&&!s.isDisplayChange&&(Ye.messageShown(s),i.persistent?n("Persistent message shown, skipping logging view"):await Ne(s)),s.firstLoad=!1,s.isDisplayChange=!1),K(e,s);break}case"tap":{const e=t.gist.parameters.action,n=t.gist.parameters.name;if(Ye.messageAction(s,e,n),t.gist.parameters.system&&!i.persistent){await Te(s);break}try{const t=new URL(e);if(t&&"gist:"===t.protocol)switch(t.href.replace("gist://","").split("?")[0]){case"close":await Te(s),await qe(s),await Ue(s),await Je();break;case"showMessage":{const e=t.searchParams.get("messageId");let s=t.searchParams.get("properties");e&&(s&&(s=JSON.parse(atob(s))),await Ye.showMessage({messageId:e,properties:s}));break}case"loadPage":{const e=t.href.substring(t.href.indexOf("?url=")+5);e&&(e.startsWith("mailto:")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("/")?window.location.href=e:window.location.href=window.location+e);break}}}catch{}break}case"changeMessageStep":{const e=t.gist.parameters.displaySettings,r=t.gist.parameters.messageStepName;(i.persistent||he(s))&&await async function(e,t,s){const i=await Ee(e);if(!i)return;const r=o(i)||{},c={stepName:void 0!==t?t:r.stepName,displaySettings:void 0!==s?s:r.displaySettings},u=new Date;u.setDate(u.getDate()+30),a(i,c,u),n(`Saved message state for queueId: ${e}`)}(s.queueId??"",r,e),e&&function(e,t){const s=(n=e).overlay?"modal":n.elementId&&G.includes(n.elementId)?"overlay":n.elementId?"inline":"modal";var n;const i=t.displayType;if(void 0===i)return!1;if(s!==i)return!0;const a=z(e);switch(i){case"modal":if((e.position||"center")!==(t.modalPosition||"center"))return!0;if(void 0!==t.dismissOutsideClick&&a.exitClick!==t.dismissOutsideClick)return!0;if(void 0!==t.overlayColor&&a.overlayColor!==t.overlayColor)return!0;break;case"overlay":{const s=Y(t.overlayPosition);if(e.elementId!==s)return!0;break}case"inline":if(e.elementId!==t.elementSelector)return!0}return void 0!==t.maxWidth&&a.messageWidth!==t.maxWidth}(s,e)&&(n("Display settings changed, reloading message"),await async function(e){e.overlay?await ae():e.elementId&&ee(e.elementId)}(s),Z(s,e),await async function(e,t){e.isDisplayChange=!0,e.renderStartTime=(new Date).getTime();const s=e.elementId||null;if(s){const t=Q(s);t&&t.instanceId!==e.instanceId&&(n(`Dismissing existing message at ${s} to make room for multi-step message`),await Te(t))}if(e.overlay){Ye.overlayInstanceId=e.instanceId??null;const t=z(e);e.shouldScale=t.shouldScale,e.shouldResizeHeight=!0}else Ye.overlayInstanceId=null,e.shouldScale=!1,e.shouldResizeHeight=!te(s??"");s&&G.includes(s)&&V(s),Le(e,s,t)}(s,r??null));break}case"routeChanged":s.currentRoute=t.gist.parameters.route,s.renderStartTime=(new Date).getTime(),K(e,s),n(`Route changed to: ${s.currentRoute}`);break;case"sizeChanged":n(`Size Changed Width: ${t.gist.parameters.width} - Height: ${t.gist.parameters.height}`),s.elementId&&!s.shouldResizeHeight||function(e,t){const s=ue(e.elementId?e.elementId:re(e.instanceId??""));if(s){const n=s.style;if(t.height>0)if(t.height>window.innerHeight){const s=1-(t.height/window.innerHeight-1);e.shouldScale&&s>=.4?(n.height=`${t.height}px`,n.transform=`translateX(-50%) translateY(-50%) scale(${s})`):n.height=`${window.innerHeight}px`}else n.height=`${t.height}px`}}(s,t.gist.parameters);break;case"titleChanged":n(`Overlay title changed to: ${t.gist.parameters.title}`),function(e,t){const s=ue(re(e));s&&(s.title=t)}(e,t.gist.parameters.title);break;case"eventDispatched":Ye.events.dispatch("eventDispatched",{name:t.gist.parameters.name,payload:t.gist.parameters.payload});break;case"error":case"routeError":Ye.messageError(s),Ye.overlayInstanceId?await Pe(!1,s):Re(s)}}}async function Oe(e){n(`Logging user message view locally for: ${e.queueId}`),fe(e)?await async function(e){n(`Marking broadcast ${e} as seen.`);const t=await ye();if(!t)return;const s=await pe(t,e);if(!s)return;const i=s.properties.gist.broadcast,{frequency:r}=i,c=we(t,e),u=be(t,e),l=o(c)||0;if(a(c,l+1),1===r.count)a(u,!1),n(`Marked broadcast ${e} as seen.`);else{const t=new Date;t.setSeconds(t.getSeconds()+r.delay),a(u,!1,t),n(`Marked broadcast ${e} as seen, broadcast was seen ${l+1} times, next show date is ${t}.`)}}(e.queueId??""):await async function(e){const t=await xe();if(!t)return;const s=o(t)??[];s.push(e),a(t,s)}(e.queueId??"")}async function Ue(e){fe(e)&&(n(`Logging broadcast dismissed locally for: ${e.queueId}`),await async function(e){n(`Marking broadcast ${e} as dismissed.`);const t=await ye();if(!t)return;const s=await pe(t,e);s&&(!0!==s.properties.gist.broadcast.frequency.ignoreDismiss?(a(be(t,e),!1),n(`Marked broadcast ${e} as dismissed and will not show again.`)):n(`Broadcast ${e} is set to ignore dismiss.`))}(e.queueId??""),await Ce(e.queueId??""))}const _e="messageInboxUpdated";async function je(e){const t=await ze();if(!t)return;const s=new Date;s.setMinutes(s.getMinutes()+60),a(t,e,s),Ye.events.dispatch(_e,e)}async function He(){const e=await ze();if(!e)return[];const t=o(e)??[],s=new Date;return t.filter(e=>!e.expiry||new Date(e.expiry)>s)}async function ze(){const e=await _();return e?`gist.web.inbox.messages.${e}`:null}const Ge=(e,t)=>e().then((e=>new Promise(t=>setTimeout(t,e)))(t).then(()=>Ge(e,t)));let Ve=!1,Fe=null;async function Be(){Ve?await Je():O()?(n("Queue watcher started"),Ve=!0,Ge(()=>new Promise(()=>{!async function(){if(x.hasActiveSSEConnection())return!x.isSSEConnectionManagedBySDK()&&Fe&&(n("Not the main instance, closing our SSE connection."),Ke()),void await Je();Fe&&(n("SSE connection not active, closing it."),Ke()),!x.useSSE()||A()?await Xe():await async function(){Ke();const e=function(){const e=j();return null===e?(n("No user token available for SSE endpoint."),null):x.GIST_QUEUE_REALTIME_API_ENDPOINT[Ye.config.env??"prod"]+`/api/v3/sse?userToken=${e}&siteId=${Ye.config.siteId}&sessionId=${P()}`}();if(null===e)return n("SSE endpoint not available, falling back to polling."),void await Xe();n(`Starting SSE queue listener on ${e}`),Fe=new EventSource(e),x.setActiveSSEConnection(),Fe.addEventListener("connected",async e=>{try{n("SSE connection received"),x.setUseSSEFlag(!0);const t=JSON.parse(e.data);t.heartbeat&&(x.setSSEHeartbeat(t.heartbeat),n(`SSE heartbeat set to ${t.heartbeat} seconds`)),x.setActiveSSEConnection()}catch(e){n(`Failed to parse SSE settings: ${e}`)}r(q),await Xe()}),Fe.addEventListener("messages",async e=>{try{const t=JSON.parse(e.data);n("SSE message received"),await Se(t),await me(t),await Je()}catch(e){n(`Failed to parse SSE message: ${e}`),Ke()}}),Fe.addEventListener("inbox_messages",async e=>{try{const t=JSON.parse(e.data);n("SSE inbox messages received"),await je(t)}catch(e){n(`Failed to parse SSE inbox messages: ${e}`)}}),Fe.addEventListener("error",async()=>{n("SSE error received"),Ke()}),Fe.addEventListener("heartbeat",async()=>{n("SSE heartbeat received"),x.setActiveSSEConnection(),x.setUseSSEFlag(!0)})}()}()}),1e3)):n("User token not setup, queue not started.")}async function Je(){const e=await async function(){const e=await ye();return e?(o(e)??[]).filter(t=>{const s=t.properties.gist.broadcast,{frequency:n}=s,i=o(be(e,t.queueId))??!0,a=o(we(e,t.queueId))||0,r=0===n.count;return i&&(r||a<n.count)}):[]}(),t=await async function(){const e=await Ie();if(!e)return[];const t=o(e)??[],s=await async function(){const e=await xe();return e?o(e)??[]:[]}();return t.filter(e=>!s.includes(e.queueId??""))}(),s=e.concat(t);n(`Messages in local queue: ${s.length}`);const i=s.sort((e,t)=>e.priority-t.priority);for(const e of i)await Qe(e)}async function Qe(e){let t=z(e);if(t.hasRouteRule){let e=Ye.currentRoute;null==e&&(e=new URL(window.location.href).pathname);const s=t.routeRule;if(n(`Verifying route ${e} against rule: ${s}`),!new RegExp(s).test(e))return n(`Route ${e} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),t.persistent||he(e)){const s=await async function(e){const t=await Ee(e);return t?o(t):null}(e.queueId??"");s&&(n(`Restoring saved state for queueId ${e.queueId}`),s.displaySettings&&(Z(e,s.displaySettings),t=z(e)),e.savedStepName=s.stepName??null)}if(t.persistent||he(e)||!await async function(e){const t=await $e(e);return!!t&&null!==o(t)}(e.queueId??"")){let s=null;return s=t.isEmbedded?De(e,t.elementId):await ke(e),s&&async function(e){const t=await $e(e);t&&a(t,!0,new Date(Date.now()+5e3))}(e.queueId??""),null!==s}return n(`Not showing message with queueId ${e.queueId} because its already loading.`),!1}async function Xe(){if(O())if(Ye.isDocumentVisible)if(null===o(q)){const e=await async function(){const e=O();let t;try{if(!M){M=!0;const e={"X-Gist-User-Anonymous":String(A()),"Content-Language":String(D())};t=await C().post(`/api/v4/users?sessionId=${P()}`,{},{headers:e})}}catch(e){const s=E(e);s?t=s:n(`Error getting user queue: ${e}`)}finally{M=!1}return e!==O()?(n("User token changed, clearing queue next pull check."),void r(q)):(function(e){if(e?.headers){const t=e.headers["x-gist-queue-polling-interval"];t&&Number(t)>0&&(T=Number(t))}const t=new Date((new Date).getTime()+1e3*T);a(q,T,t)}(t),function(e){const t="true"===e?.headers?.["x-cio-use-sse"]?.toLowerCase();x.setUseSSEFlag(t)}(t),t)}();if(e){if(200===e.status||204===e.status){n("200 response, updating local store.");const t=e.data,s=t?.inAppMessages??[],i=t?.inboxMessages??[];Se(s),me(s),je(i)}else 304===e.status&&n("304 response, using local store.");await Je()}else n("No response object returned while checking message queue.")}else n("Next queue pull scheduled for later.");else n("Document not visible, skipping queue check.");else n("User token reset, skipping queue check.")}function Ke(e=!1){e&&x.removeActiveSSEConnection(),(e||x.isSSEConnectionManagedBySDK())&&x.setUseSSEFlag(!1),Fe&&(n("Stopping SSE queue listener..."),Fe.close(),Fe=null)}const Ye=class{static events;static config;static initialized;static currentMessages;static overlayInstanceId;static currentRoute;static isDocumentVisible;static async setup(e){this.initialized?n("Gist SDK already initialized, skipping setup."):(this.initialized=!0,this.events=new s,this.config={useAnonymousSession:void 0!==e.useAnonymousSession&&e.useAnonymousSession,siteId:e.siteId,dataCenter:e.dataCenter,env:void 0===e.env?"prod":e.env,logging:void 0!==e.logging&&e.logging,experiments:void 0!==e.experiments&&e.experiments},this.currentMessages=[],this.overlayInstanceId=null,this.currentRoute=null,this.isDocumentVisible=!0,this.config.isPreviewSession=function(){const e=new URLSearchParams(window.location.search).get("cioPreviewId");return e&&(sessionStorage.setItem(i,String(!1)),Ye.setUserToken(e),n(`Preview mode enabled with user token: ${e}`)),!c()}(),function(){const e=u();for(let t=e.length-1;t>=0;t--)l(e.key(t))}(),n(`Setup complete on ${this.config.env} environment.`),this.config.isPreviewSession||!this.config.useAnonymousSession||new URLSearchParams(location.search).has("ajs_uid")||U(),await Be(),document.addEventListener("visibilitychange",async()=>{"hidden"===document.visibilityState?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await Je())},!1))}static async setCurrentRoute(e){this.currentRoute=e,n(`Current route set to: ${e}`),await async function(){if(0!==Ye.currentMessages.length)for(const e of[...Ye.currentMessages])null==document.querySelector(`#gist-${e.instanceId}`)&&(n(`Removing active message ${e.instanceId} that no longer exists after route change`),await Me(e))}(),await Je()}static async setUserToken(e,t){this.config.isPreviewSession||(function(e,t){void 0===t&&(t=new Date).setDate(t.getDate()+30),a(L,e,t),A()&&(r(q),r(N)),n(`Set user token "${e}" with expiry date set to ${t}`)}(e,t),Ke(!0),await Be())}static setUserLocale(e){var t;a(k,t=e),n(`Set user locate to "${t}"`)}static setCustomAttribute(e,t){return function(e,t){return e&&"string"==typeof e?(de.set(e,t),ge(),n(`Set custom attribute "${e}" to "${t}"`),!0):(n(`Invalid key for custom attribute: ${e}`),!1)}(e,t)}static clearCustomAttributes(){de.clear(),r(le),n("Cleared all custom attributes")}static removeCustomAttribute(e){return function(e){if(!e||"string"!=typeof e)return n(`Invalid key for custom attribute: ${e}`),!1;const t=de.has(e);return de.delete(e),de.size>0?ge():r(le),n(`Removed custom attribute "${e}"`),t}(e)}static async clearUserToken(){this.config.isPreviewSession||(r(L),n("Cleared user token"),this.config.useAnonymousSession&&U(),Ke(!0),await Be())}static async dismissMessage(e){var t=B(e);await Te(t),await qe(t),await Ue(t),await Je()}static async embedMessage(e,t){var s=De(e,t);return s?s.instanceId:null}static async showMessage(e){var t=await ke(e);return t?t.instanceId:null}static updateMessageDisplaySettings(e,t){var s=B(e);return!!s&&(s.displaySettings=t,ie(s),!0)}static messageShown(e){n(`Message shown: ${e.messageId}`),this.events.dispatch("messageShown",e)}static messageDismissed(e){null!==e&&(n(`Message dismissed: ${e.messageId}`),this.events.dispatch("messageDismissed",e))}static messageError(e){n(`Message error: ${e.messageId}`),this.events.dispatch("messageError",e)}static messageAction(e,t,s){n(`Message action: ${e.currentRoute}, ${t} with name ${s} on ${e.instanceId}`),this.events.dispatch("messageAction",{message:e,action:t,name:s})}static async getInboxUnopenedCount(){return(await He()).filter(e=>!e.opened).length}static async getInboxMessages(){return await He()}static async updateInboxMessageOpenState(e,t){return await async function(e,t){const s=await ze();if(!s)return;const i=await async function(e,t){try{return await C()(`/api/v1/messages/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}catch(e){return E(e)}}(e,{opened:t});if(!i||i.status<200||i.status>=300){const e=`Failed to mark inbox message opened: ${i?.status??"unknown error"}`;throw n(e),new Error(e)}const o=await He();let r=null;const c=o.map(s=>{if(s.queueId===e){const e={...s,opened:t};return r=e,e}return s}),u=new Date;if(u.setMinutes(u.getMinutes()+60),a(s,c,u),r){const e=t?"opened":"unopened";Ye.events.dispatch("inboxMessageAction",{message:r,action:e})}Ye.events.dispatch(_e,await He())}(e,t)}static async removeInboxMessage(e){return await async function(e){const t=await ze();if(!t)return;const s=await H(e);if(!s||s.status<200||s.status>=300){const e=`Failed to remove inbox message: ${s?.status??"unknown error"}`;throw n(e),new Error(e)}const i=(await He()).filter(t=>t.queueId!==e),o=new Date;o.setMinutes(o.getMinutes()+60),a(t,i,o),Ye.events.dispatch(_e,await He())}(e)}};return t.default})());
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Gist=t():e.Gist=t()}(this,()=>(()=>{"use strict";var e={d:(t,n)=>{for(var s in n)e.o(n,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:n[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>Ye});class n{constructor(){this.callbacks={}}on(e,t){const n=this.callbacks[e];n?n.push(t):this.callbacks[e]=[t]}off(e,t){const n=this.callbacks[e];if(!n)return;if(!t)return void delete this.callbacks[e];const s=n.indexOf(t);-1!==s&&n.splice(s,1),0===n.length&&delete this.callbacks[e]}dispatch(e,t){const n=this.callbacks[e];n&&n.forEach(e=>e(t))}}function s(e){Ye.config&&Ye.config.logging&&console.log(`Gist: ${e}`)}const i="gist.web.isPersistingSession";function o(e,t,n=null){let s=n;s||(s=new Date,s.setDate(s.getDate()+365));const i={value:t,expiry:s};u().setItem(e,JSON.stringify(i))}function a(e){return l(e)}function r(e){u().removeItem(e)}function c(){const e=sessionStorage.getItem(i);return null===e?(sessionStorage.setItem(i,"true"),!0):"true"===e}function u(){return c()?localStorage:sessionStorage}function l(e){if(!e)return null;try{const t=u().getItem(e);if(!t)return null;const n=JSON.parse(t);if(!n.expiry)return n.value;const s=new Date,i=new Date(n.expiry),o=e.startsWith("gist.web.message.broadcasts")&&!e.endsWith("shouldShow")&&!e.endsWith("numberOfTimesShown")||e.startsWith("gist.web.message.user")&&!e.endsWith("seen")&&!e.endsWith("state"),a=new Date(s.getTime()+366e4);return o&&i.getTime()>a.getTime()||s.getTime()>i.getTime()?(r(e),null):n.value}catch(t){s(`Error checking key ${e} for expiry: ${t}`)}return null}var d,g=new Uint8Array(16);function m(){if(!d&&!(d="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return d(g)}const p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var f=[],h=0;h<256;++h)f.push((h+256).toString(16).substr(1));const w=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(f[e[t+0]]+f[e[t+1]]+f[e[t+2]]+f[e[t+3]]+"-"+f[e[t+4]]+f[e[t+5]]+"-"+f[e[t+6]]+f[e[t+7]]+"-"+f[e[t+8]]+f[e[t+9]]+"-"+f[e[t+10]]+f[e[t+11]]+f[e[t+12]]+f[e[t+13]]+f[e[t+14]]+f[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n},y=function(e,t,n){var s=(e=e||{}).random||(e.rng||m)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(var i=0;i<16;++i)t[n+i]=s[i];return t}return w(s)},b="gist.web.userQueueUseSSE",S="gist.web.activeSSEConnection";let v,I=30;const $={RENDERER_HOST:"https://code.gist.build",ENGINE_API_ENDPOINT:{prod:"https://engine.api.gist.build",dev:"https://engine.api.dev.gist.build",local:"http://engine.api.local.gist.build:82"},GIST_QUEUE_API_ENDPOINT:{prod:"https://consumer.cloud.gist.build",dev:"https://consumer.cloud.dev.gist.build",local:"http://api.local.gist.build:86"},GIST_QUEUE_REALTIME_API_ENDPOINT:{prod:"https://realtime.cloud.gist.build",dev:"https://realtime.cloud.dev.gist.build",local:"http://api.local.gist.build:3000"},GIST_VIEW_ENDPOINT:{prod:"https://renderer.gist.build/3.0",dev:"https://renderer.gist.build/3.0",local:"http://app.local.gist.build:8080/web"},getSdkId:()=>(v||(v=y()),v),useSSE:()=>a(b)??!1,setUseSSEFlag(e){o(b,e,new Date((new Date).getTime()+6e4)),s(`Set user uses SSE to "${e}"`)},removeActiveSSEConnection(){r(S)},setActiveSSEConnection(){o(S,$.getSdkId(),new Date((new Date).getTime()+$.getSSEHeartbeat()))},hasActiveSSEConnection:()=>a(S)??!1,isSSEConnectionManagedBySDK:()=>a(S)===$.getSdkId(),getSSEHeartbeat:()=>1e3*(I+5),setSSEHeartbeat(e){e&&e>0&&(I=e)}};function x(e){return null!==e&&"object"==typeof e&&"response"in e}function E(e){return x(e)?e.response:void 0}function C(){const e=$.GIST_QUEUE_API_ENDPOINT[Ye.config.env??"prod"],t={"X-CIO-Site-Id":Ye.config.siteId,"X-CIO-Client-Platform":"web"},n=j();async function s(n,s={}){const i=e+n,o=new AbortController,a=setTimeout(()=>o.abort(),5e3);try{const e=await fetch(i,{method:s.method||"GET",headers:{...t,...s.headers||{}},body:s.method&&"GET"!==s.method.toUpperCase()?s.body:void 0,signal:o.signal});clearTimeout(a);const n=e.headers.get("content-type")?.includes("application/json"),r=n?await e.json():await e.text(),c=Object.fromEntries(e.headers.entries());if(e.status<200||e.status>=400)throw function(e){return Object.assign(new Error,{response:e})}({status:e.status,data:r,headers:c});return{status:e.status,headers:c,data:r}}catch(e){if(clearTimeout(a),x(e))throw e;if(e instanceof Error)throw Object.assign(e,{response:{status:0,data:e.message||"Unknown error",headers:{}}});throw e}}return null!=n&&(t["X-Gist-Encoded-User-Token"]=n),s.post=(e,t={},n={})=>s(e,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n.headers||{}}}),s}const k="gist.web.userLocale";function D(){const e=a(k);return null!==e?e:navigator.language}let T=600,M=!1;const q="gist.web.userQueueNextPullCheck",P="gist.web.sessionId";function R(){let e=a(P);return e||(e=y()),o(P,e,new Date((new Date).getTime()+18e5)),String(e)}const L="gist.web.userToken",N="gist.web.usingGuestUserToken",W="gist.web.guestUserToken";function A(){return null!==a(N)}function O(){return a(L)}function U(){if(null===O()){let e=a(W);null==e&&(e=y(),o(W,e),s(`Set guest user token "${e}" with expiry date set to 1 year from today`)),o(L,e),o(N,!0),s(`Using anonymous session with token: "${e}"`)}}async function _(){const e=O();return null===e?null:await async function(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}(e)}function j(){const e=O();return null===e?null:btoa(e)}async function H(e){try{return await C().post(`/api/v1/logs/queue/${e}`)}catch(e){return E(e)}}function G(e){const t={isEmbedded:!1,elementId:"",hasRouteRule:!1,routeRule:"",position:"",hasPosition:!1,shouldScale:!1,campaignId:null,messageWidth:414,overlayColor:"#00000033",persistent:!1,exitClick:!1,hasCustomWidth:!1},n=e?.properties?.gist;return n?{isEmbedded:!!n.elementId,elementId:n.elementId||"",hasRouteRule:!!n.routeRuleWeb,routeRule:n.routeRuleWeb||"",position:n.position||"",hasPosition:!!n.position,shouldScale:!!n.scale,campaignId:n.campaignId??null,messageWidth:null!=n.messageWidth&&n.messageWidth>0?n.messageWidth:t.messageWidth,hasCustomWidth:(n.messageWidth??0)>0,overlayColor:n.overlayColor||t.overlayColor,persistent:!!n.persistent,exitClick:!!n.exitClick}:t}const z=["x-gist-top","x-gist-floating-top","x-gist-bottom","x-gist-floating-bottom","x-gist-floating-bottom-left","x-gist-floating-bottom-right","x-gist-floating-top-left","x-gist-floating-top-right"];function V(e){if(document.getElementById(e))return;const t=document.createElement("div");t.id=e,"x-gist-top"===e?document.body.insertBefore(t,document.body.firstChild):document.body.insertAdjacentElement("beforeend",t),s("Top & bottom elements injected into page")}const F=["x-gist-top","x-gist-bottom","x-gist-floating-top","x-gist-floating-bottom"];function B(e){return Ye.currentMessages.find(t=>t.instanceId===e)}function J(e){return!!e&&Ye.currentMessages.some(t=>t.queueId===e)}function Q(e){return e?Ye.currentMessages.find(t=>t.elementId===e)??null:null}function X(e){Ye.currentMessages=Ye.currentMessages.filter(t=>t.instanceId!==e)}function K(e,t){X(e),Ye.currentMessages.push(t)}function Y(e){const t={topLeft:"x-gist-floating-top-left",topCenter:"x-gist-floating-top",topRight:"x-gist-floating-top-right",bottomLeft:"x-gist-floating-bottom-left",bottomCenter:"x-gist-floating-bottom",bottomRight:"x-gist-floating-bottom-right"};return e&&t[e]?t[e]:(s(`Invalid overlay position "${e}", defaulting to "topCenter"`),t.topCenter)}function Z(e,t){if(e.properties||(e.properties={}),e.properties.gist||(e.properties.gist={}),"modal"===t.displayType)e.overlay=!0,e.elementId=null,e.properties.gist.elementId=null,e.position=t.modalPosition||"center",e.properties.gist.position=t.modalPosition||"center";else if("overlay"===t.displayType){e.overlay=!1;const n=Y(t.overlayPosition);e.elementId=n,e.properties.gist.elementId=n,e.position=null,e.properties.gist.position=null}else"inline"===t.displayType&&(e.overlay=!1,e.elementId=t.elementSelector,e.properties.gist.elementId=t.elementSelector,e.position=null,e.properties.gist.position=null);e.elementId&&F.includes(e.elementId)?delete e.properties.gist.messageWidth:void 0!==t.maxWidth&&t.maxWidth>0?e.properties.gist.messageWidth=t.maxWidth:delete e.properties.gist.messageWidth,void 0!==t.overlayColor?e.properties.gist.overlayColor=t.overlayColor:delete e.properties.gist.overlayColor,void 0!==t.dismissOutsideClick?e.properties.gist.exitClick=t.dismissOutsideClick:delete e.properties.gist.exitClick}function ee(e){const t=ue(e);t&&(t.classList.remove("gist-visible"),Array.from(t.classList).filter(e=>e.startsWith("gist-")).forEach(e=>t.classList.remove(e)),t.style.removeProperty("height"),t.style.removeProperty("width"),t.innerHTML="")}function te(e){const t=ue(e);if(t)return!(!t.style||!t.style.height||"0px"===t.style.height)}function ne(e,t,n=null){const s=document.getElementById(e);s&&(s.onload=()=>{!function(e,t,n=null){const s=document.getElementById(e);if(s?.contentWindow){const e={options:t,capabilities:se};n&&(t.stepId=n),s.contentWindow.postMessage(e,"*")}}(e,t,n)})}const se=["MultiStepDisplayTypes"];function ie(e){if(!e.displaySettings)return;const t=re(e.instanceId??""),n=document.getElementById(t);n?.contentWindow&&n.contentWindow.postMessage({action:"updateDisplaySettings",displaySettings:e.displaySettings},"*")}async function oe(){const e=document.querySelector(".gist-message");e&&(e.classList.remove("gist-visible"),await new Promise(e=>setTimeout(e,300))),ae()}function ae(){const e=document.querySelector("#gist-embed-message");e&&e.parentNode?.removeChild(e)}function re(e){return`gist-${e}`}function ce(){const e=document.querySelector(".gist-message");e&&e.classList.add("gist-visible")}function ue(e){try{const t=document.querySelector(`#${e}`);return t instanceof HTMLElement?t:null}catch{return null}}const le="gist.web.customAttributes";let de=new Map;function ge(){const e=Array.from(de.entries()),t=new Date;t.setDate(t.getDate()+30),o(le,e,t),s(`Saved ${de.size} custom attributes to storage with TTL of 30 days`)}async function me(e){const t=await we();if(!t)return;const n=new Date;n.setMinutes(n.getMinutes()+60),o(t,e.filter(fe),n)}async function pe(e,t){const n=a(e);return n?.find(e=>e.queueId===t)}function fe(e){return!(!e.properties?.gist||!e.properties.gist.broadcast)}function he(e){if(!fe(e))return!1;const t=e.properties.gist.broadcast;return 0===t.frequency.delay&&0===t.frequency.count}async function we(){const e=await _();return e?`gist.web.message.broadcasts.${e}`:null}function ye(e,t){return`${e}.${t}.numberOfTimesShown`}function be(e,t){return`${e}.${t}.shouldShow`}!function(){const e=a(le);if(e)try{de=new Map(e)}catch{de=new Map}else de=new Map}();const Se="gist.web.message.user";async function ve(e){const t=await Ie();if(!t)return;const n=e.filter(e=>!(e.properties&&e.properties.gist&&e.properties.gist.broadcast)),s=new Date;s.setMinutes(s.getMinutes()+60),o(t,n,s)}async function Ie(){const e=await _();return e?`${Se}.${e}`:null}async function $e(){const e=await _();return e?`${Se}.${e}.seen`:null}async function xe(e){const t=await _();return t?`${Se}.${t}.message.${e}.loading`:null}async function Ee(e){const t=await _();return t?`${Se}.${t}.message.${e}.state`:null}async function Ce(e){const t=await Ee(e);t&&(r(t),s(`Cleared message state for queueId: ${e}`))}async function ke(e){if(Ye.isDocumentVisible){if(J(e.queueId))return s(`Message with queueId ${e.queueId} is already showing.`),null;if(Ye.overlayInstanceId)return s(`Message ${Ye.overlayInstanceId} already showing.`),null;{const t=G(e);return e.instanceId=y(),e.overlay=!0,e.firstLoad=!0,e.shouldResizeHeight=!0,e.shouldScale=t.shouldScale,e.renderStartTime=(new Date).getTime(),Ye.overlayInstanceId=e.instanceId,Ye.currentMessages.push(e),Le(e,null,e.savedStepName||null)}}return s("Document hidden, not showing message now."),null}function De(e,t){return Ye.isDocumentVisible?J(e.queueId)?(s(`Message with queueId ${e.queueId} is already showing.`),null):Q(t)?(s(`Message with elementId ${t} already has a message.`),null):(e.instanceId=y(),e.overlay=!1,e.firstLoad=!0,e.shouldScale=!1,e.elementId=t,e.shouldResizeHeight=!te(t),e.renderStartTime=(new Date).getTime(),Ye.currentMessages.push(e),Le(e,t,e.savedStepName||null)):(s("Document hidden, not showing message now."),null)}async function Te(e){e?(Ye.messageDismissed(e),await Me(e)):s("Message not found")}async function Me(e){e.overlay?await Re(!0,e):Pe(e)}async function qe(e){e?G(e).persistent&&(s("Persistent message dismissed, logging view"),await Oe(e),await Ne(e),await Ce(e.queueId??"")):s("Message not found")}function Pe(e){e.instanceId&&X(e.instanceId),e.elementId&&ee(e.elementId)}async function Re(e,t){e?await oe():ae(),0===Ye.currentMessages.length&&(window.removeEventListener("message",Ae),window.removeEventListener("touchstart",We)),t.instanceId&&X(t.instanceId),Ye.overlayInstanceId=null}function Le(e,t=null,n=null){const i=Ye.config.env,o={endpoint:$.ENGINE_API_ENDPOINT[i],siteId:Ye.config.siteId,dataCenter:Ye.config.dataCenter,messageId:e.messageId,instanceId:e.instanceId??"",livePreview:!1,properties:e.properties,customAttributes:Object.fromEntries(new Map(de))},a=`${$.GIST_VIEW_ENDPOINT[i]}/index.html`;return window.addEventListener("message",Ae),window.addEventListener("touchstart",We),t?(z.includes(t)&&V(t),function(e,t,n,i,o=null){const a=ue(e);if(a){const s=re(n.instanceId??"");a.classList.add(s);const r=G(n);let c=r.messageWidth+"px";F.includes(e)&&!r.hasCustomWidth&&(c="100%"),z.includes(e)&&(a.style.width=c),te(e)||(a.style.height="0px"),a.innerHTML=function(e,t,n){return function(e,t,n){let s=800;return t.messageWidth>s&&(s=t.messageWidth),`\n <div id="gist-embed">\n <style>\n #x-gist-floating-top, #x-gist-floating-top-left, #x-gist-floating-top-right {\n position: fixed;\n top: 0px;\n z-index: 1000000;\n }\n #x-gist-floating-bottom, #x-gist-floating-bottom-left, #x-gist-floating-bottom-right {\n position: fixed;\n bottom: 0px;\n z-index: 1000000;\n }\n #x-gist-bottom, #x-gist-top, #x-gist-floating-top, #x-gist-floating-bottom {\n left: 50%;\n transform: translate(-50%, 0%);\n }\n #x-gist-floating-top-right, #x-gist-floating-bottom-right {\n right: 0px;\n }\n #gist-embed {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container {\n position: relative;\n height: 100%;\n width: 100%;\n }\n #gist-embed-container .gist-frame {\n height: 100%;\n width: 100%;\n border: none;\n }\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n transition: height 0.1s ease-in-out;\n }\n @media (max-width: ${s}px) {\n #x-gist-top.${e},\n #x-gist-bottom.${e},\n #x-gist-floating-top.${e},\n #x-gist-floating-bottom.${e},\n #x-gist-floating-top-left.${e},\n #x-gist-floating-top-right.${e},\n #x-gist-floating-bottom-left.${e},\n #x-gist-floating-bottom-right.${e} {\n width: 100% !important;\n }\n }\n </style>\n <div id="gist-embed-container">\n <iframe id="${e}" class="gist-frame" src="${n}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),n,e)}(t,n,r),ne(s,i,o)}else s(`Message could not be embedded, elementId ${e} not found.`)}(t,a,e,o,n)):function(e,t,n,s=null){document.querySelectorAll("#gist-embed-message").forEach(e=>{e.parentNode?.removeChild(e)}),document.body.insertAdjacentHTML("afterbegin",function(e,t){const n=G(t);return function(e,t,n){let s=600;return t.messageWidth>s&&(s=t.messageWidth),`\n <div id="gist-embed-message">\n <style>\n #gist-overlay.gist-background {\n position: fixed;\n z-index: 9999999998;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: ${t.overlayColor};\n visibility: hidden;\n }\n #gist-overlay.gist-background.gist-visible {\n visibility: visible;\n }\n .gist-message {\n width: ${t.messageWidth}px;\n position: absolute;\n border: none;\n opacity: 0;\n transition: opacity 0.3s ease-in-out, height 0.1s ease-in-out;\n z-index: 9999999999;\n left: 50%;\n transform: translateX(-50%);\n }\n .gist-message.gist-visible {\n opacity: 1;\n pointer-events: auto;\n }\n .gist-message.gist-center {\n transform: translate(-50%, -50%);\n top: 50%;\n }\n .gist-message.gist-bottom {\n bottom: 0;\n }\n .gist-message.gist-top {\n top: 0;\n }\n @media (max-width: ${s}px) {\n .gist-message {\n width: 100%;\n }\n }\n </style>\n <div id="gist-overlay" class="gist-background">\n <iframe id="${e}" class="gist-message" src="${n}"></iframe>\n </div>\n </div>`}(re(t.instanceId??""),n,e)}(e,t)),ne(re(t.instanceId??""),n,s)}(a,e,o,n),e}async function Ne(e){let t;s(`Message shown, logging view for: ${e.messageId}`),null!=e.queueId?(await Oe(e),t=await H(e.queueId)):t=await async function(e){try{return await C().post(`/api/v1/logs/message/${e}`)}catch(e){return E(e)}}(e.messageId),s(200===t?.status?"Message view logged":`Problem logging message: ${t?.status}`)}function We(){}async function Ae(e){const t=e.data;if(t.gist&&e.origin===$.RENDERER_HOST){const e=t.gist.instanceId,n=B(e);if(!n)return;const i=G(n);switch(t.gist.method){case"routeLoaded":{const o=.001*((new Date).getTime()-(n.renderStartTime??0));s(`Engine render for message: ${n.messageId} timer elapsed in ${o.toFixed(3)} seconds`),async function(e){const t=await xe(e);t&&r(t)}(n.queueId??""),n.currentRoute=t.gist.parameters.route,t.gist.parameters.fullDisplaySettings&&!n.displaySettings?n.displaySettings=t.gist.parameters.fullDisplaySettings:n.displaySettings&&(s("SDK already has display settings state, sending it to iframe"),ie(n)),(n.firstLoad||n.isDisplayChange)&&(n.overlay?function(e){const t=G(e),n=document.querySelector("#gist-overlay");if(n){n.classList.add("gist-visible");const s=document.querySelector(".gist-message");s&&(e.position?s.classList.add("gist-"+e.position):s.classList.add("gist-center")),setTimeout(ce,100),t.exitClick&&setTimeout(()=>function(e){const t=document.querySelector("#gist-overlay");t&&t.addEventListener("click",()=>{Ye.dismissMessage(e)})}(e.instanceId??""),1e3)}else ae()}(n):function(e){const t=ue(e);t&&t.classList.add("gist-visible")}(n.elementId),n.firstLoad&&!n.isDisplayChange&&(Ye.messageShown(n),i.persistent?s("Persistent message shown, skipping logging view"):await Ne(n)),n.firstLoad=!1,n.isDisplayChange=!1),K(e,n);break}case"tap":{const e=t.gist.parameters.action,s=t.gist.parameters.name;if(Ye.messageAction(n,e,s),t.gist.parameters.system&&!i.persistent){await Te(n);break}try{const t=new URL(e);if(t&&"gist:"===t.protocol)switch(t.href.replace("gist://","").split("?")[0]){case"close":await Te(n),await qe(n),await Ue(n),await Je();break;case"showMessage":{const e=t.searchParams.get("messageId"),n=t.searchParams.get("properties");if(e){const t=n?JSON.parse(atob(n)):void 0;await Ye.showMessage({messageId:e,properties:t})}break}case"loadPage":{const e=t.href.substring(t.href.indexOf("?url=")+5);e&&(e.startsWith("mailto:")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("/")?window.location.href=e:window.location.href=window.location+e);break}}}catch{}break}case"changeMessageStep":{const e=t.gist.parameters.displaySettings,r=t.gist.parameters.messageStepName;(i.persistent||he(n))&&await async function(e,t,n){const i=await Ee(e);if(!i)return;const r=a(i)||{},c={stepName:void 0!==t?t:r.stepName,displaySettings:void 0!==n?n:r.displaySettings},u=new Date;u.setDate(u.getDate()+30),o(i,c,u),s(`Saved message state for queueId: ${e}`)}(n.queueId??"",r,e),e&&function(e,t){const n=(s=e).overlay?"modal":s.elementId&&z.includes(s.elementId)?"overlay":s.elementId?"inline":"modal";var s;const i=t.displayType;if(void 0===i)return!1;if(n!==i)return!0;const o=G(e);switch(i){case"modal":if((e.position||"center")!==(t.modalPosition||"center"))return!0;if(void 0!==t.dismissOutsideClick&&o.exitClick!==t.dismissOutsideClick)return!0;if(void 0!==t.overlayColor&&o.overlayColor!==t.overlayColor)return!0;break;case"overlay":{const n=Y(t.overlayPosition);if(e.elementId!==n)return!0;break}case"inline":if(e.elementId!==t.elementSelector)return!0}return void 0!==t.maxWidth&&o.messageWidth!==t.maxWidth}(n,e)&&(s("Display settings changed, reloading message"),await async function(e){e.overlay?await oe():e.elementId&&ee(e.elementId)}(n),Z(n,e),await async function(e,t){e.isDisplayChange=!0,e.renderStartTime=(new Date).getTime();const n=e.elementId||null;if(n){const t=Q(n);t&&t.instanceId!==e.instanceId&&(s(`Dismissing existing message at ${n} to make room for multi-step message`),await Te(t))}if(e.overlay){Ye.overlayInstanceId=e.instanceId??null;const t=G(e);e.shouldScale=t.shouldScale,e.shouldResizeHeight=!0}else Ye.overlayInstanceId=null,e.shouldScale=!1,e.shouldResizeHeight=!te(n??"");n&&z.includes(n)&&V(n),Le(e,n,t)}(n,r??null));break}case"routeChanged":n.currentRoute=t.gist.parameters.route,n.renderStartTime=(new Date).getTime(),K(e,n),s(`Route changed to: ${n.currentRoute}`);break;case"sizeChanged":s(`Size Changed Width: ${t.gist.parameters.width} - Height: ${t.gist.parameters.height}`),n.elementId&&!n.shouldResizeHeight||function(e,t){const n=ue(e.elementId?e.elementId:re(e.instanceId??""));if(n){const s=n.style;if(t.height>0)if(t.height>window.innerHeight){const n=1-(t.height/window.innerHeight-1);e.shouldScale&&n>=.4?(s.height=`${t.height}px`,s.transform=`translateX(-50%) translateY(-50%) scale(${n})`):s.height=`${window.innerHeight}px`}else s.height=`${t.height}px`}}(n,t.gist.parameters);break;case"titleChanged":s(`Overlay title changed to: ${t.gist.parameters.title}`),function(e,t){const n=ue(re(e));n&&(n.title=t)}(e,t.gist.parameters.title);break;case"eventDispatched":Ye.events.dispatch("eventDispatched",{name:t.gist.parameters.name,payload:t.gist.parameters.payload});break;case"error":case"routeError":Ye.messageError(n),Ye.overlayInstanceId?await Re(!1,n):Pe(n)}}}async function Oe(e){s(`Logging user message view locally for: ${e.queueId}`),fe(e)?await async function(e){s(`Marking broadcast ${e} as seen.`);const t=await we();if(!t)return;const n=await pe(t,e);if(!n)return;const i=n.properties.gist.broadcast,{frequency:r}=i,c=ye(t,e),u=be(t,e),l=a(c)||0;if(o(c,l+1),1===r.count)o(u,!1),s(`Marked broadcast ${e} as seen.`);else{const t=new Date;t.setSeconds(t.getSeconds()+r.delay),o(u,!1,t),s(`Marked broadcast ${e} as seen, broadcast was seen ${l+1} times, next show date is ${t}.`)}}(e.queueId??""):await async function(e){const t=await $e();if(!t)return;const n=a(t)??[];n.push(e),o(t,n)}(e.queueId??"")}async function Ue(e){fe(e)&&(s(`Logging broadcast dismissed locally for: ${e.queueId}`),await async function(e){s(`Marking broadcast ${e} as dismissed.`);const t=await we();if(!t)return;const n=await pe(t,e);n&&(!0!==n.properties.gist.broadcast.frequency.ignoreDismiss?(o(be(t,e),!1),s(`Marked broadcast ${e} as dismissed and will not show again.`)):s(`Broadcast ${e} is set to ignore dismiss.`))}(e.queueId??""),await Ce(e.queueId??""))}const _e="messageInboxUpdated";async function je(e){const t=await Ge();if(!t)return;const n=new Date;n.setMinutes(n.getMinutes()+60),o(t,e,n),Ye.events.dispatch(_e,e)}async function He(){const e=await Ge();if(!e)return[];const t=a(e)??[],n=new Date;return t.filter(e=>!e.expiry||new Date(e.expiry)>n)}async function Ge(){const e=await _();return e?`gist.web.inbox.messages.${e}`:null}const ze=(e,t)=>e().then((e=>new Promise(t=>setTimeout(t,e)))(t).then(()=>ze(e,t)));let Ve=!1,Fe=null;async function Be(){Ve?await Je():O()?(s("Queue watcher started"),Ve=!0,ze(()=>new Promise(()=>{!async function(){if($.hasActiveSSEConnection())return!$.isSSEConnectionManagedBySDK()&&Fe&&(s("Not the main instance, closing our SSE connection."),Ke()),void await Je();Fe&&(s("SSE connection not active, closing it."),Ke()),!$.useSSE()||A()?await Xe():await async function(){Ke();const e=function(){const e=j();return null===e?(s("No user token available for SSE endpoint."),null):$.GIST_QUEUE_REALTIME_API_ENDPOINT[Ye.config.env??"prod"]+`/api/v3/sse?userToken=${e}&siteId=${Ye.config.siteId}&sessionId=${R()}`}();if(null===e)return s("SSE endpoint not available, falling back to polling."),void await Xe();s(`Starting SSE queue listener on ${e}`),Fe=new EventSource(e),$.setActiveSSEConnection(),Fe.addEventListener("connected",async e=>{try{s("SSE connection received"),$.setUseSSEFlag(!0);const t=JSON.parse(e.data);t.heartbeat&&($.setSSEHeartbeat(t.heartbeat),s(`SSE heartbeat set to ${t.heartbeat} seconds`)),$.setActiveSSEConnection()}catch(e){s(`Failed to parse SSE settings: ${e}`)}r(q),await Xe()}),Fe.addEventListener("messages",async e=>{try{const t=JSON.parse(e.data);s("SSE message received"),await ve(t),await me(t),await Je()}catch(e){s(`Failed to parse SSE message: ${e}`),Ke()}}),Fe.addEventListener("inbox_messages",async e=>{try{const t=JSON.parse(e.data);s("SSE inbox messages received"),await je(t)}catch(e){s(`Failed to parse SSE inbox messages: ${e}`)}}),Fe.addEventListener("error",async()=>{s("SSE error received"),Ke()}),Fe.addEventListener("heartbeat",async()=>{s("SSE heartbeat received"),$.setActiveSSEConnection(),$.setUseSSEFlag(!0)})}()}()}),1e3)):s("User token not setup, queue not started.")}async function Je(){const e=await async function(){const e=await we();return e?(a(e)??[]).filter(t=>{const n=t.properties.gist.broadcast,{frequency:s}=n,i=a(be(e,t.queueId))??!0,o=a(ye(e,t.queueId))||0,r=0===s.count;return i&&(r||o<s.count)}):[]}(),t=await async function(){const e=await Ie();if(!e)return[];const t=a(e)??[],n=await async function(){const e=await $e();return e?a(e)??[]:[]}();return t.filter(e=>!n.includes(e.queueId??""))}(),n=e.concat(t);s(`Messages in local queue: ${n.length}`);const i=n.sort((e,t)=>e.priority-t.priority);for(const e of i)await Qe(e)}async function Qe(e){let t=G(e);if(t.hasRouteRule){let e=Ye.currentRoute;null==e&&(e=new URL(window.location.href).pathname);const n=t.routeRule;if(s(`Verifying route ${e} against rule: ${n}`),!new RegExp(n).test(e))return s(`Route ${e} does not match rule.`),!1}if(t.hasPosition&&(e.position=t.position),t.persistent||he(e)){const n=await async function(e){const t=await Ee(e);return t?a(t):null}(e.queueId??"");n&&(s(`Restoring saved state for queueId ${e.queueId}`),n.displaySettings&&(Z(e,n.displaySettings),t=G(e)),e.savedStepName=n.stepName??null)}if(t.persistent||he(e)||!await async function(e){const t=await xe(e);return!!t&&null!==a(t)}(e.queueId??"")){let n=null;return n=t.isEmbedded?De(e,t.elementId):await ke(e),n&&async function(e){const t=await xe(e);t&&o(t,!0,new Date(Date.now()+5e3))}(e.queueId??""),null!==n}return s(`Not showing message with queueId ${e.queueId} because its already loading.`),!1}async function Xe(){if(O())if(Ye.isDocumentVisible)if(null===a(q)){const e=await async function(){const e=O();let t;try{if(!M){M=!0;const e={"X-Gist-User-Anonymous":String(A()),"Content-Language":String(D())};t=await C().post(`/api/v4/users?sessionId=${R()}`,{},{headers:e})}}catch(e){const n=E(e);n?t=n:s(`Error getting user queue: ${e}`)}finally{M=!1}return e!==O()?(s("User token changed, clearing queue next pull check."),void r(q)):(function(e){if(e?.headers){const t=e.headers["x-gist-queue-polling-interval"];t&&Number(t)>0&&(T=Number(t))}const t=new Date((new Date).getTime()+1e3*T);o(q,T,t)}(t),function(e){const t="true"===e?.headers?.["x-cio-use-sse"]?.toLowerCase();$.setUseSSEFlag(t)}(t),t)}();if(e){if(200===e.status||204===e.status){s("200 response, updating local store.");const t=e.data,n=t?.inAppMessages??[],i=t?.inboxMessages??[];ve(n),me(n),je(i)}else 304===e.status&&s("304 response, using local store.");await Je()}else s("No response object returned while checking message queue.")}else s("Next queue pull scheduled for later.");else s("Document not visible, skipping queue check.");else s("User token reset, skipping queue check.")}function Ke(e=!1){e&&$.removeActiveSSEConnection(),(e||$.isSSEConnectionManagedBySDK())&&$.setUseSSEFlag(!1),Fe&&(s("Stopping SSE queue listener..."),Fe.close(),Fe=null)}class Ye{static async setup(e){this.initialized?s("Gist SDK already initialized, skipping setup."):(this.initialized=!0,this.events=new n,this.config={useAnonymousSession:e.useAnonymousSession??!1,siteId:e.siteId,dataCenter:e.dataCenter,env:e.env??"prod",logging:e.logging??!1,experiments:e.experiments??!1},this.currentMessages=[],this.overlayInstanceId=null,this.currentRoute=null,this.isDocumentVisible=!0,this.config.isPreviewSession=function(){const e=new URLSearchParams(window.location.search).get("cioPreviewId");return e&&(sessionStorage.setItem(i,String(!1)),Ye.setUserToken(e),s(`Preview mode enabled with user token: ${e}`)),!c()}(),function(){const e=u();for(let t=e.length-1;t>=0;t--)l(e.key(t))}(),s(`Setup complete on ${this.config.env} environment.`),this.config.isPreviewSession||!this.config.useAnonymousSession||new URLSearchParams(location.search).has("ajs_uid")||U(),await Be(),document.addEventListener("visibilitychange",async()=>{"hidden"===document.visibilityState?this.isDocumentVisible=!1:(this.isDocumentVisible=!0,await Je())},!1))}static async setCurrentRoute(e){this.currentRoute=e,s(`Current route set to: ${e}`),await async function(){if(0!==Ye.currentMessages.length)for(const e of[...Ye.currentMessages])null==document.querySelector(`#gist-${e.instanceId}`)&&(s(`Removing active message ${e.instanceId} that no longer exists after route change`),await Me(e))}(),await Je()}static async setUserToken(e,t){this.config.isPreviewSession||(function(e,t){void 0===t&&(t=new Date).setDate(t.getDate()+30),o(L,e,t),A()&&(r(q),r(N)),s(`Set user token "${e}" with expiry date set to ${t}`)}(e,t),Ke(!0),await Be())}static setUserLocale(e){var t;o(k,t=e),s(`Set user locate to "${t}"`)}static setCustomAttribute(e,t){return function(e,t){return e&&"string"==typeof e?(de.set(e,t),ge(),s(`Set custom attribute "${e}" to "${t}"`),!0):(s(`Invalid key for custom attribute: ${e}`),!1)}(e,t)}static clearCustomAttributes(){de.clear(),r(le),s("Cleared all custom attributes")}static removeCustomAttribute(e){return function(e){if(!e||"string"!=typeof e)return s(`Invalid key for custom attribute: ${e}`),!1;const t=de.has(e);return de.delete(e),de.size>0?ge():r(le),s(`Removed custom attribute "${e}"`),t}(e)}static async clearUserToken(){this.config.isPreviewSession||(r(L),s("Cleared user token"),this.config.useAnonymousSession&&U(),Ke(!0),await Be())}static async dismissMessage(e){const t=B(e);t&&(await Te(t),await qe(t),await Ue(t),await Je())}static async embedMessage(e,t){const n=De(e,t);return n?.instanceId??null}static async showMessage(e){const t=await ke(e);return t?.instanceId??null}static updateMessageDisplaySettings(e,t){const n=B(e);return!!n&&(n.displaySettings=t,ie(n),!0)}static messageShown(e){s(`Message shown: ${e.messageId}`),this.events.dispatch("messageShown",e)}static messageDismissed(e){null!==e&&(s(`Message dismissed: ${e.messageId}`),this.events.dispatch("messageDismissed",e))}static messageError(e){s(`Message error: ${e.messageId}`),this.events.dispatch("messageError",e)}static messageAction(e,t,n){s(`Message action: ${e.currentRoute}, ${t} with name ${n} on ${e.instanceId}`),this.events.dispatch("messageAction",{message:e,action:t,name:n})}static async getInboxUnopenedCount(){return(await He()).filter(e=>!e.opened).length}static async getInboxMessages(){return await He()}static async updateInboxMessageOpenState(e,t){return await async function(e,t){const n=await Ge();if(!n)return;const i=await async function(e,t){try{return await C()(`/api/v1/messages/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}})}catch(e){return E(e)}}(e,{opened:t});if(!i||i.status<200||i.status>=300){const e=`Failed to mark inbox message opened: ${i?.status??"unknown error"}`;throw s(e),new Error(e)}const a=await He();let r=null;const c=a.map(n=>{if(n.queueId===e){const e={...n,opened:t};return r=e,e}return n}),u=new Date;if(u.setMinutes(u.getMinutes()+60),o(n,c,u),r){const e=t?"opened":"unopened";Ye.events.dispatch("inboxMessageAction",{message:r,action:e})}Ye.events.dispatch(_e,await He())}(e,t)}static async removeInboxMessage(e){return await async function(e){const t=await Ge();if(!t)return;const n=await H(e);if(!n||n.status<200||n.status>=300){const e=`Failed to remove inbox message: ${n?.status??"unknown error"}`;throw s(e),new Error(e)}const i=(await He()).filter(t=>t.queueId!==e),a=new Date;a.setMinutes(a.getMinutes()+60),o(t,i,a),Ye.events.dispatch(_e,await He())}(e)}}return t.default})());
|
package/dist/types/gist.d.ts
CHANGED
|
@@ -1,37 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
static
|
|
6
|
-
|
|
1
|
+
import EventEmitter from "./utilities/event-emitter";
|
|
2
|
+
import type { GistConfig, GistMessage, DisplaySettings } from "./types";
|
|
3
|
+
import type { InboxMessage } from "./managers/inbox-message-manager";
|
|
4
|
+
export default class Gist {
|
|
5
|
+
static events: EventEmitter;
|
|
6
|
+
static config: GistConfig;
|
|
7
7
|
static initialized: boolean;
|
|
8
|
-
|
|
9
|
-
static currentMessages: any[];
|
|
10
|
-
/** @type {string | null} */
|
|
8
|
+
static currentMessages: GistMessage[];
|
|
11
9
|
static overlayInstanceId: string | null;
|
|
12
|
-
/** @type {string | null} */
|
|
13
10
|
static currentRoute: string | null;
|
|
14
|
-
/** @type {boolean} */
|
|
15
11
|
static isDocumentVisible: boolean;
|
|
16
|
-
static setup(config:
|
|
17
|
-
static setCurrentRoute(route:
|
|
18
|
-
/** @param {string} userToken @param {Date} [expiryDate] */
|
|
12
|
+
static setup(config: GistConfig): Promise<void>;
|
|
13
|
+
static setCurrentRoute(route: string): Promise<void>;
|
|
19
14
|
static setUserToken(userToken: string, expiryDate?: Date): Promise<void>;
|
|
20
|
-
static setUserLocale(userLocale:
|
|
21
|
-
static setCustomAttribute(key:
|
|
15
|
+
static setUserLocale(userLocale: string): void;
|
|
16
|
+
static setCustomAttribute(key: string, value: unknown): boolean;
|
|
22
17
|
static clearCustomAttributes(): void;
|
|
23
|
-
static removeCustomAttribute(key:
|
|
18
|
+
static removeCustomAttribute(key: string): boolean;
|
|
24
19
|
static clearUserToken(): Promise<void>;
|
|
25
|
-
static dismissMessage(instanceId:
|
|
26
|
-
static embedMessage(message:
|
|
27
|
-
static showMessage(message:
|
|
28
|
-
static updateMessageDisplaySettings(instanceId:
|
|
29
|
-
static messageShown(message:
|
|
30
|
-
static messageDismissed(message:
|
|
31
|
-
static messageError(message:
|
|
32
|
-
static messageAction(message:
|
|
20
|
+
static dismissMessage(instanceId: string): Promise<void>;
|
|
21
|
+
static embedMessage(message: GistMessage, elementId: string): Promise<string | null>;
|
|
22
|
+
static showMessage(message: GistMessage): Promise<string | null>;
|
|
23
|
+
static updateMessageDisplaySettings(instanceId: string, displaySettings: DisplaySettings): boolean;
|
|
24
|
+
static messageShown(message: GistMessage): void;
|
|
25
|
+
static messageDismissed(message: GistMessage | null): void;
|
|
26
|
+
static messageError(message: GistMessage): void;
|
|
27
|
+
static messageAction(message: GistMessage, action: string, name: string): void;
|
|
33
28
|
static getInboxUnopenedCount(): Promise<number>;
|
|
34
|
-
static getInboxMessages(): Promise<
|
|
35
|
-
static updateInboxMessageOpenState(queueId:
|
|
36
|
-
static removeInboxMessage(queueId:
|
|
29
|
+
static getInboxMessages(): Promise<InboxMessage[]>;
|
|
30
|
+
static updateInboxMessageOpenState(queueId: string, opened: boolean): Promise<void>;
|
|
31
|
+
static removeInboxMessage(queueId: string): Promise<void>;
|
|
37
32
|
}
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/types.d.ts
CHANGED