@saasquatch/squatch-js 2.7.0-2 → 2.7.0-4

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.
Files changed (47) hide show
  1. package/{dist copy/api/AnalyticsApi.d.ts → dist/api/AnalyticsApi.d.ts} +1 -1
  2. package/{dist copy/api/EventsApi.d.ts → dist/api/EventsApi.d.ts} +1 -1
  3. package/{dist copy/api/WidgetApi.d.ts → dist/api/WidgetApi.d.ts} +1 -1
  4. package/{dist copy/async.d.ts → dist/async.d.ts} +1 -1
  5. package/dist/squatch.cjs.js +2120 -7
  6. package/dist/squatch.cjs.js.map +1 -0
  7. package/{dist copy/squatch.d.ts → dist/squatch.d.ts} +9 -9
  8. package/dist/squatch.esm.js +2161 -0
  9. package/dist/squatch.esm.js.map +1 -0
  10. package/dist/squatch.js +2126 -9
  11. package/dist/squatch.js.map +1 -0
  12. package/dist/squatch.min.js +6 -0
  13. package/{dist copy/types.d.ts → dist/types.d.ts} +1 -1
  14. package/{dist copy/utils/decodeUserJwt.d.ts → dist/utils/decodeUserJwt.d.ts} +1 -1
  15. package/{dist copy/utils/io.d.ts → dist/utils/io.d.ts} +1 -1
  16. package/{dist copy/utils/utmUtils.d.ts → dist/utils/utmUtils.d.ts} +1 -1
  17. package/{dist copy/utils/validate.d.ts → dist/utils/validate.d.ts} +1 -1
  18. package/{dist copy/widgets/EmbedWidget.d.ts → dist/widgets/EmbedWidget.d.ts} +1 -1
  19. package/{dist copy/widgets/PopupWidget.d.ts → dist/widgets/PopupWidget.d.ts} +1 -1
  20. package/{dist copy/widgets/Widget.d.ts → dist/widgets/Widget.d.ts} +3 -3
  21. package/{dist copy/widgets/Widgets.d.ts → dist/widgets/Widgets.d.ts} +2 -2
  22. package/{dist copy/widgets/declarative/DeclarativeWidget.d.ts → dist/widgets/declarative/DeclarativeWidget.d.ts} +5 -5
  23. package/{dist copy/widgets/declarative/DeclarativeWidgets.d.ts → dist/widgets/declarative/DeclarativeWidgets.d.ts} +1 -1
  24. package/package.json +9 -8
  25. package/vite.config.ts +19 -4
  26. package/coverage/clover.xml +0 -917
  27. package/coverage/coverage-final.json +0 -21
  28. package/coverage/lcov-report/base.css +0 -224
  29. package/coverage/lcov-report/block-navigation.js +0 -87
  30. package/coverage/lcov-report/favicon.png +0 -0
  31. package/coverage/lcov-report/prettify.css +0 -1
  32. package/coverage/lcov-report/prettify.js +0 -2
  33. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  34. package/coverage/lcov-report/sorter.js +0 -196
  35. package/coverage/lcov.info +0 -1669
  36. package/dist/squatch.es.js +0 -1622
  37. package/dist copy/squatch.cjs.js +0 -48
  38. package/dist copy/squatch.es.js +0 -1622
  39. package/dist copy/squatch.esm.js +0 -2317
  40. package/dist copy/squatch.esm.js.map +0 -1
  41. package/dist copy/squatch.js +0 -2337
  42. package/dist copy/squatch.js.map +0 -1
  43. /package/{dist copy → dist}/api/graphql.d.ts +0 -0
  44. /package/{dist copy → dist}/docs.d.ts +0 -0
  45. /package/{dist copy → dist}/globals.d.ts +0 -0
  46. /package/{dist copy → dist}/utils/cookieUtils.d.ts +0 -0
  47. /package/{dist copy → dist}/utils/domready.d.ts +0 -0
package/dist/squatch.js CHANGED
@@ -1,4 +1,612 @@
1
- (function(p,w){typeof exports=="object"&&typeof module<"u"?w(exports):(p=typeof globalThis<"u"?globalThis:p||self,w(p.squatch={}))})(this,function(p){"use strict";var rt=Object.defineProperty;var st=(p,w,A)=>w in p?rt(p,w,{enumerable:!0,configurable:!0,writable:!0,value:A}):p[w]=A;var f=(p,w,A)=>st(p,typeof w!="symbol"?w+"":w,A);var Ce;function w(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var A={exports:{}},X,se;function be(){if(se)return X;se=1;var i=1e3,n=i*60,t=n*60,e=t*24,o=e*7,r=e*365.25;X=function(s,c){c=c||{};var l=typeof s;if(l==="string"&&s.length>0)return a(s);if(l==="number"&&isFinite(s))return c.long?u(s):d(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};function a(s){if(s=String(s),!(s.length>100)){var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(c){var l=parseFloat(c[1]),g=(c[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return l*r;case"weeks":case"week":case"w":return l*o;case"days":case"day":case"d":return l*e;case"hours":case"hour":case"hrs":case"hr":case"h":return l*t;case"minutes":case"minute":case"mins":case"min":case"m":return l*n;case"seconds":case"second":case"secs":case"sec":case"s":return l*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}}}function d(s){var c=Math.abs(s);return c>=e?Math.round(s/e)+"d":c>=t?Math.round(s/t)+"h":c>=n?Math.round(s/n)+"m":c>=i?Math.round(s/i)+"s":s+"ms"}function u(s){var c=Math.abs(s);return c>=e?h(s,c,e,"day"):c>=t?h(s,c,t,"hour"):c>=n?h(s,c,n,"minute"):c>=i?h(s,c,i,"second"):s+" ms"}function h(s,c,l,g){var m=c>=l*1.5;return Math.round(s/l)+" "+g+(m?"s":"")}return X}var Q,ae;function ve(){if(ae)return Q;ae=1;function i(n){e.debug=e,e.default=e,e.coerce=h,e.disable=d,e.enable=a,e.enabled=u,e.humanize=be(),Object.keys(n).forEach(function(s){e[s]=n[s]}),e.instances=[],e.names=[],e.skips=[],e.formatters={};function t(s){for(var c=0,l=0;l<s.length;l++)c=(c<<5)-c+s.charCodeAt(l),c|=0;return e.colors[Math.abs(c)%e.colors.length]}e.selectColor=t;function e(s){var c;function l(){if(l.enabled){for(var g=arguments.length,m=new Array(g),I=0;I<g;I++)m[I]=arguments[I];var b=l,v=Number(new Date),tt=v-(c||v);b.diff=tt,b.prev=c,b.curr=v,c=v,m[0]=e.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");var G=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,function(V,ot){if(V==="%%")return V;G++;var Ee=e.formatters[ot];if(typeof Ee=="function"){var it=m[G];V=Ee.call(b,it),m.splice(G,1),G--}return V}),e.formatArgs.call(b,m);var nt=b.log||e.log;nt.apply(b,m)}}return l.namespace=s,l.enabled=e.enabled(s),l.useColors=e.useColors(),l.color=t(s),l.destroy=o,l.extend=r,typeof e.init=="function"&&e.init(l),e.instances.push(l),l}function o(){var s=e.instances.indexOf(this);return s!==-1?(e.instances.splice(s,1),!0):!1}function r(s,c){return e(this.namespace+(typeof c>"u"?":":c)+s)}function a(s){e.save(s),e.names=[],e.skips=[];var c,l=(typeof s=="string"?s:"").split(/[\s,]+/),g=l.length;for(c=0;c<g;c++)l[c]&&(s=l[c].replace(/\*/g,".*?"),s[0]==="-"?e.skips.push(new RegExp("^"+s.substr(1)+"$")):e.names.push(new RegExp("^"+s+"$")));for(c=0;c<e.instances.length;c++){var m=e.instances[c];m.enabled=e.enabled(m.namespace)}}function d(){e.enable("")}function u(s){if(s[s.length-1]==="*")return!0;var c,l;for(c=0,l=e.skips.length;c<l;c++)if(e.skips[c].test(s))return!1;for(c=0,l=e.names.length;c<l;c++)if(e.names[c].test(s))return!0;return!1}function h(s){return s instanceof Error?s.stack||s.message:s}return e.enable(e.load()),e}return Q=i,Q}var ce;function Ae(){return ce||(ce=1,function(i,n){function t(s){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?t=function(l){return typeof l}:t=function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},t(s)}n.log=r,n.formatArgs=o,n.save=a,n.load=d,n.useColors=e,n.storage=u(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function e(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(s){if(s[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+s[0]+(this.useColors?"%c ":" ")+"+"+i.exports.humanize(this.diff),!!this.useColors){var c="color: "+this.color;s.splice(1,0,c,"color: inherit");var l=0,g=0;s[0].replace(/%[a-zA-Z%]/g,function(m){m!=="%%"&&(l++,m==="%c"&&(g=l))}),s.splice(g,0,c)}}function r(){var s;return(typeof console>"u"?"undefined":t(console))==="object"&&console.log&&(s=console).log.apply(s,arguments)}function a(s){try{s?n.storage.setItem("debug",s):n.storage.removeItem("debug")}catch{}}function d(){var s;try{s=n.storage.getItem("debug")}catch{}return!s&&typeof process<"u"&&"env"in process&&(s=process.env.DEBUG),s}function u(){try{return localStorage}catch{}}i.exports=ve()(n);var h=i.exports.formatters;h.j=function(s){try{return JSON.stringify(s)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}(A,A.exports)),A.exports}var y=Ae();const Ie=w(y);/*! js-cookie v3.0.5 | MIT */function $(i){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var e in t)i[e]=t[e]}return i}var _e={read:function(i){return i[0]==='"'&&(i=i.slice(1,-1)),i.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(i){return encodeURIComponent(i).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Y(i,n){function t(o,r,a){if(!(typeof document>"u")){a=$({},n,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var d="";for(var u in a)a[u]&&(d+="; "+u,a[u]!==!0&&(d+="="+a[u].split(";")[0]));return document.cookie=o+"="+i.write(r,o)+d}}function e(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var r=document.cookie?document.cookie.split("; "):[],a={},d=0;d<r.length;d++){var u=r[d].split("="),h=u.slice(1).join("=");try{var s=decodeURIComponent(u[0]);if(a[s]=i.read(h,s),o===s)break}catch{}}return o?a[o]:a}}return Object.create({set:t,get:e,remove:function(o,r){t(o,"",$({},r,{expires:-1}))},withAttributes:function(o){return Y(this.converter,$({},this.attributes,o))},withConverter:function(o){return Y($({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(i)}})}var W=Y(_e,{path:"/"});const F="https://app.referralsaasquatch.com",Z="https://fast.ssqt.io/npm",O="squatch",K="impact";function L(i){if(typeof i!="object")throw new Error("config must be an object");const n=window.squatchTenant,t=ee(),e={tenantAlias:(i==null?void 0:i.tenantAlias)||n,domain:(i==null?void 0:i.domain)||(t==null?void 0:t.domain),npmCdn:(i==null?void 0:i.npmCdn)||(t==null?void 0:t.npmCdn),debug:(i==null?void 0:i.debug)||(t==null?void 0:t.debug)};if(typeof e.tenantAlias!="string")throw new Error("tenantAlias not provided");const o=e.tenantAlias,r=typeof e.domain=="string"&&e.domain||F,a=typeof e.debug=="boolean"&&e.debug||!1,d=typeof e.npmCdn=="string"&&e.npmCdn||Z;return{tenantAlias:o,domain:r,debug:a,npmCdn:d}}function k(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function Fe(i){if(i&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(i))return i}function de(i){if(!k(i))throw new Error("Widget properties must be an object");if(!(i!=null&&i.user))throw new Error("Required properties missing.");return i}function le(i){if(!k(i))throw new Error("Widget properties must be an object");return i}function R(){return window.impactToken||window.squatchToken}function ee(){return window.impactConfig||window.squatchConfig}y.debug("squatch-js:io");async function ke(i,n,t,e){const o=e||R(),r={Accept:"application/json","Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const a=await fetch(i,{method:"POST",body:JSON.stringify({query:n,variables:t}),headers:r});if(!a.ok)throw new Error(await a.text());return await a.json()}catch(a){throw a}}async function qe(i,n=""){const t={Accept:"application/json","Content-Type":"application/json"},e=n||R();e&&(t["X-SaaSquatch-User-Token"]=e);try{const o=await fetch(i,{method:"GET",credentials:"include",headers:t}),r=await o.text();if(!o.ok)throw new Error(r);return r&&JSON.parse(r)}catch(o){throw o}}async function te(i,n,t){const e={Accept:"application/json","Content-Type":"application/json"},o=t||R();o&&(e["X-SaaSquatch-User-Token"]=o);try{const r=await fetch(i,{method:"POST",body:n,headers:e}),a=await r.text();if(!r.ok)throw new Error(a);return a&&JSON.parse(a)}catch(r){throw r}}async function Re(i,n,t){const e={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},o=t||R();o&&(e["X-SaaSquatch-User-Token"]=o);try{const r=await fetch(i,{headers:e,method:"PUT",credentials:"include",body:n}),a=await r.text();if(!r.ok)throw new Error(a);return a&&JSON.parse(a)}catch(r){throw r}}const Te=`
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : false ? false(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.squatch = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
8
+ var _a;
9
+ function getDefaultExportFromCjs(x) {
10
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
11
+ }
12
+ var browser = { exports: {} };
13
+ var ms;
14
+ var hasRequiredMs;
15
+ function requireMs() {
16
+ if (hasRequiredMs) return ms;
17
+ hasRequiredMs = 1;
18
+ var s = 1e3;
19
+ var m = s * 60;
20
+ var h = m * 60;
21
+ var d = h * 24;
22
+ var w = d * 7;
23
+ var y = d * 365.25;
24
+ ms = function(val, options) {
25
+ options = options || {};
26
+ var type = typeof val;
27
+ if (type === "string" && val.length > 0) {
28
+ return parse(val);
29
+ } else if (type === "number" && isFinite(val)) {
30
+ return options.long ? fmtLong(val) : fmtShort(val);
31
+ }
32
+ throw new Error(
33
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
34
+ );
35
+ };
36
+ function parse(str) {
37
+ str = String(str);
38
+ if (str.length > 100) {
39
+ return;
40
+ }
41
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
42
+ str
43
+ );
44
+ if (!match) {
45
+ return;
46
+ }
47
+ var n = parseFloat(match[1]);
48
+ var type = (match[2] || "ms").toLowerCase();
49
+ switch (type) {
50
+ case "years":
51
+ case "year":
52
+ case "yrs":
53
+ case "yr":
54
+ case "y":
55
+ return n * y;
56
+ case "weeks":
57
+ case "week":
58
+ case "w":
59
+ return n * w;
60
+ case "days":
61
+ case "day":
62
+ case "d":
63
+ return n * d;
64
+ case "hours":
65
+ case "hour":
66
+ case "hrs":
67
+ case "hr":
68
+ case "h":
69
+ return n * h;
70
+ case "minutes":
71
+ case "minute":
72
+ case "mins":
73
+ case "min":
74
+ case "m":
75
+ return n * m;
76
+ case "seconds":
77
+ case "second":
78
+ case "secs":
79
+ case "sec":
80
+ case "s":
81
+ return n * s;
82
+ case "milliseconds":
83
+ case "millisecond":
84
+ case "msecs":
85
+ case "msec":
86
+ case "ms":
87
+ return n;
88
+ default:
89
+ return void 0;
90
+ }
91
+ }
92
+ function fmtShort(ms2) {
93
+ var msAbs = Math.abs(ms2);
94
+ if (msAbs >= d) {
95
+ return Math.round(ms2 / d) + "d";
96
+ }
97
+ if (msAbs >= h) {
98
+ return Math.round(ms2 / h) + "h";
99
+ }
100
+ if (msAbs >= m) {
101
+ return Math.round(ms2 / m) + "m";
102
+ }
103
+ if (msAbs >= s) {
104
+ return Math.round(ms2 / s) + "s";
105
+ }
106
+ return ms2 + "ms";
107
+ }
108
+ function fmtLong(ms2) {
109
+ var msAbs = Math.abs(ms2);
110
+ if (msAbs >= d) {
111
+ return plural(ms2, msAbs, d, "day");
112
+ }
113
+ if (msAbs >= h) {
114
+ return plural(ms2, msAbs, h, "hour");
115
+ }
116
+ if (msAbs >= m) {
117
+ return plural(ms2, msAbs, m, "minute");
118
+ }
119
+ if (msAbs >= s) {
120
+ return plural(ms2, msAbs, s, "second");
121
+ }
122
+ return ms2 + " ms";
123
+ }
124
+ function plural(ms2, msAbs, n, name) {
125
+ var isPlural = msAbs >= n * 1.5;
126
+ return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : "");
127
+ }
128
+ return ms;
129
+ }
130
+ var common;
131
+ var hasRequiredCommon;
132
+ function requireCommon() {
133
+ if (hasRequiredCommon) return common;
134
+ hasRequiredCommon = 1;
135
+ function setup(env) {
136
+ createDebug.debug = createDebug;
137
+ createDebug.default = createDebug;
138
+ createDebug.coerce = coerce;
139
+ createDebug.disable = disable;
140
+ createDebug.enable = enable;
141
+ createDebug.enabled = enabled;
142
+ createDebug.humanize = requireMs();
143
+ Object.keys(env).forEach(function(key) {
144
+ createDebug[key] = env[key];
145
+ });
146
+ createDebug.instances = [];
147
+ createDebug.names = [];
148
+ createDebug.skips = [];
149
+ createDebug.formatters = {};
150
+ function selectColor(namespace) {
151
+ var hash = 0;
152
+ for (var i = 0; i < namespace.length; i++) {
153
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
154
+ hash |= 0;
155
+ }
156
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
157
+ }
158
+ createDebug.selectColor = selectColor;
159
+ function createDebug(namespace) {
160
+ var prevTime;
161
+ function debug2() {
162
+ if (!debug2.enabled) {
163
+ return;
164
+ }
165
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
166
+ args[_key] = arguments[_key];
167
+ }
168
+ var self2 = debug2;
169
+ var curr = Number(/* @__PURE__ */ new Date());
170
+ var ms2 = curr - (prevTime || curr);
171
+ self2.diff = ms2;
172
+ self2.prev = prevTime;
173
+ self2.curr = curr;
174
+ prevTime = curr;
175
+ args[0] = createDebug.coerce(args[0]);
176
+ if (typeof args[0] !== "string") {
177
+ args.unshift("%O");
178
+ }
179
+ var index = 0;
180
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
181
+ if (match === "%%") {
182
+ return match;
183
+ }
184
+ index++;
185
+ var formatter = createDebug.formatters[format];
186
+ if (typeof formatter === "function") {
187
+ var val = args[index];
188
+ match = formatter.call(self2, val);
189
+ args.splice(index, 1);
190
+ index--;
191
+ }
192
+ return match;
193
+ });
194
+ createDebug.formatArgs.call(self2, args);
195
+ var logFn = self2.log || createDebug.log;
196
+ logFn.apply(self2, args);
197
+ }
198
+ debug2.namespace = namespace;
199
+ debug2.enabled = createDebug.enabled(namespace);
200
+ debug2.useColors = createDebug.useColors();
201
+ debug2.color = selectColor(namespace);
202
+ debug2.destroy = destroy;
203
+ debug2.extend = extend;
204
+ if (typeof createDebug.init === "function") {
205
+ createDebug.init(debug2);
206
+ }
207
+ createDebug.instances.push(debug2);
208
+ return debug2;
209
+ }
210
+ function destroy() {
211
+ var index = createDebug.instances.indexOf(this);
212
+ if (index !== -1) {
213
+ createDebug.instances.splice(index, 1);
214
+ return true;
215
+ }
216
+ return false;
217
+ }
218
+ function extend(namespace, delimiter) {
219
+ return createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
220
+ }
221
+ function enable(namespaces) {
222
+ createDebug.save(namespaces);
223
+ createDebug.names = [];
224
+ createDebug.skips = [];
225
+ var i;
226
+ var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
227
+ var len = split.length;
228
+ for (i = 0; i < len; i++) {
229
+ if (!split[i]) {
230
+ continue;
231
+ }
232
+ namespaces = split[i].replace(/\*/g, ".*?");
233
+ if (namespaces[0] === "-") {
234
+ createDebug.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
235
+ } else {
236
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
237
+ }
238
+ }
239
+ for (i = 0; i < createDebug.instances.length; i++) {
240
+ var instance = createDebug.instances[i];
241
+ instance.enabled = createDebug.enabled(instance.namespace);
242
+ }
243
+ }
244
+ function disable() {
245
+ createDebug.enable("");
246
+ }
247
+ function enabled(name) {
248
+ if (name[name.length - 1] === "*") {
249
+ return true;
250
+ }
251
+ var i;
252
+ var len;
253
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
254
+ if (createDebug.skips[i].test(name)) {
255
+ return false;
256
+ }
257
+ }
258
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
259
+ if (createDebug.names[i].test(name)) {
260
+ return true;
261
+ }
262
+ }
263
+ return false;
264
+ }
265
+ function coerce(val) {
266
+ if (val instanceof Error) {
267
+ return val.stack || val.message;
268
+ }
269
+ return val;
270
+ }
271
+ createDebug.enable(createDebug.load());
272
+ return createDebug;
273
+ }
274
+ common = setup;
275
+ return common;
276
+ }
277
+ var hasRequiredBrowser;
278
+ function requireBrowser() {
279
+ if (hasRequiredBrowser) return browser.exports;
280
+ hasRequiredBrowser = 1;
281
+ (function(module2, exports3) {
282
+ function _typeof(obj) {
283
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
284
+ _typeof = function _typeof2(obj2) {
285
+ return typeof obj2;
286
+ };
287
+ } else {
288
+ _typeof = function _typeof2(obj2) {
289
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
290
+ };
291
+ }
292
+ return _typeof(obj);
293
+ }
294
+ exports3.log = log;
295
+ exports3.formatArgs = formatArgs;
296
+ exports3.save = save;
297
+ exports3.load = load;
298
+ exports3.useColors = useColors;
299
+ exports3.storage = localstorage();
300
+ exports3.colors = ["#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33"];
301
+ function useColors() {
302
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
303
+ return true;
304
+ }
305
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
306
+ return false;
307
+ }
308
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
309
+ typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
310
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
311
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
312
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
313
+ }
314
+ function formatArgs(args) {
315
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
316
+ if (!this.useColors) {
317
+ return;
318
+ }
319
+ var c = "color: " + this.color;
320
+ args.splice(1, 0, c, "color: inherit");
321
+ var index = 0;
322
+ var lastC = 0;
323
+ args[0].replace(/%[a-zA-Z%]/g, function(match) {
324
+ if (match === "%%") {
325
+ return;
326
+ }
327
+ index++;
328
+ if (match === "%c") {
329
+ lastC = index;
330
+ }
331
+ });
332
+ args.splice(lastC, 0, c);
333
+ }
334
+ function log() {
335
+ var _console;
336
+ return (typeof console === "undefined" ? "undefined" : _typeof(console)) === "object" && console.log && (_console = console).log.apply(_console, arguments);
337
+ }
338
+ function save(namespaces) {
339
+ try {
340
+ if (namespaces) {
341
+ exports3.storage.setItem("debug", namespaces);
342
+ } else {
343
+ exports3.storage.removeItem("debug");
344
+ }
345
+ } catch (error) {
346
+ }
347
+ }
348
+ function load() {
349
+ var r;
350
+ try {
351
+ r = exports3.storage.getItem("debug");
352
+ } catch (error) {
353
+ }
354
+ if (!r && typeof process !== "undefined" && "env" in process) {
355
+ r = process.env.DEBUG;
356
+ }
357
+ return r;
358
+ }
359
+ function localstorage() {
360
+ try {
361
+ return localStorage;
362
+ } catch (error) {
363
+ }
364
+ }
365
+ module2.exports = requireCommon()(exports3);
366
+ var formatters = module2.exports.formatters;
367
+ formatters.j = function(v) {
368
+ try {
369
+ return JSON.stringify(v);
370
+ } catch (error) {
371
+ return "[UnexpectedJSONParseError]: " + error.message;
372
+ }
373
+ };
374
+ })(browser, browser.exports);
375
+ return browser.exports;
376
+ }
377
+ var browserExports = requireBrowser();
378
+ const debug = /* @__PURE__ */ getDefaultExportFromCjs(browserExports);
379
+ /*! js-cookie v3.0.5 | MIT */
380
+ function assign(target) {
381
+ for (var i = 1; i < arguments.length; i++) {
382
+ var source = arguments[i];
383
+ for (var key in source) {
384
+ target[key] = source[key];
385
+ }
386
+ }
387
+ return target;
388
+ }
389
+ var defaultConverter = {
390
+ read: function(value) {
391
+ if (value[0] === '"') {
392
+ value = value.slice(1, -1);
393
+ }
394
+ return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
395
+ },
396
+ write: function(value) {
397
+ return encodeURIComponent(value).replace(
398
+ /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
399
+ decodeURIComponent
400
+ );
401
+ }
402
+ };
403
+ function init$1(converter, defaultAttributes) {
404
+ function set(name, value, attributes) {
405
+ if (typeof document === "undefined") {
406
+ return;
407
+ }
408
+ attributes = assign({}, defaultAttributes, attributes);
409
+ if (typeof attributes.expires === "number") {
410
+ attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
411
+ }
412
+ if (attributes.expires) {
413
+ attributes.expires = attributes.expires.toUTCString();
414
+ }
415
+ name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
416
+ var stringifiedAttributes = "";
417
+ for (var attributeName in attributes) {
418
+ if (!attributes[attributeName]) {
419
+ continue;
420
+ }
421
+ stringifiedAttributes += "; " + attributeName;
422
+ if (attributes[attributeName] === true) {
423
+ continue;
424
+ }
425
+ stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
426
+ }
427
+ return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
428
+ }
429
+ function get(name) {
430
+ if (typeof document === "undefined" || arguments.length && !name) {
431
+ return;
432
+ }
433
+ var cookies = document.cookie ? document.cookie.split("; ") : [];
434
+ var jar = {};
435
+ for (var i = 0; i < cookies.length; i++) {
436
+ var parts = cookies[i].split("=");
437
+ var value = parts.slice(1).join("=");
438
+ try {
439
+ var found = decodeURIComponent(parts[0]);
440
+ jar[found] = converter.read(value, found);
441
+ if (name === found) {
442
+ break;
443
+ }
444
+ } catch (e) {
445
+ }
446
+ }
447
+ return name ? jar[name] : jar;
448
+ }
449
+ return Object.create(
450
+ {
451
+ set,
452
+ get,
453
+ remove: function(name, attributes) {
454
+ set(
455
+ name,
456
+ "",
457
+ assign({}, attributes, {
458
+ expires: -1
459
+ })
460
+ );
461
+ },
462
+ withAttributes: function(attributes) {
463
+ return init$1(this.converter, assign({}, this.attributes, attributes));
464
+ },
465
+ withConverter: function(converter2) {
466
+ return init$1(assign({}, this.converter, converter2), this.attributes);
467
+ }
468
+ },
469
+ {
470
+ attributes: { value: Object.freeze(defaultAttributes) },
471
+ converter: { value: Object.freeze(converter) }
472
+ }
473
+ );
474
+ }
475
+ var api$1 = init$1(defaultConverter, { path: "/" });
476
+ const DEFAULT_DOMAIN = "https://app.referralsaasquatch.com";
477
+ const DEFAULT_NPM_CDN = "https://fast.ssqt.io/npm";
478
+ const DEFAULT_NAMESPACE = "squatch";
479
+ const IMPACT_NAMESPACE = "impact";
480
+ function validateConfig(_raw) {
481
+ if (typeof _raw !== "object") throw new Error("config must be an object");
482
+ const tenant = window.squatchTenant;
483
+ const config = getConfig();
484
+ const raw = {
485
+ tenantAlias: (_raw == null ? void 0 : _raw["tenantAlias"]) || tenant,
486
+ domain: (_raw == null ? void 0 : _raw["domain"]) || (config == null ? void 0 : config.domain),
487
+ npmCdn: (_raw == null ? void 0 : _raw["npmCdn"]) || (config == null ? void 0 : config.npmCdn),
488
+ debug: (_raw == null ? void 0 : _raw["debug"]) || (config == null ? void 0 : config.debug)
489
+ };
490
+ if (typeof raw.tenantAlias !== "string")
491
+ throw new Error("tenantAlias not provided");
492
+ const tenantAlias = raw.tenantAlias;
493
+ const domain = typeof raw.domain === "string" && raw.domain || DEFAULT_DOMAIN;
494
+ const debug2 = typeof raw.debug === "boolean" && raw.debug || false;
495
+ const npmCdn = typeof raw.npmCdn === "string" && raw.npmCdn || DEFAULT_NPM_CDN;
496
+ return {
497
+ tenantAlias,
498
+ domain,
499
+ debug: debug2,
500
+ npmCdn
501
+ };
502
+ }
503
+ function isObject$1(obj) {
504
+ return typeof obj === "object" && !Array.isArray(obj) && obj !== null;
505
+ }
506
+ function validateLocale(locale) {
507
+ if (locale && /^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(locale)) {
508
+ return locale;
509
+ }
510
+ }
511
+ function validateWidgetConfig(raw) {
512
+ if (!isObject$1(raw)) throw new Error("Widget properties must be an object");
513
+ if (!(raw == null ? void 0 : raw["user"])) throw new Error("Required properties missing.");
514
+ return raw;
515
+ }
516
+ function validatePasswordlessConfig(raw) {
517
+ if (!isObject$1(raw)) throw new Error("Widget properties must be an object");
518
+ return raw;
519
+ }
520
+ function getToken() {
521
+ return window.impactToken || window.squatchToken;
522
+ }
523
+ function getConfig() {
524
+ return window.impactConfig || window.squatchConfig;
525
+ }
526
+ browserExports.debug("squatch-js:io");
527
+ async function doQuery(url, query, variables, jwt) {
528
+ const token = jwt || getToken();
529
+ const headers = {
530
+ Accept: "application/json",
531
+ "Content-Type": "application/json",
532
+ ...token ? { Authorization: `Bearer ${token}` } : {},
533
+ "X-SaaSquatch-Referrer": window ? window.location.href : ""
534
+ };
535
+ try {
536
+ const res = await fetch(url, {
537
+ method: "POST",
538
+ body: JSON.stringify({ query, variables }),
539
+ headers
540
+ });
541
+ if (!res.ok) throw new Error(await res.text());
542
+ return await res.json();
543
+ } catch (e) {
544
+ throw e;
545
+ }
546
+ }
547
+ async function doGet(url, jwt = "") {
548
+ const headers = {
549
+ Accept: "application/json",
550
+ "Content-Type": "application/json"
551
+ };
552
+ const token = jwt || getToken();
553
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
554
+ try {
555
+ const res = await fetch(url, {
556
+ method: "GET",
557
+ credentials: "include",
558
+ headers
559
+ });
560
+ const reply = await res.text();
561
+ if (!res.ok) throw new Error(reply);
562
+ return reply ? JSON.parse(reply) : reply;
563
+ } catch (e) {
564
+ throw e;
565
+ }
566
+ }
567
+ async function doPost(url, data, jwt) {
568
+ const headers = {
569
+ Accept: "application/json",
570
+ "Content-Type": "application/json"
571
+ };
572
+ const token = jwt || getToken();
573
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
574
+ try {
575
+ const res = await fetch(url, {
576
+ method: "POST",
577
+ body: data,
578
+ headers
579
+ });
580
+ const reply = await res.text();
581
+ if (!res.ok) throw new Error(reply);
582
+ return reply ? JSON.parse(reply) : reply;
583
+ } catch (e) {
584
+ throw e;
585
+ }
586
+ }
587
+ async function doPut(url, data, jwt) {
588
+ const headers = {
589
+ Accept: "application/json",
590
+ "Content-Type": "application/json",
591
+ "X-SaaSquatch-Referrer": window ? window.location.href : ""
592
+ };
593
+ const token = jwt || getToken();
594
+ if (token) headers["X-SaaSquatch-User-Token"] = token;
595
+ try {
596
+ const res = await fetch(url, {
597
+ headers,
598
+ method: "PUT",
599
+ credentials: "include",
600
+ body: data
601
+ });
602
+ const reply = await res.text();
603
+ if (!res.ok) throw new Error(reply);
604
+ return reply ? JSON.parse(reply) : reply;
605
+ } catch (e) {
606
+ throw e;
607
+ }
608
+ }
609
+ const RENDER_WIDGET_QUERY = `
2
610
  query renderWidget ($user: UserIdInput, $engagementMedium: UserEngagementMedium, $widgetType: WidgetType, $locale: RSLocale) {
3
611
  renderWidget(user: $user, engagementMedium: $engagementMedium, widgetType: $widgetType, locale: $locale) {
4
612
  template
@@ -12,19 +620,331 @@
12
620
  }
13
621
  }
14
622
  }
15
- `;class D{constructor(n){f(this,"tenantAlias");f(this,"domain");f(this,"npmCdn");f(this,"referralCookie",this.squatchReferralCookie);const e=L(n);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn}upsertUser(n){const e=de(n),{widgetType:o,engagementMedium:r="POPUP",jwt:a,locale:d,user:u}=e,h=encodeURIComponent(this.tenantAlias),s=u.accountId?encodeURIComponent(u.accountId):null,c=u.id?encodeURIComponent(u.id):null,l=Ue({widgetType:o,engagementMedium:r,locale:d}),g=`/api/v1/${h}/widget/account/${s}/user/${c}/upsert${l}`,m=this.domain+g,I=(W||window.Cookies).get("_saasquatch");return I&&(u.cookies=I),Re(m,JSON.stringify(u),a)}render(n){const e=le(n),{widgetType:o,engagementMedium:r="POPUP",jwt:a,user:d}=e,u=encodeURIComponent(this.tenantAlias),h=d!=null&&d.accountId?encodeURIComponent(d.accountId):null,s=d!=null&&d.id?encodeURIComponent(d.id):null,c=e.locale??Fe(navigator.language.replace(/\-/g,"_")),l=`/api/v1/${u}/graphql`,g=this.domain+l;return new Promise(async(m,I)=>{var b;try{const v=await ke(g,Te,{user:s&&h?{id:s,accountId:h}:null,engagementMedium:r,widgetType:o,locale:c},a);m((b=v==null?void 0:v.data)==null?void 0:b.renderWidget)}catch(v){I(v)}})}async squatchReferralCookie(){const n=encodeURIComponent(this.tenantAlias),t=(W||window.Cookies).get("_saasquatch")||"",e=t?`?cookies=${encodeURIComponent(t)}`:"",o=`${this.domain}/a/${n}/widgets/squatchcookiejson${e}`,r=await qe(o);return Promise.resolve({...r,encodedCookie:t})}}function Ue({widgetType:i,engagementMedium:n,locale:t}){const e=new URLSearchParams;return e.append("engagementMedium",n),i&&e.append("widgetType",i),t&&e.append("locale",t),`?${e.toString()}`}class ue{constructor(n){f(this,"domain");var o;const e=Se(n);this.domain=(e==null?void 0:e.domain)||((o=ee())==null?void 0:o.domain)||F}pushAnalyticsLoadEvent(n){if(!n.externalUserId||!n.externalAccountId)return;const t=encodeURIComponent(n.tenantAlias),e=encodeURIComponent(n.externalAccountId),o=encodeURIComponent(n.externalUserId),r=encodeURIComponent(n.engagementMedium),a=n.programId?`&programId=${encodeURIComponent(n.programId)}`:"",d=`/a/${t}/widgets/analytics/loaded?externalAccountId=${e}&externalUserId=${o}&engagementMedium=${r}${a}`,u=this.domain+d;return te(u,JSON.stringify({}))}pushAnalyticsShareClickedEvent(n){const t=encodeURIComponent(n.tenantAlias),e=encodeURIComponent(n.externalAccountId),o=encodeURIComponent(n.externalUserId),r=encodeURIComponent(n.engagementMedium),a=encodeURIComponent(n.shareMedium),d=`/a/${t}/widgets/analytics/shared?externalAccountId=${e}&externalUserId=${o}&engagementMedium=${r}&shareMedium=${a}`,u=this.domain+d;return te(u,JSON.stringify({}))}}function Se(i){if(!k(i))throw new Error("'options' should be an object");return i}const C=y.debug("squatch-js:widget");class he{constructor(n){f(this,"type");f(this,"content");f(this,"analyticsApi");f(this,"widgetApi");f(this,"context");f(this,"npmCdn");f(this,"container");f(this,"loadEventListener",null);var t;C("widget initializing ..."),this.content=n.content==="error"?this._error(n.rsCode):n.content,this.type=n.type,this.widgetApi=n.api,this.npmCdn=n.npmCdn,this.analyticsApi=new ue({domain:n.domain}),this.context=n.context,this.container=((t=n.context)==null?void 0:t.container)||n.container}_findElement(){let n;if(typeof this.container=="string"?(n=document.querySelector(this.container),C("loading widget with selector",n)):this.container instanceof HTMLElement?(n=this.container,C("loading widget with container",n)):this.container?(n=null,C("container must be an HTMLElement or string",this.container)):(n=document.querySelector("#squatchembed")||document.querySelector(".squatchembed")||document.querySelector("#impactembed")||document.querySelector(".impactembed"),C("loading widget with default selector",n)),!(n instanceof HTMLElement))throw new Error(`element with selector '${this.container||"#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`);return n}_createFrame(){const n=document.createElement("iframe");return n.squatchJsApi=this,n.id="squatchFrame",n.width="100%",n.src="about:blank",n.scrolling="no",n.setAttribute("style","border: 0; background-color: none; width: 1px; min-width: 100%;"),n}_findFrame(){const n=this.container?this._findElement():document.body;return(n.shadowRoot||n).querySelector("iframe#squatchFrame")}_detachLoadEventListener(n){this.loadEventListener&&(n.removeEventListener("sq:user-registration",this.loadEventListener),this.loadEventListener=null)}_attachLoadEventListener(n,t){this.loadEventListener===null&&(this.loadEventListener=e=>{this._loadEvent({...t,userId:e.detail.userId,accountId:e.detail.accountId})},n.addEventListener("sq:user-registration",this.loadEventListener))}_loadEvent(n){var e;if(!n)return;if(!k(n))throw new Error("Widget Load event identity property is not an object");let t;if("programId"in n){if(!n.tenantAlias||!n.accountId||!n.userId||!n.engagementMedium)throw new Error("Widget Load event missing required properties");t={tenantAlias:n.tenantAlias,externalAccountId:n.accountId,externalUserId:n.userId,engagementMedium:n.engagementMedium,programId:n.programId}}else{const{analytics:o,mode:r}=n;t={tenantAlias:o.attributes.tenant,externalAccountId:o.attributes.accountId,externalUserId:o.attributes.userId,engagementMedium:r.widgetMode}}(e=this.analyticsApi.pushAnalyticsLoadEvent(t))==null||e.then(o=>{C(`${t.engagementMedium} loaded event recorded.`)}).catch(o=>{C(`ERROR: pushAnalyticsLoadEvent() ${o}`)})}_shareEvent(n,t){n&&this.analyticsApi.pushAnalyticsShareClickedEvent({tenantAlias:n.analytics.attributes.tenant,externalAccountId:n.analytics.attributes.accountId,externalUserId:n.analytics.attributes.userId,engagementMedium:n.mode.widgetMode,shareMedium:t}).then(e=>{C(`${n.mode.widgetMode} share ${t} event recorded. ${e}`)}).catch(e=>{C(`ERROR: pushAnalyticsShareClickedEvent() ${e}`)})}_error(n,t="modal",e=""){return`<!DOCTYPE html>
623
+ `;
624
+ class WidgetApi {
625
+ /**
626
+ * Initialize a new {@link WidgetApi} instance.
627
+ *
628
+ * @param {ConfigOptions} config Config details
629
+ *
630
+ * @example <caption>Browser example</caption>
631
+ * var squatchApi = new squatch.WidgetApi({tenantAlias:'test_12b5bo1b25125'});
632
+ *
633
+ * @example <caption>Browserify/Webpack example</caption>
634
+ * var WidgetApi = require('@saasquatch/squatch-js').WidgetApi;
635
+ * var squatchApi = new WidgetApi({tenantAlias:'test_12b5bo1b25125'});
636
+ *
637
+ * @example <caption>Babel+Browserify/Webpack example</caption>
638
+ * import {WidgetApi} from '@saasquatch/squatch-js';
639
+ * let squatchApi = new WidgetApi({tenantAlias:'test_12b5bo1b25125'});
640
+ */
641
+ constructor(config) {
642
+ __publicField(this, "tenantAlias");
643
+ __publicField(this, "domain");
644
+ __publicField(this, "npmCdn");
645
+ __publicField(this, "referralCookie", this.squatchReferralCookie);
646
+ const raw = config;
647
+ const clean = validateConfig(raw);
648
+ this.tenantAlias = clean.tenantAlias;
649
+ this.domain = clean.domain;
650
+ this.npmCdn = clean.npmCdn;
651
+ }
652
+ /**
653
+ * Creates/upserts user, requests widget template.
654
+ *
655
+ * @param {Object} params Parameters for request
656
+ * @param {Object?} params.user The user details
657
+ * @param {string} params.user.id The user id
658
+ * @param {string} params.user.accountId The user account id
659
+ * @param {WidgetType} params.widgetType The content of the widget.
660
+ * @param {EngagementMedium?} params.engagementMedium How to display the widget.
661
+ * @param {string?} params.jwt the JSON Web Token (JWT) that is used
662
+ * to validate the data (can be disabled)
663
+ *
664
+ * @return {Promise} string if true, with the widget template, jsOptions and user details.
665
+ */
666
+ upsertUser(params) {
667
+ const raw = params;
668
+ const clean = validateWidgetConfig(raw);
669
+ const {
670
+ widgetType,
671
+ engagementMedium = "POPUP",
672
+ jwt,
673
+ locale,
674
+ user
675
+ } = clean;
676
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
677
+ const accountId = user.accountId ? encodeURIComponent(user.accountId) : null;
678
+ const userId = user.id ? encodeURIComponent(user.id) : null;
679
+ const optionalParams = _buildParams({
680
+ widgetType,
681
+ engagementMedium,
682
+ locale
683
+ });
684
+ const path = `/api/v1/${tenantAlias}/widget/account/${accountId}/user/${userId}/upsert${optionalParams}`;
685
+ const url = this.domain + path;
686
+ const cookies = (api$1 || window.Cookies).get("_saasquatch");
687
+ if (cookies) user["cookies"] = cookies;
688
+ return doPut(url, JSON.stringify(user), jwt);
689
+ }
690
+ /**
691
+ * Requests widget template
692
+ *
693
+ * @param {Object} params Parameters for request
694
+ * @param {Object} params.user The user details
695
+ * @param {string} params.user.id The user id
696
+ * @param {string} params.user.accountId The user account id
697
+ * @param {WidgetType} params.widgetType The content of the widget.
698
+ * @param {EngagementMedium} params.engagementMedium How to display the widget.
699
+ * @param {string} params.jwt the JSON Web Token (JWT) that is used
700
+ * to validate the data (can be disabled)
701
+ * @return {Promise} template html if true.
702
+ */
703
+ render(params) {
704
+ const raw = params;
705
+ const clean = validatePasswordlessConfig(raw);
706
+ const { widgetType, engagementMedium = "POPUP", jwt, user } = clean;
707
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
708
+ const accountId = (user == null ? void 0 : user.accountId) ? encodeURIComponent(user.accountId) : null;
709
+ const userId = (user == null ? void 0 : user.id) ? encodeURIComponent(user.id) : null;
710
+ const locale = clean.locale ?? validateLocale(navigator.language.replace(/\-/g, "_"));
711
+ const path = `/api/v1/${tenantAlias}/graphql`;
712
+ const url = this.domain + path;
713
+ return new Promise(async (resolve, reject) => {
714
+ var _a2;
715
+ try {
716
+ const res = await doQuery(
717
+ url,
718
+ RENDER_WIDGET_QUERY,
719
+ {
720
+ user: userId && accountId ? { id: userId, accountId } : null,
721
+ engagementMedium,
722
+ widgetType,
723
+ locale
724
+ },
725
+ jwt
726
+ );
727
+ resolve((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.renderWidget);
728
+ } catch (e) {
729
+ reject(e);
730
+ }
731
+ });
732
+ }
733
+ /**
734
+ * Looks up the referral code of the current user, if there is any.
735
+ *
736
+ * @return {Promise<ReferralCookie>} code referral code if true.
737
+ */
738
+ async squatchReferralCookie() {
739
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
740
+ const _saasquatch = (api$1 || window.Cookies).get("_saasquatch") || "";
741
+ const cookie = _saasquatch ? `?cookies=${encodeURIComponent(_saasquatch)}` : ``;
742
+ const url = `${this.domain}/a/${tenantAlias}/widgets/squatchcookiejson${cookie}`;
743
+ const response = await doGet(url);
744
+ return Promise.resolve({
745
+ ...response,
746
+ encodedCookie: _saasquatch
747
+ });
748
+ }
749
+ }
750
+ function _buildParams({
751
+ widgetType,
752
+ engagementMedium,
753
+ locale
754
+ }) {
755
+ const queryParams = new URLSearchParams();
756
+ queryParams.append("engagementMedium", engagementMedium);
757
+ if (widgetType) queryParams.append("widgetType", widgetType);
758
+ if (locale) queryParams.append("locale", locale);
759
+ return `?${queryParams.toString()}`;
760
+ }
761
+ class AnalyticsApi {
762
+ /**
763
+ * Initialize a new {@link AnalyticsApi} instance.
764
+ *
765
+ * @param {Object} config Config details
766
+ * @param {string} [config.domain='https://app.referralsaasquatch.com'] The server domain.
767
+ *
768
+ */
769
+ constructor(config) {
770
+ __publicField(this, "domain");
771
+ var _a2;
772
+ const raw = config;
773
+ const clean = _validateAnalyticsConfig(raw);
774
+ this.domain = (clean == null ? void 0 : clean["domain"]) || ((_a2 = getConfig()) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN;
775
+ }
776
+ pushAnalyticsLoadEvent(params) {
777
+ if (!params.externalUserId || !params.externalAccountId) return;
778
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
779
+ const accountId = encodeURIComponent(params.externalAccountId);
780
+ const userId = encodeURIComponent(params.externalUserId);
781
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
782
+ const programId = params.programId ? `&programId=${encodeURIComponent(params.programId)}` : ``;
783
+ const path = `/a/${tenantAlias}/widgets/analytics/loaded?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}${programId}`;
784
+ const url = this.domain + path;
785
+ return doPost(url, JSON.stringify({}));
786
+ }
787
+ pushAnalyticsShareClickedEvent(params) {
788
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
789
+ const accountId = encodeURIComponent(params.externalAccountId);
790
+ const userId = encodeURIComponent(params.externalUserId);
791
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
792
+ const shareMedium = encodeURIComponent(params.shareMedium);
793
+ const path = `/a/${tenantAlias}/widgets/analytics/shared?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}&shareMedium=${shareMedium}`;
794
+ const url = this.domain + path;
795
+ return doPost(url, JSON.stringify({}));
796
+ }
797
+ }
798
+ function _validateAnalyticsConfig(raw) {
799
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
800
+ return raw;
801
+ }
802
+ const _log$8 = browserExports.debug("squatch-js:widget");
803
+ class Widget {
804
+ constructor(params) {
805
+ __publicField(this, "type");
806
+ __publicField(this, "content");
807
+ __publicField(this, "analyticsApi");
808
+ __publicField(this, "widgetApi");
809
+ __publicField(this, "context");
810
+ __publicField(this, "npmCdn");
811
+ __publicField(this, "container");
812
+ __publicField(this, "loadEventListener", null);
813
+ var _a2;
814
+ _log$8("widget initializing ...");
815
+ this.content = params.content === "error" ? this._error(params.rsCode) : params.content;
816
+ this.type = params.type;
817
+ this.widgetApi = params.api;
818
+ this.npmCdn = params.npmCdn;
819
+ this.analyticsApi = new AnalyticsApi({ domain: params.domain });
820
+ this.context = params.context;
821
+ this.container = ((_a2 = params.context) == null ? void 0 : _a2.container) || params.container;
822
+ }
823
+ _findElement() {
824
+ let element;
825
+ if (typeof this.container === "string") {
826
+ element = document.querySelector(this.container);
827
+ _log$8("loading widget with selector", element);
828
+ } else if (this.container instanceof HTMLElement) {
829
+ element = this.container;
830
+ _log$8("loading widget with container", element);
831
+ } else if (this.container) {
832
+ element = null;
833
+ _log$8("container must be an HTMLElement or string", this.container);
834
+ } else {
835
+ element = document.querySelector("#squatchembed") || document.querySelector(".squatchembed") || document.querySelector("#impactembed") || document.querySelector(".impactembed");
836
+ _log$8("loading widget with default selector", element);
837
+ }
838
+ if (!(element instanceof HTMLElement))
839
+ throw new Error(
840
+ `element with selector '${this.container || "#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`
841
+ );
842
+ return element;
843
+ }
844
+ _createFrame() {
845
+ const frame = document.createElement("iframe");
846
+ frame["squatchJsApi"] = this;
847
+ frame.id = "squatchFrame";
848
+ frame.width = "100%";
849
+ frame.src = "about:blank";
850
+ frame.scrolling = "no";
851
+ frame.setAttribute(
852
+ "style",
853
+ "border: 0; background-color: none; width: 1px; min-width: 100%;"
854
+ );
855
+ return frame;
856
+ }
857
+ _findFrame() {
858
+ const element = this.container ? this._findElement() : document.body;
859
+ const parent = element.shadowRoot || element;
860
+ return parent.querySelector(
861
+ "iframe#squatchFrame"
862
+ );
863
+ }
864
+ _detachLoadEventListener(frameDoc) {
865
+ if (this.loadEventListener) {
866
+ frameDoc.removeEventListener(
867
+ "sq:user-registration",
868
+ this.loadEventListener
869
+ );
870
+ this.loadEventListener = null;
871
+ }
872
+ }
873
+ _attachLoadEventListener(frameDoc, sqh) {
874
+ if (this.loadEventListener === null) {
875
+ this.loadEventListener = (e) => {
876
+ this._loadEvent({
877
+ ...sqh,
878
+ userId: e.detail.userId,
879
+ accountId: e.detail.accountId
880
+ });
881
+ };
882
+ frameDoc.addEventListener("sq:user-registration", this.loadEventListener);
883
+ }
884
+ }
885
+ _loadEvent(sqh) {
886
+ var _a2;
887
+ if (!sqh) return;
888
+ if (!isObject$1(sqh)) {
889
+ throw new Error("Widget Load event identity property is not an object");
890
+ }
891
+ let params;
892
+ if ("programId" in sqh) {
893
+ if (!sqh.tenantAlias || !sqh.accountId || !sqh.userId || !sqh.engagementMedium)
894
+ throw new Error("Widget Load event missing required properties");
895
+ params = {
896
+ tenantAlias: sqh.tenantAlias,
897
+ externalAccountId: sqh.accountId,
898
+ externalUserId: sqh.userId,
899
+ engagementMedium: sqh.engagementMedium,
900
+ programId: sqh.programId
901
+ };
902
+ } else {
903
+ const { analytics, mode } = sqh;
904
+ params = {
905
+ tenantAlias: analytics.attributes.tenant,
906
+ externalAccountId: analytics.attributes.accountId,
907
+ externalUserId: analytics.attributes.userId,
908
+ engagementMedium: mode.widgetMode
909
+ };
910
+ }
911
+ (_a2 = this.analyticsApi.pushAnalyticsLoadEvent(params)) == null ? void 0 : _a2.then((response) => {
912
+ _log$8(`${params.engagementMedium} loaded event recorded.`);
913
+ }).catch((ex) => {
914
+ _log$8(`ERROR: pushAnalyticsLoadEvent() ${ex}`);
915
+ });
916
+ }
917
+ _shareEvent(sqh, medium) {
918
+ if (sqh) {
919
+ this.analyticsApi.pushAnalyticsShareClickedEvent({
920
+ tenantAlias: sqh.analytics.attributes.tenant,
921
+ externalAccountId: sqh.analytics.attributes.accountId,
922
+ externalUserId: sqh.analytics.attributes.userId,
923
+ engagementMedium: sqh.mode.widgetMode,
924
+ shareMedium: medium
925
+ }).then((response) => {
926
+ _log$8(
927
+ `${sqh.mode.widgetMode} share ${medium} event recorded. ${response}`
928
+ );
929
+ }).catch((ex) => {
930
+ _log$8(`ERROR: pushAnalyticsShareClickedEvent() ${ex}`);
931
+ });
932
+ }
933
+ }
934
+ _error(rs, mode = "modal", style = "") {
935
+ const errorTemplate = `<!DOCTYPE html>
16
936
  <!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]-->
17
937
  <!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]-->
18
938
  <!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
19
939
  <head>
20
940
  <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">
21
941
  <style>
22
- ${e}
942
+ ${style}
23
943
  </style>
24
944
  </head>
25
945
  <body>
26
946
 
27
- <div class="squatch-container ${t}" style="width:100%">
947
+ <div class="squatch-container ${mode}" style="width:100%">
28
948
  <div class="errorheader">
29
949
  <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">&times;</button>
30
950
  <p class="errortitle">Error</p>
@@ -37,12 +957,1209 @@
37
957
  <br>
38
958
  <br>
39
959
  <div class="right-align errtxt">
40
- Error Code: ${n}
960
+ Error Code: ${rs}
41
961
  </div>
42
962
  </div>
43
963
  </div>
44
964
  </body>
45
- </html>`}async _findInnerContainer(n){const{contentWindow:t}=n;if(!t)throw new Error("Squatch.js frame inner frame is empty");const e=t.document;function o(){const a=e.getElementsByTagName("sqh-global-container"),d=e.getElementsByClassName("squatch-container");return a.length>0?a[0]:d.length>0?d[0]:null}let r=null;for(let a=0;a<5&&(r=o(),!r);a++)await Pe(100);return r||e.body}reload({email:n,firstName:t,lastName:e},o){const r=this._findFrame();if(!r)throw new Error("Could not find widget iframe");const a=r.contentWindow,d=this.context.engagementMedium||"POPUP";if(!a)throw new Error("Frame needs a content window");let u;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let h={email:n||null,firstName:t||null,lastName:e||null,id:this.context.user.id,accountId:this.context.user.accountId};u=this.widgetApi.upsertUser({user:h,engagementMedium:d,widgetType:this.type,jwt:o})}else if(this.context.type==="passwordless")u=this.widgetApi.render({user:void 0,engagementMedium:d,widgetType:this.type,jwt:void 0});else throw new Error("can't reload an error widget");u.then(({template:h})=>{h&&(this.content=h,this.__deprecated__register(r,{email:n,engagementMedium:d},()=>{this.load(),d==="POPUP"&&this.open()}))}).catch(({message:h})=>{C(`${h}`)})}__deprecated__register(n,t,e){const r=n.contentWindow.document,a=r.createElement("button"),d=r.getElementsByClassName("squatch-register")[0];if(d){a.className="btn btn-primary",a.id="show-stats-btn",a.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const u=t.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";a.setAttribute("style",u),a.onclick=e,d.style.paddingTop="30px",d.innerHTML=`<p><strong>${t.email}</strong><br>Has been successfully registered</p>`,d.appendChild(a)}}}function Pe(i){return new Promise(n=>{setTimeout(n,i)})}/*!
46
- * domready (c) Dustin Diaz 2014 - License MIT
47
- *
48
- */function ne(i,n){let t=[],e,o=i,r=o.documentElement.doScroll,a="DOMContentLoaded",d=(r?/^loaded|^c/:/^loaded|^i|^c/).test(o.readyState);return d||o.addEventListener(a,e=()=>{for(o.removeEventListener(a,e),d=!0;e=t.shift();)e()}),d?setTimeout(n,0):t.push(n)}const q=y.debug("squatch-js:EMBEDwidget");class T extends he{constructor(t,e){super(t);f(this,"show",this.open);f(this,"hide",this.close);e&&(this.container=e)}async load(){var a,d;const t=this._createFrame(),e=this._findElement();(a=this.context)!=null&&a.container&&(e.style.visibility="hidden",e.style.height="0",e.style["overflow-y"]="hidden"),this.container?e.shadowRoot?((d=e.shadowRoot.lastChild)==null?void 0:d.nodeName)==="IFRAME"?e.shadowRoot.replaceChild(t,e.shadowRoot.lastChild):e.shadowRoot.appendChild(t):e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t):(!e.firstChild||e.firstChild.nodeName==="#text")&&e.appendChild(t);const{contentWindow:o}=t;if(!o)throw new Error("Frame needs a content window");const r=o.document;r.open(),r.write(this.content),r.write(`<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`),r.close(),ne(r,async()=>{const u=o.squatch||o.widgetIdent;t.height=r.body.scrollHeight;const h=new o.ResizeObserver(c=>{for(const l of c){const{height:g}=l.contentRect;t.height=g}}),s=await this._findInnerContainer(t);h.observe(s),this._shouldFireLoadEvent()?(this._loadEvent(u),q("loaded")):r&&this._attachLoadEventListener(r,u)})}open(){const t=this._findFrame();if(!t)return q("no target element to open");if(!t.contentWindow)return q("Frame needs a content window");const e=this._findElement();e.style.visibility="unset",e.style.height="auto",e.style["overflow-y"]="auto",t.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const o=t.contentWindow.squatch||t.contentWindow.widgetIdent;if(this.context.user)this._loadEvent(o),q("loaded");else{if(!t.contentDocument)return;this._attachLoadEventListener(t.contentDocument,o)}}close(){const t=this._findFrame();if(!t)return q("no target element to close");t.contentDocument&&this._detachLoadEventListener(t.contentDocument);const e=this._findElement();e.style.visibility="hidden",e.style.height="0",e.style["overflow-y"]="hidden",q("Embed widget closed")}_error(t,e="embed",o=""){return super._error(t,e,o)}_shouldFireLoadEvent(){const t=!this.container,e=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));return!!this.context.user&&(t||e)}}const U=y.debug("squatch-js:POPUPwidget");let j=0;class S extends he{constructor(t,e=".squatchpop"){super(t);f(this,"trigger");f(this,"id");f(this,"show",this.open);f(this,"hide",this.close);this.trigger=e,this.container?this.id="squatchModal":(this.id=j===0?"squatchModal":`squatchModal__${j}`,j=j+1),document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let t;try{t=document.querySelector(this.trigger)||document.querySelector(".impactpop"),this.trigger&&!t&&U("No element found with trigger selector",this.trigger)}catch{U("Not a valid selector",this.trigger)}t&&(t.onclick=()=>{this.open()})}_createPopupDialog(){const t=document.createElement("dialog");t.id=this.id,t.setAttribute("style","width: 100%; max-width: 500px; border: none; padding: 0;");const e=o=>{o.stopPropagation(),o.target===t&&t.close()};return t.addEventListener("click",e),t}async load(){var u;const t=this._createFrame();this._initialiseCTA();const e=this.container?this._findElement():document.body,o=e.shadowRoot||e,r=this._createPopupDialog();r.appendChild(t),((u=o.lastChild)==null?void 0:u.nodeName)==="DIALOG"?o.replaceChild(r,o.lastChild):o.appendChild(r);const{contentWindow:a}=t;if(!a)throw new Error("Frame needs a content window");const d=a.document;d.open(),d.write(this.content),d.write(`<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`),d.close(),U("Popup template loaded into iframe"),await this._setupResizeHandler(t)}async _setupResizeHandler(t){const{contentWindow:e}=t;if(!e)throw new Error("Frame needs a content window");const o=e.document;ne(o,async()=>{o.body.style.overflowY="hidden",t.height=`${o.body.offsetHeight}px`,new e.ResizeObserver(a=>{for(const d of a){const{top:u,bottom:h}=d.contentRect,s=h+u;t.height=s+"",d.target.style=""}}).observe(await this._findInnerContainer(t))})}open(){const t=this.container?this._findElement():document.body,o=(t.shadowRoot||t).querySelector(`#${this.id}`);if(!o)throw new Error("Could not determine container div");o.showModal();const r=this._findFrame();if(!r)throw new Error("Could not find iframe");const{contentWindow:a}=r;if(!a)throw new Error("Squatch.js has an empty iframe");const d=a.document;ne(d,()=>{var h;const u=a.squatch||a.widgetIdent;(h=r.contentDocument)==null||h.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(u),U("Popup opened")):this._attachLoadEventListener(d,u)})}close(){const t=this._findFrame();t!=null&&t.contentDocument&&this._detachLoadEventListener(t.contentDocument);const e=this.container?this._findElement():document.body,r=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!r)throw new Error("Could not determine container div");r.close(),U("Popup closed")}_clickedOutside({target:t}){}_error(t,e="modal",o=""){return super._error(t,e,o||"body { margin: 0; } .modal { box-shadow: none; border: 0; }")}}const E=y.debug("squatch-js:widgets");class P{constructor(n){f(this,"api");f(this,"tenantAlias");f(this,"domain");f(this,"npmCdn");const t=L(n);this.tenantAlias=t.tenantAlias,this.domain=t.domain,this.npmCdn=t.npmCdn,this.api=new D(t)}async upsertUser(n){const e=de(n);try{const o=await this.api.upsertUser(e);return{widget:this._renderWidget(o,e,{type:"upsert",user:e.user,engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger}),user:o.user}}catch(o){throw E(o),o.apiErrorCode&&this._renderErrorWidget(o,n.engagementMedium),new Error(o)}}async render(n){const e=le(n);try{const o=await this.api.render(e);return{widget:this._renderWidget(o,e,{type:"passwordless",engagementMedium:e.engagementMedium,container:e.container,trigger:e.trigger}),user:o.user}}catch(o){throw o.apiErrorCode&&this._renderErrorWidget(o,e.engagementMedium),new Error(o)}}async autofill(n){const t=n;if(typeof t=="function"){try{const r=await this.api.squatchReferralCookie();t(r)}catch(r){throw E("Autofill error",r),new Error(r)}return}if(typeof t!="string")throw new Error("Autofill accepts a string or function");let e=document.querySelectorAll(t),o;if(e.length>0)o=e[0];else throw E("Element id/class or function missing"),new Error("Element id/class or function missing");try{const r=await this.api.squatchReferralCookie();o.value=r.codes[0]}catch(r){throw new Error(r)}}_renderWidget(n,t,e){var u;if(E("Rendering Widget..."),!n)throw new Error("Unable to get a response");let o,r=!!t.displayOnLoad;const a=n.jsOptions||{},d={content:n.template,type:t.widgetType||((u=a.widget)==null?void 0:u.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:e};return a.widgetUrlMappings&&a.widgetUrlMappings.forEach(h=>{var s,c;P._matchesUrl(h.url)&&(h.widgetType!=="CONVERSION_WIDGET"||(c=(s=n.user)==null?void 0:s.referredBy)!=null&&c.code?(r=h.displayOnLoad,E(`Display ${h.widgetType} on ${h.url}`)):E(`Don't display ${h.widgetType} when no referral on widget rule match ${h.url}`))}),a.fuelTankAutofillUrls&&(E("We found a fuel tank autofill!"),a.fuelTankAutofillUrls.forEach(({url:h,formSelector:s})=>{var c,l,g;if(P._matchesUrl(h)&&(E("Fuel Tank URL matches"),(l=(c=n.user)==null?void 0:c.referredBy)!=null&&l.code)){const m=document.querySelector(s);m?m.value=((g=n.user.referredBy.referredReward)==null?void 0:g.fuelTankCode)||"":E(new Error(`Element with id/class ${s} was not found.`))}})),t.engagementMedium==="EMBED"?o=this._renderEmbedWidget(d):(o=this._renderPopupWidget(d),r&&o.open()),o}_renderPopupWidget(n){const t=new S(n,n.context.trigger);return t.load(),t}_renderEmbedWidget(n){const t=new T(n,n.context.container);return t.load(),t}_renderErrorWidget(n,t="POPUP"){const{apiErrorCode:e,rsCode:o,message:r}=n;E(new Error(`${e} (${o}) ${r}`));const a={content:"error",rsCode:o,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;t==="EMBED"?(d=new T(a),d.load()):t==="POPUP"&&(d=new S(a),d.load())}static _matchesUrl(n){return!!window.location.href.match(new RegExp(n))}}class Me{constructor(n){f(this,"tenantAlias");f(this,"domain");const e=L(n);this.tenantAlias=e.tenantAlias,this.domain=e.domain}track(n,t){const e=n,o=t,r=xe(e),{jwt:a}=$e(o),d=encodeURIComponent(this.tenantAlias),u=encodeURIComponent(r.userId),h=encodeURIComponent(r.accountId),s=`/api/v1/${d}/open/account/${h}/user/${u}/events`,c=this.domain+s;return te(c,JSON.stringify(r),a)}}function xe(i){if(!k(i))throw new Error("tracking parameter must be an object");if(!(i!=null&&i.accountId))throw new Error("accountId field is required");if(!(i!=null&&i.events))throw new Error("events field is required");if(!(i!=null&&i.userId))throw new Error("userId field is required");const n=i;if(!Array.isArray(n.events))throw new Error("'events' should be an array");return n}function $e(i){if(!k(i))throw new Error("'options' should be an object");return i}function We(){var o;const i=window[K]?K:O,n=((o=window["_"+i])==null?void 0:o.ready)||[],t=window.impactOnReady||window.squatchOnReady,e=[...n,t].filter(r=>!!r);setTimeout(()=>{window[O]&&(window[K]=window[O],e.forEach(r=>r()),window[O]._auto(),window["_"+i]=void 0,delete window["_"+i])},0)}const _=y.debug("squatch-js"),fe=i=>typeof i=="object"&&!Array.isArray(i),pe=(i,n)=>{const t=o=>fe(n[o])&&i.hasOwnProperty(o)&&fe(i[o]),e=Object.getOwnPropertyNames(n).map(o=>({[o]:t(o)?pe(i[o],n[o]):n[o]})).reduce((o,r)=>({...o,...r}),{});return{...i,...e}};function N(i){const n=atob(i.replace(/_/g,"/").replace(/-/g,"+")),t=new Uint8Array(n.length);for(let e=0;e<n.length;e++)t[e]=n.charCodeAt(e);return new TextDecoder("utf8").decode(t)}function me(i){const n=new TextEncoder().encode(i),t=Array.from(n,e=>String.fromCodePoint(e)).join("");return btoa(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Oe(){var i,n,t="weird_get_top_level_domain=cookie",e=document.location.hostname.split(".");for(i=e.length-1;i>=0;i--)if(n=e.slice(i).join("."),document.cookie=t+";domain=."+n+";",document.cookie.indexOf(t)>-1)return document.cookie=t.split("=")[0]+"=;domain=."+n+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",n}function Le(){const i=window.location.search,t=new URLSearchParams(i).get("_saasquatch")||"";if(t){let e="",o="",r="";try{e=JSON.parse(N(t))}catch(a){_("Unable to decode params",a);return}try{o=JSON.parse(N(W.get("_saasquatch"))),_("existing cookie",o)}catch(a){_("Unable to retrieve cookie",a)}try{const a=Oe();if(_("domain retrieved:",a),o){const d=pe(o,e);r=me(JSON.stringify(d)),_("cookie to store:",d)}else r=me(JSON.stringify(e)),_("cookie to store:",e);W.set("_saasquatch",r,{expires:365,secure:!1,sameSite:"Lax",domain:a,path:"/"})}catch(a){_("Unable to set cookie",a)}}}const oe=y.debug("squatch-js");function De(i){const n=window.location.search,e=new URLSearchParams(n).get("_saasquatchExtra")||"";if(!e){oe("No _saasquatchExtra param");return}let o;try{o=JSON.parse(N(e))}catch{oe("Unable to decode _saasquatchExtra config");return}const{domain:r,tenantAlias:a,widgetConfig:d}=je(o);if(!r||!a||!d){oe("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:u,...h}=d;return{widgetConfig:{widgetType:u,displayOnLoad:!0,...h},squatchConfig:{...i?{configIn:i}:{},domain:r,tenantAlias:a}}}function je(i){var r;const n=Object.keys(i||{})[0],t=Object.keys((i==null?void 0:i[n])||{})[0],e=(r=i==null?void 0:i[n])==null?void 0:r[t];return{domain:n?`https://${n}`:void 0,tenantAlias:t,widgetConfig:e}}const Ne=y.debug("squatch-js:decodeUserJwt");function Je(i){var n;try{const t=i.split(".")[1];if(t===void 0)return null;const e=N(t);return(n=JSON.parse(e))==null?void 0:n.user}catch(t){return Ne(t),null}}const ge=Ie("squatch-js:DeclarativeWidget");class we extends HTMLElement{constructor(){super();f(this,"config");f(this,"token");f(this,"tenant");f(this,"widgetType");f(this,"locale");f(this,"widgetApi");f(this,"analyticsApi");f(this,"widgetInstance");f(this,"type");f(this,"container");f(this,"element");f(this,"loaded");f(this,"_setWidget",(t,e)=>{var r;const o={api:this.widgetApi,content:t,context:{type:e.type,user:e.user,container:this.container||void 0,engagementMedium:this.type},type:this.widgetType,domain:((r=this.config)==null?void 0:r.domain)||F,npmCdn:Z,container:this};if(this.type==="EMBED")return new T(o);{const a=this.firstChild?null:void 0;return new S(o,a)}});f(this,"setErrorWidget",t=>{var o;const e={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((o=this.config)==null?void 0:o.domain)||F,npmCdn:Z,container:this};if(this.type==="EMBED")return new T(e);{const r=this.firstChild?null:void 0;return new S(e,r)}});f(this,"reload",this.renderWidget);f(this,"show",this.open);f(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=ee(),this.token=R(),this.tenant=window.squatchTenant,this.container=this}_setupApis(t){var e,o;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new D({tenantAlias:(t==null?void 0:t.tenantAlias)||this.tenant,domain:(t==null?void 0:t.domain)||((e=this.config)==null?void 0:e.domain)||F}),this.analyticsApi=new ue({domain:(t==null?void 0:t.domain)||((o=this.config)==null?void 0:o.domain)||F})}async renderPasswordlessVariant(){return this._setupApis(),ge("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(t=>this._setWidget(t.template,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const t=Je(this.token);return t?(ge("Rendering as a Verified widget"),await this.widgetApi.upsertUser({user:t,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token}).then(o=>this._setWidget(o.template,{type:"upsert",user:t})).catch(this.setErrorWidget)):this.setErrorWidget(Error("No user object in token."))}async getWidgetInstance(){let t;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?t=await this.renderUserUpsertVariant():t=await this.renderPasswordlessVariant(),this.widgetInstance=t,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),t}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 ie extends we{constructor(){super(),this.type="EMBED",this.loaded=!1}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(n,t,e){if(!(t===e||!this.loaded))switch(n){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){var t,e;this.loaded=!0,this.container=this.getAttribute("container"),await this.renderWidget();const n=(t=this.shadowRoot&&Array.from(this.shadowRoot.children))==null?void 0:t.find(o=>o.tagName==="SLOT");n&&((e=this.shadowRoot)==null||e.removeChild(n)),this.getAttribute("open")!==null&&this.open()}}class re extends we{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",n=>{n.stopPropagation(),this.open()})}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(n,t,e){if(!(t===e||!this.loaded))switch(n){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),await this.renderWidget(),this.getAttribute("open")!==null&&this.open()}}class Be extends ie{}class ze extends re{}class He extends ie{}class Ge extends re{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Be),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",He),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",ze),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Ge);function Ve(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const M=y.debug("squatch-js");let J=null,B=null,z=null;function Xe(){return J||x({}),J}function H(){return B||x({}),B}function Qe(){return z||x({}),z}function Ye(i){var n;return(n=H())==null?void 0:n.render(i)}function Ze(i){var t;const n=De(i);if(n){const{squatchConfig:e,widgetConfig:o}=n;return x(e),(t=H())==null?void 0:t.render(o)}}function x(i){const t=L(i);t.tenantAlias.match("^test")||t.debug?y.debug.enable("squatch-js*"):y.debug.disable(),M("initializing ..."),J=new D(t),B=new P(t),z=new Me(t),M("Widget API instance",J),M("Widgets instance",B),M("Events API instance",z)}function Ke(i){i()}function et(i){H().autofill(i)}function ye(){Le()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&ye(),(Ce=window.squatch)!=null&&Ce.init&&M("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&We(),p.DeclarativeEmbedWidget=ie,p.DeclarativePopupWidget=re,p.EmbedWidget=T,p.PopupWidget=S,p.WidgetApi=D,p.Widgets=P,p._auto=Ze,p.api=Xe,p.autofill=et,p.events=Qe,p.help=Ve,p.init=x,p.pushCookie=ye,p.ready=Ke,p.widget=Ye,p.widgets=H,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
965
+ </html>`;
966
+ return errorTemplate;
967
+ }
968
+ async _findInnerContainer(frame) {
969
+ const { contentWindow } = frame;
970
+ if (!contentWindow)
971
+ throw new Error("Squatch.js frame inner frame is empty");
972
+ const frameDoc = contentWindow.document;
973
+ function search() {
974
+ const containers = frameDoc.getElementsByTagName("sqh-global-container");
975
+ const legacyContainers = frameDoc.getElementsByClassName("squatch-container");
976
+ const fallback = containers.length > 0 ? containers[0] : legacyContainers.length > 0 ? legacyContainers[0] : null;
977
+ return fallback;
978
+ }
979
+ let found = null;
980
+ for (let i = 0; i < 5; i++) {
981
+ found = search();
982
+ if (found) break;
983
+ await delay(100);
984
+ }
985
+ if (!found) {
986
+ return frameDoc.body;
987
+ }
988
+ return found;
989
+ }
990
+ /**
991
+ * Reloads the current widget, makes updated request to API and renders result.
992
+ * Primarily for Classic widgets with registration
993
+ * @param param0 Form field values
994
+ * @param jwt JWT for API authentication
995
+ */
996
+ reload({ email, firstName, lastName }, jwt) {
997
+ const frame = this._findFrame();
998
+ if (!frame) throw new Error("Could not find widget iframe");
999
+ const frameWindow = frame.contentWindow;
1000
+ const engagementMedium = this.context.engagementMedium || "POPUP";
1001
+ if (!frameWindow) {
1002
+ throw new Error("Frame needs a content window");
1003
+ }
1004
+ let response;
1005
+ if (this.context.type === "upsert") {
1006
+ if (!this.context.user) throw new Error("Can't reload without user ids");
1007
+ let userObj = {
1008
+ email: email || null,
1009
+ firstName: firstName || null,
1010
+ lastName: lastName || null,
1011
+ id: this.context.user.id,
1012
+ accountId: this.context.user.accountId
1013
+ };
1014
+ response = this.widgetApi.upsertUser({
1015
+ user: userObj,
1016
+ engagementMedium,
1017
+ widgetType: this.type,
1018
+ jwt
1019
+ });
1020
+ } else if (this.context.type === "passwordless") {
1021
+ response = this.widgetApi.render({
1022
+ user: void 0,
1023
+ engagementMedium,
1024
+ widgetType: this.type,
1025
+ jwt: void 0
1026
+ });
1027
+ } else {
1028
+ throw new Error("can't reload an error widget");
1029
+ }
1030
+ response.then(({ template }) => {
1031
+ if (template) {
1032
+ this.content = template;
1033
+ this.__deprecated__register(
1034
+ frame,
1035
+ { email, engagementMedium },
1036
+ () => {
1037
+ this.load();
1038
+ engagementMedium === "POPUP" && this.open();
1039
+ }
1040
+ );
1041
+ }
1042
+ }).catch(({ message }) => {
1043
+ _log$8(`${message}`);
1044
+ });
1045
+ }
1046
+ __deprecated__register(frame, params, onClick) {
1047
+ const frameWindow = frame.contentWindow;
1048
+ const frameDoc = frameWindow.document;
1049
+ const showStatsBtn = frameDoc.createElement("button");
1050
+ const registerForm = frameDoc.getElementsByClassName("squatch-register")[0];
1051
+ if (registerForm) {
1052
+ showStatsBtn.className = "btn btn-primary";
1053
+ showStatsBtn.id = "show-stats-btn";
1054
+ showStatsBtn.textContent = this.type === "REFERRER_WIDGET" ? "Show Stats" : "Show Reward";
1055
+ const widgetStyle = params.engagementMedium === "POPUP" ? "margin-top: 10px; max-width: 130px; width: 100%;" : "margin-top: 10px;";
1056
+ showStatsBtn.setAttribute("style", widgetStyle);
1057
+ showStatsBtn.onclick = onClick;
1058
+ registerForm.style.paddingTop = "30px";
1059
+ registerForm.innerHTML = `<p><strong>${params.email}</strong><br>Has been successfully registered</p>`;
1060
+ registerForm.appendChild(showStatsBtn);
1061
+ }
1062
+ }
1063
+ }
1064
+ function delay(duration) {
1065
+ return new Promise((resolve) => {
1066
+ setTimeout(resolve, duration);
1067
+ });
1068
+ }
1069
+ /*!
1070
+ * domready (c) Dustin Diaz 2014 - License MIT
1071
+ *
1072
+ */
1073
+ function domready(targetDoc, fn) {
1074
+ let fns = [];
1075
+ let listener;
1076
+ let doc = targetDoc;
1077
+ let hack = doc.documentElement.doScroll;
1078
+ let domContentLoaded = "DOMContentLoaded";
1079
+ let loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState);
1080
+ if (!loaded)
1081
+ doc.addEventListener(
1082
+ domContentLoaded,
1083
+ listener = () => {
1084
+ doc.removeEventListener(domContentLoaded, listener);
1085
+ loaded = true;
1086
+ while (listener = fns.shift()) listener();
1087
+ }
1088
+ );
1089
+ return loaded ? setTimeout(fn, 0) : fns.push(fn);
1090
+ }
1091
+ const _log$7 = browserExports.debug("squatch-js:EMBEDwidget");
1092
+ class EmbedWidget extends Widget {
1093
+ constructor(params, container) {
1094
+ super(params);
1095
+ __publicField(this, "show", this.open);
1096
+ __publicField(this, "hide", this.close);
1097
+ if (container) this.container = container;
1098
+ }
1099
+ async load() {
1100
+ var _a2, _b;
1101
+ const frame = this._createFrame();
1102
+ const element = this._findElement();
1103
+ if ((_a2 = this.context) == null ? void 0 : _a2.container) {
1104
+ element.style.visibility = "hidden";
1105
+ element.style.height = "0";
1106
+ element.style["overflow-y"] = "hidden";
1107
+ }
1108
+ if (this.container) {
1109
+ if (element.shadowRoot) {
1110
+ if (((_b = element.shadowRoot.lastChild) == null ? void 0 : _b.nodeName) === "IFRAME") {
1111
+ element.shadowRoot.replaceChild(frame, element.shadowRoot.lastChild);
1112
+ } else {
1113
+ element.shadowRoot.appendChild(frame);
1114
+ }
1115
+ } else if (element.firstChild) {
1116
+ element.replaceChild(frame, element.firstChild);
1117
+ } else {
1118
+ element.appendChild(frame);
1119
+ }
1120
+ } else if (!element.firstChild || element.firstChild.nodeName === "#text") {
1121
+ element.appendChild(frame);
1122
+ }
1123
+ const { contentWindow } = frame;
1124
+ if (!contentWindow) {
1125
+ throw new Error("Frame needs a content window");
1126
+ }
1127
+ const frameDoc = contentWindow.document;
1128
+ frameDoc.open();
1129
+ frameDoc.write(this.content);
1130
+ frameDoc.write(
1131
+ `<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`
1132
+ );
1133
+ frameDoc.close();
1134
+ domready(frameDoc, async () => {
1135
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1136
+ frame.height = frameDoc.body.scrollHeight;
1137
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1138
+ for (const entry of entries) {
1139
+ const { height } = entry.contentRect;
1140
+ frame.height = height;
1141
+ }
1142
+ });
1143
+ const container = await this._findInnerContainer(frame);
1144
+ ro.observe(container);
1145
+ if (this._shouldFireLoadEvent()) {
1146
+ this._loadEvent(_sqh);
1147
+ _log$7("loaded");
1148
+ } else if (frameDoc) {
1149
+ this._attachLoadEventListener(frameDoc, _sqh);
1150
+ }
1151
+ });
1152
+ }
1153
+ /**
1154
+ * Un-hide if element is available and refresh data
1155
+ */
1156
+ open() {
1157
+ const frame = this._findFrame();
1158
+ if (!frame) return _log$7("no target element to open");
1159
+ if (!frame.contentWindow) return _log$7("Frame needs a content window");
1160
+ const element = this._findElement();
1161
+ element.style.visibility = "unset";
1162
+ element.style.height = "auto";
1163
+ element.style["overflow-y"] = "auto";
1164
+ frame.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));
1165
+ const _sqh = frame.contentWindow.squatch || frame.contentWindow.widgetIdent;
1166
+ if (this.context.user) {
1167
+ this._loadEvent(_sqh);
1168
+ _log$7("loaded");
1169
+ } else {
1170
+ if (!frame.contentDocument) return;
1171
+ this._attachLoadEventListener(frame.contentDocument, _sqh);
1172
+ }
1173
+ }
1174
+ close() {
1175
+ const frame = this._findFrame();
1176
+ if (!frame) return _log$7("no target element to close");
1177
+ if (frame.contentDocument)
1178
+ this._detachLoadEventListener(frame.contentDocument);
1179
+ const element = this._findElement();
1180
+ element.style.visibility = "hidden";
1181
+ element.style.height = "0";
1182
+ element.style["overflow-y"] = "hidden";
1183
+ _log$7("Embed widget closed");
1184
+ }
1185
+ _error(rs, mode = "embed", style = "") {
1186
+ return super._error(rs, mode, style);
1187
+ }
1188
+ _shouldFireLoadEvent() {
1189
+ const noContainer = !this.container;
1190
+ const isComponent = this.container instanceof HTMLElement && (this.container.tagName.startsWith("SQUATCH-") || this.container.tagName.startsWith("IMPACT-"));
1191
+ const isVerified = !!this.context.user;
1192
+ return isVerified && (noContainer || isComponent);
1193
+ }
1194
+ }
1195
+ const _log$6 = browserExports.debug("squatch-js:POPUPwidget");
1196
+ let popupId = 0;
1197
+ class PopupWidget extends Widget {
1198
+ constructor(params, trigger = ".squatchpop") {
1199
+ super(params);
1200
+ __publicField(this, "trigger");
1201
+ __publicField(this, "id");
1202
+ __publicField(this, "show", this.open);
1203
+ __publicField(this, "hide", this.close);
1204
+ this.trigger = trigger;
1205
+ if (this.container) {
1206
+ this.id = "squatchModal";
1207
+ } else {
1208
+ this.id = popupId === 0 ? `squatchModal` : `squatchModal__${popupId}`;
1209
+ popupId = popupId + 1;
1210
+ }
1211
+ document.head.insertAdjacentHTML(
1212
+ "beforeend",
1213
+ `<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`
1214
+ );
1215
+ }
1216
+ _initialiseCTA() {
1217
+ if (!this.trigger) return;
1218
+ let triggerElement;
1219
+ try {
1220
+ triggerElement = document.querySelector(this.trigger) || document.querySelector(".impactpop");
1221
+ if (this.trigger && !triggerElement)
1222
+ _log$6("No element found with trigger selector", this.trigger);
1223
+ } catch {
1224
+ _log$6("Not a valid selector", this.trigger);
1225
+ }
1226
+ if (triggerElement) {
1227
+ triggerElement.onclick = () => {
1228
+ this.open();
1229
+ };
1230
+ }
1231
+ }
1232
+ _createPopupDialog() {
1233
+ const dialog = document.createElement("dialog");
1234
+ dialog.id = this.id;
1235
+ dialog.setAttribute(
1236
+ "style",
1237
+ "width: 100%; max-width: 500px; border: none; padding: 0;"
1238
+ );
1239
+ const onClick = (e) => {
1240
+ e.stopPropagation();
1241
+ if (e.target === dialog) dialog.close();
1242
+ };
1243
+ dialog.addEventListener("click", onClick);
1244
+ return dialog;
1245
+ }
1246
+ async load() {
1247
+ var _a2;
1248
+ const frame = this._createFrame();
1249
+ this._initialiseCTA();
1250
+ const element = this.container ? this._findElement() : document.body;
1251
+ const dialogParent = element.shadowRoot || element;
1252
+ const dialog = this._createPopupDialog();
1253
+ dialog.appendChild(frame);
1254
+ if (((_a2 = dialogParent.lastChild) == null ? void 0 : _a2.nodeName) === "DIALOG") {
1255
+ dialogParent.replaceChild(dialog, dialogParent.lastChild);
1256
+ } else {
1257
+ dialogParent.appendChild(dialog);
1258
+ }
1259
+ const { contentWindow } = frame;
1260
+ if (!contentWindow) {
1261
+ throw new Error("Frame needs a content window");
1262
+ }
1263
+ const frameDoc = contentWindow.document;
1264
+ frameDoc.open();
1265
+ frameDoc.write(this.content);
1266
+ frameDoc.write(
1267
+ `<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`
1268
+ );
1269
+ frameDoc.close();
1270
+ _log$6("Popup template loaded into iframe");
1271
+ await this._setupResizeHandler(frame);
1272
+ }
1273
+ async _setupResizeHandler(frame) {
1274
+ const { contentWindow } = frame;
1275
+ if (!contentWindow) {
1276
+ throw new Error("Frame needs a content window");
1277
+ }
1278
+ const frameDoc = contentWindow.document;
1279
+ domready(frameDoc, async () => {
1280
+ frameDoc.body.style.overflowY = "hidden";
1281
+ frame.height = `${frameDoc.body.offsetHeight}px`;
1282
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1283
+ for (const entry of entries) {
1284
+ const { top, bottom } = entry.contentRect;
1285
+ const computedHeight = bottom + top;
1286
+ frame.height = computedHeight + "";
1287
+ entry.target.style = ``;
1288
+ }
1289
+ });
1290
+ ro.observe(await this._findInnerContainer(frame));
1291
+ });
1292
+ }
1293
+ open() {
1294
+ const element = this.container ? this._findElement() : document.body;
1295
+ const parent = element.shadowRoot || element;
1296
+ const dialog = parent.querySelector(`#${this.id}`);
1297
+ if (!dialog) throw new Error("Could not determine container div");
1298
+ dialog.showModal();
1299
+ const frame = this._findFrame();
1300
+ if (!frame) throw new Error("Could not find iframe");
1301
+ const { contentWindow } = frame;
1302
+ if (!contentWindow) throw new Error("Squatch.js has an empty iframe");
1303
+ const frameDoc = contentWindow.document;
1304
+ domready(frameDoc, () => {
1305
+ var _a2;
1306
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1307
+ (_a2 = frame.contentDocument) == null ? void 0 : _a2.dispatchEvent(new CustomEvent("sq:refresh"));
1308
+ if (this.context.user) {
1309
+ this._loadEvent(_sqh);
1310
+ _log$6("Popup opened");
1311
+ } else {
1312
+ this._attachLoadEventListener(frameDoc, _sqh);
1313
+ }
1314
+ });
1315
+ }
1316
+ close() {
1317
+ const frame = this._findFrame();
1318
+ if (frame == null ? void 0 : frame.contentDocument)
1319
+ this._detachLoadEventListener(frame.contentDocument);
1320
+ const element = this.container ? this._findElement() : document.body;
1321
+ const parent = element.shadowRoot || element;
1322
+ const dialog = parent.querySelector(`#${this.id}`);
1323
+ if (!dialog) throw new Error("Could not determine container div");
1324
+ dialog.close();
1325
+ _log$6("Popup closed");
1326
+ }
1327
+ _clickedOutside({ target }) {
1328
+ }
1329
+ _error(rs, mode = "modal", style = "") {
1330
+ const _style = "body { margin: 0; } .modal { box-shadow: none; border: 0; }";
1331
+ return super._error(rs, mode, style || _style);
1332
+ }
1333
+ }
1334
+ const _log$5 = browserExports.debug("squatch-js:widgets");
1335
+ class Widgets {
1336
+ /**
1337
+ * Initialize a new {@link Widgets} instance.
1338
+ *
1339
+ * @param {ConfigOptions} config Config details
1340
+ *
1341
+ * @example <caption>Browser example</caption>
1342
+ * var widgets = new squatch.Widgets({tenantAlias:'test_12b5bo1b25125'});
1343
+ *
1344
+ * @example <caption>Browserify/Webpack example</caption>
1345
+ * var Widgets = require('@saasquatch/squatch-js').Widgets;
1346
+ * var widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1347
+ *
1348
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1349
+ * import {Widgets} from '@saasquatch/squatch-js';
1350
+ * let widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1351
+ */
1352
+ constructor(configin) {
1353
+ /**
1354
+ * Instance of {@link WidgetApi}
1355
+ */
1356
+ __publicField(this, "api");
1357
+ /**
1358
+ * Tenant alias of SaaSquatch tenant
1359
+ */
1360
+ __publicField(this, "tenantAlias");
1361
+ /**
1362
+ * SaaSquatch domain for API requests
1363
+ * @default "https://app.referralsaasquatch.com"
1364
+ */
1365
+ __publicField(this, "domain");
1366
+ /**
1367
+ * Hosted CDN for npm packages
1368
+ * @default "https://fast.ssqt.io/npm"
1369
+ */
1370
+ __publicField(this, "npmCdn");
1371
+ const config = validateConfig(configin);
1372
+ this.tenantAlias = config.tenantAlias;
1373
+ this.domain = config.domain;
1374
+ this.npmCdn = config.npmCdn;
1375
+ this.api = new WidgetApi(config);
1376
+ }
1377
+ /**
1378
+ * This function calls the {@link WidgetApi.upsertUser} method, and it renders
1379
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1380
+ *
1381
+ * @param {Object} config Config details
1382
+ * @param {Object} config.user The user details
1383
+ * @param {string} config.user.id The user id
1384
+ * @param {string} config.user.accountId The user account id
1385
+ * @param {WidgetType} config.widgetType The content of the widget
1386
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1387
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used to validate the data (can be disabled)
1388
+ * @param {HTMLElement | string | undefined} config.container Element to load the widget into
1389
+ * @param {string | undefined} config.trigger Trigger element for opening the popup widget
1390
+ *
1391
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1392
+ */
1393
+ async upsertUser(config) {
1394
+ const raw = config;
1395
+ const clean = validateWidgetConfig(raw);
1396
+ try {
1397
+ const response = await this.api.upsertUser(clean);
1398
+ return {
1399
+ widget: this._renderWidget(response, clean, {
1400
+ type: "upsert",
1401
+ user: clean.user,
1402
+ engagementMedium: config.engagementMedium,
1403
+ container: config.container,
1404
+ trigger: config.trigger
1405
+ }),
1406
+ user: response.user
1407
+ };
1408
+ } catch (err) {
1409
+ _log$5(err);
1410
+ if (err.apiErrorCode) {
1411
+ this._renderErrorWidget(err, config.engagementMedium);
1412
+ }
1413
+ throw new Error(err);
1414
+ }
1415
+ }
1416
+ /**
1417
+ * This function calls the {@link WidgetApi.render} method, and it renders
1418
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1419
+ *
1420
+ * @param {Object} config Config details
1421
+ * @param {Object} config.user The user details
1422
+ * @param {string} config.user.id The user id
1423
+ * @param {string} config.user.accountId The user account id
1424
+ * @param {WidgetType} config.widgetType The content of the widget
1425
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1426
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used
1427
+ * to validate the data (can be disabled)
1428
+ *
1429
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1430
+ */
1431
+ async render(config) {
1432
+ const raw = config;
1433
+ const clean = validatePasswordlessConfig(raw);
1434
+ try {
1435
+ const response = await this.api.render(clean);
1436
+ return {
1437
+ widget: this._renderWidget(response, clean, {
1438
+ type: "passwordless",
1439
+ engagementMedium: clean.engagementMedium,
1440
+ container: clean.container,
1441
+ trigger: clean.trigger
1442
+ }),
1443
+ user: response.user
1444
+ };
1445
+ } catch (err) {
1446
+ if (err.apiErrorCode) {
1447
+ this._renderErrorWidget(err, clean.engagementMedium);
1448
+ }
1449
+ throw new Error(err);
1450
+ }
1451
+ }
1452
+ /**
1453
+ * Autofills a referral code into an element when someone has been referred.
1454
+ * Uses {@link WidgetApi.squatchReferralCookie} behind the scenes.
1455
+ *
1456
+ * @param selector Element class/id selector, or a callback function
1457
+ * @returns
1458
+ */
1459
+ async autofill(selector) {
1460
+ const input = selector;
1461
+ if (typeof input === "function") {
1462
+ try {
1463
+ const response = await this.api.squatchReferralCookie();
1464
+ input(response);
1465
+ } catch (e) {
1466
+ _log$5("Autofill error", e);
1467
+ throw new Error(e);
1468
+ }
1469
+ return;
1470
+ }
1471
+ if (typeof input !== "string")
1472
+ throw new Error("Autofill accepts a string or function");
1473
+ let elems = document.querySelectorAll(input);
1474
+ let elem;
1475
+ if (elems.length > 0) {
1476
+ elem = elems[0];
1477
+ } else {
1478
+ _log$5("Element id/class or function missing");
1479
+ throw new Error("Element id/class or function missing");
1480
+ }
1481
+ try {
1482
+ const response = await this.api.squatchReferralCookie();
1483
+ elem.value = response.codes[0];
1484
+ } catch (e) {
1485
+ throw new Error(e);
1486
+ }
1487
+ }
1488
+ /**
1489
+ * @hidden
1490
+ * @param {Object} response The json object return from the WidgetApi
1491
+ * @param {Object} config Config details
1492
+ * @param {string} config.widgetType The widget type (REFERRER_WIDGET, CONVERSION_WIDGET)
1493
+ * @param {string} config.engagementMedium (POPUP, EMBED)
1494
+ * @returns {Widget} widget (PopupWidget or EmbedWidget)
1495
+ */
1496
+ _renderWidget(response, config, context) {
1497
+ var _a2;
1498
+ _log$5("Rendering Widget...");
1499
+ if (!response) throw new Error("Unable to get a response");
1500
+ let widget2;
1501
+ let displayOnLoad = !!config.displayOnLoad;
1502
+ const opts = response.jsOptions || {};
1503
+ const params = {
1504
+ content: response.template,
1505
+ type: config.widgetType || ((_a2 = opts.widget) == null ? void 0 : _a2.defaultWidgetType),
1506
+ api: this.api,
1507
+ domain: this.domain,
1508
+ npmCdn: this.npmCdn,
1509
+ context
1510
+ };
1511
+ if (opts.widgetUrlMappings) {
1512
+ opts.widgetUrlMappings.forEach((rule) => {
1513
+ var _a3, _b;
1514
+ if (Widgets._matchesUrl(rule.url)) {
1515
+ if (rule.widgetType !== "CONVERSION_WIDGET" || ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code)) {
1516
+ displayOnLoad = rule.displayOnLoad;
1517
+ _log$5(`Display ${rule.widgetType} on ${rule.url}`);
1518
+ } else {
1519
+ _log$5(
1520
+ `Don't display ${rule.widgetType} when no referral on widget rule match ${rule.url}`
1521
+ );
1522
+ }
1523
+ }
1524
+ });
1525
+ }
1526
+ if (opts.fuelTankAutofillUrls) {
1527
+ _log$5("We found a fuel tank autofill!");
1528
+ opts.fuelTankAutofillUrls.forEach(({ url, formSelector }) => {
1529
+ var _a3, _b, _c;
1530
+ if (Widgets._matchesUrl(url)) {
1531
+ _log$5("Fuel Tank URL matches");
1532
+ if ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code) {
1533
+ const formAutofill = document.querySelector(formSelector);
1534
+ if (formAutofill) {
1535
+ formAutofill.value = ((_c = response.user.referredBy.referredReward) == null ? void 0 : _c.fuelTankCode) || "";
1536
+ } else {
1537
+ _log$5(
1538
+ new Error(
1539
+ `Element with id/class ${formSelector} was not found.`
1540
+ )
1541
+ );
1542
+ }
1543
+ }
1544
+ }
1545
+ });
1546
+ }
1547
+ if (config.engagementMedium === "EMBED") {
1548
+ widget2 = this._renderEmbedWidget(params);
1549
+ } else {
1550
+ widget2 = this._renderPopupWidget(params);
1551
+ if (displayOnLoad) widget2.open();
1552
+ }
1553
+ return widget2;
1554
+ }
1555
+ _renderPopupWidget(params) {
1556
+ const widget2 = new PopupWidget(params, params.context.trigger);
1557
+ widget2.load();
1558
+ return widget2;
1559
+ }
1560
+ _renderEmbedWidget(params) {
1561
+ const widget2 = new EmbedWidget(params, params.context.container);
1562
+ widget2.load();
1563
+ return widget2;
1564
+ }
1565
+ /**
1566
+ * @hidden
1567
+ * @param {Object} error The json object containing the error details
1568
+ * @param {string} em The engagementMedium
1569
+ * @returns {void}
1570
+ */
1571
+ _renderErrorWidget(props, em = "POPUP") {
1572
+ const { apiErrorCode, rsCode, message } = props;
1573
+ _log$5(new Error(`${apiErrorCode} (${rsCode}) ${message}`));
1574
+ const params = {
1575
+ content: "error",
1576
+ rsCode,
1577
+ api: this.api,
1578
+ domain: this.domain,
1579
+ npmCdn: this.npmCdn,
1580
+ type: "ERROR_WIDGET",
1581
+ context: { type: "error" }
1582
+ };
1583
+ let widget2;
1584
+ if (em === "EMBED") {
1585
+ widget2 = new EmbedWidget(params);
1586
+ widget2.load();
1587
+ } else if (em === "POPUP") {
1588
+ widget2 = new PopupWidget(params);
1589
+ widget2.load();
1590
+ }
1591
+ }
1592
+ /**
1593
+ * @hidden
1594
+ * @param {string} rule A regular expression
1595
+ * @returns {boolean} true if rule matches Url, false otherwise
1596
+ */
1597
+ static _matchesUrl(rule) {
1598
+ return window.location.href.match(new RegExp(rule)) ? true : false;
1599
+ }
1600
+ }
1601
+ class EventsApi {
1602
+ /**
1603
+ * Initialize a new {@link EventsApi} instance.
1604
+ *
1605
+ * @param {ConfigOptions} config Config details
1606
+ *
1607
+ * @example <caption>Browser example</caption>
1608
+ * var squatchApi = new squatch.EventsApi({tenantAlias:'test_12b5bo1b25125'});
1609
+ *
1610
+ * @example <caption>Browserify/Webpack example</caption>
1611
+ * var EventsApi = require('@saasquatch/squatch-js').EventsApi;
1612
+ * var squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1613
+ *
1614
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1615
+ * import {EventsApi} from '@saasquatch/squatch-js';
1616
+ * let squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1617
+ */
1618
+ constructor(config) {
1619
+ __publicField(this, "tenantAlias");
1620
+ __publicField(this, "domain");
1621
+ const raw = config;
1622
+ const clean = validateConfig(raw);
1623
+ this.tenantAlias = clean.tenantAlias;
1624
+ this.domain = clean.domain;
1625
+ }
1626
+ /**
1627
+ * Track an event for a user
1628
+ *
1629
+ * @param params Parameters for request
1630
+ * @param options.jwt the JSON Web Token (JWT) that is used to authenticate the user
1631
+ *
1632
+ * @return An ID to confirm the event has been accepted for asynchronous processing
1633
+ */
1634
+ track(params, options) {
1635
+ const raw = params;
1636
+ const rawOpts = options;
1637
+ const body = _validateEvent(raw);
1638
+ const { jwt } = _validateTrackOptions(rawOpts);
1639
+ const ta = encodeURIComponent(this.tenantAlias);
1640
+ const userId = encodeURIComponent(body.userId);
1641
+ const accountId = encodeURIComponent(body.accountId);
1642
+ const path = `/api/v1/${ta}/open/account/${accountId}/user/${userId}/events`;
1643
+ const url = this.domain + path;
1644
+ return doPost(url, JSON.stringify(body), jwt);
1645
+ }
1646
+ }
1647
+ function _validateEvent(raw) {
1648
+ if (!isObject$1(raw)) throw new Error("tracking parameter must be an object");
1649
+ if (!(raw == null ? void 0 : raw["accountId"])) throw new Error("accountId field is required");
1650
+ if (!(raw == null ? void 0 : raw["events"])) throw new Error("events field is required");
1651
+ if (!(raw == null ? void 0 : raw["userId"])) throw new Error("userId field is required");
1652
+ const clean = raw;
1653
+ if (!Array.isArray(clean.events))
1654
+ throw new Error("'events' should be an array");
1655
+ return clean;
1656
+ }
1657
+ function _validateTrackOptions(raw) {
1658
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
1659
+ return raw;
1660
+ }
1661
+ function asyncLoad() {
1662
+ var _a2;
1663
+ const namespace = window[IMPACT_NAMESPACE] ? IMPACT_NAMESPACE : DEFAULT_NAMESPACE;
1664
+ const cached = ((_a2 = window["_" + namespace]) == null ? void 0 : _a2.ready) || [];
1665
+ const declarativeCache = window.impactOnReady || window.squatchOnReady;
1666
+ const readyFns = [...cached, declarativeCache].filter((a) => !!a);
1667
+ setTimeout(() => {
1668
+ if (!window[DEFAULT_NAMESPACE]) return;
1669
+ window[IMPACT_NAMESPACE] = window[DEFAULT_NAMESPACE];
1670
+ readyFns.forEach((cb) => cb());
1671
+ window[DEFAULT_NAMESPACE]._auto();
1672
+ window["_" + namespace] = void 0;
1673
+ delete window["_" + namespace];
1674
+ }, 0);
1675
+ }
1676
+ const _log$4 = browserExports.debug("squatch-js");
1677
+ const isObject = (item) => typeof item === "object" && !Array.isArray(item);
1678
+ const deepMerge = (target, source) => {
1679
+ const isDeep = (prop) => isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
1680
+ const replaced = Object.getOwnPropertyNames(source).map((prop) => ({
1681
+ [prop]: isDeep(prop) ? deepMerge(target[prop], source[prop]) : source[prop]
1682
+ })).reduce((a, b) => ({ ...a, ...b }), {});
1683
+ return {
1684
+ ...target,
1685
+ ...replaced
1686
+ };
1687
+ };
1688
+ function b64decode(input) {
1689
+ const binary = atob(input.replace(/_/g, "/").replace(/-/g, "+"));
1690
+ const bytes = new Uint8Array(binary.length);
1691
+ for (let i = 0; i < binary.length; i++) {
1692
+ bytes[i] = binary.charCodeAt(i);
1693
+ }
1694
+ return new TextDecoder("utf8").decode(bytes);
1695
+ }
1696
+ function b64encode(input) {
1697
+ const encodedInput = new TextEncoder().encode(input);
1698
+ const binary = Array.from(
1699
+ encodedInput,
1700
+ (byte) => String.fromCodePoint(byte)
1701
+ ).join("");
1702
+ return btoa(binary).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
1703
+ }
1704
+ function getTopDomain() {
1705
+ var i, h, weird_cookie = "weird_get_top_level_domain=cookie", hostname = document.location.hostname.split(".");
1706
+ for (i = hostname.length - 1; i >= 0; i--) {
1707
+ h = hostname.slice(i).join(".");
1708
+ document.cookie = weird_cookie + ";domain=." + h + ";";
1709
+ if (document.cookie.indexOf(weird_cookie) > -1) {
1710
+ document.cookie = weird_cookie.split("=")[0] + "=;domain=." + h + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
1711
+ return h;
1712
+ }
1713
+ }
1714
+ }
1715
+ function _pushCookie() {
1716
+ const queryString = window.location.search;
1717
+ const urlParams = new URLSearchParams(queryString);
1718
+ const refParam = urlParams.get("_saasquatch") || "";
1719
+ if (refParam) {
1720
+ let paramsJSON = "", existingCookie = "", reEncodedCookie = "";
1721
+ try {
1722
+ paramsJSON = JSON.parse(b64decode(refParam));
1723
+ } catch (error) {
1724
+ _log$4("Unable to decode params", error);
1725
+ return;
1726
+ }
1727
+ try {
1728
+ existingCookie = JSON.parse(b64decode(api$1.get("_saasquatch")));
1729
+ _log$4("existing cookie", existingCookie);
1730
+ } catch (error) {
1731
+ _log$4("Unable to retrieve cookie", error);
1732
+ }
1733
+ try {
1734
+ const domain = getTopDomain();
1735
+ _log$4("domain retrieved:", domain);
1736
+ if (existingCookie) {
1737
+ const newCookie = deepMerge(existingCookie, paramsJSON);
1738
+ reEncodedCookie = b64encode(JSON.stringify(newCookie));
1739
+ _log$4("cookie to store:", newCookie);
1740
+ } else {
1741
+ reEncodedCookie = b64encode(JSON.stringify(paramsJSON));
1742
+ _log$4("cookie to store:", paramsJSON);
1743
+ }
1744
+ api$1.set("_saasquatch", reEncodedCookie, {
1745
+ expires: 365,
1746
+ secure: false,
1747
+ sameSite: "Lax",
1748
+ domain,
1749
+ path: "/"
1750
+ });
1751
+ } catch (error) {
1752
+ _log$4("Unable to set cookie", error);
1753
+ }
1754
+ }
1755
+ }
1756
+ const _log$3 = browserExports.debug("squatch-js");
1757
+ function _getAutoConfig(configIn) {
1758
+ const queryString = window.location.search;
1759
+ const urlParams = new URLSearchParams(queryString);
1760
+ const refParam = urlParams.get("_saasquatchExtra") || "";
1761
+ if (!refParam) {
1762
+ _log$3("No _saasquatchExtra param");
1763
+ return;
1764
+ }
1765
+ let raw;
1766
+ try {
1767
+ raw = JSON.parse(b64decode(refParam));
1768
+ } catch (e) {
1769
+ _log$3("Unable to decode _saasquatchExtra config");
1770
+ return;
1771
+ }
1772
+ const { domain, tenantAlias, widgetConfig } = convertExtraToConfig(raw);
1773
+ if (!domain || !tenantAlias || !widgetConfig) {
1774
+ _log$3("_saasquatchExtra did not have an expected structure");
1775
+ return void 0;
1776
+ }
1777
+ const { autoPopupWidgetType, ...rest } = widgetConfig;
1778
+ return {
1779
+ widgetConfig: {
1780
+ widgetType: autoPopupWidgetType,
1781
+ displayOnLoad: true,
1782
+ ...rest
1783
+ },
1784
+ squatchConfig: {
1785
+ ...configIn ? { configIn } : {},
1786
+ domain,
1787
+ tenantAlias
1788
+ }
1789
+ };
1790
+ }
1791
+ function convertExtraToConfig(obj) {
1792
+ var _a2;
1793
+ const _domain = Object.keys(obj || {})[0];
1794
+ const tenantAlias = Object.keys((obj == null ? void 0 : obj[_domain]) || {})[0];
1795
+ const widgetConfig = (_a2 = obj == null ? void 0 : obj[_domain]) == null ? void 0 : _a2[tenantAlias];
1796
+ const domain = _domain ? `https://${_domain}` : void 0;
1797
+ return { domain, tenantAlias, widgetConfig };
1798
+ }
1799
+ const _log$2 = browserExports.debug("squatch-js:decodeUserJwt");
1800
+ function decodeUserJwt(tokenStr) {
1801
+ var _a2;
1802
+ try {
1803
+ const base64Url = tokenStr.split(".")[1];
1804
+ if (base64Url === void 0) return null;
1805
+ const jsonStr = b64decode(base64Url);
1806
+ return (_a2 = JSON.parse(jsonStr)) == null ? void 0 : _a2.user;
1807
+ } catch (e) {
1808
+ _log$2(e);
1809
+ return null;
1810
+ }
1811
+ }
1812
+ const _log$1 = debug("squatch-js:DeclarativeWidget");
1813
+ class DeclarativeWidget extends HTMLElement {
1814
+ constructor() {
1815
+ super();
1816
+ /**
1817
+ * Configuration overrides
1818
+ * @default window.squatchConfig
1819
+ */
1820
+ __publicField(this, "config");
1821
+ /**
1822
+ * Signed JWT containing user information
1823
+ * @default window.squatchToken
1824
+ */
1825
+ __publicField(this, "token");
1826
+ /**
1827
+ * Tenant alias of SaaSquatch tenant
1828
+ * @default window.squatchTenant
1829
+ */
1830
+ __publicField(this, "tenant");
1831
+ /**
1832
+ * widgetType of widget to load
1833
+ */
1834
+ __publicField(this, "widgetType");
1835
+ /**
1836
+ * Locale to render the widget in
1837
+ */
1838
+ __publicField(this, "locale");
1839
+ /**
1840
+ * Instance of {@link WidgetApi}
1841
+ */
1842
+ __publicField(this, "widgetApi");
1843
+ /**
1844
+ * Instance of {@link AnalyticsApi}
1845
+ */
1846
+ __publicField(this, "analyticsApi");
1847
+ /**
1848
+ * Instance of {@link EmbedWidget} or {@link PopupWidget}
1849
+ */
1850
+ __publicField(this, "widgetInstance");
1851
+ /**
1852
+ * Determines whether to render the widget as an embedding widget or popup widget
1853
+ */
1854
+ __publicField(this, "type");
1855
+ /**
1856
+ * Container element to contain the widget iframe
1857
+ * @default this
1858
+ */
1859
+ __publicField(this, "container");
1860
+ __publicField(this, "element");
1861
+ /**
1862
+ * Flag for if the component has been loaded or not
1863
+ * @hidden
1864
+ */
1865
+ __publicField(this, "loaded");
1866
+ __publicField(this, "_setWidget", (template, config) => {
1867
+ var _a2;
1868
+ const params = {
1869
+ api: this.widgetApi,
1870
+ content: template,
1871
+ context: {
1872
+ type: config.type,
1873
+ user: config.user,
1874
+ container: this.container || void 0,
1875
+ engagementMedium: this.type
1876
+ },
1877
+ type: this.widgetType,
1878
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
1879
+ npmCdn: DEFAULT_NPM_CDN,
1880
+ container: this
1881
+ };
1882
+ if (this.type === "EMBED") {
1883
+ return new EmbedWidget(params);
1884
+ } else {
1885
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
1886
+ return new PopupWidget(params, useFirstChildTrigger);
1887
+ }
1888
+ });
1889
+ /**
1890
+ * Builds a Widget instance for the default error widget
1891
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
1892
+ */
1893
+ __publicField(this, "setErrorWidget", (e) => {
1894
+ var _a2;
1895
+ const params = {
1896
+ api: this.widgetApi,
1897
+ content: "error",
1898
+ context: {
1899
+ type: "error",
1900
+ container: this.container || void 0
1901
+ },
1902
+ type: "ERROR_WIDGET",
1903
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
1904
+ npmCdn: DEFAULT_NPM_CDN,
1905
+ container: this
1906
+ };
1907
+ if (this.type === "EMBED") {
1908
+ return new EmbedWidget(params);
1909
+ } else {
1910
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
1911
+ return new PopupWidget(params, useFirstChildTrigger);
1912
+ }
1913
+ });
1914
+ __publicField(this, "reload", this.renderWidget);
1915
+ __publicField(this, "show", this.open);
1916
+ __publicField(this, "hide", this.close);
1917
+ this.attachShadow({
1918
+ mode: "open"
1919
+ }).innerHTML = `<style>:host { display: block; }</style><slot></slot>`;
1920
+ this.config = getConfig();
1921
+ this.token = getToken();
1922
+ this.tenant = window.squatchTenant;
1923
+ this.container = this;
1924
+ }
1925
+ _setupApis(config) {
1926
+ var _a2, _b;
1927
+ if (!this.tenant) throw new Error("tenantAlias not provided");
1928
+ this.widgetApi = new WidgetApi({
1929
+ tenantAlias: (config == null ? void 0 : config.tenantAlias) || this.tenant,
1930
+ domain: (config == null ? void 0 : config.domain) || ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN
1931
+ });
1932
+ this.analyticsApi = new AnalyticsApi({
1933
+ domain: (config == null ? void 0 : config.domain) || ((_b = this.config) == null ? void 0 : _b.domain) || DEFAULT_DOMAIN
1934
+ });
1935
+ }
1936
+ async renderPasswordlessVariant() {
1937
+ this._setupApis();
1938
+ _log$1("Rendering as an Instant Access widget");
1939
+ return await this.widgetApi.render({
1940
+ engagementMedium: this.type,
1941
+ widgetType: this.widgetType,
1942
+ locale: this.locale
1943
+ }).then((res) => this._setWidget(res.template, { type: "passwordless" })).catch(this.setErrorWidget);
1944
+ }
1945
+ async renderUserUpsertVariant() {
1946
+ this._setupApis();
1947
+ const userObj = decodeUserJwt(this.token);
1948
+ if (!userObj) {
1949
+ return this.setErrorWidget(Error("No user object in token."));
1950
+ }
1951
+ _log$1("Rendering as a Verified widget");
1952
+ const widgetInstance = await this.widgetApi.upsertUser({
1953
+ user: userObj,
1954
+ locale: this.locale,
1955
+ engagementMedium: this.type,
1956
+ widgetType: this.widgetType,
1957
+ jwt: this.token
1958
+ }).then(
1959
+ (res) => this._setWidget(res.template, { type: "upsert", user: userObj })
1960
+ ).catch(this.setErrorWidget);
1961
+ return widgetInstance;
1962
+ }
1963
+ /**
1964
+ * Fetches widget content from SaaSquatch and builds a Widget instance to support rendering the widget in the DOM
1965
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
1966
+ * @throws Throws an Error if `widgetType` is undefined
1967
+ */
1968
+ async getWidgetInstance() {
1969
+ let widgetInstance;
1970
+ this.widgetType = this.getAttribute("widget") || void 0;
1971
+ this.locale = this.getAttribute("locale") || this.locale;
1972
+ if (!this.widgetType) throw new Error("No widget has been specified");
1973
+ if (!this.token) {
1974
+ widgetInstance = await this.renderPasswordlessVariant();
1975
+ } else {
1976
+ widgetInstance = await this.renderUserUpsertVariant();
1977
+ }
1978
+ this.widgetInstance = widgetInstance;
1979
+ if (this.widgetInstance)
1980
+ this.dispatchEvent(new CustomEvent("sq:widget-loaded"));
1981
+ return widgetInstance;
1982
+ }
1983
+ /**
1984
+ * Calls {@link getWidgetInstance} to build the Widget instance and loads the widget iframe into the DOM
1985
+ */
1986
+ async renderWidget() {
1987
+ await this.getWidgetInstance();
1988
+ await this.widgetInstance.load();
1989
+ }
1990
+ /**
1991
+ * Calls `open` method of `widgetInstance`
1992
+ * @throws Throws an Error if called before the widget has loaded
1993
+ */
1994
+ open() {
1995
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
1996
+ this.widgetInstance.open();
1997
+ }
1998
+ /**
1999
+ * Calls `close` method of `widgetInstance`
2000
+ * @throws Throws an Error if called before the widget has loaded
2001
+ */
2002
+ close() {
2003
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
2004
+ this.widgetInstance.close();
2005
+ }
2006
+ }
2007
+ class DeclarativeEmbedWidget extends DeclarativeWidget {
2008
+ constructor() {
2009
+ super();
2010
+ this.type = "EMBED";
2011
+ this.loaded = false;
2012
+ }
2013
+ static get observedAttributes() {
2014
+ return ["widget", "locale"];
2015
+ }
2016
+ attributeChangedCallback(attr, oldVal, newVal) {
2017
+ if (oldVal === newVal || !this.loaded) return;
2018
+ switch (attr) {
2019
+ case "locale":
2020
+ case "widget":
2021
+ this.connectedCallback();
2022
+ break;
2023
+ }
2024
+ }
2025
+ async connectedCallback() {
2026
+ var _a2, _b;
2027
+ this.loaded = true;
2028
+ this.container = this.getAttribute("container");
2029
+ await this.renderWidget();
2030
+ const slot = (_a2 = this.shadowRoot && Array.from(this.shadowRoot.children)) == null ? void 0 : _a2.find((c) => c.tagName === "SLOT");
2031
+ if (slot) (_b = this.shadowRoot) == null ? void 0 : _b.removeChild(slot);
2032
+ if (this.getAttribute("open") !== null) this.open();
2033
+ }
2034
+ }
2035
+ class DeclarativePopupWidget extends DeclarativeWidget {
2036
+ constructor() {
2037
+ super();
2038
+ this.type = "POPUP";
2039
+ this.loaded = false;
2040
+ this.addEventListener("click", (e) => {
2041
+ e.stopPropagation();
2042
+ this.open();
2043
+ });
2044
+ }
2045
+ static get observedAttributes() {
2046
+ return ["widget", "locale"];
2047
+ }
2048
+ attributeChangedCallback(attr, oldVal, newVal) {
2049
+ if (oldVal === newVal || !this.loaded) return;
2050
+ switch (attr) {
2051
+ case "locale":
2052
+ case "widget":
2053
+ this.connectedCallback();
2054
+ break;
2055
+ }
2056
+ }
2057
+ async connectedCallback() {
2058
+ this.loaded = true;
2059
+ this.container = this.getAttribute("container");
2060
+ await this.renderWidget();
2061
+ if (this.getAttribute("open") !== null) this.open();
2062
+ }
2063
+ }
2064
+ class SquatchEmbed extends DeclarativeEmbedWidget {
2065
+ }
2066
+ class SquatchPopup extends DeclarativePopupWidget {
2067
+ }
2068
+ class ImpactEmbed extends DeclarativeEmbedWidget {
2069
+ }
2070
+ class ImpactPopup extends DeclarativePopupWidget {
2071
+ }
2072
+ if (!window.customElements.get("squatch-embed"))
2073
+ window.customElements.define("squatch-embed", SquatchEmbed);
2074
+ if (!window.customElements.get("impact-embed"))
2075
+ window.customElements.define("impact-embed", ImpactEmbed);
2076
+ if (!window.customElements.get("squatch-popup"))
2077
+ window.customElements.define("squatch-popup", SquatchPopup);
2078
+ if (!window.customElements.get("impact-popup"))
2079
+ window.customElements.define("impact-popup", ImpactPopup);
2080
+ function help() {
2081
+ console.log(
2082
+ `Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.`
2083
+ );
2084
+ }
2085
+ const _log = browserExports.debug("squatch-js");
2086
+ let _api = null;
2087
+ let _widgets = null;
2088
+ let _events = null;
2089
+ function api() {
2090
+ if (!_api) init({});
2091
+ return _api;
2092
+ }
2093
+ function widgets() {
2094
+ if (!_widgets) init({});
2095
+ return _widgets;
2096
+ }
2097
+ function events() {
2098
+ if (!_events) init({});
2099
+ return _events;
2100
+ }
2101
+ function widget(widgetConfig) {
2102
+ var _a2;
2103
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2104
+ }
2105
+ function _auto(configIn) {
2106
+ var _a2;
2107
+ const configs = _getAutoConfig(configIn);
2108
+ if (configs) {
2109
+ const { squatchConfig, widgetConfig } = configs;
2110
+ init(squatchConfig);
2111
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2112
+ }
2113
+ }
2114
+ function init(configIn) {
2115
+ const raw = configIn;
2116
+ const config = validateConfig(raw);
2117
+ if (config.tenantAlias.match("^test") || config.debug) {
2118
+ browserExports.debug.enable("squatch-js*");
2119
+ } else {
2120
+ browserExports.debug.disable();
2121
+ }
2122
+ _log("initializing ...");
2123
+ _api = new WidgetApi(config);
2124
+ _widgets = new Widgets(config);
2125
+ _events = new EventsApi(config);
2126
+ _log("Widget API instance", _api);
2127
+ _log("Widgets instance", _widgets);
2128
+ _log("Events API instance", _events);
2129
+ }
2130
+ function ready(fn) {
2131
+ fn();
2132
+ }
2133
+ function autofill(selector) {
2134
+ widgets().autofill(selector);
2135
+ }
2136
+ function pushCookie() {
2137
+ _pushCookie();
2138
+ }
2139
+ if (typeof document !== "undefined" && !window.SaaSquatchDoNotAutoDrop) {
2140
+ pushCookie();
2141
+ }
2142
+ if ((_a = window["squatch"]) == null ? void 0 : _a.init)
2143
+ _log(
2144
+ "Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."
2145
+ );
2146
+ if (typeof document !== "undefined") asyncLoad();
2147
+ exports2.DeclarativeEmbedWidget = DeclarativeEmbedWidget;
2148
+ exports2.DeclarativePopupWidget = DeclarativePopupWidget;
2149
+ exports2.EmbedWidget = EmbedWidget;
2150
+ exports2.PopupWidget = PopupWidget;
2151
+ exports2.WidgetApi = WidgetApi;
2152
+ exports2.Widgets = Widgets;
2153
+ exports2._auto = _auto;
2154
+ exports2.api = api;
2155
+ exports2.autofill = autofill;
2156
+ exports2.events = events;
2157
+ exports2.help = help;
2158
+ exports2.init = init;
2159
+ exports2.pushCookie = pushCookie;
2160
+ exports2.ready = ready;
2161
+ exports2.widget = widget;
2162
+ exports2.widgets = widgets;
2163
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2164
+ });
2165
+ //# sourceMappingURL=squatch.js.map