@jitsu/js 1.9.18-canary.1288.20250415192732 → 1.9.18-canary.1288.20250415194526

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/analytics-plugin.d.ts +1 -0
  2. package/dist/jitsu.cjs.js +36 -31
  3. package/dist/jitsu.es.js +36 -32
  4. package/dist/web/p.js.txt +35 -31
  5. package/package.json +6 -3
  6. package/.turbo/turbo-build.log +0 -67
  7. package/.turbo/turbo-clean.log +0 -5
  8. package/.turbo/turbo-test.log +0 -2884
  9. package/__tests__/node/method-queue.test.ts +0 -66
  10. package/__tests__/node/nodejs.test.ts +0 -306
  11. package/__tests__/playwright/cases/anonymous-id-bug.html +0 -26
  12. package/__tests__/playwright/cases/basic.html +0 -32
  13. package/__tests__/playwright/cases/callbacks.html +0 -21
  14. package/__tests__/playwright/cases/cookie-names.html +0 -22
  15. package/__tests__/playwright/cases/disable-user-ids.html +0 -23
  16. package/__tests__/playwright/cases/dont-send.html +0 -22
  17. package/__tests__/playwright/cases/ip-policy.html +0 -22
  18. package/__tests__/playwright/cases/reset.html +0 -32
  19. package/__tests__/playwright/cases/segment-reference.html +0 -64
  20. package/__tests__/playwright/cases/url-bug.html +0 -20
  21. package/__tests__/playwright/integration.test.ts +0 -640
  22. package/__tests__/simple-syrup.ts +0 -136
  23. package/jest.config.js +0 -13
  24. package/package/README.md +0 -9
  25. package/package/dist/analytics-plugin.d.ts +0 -28
  26. package/package/dist/browser.d.ts +0 -10
  27. package/package/dist/index.d.ts +0 -28
  28. package/package/dist/jitsu.cjs.js +0 -2100
  29. package/package/dist/jitsu.d.ts +0 -78
  30. package/package/dist/jitsu.es.js +0 -2090
  31. package/package/dist/method-queue.d.ts +0 -19
  32. package/package/dist/script-loader.d.ts +0 -8
  33. package/package/dist/tlds.d.ts +0 -3
  34. package/package/dist/version.d.ts +0 -3
  35. package/package/dist/web/p.js.txt +0 -2219
  36. package/package/package.json +0 -56
  37. package/playwrite.config.ts +0 -91
  38. package/rollup.config.js +0 -32
  39. package/src/analytics-plugin.ts +0 -989
  40. package/src/browser.ts +0 -163
  41. package/src/destination-plugins/ga4.ts +0 -138
  42. package/src/destination-plugins/gtm.ts +0 -142
  43. package/src/destination-plugins/index.ts +0 -61
  44. package/src/destination-plugins/logrocket.ts +0 -85
  45. package/src/destination-plugins/tag.ts +0 -85
  46. package/src/index.ts +0 -255
  47. package/src/method-queue.ts +0 -70
  48. package/src/script-loader.ts +0 -76
  49. package/src/tlds.ts +0 -27
  50. package/src/version.ts +0 -6
  51. package/tsconfig.json +0 -23
  52. package/tsconfig.test.json +0 -15
@@ -1,2219 +0,0 @@
1
- (function () {
2
- 'use strict';
3
-
4
- function n$2(t,e,l,n,r){for(e=e.split?e.split("."):e,n=0;n<e.length;n++)t=t?t[e[n]]:r;return t===r?l:t}
5
-
6
- var e="undefined",o$1="object",b$3="any",m$1="*",j$1="__",F$2="undefined"!=typeof process?process:{};F$2.env&&F$2.env.NODE_ENV||"";var $$1="undefined"!=typeof document;null!=F$2.versions&&null!=F$2.versions.node;"undefined"!=typeof Deno&&void 0!==Deno.core;$$1&&"nodejs"===window.name||"undefined"!=typeof navigator&&void 0!==navigator.userAgent&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));function M$1(n,t){return t.charAt(0)[n]()+t.slice(1)}var U$1=M$1.bind(null,"toUpperCase"),H$1=M$1.bind(null,"toLowerCase");function J$2(n){return Y$1(n)?U$1("null"):"object"==typeof n?yn(n):Object.prototype.toString.call(n).slice(8,-1)}function R$1(n,t){void 0===t&&(t=!0);var e=J$2(n);return t?H$1(e):e}function V$1(n,t){return typeof t===n}var W$1=V$1.bind(null,"function"),q$1=V$1.bind(null,"string"),I$2=V$1.bind(null,"undefined");var Q$1=V$1.bind(null,"boolean");V$1.bind(null,"symbol");function Y$1(n){return null===n}function nn(n){return "number"===R$1(n)&&!isNaN(n)}function rn(n){return "array"===R$1(n)}function on(n){if(!un(n))return !1;for(var t=n;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(n)===t}function un(n){return n&&("object"==typeof n||null!==n)}function yn(n){return W$1(n.constructor)?n.constructor.name:null}function hn(n){return n instanceof Error||q$1(n.message)&&n.constructor&&nn(n.constructor.stackTraceLimit)}function On(n,t){if("object"!=typeof t||Y$1(t))return !1;if(t instanceof n)return !0;var e=R$1(new n(""));if(hn(t))for(;t;){if(R$1(t)===e)return !0;t=Object.getPrototypeOf(t);}return !1}On.bind(null,TypeError);On.bind(null,SyntaxError);function $n(n,t){var e=n instanceof Element||n instanceof HTMLDocument;return e&&t?Tn(n,t):e}function Tn(n,t){return void 0===t&&(t=""),n&&n.nodeName===t.toUpperCase()}function _n(n){var t=[].slice.call(arguments,1);return function(){return n.apply(void 0,[].slice.call(arguments).concat(t))}}_n($n,"form");_n($n,"button");_n($n,"input");_n($n,"select");
7
-
8
- function n$1(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s(r){return function(e){for(var r,t=Object.create(null),o=/([^&=]+)=?([^&]*)/g;r=o.exec(e);){var a=n$1(r[1]),i=n$1(r[2]);"[]"===a.substring(a.length-2)?(t[a=a.substring(0,a.length-2)]||(t[a]=[])).push(i):t[a]=""===i||i;}for(var u in t){var c=u.split("[");c.length>1&&(m(t,c.map(function(e){return e.replace(/[?[\]\\ ]/g,"")}),t[u]),delete t[u]);}return t}(function(r){if(r){var t=r.match(/\?(.*)/);return t&&t[1]?t[1].split("#")[0]:""}return $$1&&window.location.search.substring(1)}(r))}function m(e,r,t){for(var n=r.length-1,o=0;o<n;++o){var a=r[o];if("__proto__"===a||"constructor"===a)break;a in e||(e[a]={}),e=e[a];}e[r[n]]=t;}function y$1(){for(var e="",r=0,t=4294967295*Math.random()|0;r++<36;){var n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[r-1],o=15&t;e+="-"==n||"4"==n?n:("x"==n?o:3&o|8).toString(16),t=r%8==0?4294967295*Math.random()|0:t>>4;}return e}
9
-
10
- var l="global",o=j$1+"global"+j$1,n=typeof self===o$1&&self.self===self&&self||typeof global===o$1&&global.global===global&&global||void 0;function a$2(t){return n[o][t]}function f(t,e){return n[o][t]=e}function i$2(t){delete n[o][t];}function u$1(t,e,r){var l;try{if(b$2(t)){var o=window[t];l=o[e].bind(o);}}catch(t){}return l||r}n[o]||(n[o]={});var c$1={};function b$2(t){if(typeof c$1[t]!==e)return c$1[t];try{var e$1=window[t];e$1.setItem(e,e),e$1.removeItem(e);}catch(e){return c$1[t]=!1}return c$1[t]=!0}
11
-
12
- function g$1(){return g$1=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}return e},g$1.apply(this,arguments)}var h$1="function",v="undefined",y="@@redux/"+Math.random().toString(36),b$1=/* #__PURE__ */function(){return typeof Symbol===h$1&&Symbol.observable||"@@observable"}(),I$1=" != "+h$1;function w(e,t,n){var r;if(typeof t===h$1&&typeof n===v&&(n=t,t=void 0),typeof n!==v){if(typeof n!==h$1)throw new Error("enhancer"+I$1);return n(w)(e,t)}if(typeof e!==h$1)throw new Error("reducer"+I$1);var i=e,a=t,o=[],u=o,s=!1;function l(){u===o&&(u=o.slice());}function f(){return a}function d(e){if(typeof e!==h$1)throw new Error("Listener"+I$1);var t=!0;return l(),u.push(e),function(){if(t){t=!1,l();var n=u.indexOf(e);u.splice(n,1);}}}function p(e){if(!on(e))throw new Error("Act != obj");if(typeof e.type===v)throw new Error("ActType "+v);if(s)throw new Error("Dispatch in reducer");try{s=!0,a=i(a,e);}finally{s=!1;}for(var t=o=u,n=0;n<t.length;n++)(0, t[n])();return e}return p({type:"@@redux/INIT"}),(r={dispatch:p,subscribe:d,getState:f,replaceReducer:function(e){if(typeof e!==h$1)throw new Error("next reducer"+I$1);i=e,p({type:"@@redux/INIT"});}})[b$1]=function(){var e,t=d;return (e={subscribe:function(e){if("object"!=typeof e)throw new TypeError("Observer != obj");function n(){e.next&&e.next(f());}return n(),{unsubscribe:t(n)}}})[b$1]=function(){return this},e},r}function E$1(e,t){var n=t&&t.type;return "action "+(n&&n.toString()||"?")+"reducer "+e+" returns "+v}function P(){var e=[].slice.call(arguments);return 0===e.length?function(e){return e}:1===e.length?e[0]:e.reduce(function(e,t){return function(){return e(t.apply(void 0,[].slice.call(arguments)))}})}function S(){var e=arguments;return function(t){return function(n,r,i){var a,o=t(n,r,i),u=o.dispatch,c={getState:o.getState,dispatch:function(e){return u(e)}};return a=[].slice.call(e).map(function(e){return e(c)}),g$1({},o,{dispatch:u=P.apply(void 0,a)(o.dispatch)})}}}var N$1=j$1+"anon_id",A$1=j$1+"user_id",_=j$1+"user_traits",j="userId",k$1="anonymousId",x$1=["bootstrap","params","campaign","initializeStart","initialize","initializeEnd","ready","resetStart","reset","resetEnd","pageStart","page","pageEnd","pageAborted","trackStart","track","trackEnd","trackAborted","identifyStart","identify","identifyEnd","identifyAborted","userIdChanged","registerPlugins","enablePlugin","disablePlugin","online","offline","setItemStart","setItem","setItemEnd","setItemAborted","removeItemStart","removeItem","removeItemEnd","removeItemAborted"],T=["name","EVENTS","config","loaded"],z=x$1.reduce(function(e,t){return e[t]=t,e},{registerPluginType:function(e){return "registerPlugin:"+e},pluginReadyType:function(e){return "ready:"+e}}),M=/^utm_/,q=/^an_prop_/,V=/^an_trait_/;function C$1(e){var t=e.storage.setItem;return function(n){return function(r){return function(i){if(i.type===z.bootstrap){var a=i.params,o=i.user,u=i.persistedUser,c=i.initialUser,s=u.userId===o.userId;u.anonymousId!==o.anonymousId&&t(N$1,o.anonymousId),s||t(A$1,o.userId),c.traits&&t(_,g$1({},s&&u.traits?u.traits:{},c.traits));var l=Object.keys(i.params);if(l.length){var f=a.an_uid,d=a.an_event,p=l.reduce(function(e,t){if(t.match(M)||t.match(/^(d|g)clid/)){var n=t.replace(M,"");e.campaign["campaign"===n?"name":n]=a[t];}return t.match(q)&&(e.props[t.replace(q,"")]=a[t]),t.match(V)&&(e.traits[t.replace(V,"")]=a[t]),e},{campaign:{},props:{},traits:{}});n.dispatch(g$1({type:z.params,raw:a},p,f?{userId:f}:{})),f&&setTimeout(function(){return e.identify(f,p.traits)},0),d&&setTimeout(function(){return e.track(d,p.props)},0),Object.keys(p.campaign).length&&n.dispatch({type:z.campaign,campaign:p.campaign});}}return r(i)}}}}function U(e){return function(t,n){if(void 0===t&&(t={}),void 0===n&&(n={}),n.type===z.setItemEnd){if(n.key===N$1)return g$1({},t,{anonymousId:n.value});if(n.key===A$1)return g$1({},t,{userId:n.value})}switch(n.type){case z.identify:return Object.assign({},t,{userId:n.userId,traits:g$1({},t.traits,n.traits)});case z.reset:return [A$1,N$1,_].forEach(function(t){e.removeItem(t);}),Object.assign({},t,{userId:null,anonymousId:null,traits:{}});default:return t}}}function R(e){return {userId:e.getItem(A$1),anonymousId:e.getItem(N$1),traits:e.getItem(_)}}var $=function(e){return j$1+"TEMP"+j$1+e};function D(t){var n=t.storage,r=n.setItem,a=n.removeItem,o=n.getItem;return function(t){return function(n){return function(u){var c=u.userId,s=u.traits,l=u.options;if(u.type===z.reset&&([A$1,_,N$1].forEach(function(e){a(e);}),[j,k$1,"traits"].forEach(function(e){i$2($(e));})),u.type===z.identify){o(N$1)||r(N$1,y$1());var f=o(A$1),d=o(_)||{};f&&f!==c&&t.dispatch({type:z.userIdChanged,old:{userId:f,traits:d},new:{userId:c,traits:s},options:l}),c&&r(A$1,c),s&&r(_,g$1({},d,s));}return n(u)}}}}var B={};function L$1(e,t){B[e]&&W$1(B[e])&&(B[e](t),delete B[e]);}function J$1(e,t,n){return new Promise(function(r,i){return t()?r(e):n<1?i(g$1({},e,{queue:!0})):new Promise(function(e){return setTimeout(e,10)}).then(function(a){return J$1(e,t,n-10).then(r,i)})})}function X(e){return {abort:e}}var H=function(e){var t=e.data,n=e.action,r=e.instance,i=e.state,a=e.allPlugins,o=e.allMatches,u=e.store,s=e.EVENTS;try{var f=i.plugins,d=i.context,p=n.type,m=p.match(W),h=t.exact.map(function(e){return e.pluginName});m&&(h=o.during.map(function(e){return e.pluginName}));var v=function(e,t){return function(n,r,i){var a=r.config,o=r.name,u=o+"."+n.type;i&&(u=i.event);var c=n.type.match(W)?function(e,t,n,r,i){return function(a,o){var u=r?r.name:e,c=o&&ne(o)?o:n;if(r&&(!(c=o&&ne(o)?o:[e]).includes(e)||1!==c.length))throw new Error("Method "+t+" can only abort "+e+" plugin. "+JSON.stringify(c)+" input valid");return g$1({},i,{abort:{reason:a,plugins:c,caller:t,_:u}})}}(o,u,t,i,n):function(e,t){return function(){throw new Error(e.type+" action not cancellable. Remove abort in "+t)}}(n,u);return {payload:ae(n),instance:e,config:a||{},abort:c}}}(r,h),y=t.exact.reduce(function(e,t){var n=t.pluginName,r=t.methodName,i=!1;return r.match(/^initialize/)||r.match(/^reset/)||(i=!f[n].loaded),d.offline&&r.match(/^(page|track|identify)/)&&(i=!0),e[""+n]=i,e},{});return Promise.resolve(t.exact.reduce(function(e,i,o){try{var u=i.pluginName;return Promise.resolve(e).then(function(e){function i(){return Promise.resolve(e)}var o=function(){if(t.namespaced&&t.namespaced[u])return Promise.resolve(t.namespaced[u].reduce(function(e,t,n){try{return Promise.resolve(e).then(function(e){return t.method&&W$1(t.method)?(function(e,t){var n=ie(e);if(n&&n.name===t){var r=ie(n.method);throw new Error([t+" plugin is calling method "+e,"Plugins cant call self","Use "+n.method+" "+(r?"or "+r.method:"")+" in "+t+" plugin insteadof "+e].join("\n"))}}(t.methodName,t.pluginName),Promise.resolve(t.method({payload:e,instance:r,abort:(n=e,i=u,o=t.pluginName,function(e,t){return g$1({},n,{abort:{reason:e,plugins:t||[i],caller:p,from:o||i}})}),config:Q(t.pluginName,f,a),plugins:f})).then(function(t){var n=on(t)?t:{};return Promise.resolve(g$1({},e,n))})):e;var n,i,o;})}catch(e){return Promise.reject(e)}},Promise.resolve(n))).then(function(t){e[u]=t;});e[u]=n;}();return o&&o.then?o.then(i):i()})}catch(e){return Promise.reject(e)}},Promise.resolve({}))).then(function(e){return Promise.resolve(t.exact.reduce(function(n,i,o){try{var s=t.exact.length===o+1,l=i.pluginName,d=a[l];return Promise.resolve(n).then(function(t){var n=e[l]?e[l]:{};if(m&&(n=t),ee(n,l))return K({data:n,method:p,instance:r,pluginName:l,store:u}),Promise.resolve(t);if(ee(t,l))return s&&K({data:t,method:p,instance:r,store:u}),Promise.resolve(t);if(y.hasOwnProperty(l)&&!0===y[l])return u.dispatch({type:"queue",plugin:l,payload:n,_:{called:"queue",from:"queueMechanism"}}),Promise.resolve(t);var i=v(e[l],a[l]);return Promise.resolve(d[p]({abort:i.abort,payload:n,instance:r,config:Q(l,f,a),plugins:f})).then(function(i){var a=on(i)?i:{},o=g$1({},t,a),s=e[l];if(ee(s,l))K({data:s,method:p,instance:r,pluginName:l,store:u});else {var f=p+":"+l;(f.match(/:/g)||[]).length<2&&!p.match(F$1)&&!p.match(G$1)&&r.dispatch(g$1({},m?o:n,{type:f,_:{called:f,from:"submethod"}}));}return Promise.resolve(o)})})}catch(e){return Promise.reject(e)}},Promise.resolve(n))).then(function(e){if(!(p.match(W)||p.match(/^registerPlugin/)||p.match(G$1)||p.match(F$1)||p.match(/^params/)||p.match(/^userIdChanged/))){if(s.plugins.includes(p),e._&&e._.originalAction===p)return e;var n=g$1({},e,{_:{originalAction:e.type,called:e.type,from:"engineEnd"}});te(e,t.exact.length)&&!p.match(/End$/)&&(n=g$1({},n,{type:e.type+"Aborted"})),u.dispatch(n);}return e})})}catch(e){return Promise.reject(e)}},W=/Start$/,F$1=/^bootstrap/,G$1=/^ready/;function K(e){var t=e.pluginName,n=e.method+"Aborted"+(t?":"+t:"");e.store.dispatch(g$1({},e.data,{type:n,_:{called:n,from:"abort"}}));}function Q(e,t,n){var r=t[e]||n[e];return r&&r.config?r.config:{}}function Y(e,t){return t.reduce(function(t,n){return n[e]?t.concat({methodName:e,pluginName:n.name,method:n[e]}):t},[])}function Z(e,t){var n=e.replace(W,""),r=t?":"+t:"";return [""+e+r,""+n+r,n+"End"+r]}function ee(e,t){var n=e.abort;return !!n&&(!0===n||re(n,t)||n&&re(n.plugins,t))}function te(e,t){var n=e.abort;if(!n)return !1;if(!0===n||q$1(n))return !0;var r=n.plugins;return ne(n)&&n.length===t||ne(r)&&r.length===t}function ne(e){return Array.isArray(e)}function re(e,t){return !(!e||!ne(e))&&e.includes(t)}function ie(e){var t=e.match(/(.*):(.*)/);return !!t&&{method:t[1],name:t[2]}}function ae(e){return Object.keys(e).reduce(function(t,n){return "type"===n||(t[n]=on(e[n])?Object.assign({},e[n]):e[n]),t},{})}function oe(e,t,n){var r={};return function(i){return function(a){return function(o){try{var u,s=function(e){return u?e:a(m)},d=o.type,p=o.plugins,m=o;if(o.abort)return Promise.resolve(a(o));if(d===z.enablePlugin&&i.dispatch({type:z.initializeStart,plugins:p,disabled:[],fromEnable:!0,meta:o.meta}),d===z.disablePlugin&&setTimeout(function(){return L$1(o.meta.rid,{payload:o})},0),d===z.initializeEnd){var h=t(),v=Object.keys(h),y=v.filter(function(e){return p.includes(e)}).map(function(e){return h[e]}),b=[],I=[],w=o.disabled,E=y.map(function(e){var t=e.loaded,n=e.name,a=e.config;return J$1(e,function(){return t({config:a})},1e4).then(function(t){return r[n]||(i.dispatch({type:z.pluginReadyType(n),name:n,events:Object.keys(e).filter(function(e){return !T.includes(e)})}),r[n]=!0),b=b.concat(n),e}).catch(function(e){if(e instanceof Error)throw new Error(e);return I=I.concat(e.name),e})});Promise.all(E).then(function(e){var t={plugins:b,failed:I,disabled:w};setTimeout(function(){v.length===E.length+w.length&&i.dispatch(g$1({},{type:z.ready},t));},0);});}var P=function(){if(d!==z.bootstrap)return /^ready:([^:]*)$/.test(d)&&setTimeout(function(){return function(e,t,n){var r={},i=t(),a=e.getState(),o=a.plugins,u=a.queue,s=a.user;if(!a.context.offline&&u&&u.actions&&u.actions.length){var f=u.actions.reduce(function(e,t,n){return o[t.plugin].loaded?(e.process.push(t),e.processIndex.push(n)):(e.requeue.push(t),e.requeueIndex.push(n)),e},{processIndex:[],process:[],requeue:[],requeueIndex:[]});if(f.processIndex&&f.processIndex.length){f.processIndex.forEach(function(t){var a=u.actions[t],f=a.plugin,d=a.payload.type,p=i[f][d];if(p&&W$1(p)){var m,h=function(e,t){return void 0===e&&(e={}),void 0===t&&(t={}),[j,k$1].reduce(function(n,r){return e.hasOwnProperty(r)&&t[r]&&t[r]!==e[r]&&(n[r]=t[r]),n},e)}(a.payload,s),v=r[h.meta.rid];if(!v&&(m=p({payload:h,config:o[f].config,instance:n,abort:X}))&&on(m)&&m.abort)return void(r[h.meta.rid]=!0);if(!v){var y=d+":"+f;e.dispatch(g$1({},h,{type:y,_:{called:y,from:"queueDrain"}}));}}});var d=u.actions.filter(function(e,t){return !~f.processIndex.indexOf(t)});u.actions=d;}}}(i,t,e)},0),Promise.resolve(function(e,t,n,r,i){try{var a=W$1(t)?t():t,o=e.type,u=o.replace(W,"");if(e._&&e._.called)return Promise.resolve(e);var c=n.getState(),s=(m=a,void 0===(h=c.plugins)&&(h={}),void 0===(v=e.options)&&(v={}),Object.keys(m).filter(function(e){var t=v.plugins||{};return Q$1(t[e])?t[e]:!1!==t.all&&(!h[e]||!1!==h[e].enabled)}).map(function(e){return m[e]}));o===z.initializeStart&&e.fromEnable&&(s=Object.keys(c.plugins).filter(function(t){var n=c.plugins[t];return e.plugins.includes(t)&&!n.initialized}).map(function(e){return a[e]}));var d=s.map(function(e){return e.name}),p=function(e,t,n){var r=Z(e).map(function(e){return Y(e,t)});return t.reduce(function(n,r){var i=r.name,a=Z(e,i).map(function(e){return Y(e,t)}),o=a[0],u=a[1],c=a[2];return o.length&&(n.beforeNS[i]=o),u.length&&(n.duringNS[i]=u),c.length&&(n.afterNS[i]=c),n},{before:r[0],beforeNS:{},during:r[1],duringNS:{},after:r[2],afterNS:{}})}(o,s);return Promise.resolve(H({action:e,data:{exact:p.before,namespaced:p.beforeNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){function t(){var t=function(){if(o.match(W))return Promise.resolve(H({action:g$1({},s,{type:u+"End"}),data:{exact:p.after,namespaced:p.afterNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){e.meta&&e.meta.hasCallback&&L$1(e.meta.rid,{payload:e});})}();return t&&t.then?t.then(function(){return e}):e}if(te(e,d.length))return e;var s,l=function(){if(o!==u)return Promise.resolve(H({action:g$1({},e,{type:u}),data:{exact:p.during,namespaced:p.duringNS},state:c,allPlugins:a,allMatches:p,instance:n,store:r,EVENTS:i})).then(function(e){s=e;});s=e;}();return l&&l.then?l.then(t):t()})}catch(e){return Promise.reject(e)}var m,h,v;}(o,t,e,i,n)).then(function(e){return u=1,a(e)})}();return Promise.resolve(P&&P.then?P.then(s):s(P))}catch(e){return Promise.reject(e)}}}}}function ue(e){return function(t){return function(t){return function(n){var r=n.type,i=n.key,a=n.value,o=n.options;if(r===z.setItem||r===z.removeItem){if(n.abort)return t(n);r===z.setItem?e.setItem(i,a,o):e.removeItem(i,o);}return t(n)}}}}var ce=function(){var e=this;this.before=[],this.after=[],this.addMiddleware=function(t,n){e[n]=e[n].concat(t);},this.removeMiddleware=function(t,n){var r=e[n].findIndex(function(e){return e===t});-1!==r&&(e[n]=[].concat(e[n].slice(0,r),e[n].slice(r+1)));},this.dynamicMiddlewares=function(t){return function(n){return function(r){return function(i){var a={getState:n.getState,dispatch:function(e){return n.dispatch(e)}},o=e[t].map(function(e){return e(a)});return P.apply(void 0,o)(r)(i)}}}};};function se(e){return function(t,n){void 0===t&&(t={});var r={};if("initialize:aborted"===n.type)return t;if(/^registerPlugin:([^:]*)$/.test(n.type)){var i=le(n.type,"registerPlugin"),a=e()[i];if(!a||!i)return t;var o=n.enabled,u=a.config;return r[i]={enabled:o,initialized:!!o&&Boolean(!a.initialize),loaded:!!o&&Boolean(a.loaded({config:u})),config:u},g$1({},t,r)}if(/^initialize:([^:]*)$/.test(n.type)){var c=le(n.type,z.initialize),s=e()[c];return s&&c?(r[c]=g$1({},t[c],{initialized:!0,loaded:Boolean(s.loaded({config:s.config}))}),g$1({},t,r)):t}if(/^ready:([^:]*)$/.test(n.type))return r[n.name]=g$1({},t[n.name],{loaded:!0}),g$1({},t,r);switch(n.type){case z.disablePlugin:return g$1({},t,fe(n.plugins,!1,t));case z.enablePlugin:return g$1({},t,fe(n.plugins,!0,t));default:return t}}}function le(e,t){return e.substring(t.length+1,e.length)}function fe(e,t,n){return e.reduce(function(e,r){return e[r]=g$1({},n[r],{enabled:t}),e},n)}function de(e){try{return JSON.parse(JSON.stringify(e))}catch(e){}return e}var pe={last:{},history:[]};function me(e,t){void 0===e&&(e=pe);var n=t.options,r=t.meta;if(t.type===z.track){var i=de(g$1({event:t.event,properties:t.properties},Object.keys(n).length&&{options:n},{meta:r}));return g$1({},e,{last:i,history:e.history.concat(i)})}return e}var ge={actions:[]};function he(e,t){void 0===e&&(e=ge);var n=t.payload;switch(t.type){case"queue":var r;return r=n&&n.type&&n.type===z.identify?[t].concat(e.actions):e.actions.concat(t),g$1({},e,{actions:r});case"dequeue":return [];default:return e}}var ve=/#.*$/;function ye(e){var t=/(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g.exec(e);return "/"+(t&&t[3]?t[3].split("?")[0].replace(ve,""):"")}var be,Ie=function(e){if(void 0===e&&(e={}),!$$1)return e;var t=document,n=t.title,r=t.referrer,i=window,a=i.location,o=i.innerWidth,u=i.innerHeight,c=a.hash,s=a.search,l=function(e){var t=function(){if($$1)for(var e,t=document.getElementsByTagName("link"),n=0;e=t[n];n++)if("canonical"===e.getAttribute("rel"))return e.getAttribute("href")}();return t?t.match(/\?/)?t:t+e:window.location.href.replace(ve,"")}(s),f={title:n,url:l,path:ye(l),hash:c,search:s,width:o,height:u};return r&&""!==r&&(f.referrer=r),g$1({},f,e)},we={last:{},history:[]};function Ee(e,t){void 0===e&&(e=we);var n=t.options;if(t.type===z.page){var r=de(g$1({properties:t.properties,meta:t.meta},Object.keys(n).length&&{options:n}));return g$1({},e,{last:r,history:e.history.concat(r)})}return e}be={};var Pe={initialized:!1,sessionId:y$1(),app:null,version:null,debug:!1,offline:!!$$1&&!navigator.onLine,os:{name:"na"},userAgent:$$1?navigator.userAgent:"node",library:{name:"analytics",version:"0.12.14"},timezone:void 0,locale:void 0,campaign:{},referrer:be};function Se(e,t){void 0===e&&(e=Pe);var n=e.initialized,r=t.campaign;switch(t.type){case z.campaign:return g$1({},e,{campaign:r});case z.offline:return g$1({},e,{offline:!0});case z.online:return g$1({},e,{offline:!1});default:return n?e:g$1({},Pe,e,{initialized:!0})}}var Ne=["plugins","reducers","storage"];function Ae(){return f("analytics",[]),function(e){return function(t,n$1,r){var i=e(t,n$1,r),a=i.dispatch;return Object.assign(i,{dispatch:function(e){return n[o].analytics.push(e.action||e),a(e)}})}}}function _e(e){return function(){return P(P.apply(null,arguments),Ae())}}function Oe(e){return e?rn(e)?e:[e]:[]}function je(t,n,r){void 0===t&&(t={});var i,a,o=y$1();return n&&(B[o]=(i=n,a=function(e){for(var t,n=e||Array.prototype.slice.call(arguments),r=0;r<n.length;r++)if(W$1(n[r])){t=n[r];break}return t}(r),function(e){a&&a(e),i(e);})),g$1({},t,{rid:o,ts:(new Date).getTime()},n?{hasCallback:!0}:{})}function ke(o){void 0===o&&(o={});var u=o.reducers||{},s$1=o.initialUser||{},f$1=(o.plugins||[]).reduce(function(e,t){if(W$1(t))return e.middlewares=e.middlewares.concat(t),e;if(t.NAMESPACE&&(t.name=t.NAMESPACE),!t.name)throw new Error("https://lytics.dev/errors/1");t.config||(t.config={});var n=t.EVENTS?Object.keys(t.EVENTS).map(function(e){return t.EVENTS[e]}):[];e.pluginEnabled[t.name]=!(!1===t.enabled||!1===t.config.enabled),delete t.enabled,t.methods&&(e.methods[t.name]=Object.keys(t.methods).reduce(function(e,n){var r;return e[n]=(r=t.methods[n],function(){for(var e=Array.prototype.slice.call(arguments),t=new Array(r.length),n=0;n<e.length;n++)t[n]=e[n];return t[t.length]=K,r.apply({instance:K},t)}),e},{}),delete t.methods);var r=Object.keys(t).concat(n),i=new Set(e.events.concat(r));if(e.events=Array.from(i),e.pluginsArray=e.pluginsArray.concat(t),e.plugins[t.name])throw new Error(t.name+"AlreadyLoaded");return e.plugins[t.name]=t,e.plugins[t.name].loaded||(e.plugins[t.name].loaded=function(){return !0}),e},{plugins:{},pluginEnabled:{},methods:{},pluginsArray:[],middlewares:[],events:[]}),m=o.storage?o.storage:{getItem:a$2,setItem:f,removeItem:i$2},b=function(e){return function(t,n,i){return n.getState("user")[t]||(i&&on(i)&&i[t]?i[t]:R(e)[t]||a$2($(t))||null)}}(m),I=f$1.plugins,A=f$1.events.filter(function(e){return !T.includes(e)}).sort(),_=new Set(A.concat(x$1).filter(function(e){return !T.includes(e)})),O=Array.from(_).sort(),M=function(){return I},q=new ce,V=q.addMiddleware,B=q.removeMiddleware,L=q.dynamicMiddlewares,J=function(){throw new Error("Abort disabled inListener")},X=s(),H=R(m),W=g$1({},H,s$1,X.an_uid?{userId:X.an_uid}:{},X.an_aid?{anonymousId:X.an_aid}:{});W.anonymousId||(W.anonymousId=y$1());var F=g$1({enable:function(e,t){return new Promise(function(n){le.dispatch({type:z.enablePlugin,plugins:Oe(e),_:{originalAction:z.enablePlugin}},n,[t]);})},disable:function(e,t){return new Promise(function(n){le.dispatch({type:z.disablePlugin,plugins:Oe(e),_:{originalAction:z.disablePlugin}},n,[t]);})}},f$1.methods),G=!1,K={identify:function(e,t,n,r){try{var i=q$1(e)?e:null,o=on(e)?e:t,u=n||{},s=K.user();f($(j),i);var l=i||o.userId||b(j,K,o);return Promise.resolve(new Promise(function(e){le.dispatch(g$1({type:z.identifyStart,userId:l,traits:o||{},options:u,anonymousId:s.anonymousId},s.id&&s.id!==i&&{previousId:s.id}),e,[t,n,r]);}))}catch(e){return Promise.reject(e)}},track:function(e,t,n,r){try{var i=on(e)?e.event:e;if(!i||!q$1(i))throw new Error("EventMissing");var a=on(e)?e:t||{},o=on(n)?n:{};return Promise.resolve(new Promise(function(e){le.dispatch({type:z.trackStart,event:i,properties:a,options:o,userId:b(j,K,t),anonymousId:b(k$1,K,t)},e,[t,n,r]);}))}catch(e){return Promise.reject(e)}},page:function(e,t,n){try{var r=on(e)?e:{},i=on(t)?t:{};return Promise.resolve(new Promise(function(a){le.dispatch({type:z.pageStart,properties:Ie(r),options:i,userId:b(j,K,r),anonymousId:b(k$1,K,r)},a,[e,t,n]);}))}catch(e){return Promise.reject(e)}},user:function(e){if(e===j||"id"===e)return b(j,K);if(e===k$1||"anonId"===e)return b(k$1,K);var t=K.getState("user");return e?n$2(t,e):t},reset:function(e){return new Promise(function(t){le.dispatch({type:z.resetStart},t,e);})},ready:function(e){return G&&e({plugins:F,instance:K}),K.on(z.ready,function(t){e(t),G=!0;})},on:function(e,t){if(!e||!W$1(t))return !1;if(e===z.bootstrap)throw new Error(".on disabled for "+e);var n=/Start$|Start:/;if("*"===e){var r=function(e){return function(e){return function(r){return r.type.match(n)&&t({payload:r,instance:K,plugins:I}),e(r)}}},i=function(e){return function(e){return function(r){return r.type.match(n)||t({payload:r,instance:K,plugins:I}),e(r)}}};return V(r,xe),V(i,Te),function(){B(r,xe),B(i,Te);}}var a=e.match(n)?xe:Te,o=function(n){return function(n){return function(r){return r.type===e&&t({payload:r,instance:K,plugins:I,abort:J}),n(r)}}};return V(o,a),function(){return B(o,a)}},once:function(e,t){if(!e||!W$1(t))return !1;if(e===z.bootstrap)throw new Error(".once disabled for "+e);var n=K.on(e,function(e){t({payload:e.payload,instance:K,plugins:I,abort:J}),n();});return n},getState:function(e){var t=le.getState();return e?n$2(t,e):Object.assign({},t)},dispatch:function(e){var t=q$1(e)?{type:e}:e;if(x$1.includes(t.type))throw new Error("reserved action "+t.type);var n=g$1({},t,{_:g$1({originalAction:t.type},e._||{})});le.dispatch(n);},enablePlugin:F.enable,disablePlugin:F.disable,plugins:F,storage:{getItem:m.getItem,setItem:function(e,t,n){le.dispatch({type:z.setItemStart,key:e,value:t,options:n});},removeItem:function(e,t){le.dispatch({type:z.removeItemStart,key:e,options:t});}},setAnonymousId:function(e,t){K.storage.setItem(N$1,e,t);},events:{core:x$1,plugins:A}},Q=f$1.middlewares.concat([function(e){return function(e){return function(t){return t.meta||(t.meta=je()),e(t)}}},L(xe),oe(K,M,{all:O,plugins:A}),ue(m),C$1(K),D(K),L(Te)]),Y={context:Se,user:U(m),page:Ee,track:me,plugins:se(M),queue:he},Z=P,ee=P;if($$1&&o.debug){var te=window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;te&&(Z=te({trace:!0,traceLimit:25})),ee=function(){return 0===arguments.length?Ae():on(typeof arguments[0])?_e():_e().apply(null,arguments)};}var ne,re=function(e){return Object.keys(e).reduce(function(t,n){return Ne.includes(n)||(t[n]=e[n]),t},{})}(o),ie=f$1.pluginsArray.reduce(function(e,t){var n=t.name,r=t.config,i=t.loaded,a=f$1.pluginEnabled[n];return e[n]={enabled:a,initialized:!!a&&Boolean(!t.initialize),loaded:Boolean(i({config:r})),config:r},e},{}),ae={context:re,user:W,plugins:ie},le=w(function(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++){var i=t[r];typeof e[i]===h$1&&(n[i]=e[i]);}var a,o=Object.keys(n);try{!function(e){Object.keys(e).forEach(function(t){var n=e[t];if(typeof n(void 0,{type:"@@redux/INIT"})===v||typeof n(void 0,{type:y})===v)throw new Error("reducer "+t+" "+v)});}(n);}catch(e){a=e;}return function(e,t){if(void 0===e&&(e={}),a)throw a;for(var r=!1,i={},u=0;u<o.length;u++){var c=o[u],s=e[c],l=(0, n[c])(s,t);if(typeof l===v){var f=E$1(c,t);throw new Error(f)}i[c]=l,r=r||l!==s;}return r?i:e}}(g$1({},Y,u)),ae,ee(Z(S.apply(void 0,Q))));le.dispatch=(ne=le.dispatch,function(e,t,n){var r=g$1({},e,{meta:je(e.meta,t,Oe(n))});return ne.apply(null,[r])});var fe=Object.keys(I);le.dispatch({type:z.bootstrap,plugins:fe,config:re,params:X,user:W,initialUser:s$1,persistedUser:H});var de=fe.filter(function(e){return f$1.pluginEnabled[e]}),pe=fe.filter(function(e){return !f$1.pluginEnabled[e]});return le.dispatch({type:z.registerPlugins,plugins:fe,enabled:f$1.pluginEnabled}),f$1.pluginsArray.map(function(e,t){var n=e.bootstrap,r=e.config,i=e.name;n&&W$1(n)&&n({instance:K,config:r,payload:e}),le.dispatch({type:z.registerPluginType(i),name:i,enabled:f$1.pluginEnabled[i],plugin:e}),f$1.pluginsArray.length===t+1&&le.dispatch({type:z.initializeStart,plugins:de,disabled:pe});}),K}var xe="before",Te="after";
13
-
14
- var t="cookie",i$1=a$1(),r$1=d$1,c=d$1;function u(o){return i$1?d$1(o,"",-1):i$2(o)}function a$1(){if(void 0!==i$1)return i$1;var e="cookiecookie";try{d$1(e,e),i$1=-1!==document.cookie.indexOf(e),u(e);}catch(e){i$1=!1;}return i$1}function d$1(e,t,r,c,u,a){if("undefined"!=typeof window){var d=arguments.length>1;return !1===i$1&&(d?f(e,t):a$2(e)),d?document.cookie=e+"="+encodeURIComponent(t)+(r?"; expires="+new Date(+new Date+1e3*r).toUTCString()+(c?"; path="+c:"")+(u?"; domain="+u:"")+(a?"; secure":""):""):decodeURIComponent((("; "+document.cookie).split("; "+e+"=")[1]||"").split(";")[0])}}
15
-
16
- var r="localStorage",g=b$2.bind(null,"localStorage");u$1("localStorage","getItem",a$2);u$1("localStorage","setItem",f);u$1("localStorage","removeItem",i$2);
17
-
18
- var a="sessionStorage",i=b$2.bind(null,"sessionStorage");u$1("sessionStorage","getItem",a$2);u$1("sessionStorage","setItem",f);u$1("sessionStorage","removeItem",i$2);
19
-
20
- function I(t){var o=t;try{if("true"===(o=JSON.parse(t)))return !0;if("false"===o)return !1;if(on(o))return o;parseFloat(o)===o&&(o=parseFloat(o));}catch(t){}if(null!==o&&""!==o)return o}var k=g(),O=i(),x=a$1();function C(o,e){if(o){var r=A(e),a=!N(r),i=d(r)?I(localStorage.getItem(o)):void 0;if(a&&!I$2(i))return i;var n=h(r)?I(r$1(o)):void 0;if(a&&n)return n;var l=E(r)?I(sessionStorage.getItem(o)):void 0;if(a&&l)return l;var u=a$2(o);return a?u:{localStorage:i,sessionStorage:l,cookie:n,global:u}}}function L(r$2,a$1,l$1){if(r$2&&!I$2(a$1)){var u={},g=A(l$1),m=JSON.stringify(a$1),S=!N(g);return d(g)&&(u[r]=F(r,a$1,I(localStorage.getItem(r$2))),localStorage.setItem(r$2,m),S)?u[r]:h(g)&&(u[t]=F(t,a$1,I(r$1(r$2))),c(r$2,m),S)?u[t]:E(g)&&(u[a]=F(a,a$1,I(sessionStorage.getItem(r$2))),sessionStorage.setItem(r$2,m),S)?u[a]:(u[l]=F(l,a$1,a$2(r$2)),f(r$2,a$1),S?u[l]:u)}}function b(t$1,e){if(t$1){var a$1=A(e),s=C(t$1,m$1),n={};return !I$2(s.localStorage)&&d(a$1)&&(localStorage.removeItem(t$1),n[r]=s.localStorage),!I$2(s.cookie)&&h(a$1)&&(u(t$1),n[t]=s.cookie),!I$2(s.sessionStorage)&&E(a$1)&&(sessionStorage.removeItem(t$1),n[a]=s.sessionStorage),!I$2(s.global)&&G(a$1,l)&&(i$2(t$1),n[l]=s.global),n}}function A(t){return t?q$1(t)?t:t.storage:b$3}function d(t){return k&&G(t,r)}function h(t$1){return x&&G(t$1,t)}function E(t){return O&&G(t,a)}function N(t){return t===m$1||"all"===t}function G(t,o){return t===b$3||t===o||N(t)}function F(t,o,e){return {location:t,current:o,previous:e}}var J={setItem:L,getItem:C,removeItem:b};
21
-
22
- function _defineProperty(obj, key, value) {
23
- if (key in obj) {
24
- Object.defineProperty(obj, key, {
25
- value: value,
26
- enumerable: true,
27
- configurable: true,
28
- writable: true
29
- });
30
- } else {
31
- obj[key] = value;
32
- }
33
-
34
- return obj;
35
- }
36
-
37
- function ownKeys(object, enumerableOnly) {
38
- var keys = Object.keys(object);
39
-
40
- if (Object.getOwnPropertySymbols) {
41
- var symbols = Object.getOwnPropertySymbols(object);
42
- enumerableOnly && (symbols = symbols.filter(function (sym) {
43
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
44
- })), keys.push.apply(keys, symbols);
45
- }
46
-
47
- return keys;
48
- }
49
-
50
- function _objectSpread2(target) {
51
- for (var i = 1; i < arguments.length; i++) {
52
- var source = null != arguments[i] ? arguments[i] : {};
53
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
54
- _defineProperty(target, key, source[key]);
55
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
56
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
57
- });
58
- }
59
-
60
- return target;
61
- }
62
-
63
- function analyticsLib() {
64
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
65
- var defaultSettings = {
66
- storage: J
67
- };
68
- return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
69
- }
70
-
71
- function findScript(src) {
72
- const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
73
- return scripts.find(s => s.src === src);
74
- }
75
- function buildScriptSrc(src, options) {
76
- let result = src;
77
- if (!result.startsWith("http")) {
78
- result = `https://${(options === null || options === void 0 ? void 0 : options.www) ? "www." : ""}${result}`;
79
- }
80
- if (options === null || options === void 0 ? void 0 : options.min) {
81
- result = result + ".min.js";
82
- }
83
- else if (options === null || options === void 0 ? void 0 : options.js) {
84
- result = result + ".js";
85
- }
86
- if (options === null || options === void 0 ? void 0 : options.query) {
87
- result += "?" + options.query;
88
- }
89
- return result;
90
- }
91
- function loadScript(src, options) {
92
- const found = findScript(src);
93
- if (found !== undefined) {
94
- const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
95
- if (status === "loaded") {
96
- return Promise.resolve(found);
97
- }
98
- if (status === "loading") {
99
- return new Promise((resolve, reject) => {
100
- found.addEventListener("load", () => resolve(found));
101
- found.addEventListener("error", err => reject(err));
102
- });
103
- }
104
- }
105
- return new Promise((resolve, reject) => {
106
- var _a, _b;
107
- const script = window.document.createElement("script");
108
- script.type = "text/javascript";
109
- script.src = buildScriptSrc(src, options);
110
- script.async = true;
111
- script.setAttribute("status", "loading");
112
- for (const [k, v] of Object.entries((_a = options === null || options === void 0 ? void 0 : options.attributes) !== null && _a !== void 0 ? _a : {})) {
113
- script.setAttribute(k, v);
114
- }
115
- script.onload = () => {
116
- script.onerror = script.onload = null;
117
- script.setAttribute("status", "loaded");
118
- resolve(script);
119
- };
120
- script.onerror = () => {
121
- script.onerror = script.onload = null;
122
- script.setAttribute("status", "error");
123
- reject(new Error(`Failed to load ${src}`));
124
- };
125
- const tag = window.document.getElementsByTagName("script")[0];
126
- (_b = tag.parentElement) === null || _b === void 0 ? void 0 : _b.insertBefore(script, tag);
127
- });
128
- }
129
-
130
- var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
131
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
132
- return new (P || (P = Promise))(function (resolve, reject) {
133
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
134
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
135
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
136
- step((generator = generator.apply(thisArg, _arguments || [])).next());
137
- });
138
- };
139
- const tagPlugin = {
140
- id: "tag",
141
- handle(config, payload) {
142
- return __awaiter$5(this, void 0, void 0, function* () {
143
- if (!applyFilters(payload, config)) {
144
- return;
145
- }
146
- insertTags(config.code, payload);
147
- });
148
- },
149
- };
150
- function insertTags(code, event, opts = {}) {
151
- let tag;
152
- try {
153
- tag = JSON.parse(code);
154
- }
155
- catch (e) {
156
- tag = { code, lang: "javascript" };
157
- }
158
- const debug = opts.debug || false;
159
- if (isInBrowser()) {
160
- if (tag.lang === "javascript") {
161
- execJs(tag.code, event);
162
- }
163
- else {
164
- const codeHolder = document.createElement("span");
165
- codeHolder.innerHTML = replaceMacro(tag.code, event);
166
- document.body.insertAdjacentElement("beforeend", codeHolder);
167
- const scripts = codeHolder.querySelectorAll("script");
168
- scripts.forEach(script => {
169
- const scriptClone = document.createElement("script");
170
- scriptClone.type = scriptClone.type || "text/javascript";
171
- if (script.hasAttribute("src")) {
172
- scriptClone.src = script.src;
173
- }
174
- scriptClone.text = script.text;
175
- if (debug) {
176
- console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
177
- }
178
- document.head.appendChild(scriptClone);
179
- document.head.removeChild(scriptClone);
180
- });
181
- }
182
- }
183
- else {
184
- if (debug) {
185
- console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
186
- }
187
- }
188
- }
189
- //This weird code is used to mask eval() usage.
190
- //Although the code can be executed in the browser, some server side bundlers (like Vercel) fails
191
- //the build if a direct reference to eval() is found.
192
- let al = "al";
193
- let ev = "ve".split("").reverse().join("");
194
- const execF = globalThis[ev + al];
195
- function execJs(code, event) {
196
- const varName = `jitsu_event_${randomId()}`;
197
- window[varName] = event;
198
- const iif = `(function(){
199
- const event = ${varName};
200
- ${code}
201
- })()`;
202
- try {
203
- execF(iif);
204
- }
205
- catch (e) {
206
- console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
207
- }
208
- finally {
209
- delete window[varName];
210
- }
211
- return iif;
212
- }
213
- function replaceMacro(code, event) {
214
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
215
- }
216
-
217
- var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
218
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
219
- return new (P || (P = Promise))(function (resolve, reject) {
220
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
221
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
222
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
223
- step((generator = generator.apply(thisArg, _arguments || [])).next());
224
- });
225
- };
226
- const cdn = "cdn.lr-ingest.io/";
227
- const logrocketPlugin = {
228
- id: "logrocket",
229
- handle(config, payload) {
230
- return __awaiter$4(this, void 0, void 0, function* () {
231
- if (!applyFilters(payload, config)) {
232
- return;
233
- }
234
- initLogrocketIfNeeded(config.appId);
235
- const action = logRocket => {
236
- if (payload.type === "identify" && payload.userId) {
237
- logRocket.identify(payload.userId, payload.traits || {});
238
- }
239
- };
240
- getLogRocketQueue().push(action);
241
- if (getLogRocketState() === "loaded") {
242
- flushLogRocketQueue(window["LogRocket"]);
243
- }
244
- });
245
- },
246
- };
247
- function getLogRocketState() {
248
- return window["__jitsuLrState"] || "fresh";
249
- }
250
- function setLogRocketState(s) {
251
- window["__jitsuLrState"] = s;
252
- }
253
- function getLogRocketQueue() {
254
- return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
255
- }
256
- function flushLogRocketQueue(lr) {
257
- const queue = getLogRocketQueue();
258
- while (queue.length > 0) {
259
- const method = queue.shift();
260
- try {
261
- const res = method(lr);
262
- if (res) {
263
- res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
264
- }
265
- }
266
- catch (e) {
267
- console.warn(`LogRocket method failed: ${e.message}`, e);
268
- }
269
- }
270
- }
271
- function initLogrocketIfNeeded(appId) {
272
- return __awaiter$4(this, void 0, void 0, function* () {
273
- if (getLogRocketState() !== "fresh") {
274
- return;
275
- }
276
- setLogRocketState("loading");
277
- loadScript(`${cdn}LogRocket`, { min: true, attributes: { crossOrigin: "anonymous" } })
278
- .then(() => {
279
- if (window["LogRocket"]) {
280
- try {
281
- window["LogRocket"].init(appId);
282
- }
283
- catch (e) {
284
- console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
285
- setLogRocketState("failed");
286
- }
287
- setLogRocketState("loaded");
288
- flushLogRocketQueue(window["LogRocket"]);
289
- }
290
- })
291
- .catch(e => {
292
- console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
293
- setLogRocketState("failed");
294
- });
295
- });
296
- }
297
-
298
- var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
299
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
300
- return new (P || (P = Promise))(function (resolve, reject) {
301
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
302
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
303
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
304
- step((generator = generator.apply(thisArg, _arguments || [])).next());
305
- });
306
- };
307
- function omit(obj, ...keys) {
308
- return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
309
- }
310
- const gtmPlugin = {
311
- id: "gtm",
312
- handle(config, payload) {
313
- return __awaiter$3(this, void 0, void 0, function* () {
314
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
315
- const debug = !!config.debug;
316
- if (!applyFilters(payload, config)) {
317
- return;
318
- }
319
- yield initGtmIfNeeded(config, payload);
320
- const dataLayer = window[config.dataLayerName || "dataLayer"];
321
- //traits could be in both nodes, context.traits takes precedence
322
- const traits = Object.assign(Object.assign({}, ((payload === null || payload === void 0 ? void 0 : payload.traits) || {})), (((_a = payload === null || payload === void 0 ? void 0 : payload.context) === null || _a === void 0 ? void 0 : _a.traits) || {}));
323
- //remove properties that defined separately
324
- const idsFromTraits = omit(traits, "id", "userId", "user_id", "anonymousId", "userId");
325
- if (debug) {
326
- console.debug("GTM plugin will be applied to following payload", payload);
327
- }
328
- // See https://developers.google.com/tag-platform/tag-manager/server-side/common-event-data
329
- const userData = {
330
- email_address: traits.email,
331
- };
332
- const ids = Object.assign(Object.assign(Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId, userId: payload.userId } : {})), (payload.anonymousId ? { anonymousId: payload.anonymousId } : {})), idsFromTraits), { user_data: Object.keys(userData).length > 0 ? userData : undefined });
333
- if (debug) {
334
- console.debug("GTM plugin will set following user-related data layer vars", ids);
335
- }
336
- const pageProperties = payload.properties || {};
337
- const pageVariables = {
338
- page_location: pageProperties.url || ((_c = (_b = payload.context) === null || _b === void 0 ? void 0 : _b.page) === null || _c === void 0 ? void 0 : _c.url),
339
- page_title: pageProperties.title || ((_e = (_d = payload.context) === null || _d === void 0 ? void 0 : _d.page) === null || _e === void 0 ? void 0 : _e.title),
340
- page_path: pageProperties.path || ((_g = (_f = payload.context) === null || _f === void 0 ? void 0 : _f.page) === null || _g === void 0 ? void 0 : _g.path),
341
- page_hash: pageProperties.hash || ((_j = (_h = payload.context) === null || _h === void 0 ? void 0 : _h.page) === null || _j === void 0 ? void 0 : _j.hash),
342
- page_search: pageProperties.search || ((_l = (_k = payload.context) === null || _k === void 0 ? void 0 : _k.page) === null || _l === void 0 ? void 0 : _l.search),
343
- page_referrer: (_p = (_o = (_m = payload === null || payload === void 0 ? void 0 : payload.context) === null || _m === void 0 ? void 0 : _m.page) === null || _o === void 0 ? void 0 : _o.referrer) !== null && _p !== void 0 ? _p : "",
344
- };
345
- if (debug) {
346
- console.debug("GTM plugin will set following context (page) related data layer vars", ids);
347
- }
348
- const pushToDataLayer = (data) => {
349
- dataLayer.push(data);
350
- if (debug) {
351
- console.debug("GTM plugin will push following data to dataLayer", data);
352
- }
353
- };
354
- switch (payload.type) {
355
- case "page":
356
- const pageEvent = Object.assign(Object.assign({ event: "page_view" }, pageVariables), ids);
357
- pushToDataLayer(pageEvent);
358
- break;
359
- case "track":
360
- const { properties: trackProperties } = payload;
361
- const trackEvent = Object.assign(Object.assign(Object.assign({ event: payload.event }, pageVariables), trackProperties), ids);
362
- pushToDataLayer(trackEvent);
363
- break;
364
- case "identify":
365
- const { traits } = payload;
366
- const identifyEvent = Object.assign(Object.assign(Object.assign({ event: "identify" }, pageVariables), traits), ids);
367
- pushToDataLayer(identifyEvent);
368
- break;
369
- }
370
- dataLayer.push(function () {
371
- this.reset();
372
- });
373
- });
374
- },
375
- };
376
- function getGtmState() {
377
- return window["__jitsuGtmState"] || "fresh";
378
- }
379
- function setGtmState(s) {
380
- window["__jitsuGtmState"] = s;
381
- }
382
- function initGtmIfNeeded(config, payload) {
383
- return __awaiter$3(this, void 0, void 0, function* () {
384
- if (getGtmState() !== "fresh") {
385
- return;
386
- }
387
- setGtmState("loading");
388
- const dlName = config.dataLayerName || "dataLayer";
389
- const tagId = config.containerId;
390
- (function (w, l, i) {
391
- w[l] = w[l] || [];
392
- w[l].push({
393
- user_id: payload.userId,
394
- });
395
- w[l].push({
396
- "gtm.start": new Date().getTime(),
397
- event: "gtm.js",
398
- });
399
- const dl = l != "dataLayer" ? "&l=" + l : "";
400
- const scriptSrc = "googletagmanager.com/gtm";
401
- loadScript(scriptSrc, { www: true, js: true, query: "id=" + i + dl })
402
- .then(() => {
403
- setGtmState("loaded");
404
- })
405
- .catch(e => {
406
- console.warn(`GTM (containerId=${tagId}) init failed: ${e.message}`, e);
407
- setGtmState("failed");
408
- });
409
- })(window, dlName, tagId);
410
- });
411
- }
412
-
413
- var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
414
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
415
- return new (P || (P = Promise))(function (resolve, reject) {
416
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
417
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
418
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
419
- step((generator = generator.apply(thisArg, _arguments || [])).next());
420
- });
421
- };
422
- const urlData = [
423
- new Uint8Array([109, 111, 99, 46, 114, 101, 103, 97, 110, 97, 109, 103, 97, 116, 101, 108, 103, 111, 111, 103]),
424
- new Uint8Array([103, 97, 116, 103]),
425
- new Uint8Array([115, 106]),
426
- ];
427
- function byteArrayToString(byteArray) {
428
- const decoder = new TextDecoder();
429
- return decoder.decode(byteArray);
430
- }
431
- function buildTagUrl() {
432
- return urlData
433
- .map(d => d.reverse())
434
- .map(byteArrayToString)
435
- .join("/");
436
- }
437
- const ga4Plugin = {
438
- id: "ga4-tag",
439
- handle(config, payload) {
440
- return __awaiter$2(this, void 0, void 0, function* () {
441
- var _a, _b;
442
- if (!applyFilters(payload, config)) {
443
- return;
444
- }
445
- yield initGa4IfNeeded(config, payload);
446
- const dataLayer = window[config.dataLayerName || "dataLayer"];
447
- const gtag = function () {
448
- dataLayer.push(arguments);
449
- };
450
- const ids = Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId, userId: payload.userId } : {})), (payload.anonymousId ? { anonymousId: payload.anonymousId } : {}));
451
- if (payload.userId) {
452
- // @ts-ignore
453
- gtag("set", { user_id: payload.userId });
454
- }
455
- switch (payload.type) {
456
- case "page":
457
- if (config.autoPageView) {
458
- console.log("autoPageView");
459
- break;
460
- }
461
- const { properties: pageProperties, context } = payload;
462
- const pageEvent = Object.assign({ page_location: pageProperties.url, page_title: pageProperties.title, page_path: pageProperties.path, page_hash: pageProperties.hash, page_search: pageProperties.search, page_referrer: (_b = (_a = context === null || context === void 0 ? void 0 : context.page) === null || _a === void 0 ? void 0 : _a.referrer) !== null && _b !== void 0 ? _b : "" }, ids);
463
- // @ts-ignore
464
- gtag("event", "page_view", pageEvent);
465
- break;
466
- case "track":
467
- const { properties: trackProperties } = payload;
468
- const trackEvent = Object.assign(Object.assign({}, trackProperties), ids);
469
- // @ts-ignore
470
- gtag("event", payload.event, trackEvent);
471
- break;
472
- case "identify":
473
- const { traits } = payload;
474
- const identifyEvent = Object.assign(Object.assign({}, traits), ids);
475
- // @ts-ignore
476
- gtag("event", "identify", identifyEvent);
477
- break;
478
- }
479
- });
480
- },
481
- };
482
- function getGa4State() {
483
- return window["__jitsuGa4State"] || "fresh";
484
- }
485
- function setGa4State(s) {
486
- window["__jitsuGa4State"] = s;
487
- }
488
- function initGa4IfNeeded(config, payload) {
489
- return __awaiter$2(this, void 0, void 0, function* () {
490
- if (getGa4State() !== "fresh") {
491
- return;
492
- }
493
- setGa4State("loading");
494
- const dlName = config.dataLayerName || "dataLayer";
495
- const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
496
- // to work with both GA4 and GTM
497
- const tagId = config.measurementIds;
498
- window[dlName] = window[dlName] || [];
499
- const gtag = function () {
500
- window[dlName].push(arguments);
501
- };
502
- // @ts-ignore
503
- gtag("js", new Date());
504
- gtag(
505
- // @ts-ignore
506
- "config", tagId, Object.assign(Object.assign({}, (payload.userId ? { user_id: payload.userId } : {})), (!config.autoPageView ? { send_page_view: false } : {})));
507
- loadScript(buildTagUrl(), { query: `id=${tagId}${dlParam}`, www: true })
508
- .then(() => {
509
- setGa4State("loaded");
510
- })
511
- .catch(e => {
512
- console.warn(`GA4 (containerId=${config.measurementIds}) init failed: ${e.message}`, e);
513
- setGa4State("failed");
514
- });
515
- });
516
- }
517
-
518
- function satisfyFilter(filter, subject) {
519
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
520
- }
521
- function satisfyDomainFilter(filter, subject) {
522
- if (filter === "*") {
523
- return true;
524
- }
525
- subject = subject || "";
526
- if (filter.startsWith("*.")) {
527
- return subject.endsWith(filter.substring(1));
528
- }
529
- else {
530
- return filter === subject;
531
- }
532
- }
533
- function applyFilters(event, creds) {
534
- const { hosts = "*", events = "*" } = creds;
535
- try {
536
- const eventsArray = Array.isArray(events) ? events : events.split("\n");
537
- const hostsArray = Array.isArray(hosts) ? hosts : hosts.split("\n");
538
- return (!!hostsArray.find(hostFilter => { var _a, _b; return satisfyDomainFilter(hostFilter, (_b = (_a = event.context) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.host); }) &&
539
- (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
540
- !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
541
- }
542
- catch (e) {
543
- console.warn(`Failed to apply filters: ${e.message}. Typeof events: ${typeof events}, typeof hosts: ${typeof hosts}. Values`, events, hosts);
544
- throw new Error(`Failed to apply filters: ${e.message}. Typeof events: ${typeof events}, typeof hosts: ${typeof hosts}`);
545
- }
546
- }
547
- const internalDestinationPlugins = {
548
- [tagPlugin.id]: tagPlugin,
549
- [gtmPlugin.id]: gtmPlugin,
550
- [ga4Plugin.id]: ga4Plugin,
551
- [logrocketPlugin.id]: logrocketPlugin,
552
- };
553
-
554
- const jitsuVersion = "2.0.0";
555
- const jitsuLibraryName = "@jitsu/js";
556
-
557
- const publicSuffixes = "myshopify.com,ac,com.ac,edu.ac,gov.ac,net.ac,mil.ac,org.ac,ad,nom.ad,ae,co.ae,net.ae,org.ae,sch.ae,ac.ae,gov.ae,mil.ae,aero,af,gov.af,com.af,org.af,net.af,edu.af,ag,com.ag,org.ag,net.ag,co.ag,nom.ag,ai,off.ai,com.ai,net.ai,org.ai,al,com.al,edu.al,gov.al,mil.al,net.al,org.al,am,co.am,com.am,commune.am,net.am,org.am,ao,ed.ao,gv.ao,og.ao,co.ao,pb.ao,it.ao,aq,ar,bet.ar,com.ar,coop.ar,edu.ar,gob.ar,gov.ar,int.ar,mil.ar,musica.ar,mutual.ar,net.ar,org.ar,senasa.ar,tur.ar,arpa,e164.arpa,in-addr.arpa,ip6.arpa,iris.arpa,uri.arpa,urn.arpa,as,gov.as,asia,at,ac.at,co.at,gv.at,or.at,sth.ac.at,au,com.au,net.au,org.au,edu.au,gov.au,asn.au,id.au,act.au,nsw.au,nt.au,qld.au,sa.au,tas.au,vic.au,wa.au,aw,com.aw,ax,az,com.az,net.az,int.az,gov.az,org.az,edu.az,info.az,pp.az,mil.az,name.az,pro.az,biz.az,ba,com.ba,edu.ba,gov.ba,mil.ba,net.ba,org.ba,bb,biz.bb,co.bb,com.bb,edu.bb,gov.bb,info.bb,net.bb,org.bb,store.bb,tv.bb,bd,be,ac.be,bf,gov.bf,bg,a.bg,b.bg,c.bg,d.bg,e.bg,f.bg,g.bg,h.bg,i.bg,j.bg,k.bg,l.bg,m.bg,n.bg,o.bg,p.bg,q.bg,r.bg,s.bg,t.bg,u.bg,v.bg,w.bg,x.bg,y.bg,z.bg,0.bg,1.bg,2.bg,3.bg,4.bg,5.bg,6.bg,7.bg,8.bg,9.bg,bh,com.bh,edu.bh,net.bh,org.bh,gov.bh,bi,co.bi,com.bi,edu.bi,or.bi,org.bi,biz,bj,africa.bj,agro.bj,architectes.bj,assur.bj,avocats.bj,co.bj,com.bj,eco.bj,econo.bj,edu.bj,info.bj,loisirs.bj,money.bj,net.bj,org.bj,ote.bj,resto.bj,restaurant.bj,tourism.bj,univ.bj,bm,com.bm,edu.bm,gov.bm,net.bm,org.bm,bn,com.bn,edu.bn,gov.bn,net.bn,org.bn,bo,com.bo,edu.bo,gob.bo,int.bo,org.bo,net.bo,mil.bo,tv.bo,web.bo,br,9guacu.br,abc.br,adm.br,adv.br,agr.br,aju.br,am.br,anani.br,aparecida.br,app.br,arq.br,art.br,ato.br,b.br,barueri.br,belem.br,bhz.br,bib.br,bio.br,blog.br,bmd.br,boavista.br,bsb.br,campinagrande.br,campinas.br,caxias.br,cim.br,cng.br,cnt.br,com.br,contagem.br,coop.br,coz.br,cri.br,cuiaba.br,curitiba.br,def.br,des.br,det.br,dev.br,ecn.br,eco.br,edu.br,emp.br,enf.br,eng.br,esp.br,etc.br,eti.br,far.br,feira.br,flog.br,floripa.br,fm.br,fnd.br,fortal.br,fot.br,foz.br,fst.br,g12.br,geo.br,ggf.br,goiania.br,gov.br,gru.br,imb.br,ind.br,inf.br,jab.br,jampa.br,jdf.br,joinville.br,jor.br,jus.br,leg.br,lel.br,log.br,londrina.br,macapa.br,maceio.br,manaus.br,maringa.br,mat.br,med.br,mil.br,morena.br,mp.br,mus.br,natal.br,net.br,niteroi.br,nom.br,not.br,ntr.br,odo.br,ong.br,org.br,osasco.br,palmas.br,poa.br,ppg.br,pro.br,psc.br,psi.br,pvh.br,qsl.br,radio.br,rec.br,recife.br,rep.br,ribeirao.br,rio.br,riobranco.br,riopreto.br,salvador.br,sampa.br,santamaria.br,santoandre.br,saobernardo.br,saogonca.br,seg.br,sjc.br,slg.br,slz.br,sorocaba.br,srv.br,taxi.br,tc.br,tec.br,teo.br,the.br,tmp.br,trd.br,tur.br,tv.br,udi.br,vet.br,vix.br,vlog.br,wiki.br,zlg.br,bs,com.bs,net.bs,org.bs,edu.bs,gov.bs,bt,com.bt,edu.bt,gov.bt,net.bt,org.bt,bv,bw,co.bw,org.bw,by,gov.by,mil.by,com.by,of.by,bz,com.bz,net.bz,org.bz,edu.bz,gov.bz,ca,ab.ca,bc.ca,mb.ca,nb.ca,nf.ca,nl.ca,ns.ca,nt.ca,nu.ca,on.ca,pe.ca,qc.ca,sk.ca,yk.ca,gc.ca,cat,cc,cd,gov.cd,cf,cg,ch,ci,org.ci,or.ci,com.ci,co.ci,edu.ci,ed.ci,ac.ci,net.ci,go.ci,asso.ci,aéroport.ci,int.ci,presse.ci,md.ci,gouv.ci,ck,cl,co.cl,gob.cl,gov.cl,mil.cl,cm,co.cm,com.cm,gov.cm,net.cm,cn,ac.cn,com.cn,edu.cn,gov.cn,net.cn,org.cn,mil.cn,co,arts.co,com.co,edu.co,firm.co,gov.co,info.co,int.co,mil.co,net.co,nom.co,org.co,rec.co,web.co,com,coop,cr,ac.cr,co.cr,ed.cr,fi.cr,go.cr,or.cr,sa.cr,cu,com.cu,edu.cu,org.cu,net.cu,gov.cu,inf.cu,cv,com.cv,edu.cv,int.cv,nome.cv,org.cv,cw,com.cw,edu.cw,net.cw,org.cw,cx,gov.cx,cy,ac.cy,biz.cy,com.cy,ekloges.cy,gov.cy,ltd.cy,mil.cy,net.cy,org.cy,press.cy,pro.cy,tm.cy,cz,de,dj,dk,dm,com.dm,net.dm,org.dm,edu.dm,gov.dm,do,art.do,com.do,edu.do,gob.do,gov.do,mil.do,net.do,org.do,sld.do,web.do,dz,art.dz,asso.dz,com.dz,edu.dz,gov.dz,org.dz,net.dz,pol.dz,soc.dz,tm.dz,ec,com.ec,info.ec,net.ec,fin.ec,k12.ec,med.ec,pro.ec,org.ec,edu.ec,gov.ec,gob.ec,mil.ec,edu,ee,edu.ee,gov.ee,riik.ee,lib.ee,med.ee,com.ee,pri.ee,aip.ee,org.ee,fie.ee,eg,com.eg,edu.eg,eun.eg,gov.eg,mil.eg,name.eg,net.eg,org.eg,sci.eg,er,es,com.es,nom.es,org.es,gob.es,edu.es,et,com.et,gov.et,org.et,edu.et,biz.et,name.et,info.et,net.et,eu,fi,aland.fi,fj,ac.fj,biz.fj,com.fj,gov.fj,info.fj,mil.fj,name.fj,net.fj,org.fj,pro.fj,fk,com.fm,edu.fm,net.fm,org.fm,fm,fo,fr,asso.fr,com.fr,gouv.fr,nom.fr,prd.fr,tm.fr,aeroport.fr,avocat.fr,avoues.fr,cci.fr,chambagri.fr,chirurgiens-dentistes.fr,experts-comptables.fr,geometre-expert.fr,greta.fr,huissier-justice.fr,medecin.fr,notaires.fr,pharmacien.fr,port.fr,veterinaire.fr,ga,gb,edu.gd,gov.gd,gd,ge,com.ge,edu.ge,gov.ge,org.ge,mil.ge,net.ge,pvt.ge,gf,gg,co.gg,net.gg,org.gg,gh,com.gh,edu.gh,gov.gh,org.gh,mil.gh,gi,com.gi,ltd.gi,gov.gi,mod.gi,edu.gi,org.gi,gl,co.gl,com.gl,edu.gl,net.gl,org.gl,gm,gn,ac.gn,com.gn,edu.gn,gov.gn,org.gn,net.gn,gov,gp,com.gp,net.gp,mobi.gp,edu.gp,org.gp,asso.gp,gq,gr,com.gr,edu.gr,net.gr,org.gr,gov.gr,gs,gt,com.gt,edu.gt,gob.gt,ind.gt,mil.gt,net.gt,org.gt,gu,com.gu,edu.gu,gov.gu,guam.gu,info.gu,net.gu,org.gu,web.gu,gw,gy,co.gy,com.gy,edu.gy,gov.gy,net.gy,org.gy,hk,com.hk,edu.hk,gov.hk,idv.hk,net.hk,org.hk,hm,hn,com.hn,edu.hn,org.hn,net.hn,mil.hn,gob.hn,hr,iz.hr,from.hr,name.hr,com.hr,ht,com.ht,shop.ht,firm.ht,info.ht,adult.ht,net.ht,pro.ht,org.ht,med.ht,art.ht,coop.ht,pol.ht,asso.ht,edu.ht,rel.ht,gouv.ht,perso.ht,hu,co.hu,info.hu,org.hu,priv.hu,sport.hu,tm.hu,2000.hu,agrar.hu,bolt.hu,casino.hu,city.hu,erotica.hu,erotika.hu,film.hu,forum.hu,games.hu,hotel.hu,ingatlan.hu,jogasz.hu,konyvelo.hu,lakas.hu,media.hu,news.hu,reklam.hu,sex.hu,shop.hu,suli.hu,szex.hu,tozsde.hu,utazas.hu,video.hu,id,ac.id,biz.id,co.id,desa.id,go.id,mil.id,my.id,net.id,or.id,ponpes.id,sch.id,web.id,ie,gov.ie,il,ac.il,co.il,gov.il,idf.il,k12.il,muni.il,net.il,org.il,im,ac.im,co.im,com.im,ltd.co.im,net.im,org.im,plc.co.im,tt.im,tv.im,in,5g.in,6g.in,ac.in,ai.in,am.in,bihar.in,biz.in,business.in,ca.in,cn.in,co.in,com.in,coop.in,cs.in,delhi.in,dr.in,edu.in,er.in,firm.in,gen.in,gov.in,gujarat.in,ind.in,info.in,int.in,internet.in,io.in,me.in,mil.in,net.in,nic.in,org.in,pg.in,post.in,pro.in,res.in,travel.in,tv.in,uk.in,up.in,us.in,info,int,eu.int,io,com.io,iq,gov.iq,edu.iq,mil.iq,com.iq,org.iq,net.iq,ir,ac.ir,co.ir,gov.ir,id.ir,net.ir,org.ir,sch.ir,is,net.is,com.is,edu.is,gov.is,org.is,int.is,it,gov.it,edu.it,je,co.je,net.je,org.je,jm,jo,com.jo,org.jo,net.jo,edu.jo,sch.jo,gov.jo,mil.jo,name.jo,jobs,jp,ac.jp,ad.jp,co.jp,ed.jp,go.jp,gr.jp,lg.jp,ne.jp,or.jp,ke,ac.ke,co.ke,go.ke,info.ke,me.ke,mobi.ke,ne.ke,or.ke,sc.ke,kg,org.kg,net.kg,com.kg,edu.kg,gov.kg,mil.kg,kh,ki,edu.ki,biz.ki,net.ki,org.ki,gov.ki,info.ki,com.ki,km,org.km,nom.km,gov.km,prd.km,tm.km,edu.km,mil.km,ass.km,com.km,kn,net.kn,org.kn,edu.kn,gov.kn,kp,com.kp,edu.kp,gov.kp,org.kp,rep.kp,tra.kp,kr,ac.kr,co.kr,es.kr,go.kr,hs.kr,kg.kr,mil.kr,ms.kr,ne.kr,or.kr,pe.kr,re.kr,sc.kr,kw,com.kw,edu.kw,emb.kw,gov.kw,ind.kw,net.kw,org.kw,ky,com.ky,edu.ky,net.ky,org.ky,kz,org.kz,edu.kz,net.kz,gov.kz,mil.kz,com.kz,la,int.la,net.la,info.la,edu.la,gov.la,per.la,com.la,org.la,lb,com.lb,edu.lb,gov.lb,net.lb,org.lb,lc,com.lc,net.lc,co.lc,org.lc,edu.lc,gov.lc,li,lk,gov.lk,sch.lk,net.lk,int.lk,com.lk,org.lk,edu.lk,ngo.lk,soc.lk,web.lk,ltd.lk,assn.lk,grp.lk,hotel.lk,ac.lk,lr,com.lr,edu.lr,gov.lr,org.lr,net.lr,ls,ac.ls,biz.ls,co.ls,edu.ls,gov.ls,info.ls,net.ls,org.ls,sc.ls,lt,gov.lt,lu,lv,com.lv,edu.lv,gov.lv,org.lv,mil.lv,id.lv,net.lv,asn.lv,conf.lv,ly,com.ly,net.ly,gov.ly,plc.ly,edu.ly,sch.ly,med.ly,org.ly,id.ly,ma,co.ma,net.ma,gov.ma,org.ma,ac.ma,press.ma,mc,tm.mc,asso.mc,md,me,co.me,net.me,org.me,edu.me,ac.me,gov.me,its.me,priv.me,mg,org.mg,nom.mg,gov.mg,prd.mg,tm.mg,edu.mg,mil.mg,com.mg,co.mg,mh,mil,mk,com.mk,org.mk,net.mk,edu.mk,gov.mk,inf.mk,name.mk,ml,com.ml,edu.ml,gouv.ml,gov.ml,net.ml,org.ml,presse.ml,mm,mn,gov.mn,edu.mn,org.mn,mo,com.mo,net.mo,org.mo,edu.mo,gov.mo,mobi,mp,mq,mr,gov.mr,ms,com.ms,edu.ms,gov.ms,net.ms,org.ms,mt,com.mt,edu.mt,net.mt,org.mt,mu,com.mu,net.mu,org.mu,gov.mu,ac.mu,co.mu,or.mu,museum,mv,aero.mv,biz.mv,com.mv,coop.mv,edu.mv,gov.mv,info.mv,int.mv,mil.mv,museum.mv,name.mv,net.mv,org.mv,pro.mv,mw,ac.mw,biz.mw,co.mw,com.mw,coop.mw,edu.mw,gov.mw,int.mw,museum.mw,net.mw,org.mw,mx,com.mx,org.mx,gob.mx,edu.mx,net.mx,my,biz.my,com.my,edu.my,gov.my,mil.my,name.my,net.my,org.my,mz,ac.mz,adv.mz,co.mz,edu.mz,gov.mz,mil.mz,net.mz,org.mz,na,info.na,pro.na,name.na,school.na,or.na,dr.na,us.na,mx.na,ca.na,in.na,cc.na,tv.na,ws.na,mobi.na,co.na,com.na,org.na,name,nc,asso.nc,nom.nc,ne,net,nf,com.nf,net.nf,per.nf,rec.nf,web.nf,arts.nf,firm.nf,info.nf,other.nf,store.nf,ng,com.ng,edu.ng,gov.ng,i.ng,mil.ng,mobi.ng,name.ng,net.ng,org.ng,sch.ng,ni,ac.ni,biz.ni,co.ni,com.ni,edu.ni,gob.ni,in.ni,info.ni,int.ni,mil.ni,net.ni,nom.ni,org.ni,web.ni,nl,no,fhs.no,vgs.no,fylkesbibl.no,folkebibl.no,museum.no,idrett.no,priv.no,mil.no,stat.no,dep.no,kommune.no,herad.no,np,nr,biz.nr,info.nr,gov.nr,edu.nr,org.nr,net.nr,com.nr,nu,nz,ac.nz,co.nz,cri.nz,geek.nz,gen.nz,govt.nz,health.nz,iwi.nz,kiwi.nz,maori.nz,mil.nz,māori.nz,net.nz,org.nz,parliament.nz,school.nz,om,co.om,com.om,edu.om,gov.om,med.om,museum.om,net.om,org.om,pro.om,onion,org,pa,ac.pa,gob.pa,com.pa,org.pa,sld.pa,edu.pa,net.pa,ing.pa,abo.pa,med.pa,nom.pa,pe,edu.pe,gob.pe,nom.pe,mil.pe,org.pe,com.pe,net.pe,pf,com.pf,org.pf,edu.pf,pg,ph,com.ph,net.ph,org.ph,gov.ph,edu.ph,ngo.ph,mil.ph,i.ph,pk,com.pk,net.pk,edu.pk,org.pk,fam.pk,biz.pk,web.pk,gov.pk,gob.pk,gok.pk,gon.pk,gop.pk,gos.pk,info.pk,pl,com.pl,net.pl,org.pl,aid.pl,agro.pl,atm.pl,auto.pl,biz.pl,edu.pl,gmina.pl,gsm.pl,info.pl,mail.pl,miasta.pl,media.pl,mil.pl,nieruchomosci.pl,nom.pl,pc.pl,powiat.pl,priv.pl,realestate.pl,rel.pl,sex.pl,shop.pl,sklep.pl,sos.pl,szkola.pl,targi.pl,tm.pl,tourism.pl,travel.pl,turystyka.pl,pm,pn,gov.pn,co.pn,org.pn,edu.pn,net.pn,post,pr,com.pr,net.pr,org.pr,gov.pr,edu.pr,isla.pr,pro.pr,biz.pr,info.pr,name.pr,est.pr,prof.pr,ac.pr,pro,aaa.pro,aca.pro,acct.pro,avocat.pro,bar.pro,cpa.pro,eng.pro,jur.pro,law.pro,med.pro,recht.pro,ps,edu.ps,gov.ps,sec.ps,plo.ps,com.ps,org.ps,net.ps,pt,net.pt,gov.pt,org.pt,edu.pt,int.pt,publ.pt,com.pt,nome.pt,pw,co.pw,ne.pw,or.pw,ed.pw,go.pw,belau.pw,py,com.py,coop.py,edu.py,gov.py,mil.py,net.py,org.py,qa,com.qa,edu.qa,gov.qa,mil.qa,name.qa,net.qa,org.qa,sch.qa,re,asso.re,com.re,nom.re,ro,arts.ro,com.ro,firm.ro,info.ro,nom.ro,nt.ro,org.ro,rec.ro,store.ro,tm.ro,www.ro,rs,ac.rs,co.rs,edu.rs,gov.rs,in.rs,org.rs,ru,rw,ac.rw,co.rw,coop.rw,gov.rw,mil.rw,net.rw,org.rw,sa,com.sa,net.sa,org.sa,gov.sa,med.sa,pub.sa,edu.sa,sch.sa,sb,com.sb,edu.sb,gov.sb,net.sb,org.sb,sc,com.sc,gov.sc,net.sc,org.sc,edu.sc,sd,com.sd,net.sd,org.sd,edu.sd,med.sd,tv.sd,gov.sd,info.sd,se,a.se,ac.se,b.se,bd.se,brand.se,c.se,d.se,e.se,f.se,fh.se,fhsk.se,fhv.se,g.se,h.se,i.se,k.se,komforb.se,kommunalforbund.se,komvux.se,l.se,lanbib.se,m.se,n.se,naturbruksgymn.se,o.se,org.se,p.se,parti.se,pp.se,press.se,r.se,s.se,t.se,tm.se,u.se,w.se,x.se,y.se,z.se,sg,com.sg,net.sg,org.sg,gov.sg,edu.sg,per.sg,sh,com.sh,net.sh,gov.sh,org.sh,mil.sh,si,sj,sk,sl,com.sl,net.sl,edu.sl,gov.sl,org.sl,sm,sn,art.sn,com.sn,edu.sn,gouv.sn,org.sn,perso.sn,univ.sn,so,com.so,edu.so,gov.so,me.so,net.so,org.so,sr,ss,biz.ss,com.ss,edu.ss,gov.ss,me.ss,net.ss,org.ss,sch.ss,st,co.st,com.st,consulado.st,edu.st,embaixada.st,mil.st,net.st,org.st,principe.st,saotome.st,store.st,su,sv,com.sv,edu.sv,gob.sv,org.sv,red.sv,sx,gov.sx,sy,edu.sy,gov.sy,net.sy,mil.sy,com.sy,org.sy,sz,co.sz,ac.sz,org.sz,tc,td,tel,tf,tg,th,ac.th,co.th,go.th,in.th,mi.th,net.th,or.th,tj,ac.tj,biz.tj,co.tj,com.tj,edu.tj,go.tj,gov.tj,int.tj,mil.tj,name.tj,net.tj,nic.tj,org.tj,test.tj,web.tj,tk,tl,gov.tl,tm,com.tm,co.tm,org.tm,net.tm,nom.tm,gov.tm,mil.tm,edu.tm,tn,com.tn,ens.tn,fin.tn,gov.tn,ind.tn,info.tn,intl.tn,mincom.tn,nat.tn,net.tn,org.tn,perso.tn,tourism.tn,to,com.to,gov.to,net.to,org.to,edu.to,mil.to,tr,av.tr,bbs.tr,bel.tr,biz.tr,com.tr,dr.tr,edu.tr,gen.tr,gov.tr,info.tr,mil.tr,k12.tr,kep.tr,name.tr,net.tr,org.tr,pol.tr,tel.tr,tsk.tr,tv.tr,web.tr,nc.tr,tt,co.tt,com.tt,org.tt,net.tt,biz.tt,info.tt,pro.tt,int.tt,coop.tt,jobs.tt,mobi.tt,travel.tt,museum.tt,aero.tt,name.tt,gov.tt,edu.tt,tv,tw,edu.tw,gov.tw,mil.tw,com.tw,net.tw,org.tw,idv.tw,game.tw,ebiz.tw,club.tw,tz,ac.tz,co.tz,go.tz,hotel.tz,info.tz,me.tz,mil.tz,mobi.tz,ne.tz,or.tz,sc.tz,tv.tz,ua,com.ua,edu.ua,gov.ua,in.ua,net.ua,org.ua,ug,co.ug,or.ug,ac.ug,sc.ug,go.ug,ne.ug,com.ug,org.ug,uk,ac.uk,co.uk,gov.uk,ltd.uk,me.uk,net.uk,nhs.uk,org.uk,plc.uk,police.uk,us,dni.us,fed.us,isa.us,kids.us,nsn.us,ak.us,al.us,ar.us,as.us,az.us,ca.us,co.us,ct.us,dc.us,de.us,fl.us,ga.us,gu.us,hi.us,ia.us,id.us,il.us,in.us,ks.us,ky.us,la.us,ma.us,md.us,me.us,mi.us,mn.us,mo.us,ms.us,mt.us,nc.us,nd.us,ne.us,nh.us,nj.us,nm.us,nv.us,ny.us,oh.us,ok.us,or.us,pa.us,pr.us,ri.us,sc.us,sd.us,tn.us,tx.us,ut.us,vi.us,vt.us,va.us,wa.us,wi.us,wv.us,wy.us,uy,com.uy,edu.uy,gub.uy,mil.uy,net.uy,org.uy,uz,co.uz,com.uz,net.uz,org.uz,va,vc,com.vc,net.vc,org.vc,gov.vc,mil.vc,edu.vc,ve,arts.ve,bib.ve,co.ve,com.ve,e12.ve,edu.ve,firm.ve,gob.ve,gov.ve,info.ve,int.ve,mil.ve,net.ve,nom.ve,org.ve,rar.ve,rec.ve,store.ve,tec.ve,web.ve,vg,vi,co.vi,com.vi,k12.vi,net.vi,org.vi,vn,ac.vn,ai.vn,biz.vn,com.vn,edu.vn,gov.vn,health.vn,id.vn,info.vn,int.vn,io.vn,name.vn,net.vn,org.vn,pro.vn,vu,com.vu,edu.vu,net.vu,org.vu,wf,ws,com.ws,net.ws,org.ws,gov.ws,edu.ws,yt,ye,com.ye,edu.ye,gov.ye,net.ye,mil.ye,org.ye,ac.za,agric.za,alt.za,co.za,edu.za,gov.za,grondar.za,law.za,mil.za,net.za,ngo.za,nic.za,nis.za,nom.za,org.za,school.za,tm.za,web.za,zm,ac.zm,biz.zm,co.zm,com.zm,edu.zm,gov.zm,info.zm,mil.zm,net.zm,org.zm,sch.zm,zw,ac.zw,co.zw,gov.zw,mil.zw,org.zw".split(",");
558
- //convert to Map
559
- const _publicSuffixesMap = {};
560
- publicSuffixes.forEach(tld => {
561
- _publicSuffixesMap[tld] = true;
562
- });
563
- const publicSuffixesMap = _publicSuffixesMap;
564
- function getTopLevelDomain(hostname) {
565
- const [domain] = hostname.split(":");
566
- const parts = domain.split(".");
567
- if (parts[parts.length - 1] === "localhost" || parts.length < 2) {
568
- return parts[parts.length - 1];
569
- }
570
- else {
571
- const d = parts[parts.length - 2] + "." + parts[parts.length - 1];
572
- if (parts.length > 2 && publicSuffixesMap[d]) {
573
- return parts[parts.length - 3] + "." + d;
574
- }
575
- else {
576
- return d;
577
- }
578
- }
579
- }
580
-
581
- class Processor {
582
- constructor(options) {
583
- this.selfOptions = options || {};
584
- this.pipes = {};
585
- }
586
- options(options) {
587
- if (options) {
588
- this.selfOptions = options;
589
- }
590
- return this.selfOptions;
591
- }
592
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
593
- pipe(name, pipeArg) {
594
- let pipe = pipeArg;
595
- if (typeof name === "string") {
596
- if (typeof pipe === "undefined") {
597
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
598
- return this.pipes[name];
599
- }
600
- else {
601
- this.pipes[name] = pipe;
602
- }
603
- }
604
- if (name && name.name) {
605
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
606
- pipe = name;
607
- if (pipe.processor === this) {
608
- return pipe;
609
- }
610
- this.pipes[pipe.name] = pipe;
611
- }
612
- pipe.processor = this;
613
- return pipe;
614
- }
615
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
616
- process(input, pipe) {
617
- let context = input;
618
- context.options = this.options();
619
- let nextPipe = pipe || input.pipe || "default";
620
- let lastPipe;
621
- while (nextPipe) {
622
- if (typeof context.nextAfterChildren !== "undefined") {
623
- // children processed and coming back to parent
624
- context.next = context.nextAfterChildren;
625
- context.nextAfterChildren = null;
626
- }
627
- if (typeof nextPipe === "string") {
628
- nextPipe = this.pipe(nextPipe);
629
- }
630
- nextPipe.process(context);
631
- lastPipe = nextPipe;
632
- nextPipe = null;
633
- if (context) {
634
- if (context.next) {
635
- context = context.next;
636
- nextPipe = context.pipe || lastPipe;
637
- }
638
- }
639
- }
640
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
641
- return context.hasResult ? context.result : undefined;
642
- }
643
- }
644
-
645
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
646
- class Pipe {
647
- constructor(name) {
648
- this.name = name;
649
- this.filters = [];
650
- }
651
- process(input) {
652
- if (!this.processor) {
653
- throw new Error("add this pipe to a processor before using it");
654
- }
655
- const debug = this.debug;
656
- const length = this.filters.length;
657
- const context = input;
658
- for (let index = 0; index < length; index++) {
659
- const filter = this.filters[index];
660
- if (debug) {
661
- this.log(`filter: ${filter.filterName}`);
662
- }
663
- filter(context);
664
- if (typeof context === "object" && context.exiting) {
665
- context.exiting = false;
666
- break;
667
- }
668
- }
669
- if (!context.next && this.resultCheck) {
670
- this.resultCheck(context);
671
- }
672
- }
673
- log(msg) {
674
- console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
675
- }
676
- append(...args) {
677
- this.filters.push(...args);
678
- return this;
679
- }
680
- prepend(...args) {
681
- this.filters.unshift(...args);
682
- return this;
683
- }
684
- indexOf(filterName) {
685
- if (!filterName) {
686
- throw new Error("a filter name is required");
687
- }
688
- for (let index = 0; index < this.filters.length; index++) {
689
- const filter = this.filters[index];
690
- if (filter.filterName === filterName) {
691
- return index;
692
- }
693
- }
694
- throw new Error(`filter not found: ${filterName}`);
695
- }
696
- list() {
697
- return this.filters.map(f => f.filterName);
698
- }
699
- after(filterName, ...params) {
700
- const index = this.indexOf(filterName);
701
- this.filters.splice(index + 1, 0, ...params);
702
- return this;
703
- }
704
- before(filterName, ...params) {
705
- const index = this.indexOf(filterName);
706
- this.filters.splice(index, 0, ...params);
707
- return this;
708
- }
709
- replace(filterName, ...params) {
710
- const index = this.indexOf(filterName);
711
- this.filters.splice(index, 1, ...params);
712
- return this;
713
- }
714
- remove(filterName) {
715
- const index = this.indexOf(filterName);
716
- this.filters.splice(index, 1);
717
- return this;
718
- }
719
- clear() {
720
- this.filters.length = 0;
721
- return this;
722
- }
723
- shouldHaveResult(should) {
724
- if (should === false) {
725
- this.resultCheck = null;
726
- return;
727
- }
728
- if (this.resultCheck) {
729
- return;
730
- }
731
- this.resultCheck = context => {
732
- if (!context.hasResult) {
733
- console.log(context);
734
- const error = new Error(`${this.name} failed`);
735
- error.noResult = true;
736
- throw error;
737
- }
738
- };
739
- return this;
740
- }
741
- }
742
-
743
- class Context {
744
- setResult(result) {
745
- this.result = result;
746
- this.hasResult = true;
747
- return this;
748
- }
749
- exit() {
750
- this.exiting = true;
751
- return this;
752
- }
753
- push(child, name) {
754
- child.parent = this;
755
- if (typeof name !== "undefined") {
756
- child.childName = name;
757
- }
758
- child.root = this.root || this;
759
- child.options = child.options || this.options;
760
- if (!this.children) {
761
- this.children = [child];
762
- this.nextAfterChildren = this.next || null;
763
- this.next = child;
764
- }
765
- else {
766
- this.children[this.children.length - 1].next = child;
767
- this.children.push(child);
768
- }
769
- child.next = this;
770
- return this;
771
- }
772
- }
773
-
774
- class DiffContext extends Context {
775
- constructor(left, right) {
776
- super();
777
- this.left = left;
778
- this.right = right;
779
- this.pipe = "diff";
780
- }
781
- setResult(result) {
782
- return super.setResult(result);
783
- }
784
- }
785
-
786
- class PatchContext extends Context {
787
- constructor(left, delta) {
788
- super();
789
- this.left = left;
790
- this.delta = delta;
791
- this.pipe = "patch";
792
- }
793
- }
794
-
795
- function arrayEquals(a, b) {
796
- if (a.length !== b.length) {
797
- return false;
798
- }
799
- for (let i = 0; i < a.length; i++) {
800
- if (a[i] !== b[i]) {
801
- return false;
802
- }
803
- }
804
- return true;
805
- }
806
- const diffFilter$1 = function trivialMatchesDiffFilter(context) {
807
- if (context.left === context.right) {
808
- context.setResult(undefined).exit();
809
- return;
810
- }
811
- if (typeof context.left === "undefined") {
812
- if (typeof context.right === "function") {
813
- throw new Error("functions are not supported");
814
- }
815
- context.setResult([context.right]).exit();
816
- return;
817
- }
818
- if (typeof context.right === "undefined") {
819
- context.setResult([context.left, 0, 0]).exit();
820
- return;
821
- }
822
- if (typeof context.left === "function" || typeof context.right === "function") {
823
- throw new Error("functions are not supported");
824
- }
825
- context.leftType = context.left === null ? "null" : typeof context.left;
826
- context.rightType = context.right === null ? "null" : typeof context.right;
827
- if (context.leftType !== context.rightType) {
828
- context.setResult([context.left, context.right]).exit();
829
- return;
830
- }
831
- if (context.leftType === "boolean" || context.leftType === "number" || context.leftType === "string") {
832
- context.setResult([context.left, context.right]).exit();
833
- return;
834
- }
835
- if (context.leftType === "object") {
836
- context.leftIsArray = Array.isArray(context.left);
837
- }
838
- if (context.rightType === "object") {
839
- context.rightIsArray = Array.isArray(context.right);
840
- }
841
- if (context.leftIsArray !== context.rightIsArray) {
842
- context.setResult([context.left, context.right]).exit();
843
- return;
844
- }
845
- if (context.leftIsArray && context.rightIsArray) {
846
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
847
- if (arrayEquals(context.left, context.right)) {
848
- context.setResult(undefined).exit();
849
- return;
850
- }
851
- else {
852
- context.setResult([context.left, context.right]).exit();
853
- return;
854
- }
855
- }
856
- if (context.left instanceof RegExp) {
857
- if (context.right instanceof RegExp) {
858
- context.setResult([context.left.toString(), context.right.toString()]).exit();
859
- }
860
- else {
861
- context.setResult([context.left, context.right]).exit();
862
- }
863
- }
864
- };
865
- diffFilter$1.filterName = "trivial";
866
- const patchFilter$1 = function trivialMatchesPatchFilter(context) {
867
- if (typeof context.delta === "undefined") {
868
- context.setResult(context.left).exit();
869
- return;
870
- }
871
- context.nested = !Array.isArray(context.delta);
872
- if (context.nested) {
873
- return;
874
- }
875
- const nonNestedDelta = context.delta;
876
- if (nonNestedDelta.length === 1) {
877
- context.setResult(nonNestedDelta[0]).exit();
878
- return;
879
- }
880
- if (nonNestedDelta.length === 2) {
881
- if (context.left instanceof RegExp) {
882
- const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
883
- if (regexArgs) {
884
- context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
885
- return;
886
- }
887
- }
888
- context.setResult(nonNestedDelta[1]).exit();
889
- return;
890
- }
891
- if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
892
- context.setResult(undefined).exit();
893
- }
894
- };
895
- patchFilter$1.filterName = "trivial";
896
-
897
- const collectChildrenDiffFilter = context => {
898
- if (!context || !context.children) {
899
- return;
900
- }
901
- const length = context.children.length;
902
- let child;
903
- let result = context.result;
904
- for (let index = 0; index < length; index++) {
905
- child = context.children[index];
906
- if (typeof child.result === "undefined") {
907
- continue;
908
- }
909
- result = result || {};
910
- result[child.childName] = child.result;
911
- }
912
- if (result && context.leftIsArray) {
913
- result._t = "a";
914
- }
915
- context.setResult(result).exit();
916
- };
917
- collectChildrenDiffFilter.filterName = "collectChildren";
918
- const objectsDiffFilter = context => {
919
- if (context.leftIsArray || context.leftType !== "object") {
920
- return;
921
- }
922
- const left = context.left;
923
- const right = context.right;
924
- let name;
925
- let child;
926
- const propertyFilter = context.options.propertyFilter;
927
- for (name in left) {
928
- if (!Object.prototype.hasOwnProperty.call(left, name)) {
929
- continue;
930
- }
931
- if (propertyFilter && !propertyFilter(name, context)) {
932
- continue;
933
- }
934
- child = new DiffContext(left[name], right[name]);
935
- context.push(child, name);
936
- }
937
- for (name in right) {
938
- if (!Object.prototype.hasOwnProperty.call(right, name)) {
939
- continue;
940
- }
941
- if (propertyFilter && !propertyFilter(name, context)) {
942
- continue;
943
- }
944
- if (typeof left[name] === "undefined") {
945
- child = new DiffContext(undefined, right[name]);
946
- context.push(child, name);
947
- }
948
- }
949
- if (!context.children || context.children.length === 0) {
950
- context.setResult(undefined).exit();
951
- return;
952
- }
953
- context.exit();
954
- };
955
- objectsDiffFilter.filterName = "objects";
956
- const patchFilter = function nestedPatchFilter(context) {
957
- if (!context.nested) {
958
- return;
959
- }
960
- const nestedDelta = context.delta;
961
- if (nestedDelta._t) {
962
- return;
963
- }
964
- const objectDelta = nestedDelta;
965
- let name;
966
- let child;
967
- for (name in objectDelta) {
968
- child = new PatchContext(context.left[name], objectDelta[name]);
969
- context.push(child, name);
970
- }
971
- context.exit();
972
- };
973
- patchFilter.filterName = "objects";
974
- const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {
975
- if (!context || !context.children) {
976
- return;
977
- }
978
- const deltaWithChildren = context.delta;
979
- if (deltaWithChildren._t) {
980
- return;
981
- }
982
- const object = context.left;
983
- const length = context.children.length;
984
- let child;
985
- for (let index = 0; index < length; index++) {
986
- child = context.children[index];
987
- const property = child.childName;
988
- if (Object.prototype.hasOwnProperty.call(context.left, property) && child.result === undefined) {
989
- delete object[property];
990
- }
991
- else if (object[property] !== child.result) {
992
- object[property] = child.result;
993
- }
994
- }
995
- context.setResult(object).exit();
996
- };
997
- collectChildrenPatchFilter.filterName = "collectChildren";
998
-
999
- const diffFilter = function datesDiffFilter(context) {
1000
- if (context.left instanceof Date) {
1001
- if (context.right instanceof Date) {
1002
- if (context.left.getTime() !== context.right.getTime()) {
1003
- context.setResult([context.left, context.right]);
1004
- }
1005
- else {
1006
- context.setResult(undefined);
1007
- }
1008
- }
1009
- else {
1010
- context.setResult([context.left, context.right]);
1011
- }
1012
- context.exit();
1013
- }
1014
- else if (context.right instanceof Date) {
1015
- context.setResult([context.left, context.right]).exit();
1016
- }
1017
- };
1018
- diffFilter.filterName = "dates";
1019
-
1020
- class DiffPatcher {
1021
- constructor(options) {
1022
- this.processor = new Processor(options);
1023
- this.processor.pipe(new Pipe("diff")
1024
- .append(collectChildrenDiffFilter, diffFilter$1, diffFilter, objectsDiffFilter)
1025
- .shouldHaveResult());
1026
- this.processor.pipe(new Pipe("patch")
1027
- .append(collectChildrenPatchFilter, patchFilter$1, patchFilter)
1028
- .shouldHaveResult());
1029
- }
1030
- options(options) {
1031
- return this.processor.options(options);
1032
- }
1033
- diff(left, right) {
1034
- return this.processor.process(new DiffContext(left, right));
1035
- }
1036
- patch(left, delta) {
1037
- return this.processor.process(new PatchContext(left, delta));
1038
- }
1039
- }
1040
-
1041
- function create(options) {
1042
- return new DiffPatcher(options);
1043
- }
1044
-
1045
- /* global analytics */
1046
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1047
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1048
- return new (P || (P = Promise))(function (resolve, reject) {
1049
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1050
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1051
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1052
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1053
- });
1054
- };
1055
- const diff = create();
1056
- const defaultConfig = {
1057
- /* Your segment writeKey */
1058
- writeKey: null,
1059
- /* Disable anonymous MTU */
1060
- host: null,
1061
- debug: false,
1062
- fetch: null,
1063
- echoEvents: false,
1064
- cookieDomain: undefined,
1065
- cookieNames: {},
1066
- cookieCapture: {},
1067
- runtime: undefined,
1068
- fetchTimeoutMs: undefined,
1069
- s2s: undefined,
1070
- idEndpoint: undefined,
1071
- errorPolicy: "log",
1072
- defaultPayloadContext: {},
1073
- privacy: {
1074
- dontSend: false,
1075
- disableUserIds: false,
1076
- ipPolicy: "keep",
1077
- consentCategories: undefined,
1078
- },
1079
- };
1080
- // mergeConfig merges newConfig into currentConfig also making sure that all undefined values are replaced with defaultConfig values
1081
- const mergeConfig = (current, newConfig) => {
1082
- for (const key of Object.keys(defaultConfig)) {
1083
- const value = newConfig[key];
1084
- if (key === "privacy") {
1085
- if (typeof value === "object") {
1086
- current.privacy = Object.assign(Object.assign(Object.assign({}, defaultConfig.privacy), current.privacy), value);
1087
- }
1088
- else if (newConfig.hasOwnProperty("privacy") && typeof value === "undefined") {
1089
- // explicitly set to undefined - reset to default
1090
- current.privacy = Object.assign({}, defaultConfig.privacy);
1091
- }
1092
- }
1093
- else if (typeof value === "undefined") {
1094
- if (newConfig.hasOwnProperty(key) || !current.hasOwnProperty(key)) {
1095
- // explicitly set to undefined - reset to default
1096
- // or was not set at all - set to default
1097
- current[key] = defaultConfig[key];
1098
- }
1099
- }
1100
- else {
1101
- current[key] = value;
1102
- }
1103
- }
1104
- };
1105
- const parseQuery = (qs) => {
1106
- if (!qs) {
1107
- return {};
1108
- }
1109
- let queryString = qs.length > 0 && qs.charAt(0) === "?" ? qs.substring(1) : qs;
1110
- let query = {};
1111
- let pairs = (queryString[0] === "?" ? queryString.substr(1) : queryString).split("&");
1112
- for (let i = 0; i < pairs.length; i++) {
1113
- let pair = pairs[i].split("=");
1114
- query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
1115
- }
1116
- return query;
1117
- };
1118
- function utmToKey(key) {
1119
- const name = key.substring("utm_".length);
1120
- return name === "campaign" ? "name" : name;
1121
- }
1122
- function parseUtms(query) {
1123
- return Object.entries(query)
1124
- .filter(([key]) => key.indexOf("utm_") === 0)
1125
- .reduce((acc, [key, value]) => (Object.assign(Object.assign({}, acc), { [utmToKey(key)]: value })), {});
1126
- }
1127
- function safeCall(f, defaultVal) {
1128
- try {
1129
- return f();
1130
- }
1131
- catch (e) {
1132
- return defaultVal;
1133
- }
1134
- }
1135
- function restoreTraits(storage) {
1136
- let val = storage.getItem("__user_traits");
1137
- if (typeof val === "string") {
1138
- val = safeCall(() => JSON.parse(val), {});
1139
- }
1140
- if (typeof val !== "object" || val === null || Array.isArray(val)) {
1141
- val = {};
1142
- }
1143
- let groupVal = storage.getItem("__group_traits");
1144
- if (typeof groupVal === "string") {
1145
- groupVal = safeCall(() => JSON.parse(groupVal), {});
1146
- }
1147
- if (typeof groupVal !== "object" || groupVal === null || Array.isArray(groupVal)) {
1148
- groupVal = {};
1149
- }
1150
- return Object.assign(Object.assign({}, (groupVal || {})), (val || {}));
1151
- }
1152
- function getCookie(name) {
1153
- const value = `; ${document.cookie}`;
1154
- const parts = value.split(`; ${name}=`);
1155
- return parts.length === 2 ? parts.pop().split(";").shift() : undefined;
1156
- }
1157
- function getClientIds(runtime, customCookieCapture) {
1158
- const cookieCapture = Object.assign({ fbc: "_fbc", fbp: "_fbp" }, customCookieCapture);
1159
- const clientIds = Object.entries(cookieCapture).reduce((acc, [key, cookieName]) => {
1160
- acc[key] = runtime.getCookie(cookieName);
1161
- return acc;
1162
- }, {});
1163
- return Object.assign(Object.assign({}, clientIds), getGa4Ids(runtime));
1164
- }
1165
- function getGa4Ids(runtime) {
1166
- var _a;
1167
- const allCookies = runtime.getCookies();
1168
- const clientId = (_a = allCookies["_ga"]) === null || _a === void 0 ? void 0 : _a.split(".").slice(-2).join(".");
1169
- const gaSessionCookies = Object.entries(allCookies).filter(([key]) => key.startsWith("_ga_"));
1170
- const sessionIds = gaSessionCookies.length > 0
1171
- ? Object.fromEntries(gaSessionCookies
1172
- .map(([key, value]) => {
1173
- if (typeof value !== "string") {
1174
- return null;
1175
- }
1176
- const parts = value.split(".");
1177
- if (parts.length < 3) {
1178
- return null;
1179
- }
1180
- return [key.substring("_ga_".length), parts[2]];
1181
- })
1182
- .filter(v => v !== null))
1183
- : undefined;
1184
- if (clientId || sessionIds) {
1185
- return { ga4: { clientId, sessionIds } };
1186
- }
1187
- else {
1188
- return undefined;
1189
- }
1190
- }
1191
- function removeCookie(name, { domain, secure }) {
1192
- document.cookie =
1193
- name +
1194
- "=;domain=" +
1195
- domain +
1196
- ";path=/" +
1197
- ";expires=Thu, 01 Jan 1970 00:00:01 GMT;SameSite=" +
1198
- (secure ? "None" : "Lax") +
1199
- (secure ? ";secure" : "");
1200
- }
1201
- function setCookie(name, val, { domain, secure }) {
1202
- document.cookie =
1203
- name +
1204
- "=" +
1205
- val +
1206
- ";domain=" +
1207
- domain +
1208
- ";path=/" +
1209
- ";expires=" +
1210
- new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 5).toUTCString() +
1211
- ";SameSite=" +
1212
- (secure ? "None" : "Lax") +
1213
- (secure ? ";secure" : "");
1214
- }
1215
- const defaultCookie2Key = {
1216
- __anon_id: "__eventn_id",
1217
- __user_id: "__eventn_uid",
1218
- __user_traits: "__eventn_id_usr",
1219
- __group_id: "__group_id",
1220
- __group_traits: "__group_traits",
1221
- };
1222
- const cookieStorage = (cookieDomain, key2cookie) => {
1223
- return {
1224
- setItem(key, val) {
1225
- const cookieName = key2cookie(key) || key;
1226
- if (typeof val === "undefined") {
1227
- removeCookie(cookieName, {
1228
- domain: cookieDomain,
1229
- secure: window.location.protocol === "https:",
1230
- });
1231
- return;
1232
- }
1233
- const strVal = typeof val === "object" && val !== null ? encodeURIComponent(JSON.stringify(val)) : val;
1234
- setCookie(cookieName, strVal, {
1235
- domain: cookieDomain,
1236
- secure: window.location.protocol === "https:",
1237
- });
1238
- },
1239
- getItem(key) {
1240
- const cookieName = key2cookie(key) || key;
1241
- const result = getCookie(cookieName);
1242
- if (key === "__anon_id") {
1243
- //anonymous id must always be a string, so we don't parse it to preserve its exact value
1244
- return result;
1245
- }
1246
- if (typeof result === "undefined" && key === "__user_id") {
1247
- //backward compatibility with old jitsu cookie. get user id if from traits
1248
- const traits = parse(getCookie(key2cookie("__user_traits") || "__eventn_id_usr")) || {};
1249
- return traits.internal_id || traits.user_id || traits.id || traits.userId;
1250
- }
1251
- return parse(result);
1252
- },
1253
- removeItem(key) {
1254
- removeCookie(key2cookie(key) || key, {
1255
- domain: cookieDomain,
1256
- secure: window.location.protocol === "https:",
1257
- });
1258
- },
1259
- reset() {
1260
- for (const key of Object.keys(defaultCookie2Key)) {
1261
- removeCookie(key2cookie(key) || key, {
1262
- domain: cookieDomain,
1263
- secure: window.location.protocol === "https:",
1264
- });
1265
- }
1266
- },
1267
- };
1268
- };
1269
- function windowRuntime(opts) {
1270
- const key2Cookie = (key) => {
1271
- var _a, _b, _c, _d, _e;
1272
- switch (key) {
1273
- case "__anon_id":
1274
- return ((_a = opts.cookieNames) === null || _a === void 0 ? void 0 : _a.anonymousId) || defaultCookie2Key.__anon_id;
1275
- case "__user_id":
1276
- return ((_b = opts.cookieNames) === null || _b === void 0 ? void 0 : _b.userId) || defaultCookie2Key.__user_id;
1277
- case "__user_traits":
1278
- return ((_c = opts.cookieNames) === null || _c === void 0 ? void 0 : _c.userTraits) || defaultCookie2Key.__user_traits;
1279
- case "__group_id":
1280
- return ((_d = opts.cookieNames) === null || _d === void 0 ? void 0 : _d.groupId) || defaultCookie2Key.__group_id;
1281
- case "__group_traits":
1282
- return ((_e = opts.cookieNames) === null || _e === void 0 ? void 0 : _e.groupTraits) || defaultCookie2Key.__group_traits;
1283
- default:
1284
- return key;
1285
- }
1286
- };
1287
- return {
1288
- getCookie(name) {
1289
- const value = `; ${document.cookie}`;
1290
- const parts = value.split(`; ${name}=`);
1291
- return parts.length === 2 ? parts.pop().split(";").shift() : undefined;
1292
- },
1293
- getCookies() {
1294
- const value = `; ${document.cookie}`;
1295
- const cookies = {};
1296
- const matches = value.matchAll(/(\w+)=([^;]+)/g);
1297
- for (const match of matches) {
1298
- cookies[match[1]] = match[2];
1299
- }
1300
- return cookies;
1301
- },
1302
- documentEncoding() {
1303
- return window.document.characterSet;
1304
- },
1305
- timezoneOffset() {
1306
- return new Date().getTimezoneOffset();
1307
- },
1308
- store() {
1309
- return cookieStorage(opts.cookieDomain || getTopLevelDomain(window.location.hostname), key2Cookie);
1310
- },
1311
- language() {
1312
- return window.navigator.language;
1313
- },
1314
- pageTitle() {
1315
- return window.document.title;
1316
- },
1317
- pageUrl() {
1318
- return window.location.href;
1319
- },
1320
- referrer() {
1321
- return window.document.referrer;
1322
- },
1323
- screen() {
1324
- return {
1325
- width: window.screen.width,
1326
- height: window.screen.height,
1327
- innerWidth: window.innerWidth,
1328
- innerHeight: window.innerHeight,
1329
- density: Math.floor(window.devicePixelRatio),
1330
- };
1331
- },
1332
- userAgent() {
1333
- return window.navigator.userAgent;
1334
- },
1335
- };
1336
- }
1337
- const emptyRuntime = (config) => ({
1338
- documentEncoding() {
1339
- return undefined;
1340
- },
1341
- timezoneOffset() {
1342
- return undefined;
1343
- },
1344
- getCookie(name) {
1345
- return undefined;
1346
- },
1347
- getCookies() {
1348
- return {};
1349
- },
1350
- store() {
1351
- const storage = {};
1352
- return {
1353
- reset() {
1354
- Object.keys(storage).forEach(key => delete storage[key]);
1355
- },
1356
- setItem(key, val) {
1357
- if (config.debug) {
1358
- console.log(`[JITSU EMPTY RUNTIME] Set storage item ${key}=${JSON.stringify(val)}`);
1359
- }
1360
- if (typeof val === "undefined") {
1361
- delete storage[key];
1362
- }
1363
- else {
1364
- storage[key] = val;
1365
- }
1366
- },
1367
- getItem(key) {
1368
- const val = storage[key];
1369
- if (config.debug) {
1370
- console.log(`[JITSU EMPTY RUNTIME] Get storage item ${key}=${JSON.stringify(val)}`);
1371
- }
1372
- return val;
1373
- },
1374
- removeItem(key) {
1375
- if (config.debug) {
1376
- console.log(`[JITSU EMPTY RUNTIME] Get storage item ${key}=${storage[key]}`);
1377
- }
1378
- delete storage[key];
1379
- },
1380
- };
1381
- },
1382
- language() {
1383
- return undefined;
1384
- },
1385
- pageTitle() {
1386
- return undefined;
1387
- },
1388
- pageUrl() {
1389
- return undefined;
1390
- },
1391
- referrer() {
1392
- return undefined;
1393
- },
1394
- screen() {
1395
- return undefined;
1396
- },
1397
- userAgent() {
1398
- return undefined;
1399
- },
1400
- });
1401
- function deepMerge(target, source) {
1402
- if (typeof source !== "object" || source === null) {
1403
- return source;
1404
- }
1405
- if (typeof target !== "object" || target === null) {
1406
- return source;
1407
- }
1408
- return Object.entries(source).reduce((acc, [key, value]) => {
1409
- acc[key] = deepMerge(target[key], value);
1410
- return acc;
1411
- }, target);
1412
- }
1413
- function isInBrowser() {
1414
- return typeof document !== "undefined" && typeof window !== "undefined";
1415
- }
1416
- /**
1417
- * Fixes a weird bug in analytics URL where path
1418
- * of https://test.com becomes //test.com
1419
- */
1420
- function fixPath(path) {
1421
- if (path.indexOf("//") === 0 && path.lastIndexOf("/") === 1) {
1422
- return "/";
1423
- }
1424
- return path;
1425
- }
1426
- const hashRegex = /#.*$/;
1427
- /**
1428
- * for compatibility with path produced by analytics.js
1429
- * @param url
1430
- */
1431
- function urlPath(url) {
1432
- const regex = /(http[s]?:\/\/)?([^\/\s]+\/)(.*)/g;
1433
- const matches = regex.exec(url);
1434
- const pathMatch = matches && matches[3] ? matches[3].split("?")[0].replace(hashRegex, "") : "";
1435
- return "/" + pathMatch;
1436
- }
1437
- function adjustPayload(payload, config, storage, s2s) {
1438
- var _a, _b, _c, _d, _e, _f;
1439
- const runtime = config.runtime || (isInBrowser() ? windowRuntime(config) : emptyRuntime(config));
1440
- const url = runtime.pageUrl();
1441
- const parsedUrl = safeCall(() => new URL(url), undefined);
1442
- const query = parsedUrl ? parseQuery(parsedUrl.search) : {};
1443
- const properties = payload.properties || {};
1444
- if (payload.type === "page" && (properties.url || url)) {
1445
- const targetUrl = properties.url || url;
1446
- properties.url = targetUrl.replace(hashRegex, "");
1447
- properties.path = fixPath(urlPath(targetUrl));
1448
- }
1449
- const customContext = deepMerge(config.defaultPayloadContext, ((_a = payload.properties) === null || _a === void 0 ? void 0 : _a.context) || ((_b = payload.options) === null || _b === void 0 ? void 0 : _b.context) || {});
1450
- (_c = payload.properties) === null || _c === void 0 ? true : delete _c.context;
1451
- const referrer = runtime.referrer();
1452
- const context = {
1453
- library: {
1454
- name: jitsuLibraryName,
1455
- version: jitsuVersion,
1456
- env: isInBrowser() ? "browser" : "node",
1457
- },
1458
- consent: ((_d = config.privacy) === null || _d === void 0 ? void 0 : _d.consentCategories)
1459
- ? {
1460
- categoryPreferences: config.privacy.consentCategories,
1461
- }
1462
- : undefined,
1463
- userAgent: runtime.userAgent(),
1464
- locale: runtime.language(),
1465
- screen: runtime.screen(),
1466
- ip: runtime.ip ? runtime.ip() : undefined,
1467
- traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
1468
- page: {
1469
- path: properties.path || (parsedUrl && parsedUrl.pathname),
1470
- referrer: referrer,
1471
- referring_domain: safeCall(() => referrer && new URL(referrer).hostname),
1472
- host: parsedUrl && parsedUrl.host,
1473
- search: properties.search || (parsedUrl && parsedUrl.search),
1474
- title: properties.title || runtime.pageTitle(),
1475
- url: properties.url || url,
1476
- encoding: properties.encoding || runtime.documentEncoding(),
1477
- },
1478
- clientIds: !((_e = config.privacy) === null || _e === void 0 ? void 0 : _e.disableUserIds) ? getClientIds(runtime, config.cookieCapture) : undefined,
1479
- campaign: parseUtms(query),
1480
- };
1481
- const withContext = Object.assign(Object.assign({}, payload), { timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: maskWriteKey(config.writeKey), groupId: storage.getItem("__group_id"), context: deepMerge(context, customContext) });
1482
- delete withContext.meta;
1483
- delete withContext.options;
1484
- if ((_f = config.privacy) === null || _f === void 0 ? void 0 : _f.disableUserIds) {
1485
- delete withContext.userId;
1486
- delete withContext.anonymousId;
1487
- delete withContext.context.traits;
1488
- delete withContext.groupId;
1489
- }
1490
- return withContext;
1491
- }
1492
- function isDiff(obj) {
1493
- const keys = Object.keys(obj);
1494
- return keys.length === 1 && keys[0] === "__diff";
1495
- }
1496
- function processDestinations(destinations, method, originalEvent, debug, analyticsInstance) {
1497
- return __awaiter$1(this, void 0, void 0, function* () {
1498
- const promises = [];
1499
- for (const destination of destinations) {
1500
- let newEvents = [originalEvent];
1501
- if (destination.newEvents) {
1502
- try {
1503
- newEvents = destination.newEvents.map(e => e === "same" ? originalEvent : isDiff(e) ? diff.patch(originalEvent, e.__diff) : e);
1504
- }
1505
- catch (e) {
1506
- console.error(`[JITSU] Error applying '${destination.id}' changes to event: ${e === null || e === void 0 ? void 0 : e.message}`, e);
1507
- }
1508
- }
1509
- const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
1510
- if (destination.deviceOptions.type === "internal-plugin") {
1511
- const plugin = internalDestinationPlugins[destination.deviceOptions.name];
1512
- if (plugin) {
1513
- for (const event of newEvents) {
1514
- try {
1515
- promises.push(plugin.handle(Object.assign(Object.assign({}, credentials), { debug }), event));
1516
- }
1517
- catch (e) {
1518
- console.warn(`[JITSU] Error processing event with internal plugin '${destination.deviceOptions.name}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
1519
- }
1520
- }
1521
- }
1522
- else {
1523
- console.warn(`[JITSU] Unknown internal plugin '${destination.deviceOptions.name}' for destination '${destination.id}'`);
1524
- }
1525
- }
1526
- else if (destination.deviceOptions.type === "analytics-plugin") {
1527
- yield loadScript(destination.deviceOptions.packageCdn);
1528
- const plugin = window[destination.deviceOptions.moduleVarName];
1529
- if (!plugin) {
1530
- console.warn(`[JITSU] Broken plugin '${destination.deviceOptions.packageCdn}' for destination '${destination.id}' - it doesn't export '${destination.deviceOptions.moduleVarName}' variable`);
1531
- }
1532
- else {
1533
- let pluginInstance;
1534
- try {
1535
- pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
1536
- }
1537
- catch (e) {
1538
- console.warn(`[JITSU] Error creating plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
1539
- }
1540
- try {
1541
- if (debug) {
1542
- console.log(`[JITSU] Plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}' initialized with config:`, pluginInstance.config);
1543
- }
1544
- pluginInstance.initialize({ config: pluginInstance.config, instance: analyticsInstance });
1545
- }
1546
- catch (e) {
1547
- console.warn(`[JITSU] Error initializing plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}. Config: ${JSON.stringify(pluginInstance.config)}`, e);
1548
- continue;
1549
- }
1550
- if (pluginInstance[method]) {
1551
- for (const event of newEvents) {
1552
- try {
1553
- pluginInstance[method]({
1554
- payload: event,
1555
- config: pluginInstance.config,
1556
- instance: analyticsInstance,
1557
- });
1558
- }
1559
- catch (e) {
1560
- console.warn(`[JITSU] Error processing ${method}() with plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
1561
- }
1562
- }
1563
- }
1564
- }
1565
- }
1566
- }
1567
- });
1568
- }
1569
- function looksLikeCuid(id) {
1570
- return id.length === 25 && id.charAt(0) === "c";
1571
- }
1572
- function validateWriteKey(writeKey) {
1573
- if (writeKey) {
1574
- const [, secret] = writeKey.split(":", 2);
1575
- if (!secret && !looksLikeCuid(writeKey)) {
1576
- throw new Error(`Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`);
1577
- }
1578
- }
1579
- return writeKey;
1580
- }
1581
- function maskWriteKey(writeKey) {
1582
- if (writeKey) {
1583
- const [id, secret] = writeKey.split(":", 2);
1584
- if (secret) {
1585
- return `${id}:***`;
1586
- }
1587
- else {
1588
- return "***";
1589
- }
1590
- }
1591
- return writeKey;
1592
- }
1593
- function getErrorHandler(opts) {
1594
- const configuredHandler = opts.errorPolicy || "log";
1595
- if (typeof configuredHandler === "function") {
1596
- return configuredHandler;
1597
- }
1598
- else if (configuredHandler === "rethrow") {
1599
- return (msg, ...args) => {
1600
- //ignore args, not clear what to do with them
1601
- throw new Error(msg);
1602
- };
1603
- }
1604
- else {
1605
- return (msg, ...args) => {
1606
- console.error(msg, ...args);
1607
- };
1608
- }
1609
- }
1610
- function send(method, payload, jitsuConfig, instance, store) {
1611
- return __awaiter$1(this, void 0, void 0, function* () {
1612
- var _a, _b;
1613
- if (jitsuConfig.echoEvents) {
1614
- console.log(`[JITSU DEBUG] sending '${method}' event:`, payload);
1615
- return;
1616
- }
1617
- const s2s = !!jitsuConfig.s2s;
1618
- const url = s2s ? `${jitsuConfig.host}/api/s/s2s/${method}` : `${jitsuConfig.host}/api/s/${method}`;
1619
- const fetch = jitsuConfig.fetch || globalThis.fetch;
1620
- if (!fetch) {
1621
- //don't run it through error handler since error is critical and should be addressed
1622
- throw new Error("Please specify fetch function in jitsu plugin initialization, fetch isn't available in global scope");
1623
- }
1624
- const debugHeader = jitsuConfig.debug ? { "X-Enable-Debug": "true" } : {};
1625
- // if (jitsuConfig.debug) {
1626
- // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
1627
- // }
1628
- const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
1629
- const abortController = jitsuConfig.fetchTimeoutMs ? new AbortController() : undefined;
1630
- const abortTimeout = jitsuConfig.fetchTimeoutMs
1631
- ? setTimeout(() => {
1632
- abortController.abort();
1633
- }, jitsuConfig.fetchTimeoutMs)
1634
- : undefined;
1635
- const authHeader = jitsuConfig.writeKey ? { "X-Write-Key": jitsuConfig.writeKey } : {};
1636
- const ipHeader = typeof ((_a = jitsuConfig.privacy) === null || _a === void 0 ? void 0 : _a.ipPolicy) === "undefined" || ((_b = jitsuConfig.privacy) === null || _b === void 0 ? void 0 : _b.ipPolicy) === "keep"
1637
- ? {}
1638
- : { "X-IP-Policy": jitsuConfig.privacy.ipPolicy };
1639
- let fetchResult;
1640
- try {
1641
- fetchResult = yield fetch(url, {
1642
- method: "POST",
1643
- headers: Object.assign(Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader), ipHeader),
1644
- body: JSON.stringify(adjustedPayload),
1645
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
1646
- });
1647
- if (abortTimeout) {
1648
- clearTimeout(abortTimeout);
1649
- }
1650
- }
1651
- catch (e) {
1652
- getErrorHandler(jitsuConfig)(`Call to ${url} failed with error ${e.message}`);
1653
- return Promise.resolve();
1654
- }
1655
- let responseText;
1656
- try {
1657
- responseText = yield fetchResult.text();
1658
- }
1659
- catch (e) {
1660
- console.warn(`Can't read response text from ${url} (status - ${fetchResult.status} ${fetchResult.statusText}): ${e === null || e === void 0 ? void 0 : e.message}`);
1661
- }
1662
- if (jitsuConfig.debug) {
1663
- console.log(`[JITSU DEBUG] ${url} replied ${fetchResult.status}: ${responseText}. Original payload:\n${JSON.stringify(adjustedPayload, null, 2)}`);
1664
- }
1665
- if (!fetchResult.ok) {
1666
- getErrorHandler(jitsuConfig)(`Call to ${url} failed with error: ${fetchResult.status} - ${fetchResult.statusText}: ${responseText}`);
1667
- return Promise.resolve();
1668
- }
1669
- let responseJson;
1670
- try {
1671
- responseJson = JSON.parse(responseText);
1672
- }
1673
- catch (e) {
1674
- getErrorHandler(jitsuConfig)(`Can't parse JSON: ${responseText}: ${e === null || e === void 0 ? void 0 : e.message}`);
1675
- return Promise.resolve();
1676
- }
1677
- if (responseJson.destinations && responseJson.destinations.length > 0) {
1678
- if (jitsuConfig.s2s) {
1679
- console.warn(`[JITSU] ${payload.type} responded with list of ${responseJson.destinations.length} destinations. However, this code is running in server-to-server mode, so destinations will be ignored`, jitsuConfig.debug ? JSON.stringify(responseJson.destinations, null, 2) : undefined);
1680
- }
1681
- else {
1682
- //double protection, ingest should not return destinations in s2s mode
1683
- if (isInBrowser()) {
1684
- if (jitsuConfig.debug) {
1685
- console.log(`[JITSU] Processing device destinations: `, JSON.stringify(responseJson.destinations, null, 2));
1686
- }
1687
- return processDestinations(responseJson.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
1688
- }
1689
- }
1690
- }
1691
- return adjustedPayload;
1692
- });
1693
- }
1694
- const controllingTraits = ["$doNotSend"];
1695
- /**
1696
- * Remove all members of traits that controls identify/group behavior (see analytics.d.ts), and should not be recorded. Returns
1697
- * copy of the object with these members removed.
1698
- *
1699
- * Do not modify traits object, but creates one
1700
- * @param traits
1701
- */
1702
- function stripControllingTraits(traits) {
1703
- const res = Object.assign({}, traits);
1704
- // see Traits definition in analytics.d.ts. We cannot define const here, so here's a little code duplication
1705
- for (const key of controllingTraits) {
1706
- delete res[key];
1707
- }
1708
- return res;
1709
- }
1710
- const jitsuAnalyticsPlugin = (jitsuOptions = {}, storage) => {
1711
- // just to make sure that all undefined values are replaced with defaultConfig values
1712
- mergeConfig(jitsuOptions, jitsuOptions);
1713
- return {
1714
- name: "jitsu",
1715
- config: jitsuOptions,
1716
- initialize: (args) => __awaiter$1(void 0, void 0, void 0, function* () {
1717
- const { config } = args;
1718
- if (config.debug) {
1719
- console.debug("[JITSU DEBUG] Initializing Jitsu plugin with config: ", JSON.stringify(config, null, 2));
1720
- }
1721
- if (!config.host && !config.echoEvents) {
1722
- throw new Error("Please specify host variable in jitsu plugin initialization, or set echoEvents to true");
1723
- }
1724
- validateWriteKey(config.writeKey);
1725
- if (config.idEndpoint) {
1726
- if (!isInBrowser()) {
1727
- console.error(`[JITSU] 'idEndpoint' option can be used only in browser environment`);
1728
- return;
1729
- }
1730
- try {
1731
- const fetch = config.fetch || globalThis.fetch;
1732
- const controller = new AbortController();
1733
- setTimeout(() => controller.abort(), 1000);
1734
- const domain = config.cookieDomain || getTopLevelDomain(window.location.hostname);
1735
- const res = yield fetch(config.idEndpoint + "?domain=" + encodeURIComponent(domain), {
1736
- credentials: "include",
1737
- signal: controller.signal,
1738
- });
1739
- if (!res.ok) {
1740
- console.error(`[JITSU] Can't fetch idEndpoint: ${res.status} - ${res.statusText}`);
1741
- }
1742
- else if (config.debug) {
1743
- console.log(`[JITSU DEBUG] Fetch idEndpoint: ${res.status}`);
1744
- }
1745
- }
1746
- catch (e) {
1747
- console.error(`[JITSU] Can't fetch idEndpoint: ${e.message}`);
1748
- }
1749
- }
1750
- }),
1751
- page: args => {
1752
- var _a;
1753
- const { payload, config, instance } = args;
1754
- if ((_a = config.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) {
1755
- return;
1756
- }
1757
- return send("page", payload, config, instance, storage);
1758
- },
1759
- track: args => {
1760
- var _a;
1761
- const { payload, config, instance } = args;
1762
- if ((_a = config.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) {
1763
- return;
1764
- }
1765
- return send("track", payload, config, instance, storage);
1766
- },
1767
- identify: args => {
1768
- var _a, _b, _c;
1769
- const { payload, config, instance } = args;
1770
- if (((_a = config.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) || ((_b = config.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds)) {
1771
- return;
1772
- }
1773
- // Store traits in cache to be able to use them in page and track events that run asynchronously with current identify.
1774
- storage.setItem("__user_id", payload.userId);
1775
- const doNotSend = (_c = payload.traits) === null || _c === void 0 ? void 0 : _c.$doNotSend;
1776
- if (payload.traits && typeof payload.traits === "object") {
1777
- payload.traits = stripControllingTraits(payload.traits);
1778
- storage.setItem("__user_traits", payload.traits);
1779
- }
1780
- if (doNotSend) {
1781
- return Promise.resolve();
1782
- }
1783
- return send("identify", payload, config, instance, storage);
1784
- },
1785
- reset: args => {
1786
- const { config, instance } = args;
1787
- storage.reset();
1788
- if (config.debug) {
1789
- console.log("[JITSU DEBUG] Resetting Jitsu plugin storage");
1790
- }
1791
- },
1792
- methods: {
1793
- //analytics doesn't support group as a base method, so we need to add it manually
1794
- configure(newOptions) {
1795
- var _a, _b, _c, _d;
1796
- const idsWasDisabled = ((_a = jitsuOptions.privacy) === null || _a === void 0 ? void 0 : _a.disableUserIds) || ((_b = jitsuOptions.privacy) === null || _b === void 0 ? void 0 : _b.dontSend);
1797
- mergeConfig(jitsuOptions, newOptions);
1798
- const idsDisabledNow = ((_c = jitsuOptions.privacy) === null || _c === void 0 ? void 0 : _c.disableUserIds) || ((_d = jitsuOptions.privacy) === null || _d === void 0 ? void 0 : _d.dontSend);
1799
- if (!idsDisabledNow && idsWasDisabled) {
1800
- if (jitsuOptions.debug) {
1801
- console.log("[JITSU] Enabling Anonymous ID. Generating new Id.");
1802
- }
1803
- const instance = this.instance;
1804
- const newAnonymousId = uuid();
1805
- const userState = instance.user();
1806
- if (userState) {
1807
- userState.anonymousId = newAnonymousId;
1808
- }
1809
- storage.setItem("__anon_id", newAnonymousId);
1810
- instance.setAnonymousId(newAnonymousId);
1811
- }
1812
- },
1813
- group(groupId, traits, options, callback) {
1814
- var _a, _b;
1815
- if (((_a = jitsuOptions.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) || ((_b = jitsuOptions.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds)) {
1816
- return;
1817
- }
1818
- if (typeof groupId === "number") {
1819
- //fix potential issues with group id being used incorrectly
1820
- groupId = groupId + "";
1821
- }
1822
- const instance = this.instance;
1823
- const user = instance.user();
1824
- const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
1825
- const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId) || storage.getItem("__anon_id");
1826
- storage.setItem("__group_id", groupId);
1827
- const doNotSend = traits === null || traits === void 0 ? void 0 : traits.$doNotSend;
1828
- if (traits && typeof traits === "object") {
1829
- traits = stripControllingTraits(traits);
1830
- storage.setItem("__group_traits", traits);
1831
- }
1832
- if (doNotSend) {
1833
- return Promise.resolve();
1834
- }
1835
- return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), jitsuOptions, instance, storage);
1836
- },
1837
- },
1838
- };
1839
- };
1840
- let seedCounter = 0;
1841
- function getSeed() {
1842
- var _a;
1843
- seedCounter = (seedCounter + 1) % Number.MAX_SAFE_INTEGER;
1844
- const defaultSeed = Date.now() % 2147483647;
1845
- const seed = isInBrowser() ? ((_a = window === null || window === void 0 ? void 0 : window.performance) === null || _a === void 0 ? void 0 : _a.now()) || defaultSeed : defaultSeed;
1846
- return seed + seedCounter;
1847
- }
1848
- function randomId(hashString = "") {
1849
- const d = Date.now();
1850
- return (((Math.random() * d * hash(hashString !== null && hashString !== void 0 ? hashString : "", getSeed())) % Number.MAX_SAFE_INTEGER).toString(36) +
1851
- ((Math.random() * d * hash(hashString !== null && hashString !== void 0 ? hashString : "", getSeed())) % Number.MAX_SAFE_INTEGER).toString(36));
1852
- }
1853
- function uuid() {
1854
- var u = "", m = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx", i = 0, rb = (Math.random() * 0xffffffff) | 0;
1855
- while (i++ < 36) {
1856
- var c = m[i - 1], r = rb & 0xf, v = c == "x" ? r : (r & 0x3) | 0x8;
1857
- u += c == "-" || c == "4" ? c : v.toString(16);
1858
- rb = i % 8 == 0 ? (Math.random() * 0xffffffff) | 0 : rb >> 4;
1859
- }
1860
- return u;
1861
- }
1862
- function hash(str, seed = 0) {
1863
- let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
1864
- for (let i = 0, ch; i < str.length; i++) {
1865
- ch = str.charCodeAt(i);
1866
- h1 = Math.imul(h1 ^ ch, 2654435761);
1867
- h2 = Math.imul(h2 ^ ch, 1597334677);
1868
- }
1869
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
1870
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
1871
- return 4294967296 * (2097151 & h2) + (h1 >>> 0);
1872
- }
1873
-
1874
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1875
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1876
- return new (P || (P = Promise))(function (resolve, reject) {
1877
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1878
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1879
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1880
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1881
- });
1882
- };
1883
- function parse(input) {
1884
- let value = input;
1885
- if ((input === null || input === void 0 ? void 0 : input.indexOf("%7B%22")) === 0) {
1886
- value = decodeURIComponent(input);
1887
- }
1888
- try {
1889
- value = JSON.parse(value);
1890
- if (value === "true")
1891
- return true;
1892
- if (value === "false")
1893
- return false;
1894
- if (typeof value === "object")
1895
- return value;
1896
- if (parseFloat(value) === value) {
1897
- value = parseFloat(value);
1898
- }
1899
- }
1900
- catch (e) { }
1901
- if (value === null || value === "") {
1902
- return;
1903
- }
1904
- return value;
1905
- }
1906
- function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
1907
- var _a, _b;
1908
- const storageCache = {};
1909
- // AnalyticsInstance's storage is async somewhere inside. So if we make 'page' call right after 'identify' call
1910
- // 'page' call will load traits from storage before 'identify' call had a change to save them.
1911
- // to avoid that we use in-memory cache for storage
1912
- const cachingStorageWrapper = (persistentStorage) => ({
1913
- setItem(key, val) {
1914
- var _a, _b;
1915
- if (((_a = opts.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) || ((_b = opts.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds)) {
1916
- return;
1917
- }
1918
- if (opts.debug) {
1919
- console.log(`[JITSU DEBUG] Caching storage setItem: ${key}=${val}`);
1920
- }
1921
- storageCache[key] = val;
1922
- persistentStorage.setItem(key, val);
1923
- },
1924
- getItem(key) {
1925
- var _a, _b;
1926
- if (((_a = opts.privacy) === null || _a === void 0 ? void 0 : _a.dontSend) || ((_b = opts.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds)) {
1927
- return;
1928
- }
1929
- const value = storageCache[key] || persistentStorage.getItem(key);
1930
- if (opts.debug) {
1931
- console.log(`[JITSU DEBUG] Caching storage getItem: ${key}=${value}. Evicted from cache: ${!storageCache[key]}`);
1932
- }
1933
- return value;
1934
- },
1935
- reset() {
1936
- for (const key of [...Object.keys(storageCache)]) {
1937
- delete storageCache[key];
1938
- }
1939
- persistentStorage.reset();
1940
- },
1941
- removeItem(key) {
1942
- if (opts.debug) {
1943
- console.log(`[JITSU DEBUG] Caching storage removeItem: ${key}`);
1944
- }
1945
- delete storageCache[key];
1946
- persistentStorage.removeItem(key);
1947
- },
1948
- });
1949
- const storage = cachingStorageWrapper(rt.store());
1950
- const analytics = analyticsLib({
1951
- debug: !!opts.debug,
1952
- storage,
1953
- plugins: [jitsuAnalyticsPlugin(opts, storage), ...plugins],
1954
- });
1955
- const a = Object.assign(Object.assign({}, analytics), { page: (...args) => {
1956
- if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object") {
1957
- return analytics.page(Object.assign({ name: args[0] }, args[1]));
1958
- }
1959
- else {
1960
- return analytics.page(...args);
1961
- }
1962
- }, identify: (...args) => {
1963
- if (args[0] && typeof args[0] !== "object" && typeof args[0] !== "string") {
1964
- //fix the quirk of analytics.js: if you pass number as first argument, it will be converted to string
1965
- args[0] = args[0] + "";
1966
- }
1967
- //analytics.js sets userId and traits asynchronously, so if
1968
- //we want them to be available immediately after identify call in subsequent page() calls,
1969
- //we need to put them into storage manually
1970
- const storage = analytics.storage;
1971
- const storageWrapper = cachingStorageWrapper(storage);
1972
- if (typeof args[0] === "string") {
1973
- //first argument is user id
1974
- storageWrapper.setItem("__user_id", args[0]);
1975
- }
1976
- else if (typeof args[0] === "object") {
1977
- //first argument is traits
1978
- storageWrapper.setItem("__user_traits", args[0]);
1979
- }
1980
- if (args.length === 2 && typeof args[1] === "object") {
1981
- //first argument is user id, second is traits
1982
- storageWrapper.setItem("__user_traits", args[1]);
1983
- }
1984
- return analytics.identify(...args);
1985
- }, setAnonymousId: (id) => {
1986
- if (opts.debug) {
1987
- console.log("[JITSU DEBUG] Setting anonymous id to " + id);
1988
- }
1989
- //Workaround for analytics.js bug. Underlying setAnonymousId doesn't set the id immediately,
1990
- //so we got to it manually here. See https://github.com/jitsucom/jitsu/issues/1060
1991
- storage.setItem("__anon_id", id);
1992
- const userState = analytics.user();
1993
- if (userState) {
1994
- userState.anonymousId = id;
1995
- }
1996
- analytics.setAnonymousId(id);
1997
- }, reset() {
1998
- return __awaiter(this, void 0, void 0, function* () {
1999
- if (opts.debug) {
2000
- console.log("[JITSU DEBUG] Called reset(). Storage state", JSON.stringify(analytics.user()));
2001
- }
2002
- storage.reset();
2003
- yield analytics.reset();
2004
- this.setAnonymousId(uuid());
2005
- if (opts.debug) {
2006
- console.log("[JITSU DEBUG] User state after reset", JSON.stringify(analytics.user()));
2007
- }
2008
- });
2009
- },
2010
- configure(options) {
2011
- return __awaiter(this, void 0, void 0, function* () {
2012
- var _a, _b;
2013
- if (opts.debug) {
2014
- console.log("[JITSU DEBUG] Update Jitsu config with", JSON.stringify(options));
2015
- }
2016
- if (((_a = options.privacy) === null || _a === void 0 ? void 0 : _a.disableUserIds) || ((_b = options.privacy) === null || _b === void 0 ? void 0 : _b.dontSend)) {
2017
- storage.reset();
2018
- }
2019
- for (const plugin of Object.values(analytics.plugins)) {
2020
- if (typeof plugin["configure"] === "function") {
2021
- plugin["configure"](options);
2022
- }
2023
- }
2024
- });
2025
- },
2026
- group(groupId, traits, options, callback) {
2027
- return __awaiter(this, void 0, void 0, function* () {
2028
- const results = [];
2029
- for (const plugin of Object.values(analytics.plugins)) {
2030
- if (plugin["group"]) {
2031
- results.push(yield plugin["group"](groupId, traits, options, callback));
2032
- }
2033
- }
2034
- //It's incorrect at many levels. First, it's not a dispatched event. Second, we take a first result
2035
- //However, since returned values are used for debugging purposes only, it's ok
2036
- return results[0];
2037
- });
2038
- } });
2039
- if (((_a = opts.privacy) === null || _a === void 0 ? void 0 : _a.disableUserIds) || ((_b = opts.privacy) === null || _b === void 0 ? void 0 : _b.dontSend)) {
2040
- storage.reset();
2041
- }
2042
- return a;
2043
- }
2044
- /**
2045
- * Fix common mistakes in jitsu configuration
2046
- * @param opts
2047
- */
2048
- function fixOptions(opts) {
2049
- var _a, _b;
2050
- return Object.assign(Object.assign({}, opts), { host: ((_a = opts.host) !== null && _a !== void 0 ? _a : "").indexOf("https://") !== 0 && ((_b = opts.host) !== null && _b !== void 0 ? _b : "").indexOf("http://") !== 0
2051
- ? `https://${opts.host}`
2052
- : opts.host });
2053
- }
2054
- function jitsuAnalytics(_opts) {
2055
- const opts = fixOptions(_opts);
2056
- const inBrowser = isInBrowser();
2057
- const rt = opts.runtime || (inBrowser ? windowRuntime(opts) : emptyRuntime(opts));
2058
- return createUnderlyingAnalyticsInstance(opts, rt);
2059
- // if (inBrowser) {
2060
- // const fetch = opts.fetch || globalThis.fetch;
2061
- // if (!fetch) {
2062
- // throw new Error(
2063
- // "Please specify fetch function in jitsu plugin initialization, fetch isn't available in global scope"
2064
- // );
2065
- // }
2066
- // const url = `${opts.host}/api/s/cfg`;
2067
- // const authHeader = {};
2068
- // const debugHeader = opts.debug ? { "X-Enable-Debug": "true" } : {};
2069
- // fetch(url)
2070
- // .then(res => res.json())
2071
- // .then(res => {
2072
- // result.loaded(createUnderlyingAnalyticsInstance(opts, rt, []));
2073
- // })
2074
- // .catch(e => {
2075
- // console.warn(`[JITSU] error getting device-destinations from ${url}`, e);
2076
- // result.loaded(createUnderlyingAnalyticsInstance(opts, rt));
2077
- // });
2078
- // } else {
2079
- // result.loaded(createUnderlyingAnalyticsInstance(opts, rt));
2080
- // }
2081
- }
2082
-
2083
- function snakeToCamel(s) {
2084
- return s.replace(/([-_][a-z])/gi, $1 => {
2085
- return $1.toUpperCase().replace("-", "").replace("_", "");
2086
- });
2087
- }
2088
- const trimPrefix = (s, prefix) => s.replace(new RegExp(`^${prefix}`), "");
2089
- const defaultParser = (nestedPath = []) => ({
2090
- path: (name) => [
2091
- ...nestedPath,
2092
- snakeToCamel(nestedPath.length > 0 ? trimPrefix(name, nestedPath.join("-") + "-") : name),
2093
- ],
2094
- parse: (arg) => arg,
2095
- });
2096
- const booleanParser = (nestedPath = []) => (Object.assign(Object.assign({}, defaultParser(nestedPath)), { parse: (arg) => arg === "true" || arg === "1" || arg === "yes" }));
2097
- const jsonParser = (nestedPath = []) => (Object.assign(Object.assign({}, defaultParser(nestedPath)), { parse: (arg) => {
2098
- try {
2099
- return JSON.parse(arg);
2100
- }
2101
- catch (e) {
2102
- console.error(`Can't parse Jitsu Option as JSON: ${arg}`);
2103
- return {};
2104
- }
2105
- } }));
2106
- const parsers = {
2107
- debug: booleanParser(),
2108
- "privacy-disable-user-ids": booleanParser(["privacy"]),
2109
- "privacy-dont-send": booleanParser(["privacy"]),
2110
- "privacy-ip-policy": defaultParser(["privacy"]),
2111
- "echo-events": booleanParser(),
2112
- "init-only": booleanParser(),
2113
- "cookie-names": jsonParser(),
2114
- "cookie-capture": jsonParser(),
2115
- "default-payload-context": jsonParser(),
2116
- };
2117
- function getParser(name) {
2118
- return parsers[name] || defaultParser();
2119
- }
2120
- function setPath(obj, path, value) {
2121
- let current = obj;
2122
- let i = 0;
2123
- for (; i < path.length - 1; i++) {
2124
- const key = path[i];
2125
- current[key] = current[key] || {};
2126
- current = current[key];
2127
- }
2128
- current[path[i]] = value;
2129
- }
2130
- function getScriptAttributes(scriptElement) {
2131
- return scriptElement
2132
- .getAttributeNames()
2133
- .filter(name => name.indexOf("data-") === 0)
2134
- .map(name => name.substring("data-".length))
2135
- .reduce((res, name) => {
2136
- const parser = getParser(name);
2137
- const path = parser.path(name);
2138
- setPath(res, path, parser.parse(scriptElement.getAttribute(`data-${name}`)));
2139
- return res;
2140
- }, {});
2141
- }
2142
- function runCallback(callback, jitsu) {
2143
- if (typeof callback === "function") {
2144
- callback(jitsu);
2145
- }
2146
- else if (Array.isArray(callback) && typeof callback[0] === "string") {
2147
- const [method, ...args] = callback;
2148
- if (typeof jitsu[method] === "function") {
2149
- jitsu[method](...args);
2150
- }
2151
- else {
2152
- console.warn(`Method ${method} is not supported, ignoring callback`);
2153
- }
2154
- }
2155
- else {
2156
- console.warn(`Invalid jitsu queue callback`, callback);
2157
- }
2158
- }
2159
- (function () {
2160
- function readJitsuOptions() {
2161
- const scriptElement = window.document.currentScript;
2162
- if (!scriptElement) {
2163
- throw new Error(`Can't find script element`);
2164
- }
2165
- const host = new URL(scriptElement.src).origin;
2166
- return Object.assign(Object.assign(Object.assign({}, ((window === null || window === void 0 ? void 0 : window.jitsuConfig) || {})), getScriptAttributes(scriptElement)), { host });
2167
- }
2168
- const options = readJitsuOptions();
2169
- const JITSU_V2_ID = options.namespace || "jitsu";
2170
- if (options.debug) {
2171
- console.log(`Jitsu options: `, JSON.stringify(options));
2172
- }
2173
- const jitsu = jitsuAnalytics(options);
2174
- if (options.onload) {
2175
- const onloadFunction = window[options.onload];
2176
- if (!onloadFunction) {
2177
- console.warn(`onload function ${options.onload} is not found in window`);
2178
- }
2179
- if (typeof onloadFunction === "function") {
2180
- onloadFunction(jitsu);
2181
- }
2182
- else {
2183
- console.warn(`onload function ${options.onload} is not callable: ${typeof onloadFunction}`);
2184
- }
2185
- }
2186
- window[JITSU_V2_ID] = jitsu;
2187
- /**
2188
- * New callback based queue, see below
2189
- */
2190
- //make a copy of the queue
2191
- const callbackQueue = window[JITSU_V2_ID + "Q"] && window[JITSU_V2_ID + "Q"].length ? [...window[JITSU_V2_ID + "Q"]] : [];
2192
- //replace push with a function that calls callback immediately
2193
- window[JITSU_V2_ID + "Q"] = {
2194
- push: (callback) => {
2195
- if (typeof callback === "function") {
2196
- callback(jitsu);
2197
- }
2198
- else {
2199
- console.warn(`${JITSU_V2_ID}Q.push() accepts only function, ${typeof callback} given`);
2200
- }
2201
- },
2202
- };
2203
- if (options.debug) {
2204
- console.log(`[JITSU DEBUG] Jitsu callback queue size: ${callbackQueue.length}`, callbackQueue);
2205
- }
2206
- callbackQueue.forEach((callback) => {
2207
- try {
2208
- runCallback(callback, jitsu);
2209
- }
2210
- catch (e) {
2211
- console.warn(`Error processing callback from Jitsu queue`, e);
2212
- }
2213
- });
2214
- if (!options.initOnly) {
2215
- jitsu.page();
2216
- }
2217
- })();
2218
-
2219
- })();