@saasquatch/squatch-js 2.8.2-9 → 2.8.3-0
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/coverage/clover.xml +944 -0
- package/coverage/coverage-final.json +22 -0
- package/coverage/lcov-report/base.css +224 -0
- package/coverage/lcov-report/block-navigation.js +87 -0
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/prettify.css +1 -0
- package/coverage/lcov-report/prettify.js +2 -0
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +196 -0
- package/coverage/lcov.info +1714 -0
- package/dist/SkeletonTemplate-CIRGs_GB.js +258 -0
- package/dist/SkeletonTemplate-CIRGs_GB.js.map +1 -0
- package/dist/SkeletonTemplate-hwDwv3Ys.cjs +250 -0
- package/dist/SkeletonTemplate-hwDwv3Ys.cjs.map +1 -0
- package/dist/squatch.cjs.js +25 -2593
- package/dist/squatch.cjs.js.map +1 -1
- package/dist/squatch.esm.js +812 -1988
- package/dist/squatch.esm.js.map +1 -1
- package/dist/squatch.js +251 -2575
- package/dist/squatch.js.map +1 -1
- package/dist/squatch.min.js +4 -5
- package/dist/utils/logger.d.ts +20 -0
- package/dist/widgets/PopupWidget.d.ts +2 -2
- package/dist/widgets/SkeletonTemplate.d.ts +3 -2
- package/dist/widgets/declarative/DeclarativeWidget.d.ts +4 -0
- package/dist/widgets/declarative/DeclarativeWidgets.d.ts +0 -6
- package/package.json +1 -2
- package/vite.config.ts +1 -1
package/dist/squatch.min.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
/*! js-cookie v3.0.5 | MIT */function assign(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){target[key]=source[key]}}return target}var defaultConverter={read:function(value){if(value[0]==='"'){value=value.slice(1,-1)}return value.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(value){return encodeURIComponent(value).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function init$1(converter,defaultAttributes){function set(name,value,attributes){if(typeof document==="undefined"){return}attributes=assign({},defaultAttributes,attributes);if(typeof attributes.expires==="number"){attributes.expires=new Date(Date.now()+attributes.expires*864e5)}if(attributes.expires){attributes.expires=attributes.expires.toUTCString()}name=encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var stringifiedAttributes="";for(var attributeName in attributes){if(!attributes[attributeName]){continue}stringifiedAttributes+="; "+attributeName;if(attributes[attributeName]===true){continue}stringifiedAttributes+="="+attributes[attributeName].split(";")[0]}return document.cookie=name+"="+converter.write(value,name)+stringifiedAttributes}function get(name){if(typeof document==="undefined"||arguments.length&&!name){return}var cookies=document.cookie?document.cookie.split("; "):[];var jar={};for(var i=0;i<cookies.length;i++){var parts=cookies[i].split("=");var value=parts.slice(1).join("=");try{var found=decodeURIComponent(parts[0]);jar[found]=converter.read(value,found);if(name===found){break}}catch(e){}}return name?jar[name]:jar}return Object.create({set:set,get:get,remove:function(name,attributes){set(name,"",assign({},attributes,{expires:-1}))},withAttributes:function(attributes){return init$1(this.converter,assign({},this.attributes,attributes))},withConverter:function(converter2){return init$1(assign({},this.converter,converter2),this.attributes)}},{attributes:{value:Object.freeze(defaultAttributes)},converter:{value:Object.freeze(converter)}})}var api$1=init$1(defaultConverter,{path:"/"});const DEFAULT_DOMAIN="https://app.referralsaasquatch.com";const DEFAULT_NPM_CDN="https://fast.ssqt.io/npm";const DEFAULT_NAMESPACE="squatch";const IMPACT_NAMESPACE="impact";function validateConfig(_raw){if(typeof _raw!=="object")throw new Error("config must be an object");const tenant=window.squatchTenant;const config=getConfig();const raw={tenantAlias:(_raw==null?void 0:_raw["tenantAlias"])||tenant,domain:(_raw==null?void 0:_raw["domain"])||(config==null?void 0:config.domain),npmCdn:(_raw==null?void 0:_raw["npmCdn"])||(config==null?void 0:config.npmCdn),debug:(_raw==null?void 0:_raw["debug"])||(config==null?void 0:config.debug)};if(typeof raw.tenantAlias!=="string")throw new Error("tenantAlias not provided");const tenantAlias=raw.tenantAlias;const domain=typeof raw.domain==="string"&&raw.domain||DEFAULT_DOMAIN;const debug2=typeof raw.debug==="boolean"&&raw.debug||false;const npmCdn=typeof raw.npmCdn==="string"&&raw.npmCdn||DEFAULT_NPM_CDN;return{tenantAlias:tenantAlias,domain:domain,debug:debug2,npmCdn:npmCdn}}function isObject$1(obj){return typeof obj==="object"&&!Array.isArray(obj)&&obj!==null}function validateLocale(locale){if(locale&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(locale)){return locale}}function validateWidgetConfig(raw){if(!isObject$1(raw))throw new Error("Widget properties must be an object");if(!(raw==null?void 0:raw["user"]))throw new Error("Required properties missing.");return raw}function validatePasswordlessConfig(raw){if(!isObject$1(raw))throw new Error("Widget properties must be an object");return raw}function getToken(){return window.impactToken||window.squatchToken}function getConfig(){return window.impactConfig||window.squatchConfig}browserExports.debug("squatch-js:io");async function doQuery(url,query,variables,jwt){const token=jwt||getToken();const headers={Accept:"application/json","Content-Type":"application/json",...token?{Authorization:`Bearer ${token}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const res=await fetch(url,{method:"POST",body:JSON.stringify({query:query,variables:variables}),headers:headers});if(!res.ok)throw new Error(await res.text());return await res.json()}catch(e){throw e}}async function doGet(url,jwt=""){const headers={Accept:"application/json","Content-Type":"application/json"};const token=jwt||getToken();if(token)headers["X-SaaSquatch-User-Token"]=token;try{const res=await fetch(url,{method:"GET",credentials:"include",headers:headers});const reply=await res.text();if(!res.ok)throw new Error(reply);return reply?JSON.parse(reply):reply}catch(e){throw e}}async function doPost(url,data,jwt){const headers={Accept:"application/json","Content-Type":"application/json"};const token=jwt||getToken();if(token)headers["X-SaaSquatch-User-Token"]=token;try{const res=await fetch(url,{method:"POST",body:data,headers:headers});const reply=await res.text();if(!res.ok)throw new Error(reply);return reply?JSON.parse(reply):reply}catch(e){throw e}}async function doPut(url,data,jwt){const headers={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""};const token=jwt||getToken();if(token)headers["X-SaaSquatch-User-Token"]=token;try{const res=await fetch(url,{headers:headers,method:"PUT",credentials:"include",body:data});const reply=await res.text();if(!res.ok)throw new Error(reply);return reply?JSON.parse(reply):reply}catch(e){throw e}}const RENDER_WIDGET_QUERY=`\n query renderWidget ($user: UserIdInput, $engagementMedium: UserEngagementMedium, $widgetType: WidgetType, $locale: RSLocale) {\n renderWidget(user: $user, engagementMedium: $engagementMedium, widgetType: $widgetType, locale: $locale) {\n template\n user {\n id\n accountId\n }\n jsOptions\n widgetConfig {\n values\n }\n }\n }\n`;class WidgetApi{constructor(config){__publicField(this,"tenantAlias");__publicField(this,"domain");__publicField(this,"npmCdn");__publicField(this,"referralCookie",this.squatchReferralCookie);const raw=config;const clean=validateConfig(raw);this.tenantAlias=clean.tenantAlias;this.domain=clean.domain;this.npmCdn=clean.npmCdn}upsertUser(params){const raw=params;const clean=validateWidgetConfig(raw);const{widgetType:widgetType,engagementMedium:engagementMedium="POPUP",jwt:jwt,locale:locale,user:user}=clean;const tenantAlias=encodeURIComponent(this.tenantAlias);const accountId=user.accountId?encodeURIComponent(user.accountId):null;const userId=user.id?encodeURIComponent(user.id):null;const optionalParams=_buildParams({widgetType:widgetType,engagementMedium:engagementMedium,locale:locale});const path=`/api/v1/${tenantAlias}/widget/account/${accountId}/user/${userId}/upsert${optionalParams}`;const url=this.domain+path;const cookies=(api$1||window.Cookies).get("_saasquatch");if(cookies)user["cookies"]=cookies;return doPut(url,JSON.stringify(user),jwt)}render(params){const raw=params;const clean=validatePasswordlessConfig(raw);const{widgetType:widgetType,engagementMedium:engagementMedium="POPUP",jwt:jwt,user:user}=clean;console.log({params:params});const tenantAlias=encodeURIComponent(this.tenantAlias);const accountId=(user==null?void 0:user.accountId)?encodeURIComponent(user.accountId):null;const userId=(user==null?void 0:user.id)?encodeURIComponent(user.id):null;const locale=clean.locale??validateLocale(navigator.language.replace(/\-/g,"_"));const path=`/api/v1/${tenantAlias}/graphql`;const url=this.domain+path;return new Promise((async(resolve,reject)=>{var _a2;try{const res=await doQuery(url,RENDER_WIDGET_QUERY,{user:userId&&accountId?{id:userId,accountId:accountId}:null,engagementMedium:engagementMedium,widgetType:widgetType,locale:locale},jwt);resolve((_a2=res==null?void 0:res.data)==null?void 0:_a2.renderWidget)}catch(e){reject(e)}}))}async squatchReferralCookie(){const tenantAlias=encodeURIComponent(this.tenantAlias);const _saasquatch=(api$1||window.Cookies).get("_saasquatch")||"";const cookie=_saasquatch?`?cookies=${encodeURIComponent(_saasquatch)}`:``;const url=`${this.domain}/a/${tenantAlias}/widgets/squatchcookiejson${cookie}`;const response=await doGet(url);return Promise.resolve({...response,encodedCookie:_saasquatch})}}function _buildParams({widgetType:widgetType,engagementMedium:engagementMedium,locale:locale}){const queryParams=new URLSearchParams;queryParams.append("engagementMedium",engagementMedium);if(widgetType)queryParams.append("widgetType",widgetType);if(locale)queryParams.append("locale",locale);return`?${queryParams.toString()}`}
|
|
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 Ke=Object.defineProperty;var Ze=(u,g,C)=>g in u?Ke(u,g,{enumerable:!0,configurable:!0,writable:!0,value:C}):u[g]=C;var l=(u,g,C)=>Ze(u,typeof g!="symbol"?g+"":g,C);var pe;let g=null;function C(o){const e=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");g=new RegExp(`^${e}$`)}function fe(){g=null}function k(o){return(...t)=>{g&&g.test(o)&&console.log(`[${o}]`,...t)}}/*! js-cookie v3.0.5 | MIT */function L(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 we={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 X(o,t){function e(i,s,a){if(!(typeof document>"u")){a=L({},t,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var d in a)a[d]&&(r+="; "+d,a[d]!==!0&&(r+="="+a[d].split(";")[0]));return document.cookie=i+"="+o.write(s,i)+r}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],a={},r=0;r<s.length;r++){var d=s[r].split("="),c=d.slice(1).join("=");try{var h=decodeURIComponent(d[0]);if(a[h]=o.read(c,h),i===h)break}catch{}}return i?a[i]:a}}return Object.create({set:e,get:n,remove:function(i,s){e(i,"",L({},s,{expires:-1}))},withAttributes:function(i){return X(this.converter,L({},this.attributes,i))},withConverter:function(i){return X(L({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(o)}})}var O=X(we,{path:"/"});const A="https://app.referralsaasquatch.com",Q="https://fast.ssqt.io/npm",j="squatch",Y="impact";function T(o){if(typeof o!="object")throw new Error("config must be an object");const t=window.squatchTenant,e=K(),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||A,a=typeof n.debug=="boolean"&&n.debug||!1,r=typeof n.npmCdn=="string"&&n.npmCdn||Q;return{tenantAlias:i,domain:s,debug:a,npmCdn:r}}function I(o){return typeof o=="object"&&!Array.isArray(o)&&o!==null}function ye(o){if(o&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(o))return o}function ie(o){if(!I(o))throw new Error("Widget properties must be an object");if(!(o!=null&&o.user))throw new Error("Required properties missing.");return o}function oe(o){if(!I(o))throw new Error("Widget properties must be an object");return o}function W(){return window.impactToken||window.squatchToken}function K(){return window.impactConfig||window.squatchConfig}async function ve(o,t,e,n){const i=n||W(),s={Accept:"application/json","Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const a=await fetch(o,{method:"POST",body:JSON.stringify({query:t,variables:e}),headers:s});if(!a.ok)throw new Error(await a.text());return await a.json()}catch(a){throw a}}async function be(o,t=""){const e={Accept:"application/json","Content-Type":"application/json"},n=t||W();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 new Error(s);return s&&JSON.parse(s)}catch(i){throw i}}async function Z(o,t,e){const n={Accept:"application/json","Content-Type":"application/json"},i=e||W();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{method:"POST",body:t,headers:n}),a=await s.text();if(!s.ok)throw new Error(a);return a&&JSON.parse(a)}catch(s){throw s}}async function ke(o,t,e){const n={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},i=e||W();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{headers:n,method:"PUT",credentials:"include",body:t}),a=await s.text();if(!s.ok)throw new Error(a);return a&&JSON.parse(a)}catch(s){throw s}}const Ee=`\n query renderWidget ($user: UserIdInput, $engagementMedium: UserEngagementMedium, $widgetType: WidgetType, $locale: RSLocale) {\n renderWidget(user: $user, engagementMedium: $engagementMedium, widgetType: $widgetType, locale: $locale) {\n template\n user {\n id\n accountId\n }\n jsOptions\n widgetConfig {\n values\n }\n }\n }\n`;class D{constructor(t){l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");l(this,"referralCookie",this.squatchReferralCookie);const n=T(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain,this.npmCdn=n.npmCdn}upsertUser(t){const n=ie(t),{widgetType:i,engagementMedium:s="POPUP",jwt:a,locale:r,user:d}=n,c=encodeURIComponent(this.tenantAlias),h=d.accountId?encodeURIComponent(d.accountId):null,p=d.id?encodeURIComponent(d.id):null,m=xe({widgetType:i,engagementMedium:s,locale:r}),f=`/api/v1/${c}/widget/account/${h}/user/${p}/upsert${m}`,w=this.domain+f,b=(O||window.Cookies).get("_saasquatch");return b&&(d.cookies=b),ke(w,JSON.stringify(d),a)}render(t){const n=oe(t),{widgetType:i,engagementMedium:s="POPUP",jwt:a,user:r}=n,d=encodeURIComponent(this.tenantAlias),c=r!=null&&r.accountId?encodeURIComponent(r.accountId):null,h=r!=null&&r.id?encodeURIComponent(r.id):null,p=n.locale??ye(navigator.language.replace(/\-/g,"_")),m=`/api/v1/${d}/graphql`,f=this.domain+m;return new Promise((async(w,b)=>{var M;try{const E=await ve(f,Ee,{user:h&&c?{id:h,accountId:c}:null,engagementMedium:s,widgetType:i,locale:p},a);w((M=E==null?void 0:E.data)==null?void 0:M.renderWidget)}catch(E){b(E)}}))}async squatchReferralCookie(){const t=encodeURIComponent(this.tenantAlias),e=(O||window.Cookies).get("_saasquatch")||"",n=e?`?cookies=${encodeURIComponent(e)}`:"",i=`${this.domain}/a/${t}/widgets/squatchcookiejson${n}`,s=await be(i);return Promise.resolve({...s,encodedCookie:e})}}function xe({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()}`
|
|
3
2
|
/*!
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
*/function domready(targetDoc,fn){let fns=[];let listener;let doc=targetDoc;let hack=doc.documentElement.doScroll;let domContentLoaded="DOMContentLoaded";let loaded=(hack?/^loaded|^c/:/^loaded|^i|^c/).test(doc.readyState);if(!loaded)doc.addEventListener(domContentLoaded,listener=()=>{doc.removeEventListener(domContentLoaded,listener);loaded=true;while(listener=fns.shift())listener()});return loaded?setTimeout(fn,0):fns.push(fn)}function formatWidth({value:value,unit:unit}){switch(unit){case"px":return`${value}px`;case"%":return`${value}%`;default:return`${value}px`}}class AnalyticsApi{constructor(config){__publicField(this,"domain");var _a2;const raw=config;const clean=_validateAnalyticsConfig(raw);this.domain=(clean==null?void 0:clean["domain"])||((_a2=getConfig())==null?void 0:_a2.domain)||DEFAULT_DOMAIN}pushAnalyticsLoadEvent(params){if(!params.externalUserId||!params.externalAccountId)return;const tenantAlias=encodeURIComponent(params.tenantAlias);const accountId=encodeURIComponent(params.externalAccountId);const userId=encodeURIComponent(params.externalUserId);const engagementMedium=encodeURIComponent(params.engagementMedium);const programId=params.programId?`&programId=${encodeURIComponent(params.programId)}`:``;const path=`/a/${tenantAlias}/widgets/analytics/loaded?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}${programId}`;const url=this.domain+path;return doPost(url,JSON.stringify({}))}pushAnalyticsShareClickedEvent(params){const tenantAlias=encodeURIComponent(params.tenantAlias);const accountId=encodeURIComponent(params.externalAccountId);const userId=encodeURIComponent(params.externalUserId);const engagementMedium=encodeURIComponent(params.engagementMedium);const shareMedium=encodeURIComponent(params.shareMedium);const path=`/a/${tenantAlias}/widgets/analytics/shared?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}&shareMedium=${shareMedium}`;const url=this.domain+path;return doPost(url,JSON.stringify({}))}}function _validateAnalyticsConfig(raw){if(!isObject$1(raw))throw new Error("'options' should be an object");return raw}const _log$8=browserExports.debug("squatch-js:widget");class Widget{constructor(params){__publicField(this,"type");__publicField(this,"content");__publicField(this,"analyticsApi");__publicField(this,"widgetApi");__publicField(this,"context");__publicField(this,"npmCdn");__publicField(this,"container");__publicField(this,"loadEventListener",null);var _a2;_log$8("widget initializing ...");this.content=params.content==="error"?this._error(params.rsCode):params.content;this.type=params.type;this.widgetApi=params.api;this.npmCdn=params.npmCdn;this.analyticsApi=new AnalyticsApi({domain:params.domain});this.context=params.context;this.container=((_a2=params.context)==null?void 0:_a2.container)||params.container}_findElement(){let element;if(typeof this.container==="string"){element=document.querySelector(this.container);_log$8("loading widget with selector",element)}else if(this.container instanceof HTMLElement){element=this.container;_log$8("loading widget with container",element)}else if(this.container){element=null;_log$8("container must be an HTMLElement or string",this.container)}else{element=document.querySelector("#squatchembed")||document.querySelector(".squatchembed")||document.querySelector("#impactembed")||document.querySelector(".impactembed");_log$8("loading widget with default selector",element)}if(!(element instanceof HTMLElement))throw new Error(`element with selector '${this.container||"#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`);return element}_createFrame(options){const frame=document.createElement("iframe");frame["squatchJsApi"]=this;frame.id="squatchFrame";frame.width="100%";frame.src="about:blank";frame.scrolling="no";frame.setAttribute("style","border: 0; background-color: none; width: 1px; min-width: 100%;");if(options==null?void 0:options.minWidth)frame.style.minWidth=options.minWidth;if(options==null?void 0:options.maxWidth)frame.style.maxWidth=options.maxWidth;if((options==null?void 0:options.maxWidth)||(options==null?void 0:options.minWidth)){frame.style.width="100%"}if(options==null?void 0:options.initialHeight){frame.height=options.initialHeight}return frame}_findFrame(){const element=this.container?this._findElement():document.body;const parent=element.shadowRoot||element;return parent.querySelector("iframe#squatchFrame")}_detachLoadEventListener(frameDoc){if(this.loadEventListener){frameDoc.removeEventListener("sq:user-registration",this.loadEventListener);this.loadEventListener=null}}_attachLoadEventListener(frameDoc,sqh){if(this.loadEventListener===null){this.loadEventListener=e=>{this._loadEvent({...sqh,userId:e.detail.userId,accountId:e.detail.accountId})};frameDoc.addEventListener("sq:user-registration",this.loadEventListener)}}_loadEvent(sqh){var _a2;if(!sqh)return;if(!isObject$1(sqh)){throw new Error("Widget Load event identity property is not an object")}let params;if("programId"in sqh){if(!sqh.tenantAlias||!sqh.accountId||!sqh.userId||!sqh.engagementMedium)throw new Error("Widget Load event missing required properties");params={tenantAlias:sqh.tenantAlias,externalAccountId:sqh.accountId,externalUserId:sqh.userId,engagementMedium:sqh.engagementMedium,programId:sqh.programId}}else{const{analytics:analytics,mode:mode}=sqh;params={tenantAlias:analytics.attributes.tenant,externalAccountId:analytics.attributes.accountId,externalUserId:analytics.attributes.userId,engagementMedium:mode.widgetMode}}(_a2=this.analyticsApi.pushAnalyticsLoadEvent(params))==null?void 0:_a2.then((response=>{_log$8(`${params.engagementMedium} loaded event recorded.`)})).catch((ex=>{_log$8(`ERROR: pushAnalyticsLoadEvent() ${ex}`)}))}_shareEvent(sqh,medium){if(sqh){this.analyticsApi.pushAnalyticsShareClickedEvent({tenantAlias:sqh.analytics.attributes.tenant,externalAccountId:sqh.analytics.attributes.accountId,externalUserId:sqh.analytics.attributes.userId,engagementMedium:sqh.mode.widgetMode,shareMedium:medium}).then((response=>{_log$8(`${sqh.mode.widgetMode} share ${medium} event recorded. ${response}`)})).catch((ex=>{_log$8(`ERROR: pushAnalyticsShareClickedEvent() ${ex}`)}))}}_error(rs,mode="modal",style=""){const errorTemplate=`<!DOCTYPE html>\n \x3c!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]--\x3e\n \x3c!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]--\x3e\n \x3c!--[if gt IE 8]>\x3c!--\x3e<html lang="en">\x3c!--<![endif]--\x3e\n <head>\n <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">\n <style>\n ${style}\n </style>\n </head>\n <body>\n\n <div class="squatch-container ${mode}" style="width:100%">\n <div class="errorheader">\n <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">×</button>\n <p class="errortitle">Error</p>\n </div>\n <div class="errorbody">\n <div class="sadface"><img src="https://fast.ssqt.io/assets/images/face.png"></div>\n <h4>Our referral program is temporarily unavailable.</h4><br>\n <p>Please reload the page or check back later.</p>\n <p>If the persists please contact our support team.</p>\n <br>\n <br>\n <div class="right-align errtxt">\n Error Code: ${rs}\n </div>\n </div>\n </div>\n </body>\n </html>`;return errorTemplate}async _findInnerContainer(frame){const{contentWindow:contentWindow}=frame;if(!contentWindow)throw new Error("Squatch.js frame inner frame is empty");const frameDoc=contentWindow.document;function search(){const containers=frameDoc.getElementsByTagName("sqh-global-container");const legacyContainers=frameDoc.getElementsByClassName("squatch-container");const fallback=containers.length>0?containers[0]:legacyContainers.length>0?legacyContainers[0]:null;return fallback}let found=null;for(let i=0;i<5;i++){found=search();if(found)break;await delay(100)}if(!found){return frameDoc.body}return found}reload({email:email,firstName:firstName,lastName:lastName},jwt){const frame=this._findFrame();if(!frame)throw new Error("Could not find widget iframe");const frameWindow=frame.contentWindow;const engagementMedium=this.context.engagementMedium||"POPUP";if(!frameWindow){throw new Error("Frame needs a content window")}let response;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let userObj={email:email||null,firstName:firstName||null,lastName:lastName||null,id:this.context.user.id,accountId:this.context.user.accountId};response=this.widgetApi.upsertUser({user:userObj,engagementMedium:engagementMedium,widgetType:this.type,jwt:jwt})}else if(this.context.type==="passwordless"){response=this.widgetApi.render({user:void 0,engagementMedium:engagementMedium,widgetType:this.type,jwt:void 0})}else{throw new Error("can't reload an error widget")}response.then((({template:template})=>{if(template){this.content=template;this.__deprecated__register(frame,{email:email,engagementMedium:engagementMedium},(()=>{this.load();engagementMedium==="POPUP"&&this.open()}))}})).catch((({message:message})=>{_log$8(`${message}`)}))}__deprecated__register(frame,params,onClick){const frameWindow=frame.contentWindow;const frameDoc=frameWindow.document;const showStatsBtn=frameDoc.createElement("button");const registerForm=frameDoc.getElementsByClassName("squatch-register")[0];if(registerForm){showStatsBtn.className="btn btn-primary";showStatsBtn.id="show-stats-btn";showStatsBtn.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const widgetStyle=params.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";showStatsBtn.setAttribute("style",widgetStyle);showStatsBtn.onclick=onClick;registerForm.style.paddingTop="30px";registerForm.innerHTML=`<p><strong>${params.email}</strong><br>Has been successfully registered</p>`;registerForm.appendChild(showStatsBtn)}}}function delay(duration){return new Promise((resolve=>{setTimeout(resolve,duration)}))}const getSkeleton=({height:height="500px",skeletonBackgroundColor:skeletonBackgroundColor="#e0e0e0",skeletonShimmerColor:skeletonShimmerColor="#f5f5f5",borderColor:borderColor="#ccc"})=>`\n <style>\n * {\n box-sizing: border-box;\n padding: 0;\n margin: 0;\n }\n\n\t\t\t.widget-container {\n\t\t\t\tbackground: white;\n\t\t\t\twidth: 100%;\n\t\t\t\tmax-width: 900px;\n\t\t\t\tpadding: 40px;\n\t\t\t\tborder-radius: 12px;\n\t\t\t\tbox-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);\n\t\t\t\tbox-sizing: border-box;\n\t\t\t}\n\n\t\t\t@keyframes shimmer {\n\t\t\t\t0% {\n\t\t\t\t\tbackground-position: -100% 0;\n\t\t\t\t}\n\t\t\t\t100% {\n\t\t\t\t\tbackground-position: 100% 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t.skeleton {\n\t\t\t\tbackground: ${skeletonBackgroundColor};\n\t\t\t\tbackground: linear-gradient(\n\t\t\t\t\t90deg,\n\t\t\t\t\t${skeletonBackgroundColor} 25%,\n\t\t\t\t\t${skeletonShimmerColor} 50%,\n\t\t\t\t\t${skeletonBackgroundColor} 75%\n\t\t\t\t);\n\t\t\t\tbackground-size: 200% 100%;\n\t\t\t\tanimation: shimmer 1.5s infinite linear;\n\t\t\t\tborder-radius: 6px;\n\t\t\t\tmargin-bottom: 12px;\n\t\t\t}\n\n\t\t\t.sk-title-lg {\n\t\t\t\theight: 36px;\n\t\t\t\twidth: 50%;\n\t\t\t\tmargin-bottom: 16px;\n\t\t\t}\n\t\t\t.sk-title-md {\n\t\t\t\theight: 28px;\n\t\t\t\twidth: 30%;\n\t\t\t\tmargin-bottom: 20px;\n\t\t\t\tmargin-top: 40px;\n\t\t\t}\n\t\t\t.sk-text {\n\t\t\t\theight: 16px;\n\t\t\t\twidth: 80%;\n\t\t\t\tmargin-bottom: 8px;\n\t\t\t}\n\t\t\t.sk-text-short {\n\t\t\t\twidth: 40%;\n\t\t\t}\n\t\t\t.sk-label {\n\t\t\t\theight: 14px;\n\t\t\t\twidth: 25%;\n\t\t\t\tmargin-bottom: 10px;\n\t\t\t}\n\n\t\t\t.hero-section {\n\t\t\t\tdisplay: flex;\n\t\t\t\tgap: 40px;\n\t\t\t\tmargin-bottom: 40px;\n\t\t\t\tborder-bottom: 1px solid ${borderColor};\n\t\t\t\tpadding-bottom: 40px;\n\t\t\t\tflex-direction: row;\n\t\t\t}\n\t\t\t.hero-content {\n\t\t\t\tflex: 1;\n\t\t\t\tdisplay: flex;\n\t\t\t\tflex-direction: column;\n\t\t\t\tjustify-content: center;\n\t\t\t}\n\t\t\t.hero-image {\n\t\t\t\tflex: 1;\n\t\t\t\theight: 300px;\n\t\t\t\tborder-radius: 12px;\n\t\t\t}\n\n\t\t\t.share-section {\n\t\t\t\tmargin-bottom: 40px;\n\t\t\t}\n\t\t\t.sk-input {\n\t\t\t\theight: 50px;\n\t\t\t\twidth: 100%;\n\t\t\t\tborder-radius: 8px;\n\t\t\t\tmargin-bottom: 16px;\n\t\t\t}\n\t\t\t.social-buttons {\n\t\t\t\tdisplay: flex;\n\t\t\t\tgap: 12px;\n\t\t\t}\n\t\t\t.sk-btn-social {\n\t\t\t\tflex: 1;\n\t\t\t\theight: 50px;\n\t\t\t\tborder-radius: 8px;\n\t\t\t}\n\n\t\t\t.stats-section {\n\t\t\t\tdisplay: flex;\n\t\t\t\tgap: 24px;\n\t\t\t\tmargin-bottom: 40px;\n\t\t\t\tpadding: 30px 0;\n\t\t\t\tborder-top: 1px solid ${borderColor};\n\t\t\t\tborder-bottom: 1px solid ${borderColor};\n\t\t\t}\n\t\t\t.stat-card {\n\t\t\t\tflex: 1;\n\t\t\t\tdisplay: flex;\n\t\t\t\tflex-direction: column;\n\t\t\t\talign-items: center;\n\t\t\t}\n\t\t\t.stat-divider {\n\t\t\t\tpadding-left: 24px;\n\t\t\t}\n\n\t\t\t.sk-stat-num {\n\t\t\t\theight: 48px;\n\t\t\t\twidth: 120px;\n\t\t\t\tmargin-bottom: 8px;\n\t\t\t}\n\t\t\t.sk-stat-label {\n\t\t\t\theight: 18px;\n\t\t\t\twidth: 80px;\n\t\t\t}\n\n\t\t\t.table-header {\n\t\t\t\tdisplay: flex;\n\t\t\t\tgap: 16px;\n\t\t\t\tmargin-bottom: 16px;\n\t\t\t}\n\t\t\t.sk-th {\n\t\t\t\theight: 16px;\n\t\t\t}\n\t\t\t.table-row {\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t\tgap: 16px;\n\t\t\t\tpadding: 16px 0;\n\t\t\t\tborder-bottom: 1px solid ${borderColor};\n\t\t\t}\n\n\t\t\t.col-user {\n\t\t\t\tflex: 2;\n\t\t\t}\n\t\t\t.col-status {\n\t\t\t\tflex: 1;\n\t\t\t}\n\t\t\t.col-reward {\n\t\t\t\tflex: 2;\n\t\t\t}\n\t\t\t.col-date {\n\t\t\t\tflex: 1;\n\t\t\t}\n\n\t\t\t.sk-badge {\n\t\t\t\theight: 28px;\n\t\t\t\twidth: 90px;\n\t\t\t\tborder-radius: 14px;\n\t\t\t}\n\t\t\t.sk-reward-block {\n\t\t\t\theight: 36px;\n\t\t\t\twidth: 100%;\n\t\t\t\tborder-radius: 6px;\n\t\t\t}\n\n\t\t\t.pagination {\n\t\t\t\tdisplay: flex;\n\t\t\t\tjustify-content: flex-end;\n\t\t\t\tgap: 8px;\n\t\t\t\tmargin-top: 24px;\n\t\t\t}\n\t\t\t.sk-btn-page {\n\t\t\t\theight: 36px;\n\t\t\t\twidth: 64px;\n\t\t\t\tborder-radius: 6px;\n\t\t\t\tmargin-bottom: 0;\n\t\t\t}\n\n\t\t\t@media (max-width: 768px) {\n\t\t\t\tbody {\n\t\t\t\t\tpadding: 20px;\n\t\t\t\t}\n\t\t\t\t.widget-container {\n\t\t\t\t\tpadding: 24px;\n\t\t\t\t}\n\n\t\t\t\t.hero-section {\n\t\t\t\t\tflex-direction: column-reverse;\n\t\t\t\t\tgap: 24px;\n\t\t\t\t}\n\t\t\t\t.hero-image {\n\t\t\t\t\theight: 220px;\n\t\t\t\t\twidth: 100%;\n\t\t\t\t}\n\t\t\t\t.sk-title-lg {\n\t\t\t\t\twidth: 80%;\n\t\t\t\t}\n\n\t\t\t\t.col-date {\n\t\t\t\t\tdisplay: none;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@media (max-width: 480px) {\n\t\t\t\tbody {\n\t\t\t\t\tpadding: 10px;\n\t\t\t\t}\n\t\t\t\t.widget-container {\n\t\t\t\t\tpadding: 16px;\n\t\t\t\t}\n\n\t\t\t\t.sk-stat-num {\n\t\t\t\t\twidth: 80px;\n\t\t\t\t\theight: 40px;\n\t\t\t\t}\n\n\t\t\t\t.col-reward {\n\t\t\t\t\tdisplay: none;\n\t\t\t\t}\n\n\t\t\t\t.col-user {\n\t\t\t\t\tflex: 3;\n\t\t\t\t}\n\t\t\t\t.col-status {\n\t\t\t\t\tflex: 2;\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tjustify-content: flex-end;\n\t\t\t\t}\n\t\t\t}\n </style>\n\n <div class="widget-container">\n\t\t\t<div class="hero-section">\n\t\t\t\t<div class="hero-content">\n\t\t\t\t\t<div class="skeleton sk-title-lg"></div>\n\t\t\t\t\t<div class="skeleton sk-text"></div>\n\t\t\t\t\t<div class="skeleton sk-text sk-text-short"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="skeleton hero-image"></div>\n\t\t\t</div>\n\n\t\t\t<div class="share-section">\n\t\t\t\t<div class="skeleton sk-label"></div>\n\t\t\t\t<div class="skeleton sk-input"></div>\n\t\t\t\t<div class="social-buttons">\n\t\t\t\t\t<div class="skeleton sk-btn-social"></div>\n\t\t\t\t\t<div class="skeleton sk-btn-social"></div>\n\t\t\t\t\t<div class="skeleton sk-btn-social"></div>\n\t\t\t\t\t<div class="skeleton sk-btn-social"></div>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t<div\n\t\t\t\tclass="skeleton sk-title-md"\n\t\t\t\tstyle="margin-top: 0; width: 30%; margin-left: auto; margin-right: auto"\n\t\t\t></div>\n\t\t\t<div\n\t\t\t\tclass="skeleton sk-text"\n\t\t\t\tstyle="width: 60%; margin-left: auto; margin-right: auto"\n\t\t\t></div>\n\n\t\t\t<div class="stats-section">\n\t\t\t\t<div class="stat-card">\n\t\t\t\t\t<div class="skeleton sk-stat-num"></div>\n\t\t\t\t\t<div class="skeleton sk-stat-label"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="stat-card stat-divider">\n\t\t\t\t\t<div class="skeleton sk-stat-num"></div>\n\t\t\t\t\t<div class="skeleton sk-stat-label"></div>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t<div class="skeleton sk-title-md"></div>\n\n\t\t\t<div class="table-header">\n\t\t\t\t<div class="skeleton sk-th col-user"></div>\n\t\t\t\t<div class="skeleton sk-th col-status"></div>\n\t\t\t\t<div class="skeleton sk-th col-reward"></div>\n\t\t\t\t<div class="skeleton sk-th col-date"></div>\n\t\t\t</div>\n\n\t\t\t<div class="table-row">\n\t\t\t\t<div class="col-user">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 70%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-status">\n\t\t\t\t\t<div class="skeleton sk-badge" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-reward">\n\t\t\t\t\t<div class="skeleton sk-reward-block" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-date">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 80%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class="table-row">\n\t\t\t\t<div class="col-user">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 60%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-status">\n\t\t\t\t\t<div class="skeleton sk-badge" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-reward">\n\t\t\t\t\t<div class="skeleton sk-reward-block" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-date">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 80%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class="table-row">\n\t\t\t\t<div class="col-user">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 75%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-status">\n\t\t\t\t\t<div class="skeleton sk-badge" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-reward">\n\t\t\t\t\t<div class="skeleton sk-reward-block" style="margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t\t<div class="col-date">\n\t\t\t\t\t<div class="skeleton sk-text" style="width: 80%; margin: 0"></div>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t<div class="pagination">\n\t\t\t\t<div class="skeleton sk-btn-page"></div>\n\t\t\t\t<div class="skeleton sk-btn-page"></div>\n\t\t\t</div>\n\t\t</div>\n `;const _log$7=browserExports.debug("squatch-js:EMBEDwidget");class EmbedWidget extends Widget{constructor(params,container){super(params);__publicField(this,"show",this.open);__publicField(this,"hide",this.close);if(container){this.container=container}}async load(){var _a2,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l;const brandingConfig=(_b=(_a2=this.context.widgetConfig)==null?void 0:_a2.values)==null?void 0:_b.brandingConfig;const initialHeight=brandingConfig==null?void 0:brandingConfig.loadingHeight;const skeletonBackgroundColor=(_d=(_c=brandingConfig==null?void 0:brandingConfig.color)==null?void 0:_c.loadingSkeleton)==null?void 0:_d.background;const skeletonShimmerColor=(_f=(_e=brandingConfig==null?void 0:brandingConfig.color)==null?void 0:_e.loadingSkeleton)==null?void 0:_f.animationBackground;const borderColor=(_g=brandingConfig==null?void 0:brandingConfig.border)==null?void 0:_g.borderColor;const sizes=(_h=brandingConfig==null?void 0:brandingConfig.widgetSize)==null?void 0:_h.embeddedWidgets;const maxWidth=(sizes==null?void 0:sizes.maxWidth)?formatWidth(sizes.maxWidth):"";const minWidth=(sizes==null?void 0:sizes.minWidth)?formatWidth(sizes.minWidth):"";console.log({brandingConfig:brandingConfig,initialHeight:initialHeight,widgetConfig:this.context.widgetConfig});const skeletonHTML=getSkeleton({height:initialHeight,skeletonBackgroundColor:skeletonBackgroundColor,skeletonShimmerColor:skeletonShimmerColor,borderColor:borderColor});const skeletonContainer=document.createElement("div");skeletonContainer.innerHTML=skeletonHTML;const frame=this._createFrame({minWidth:minWidth,maxWidth:maxWidth,initialHeight:initialHeight});const element=this._findElement();element.innerHTML=skeletonHTML;frame.style.display="none";const injectContents=target=>{target.appendChild(skeletonContainer);target.appendChild(frame)};if((_i=this.context)==null?void 0:_i.container){element.style.visibility="hidden";element.style.height="0";element.style["overflow-y"]="hidden"}if(this.container){if(element.shadowRoot){if(((_j=element.shadowRoot.lastChild)==null?void 0:_j.nodeName)==="IFRAME"){element.shadowRoot.replaceChild(frame,element.shadowRoot.lastChild)}else{injectContents(element.shadowRoot)}}else if(element.firstChild){element.innerHTML="";injectContents(element)}else{injectContents(element)}}else if(!element.firstChild||element.firstChild.nodeName==="#text"){injectContents(element)}const{contentWindow:contentWindow}=frame;if(!contentWindow){throw new Error("Frame needs a content window")}const frameDoc=contentWindow.document;frameDoc.open();console.log({content:this.content,context:this.context,this:this});const domain=this.widgetApi.domain;frameDoc.write(`\n ${((_k=brandingConfig==null?void 0:brandingConfig.main)==null?void 0:_k.brandFont)&&`\n <link rel="preconnect" href="https://fast${domain==="https://staging.referralsaasquatch.com"&&"-staging"}.ssqt.io">\n <link rel="preconnect" href="https://fonts.gstatic.com">\n <link rel="preconnect" href="https://fonts.googleapis.com">\n <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent((_l=brandingConfig==null?void 0:brandingConfig.main)==null?void 0:_l.brandFont)}" as="style">`}\n <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>\n <style data-styles>\n html { visibility:hidden;}\n </style>\n ${this.content}\n\n `);frameDoc.close();domready(frameDoc,(async()=>{if(skeletonContainer&&skeletonContainer.parentNode){skeletonContainer.parentNode.removeChild(skeletonContainer)}frame.style.display="block";const _sqh=contentWindow.squatch||contentWindow.widgetIdent;frame.height=initialHeight||frameDoc.body.scrollHeight;console.log({height:frameDoc.body.scrollHeight});const ro=new contentWindow["ResizeObserver"]((entries=>{for(const entry of entries){const{height:height}=entry.contentRect;frame.height=height}}));const container=await this._findInnerContainer(frame);ro.observe(container);if(this._shouldFireLoadEvent()){this._loadEvent(_sqh);_log$7("loaded")}else if(frameDoc){this._attachLoadEventListener(frameDoc,_sqh)}}))}open(){const frame=this._findFrame();if(!frame)return _log$7("no target element to open");if(!frame.contentWindow)return _log$7("Frame needs a content window");const element=this._findElement();element.style.visibility="unset";element.style.height="auto";element.style["overflow-y"]="auto";frame.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const _sqh=frame.contentWindow.squatch||frame.contentWindow.widgetIdent;if(this.context.user){this._loadEvent(_sqh);_log$7("loaded")}else{if(!frame.contentDocument)return;this._attachLoadEventListener(frame.contentDocument,_sqh)}}close(){const frame=this._findFrame();if(!frame)return _log$7("no target element to close");if(frame.contentDocument)this._detachLoadEventListener(frame.contentDocument);const element=this._findElement();element.style.visibility="hidden";element.style.height="0";element.style["overflow-y"]="hidden";_log$7("Embed widget closed")}_error(rs,mode="embed",style=""){return super._error(rs,mode,style)}_shouldFireLoadEvent(){const noContainer=!this.container;const isComponent=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));const isVerified=!!this.context.user;return isVerified&&(noContainer||isComponent)}}const _log$6=browserExports.debug("squatch-js:POPUPwidget");let popupId=0;class PopupWidget extends Widget{constructor(params,trigger=".squatchpop"){super(params);__publicField(this,"trigger");__publicField(this,"id");__publicField(this,"show",this.open);__publicField(this,"hide",this.close);this.trigger=trigger;if(this.container){this.id="squatchModal"}else{this.id=popupId===0?`squatchModal`:`squatchModal__${popupId}`;popupId=popupId+1}document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let triggerElement;try{triggerElement=document.querySelector(this.trigger)||document.querySelector(".impactpop");if(this.trigger&&!triggerElement)_log$6("No element found with trigger selector",this.trigger)}catch{_log$6("Not a valid selector",this.trigger)}if(triggerElement){triggerElement.onclick=()=>{this.open()}}}_createPopupDialog(){var _a2,_b,_c;const dialog=document.createElement("dialog");const brandingConfig=(_b=(_a2=this.context.widgetConfig)==null?void 0:_a2.values)==null?void 0:_b.brandingConfig;const sizes=(_c=brandingConfig==null?void 0:brandingConfig.widgetSize)==null?void 0:_c.popupWidgets;const minWidth=(sizes==null?void 0:sizes.minWidth)?formatWidth(sizes.minWidth):"auto";const maxWidth=(sizes==null?void 0:sizes.maxWidth)?formatWidth(sizes.maxWidth):"500px";dialog.id=this.id;dialog.setAttribute("style",`width: 100%; min-width: ${minWidth}; max-width: ${maxWidth}; border: none; padding: 0;`);const onClick=e=>{e.stopPropagation();if(e.target===dialog)dialog.close()};dialog.addEventListener("click",onClick);return dialog}async load(){var _a2;const frame=this._createFrame();this._initialiseCTA();const element=this.container?this._findElement():document.body;const dialogParent=element.shadowRoot||element;const dialog=this._createPopupDialog();dialog.appendChild(frame);if(((_a2=dialogParent.lastChild)==null?void 0:_a2.nodeName)==="DIALOG"){dialogParent.replaceChild(dialog,dialogParent.lastChild)}else{dialogParent.appendChild(dialog)}const{contentWindow:contentWindow}=frame;if(!contentWindow){throw new Error("Frame needs a content window")}const frameDoc=contentWindow.document;frameDoc.open();frameDoc.write(this.content);frameDoc.write(`<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`);frameDoc.close();_log$6("Popup template loaded into iframe");await this._setupResizeHandler(frame)}async _setupResizeHandler(frame){const{contentWindow:contentWindow}=frame;if(!contentWindow){throw new Error("Frame needs a content window")}const frameDoc=contentWindow.document;domready(frameDoc,(async()=>{frameDoc.body.style.overflowY="hidden";frame.height=`${frameDoc.body.offsetHeight}px`;const ro=new contentWindow["ResizeObserver"]((entries=>{for(const entry of entries){const{top:top,bottom:bottom}=entry.contentRect;const computedHeight=bottom+top;frame.height=computedHeight+"";entry.target.style=``}}));ro.observe(await this._findInnerContainer(frame))}))}open(){const element=this.container?this._findElement():document.body;const parent=element.shadowRoot||element;const dialog=parent.querySelector(`#${this.id}`);if(!dialog)throw new Error("Could not determine container div");dialog.showModal();const frame=this._findFrame();if(!frame)throw new Error("Could not find iframe");const{contentWindow:contentWindow}=frame;if(!contentWindow)throw new Error("Squatch.js has an empty iframe");const frameDoc=contentWindow.document;domready(frameDoc,(()=>{var _a2;const _sqh=contentWindow.squatch||contentWindow.widgetIdent;(_a2=frame.contentDocument)==null?void 0:_a2.dispatchEvent(new CustomEvent("sq:refresh"));if(this.context.user){this._loadEvent(_sqh);_log$6("Popup opened")}else{this._attachLoadEventListener(frameDoc,_sqh)}}))}close(){const frame=this._findFrame();if(frame==null?void 0:frame.contentDocument)this._detachLoadEventListener(frame.contentDocument);const element=this.container?this._findElement():document.body;const parent=element.shadowRoot||element;const dialog=parent.querySelector(`#${this.id}`);if(!dialog)throw new Error("Could not determine container div");dialog.close();_log$6("Popup closed")}_clickedOutside({target:target}){}_error(rs,mode="modal",style=""){const _style="body { margin: 0; } .modal { box-shadow: none; border: 0; }";return super._error(rs,mode,style||_style)}}const _log$5=browserExports.debug("squatch-js:widgets");class Widgets{constructor(configin){__publicField(this,"api");__publicField(this,"tenantAlias");__publicField(this,"domain");__publicField(this,"npmCdn");const config=validateConfig(configin);this.tenantAlias=config.tenantAlias;this.domain=config.domain;this.npmCdn=config.npmCdn;this.api=new WidgetApi(config)}async upsertUser(config){const raw=config;const clean=validateWidgetConfig(raw);try{const response=await this.api.upsertUser(clean);return{widget:this._renderWidget(response,clean,{type:"upsert",user:clean.user,engagementMedium:config.engagementMedium,container:config.container,trigger:config.trigger,widgetConfig:{values:{brandingConfig:response==null?void 0:response.brandingConfig}}}),user:response.user}}catch(err){_log$5(err);if(err.apiErrorCode){this._renderErrorWidget(err,config.engagementMedium)}throw new Error(err)}}async render(config){const raw=config;const clean=validatePasswordlessConfig(raw);try{const response=await this.api.render(clean);return{widget:this._renderWidget(response,clean,{type:"passwordless",engagementMedium:clean.engagementMedium,container:clean.container,trigger:clean.trigger,widgetConfig:{values:{brandingConfig:response==null?void 0:response.brandingConfig}}}),user:response.user}}catch(err){if(err.apiErrorCode){this._renderErrorWidget(err,clean.engagementMedium)}throw new Error(err)}}async autofill(selector){const input=selector;if(typeof input==="function"){try{const response=await this.api.squatchReferralCookie();input(response)}catch(e){_log$5("Autofill error",e);throw new Error(e)}return}if(typeof input!=="string")throw new Error("Autofill accepts a string or function");let elems=document.querySelectorAll(input);let elem;if(elems.length>0){elem=elems[0]}else{_log$5("Element id/class or function missing");throw new Error("Element id/class or function missing")}try{const response=await this.api.squatchReferralCookie();elem.value=response.codes[0]}catch(e){throw new Error(e)}}_renderWidget(response,config,context){var _a2;_log$5("Rendering Widget...");if(!response)throw new Error("Unable to get a response");let widget2;let displayOnLoad=!!config.displayOnLoad;const opts=response.jsOptions||{};const params={content:response.template,type:config.widgetType||((_a2=opts.widget)==null?void 0:_a2.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:context};if(opts.widgetUrlMappings){opts.widgetUrlMappings.forEach((rule=>{var _a3,_b;if(Widgets._matchesUrl(rule.url)){if(rule.widgetType!=="CONVERSION_WIDGET"||((_b=(_a3=response.user)==null?void 0:_a3.referredBy)==null?void 0:_b.code)){displayOnLoad=rule.displayOnLoad;_log$5(`Display ${rule.widgetType} on ${rule.url}`)}else{_log$5(`Don't display ${rule.widgetType} when no referral on widget rule match ${rule.url}`)}}}))}if(opts.fuelTankAutofillUrls){_log$5("We found a fuel tank autofill!");opts.fuelTankAutofillUrls.forEach((({url:url,formSelector:formSelector})=>{var _a3,_b,_c;if(Widgets._matchesUrl(url)){_log$5("Fuel Tank URL matches");if((_b=(_a3=response.user)==null?void 0:_a3.referredBy)==null?void 0:_b.code){const formAutofill=document.querySelector(formSelector);if(formAutofill){formAutofill.value=((_c=response.user.referredBy.referredReward)==null?void 0:_c.fuelTankCode)||""}else{_log$5(new Error(`Element with id/class ${formSelector} was not found.`))}}}}))}if(config.engagementMedium==="EMBED"){widget2=this._renderEmbedWidget(params)}else{widget2=this._renderPopupWidget(params);if(displayOnLoad)widget2.open()}return widget2}_renderPopupWidget(params){const widget2=new PopupWidget(params,params.context.trigger);widget2.load();return widget2}_renderEmbedWidget(params){const widget2=new EmbedWidget(params,params.context.container);widget2.load();return widget2}_renderErrorWidget(props,em="POPUP"){const{apiErrorCode:apiErrorCode,rsCode:rsCode,message:message}=props;_log$5(new Error(`${apiErrorCode} (${rsCode}) ${message}`));const params={content:"error",rsCode:rsCode,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let widget2;if(em==="EMBED"){widget2=new EmbedWidget(params);widget2.load()}else if(em==="POPUP"){widget2=new PopupWidget(params);widget2.load()}}static _matchesUrl(rule){return window.location.href.match(new RegExp(rule))?true:false}}class EventsApi{constructor(config){__publicField(this,"tenantAlias");__publicField(this,"domain");const raw=config;const clean=validateConfig(raw);this.tenantAlias=clean.tenantAlias;this.domain=clean.domain}track(params,options){const raw=params;const rawOpts=options;const body=_validateEvent(raw);const{jwt:jwt}=_validateTrackOptions(rawOpts);const ta=encodeURIComponent(this.tenantAlias);const userId=encodeURIComponent(body.userId);const accountId=encodeURIComponent(body.accountId);const path=`/api/v1/${ta}/open/account/${accountId}/user/${userId}/events`;const url=this.domain+path;return doPost(url,JSON.stringify(body),jwt)}}function _validateEvent(raw){if(!isObject$1(raw))throw new Error("tracking parameter must be an object");if(!(raw==null?void 0:raw["accountId"]))throw new Error("accountId field is required");if(!(raw==null?void 0:raw["events"]))throw new Error("events field is required");if(!(raw==null?void 0:raw["userId"]))throw new Error("userId field is required");const clean=raw;if(!Array.isArray(clean.events))throw new Error("'events' should be an array");return clean}function _validateTrackOptions(raw){if(!isObject$1(raw))throw new Error("'options' should be an object");return raw}function asyncLoad(){var _a2;const namespace=window[IMPACT_NAMESPACE]?IMPACT_NAMESPACE:DEFAULT_NAMESPACE;const cached=((_a2=window["_"+namespace])==null?void 0:_a2.ready)||[];const declarativeCache=window.impactOnReady||window.squatchOnReady;const readyFns=[...cached,declarativeCache].filter((a=>!!a));setTimeout((()=>{if(!window[DEFAULT_NAMESPACE])return;window[IMPACT_NAMESPACE]=window[DEFAULT_NAMESPACE];readyFns.forEach((cb=>cb()));window[DEFAULT_NAMESPACE]._auto();window["_"+namespace]=void 0;delete window["_"+namespace]}),0)}const _log$4=browserExports.debug("squatch-js");const isObject=item=>typeof item==="object"&&!Array.isArray(item);const deepMerge=(target,source)=>{const isDeep=prop=>isObject(source[prop])&&target.hasOwnProperty(prop)&&isObject(target[prop]);const replaced=Object.getOwnPropertyNames(source).map((prop=>({[prop]:isDeep(prop)?deepMerge(target[prop],source[prop]):source[prop]}))).reduce(((a,b)=>({...a,...b})),{});return{...target,...replaced}};function b64decode(input){const binary=atob(input.replace(/_/g,"/").replace(/-/g,"+"));const bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++){bytes[i]=binary.charCodeAt(i)}return new TextDecoder("utf8").decode(bytes)}function b64encode(input){const encodedInput=(new TextEncoder).encode(input);const binary=Array.from(encodedInput,(byte=>String.fromCodePoint(byte))).join("");return btoa(binary).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function getTopDomain(){var i,h,weird_cookie="weird_get_top_level_domain=cookie",hostname=document.location.hostname.split(".");for(i=hostname.length-1;i>=0;i--){h=hostname.slice(i).join(".");document.cookie=weird_cookie+";domain=."+h+";";if(document.cookie.indexOf(weird_cookie)>-1){document.cookie=weird_cookie.split("=")[0]+"=;domain=."+h+";expires=Thu, 01 Jan 1970 00:00:01 GMT;";return h}}}function _pushCookie(){const queryString=window.location.search;const urlParams=new URLSearchParams(queryString);const refParam=urlParams.get("_saasquatch")||"";if(refParam){let paramsJSON="",existingCookie="",reEncodedCookie="";try{paramsJSON=JSON.parse(b64decode(refParam))}catch(error){_log$4("Unable to decode params",error);return}try{existingCookie=JSON.parse(b64decode(api$1.get("_saasquatch")));_log$4("existing cookie",existingCookie)}catch(error){_log$4("Unable to retrieve cookie",error)}try{const domain=getTopDomain();_log$4("domain retrieved:",domain);if(existingCookie){const newCookie=deepMerge(existingCookie,paramsJSON);reEncodedCookie=b64encode(JSON.stringify(newCookie));_log$4("cookie to store:",newCookie)}else{reEncodedCookie=b64encode(JSON.stringify(paramsJSON));_log$4("cookie to store:",paramsJSON)}api$1.set("_saasquatch",reEncodedCookie,{expires:365,secure:false,sameSite:"Lax",domain:domain,path:"/"})}catch(error){_log$4("Unable to set cookie",error)}}}const _log$3=browserExports.debug("squatch-js");function _getAutoConfig(){var _a2;const queryString=window.location.search;const urlParams=new URLSearchParams(queryString);const refParam=urlParams.get("_saasquatchExtra")||"";if(!refParam){_log$3("No _saasquatchExtra param");return}const config=validateConfig({tenantAlias:"UNKNOWN"});if(!config.domain){_log$3("domain must be provided in config to use _saasquatchExtra");return}let raw;try{raw=JSON.parse(b64decode(refParam))}catch(e){_log$3("Unable to decode _saasquatchExtra config");return}function normalizeDomain(domain){return domain.replace(/^https?:\/\//,"")}const normalizedDomain=normalizeDomain(config.domain);const tenantAlias=Object.keys((raw==null?void 0:raw[normalizedDomain])||{})[0];const widgetConfig=(_a2=raw==null?void 0:raw[normalizedDomain])==null?void 0:_a2[tenantAlias];if(!widgetConfig){_log$3("_saasquatchExtra did not have an expected structure");return void 0}const{autoPopupWidgetType:autoPopupWidgetType,...rest}=widgetConfig;return{widgetConfig:{widgetType:autoPopupWidgetType,displayOnLoad:true,...rest},squatchConfig:{...config,tenantAlias:tenantAlias}}}const _log$2=browserExports.debug("squatch-js:decodeUserJwt");function decodeUserJwt(tokenStr){var _a2;try{const base64Url=tokenStr.split(".")[1];if(base64Url===void 0)return null;const jsonStr=b64decode(base64Url);return(_a2=JSON.parse(jsonStr))==null?void 0:_a2.user}catch(e){_log$2(e);return null}}const _log$1=debug("squatch-js:DeclarativeWidget");class DeclarativeWidget extends HTMLElement{constructor(){super();__publicField(this,"config");__publicField(this,"token");__publicField(this,"tenant");__publicField(this,"widgetType");__publicField(this,"locale");__publicField(this,"widgetApi");__publicField(this,"analyticsApi");__publicField(this,"widgetInstance");__publicField(this,"type");__publicField(this,"container");__publicField(this,"element");__publicField(this,"loaded");__publicField(this,"_setWidget",((res,config)=>{var _a2;const params={api:this.widgetApi,content:res.template,context:{type:config.type,user:config.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:res.widgetConfig},type:this.widgetType,domain:((_a2=this.config)==null?void 0:_a2.domain)||DEFAULT_DOMAIN,npmCdn:DEFAULT_NPM_CDN,container:this};if(this.type==="EMBED"){return new EmbedWidget(params)}else{const useFirstChildTrigger=this.firstChild?null:void 0;return new PopupWidget(params,useFirstChildTrigger)}}));__publicField(this,"setErrorWidget",(e=>{var _a2;const params={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((_a2=this.config)==null?void 0:_a2.domain)||DEFAULT_DOMAIN,npmCdn:DEFAULT_NPM_CDN,container:this};if(this.type==="EMBED"){return new EmbedWidget(params)}else{const useFirstChildTrigger=this.firstChild?null:void 0;return new PopupWidget(params,useFirstChildTrigger)}}));__publicField(this,"reload",this.renderWidget);__publicField(this,"show",this.open);__publicField(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML=`<style>:host { display: block; }</style><slot></slot>`;this.config=getConfig();this.token=getToken();this.tenant=window.squatchTenant;this.container=this}_setupApis(config){var _a2,_b;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new WidgetApi({tenantAlias:(config==null?void 0:config.tenantAlias)||this.tenant,domain:(config==null?void 0:config.domain)||((_a2=this.config)==null?void 0:_a2.domain)||DEFAULT_DOMAIN});this.analyticsApi=new AnalyticsApi({domain:(config==null?void 0:config.domain)||((_b=this.config)==null?void 0:_b.domain)||DEFAULT_DOMAIN})}async renderPasswordlessVariant(){this._setupApis();_log$1("Rendering as an Instant Access widget");return await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then((res=>this._setWidget(res,{type:"passwordless"}))).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const userObj=decodeUserJwt(this.token);if(!userObj){return this.setErrorWidget(Error("No user object in token."))}_log$1("Rendering as a Verified widget");await this.widgetApi.upsertUser({user:userObj,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token});const widgetInstance=await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then((res=>this._setWidget(res,{type:"upsert",user:userObj}))).catch(this.setErrorWidget);return widgetInstance}async getWidgetInstance(){let widgetInstance;this.widgetType=this.getAttribute("widget")||void 0;this.locale=this.getAttribute("locale")||this.locale;if(!this.widgetType)throw new Error("No widget has been specified");if(!this.token){widgetInstance=await this.renderPasswordlessVariant()}else{widgetInstance=await this.renderUserUpsertVariant()}this.widgetInstance=widgetInstance;if(this.widgetInstance)this.dispatchEvent(new CustomEvent("sq:widget-loaded"));return widgetInstance}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()}}class DeclarativeEmbedWidget extends DeclarativeWidget{constructor(){super();this.type="EMBED";this.loaded=false}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(attr,oldVal,newVal){if(oldVal===newVal||!this.loaded)return;switch(attr){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){var _a2;this.loaded=true;this.container=this.getAttribute("container");const skeletonHTML=`\n <div>\n <h1>Dynamic Content</h1>\n <p>This content was dynamically added to the widget before it loaded.</p>\n <p>This content comes from the embeded widget class</p>\n </div>\n `;const skeletonContainer=document.createElement("div");skeletonContainer.id="loading-skeleton";skeletonContainer.innerHTML=skeletonHTML;if(!this.shadowRoot){this.attachShadow({mode:"open"})}if(this.shadowRoot){this.shadowRoot.innerHTML=skeletonHTML}await this.renderWidget();const loadingElement=(_a2=this.shadowRoot)==null?void 0:_a2.getElementById("loading-skeleton");if(loadingElement){loadingElement.remove()}if(this.getAttribute("open")!==null)this.open()}}class DeclarativePopupWidget extends DeclarativeWidget{constructor(){super();this.type="POPUP";this.loaded=false;this.addEventListener("click",(e=>{e.stopPropagation();this.open()}))}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(attr,oldVal,newVal){if(oldVal===newVal||!this.loaded)return;switch(attr){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=true;this.container=this.getAttribute("container");const skeletonHTML=`\n <div>\n <h1>Dynamic Content</h1>\n <p>This content was dynamically added to the widget before it loaded.</p>\n <p>This content comes from the embedded widget class</p>\n </div>\n `;const skeletonContainer=document.createElement("div");skeletonContainer.id="loading-skeleton";skeletonContainer.innerHTML=skeletonHTML;const root=this.shadowRoot||this.attachShadow({mode:"open"});root.innerHTML="";root.appendChild(skeletonContainer);await this.renderWidget();const loadingElement=root.getElementById("loading-skeleton");if(loadingElement){loadingElement.remove();console.log("Skeleton removed successfully")}else{console.warn("Could not find skeleton to remove")}if(this.getAttribute("open")!==null)this.open()}}class SquatchEmbed extends DeclarativeEmbedWidget{}class SquatchPopup extends DeclarativePopupWidget{}class ImpactEmbed extends DeclarativeEmbedWidget{}class ImpactPopup extends DeclarativePopupWidget{}if(!window.customElements.get("squatch-embed"))window.customElements.define("squatch-embed",SquatchEmbed);if(!window.customElements.get("impact-embed"))window.customElements.define("impact-embed",ImpactEmbed);if(!window.customElements.get("squatch-popup"))window.customElements.define("squatch-popup",SquatchPopup);if(!window.customElements.get("impact-popup"))window.customElements.define("impact-popup",ImpactPopup);function help(){console.log(`Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.`)}const _log=browserExports.debug("squatch-js");let _api=null;let _widgets=null;let _events=null;function api(){if(!_api)init({});return _api}function widgets(){if(!_widgets)init({});return _widgets}function events(){if(!_events)init({});return _events}function widget(widgetConfig){var _a2;return(_a2=widgets())==null?void 0:_a2.render(widgetConfig)}function _auto(){var _a2;const configs=_getAutoConfig();if(configs){const{squatchConfig:squatchConfig,widgetConfig:widgetConfig}=configs;init(squatchConfig);return(_a2=widgets())==null?void 0:_a2.render(widgetConfig)}}function init(configIn){const raw=configIn;const config=validateConfig(raw);if(config.tenantAlias.match("^test")||config.debug){browserExports.debug.enable("squatch-js*")}else{browserExports.debug.disable()}_log("initializing ...");_api=new WidgetApi(config);_widgets=new Widgets(config);_events=new EventsApi(config);_log("Widget API instance",_api);_log("Widgets instance",_widgets);_log("Events API instance",_events)}function ready(fn){fn()}function autofill(selector){widgets().autofill(selector)}function pushCookie(){_pushCookie()}if(typeof document!=="undefined"&&!window.SaaSquatchDoNotAutoDrop){pushCookie()}if((_a=window["squatch"])==null?void 0:_a.init)_log("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics.");if(typeof document!=="undefined")asyncLoad();exports2.DeclarativeEmbedWidget=DeclarativeEmbedWidget;exports2.DeclarativePopupWidget=DeclarativePopupWidget;exports2.EmbedWidget=EmbedWidget;exports2.PopupWidget=PopupWidget;exports2.WidgetApi=WidgetApi;exports2.Widgets=Widgets;exports2._auto=_auto;exports2.api=api;exports2.autofill=autofill;exports2.events=events;exports2.help=help;exports2.init=init;exports2.pushCookie=pushCookie;exports2.ready=ready;exports2.widget=widget;exports2.widgets=widgets;Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})}));
|
|
3
|
+
* domready (c) Dustin Diaz 2014 - License MIT
|
|
4
|
+
*
|
|
5
|
+
*/}function ee(o,t){let e=[],n,i=o,s=i.documentElement.doScroll,a="DOMContentLoaded",r=(s?/^loaded|^c/:/^loaded|^i|^c/).test(i.readyState);return r||i.addEventListener(a,n=()=>{for(i.removeEventListener(a,n),r=!0;n=e.shift();)n()}),r?setTimeout(t,0):e.push(t)}function N({value:o,unit:t}){switch(t){case"px":return`${o}px`;case"%":return`${o}%`;default:return`${o}px`}}class se{constructor(t){l(this,"domain");var i;const n=Ce(t);this.domain=(n==null?void 0:n.domain)||((i=K())==null?void 0:i.domain)||A}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),a=t.programId?`&programId=${encodeURIComponent(t.programId)}`:"",r=`/a/${e}/widgets/analytics/loaded?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}${a}`,d=this.domain+r;return Z(d,JSON.stringify({}))}pushAnalyticsShareClickedEvent(t){const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),a=encodeURIComponent(t.shareMedium),r=`/a/${e}/widgets/analytics/shared?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}&shareMedium=${a}`,d=this.domain+r;return Z(d,JSON.stringify({}))}}function Ce(o){if(!I(o))throw new Error("'options' should be an object");return o}const y=k("squatch-js:widget");class ae{constructor(t){l(this,"type");l(this,"content");l(this,"analyticsApi");l(this,"widgetApi");l(this,"context");l(this,"npmCdn");l(this,"container");l(this,"loadEventListener",null);var e;y("widget initializing ..."),this.content=t.content==="error"?this._error(t.rsCode):t.content,this.type=t.type,this.widgetApi=t.api,this.npmCdn=t.npmCdn,this.analyticsApi=new se({domain:t.domain}),this.context=t.context,this.container=((e=t.context)==null?void 0:e.container)||t.container}_findElement(){let t;if(typeof this.container=="string"?(t=document.querySelector(this.container),y("loading widget with selector",t)):this.container instanceof HTMLElement?(t=this.container,y("loading widget with container",t)):this.container?(t=null,y("container must be an HTMLElement or string",this.container)):(t=document.querySelector("#squatchembed")||document.querySelector(".squatchembed")||document.querySelector("#impactembed")||document.querySelector(".impactembed"),y("loading widget with default selector",t)),!(t instanceof HTMLElement))throw new Error(`element with selector '${this.container||"#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`);return t}_createFrame(t){const e=document.createElement("iframe");return e.squatchJsApi=this,e.id="squatchFrame",e.width="100%",e.src="about:blank",e.scrolling="no",e.setAttribute("style","border: 0; background-color: none; width: 1px; min-width: 100%;"),t!=null&&t.minWidth&&(e.style.minWidth=t.minWidth),t!=null&&t.maxWidth&&(e.style.maxWidth=t.maxWidth),(t!=null&&t.maxWidth||t!=null&&t.minWidth)&&(e.style.width="100%"),t!=null&&t.initialHeight&&(e.height=t.initialHeight),e}_findFrame(){const t=this.container?this._findElement():document.body;return(t.shadowRoot||t).querySelector("iframe#squatchFrame")}_detachLoadEventListener(t){this.loadEventListener&&(t.removeEventListener("sq:user-registration",this.loadEventListener),this.loadEventListener=null)}_attachLoadEventListener(t,e){this.loadEventListener===null&&(this.loadEventListener=n=>{this._loadEvent({...e,userId:n.detail.userId,accountId:n.detail.accountId})},t.addEventListener("sq:user-registration",this.loadEventListener))}_loadEvent(t){var n;if(!t)return;if(!I(t))throw new Error("Widget Load event identity property is not an object");let e;if("programId"in t){if(!t.tenantAlias||!t.accountId||!t.userId||!t.engagementMedium)throw new Error("Widget Load event missing required properties");e={tenantAlias:t.tenantAlias,externalAccountId:t.accountId,externalUserId:t.userId,engagementMedium:t.engagementMedium,programId:t.programId}}else{const{analytics:i,mode:s}=t;e={tenantAlias:i.attributes.tenant,externalAccountId:i.attributes.accountId,externalUserId:i.attributes.userId,engagementMedium:s.widgetMode}}(n=this.analyticsApi.pushAnalyticsLoadEvent(e))==null||n.then((i=>{y(`${e.engagementMedium} loaded event recorded.`)})).catch((i=>{y(`ERROR: pushAnalyticsLoadEvent() ${i}`)}))}_shareEvent(t,e){t&&this.analyticsApi.pushAnalyticsShareClickedEvent({tenantAlias:t.analytics.attributes.tenant,externalAccountId:t.analytics.attributes.accountId,externalUserId:t.analytics.attributes.userId,engagementMedium:t.mode.widgetMode,shareMedium:e}).then((n=>{y(`${t.mode.widgetMode} share ${e} event recorded. ${n}`)})).catch((n=>{y(`ERROR: pushAnalyticsShareClickedEvent() ${n}`)}))}_error(t,e="modal",n=""){return`<!DOCTYPE html>\n \x3c!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]--\x3e\n \x3c!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]--\x3e\n \x3c!--[if gt IE 8]>\x3c!--\x3e<html lang="en">\x3c!--<![endif]--\x3e\n <head>\n <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">\n <style>\n ${n}\n </style>\n </head>\n <body>\n\n <div class="squatch-container ${e}" style="width:100%">\n <div class="errorheader">\n <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">×</button>\n <p class="errortitle">Error</p>\n </div>\n <div class="errorbody">\n <div class="sadface"><img src="https://fast.ssqt.io/assets/images/face.png"></div>\n <h4>Our referral program is temporarily unavailable.</h4><br>\n <p>Please reload the page or check back later.</p>\n <p>If the persists please contact our support team.</p>\n <br>\n <br>\n <div class="right-align errtxt">\n Error Code: ${t}\n </div>\n </div>\n </div>\n </body>\n </html>`}async _findInnerContainer(t){const{contentWindow:e}=t;if(!e)throw new Error("Squatch.js frame inner frame is empty");const n=e.document;function i(){const a=n.getElementsByTagName("sqh-global-container"),r=n.getElementsByClassName("squatch-container");return a.length>0?a[0]:r.length>0?r[0]:null}let s=null;for(let a=0;a<5&&(s=i(),!s);a++)await Ae(100);return s||n.body}reload({email:t,firstName:e,lastName:n},i){const s=this._findFrame();if(!s)throw new Error("Could not find widget iframe");const a=s.contentWindow,r=this.context.engagementMedium||"POPUP";if(!a)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:r,widgetType:this.type,jwt:i})}else if(this.context.type==="passwordless")d=this.widgetApi.render({user:void 0,engagementMedium:r,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:r},(()=>{this.load(),r==="POPUP"&&this.open()})))})).catch((({message:c})=>{y(`${c}`)}))}__deprecated__register(t,e,n){const s=t.contentWindow.document,a=s.createElement("button"),r=s.getElementsByClassName("squatch-register")[0];if(r){a.className="btn btn-primary",a.id="show-stats-btn",a.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;";a.setAttribute("style",d),a.onclick=n,r.style.paddingTop="30px",r.innerHTML=`<p><strong>${e.email}</strong><br>Has been successfully registered</p>`,r.appendChild(a)}}}function Ae(o){return new Promise((t=>{setTimeout(t,o)}))}const _=k("squatch-js:EMBEDwidget");class q extends ae{constructor(e,n){super(e);l(this,"show",this.open);l(this,"hide",this.close);n&&(this.container=n)}async load(){var m,f,w,b,M,E,ge;const e=(f=(m=this.context.widgetConfig)==null?void 0:m.values)==null?void 0:f.brandingConfig,n=e==null?void 0:e.loadingHeight,i=(w=e==null?void 0:e.widgetSize)==null?void 0:w.embeddedWidgets,s=i!=null&&i.maxWidth?N(i.maxWidth):"",a=i!=null&&i.minWidth?N(i.minWidth):"",r=this._createFrame({minWidth:a,maxWidth:s,initialHeight:n}),d=this._findElement();(b=this.context)!=null&&b.container&&(d.style.visibility="hidden",d.style.height="0",d.style["overflow-y"]="hidden"),this.container?d.shadowRoot?((M=d.shadowRoot.lastChild)==null?void 0:M.nodeName)==="IFRAME"?d.shadowRoot.replaceChild(r,d.shadowRoot.lastChild):d.shadowRoot.appendChild(r):d.firstChild?d.replaceChild(r,d.firstChild):d.appendChild(r):(!d.firstChild||d.firstChild.nodeName==="#text")&&d.appendChild(r);const{contentWindow:c}=r;if(!c)throw new Error("Frame needs a content window");const h=c.document;h.open();const p=this.widgetApi.domain;h.write(`\n ${(E=e==null?void 0:e.main)!=null&&E.brandFont?`\n <link rel="preconnect" href="https://fast${p==="https://staging.referralsaasquatch.com"&&"-staging"}.ssqt.io">\n <link rel="preconnect" href="https://fonts.gstatic.com">\n <link rel="preconnect" href="https://fonts.googleapis.com">\n <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent((ge=e==null?void 0:e.main)==null?void 0:ge.brandFont)}" as="style">`:""}\n <link rel="dns-prefetch" href="https://res.cloudinary.com">\n <link rel="preconnect" href="https://res.cloudinary.com" crossorigin>\n <style data-styles>\n html { visibility:hidden;}\n </style>\n ${this.content}\n\n `),h.close(),ee(h,(async()=>{const me=c.squatch||c.widgetIdent;r.height=n||h.body.scrollHeight;const Ge=new ResizeObserver((Xe=>{for(const Qe of Xe){const{height:Ye}=Qe.contentRect;r.height=Ye}})),Ve=await this._findInnerContainer(r);Ge.observe(Ve),this._shouldFireLoadEvent()?(this._loadEvent(me),_("loaded")):h&&this._attachLoadEventListener(h,me)}))}open(){const e=this._findFrame();if(!e)return _("no target element to open");if(!e.contentWindow)return _("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),_("loaded");else{if(!e.contentDocument)return;this._attachLoadEventListener(e.contentDocument,i)}}close(){const e=this._findFrame();if(!e)return _("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",_("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 $=k("squatch-js:POPUPwidget");let F=0;class R extends ae{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=F===0?"squatchModal":`squatchModal__${F}`,F=F+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&&$("No element found with trigger selector",this.trigger)}catch{$("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?N(i.minWidth):"auto",a=i!=null&&i.maxWidth?N(i.maxWidth):"500px";n.id=this.id,n.setAttribute("style",`width: 100%; min-width: ${s}; max-width: ${a}; border: none; padding: 0;`);const r=c=>{c.stopPropagation(),c.target===n&&n.close()};return n.addEventListener("click",r),n}async load(){var p,m,f,w,b;const e=(m=(p=this.context.widgetConfig)==null?void 0:p.values)==null?void 0:m.brandingConfig,n=e==null?void 0:e.loadingHeight,i=this._createFrame({initialHeight:n});this._initialiseCTA();const s=this.container?this._findElement():document.body,a=s.shadowRoot||s,r=this._createPopupDialog(e);r.appendChild(i),((f=a.lastChild)==null?void 0:f.nodeName)==="DIALOG"?a.replaceChild(r,a.lastChild):a.appendChild(r);const{contentWindow:d}=i;if(!d)throw new Error("Frame needs a content window");const c=d.document;c.open();const h=this.widgetApi.domain;c.write(`\n ${(w=e==null?void 0:e.main)!=null&&w.brandFont?`\n <link rel="preconnect" href="https://fast${h==="https://staging.referralsaasquatch.com"&&"-staging"}.ssqt.io">\n <link rel="preconnect" href="https://fonts.gstatic.com">\n <link rel="preconnect" href="https://fonts.googleapis.com">\n <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent((b=e==null?void 0:e.main)==null?void 0:b.brandFont)}" as="style">`:""}\n <link rel="dns-prefetch" href="https://res.cloudinary.com">\n <link rel="preconnect" href="https://res.cloudinary.com" crossorigin>\n <style data-styles>\n html { visibility:hidden;}\n </style>\n ${this.content}\n\n `),c.close(),$("Popup template loaded into iframe"),await this._setupResizeHandler(i,n)}async _setupResizeHandler(e,n){const{contentWindow:i}=e;if(!i)throw new Error("Frame needs a content window");const s=i.document;ee(s,(async()=>{s.body.style.overflowY="hidden",e.height=n||s.body.offsetHeight,new ResizeObserver((r=>{for(const d of r){const{top:c,bottom:h}=d.contentRect,p=h+c;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:a}=s;if(!a)throw new Error("Squatch.js has an empty iframe");const r=a.document;ee(r,(()=>{var c;const d=a.squatch||a.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),$("Popup opened")):this._attachLoadEventListener(r,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(),$("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 v=k("squatch-js:widgets");class U{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=T(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new D(e)}async upsertUser(t){const n=ie(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 v(i),i.apiErrorCode&&this._renderErrorWidget(i,t.engagementMedium),new Error(i)}}async render(t){const n=oe(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 v("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 v("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(v("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const a=t.jsOptions||{},r={content:t.template,type:e.widgetType||((d=a.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return a.widgetUrlMappings&&a.widgetUrlMappings.forEach((c=>{var h,p;U._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(p=(h=t.user)==null?void 0:h.referredBy)!=null&&p.code?(s=c.displayOnLoad,v(`Display ${c.widgetType} on ${c.url}`)):v(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))})),a.fuelTankAutofillUrls&&(v("We found a fuel tank autofill!"),a.fuelTankAutofillUrls.forEach((({url:c,formSelector:h})=>{var p,m,f;if(U._matchesUrl(c)&&(v("Fuel Tank URL matches"),(m=(p=t.user)==null?void 0:p.referredBy)!=null&&m.code)){const w=document.querySelector(h);w?w.value=((f=t.user.referredBy.referredReward)==null?void 0:f.fuelTankCode)||"":v(new Error(`Element with id/class ${h} was not found.`))}}))),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(r):(i=this._renderPopupWidget(r),s&&i.open()),i}_renderPopupWidget(t){const e=new R(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new q(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,message:s}=t;v(new Error(`${n} (${i}) ${s}`));const a={content:"error",rsCode:i,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let r;e==="EMBED"?(r=new q(a),r.load()):e==="POPUP"&&(r=new R(a),r.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Ie{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=T(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=_e(n),{jwt:a}=Te(i),r=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${r}/open/account/${c}/user/${d}/events`,p=this.domain+h;return Z(p,JSON.stringify(s),a)}}function _e(o){if(!I(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 Te(o){if(!I(o))throw new Error("'options' should be an object");return o}function We(){var i;const o=window[Y]?Y: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[Y]=window[j],n.forEach((s=>s())),window[j]._auto(),window["_"+o]=void 0,delete window["_"+o])}),0)}const x=k("squatch-js"),re=o=>typeof o=="object"&&!Array.isArray(o),de=(o,t)=>{const e=i=>re(t[i])&&o.hasOwnProperty(i)&&re(o[i]),n=Object.getOwnPropertyNames(t).map((i=>({[i]:e(i)?de(o[i],t[i]):t[i]}))).reduce(((i,s)=>({...i,...s})),{});return{...o,...n}};function H(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 ce(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 qe(){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 $e(){const o=window.location.search,e=new URLSearchParams(o).get("_saasquatch")||"";if(e){let n="",i="",s="";try{n=JSON.parse(H(e))}catch(a){x("Unable to decode params",a);return}try{i=JSON.parse(H(O.get("_saasquatch"))),x("existing cookie",i)}catch(a){x("Unable to retrieve cookie",a)}try{const a=qe();if(x("domain retrieved:",a),i){const r=de(i,n);s=ce(JSON.stringify(r)),x("cookie to store:",r)}else s=ce(JSON.stringify(n)),x("cookie to store:",n);O.set("_saasquatch",s,{expires:365,secure:!1,sameSite:"Lax",domain:a,path:"/"})}catch(a){x("Unable to set cookie",a)}}}const J=k("squatch-js");function Re(){var p;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){J("No _saasquatchExtra param");return}const n=T({tenantAlias:"UNKNOWN"});if(!n.domain){J("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(H(e))}catch{J("Unable to decode _saasquatchExtra config");return}function s(m){return m.replace(/^https?:\/\//,"")}const a=s(n.domain),r=Object.keys((i==null?void 0:i[a])||{})[0],d=(p=i==null?void 0:i[a])==null?void 0:p[r];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:r}}}const Ue=k("squatch-js:decodeUserJwt");function Pe(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=H(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return Ue(e),null}}const le=k("squatch-js:DeclarativeWidget");class he 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)||A,npmCdn:Q,container:this};if(this.type==="EMBED")return new q(i);{const a=this.firstChild?null:void 0;return new R(i,a)}}));l(this,"setErrorWidget",(e=>{var i;const n={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((i=this.config)==null?void 0:i.domain)||A,npmCdn:Q,container:this};if(this.type==="EMBED")return new q(n);{const s=this.firstChild?null:void 0;return new R(n,s)}}));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=K(),this.token=W(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new D({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||A}),this.analyticsApi=new se({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||A})}getWidgetType(e){return e&&(e.includes("websiteReferralWidget")||e.includes("friendWidget"))?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),le("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=Pe(this.token);return e?(le("Rendering as a Verified widget"),await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token}),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)):this.setErrorWidget(Error("No user object in token."))}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((()=>ze)),i=n({height:"100%",type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const a=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const d=a.getElementById("#squatchModal");d&&(d.innerHTML="",d.appendChild(s))}else a.innerHTML="",a.appendChild(s);await this.renderWidget();const r=a.getElementById("loading-skeleton");r&&r.remove(),this.getAttribute("open")!==null&&this.open()}}class te extends he{constructor(){super(),this.type="EMBED",this.loaded=!1}}class ne extends he{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",(t=>{t.stopPropagation(),this.open()}))}}class Se extends te{}class Me extends ne{}class Le extends te{}class Oe extends ne{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Se),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",Le),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",Me),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Oe);function je(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const P=k("squatch-js");let B=null,z=null,G=null;function De(){return B||S({}),B}function V(){return z||S({}),z}function Ne(){return G||S({}),G}function Fe(o){var t;return(t=V())==null?void 0:t.render(o)}function He(){var t;const o=Re();if(o){const{squatchConfig:e,widgetConfig:n}=o;return S(e),(t=V())==null?void 0:t.render(n)}}function S(o){const e=T(o);e.tenantAlias.match("^test")||e.debug?C("squatch-js*"):fe(),P("initializing ..."),B=new D(e),z=new U(e),G=new Ie(e),P("Widget API instance",B),P("Widgets instance",z),P("Events API instance",G)}function Je(o){o()}function Be(o){V().autofill(o)}function ue(){$e()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&ue(),(pe=window.squatch)!=null&&pe.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"&&We();const ze=Object.freeze(Object.defineProperty({__proto__:null,getSkeleton:({type:o="verified-access",height:t="500px",skeletonBackgroundColor:e="#e0e0e0",skeletonShimmerColor:n="#f5f5f5"})=>`\n <style>\n * {\n box-sizing: border-box;\n padding: 0;\n margin: 0;\n }\n\n .widget-container {\n background: white;\n width: 100%;\n padding: 40px;\n box-sizing: border-box;\n overflow: hidden; \n }\n\n @keyframes shimmer {\n 0% { background-position: -100% 0; }\n 100% { background-position: 100% 0; }\n }\n\n .skeleton {\n background: ${e};\n background: linear-gradient(\n 90deg,\n ${e} 25%,\n ${n} 50%,\n ${e} 75%\n );\n background-size: 200% 100%;\n animation: shimmer 1.5s infinite linear;\n border-radius: 6px;\n margin-bottom: 12px;\n }\n\n /* Typography Skeletons */\n .sk-title-lg { height: 36px; width: 80%; margin-bottom: 16px; }\n .sk-title-md { height: 28px; width: 30%; margin-bottom: 20px; margin-top: 40px; }\n .sk-text { height: 16px; width: 90%; margin-bottom: 8px; }\n .sk-text-short { width: 40%; }\n .sk-label { height: 14px; width: 25%; margin-bottom: 10px; }\n\n /* Layouts */\n .hero-section {\n display: flex;\n gap: 40px;\n margin-bottom: 40px;\n padding-bottom: 40px;\n flex-direction: row;\n height: 100%;\n /* Removed border-bottom */\n }\n \n .hero-content {\n flex: 1;\n display: flex;\n flex-direction: column;\n justify-content: center;\n }\n \n .hero-image {\n flex: 1;\n height: 300px;\n border-radius: 12px;\n }\n\n /* -- Specific Instant Access Overrides -- */\n .instant-access-layout {\n margin-bottom: 0;\n padding-bottom: 0;\n align-items: center; \n }\n .ia-image {\n height: 400px; \n }\n .ia-center {\n margin-left: auto;\n margin-right: auto;\n }\n .ia-content {\n align-items: center; \n text-align: center;\n }\n .sk-btn-action {\n height: 45px;\n width: 140px;\n border-radius: 6px;\n margin: 24px auto;\n }\n .input-group {\n display: flex;\n gap: 10px;\n width: 100%;\n max-width: 400px;\n }\n .sk-btn-copy {\n height: 50px;\n width: 120px;\n border-radius: 8px;\n }\n /* ------------------------------------- */\n\n .share-section { margin-bottom: 40px; }\n .sk-input { height: 50px; width: 100%; border-radius: 8px; margin-bottom: 16px; }\n \n .social-buttons { display: flex; gap: 12px; }\n .sk-btn-social { flex: 1; height: 50px; border-radius: 8px; }\n\n .stats-section {\n display: flex;\n gap: 24px;\n margin-bottom: 40px;\n padding: 30px 0;\n /* Removed border-top and border-bottom */\n }\n .stat-card { flex: 1; display: flex; flex-direction: column; align-items: center; }\n .stat-divider { padding-left: 24px; }\n .sk-stat-num { height: 48px; width: 120px; margin-bottom: 8px; }\n .sk-stat-label { height: 18px; width: 80px; }\n\n /* Table Styles */\n .table-header { display: flex; gap: 16px; margin-bottom: 16px; }\n .sk-th { height: 16px; }\n .table-row { \n display: flex; \n align-items: center; \n gap: 16px; \n padding: 16px 0; \n /* Removed border-bottom */\n }\n \n .col-user { flex: 2; }\n .col-status { flex: 1; }\n .col-reward { flex: 2; }\n .col-date { flex: 1; }\n\n .sk-badge { height: 28px; width: 90px; border-radius: 14px; }\n .sk-reward-block { height: 36px; width: 100%; border-radius: 6px; }\n\n .pagination { display: flex; justify-content: flex-end; gap: 8px; margin-top: 24px; }\n .sk-btn-page { height: 36px; width: 64px; border-radius: 6px; margin-bottom: 0; }\n\n @media (max-width: 768px) {\n body { padding: 20px; }\n .widget-container { padding: 24px; }\n\n .hero-section { flex-direction: column-reverse; gap: 24px; }\n .instant-access-layout { flex-direction: column; }\n \n .hero-image { height: 220px; width: 100%; }\n .sk-title-lg { width: 100%; }\n\n .col-date { display: none; }\n }\n </style>\n\n <div class="widget-container">\n ${o==="verified-access"?`\n <div class="hero-section">\n <div class="hero-content">\n <div class="skeleton sk-title-lg"></div>\n <div class="skeleton sk-text"></div>\n <div class="skeleton sk-text sk-text-short"></div>\n </div>\n <div class="skeleton hero-image"></div>\n </div>\n\n <div class="share-section">\n <div class="skeleton sk-label"></div>\n <div class="skeleton sk-input"></div>\n <div class="social-buttons">\n <div class="skeleton sk-btn-social"></div>\n <div class="skeleton sk-btn-social"></div>\n <div class="skeleton sk-btn-social"></div>\n <div class="skeleton sk-btn-social"></div>\n </div>\n </div>\n\n <div class="skeleton sk-title-md" style="margin-top: 0; width: 30%; margin-left: auto; margin-right: auto"></div>\n <div class="skeleton sk-text" style="width: 60%; margin-left: auto; margin-right: auto"></div>\n\n <div class="stats-section">\n <div class="stat-card">\n <div class="skeleton sk-stat-num"></div>\n <div class="skeleton sk-stat-label"></div>\n </div>\n <div class="stat-card stat-divider">\n <div class="skeleton sk-stat-num"></div>\n <div class="skeleton sk-stat-label"></div>\n </div>\n </div>\n\n <div class="skeleton sk-title-md"></div>\n\n <div class="table-header">\n <div class="skeleton sk-th col-user"></div>\n <div class="skeleton sk-th col-status"></div>\n <div class="skeleton sk-th col-reward"></div>\n <div class="skeleton sk-th col-date"></div>\n </div>\n\n <div class="table-row">\n <div class="col-user"><div class="skeleton sk-text" style="width: 70%; margin: 0"></div></div>\n <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>\n <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>\n <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>\n </div>\n \n <div class="table-row">\n <div class="col-user"><div class="skeleton sk-text" style="width: 60%; margin: 0"></div></div>\n <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>\n <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>\n <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>\n </div>\n\n <div class="table-row">\n <div class="col-user"><div class="skeleton sk-text" style="width: 75%; margin: 0"></div></div>\n <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>\n <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>\n <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>\n </div>\n\n <div class="pagination">\n <div class="skeleton sk-btn-page"></div>\n <div class="skeleton sk-btn-page"></div>\n </div>\n `:`\n <div class="hero-section instant-access-layout">\n <div class="skeleton hero-image ia-image"></div>\n \n <div class="hero-content ia-content">\n <div class="skeleton sk-title-lg ia-center"></div>\n <div class="skeleton sk-text ia-center"></div>\n \n <div class="skeleton sk-btn-action"></div>\n\n <div class="skeleton sk-label"></div>\n <div class="input-group">\n <div class="skeleton sk-input"></div>\n <div class="skeleton sk-btn-copy"></div>\n </div>\n\n <div class="skeleton sk-text-short ia-center" style="margin-top: 20px; width: 30%"></div>\n <div class="skeleton sk-text-short ia-center" style="width: 20%"></div>\n </div>\n </div>\n `}\n </div>\n `},Symbol.toStringTag,{value:"Module"}));u.DeclarativeEmbedWidget=te,u.DeclarativePopupWidget=ne,u.EmbedWidget=q,u.PopupWidget=R,u.WidgetApi=D,u.Widgets=U,u._auto=He,u.api=De,u.autofill=Be,u.events=Ne,u.help=je,u.init=S,u.pushCookie=ue,u.ready=Je,u.widget=Fe,u.widgets=V,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight logger with namespace filtering, replacing the `debug` npm package.
|
|
3
|
+
*
|
|
4
|
+
* Supports glob-style enable patterns (e.g. "squatch-js*" enables all namespaces
|
|
5
|
+
* starting with "squatch-js"). When disabled, logger calls are effectively no-ops.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Enable logging for namespaces matching a glob pattern.
|
|
9
|
+
* Supports `*` as a wildcard (e.g. "squatch-js*" or "squatch-js:widget").
|
|
10
|
+
*/
|
|
11
|
+
export declare function enableDebug(pattern: string): void;
|
|
12
|
+
/**
|
|
13
|
+
* Disable all logging.
|
|
14
|
+
*/
|
|
15
|
+
export declare function disableDebug(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Create a namespaced logger function.
|
|
18
|
+
* Returns a function that logs to console when the namespace is enabled.
|
|
19
|
+
*/
|
|
20
|
+
export declare function debug(namespace: string): (...args: any[]) => void;
|
|
@@ -16,9 +16,9 @@ export default class PopupWidget extends Widget {
|
|
|
16
16
|
id: string;
|
|
17
17
|
constructor(params: Params, trigger?: string | null);
|
|
18
18
|
_initialiseCTA(): void;
|
|
19
|
-
_createPopupDialog(): HTMLDialogElement;
|
|
19
|
+
_createPopupDialog(brandingConfig?: any): HTMLDialogElement;
|
|
20
20
|
load(): Promise<void>;
|
|
21
|
-
protected _setupResizeHandler(frame: HTMLIFrameElement): Promise<void>;
|
|
21
|
+
protected _setupResizeHandler(frame: HTMLIFrameElement, initialHeight?: string): Promise<void>;
|
|
22
22
|
open(): void;
|
|
23
23
|
close(): void;
|
|
24
24
|
protected _clickedOutside({ target }: {
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
export type WidgetType = "instant-access" | "verified-access";
|
|
1
2
|
interface SkeletonProps {
|
|
3
|
+
type?: WidgetType;
|
|
2
4
|
height?: string | number;
|
|
3
5
|
skeletonBackgroundColor?: string;
|
|
4
6
|
skeletonShimmerColor?: string;
|
|
5
|
-
borderColor?: string;
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
8
9
|
* Returns the complete HTML string (including <style>) for the skeleton.
|
|
9
10
|
* Values are injected directly into the CSS string.
|
|
10
11
|
*/
|
|
11
|
-
export declare const getSkeleton: ({ height, skeletonBackgroundColor, skeletonShimmerColor,
|
|
12
|
+
export declare const getSkeleton: ({ type, height, skeletonBackgroundColor, skeletonShimmerColor, }: SkeletonProps) => string;
|
|
12
13
|
export {};
|
|
@@ -66,6 +66,7 @@ export default abstract class DeclarativeWidget extends HTMLElement {
|
|
|
66
66
|
loaded: boolean;
|
|
67
67
|
constructor();
|
|
68
68
|
private _setupApis;
|
|
69
|
+
protected getWidgetType(widgetType?: string): "instant-access" | "verified-access";
|
|
69
70
|
private renderPasswordlessVariant;
|
|
70
71
|
private renderUserUpsertVariant;
|
|
71
72
|
private _setWidget;
|
|
@@ -97,4 +98,7 @@ export default abstract class DeclarativeWidget extends HTMLElement {
|
|
|
97
98
|
reload: () => Promise<void>;
|
|
98
99
|
show: () => void;
|
|
99
100
|
hide: () => void;
|
|
101
|
+
static get observedAttributes(): string[];
|
|
102
|
+
attributeChangedCallback(attr: string, oldVal: string, newVal: string): void;
|
|
103
|
+
connectedCallback(): Promise<void>;
|
|
100
104
|
}
|
|
@@ -12,9 +12,6 @@ import { default as DeclarativeWidget } from './DeclarativeWidget';
|
|
|
12
12
|
*/
|
|
13
13
|
export declare class DeclarativeEmbedWidget extends DeclarativeWidget {
|
|
14
14
|
constructor();
|
|
15
|
-
static get observedAttributes(): string[];
|
|
16
|
-
attributeChangedCallback(attr: string, oldVal: string, newVal: string): void;
|
|
17
|
-
connectedCallback(): Promise<void>;
|
|
18
15
|
}
|
|
19
16
|
/**
|
|
20
17
|
* Base class for `squatch-popup` web-component
|
|
@@ -29,7 +26,4 @@ export declare class DeclarativeEmbedWidget extends DeclarativeWidget {
|
|
|
29
26
|
*/
|
|
30
27
|
export declare class DeclarativePopupWidget extends DeclarativeWidget {
|
|
31
28
|
constructor();
|
|
32
|
-
static get observedAttributes(): string[];
|
|
33
|
-
attributeChangedCallback(attr: string, oldVal: string, newVal: string): void;
|
|
34
|
-
connectedCallback(): Promise<void>;
|
|
35
29
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saasquatch/squatch-js",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.8.
|
|
4
|
+
"version": "2.8.3-0",
|
|
5
5
|
"description": "The official Referral SaaSquatch Javascript Web/Browser SDK https://docs.referralsaasquatch.com/developer/squatchjs/",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "ReferralSaaSquatch.com, Inc.",
|
|
@@ -111,7 +111,6 @@
|
|
|
111
111
|
},
|
|
112
112
|
"prettier": {},
|
|
113
113
|
"dependencies": {
|
|
114
|
-
"debug": "^3.2.6",
|
|
115
114
|
"js-cookie": "^3.0.5"
|
|
116
115
|
},
|
|
117
116
|
"browserslist": "> 0.25%, not dead",
|