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