@walkeros/collector 4.0.0 → 4.0.1-next-1778183328892
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.d.mts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -209,6 +209,18 @@ declare function callDestinationOn(collector: Collector.Instance, destination: D
|
|
|
209
209
|
*/
|
|
210
210
|
declare function onApply(collector: Collector.Instance, type: On.Types, options?: Array<On.Subscription>, config?: unknown): Promise<boolean>;
|
|
211
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Flush a source's queueOn buffer. Called when the source becomes "started"
|
|
214
|
+
* (config.init === true AND config.require is empty/absent). Idempotent:
|
|
215
|
+
* the buffer is cleared before iteration, so re-entry from within an `on`
|
|
216
|
+
* handler does not re-fire the same items.
|
|
217
|
+
*/
|
|
218
|
+
declare function flushSourceQueueOn(collector: Collector.Instance, source: Source.Instance): Promise<void>;
|
|
219
|
+
/**
|
|
220
|
+
* A source is "started" — eligible to receive on() events directly — when
|
|
221
|
+
* its init has run and any require gate is satisfied.
|
|
222
|
+
*/
|
|
223
|
+
declare function isSourceStarted(source: Source.Instance): boolean;
|
|
212
224
|
/**
|
|
213
225
|
* Initialize a single source. Extracted from the initSources loop body
|
|
214
226
|
* so it can be reused by the pending-source activator.
|
|
@@ -316,4 +328,4 @@ declare function wrapEnv(env: Record<string, unknown> & {
|
|
|
316
328
|
*/
|
|
317
329
|
declare function getCacheStore(compiled: CompiledCache, collector: Collector.Instance): Store.Instance | undefined;
|
|
318
330
|
|
|
319
|
-
export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, getCacheStore, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, runTransformerChain, startFlow, transformerInit, transformerPush, walkChain, wrapEnv };
|
|
331
|
+
export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, flushSourceQueueOn, getCacheStore, initDestinations, initSource, initSources, isSourceStarted, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, runTransformerChain, startFlow, transformerInit, transformerPush, walkChain, wrapEnv };
|
package/dist/index.d.ts
CHANGED
|
@@ -209,6 +209,18 @@ declare function callDestinationOn(collector: Collector.Instance, destination: D
|
|
|
209
209
|
*/
|
|
210
210
|
declare function onApply(collector: Collector.Instance, type: On.Types, options?: Array<On.Subscription>, config?: unknown): Promise<boolean>;
|
|
211
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Flush a source's queueOn buffer. Called when the source becomes "started"
|
|
214
|
+
* (config.init === true AND config.require is empty/absent). Idempotent:
|
|
215
|
+
* the buffer is cleared before iteration, so re-entry from within an `on`
|
|
216
|
+
* handler does not re-fire the same items.
|
|
217
|
+
*/
|
|
218
|
+
declare function flushSourceQueueOn(collector: Collector.Instance, source: Source.Instance): Promise<void>;
|
|
219
|
+
/**
|
|
220
|
+
* A source is "started" — eligible to receive on() events directly — when
|
|
221
|
+
* its init has run and any require gate is satisfied.
|
|
222
|
+
*/
|
|
223
|
+
declare function isSourceStarted(source: Source.Instance): boolean;
|
|
212
224
|
/**
|
|
213
225
|
* Initialize a single source. Extracted from the initSources loop body
|
|
214
226
|
* so it can be reused by the pending-source activator.
|
|
@@ -316,4 +328,4 @@ declare function wrapEnv(env: Record<string, unknown> & {
|
|
|
316
328
|
*/
|
|
317
329
|
declare function getCacheStore(compiled: CompiledCache, collector: Collector.Instance): Store.Instance | undefined;
|
|
318
330
|
|
|
319
|
-
export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, getCacheStore, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, runTransformerChain, startFlow, transformerInit, transformerPush, walkChain, wrapEnv };
|
|
331
|
+
export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, flushSourceQueueOn, getCacheStore, initDestinations, initSource, initSources, isSourceStarted, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, runTransformerChain, startFlow, transformerInit, transformerPush, walkChain, wrapEnv };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,n=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r={};((e,t)=>{for(var o in t)n(e,o,{get:t[o],enumerable:!0})})(r,{Code:()=>i,Commands:()=>a,Const:()=>c,addDestination:()=>$,callDestinationOn:()=>D,commonHandleCommand:()=>V,createEvent:()=>W,createPush:()=>K,createPushResult:()=>M,destinationInit:()=>R,destinationPush:()=>N,extractTransformerNextMap:()=>b,getCacheStore:()=>y,initDestinations:()=>T,initSource:()=>j,initSources:()=>A,mergeEnvironments:()=>G,on:()=>S,onApply:()=>P,processConsent:()=>l,pushToDestinations:()=>_,registerDestination:()=>H,runCollector:()=>z,runTransformerChain:()=>x,startFlow:()=>Z,transformerInit:()=>w,transformerPush:()=>C,walkChain:()=>k,wrapEnv:()=>ne}),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||n(e,c,{get:()=>r[c],enumerable:!(a=t(r,c))||a.enumerable});return e})(n({},"__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,n){const t={};return Object.entries(n).forEach(([e,n])=>{t[e]=!!n}),e.consent=(0,u.assign)(e.consent,t),{update:t}}var f=require("@walkeros/core"),d=require("@walkeros/core"),g=require("@walkeros/core"),m=require("@walkeros/core"),p=require("@walkeros/core"),h=require("@walkeros/core");function y(e,n){return e.storeId&&n.stores[e.storeId]?n.stores[e.storeId]:n.stores.__cache}function b(e){const n={};for(const[t,o]of Object.entries(e)){const e=o.config?.next;e&&!(0,h.isRouteArray)(e)?n[t]={next:e}:n[t]={}}return n}function v(e,n){const t=e.config||{},o=e[n];return void 0!==o?{config:{...t,[n]:o},chainValue:o}:{config:t,chainValue:void 0}}function k(e,n={}){if(!e)return[];if(Array.isArray(e))return e;const t=[],o=new Set;let s=e;for(;s&&n[s]&&!o.has(s);){o.add(s),t.push(s);const e=n[s].next;if(Array.isArray(e)){t.push(...e);break}s=e}return t}async function w(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:t,ingest:(0,h.createIngest)(t),config:n.config,env:O(n.config.env)};s.debug("init");const i=await(0,h.useHooks)(n.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;n.config={...i||n.config,env:i?.env||n.config.env,init:!0},s.debug("init done")}return!0}async function C(e,n,t,o,s,r){const i=n.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:t,ingest:s,config:n.config,env:{...O(n.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,h.useHooks)(n.push,"TransformerPush",e.hooks,e.logger)(o,c);return a.debug("push done"),u}async function x(e,n,t,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of t){const r=n[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,h.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 n=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=n;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,h.compileCache)(u):void 0,f=l?y(l,e):void 0;let d;if(l&&f){const e=(0,h.buildCacheContext)(s,a),n=(0,h.checkCache)(l,f,e,`t:${o}`);if("HIT"===n?.status&&n.value){if(a=n.value,l.full)return{event:a,respond:c};continue}"MISS"===n?.status&&(d={key:n.key,ttl:n.rule.ttl})}const g=r.config.before;if(g){const t=k("string"==typeof g||Array.isArray(g)&&!(0,h.isRouteArray)(g)?g:(0,h.resolveNext)((0,h.compileNext)(g),(0,h.buildCacheContext)(s,a))||void 0,b(n));if(t.length>0){const o=await x(e,n,t,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 m=await(0,h.tryCatchAsync)(C,n=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,r,o,a,s,c);if(!1===m)return{event:null,respond:c};if(Array.isArray(m)){const r=t.slice(t.indexOf(o)+1),u=await Promise.all(m.map(async t=>{const o=t.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:(0,h.createIngest)("unknown");if(t.next){let s=t.next;if((0,h.isRouteArray)(t.next)){const e=(0,h.compileNext)(t.next);s=(0,h.resolveNext)(e,(0,h.buildCacheContext)(u,o))}if(s){const t=k(s,b(n));if(t.length>0)return x(e,n,t,o,u,c,i)}return{event:o,respond:c}}return r.length>0?x(e,n,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 n=e;if(n.respond&&(l=n.respond),null===n.event)continue;Array.isArray(n.event)?f.push(...n.event):f.push(n.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(m&&"object"==typeof m){const{event:t,respond:o,next:r}=m;if(o&&(c=o),r){let o=r;if((0,h.isRouteArray)(r)){const e=(0,h.compileNext)(r);if(o=(0,h.resolveNext)(e,(0,h.buildCacheContext)(s,a)),!o){t&&(a=t);continue}}const u=k(o,b(n));return u.length>0?x(e,n,u,t||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}t&&(a=t)}if(d&&f&&(0,h.storeCache)(f,d.key,a,d.ttl),(!m||"object"==typeof m&&!m.next)&&r.config.next&&(0,h.isRouteArray)(r.config.next)){const t=r.config.next,o=(0,h.compileNext)(t),u=(0,h.resolveNext)(o,(0,h.buildCacheContext)(s,a));if(u){const t=k(u,b(n));if(t.length>0)return x(e,n,t,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function O(e){return e&&(0,h.isObject)(e)?e:{}}async function j(e,n,t){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=t;let l,f=(0,p.createIngest)(n);const d=u?(0,p.compileCache)({...u,full:u.full??!0}):void 0,g=(0,p.compileNext)(a),m=!(Array.isArray(a)&&(0,p.isRouteArray)(a))&&g?k((0,p.resolveNext)(g),b(e.transformers)):void 0,h=(0,p.compileNext)(c),v=!(Array.isArray(c)&&(0,p.isRouteArray)(c))&&h?k((0,p.resolveNext)(h),b(e.transformers)):void 0,w=e.logger.scope("source").scope(n),C={push:async(t,o={})=>{let r,i=t;const a=v??(h?k((0,p.resolveNext)(h,(0,p.buildCacheContext)(f)),b(e.transformers)):[]);if(a.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await x(e,e.transformers,a,i,f,l,`source.${n}.before`);if(null===t.event)return{ok:!0};t.respond&&(l=t.respond),i=Array.isArray(t.event)?t.event[0]:t.event}if(d){const t=y(d,e);if(t){const o=(0,p.buildCacheContext)(f),s=(0,p.checkCache)(d,t,o,`s:${n}`);if(s){if("HIT"===s.status&&void 0!==s.value&&d.full){let n=s.value;return s.rule.update&&(n=await(0,p.applyUpdate)(n,s.rule.update,{...o,cache:{status:"HIT"}},e)),l?.(n),{ok:!0}}if("MISS"===s.status&&d.full&&l){const n=l,i=s.rule.update,a={...o,cache:{status:"MISS"}},c=s.key,u=s.rule.ttl;l=o=>{(0,p.storeCache)(t,c,o,u),i?r=(async()=>{const t=await(0,p.applyUpdate)(o,i,a,e);n(t)})():n(o)}}"MISS"!==s.status||d.full||(0,p.storeCache)(t,s.key,!0,s.rule.ttl)}}}const c=m??(g?k((0,p.resolveNext)(g,(0,p.buildCacheContext)(f)),b(e.transformers)):[]),u=await e.push(i,{...o,id:n,ingest:f,respond:l,mapping:s,preChain:c});return r&&await r,u},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:w,...r},O={collector:e,logger:w,id:n,config:s,env:C,setIngest:async t=>{if(!s.ingest)return void(f=(0,p.createIngest)(n));const o=await(0,p.getMappingValue)(t,s.ingest,{collector:e}),r=(0,p.createIngest)(n);f={...r,...o,_meta:r._meta}},setRespond:e=>{l=e}},j=await(0,p.tryCatchAsync)(o)(O);if(!j)return;const A=j.type||"unknown",q=e.logger.scope(A).scope(n);return C.logger=q,i&&(j.config={...j.config,primary:i}),j}async function A(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{config:n={}}=s;if(n.require&&n.require.length>0){e.pending.sources[o]=s;continue}const r=await j(e,o,s);r&&(t[o]=r)}return t}function q(e,n){return{collector:e,logger:e.logger.scope("on").scope(String(n))}}async function S(e,n,t){const o=e.on,s=o[n]||[],r=(0,g.isArray)(t)?t:[t];r.forEach(e=>{s.push(e)}),o[n]=s,I(e,n,r)}function D(e,n,t,o,s){if(!n.on)return;const r=n.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:t,config:n.config,data:s,env:G(n.env,n.config.env)};(0,m.tryCatch)(n.on)(o,a)}function I(e,n,t,o){let s;switch(n){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}if(t.length)switch(n){case c.Commands.Consent:!function(e,n,t){const o=t||e.consent,s=q(e,c.Commands.Consent);n.forEach(e=>{Object.keys(o).filter(n=>n in e).forEach(n=>{(0,m.tryCatch)(e[n])(o,s)})})}(e,t,o);break;case c.Commands.Ready:!function(e,n){if(!e.allowed)return;const t=q(e,c.Commands.Ready);n.forEach(e=>{(0,m.tryCatch)(e)(void 0,t)})}(e,t);break;case c.Commands.Run:!function(e,n){if(!e.allowed)return;const t=q(e,c.Commands.Run);n.forEach(e=>{(0,m.tryCatch)(e)(void 0,t)})}(e,t);break;case c.Commands.Session:!function(e,n){if(!e.session)return;const t=q(e,c.Commands.Session);n.forEach(n=>{(0,m.tryCatch)(n)(e.session,t)})}(e,t);break;default:{const o=q(e,n);t.forEach(e=>{"function"==typeof e&&(0,m.tryCatch)(e)(s,o)});break}}}async function P(e,n,t,o){let s,r=t||[];switch(t||(r=e.on[n]||[]),n){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 t of Object.values(e.sources))if(t.on){!1===await(0,m.tryCatchAsync)(t.on)(n,s)&&(i=!0)}return Object.entries(e.destinations).forEach(([t,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:n,data:s});D(e,o,t,n,s)}}),(Object.keys(e.pending.sources).length>0||Object.keys(e.pending.destinations).length>0)&&await async function(e,n){for(const[t,o]of Object.entries(e.pending.sources)){if(!e.pending.sources[t]||e.sources[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(n);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.sources[t];const i=await j(e,t,o);i&&(e.sources[t]=i)}for(const[t,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(n);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[t];const i=H(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[t]=i}}(e,n),I(e,n,r,o),!i}function E(e,n,t,o){if(!e)return[];if(n){const e=(0,d.resolveNext)(n,(0,d.buildCacheContext)(o));return e?k(e,b(t)):[]}return k(e,b(t))}async function $(e,n,t){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=n;if(!(0,d.isFunction)(o.push))return M({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=t||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:G(o.env,r)};let g=f.config.id;if(!g)do{g=(0,d.getId)(5,"abcdefghijklmnopqrstuvwxyz")}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,n,t={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return M({ok:!1});n&&(e.queue.push(n),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=[],n&&c.push((0,d.clone)(n));const u=t.ingest?{...t.ingest,_meta:{...t.ingest._meta,path:[...t.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 n=await(0,d.tryCatchAsync)(R)(e,s,o);return{id:o,destination:s,skipped:!n}}const l=[],f=c.filter(e=>{const n=(0,d.getGrantedConsent)(s.config.consent,r,e.consent);return!n||(e.consent=n,l.push(e),!1)});if(s.queuePush.push(...f),!l.length)return{id:o,destination:s,queue:c};if(!await(0,d.tryCatchAsync)(R)(e,s,o))return{id:o,destination:s,queue:c};let g,m;s.dlq||(s.dlq=[]);const p=s.config.before,h=E(p,p&&(0,d.isRouteArray)(p)?(0,d.compileNext)(p):void 0,e.transformers,u),b=s.config.next,v=b&&(0,d.isRouteArray)(b)?(0,d.compileNext)(b):void 0,k=s.config?.cache,w=k?(0,d.compileCache)(k):void 0,C=w?y(w,e):void 0;let O=0;return await Promise.all(l.map(async n=>{let r;if(n.globals=(0,d.assign)(i,n.globals),n.user=(0,d.assign)(a,n.user),w?.full&&C){const e=(0,d.buildCacheContext)(u,n),t=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}let c=n,l=t.respond;if(h.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await x(e,e.transformers,h,n,u,t.respond,`destination.${o}.before`);if(null===s.event)return n;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),t=(0,d.checkCache)(w,C,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}const f=Date.now();let p=!1;const y=await(0,d.tryCatchAsync)(N,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:c.name}),g=n,p=!0,s.dlq.push([c,n])})(e,s,o,c,u,l);if(O+=Date.now()-f,r&&C&&void 0===s.config.mock&&(0,d.storeCache)(C,r.key,y??!0,r.ttl),void 0!==y&&(m=y),!p&&b){void 0!==y&&(u._response=y);const n=E(b,v,e.transformers,u);if(n.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await x(e,e.transformers,n,c,u,l,`destination.${o}.next`);t.respond&&(l=t.respond)}}return n})),{id:o,destination:s,error:g,response:m,totalDuration:O}})),u={},l={},f={};for(const n of c){if(n.skipped)continue;const t={type:n.destination.type||"unknown",data:n.response};e.status.destinations[n.id]||(e.status.destinations[n.id]={count:0,failed:0,duration:0});const o=e.status.destinations[n.id],s=Date.now();n.error?(t.error=n.error,f[n.id]=t,o.failed++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?l[n.id]=t:(u[n.id]=t,o.count++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.out++)}return M({event:n,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(f).length&&{failed:f}})}async function R(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:t,config:n.config,env:G(n.env,n.config.env)};s.debug("init");const i=await(0,d.useHooks)(n.init,"DestinationInit",e.hooks,e.logger)(r);if(!1===i)return i;if(n.config={...i||n.config,init:!0},n.queueOn?.length){const o=n.queueOn;n.queueOn=[];for(const{type:s,data:r}of o)D(e,n,t,s,r)}s.debug("init done")}return!0}async function N(e,n,t,o,s,r){const{config:i}=n,a=await(0,d.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=n.type||"unknown",u=e.logger.scope(c),l={collector:e,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...G(n.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||!n.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const t=await(0,d.useHooks)(n.push,"DestinationPush",e.hooks,e.logger)(a.event,l);return u.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[g]){const o={key:g,events:[],data:[]};n.batches[g]={batched:o,batchFn:(0,d.debounce)(()=>{const o=n.batches[g].batched,a={collector:e,logger:u,id:t,config:i,data:void 0,rule:f,ingest:s,env:{...G(n.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,d.useHooks)(n.pushBatch,"DestinationPushBatch",e.hooks,e.logger)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},f.batch)}}const o=n.batches[g];o.batched.events.push(a.event),(0,d.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function M(e){return{ok:!e?.failed,...e}}function H(e){const{code:n,config:t={},env:o={},cache:s}=e,{config:r}=v(e,"before"),{config:i}=v({...e,config:r},"next"),a={...n.config,...t,...i};s&&(a.cache=s);const c=G(n.env,o);return{...n,config:a,env:c}}async function T(e,n={}){const t={};for(const[o,s]of Object.entries(n))s.config?.require?.length?e.pending.destinations[o]=s:t[o]=H(s);return t}function G(e,n){return e||n?n?e&&(0,d.isObject)(e)&&(0,d.isObject)(n)?{...e,...n}:n:e:{}}var U=require("@walkeros/core"),F=require("@walkeros/core"),B=5e3;async function L(e,n,t){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=t.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((t,o)=>setTimeout(()=>o(new Error(`${n} '${e}' destroy timed out`)),B))])}catch(t){i.error(`${n} '${e}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function V(e,n,t,o){let s,r,i=!1;switch(n){case c.Commands.Config:(0,F.isObject)(t)&&((0,U.assign)(e.config,t,{shallow:!1}),r=t,i=!0);break;case c.Commands.Consent:if((0,F.isObject)(t)){const{update:n}=l(e,t);r=n,i=!0}break;case c.Commands.Custom:(0,F.isObject)(t)&&(e.custom=(0,U.assign)(e.custom,t),r=t,i=!0);break;case c.Commands.Destination:(0,F.isObject)(t)&&("code"in t&&(0,F.isObject)(t.code)?s=await $(e,t,o):(0,U.isFunction)(t.push)&&(s=await $(e,{code:t},o)));break;case c.Commands.Globals:(0,F.isObject)(t)&&(e.globals=(0,U.assign)(e.globals,t),r=t,i=!0);break;case c.Commands.On:(0,U.isString)(t)&&await S(e,t,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await z(e,t),i=!0;break;case c.Commands.Session:i=!0;break;case c.Commands.Shutdown:await async function(e){const n=e.logger;await L(e.sources,"source",n),await L(e.destinations,"destination",n),await L(e.transformers,"transformer",n),await L(e.stores,"store",n)}(e);break;case c.Commands.User:(0,F.isObject)(t)&&((0,U.assign)(e.user,t,{shallow:!1}),r=t,i=!0)}return i&&(await P(e,n,void 0,r),s=await _(e)),s||M({ok:!0})}function W(e,n){if(!n.name)throw new Error("Event name is required");const[t,o]=n.name.split(" ");if(!t||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${t} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:l=e.user,nested:f=[],consent:d=e.consent,id:g=(0,U.getSpanId)(),trigger:m="",entity:p=t,action:h=o,timing:y=0,source:b={type:"collector",schema:"4"}}=n;return{name:r,data:i,context:a,globals:c,custom:u,user:l,nested:f,consent:d,id:g,trigger:m,entity:p,action:h,timestamp:s,timing:y,source:b}}async function z(e,n){e.allowed=!0,e.timing=Date.now(),n&&(n.consent&&(e.consent=(0,U.assign)(e.consent,n.consent)),n.user&&(e.user=(0,U.assign)(e.user,n.user)),n.globals&&(e.globals=(0,U.assign)(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=(0,U.assign)(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await _(e)}var J=require("@walkeros/core");function K(e,n){return(0,J.useHooks)(async(t,o={})=>await(0,J.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=t;const m=l||f?function(e,n,t){let o=e;return n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>n.includes(e)))),t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!t.includes(e)))),o}(e.destinations,l,f):void 0,p=i??(0,J.createIngest)(r||"unknown");if(c){const n=await(0,J.processEventMapping)(g,c,e);if(n.ignore)return M({ok:!0});if(c.consent){if(!(0,J.getGrantedConsent)(c.consent,e.consent,n.event.consent))return M({ok:!0})}g=n.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const t=await x(e,e.transformers,u,g,p,d,r?`source.${r}.next`:void 0);if(null===t.event)return M({ok:!0});if(t.respond&&(d=t.respond),Array.isArray(t.event)){const o=await Promise.all(t.event.map(async t=>{const o=n(t),s=W(e,o);return _(e,s,{id:r,ingest:p,respond:d},m)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count+=t.event.length,n.lastAt=Date.now(),n.duration+=Date.now()-s}return o[0]??M({ok:!0})}g=t.event}const h=n(g),y=W(e,h),b=await _(e,y,{id:r,ingest:p,respond:d},m);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count++,n.lastAt=Date.now(),n.duration+=Date.now()-s}return b},()=>M({ok:!1}))(),"Push",e.hooks,e.logger)}var Q=require("@walkeros/core");var X=require("@walkeros/core");async function Y(e){const n=(0,f.assign)({globalsStatic:{},sessionStatic:{},run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=(0,f.createLogger)(t),s={...n.globalsStatic,...e.globals},r={allowed:!1,config:n,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,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||{},sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};r.push=K(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.0.0"},...e})),r.command=function(e,n){return(0,Q.useHooks)(async(t,o,s)=>await(0,Q.tryCatchAsync)(async()=>await n(e,t,o,s),()=>M({ok:!1}))(),"Command",e.hooks,e.logger)}(r,V);const i=e.stores||{};if(r.stores=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,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 n(c),l=u.get,f=u.set,d=u.delete;u.get=(0,X.useHooks)(l,"StoreGet",e.hooks,e.logger),u.set=(0,X.useHooks)(f,"StoreSet",e.hooks,e.logger),u.delete=(0,X.useHooks)(d,"StoreDelete",e.hooks,e.logger),t[o]=u}return t}(r,i),function(e,n,t){const o=new Map;for(const[t,s]of Object.entries(e))n[t]&&o.set(s,n[t]);if(0!==o.size)for(const e of[t.transformers,t.destinations,t.sources])if(e)for(const n of Object.values(e))s(n.env);function s(e){if(e)for(const[n,t]of Object.entries(e))if("object"==typeof t&&null!==t){const s=o.get(t);s&&(e[n]=s)}}}(i,r.stores,e),!r.stores.__cache){const e=new Map;r.stores.__cache={type:"memory",config:{},get:n=>{const t=e.get(n);if(t){if(!(t.expires&&Date.now()>t.expires))return t.value;e.delete(n)}},set:(n,t,o)=>{e.set(n,{value:t,expires:o?Date.now()+o:void 0})},delete:n=>{e.delete(n)}}}return r.destinations=await T(r,e.destinations||{}),r.transformers=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,env:r={}}=s,{config:i}=v(s,"before"),{config:a}=v({...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,h.createIngest)(o),config:l,env:r},g=await n(d);t[o]=g}return t}(r,e.transformers||{}),r}async function Z(e){e=e||{};const n=await Y(e),t=(o=n,{type:"elb",config:{},push:async(e,n,t,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,n,t)}let a;if("string"==typeof e)a={name:e},n&&"object"==typeof n&&!Array.isArray(n)&&(a.data=n);else{if(!e||"object"!=typeof e)return M({ok:!1});a=e,n&&"object"==typeof n&&!Array.isArray(n)&&(a.data={...a.data||{},...n})}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;n.sources.elb=t;const s=await A(n,e.sources||{});Object.assign(n.sources,s);const{consent:r,user:i,globals:a,custom:c}=e;r&&await n.command("consent",r),i&&await n.command("user",i),a&&Object.assign(n.globals,a),c&&Object.assign(n.custom,c),n.config.run&&await n.command("run");let u=t.push;const l=Object.values(n.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:n,elb:u}}function ee(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ee);const n={};for(const[t,o]of Object.entries(e))n[t]="function"==typeof o?o:ee(o);return n}function ne(e){const n=[],{simulation:t,...o}=e,s=ee(o);for(const e of t){const t=e.startsWith("call:")?e.slice(5):e,o=t.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 n.push({fn:t,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:n}}//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";var e,n=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r={};((e,t)=>{for(var o in t)n(e,o,{get:t[o],enumerable:!0})})(r,{Code:()=>i,Commands:()=>a,Const:()=>c,addDestination:()=>R,callDestinationOn:()=>P,commonHandleCommand:()=>z,createEvent:()=>J,createPush:()=>X,createPushResult:()=>T,destinationInit:()=>M,destinationPush:()=>H,extractTransformerNextMap:()=>b,flushSourceQueueOn:()=>j,getCacheStore:()=>y,initDestinations:()=>U,initSource:()=>A,initSources:()=>S,isSourceStarted:()=>q,mergeEnvironments:()=>B,on:()=>I,onApply:()=>$,processConsent:()=>l,pushToDestinations:()=>N,registerDestination:()=>G,runCollector:()=>K,runTransformerChain:()=>O,startFlow:()=>ne,transformerInit:()=>w,transformerPush:()=>C,walkChain:()=>k,wrapEnv:()=>oe}),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||n(e,c,{get:()=>r[c],enumerable:!(a=t(r,c))||a.enumerable});return e})(n({},"__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,n){const t={};return Object.entries(n).forEach(([e,n])=>{t[e]=!!n}),e.consent=(0,u.assign)(e.consent,t),{update:t}}var f=require("@walkeros/core"),d=require("@walkeros/core"),g=require("@walkeros/core"),m=require("@walkeros/core");var p=require("@walkeros/core"),h=require("@walkeros/core");function y(e,n){return e.storeId&&n.stores[e.storeId]?n.stores[e.storeId]:n.stores.__cache}function b(e){const n={};for(const[t,o]of Object.entries(e)){const e=o.config?.next;e&&!(0,h.isRouteArray)(e)?n[t]={next:e}:n[t]={}}return n}function v(e,n){const t=e.config||{},o=e[n];return void 0!==o?{config:{...t,[n]:o},chainValue:o}:{config:t,chainValue:void 0}}function k(e,n={}){if(!e)return[];if(Array.isArray(e))return e;const t=[],o=new Set;let s=e;for(;s&&n[s]&&!o.has(s);){o.add(s),t.push(s);const e=n[s].next;if(Array.isArray(e)){t.push(...e);break}s=e}return t}async function w(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(`transformer:${o}`),r={collector:e,logger:s,id:t,ingest:(0,h.createIngest)(t),config:n.config,env:x(n.config.env)};s.debug("init");const i=await(0,h.useHooks)(n.init,"TransformerInit",e.hooks,e.logger)(r);if(!1===i)return!1;n.config={...i||n.config,env:i?.env||n.config.env,init:!0},s.debug("init done")}return!0}async function C(e,n,t,o,s,r){const i=n.type||"unknown",a=e.logger.scope(`transformer:${i}`),c={collector:e,logger:a,id:t,ingest:s,config:n.config,env:{...x(n.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,h.useHooks)(n.push,"TransformerPush",e.hooks,e.logger)(o,c);return a.debug("push done"),u}async function O(e,n,t,o,s,r,i){i&&s?._meta&&(s._meta.chainPath=i);let a=o,c=r;for(const o of t){const r=n[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,h.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 n=r.config.chainMocks[i];e.logger.scope(`transformer:${r.type||"unknown"}`).debug("chainMock",{chain:i}),a=n;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,h.compileCache)(u):void 0,f=l?y(l,e):void 0;let d;if(l&&f){const e=(0,h.buildCacheContext)(s,a),n=(0,h.checkCache)(l,f,e,`t:${o}`);if("HIT"===n?.status&&n.value){if(a=n.value,l.full)return{event:a,respond:c};continue}"MISS"===n?.status&&(d={key:n.key,ttl:n.rule.ttl})}const g=r.config.before;if(g){const t=k("string"==typeof g||Array.isArray(g)&&!(0,h.isRouteArray)(g)?g:(0,h.resolveNext)((0,h.compileNext)(g),(0,h.buildCacheContext)(s,a))||void 0,b(n));if(t.length>0){const o=await O(e,n,t,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 m=await(0,h.tryCatchAsync)(C,n=>(e.logger.scope(`transformer:${r.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,r,o,a,s,c);if(!1===m)return{event:null,respond:c};if(Array.isArray(m)){const r=t.slice(t.indexOf(o)+1),u=await Promise.all(m.map(async t=>{const o=t.event||a,u=s?{...s,_meta:{...s._meta,path:[...s._meta.path]}}:(0,h.createIngest)("unknown");if(t.next){let s=t.next;if((0,h.isRouteArray)(t.next)){const e=(0,h.compileNext)(t.next);s=(0,h.resolveNext)(e,(0,h.buildCacheContext)(u,o))}if(s){const t=k(s,b(n));if(t.length>0)return O(e,n,t,o,u,c,i)}return{event:o,respond:c}}return r.length>0?O(e,n,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 n=e;if(n.respond&&(l=n.respond),null===n.event)continue;Array.isArray(n.event)?f.push(...n.event):f.push(n.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(m&&"object"==typeof m){const{event:t,respond:o,next:r}=m;if(o&&(c=o),r){let o=r;if((0,h.isRouteArray)(r)){const e=(0,h.compileNext)(r);if(o=(0,h.resolveNext)(e,(0,h.buildCacheContext)(s,a)),!o){t&&(a=t);continue}}const u=k(o,b(n));return u.length>0?O(e,n,u,t||a,s,c,i):(e.logger.warn(`Branch target not found: ${JSON.stringify(r)}`),{event:null,respond:c})}t&&(a=t)}if(d&&f&&(0,h.storeCache)(f,d.key,a,d.ttl),(!m||"object"==typeof m&&!m.next)&&r.config.next&&(0,h.isRouteArray)(r.config.next)){const t=r.config.next,o=(0,h.compileNext)(t),u=(0,h.resolveNext)(o,(0,h.buildCacheContext)(s,a));if(u){const t=k(u,b(n));if(t.length>0)return O(e,n,t,a,s,c,i)}return{event:a,respond:c}}}return{event:a,respond:c}}function x(e){return e&&(0,h.isObject)(e)?e:{}}async function j(e,n){if(!n.on||!n.queueOn?.length)return;const t=n.queueOn;n.queueOn=[];for(const{type:e,data:o}of t)await(0,p.tryCatchAsync)(n.on)(e,o)}function q(e){return Boolean(e.config.init)&&!e.config.require?.length}async function A(e,n,t){const{code:o,config:s={},env:r={},primary:i,next:a,before:c,cache:u}=t;let l,f=(0,p.createIngest)(n);const d=u?(0,p.compileCache)({...u,full:u.full??!0}):void 0,g=(0,p.compileNext)(a),m=!(Array.isArray(a)&&(0,p.isRouteArray)(a))&&g?k((0,p.resolveNext)(g),b(e.transformers)):void 0,h=(0,p.compileNext)(c),v=!(Array.isArray(c)&&(0,p.isRouteArray)(c))&&h?k((0,p.resolveNext)(h),b(e.transformers)):void 0,w=e.logger.scope("source").scope(n),C={push:async(t,o={})=>{let r,i=t;const a=v??(h?k((0,p.resolveNext)(h,(0,p.buildCacheContext)(f)),b(e.transformers)):[]);if(a.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await O(e,e.transformers,a,i,f,l,`source.${n}.before`);if(null===t.event)return{ok:!0};t.respond&&(l=t.respond),i=Array.isArray(t.event)?t.event[0]:t.event}if(d){const t=y(d,e);if(t){const o=(0,p.buildCacheContext)(f),s=(0,p.checkCache)(d,t,o,`s:${n}`);if(s){if("HIT"===s.status&&void 0!==s.value&&d.full){let n=s.value;return s.rule.update&&(n=await(0,p.applyUpdate)(n,s.rule.update,{...o,cache:{status:"HIT"}},e)),l?.(n),{ok:!0}}if("MISS"===s.status&&d.full&&l){const n=l,i=s.rule.update,a={...o,cache:{status:"MISS"}},c=s.key,u=s.rule.ttl;l=o=>{(0,p.storeCache)(t,c,o,u),i?r=(async()=>{const t=await(0,p.applyUpdate)(o,i,a,e);n(t)})():n(o)}}"MISS"!==s.status||d.full||(0,p.storeCache)(t,s.key,!0,s.rule.ttl)}}}const c=m??(g?k((0,p.resolveNext)(g,(0,p.buildCacheContext)(f)),b(e.transformers)):[]),u=await e.push(i,{...o,id:n,ingest:f,respond:l,mapping:s,preChain:c});return r&&await r,u},command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:w,...r},x={collector:e,logger:w,id:n,config:s,env:C,setIngest:async t=>{if(!s.ingest)return void(f=(0,p.createIngest)(n));const o=await(0,p.getMappingValue)(t,s.ingest,{collector:e}),r=(0,p.createIngest)(n);f={...r,...o,_meta:r._meta}},setRespond:e=>{l=e}},j=await(0,p.tryCatchAsync)(o)(x);if(!j)return;const q=j.type||"unknown",A=e.logger.scope(q).scope(n);return C.logger=A,i&&(j.config={...j.config,primary:i}),j}async function S(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const n=await A(e,o,s);if(!n)continue;const r=s.config?.require;n.config={...n.config,init:!1,...r?{require:[...r]}:{}},t[o]=n}Object.assign(e.sources,t);for(const n of Object.keys(t)){const t=e.sources[n];t.init&&await(0,p.tryCatchAsync)(t.init.bind(t))(),t.config.init=!0,q(t)&&await j(0,t)}return t}function D(e,n){return{collector:e,logger:e.logger.scope("on").scope(String(n))}}async function I(e,n,t){const o=e.on,s=o[n]||[],r=(0,g.isArray)(t)?t:[t];r.forEach(e=>{s.push(e)}),o[n]=s,E(e,n,r)}function P(e,n,t,o,s){if(!n.on)return;const r=n.type||"unknown",i=e.logger.scope(r).scope("on").scope(o),a={collector:e,logger:i,id:t,config:n.config,data:s,env:B(n.env,n.config.env)};(0,m.tryCatch)(n.on)(o,a)}function E(e,n,t,o){let s;switch(n){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}if(t.length)switch(n){case c.Commands.Consent:!function(e,n,t){const o=t||e.consent,s=D(e,c.Commands.Consent);n.forEach(e=>{Object.keys(o).filter(n=>n in e).forEach(n=>{(0,m.tryCatch)(e[n])(o,s)})})}(e,t,o);break;case c.Commands.Ready:!function(e,n){if(!e.allowed)return;const t=D(e,c.Commands.Ready);n.forEach(e=>{(0,m.tryCatch)(e)(void 0,t)})}(e,t);break;case c.Commands.Run:!function(e,n){if(!e.allowed)return;const t=D(e,c.Commands.Run);n.forEach(e=>{(0,m.tryCatch)(e)(void 0,t)})}(e,t);break;case c.Commands.Session:!function(e,n){if(!e.session)return;const t=D(e,c.Commands.Session);n.forEach(n=>{(0,m.tryCatch)(n)(e.session,t)})}(e,t);break;default:{const o=D(e,n);t.forEach(e=>{"function"==typeof e&&(0,m.tryCatch)(e)(s,o)});break}}}async function $(e,n,t,o){let s,r=t||[];switch(t||(r=e.on[n]||[]),n){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 t of Object.values(e.sources)){if(t.config.require?.length){const e=t.config.require.indexOf(n);-1!==e&&t.config.require.splice(e,1)}if(t.on)if(q(t)){!1===await(0,m.tryCatchAsync)(t.on)(n,s)&&(i=!0)}else t.queueOn=t.queueOn||[],t.queueOn.push({type:n,data:s})}Object.entries(e.destinations).forEach(([t,o])=>{if(o.on){if(!o.config.init)return o.queueOn=o.queueOn||[],void o.queueOn.push({type:n,data:s});P(e,o,t,n,s)}});for(const n of Object.values(e.sources))q(n)&&n.queueOn?.length&&await j(0,n);return Object.keys(e.pending.destinations).length>0&&await async function(e,n){for(const[t,o]of Object.entries(e.pending.destinations)){if(!e.pending.destinations[t]||e.destinations[t])continue;const s=o.config?.require;if(!s)continue;const r=s.indexOf(n);if(-1===r)continue;if(s.splice(r,1),s.length>0)continue;delete e.pending.destinations[t];const i=G(o);!1!==i.config.queue&&(i.queuePush=[...e.queue]),e.destinations[t]=i}}(e,n),E(e,n,r,o),!i}function _(e,n,t,o){if(!e)return[];if(n){const e=(0,d.resolveNext)(n,(0,d.buildCacheContext)(o));return e?k(e,b(t)):[]}return k(e,b(t))}async function R(e,n,t){const{code:o,config:s={},env:r={},before:i,next:a,cache:c}=n;if(!(0,d.isFunction)(o.push))return T({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const u=t||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:B(o.env,r)};let g=f.config.id;if(!g)do{g=(0,d.getId)(5,"abcdefghijklmnopqrstuvwxyz")}while(e.destinations[g]);return e.destinations[g]=f,!1!==f.config.queue&&(f.queuePush=[...e.queue]),N(e,void 0,{},{[g]:f})}async function N(e,n,t={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return T({ok:!1});n&&(e.queue.push(n),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=[],n&&c.push((0,d.clone)(n));const u=t.ingest?{...t.ingest,_meta:{...t.ingest._meta,path:[...t.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){let n=!1;try{n=await M(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}return{id:o,destination:s,skipped:!n}}const l=[],f=c.filter(e=>{const n=(0,d.getGrantedConsent)(s.config.consent,r,e.consent);return!n||(e.consent=n,l.push(e),!1)});if(s.queuePush.push(...f),!l.length)return{id:o,destination:s,queue:c};let g,m,p=!1;try{p=await M(e,s,o)}catch(n){const t=s.type||"unknown";e.logger.scope(t).error("Destination init threw",{error:n instanceof Error?n.message:String(n)})}if(!p)return{id:o,destination:s,queue:c};s.dlq||(s.dlq=[]);const h=s.config.before,b=_(h,h&&(0,d.isRouteArray)(h)?(0,d.compileNext)(h):void 0,e.transformers,u),v=s.config.next,k=v&&(0,d.isRouteArray)(v)?(0,d.compileNext)(v):void 0,w=s.config?.cache,C=w?(0,d.compileCache)(w):void 0,x=C?y(C,e):void 0;let j=0;return await Promise.all(l.map(async n=>{let r;if(n.globals=(0,d.assign)(i,n.globals),n.user=(0,d.assign)(a,n.user),C?.full&&x){const e=(0,d.buildCacheContext)(u,n),t=(0,d.checkCache)(C,x,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}let c=n,l=t.respond;if(b.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const s=await O(e,e.transformers,b,n,u,t.respond,`destination.${o}.before`);if(null===s.event)return n;s.respond&&(l=s.respond),c=Array.isArray(s.event)?s.event[0]:s.event}if(C&&!C.full&&x){const e=(0,d.buildCacheContext)(u,c),t=(0,d.checkCache)(C,x,e,`d:${o}`);if("HIT"===t?.status)return n;"MISS"===t?.status&&(r={key:t.key,ttl:t.rule.ttl})}const f=Date.now();let p=!1;const h=await(0,d.tryCatchAsync)(H,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:c.name}),g=n,p=!0,s.dlq.push([c,n])})(e,s,o,c,u,l);if(j+=Date.now()-f,r&&x&&void 0===s.config.mock&&(0,d.storeCache)(x,r.key,h??!0,r.ttl),void 0!==h&&(m=h),!p&&v){void 0!==h&&(u._response=h);const n=_(v,k,e.transformers,u);if(n.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const t=await O(e,e.transformers,n,c,u,l,`destination.${o}.next`);t.respond&&(l=t.respond)}}return n})),{id:o,destination:s,error:g,response:m,totalDuration:j}})),u={},l={},f={};for(const n of c){if(n.skipped)continue;const t={type:n.destination.type||"unknown",data:n.response};e.status.destinations[n.id]||(e.status.destinations[n.id]={count:0,failed:0,duration:0});const o=e.status.destinations[n.id],s=Date.now();n.error?(t.error=n.error,f[n.id]=t,o.failed++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?l[n.id]=t:(u[n.id]=t,o.count++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.out++)}return T({event:n,...Object.keys(u).length&&{done:u},...Object.keys(l).length&&{queued:l},...Object.keys(f).length&&{failed:f}})}async function M(e,n,t){if(n.init&&!n.config.init){const o=n.type||"unknown",s=e.logger.scope(o),r={collector:e,logger:s,id:t,config:n.config,env:B(n.env,n.config.env)};s.debug("init");const i=await(0,d.useHooks)(n.init,"DestinationInit",e.hooks,e.logger)(r);if(!1===i)return i;if(n.config={...i||n.config,init:!0},n.queueOn?.length){const o=n.queueOn;n.queueOn=[];for(const{type:s,data:r}of o)P(e,n,t,s,r)}s.debug("init done")}return!0}async function H(e,n,t,o,s,r){const{config:i}=n,a=await(0,d.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=n.type||"unknown",u=e.logger.scope(c),l={collector:e,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...B(n.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||!n.pushBatch||void 0!==i.mock){u.debug("push",{event:a.event.name});const t=await(0,d.useHooks)(n.push,"DestinationPush",e.hooks,e.logger)(a.event,l);return u.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[g]){const o={key:g,events:[],data:[]};n.batches[g]={batched:o,batchFn:(0,d.debounce)(()=>{const o=n.batches[g].batched,a={collector:e,logger:u,id:t,config:i,data:void 0,rule:f,ingest:s,env:{...B(n.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,d.useHooks)(n.pushBatch,"DestinationPushBatch",e.hooks,e.logger)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},f.batch)}}const o=n.batches[g];o.batched.events.push(a.event),(0,d.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function T(e){return{ok:!e?.failed,...e}}function G(e){const{code:n,config:t={},env:o={},cache:s}=e,{config:r}=v(e,"before"),{config:i}=v({...e,config:r},"next"),a={...n.config,...t,...i};s&&(a.cache=s);const c=B(n.env,o);return{...n,config:a,env:c}}async function U(e,n={}){const t={};for(const[o,s]of Object.entries(n))s.config?.require?.length?e.pending.destinations[o]=s:t[o]=G(s);return t}function B(e,n){return e||n?n?e&&(0,d.isObject)(e)&&(0,d.isObject)(n)?{...e,...n}:n:e:{}}var F=require("@walkeros/core"),L=require("@walkeros/core"),V=5e3;async function W(e,n,t){const o=Object.entries(e).map(async([e,o])=>{const s=o.destroy;if(!s)return;const r=o.type||"unknown",i=t.scope(r),a={id:e,config:o.config,env:o.env??{},logger:i};try{await Promise.race([s(a),new Promise((t,o)=>setTimeout(()=>o(new Error(`${n} '${e}' destroy timed out`)),V))])}catch(t){i.error(`${n} '${e}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function z(e,n,t,o){let s,r,i=!1;switch(n){case c.Commands.Config:(0,L.isObject)(t)&&((0,F.assign)(e.config,t,{shallow:!1}),r=t,i=!0);break;case c.Commands.Consent:if((0,L.isObject)(t)){const{update:n}=l(e,t);r=n,i=!0}break;case c.Commands.Custom:(0,L.isObject)(t)&&(e.custom=(0,F.assign)(e.custom,t),r=t,i=!0);break;case c.Commands.Destination:(0,L.isObject)(t)&&("code"in t&&(0,L.isObject)(t.code)?s=await R(e,t,o):(0,F.isFunction)(t.push)&&(s=await R(e,{code:t},o)));break;case c.Commands.Globals:(0,L.isObject)(t)&&(e.globals=(0,F.assign)(e.globals,t),r=t,i=!0);break;case c.Commands.On:(0,F.isString)(t)&&await I(e,t,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await K(e,t),i=!0;break;case c.Commands.Session:i=!0;break;case c.Commands.Shutdown:await async function(e){const n=e.logger;await W(e.sources,"source",n),await W(e.destinations,"destination",n),await W(e.transformers,"transformer",n),await W(e.stores,"store",n)}(e);break;case c.Commands.User:(0,L.isObject)(t)&&((0,F.assign)(e.user,t,{shallow:!1}),r=t,i=!0)}return i&&(await $(e,n,void 0,r),s=await N(e)),s||T({ok:!0})}function J(e,n){if(!n.name)throw new Error("Event name is required");const[t,o]=n.name.split(" ");if(!t||!o)throw new Error("Event name is invalid");const{timestamp:s=Date.now(),name:r=`${t} ${o}`,data:i={},context:a={},globals:c=e.globals,custom:u={},user:l=e.user,nested:f=[],consent:d=e.consent,id:g=(0,F.getSpanId)(),trigger:m="",entity:p=t,action:h=o,timing:y=0,source:b={type:"collector",schema:"4"}}=n;return{name:r,data:i,context:a,globals:c,custom:u,user:l,nested:f,consent:d,id:g,trigger:m,entity:p,action:h,timestamp:s,timing:y,source:b}}async function K(e,n){e.allowed=!0,e.timing=Date.now(),n&&(n.consent&&(e.consent=(0,F.assign)(e.consent,n.consent)),n.user&&(e.user=(0,F.assign)(e.user,n.user)),n.globals&&(e.globals=(0,F.assign)(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=(0,F.assign)(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await N(e)}var Q=require("@walkeros/core");function X(e,n){return(0,Q.useHooks)(async(t,o={})=>await(0,Q.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=t;const m=l||f?function(e,n,t){let o=e;return n&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>n.includes(e)))),t&&(o=Object.fromEntries(Object.entries(o).filter(([e])=>!t.includes(e)))),o}(e.destinations,l,f):void 0,p=i??(0,Q.createIngest)(r||"unknown");if(c){const n=await(0,Q.processEventMapping)(g,c,e);if(n.ignore)return T({ok:!0});if(c.consent){if(!(0,Q.getGrantedConsent)(c.consent,e.consent,n.event.consent))return T({ok:!0})}g=n.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const t=await O(e,e.transformers,u,g,p,d,r?`source.${r}.next`:void 0);if(null===t.event)return T({ok:!0});if(t.respond&&(d=t.respond),Array.isArray(t.event)){const o=await Promise.all(t.event.map(async t=>{const o=n(t),s=J(e,o);return N(e,s,{id:r,ingest:p,respond:d},m)}));if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count+=t.event.length,n.lastAt=Date.now(),n.duration+=Date.now()-s}return o[0]??T({ok:!0})}g=t.event}const h=n(g),y=J(e,h),b=await N(e,y,{id:r,ingest:p,respond:d},m);if(r){e.status.sources[r]||(e.status.sources[r]={count:0,duration:0});const n=e.status.sources[r];n.count++,n.lastAt=Date.now(),n.duration+=Date.now()-s}return b},()=>T({ok:!1}))(),"Push",e.hooks,e.logger)}var Y=require("@walkeros/core");var Z=require("@walkeros/core");async function ee(e){const n=(0,f.assign)({globalsStatic:{},sessionStatic:{},run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=(0,f.createLogger)(t),s={...n.globalsStatic,...e.globals},r={allowed:!1,config:n,consent:e.consent||{},custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,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||{},sources:{},pending:{destinations:{}},push:void 0,command:void 0};r.push=X(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",schema:"4",version:"4.0.1-next-1778183328892"},...e})),r.command=function(e,n){return(0,Y.useHooks)(async(t,o,s)=>await(0,Y.tryCatchAsync)(async()=>await n(e,t,o,s),()=>T({ok:!1}))(),"Command",e.hooks,e.logger)}(r,z);const i=e.stores||{};if(r.stores=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,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 n(c),l=u.get,f=u.set,d=u.delete;u.get=(0,Z.useHooks)(l,"StoreGet",e.hooks,e.logger),u.set=(0,Z.useHooks)(f,"StoreSet",e.hooks,e.logger),u.delete=(0,Z.useHooks)(d,"StoreDelete",e.hooks,e.logger),t[o]=u}return t}(r,i),function(e,n,t){const o=new Map;for(const[t,s]of Object.entries(e))n[t]&&o.set(s,n[t]);if(0!==o.size)for(const e of[t.transformers,t.destinations,t.sources])if(e)for(const n of Object.values(e))s(n.env);function s(e){if(e)for(const[n,t]of Object.entries(e))if("object"==typeof t&&null!==t){const s=o.get(t);s&&(e[n]=s)}}}(i,r.stores,e),!r.stores.__cache){const e=new Map;r.stores.__cache={type:"memory",config:{},get:n=>{const t=e.get(n);if(t){if(!(t.expires&&Date.now()>t.expires))return t.value;e.delete(n)}},set:(n,t,o)=>{e.set(n,{value:t,expires:o?Date.now()+o:void 0})},delete:n=>{e.delete(n)}}}return r.destinations=await U(r,e.destinations||{}),r.transformers=await async function(e,n={}){const t={};for(const[o,s]of Object.entries(n)){const{code:n,env:r={}}=s,{config:i}=v(s,"before"),{config:a}=v({...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,h.createIngest)(o),config:l,env:r},g=await n(d);t[o]=g}return t}(r,e.transformers||{}),r}async function ne(e){e=e||{};const n=await ee(e),t=(o=n,{type:"elb",config:{},push:async(e,n,t,s,r,i)=>{if("string"==typeof e&&e.startsWith("walker ")){const s=e.replace("walker ","");return o.command(s,n,t)}let a;if("string"==typeof e)a={name:e},n&&"object"==typeof n&&!Array.isArray(n)&&(a.data=n);else{if(!e||"object"!=typeof e)return T({ok:!1});a=e,n&&"object"==typeof n&&!Array.isArray(n)&&(a.data={...a.data||{},...n})}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;n.sources.elb=t,await S(n,e.sources||{});const{consent:s,user:r,globals:i,custom:a}=e;s&&await n.command("consent",s),r&&await n.command("user",r),i&&Object.assign(n.globals,i),a&&Object.assign(n.custom,a),n.config.run&&await n.command("run");let c=t.push;const u=Object.values(n.sources).filter(e=>"elb"!==e.type),l=u.find(e=>e.config.primary);return l?c=l.push:u.length>0&&(c=u[0].push),{collector:n,elb:c}}function te(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(te);const n={};for(const[t,o]of Object.entries(e))n[t]="function"==typeof o?o:te(o);return n}function oe(e){const n=[],{simulation:t,...o}=e,s=te(o);for(const e of t){const t=e.startsWith("call:")?e.slice(5):e,o=t.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 n.push({fn:t,args:e,ts:Date.now()}),a.apply(this,e)})}return{wrappedEnv:s,calls:n}}//# sourceMappingURL=index.js.map
|