UNPKG

@elbwalker/utils

Version:

Shared utils for walkerOS packages

1 lines 18 kB
function e(e){return/^(?:\d{1,3}\.){3}\d{1,3}$/.test(e)?e.replace(/\.\d+$/,".0"):""}var t={merge:!0,shallow:!0,extend:!0};function n(e,n={},o={}){o={...t,...o};const i=Object.entries(n).reduce(((t,[n,i])=>{const r=e[n];return o.merge&&Array.isArray(r)&&Array.isArray(i)?t[n]=i.reduce(((e,t)=>e.includes(t)?e:[...e,t]),[...r]):(o.extend||n in e)&&(t[n]=i),t}),{});return o.shallow?{...e,...i}:(Object.assign(e,i),e)}var o={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"},i={Commands:o,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}};function r(e){return"[object Arguments]"===Object.prototype.toString.call(e)}function s(e){return Array.isArray(e)}function c(e){return"boolean"==typeof e}function a(e){return e===i.Commands.Walker}function u(e){return void 0!==e}function l(e){return e===document||e instanceof Element}function d(e){return"number"==typeof e&&!Number.isNaN(e)}function f(e){return"object"==typeof e&&null!==e&&!s(e)&&"[object Object]"===Object.prototype.toString.call(e)}function p(e,t){return typeof e==typeof t}function g(e){return"string"==typeof e}function m(e,t="",n,o=0){const i=t.split(".");let r=e;for(let e=0;e<i.length;e++){const t=i[e];if("*"===t&&s(r)){const t=i.slice(e+1).join("."),s=[];for(const e of r){const i=m(e,t,n,o);s.push(i)}return s}if(r=r instanceof Object?r[t]:void 0,!r)break}return u(r)?r:n}function h(e,t,n){const o=t.split(".");let i=e;for(let e=0;e<o.length;e++){const t=o[e];e===o.length-1?i[t]=n:(t in i&&"object"==typeof i[t]&&null!==i[t]||(i[t]={}),i=i[t])}return e}function b(e){if("true"===e)return!0;if("false"===e)return!1;const t=Number(e);return e==t&&""!==e?t:String(e)}function y(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]=y(e[o],t));return n}if("[object Array]"===n){const n=[];return t.set(e,n),e.forEach((e=>{n.push(y(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 v(e=6){let t="";for(let n=36;t.length<e;)t+=(Math.random()*n|0).toString(n);return t}function w(e){return c(e)||g(e)||d(e)||!u(e)||s(e)&&e.every(w)||f(e)&&Object.values(e).every(w)}function k(e){return c(e)||g(e)||d(e)?e:r(e)?k(Array.from(e)):s(e)?e.map((e=>k(e))).filter((e=>void 0!==e)):f(e)?Object.entries(e).reduce(((e,[t,n])=>{const o=k(n);return void 0!==o&&(e[t]=o),e}),{}):void 0}function x(e){return w(e)?e:void 0}function E(e,t,n){return function(...o){try{return e(...o)}catch(e){if(!t)return;return t(e)}finally{n?.()}}}function j(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 O(e,t){const[n,o]=(e.event||"").split(" ");if(!t||!n||!o)return{};let i,r="",c=n,a=o;const u=t=>{if(t)return(t=s(t)?t:[t]).find((t=>!t.condition||t.condition(e)))};t[c]||(c="*");const l=t[c];return l&&(l[a]||(a="*"),i=u(l[a])),i||(c="*",a="*",i=u(t[c]?.[a])),i&&(r=`${c} ${a}`),{eventMapping:i,mappingKey:r}}async function S(e,t={},n={}){if(!u(e))return;const o=f(e)&&e.consent||n.consent||n.instance?.consent,i=s(t)?t:[t];for(const t of i){const i=await j(C)(e,t,{...n,consent:o});if(u(i))return i}}async function C(e,t,n={}){const{instance:o,consent:i}=n;return(s(t)?t:[t]).reduce((async(t,r)=>{const c=await t;if(c)return c;const a=g(r)?{key:r}:r;if(!Object.keys(a).length)return;const{condition:l,consent:d,fn:f,key:p,loop:h,map:b,set:y,validate:v,value:w}=a;if(l&&!await j(l)(e,r,o))return;if(d&&!K(d,i))return w;let k=u(w)?w:e;if(f&&(k=await j(f)(e,r,n)),p&&(k=m(e,p,w)),h){const[t,o]=h,i="this"===t?[e]:await S(e,t,n);s(i)&&(k=(await Promise.all(i.map((e=>S(e,o,n))))).filter(u))}else b?k=await Object.entries(b).reduce((async(t,[o,i])=>{const r=await t,s=await S(e,i,n);return u(s)&&(r[o]=s),r}),Promise.resolve({})):y&&(k=await Promise.all(y.map((t=>C(e,t,n)))));v&&!await j(v)(k)&&(k=void 0);const E=x(k);return u(E)?E:x(w)}),Promise.resolve(void 0))}function q(e,t,n){return function(...o){let i;const r="post"+t,s=n["pre"+t],c=n[r];return i=s?s({fn:e},...o):e(...o),c&&(i=c({fn:e,result:i},...o)),i}}function $(e,t=1e3,n=!1){let o,i=null,r=!1;return(...s)=>new Promise((c=>{const a=n&&!r;i&&clearTimeout(i),i=setTimeout((()=>{i=null,n&&!r||(o=e(...s),c(o))}),t),a&&(r=!0,o=e(...s),c(o))}))}function P(e,t=1e3){let n=null;return function(...o){if(null===n)return n=setTimeout((()=>{n=null}),t),e(...o)}}async function A(e,t,o,r){let s;switch(t){case i.Commands.Consent:f(o)&&(s=await U(e,o));break;case i.Commands.Custom:f(o)&&(e.custom=n(e.custom,o));break;case i.Commands.Destination:f(o)&&"function"==typeof o.push&&(s=await I(e,o,r));break;case i.Commands.Globals:f(o)&&(e.globals=n(e.globals,o));break;case i.Commands.User:f(o)&&n(e.user,o,{shallow:!1})}return s}function M(e,t,n={}){const i=p(t,"")?{event:t,...n}:{...n,...t||{}};if(!i.event)throw new Error("Event name is required");const[r,s]=i.event.split(" ");if(!r||!s)throw new Error("Event name is invalid");if(r===o.Walker)return{command:s};++e.count;const{timestamp:c=Date.now(),group:a=e.group,count:u=e.count}=i,{event:l=`${r} ${s}`,data:d={},context:f={},globals:g=e.globals,custom:m={},user:h=e.user,nested:b=[],consent:y=e.consent,id:v=`${c}-${a}-${u}`,trigger:w="",entity:k=r,action:x=s,timing:E=0,version:j={source:e.version,tagging:e.config.tagging||0},source:O={type:"",id:"",previous_id:""}}=i;return{event:{event:l,data:d,context:f,globals:g,custom:m,user:h,nested:b,consent:y,id:v,trigger:w,entity:k,action:x,timestamp:c,timing:E,group:a,count:u,version:j,source:O}}}function D(e,t,n){return q((async(...o)=>await j((async(...o)=>{const[i,r,s]=o,c=n(...o),{event:a,command:u}=M(e,i,c);return u?await t(e,u,r,s):await T(e,a)}),(t=>(e.config.onError&&e.config.onError(t,e),_({ok:!1}))))(...o)),"Push",e.hooks)}async function I(e,t,n){const o=n||t.config||{init:!1},i={...t,config:o};let r=o.id;if(!r)do{r=v(4)}while(e.destinations[r]);return e.destinations[r]=i,!1!==o.queue&&(i.queue=[...e.queue]),T(e,void 0,{[r]:i})}async function T(e,t,o){const{allowed:i,consent:r,globals:s,user:c}=e;if(!i)return _({ok:!1});t&&e.queue.push(t),o||(o=e.destinations);const a=await Promise.all(Object.entries(o).map((async([o,i])=>{let a=(i.queue||[]).map((e=>({...e,consent:r})));if(i.queue=[],t){let n=y(t);await Promise.all(Object.entries(i.config.policy||[]).map((async([o,i])=>{const r=await S(t,i,{instance:e});n=h(n,o,r)}))),a.push(n)}if(!a.length)return{id:o,destination:i,skipped:!0};const u=[],l=a.filter((e=>{const t=K(i.config.consent,r,e.consent);return!t||(e.consent=t,u.push(e),!1)}));if(i.queue.concat(l),!u.length)return{id:o,destination:i,queue:a};if(!await j(N)(e,i))return{id:o,destination:i,queue:a};let d=!1;return i.dlq||(i.dlq=[]),await Promise.all(u.map((async t=>(t.globals=n(s,t.globals),t.user=n(c,t.user),await j(R,(n=>(e.config.onError&&e.config.onError(n,e),d=!0,i.dlq.push([t,n]),!1)))(e,i,t),t)))),{id:o,destination:i,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 _({ok:!d.length,event:t,successful:u,queued:l,failed:d})}async function N(e,t){if(t.init&&!t.config.init){const n=await q(t.init,"DestinationInit",e.hooks)(t.config,e);if(!1===n)return n;t.config={...n||t.config,init:!0}}return!0}async function R(e,t,o){const{config:i}=t,{eventMapping:r,mappingKey:s}=await O(o,i.mapping);let c=i.data&&await S(o,i.data,{instance:e});if(r){if(r.ignore)return!1;if(r.name&&(o.event=r.name),r.data){const t=r.data&&await S(o,r.data,{instance:e});c=f(c)&&f(t)?n(c,t):t}}const a={data:c,instance:e};if(r?.batch&&t.pushBatch){const n=r.batched||{key:s||"",events:[],data:[]};n.events.push(o),u(c)&&n.data.push(c),r.batchFn=r.batchFn||$(((e,t)=>{q(e.pushBatch,"DestinationPushBatch",t.hooks)(n,i,a),n.events=[],n.data=[]}),r.batch),r.batched=n,r.batchFn(t,e)}else await q(t.push,"DestinationPush",e.hooks)(o,i,r,a);return!0}function _(e){return n({ok:!e?.failed?.length,successful:[],queued:[],failed:[]},e)}function L(e,t,n){const o=e.on,i=o[t]||[],r=s(n)?n:[n];r.forEach((e=>{i.push(e)})),o[t]=i,V(e,t,r)}function V(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 i.Commands.Consent:!function(e,t,n){const o=n||e.consent;t.forEach((t=>{Object.keys(o).filter((e=>e in t)).forEach((n=>{E(t[n])(e,o)}))}))}(e,r,o);break;case i.Commands.Ready:case i.Commands.Run:!function(e,t){e.allowed&&t.forEach((t=>{E(t)(e)}))}(e,r);break;case i.Commands.Session:!function(e,t){if(!e.config.session)return;t.forEach((t=>{E(t)(e,e.session)}))}(e,r)}}function K(e,t={},n={}){const o={...t,...n},i={};let r=void 0===e;return Object.keys(o).forEach((t=>{o[t]&&(i[t]=!0,e&&e[t]&&(r=!0))})),!!r&&i}async function U(e,t){const{consent:o}=e;let i=!1;const r={};return Object.entries(t).forEach((([e,t])=>{const n=!!t;r[e]=n,i=i||n})),e.consent=n(o,r),V(e,"consent",void 0,r),i?T(e):_({ok:!0})}function W(e={}){const t=e.timestamp||(new Date).setHours(0,13,37,0),o=e.group||"gr0up",i=e.count||1,r=n({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}-${o}-${i}`,trigger:"test",entity:"entity",action:"action",timestamp:t,timing:3.14,group:o,count:i,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 z(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}},i={data:{id:"cc",name:"Cool Cap",size:"one size",price:42}};return W({...{"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+i.data.price},context:{shopping:["checkout",0]},globals:{pagegroup:"shop"},nested:[{type:"product",...o,context:{shopping:["checkout",0]},nested:[]},{type:"product",...i,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",...i,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 B(e,t={}){const o="clickId",i={},r={utm_campaign:"campaign",utm_content:"content",utm_medium:"medium",utm_source:"source",utm_term:"term",dclid:o,fbclid:o,gclid:o,msclkid:o,ttclid:o,twclid:o,igshid:o,sclid:o};return Object.entries(n(r,t)).forEach((([t,n])=>{const r=e.searchParams.get(t);r&&(n===o&&(n=t,i[o]=t),i[n]=r)})),i}function F(e,t=!1){t&&console.dir(e,{depth:4})}function H(e){const t=String(e),n=t.split("?")[1]||t;return E((()=>{const e=new URLSearchParams(n),t={};return e.forEach(((e,n)=>{const o=n.split(/[[\]]+/).filter(Boolean);let i=t;o.forEach(((t,n)=>{const r=n===o.length-1;if(s(i)){const s=parseInt(t,10);r?i[s]=b(e):(i[s]=i[s]||(isNaN(parseInt(o[n+1],10))?{}:[]),i=i[s])}else f(i)&&(r?i[t]=b(e):(i[t]=i[t]||(isNaN(parseInt(o[n+1],10))?{}:[]),i=i[t]))}))})),t}))()}function G(e){if(!e)return"";const t=[],n=encodeURIComponent;function o(e,i){null!=i&&(s(i)?i.forEach(((t,n)=>o(`${e}[${n}]`,t))):f(i)?Object.entries(i).forEach((([t,n])=>o(`${e}[${t}]`,n))):t.push(`${n(e)}=${n(String(i))}`))}return"object"!=typeof e?n(e):(Object.entries(e).forEach((([e,t])=>o(e,t))),t.join("&"))}function X(e){return void 0===e||p(e,"")?e:JSON.stringify(e)}function J(e={}){return n({"Content-Type":"application/json; charset=utf-8"},e)}function Q(e){throw new Error(String(e))}function Y(e){return e?e.trim().replace(/^'|'$/g,"").trim():""}function Z(e){return e?{userAgent:e,browser:ee(e),browserVersion:te(e),os:ne(e),osVersion:oe(e),deviceType:ie(e)}:{}}function ee(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 te(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 ne(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 oe(e){const t=e.match(/(?:Windows NT|Mac OS X|Android|iPhone OS) ([0-9._]+)/);return t?t[1].replace(/_/g,"."):void 0}function ie(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 re(e,t=[]){let n,o,i;p(e,{})||Q("Invalid object"),p(e.event,"")?(n=e.event,[o,i]=n.split(" "),o&&i||Q("Invalid event name")):p(e.entity,"")&&p(e.action,"")?(o=e.entity,i=e.action,n=`${o} ${i}`):Q("Missing or invalid event, entity, or action");const r={event:n,data:{},context:{},custom:{},globals:{},user:{},nested:[],consent:{},id:"",trigger:"",entity:o,action:i,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)=>["*",i].reduce(((e,o)=>{const i=t[n]?.[o];return i?e.concat([i]):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 i=n[o];let r=e[o];return i&&(r=E(se,(e=>{Q(String(e))}))(t,o,r,i)),p(r,t[o])&&(t[o]=r),t}),t)}),r)}function se(e,t,n,o){if(o.validate&&(n=E(o.validate,(e=>{Q(String(e))}))(n,t,e)),o.required&&void 0===n&&Q("Missing required property"),p(n,""))o.maxLength&&n.length>o.maxLength&&(o.strict&&Q("Value exceeds maxLength"),n=n.substring(0,o.maxLength));else if(p(n,1))p(o.min,1)&&n<o.min?(o.strict&&Q("Value below min"),n=o.min):p(o.max,1)&&n>o.max&&(o.strict&&Q("Value exceeds max"),n=o.max);else if(p(n,{})){if(o.schema){const e=o.schema;Object.keys(e).reduce(((t,n)=>{const o=e[n];let i=t[n];return o&&(o.type&&typeof i!==o.type&&Q(`Type doesn't match (${n})`),i=E(se,(e=>{Q(String(e))}))(t,n,i,o)),i}),n)}for(const e of Object.keys(n))o.allowedKeys&&!o.allowedKeys.includes(e)&&(o.strict&&Q("Key not allowed"),delete n[e])}return n}export{o as Commands,i as Const,I as addDestination,e as anonymizeIP,n as assign,x as castToProperty,b as castValue,y as clone,A as commonHandleCommand,W as createEvent,M as createEventOrCommand,D as createPush,_ as createPushResult,$ as debounce,N as destinationInit,R as destinationPush,k as filterValues,ee as getBrowser,te as getBrowserVersion,m as getByPath,ie as getDeviceType,z as getEvent,K as getGrantedConsent,J as getHeaders,v as getId,O as getMappingEvent,S as getMappingValue,B as getMarketingParameters,ne as getOS,oe as getOSVersion,r as isArguments,s as isArray,c as isBoolean,a as isCommand,u as isDefined,l as isElementOrDocument,d as isNumber,f as isObject,w as isPropertyType,p as isSameType,g as isString,L as on,V as onApply,F as onLog,Z as parseUserAgent,T as pushToDestinations,H as requestToData,G as requestToParameter,h as setByPath,U as setConsent,P as throttle,Q as throwError,X as transformData,Y as trim,E as tryCatch,j as tryCatchAsync,q as useHooks,re as validateEvent,se as validateProperty};//# sourceMappingURL=index.mjs.map