@walkeros/collector 3.2.0 → 3.3.0-next-1776098542393

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r={};((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(r,{Code:()=>i,Commands:()=>a,Const:()=>c,addDestination:()=>P,callDestinationOn:()=>S,commonHandleCommand:()=>B,createEvent:()=>L,createPush:()=>z,createPushResult:()=>N,destinationInit:()=>_,destinationPush:()=>E,extractTransformerNextMap:()=>v,getCacheStore:()=>y,initDestinations:()=>M,initSource:()=>j,initSources:()=>A,mergeEnvironments:()=>H,on:()=>q,onApply:()=>D,processConsent:()=>l,pushToDestinations:()=>$,registerDestination:()=>R,runCollector:()=>V,runTransformerChain:()=>O,startFlow:()=>X,transformerInit:()=>w,transformerPush:()=>C,walkChain:()=>k,wrapEnv:()=>Z}),module.exports=(e=r,((e,r,i,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let c of o(r))s.call(e,c)||c===i||t(e,c,{get:()=>r[c],enumerable:!(a=n(r,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var i={},a={Action:"action",Actions:"actions",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",Shutdown:"shutdown",User:"user",Walker:"walker"},c={Commands:a,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}},u=require("@walkeros/core");function l(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=(0,u.assign)(e.consent,n),{update:n}}var f=require("@walkeros/core"),d=require("@walkeros/core"),g=require("@walkeros/core"),p=require("@walkeros/core"),h=require("@walkeros/core"),m=require("@walkeros/core");function y(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function v(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;e&&!(0,m.isRouteArray)(e)?t[n]={next:e}:t[n]={}}return t}function b(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function k(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function w(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:(0,m.createIngest)(n),config:t.config,env:x(t.config.env)};s.debug("init");const i=await(0,m.useHooks)(t.init,"TransformerInit",e.hooks)(r);if(!1===i)return!1;t.config={...i||t.config,env:i?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function C(e,t,n,o,s,r){const i=t.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:n,ingest:s,config:t.config,env:{...x(t.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,m.useHooks)(t.push,"TransformerPush",e.hooks)(o,c);return a.debug("push done"),u}async function O(e,t,n,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};s&&s._meta&&(s._meta.hops++,s._meta.path.push(o));if(!await(0,m.tryCatchAsync)(w)(e,r,o))return e.logger.error(`Transformer init failed: ${o}`),{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const t=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,l=u?(0,m.compileCache)(u):void 0,f=l?y(l,e):void 0;let d;if(l&&f){const e=(0,m.buildCacheContext)(s,a),t=(0,m.checkCache)(l,f,e,`t:${o}`);if("HIT"===t?.status&&t.value){if(a=t.value,l.full)return{event:a,respond:c};continue}"MISS"===t?.status&&(d={key:t.key,ttl:t.rule.ttl})}const g=r.config.before;if(g){const n=k("string"==typeof g||Array.isArray(g)&&!(0,m.isRouteArray)(g)?g:(0,m.resolveNext)((0,m.compileNext)(g),(0,m.buildCacheContext)(s,a))||void 0,v(t));if(n.length>0){const o=await O(e,t,n,a,s,c,i);if(null===o.event)return{event:null,respond:o.respond??c};o.respond&&(c=o.respond),a=Array.isArray(o.event)?o.event[0]:o.event}}const p=await(0,m.tryCatchAsync)(C,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,a,s,c);if(!1===p)return{event:null,respond:c};if(Array.isArray(p)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(p.map(async n=>{const o=n.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:(0,m.createIngest)("unknown");if(n.next){let s=n.next;if((0,m.isRouteArray)(n.next)){const e=(0,m.compileNext)(n.next);s=(0,m.resolveNext)(e,(0,m.buildCacheContext)(u,o))}if(s){const n=k(s,v(t));if(n.length>0)return O(e,t,n,o,u,c,i)}return{event:o,respond:c}}return r.length>0?O(e,t,r,o,u,c,i):{event:o,respond:c}}));let l=c;const f=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(l=t.respond),null===t.event)continue;Array.isArray(t.event)?f.push(...t.event):f.push(t.event)}else f.push(e);return 0===f.length?{event:null,respond:l}:1===f.length?{event:f[0],respond:l}:{event:f,respond:l}}if(p&&"object"==typeof p){const{event:n,respond:o,next:r}=p;if(o&&(c=o),r){let o=r;if((0,m.isRouteArray)(r)){const e=(0,m.compileNext)(r);if(o=(0,m.resolveNext)(e,(0,m.buildCacheContext)(s,a)),!o){n&&(a=n);continue}}const u=k(o,v(t));return u.length>0?O(e,t,u,n||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}n&&(a=n)}if(d&&f&&(0,m.storeCache)(f,d.key,a,d.ttl),(!p||"object"==typeof p&&!p.next)&&r.config.next&&(0,m.isRouteArray)(r.config.next)){const n=r.config.next,o=(0,m.compileNext)(n),u=(0,m.resolveNext)(o,(0,m.buildCacheContext)(s,a));if(u){const n=k(u,v(t));if(n.length>0)return O(e,t,n,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function x(e){return e&&(0,m.isObject)(e)?e:{}}async function j(e,t,n){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=n;let l,f=(0,h.createIngest)(t);const d=u?(0,h.compileCache)({...u,full:u.full??!0}):void 0,g=(0,h.compileNext)(a),p=!(Array.isArray(a)&&(0,h.isRouteArray)(a))&&g?k((0,h.resolveNext)(g),v(e.transformers)):void 0,m=(0,h.compileNext)(c),b=!(Array.isArray(c)&&(0,h.isRouteArray)(c))&&m?k((0,h.resolveNext)(m),v(e.transformers)):void 0,w=e.logger.scope("source").scope(t),C={push:async(n,o={})=>{let r=n;const i=b??(m?k((0,h.resolveNext)(m,(0,h.buildCacheContext)(f)),v(e.transformers)):[]);if(i.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,i,r,f,l,`source.${t}.before`);if(null===n.event)return{ok:!0};n.respond&&(l=n.respond),r=Array.isArray(n.event)?n.event[0]:n.event}if(d){const n=y(d,e);if(n){const e=(0,h.buildCacheContext)(f),o=(0,h.checkCache)(d,n,e,`s:${t}`);if(o){if("HIT"===o.status&&void 0!==o.value&&d.full){let t=o.value;return o.rule.update&&(t=await(0,h.applyUpdate)(t,o.rule.update,{...e,cache:{status:"HIT"}})),l?.(t),{ok:!0}}if("MISS"===o.status&&d.full&&l){const t=l,s=o.rule.update,r={...e,cache:{status:"MISS"}};l=e=>{(0,h.storeCache)(n,o.key,e,o.rule.ttl),s?(0,h.applyUpdate)(e,s,r).then(e=>t(e)):t(e)}}"MISS"!==o.status||d.full||(0,h.storeCache)(n,o.key,!0,o.rule.ttl)}}}const a=p??(g?k((0,h.resolveNext)(g,(0,h.buildCacheContext)(f)),v(e.transformers)):[]);return e.push(r,{...o,id:t,ingest:f,respond:l,mapping:s,preChain:a})},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:w,...r},x={collector:e,logger:w,id:t,config:s,env:C,setIngest:async n=>{if(!s.ingest)return void(f=(0,h.createIngest)(t));const o=await(0,h.getMappingValue)(n,s.ingest,{collector:e}),r=(0,h.createIngest)(t);f={...r,...o,_meta:r._meta}},setRespond:e=>{l=e}},j=await(0,h.tryCatchAsync)(o)(x);if(!j)return;const A=j.type||"unknown",q=e.logger.scope(A).scope(t);return C.logger=q,i&&(j.config={...j.config,primary:i}),j}async function A(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{config:t={}}=s;if(t.require&&t.require.length>0){e.pending.sources[o]=s;continue}const r=await j(e,o,s);r&&(n[o]=r)}return n}async function q(e,t,n){const o=e.on,s=o[t]||[],r=(0,g.isArray)(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,await D(e,t,r)}function S(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:n,config:t.config,data:s,env:H(t.env,t.config.env)};(0,p.tryCatch)(t.on)(o,a)}async function D(e,t,n,o){let s,r=n||[];switch(n||(r=e.on[t]||[]),t){case c.Commands.Consent:s=o||e.consent;break;case c.Commands.Session:s=e.session;break;case c.Commands.User:s=o||e.user;break;case c.Commands.Custom:s=o||e.custom;break;case c.Commands.Globals:s=o||e.globals;break;case c.Commands.Config:s=o||e.config;break;case c.Commands.Ready:case c.Commands.Run:default:s=void 0}let i=!1;for(const n of Object.values(e.sources))if(n.on){!1===await(0,p.tryCatchAsync)(n.on)(t,s)&&(i=!0)}if(Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:s});S(e,o,n,t,s)}}),(Object.keys(e.pending.sources).length>0||Object.keys(e.pending.destinations).length>0)&&await async function(e,t){for(const[n,o]of Object.entries(e.pending.sources)){if(!e.pending.sources[n]||e.sources[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.sources[n];const i=await j(e,n,o);i&&(e.sources[n]=i)}for(const[n,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[n]||e.destinations[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[n];const i=R(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[n]=i}}(e,t),!r.length)return!i;switch(t){case c.Commands.Consent:!function(e,t,n){const o=n||e.consent;t.forEach(t=>{Object.keys(o).filter(e=>e in t).forEach(n=>{(0,p.tryCatch)(t[n])(e,o)})})}(e,r,o);break;case c.Commands.Ready:case c.Commands.Run:!function(e,t){e.allowed&&t.forEach(t=>{(0,p.tryCatch)(t)(e)})}(e,r);break;case c.Commands.Session:!function(e,t){if(!e.session)return;t.forEach(t=>{(0,p.tryCatch)(t)(e,e.session)})}(e,r);break;default:r.forEach(t=>{"function"==typeof t&&(0,p.tryCatch)(t)(e,s)})}return!i}function I(e,t,n,o){if(!e)return[];if(t){const e=(0,d.resolveNext)(t,(0,d.buildCacheContext)(o));return e?k(e,v(n)):[]}return k(e,v(n))}async function P(e,t,n){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=t;if(!(0,d.isFunction)(o.push))return N({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=n||s||{init:!1};let l=i?{...u,before:i}:{...u};a&&(l={...l,next:a}),c&&(l={...l,cache:c});const f={...o,config:l,env:H(o.env,r)};let g=f.config.id;if(!g)do{g=(0,d.getId)(4)}while(e.destinations[g]);return e.destinations[g]=f,!1!==f.config.queue&&(f.queuePush=[...e.queue]),$(e,void 0,{},{[g]:f})}async function $(e,t,n={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return N({ok:!1});t&&(e.queue.push(t),e.status.in++),o||(o=e.destinations);const c=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let c=(s.queuePush||[]).map(e=>({...e,consent:r,user:a,globals:i}));s.queuePush=[];const u=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:(0,d.createIngest)("unknown");if(t){const e=(0,d.clone)(t);c.push(e)}if(!c.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!c.length&&s.queueOn?.length){const t=await(0,d.tryCatchAsync)(_)(e,s,o);return{id:o,destination:s,skipped:!t}}const l=[],f=c.filter(e=>{const t=(0,d.getGrantedConsent)(s.config.consent,r,e.consent);return!t||(e.consent=t,l.push(e),!1)});if(s.queuePush.push(...f),!l.length)return{id:o,destination:s,queue:c};if(!await(0,d.tryCatchAsync)(_)(e,s,o))return{id:o,destination:s,queue:c};let g,p;s.dlq||(s.dlq=[]);const h=s.config.before,m=I(h,h&&(0,d.isRouteArray)(h)?(0,d.compileNext)(h):void 0,e.transformers,u),v=s.config.next,b=v&&(0,d.isRouteArray)(v)?(0,d.compileNext)(v):void 0,k=s.config?.cache,w=k?(0,d.compileCache)(k):void 0,C=w?y(w,e):void 0;let x=0;return await Promise.all(l.map(async t=>{let r;if(w?.full&&C){const e=(0,d.buildCacheContext)(u,t),n=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let i=t,a=n.respond;if(m.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await O(e,e.transformers,m,t,u,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(a=s.respond),i=Array.isArray(s.event)?s.event[0]:s.event}if(w&&!w.full&&C){const e=(0,d.buildCacheContext)(u,i),n=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}const c=Date.now();let l=!1;const f=await(0,d.tryCatchAsync)(E,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:i.name}),g=t,l=!0,s.dlq.push([i,t])})(e,s,o,i,u,a);if(x+=Date.now()-c,r&&C&&void 0===s.config.mock&&(0,d.storeCache)(C,r.key,f??!0,r.ttl),void 0!==f&&(p=f),!l&&v){void 0!==f&&(u._response=f);const t=I(v,b,e.transformers,u);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,t,i,u,a,`destination.${o}.next`);n.respond&&(a=n.respond)}}return t})),{id:o,destination:s,error:g,response:p,totalDuration:x}})),u={},l={},f={};for(const t of c){if(t.skipped)continue;const n={type:t.destination.type||"unknown",data:t.response};e.status.destinations[t.id]||(e.status.destinations[t.id]={count:0,failed:0,duration:0});const o=e.status.destinations[t.id],s=Date.now();t.error?(n.error=t.error,f[t.id]=n,o.failed++,o.lastAt=s,o.duration+=t.totalDuration||0,e.status.failed++):t.queue&&t.queue.length?l[t.id]=n:(u[t.id]=n,o.count++,o.lastAt=s,o.duration+=t.totalDuration||0,e.status.out++)}return N({event:t,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(f).length&&{failed:f}})}async function _(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:H(t.env,t.config.env)};s.debug("init");const i=await(0,d.useHooks)(t.init,"DestinationInit",e.hooks)(r);if(!1===i)return i;if(t.config={...i||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)S(e,t,n,s,r)}s.debug("init done")}return!0}async function E(e,t,n,o,s,r){const{config:i}=t,a=await(0,d.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),l={collector:e,logger:u,id:n,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...H(t.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const f=a.mapping,g=a.mappingKey||"* *";if(!f?.batch||!t.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const n=await(0,d.useHooks)(t.push,"DestinationPush",e.hooks)(a.event,l);return u.debug("push done"),n}{if(t.batches=t.batches||{},!t.batches[g]){const o={key:g,events:[],data:[]};t.batches[g]={batched:o,batchFn:(0,d.debounce)(()=>{const o=t.batches[g].batched,a={collector:e,logger:u,id:n,config:i,data:void 0,rule:f,ingest:s,env:{...H(t.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,d.useHooks)(t.pushBatch,"DestinationPushBatch",e.hooks)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},f.batch)}}const o=t.batches[g];o.batched.events.push(a.event),(0,d.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function N(e){return{ok:!e?.failed,...e}}function R(e){const{code:t,config:n={},env:o={},cache:s}=e,{config:r}=b(e,"before"),{config:i}=b({...e,config:r},"next"),a={...t.config,...n,...i};s&&(a.cache=s);const c=H(t.env,o);return{...t,config:a,env:c}}async function M(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=R(s);return n}function H(e,t){return e||t?t?e&&(0,d.isObject)(e)&&(0,d.isObject)(t)?{...e,...t}:t:e:{}}var T=require("@walkeros/core"),G=require("@walkeros/core"),U=5e3;async function F(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=n.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((n,o)=>setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),U))])}catch(n){i.error(`${t} '${e}' destroy failed: ${n}`)}});await Promise.allSettled(o)}async function B(e,t,n,o){let s,r,i=!1;switch(t){case c.Commands.Config:(0,G.isObject)(n)&&((0,T.assign)(e.config,n,{shallow:!1}),r=n,i=!0);break;case c.Commands.Consent:if((0,G.isObject)(n)){const{update:t}=l(e,n);r=t,i=!0}break;case c.Commands.Custom:(0,G.isObject)(n)&&(e.custom=(0,T.assign)(e.custom,n),r=n,i=!0);break;case c.Commands.Destination:(0,G.isObject)(n)&&("code"in n&&(0,G.isObject)(n.code)?s=await P(e,n,o):(0,T.isFunction)(n.push)&&(s=await P(e,{code:n},o)));break;case c.Commands.Globals:(0,G.isObject)(n)&&(e.globals=(0,T.assign)(e.globals,n),r=n,i=!0);break;case c.Commands.On:(0,T.isString)(n)&&await q(e,n,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await V(e,n),i=!0;break;case c.Commands.Session:i=!0;break;case c.Commands.Shutdown:await async function(e){const t=e.logger;await F(e.sources,"source",t),await F(e.destinations,"destination",t),await F(e.transformers,"transformer",t),await F(e.stores,"store",t)}(e);break;case c.Commands.User:(0,G.isObject)(n)&&((0,T.assign)(e.user,n,{shallow:!1}),r=n,i=!0)}return i&&(await D(e,t,void 0,r),s=await $(e)),s||N({ok:!0})}function L(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");++e.count;const{timestamp:s=Date.now(),group:r=e.group,count:i=e.count}=t,{name:a=`${n} ${o}`,data:c={},context:u={},globals:l=e.globals,custom:f={},user:d=e.user,nested:g=[],consent:p=e.consent,id:h=`${s}-${r}-${i}`,trigger:m="",entity:y=n,action:v=o,timing:b=0,version:k={source:e.version,tagging:e.config.tagging||0},source:w={type:"collector",id:"",previous_id:""}}=t;return{name:a,data:c,context:u,globals:l,custom:f,user:d,nested:g,consent:p,id:h,trigger:m,entity:y,action:v,timestamp:s,timing:b,group:r,count:i,version:k,source:w}}async function V(e,t){e.allowed=!0,e.count=0,e.group=(0,T.getId)(),e.timing=Date.now(),t&&(t.consent&&(e.consent=(0,T.assign)(e.consent,t.consent)),t.user&&(e.user=(0,T.assign)(e.user,t.user)),t.globals&&(e.globals=(0,T.assign)(e.config.globalsStatic||{},t.globals)),t.custom&&(e.custom=(0,T.assign)(e.custom,t.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await $(e)}var W=require("@walkeros/core");function z(e,t){return(0,W.useHooks)(async(n,o={})=>await(0,W.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:l,exclude:f}=o;let d=a,g=n;const p=l||f?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,l,f):void 0,h=i??(0,W.createIngest)(r||"unknown");if(c){const t=await(0,W.processEventMapping)(g,c,e);if(t.ignore)return N({ok:!0});if(c.consent){if(!(0,W.getGrantedConsent)(c.consent,e.consent,t.event.consent))return N({ok:!0})}g=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,u,g,h,d,r?`source.${r}.next`:void 0);if(null===n.event)return N({ok:!0});if(n.respond&&(d=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=L(e,o);return $(e,s,{id:r,ingest:h,respond:d},p)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??N({ok:!0})}g=n.event}const m=t(g),y=L(e,m),v=await $(e,y,{id:r,ingest:h,respond:d},p);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return v},()=>N({ok:!1}))(),"Push",e.hooks)}var J=require("@walkeros/core");var K=require("@walkeros/core");async function Q(e){const t=(0,f.assign)({globalsStatic:{},sessionStatic:{},tagging:0,run:!0},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=(0,f.createLogger)(n),s={...t.globalsStatic,...e.globals},r={allowed:!1,config:t,consent:e.consent||{},count:0,custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,group:"",hooks:e.hooks||{},logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{}},timing:Date.now(),user:e.user||{},version:"3.1.1",sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};r.push=z(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",id:"",previous_id:""},...e})),r.command=function(e,t){return(0,J.useHooks)(async(n,o,s)=>await(0,J.tryCatchAsync)(async()=>await t(e,n,o,s),()=>N({ok:!1}))(),"Command",e.hooks)}(r,B);const i=e.stores||{};if(r.stores=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await t(c),l=u.get,f=u.set,d=u.delete;u.get=(0,K.useHooks)(l,"StoreGet",e.hooks),u.set=(0,K.useHooks)(f,"StoreSet",e.hooks),u.delete=(0,K.useHooks)(d,"StoreDelete",e.hooks),n[o]=u}return n}(r,i),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(i,r.stores,e),!r.stores.__cache){const e=new Map;r.stores.__cache={type:"memory",config:{},get:t=>{const n=e.get(t);if(n){if(!(n.expires&&Date.now()>n.expires))return n.value;e.delete(t)}},set:(t,n,o)=>{e.set(t,{value:n,expires:o?Date.now()+o:void 0})},delete:t=>{e.delete(t)}}}return r.destinations=await M(r,e.destinations||{}),r.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,{config:i}=b(s,"before"),{config:a}=b({...s,config:i},"next"),c=Object.keys(r).length>0?{...a,env:r}:a,{cache:u}=s,l=u?{...c,cache:u}:c,f=e.logger.scope("transformer").scope(o),d={collector:e,logger:f,id:o,ingest:(0,m.createIngest)(o),config:l,env:r},g=await t(d);n[o]=g}return n}(r,e.transformers||{}),r}async function X(e){e=e||{};const t=await Q(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,t,n)}let a;if("string"==typeof e)a={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(a.data=t);else{if(!e||"object"!=typeof e)return N({ok:!1});a=e,t&&"object"==typeof t&&!Array.isArray(t)&&(a.data={...a.data||{},...t})}return s&&"object"==typeof s&&(a.context=s),r&&Array.isArray(r)&&(a.nested=r),i&&"object"==typeof i&&(a.custom=i),o.push(a)}});var o;t.sources.elb=n;const s=await A(t,e.sources||{});Object.assign(t.sources,s);const{consent:r,user:i,globals:a,custom:c}=e;r&&await t.command("consent",r),i&&await t.command("user",i),a&&Object.assign(t.globals,a),c&&Object.assign(t.custom,c),t.config.run&&await t.command("run");let u=n.push;const l=Object.values(t.sources).filter(e=>"elb"!==e.type),f=l.find(e=>e.config.primary);return f?u=f.push:l.length>0&&(u=l[0].push),{collector:t,elb:u}}function Y(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Y);const t={};for(const[n,o]of Object.entries(e))t[n]="function"==typeof o?o:Y(o);return t}function Z(e){const t=[],{simulation:n,...o}=e,s=Y(o);for(const e of n){const n=e.startsWith("call:")?e.slice(5):e,o=n.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const i=o[o.length-1];if(null==r||!(i in r))continue;const a=r[i];"function"==typeof a&&(r[i]=function(...e){return t.push({fn:n,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:t}}//# sourceMappingURL=index.js.map
1
+ "use strict";var e,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r={};((e,n)=>{for(var o in n)t(e,o,{get:n[o],enumerable:!0})})(r,{Code:()=>i,Commands:()=>a,Const:()=>c,addDestination:()=>P,callDestinationOn:()=>S,commonHandleCommand:()=>B,createEvent:()=>L,createPush:()=>z,createPushResult:()=>N,destinationInit:()=>_,destinationPush:()=>E,extractTransformerNextMap:()=>v,getCacheStore:()=>y,initDestinations:()=>M,initSource:()=>j,initSources:()=>A,mergeEnvironments:()=>H,on:()=>q,onApply:()=>D,processConsent:()=>l,pushToDestinations:()=>$,registerDestination:()=>R,runCollector:()=>V,runTransformerChain:()=>O,startFlow:()=>X,transformerInit:()=>w,transformerPush:()=>C,walkChain:()=>k,wrapEnv:()=>Z}),module.exports=(e=r,((e,r,i,a)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let c of o(r))s.call(e,c)||c===i||t(e,c,{get:()=>r[c],enumerable:!(a=n(r,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var i={},a={Action:"action",Actions:"actions",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",Shutdown:"shutdown",User:"user",Walker:"walker"},c={Commands:a,Utils:{Storage:{Cookie:"cookie",Local:"local",Session:"session"}}},u=require("@walkeros/core");function l(e,t){const n={};return Object.entries(t).forEach(([e,t])=>{n[e]=!!t}),e.consent=(0,u.assign)(e.consent,n),{update:n}}var f=require("@walkeros/core"),d=require("@walkeros/core"),g=require("@walkeros/core"),p=require("@walkeros/core"),h=require("@walkeros/core"),m=require("@walkeros/core");function y(e,t){return e.storeId&&t.stores[e.storeId]?t.stores[e.storeId]:t.stores.__cache}function v(e){const t={};for(const[n,o]of Object.entries(e)){const e=o.config?.next;e&&!(0,m.isRouteArray)(e)?t[n]={next:e}:t[n]={}}return t}function b(e,t){const n=e.config||{},o=e[t];return void 0!==o?{config:{...n,[t]:o},chainValue:o}:{config:n,chainValue:void 0}}function k(e,t={}){if(!e)return[];if(Array.isArray(e))return e;const n=[],o=new Set;let s=e;for(;s&&t[s]&&!o.has(s);){o.add(s),n.push(s);const e=t[s].next;if(Array.isArray(e)){n.push(...e);break}s=e}return n}async function w(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:n,ingest:(0,m.createIngest)(n),config:t.config,env:x(t.config.env)};s.debug("init");const i=await(0,m.useHooks)(t.init,"TransformerInit",e.hooks)(r);if(!1===i)return!1;t.config={...i||t.config,env:i?.env||t.config.env,init:!0},s.debug("init done")}return!0}async function C(e,t,n,o,s,r){const i=t.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:n,ingest:s,config:t.config,env:{...x(t.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,m.useHooks)(t.push,"TransformerPush",e.hooks)(o,c);return a.debug("push done"),u}async function O(e,t,n,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of n){const r=t[o];if(!r){e.logger.warn(`Transformer not found: ${o}`);continue}if(s&&s._meta&&s._meta.path.length>256)return e.logger.error(`Max path length exceeded at ${o}`),{event:null,respond:c};s&&s._meta&&(s._meta.hops++,s._meta.path.push(o));if(!await(0,m.tryCatchAsync)(w)(e,r,o))return e.logger.error(`Transformer init failed: ${o}`),{event:null,respond:c};if(i&&void 0!==r.config?.chainMocks?.[i]){const t=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=t;continue}if(void 0!==r.config?.mock){e.logger.scope(`transformer:${r.type||"unknown"}`).debug("mock"),a=r.config.mock;continue}if(r.config?.disabled)continue;const u=r.config?.cache,l=u?(0,m.compileCache)(u):void 0,f=l?y(l,e):void 0;let d;if(l&&f){const e=(0,m.buildCacheContext)(s,a),t=(0,m.checkCache)(l,f,e,`t:${o}`);if("HIT"===t?.status&&t.value){if(a=t.value,l.full)return{event:a,respond:c};continue}"MISS"===t?.status&&(d={key:t.key,ttl:t.rule.ttl})}const g=r.config.before;if(g){const n=k("string"==typeof g||Array.isArray(g)&&!(0,m.isRouteArray)(g)?g:(0,m.resolveNext)((0,m.compileNext)(g),(0,m.buildCacheContext)(s,a))||void 0,v(t));if(n.length>0){const o=await O(e,t,n,a,s,c,i);if(null===o.event)return{event:null,respond:o.respond??c};o.respond&&(c=o.respond),a=Array.isArray(o.event)?o.event[0]:o.event}}const p=await(0,m.tryCatchAsync)(C,t=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:t}),!1))(e,r,o,a,s,c);if(!1===p)return{event:null,respond:c};if(Array.isArray(p)){const r=n.slice(n.indexOf(o)+1),u=await Promise.all(p.map(async n=>{const o=n.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:(0,m.createIngest)("unknown");if(n.next){let s=n.next;if((0,m.isRouteArray)(n.next)){const e=(0,m.compileNext)(n.next);s=(0,m.resolveNext)(e,(0,m.buildCacheContext)(u,o))}if(s){const n=k(s,v(t));if(n.length>0)return O(e,t,n,o,u,c,i)}return{event:o,respond:c}}return r.length>0?O(e,t,r,o,u,c,i):{event:o,respond:c}}));let l=c;const f=[];for(const e of u.flat())if(null!==e)if(e&&"object"==typeof e&&"event"in e){const t=e;if(t.respond&&(l=t.respond),null===t.event)continue;Array.isArray(t.event)?f.push(...t.event):f.push(t.event)}else f.push(e);return 0===f.length?{event:null,respond:l}:1===f.length?{event:f[0],respond:l}:{event:f,respond:l}}if(p&&"object"==typeof p){const{event:n,respond:o,next:r}=p;if(o&&(c=o),r){let o=r;if((0,m.isRouteArray)(r)){const e=(0,m.compileNext)(r);if(o=(0,m.resolveNext)(e,(0,m.buildCacheContext)(s,a)),!o){n&&(a=n);continue}}const u=k(o,v(t));return u.length>0?O(e,t,u,n||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}n&&(a=n)}if(d&&f&&(0,m.storeCache)(f,d.key,a,d.ttl),(!p||"object"==typeof p&&!p.next)&&r.config.next&&(0,m.isRouteArray)(r.config.next)){const n=r.config.next,o=(0,m.compileNext)(n),u=(0,m.resolveNext)(o,(0,m.buildCacheContext)(s,a));if(u){const n=k(u,v(t));if(n.length>0)return O(e,t,n,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function x(e){return e&&(0,m.isObject)(e)?e:{}}async function j(e,t,n){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=n;let l,f=(0,h.createIngest)(t);const d=u?(0,h.compileCache)({...u,full:u.full??!0}):void 0,g=(0,h.compileNext)(a),p=!(Array.isArray(a)&&(0,h.isRouteArray)(a))&&g?k((0,h.resolveNext)(g),v(e.transformers)):void 0,m=(0,h.compileNext)(c),b=!(Array.isArray(c)&&(0,h.isRouteArray)(c))&&m?k((0,h.resolveNext)(m),v(e.transformers)):void 0,w=e.logger.scope("source").scope(t),C={push:async(n,o={})=>{let r=n;const i=b??(m?k((0,h.resolveNext)(m,(0,h.buildCacheContext)(f)),v(e.transformers)):[]);if(i.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,i,r,f,l,`source.${t}.before`);if(null===n.event)return{ok:!0};n.respond&&(l=n.respond),r=Array.isArray(n.event)?n.event[0]:n.event}if(d){const n=y(d,e);if(n){const e=(0,h.buildCacheContext)(f),o=(0,h.checkCache)(d,n,e,`s:${t}`);if(o){if("HIT"===o.status&&void 0!==o.value&&d.full){let t=o.value;return o.rule.update&&(t=await(0,h.applyUpdate)(t,o.rule.update,{...e,cache:{status:"HIT"}})),l?.(t),{ok:!0}}if("MISS"===o.status&&d.full&&l){const t=l,s=o.rule.update,r={...e,cache:{status:"MISS"}};l=e=>{(0,h.storeCache)(n,o.key,e,o.rule.ttl),s?(0,h.applyUpdate)(e,s,r).then(e=>t(e)):t(e)}}"MISS"!==o.status||d.full||(0,h.storeCache)(n,o.key,!0,o.rule.ttl)}}}const a=p??(g?k((0,h.resolveNext)(g,(0,h.buildCacheContext)(f)),v(e.transformers)):[]);return e.push(r,{...o,id:t,ingest:f,respond:l,mapping:s,preChain:a})},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:w,...r},x={collector:e,logger:w,id:t,config:s,env:C,setIngest:async n=>{if(!s.ingest)return void(f=(0,h.createIngest)(t));const o=await(0,h.getMappingValue)(n,s.ingest,{collector:e}),r=(0,h.createIngest)(t);f={...r,...o,_meta:r._meta}},setRespond:e=>{l=e}},j=await(0,h.tryCatchAsync)(o)(x);if(!j)return;const A=j.type||"unknown",q=e.logger.scope(A).scope(t);return C.logger=q,i&&(j.config={...j.config,primary:i}),j}async function A(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{config:t={}}=s;if(t.require&&t.require.length>0){e.pending.sources[o]=s;continue}const r=await j(e,o,s);r&&(n[o]=r)}return n}async function q(e,t,n){const o=e.on,s=o[t]||[],r=(0,g.isArray)(n)?n:[n];r.forEach(e=>{s.push(e)}),o[t]=s,await D(e,t,r)}function S(e,t,n,o,s){if(!t.on)return;const r=t.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:n,config:t.config,data:s,env:H(t.env,t.config.env)};(0,p.tryCatch)(t.on)(o,a)}async function D(e,t,n,o){let s,r=n||[];switch(n||(r=e.on[t]||[]),t){case c.Commands.Consent:s=o||e.consent;break;case c.Commands.Session:s=e.session;break;case c.Commands.User:s=o||e.user;break;case c.Commands.Custom:s=o||e.custom;break;case c.Commands.Globals:s=o||e.globals;break;case c.Commands.Config:s=o||e.config;break;case c.Commands.Ready:case c.Commands.Run:default:s=void 0}let i=!1;for(const n of Object.values(e.sources))if(n.on){!1===await(0,p.tryCatchAsync)(n.on)(t,s)&&(i=!0)}if(Object.entries(e.destinations).forEach(([n,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:t,data:s});S(e,o,n,t,s)}}),(Object.keys(e.pending.sources).length>0||Object.keys(e.pending.destinations).length>0)&&await async function(e,t){for(const[n,o]of Object.entries(e.pending.sources)){if(!e.pending.sources[n]||e.sources[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.sources[n];const i=await j(e,n,o);i&&(e.sources[n]=i)}for(const[n,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[n]||e.destinations[n])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(t);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[n];const i=R(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[n]=i}}(e,t),!r.length)return!i;switch(t){case c.Commands.Consent:!function(e,t,n){const o=n||e.consent;t.forEach(t=>{Object.keys(o).filter(e=>e in t).forEach(n=>{(0,p.tryCatch)(t[n])(e,o)})})}(e,r,o);break;case c.Commands.Ready:case c.Commands.Run:!function(e,t){e.allowed&&t.forEach(t=>{(0,p.tryCatch)(t)(e)})}(e,r);break;case c.Commands.Session:!function(e,t){if(!e.session)return;t.forEach(t=>{(0,p.tryCatch)(t)(e,e.session)})}(e,r);break;default:r.forEach(t=>{"function"==typeof t&&(0,p.tryCatch)(t)(e,s)})}return!i}function I(e,t,n,o){if(!e)return[];if(t){const e=(0,d.resolveNext)(t,(0,d.buildCacheContext)(o));return e?k(e,v(n)):[]}return k(e,v(n))}async function P(e,t,n){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=t;if(!(0,d.isFunction)(o.push))return N({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=n||s||{init:!1};let l=i?{...u,before:i}:{...u};a&&(l={...l,next:a}),c&&(l={...l,cache:c});const f={...o,config:l,env:H(o.env,r)};let g=f.config.id;if(!g)do{g=(0,d.getId)(4)}while(e.destinations[g]);return e.destinations[g]=f,!1!==f.config.queue&&(f.queuePush=[...e.queue]),$(e,void 0,{},{[g]:f})}async function $(e,t,n={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return N({ok:!1});t&&(e.queue.push(t),e.status.in++),o||(o=e.destinations);const c=await Promise.all(Object.entries(o||{}).map(async([o,s])=>{if(s.config.disabled)return{id:o,destination:s,skipped:!0};let c=(s.queuePush||[]).map(e=>({...e,consent:r}));s.queuePush=[],t&&c.push((0,d.clone)(t));const u=n.ingest?{...n.ingest,_meta:{...n.ingest._meta,path:[...n.ingest._meta.path]}}:(0,d.createIngest)("unknown");if(!c.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!c.length&&s.queueOn?.length){const t=await(0,d.tryCatchAsync)(_)(e,s,o);return{id:o,destination:s,skipped:!t}}const l=[],f=c.filter(e=>{const t=(0,d.getGrantedConsent)(s.config.consent,r,e.consent);return!t||(e.consent=t,l.push(e),!1)});if(s.queuePush.push(...f),!l.length)return{id:o,destination:s,queue:c};if(!await(0,d.tryCatchAsync)(_)(e,s,o))return{id:o,destination:s,queue:c};let g,p;s.dlq||(s.dlq=[]);const h=s.config.before,m=I(h,h&&(0,d.isRouteArray)(h)?(0,d.compileNext)(h):void 0,e.transformers,u),v=s.config.next,b=v&&(0,d.isRouteArray)(v)?(0,d.compileNext)(v):void 0,k=s.config?.cache,w=k?(0,d.compileCache)(k):void 0,C=w?y(w,e):void 0;let x=0;return await Promise.all(l.map(async t=>{let r;if(t.globals=(0,d.assign)(i,t.globals),t.user=(0,d.assign)(a,t.user),w?.full&&C){const e=(0,d.buildCacheContext)(u,t),n=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}let c=t,l=n.respond;if(m.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await O(e,e.transformers,m,t,u,n.respond,`destination.${o}.before`);if(null===s.event)return t;s.respond&&(l=s.respond),c=Array.isArray(s.event)?s.event[0]:s.event}if(w&&!w.full&&C){const e=(0,d.buildCacheContext)(u,c),n=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===n?.status)return t;"MISS"===n?.status&&(r={key:n.key,ttl:n.rule.ttl})}const f=Date.now();let h=!1;const y=await(0,d.tryCatchAsync)(E,t=>{const n=s.type||"unknown";e.logger.scope(n).error("Push failed",{error:t,event:c.name}),g=t,h=!0,s.dlq.push([c,t])})(e,s,o,c,u,l);if(x+=Date.now()-f,r&&C&&void 0===s.config.mock&&(0,d.storeCache)(C,r.key,y??!0,r.ttl),void 0!==y&&(p=y),!h&&v){void 0!==y&&(u._response=y);const t=I(v,b,e.transformers,u);if(t.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,t,c,u,l,`destination.${o}.next`);n.respond&&(l=n.respond)}}return t})),{id:o,destination:s,error:g,response:p,totalDuration:x}})),u={},l={},f={};for(const t of c){if(t.skipped)continue;const n={type:t.destination.type||"unknown",data:t.response};e.status.destinations[t.id]||(e.status.destinations[t.id]={count:0,failed:0,duration:0});const o=e.status.destinations[t.id],s=Date.now();t.error?(n.error=t.error,f[t.id]=n,o.failed++,o.lastAt=s,o.duration+=t.totalDuration||0,e.status.failed++):t.queue&&t.queue.length?l[t.id]=n:(u[t.id]=n,o.count++,o.lastAt=s,o.duration+=t.totalDuration||0,e.status.out++)}return N({event:t,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(f).length&&{failed:f}})}async function _(e,t,n){if(t.init&&!t.config.init){const o=t.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:n,config:t.config,env:H(t.env,t.config.env)};s.debug("init");const i=await(0,d.useHooks)(t.init,"DestinationInit",e.hooks)(r);if(!1===i)return i;if(t.config={...i||t.config,init:!0},t.queueOn?.length){const o=t.queueOn;t.queueOn=[];for(const{type:s,data:r}of o)S(e,t,n,s,r)}s.debug("init done")}return!0}async function E(e,t,n,o,s,r){const{config:i}=t,a=await(0,d.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=t.type||"unknown",u=e.logger.scope(c),l={collector:e,logger:u,id:n,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...H(t.env,i.env),...r?{respond:r}:{}}};if(void 0!==i.mock)return u.debug("mock",{event:a.event.name}),i.mock;const f=a.mapping,g=a.mappingKey||"* *";if(!f?.batch||!t.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const n=await(0,d.useHooks)(t.push,"DestinationPush",e.hooks)(a.event,l);return u.debug("push done"),n}{if(t.batches=t.batches||{},!t.batches[g]){const o={key:g,events:[],data:[]};t.batches[g]={batched:o,batchFn:(0,d.debounce)(()=>{const o=t.batches[g].batched,a={collector:e,logger:u,id:n,config:i,data:void 0,rule:f,ingest:s,env:{...H(t.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,d.useHooks)(t.pushBatch,"DestinationPushBatch",e.hooks)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},f.batch)}}const o=t.batches[g];o.batched.events.push(a.event),(0,d.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function N(e){return{ok:!e?.failed,...e}}function R(e){const{code:t,config:n={},env:o={},cache:s}=e,{config:r}=b(e,"before"),{config:i}=b({...e,config:r},"next"),a={...t.config,...n,...i};s&&(a.cache=s);const c=H(t.env,o);return{...t,config:a,env:c}}async function M(e,t={}){const n={};for(const[o,s]of Object.entries(t))s.config?.require?.length?e.pending.destinations[o]=s:n[o]=R(s);return n}function H(e,t){return e||t?t?e&&(0,d.isObject)(e)&&(0,d.isObject)(t)?{...e,...t}:t:e:{}}var T=require("@walkeros/core"),G=require("@walkeros/core"),U=5e3;async function F(e,t,n){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=n.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((n,o)=>setTimeout(()=>o(new Error(`${t} '${e}' destroy timed out`)),U))])}catch(n){i.error(`${t} '${e}' destroy failed: ${n}`)}});await Promise.allSettled(o)}async function B(e,t,n,o){let s,r,i=!1;switch(t){case c.Commands.Config:(0,G.isObject)(n)&&((0,T.assign)(e.config,n,{shallow:!1}),r=n,i=!0);break;case c.Commands.Consent:if((0,G.isObject)(n)){const{update:t}=l(e,n);r=t,i=!0}break;case c.Commands.Custom:(0,G.isObject)(n)&&(e.custom=(0,T.assign)(e.custom,n),r=n,i=!0);break;case c.Commands.Destination:(0,G.isObject)(n)&&("code"in n&&(0,G.isObject)(n.code)?s=await P(e,n,o):(0,T.isFunction)(n.push)&&(s=await P(e,{code:n},o)));break;case c.Commands.Globals:(0,G.isObject)(n)&&(e.globals=(0,T.assign)(e.globals,n),r=n,i=!0);break;case c.Commands.On:(0,T.isString)(n)&&await q(e,n,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await V(e,n),i=!0;break;case c.Commands.Session:i=!0;break;case c.Commands.Shutdown:await async function(e){const t=e.logger;await F(e.sources,"source",t),await F(e.destinations,"destination",t),await F(e.transformers,"transformer",t),await F(e.stores,"store",t)}(e);break;case c.Commands.User:(0,G.isObject)(n)&&((0,T.assign)(e.user,n,{shallow:!1}),r=n,i=!0)}return i&&(await D(e,t,void 0,r),s=await $(e)),s||N({ok:!0})}function L(e,t){if(!t.name)throw new Error("Event name is required");const[n,o]=t.name.split(" ");if(!n||!o)throw new Error("Event name is invalid");++e.count;const{timestamp:s=Date.now(),group:r=e.group,count:i=e.count}=t,{name:a=`${n} ${o}`,data:c={},context:u={},globals:l=e.globals,custom:f={},user:d=e.user,nested:g=[],consent:p=e.consent,id:h=`${s}-${r}-${i}`,trigger:m="",entity:y=n,action:v=o,timing:b=0,version:k={source:e.version,tagging:e.config.tagging||0},source:w={type:"collector",id:"",previous_id:""}}=t;return{name:a,data:c,context:u,globals:l,custom:f,user:d,nested:g,consent:p,id:h,trigger:m,entity:y,action:v,timestamp:s,timing:b,group:r,count:i,version:k,source:w}}async function V(e,t){e.allowed=!0,e.count=0,e.group=(0,T.getId)(),e.timing=Date.now(),t&&(t.consent&&(e.consent=(0,T.assign)(e.consent,t.consent)),t.user&&(e.user=(0,T.assign)(e.user,t.user)),t.globals&&(e.globals=(0,T.assign)(e.config.globalsStatic||{},t.globals)),t.custom&&(e.custom=(0,T.assign)(e.custom,t.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await $(e)}var W=require("@walkeros/core");function z(e,t){return(0,W.useHooks)(async(n,o={})=>await(0,W.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u,include:l,exclude:f}=o;let d=a,g=n;const p=l||f?function(e,t,n){let o=e;return t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>t.includes(e)))),n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!n.includes(e)))),o}(e.destinations,l,f):void 0,h=i??(0,W.createIngest)(r||"unknown");if(c){const t=await(0,W.processEventMapping)(g,c,e);if(t.ignore)return N({ok:!0});if(c.consent){if(!(0,W.getGrantedConsent)(c.consent,e.consent,t.event.consent))return N({ok:!0})}g=t.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,u,g,h,d,r?`source.${r}.next`:void 0);if(null===n.event)return N({ok:!0});if(n.respond&&(d=n.respond),Array.isArray(n.event)){const o=await Promise.all(n.event.map(async n=>{const o=t(n),s=L(e,o);return $(e,s,{id:r,ingest:h,respond:d},p)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count+=n.event.length,t.lastAt=Date.now(),t.duration+=Date.now()-s}return o[0]??N({ok:!0})}g=n.event}const m=t(g),y=L(e,m),v=await $(e,y,{id:r,ingest:h,respond:d},p);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const t=e.status.sources[r];t.count++,t.lastAt=Date.now(),t.duration+=Date.now()-s}return v},()=>N({ok:!1}))(),"Push",e.hooks)}var J=require("@walkeros/core");var K=require("@walkeros/core");async function Q(e){const t=(0,f.assign)({globalsStatic:{},sessionStatic:{},tagging:0,run:!0},e,{merge:!1,extend:!1}),n={level:e.logger?.level,handler:e.logger?.handler},o=(0,f.createLogger)(n),s={...t.globalsStatic,...e.globals},r={allowed:!1,config:t,consent:e.consent||{},count:0,custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,group:"",hooks:e.hooks||{},logger:o,on:{},queue:[],round:0,session:void 0,status:{startedAt:Date.now(),in:0,out:0,failed:0,sources:{},destinations:{}},timing:Date.now(),user:e.user||{},version:"3.2.0",sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};r.push=z(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",id:"",previous_id:""},...e})),r.command=function(e,t){return(0,J.useHooks)(async(n,o,s)=>await(0,J.tryCatchAsync)(async()=>await t(e,n,o,s),()=>N({ok:!1}))(),"Command",e.hooks)}(r,B);const i=e.stores||{};if(r.stores=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,config:r={},env:i={}}=s,a=e.logger.scope("store").scope(o),c={collector:e,logger:a,id:o,config:r,env:i},u=await t(c),l=u.get,f=u.set,d=u.delete;u.get=(0,K.useHooks)(l,"StoreGet",e.hooks),u.set=(0,K.useHooks)(f,"StoreSet",e.hooks),u.delete=(0,K.useHooks)(d,"StoreDelete",e.hooks),n[o]=u}return n}(r,i),function(e,t,n){const o=new Map;for(const[n,s]of Object.entries(e))t[n]&&o.set(s,t[n]);if(0!==o.size)for(const e of[n.transformers,n.destinations,n.sources])if(e)for(const t of Object.values(e))s(t.env);function s(e){if(e)for(const[t,n]of Object.entries(e))if("object"==typeof n&&null!==n){const s=o.get(n);s&&(e[t]=s)}}}(i,r.stores,e),!r.stores.__cache){const e=new Map;r.stores.__cache={type:"memory",config:{},get:t=>{const n=e.get(t);if(n){if(!(n.expires&&Date.now()>n.expires))return n.value;e.delete(t)}},set:(t,n,o)=>{e.set(t,{value:n,expires:o?Date.now()+o:void 0})},delete:t=>{e.delete(t)}}}return r.destinations=await M(r,e.destinations||{}),r.transformers=await async function(e,t={}){const n={};for(const[o,s]of Object.entries(t)){const{code:t,env:r={}}=s,{config:i}=b(s,"before"),{config:a}=b({...s,config:i},"next"),c=Object.keys(r).length>0?{...a,env:r}:a,{cache:u}=s,l=u?{...c,cache:u}:c,f=e.logger.scope("transformer").scope(o),d={collector:e,logger:f,id:o,ingest:(0,m.createIngest)(o),config:l,env:r},g=await t(d);n[o]=g}return n}(r,e.transformers||{}),r}async function X(e){e=e||{};const t=await Q(e),n=(o=t,{type:"elb",config:{},push:async(e,t,n,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,t,n)}let a;if("string"==typeof e)a={name:e},t&&"object"==typeof t&&!Array.isArray(t)&&(a.data=t);else{if(!e||"object"!=typeof e)return N({ok:!1});a=e,t&&"object"==typeof t&&!Array.isArray(t)&&(a.data={...a.data||{},...t})}return s&&"object"==typeof s&&(a.context=s),r&&Array.isArray(r)&&(a.nested=r),i&&"object"==typeof i&&(a.custom=i),o.push(a)}});var o;t.sources.elb=n;const s=await A(t,e.sources||{});Object.assign(t.sources,s);const{consent:r,user:i,globals:a,custom:c}=e;r&&await t.command("consent",r),i&&await t.command("user",i),a&&Object.assign(t.globals,a),c&&Object.assign(t.custom,c),t.config.run&&await t.command("run");let u=n.push;const l=Object.values(t.sources).filter(e=>"elb"!==e.type),f=l.find(e=>e.config.primary);return f?u=f.push:l.length>0&&(u=l[0].push),{collector:t,elb:u}}function Y(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Y);const t={};for(const[n,o]of Object.entries(e))t[n]="function"==typeof o?o:Y(o);return t}function Z(e){const t=[],{simulation:n,...o}=e,s=Y(o);for(const e of n){const n=e.startsWith("call:")?e.slice(5):e,o=n.split(".");let r=s;for(let e=0;e<o.length-1&&null!=r[o[e]];e++)r=r[o[e]];const i=o[o.length-1];if(null==r||!(i in r))continue;const a=r[i];"function"==typeof a&&(r[i]=function(...e){return t.push({fn:n,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:t}}//# sourceMappingURL=index.js.map