@walkeros/collector 3.1.1 → 3.2.0

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _walkeros_core from '@walkeros/core';
2
- import { Collector, WalkerOS, Elb, Mapping, Destination, On, Source, Transformer, Trigger, Simulation } from '@walkeros/core';
2
+ import { Collector, WalkerOS, Elb, Mapping, Destination, On, Ingest, Source, Transformer, Simulation, CompiledCache, Store } from '@walkeros/core';
3
3
 
4
4
  interface RunState {
5
5
  consent?: WalkerOS.Consent;
@@ -71,7 +71,6 @@ declare const Const: {
71
71
  */
72
72
  declare function processConsent(collector: Collector.Instance, data: WalkerOS.Consent): {
73
73
  update: WalkerOS.Consent;
74
- runQueue: boolean;
75
74
  };
76
75
 
77
76
  declare function startFlow<ElbPush extends Elb.Fn = Elb.Fn>(initConfig?: Collector.InitConfig): Promise<StartFlow<ElbPush>>;
@@ -106,7 +105,7 @@ declare function addDestination(collector: Collector.Instance, data: Destination
106
105
  */
107
106
  declare function pushToDestinations(collector: Collector.Instance, event?: WalkerOS.Event, meta?: {
108
107
  id?: string;
109
- ingest?: unknown;
108
+ ingest?: Ingest;
110
109
  respond?: _walkeros_core.RespondFn;
111
110
  }, destinations?: Collector.Destinations): Promise<Elb.PushResult>;
112
111
  /**
@@ -128,10 +127,10 @@ declare function destinationInit<Destination extends Destination.Instance>(colle
128
127
  * @param destination - The destination to push to.
129
128
  * @param destId - The destination ID.
130
129
  * @param event - The event to push.
131
- * @param ingest - Optional ingest metadata (frozen, same reference).
130
+ * @param ingest - Mutable ingest context flowing through the pipeline.
132
131
  * @returns Whether the event was pushed successfully.
133
132
  */
134
- declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown, respond?: _walkeros_core.RespondFn): Promise<unknown>;
133
+ declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise<unknown>;
135
134
  /**
136
135
  * Creates a standardized result object for push operations.
137
136
  *
@@ -260,55 +259,38 @@ declare function extractTransformerNextMap(transformers: Transformer.Transformer
260
259
  declare function walkChain(startId: string | string[] | undefined, transformers?: Record<string, {
261
260
  next?: string | string[];
262
261
  }>): string[];
263
-
264
262
  /**
265
- * Structured input for source simulation.
266
- * One format every consumer constructs this shape.
263
+ * Initializes a transformer if it hasn't been initialized yet.
264
+ * Called lazily before first push.
265
+ *
266
+ * @param collector - The collector instance
267
+ * @param transformer - The transformer to initialize
268
+ * @param transformerId - The transformer ID
269
+ * @returns Whether initialization succeeded
267
270
  */
268
- interface SourceInput {
269
- /** The actual source input (HTML string, dataLayer array, HTTP request, etc.) */
270
- content: unknown;
271
- /** Which trigger mechanism to fire (e.g., { type: 'click' }) */
272
- trigger?: {
273
- type?: string;
274
- options?: unknown;
275
- };
276
- /** Environment overrides (e.g., custom location, localStorage state) */
277
- env?: Record<string, unknown>;
278
- }
279
- interface SimulateSource {
280
- step: 'source';
281
- name: string;
282
- code: Source.Init;
283
- config?: Partial<Source.Config>;
284
- /** createTrigger factory from the source package's examples. */
285
- createTrigger: Trigger.CreateFn;
286
- /** Structured source input. */
287
- input: SourceInput;
288
- consent?: WalkerOS.Consent;
289
- }
290
- interface SimulateTransformer {
291
- step: 'transformer';
292
- name: string;
293
- code: Transformer.Init;
294
- event: WalkerOS.DeepPartialEvent;
295
- config?: Partial<Transformer.Config>;
296
- }
297
- interface SimulateDestination {
298
- step: 'destination';
299
- name: string;
300
- code: Destination.Instance;
301
- event: WalkerOS.DeepPartialEvent;
302
- config?: Partial<Destination.Config>;
303
- consent?: WalkerOS.Consent;
304
- /** Mock env objects (window, document, fetch, etc.) */
305
- env?: Record<string, unknown>;
306
- /** Dot-paths within env to wrap with call recording, e.g. ["window.gtag"] */
307
- track?: string[];
308
- }
309
- type SimulateParams = SimulateSource | SimulateTransformer | SimulateDestination;
310
-
311
- declare function simulate(params: SimulateParams): Promise<Simulation.Result>;
271
+ declare function transformerInit(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string): Promise<boolean>;
272
+ /**
273
+ * Pushes an event through a single transformer.
274
+ *
275
+ * @param collector - The collector instance
276
+ * @param transformer - The transformer to push to
277
+ * @param transformerId - The transformer ID
278
+ * @param event - The event to process
279
+ * @param ingest - Mutable ingest context flowing through the pipeline
280
+ * @returns The processed event, void for passthrough, or false to stop chain
281
+ */
282
+ declare function transformerPush(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string, event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise<Transformer.Result | Transformer.Result[] | false | void>;
283
+ /**
284
+ * Runs an event through a chain of transformers.
285
+ *
286
+ * @param collector - The collector instance with transformers
287
+ * @param transformers - Map of transformer instances
288
+ * @param chain - Ordered array of transformer IDs to execute
289
+ * @param event - The event to process
290
+ * @param ingest - Mutable ingest context flowing through the pipeline
291
+ * @returns The processed event or null if chain was stopped
292
+ */
293
+ declare function runTransformerChain(collector: Collector.Instance, transformers: Transformer.Transformers, chain: string[], event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn, chainContext?: string): Promise<Transformer.ChainResult>;
312
294
 
313
295
  interface WrapResult {
314
296
  /** Env with tracked paths wrapped by recording functions */
@@ -327,4 +309,11 @@ declare function wrapEnv(env: Record<string, unknown> & {
327
309
  simulation: string[];
328
310
  }): WrapResult;
329
311
 
330
- export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type SimulateDestination, type SimulateParams, type SimulateSource, type SimulateTransformer, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, simulate, startFlow, walkChain, wrapEnv };
312
+ /**
313
+ * Returns the store for a compiled cache config.
314
+ * Uses the explicit store reference if provided, otherwise falls back to the
315
+ * collector's default __cache store.
316
+ */
317
+ declare function getCacheStore(compiled: CompiledCache, collector: Collector.Instance): Store.Instance | undefined;
318
+
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 };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _walkeros_core from '@walkeros/core';
2
- import { Collector, WalkerOS, Elb, Mapping, Destination, On, Source, Transformer, Trigger, Simulation } from '@walkeros/core';
2
+ import { Collector, WalkerOS, Elb, Mapping, Destination, On, Ingest, Source, Transformer, Simulation, CompiledCache, Store } from '@walkeros/core';
3
3
 
4
4
  interface RunState {
5
5
  consent?: WalkerOS.Consent;
@@ -71,7 +71,6 @@ declare const Const: {
71
71
  */
72
72
  declare function processConsent(collector: Collector.Instance, data: WalkerOS.Consent): {
73
73
  update: WalkerOS.Consent;
74
- runQueue: boolean;
75
74
  };
76
75
 
77
76
  declare function startFlow<ElbPush extends Elb.Fn = Elb.Fn>(initConfig?: Collector.InitConfig): Promise<StartFlow<ElbPush>>;
@@ -106,7 +105,7 @@ declare function addDestination(collector: Collector.Instance, data: Destination
106
105
  */
107
106
  declare function pushToDestinations(collector: Collector.Instance, event?: WalkerOS.Event, meta?: {
108
107
  id?: string;
109
- ingest?: unknown;
108
+ ingest?: Ingest;
110
109
  respond?: _walkeros_core.RespondFn;
111
110
  }, destinations?: Collector.Destinations): Promise<Elb.PushResult>;
112
111
  /**
@@ -128,10 +127,10 @@ declare function destinationInit<Destination extends Destination.Instance>(colle
128
127
  * @param destination - The destination to push to.
129
128
  * @param destId - The destination ID.
130
129
  * @param event - The event to push.
131
- * @param ingest - Optional ingest metadata (frozen, same reference).
130
+ * @param ingest - Mutable ingest context flowing through the pipeline.
132
131
  * @returns Whether the event was pushed successfully.
133
132
  */
134
- declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: unknown, respond?: _walkeros_core.RespondFn): Promise<unknown>;
133
+ declare function destinationPush<Destination extends Destination.Instance>(collector: Collector.Instance, destination: Destination, destId: string, event: WalkerOS.Event, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise<unknown>;
135
134
  /**
136
135
  * Creates a standardized result object for push operations.
137
136
  *
@@ -260,55 +259,38 @@ declare function extractTransformerNextMap(transformers: Transformer.Transformer
260
259
  declare function walkChain(startId: string | string[] | undefined, transformers?: Record<string, {
261
260
  next?: string | string[];
262
261
  }>): string[];
263
-
264
262
  /**
265
- * Structured input for source simulation.
266
- * One format every consumer constructs this shape.
263
+ * Initializes a transformer if it hasn't been initialized yet.
264
+ * Called lazily before first push.
265
+ *
266
+ * @param collector - The collector instance
267
+ * @param transformer - The transformer to initialize
268
+ * @param transformerId - The transformer ID
269
+ * @returns Whether initialization succeeded
267
270
  */
268
- interface SourceInput {
269
- /** The actual source input (HTML string, dataLayer array, HTTP request, etc.) */
270
- content: unknown;
271
- /** Which trigger mechanism to fire (e.g., { type: 'click' }) */
272
- trigger?: {
273
- type?: string;
274
- options?: unknown;
275
- };
276
- /** Environment overrides (e.g., custom location, localStorage state) */
277
- env?: Record<string, unknown>;
278
- }
279
- interface SimulateSource {
280
- step: 'source';
281
- name: string;
282
- code: Source.Init;
283
- config?: Partial<Source.Config>;
284
- /** createTrigger factory from the source package's examples. */
285
- createTrigger: Trigger.CreateFn;
286
- /** Structured source input. */
287
- input: SourceInput;
288
- consent?: WalkerOS.Consent;
289
- }
290
- interface SimulateTransformer {
291
- step: 'transformer';
292
- name: string;
293
- code: Transformer.Init;
294
- event: WalkerOS.DeepPartialEvent;
295
- config?: Partial<Transformer.Config>;
296
- }
297
- interface SimulateDestination {
298
- step: 'destination';
299
- name: string;
300
- code: Destination.Instance;
301
- event: WalkerOS.DeepPartialEvent;
302
- config?: Partial<Destination.Config>;
303
- consent?: WalkerOS.Consent;
304
- /** Mock env objects (window, document, fetch, etc.) */
305
- env?: Record<string, unknown>;
306
- /** Dot-paths within env to wrap with call recording, e.g. ["window.gtag"] */
307
- track?: string[];
308
- }
309
- type SimulateParams = SimulateSource | SimulateTransformer | SimulateDestination;
310
-
311
- declare function simulate(params: SimulateParams): Promise<Simulation.Result>;
271
+ declare function transformerInit(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string): Promise<boolean>;
272
+ /**
273
+ * Pushes an event through a single transformer.
274
+ *
275
+ * @param collector - The collector instance
276
+ * @param transformer - The transformer to push to
277
+ * @param transformerId - The transformer ID
278
+ * @param event - The event to process
279
+ * @param ingest - Mutable ingest context flowing through the pipeline
280
+ * @returns The processed event, void for passthrough, or false to stop chain
281
+ */
282
+ declare function transformerPush(collector: Collector.Instance, transformer: Transformer.Instance, transformerId: string, event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn): Promise<Transformer.Result | Transformer.Result[] | false | void>;
283
+ /**
284
+ * Runs an event through a chain of transformers.
285
+ *
286
+ * @param collector - The collector instance with transformers
287
+ * @param transformers - Map of transformer instances
288
+ * @param chain - Ordered array of transformer IDs to execute
289
+ * @param event - The event to process
290
+ * @param ingest - Mutable ingest context flowing through the pipeline
291
+ * @returns The processed event or null if chain was stopped
292
+ */
293
+ declare function runTransformerChain(collector: Collector.Instance, transformers: Transformer.Transformers, chain: string[], event: WalkerOS.DeepPartialEvent, ingest?: Ingest, respond?: _walkeros_core.RespondFn, chainContext?: string): Promise<Transformer.ChainResult>;
312
294
 
313
295
  interface WrapResult {
314
296
  /** Env with tracked paths wrapped by recording functions */
@@ -327,4 +309,11 @@ declare function wrapEnv(env: Record<string, unknown> & {
327
309
  simulation: string[];
328
310
  }): WrapResult;
329
311
 
330
- export { code as Code, type CommandTypes, Commands, Const, type CreateCollector, type HandleCommandFn, type RunState, type SimulateDestination, type SimulateParams, type SimulateSource, type SimulateTransformer, type StartFlow, type StorageType, addDestination, callDestinationOn, commonHandleCommand, createEvent, createPush, createPushResult, destinationInit, destinationPush, extractTransformerNextMap, initDestinations, initSource, initSources, mergeEnvironments, on, onApply, processConsent, pushToDestinations, registerDestination, runCollector, simulate, startFlow, walkChain, wrapEnv };
312
+ /**
313
+ * Returns the store for a compiled cache config.
314
+ * Uses the explicit store reference if provided, otherwise falls back to the
315
+ * collector's default __cache store.
316
+ */
317
+ declare function getCacheStore(compiled: CompiledCache, collector: Collector.Instance): Store.Instance | undefined;
318
+
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 };
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:()=>P,callDestinationOn:()=>A,commonHandleCommand:()=>B,createEvent:()=>U,createPush:()=>J,createPushResult:()=>R,destinationInit:()=>x,destinationPush:()=>$,extractTransformerNextMap:()=>y,initDestinations:()=>T,initSource:()=>j,initSources:()=>q,mergeEnvironments:()=>I,on:()=>D,onApply:()=>E,processConsent:()=>f,pushToDestinations:()=>S,registerDestination:()=>H,runCollector:()=>_,simulate:()=>X,startFlow:()=>W,walkChain:()=>w,wrapEnv:()=>K}),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 f(e,n){let t=!1;const o={};return Object.entries(n).forEach(([e,n])=>{const s=!!n;o[e]=s,t=t||s}),e.consent=(0,u.assign)(e.consent,o),{update:o,runQueue:t}}var l=require("@walkeros/core"),g=require("@walkeros/core"),d=require("@walkeros/core"),p=require("@walkeros/core"),m=require("@walkeros/core"),h=require("@walkeros/core");function y(e){const n={};for(const[t,o]of Object.entries(e))o.config?.next?n[t]={next:o.config.next}:n[t]={};return n}function b(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 w(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 v(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,config:n.config,env:C(n.config.env)};s.debug("init");const i=await(0,h.useHooks)(n.init,"TransformerInit",e.hooks)(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 k(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:{...C(n.config.env),...r?{respond:r}:{}}};a.debug("push",{event:o.name});const u=await(0,h.useHooks)(n.push,"TransformerPush",e.hooks)(o,c);return a.debug("push done"),u}async function O(e,n,t,o,s,r){let i=o,a=r;for(const o of t){const t=n[o];if(!t){e.logger.warn(`Transformer not found: ${o}`);continue}if(!await(0,h.tryCatchAsync)(v)(e,t,o))return e.logger.error(`Transformer init failed: ${o}`),null;const r=await(0,h.tryCatchAsync)(k,n=>(e.logger.scope(`transformer:${t.type||"unknown"}`).error("Push failed",{error:n}),!1))(e,t,o,i,s,a);if(!1===r)return null;if(r&&"object"==typeof r){const{event:t,respond:o,next:c}=r;if(o&&(a=o),c){const o=w(c,y(n));return o.length>0?O(e,n,o,t||i,s,a):(e.logger.warn(`Branch target not found: ${JSON.stringify(c)}`),null)}t&&(i=t)}}return i}function C(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}=t;let c,u;const f=w(a,y(e.transformers)),l=e.logger.scope("source").scope(n),g={push:(t,o={})=>e.push(t,{...o,id:n,ingest:c,respond:u,mapping:s,preChain:f}),command:e.command,sources:e.sources,elb:e.sources.elb.push,logger:l,...r},d={collector:e,logger:l,id:n,config:s,env:g,setIngest:async n=>{c=s.ingest?await(0,m.getMappingValue)(n,s.ingest,{collector:e}):void 0},setRespond:e=>{u=e}},p=await(0,m.tryCatchAsync)(o)(d);if(!p)return;const h=p.type||"unknown",b=e.logger.scope(h).scope(n);return g.logger=b,i&&(p.config={...p.config,primary:i}),p}async function q(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}async function D(e,n,t){const o=e.on,s=o[n]||[],r=(0,d.isArray)(t)?t:[t];r.forEach(e=>{s.push(e)}),o[n]=s,await E(e,n,r)}function A(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:I(n.env,n.config.env)};(0,p.tryCatch)(n.on)(o,a)}async function E(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,p.tryCatchAsync)(t.on)(n,s)&&(i=!0)}if(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});A(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),!r.length)return!i;switch(n){case c.Commands.Consent:!function(e,n,t){const o=t||e.consent;n.forEach(n=>{Object.keys(o).filter(e=>e in n).forEach(t=>{(0,p.tryCatch)(n[t])(e,o)})})}(e,r,o);break;case c.Commands.Ready:case c.Commands.Run:!function(e,n){e.allowed&&n.forEach(n=>{(0,p.tryCatch)(n)(e)})}(e,r);break;case c.Commands.Session:!function(e,n){if(!e.session)return;n.forEach(n=>{(0,p.tryCatch)(n)(e,e.session)})}(e,r);break;default:r.forEach(n=>{"function"==typeof n&&(0,p.tryCatch)(n)(e,s)})}return!i}async function P(e,n,t){const{code:o,config:s={},env:r={},before:i}=n;if(!(0,g.isFunction)(o.push))return R({ok:!1,failed:{invalid:{type:"invalid",error:"Destination code must have a push method"}}});const a=t||s||{init:!1},c=i?{...a,before:i}:a,u={...o,config:c,env:I(o.env,r)};let f=u.config.id;if(!f)do{f=(0,g.getId)(4)}while(e.destinations[f]);return e.destinations[f]=u,!1!==u.config.queue&&(u.queuePush=[...e.queue]),S(e,void 0,{},{[f]:u})}async function S(e,n,t={},o){const{allowed:s,consent:r,globals:i,user:a}=e;if(!s)return R({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])=>{let c=(s.queuePush||[]).map(e=>({...e,consent:r}));if(s.queuePush=[],n){const e=(0,g.clone)(n);c.push(e)}if(!c.length&&!s.queueOn?.length)return{id:o,destination:s,skipped:!0};if(!c.length&&s.queueOn?.length){const n=await(0,g.tryCatchAsync)(x)(e,s,o);return{id:o,destination:s,skipped:!n}}const u=[],f=c.filter(e=>{const n=(0,g.getGrantedConsent)(s.config.consent,r,e.consent);return!n||(e.consent=n,u.push(e),!1)});if(s.queuePush.push(...f),!u.length)return{id:o,destination:s,queue:c};if(!await(0,g.tryCatchAsync)(x)(e,s,o))return{id:o,destination:s,queue:c};let l,d;s.dlq||(s.dlq=[]);const p=function(e,n){const t=e.config.before;return t?w(t,y(n)):[]}(s,e.transformers);let m=0;return await Promise.all(u.map(async n=>{n.globals=(0,g.assign)(i,n.globals),n.user=(0,g.assign)(a,n.user);let r=n;if(p.length>0&&e.transformers&&Object.keys(e.transformers).length>0){const o=await O(e,e.transformers,p,n,t.ingest,t.respond);if(null===o)return n;r=o}const c=Date.now(),u=await(0,g.tryCatchAsync)($,n=>{const t=s.type||"unknown";e.logger.scope(t).error("Push failed",{error:n,event:r.name}),l=n,s.dlq.push([r,n])})(e,s,o,r,t.ingest,t.respond);return m+=Date.now()-c,void 0!==u&&(d=u),n})),{id:o,destination:s,error:l,response:d,totalDuration:m}})),u={},f={},l={};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,l[n.id]=t,o.failed++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.failed++):n.queue&&n.queue.length?f[n.id]=t:(u[n.id]=t,o.count++,o.lastAt=s,o.duration+=n.totalDuration||0,e.status.out++)}return R({event:n,...Object.keys(u).length&&{done:u},...Object.keys(f).length&&{queued:f},...Object.keys(l).length&&{failed:l}})}async function x(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:I(n.env,n.config.env)};s.debug("init");const i=await(0,g.useHooks)(n.init,"DestinationInit",e.hooks)(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)A(e,n,t,s,r)}s.debug("init done")}return!0}async function $(e,n,t,o,s,r){const{config:i}=n,a=await(0,g.processEventMapping)(o,i,e);if(a.ignore)return!1;const c=n.type||"unknown",u=e.logger.scope(c),f={collector:e,logger:u,id:t,config:i,data:a.data,rule:a.mapping,ingest:s,env:{...I(n.env,i.env),...r?{respond:r}:{}}},l=a.mapping,d=a.mappingKey||"* *";if(!l?.batch||!n.pushBatch){u.debug("push",{event:a.event.name});const t=await(0,g.useHooks)(n.push,"DestinationPush",e.hooks)(a.event,f);return u.debug("push done"),t}{if(n.batches=n.batches||{},!n.batches[d]){const o={key:d,events:[],data:[]};n.batches[d]={batched:o,batchFn:(0,g.debounce)(()=>{const o=n.batches[d].batched,a={collector:e,logger:u,id:t,config:i,data:void 0,rule:l,ingest:s,env:{...I(n.env,i.env),...r?{respond:r}:{}}};u.debug("push batch",{events:o.events.length}),(0,g.useHooks)(n.pushBatch,"DestinationPushBatch",e.hooks)(o,a),u.debug("push batch done"),o.events=[],o.data=[]},l.batch)}}const o=n.batches[d];o.batched.events.push(a.event),(0,g.isDefined)(a.data)&&o.batched.data.push(a.data),o.batchFn()}return!0}function R(e){return{ok:!e?.failed,...e}}function H(e){const{code:n,config:t={},env:o={}}=e,{config:s}=b(e,"before"),r={...n.config,...t,...s},i=I(n.env,o);return{...n,config:r,env:i}}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 I(e,n){return e||n?n?e&&(0,g.isObject)(e)&&(0,g.isObject)(n)?{...e,...n}:n:e:{}}var M=require("@walkeros/core"),F=require("@walkeros/core"),G=5e3;async function N(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`)),G))])}catch(t){i.error(`${n} '${e}' destroy failed: ${t}`)}});await Promise.allSettled(o)}async function B(e,n,t,o){let s,r,i=!1,a=!1;switch(n){case c.Commands.Config:(0,F.isObject)(t)&&((0,M.assign)(e.config,t,{shallow:!1}),r=t,i=!0);break;case c.Commands.Consent:if((0,F.isObject)(t)){const{update:n,runQueue:o}=f(e,t);r=n,i=!0,a=o}break;case c.Commands.Custom:(0,F.isObject)(t)&&(e.custom=(0,M.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 P(e,t,o):(0,M.isFunction)(t.push)&&(s=await P(e,{code:t},o)));break;case c.Commands.Globals:(0,F.isObject)(t)&&(e.globals=(0,M.assign)(e.globals,t),r=t,i=!0);break;case c.Commands.On:(0,M.isString)(t)&&await D(e,t,o);break;case c.Commands.Ready:i=!0;break;case c.Commands.Run:s=await _(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 N(e.sources,"source",n),await N(e.destinations,"destination",n),await N(e.transformers,"transformer",n),await N(e.stores,"store",n)}(e);break;case c.Commands.User:(0,F.isObject)(t)&&((0,M.assign)(e.user,t,{shallow:!1}),r=t,i=!0)}return i&&await E(e,n,void 0,r),a&&(s=await S(e)),s||R({ok:!0})}function U(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");++e.count;const{timestamp:s=Date.now(),group:r=e.group,count:i=e.count}=n,{name:a=`${t} ${o}`,data:c={},context:u={},globals:f=e.globals,custom:l={},user:g=e.user,nested:d=[],consent:p=e.consent,id:m=`${s}-${r}-${i}`,trigger:h="",entity:y=t,action:b=o,timing:w=0,version:v={source:e.version,tagging:e.config.tagging||0},source:k={type:"collector",id:"",previous_id:""}}=n;return{name:a,data:c,context:u,globals:f,custom:l,user:g,nested:d,consent:p,id:m,trigger:h,entity:y,action:b,timestamp:s,timing:w,group:r,count:i,version:v,source:k}}async function _(e,n){e.allowed=!0,e.count=0,e.group=(0,M.getId)(),e.timing=Date.now(),n&&(n.consent&&(e.consent=(0,M.assign)(e.consent,n.consent)),n.user&&(e.user=(0,M.assign)(e.user,n.user)),n.globals&&(e.globals=(0,M.assign)(e.config.globalsStatic||{},n.globals)),n.custom&&(e.custom=(0,M.assign)(e.custom,n.custom))),Object.values(e.destinations).forEach(e=>{e.queuePush=[]}),e.queue=[],e.round++;return await S(e)}var z=require("@walkeros/core");function J(e,n){return(0,z.useHooks)(async(t,o={})=>await(0,z.tryCatchAsync)(async()=>{const s=Date.now(),{id:r,ingest:i,respond:a,mapping:c,preChain:u}=o;let f=t;const l=i?Object.freeze(i):void 0;if(c){const n=await(0,z.processEventMapping)(f,c,e);if(n.ignore)return R({ok:!0});if(c.consent){if(!(0,z.getGrantedConsent)(c.consent,e.consent,n.event.consent))return R({ok:!0})}f=n.event}if(u?.length&&e.transformers&&Object.keys(e.transformers).length>0){const n=await O(e,e.transformers,u,f,l,a);if(null===n)return R({ok:!0});f=n}const g=n(f),d=U(e,g),p=await S(e,d,{id:r,ingest:l,respond:a});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 p},()=>R({ok:!1}))(),"Push",e.hooks)}var L=require("@walkeros/core");async function V(e){const n=(0,l.assign)({globalsStatic:{},sessionStatic:{},tagging:0,run:!0},e,{merge:!1,extend:!1}),t={level:e.logger?.level,handler:e.logger?.handler},o=(0,l.createLogger)(t),s={...n.globalsStatic,...e.globals},r={allowed:!1,config:n,consent:e.consent||{},count:0,custom:e.custom||{},destinations:{},transformers:{},stores:{},globals:s,group:"",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.0",sources:{},pending:{sources:{},destinations:{}},push:void 0,command:void 0};r.push=J(r,e=>({timing:Math.round((Date.now()-r.timing)/10)/100,source:{type:"collector",id:"",previous_id:""},...e})),r.command=function(e,n){return(0,L.useHooks)(async(t,o,s)=>await(0,L.tryCatchAsync)(async()=>await n(e,t,o,s),()=>R({ok:!1}))(),"Command",e.hooks)}(r,B);const i=e.stores||{};return 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);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.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}=b(s,"next"),a=Object.keys(r).length>0?{...i,env:r}:i,c=e.logger.scope("transformer").scope(o),u={collector:e,logger:c,id:o,config:a,env:r},f=await n(u);t[o]=f}return t}(r,e.transformers||{}),r}async function W(e){e=e||{};const n=await V(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 R({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 q(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 f=Object.values(n.sources).filter(e=>"elb"!==e.type),l=f.find(e=>e.config.primary);return l?u=l.push:f.length>0&&(u=f[0].push),{collector:n,elb:u}}function Q(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Q);const n={};for(const[t,o]of Object.entries(e))n[t]="function"==typeof o?o:Q(o);return n}function K(e){const n=[],{simulation:t,...o}=e,s=Q(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}}async function X(e){const n=Date.now();try{switch(e.step){case"transformer":return await async function(e,n){const{code:t,config:o={},event:s}=e,{collector:r}=await W({transformers:{sim:{code:t,config:o}}}),i=r.transformers?.sim;if(!i)throw new Error("Transformer failed to initialize");const a=await i.push(s,{collector:r,logger:r.logger.scope("transformer").scope("sim"),id:"sim",config:i.config,env:i.config?.env||{}});let c;c=!1===a?[]:null==a?[s]:[a.event||s];return{step:"transformer",name:e.name,events:c,calls:[],duration:Date.now()-n}}(e,n);case"source":return await async function(e,n){const{code:t,config:o={},createTrigger:s,input:r,consent:i}=e,{content:a,trigger:c}=r,u={functional:!0,marketing:!0,analytics:!0},f=[],l={consent:i||u,sources:{sim:{code:t,config:o,next:"spy"}},transformers:{spy:{code:()=>({type:"spy",config:{},push:e=>(f.push(JSON.parse(JSON.stringify(e))),{event:e})})}}},{trigger:g}=await s(l);void 0!==a&&await g(c?.type,c?.options)(a);return{step:"source",name:e.name,events:f,calls:[],duration:Date.now()-n}}(e,n);case"destination":return await async function(e,n){const{code:t,config:o={},event:s,consent:r,env:i,track:a}=e,c={functional:!0,marketing:!0,analytics:!0};let u=[],f=i;if(i&&a&&a.length>0){const e=K({...i,simulation:a});f=e.wrappedEnv,u=e.calls}const l={...o};f&&(l.env=f);const{collector:g}=await W({consent:r||c,destinations:{sim:{code:t,config:l}}});return await g.push(s),{step:"destination",name:e.name,events:[],calls:u,duration:Date.now()-n}}(e,n)}}catch(t){return{step:e.step,name:e.name,events:[],calls:[],duration:Date.now()-n,error:t instanceof Error?t:new Error(String(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,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