@saasquatch/squatch-js 2.8.3-6 → 2.8.3-8

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/squatch.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(u,g){typeof exports=="object"&&typeof module<"u"?g(exports):(u=typeof globalThis<"u"?globalThis:u||self,g(u.squatch={}))})(this,function(u){"use strict";var st=Object.defineProperty;var rt=(u,g,A)=>g in u?st(u,g,{enumerable:!0,configurable:!0,writable:!0,value:A}):u[g]=A;var l=(u,g,A)=>rt(u,typeof g!="symbol"?g+"":g,A);var fe;let g=null;function A(o){const e=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");g=new RegExp(`^${e}$`)}function Ee(){g=null}function E(o){const t=(...e)=>{g&&g.test(o)&&console.log(`[${o}]`,...e)};return Object.defineProperty(t,"enabled",{get(){return!!(g&&g.test(o))}}),t}/*! js-cookie v3.0.5 | MIT */function O(o){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var n in e)o[n]=e[n]}return o}var xe={read:function(o){return o[0]==='"'&&(o=o.slice(1,-1)),o.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(o){return encodeURIComponent(o).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Y(o,t){function e(i,s,r){if(!(typeof document>"u")){r=O({},t,r),typeof r.expires=="number"&&(r.expires=new Date(Date.now()+r.expires*864e5)),r.expires&&(r.expires=r.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var d in r)r[d]&&(a+="; "+d,r[d]!==!0&&(a+="="+r[d].split(";")[0]));return document.cookie=i+"="+o.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],r={},a=0;a<s.length;a++){var d=s[a].split("="),c=d.slice(1).join("=");try{var h=decodeURIComponent(d[0]);if(r[h]=o.read(c,h),i===h)break}catch{}}return i?r[i]:r}}return Object.create({set:e,get:n,remove:function(i,s){e(i,"",O({},s,{expires:-1}))},withAttributes:function(i){return Y(this.converter,O({},this.attributes,i))},withConverter:function(i){return Y(O({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(o)}})}var D=Y(xe,{path:"/"});const I="https://app.referralsaasquatch.com",K="https://fast.ssqt.io/npm",j="squatch",Z="impact";function W(o){if(typeof o!="object")throw new Error("config must be an object");const t=window.squatchTenant,e=ee(),n={tenantAlias:(o==null?void 0:o.tenantAlias)||t,domain:(o==null?void 0:o.domain)||(e==null?void 0:e.domain),npmCdn:(o==null?void 0:o.npmCdn)||(e==null?void 0:e.npmCdn),debug:(o==null?void 0:o.debug)||(e==null?void 0:e.debug)};if(typeof n.tenantAlias!="string")throw new Error("tenantAlias not provided");const i=n.tenantAlias,s=typeof n.domain=="string"&&n.domain||I,r=typeof n.debug=="boolean"&&n.debug||!1,a=typeof n.npmCdn=="string"&&n.npmCdn||K;return{tenantAlias:i,domain:s,debug:r,npmCdn:a}}function _(o){return typeof o=="object"&&!Array.isArray(o)&&o!==null}function Ce(o){if(o&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(o))return o}function se(o){if(!_(o))throw new Error("Widget properties must be an object");if(!(o!=null&&o.user))throw new Error("Required properties missing.");return o}function re(o){if(!_(o))throw new Error("Widget properties must be an object");return o}function $(){return window.impactToken||window.squatchToken}function ee(){return window.impactConfig||window.squatchConfig}function N(o){console.log("[DEBUG] parseErrorResponse - raw responseText:",o);try{const t=JSON.parse(o);if(console.log("[DEBUG] parseErrorResponse - parsed JSON:",t),t&&typeof t=="object")return console.log("[DEBUG] parseErrorResponse - returning parsed object with apiErrorCode:",t.apiErrorCode),t}catch(t){console.log("[DEBUG] parseErrorResponse - JSON parse failed:",t)}return{message:o}}async function Ae(o,t,e,n){const i=n||$(),s={Accept:"application/json","Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const r=await fetch(o,{method:"POST",body:JSON.stringify({query:t,variables:e}),headers:s});if(!r.ok)throw N(await r.text());return await r.json()}catch(r){throw r}}async function Ie(o,t=""){const e={Accept:"application/json","Content-Type":"application/json"},n=t||$();n&&(e["X-SaaSquatch-User-Token"]=n);try{const i=await fetch(o,{method:"GET",credentials:"include",headers:e}),s=await i.text();if(!i.ok)throw N(s);return s&&JSON.parse(s)}catch(i){throw i}}async function te(o,t,e){const n={Accept:"application/json","Content-Type":"application/json"},i=e||$();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{method:"POST",body:t,headers:n}),r=await s.text();if(!s.ok)throw N(r);return r&&JSON.parse(r)}catch(s){throw s}}async function _e(o,t,e){const n={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},i=e||$();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{headers:n,method:"PUT",credentials:"include",body:t}),r=await s.text();if(!s.ok)throw N(r);return r&&JSON.parse(r)}catch(s){throw s}}const Te=`
1
+ (function(u,g){typeof exports=="object"&&typeof module<"u"?g(exports):(u=typeof globalThis<"u"?globalThis:u||self,g(u.squatch={}))})(this,function(u){"use strict";var st=Object.defineProperty;var rt=(u,g,A)=>g in u?st(u,g,{enumerable:!0,configurable:!0,writable:!0,value:A}):u[g]=A;var l=(u,g,A)=>rt(u,typeof g!="symbol"?g+"":g,A);var fe;let g=null;function A(o){const e=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");g=new RegExp(`^${e}$`)}function Ee(){g=null}function E(o){const t=(...e)=>{g&&g.test(o)&&console.log(`[${o}]`,...e)};return Object.defineProperty(t,"enabled",{get(){return!!(g&&g.test(o))}}),t}/*! js-cookie v3.0.5 | MIT */function O(o){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var n in e)o[n]=e[n]}return o}var xe={read:function(o){return o[0]==='"'&&(o=o.slice(1,-1)),o.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(o){return encodeURIComponent(o).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Y(o,t){function e(i,s,r){if(!(typeof document>"u")){r=O({},t,r),typeof r.expires=="number"&&(r.expires=new Date(Date.now()+r.expires*864e5)),r.expires&&(r.expires=r.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var d in r)r[d]&&(a+="; "+d,r[d]!==!0&&(a+="="+r[d].split(";")[0]));return document.cookie=i+"="+o.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],r={},a=0;a<s.length;a++){var d=s[a].split("="),c=d.slice(1).join("=");try{var h=decodeURIComponent(d[0]);if(r[h]=o.read(c,h),i===h)break}catch{}}return i?r[i]:r}}return Object.create({set:e,get:n,remove:function(i,s){e(i,"",O({},s,{expires:-1}))},withAttributes:function(i){return Y(this.converter,O({},this.attributes,i))},withConverter:function(i){return Y(O({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(o)}})}var D=Y(xe,{path:"/"});const I="https://app.referralsaasquatch.com",K="https://fast.ssqt.io/npm",j="squatch",Z="impact";function W(o){if(typeof o!="object")throw new Error("config must be an object");const t=window.squatchTenant,e=ee(),n={tenantAlias:(o==null?void 0:o.tenantAlias)||t,domain:(o==null?void 0:o.domain)||(e==null?void 0:e.domain),npmCdn:(o==null?void 0:o.npmCdn)||(e==null?void 0:e.npmCdn),debug:(o==null?void 0:o.debug)||(e==null?void 0:e.debug)};if(typeof n.tenantAlias!="string")throw new Error("tenantAlias not provided");const i=n.tenantAlias,s=typeof n.domain=="string"&&n.domain||I,r=typeof n.debug=="boolean"&&n.debug||!1,a=typeof n.npmCdn=="string"&&n.npmCdn||K;return{tenantAlias:i,domain:s,debug:r,npmCdn:a}}function _(o){return typeof o=="object"&&!Array.isArray(o)&&o!==null}function Ce(o){if(o&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(o))return o}function se(o){if(!_(o))throw new Error("Widget properties must be an object");if(!(o!=null&&o.user))throw new Error("Required properties missing.");return o}function re(o){if(!_(o))throw new Error("Widget properties must be an object");return o}function $(){return window.impactToken||window.squatchToken}function ee(){return window.impactConfig||window.squatchConfig}function N(o){console.log("[DEBUG] parseErrorResponse - raw responseText:",o);try{const t=JSON.parse(o);if(console.log("[DEBUG] parseErrorResponse - parsed JSON:",t),t&&typeof t=="object")return console.log("[DEBUG] parseErrorResponse - returning parsed object with apiErrorCode:",t.apiErrorCode),t}catch(t){console.log("[DEBUG] parseErrorResponse - JSON parse failed:",t)}return{message:o}}async function Ae(o,t,e,n){const i=n||$(),s={Accept:"application/json","Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const r=await fetch(o,{method:"POST",body:JSON.stringify({query:t,variables:e}),headers:s});if(!r.ok)throw N(await r.text());return await r.json()}catch(r){throw r}}async function Ie(o,t=""){const e={Accept:"application/json","Content-Type":"application/json"},n=t||$();n?(e["X-SaaSquatch-User-Token"]=n,console.log("[DEBUG] doGet - Adding token to headers:",n)):console.log("[DEBUG] doGet - No token found, proceeding without authentication header.");try{const i=await fetch(o,{method:"GET",credentials:"include",headers:e}),s=await i.text();if(!i.ok)throw N(s);return s&&JSON.parse(s)}catch(i){throw i}}async function te(o,t,e){const n={Accept:"application/json","Content-Type":"application/json"},i=e||$();i?(console.log("[DEBUG] doPost - Adding token to headers:",i),n["X-SaaSquatch-User-Token"]=i):console.log("[DEBUG] doPost - No token found, proceeding without authentication header.");try{const s=await fetch(o,{method:"POST",body:t,headers:n}),r=await s.text();if(!s.ok)throw N(r);return r&&JSON.parse(r)}catch(s){throw s}}async function _e(o,t,e){const n={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},i=e||$();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{headers:n,method:"PUT",credentials:"include",body:t}),r=await s.text();if(!s.ok)throw N(r);return r&&JSON.parse(r)}catch(s){throw s}}const Te=`
2
2
  query renderWidget ($user: UserIdInput, $engagementMedium: UserEngagementMedium, $widgetType: WidgetType, $locale: RSLocale) {
3
3
  renderWidget(user: $user, engagementMedium: $engagementMedium, widgetType: $widgetType, locale: $locale) {
4
4
  template
@@ -15,7 +15,7 @@
15
15
  `;class F{constructor(t){l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");l(this,"referralCookie",this.squatchReferralCookie);const n=W(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain,this.npmCdn=n.npmCdn}upsertUser(t){const n=se(t),{widgetType:i,engagementMedium:s="POPUP",jwt:r,locale:a,user:d}=n,c=encodeURIComponent(this.tenantAlias),h=d.accountId?encodeURIComponent(d.accountId):null,p=d.id?encodeURIComponent(d.id):null,m=We({widgetType:i,engagementMedium:s,locale:a}),w=`/api/v1/${c}/widget/account/${h}/user/${p}/upsert${m}`,f=this.domain+w,b=(D||window.Cookies).get("_saasquatch");return b&&(d.cookies=b),_e(f,JSON.stringify(d),r)}render(t){const n=re(t),{widgetType:i,engagementMedium:s="POPUP",jwt:r,user:a}=n,d=encodeURIComponent(this.tenantAlias),c=a!=null&&a.accountId?encodeURIComponent(a.accountId):null,h=a!=null&&a.id?encodeURIComponent(a.id):null,p=n.locale??Ce(navigator.language.replace(/\-/g,"_")),m=`/api/v1/${d}/graphql`,w=this.domain+m;return new Promise(async(f,b)=>{var x;try{const y=await Ae(w,Te,{user:h&&c?{id:h,accountId:c}:null,engagementMedium:s,widgetType:i,locale:p},r);f((x=y==null?void 0:y.data)==null?void 0:x.renderWidget)}catch(y){b(y)}})}async squatchReferralCookie(){const t=encodeURIComponent(this.tenantAlias),e=(D||window.Cookies).get("_saasquatch")||"",n=e?`?cookies=${encodeURIComponent(e)}`:"",i=`${this.domain}/a/${t}/widgets/squatchcookiejson${n}`,s=await Ie(i);return Promise.resolve({...s,encodedCookie:e})}}function We({widgetType:o,engagementMedium:t,locale:e}){const n=new URLSearchParams;return n.append("engagementMedium",t),o&&n.append("widgetType",o),e&&n.append("locale",e),`?${n.toString()}`}/*!
16
16
  * domready (c) Dustin Diaz 2014 - License MIT
17
17
  *
18
- */function ne(o,t){let e=[],n,i=o,s=i.documentElement.doScroll,r="DOMContentLoaded",a=(s?/^loaded|^c/:/^loaded|^i|^c/).test(i.readyState);return a||i.addEventListener(r,n=()=>{for(i.removeEventListener(r,n),a=!0;n=e.shift();)n()}),a?setTimeout(t,0):e.push(t)}function H({value:o,unit:t}){switch(t){case"px":return`${o}px`;case"%":return`${o}%`;default:return`${o}px`}}class ae{constructor(t){l(this,"domain");var i;const n=$e(t);this.domain=(n==null?void 0:n.domain)||((i=ee())==null?void 0:i.domain)||I}pushAnalyticsLoadEvent(t){if(!t.externalUserId||!t.externalAccountId)return;const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=t.programId?`&programId=${encodeURIComponent(t.programId)}`:"",a=`/a/${e}/widgets/analytics/loaded?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}${r}`,d=this.domain+a;return te(d,JSON.stringify({}))}pushAnalyticsShareClickedEvent(t){const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=encodeURIComponent(t.shareMedium),a=`/a/${e}/widgets/analytics/shared?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}&shareMedium=${r}`,d=this.domain+a;return te(d,JSON.stringify({}))}}function $e(o){if(!_(o))throw new Error("'options' should be an object");return o}const de=({type:o="verified-access",height:t="500px"})=>{const e="#e0e0e0";return`
18
+ */function ne(o,t){let e=[],n,i=o,s=i.documentElement.doScroll,r="DOMContentLoaded",a=(s?/^loaded|^c/:/^loaded|^i|^c/).test(i.readyState);return a||i.addEventListener(r,n=()=>{for(i.removeEventListener(r,n),a=!0;n=e.shift();)n()}),a?setTimeout(t,0):e.push(t)}function B({value:o,unit:t}){switch(t){case"px":return`${o}px`;case"%":return`${o}%`;default:return`${o}px`}}class ae{constructor(t){l(this,"domain");var i;const n=$e(t);this.domain=(n==null?void 0:n.domain)||((i=ee())==null?void 0:i.domain)||I}pushAnalyticsLoadEvent(t){if(!t.externalUserId||!t.externalAccountId)return;const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=t.programId?`&programId=${encodeURIComponent(t.programId)}`:"",a=`/a/${e}/widgets/analytics/loaded?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}${r}`,d=this.domain+a;return te(d,JSON.stringify({}))}pushAnalyticsShareClickedEvent(t){const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=encodeURIComponent(t.shareMedium),a=`/a/${e}/widgets/analytics/shared?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}&shareMedium=${r}`,d=this.domain+a;return te(d,JSON.stringify({}))}}function $e(o){if(!_(o))throw new Error("'options' should be an object");return o}const de=({type:o="verified-access",height:t="500px"})=>{const e="#e0e0e0";return`
19
19
  <style>
20
20
  * {
21
21
  box-sizing: border-box;
@@ -306,7 +306,7 @@
306
306
  <p class="errortitle">Error</p>
307
307
  </div>
308
308
  <div class="errorbody">
309
- <div class="sadface"><img src="https://fast.ssqt.io/assets/images/face.png"></div>
309
+ <div class="sadface"><img src="https://res.cloudinary.com/saasquatch-staging/image/upload/v1774538373/whoops-error-image_km94z1.svg"></div>
310
310
  <h4>Our referral program is temporarily unavailable.</h4>
311
311
  <p>Please reload the page or check back later.</p>
312
312
  <p>If the problem persists please contact our support team.</p>
@@ -327,7 +327,7 @@
327
327
  ${i}
328
328
  </div>
329
329
  <script>(${qe.toString()})()<\/script>
330
- `}reload({email:t,firstName:e,lastName:n},i){const s=this._findFrame();if(!s)throw new Error("Could not find widget iframe");const r=s.contentWindow,a=this.context.engagementMedium||"POPUP";if(!r)throw new Error("Frame needs a content window");let d;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let c={email:t||null,firstName:e||null,lastName:n||null,id:this.context.user.id,accountId:this.context.user.accountId};d=this.widgetApi.upsertUser({user:c,engagementMedium:a,widgetType:this.type,jwt:i})}else if(this.context.type==="passwordless")d=this.widgetApi.render({user:void 0,engagementMedium:a,widgetType:this.type,jwt:void 0});else throw new Error("can't reload an error widget");d.then(({template:c})=>{c&&(this.content=c,this.__deprecated__register(s,{email:t,engagementMedium:a},()=>{this.load(),a==="POPUP"&&this.open()}))}).catch(({message:c})=>{v(`${c}`)})}__deprecated__register(t,e,n){const s=t.contentWindow.document,r=s.createElement("button"),a=s.getElementsByClassName("squatch-register")[0];if(a){r.className="btn btn-primary",r.id="show-stats-btn",r.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const d=e.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";r.setAttribute("style",d),r.onclick=n,a.style.paddingTop="30px",a.innerHTML=`<p><strong>${e.email}</strong><br>Has been successfully registered</p>`,a.appendChild(r)}}}function Se(o){return new Promise(t=>{setTimeout(t,o)})}function qe(){var o=setTimeout(t,1e4);function t(){var n=document.getElementById("sq-preload");n&&n.remove(),clearTimeout(o)}function e(){var n=new Set;if(document.querySelectorAll("*").forEach(function(i){i.tagName.includes("-")&&n.add(i.tagName.toLowerCase())}),!n.size)return t();Promise.all(Array.from(n).map(function(i){return customElements.whenDefined(i)})).then(function(){requestAnimationFrame(function(){requestAnimationFrame(t)})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}const T=E("squatch-js:EMBEDwidget");class U extends ce{constructor(e,n){super(e);l(this,"show",this.open);l(this,"hide",this.close);n&&(this.container=n)}async load(){var f,b,x,y,L,we,ye,ve,ke;const e=(b=(f=this.context.widgetConfig)==null?void 0:f.values)==null?void 0:b.brandingConfig,n=(x=this.content)==null?void 0:x.includes("mint-components"),i=(e==null?void 0:e.loadingHeight)||500,s=(y=e==null?void 0:e.widgetSize)==null?void 0:y.embeddedWidgets,r=s!=null&&s.maxWidth?H(s.maxWidth):"",a=s!=null&&s.minWidth?H(s.minWidth):"",d=this._createFrame({minWidth:a,maxWidth:r,initialHeight:i}),c=this._findElement();(L=this.context)!=null&&L.container&&(c.style.visibility="hidden",c.style.height="0",c.style["overflow-y"]="hidden"),this.container?c.shadowRoot?((we=c.shadowRoot.lastChild)==null?void 0:we.nodeName)==="IFRAME"?c.shadowRoot.replaceChild(d,c.shadowRoot.lastChild):c.shadowRoot.appendChild(d):c.firstChild?c.replaceChild(d,c.firstChild):c.appendChild(d):(!c.firstChild||c.firstChild.nodeName==="#text")&&c.appendChild(d);const{contentWindow:h}=d;if(!h)throw new Error("Frame needs a content window");const p=h.document;p.open();const w=this.widgetApi.domain==="https://staging.referralsaasquatch.com"?"-staging":"";p.write(`
330
+ `}reload({email:t,firstName:e,lastName:n},i){const s=this._findFrame();if(!s)throw new Error("Could not find widget iframe");const r=s.contentWindow,a=this.context.engagementMedium||"POPUP";if(!r)throw new Error("Frame needs a content window");let d;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let c={email:t||null,firstName:e||null,lastName:n||null,id:this.context.user.id,accountId:this.context.user.accountId};d=this.widgetApi.upsertUser({user:c,engagementMedium:a,widgetType:this.type,jwt:i})}else if(this.context.type==="passwordless")d=this.widgetApi.render({user:void 0,engagementMedium:a,widgetType:this.type,jwt:void 0});else throw new Error("can't reload an error widget");d.then(({template:c})=>{c&&(this.content=c,this.__deprecated__register(s,{email:t,engagementMedium:a},()=>{this.load(),a==="POPUP"&&this.open()}))}).catch(({message:c})=>{v(`${c}`)})}__deprecated__register(t,e,n){const s=t.contentWindow.document,r=s.createElement("button"),a=s.getElementsByClassName("squatch-register")[0];if(a){r.className="btn btn-primary",r.id="show-stats-btn",r.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const d=e.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";r.setAttribute("style",d),r.onclick=n,a.style.paddingTop="30px",a.innerHTML=`<p><strong>${e.email}</strong><br>Has been successfully registered</p>`,a.appendChild(r)}}}function Se(o){return new Promise(t=>{setTimeout(t,o)})}function qe(){var o=setTimeout(t,1e4);function t(){var n=document.getElementById("sq-preload");n&&n.remove(),clearTimeout(o)}function e(){var n=new Set;if(document.querySelectorAll("*").forEach(function(i){i.tagName.includes("-")&&n.add(i.tagName.toLowerCase())}),!n.size)return t();Promise.all(Array.from(n).map(function(i){return customElements.whenDefined(i)})).then(function(){requestAnimationFrame(function(){requestAnimationFrame(t)})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}const T=E("squatch-js:EMBEDwidget");class U extends ce{constructor(e,n){super(e);l(this,"show",this.open);l(this,"hide",this.close);n&&(this.container=n)}async load(){var f,b,x,y,L,we,ye,ve,ke;const e=(b=(f=this.context.widgetConfig)==null?void 0:f.values)==null?void 0:b.brandingConfig,n=(x=this.content)==null?void 0:x.includes("mint-components"),i=(e==null?void 0:e.loadingHeight)||500,s=(y=e==null?void 0:e.widgetSize)==null?void 0:y.embeddedWidgets,r=s!=null&&s.maxWidth?B(s.maxWidth):"",a=s!=null&&s.minWidth?B(s.minWidth):"",d=this._createFrame({minWidth:a,maxWidth:r,initialHeight:i}),c=this._findElement();(L=this.context)!=null&&L.container&&(c.style.visibility="hidden",c.style.height="0",c.style["overflow-y"]="hidden"),this.container?c.shadowRoot?((we=c.shadowRoot.lastChild)==null?void 0:we.nodeName)==="IFRAME"?c.shadowRoot.replaceChild(d,c.shadowRoot.lastChild):c.shadowRoot.appendChild(d):c.firstChild?c.replaceChild(d,c.firstChild):c.appendChild(d):(!c.firstChild||c.firstChild.nodeName==="#text")&&c.appendChild(d);const{contentWindow:h}=d;if(!h)throw new Error("Frame needs a content window");const p=h.document;p.open();const w=this.widgetApi.domain==="https://staging.referralsaasquatch.com"?"-staging":"";p.write(`
331
331
  ${(ye=e==null?void 0:e.main)!=null&&ye.brandFont?`
332
332
  <link rel="preconnect" href="https://fast${w}.ssqt.io">
333
333
  <link rel="preconnect" href="https://fonts.gstatic.com">
@@ -342,7 +342,7 @@
342
342
  ${this._getSkeletonPreloadHTML(n,(ke=e==null?void 0:e.color)==null?void 0:ke.backgroundColor)}
343
343
  ${this.content}
344
344
  <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>
345
- `),p.close(),ne(p,async()=>{const be=h.squatch||h.widgetIdent;d.height=i;const et=new h.ResizeObserver(nt=>{for(const it of nt){const{height:ot}=it.contentRect;d.height=ot}}),tt=await this._findInnerContainer(d);et.observe(tt),this._shouldFireLoadEvent()?(this._loadEvent(be),T("loaded")):p&&this._attachLoadEventListener(p,be)})}open(){const e=this._findFrame();if(!e)return T("no target element to open");if(!e.contentWindow)return T("Frame needs a content window");const n=this._findElement();n.style.visibility="unset",n.style.height="auto",n.style["overflow-y"]="auto",e.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const i=e.contentWindow.squatch||e.contentWindow.widgetIdent;if(this.context.user)this._loadEvent(i),T("loaded");else{if(!e.contentDocument)return;this._attachLoadEventListener(e.contentDocument,i)}}close(){const e=this._findFrame();if(!e)return T("no target element to close");e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this._findElement();n.style.visibility="hidden",n.style.height="0",n.style["overflow-y"]="hidden",T("Embed widget closed")}_error(e,n="embed",i=""){return super._error(e,n,i)}_shouldFireLoadEvent(){const e=!this.container,n=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));return!!this.context.user&&(e||n)}}const S=E("squatch-js:POPUPwidget");let B=0;class q extends ce{constructor(e,n=".squatchpop"){super(e);l(this,"trigger");l(this,"id");l(this,"show",this.open);l(this,"hide",this.close);this.trigger=n,this.container?this.id="squatchModal":(this.id=B===0?"squatchModal":`squatchModal__${B}`,B=B+1),document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let e;try{e=document.querySelector(this.trigger)||document.querySelector(".impactpop"),this.trigger&&!e&&S("No element found with trigger selector",this.trigger)}catch{S("Not a valid selector",this.trigger)}e&&(e.onclick=()=>{this.open()})}_createPopupDialog(e){var d;const n=document.createElement("dialog"),i=(d=e==null?void 0:e.widgetSize)==null?void 0:d.popupWidgets,s=i!=null&&i.minWidth?H(i.minWidth):"auto",r=i!=null&&i.maxWidth?H(i.maxWidth):"500px";n.id=this.id,n.setAttribute("style",`width: 100%; min-width: ${s}; max-width: ${r}; border: none; padding: 0;`);const a=c=>{c.stopPropagation(),c.target===n&&n.close()};return n.addEventListener("click",a),n}async load(){var m,w,f,b,x,y,L;const e=(w=(m=this.context.widgetConfig)==null?void 0:m.values)==null?void 0:w.brandingConfig,n=(e==null?void 0:e.loadingHeight)||500,i=(f=this.content)==null?void 0:f.includes("mint-components"),s=this._createFrame();s.style.height=n+"px",this._initialiseCTA();const r=this.container?this._findElement():document.body,a=(r==null?void 0:r.shadowRoot)||r,d=this._createPopupDialog(e);d.appendChild(s),((b=a.lastChild)==null?void 0:b.nodeName)==="DIALOG"?a.replaceChild(d,a.lastChild):a.appendChild(d);const{contentWindow:c}=s;if(!c)throw new Error("Frame needs a content window");const h=c.document;h.open();const p=this.widgetApi.domain;h.write(`
345
+ `),p.close(),ne(p,async()=>{const be=h.squatch||h.widgetIdent;d.height=i;const et=new h.ResizeObserver(nt=>{for(const it of nt){const{height:ot}=it.contentRect;d.height=ot}}),tt=await this._findInnerContainer(d);et.observe(tt),this._shouldFireLoadEvent()?(this._loadEvent(be),T("loaded")):p&&this._attachLoadEventListener(p,be)})}open(){const e=this._findFrame();if(!e)return T("no target element to open");if(!e.contentWindow)return T("Frame needs a content window");const n=this._findElement();n.style.visibility="unset",n.style.height="auto",n.style["overflow-y"]="auto",e.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const i=e.contentWindow.squatch||e.contentWindow.widgetIdent;if(this.context.user)this._loadEvent(i),T("loaded");else{if(!e.contentDocument)return;this._attachLoadEventListener(e.contentDocument,i)}}close(){const e=this._findFrame();if(!e)return T("no target element to close");e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this._findElement();n.style.visibility="hidden",n.style.height="0",n.style["overflow-y"]="hidden",T("Embed widget closed")}_error(e,n="embed",i=""){return super._error(e,n,i)}_shouldFireLoadEvent(){const e=!this.container,n=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));return!!this.context.user&&(e||n)}}const S=E("squatch-js:POPUPwidget");let H=0;class q extends ce{constructor(e,n=".squatchpop"){super(e);l(this,"trigger");l(this,"id");l(this,"show",this.open);l(this,"hide",this.close);this.trigger=n,this.container?this.id="squatchModal":(this.id=H===0?"squatchModal":`squatchModal__${H}`,H=H+1),document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let e;try{e=document.querySelector(this.trigger)||document.querySelector(".impactpop"),this.trigger&&!e&&S("No element found with trigger selector",this.trigger)}catch{S("Not a valid selector",this.trigger)}e&&(e.onclick=()=>{this.open()})}_createPopupDialog(e){var d;const n=document.createElement("dialog"),i=(d=e==null?void 0:e.widgetSize)==null?void 0:d.popupWidgets,s=i!=null&&i.minWidth?B(i.minWidth):"auto",r=i!=null&&i.maxWidth?B(i.maxWidth):"500px";n.id=this.id,n.setAttribute("style",`width: 100%; min-width: ${s}; max-width: ${r}; border: none; padding: 0;`);const a=c=>{c.stopPropagation(),c.target===n&&n.close()};return n.addEventListener("click",a),n}async load(){var m,w,f,b,x,y,L;const e=(w=(m=this.context.widgetConfig)==null?void 0:m.values)==null?void 0:w.brandingConfig,n=(e==null?void 0:e.loadingHeight)||500,i=(f=this.content)==null?void 0:f.includes("mint-components"),s=this._createFrame();s.style.height=n+"px",this._initialiseCTA();const r=this.container?this._findElement():document.body,a=(r==null?void 0:r.shadowRoot)||r,d=this._createPopupDialog(e);d.appendChild(s),((b=a.lastChild)==null?void 0:b.nodeName)==="DIALOG"?a.replaceChild(d,a.lastChild):a.appendChild(d);const{contentWindow:c}=s;if(!c)throw new Error("Frame needs a content window");const h=c.document;h.open();const p=this.widgetApi.domain;h.write(`
346
346
  ${(x=e==null?void 0:e.main)!=null&&x.brandFont?`
347
347
  <link rel="preconnect" href="https://fast${p==="https://staging.referralsaasquatch.com"?"-staging":""}.ssqt.io">
348
348
  <link rel="preconnect" href="https://fonts.gstatic.com">
@@ -357,5 +357,5 @@
357
357
  ${this._getSkeletonPreloadHTML(i,(L=e==null?void 0:e.color)==null?void 0:L.backgroundColor)}
358
358
  ${this.content}
359
359
  <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>
360
- `),h.close(),S("Popup template loaded into iframe"),await this._setupResizeHandler(s)}async _setupResizeHandler(e){const{contentWindow:n}=e;if(!n)throw new Error("Frame needs a content window");const i=n.document;ne(i,async()=>{i.body.style.overflowY="hidden";let s=!0;new n.ResizeObserver(a=>{for(const d of a){const{top:c,bottom:h}=d.contentRect,p=h+c;p<=0||(s?(s=!1,e.style.height="0",e.height=i.body.scrollHeight+"",e.style.height=""):e.height=p+"",d.target.style="")}}).observe(await this._findInnerContainer(e))})}open(){const e=this.container?this._findElement():document.body,i=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!i)throw new Error("Could not determine container div");i.showModal();const s=this._findFrame();if(!s)throw new Error("Could not find iframe");const{contentWindow:r}=s;if(!r)throw new Error("Squatch.js has an empty iframe");const a=r.document;ne(a,()=>{var c;const d=r.squatch||r.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),S("Popup opened")):this._attachLoadEventListener(a,d)})}close(){const e=this._findFrame();e!=null&&e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this.container?this._findElement():document.body,s=(n.shadowRoot||n).querySelector(`#${this.id}`);if(!s)throw new Error("Could not determine container div");s.close(),S("Popup closed")}_clickedOutside({target:e}){}_error(e,n="modal",i=""){return super._error(e,n,i||"body { margin: 0; } .modal { box-shadow: none; border: 0; }")}}const k=E("squatch-js:widgets");class R{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=W(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new F(e)}async upsertUser(t){const n=se(t);try{const i=await this.api.upsertUser(n);return{widget:this._renderWidget(i,n,{type:"upsert",user:n.user,engagementMedium:t.engagementMedium,container:t.container,trigger:t.trigger,widgetConfig:{values:{brandingConfig:i==null?void 0:i.brandingConfig}}}),user:i.user}}catch(i){throw console.log("[DEBUG] Widgets.upsertUser catch - err:",i),console.log("[DEBUG] Widgets.upsertUser catch - typeof err:",typeof i),console.log("[DEBUG] Widgets.upsertUser catch - err.apiErrorCode:",i.apiErrorCode),console.log("[DEBUG] Widgets.upsertUser catch - err keys:",Object.keys(i||{})),k(i),i.apiErrorCode&&(console.log("[DEBUG] Widgets.upsertUser - calling _renderErrorWidget"),this._renderErrorWidget(i,t.engagementMedium)),new Error(i)}}async render(t){const n=re(t);try{const i=await this.api.render(n);return{widget:this._renderWidget(i,n,{type:"passwordless",engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger,widgetConfig:i==null?void 0:i.widgetConfig}),user:i.user}}catch(i){throw i.apiErrorCode&&this._renderErrorWidget(i,n.engagementMedium),new Error(i)}}async autofill(t){const e=t;if(typeof e=="function"){try{const s=await this.api.squatchReferralCookie();e(s)}catch(s){throw k("Autofill error",s),new Error(s)}return}if(typeof e!="string")throw new Error("Autofill accepts a string or function");let n=document.querySelectorAll(e),i;if(n.length>0)i=n[0];else throw k("Element id/class or function missing"),new Error("Element id/class or function missing");try{const s=await this.api.squatchReferralCookie();i.value=s.codes[0]}catch(s){throw new Error(s)}}_renderWidget(t,e,n){var d;if(k("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const r=t.jsOptions||{},a={content:t.template,type:e.widgetType||((d=r.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return r.widgetUrlMappings&&r.widgetUrlMappings.forEach(c=>{var h,p;R._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(p=(h=t.user)==null?void 0:h.referredBy)!=null&&p.code?(s=c.displayOnLoad,k(`Display ${c.widgetType} on ${c.url}`)):k(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))}),r.fuelTankAutofillUrls&&(k("We found a fuel tank autofill!"),r.fuelTankAutofillUrls.forEach(({url:c,formSelector:h})=>{var p,m,w;if(R._matchesUrl(c)&&(k("Fuel Tank URL matches"),(m=(p=t.user)==null?void 0:p.referredBy)!=null&&m.code)){const f=document.querySelector(h);f?f.value=((w=t.user.referredBy.referredReward)==null?void 0:w.fuelTankCode)||"":k(new Error(`Element with id/class ${h} was not found.`))}})),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(a):(i=this._renderPopupWidget(a),s&&i.open()),i}_renderPopupWidget(t){const e=new q(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new U(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,statusCode:s,message:r}=t;k(new Error(`${n} (${i}) ${r}`));const a={content:"error",rsCode:i,apiErrorCode:n,statusCode:s,errorMessage:r,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;e==="EMBED"?(d=new U(a),d.load()):e==="POPUP"&&(d=new q(a),d.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Re{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=W(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=Me(n),{jwt:r}=Pe(i),a=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${a}/open/account/${c}/user/${d}/events`,p=this.domain+h;return te(p,JSON.stringify(s),r)}}function Me(o){if(!_(o))throw new Error("tracking parameter must be an object");if(!(o!=null&&o.accountId))throw new Error("accountId field is required");if(!(o!=null&&o.events))throw new Error("events field is required");if(!(o!=null&&o.userId))throw new Error("userId field is required");const t=o;if(!Array.isArray(t.events))throw new Error("'events' should be an array");return t}function Pe(o){if(!_(o))throw new Error("'options' should be an object");return o}function Le(){var i;const o=window[Z]?Z:j,t=((i=window["_"+o])==null?void 0:i.ready)||[],e=window.impactOnReady||window.squatchOnReady,n=[...t,e].filter(s=>!!s);setTimeout(()=>{window[j]&&(window[Z]=window[j],n.forEach(s=>s()),window[j]._auto(),window["_"+o]=void 0,delete window["_"+o])},0)}const C=E("squatch-js"),le=o=>typeof o=="object"&&!Array.isArray(o),he=(o,t)=>{const e=i=>le(t[i])&&o.hasOwnProperty(i)&&le(o[i]),n=Object.getOwnPropertyNames(t).map(i=>({[i]:e(i)?he(o[i],t[i]):t[i]})).reduce((i,s)=>({...i,...s}),{});return{...o,...n}};function J(o){const t=atob(o.replace(/_/g,"/").replace(/-/g,"+")),e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return new TextDecoder("utf8").decode(e)}function ue(o){const t=new TextEncoder().encode(o),e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Oe(){var o,t,e="weird_get_top_level_domain=cookie",n=document.location.hostname.split(".");for(o=n.length-1;o>=0;o--)if(t=n.slice(o).join("."),document.cookie=e+";domain=."+t+";",document.cookie.indexOf(e)>-1)return document.cookie=e.split("=")[0]+"=;domain=."+t+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",t}function De(){const o=window.location.search,e=new URLSearchParams(o).get("_saasquatch")||"";if(e){let n="",i="",s="";try{n=JSON.parse(J(e))}catch(r){C("Unable to decode params",r);return}try{i=JSON.parse(J(D.get("_saasquatch"))),C("existing cookie",i)}catch(r){C("Unable to retrieve cookie",r)}try{const r=Oe();if(C("domain retrieved:",r),i){const a=he(i,n);s=ue(JSON.stringify(a)),C("cookie to store:",a)}else s=ue(JSON.stringify(n)),C("cookie to store:",n);D.set("_saasquatch",s,{expires:365,secure:!1,sameSite:"Lax",domain:r,path:"/"})}catch(r){C("Unable to set cookie",r)}}}const G=E("squatch-js");function je(){var p;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){G("No _saasquatchExtra param");return}const n=W({tenantAlias:"UNKNOWN"});if(!n.domain){G("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(J(e))}catch{G("Unable to decode _saasquatchExtra config");return}function s(m){return m.replace(/^https?:\/\//,"")}const r=s(n.domain),a=Object.keys((i==null?void 0:i[r])||{})[0],d=(p=i==null?void 0:i[r])==null?void 0:p[a];if(!d){G("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:c,...h}=d;return{widgetConfig:{widgetType:c,displayOnLoad:!0,...h},squatchConfig:{...n,tenantAlias:a}}}const Ne=E("squatch-js:decodeUserJwt");function Fe(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=J(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return Ne(e),null}}const pe=E("squatch-js:DeclarativeWidget");class ge extends HTMLElement{constructor(){super();l(this,"config");l(this,"token");l(this,"tenant");l(this,"widgetType");l(this,"locale");l(this,"widgetApi");l(this,"analyticsApi");l(this,"widgetInstance");l(this,"type");l(this,"container");l(this,"element");l(this,"loaded");l(this,"_setWidget",(e,n)=>{var s;const i={api:this.widgetApi,content:e.template,context:{type:n.type,user:n.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:e.widgetConfig},type:this.widgetType,domain:((s=this.config)==null?void 0:s.domain)||I,npmCdn:K,container:this};if(this.type==="EMBED")return new U(i);{const r=this.firstChild?null:void 0;return new q(i,r)}});l(this,"setErrorWidget",e=>{var d;const n=e instanceof Error?e.message:e==null?void 0:e.message,i=e instanceof Error||e==null?void 0:e.apiErrorCode,s=e instanceof Error||e==null?void 0:e.rsCode,r=e instanceof Error||e==null?void 0:e.statusCode,a={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((d=this.config)==null?void 0:d.domain)||I,npmCdn:K,container:this,apiErrorCode:i,rsCode:s,statusCode:r,errorMessage:n};if(this.type==="EMBED")return new U(a);{const c=this.firstChild?null:void 0;return new q(a,c)}});l(this,"reload",this.renderWidget);l(this,"show",this.open);l(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=ee(),this.token=$(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new F({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||I}),this.analyticsApi=new ae({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||I})}getWidgetType(e){return e&&(e.includes("websiteReferralWidget")||e.includes("friendWidget"))?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),pe("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(e=>this._setWidget(e,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const e=Fe(this.token);if(!e)return this.setErrorWidget(Error("No user object in token."));pe("Rendering as a Verified widget");try{await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token})}catch(i){return this.setErrorWidget(i)}return await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then(i=>this._setWidget(i,{type:"upsert",user:e})).catch(this.setErrorWidget)}async getWidgetInstance(){let e;if(this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale,!this.widgetType)throw new Error("No widget has been specified");return this.token?e=await this.renderUserUpsertVariant():e=await this.renderPasswordlessVariant(),this.widgetInstance=e,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),e}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(e,n,i){if(!(n===i||!this.loaded))switch(e){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),this.widgetType=this.getAttribute("widget")||void 0;const e=this.getWidgetType(this.widgetType),{getSkeleton:n}=await Promise.resolve().then(()=>Ue),i=n({height:"100%",type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const r=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const d=r.getElementById("#squatchModal");d&&(d.innerHTML="",d.appendChild(s))}else r.innerHTML="",r.appendChild(s);await this.renderWidget();const a=r.getElementById("loading-skeleton");a&&a.remove(),this.getAttribute("open")!==null&&this.open()}}class ie extends ge{constructor(){super(),this.type="EMBED",this.loaded=!1}}class oe extends ge{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",t=>{t.stopPropagation(),this.open()})}}class He extends ie{}class Be extends oe{}class Je extends ie{}class Ge extends oe{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",He),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",Je),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",Be),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Ge);function ze(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const M=E("squatch-js");let z=null,V=null,X=null;function Ve(){return z||P({}),z}function Q(){return V||P({}),V}function Xe(){return X||P({}),X}function Qe(o){var t;return(t=Q())==null?void 0:t.render(o)}function Ye(){var t;const o=je();if(o){const{squatchConfig:e,widgetConfig:n}=o;return P(e),(t=Q())==null?void 0:t.render(n)}}function P(o){const e=W(o);e.tenantAlias.match("^test")||e.debug?A("squatch-js*"):Ee(),M("initializing ..."),z=new F(e),V=new R(e),X=new Re(e),M("Widget API instance",z),M("Widgets instance",V),M("Events API instance",X)}function Ke(o){o()}function Ze(o){Q().autofill(o)}function me(){De()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&me(),(fe=window.squatch)!=null&&fe.init&&M("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&Le(),u.DeclarativeEmbedWidget=ie,u.DeclarativePopupWidget=oe,u.EmbedWidget=U,u.PopupWidget=q,u.WidgetApi=F,u.Widgets=R,u._auto=Ye,u.api=Ve,u.autofill=Ze,u.events=Xe,u.help=ze,u.init=P,u.pushCookie=me,u.ready=Ke,u.widget=Qe,u.widgets=Q,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
360
+ `),h.close(),S("Popup template loaded into iframe"),await this._setupResizeHandler(s)}async _setupResizeHandler(e){const{contentWindow:n}=e;if(!n)throw new Error("Frame needs a content window");const i=n.document;ne(i,async()=>{i.body.style.overflowY="hidden";let s=!0;new n.ResizeObserver(a=>{for(const d of a){const{top:c,bottom:h}=d.contentRect,p=h+c;p<=0||(s?(s=!1,e.style.height="0",e.height=i.body.scrollHeight+"",e.style.height=""):e.height=p+"",d.target.style="")}}).observe(await this._findInnerContainer(e))})}open(){const e=this.container?this._findElement():document.body,i=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!i)throw new Error("Could not determine container div");i.showModal();const s=this._findFrame();if(!s)throw new Error("Could not find iframe");const{contentWindow:r}=s;if(!r)throw new Error("Squatch.js has an empty iframe");const a=r.document;ne(a,()=>{var c;const d=r.squatch||r.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),S("Popup opened")):this._attachLoadEventListener(a,d)})}close(){const e=this._findFrame();e!=null&&e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this.container?this._findElement():document.body,s=(n.shadowRoot||n).querySelector(`#${this.id}`);if(!s)throw new Error("Could not determine container div");s.close(),S("Popup closed")}_clickedOutside({target:e}){}_error(e,n="modal",i=""){return super._error(e,n,i||"body { margin: 0; } .modal { box-shadow: none; border: 0; }")}}const k=E("squatch-js:widgets");class R{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=W(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new F(e)}async upsertUser(t){const n=se(t);try{const i=await this.api.upsertUser(n);return{widget:this._renderWidget(i,n,{type:"upsert",user:n.user,engagementMedium:t.engagementMedium,container:t.container,trigger:t.trigger,widgetConfig:{values:{brandingConfig:i==null?void 0:i.brandingConfig}}}),user:i.user}}catch(i){throw console.log("[DEBUG] Widgets.upsertUser catch - err:",i),console.log("[DEBUG] Widgets.upsertUser catch - typeof err:",typeof i),console.log("[DEBUG] Widgets.upsertUser catch - err.apiErrorCode:",i.apiErrorCode),console.log("[DEBUG] Widgets.upsertUser catch - err keys:",Object.keys(i||{})),k(i),i.apiErrorCode&&(console.log("[DEBUG] Widgets.upsertUser - calling _renderErrorWidget"),this._renderErrorWidget(i,t.engagementMedium)),new Error(i)}}async render(t){const n=re(t);try{const i=await this.api.render(n);return{widget:this._renderWidget(i,n,{type:"passwordless",engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger,widgetConfig:i==null?void 0:i.widgetConfig}),user:i.user}}catch(i){throw i.apiErrorCode&&this._renderErrorWidget(i,n.engagementMedium),new Error(i)}}async autofill(t){const e=t;if(typeof e=="function"){try{const s=await this.api.squatchReferralCookie();e(s)}catch(s){throw k("Autofill error",s),new Error(s)}return}if(typeof e!="string")throw new Error("Autofill accepts a string or function");let n=document.querySelectorAll(e),i;if(n.length>0)i=n[0];else throw k("Element id/class or function missing"),new Error("Element id/class or function missing");try{const s=await this.api.squatchReferralCookie();i.value=s.codes[0]}catch(s){throw new Error(s)}}_renderWidget(t,e,n){var d;if(k("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const r=t.jsOptions||{},a={content:t.template,type:e.widgetType||((d=r.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return r.widgetUrlMappings&&r.widgetUrlMappings.forEach(c=>{var h,p;R._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(p=(h=t.user)==null?void 0:h.referredBy)!=null&&p.code?(s=c.displayOnLoad,k(`Display ${c.widgetType} on ${c.url}`)):k(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))}),r.fuelTankAutofillUrls&&(k("We found a fuel tank autofill!"),r.fuelTankAutofillUrls.forEach(({url:c,formSelector:h})=>{var p,m,w;if(R._matchesUrl(c)&&(k("Fuel Tank URL matches"),(m=(p=t.user)==null?void 0:p.referredBy)!=null&&m.code)){const f=document.querySelector(h);f?f.value=((w=t.user.referredBy.referredReward)==null?void 0:w.fuelTankCode)||"":k(new Error(`Element with id/class ${h} was not found.`))}})),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(a):(i=this._renderPopupWidget(a),s&&i.open()),i}_renderPopupWidget(t){const e=new q(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new U(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,statusCode:s,message:r}=t;k(new Error(`${n} (${i}) ${r}`));const a={content:"error",rsCode:i,apiErrorCode:n,statusCode:s,errorMessage:r,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;e==="EMBED"?(d=new U(a),d.load()):e==="POPUP"&&(d=new q(a),d.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Re{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=W(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=Pe(n),{jwt:r}=Me(i),a=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${a}/open/account/${c}/user/${d}/events`,p=this.domain+h;return te(p,JSON.stringify(s),r)}}function Pe(o){if(!_(o))throw new Error("tracking parameter must be an object");if(!(o!=null&&o.accountId))throw new Error("accountId field is required");if(!(o!=null&&o.events))throw new Error("events field is required");if(!(o!=null&&o.userId))throw new Error("userId field is required");const t=o;if(!Array.isArray(t.events))throw new Error("'events' should be an array");return t}function Me(o){if(!_(o))throw new Error("'options' should be an object");return o}function Le(){var i;const o=window[Z]?Z:j,t=((i=window["_"+o])==null?void 0:i.ready)||[],e=window.impactOnReady||window.squatchOnReady,n=[...t,e].filter(s=>!!s);setTimeout(()=>{window[j]&&(window[Z]=window[j],n.forEach(s=>s()),window[j]._auto(),window["_"+o]=void 0,delete window["_"+o])},0)}const C=E("squatch-js"),le=o=>typeof o=="object"&&!Array.isArray(o),he=(o,t)=>{const e=i=>le(t[i])&&o.hasOwnProperty(i)&&le(o[i]),n=Object.getOwnPropertyNames(t).map(i=>({[i]:e(i)?he(o[i],t[i]):t[i]})).reduce((i,s)=>({...i,...s}),{});return{...o,...n}};function G(o){const t=atob(o.replace(/_/g,"/").replace(/-/g,"+")),e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return new TextDecoder("utf8").decode(e)}function ue(o){const t=new TextEncoder().encode(o),e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Oe(){var o,t,e="weird_get_top_level_domain=cookie",n=document.location.hostname.split(".");for(o=n.length-1;o>=0;o--)if(t=n.slice(o).join("."),document.cookie=e+";domain=."+t+";",document.cookie.indexOf(e)>-1)return document.cookie=e.split("=")[0]+"=;domain=."+t+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",t}function De(){const o=window.location.search,e=new URLSearchParams(o).get("_saasquatch")||"";if(e){let n="",i="",s="";try{n=JSON.parse(G(e))}catch(r){C("Unable to decode params",r);return}try{i=JSON.parse(G(D.get("_saasquatch"))),C("existing cookie",i)}catch(r){C("Unable to retrieve cookie",r)}try{const r=Oe();if(C("domain retrieved:",r),i){const a=he(i,n);s=ue(JSON.stringify(a)),C("cookie to store:",a)}else s=ue(JSON.stringify(n)),C("cookie to store:",n);D.set("_saasquatch",s,{expires:365,secure:!1,sameSite:"Lax",domain:r,path:"/"})}catch(r){C("Unable to set cookie",r)}}}const J=E("squatch-js");function je(){var p;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){J("No _saasquatchExtra param");return}const n=W({tenantAlias:"UNKNOWN"});if(!n.domain){J("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(G(e))}catch{J("Unable to decode _saasquatchExtra config");return}function s(m){return m.replace(/^https?:\/\//,"")}const r=s(n.domain),a=Object.keys((i==null?void 0:i[r])||{})[0],d=(p=i==null?void 0:i[r])==null?void 0:p[a];if(!d){J("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:c,...h}=d;return{widgetConfig:{widgetType:c,displayOnLoad:!0,...h},squatchConfig:{...n,tenantAlias:a}}}const Ne=E("squatch-js:decodeUserJwt");function Fe(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=G(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return Ne(e),null}}const pe=E("squatch-js:DeclarativeWidget");class ge extends HTMLElement{constructor(){super();l(this,"config");l(this,"token");l(this,"tenant");l(this,"widgetType");l(this,"locale");l(this,"widgetApi");l(this,"analyticsApi");l(this,"widgetInstance");l(this,"type");l(this,"container");l(this,"element");l(this,"loaded");l(this,"_setWidget",(e,n)=>{var s;const i={api:this.widgetApi,content:e.template,context:{type:n.type,user:n.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:e.widgetConfig},type:this.widgetType,domain:((s=this.config)==null?void 0:s.domain)||I,npmCdn:K,container:this};if(this.type==="EMBED")return new U(i);{const r=this.firstChild?null:void 0;return new q(i,r)}});l(this,"setErrorWidget",e=>{var d;const n=e instanceof Error?e.message:e==null?void 0:e.message,i=e instanceof Error||e==null?void 0:e.apiErrorCode,s=e instanceof Error||e==null?void 0:e.rsCode,r=e instanceof Error||e==null?void 0:e.statusCode,a={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((d=this.config)==null?void 0:d.domain)||I,npmCdn:K,container:this,apiErrorCode:i,rsCode:s,statusCode:r,errorMessage:n};if(this.type==="EMBED")return new U(a);{const c=this.firstChild?null:void 0;return new q(a,c)}});l(this,"reload",this.renderWidget);l(this,"show",this.open);l(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=ee(),this.token=$(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new F({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||I}),this.analyticsApi=new ae({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||I})}getWidgetType(e){return e&&(e.includes("websiteReferralWidget")||e.includes("friendWidget"))?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),pe("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(e=>this._setWidget(e,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const e=Fe(this.token);if(!e)return this.setErrorWidget(Error("No user object in token."));pe("Rendering as a Verified widget");try{await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token})}catch(i){return this.setErrorWidget(i)}return await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then(i=>this._setWidget(i,{type:"upsert",user:e})).catch(this.setErrorWidget)}async getWidgetInstance(){let e;if(this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale,!this.widgetType)throw new Error("No widget has been specified");return this.token?e=await this.renderUserUpsertVariant():e=await this.renderPasswordlessVariant(),this.widgetInstance=e,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),e}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(e,n,i){if(!(n===i||!this.loaded))switch(e){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),this.widgetType=this.getAttribute("widget")||void 0;const e=this.getWidgetType(this.widgetType),{getSkeleton:n}=await Promise.resolve().then(()=>Ue),i=n({height:"100%",type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const r=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const d=r.getElementById("#squatchModal");d&&(d.innerHTML="",d.appendChild(s))}else r.innerHTML="",r.appendChild(s);await this.renderWidget();const a=r.getElementById("loading-skeleton");a&&a.remove(),this.getAttribute("open")!==null&&this.open()}}class ie extends ge{constructor(){super(),this.type="EMBED",this.loaded=!1}}class oe extends ge{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",t=>{t.stopPropagation(),this.open()})}}class Be extends ie{}class He extends oe{}class Ge extends ie{}class Je extends oe{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Be),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",Ge),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",He),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Je);function ze(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const P=E("squatch-js");let z=null,V=null,X=null;function Ve(){return z||M({}),z}function Q(){return V||M({}),V}function Xe(){return X||M({}),X}function Qe(o){var t;return(t=Q())==null?void 0:t.render(o)}function Ye(){var t;const o=je();if(o){const{squatchConfig:e,widgetConfig:n}=o;return M(e),(t=Q())==null?void 0:t.render(n)}}function M(o){const e=W(o);e.tenantAlias.match("^test")||e.debug?A("squatch-js*"):Ee(),P("initializing ..."),z=new F(e),V=new R(e),X=new Re(e),P("Widget API instance",z),P("Widgets instance",V),P("Events API instance",X)}function Ke(o){o()}function Ze(o){Q().autofill(o)}function me(){De()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&me(),(fe=window.squatch)!=null&&fe.init&&P("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&Le(),u.DeclarativeEmbedWidget=ie,u.DeclarativePopupWidget=oe,u.EmbedWidget=U,u.PopupWidget=q,u.WidgetApi=F,u.Widgets=R,u._auto=Ye,u.api=Ve,u.autofill=Ze,u.events=Xe,u.help=ze,u.init=M,u.pushCookie=me,u.ready=Ke,u.widget=Qe,u.widgets=Q,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
361
361
  //# sourceMappingURL=squatch.js.map