@elbwalker/utils
Version:
Shared utils for walkerOS packages
1 lines • 18.5 kB
JavaScript
;var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i={};function s(e){return/^(?:\d{1,3}\.){3}\d{1,3}$/.test(e)?e.replace(/\.\d+$/,".0"):""}((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(i,{Commands:()=>u,Const:()=>l,addDestination:()=>B,anonymizeIP:()=>s,assign:()=>c,castToProperty:()=>P,castValue:()=>O,clone:()=>E,commonHandleCommand:()=>V,createEvent:()=>X,createEventOrCommand:()=>_,createPush:()=>R,createPushResult:()=>z,debounce:()=>I,destinationInit:()=>H,destinationPush:()=>U,filterValues:()=>C,getBrowser:()=>se,getBrowserVersion:()=>ae,getByPath:()=>k,getDeviceType:()=>le,getEvent:()=>J,getGrantedConsent:()=>F,getHeaders:()=>ne,getId:()=>j,getMappingEvent:()=>$,getMappingValue:()=>A,getMarketingParameters:()=>Q,getOS:()=>ce,getOSVersion:()=>ue,isArguments:()=>d,isArray:()=>p,isBoolean:()=>f,isCommand:()=>g,isDefined:()=>m,isElementOrDocument:()=>h,isNumber:()=>y,isObject:()=>b,isPropertyType:()=>S,isSameType:()=>v,isString:()=>w,on:()=>K,onApply:()=>W,onLog:()=>Y,parseUserAgent:()=>ie,pushToDestinations:()=>L,requestToData:()=>Z,requestToParameter:()=>ee,setByPath:()=>x,setConsent:()=>G,throttle:()=>N,throwError:()=>oe,transformData:()=>te,trim:()=>re,tryCatch:()=>q,tryCatchAsync:()=>D,useHooks:()=>M,validateEvent:()=>de,validateProperty:()=>pe}),module.exports=(e=i,((e,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of o(i))r.call(e,c)||c===s||t(e,c,{get:()=>i[c],enumerable:!(a=n(i,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var a={merge:!0,shallow:!0,extend:!0};function c(e,t={},n={}){n={...a,...n};const o=Object.entries(t).reduce(((t,[o,r])=>{const i=e[o];return n.merge&&Array.isArray(i)&&Array.isArray(r)?t[o]=r.reduce(((e,t)=>e.includes(t)?e:[...e,t]),[...i]):(n.extend||o in e)&&(t[o]=r),t}),{});return n.shallow?{...e,...o}:(Object.assign(e,o),e)}var u={Action:"action",Config:"config",Consent:"consent",Context:"context",Custom:"custom",Destination:"destination",Elb:"elb",Globals:"globals",Hook:"hook",Init:"init",Link:"link",On:"on",Prefix:"data-elb",Ready:"ready",Run:"run",Session:"session",User:"user",Walker:"walker"},l={Commands:u,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};function d(e){return"[object Arguments]"===Object.prototype.toString.call(e)}function p(e){return Array.isArray(e)}function f(e){return"boolean"==typeof e}function g(e){return e===l.Commands.Walker}function m(e){return void 0!==e}function h(e){return e===document||e instanceof Element}function y(e){return"number"==typeof e&&!Number.isNaN(e)}function b(e){return"object"==typeof e&&null!==e&&!p(e)&&"[object Object]"===Object.prototype.toString.call(e)}function v(e,t){return typeof e==typeof t}function w(e){return"string"==typeof e}function k(e,t="",n,o=0){const r=t.split(".");let i=e;for(let e=0;e<r.length;e++){const t=r[e];if("*"===t&&p(i)){const t=r.slice(e+1).join("."),s=[];for(const e of i){const r=k(e,t,n,o);s.push(r)}return s}if(i=i instanceof Object?i[t]:void 0,!i)break}return m(i)?i:n}function x(e,t,n){const o=t.split(".");let r=e;for(let e=0;e<o.length;e++){const t=o[e];e===o.length-1?r[t]=n:(t in r&&"object"==typeof r[t]&&null!==r[t]||(r[t]={}),r=r[t])}return e}function O(e){if("true"===e)return!0;if("false"===e)return!1;const t=Number(e);return e==t&&""!==e?t:String(e)}function E(e,t=new WeakMap){if("object"!=typeof e||null===e)return e;if(t.has(e))return t.get(e);const n=Object.prototype.toString.call(e);if("[object Object]"===n){const n={};t.set(e,n);for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=E(e[o],t));return n}if("[object Array]"===n){const n=[];return t.set(e,n),e.forEach((e=>{n.push(E(e,t))})),n}if("[object Date]"===n)return new Date(e.getTime());if("[object RegExp]"===n){const t=e;return new RegExp(t.source,t.flags)}return e}function j(e=6){let t="";for(let n=36;t.length<e;)t+=(Math.random()*n|0).toString(n);return t}function S(e){return f(e)||w(e)||y(e)||!m(e)||p(e)&&e.every(S)||b(e)&&Object.values(e).every(S)}function C(e){return f(e)||w(e)||y(e)?e:d(e)?C(Array.from(e)):p(e)?e.map((e=>C(e))).filter((e=>void 0!==e)):b(e)?Object.entries(e).reduce(((e,[t,n])=>{const o=C(n);return void 0!==o&&(e[t]=o),e}),{}):void 0}function P(e){return S(e)?e:void 0}function q(e,t,n){return function(...o){try{return e(...o)}catch(e){if(!t)return;return t(e)}finally{n?.()}}}function D(e,t,n){return async function(...o){try{return await e(...o)}catch(e){if(!t)return;return await t(e)}finally{await(n?.())}}}async function $(e,t){const[n,o]=(e.event||"").split(" ");if(!t||!n||!o)return{};let r,i="",s=n,a=o;const c=t=>{if(t)return(t=p(t)?t:[t]).find((t=>!t.condition||t.condition(e)))};t[s]||(s="*");const u=t[s];return u&&(u[a]||(a="*"),r=c(u[a])),r||(s="*",a="*",r=c(t[s]?.[a])),r&&(i=`${s} ${a}`),{eventMapping:r,mappingKey:i}}async function A(e,t={},n={}){if(!m(e))return;const o=b(e)&&e.consent||n.consent||n.instance?.consent,r=p(t)?t:[t];for(const t of r){const r=await D(T)(e,t,{...n,consent:o});if(m(r))return r}}async function T(e,t,n={}){const{instance:o,consent:r}=n;return(p(t)?t:[t]).reduce((async(t,i)=>{const s=await t;if(s)return s;const a=w(i)?{key:i}:i;if(!Object.keys(a).length)return;const{condition:c,consent:u,fn:l,key:d,loop:f,map:g,set:h,validate:y,value:b}=a;if(c&&!await D(c)(e,i,o))return;if(u&&!F(u,r))return b;let v=m(b)?b:e;if(l&&(v=await D(l)(e,i,n)),d&&(v=k(e,d,b)),f){const[t,o]=f,r="this"===t?[e]:await A(e,t,n);p(r)&&(v=(await Promise.all(r.map((e=>A(e,o,n))))).filter(m))}else g?v=await Object.entries(g).reduce((async(t,[o,r])=>{const i=await t,s=await A(e,r,n);return m(s)&&(i[o]=s),i}),Promise.resolve({})):h&&(v=await Promise.all(h.map((t=>T(e,t,n)))));y&&!await D(y)(v)&&(v=void 0);const x=P(v);return m(x)?x:P(b)}),Promise.resolve(void 0))}function M(e,t,n){return function(...o){let r;const i="post"+t,s=n["pre"+t],a=n[i];return r=s?s({fn:e},...o):e(...o),a&&(r=a({fn:e,result:r},...o)),r}}function I(e,t=1e3,n=!1){let o,r=null,i=!1;return(...s)=>new Promise((a=>{const c=n&&!i;r&&clearTimeout(r),r=setTimeout((()=>{r=null,n&&!i||(o=e(...s),a(o))}),t),c&&(i=!0,o=e(...s),a(o))}))}function N(e,t=1e3){let n=null;return function(...o){if(null===n)return n=setTimeout((()=>{n=null}),t),e(...o)}}async function V(e,t,n,o){let r;switch(t){case l.Commands.Consent:b(n)&&(r=await G(e,n));break;case l.Commands.Custom:b(n)&&(e.custom=c(e.custom,n));break;case l.Commands.Destination:b(n)&&"function"==typeof n.push&&(r=await B(e,n,o));break;case l.Commands.Globals:b(n)&&(e.globals=c(e.globals,n));break;case l.Commands.User:b(n)&&c(e.user,n,{shallow:!1})}return r}function _(e,t,n={}){const o=v(t,"")?{event:t,...n}:{...n,...t||{}};if(!o.event)throw new Error("Event name is required");const[r,i]=o.event.split(" ");if(!r||!i)throw new Error("Event name is invalid");if(r===u.Walker)return{command:i};++e.count;const{timestamp:s=Date.now(),group:a=e.group,count:c=e.count}=o,{event:l=`${r} ${i}`,data:d={},context:p={},globals:f=e.globals,custom:g={},user:m=e.user,nested:h=[],consent:y=e.consent,id:b=`${s}-${a}-${c}`,trigger:w="",entity:k=r,action:x=i,timing:O=0,version:E={source:e.version,tagging:e.config.tagging||0},source:j={type:"",id:"",previous_id:""}}=o;return{event:{event:l,data:d,context:p,globals:f,custom:g,user:m,nested:h,consent:y,id:b,trigger:w,entity:k,action:x,timestamp:s,timing:O,group:a,count:c,version:E,source:j}}}function R(e,t,n){return M((async(...o)=>await D((async(...o)=>{const[r,i,s]=o,a=n(...o),{event:c,command:u}=_(e,r,a);return u?await t(e,u,i,s):await L(e,c)}),(t=>(e.config.onError&&e.config.onError(t,e),z({ok:!1}))))(...o)),"Push",e.hooks)}async function B(e,t,n){const o=n||t.config||{init:!1},r={...t,config:o};let i=o.id;if(!i)do{i=j(4)}while(e.destinations[i]);return e.destinations[i]=r,!1!==o.queue&&(r.queue=[...e.queue]),L(e,void 0,{[i]:r})}async function L(e,t,n){const{allowed:o,consent:r,globals:i,user:s}=e;if(!o)return z({ok:!1});t&&e.queue.push(t),n||(n=e.destinations);const a=await Promise.all(Object.entries(n).map((async([n,o])=>{let a=(o.queue||[]).map((e=>({...e,consent:r})));if(o.queue=[],t){let n=E(t);await Promise.all(Object.entries(o.config.policy||[]).map((async([o,r])=>{const i=await A(t,r,{instance:e});n=x(n,o,i)}))),a.push(n)}if(!a.length)return{id:n,destination:o,skipped:!0};const u=[],l=a.filter((e=>{const t=F(o.config.consent,r,e.consent);return!t||(e.consent=t,u.push(e),!1)}));if(o.queue.concat(l),!u.length)return{id:n,destination:o,queue:a};if(!await D(H)(e,o))return{id:n,destination:o,queue:a};let d=!1;return o.dlq||(o.dlq=[]),await Promise.all(u.map((async t=>(t.globals=c(i,t.globals),t.user=c(s,t.user),await D(U,(n=>(e.config.onError&&e.config.onError(n,e),d=!0,o.dlq.push([t,n]),!1)))(e,o,t),t)))),{id:n,destination:o,error:d}}))),u=[],l=[],d=[];for(const e of a){if(e.skipped)continue;const t=e.destination,n={id:e.id,destination:t};e.error?d.push(n):e.queue&&e.queue.length?(t.queue=(t.queue||[]).concat(e.queue),l.push(n)):u.push(n)}return z({ok:!d.length,event:t,successful:u,queued:l,failed:d})}async function H(e,t){if(t.init&&!t.config.init){const n=await M(t.init,"DestinationInit",e.hooks)(t.config,e);if(!1===n)return n;t.config={...n||t.config,init:!0}}return!0}async function U(e,t,n){const{config:o}=t,{eventMapping:r,mappingKey:i}=await $(n,o.mapping);let s=o.data&&await A(n,o.data,{instance:e});if(r){if(r.ignore)return!1;if(r.name&&(n.event=r.name),r.data){const t=r.data&&await A(n,r.data,{instance:e});s=b(s)&&b(t)?c(s,t):t}}const a={data:s,instance:e};if(r?.batch&&t.pushBatch){const c=r.batched||{key:i||"",events:[],data:[]};c.events.push(n),m(s)&&c.data.push(s),r.batchFn=r.batchFn||I(((e,t)=>{M(e.pushBatch,"DestinationPushBatch",t.hooks)(c,o,a),c.events=[],c.data=[]}),r.batch),r.batched=c,r.batchFn(t,e)}else await M(t.push,"DestinationPush",e.hooks)(n,o,r,a);return!0}function z(e){return c({ok:!e?.failed?.length,successful:[],queued:[],failed:[]},e)}function K(e,t,n){const o=e.on,r=o[t]||[],i=p(n)?n:[n];i.forEach((e=>{r.push(e)})),o[t]=r,W(e,t,i)}function W(e,t,n,o){let r=n||[];if(n||(r=e.on[t]||[],Object.values(e.destinations).forEach((e=>{const n=e.config.on?.[t];n&&(r=r.concat(n))}))),r.length)switch(t){case l.Commands.Consent:!function(e,t,n){const o=n||e.consent;t.forEach((t=>{Object.keys(o).filter((e=>e in t)).forEach((n=>{q(t[n])(e,o)}))}))}(e,r,o);break;case l.Commands.Ready:case l.Commands.Run:!function(e,t){e.allowed&&t.forEach((t=>{q(t)(e)}))}(e,r);break;case l.Commands.Session:!function(e,t){if(!e.config.session)return;t.forEach((t=>{q(t)(e,e.session)}))}(e,r)}}function F(e,t={},n={}){const o={...t,...n},r={};let i=void 0===e;return Object.keys(o).forEach((t=>{o[t]&&(r[t]=!0,e&&e[t]&&(i=!0))})),!!i&&r}async function G(e,t){const{consent:n}=e;let o=!1;const r={};return Object.entries(t).forEach((([e,t])=>{const n=!!t;r[e]=n,o=o||n})),e.consent=c(n,r),W(e,"consent",void 0,r),o?L(e):z({ok:!0})}function X(e={}){const t=e.timestamp||(new Date).setHours(0,13,37,0),n=e.group||"gr0up",o=e.count||1,r=c({event:"entity action",data:{string:"foo",number:1,boolean:!0,array:[0,"text",!1],not:void 0},context:{dev:["test",1]},globals:{lang:"elb"},custom:{completely:"random"},user:{id:"us3r",device:"c00k13",session:"s3ss10n"},nested:[{type:"child",data:{is:"subordinated"},nested:[],context:{element:["child",0]}}],consent:{functional:!0},id:`${t}-${n}-${o}`,trigger:"test",entity:"entity",action:"action",timestamp:t,timing:3.14,group:n,count:o,version:{source:"0.0.7",tagging:1},source:{type:"web",id:"https://localhost:80",previous_id:"http://remotehost:9001"}},e,{merge:!1});if(e.event){const[t,n]=e.event.split(" ")??[];t&&n&&(r.entity=t,r.action=n)}return r}function J(e="entity action",t={}){const n=t.timestamp||(new Date).setHours(0,13,37,0),o={data:{id:"ers",name:"Everyday Ruck Snack",color:"black",size:"l",price:420}},r={data:{id:"cc",name:"Cool Cap",size:"one size",price:42}};return X({...{"cart view":{data:{currency:"EUR",value:2*o.data.price},context:{shopping:["cart",0]},globals:{pagegroup:"shop"},nested:[{type:"product",data:{...o.data,quantity:2},context:{shopping:["cart",0]},nested:[]}],trigger:"load"},"checkout view":{data:{step:"payment",currency:"EUR",value:o.data.price+r.data.price},context:{shopping:["checkout",0]},globals:{pagegroup:"shop"},nested:[{type:"product",...o,context:{shopping:["checkout",0]},nested:[]},{type:"product",...r,context:{shopping:["checkout",0]},nested:[]}],trigger:"load"},"order complete":{data:{id:"0rd3r1d",currency:"EUR",shipping:5.22,taxes:73.76,total:555},context:{shopping:["complete",0]},globals:{pagegroup:"shop"},nested:[{type:"product",...o,context:{shopping:["complete",0]},nested:[]},{type:"product",...r,context:{shopping:["complete",0]},nested:[]},{type:"gift",data:{name:"Surprise"},context:{shopping:["complete",0]},nested:[]}],trigger:"load"},"page view":{data:{domain:"www.example.com",title:"walkerOS documentation",referrer:"https://www.elbwalker.com/",search:"?foo=bar",hash:"#hash",id:"/docs/"},globals:{pagegroup:"docs"},trigger:"load"},"product add":{...o,context:{shopping:["intent",0]},globals:{pagegroup:"shop"},nested:[],trigger:"click"},"product view":{...o,context:{shopping:["detail",0]},globals:{pagegroup:"shop"},nested:[],trigger:"load"},"product visible":{data:{...o.data,position:3,promo:!0},context:{shopping:["discover",0]},globals:{pagegroup:"shop"},nested:[],trigger:"load"},"promotion visible":{data:{name:"Setting up tracking easily",position:"hero"},context:{ab_test:["engagement",0]},globals:{pagegroup:"homepage"},trigger:"visible"},"session start":{data:{id:"s3ss10n",start:n,isNew:!0,count:1,runs:1,isStart:!0,storage:!0,referrer:"",device:"c00k13"},user:{id:"us3r",device:"c00k13",session:"s3ss10n",hash:"h4sh",address:"street number",email:"user@example.com",phone:"+49 123 456 789",userAgent:"Mozilla...",browser:"Chrome",browserVersion:"90",deviceType:"desktop",language:"de-DE",country:"DE",region:"HH",city:"Hamburg",zip:"20354",timezone:"Berlin",os:"walkerOS",osVersion:"1.0",screenSize:"1337x420",ip:"127.0.0.0",internal:!0,custom:"value"}}}[e],...t,event:e})}function Q(e,t={}){const n="clickId",o={},r={utm_campaign:"campaign",utm_content:"content",utm_medium:"medium",utm_source:"source",utm_term:"term",dclid:n,fbclid:n,gclid:n,msclkid:n,ttclid:n,twclid:n,igshid:n,sclid:n};return Object.entries(c(r,t)).forEach((([t,r])=>{const i=e.searchParams.get(t);i&&(r===n&&(r=t,o[n]=t),o[r]=i)})),o}function Y(e,t=!1){t&&console.dir(e,{depth:4})}function Z(e){const t=String(e),n=t.split("?")[1]||t;return q((()=>{const e=new URLSearchParams(n),t={};return e.forEach(((e,n)=>{const o=n.split(/[[\]]+/).filter(Boolean);let r=t;o.forEach(((t,n)=>{const i=n===o.length-1;if(p(r)){const s=parseInt(t,10);i?r[s]=O(e):(r[s]=r[s]||(isNaN(parseInt(o[n+1],10))?{}:[]),r=r[s])}else b(r)&&(i?r[t]=O(e):(r[t]=r[t]||(isNaN(parseInt(o[n+1],10))?{}:[]),r=r[t]))}))})),t}))()}function ee(e){if(!e)return"";const t=[],n=encodeURIComponent;function o(e,r){null!=r&&(p(r)?r.forEach(((t,n)=>o(`${e}[${n}]`,t))):b(r)?Object.entries(r).forEach((([t,n])=>o(`${e}[${t}]`,n))):t.push(`${n(e)}=${n(String(r))}`))}return"object"!=typeof e?n(e):(Object.entries(e).forEach((([e,t])=>o(e,t))),t.join("&"))}function te(e){return void 0===e||v(e,"")?e:JSON.stringify(e)}function ne(e={}){return c({"Content-Type":"application/json; charset=utf-8"},e)}function oe(e){throw new Error(String(e))}function re(e){return e?e.trim().replace(/^'|'$/g,"").trim():""}function ie(e){return e?{userAgent:e,browser:se(e),browserVersion:ae(e),os:ce(e),osVersion:ue(e),deviceType:le(e)}:{}}function se(e){const t=[{name:"Edge",substr:"Edg"},{name:"Chrome",substr:"Chrome"},{name:"Safari",substr:"Safari",exclude:"Chrome"},{name:"Firefox",substr:"Firefox"},{name:"IE",substr:"MSIE"},{name:"IE",substr:"Trident"}];for(const n of t)if(e.includes(n.substr)&&(!n.exclude||!e.includes(n.exclude)))return n.name}function ae(e){const t=[/Edg\/([0-9]+)/,/Chrome\/([0-9]+)/,/Version\/([0-9]+).*Safari/,/Firefox\/([0-9]+)/,/MSIE ([0-9]+)/,/rv:([0-9]+).*Trident/];for(const n of t){const t=e.match(n);if(t)return t[1]}}function ce(e){const t=[{name:"Windows",substr:"Windows NT"},{name:"macOS",substr:"Mac OS X"},{name:"Android",substr:"Android"},{name:"iOS",substr:"iPhone OS"},{name:"Linux",substr:"Linux"}];for(const n of t)if(e.includes(n.substr))return n.name}function ue(e){const t=e.match(/(?:Windows NT|Mac OS X|Android|iPhone OS) ([0-9._]+)/);return t?t[1].replace(/_/g,"."):void 0}function le(e){let t="Desktop";return/Tablet|iPad/i.test(e)?t="Tablet":/Mobi|Android|iPhone|iPod|BlackBerry|Opera Mini|IEMobile|WPDesktop/i.test(e)&&(t="Mobile"),t}function de(e,t=[]){let n,o,r;v(e,{})||oe("Invalid object"),v(e.event,"")?(n=e.event,[o,r]=n.split(" "),o&&r||oe("Invalid event name")):v(e.entity,"")&&v(e.action,"")?(o=e.entity,r=e.action,n=`${o} ${r}`):oe("Missing or invalid event, entity, or action");const i={event:n,data:{},context:{},custom:{},globals:{},user:{},nested:[],consent:{},id:"",trigger:"",entity:o,action:r,timestamp:0,timing:0,group:"",count:0,version:{source:"",tagging:0},source:{type:"",id:"",previous_id:""}};return[{"*":{"*":{event:{maxLength:255},user:{allowedKeys:["id","device","session"]},consent:{allowedValues:[!0,!1]},timestamp:{min:0},timing:{min:0},count:{min:0},version:{allowedKeys:["source","tagging"]},source:{allowedKeys:["type","id","previous_id"]}}}}].concat(t).reduce(((e,t)=>["*",o].reduce(((e,n)=>["*",r].reduce(((e,o)=>{const r=t[n]?.[o];return r?e.concat([r]):e}),e)),e)),[]).reduce(((t,n)=>{const o=Object.keys(n).filter((e=>{const t=n[e];return!0===t?.required}));return[...Object.keys(e),...o].reduce(((t,o)=>{const r=n[o];let i=e[o];return r&&(i=q(pe,(e=>{oe(String(e))}))(t,o,i,r)),v(i,t[o])&&(t[o]=i),t}),t)}),i)}function pe(e,t,n,o){if(o.validate&&(n=q(o.validate,(e=>{oe(String(e))}))(n,t,e)),o.required&&void 0===n&&oe("Missing required property"),v(n,""))o.maxLength&&n.length>o.maxLength&&(o.strict&&oe("Value exceeds maxLength"),n=n.substring(0,o.maxLength));else if(v(n,1))v(o.min,1)&&n<o.min?(o.strict&&oe("Value below min"),n=o.min):v(o.max,1)&&n>o.max&&(o.strict&&oe("Value exceeds max"),n=o.max);else if(v(n,{})){if(o.schema){const e=o.schema;Object.keys(e).reduce(((t,n)=>{const o=e[n];let r=t[n];return o&&(o.type&&typeof r!==o.type&&oe(`Type doesn't match (${n})`),r=q(pe,(e=>{oe(String(e))}))(t,n,r,o)),r}),n)}for(const e of Object.keys(n))o.allowedKeys&&!o.allowedKeys.includes(e)&&(o.strict&&oe("Key not allowed"),delete n[e])}return n}//# sourceMappingURL=index.js.map