@saasquatch/squatch-js 2.8.3-2 → 2.8.3-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/squatch.js CHANGED
@@ -1,4 +1,612 @@
1
- (function(u,m){typeof exports=="object"&&typeof module<"u"?m(exports):(u=typeof globalThis<"u"?globalThis:u||self,m(u.squatch={}))})(this,function(u){"use strict";var ot=Object.defineProperty;var st=(u,m,A)=>m in u?ot(u,m,{enumerable:!0,configurable:!0,writable:!0,value:A}):u[m]=A;var l=(u,m,A)=>st(u,typeof m!="symbol"?m+"":m,A);var ge;let m=null;function A(o){const e=o.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");m=new RegExp(`^${e}$`)}function be(){m=null}function E(o){const t=(...e)=>{m&&m.test(o)&&console.log(`[${o}]`,...e)};return Object.defineProperty(t,"enabled",{get(){return!!(m&&m.test(o))}}),t}/*! js-cookie v3.0.5 | MIT */function O(o){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var n in e)o[n]=e[n]}return o}var Ee={read:function(o){return o[0]==='"'&&(o=o.slice(1,-1)),o.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(o){return encodeURIComponent(o).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Q(o,t){function e(i,s,r){if(!(typeof document>"u")){r=O({},t,r),typeof r.expires=="number"&&(r.expires=new Date(Date.now()+r.expires*864e5)),r.expires&&(r.expires=r.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var d in r)r[d]&&(a+="; "+d,r[d]!==!0&&(a+="="+r[d].split(";")[0]));return document.cookie=i+"="+o.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],r={},a=0;a<s.length;a++){var d=s[a].split("="),c=d.slice(1).join("=");try{var h=decodeURIComponent(d[0]);if(r[h]=o.read(c,h),i===h)break}catch{}}return i?r[i]:r}}return Object.create({set:e,get:n,remove:function(i,s){e(i,"",O({},s,{expires:-1}))},withAttributes:function(i){return Q(this.converter,O({},this.attributes,i))},withConverter:function(i){return Q(O({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(o)}})}var j=Q(Ee,{path:"/"});const I="https://app.referralsaasquatch.com",Y="https://fast.ssqt.io/npm",D="squatch",K="impact";function W(o){if(typeof o!="object")throw new Error("config must be an object");const t=window.squatchTenant,e=Z(),n={tenantAlias:(o==null?void 0:o.tenantAlias)||t,domain:(o==null?void 0:o.domain)||(e==null?void 0:e.domain),npmCdn:(o==null?void 0:o.npmCdn)||(e==null?void 0:e.npmCdn),debug:(o==null?void 0:o.debug)||(e==null?void 0:e.debug)};if(typeof n.tenantAlias!="string")throw new Error("tenantAlias not provided");const i=n.tenantAlias,s=typeof n.domain=="string"&&n.domain||I,r=typeof n.debug=="boolean"&&n.debug||!1,a=typeof n.npmCdn=="string"&&n.npmCdn||Y;return{tenantAlias:i,domain:s,debug:r,npmCdn:a}}function _(o){return typeof o=="object"&&!Array.isArray(o)&&o!==null}function xe(o){if(o&&/^[a-z]{2}_(?:[A-Z]{2}|[0-9]{3})$/.test(o))return o}function oe(o){if(!_(o))throw new Error("Widget properties must be an object");if(!(o!=null&&o.user))throw new Error("Required properties missing.");return o}function se(o){if(!_(o))throw new Error("Widget properties must be an object");return o}function $(){return window.impactToken||window.squatchToken}function Z(){return window.impactConfig||window.squatchConfig}async function Ce(o,t,e,n){const i=n||$(),s={Accept:"application/json","Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{},"X-SaaSquatch-Referrer":window?window.location.href:""};try{const r=await fetch(o,{method:"POST",body:JSON.stringify({query:t,variables:e}),headers:s});if(!r.ok)throw new Error(await r.text());return await r.json()}catch(r){throw r}}async function Ae(o,t=""){const e={Accept:"application/json","Content-Type":"application/json"},n=t||$();n&&(e["X-SaaSquatch-User-Token"]=n);try{const i=await fetch(o,{method:"GET",credentials:"include",headers:e}),s=await i.text();if(!i.ok)throw new Error(s);return s&&JSON.parse(s)}catch(i){throw i}}async function ee(o,t,e){const n={Accept:"application/json","Content-Type":"application/json"},i=e||$();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{method:"POST",body:t,headers:n}),r=await s.text();if(!s.ok)throw new Error(r);return r&&JSON.parse(r)}catch(s){throw s}}async function Ie(o,t,e){const n={Accept:"application/json","Content-Type":"application/json","X-SaaSquatch-Referrer":window?window.location.href:""},i=e||$();i&&(n["X-SaaSquatch-User-Token"]=i);try{const s=await fetch(o,{headers:n,method:"PUT",credentials:"include",body:t}),r=await s.text();if(!s.ok)throw new Error(r);return r&&JSON.parse(r)}catch(s){throw s}}const _e=`
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,10 +620,1357 @@
12
620
  }
13
621
  }
14
622
  }
15
- `;class N{constructor(t){l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");l(this,"referralCookie",this.squatchReferralCookie);const n=W(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain,this.npmCdn=n.npmCdn}upsertUser(t){const n=oe(t),{widgetType:i,engagementMedium:s="POPUP",jwt:r,locale:a,user:d}=n,c=encodeURIComponent(this.tenantAlias),h=d.accountId?encodeURIComponent(d.accountId):null,p=d.id?encodeURIComponent(d.id):null,g=Te({widgetType:i,engagementMedium:s,locale:a}),w=`/api/v1/${c}/widget/account/${h}/user/${p}/upsert${g}`,f=this.domain+w,b=(j||window.Cookies).get("_saasquatch");return b&&(d.cookies=b),Ie(f,JSON.stringify(d),r)}render(t){const n=se(t),{widgetType:i,engagementMedium:s="POPUP",jwt:r,user:a}=n,d=encodeURIComponent(this.tenantAlias),c=a!=null&&a.accountId?encodeURIComponent(a.accountId):null,h=a!=null&&a.id?encodeURIComponent(a.id):null,p=n.locale??xe(navigator.language.replace(/\-/g,"_")),g=`/api/v1/${d}/graphql`,w=this.domain+g;return new Promise(async(f,b)=>{var x;try{const y=await Ce(w,_e,{user:h&&c?{id:h,accountId:c}:null,engagementMedium:s,widgetType:i,locale:p},r);f((x=y==null?void 0:y.data)==null?void 0:x.renderWidget)}catch(y){b(y)}})}async squatchReferralCookie(){const t=encodeURIComponent(this.tenantAlias),e=(j||window.Cookies).get("_saasquatch")||"",n=e?`?cookies=${encodeURIComponent(e)}`:"",i=`${this.domain}/a/${t}/widgets/squatchcookiejson${n}`,s=await Ae(i);return Promise.resolve({...s,encodedCookie:e})}}function Te({widgetType:o,engagementMedium:t,locale:e}){const n=new URLSearchParams;return n.append("engagementMedium",t),o&&n.append("widgetType",o),e&&n.append("locale",e),`?${n.toString()}`}/*!
16
- * domready (c) Dustin Diaz 2014 - License MIT
17
- *
18
- */function te(o,t){let e=[],n,i=o,s=i.documentElement.doScroll,r="DOMContentLoaded",a=(s?/^loaded|^c/:/^loaded|^i|^c/).test(i.readyState);return a||i.addEventListener(r,n=()=>{for(i.removeEventListener(r,n),a=!0;n=e.shift();)n()}),a?setTimeout(t,0):e.push(t)}function F({value:o,unit:t}){switch(t){case"px":return`${o}px`;case"%":return`${o}%`;default:return`${o}px`}}class re{constructor(t){l(this,"domain");var i;const n=We(t);this.domain=(n==null?void 0:n.domain)||((i=Z())==null?void 0:i.domain)||I}pushAnalyticsLoadEvent(t){if(!t.externalUserId||!t.externalAccountId)return;const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=t.programId?`&programId=${encodeURIComponent(t.programId)}`:"",a=`/a/${e}/widgets/analytics/loaded?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}${r}`,d=this.domain+a;return ee(d,JSON.stringify({}))}pushAnalyticsShareClickedEvent(t){const e=encodeURIComponent(t.tenantAlias),n=encodeURIComponent(t.externalAccountId),i=encodeURIComponent(t.externalUserId),s=encodeURIComponent(t.engagementMedium),r=encodeURIComponent(t.shareMedium),a=`/a/${e}/widgets/analytics/shared?externalAccountId=${n}&externalUserId=${i}&engagementMedium=${s}&shareMedium=${r}`,d=this.domain+a;return ee(d,JSON.stringify({}))}}function We(o){if(!_(o))throw new Error("'options' should be an object");return o}const ae=({type:o="verified-access",height:t="500px"})=>{const e="#e0e0e0";return`
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
+ console.log({ params });
708
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
709
+ const accountId = (user == null ? void 0 : user.accountId) ? encodeURIComponent(user.accountId) : null;
710
+ const userId = (user == null ? void 0 : user.id) ? encodeURIComponent(user.id) : null;
711
+ const locale = clean.locale ?? validateLocale(navigator.language.replace(/\-/g, "_"));
712
+ const path = `/api/v1/${tenantAlias}/graphql`;
713
+ const url = this.domain + path;
714
+ return new Promise(async (resolve, reject) => {
715
+ var _a2;
716
+ try {
717
+ const res = await doQuery(
718
+ url,
719
+ RENDER_WIDGET_QUERY,
720
+ {
721
+ user: userId && accountId ? { id: userId, accountId } : null,
722
+ engagementMedium,
723
+ widgetType,
724
+ locale
725
+ },
726
+ jwt
727
+ );
728
+ resolve((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.renderWidget);
729
+ } catch (e) {
730
+ reject(e);
731
+ }
732
+ });
733
+ }
734
+ /**
735
+ * Looks up the referral code of the current user, if there is any.
736
+ *
737
+ * @return {Promise<ReferralCookie>} code referral code if true.
738
+ */
739
+ async squatchReferralCookie() {
740
+ const tenantAlias = encodeURIComponent(this.tenantAlias);
741
+ const _saasquatch = (api$1 || window.Cookies).get("_saasquatch") || "";
742
+ const cookie = _saasquatch ? `?cookies=${encodeURIComponent(_saasquatch)}` : ``;
743
+ const url = `${this.domain}/a/${tenantAlias}/widgets/squatchcookiejson${cookie}`;
744
+ const response = await doGet(url);
745
+ return Promise.resolve({
746
+ ...response,
747
+ encodedCookie: _saasquatch
748
+ });
749
+ }
750
+ }
751
+ function _buildParams({
752
+ widgetType,
753
+ engagementMedium,
754
+ locale
755
+ }) {
756
+ const queryParams = new URLSearchParams();
757
+ queryParams.append("engagementMedium", engagementMedium);
758
+ if (widgetType) queryParams.append("widgetType", widgetType);
759
+ if (locale) queryParams.append("locale", locale);
760
+ return `?${queryParams.toString()}`;
761
+ }
762
+ /*!
763
+ * domready (c) Dustin Diaz 2014 - License MIT
764
+ *
765
+ */
766
+ function domready(targetDoc, fn) {
767
+ let fns = [];
768
+ let listener;
769
+ let doc = targetDoc;
770
+ let hack = doc.documentElement.doScroll;
771
+ let domContentLoaded = "DOMContentLoaded";
772
+ let loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState);
773
+ if (!loaded)
774
+ doc.addEventListener(
775
+ domContentLoaded,
776
+ listener = () => {
777
+ doc.removeEventListener(domContentLoaded, listener);
778
+ loaded = true;
779
+ while (listener = fns.shift()) listener();
780
+ }
781
+ );
782
+ return loaded ? setTimeout(fn, 0) : fns.push(fn);
783
+ }
784
+ function formatWidth({
785
+ value,
786
+ unit
787
+ }) {
788
+ switch (unit) {
789
+ case "px":
790
+ return `${value}px`;
791
+ case "%":
792
+ return `${value}%`;
793
+ default:
794
+ return `${value}px`;
795
+ }
796
+ }
797
+ class AnalyticsApi {
798
+ /**
799
+ * Initialize a new {@link AnalyticsApi} instance.
800
+ *
801
+ * @param {Object} config Config details
802
+ * @param {string} [config.domain='https://app.referralsaasquatch.com'] The server domain.
803
+ *
804
+ */
805
+ constructor(config) {
806
+ __publicField(this, "domain");
807
+ var _a2;
808
+ const raw = config;
809
+ const clean = _validateAnalyticsConfig(raw);
810
+ this.domain = (clean == null ? void 0 : clean["domain"]) || ((_a2 = getConfig()) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN;
811
+ }
812
+ pushAnalyticsLoadEvent(params) {
813
+ if (!params.externalUserId || !params.externalAccountId) return;
814
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
815
+ const accountId = encodeURIComponent(params.externalAccountId);
816
+ const userId = encodeURIComponent(params.externalUserId);
817
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
818
+ const programId = params.programId ? `&programId=${encodeURIComponent(params.programId)}` : ``;
819
+ const path = `/a/${tenantAlias}/widgets/analytics/loaded?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}${programId}`;
820
+ const url = this.domain + path;
821
+ return doPost(url, JSON.stringify({}));
822
+ }
823
+ pushAnalyticsShareClickedEvent(params) {
824
+ const tenantAlias = encodeURIComponent(params.tenantAlias);
825
+ const accountId = encodeURIComponent(params.externalAccountId);
826
+ const userId = encodeURIComponent(params.externalUserId);
827
+ const engagementMedium = encodeURIComponent(params.engagementMedium);
828
+ const shareMedium = encodeURIComponent(params.shareMedium);
829
+ const path = `/a/${tenantAlias}/widgets/analytics/shared?externalAccountId=${accountId}&externalUserId=${userId}&engagementMedium=${engagementMedium}&shareMedium=${shareMedium}`;
830
+ const url = this.domain + path;
831
+ return doPost(url, JSON.stringify({}));
832
+ }
833
+ }
834
+ function _validateAnalyticsConfig(raw) {
835
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
836
+ return raw;
837
+ }
838
+ const _log$8 = browserExports.debug("squatch-js:widget");
839
+ class Widget {
840
+ constructor(params) {
841
+ __publicField(this, "type");
842
+ __publicField(this, "content");
843
+ __publicField(this, "analyticsApi");
844
+ __publicField(this, "widgetApi");
845
+ __publicField(this, "context");
846
+ __publicField(this, "npmCdn");
847
+ __publicField(this, "container");
848
+ __publicField(this, "loadEventListener", null);
849
+ var _a2;
850
+ _log$8("widget initializing ...");
851
+ this.content = params.content === "error" ? this._error(params.rsCode) : params.content;
852
+ this.type = params.type;
853
+ this.widgetApi = params.api;
854
+ this.npmCdn = params.npmCdn;
855
+ this.analyticsApi = new AnalyticsApi({ domain: params.domain });
856
+ this.context = params.context;
857
+ this.container = ((_a2 = params.context) == null ? void 0 : _a2.container) || params.container;
858
+ }
859
+ _findElement() {
860
+ let element;
861
+ if (typeof this.container === "string") {
862
+ element = document.querySelector(this.container);
863
+ _log$8("loading widget with selector", element);
864
+ } else if (this.container instanceof HTMLElement) {
865
+ element = this.container;
866
+ _log$8("loading widget with container", element);
867
+ } else if (this.container) {
868
+ element = null;
869
+ _log$8("container must be an HTMLElement or string", this.container);
870
+ } else {
871
+ element = document.querySelector("#squatchembed") || document.querySelector(".squatchembed") || document.querySelector("#impactembed") || document.querySelector(".impactembed");
872
+ _log$8("loading widget with default selector", element);
873
+ }
874
+ if (!(element instanceof HTMLElement))
875
+ throw new Error(
876
+ `element with selector '${this.container || "#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`
877
+ );
878
+ return element;
879
+ }
880
+ _createFrame(options) {
881
+ const frame = document.createElement("iframe");
882
+ frame["squatchJsApi"] = this;
883
+ frame.id = "squatchFrame";
884
+ frame.width = "100%";
885
+ frame.src = "about:blank";
886
+ frame.scrolling = "no";
887
+ frame.setAttribute(
888
+ "style",
889
+ "border: 0; background-color: none; width: 1px; min-width: 100%;"
890
+ );
891
+ if (options == null ? void 0 : options.minWidth) frame.style.minWidth = options.minWidth;
892
+ if (options == null ? void 0 : options.maxWidth) frame.style.maxWidth = options.maxWidth;
893
+ if ((options == null ? void 0 : options.maxWidth) || (options == null ? void 0 : options.minWidth)) {
894
+ frame.style.width = "100%";
895
+ }
896
+ if (options == null ? void 0 : options.initialHeight) {
897
+ frame.height = options.initialHeight;
898
+ }
899
+ return frame;
900
+ }
901
+ _findFrame() {
902
+ const element = this.container ? this._findElement() : document.body;
903
+ const parent = element.shadowRoot || element;
904
+ return parent.querySelector(
905
+ "iframe#squatchFrame"
906
+ );
907
+ }
908
+ _detachLoadEventListener(frameDoc) {
909
+ if (this.loadEventListener) {
910
+ frameDoc.removeEventListener(
911
+ "sq:user-registration",
912
+ this.loadEventListener
913
+ );
914
+ this.loadEventListener = null;
915
+ }
916
+ }
917
+ _attachLoadEventListener(frameDoc, sqh) {
918
+ if (this.loadEventListener === null) {
919
+ this.loadEventListener = (e) => {
920
+ this._loadEvent({
921
+ ...sqh,
922
+ userId: e.detail.userId,
923
+ accountId: e.detail.accountId
924
+ });
925
+ };
926
+ frameDoc.addEventListener("sq:user-registration", this.loadEventListener);
927
+ }
928
+ }
929
+ _loadEvent(sqh) {
930
+ var _a2;
931
+ if (!sqh) return;
932
+ if (!isObject$1(sqh)) {
933
+ throw new Error("Widget Load event identity property is not an object");
934
+ }
935
+ let params;
936
+ if ("programId" in sqh) {
937
+ if (!sqh.tenantAlias || !sqh.accountId || !sqh.userId || !sqh.engagementMedium)
938
+ throw new Error("Widget Load event missing required properties");
939
+ params = {
940
+ tenantAlias: sqh.tenantAlias,
941
+ externalAccountId: sqh.accountId,
942
+ externalUserId: sqh.userId,
943
+ engagementMedium: sqh.engagementMedium,
944
+ programId: sqh.programId
945
+ };
946
+ } else {
947
+ const { analytics, mode } = sqh;
948
+ params = {
949
+ tenantAlias: analytics.attributes.tenant,
950
+ externalAccountId: analytics.attributes.accountId,
951
+ externalUserId: analytics.attributes.userId,
952
+ engagementMedium: mode.widgetMode
953
+ };
954
+ }
955
+ (_a2 = this.analyticsApi.pushAnalyticsLoadEvent(params)) == null ? void 0 : _a2.then((response) => {
956
+ _log$8(`${params.engagementMedium} loaded event recorded.`);
957
+ }).catch((ex) => {
958
+ _log$8(`ERROR: pushAnalyticsLoadEvent() ${ex}`);
959
+ });
960
+ }
961
+ _shareEvent(sqh, medium) {
962
+ if (sqh) {
963
+ this.analyticsApi.pushAnalyticsShareClickedEvent({
964
+ tenantAlias: sqh.analytics.attributes.tenant,
965
+ externalAccountId: sqh.analytics.attributes.accountId,
966
+ externalUserId: sqh.analytics.attributes.userId,
967
+ engagementMedium: sqh.mode.widgetMode,
968
+ shareMedium: medium
969
+ }).then((response) => {
970
+ _log$8(
971
+ `${sqh.mode.widgetMode} share ${medium} event recorded. ${response}`
972
+ );
973
+ }).catch((ex) => {
974
+ _log$8(`ERROR: pushAnalyticsShareClickedEvent() ${ex}`);
975
+ });
976
+ }
977
+ }
978
+ _error(rs, mode = "modal", style = "") {
979
+ const errorTemplate = `<!DOCTYPE html>
980
+ <!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]-->
981
+ <!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]-->
982
+ <!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
983
+ <head>
984
+ <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">
985
+ <style>
986
+ ${style}
987
+ </style>
988
+ </head>
989
+ <body>
990
+
991
+ <div class="squatch-container ${mode}" style="width:100%">
992
+ <div class="errorheader">
993
+ <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">&times;</button>
994
+ <p class="errortitle">Error</p>
995
+ </div>
996
+ <div class="errorbody">
997
+ <div class="sadface"><img src="https://fast.ssqt.io/assets/images/face.png"></div>
998
+ <h4>Our referral program is temporarily unavailable.</h4><br>
999
+ <p>Please reload the page or check back later.</p>
1000
+ <p>If the persists please contact our support team.</p>
1001
+ <br>
1002
+ <br>
1003
+ <div class="right-align errtxt">
1004
+ Error Code: ${rs}
1005
+ </div>
1006
+ </div>
1007
+ </div>
1008
+ </body>
1009
+ </html>`;
1010
+ return errorTemplate;
1011
+ }
1012
+ async _findInnerContainer(frame) {
1013
+ const { contentWindow } = frame;
1014
+ if (!contentWindow)
1015
+ throw new Error("Squatch.js frame inner frame is empty");
1016
+ const frameDoc = contentWindow.document;
1017
+ function search() {
1018
+ const containers = frameDoc.getElementsByTagName("sqh-global-container");
1019
+ const legacyContainers = frameDoc.getElementsByClassName("squatch-container");
1020
+ const fallback = containers.length > 0 ? containers[0] : legacyContainers.length > 0 ? legacyContainers[0] : null;
1021
+ return fallback;
1022
+ }
1023
+ let found = null;
1024
+ for (let i = 0; i < 5; i++) {
1025
+ found = search();
1026
+ if (found) break;
1027
+ await delay(100);
1028
+ }
1029
+ if (!found) {
1030
+ return frameDoc.body;
1031
+ }
1032
+ return found;
1033
+ }
1034
+ /**
1035
+ * Reloads the current widget, makes updated request to API and renders result.
1036
+ * Primarily for Classic widgets with registration
1037
+ * @param param0 Form field values
1038
+ * @param jwt JWT for API authentication
1039
+ */
1040
+ reload({ email, firstName, lastName }, jwt) {
1041
+ const frame = this._findFrame();
1042
+ if (!frame) throw new Error("Could not find widget iframe");
1043
+ const frameWindow = frame.contentWindow;
1044
+ const engagementMedium = this.context.engagementMedium || "POPUP";
1045
+ if (!frameWindow) {
1046
+ throw new Error("Frame needs a content window");
1047
+ }
1048
+ let response;
1049
+ if (this.context.type === "upsert") {
1050
+ if (!this.context.user) throw new Error("Can't reload without user ids");
1051
+ let userObj = {
1052
+ email: email || null,
1053
+ firstName: firstName || null,
1054
+ lastName: lastName || null,
1055
+ id: this.context.user.id,
1056
+ accountId: this.context.user.accountId
1057
+ };
1058
+ response = this.widgetApi.upsertUser({
1059
+ user: userObj,
1060
+ engagementMedium,
1061
+ widgetType: this.type,
1062
+ jwt
1063
+ });
1064
+ } else if (this.context.type === "passwordless") {
1065
+ response = this.widgetApi.render({
1066
+ user: void 0,
1067
+ engagementMedium,
1068
+ widgetType: this.type,
1069
+ jwt: void 0
1070
+ });
1071
+ } else {
1072
+ throw new Error("can't reload an error widget");
1073
+ }
1074
+ response.then(({ template }) => {
1075
+ if (template) {
1076
+ this.content = template;
1077
+ this.__deprecated__register(
1078
+ frame,
1079
+ { email, engagementMedium },
1080
+ () => {
1081
+ this.load();
1082
+ engagementMedium === "POPUP" && this.open();
1083
+ }
1084
+ );
1085
+ }
1086
+ }).catch(({ message }) => {
1087
+ _log$8(`${message}`);
1088
+ });
1089
+ }
1090
+ __deprecated__register(frame, params, onClick) {
1091
+ const frameWindow = frame.contentWindow;
1092
+ const frameDoc = frameWindow.document;
1093
+ const showStatsBtn = frameDoc.createElement("button");
1094
+ const registerForm = frameDoc.getElementsByClassName("squatch-register")[0];
1095
+ if (registerForm) {
1096
+ showStatsBtn.className = "btn btn-primary";
1097
+ showStatsBtn.id = "show-stats-btn";
1098
+ showStatsBtn.textContent = this.type === "REFERRER_WIDGET" ? "Show Stats" : "Show Reward";
1099
+ const widgetStyle = params.engagementMedium === "POPUP" ? "margin-top: 10px; max-width: 130px; width: 100%;" : "margin-top: 10px;";
1100
+ showStatsBtn.setAttribute("style", widgetStyle);
1101
+ showStatsBtn.onclick = onClick;
1102
+ registerForm.style.paddingTop = "30px";
1103
+ registerForm.innerHTML = `<p><strong>${params.email}</strong><br>Has been successfully registered</p>`;
1104
+ registerForm.appendChild(showStatsBtn);
1105
+ }
1106
+ }
1107
+ }
1108
+ function delay(duration) {
1109
+ return new Promise((resolve) => {
1110
+ setTimeout(resolve, duration);
1111
+ });
1112
+ }
1113
+ const _log$7 = browserExports.debug("squatch-js:EMBEDwidget");
1114
+ class EmbedWidget extends Widget {
1115
+ constructor(params, container) {
1116
+ super(params);
1117
+ __publicField(this, "show", this.open);
1118
+ __publicField(this, "hide", this.close);
1119
+ if (container) {
1120
+ this.container = container;
1121
+ }
1122
+ }
1123
+ async load() {
1124
+ var _a2, _b, _c, _d, _e, _f, _g;
1125
+ const brandingConfig = (_b = (_a2 = this.context.widgetConfig) == null ? void 0 : _a2.values) == null ? void 0 : _b.brandingConfig;
1126
+ const initialHeight = brandingConfig == null ? void 0 : brandingConfig.loadingHeight;
1127
+ const sizes = (_c = brandingConfig == null ? void 0 : brandingConfig.widgetSize) == null ? void 0 : _c.embeddedWidgets;
1128
+ const maxWidth = (sizes == null ? void 0 : sizes.maxWidth) ? formatWidth(sizes.maxWidth) : "";
1129
+ const minWidth = (sizes == null ? void 0 : sizes.minWidth) ? formatWidth(sizes.minWidth) : "";
1130
+ const frame = this._createFrame({
1131
+ minWidth,
1132
+ maxWidth,
1133
+ initialHeight
1134
+ });
1135
+ const element = this._findElement();
1136
+ if ((_d = this.context) == null ? void 0 : _d.container) {
1137
+ element.style.visibility = "hidden";
1138
+ element.style.height = "0";
1139
+ element.style["overflow-y"] = "hidden";
1140
+ }
1141
+ if (this.container) {
1142
+ if (element.shadowRoot) {
1143
+ if (((_e = element.shadowRoot.lastChild) == null ? void 0 : _e.nodeName) === "IFRAME") {
1144
+ element.shadowRoot.replaceChild(frame, element.shadowRoot.lastChild);
1145
+ } else {
1146
+ element.shadowRoot.appendChild(frame);
1147
+ }
1148
+ } else if (element.firstChild) {
1149
+ element.replaceChild(frame, element.firstChild);
1150
+ } else {
1151
+ element.appendChild(frame);
1152
+ }
1153
+ } else if (!element.firstChild || element.firstChild.nodeName === "#text") {
1154
+ element.appendChild(frame);
1155
+ }
1156
+ const { contentWindow } = frame;
1157
+ if (!contentWindow) {
1158
+ throw new Error("Frame needs a content window");
1159
+ }
1160
+ const frameDoc = contentWindow.document;
1161
+ frameDoc.open();
1162
+ const domain = this.widgetApi.domain;
1163
+ frameDoc.write(`
1164
+ ${((_f = brandingConfig == null ? void 0 : brandingConfig.main) == null ? void 0 : _f.brandFont) ? `
1165
+ <link rel="preconnect" href="https://fast${domain === "https://staging.referralsaasquatch.com" && "-staging"}.ssqt.io">
1166
+ <link rel="preconnect" href="https://fonts.gstatic.com">
1167
+ <link rel="preconnect" href="https://fonts.googleapis.com">
1168
+ <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent(
1169
+ (_g = brandingConfig == null ? void 0 : brandingConfig.main) == null ? void 0 : _g.brandFont
1170
+ )}" as="style">` : ""}
1171
+ <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>
1172
+ <style data-styles>
1173
+ html { visibility:hidden;}
1174
+ </style>
1175
+ ${this.content}
1176
+
1177
+ `);
1178
+ frameDoc.close();
1179
+ domready(frameDoc, async () => {
1180
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1181
+ frame.height = initialHeight || frameDoc.body.scrollHeight;
1182
+ console.log({ height: frameDoc.body.scrollHeight });
1183
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1184
+ for (const entry of entries) {
1185
+ const { height } = entry.contentRect;
1186
+ frame.height = height;
1187
+ }
1188
+ });
1189
+ const container = await this._findInnerContainer(frame);
1190
+ ro.observe(container);
1191
+ if (this._shouldFireLoadEvent()) {
1192
+ this._loadEvent(_sqh);
1193
+ _log$7("loaded");
1194
+ } else if (frameDoc) {
1195
+ this._attachLoadEventListener(frameDoc, _sqh);
1196
+ }
1197
+ });
1198
+ }
1199
+ /**
1200
+ * Un-hide if element is available and refresh data
1201
+ */
1202
+ open() {
1203
+ const frame = this._findFrame();
1204
+ if (!frame) return _log$7("no target element to open");
1205
+ if (!frame.contentWindow) return _log$7("Frame needs a content window");
1206
+ const element = this._findElement();
1207
+ element.style.visibility = "unset";
1208
+ element.style.height = "auto";
1209
+ element.style["overflow-y"] = "auto";
1210
+ frame.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));
1211
+ const _sqh = frame.contentWindow.squatch || frame.contentWindow.widgetIdent;
1212
+ if (this.context.user) {
1213
+ this._loadEvent(_sqh);
1214
+ _log$7("loaded");
1215
+ } else {
1216
+ if (!frame.contentDocument) return;
1217
+ this._attachLoadEventListener(frame.contentDocument, _sqh);
1218
+ }
1219
+ }
1220
+ close() {
1221
+ const frame = this._findFrame();
1222
+ if (!frame) return _log$7("no target element to close");
1223
+ if (frame.contentDocument)
1224
+ this._detachLoadEventListener(frame.contentDocument);
1225
+ const element = this._findElement();
1226
+ element.style.visibility = "hidden";
1227
+ element.style.height = "0";
1228
+ element.style["overflow-y"] = "hidden";
1229
+ _log$7("Embed widget closed");
1230
+ }
1231
+ _error(rs, mode = "embed", style = "") {
1232
+ return super._error(rs, mode, style);
1233
+ }
1234
+ _shouldFireLoadEvent() {
1235
+ const noContainer = !this.container;
1236
+ const isComponent = this.container instanceof HTMLElement && (this.container.tagName.startsWith("SQUATCH-") || this.container.tagName.startsWith("IMPACT-"));
1237
+ const isVerified = !!this.context.user;
1238
+ return isVerified && (noContainer || isComponent);
1239
+ }
1240
+ }
1241
+ const _log$6 = browserExports.debug("squatch-js:POPUPwidget");
1242
+ let popupId = 0;
1243
+ class PopupWidget extends Widget {
1244
+ constructor(params, trigger = ".squatchpop") {
1245
+ super(params);
1246
+ __publicField(this, "trigger");
1247
+ __publicField(this, "id");
1248
+ __publicField(this, "show", this.open);
1249
+ __publicField(this, "hide", this.close);
1250
+ this.trigger = trigger;
1251
+ if (this.container) {
1252
+ this.id = "squatchModal";
1253
+ } else {
1254
+ this.id = popupId === 0 ? `squatchModal` : `squatchModal__${popupId}`;
1255
+ popupId = popupId + 1;
1256
+ }
1257
+ document.head.insertAdjacentHTML(
1258
+ "beforeend",
1259
+ `<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`
1260
+ );
1261
+ }
1262
+ _initialiseCTA() {
1263
+ if (!this.trigger) return;
1264
+ let triggerElement;
1265
+ try {
1266
+ triggerElement = document.querySelector(this.trigger) || document.querySelector(".impactpop");
1267
+ if (this.trigger && !triggerElement)
1268
+ _log$6("No element found with trigger selector", this.trigger);
1269
+ } catch {
1270
+ _log$6("Not a valid selector", this.trigger);
1271
+ }
1272
+ if (triggerElement) {
1273
+ triggerElement.onclick = () => {
1274
+ this.open();
1275
+ };
1276
+ }
1277
+ }
1278
+ _createPopupDialog() {
1279
+ var _a2, _b, _c;
1280
+ const dialog = document.createElement("dialog");
1281
+ const brandingConfig = (_b = (_a2 = this.context.widgetConfig) == null ? void 0 : _a2.values) == null ? void 0 : _b.brandingConfig;
1282
+ const sizes = (_c = brandingConfig == null ? void 0 : brandingConfig.widgetSize) == null ? void 0 : _c.popupWidgets;
1283
+ const minWidth = (sizes == null ? void 0 : sizes.minWidth) ? formatWidth(sizes.minWidth) : "auto";
1284
+ const maxWidth = (sizes == null ? void 0 : sizes.maxWidth) ? formatWidth(sizes.maxWidth) : "500px";
1285
+ dialog.id = this.id;
1286
+ dialog.setAttribute(
1287
+ "style",
1288
+ `width: 100%; min-width: ${minWidth}; max-width: ${maxWidth}; border: none; padding: 0;`
1289
+ );
1290
+ const onClick = (e) => {
1291
+ e.stopPropagation();
1292
+ if (e.target === dialog) dialog.close();
1293
+ };
1294
+ dialog.addEventListener("click", onClick);
1295
+ return dialog;
1296
+ }
1297
+ async load() {
1298
+ var _a2;
1299
+ const frame = this._createFrame();
1300
+ this._initialiseCTA();
1301
+ const element = this.container ? this._findElement() : document.body;
1302
+ const dialogParent = element.shadowRoot || element;
1303
+ const dialog = this._createPopupDialog();
1304
+ dialog.appendChild(frame);
1305
+ if (((_a2 = dialogParent.lastChild) == null ? void 0 : _a2.nodeName) === "DIALOG") {
1306
+ dialogParent.replaceChild(dialog, dialogParent.lastChild);
1307
+ } else {
1308
+ dialogParent.appendChild(dialog);
1309
+ }
1310
+ const { contentWindow } = frame;
1311
+ if (!contentWindow) {
1312
+ throw new Error("Frame needs a content window");
1313
+ }
1314
+ const frameDoc = contentWindow.document;
1315
+ frameDoc.open();
1316
+ frameDoc.write(this.content);
1317
+ frameDoc.write(
1318
+ `<script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>`
1319
+ );
1320
+ frameDoc.write(`
1321
+ <style>
1322
+ body {
1323
+ height: 600px;
1324
+ border: 2px solid #ccc;
1325
+ background-color: red;
1326
+ margin: 0;
1327
+ padding: 0;
1328
+ box-sizing: border-box;
1329
+ }
1330
+ </style>
1331
+ `);
1332
+ frameDoc.close();
1333
+ _log$6("Popup template loaded into iframe");
1334
+ await this._setupResizeHandler(frame);
1335
+ }
1336
+ async _setupResizeHandler(frame) {
1337
+ const { contentWindow } = frame;
1338
+ if (!contentWindow) {
1339
+ throw new Error("Frame needs a content window");
1340
+ }
1341
+ const frameDoc = contentWindow.document;
1342
+ domready(frameDoc, async () => {
1343
+ frameDoc.body.style.overflowY = "hidden";
1344
+ frame.height = `${frameDoc.body.offsetHeight}px`;
1345
+ const ro = new contentWindow["ResizeObserver"]((entries) => {
1346
+ for (const entry of entries) {
1347
+ const { top, bottom } = entry.contentRect;
1348
+ const computedHeight = bottom + top;
1349
+ frame.height = computedHeight + "";
1350
+ entry.target.style = ``;
1351
+ }
1352
+ });
1353
+ ro.observe(await this._findInnerContainer(frame));
1354
+ });
1355
+ }
1356
+ open() {
1357
+ const element = this.container ? this._findElement() : document.body;
1358
+ const parent = element.shadowRoot || element;
1359
+ const dialog = parent.querySelector(`#${this.id}`);
1360
+ if (!dialog) throw new Error("Could not determine container div");
1361
+ dialog.showModal();
1362
+ const frame = this._findFrame();
1363
+ if (!frame) throw new Error("Could not find iframe");
1364
+ const { contentWindow } = frame;
1365
+ if (!contentWindow) throw new Error("Squatch.js has an empty iframe");
1366
+ const frameDoc = contentWindow.document;
1367
+ domready(frameDoc, () => {
1368
+ var _a2;
1369
+ const _sqh = contentWindow.squatch || contentWindow.widgetIdent;
1370
+ (_a2 = frame.contentDocument) == null ? void 0 : _a2.dispatchEvent(new CustomEvent("sq:refresh"));
1371
+ if (this.context.user) {
1372
+ this._loadEvent(_sqh);
1373
+ _log$6("Popup opened");
1374
+ } else {
1375
+ this._attachLoadEventListener(frameDoc, _sqh);
1376
+ }
1377
+ });
1378
+ }
1379
+ close() {
1380
+ const frame = this._findFrame();
1381
+ if (frame == null ? void 0 : frame.contentDocument)
1382
+ this._detachLoadEventListener(frame.contentDocument);
1383
+ const element = this.container ? this._findElement() : document.body;
1384
+ const parent = element.shadowRoot || element;
1385
+ const dialog = parent.querySelector(`#${this.id}`);
1386
+ if (!dialog) throw new Error("Could not determine container div");
1387
+ dialog.close();
1388
+ _log$6("Popup closed");
1389
+ }
1390
+ _clickedOutside({ target }) {
1391
+ }
1392
+ _error(rs, mode = "modal", style = "") {
1393
+ const _style = "body { margin: 0; } .modal { box-shadow: none; border: 0; }";
1394
+ return super._error(rs, mode, style || _style);
1395
+ }
1396
+ }
1397
+ const _log$5 = browserExports.debug("squatch-js:widgets");
1398
+ class Widgets {
1399
+ /**
1400
+ * Initialize a new {@link Widgets} instance.
1401
+ *
1402
+ * @param {ConfigOptions} config Config details
1403
+ *
1404
+ * @example <caption>Browser example</caption>
1405
+ * var widgets = new squatch.Widgets({tenantAlias:'test_12b5bo1b25125'});
1406
+ *
1407
+ * @example <caption>Browserify/Webpack example</caption>
1408
+ * var Widgets = require('@saasquatch/squatch-js').Widgets;
1409
+ * var widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1410
+ *
1411
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1412
+ * import {Widgets} from '@saasquatch/squatch-js';
1413
+ * let widgets = new Widgets({tenantAlias:'test_12b5bo1b25125'});
1414
+ */
1415
+ constructor(configin) {
1416
+ /**
1417
+ * Instance of {@link WidgetApi}
1418
+ */
1419
+ __publicField(this, "api");
1420
+ /**
1421
+ * Tenant alias of SaaSquatch tenant
1422
+ */
1423
+ __publicField(this, "tenantAlias");
1424
+ /**
1425
+ * SaaSquatch domain for API requests
1426
+ * @default "https://app.referralsaasquatch.com"
1427
+ */
1428
+ __publicField(this, "domain");
1429
+ /**
1430
+ * Hosted CDN for npm packages
1431
+ * @default "https://fast.ssqt.io/npm"
1432
+ */
1433
+ __publicField(this, "npmCdn");
1434
+ const config = validateConfig(configin);
1435
+ this.tenantAlias = config.tenantAlias;
1436
+ this.domain = config.domain;
1437
+ this.npmCdn = config.npmCdn;
1438
+ this.api = new WidgetApi(config);
1439
+ }
1440
+ /**
1441
+ * This function calls the {@link WidgetApi.upsertUser} method, and it renders
1442
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1443
+ *
1444
+ * @param {Object} config Config details
1445
+ * @param {Object} config.user The user details
1446
+ * @param {string} config.user.id The user id
1447
+ * @param {string} config.user.accountId The user account id
1448
+ * @param {WidgetType} config.widgetType The content of the widget
1449
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1450
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used to validate the data (can be disabled)
1451
+ * @param {HTMLElement | string | undefined} config.container Element to load the widget into
1452
+ * @param {string | undefined} config.trigger Trigger element for opening the popup widget
1453
+ *
1454
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1455
+ */
1456
+ async upsertUser(config) {
1457
+ const raw = config;
1458
+ const clean = validateWidgetConfig(raw);
1459
+ try {
1460
+ const response = await this.api.upsertUser(clean);
1461
+ return {
1462
+ widget: this._renderWidget(response, clean, {
1463
+ type: "upsert",
1464
+ user: clean.user,
1465
+ engagementMedium: config.engagementMedium,
1466
+ container: config.container,
1467
+ trigger: config.trigger,
1468
+ widgetConfig: {
1469
+ values: {
1470
+ brandingConfig: response == null ? void 0 : response.brandingConfig
1471
+ }
1472
+ }
1473
+ }),
1474
+ user: response.user
1475
+ };
1476
+ } catch (err) {
1477
+ _log$5(err);
1478
+ if (err.apiErrorCode) {
1479
+ this._renderErrorWidget(err, config.engagementMedium);
1480
+ }
1481
+ throw new Error(err);
1482
+ }
1483
+ }
1484
+ /**
1485
+ * This function calls the {@link WidgetApi.render} method, and it renders
1486
+ * the widget if it is successful. Otherwise it shows the "error" widget.
1487
+ *
1488
+ * @param {Object} config Config details
1489
+ * @param {Object} config.user The user details
1490
+ * @param {string} config.user.id The user id
1491
+ * @param {string} config.user.accountId The user account id
1492
+ * @param {WidgetType} config.widgetType The content of the widget
1493
+ * @param {EngagementMedium} config.engagementMedium How to display the widget
1494
+ * @param {string} config.jwt the JSON Web Token (JWT) that is used
1495
+ * to validate the data (can be disabled)
1496
+ *
1497
+ * @return {Promise<WidgetResult>} json object if true, with a Widget and user details
1498
+ */
1499
+ async render(config) {
1500
+ const raw = config;
1501
+ const clean = validatePasswordlessConfig(raw);
1502
+ try {
1503
+ const response = await this.api.render(clean);
1504
+ return {
1505
+ widget: this._renderWidget(response, clean, {
1506
+ type: "passwordless",
1507
+ engagementMedium: clean.engagementMedium,
1508
+ container: clean.container,
1509
+ trigger: clean.trigger,
1510
+ widgetConfig: {
1511
+ values: {
1512
+ brandingConfig: response == null ? void 0 : response.brandingConfig
1513
+ }
1514
+ }
1515
+ }),
1516
+ user: response.user
1517
+ };
1518
+ } catch (err) {
1519
+ if (err.apiErrorCode) {
1520
+ this._renderErrorWidget(err, clean.engagementMedium);
1521
+ }
1522
+ throw new Error(err);
1523
+ }
1524
+ }
1525
+ /**
1526
+ * Autofills a referral code into an element when someone has been referred.
1527
+ * Uses {@link WidgetApi.squatchReferralCookie} behind the scenes.
1528
+ *
1529
+ * @param selector Element class/id selector, or a callback function
1530
+ * @returns
1531
+ */
1532
+ async autofill(selector) {
1533
+ const input = selector;
1534
+ if (typeof input === "function") {
1535
+ try {
1536
+ const response = await this.api.squatchReferralCookie();
1537
+ input(response);
1538
+ } catch (e) {
1539
+ _log$5("Autofill error", e);
1540
+ throw new Error(e);
1541
+ }
1542
+ return;
1543
+ }
1544
+ if (typeof input !== "string")
1545
+ throw new Error("Autofill accepts a string or function");
1546
+ let elems = document.querySelectorAll(input);
1547
+ let elem;
1548
+ if (elems.length > 0) {
1549
+ elem = elems[0];
1550
+ } else {
1551
+ _log$5("Element id/class or function missing");
1552
+ throw new Error("Element id/class or function missing");
1553
+ }
1554
+ try {
1555
+ const response = await this.api.squatchReferralCookie();
1556
+ elem.value = response.codes[0];
1557
+ } catch (e) {
1558
+ throw new Error(e);
1559
+ }
1560
+ }
1561
+ /**
1562
+ * @hidden
1563
+ * @param {Object} response The json object return from the WidgetApi
1564
+ * @param {Object} config Config details
1565
+ * @param {string} config.widgetType The widget type (REFERRER_WIDGET, CONVERSION_WIDGET)
1566
+ * @param {string} config.engagementMedium (POPUP, EMBED)
1567
+ * @returns {Widget} widget (PopupWidget or EmbedWidget)
1568
+ */
1569
+ _renderWidget(response, config, context) {
1570
+ var _a2;
1571
+ _log$5("Rendering Widget...");
1572
+ if (!response) throw new Error("Unable to get a response");
1573
+ let widget2;
1574
+ let displayOnLoad = !!config.displayOnLoad;
1575
+ const opts = response.jsOptions || {};
1576
+ const params = {
1577
+ content: response.template,
1578
+ type: config.widgetType || ((_a2 = opts.widget) == null ? void 0 : _a2.defaultWidgetType),
1579
+ api: this.api,
1580
+ domain: this.domain,
1581
+ npmCdn: this.npmCdn,
1582
+ context
1583
+ };
1584
+ if (opts.widgetUrlMappings) {
1585
+ opts.widgetUrlMappings.forEach((rule) => {
1586
+ var _a3, _b;
1587
+ if (Widgets._matchesUrl(rule.url)) {
1588
+ if (rule.widgetType !== "CONVERSION_WIDGET" || ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code)) {
1589
+ displayOnLoad = rule.displayOnLoad;
1590
+ _log$5(`Display ${rule.widgetType} on ${rule.url}`);
1591
+ } else {
1592
+ _log$5(
1593
+ `Don't display ${rule.widgetType} when no referral on widget rule match ${rule.url}`
1594
+ );
1595
+ }
1596
+ }
1597
+ });
1598
+ }
1599
+ if (opts.fuelTankAutofillUrls) {
1600
+ _log$5("We found a fuel tank autofill!");
1601
+ opts.fuelTankAutofillUrls.forEach(({ url, formSelector }) => {
1602
+ var _a3, _b, _c;
1603
+ if (Widgets._matchesUrl(url)) {
1604
+ _log$5("Fuel Tank URL matches");
1605
+ if ((_b = (_a3 = response.user) == null ? void 0 : _a3.referredBy) == null ? void 0 : _b.code) {
1606
+ const formAutofill = document.querySelector(formSelector);
1607
+ if (formAutofill) {
1608
+ formAutofill.value = ((_c = response.user.referredBy.referredReward) == null ? void 0 : _c.fuelTankCode) || "";
1609
+ } else {
1610
+ _log$5(
1611
+ new Error(
1612
+ `Element with id/class ${formSelector} was not found.`
1613
+ )
1614
+ );
1615
+ }
1616
+ }
1617
+ }
1618
+ });
1619
+ }
1620
+ if (config.engagementMedium === "EMBED") {
1621
+ widget2 = this._renderEmbedWidget(params);
1622
+ } else {
1623
+ widget2 = this._renderPopupWidget(params);
1624
+ if (displayOnLoad) widget2.open();
1625
+ }
1626
+ return widget2;
1627
+ }
1628
+ _renderPopupWidget(params) {
1629
+ const widget2 = new PopupWidget(params, params.context.trigger);
1630
+ widget2.load();
1631
+ return widget2;
1632
+ }
1633
+ _renderEmbedWidget(params) {
1634
+ const widget2 = new EmbedWidget(params, params.context.container);
1635
+ widget2.load();
1636
+ return widget2;
1637
+ }
1638
+ /**
1639
+ * @hidden
1640
+ * @param {Object} error The json object containing the error details
1641
+ * @param {string} em The engagementMedium
1642
+ * @returns {void}
1643
+ */
1644
+ _renderErrorWidget(props, em = "POPUP") {
1645
+ const { apiErrorCode, rsCode, message } = props;
1646
+ _log$5(new Error(`${apiErrorCode} (${rsCode}) ${message}`));
1647
+ const params = {
1648
+ content: "error",
1649
+ rsCode,
1650
+ api: this.api,
1651
+ domain: this.domain,
1652
+ npmCdn: this.npmCdn,
1653
+ type: "ERROR_WIDGET",
1654
+ context: { type: "error" }
1655
+ };
1656
+ let widget2;
1657
+ if (em === "EMBED") {
1658
+ widget2 = new EmbedWidget(params);
1659
+ widget2.load();
1660
+ } else if (em === "POPUP") {
1661
+ widget2 = new PopupWidget(params);
1662
+ widget2.load();
1663
+ }
1664
+ }
1665
+ /**
1666
+ * @hidden
1667
+ * @param {string} rule A regular expression
1668
+ * @returns {boolean} true if rule matches Url, false otherwise
1669
+ */
1670
+ static _matchesUrl(rule) {
1671
+ return window.location.href.match(new RegExp(rule)) ? true : false;
1672
+ }
1673
+ }
1674
+ class EventsApi {
1675
+ /**
1676
+ * Initialize a new {@link EventsApi} instance.
1677
+ *
1678
+ * @param {ConfigOptions} config Config details
1679
+ *
1680
+ * @example <caption>Browser example</caption>
1681
+ * var squatchApi = new squatch.EventsApi({tenantAlias:'test_12b5bo1b25125'});
1682
+ *
1683
+ * @example <caption>Browserify/Webpack example</caption>
1684
+ * var EventsApi = require('@saasquatch/squatch-js').EventsApi;
1685
+ * var squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1686
+ *
1687
+ * @example <caption>Babel+Browserify/Webpack example</caption>
1688
+ * import {EventsApi} from '@saasquatch/squatch-js';
1689
+ * let squatchApi = new EventsApi({tenantAlias:'test_12b5bo1b25125'});
1690
+ */
1691
+ constructor(config) {
1692
+ __publicField(this, "tenantAlias");
1693
+ __publicField(this, "domain");
1694
+ const raw = config;
1695
+ const clean = validateConfig(raw);
1696
+ this.tenantAlias = clean.tenantAlias;
1697
+ this.domain = clean.domain;
1698
+ }
1699
+ /**
1700
+ * Track an event for a user
1701
+ *
1702
+ * @param params Parameters for request
1703
+ * @param options.jwt the JSON Web Token (JWT) that is used to authenticate the user
1704
+ *
1705
+ * @return An ID to confirm the event has been accepted for asynchronous processing
1706
+ */
1707
+ track(params, options) {
1708
+ const raw = params;
1709
+ const rawOpts = options;
1710
+ const body = _validateEvent(raw);
1711
+ const { jwt } = _validateTrackOptions(rawOpts);
1712
+ const ta = encodeURIComponent(this.tenantAlias);
1713
+ const userId = encodeURIComponent(body.userId);
1714
+ const accountId = encodeURIComponent(body.accountId);
1715
+ const path = `/api/v1/${ta}/open/account/${accountId}/user/${userId}/events`;
1716
+ const url = this.domain + path;
1717
+ return doPost(url, JSON.stringify(body), jwt);
1718
+ }
1719
+ }
1720
+ function _validateEvent(raw) {
1721
+ if (!isObject$1(raw)) throw new Error("tracking parameter must be an object");
1722
+ if (!(raw == null ? void 0 : raw["accountId"])) throw new Error("accountId field is required");
1723
+ if (!(raw == null ? void 0 : raw["events"])) throw new Error("events field is required");
1724
+ if (!(raw == null ? void 0 : raw["userId"])) throw new Error("userId field is required");
1725
+ const clean = raw;
1726
+ if (!Array.isArray(clean.events))
1727
+ throw new Error("'events' should be an array");
1728
+ return clean;
1729
+ }
1730
+ function _validateTrackOptions(raw) {
1731
+ if (!isObject$1(raw)) throw new Error("'options' should be an object");
1732
+ return raw;
1733
+ }
1734
+ function asyncLoad() {
1735
+ var _a2;
1736
+ const namespace = window[IMPACT_NAMESPACE] ? IMPACT_NAMESPACE : DEFAULT_NAMESPACE;
1737
+ const cached = ((_a2 = window["_" + namespace]) == null ? void 0 : _a2.ready) || [];
1738
+ const declarativeCache = window.impactOnReady || window.squatchOnReady;
1739
+ const readyFns = [...cached, declarativeCache].filter((a) => !!a);
1740
+ setTimeout(() => {
1741
+ if (!window[DEFAULT_NAMESPACE]) return;
1742
+ window[IMPACT_NAMESPACE] = window[DEFAULT_NAMESPACE];
1743
+ readyFns.forEach((cb) => cb());
1744
+ window[DEFAULT_NAMESPACE]._auto();
1745
+ window["_" + namespace] = void 0;
1746
+ delete window["_" + namespace];
1747
+ }, 0);
1748
+ }
1749
+ const _log$4 = browserExports.debug("squatch-js");
1750
+ const isObject = (item) => typeof item === "object" && !Array.isArray(item);
1751
+ const deepMerge = (target, source) => {
1752
+ const isDeep = (prop) => isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
1753
+ const replaced = Object.getOwnPropertyNames(source).map((prop) => ({
1754
+ [prop]: isDeep(prop) ? deepMerge(target[prop], source[prop]) : source[prop]
1755
+ })).reduce((a, b) => ({ ...a, ...b }), {});
1756
+ return {
1757
+ ...target,
1758
+ ...replaced
1759
+ };
1760
+ };
1761
+ function b64decode(input) {
1762
+ const binary = atob(input.replace(/_/g, "/").replace(/-/g, "+"));
1763
+ const bytes = new Uint8Array(binary.length);
1764
+ for (let i = 0; i < binary.length; i++) {
1765
+ bytes[i] = binary.charCodeAt(i);
1766
+ }
1767
+ return new TextDecoder("utf8").decode(bytes);
1768
+ }
1769
+ function b64encode(input) {
1770
+ const encodedInput = new TextEncoder().encode(input);
1771
+ const binary = Array.from(
1772
+ encodedInput,
1773
+ (byte) => String.fromCodePoint(byte)
1774
+ ).join("");
1775
+ return btoa(binary).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
1776
+ }
1777
+ function getTopDomain() {
1778
+ var i, h, weird_cookie = "weird_get_top_level_domain=cookie", hostname = document.location.hostname.split(".");
1779
+ for (i = hostname.length - 1; i >= 0; i--) {
1780
+ h = hostname.slice(i).join(".");
1781
+ document.cookie = weird_cookie + ";domain=." + h + ";";
1782
+ if (document.cookie.indexOf(weird_cookie) > -1) {
1783
+ document.cookie = weird_cookie.split("=")[0] + "=;domain=." + h + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
1784
+ return h;
1785
+ }
1786
+ }
1787
+ }
1788
+ function _pushCookie() {
1789
+ const queryString = window.location.search;
1790
+ const urlParams = new URLSearchParams(queryString);
1791
+ const refParam = urlParams.get("_saasquatch") || "";
1792
+ if (refParam) {
1793
+ let paramsJSON = "", existingCookie = "", reEncodedCookie = "";
1794
+ try {
1795
+ paramsJSON = JSON.parse(b64decode(refParam));
1796
+ } catch (error) {
1797
+ _log$4("Unable to decode params", error);
1798
+ return;
1799
+ }
1800
+ try {
1801
+ existingCookie = JSON.parse(b64decode(api$1.get("_saasquatch")));
1802
+ _log$4("existing cookie", existingCookie);
1803
+ } catch (error) {
1804
+ _log$4("Unable to retrieve cookie", error);
1805
+ }
1806
+ try {
1807
+ const domain = getTopDomain();
1808
+ _log$4("domain retrieved:", domain);
1809
+ if (existingCookie) {
1810
+ const newCookie = deepMerge(existingCookie, paramsJSON);
1811
+ reEncodedCookie = b64encode(JSON.stringify(newCookie));
1812
+ _log$4("cookie to store:", newCookie);
1813
+ } else {
1814
+ reEncodedCookie = b64encode(JSON.stringify(paramsJSON));
1815
+ _log$4("cookie to store:", paramsJSON);
1816
+ }
1817
+ api$1.set("_saasquatch", reEncodedCookie, {
1818
+ expires: 365,
1819
+ secure: false,
1820
+ sameSite: "Lax",
1821
+ domain,
1822
+ path: "/"
1823
+ });
1824
+ } catch (error) {
1825
+ _log$4("Unable to set cookie", error);
1826
+ }
1827
+ }
1828
+ }
1829
+ const _log$3 = browserExports.debug("squatch-js");
1830
+ function _getAutoConfig() {
1831
+ var _a2;
1832
+ const queryString = window.location.search;
1833
+ const urlParams = new URLSearchParams(queryString);
1834
+ const refParam = urlParams.get("_saasquatchExtra") || "";
1835
+ if (!refParam) {
1836
+ _log$3("No _saasquatchExtra param");
1837
+ return;
1838
+ }
1839
+ const config = validateConfig({
1840
+ tenantAlias: "UNKNOWN"
1841
+ });
1842
+ if (!config.domain) {
1843
+ _log$3("domain must be provided in config to use _saasquatchExtra");
1844
+ return;
1845
+ }
1846
+ let raw;
1847
+ try {
1848
+ raw = JSON.parse(b64decode(refParam));
1849
+ } catch (e) {
1850
+ _log$3("Unable to decode _saasquatchExtra config");
1851
+ return;
1852
+ }
1853
+ function normalizeDomain(domain) {
1854
+ return domain.replace(/^https?:\/\//, "");
1855
+ }
1856
+ const normalizedDomain = normalizeDomain(config.domain);
1857
+ const tenantAlias = Object.keys((raw == null ? void 0 : raw[normalizedDomain]) || {})[0];
1858
+ const widgetConfig = (_a2 = raw == null ? void 0 : raw[normalizedDomain]) == null ? void 0 : _a2[tenantAlias];
1859
+ if (!widgetConfig) {
1860
+ _log$3("_saasquatchExtra did not have an expected structure");
1861
+ return void 0;
1862
+ }
1863
+ const { autoPopupWidgetType, ...rest } = widgetConfig;
1864
+ return {
1865
+ widgetConfig: {
1866
+ widgetType: autoPopupWidgetType,
1867
+ displayOnLoad: true,
1868
+ ...rest
1869
+ },
1870
+ squatchConfig: {
1871
+ ...config,
1872
+ tenantAlias
1873
+ }
1874
+ };
1875
+ }
1876
+ const getSkeleton = ({
1877
+ type = "verified-access",
1878
+ height = "500px",
1879
+ skeletonBackgroundColor = "#e0e0e0",
1880
+ skeletonShimmerColor = "#f5f5f5"
1881
+ }) => {
1882
+ const referrerHTML = `
1883
+ <div class="hero-section">
1884
+ <div class="hero-content">
1885
+ <div class="skeleton sk-title-lg"></div>
1886
+ <div class="skeleton sk-text"></div>
1887
+ <div class="skeleton sk-text sk-text-short"></div>
1888
+ </div>
1889
+ <div class="skeleton hero-image"></div>
1890
+ </div>
1891
+
1892
+ <div class="share-section">
1893
+ <div class="skeleton sk-label"></div>
1894
+ <div class="skeleton sk-input"></div>
1895
+ <div class="social-buttons">
1896
+ <div class="skeleton sk-btn-social"></div>
1897
+ <div class="skeleton sk-btn-social"></div>
1898
+ <div class="skeleton sk-btn-social"></div>
1899
+ <div class="skeleton sk-btn-social"></div>
1900
+ </div>
1901
+ </div>
1902
+
1903
+ <div class="skeleton sk-title-md" style="margin-top: 0; width: 30%; margin-left: auto; margin-right: auto"></div>
1904
+ <div class="skeleton sk-text" style="width: 60%; margin-left: auto; margin-right: auto"></div>
1905
+
1906
+ <div class="stats-section">
1907
+ <div class="stat-card">
1908
+ <div class="skeleton sk-stat-num"></div>
1909
+ <div class="skeleton sk-stat-label"></div>
1910
+ </div>
1911
+ <div class="stat-card stat-divider">
1912
+ <div class="skeleton sk-stat-num"></div>
1913
+ <div class="skeleton sk-stat-label"></div>
1914
+ </div>
1915
+ </div>
1916
+
1917
+ <div class="skeleton sk-title-md"></div>
1918
+
1919
+ <div class="table-header">
1920
+ <div class="skeleton sk-th col-user"></div>
1921
+ <div class="skeleton sk-th col-status"></div>
1922
+ <div class="skeleton sk-th col-reward"></div>
1923
+ <div class="skeleton sk-th col-date"></div>
1924
+ </div>
1925
+
1926
+ <div class="table-row">
1927
+ <div class="col-user"><div class="skeleton sk-text" style="width: 70%; margin: 0"></div></div>
1928
+ <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
1929
+ <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
1930
+ <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
1931
+ </div>
1932
+
1933
+ <div class="table-row">
1934
+ <div class="col-user"><div class="skeleton sk-text" style="width: 60%; margin: 0"></div></div>
1935
+ <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
1936
+ <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
1937
+ <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
1938
+ </div>
1939
+
1940
+ <div class="table-row">
1941
+ <div class="col-user"><div class="skeleton sk-text" style="width: 75%; margin: 0"></div></div>
1942
+ <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
1943
+ <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
1944
+ <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
1945
+ </div>
1946
+
1947
+ <div class="pagination">
1948
+ <div class="skeleton sk-btn-page"></div>
1949
+ <div class="skeleton sk-btn-page"></div>
1950
+ </div>
1951
+ `;
1952
+ const instantAccessHTML = `
1953
+ <div class="hero-section instant-access-layout">
1954
+ <div class="skeleton hero-image ia-image"></div>
1955
+
1956
+ <div class="hero-content ia-content">
1957
+ <div class="skeleton sk-title-lg ia-center"></div>
1958
+ <div class="skeleton sk-text ia-center"></div>
1959
+
1960
+ <div class="skeleton sk-btn-action"></div>
1961
+
1962
+ <div class="skeleton sk-label"></div>
1963
+ <div class="input-group">
1964
+ <div class="skeleton sk-input"></div>
1965
+ <div class="skeleton sk-btn-copy"></div>
1966
+ </div>
1967
+
1968
+ <div class="skeleton sk-text-short ia-center" style="margin-top: 20px; width: 30%"></div>
1969
+ <div class="skeleton sk-text-short ia-center" style="width: 20%"></div>
1970
+ </div>
1971
+ </div>
1972
+ `;
1973
+ return `
19
1974
  <style>
20
1975
  * {
21
1976
  box-sizing: border-box;
@@ -37,12 +1992,12 @@
37
1992
  }
38
1993
 
39
1994
  .skeleton {
40
- background: ${e};
1995
+ background: ${skeletonBackgroundColor};
41
1996
  background: linear-gradient(
42
1997
  90deg,
43
- ${e} 25%,
44
- #f5f5f5 50%,
45
- ${e} 75%
1998
+ ${skeletonBackgroundColor} 25%,
1999
+ ${skeletonShimmerColor} 50%,
2000
+ ${skeletonBackgroundColor} 75%
46
2001
  );
47
2002
  background-size: 200% 100%;
48
2003
  animation: shimmer 1.5s infinite linear;
@@ -172,161 +2127,420 @@
172
2127
  </style>
173
2128
 
174
2129
  <div class="widget-container">
175
- ${o==="verified-access"?`
176
- <div class="hero-section">
177
- <div class="hero-content">
178
- <div class="skeleton sk-title-lg"></div>
179
- <div class="skeleton sk-text"></div>
180
- <div class="skeleton sk-text sk-text-short"></div>
181
- </div>
182
- <div class="skeleton hero-image"></div>
183
- </div>
184
-
185
- <div class="share-section">
186
- <div class="skeleton sk-label"></div>
187
- <div class="skeleton sk-input"></div>
188
- <div class="social-buttons">
189
- <div class="skeleton sk-btn-social"></div>
190
- <div class="skeleton sk-btn-social"></div>
191
- <div class="skeleton sk-btn-social"></div>
192
- <div class="skeleton sk-btn-social"></div>
193
- </div>
194
- </div>
195
-
196
- <div class="skeleton sk-title-md" style="margin-top: 0; width: 30%; margin-left: auto; margin-right: auto"></div>
197
- <div class="skeleton sk-text" style="width: 60%; margin-left: auto; margin-right: auto"></div>
198
-
199
- <div class="stats-section">
200
- <div class="stat-card">
201
- <div class="skeleton sk-stat-num"></div>
202
- <div class="skeleton sk-stat-label"></div>
203
- </div>
204
- <div class="stat-card stat-divider">
205
- <div class="skeleton sk-stat-num"></div>
206
- <div class="skeleton sk-stat-label"></div>
207
- </div>
208
- </div>
209
-
210
- <div class="skeleton sk-title-md"></div>
211
-
212
- <div class="table-header">
213
- <div class="skeleton sk-th col-user"></div>
214
- <div class="skeleton sk-th col-status"></div>
215
- <div class="skeleton sk-th col-reward"></div>
216
- <div class="skeleton sk-th col-date"></div>
217
- </div>
218
-
219
- <div class="table-row">
220
- <div class="col-user"><div class="skeleton sk-text" style="width: 70%; margin: 0"></div></div>
221
- <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
222
- <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
223
- <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
224
- </div>
225
-
226
- <div class="table-row">
227
- <div class="col-user"><div class="skeleton sk-text" style="width: 60%; margin: 0"></div></div>
228
- <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
229
- <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
230
- <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
231
- </div>
232
-
233
- <div class="table-row">
234
- <div class="col-user"><div class="skeleton sk-text" style="width: 75%; margin: 0"></div></div>
235
- <div class="col-status"><div class="skeleton sk-badge" style="margin: 0"></div></div>
236
- <div class="col-reward"><div class="skeleton sk-reward-block" style="margin: 0"></div></div>
237
- <div class="col-date"><div class="skeleton sk-text" style="width: 80%; margin: 0"></div></div>
238
- </div>
239
-
240
- <div class="pagination">
241
- <div class="skeleton sk-btn-page"></div>
242
- <div class="skeleton sk-btn-page"></div>
243
- </div>
244
- `:`
245
- <div class="hero-section instant-access-layout">
246
- <div class="skeleton hero-image ia-image"></div>
247
-
248
- <div class="hero-content ia-content">
249
- <div class="skeleton sk-title-lg ia-center"></div>
250
- <div class="skeleton sk-text ia-center"></div>
251
-
252
- <div class="skeleton sk-btn-action"></div>
253
-
254
- <div class="skeleton sk-label"></div>
255
- <div class="input-group">
256
- <div class="skeleton sk-input"></div>
257
- <div class="skeleton sk-btn-copy"></div>
258
- </div>
259
-
260
- <div class="skeleton sk-text-short ia-center" style="margin-top: 20px; width: 30%"></div>
261
- <div class="skeleton sk-text-short ia-center" style="width: 20%"></div>
262
- </div>
263
- </div>
264
- `}
2130
+ ${type === "verified-access" ? referrerHTML : instantAccessHTML}
265
2131
  </div>
266
- `},$e=Object.freeze(Object.defineProperty({__proto__:null,getSkeleton:ae},Symbol.toStringTag,{value:"Module"})),v=E("squatch-js:widget");class de{constructor(t){l(this,"type");l(this,"content");l(this,"analyticsApi");l(this,"widgetApi");l(this,"context");l(this,"npmCdn");l(this,"container");l(this,"loadEventListener",null);var e;v("widget initializing ..."),this.content=t.content==="error"?this._error(t.rsCode):t.content,this.type=t.type,this.widgetApi=t.api,this.npmCdn=t.npmCdn,this.analyticsApi=new re({domain:t.domain}),this.context=t.context,this.container=((e=t.context)==null?void 0:e.container)||t.container}_findElement(){let t;if(typeof this.container=="string"?(t=document.querySelector(this.container),v("loading widget with selector",t)):this.container instanceof HTMLElement?(t=this.container,v("loading widget with container",t)):this.container?(t=null,v("container must be an HTMLElement or string",this.container)):(t=document.querySelector("#squatchembed")||document.querySelector(".squatchembed")||document.querySelector("#impactembed")||document.querySelector(".impactembed"),v("loading widget with default selector",t)),!(t instanceof HTMLElement))throw new Error(`element with selector '${this.container||"#squatchembed, .squatchembed, #impactembed, or .impactembed"}' not found.'`);return t}_createFrame(t){const e=document.createElement("iframe");return e.squatchJsApi=this,e.id="squatchFrame",e.width="100%",e.src="about:blank",e.scrolling="no",e.setAttribute("style","border: 0; background-color: none; width: 1px; min-width: 100%; display: block;"),t!=null&&t.minWidth&&(e.style.minWidth=t.minWidth),t!=null&&t.maxWidth&&(e.style.maxWidth=t.maxWidth),(t!=null&&t.maxWidth||t!=null&&t.minWidth)&&(e.style.width="100%"),t!=null&&t.initialHeight&&(e.height=String(t.initialHeight)),e}_findFrame(){const t=this.container?this._findElement():document.body;return(t.shadowRoot||t).querySelector("iframe#squatchFrame")}_detachLoadEventListener(t){this.loadEventListener&&(t.removeEventListener("sq:user-registration",this.loadEventListener),this.loadEventListener=null)}_attachLoadEventListener(t,e){this.loadEventListener===null&&(this.loadEventListener=n=>{this._loadEvent({...e,userId:n.detail.userId,accountId:n.detail.accountId})},t.addEventListener("sq:user-registration",this.loadEventListener))}_loadEvent(t){var n;if(!t)return;if(!_(t))throw new Error("Widget Load event identity property is not an object");let e;if("programId"in t){if(!t.tenantAlias||!t.accountId||!t.userId||!t.engagementMedium)throw new Error("Widget Load event missing required properties");e={tenantAlias:t.tenantAlias,externalAccountId:t.accountId,externalUserId:t.userId,engagementMedium:t.engagementMedium,programId:t.programId}}else{const{analytics:i,mode:s}=t;e={tenantAlias:i.attributes.tenant,externalAccountId:i.attributes.accountId,externalUserId:i.attributes.userId,engagementMedium:s.widgetMode}}(n=this.analyticsApi.pushAnalyticsLoadEvent(e))==null||n.then(i=>{v(`${e.engagementMedium} loaded event recorded.`)}).catch(i=>{v(`ERROR: pushAnalyticsLoadEvent() ${i}`)})}_shareEvent(t,e){t&&this.analyticsApi.pushAnalyticsShareClickedEvent({tenantAlias:t.analytics.attributes.tenant,externalAccountId:t.analytics.attributes.accountId,externalUserId:t.analytics.attributes.userId,engagementMedium:t.mode.widgetMode,shareMedium:e}).then(n=>{v(`${t.mode.widgetMode} share ${e} event recorded. ${n}`)}).catch(n=>{v(`ERROR: pushAnalyticsShareClickedEvent() ${n}`)})}_error(t,e="modal",n=""){return`<!DOCTYPE html>
267
- <!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]-->
268
- <!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]-->
269
- <!--[if gt IE 8]><!--><html lang="en"><!--<![endif]-->
270
- <head>
271
- <link rel="stylesheet" media="all" href="https://fast.ssqt.io/assets/css/widget/errorpage.css">
272
- <style>
273
- ${n}
274
- </style>
275
- </head>
276
- <body>
277
-
278
- <div class="squatch-container ${e}" style="width:100%">
279
- <div class="errorheader">
280
- <button type="button" class="close" onclick="window.frameElement.squatchJsApi.close();">&times;</button>
281
- <p class="errortitle">Error</p>
282
- </div>
283
- <div class="errorbody">
284
- <div class="sadface"><img src="https://fast.ssqt.io/assets/images/face.png"></div>
285
- <h4>Our referral program is temporarily unavailable.</h4><br>
286
- <p>Please reload the page or check back later.</p>
287
- <p>If the persists please contact our support team.</p>
288
- <br>
289
- <br>
290
- <div class="right-align errtxt">
291
- Error Code: ${t}
292
- </div>
293
- </div>
294
- </div>
295
- </body>
296
- </html>`}async _findInnerContainer(t){const{contentWindow:e}=t;if(!e)throw new Error("Squatch.js frame inner frame is empty");const n=e.document;function i(){const r=n.getElementsByTagName("sqh-global-container"),a=n.getElementsByClassName("squatch-container");return r.length>0?r[0]:a.length>0?a[0]:null}let s=null;for(let r=0;r<5&&(s=i(),!s);r++)await qe(100);return s||n.body}_getSkeletonPreloadHTML(t,e){if(!t)return"";const n=this.context.type==="passwordless"?"instant-access":"verified-access",i=ae({type:n,height:"100%"});return`
297
- <div id="sq-preload" style="visibility: visible; position: absolute; top: 0; left: 0; width: 100%; z-index: 9999; background: ${e||"white"};">
298
- ${i}
299
- </div>
300
- <script>(${Se.toString()})()<\/script>
301
- `}reload({email:t,firstName:e,lastName:n},i){const s=this._findFrame();if(!s)throw new Error("Could not find widget iframe");const r=s.contentWindow,a=this.context.engagementMedium||"POPUP";if(!r)throw new Error("Frame needs a content window");let d;if(this.context.type==="upsert"){if(!this.context.user)throw new Error("Can't reload without user ids");let c={email:t||null,firstName:e||null,lastName:n||null,id:this.context.user.id,accountId:this.context.user.accountId};d=this.widgetApi.upsertUser({user:c,engagementMedium:a,widgetType:this.type,jwt:i})}else if(this.context.type==="passwordless")d=this.widgetApi.render({user:void 0,engagementMedium:a,widgetType:this.type,jwt:void 0});else throw new Error("can't reload an error widget");d.then(({template:c})=>{c&&(this.content=c,this.__deprecated__register(s,{email:t,engagementMedium:a},()=>{this.load(),a==="POPUP"&&this.open()}))}).catch(({message:c})=>{v(`${c}`)})}__deprecated__register(t,e,n){const s=t.contentWindow.document,r=s.createElement("button"),a=s.getElementsByClassName("squatch-register")[0];if(a){r.className="btn btn-primary",r.id="show-stats-btn",r.textContent=this.type==="REFERRER_WIDGET"?"Show Stats":"Show Reward";const d=e.engagementMedium==="POPUP"?"margin-top: 10px; max-width: 130px; width: 100%;":"margin-top: 10px;";r.setAttribute("style",d),r.onclick=n,a.style.paddingTop="30px",a.innerHTML=`<p><strong>${e.email}</strong><br>Has been successfully registered</p>`,a.appendChild(r)}}}function qe(o){return new Promise(t=>{setTimeout(t,o)})}function Se(){var o=setTimeout(t,1e4);function t(){var n=document.getElementById("sq-preload");n&&n.remove(),clearTimeout(o)}function e(){var n=new Set;if(document.querySelectorAll("*").forEach(function(i){i.tagName.includes("-")&&n.add(i.tagName.toLowerCase())}),!n.size)return t();Promise.all(Array.from(n).map(function(i){return customElements.whenDefined(i)})).then(function(){requestAnimationFrame(function(){requestAnimationFrame(t)})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}const T=E("squatch-js:EMBEDwidget");class q extends de{constructor(e,n){super(e);l(this,"show",this.open);l(this,"hide",this.close);n&&(this.container=n)}async load(){var f,b,x,y,L,fe,we,ye,ve;const e=(b=(f=this.context.widgetConfig)==null?void 0:f.values)==null?void 0:b.brandingConfig,n=(x=this.content)==null?void 0:x.includes("mint-components"),i=(e==null?void 0:e.loadingHeight)||500,s=(y=e==null?void 0:e.widgetSize)==null?void 0:y.embeddedWidgets,r=s!=null&&s.maxWidth?F(s.maxWidth):"",a=s!=null&&s.minWidth?F(s.minWidth):"",d=this._createFrame({minWidth:a,maxWidth:r,initialHeight:i}),c=this._findElement();(L=this.context)!=null&&L.container&&(c.style.visibility="hidden",c.style.height="0",c.style["overflow-y"]="hidden"),this.container?c.shadowRoot?((fe=c.shadowRoot.lastChild)==null?void 0:fe.nodeName)==="IFRAME"?c.shadowRoot.replaceChild(d,c.shadowRoot.lastChild):c.shadowRoot.appendChild(d):c.firstChild?c.replaceChild(d,c.firstChild):c.appendChild(d):(!c.firstChild||c.firstChild.nodeName==="#text")&&c.appendChild(d);const{contentWindow:h}=d;if(!h)throw new Error("Frame needs a content window");const p=h.document;p.open();const w=this.widgetApi.domain==="https://staging.referralsaasquatch.com"?"-staging":"";p.write(`
302
- ${(we=e==null?void 0:e.main)!=null&&we.brandFont?`
303
- <link rel="preconnect" href="https://fast${w}.ssqt.io">
304
- <link rel="preconnect" href="https://fonts.gstatic.com">
305
- <link rel="preconnect" href="https://fonts.googleapis.com">
306
- <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent((ye=e==null?void 0:e.main)==null?void 0:ye.brandFont)}" as="style">`:""}
307
- <link rel="dns-prefetch" href="https://res.cloudinary.com">
308
- <link rel="preconnect" href="https://res.cloudinary.com" crossorigin>
309
- ${n?`
310
- <style data-styles>
311
- html { visibility: hidden; }
312
- </style>`:""}
313
- ${this._getSkeletonPreloadHTML(n,(ve=e==null?void 0:e.color)==null?void 0:ve.backgroundColor)}
314
- ${this.content}
315
- <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>
316
- `),p.close(),te(p,async()=>{const ke=h.squatch||h.widgetIdent;d.height=i;const Ze=new h.ResizeObserver(tt=>{for(const nt of tt){const{height:it}=nt.contentRect;d.height=it}}),et=await this._findInnerContainer(d);Ze.observe(et),this._shouldFireLoadEvent()?(this._loadEvent(ke),T("loaded")):p&&this._attachLoadEventListener(p,ke)})}open(){const e=this._findFrame();if(!e)return T("no target element to open");if(!e.contentWindow)return T("Frame needs a content window");const n=this._findElement();n.style.visibility="unset",n.style.height="auto",n.style["overflow-y"]="auto",e.contentWindow.document.dispatchEvent(new CustomEvent("sq:refresh"));const i=e.contentWindow.squatch||e.contentWindow.widgetIdent;if(this.context.user)this._loadEvent(i),T("loaded");else{if(!e.contentDocument)return;this._attachLoadEventListener(e.contentDocument,i)}}close(){const e=this._findFrame();if(!e)return T("no target element to close");e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this._findElement();n.style.visibility="hidden",n.style.height="0",n.style["overflow-y"]="hidden",T("Embed widget closed")}_error(e,n="embed",i=""){return super._error(e,n,i)}_shouldFireLoadEvent(){const e=!this.container,n=this.container instanceof HTMLElement&&(this.container.tagName.startsWith("SQUATCH-")||this.container.tagName.startsWith("IMPACT-"));return!!this.context.user&&(e||n)}}const S=E("squatch-js:POPUPwidget");let H=0;class P extends de{constructor(e,n=".squatchpop"){super(e);l(this,"trigger");l(this,"id");l(this,"show",this.open);l(this,"hide",this.close);this.trigger=n,this.container?this.id="squatchModal":(this.id=H===0?"squatchModal":`squatchModal__${H}`,H=H+1),document.head.insertAdjacentHTML("beforeend",`<style>#${this.id}::-webkit-scrollbar { display: none; }</style>`)}_initialiseCTA(){if(!this.trigger)return;let e;try{e=document.querySelector(this.trigger)||document.querySelector(".impactpop"),this.trigger&&!e&&S("No element found with trigger selector",this.trigger)}catch{S("Not a valid selector",this.trigger)}e&&(e.onclick=()=>{this.open()})}_createPopupDialog(e){var d;const n=document.createElement("dialog"),i=(d=e==null?void 0:e.widgetSize)==null?void 0:d.popupWidgets,s=i!=null&&i.minWidth?F(i.minWidth):"auto",r=i!=null&&i.maxWidth?F(i.maxWidth):"500px";n.id=this.id,n.setAttribute("style",`width: 100%; min-width: ${s}; max-width: ${r}; border: none; padding: 0;`);const a=c=>{c.stopPropagation(),c.target===n&&n.close()};return n.addEventListener("click",a),n}async load(){var g,w,f,b,x,y,L;const e=(w=(g=this.context.widgetConfig)==null?void 0:g.values)==null?void 0:w.brandingConfig,n=(e==null?void 0:e.loadingHeight)||500,i=(f=this.content)==null?void 0:f.includes("mint-components"),s=this._createFrame();s.style.height=n+"px",this._initialiseCTA();const r=this.container?this._findElement():document.body,a=(r==null?void 0:r.shadowRoot)||r,d=this._createPopupDialog(e);d.appendChild(s),((b=a.lastChild)==null?void 0:b.nodeName)==="DIALOG"?a.replaceChild(d,a.lastChild):a.appendChild(d);const{contentWindow:c}=s;if(!c)throw new Error("Frame needs a content window");const h=c.document;h.open();const p=this.widgetApi.domain;h.write(`
317
- ${(x=e==null?void 0:e.main)!=null&&x.brandFont?`
318
- <link rel="preconnect" href="https://fast${p==="https://staging.referralsaasquatch.com"?"-staging":""}.ssqt.io">
319
- <link rel="preconnect" href="https://fonts.gstatic.com">
320
- <link rel="preconnect" href="https://fonts.googleapis.com">
321
- <link rel="preload" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent((y=e==null?void 0:e.main)==null?void 0:y.brandFont)}" as="style">`:""}
322
- <link rel="dns-prefetch" href="https://res.cloudinary.com">
323
- <link rel="preconnect" href="https://res.cloudinary.com" crossorigin>
324
- ${i?`
325
- <style data-styles>
326
- html { visibility: hidden; }
327
- </style>`:""}
328
- ${this._getSkeletonPreloadHTML(i,(L=e==null?void 0:e.color)==null?void 0:L.backgroundColor)}
329
- ${this.content}
330
- <script src="${this.npmCdn}/resize-observer-polyfill@1.5.x"><\/script>
331
- `),h.close(),S("Popup template loaded into iframe"),await this._setupResizeHandler(s)}async _setupResizeHandler(e){const{contentWindow:n}=e;if(!n)throw new Error("Frame needs a content window");const i=n.document;te(i,async()=>{i.body.style.overflowY="hidden";let s=!0;new n.ResizeObserver(a=>{for(const d of a){const{top:c,bottom:h}=d.contentRect,p=h+c;p<=0||(s?(s=!1,e.style.height="0",e.height=i.body.scrollHeight+"",e.style.height=""):e.height=p+"",d.target.style="")}}).observe(await this._findInnerContainer(e))})}open(){const e=this.container?this._findElement():document.body,i=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!i)throw new Error("Could not determine container div");i.showModal();const s=this._findFrame();if(!s)throw new Error("Could not find iframe");const{contentWindow:r}=s;if(!r)throw new Error("Squatch.js has an empty iframe");const a=r.document;te(a,()=>{var c;const d=r.squatch||r.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),S("Popup opened")):this._attachLoadEventListener(a,d)})}close(){const e=this._findFrame();e!=null&&e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this.container?this._findElement():document.body,s=(n.shadowRoot||n).querySelector(`#${this.id}`);if(!s)throw new Error("Could not determine container div");s.close(),S("Popup closed")}_clickedOutside({target:e}){}_error(e,n="modal",i=""){return super._error(e,n,i||"body { margin: 0; } .modal { box-shadow: none; border: 0; }")}}const k=E("squatch-js:widgets");class R{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=W(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new N(e)}async upsertUser(t){const n=oe(t);try{const i=await this.api.upsertUser(n);return{widget:this._renderWidget(i,n,{type:"upsert",user:n.user,engagementMedium:t.engagementMedium,container:t.container,trigger:t.trigger,widgetConfig:{values:{brandingConfig:i==null?void 0:i.brandingConfig}}}),user:i.user}}catch(i){throw k(i),i.apiErrorCode&&this._renderErrorWidget(i,t.engagementMedium),new Error(i)}}async render(t){const n=se(t);try{const i=await this.api.render(n);return{widget:this._renderWidget(i,n,{type:"passwordless",engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger,widgetConfig:i==null?void 0:i.widgetConfig}),user:i.user}}catch(i){throw i.apiErrorCode&&this._renderErrorWidget(i,n.engagementMedium),new Error(i)}}async autofill(t){const e=t;if(typeof e=="function"){try{const s=await this.api.squatchReferralCookie();e(s)}catch(s){throw k("Autofill error",s),new Error(s)}return}if(typeof e!="string")throw new Error("Autofill accepts a string or function");let n=document.querySelectorAll(e),i;if(n.length>0)i=n[0];else throw k("Element id/class or function missing"),new Error("Element id/class or function missing");try{const s=await this.api.squatchReferralCookie();i.value=s.codes[0]}catch(s){throw new Error(s)}}_renderWidget(t,e,n){var d;if(k("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const r=t.jsOptions||{},a={content:t.template,type:e.widgetType||((d=r.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return r.widgetUrlMappings&&r.widgetUrlMappings.forEach(c=>{var h,p;R._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(p=(h=t.user)==null?void 0:h.referredBy)!=null&&p.code?(s=c.displayOnLoad,k(`Display ${c.widgetType} on ${c.url}`)):k(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))}),r.fuelTankAutofillUrls&&(k("We found a fuel tank autofill!"),r.fuelTankAutofillUrls.forEach(({url:c,formSelector:h})=>{var p,g,w;if(R._matchesUrl(c)&&(k("Fuel Tank URL matches"),(g=(p=t.user)==null?void 0:p.referredBy)!=null&&g.code)){const f=document.querySelector(h);f?f.value=((w=t.user.referredBy.referredReward)==null?void 0:w.fuelTankCode)||"":k(new Error(`Element with id/class ${h} was not found.`))}})),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(a):(i=this._renderPopupWidget(a),s&&i.open()),i}_renderPopupWidget(t){const e=new P(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new q(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,message:s}=t;k(new Error(`${n} (${i}) ${s}`));const r={content:"error",rsCode:i,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let a;e==="EMBED"?(a=new q(r),a.load()):e==="POPUP"&&(a=new P(r),a.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Pe{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=W(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=Re(n),{jwt:r}=Ue(i),a=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${a}/open/account/${c}/user/${d}/events`,p=this.domain+h;return ee(p,JSON.stringify(s),r)}}function Re(o){if(!_(o))throw new Error("tracking parameter must be an object");if(!(o!=null&&o.accountId))throw new Error("accountId field is required");if(!(o!=null&&o.events))throw new Error("events field is required");if(!(o!=null&&o.userId))throw new Error("userId field is required");const t=o;if(!Array.isArray(t.events))throw new Error("'events' should be an array");return t}function Ue(o){if(!_(o))throw new Error("'options' should be an object");return o}function Me(){var i;const o=window[K]?K:D,t=((i=window["_"+o])==null?void 0:i.ready)||[],e=window.impactOnReady||window.squatchOnReady,n=[...t,e].filter(s=>!!s);setTimeout(()=>{window[D]&&(window[K]=window[D],n.forEach(s=>s()),window[D]._auto(),window["_"+o]=void 0,delete window["_"+o])},0)}const C=E("squatch-js"),ce=o=>typeof o=="object"&&!Array.isArray(o),le=(o,t)=>{const e=i=>ce(t[i])&&o.hasOwnProperty(i)&&ce(o[i]),n=Object.getOwnPropertyNames(t).map(i=>({[i]:e(i)?le(o[i],t[i]):t[i]})).reduce((i,s)=>({...i,...s}),{});return{...o,...n}};function B(o){const t=atob(o.replace(/_/g,"/").replace(/-/g,"+")),e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return new TextDecoder("utf8").decode(e)}function he(o){const t=new TextEncoder().encode(o),e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Le(){var o,t,e="weird_get_top_level_domain=cookie",n=document.location.hostname.split(".");for(o=n.length-1;o>=0;o--)if(t=n.slice(o).join("."),document.cookie=e+";domain=."+t+";",document.cookie.indexOf(e)>-1)return document.cookie=e.split("=")[0]+"=;domain=."+t+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",t}function Oe(){const o=window.location.search,e=new URLSearchParams(o).get("_saasquatch")||"";if(e){let n="",i="",s="";try{n=JSON.parse(B(e))}catch(r){C("Unable to decode params",r);return}try{i=JSON.parse(B(j.get("_saasquatch"))),C("existing cookie",i)}catch(r){C("Unable to retrieve cookie",r)}try{const r=Le();if(C("domain retrieved:",r),i){const a=le(i,n);s=he(JSON.stringify(a)),C("cookie to store:",a)}else s=he(JSON.stringify(n)),C("cookie to store:",n);j.set("_saasquatch",s,{expires:365,secure:!1,sameSite:"Lax",domain:r,path:"/"})}catch(r){C("Unable to set cookie",r)}}}const J=E("squatch-js");function je(){var p;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){J("No _saasquatchExtra param");return}const n=W({tenantAlias:"UNKNOWN"});if(!n.domain){J("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(B(e))}catch{J("Unable to decode _saasquatchExtra config");return}function s(g){return g.replace(/^https?:\/\//,"")}const r=s(n.domain),a=Object.keys((i==null?void 0:i[r])||{})[0],d=(p=i==null?void 0:i[r])==null?void 0:p[a];if(!d){J("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:c,...h}=d;return{widgetConfig:{widgetType:c,displayOnLoad:!0,...h},squatchConfig:{...n,tenantAlias:a}}}const De=E("squatch-js:decodeUserJwt");function Ne(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=B(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return De(e),null}}const ue=E("squatch-js:DeclarativeWidget");class pe extends HTMLElement{constructor(){super();l(this,"config");l(this,"token");l(this,"tenant");l(this,"widgetType");l(this,"locale");l(this,"widgetApi");l(this,"analyticsApi");l(this,"widgetInstance");l(this,"type");l(this,"container");l(this,"element");l(this,"loaded");l(this,"_setWidget",(e,n)=>{var s;const i={api:this.widgetApi,content:e.template,context:{type:n.type,user:n.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:e.widgetConfig},type:this.widgetType,domain:((s=this.config)==null?void 0:s.domain)||I,npmCdn:Y,container:this};if(this.type==="EMBED")return new q(i);{const r=this.firstChild?null:void 0;return new P(i,r)}});l(this,"setErrorWidget",e=>{var i;const n={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((i=this.config)==null?void 0:i.domain)||I,npmCdn:Y,container:this};if(this.type==="EMBED")return new q(n);{const s=this.firstChild?null:void 0;return new P(n,s)}});l(this,"reload",this.renderWidget);l(this,"show",this.open);l(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=Z(),this.token=$(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new N({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||I}),this.analyticsApi=new re({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||I})}getWidgetType(e){return e&&(e.includes("websiteReferralWidget")||e.includes("friendWidget"))?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),ue("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(e=>this._setWidget(e,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const e=Ne(this.token);return e?(ue("Rendering as a Verified widget"),await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token}),await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then(i=>this._setWidget(i,{type:"upsert",user:e})).catch(this.setErrorWidget)):this.setErrorWidget(Error("No user object in token."))}async getWidgetInstance(){let e;if(this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale,!this.widgetType)throw new Error("No widget has been specified");return this.token?e=await this.renderUserUpsertVariant():e=await this.renderPasswordlessVariant(),this.widgetInstance=e,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),e}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(e,n,i){if(!(n===i||!this.loaded))switch(e){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),this.widgetType=this.getAttribute("widget")||void 0;const e=this.getWidgetType(this.widgetType),{getSkeleton:n}=await Promise.resolve().then(()=>$e),i=n({height:"100%",type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const r=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const d=r.getElementById("#squatchModal");d&&(d.innerHTML="",d.appendChild(s))}else r.innerHTML="",r.appendChild(s);await this.renderWidget();const a=r.getElementById("loading-skeleton");a&&a.remove(),this.getAttribute("open")!==null&&this.open()}}class ne extends pe{constructor(){super(),this.type="EMBED",this.loaded=!1}}class ie extends pe{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",t=>{t.stopPropagation(),this.open()})}}class Fe extends ne{}class He extends ie{}class Be extends ne{}class Je extends ie{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Fe),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",Be),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",He),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Je);function ze(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const U=E("squatch-js");let z=null,G=null,V=null;function Ge(){return z||M({}),z}function X(){return G||M({}),G}function Ve(){return V||M({}),V}function Xe(o){var t;return(t=X())==null?void 0:t.render(o)}function Qe(){var t;const o=je();if(o){const{squatchConfig:e,widgetConfig:n}=o;return M(e),(t=X())==null?void 0:t.render(n)}}function M(o){const e=W(o);e.tenantAlias.match("^test")||e.debug?A("squatch-js*"):be(),U("initializing ..."),z=new N(e),G=new R(e),V=new Pe(e),U("Widget API instance",z),U("Widgets instance",G),U("Events API instance",V)}function Ye(o){o()}function Ke(o){X().autofill(o)}function me(){Oe()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&me(),(ge=window.squatch)!=null&&ge.init&&U("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&Me(),u.DeclarativeEmbedWidget=ne,u.DeclarativePopupWidget=ie,u.EmbedWidget=q,u.PopupWidget=P,u.WidgetApi=N,u.Widgets=R,u._auto=Qe,u.api=Ge,u.autofill=Ke,u.events=Ve,u.help=ze,u.init=M,u.pushCookie=me,u.ready=Ye,u.widget=Xe,u.widgets=X,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
2132
+ `;
2133
+ };
2134
+ const _log$2 = browserExports.debug("squatch-js:decodeUserJwt");
2135
+ function decodeUserJwt(tokenStr) {
2136
+ var _a2;
2137
+ try {
2138
+ const base64Url = tokenStr.split(".")[1];
2139
+ if (base64Url === void 0) return null;
2140
+ const jsonStr = b64decode(base64Url);
2141
+ return (_a2 = JSON.parse(jsonStr)) == null ? void 0 : _a2.user;
2142
+ } catch (e) {
2143
+ _log$2(e);
2144
+ return null;
2145
+ }
2146
+ }
2147
+ const _log$1 = debug("squatch-js:DeclarativeWidget");
2148
+ class DeclarativeWidget extends HTMLElement {
2149
+ constructor() {
2150
+ super();
2151
+ /**
2152
+ * Configuration overrides
2153
+ * @default window.squatchConfig
2154
+ */
2155
+ __publicField(this, "config");
2156
+ /**
2157
+ * Signed JWT containing user information
2158
+ * @default window.squatchToken
2159
+ */
2160
+ __publicField(this, "token");
2161
+ /**
2162
+ * Tenant alias of SaaSquatch tenant
2163
+ * @default window.squatchTenant
2164
+ */
2165
+ __publicField(this, "tenant");
2166
+ /**
2167
+ * widgetType of widget to load
2168
+ */
2169
+ __publicField(this, "widgetType");
2170
+ /**
2171
+ * Locale to render the widget in
2172
+ */
2173
+ __publicField(this, "locale");
2174
+ /**
2175
+ * Instance of {@link WidgetApi}
2176
+ */
2177
+ __publicField(this, "widgetApi");
2178
+ /**
2179
+ * Instance of {@link AnalyticsApi}
2180
+ */
2181
+ __publicField(this, "analyticsApi");
2182
+ /**
2183
+ * Instance of {@link EmbedWidget} or {@link PopupWidget}
2184
+ */
2185
+ __publicField(this, "widgetInstance");
2186
+ /**
2187
+ * Determines whether to render the widget as an embedding widget or popup widget
2188
+ */
2189
+ __publicField(this, "type");
2190
+ /**
2191
+ * Container element to contain the widget iframe
2192
+ * @default this
2193
+ */
2194
+ __publicField(this, "container");
2195
+ __publicField(this, "element");
2196
+ /**
2197
+ * Flag for if the component has been loaded or not
2198
+ * @hidden
2199
+ */
2200
+ __publicField(this, "loaded");
2201
+ __publicField(this, "_setWidget", (res, config) => {
2202
+ var _a2;
2203
+ const params = {
2204
+ api: this.widgetApi,
2205
+ content: res.template,
2206
+ context: {
2207
+ type: config.type,
2208
+ user: config.user,
2209
+ container: this.container || void 0,
2210
+ engagementMedium: this.type,
2211
+ widgetConfig: res.widgetConfig
2212
+ },
2213
+ type: this.widgetType,
2214
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
2215
+ npmCdn: DEFAULT_NPM_CDN,
2216
+ container: this
2217
+ };
2218
+ if (this.type === "EMBED") {
2219
+ return new EmbedWidget(params);
2220
+ } else {
2221
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
2222
+ return new PopupWidget(params, useFirstChildTrigger);
2223
+ }
2224
+ });
2225
+ /**
2226
+ * Builds a Widget instance for the default error widget
2227
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
2228
+ */
2229
+ __publicField(this, "setErrorWidget", (e) => {
2230
+ var _a2;
2231
+ const params = {
2232
+ api: this.widgetApi,
2233
+ content: "error",
2234
+ context: {
2235
+ type: "error",
2236
+ container: this.container || void 0
2237
+ },
2238
+ type: "ERROR_WIDGET",
2239
+ domain: ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN,
2240
+ npmCdn: DEFAULT_NPM_CDN,
2241
+ container: this
2242
+ };
2243
+ if (this.type === "EMBED") {
2244
+ return new EmbedWidget(params);
2245
+ } else {
2246
+ const useFirstChildTrigger = this.firstChild ? null : void 0;
2247
+ return new PopupWidget(params, useFirstChildTrigger);
2248
+ }
2249
+ });
2250
+ __publicField(this, "reload", this.renderWidget);
2251
+ __publicField(this, "show", this.open);
2252
+ __publicField(this, "hide", this.close);
2253
+ this.attachShadow({
2254
+ mode: "open"
2255
+ }).innerHTML = `<style>:host { display: block; }</style><slot></slot>`;
2256
+ this.config = getConfig();
2257
+ this.token = getToken();
2258
+ this.tenant = window.squatchTenant;
2259
+ this.container = this;
2260
+ }
2261
+ _setupApis(config) {
2262
+ var _a2, _b;
2263
+ if (!this.tenant) throw new Error("tenantAlias not provided");
2264
+ this.widgetApi = new WidgetApi({
2265
+ tenantAlias: (config == null ? void 0 : config.tenantAlias) || this.tenant,
2266
+ domain: (config == null ? void 0 : config.domain) || ((_a2 = this.config) == null ? void 0 : _a2.domain) || DEFAULT_DOMAIN
2267
+ });
2268
+ this.analyticsApi = new AnalyticsApi({
2269
+ domain: (config == null ? void 0 : config.domain) || ((_b = this.config) == null ? void 0 : _b.domain) || DEFAULT_DOMAIN
2270
+ });
2271
+ }
2272
+ getWidgetType(widgetType) {
2273
+ if (widgetType && (widgetType.includes("websiteReferralWidget") || widgetType.includes("friendWidget"))) {
2274
+ return "instant-access";
2275
+ }
2276
+ return "verified-access";
2277
+ }
2278
+ async renderPasswordlessVariant() {
2279
+ this._setupApis();
2280
+ _log$1("Rendering as an Instant Access widget");
2281
+ return await this.widgetApi.render({
2282
+ engagementMedium: this.type,
2283
+ widgetType: this.widgetType,
2284
+ locale: this.locale
2285
+ }).then((res) => this._setWidget(res, { type: "passwordless" })).catch(this.setErrorWidget);
2286
+ }
2287
+ async renderUserUpsertVariant() {
2288
+ this._setupApis();
2289
+ const userObj = decodeUserJwt(this.token);
2290
+ if (!userObj) {
2291
+ return this.setErrorWidget(Error("No user object in token."));
2292
+ }
2293
+ _log$1("Rendering as a Verified widget");
2294
+ await this.widgetApi.upsertUser({
2295
+ user: userObj,
2296
+ locale: this.locale,
2297
+ engagementMedium: this.type,
2298
+ widgetType: this.widgetType,
2299
+ jwt: this.token
2300
+ });
2301
+ const widgetInstance = await this.widgetApi.render({
2302
+ locale: this.locale,
2303
+ engagementMedium: this.type,
2304
+ widgetType: this.widgetType
2305
+ }).then((res) => {
2306
+ return this._setWidget(res, { type: "upsert", user: userObj });
2307
+ }).catch(this.setErrorWidget);
2308
+ return widgetInstance;
2309
+ }
2310
+ /**
2311
+ * Fetches widget content from SaaSquatch and builds a Widget instance to support rendering the widget in the DOM
2312
+ * @returns Instance of either {@link EmbedWidget} or {@link PopupWidget} depending on `this.type`
2313
+ * @throws Throws an Error if `widgetType` is undefined
2314
+ */
2315
+ async getWidgetInstance() {
2316
+ let widgetInstance;
2317
+ this.widgetType = this.getAttribute("widget") || void 0;
2318
+ this.locale = this.getAttribute("locale") || this.locale;
2319
+ if (!this.widgetType) throw new Error("No widget has been specified");
2320
+ if (!this.token) {
2321
+ widgetInstance = await this.renderPasswordlessVariant();
2322
+ } else {
2323
+ widgetInstance = await this.renderUserUpsertVariant();
2324
+ }
2325
+ this.widgetInstance = widgetInstance;
2326
+ if (this.widgetInstance)
2327
+ this.dispatchEvent(new CustomEvent("sq:widget-loaded"));
2328
+ return widgetInstance;
2329
+ }
2330
+ /**
2331
+ * Calls {@link getWidgetInstance} to build the Widget instance and loads the widget iframe into the DOM
2332
+ */
2333
+ async renderWidget() {
2334
+ await this.getWidgetInstance();
2335
+ await this.widgetInstance.load();
2336
+ }
2337
+ /**
2338
+ * Calls `open` method of `widgetInstance`
2339
+ * @throws Throws an Error if called before the widget has loaded
2340
+ */
2341
+ open() {
2342
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
2343
+ this.widgetInstance.open();
2344
+ }
2345
+ /**
2346
+ * Calls `close` method of `widgetInstance`
2347
+ * @throws Throws an Error if called before the widget has loaded
2348
+ */
2349
+ close() {
2350
+ if (!this.widgetInstance) throw new Error("Widget has not loaded yet");
2351
+ this.widgetInstance.close();
2352
+ }
2353
+ }
2354
+ class DeclarativeEmbedWidget extends DeclarativeWidget {
2355
+ constructor() {
2356
+ super();
2357
+ this.type = "EMBED";
2358
+ this.loaded = false;
2359
+ }
2360
+ static get observedAttributes() {
2361
+ return ["widget", "locale"];
2362
+ }
2363
+ attributeChangedCallback(attr, oldVal, newVal) {
2364
+ if (oldVal === newVal || !this.loaded) return;
2365
+ switch (attr) {
2366
+ case "locale":
2367
+ case "widget":
2368
+ this.connectedCallback();
2369
+ break;
2370
+ }
2371
+ }
2372
+ async connectedCallback() {
2373
+ this.loaded = true;
2374
+ this.container = this.getAttribute("container");
2375
+ this.widgetType = this.getAttribute("widget") || void 0;
2376
+ console.log("widget type", this.widgetType);
2377
+ const skeletonWidgetType = this.getWidgetType(this.widgetType);
2378
+ const skeletonHTML = getSkeleton({
2379
+ height: "100%",
2380
+ type: skeletonWidgetType
2381
+ });
2382
+ const skeletonContainer = document.createElement("div");
2383
+ skeletonContainer.id = "loading-skeleton";
2384
+ skeletonContainer.innerHTML = skeletonHTML;
2385
+ const root = this.shadowRoot || this.attachShadow({ mode: "open" });
2386
+ root.innerHTML = "";
2387
+ root.appendChild(skeletonContainer);
2388
+ await this.renderWidget();
2389
+ const loadingElement = root.getElementById("loading-skeleton");
2390
+ if (loadingElement) {
2391
+ loadingElement.remove();
2392
+ }
2393
+ if (this.getAttribute("open") !== null) this.open();
2394
+ }
2395
+ }
2396
+ class DeclarativePopupWidget extends DeclarativeWidget {
2397
+ constructor() {
2398
+ super();
2399
+ this.type = "POPUP";
2400
+ this.loaded = false;
2401
+ this.addEventListener("click", (e) => {
2402
+ e.stopPropagation();
2403
+ this.open();
2404
+ });
2405
+ }
2406
+ static get observedAttributes() {
2407
+ return ["widget", "locale"];
2408
+ }
2409
+ attributeChangedCallback(attr, oldVal, newVal) {
2410
+ if (oldVal === newVal || !this.loaded) return;
2411
+ switch (attr) {
2412
+ case "locale":
2413
+ case "widget":
2414
+ this.connectedCallback();
2415
+ break;
2416
+ }
2417
+ }
2418
+ async connectedCallback() {
2419
+ this.loaded = true;
2420
+ this.container = this.getAttribute("container");
2421
+ this.widgetType = this.getAttribute("widget") || void 0;
2422
+ const skeletonWidgetType = this.getWidgetType(this.widgetType);
2423
+ const skeletonHTML = getSkeleton({
2424
+ height: "100%",
2425
+ type: skeletonWidgetType
2426
+ });
2427
+ const skeletonContainer = document.createElement("div");
2428
+ skeletonContainer.id = "loading-skeleton";
2429
+ skeletonContainer.innerHTML = skeletonHTML;
2430
+ const root = this.shadowRoot || this.attachShadow({ mode: "open" });
2431
+ const container = root.getElementById("#squatchModal");
2432
+ console.log("Container is ", container);
2433
+ if (container) {
2434
+ container.innerHTML = "";
2435
+ container.appendChild(skeletonContainer);
2436
+ }
2437
+ await this.renderWidget();
2438
+ const loadingElement = root.getElementById("loading-skeleton");
2439
+ if (loadingElement) {
2440
+ loadingElement.remove();
2441
+ }
2442
+ if (this.getAttribute("open") !== null) this.open();
2443
+ }
2444
+ }
2445
+ class SquatchEmbed extends DeclarativeEmbedWidget {
2446
+ }
2447
+ class SquatchPopup extends DeclarativePopupWidget {
2448
+ }
2449
+ class ImpactEmbed extends DeclarativeEmbedWidget {
2450
+ }
2451
+ class ImpactPopup extends DeclarativePopupWidget {
2452
+ }
2453
+ if (!window.customElements.get("squatch-embed"))
2454
+ window.customElements.define("squatch-embed", SquatchEmbed);
2455
+ if (!window.customElements.get("impact-embed"))
2456
+ window.customElements.define("impact-embed", ImpactEmbed);
2457
+ if (!window.customElements.get("squatch-popup"))
2458
+ window.customElements.define("squatch-popup", SquatchPopup);
2459
+ if (!window.customElements.get("impact-popup"))
2460
+ window.customElements.define("impact-popup", ImpactPopup);
2461
+ function help() {
2462
+ console.log(
2463
+ `Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.`
2464
+ );
2465
+ }
2466
+ const _log = browserExports.debug("squatch-js");
2467
+ let _api = null;
2468
+ let _widgets = null;
2469
+ let _events = null;
2470
+ function api() {
2471
+ if (!_api) init({});
2472
+ return _api;
2473
+ }
2474
+ function widgets() {
2475
+ if (!_widgets) init({});
2476
+ return _widgets;
2477
+ }
2478
+ function events() {
2479
+ if (!_events) init({});
2480
+ return _events;
2481
+ }
2482
+ function widget(widgetConfig) {
2483
+ var _a2;
2484
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2485
+ }
2486
+ function _auto() {
2487
+ var _a2;
2488
+ const configs = _getAutoConfig();
2489
+ if (configs) {
2490
+ const { squatchConfig, widgetConfig } = configs;
2491
+ init(squatchConfig);
2492
+ return (_a2 = widgets()) == null ? void 0 : _a2.render(widgetConfig);
2493
+ }
2494
+ }
2495
+ function init(configIn) {
2496
+ const raw = configIn;
2497
+ const config = validateConfig(raw);
2498
+ if (config.tenantAlias.match("^test") || config.debug) {
2499
+ browserExports.debug.enable("squatch-js*");
2500
+ } else {
2501
+ browserExports.debug.disable();
2502
+ }
2503
+ _log("initializing ...");
2504
+ _api = new WidgetApi(config);
2505
+ _widgets = new Widgets(config);
2506
+ _events = new EventsApi(config);
2507
+ _log("Widget API instance", _api);
2508
+ _log("Widgets instance", _widgets);
2509
+ _log("Events API instance", _events);
2510
+ }
2511
+ function ready(fn) {
2512
+ fn();
2513
+ }
2514
+ function autofill(selector) {
2515
+ widgets().autofill(selector);
2516
+ }
2517
+ function pushCookie() {
2518
+ _pushCookie();
2519
+ }
2520
+ if (typeof document !== "undefined" && !window.SaaSquatchDoNotAutoDrop) {
2521
+ pushCookie();
2522
+ }
2523
+ if ((_a = window["squatch"]) == null ? void 0 : _a.init)
2524
+ _log(
2525
+ "Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."
2526
+ );
2527
+ if (typeof document !== "undefined") asyncLoad();
2528
+ exports2.DeclarativeEmbedWidget = DeclarativeEmbedWidget;
2529
+ exports2.DeclarativePopupWidget = DeclarativePopupWidget;
2530
+ exports2.EmbedWidget = EmbedWidget;
2531
+ exports2.PopupWidget = PopupWidget;
2532
+ exports2.WidgetApi = WidgetApi;
2533
+ exports2.Widgets = Widgets;
2534
+ exports2._auto = _auto;
2535
+ exports2.api = api;
2536
+ exports2.autofill = autofill;
2537
+ exports2.events = events;
2538
+ exports2.help = help;
2539
+ exports2.init = init;
2540
+ exports2.pushCookie = pushCookie;
2541
+ exports2.ready = ready;
2542
+ exports2.widget = widget;
2543
+ exports2.widgets = widgets;
2544
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2545
+ });
332
2546
  //# sourceMappingURL=squatch.js.map