{"version":3,"sources":["../src/types/cache.ts","../src/types/collector.ts","../src/types/context.ts","../src/types/destination.ts","../src/types/elb.ts","../src/types/hooks.ts","../src/types/logger.ts","../src/types/mapping.ts","../src/types/on.ts","../src/types/transformer.ts","../src/types/request.ts","../src/types/source.ts","../src/types/store.ts","../src/types/trigger.ts","../src/types/lifecycle.ts","../src/types/walkeros.ts","../src/types/simulation.ts","../src/types/matcher.ts","../src/types/hint.ts","../src/types/storage.ts","../src/types/ingest.ts","../src/branch.ts","../src/anonymizeIP.ts","../src/throwError.ts","../src/contract.ts","../src/references.ts","../src/flow.ts","../src/assign.ts","../src/is.ts","../src/clone.ts","../src/byPath.ts","../src/include.ts","../src/castValue.ts","../src/consent.ts","../src/createDestination.ts","../src/deepMerge.ts","../src/getId.ts","../src/hexId.ts","../src/getSpanId.ts","../src/eventGenerator.ts","../src/getTraceId.ts","../src/getMarketingParameters.ts","../src/invocations.ts","../src/logger.ts","../src/property.ts","../src/tryCatch.ts","../src/fatalError.ts","../src/mapping.ts","../src/mergeMapping.ts","../src/mockEnv.ts","../src/mockLogger.ts","../src/mockContext.ts","../src/request.ts","../src/send.ts","../src/setup.ts","../src/trim.ts","../src/useHooks.ts","../src/telemetry.ts","../src/telemetryResolver.ts","../src/traceState.ts","../src/emitStep.ts","../src/batchedPoster.ts","../src/userAgent.ts","../src/wrapInlineCode.ts","../src/cdn.ts","../src/mcpHelpers.ts","../src/respond.ts","../src/matcher.ts","../src/route.ts","../src/cache-envelope.ts","../src/store/codec.ts","../src/cache.ts","../src/state.ts","../src/step-entry.ts","../src/examples/formatOut.ts"],"sourcesContent":["import type { MatchExpression } from './matcher';\nimport type { Value } from './mapping';\n\ninterface BaseCacheRule {\n  /**\n   * Optional match expression. Omitted means always-match.\n   */\n  match?: MatchExpression;\n  ttl: number;\n}\n\nexport interface EventCacheRule extends BaseCacheRule {\n  key: string[];\n  update?: Record<string, Value>;\n}\n\nexport interface StoreCacheRule extends BaseCacheRule {\n  // intentionally no key (caller provides one) and no update (no event).\n}\n\nexport type CacheRule = EventCacheRule | StoreCacheRule;\n\nexport interface Cache<R extends CacheRule = CacheRule> {\n  /**\n   * Stop the chain on cache HIT (default: false). When true, skip remaining steps and return cached value.\n   */\n  stop?: boolean;\n  store?: string;\n  /**\n   * Optional key prefix written to the store. When absent, cache keys are written directly. Same store + same key + same namespace = same cache entry.\n   */\n  namespace?: string;\n  rules: R[];\n}\n","import type {\n  Source,\n  Destination,\n  Store,\n  Elb as ElbTypes,\n  Hooks,\n  Logger,\n  On,\n  Transformer,\n  WalkerOS,\n  Mapping,\n} from '.';\nimport type { Ingest } from './ingest';\nimport type { ObserverFn } from './observer';\n\n/** Identifies which kind of step a stepId belongs to. */\nexport type StepKind =\n  | 'collector'\n  | 'source'\n  | 'transformer'\n  | 'destination'\n  | 'store';\n\n/**\n * Build a stepId for use as a key in `Status.dropped` /\n * `Status.connectionErrors` (and future status maps). The collector-level\n * stepId is the literal \"collector\" (no id). Source/transformer/destination/\n * store ids take the form `\"<kind>.<id>\"`, e.g. `\"destination.ga4\"`.\n *\n * The dot separator mirrors the vocabulary already used in collector\n * log messages (\"collector.queue overflow\", \"destination.dlq overflow\").\n */\nexport function stepId(kind: 'collector'): 'collector';\nexport function stepId(\n  kind: 'source' | 'transformer' | 'destination' | 'store',\n  id: string,\n): string;\nexport function stepId(kind: StepKind, id?: string): string {\n  if (kind === 'collector') return 'collector';\n  if (!id) {\n    throw new Error(`stepId(${kind}) requires an id`);\n  }\n  return `${kind}.${id}`;\n}\n\n/**\n * Drop counters at a single step. Each buffer is optional: a step kind\n * may have only `queue` (collector), only `dlq`, both (destinations\n * today), or neither. Counts are monotonic.\n */\nexport interface DroppedCounters {\n  queue?: number;\n  dlq?: number;\n}\n\n/**\n * Circuit-breaker state for a single step (keyed by `stepId()` in\n * `Status.breakers`). Tracks consecutive transport failures so a step whose\n * transport is down can be skipped (gated) until a cooldown elapses, instead\n * of every event hammering a known-broken writer.\n *\n * - `closed`: healthy; events pass through. `consecutiveFailures` accrues on\n *   transport failures and resets to 0 on any success.\n * - `open`: tripped; events are skipped until `openUntil`. The first event at\n *   or after `openUntil` transitions to `half-open` and becomes the probe.\n * - `half-open`: a single probe event is allowed through; `probing` marks that\n *   the probe slot is taken so concurrent events still skip. A probe success\n *   closes the breaker; a probe failure re-opens it with a fresh `openUntil`.\n *\n * `consecutiveFailures` is CONSECUTIVE, not cumulative: a single success\n * resets it, so only an unbroken run reaching the threshold opens the breaker.\n */\nexport interface BreakerState {\n  state: 'closed' | 'open' | 'half-open';\n  consecutiveFailures: number;\n  /** Epoch ms after which an open breaker admits a single probe. */\n  openUntil?: number;\n  /** True while a half-open probe is in flight (probe slot taken). */\n  probing?: boolean;\n}\n\n/**\n * Core collector configuration interface\n */\nexport interface Config {\n  /** Whether to run collector automatically */\n  run?: boolean;\n  /** Static global properties even on a new run */\n  globalsStatic: WalkerOS.Properties;\n  /** Static session data even on a new run */\n  sessionStatic: Partial<SessionData>;\n  /** Logger configuration */\n  logger?: Logger.Config;\n  /**\n   * Maximum number of events retained in `collector.queue` for late-registered\n   * destination backfill. Overflow drops oldest (FIFO). Default 1000.\n   */\n  queueMax?: number;\n}\n\n/**\n * Initialization configuration that extends Config with initial state\n */\nexport interface InitConfig extends Partial<Config> {\n  /** Initial consent state */\n  consent?: WalkerOS.Consent;\n  /** Initial user data */\n  user?: WalkerOS.User;\n  /** Initial global properties */\n  globals?: WalkerOS.Properties;\n  /** Source configurations */\n  sources?: Source.InitSources;\n  /** Destination configurations */\n  destinations?: Destination.InitDestinations;\n  /** Transformer configurations */\n  transformers?: Transformer.InitTransformers;\n  /** Store configurations */\n  stores?: Store.InitStores;\n  /** Initial custom properties */\n  custom?: WalkerOS.Properties;\n  /** Hooks for pipeline observation and interception */\n  hooks?: Hooks.Functions;\n}\n\nexport interface SessionData extends WalkerOS.Properties {\n  isStart: boolean;\n  storage: boolean;\n  id?: string;\n  start?: number;\n  marketing?: true;\n  updated?: number;\n  isNew?: boolean;\n  device?: string;\n  count?: number;\n  runs?: number;\n}\n\nexport interface Status {\n  startedAt: number;\n  in: number;\n  out: number;\n  failed: number;\n  sources: Record<string, SourceStatus>;\n  destinations: Record<string, DestinationStatus>;\n  /**\n   * Monotonic counts of events dropped due to buffer caps, keyed by\n   * stepId. See `stepId()` for key construction.\n   *\n   * Examples:\n   *  - `dropped[\"collector\"]?.queue`: collector replay buffer drops\n   *  - `dropped[\"destination.ga4\"]?.queue`: ga4's consent-denied buffer drops\n   *  - `dropped[\"destination.ga4\"]?.dlq`: ga4's dead-letter queue drops\n   */\n  dropped: Record<string, DroppedCounters>;\n  /**\n   * Per-step circuit-breaker state, keyed by stepId. See `stepId()` for key\n   * construction; keyed step-agnostically (NOT embedded in\n   * `DestinationStatus`) so the breaker can guard any step kind, though\n   * destinations are the primary use today. A breaker is created lazily on\n   * first accounting and stays inert unless its step is configured with a\n   * `breaker` (presence-gated): existing flows never trip a breaker.\n   *\n   * A runtime status field, not drift-guarded (it is observed, never authored\n   * in a flow config).\n   *\n   * Example:\n   *  - `breakers[\"destination.bigquery\"]`: bigquery's consecutive-failure gate.\n   */\n  breakers: Record<string, BreakerState>;\n  /**\n   * Monotonic counts of out-of-band connection-level errors reported by a\n   * step via `context.reportError(err)` with no event (an orphan error from\n   * an EventEmitter SDK object's `'error'` handler), keyed by stepId. See\n   * `stepId()` for key construction; mirrors `dropped`.\n   *\n   * Distinct from `failed`: `failed` counts events lost in-band (a push that\n   * threw, a DLQ'd entry). `connectionErrors` counts connection faults that\n   * did not lose a specific event at the moment they fired. Operators read\n   * both: a rising `connectionErrors` with flat `failed` means a writer is\n   * flapping but events are still landing; both rising means the fault is\n   * now dropping events.\n   *\n   * Example:\n   *  - `connectionErrors[\"destination.bigquery\"]`: BigQuery stream writer\n   *    `'error'` events reported between pushes.\n   */\n  connectionErrors: Record<string, number>;\n}\n\nexport interface SourceStatus {\n  count: number;\n  lastAt?: number;\n  duration: number;\n}\n\nexport interface DestinationStatus {\n  count: number;\n  failed: number;\n  lastAt?: number;\n  duration: number;\n  /** Current size of the destination's queuePush buffer (point-in-time). */\n  queuePushSize: number;\n  /** Current size of the destination's DLQ (point-in-time). */\n  dlqSize: number;\n  /**\n   * Number of events buffered in batch scheduler windows but not yet\n   * delivered to `pushBatch`. Incremented on enqueue, decremented on\n   * flush (whether the flush succeeds or fails). Operators read this\n   * to spot batches that never drain.\n   */\n  inFlightBatch?: number;\n}\n\nexport interface Sources {\n  [id: string]: Source.Instance;\n}\n\nexport interface Destinations {\n  [id: string]: Destination.Instance;\n}\n\nexport interface Transformers {\n  [id: string]: Transformer.Instance;\n}\n\nexport interface Stores {\n  [id: string]: Store.Instance;\n}\n\nexport type CommandType =\n  | 'action'\n  | 'config'\n  | 'consent'\n  | 'context'\n  | 'destination'\n  | 'elb'\n  | 'globals'\n  | 'hook'\n  | 'init'\n  | 'link'\n  | 'run'\n  | 'user'\n  | 'walker'\n  | string;\n\n/**\n * Options passed to collector.push() from sources.\n * NOT a Context - just push metadata.\n */\nexport interface PushOptions {\n  id?: string;\n  ingest?: Ingest;\n  respond?: import('../respond').RespondFn;\n  mapping?: Mapping.Config;\n  preChain?: string[];\n  include?: string[];\n  exclude?: string[];\n}\n\n/**\n * Push function signature - handles events only\n */\nexport interface PushFn {\n  (\n    event: WalkerOS.DeepPartialEvent,\n    options?: PushOptions,\n  ): Promise<ElbTypes.PushResult>;\n}\n\n/**\n * Command function signature - handles walker commands only\n */\nexport interface CommandFn {\n  (command: 'config', config: Partial<Config>): Promise<ElbTypes.PushResult>;\n  (command: 'consent', consent: WalkerOS.Consent): Promise<ElbTypes.PushResult>;\n  <T extends Destination.Types>(\n    command: 'destination',\n    init: Destination.Init<T>,\n  ): Promise<ElbTypes.PushResult>;\n  <K extends keyof Hooks.Functions>(\n    command: 'hook',\n    init: { name: K; fn: Hooks.Functions[K] },\n  ): Promise<ElbTypes.PushResult>;\n  (\n    command: 'on',\n    init: {\n      type: On.Types;\n      rules: WalkerOS.SingleOrArray<On.Subscription>;\n    },\n  ): Promise<ElbTypes.PushResult>;\n  (command: 'user', user: WalkerOS.User): Promise<ElbTypes.PushResult>;\n  (\n    command: 'run',\n    runState?: {\n      consent?: WalkerOS.Consent;\n      user?: WalkerOS.User;\n      globals?: WalkerOS.Properties;\n      custom?: WalkerOS.Properties;\n    },\n  ): Promise<ElbTypes.PushResult>;\n  (command: string, data?: unknown): Promise<ElbTypes.PushResult>;\n}\n\n/**\n * Per-cascade tracking for the bounded recursion guard (see `Instance.cascade`).\n * `counts` maps a subscriber identity object to per-cell-type delivery counts\n * within one top-level command's cascade. A pair is stopped once its count\n * exceeds the guard's bound; the non-convergence error logs once per pair on the\n * crossing transition.\n */\nexport interface Cascade {\n  counts: WeakMap<object, Record<string, number>>;\n}\n\n// Main Collector interface\nexport interface Instance {\n  push: PushFn;\n  command: CommandFn;\n  allowed: boolean;\n  config: Config;\n  consent: WalkerOS.Consent;\n  custom: WalkerOS.Properties;\n  sources: Sources;\n  destinations: Destinations;\n  transformers: Transformers;\n  stores: Stores;\n  globals: WalkerOS.Properties;\n  hooks: Hooks.Functions;\n  /**\n   * First-class observation channel. The runtime self-emits FlowState\n   * records at canonical step sites (collector.push, destination.push,\n   * destination.init, destination.pushBatch, destination consent skip,\n   * transformer.push, store.get/set/delete, store cache HIT/MISS).\n   * Observers run synchronously inside emitStep; thrown values are\n   * swallowed. Subscribers add/remove via the standard Set API.\n   */\n  observers: Set<ObserverFn>;\n  logger: Logger.Instance;\n  on: On.OnConfig;\n  queue: WalkerOS.Events;\n  round: number;\n  /** Run-scoped W3C trace id, minted on each run and stamped onto events. */\n  trace?: string;\n  /** Per-run emission sequence; reset on each run, incremented per stamped event. */\n  count: number;\n  /**\n   * Monotonic counter bumped on every accepted reactive-state mutation\n   * (consent, user, globals, custom). Used for per-subscriber high-water-mark\n   * dedup. Not bumped for non-reactive config changes.\n   */\n  stateVersion: number;\n  /**\n   * Per-cell change version: the `stateVersion` at which each state cell\n   * (`consent`/`user`/`globals`/`custom`) last changed. Lets delivery dedup be\n   * per-cell — a subscriber owed two cells at the same `stateVersion` receives\n   * both, because each cell's freshness is tracked independently rather than\n   * against the single global `stateVersion`. A missing entry reads as 0.\n   */\n  cellVersion: Record<string, number>;\n  /**\n   * Per-subscriber, per-cell high-water mark registry for exactly-once state\n   * delivery. Keys are subscriber identity objects (a ConsentRule object, a\n   * generic-fn, or a source instance); the inner record maps each state-cell\n   * type (`consent`/`user`/`globals`/`custom`) to the `stateVersion` at which\n   * that subscriber was last invoked FOR THAT CELL. A missing entry means never\n   * delivered (sentinel \"-infinity\", read as -1). A subscriber is invoked for a\n   * cell iff `stateVersion > mark[cell]` AND `allowed === true`.\n   *\n   * Per-cell (not a single scalar per subscriber) so a handler owed two\n   * distinct cells at the same `stateVersion` — e.g. consent and user both\n   * bumped before run — receives both at the run barrier instead of the first\n   * delivery advancing one mark and swallowing the second cell's edge.\n   */\n  delivery: WeakMap<object, Record<string, number>>;\n  /**\n   * Transient per-cascade tracking for the bounded recursion guard. A\n   * top-level state command creates this when it first enters the delivery\n   * cascade and tears it down when it returns; nested commands emitted by\n   * reacting callbacks reuse the same structure. It counts deliveries per\n   * `(subscriber, cell-type)` so a cyclic cascade terminates (and logs once)\n   * instead of recursing until stack overflow. `undefined` between top-level\n   * commands. See `on.ts` `cascadeAllow`.\n   *\n   * This tracker, together with `stateVersion` and `delivery`, assumes top-level\n   * state commands are processed serially on a given collector. Concurrent,\n   * overlapping state commands on one shared collector are not supported (web is\n   * serial; the server per-request path is event push, not state commands).\n   */\n  cascade?: Cascade;\n  session: undefined | SessionData;\n  status: Status;\n  timing: number;\n  user: WalkerOS.User;\n  pending: {\n    destinations: Destination.InitDestinations;\n  };\n  /**\n   * Set true on the first `shutdown` command, guarding re-entrancy: a second\n   * `walker shutdown` must not re-run `destroyAllSteps` and double-close\n   * writers, destinations, or stores. Subsequent shutdown commands no-op.\n   * Initialized to `false` by the collector factory; absence (`undefined`)\n   * is treated as \"not yet shut down\", so the first shutdown still runs.\n   */\n  hasShutdown?: boolean;\n  /**\n   * Every event type ever broadcast through `onApply` (state, lifecycle, and\n   * arbitrary). Lets a `require:[<arbitrary>]` gate be satisfied by the current\n   * recorded state for events that have no backing cell, including a broadcast\n   * that fired before the requiring step registered.\n   */\n  seenEvents: Set<string>;\n}\n","import type { Collector, Logger, WalkerOS } from '.';\n\n/**\n * Base context interface for walkerOS stages.\n * Sources, Transformers, and Destinations extend this.\n */\nexport interface Base<C = unknown, E = unknown> {\n  collector: Collector.Instance;\n  logger: Logger.Instance;\n  config: C;\n  env: E;\n  /**\n   * Out-of-band error seam available to every step kind (source,\n   * transformer, store, destination). A step that owns an EventEmitter SDK\n   * object (BigQuery `StreamConnection`, a Redis client, a Kafka producer)\n   * calls this from the object's `'error'` handler, where there is no\n   * surrounding `await`/`tryCatchAsync` to catch into and an unhandled\n   * `'error'` would otherwise crash the process on a detached tick.\n   *\n   * MUST NOT throw (it runs on a detached emitter tick; a throw inside it\n   * would reintroduce the uncaughtException it exists to prevent).\n   *\n   * - With `event`: routes that event through the same per-step failure\n   *   accounting an in-band push failure uses (the destination DLQ + the\n   *   `failed` counters), so a connection error that loses a specific event\n   *   is counted and surfaced exactly like a synchronous push failure.\n   * - Without `event` (an orphan / connection-level error, e.g. a stream\n   *   writer that errored between pushes): a contained `logger.error` plus a\n   *   bump of `Status.connectionErrors[stepId]`. It does NOT bump\n   *   `Status.failed` (no event was lost at this instant; the next push that\n   *   hits the broken writer is what gets DLQ'd and counted as failed, so\n   *   counting the orphan against `failed` would double-count).\n   */\n  reportError?(err: unknown, event?: WalkerOS.Event): void;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n  Collector,\n  Logger,\n  Mapping as WalkerOSMapping,\n  On,\n  Transformer,\n  WalkerOS,\n  Context as BaseContext,\n} from '.';\nimport type { DestroyFn, SetupFn } from './lifecycle';\nimport type { Ingest } from './ingest';\n\n/**\n * Base environment requirements interface for walkerOS destinations\n *\n * This defines the core interface that destinations can use to declare\n * their runtime environment requirements. Platform-specific extensions\n * should extend this interface.\n */\nexport interface BaseEnv {\n  /**\n   * Generic global properties that destinations may require\n   * Platform-specific implementations can extend this interface\n   */\n  [key: string]: unknown;\n}\n\n/**\n * Type bundle for destination generics.\n * Groups Settings, InitSettings, Mapping, Env, and Setup into a single type parameter.\n */\nexport interface Types<\n  S = unknown,\n  M = unknown,\n  E = BaseEnv,\n  I = S,\n  U = unknown,\n  C = unknown,\n> {\n  settings: S;\n  initSettings: I;\n  mapping: M;\n  env: E;\n  setup: U;\n  credentials: C;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n  settings: any;\n  initSettings: any;\n  mapping: any;\n  env: any;\n  setup: any;\n  credentials: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\nexport type SetupOptions<T extends TypesGeneric = Types> = T['setup'];\nexport type Credentials<T extends TypesGeneric = Types> = T['credentials'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n  config: Config<T>;\n  queuePush?: WalkerOS.Events;\n  queueOn?: Array<{ type: On.Types; data?: unknown }>;\n  dlq?: DLQ;\n  batches?: BatchRegistry<Mapping<T>>;\n  type?: string;\n  env?: Env<T>;\n  setup?: SetupFn<Config<T>, Env<T>>;\n  init?: InitFn<T>;\n  push: PushFn<T>;\n  pushBatch?: PushBatchFn<T>;\n  on?: On.OnFn;\n  destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport interface Config<T extends TypesGeneric = Types> {\n  /** Required consent states to push events; queues events when not granted. */\n  consent?: WalkerOS.Consent;\n  /** Implementation-specific configuration passed to the init function. */\n  settings?: InitSettings<T>;\n  /**\n   * Optional, strictly-typed credentials slot ($env-resolved). The package\n   * defines the shape via `Types['credentials']`. `settings.<sdk>` stays the\n   * escape hatch for raw SDK options.\n   */\n  credentials?: Credentials<T>;\n  /** Global data transformation applied to all events; result passed as context.data to push. */\n  data?: WalkerOSMapping.Value | WalkerOSMapping.Values;\n  /** Event sections to flatten into context.data. */\n  include?: string[];\n  /** Runtime dependencies merged from code and config env; extensible per destination. */\n  env?: Env<T>;\n  /** Destination identifier; auto-generated if not provided. */\n  id?: string;\n  /** Whether the destination has been initialized; prevents re-initialization. */\n  init?: boolean;\n  /** Whether to load external scripts (e.g., gtag.js); destination-specific behavior. */\n  loadScript?: boolean;\n  /** Logger configuration (level, handler) to override the collector's defaults. */\n  logger?: Logger.Config;\n  /** Entity-action rules to filter, rename, transform, and batch events for this destination. */\n  mapping?: WalkerOSMapping.Rules<WalkerOSMapping.Rule<Mapping<T>>>;\n  /** Pre-processing rules applied to all events before mapping; modifies events in-place. */\n  policy?: Policy;\n  /** Whether to queue events when consent is not granted; defaults to true. */\n  queue?: boolean;\n  /** Defer destination initialization until these collector events fire (e.g., `['consent']`). */\n  require?: string[];\n  /**\n   * Provisioning options for `walkeros setup`. `boolean | object`.\n   * Triggered only by explicit CLI invocation; never automatic.\n   */\n  setup?: boolean | SetupOptions<T>;\n  /** Transformer chain to run after collector processing but before this destination. */\n  before?: Transformer.Route;\n  /** Transformer chain to run after destination push completes. Push response available at ingest._response. */\n  next?: Transformer.Route;\n  /** Cache configuration for deduplication (step-level: skip push on HIT). */\n  cache?: import('./cache').Cache;\n  /** Declarative store get/set operations applied around this destination. */\n  state?: import('./state').State | import('./state').State[];\n  /** Completely skip this destination — no init, no push, no queuing. */\n  disabled?: boolean;\n  /**\n   * Per-destination delivery timeout in ms (default 10000); a delivery that\n   * does not settle within this window is routed to the DLQ like a thrown push.\n   */\n  timeout?: number;\n  /** Return this value instead of calling push(). Uses !== undefined check to support falsy values. */\n  mock?: unknown;\n  /**\n   * Maximum number of consent-denied events retained in `queuePush` for\n   * this destination. Overflow drops oldest (FIFO). Default 1000.\n   */\n  queueMax?: number;\n  /**\n   * Maximum number of failed-push entries retained in `dlq` for this\n   * destination. Overflow drops oldest (FIFO). Default 100.\n   */\n  dlqMax?: number;\n  /**\n   * Enables batching for ALL of this destination's events into one shared\n   * default buffer. A mapping rule's own `batch` splits that entity-action\n   * into its own buffer and overrides per field (`rule ?? config ?? default`).\n   * Batching stays off when neither is set. A bare number is treated as the\n   * debounce `wait` window.\n   *\n   * - `wait`: debounce window in ms; the timer resets on every push.\n   * - `size`: hard count cap; flush immediately when entries reach this number. Default 1000 when batching is enabled.\n   * - `age`: time since the first entry of the current window. Forces a flush even if pushes keep arriving. Default 30000 (30s).\n   */\n  batch?: number | BatchOptions;\n  /**\n   * Per-destination circuit breaker. Presence-gated: when unset the breaker is\n   * inert and behavior is unchanged. After `threshold` CONSECUTIVE transport\n   * failures (a thrown push, a timed-out push, a whole-batch throw, a\n   * connection-level `reportError(err, event)`) the breaker opens and events\n   * are skipped (counted, not pushed) until `cooldown` ms elapse, then a single\n   * probe event is allowed; its success closes the breaker, its failure\n   * re-opens it. Partial-batch row failures are breaker-neutral. A bare number\n   * is the `threshold`.\n   *\n   * - `threshold`: consecutive transport failures before opening. Default 5.\n   * - `cooldown`: ms an open breaker waits before admitting a probe. Default 30000.\n   */\n  breaker?: number | BreakerOptions;\n}\n\n/**\n * Circuit-breaker tuning. Used at the destination-config layer\n * (`Destination.Config.breaker`). A bare number is treated as `threshold`.\n */\nexport interface BreakerOptions {\n  /** Consecutive transport failures before the breaker opens. Default 5. */\n  threshold?: number;\n  /** Milliseconds an open breaker waits before admitting a probe. Default 30000. */\n  cooldown?: number;\n}\n\n/**\n * Batch scheduling options. Used at both the mapping-rule layer\n * (`Mapping.Rule.batch`) and the destination-config layer\n * (`Destination.Config.batch`). Same shape at both layers.\n */\nexport interface BatchOptions {\n  /** Debounce window in ms. Timer resets on every push. */\n  wait?: number;\n  /** Hard count cap. Flushes immediately at this size. */\n  size?: number;\n  /** Hard age cap in ms since first entry of current window. */\n  age?: number;\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n  Types<\n    Partial<Settings<T>> | Settings<T>,\n    Partial<Mapping<T>> | Mapping<T>,\n    Env<T>,\n    InitSettings<T>,\n    SetupOptions<T>,\n    Credentials<T>\n  >\n>;\n\nexport interface Policy {\n  [key: string]: WalkerOSMapping.Value;\n}\n\nexport type Code<T extends TypesGeneric = Types> = Instance<T>;\n\nexport type Init<T extends TypesGeneric = Types> = {\n  code: Code<T>;\n  config?: Partial<Config<T>>;\n  env?: Partial<Env<T>>;\n  before?: Transformer.Route;\n  next?: Transformer.Route;\n  cache?: import('./cache').Cache;\n  state?: import('./state').State | import('./state').State[];\n};\n\nexport interface InitDestinations {\n  [key: string]: Init<any>;\n}\n\nexport interface Destinations {\n  [key: string]: Instance;\n}\n\n/**\n * Context provided to destination functions.\n * Extends base context with destination-specific properties.\n */\nexport interface Context<\n  T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n  id: string;\n  data?: Data;\n}\n\nexport interface PushContext<\n  T extends TypesGeneric = Types,\n> extends Context<T> {\n  ingest: Ingest;\n  rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport interface PushBatchContext<\n  T extends TypesGeneric = Types,\n> extends Context<T> {\n  ingest: Ingest;\n  rule?: WalkerOSMapping.Rule<Mapping<T>>;\n}\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n  context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type PushFn<T extends TypesGeneric = Types> = (\n  event: WalkerOS.Event,\n  context: PushContext<T>,\n) => WalkerOS.PromiseOrValue<void | unknown>;\n\n/**\n * Per-row outcome for a single failed batch entry.\n *\n * `index` is the position into the flushed batch's `entries` array (the same\n * order `flushBatch` iterates), so the collector can route exactly that entry\n * to the DLQ. `error` is the per-row failure carried into the DLQ pair; when\n * omitted the collector substitutes a generic batch error.\n */\nexport interface BatchFailure {\n  index: number;\n  error?: unknown;\n}\n\n/**\n * Partial-failure result of a `pushBatch` call.\n *\n * `failed` lists the entries (by index into the flushed batch's `entries`\n * array) that did NOT succeed. Every other entry is treated as delivered.\n */\nexport interface BatchOutcome {\n  failed: BatchFailure[];\n}\n\n/**\n * Pushes a batch of events to a destination.\n *\n * Return contract (backward-compatible, additive):\n * - Resolve `void` (the historical contract): the WHOLE batch succeeded. The\n *   collector counts every entry as delivered.\n * - Throw / reject: the WHOLE batch failed. The collector routes every entry\n *   to the DLQ and increments `failed` by the batch size. Unchanged.\n * - Resolve a `BatchOutcome`: PARTIAL failure. Only the entries listed in\n *   `outcome.failed` (by `index` into the flushed `entries` array) are routed\n *   to the DLQ and counted as failed, each with its own `error`. The remaining\n *   entries are counted as delivered. This lets a destination report row-level\n *   failures without forcing already-succeeded rows onto the DLQ, which would\n *   duplicate them on a later DLQ retry.\n *\n * Indices in `failed` must line up with the order of `batch.entries`.\n */\nexport type PushBatchFn<T extends TypesGeneric = Types> = (\n  batch: Batch<Mapping<T>>,\n  context: PushBatchContext<T>,\n) => WalkerOS.PromiseOrValue<void | BatchOutcome>;\n\nexport type PushEvent<Mapping = unknown> = {\n  event: WalkerOS.Event;\n  mapping?: WalkerOSMapping.Rule<Mapping>;\n};\nexport type PushEvents<Mapping = unknown> = Array<PushEvent<Mapping>>;\n\nexport interface BatchEntry<Mapping = unknown> {\n  event: WalkerOS.Event;\n  ingest?: Ingest;\n  respond?: import('../respond').RespondFn;\n  rule?: WalkerOSMapping.Rule<Mapping>;\n  data?: Data;\n}\n\nexport interface Batch<Mapping> {\n  key: string;\n  /**\n   * Per-event entries carrying per-event ingest, respond, rule, and data.\n   * Destinations needing per-event metadata should read this instead of\n   * (or in addition to) `events` and `data`.\n   */\n  entries: BatchEntry<Mapping>[];\n  /** Derived view: events from `entries`. Kept for back-compat. */\n  events: WalkerOS.Events;\n  /** Derived view: data from `entries`. Kept for back-compat. */\n  data: Array<Data>;\n  mapping?: WalkerOSMapping.Rule<Mapping>;\n}\n\nexport interface BatchRegistry<Mapping> {\n  [mappingKey: string]: {\n    batched: Batch<Mapping>;\n    /**\n     * Marks a buffer created by `config.batch` (the destination-wide default\n     * batch) rather than a mapping rule's own `batch`. The default buffer is\n     * heterogeneous, so its flush reports `rule: undefined` to consumers.\n     */\n    isDefault?: boolean;\n    batchFn: () => void;\n    /**\n     * Force a flush of the current batch immediately. Used by shutdown\n     * drain and by tests for deterministic flushing without timer\n     * advancement. Resolves after the underlying `pushBatch` settles.\n     */\n    flush: () => Promise<void>;\n  };\n}\n\nexport type Data =\n  | WalkerOS.Property\n  | undefined\n  | Array<WalkerOS.Property | undefined>;\n\nexport interface Ref {\n  type: string; // Destination type (\"gtag\", \"meta\", \"bigquery\")\n  data?: unknown; // Response from push()\n  error?: unknown; // Error if failed\n}\n\nexport type Push = {\n  queuePush?: WalkerOS.Events;\n  error?: unknown;\n};\n\nexport type DLQ = Array<[WalkerOS.Event, unknown]>;\n\n/**\n * Typed accessor for destinations registered on a collector.\n *\n * The collector's `destinations` bag indexes to `Destination.Instance`\n * (defaults erase the generic). Use this helper at the call site to recover\n * the narrow type without casts.\n *\n * @example\n * type MyDestTypes = Destination.Types<MySettings, MyMapping>;\n * const dest = getDestination<MyDestTypes>(collector, 'myDest');\n * await dest.push(event, context);\n *\n * @throws Error with message `Destination not found: <id>` when the id is unknown.\n */\nexport function getDestination<T extends TypesGeneric = Types>(\n  collector: { destinations: { [id: string]: Instance<any> } },\n  id: string,\n): Instance<T> {\n  const destination = collector.destinations[id];\n  if (!destination) {\n    throw new Error(`Destination not found: ${id}`);\n  }\n  return destination as unknown as Instance<T>;\n}\n","import type { Destination, Hooks, On, WalkerOS } from '.';\n\n// Event signatures only\nexport interface EventFn<R = Promise<PushResult>> {\n  (partialEvent: WalkerOS.DeepPartialEvent): R;\n  (event: string): R;\n  (event: string, data: WalkerOS.Properties): R;\n}\n\n// Complete function interface - can be extended by other interfaces\nexport interface Fn<R = Promise<PushResult>, Config = unknown>\n  extends EventFn<R>, WalkerCommands<R, Config> {\n  // Interface intentionally empty - combines EventFn and WalkerCommands\n}\n\n// Walker commands (clear, predefined list)\nexport interface WalkerCommands<R = Promise<PushResult>, Config = unknown> {\n  (event: 'walker config', config: Partial<Config>): R;\n  (event: 'walker consent', consent: WalkerOS.Consent): R;\n  <T extends Destination.Types>(\n    event: 'walker destination',\n    init: Destination.Init<T>,\n  ): R;\n  <K extends keyof Hooks.Functions>(\n    event: 'walker hook',\n    init: { name: K; fn: Hooks.Functions[K] },\n  ): R;\n  (\n    event: 'walker on',\n    init: {\n      type: On.Types;\n      rules: WalkerOS.SingleOrArray<On.Subscription>;\n    },\n  ): R;\n  (event: 'walker user', user: WalkerOS.User): R;\n  (\n    event: 'walker run',\n    runState?: {\n      consent?: WalkerOS.Consent;\n      user?: WalkerOS.User;\n      globals?: WalkerOS.Properties;\n      custom?: WalkerOS.Properties;\n    },\n  ): R;\n}\n\nexport type Event<R = Promise<PushResult>> = (\n  partialEvent: WalkerOS.DeepPartialEvent,\n) => R;\n\n// Simplified push data types for core collector\nexport type PushData<Config = unknown> =\n  | WalkerOS.DeepPartial<Config>\n  | WalkerOS.Consent\n  | WalkerOS.User\n  | WalkerOS.Properties;\n\nexport interface PushResult {\n  ok: boolean;\n  event?: WalkerOS.Event;\n  done?: Record<string, Destination.Ref>;\n  queued?: Record<string, Destination.Ref>;\n  failed?: Record<string, Destination.Ref>;\n}\n\n// Simplified Layer type for core collector\nexport type Layer = Array<IArguments | WalkerOS.DeepPartialEvent | unknown[]>;\n","// Define a generic type for functions with specific parameters and return type\nexport type AnyFunction<P extends unknown[] = never[], R = unknown> = (\n  ...args: P\n) => R;\n\n// Define a generic type for a dictionary of functions\nexport type Functions = {\n  [key: string]: AnyFunction;\n};\n\n// Define a parameter interface to wrap the function and its result\ninterface Parameter<P extends unknown[], R> {\n  fn: (...args: P) => R;\n  result?: R;\n}\n\n// Define the HookFn type using generics for better type safety\nexport type HookFn<T extends AnyFunction> = (\n  params: Parameter<Parameters<T>, ReturnType<T>>,\n  ...args: Parameters<T>\n) => ReturnType<T>;\n","/**\n * Log levels from most to least severe\n */\nexport enum Level {\n  ERROR = 0,\n  WARN = 1,\n  INFO = 2,\n  DEBUG = 3,\n}\n\n/**\n * Normalized error context extracted from Error objects\n */\nexport interface ErrorContext {\n  message: string;\n  name: string;\n  stack?: string;\n  cause?: unknown;\n}\n\n/**\n * Context passed to log handlers\n * If an Error was passed, it's normalized into the error property\n */\nexport interface LogContext {\n  [key: string]: unknown;\n  error?: ErrorContext;\n}\n\n/**\n * Log message function signature\n * Accepts string or Error as message, with optional context\n */\nexport type LogFn = (\n  message: string | Error,\n  context?: unknown | Error,\n) => void;\n\n/**\n * Throw function signature - logs error then throws\n * Returns never as it always throws\n */\nexport type ThrowFn = (message: string | Error, context?: unknown) => never;\n\n/**\n * Default handler function (passed to custom handlers for chaining)\n */\nexport type DefaultHandler = (\n  level: Level,\n  message: string,\n  context: LogContext,\n  scope: string[],\n) => void;\n\n/**\n * Custom log handler function\n * Receives originalHandler to allow middleware-style chaining\n */\nexport type Handler = (\n  level: Level,\n  message: string,\n  context: LogContext,\n  scope: string[],\n  originalHandler: DefaultHandler,\n) => void;\n\n/**\n * Logger instance with scoping support\n * All logs automatically include trace path from scoping\n */\nexport interface Instance {\n  /**\n   * Log an error message (always visible unless silenced)\n   */\n  error: LogFn;\n\n  /**\n   * Log a warning (degraded state, config issues, transient failures)\n   */\n  warn: LogFn;\n\n  /**\n   * Log an informational message\n   */\n  info: LogFn;\n\n  /**\n   * Log a debug message\n   */\n  debug: LogFn;\n\n  /**\n   * Log an error message and throw an Error\n   * Combines logging and throwing in one call\n   */\n  throw: ThrowFn;\n\n  /**\n   * Output structured JSON data\n   */\n  json: (data: unknown) => void;\n\n  /**\n   * Create a scoped child logger with automatic trace path\n   * @param name - Scope name (e.g., destination type, destination key)\n   * @returns A new logger instance with the scope applied\n   */\n  scope: (name: string) => Instance;\n}\n\n/**\n * Logger configuration options\n */\nexport interface Config {\n  /**\n   * Minimum log level to display\n   * @default Level.ERROR\n   */\n  level?: Level | keyof typeof Level;\n\n  /**\n   * Custom log handler function\n   * Receives originalHandler to preserve default behavior\n   */\n  handler?: Handler;\n\n  /** Custom handler for json() output. Default: console.log(JSON.stringify(data, null, 2)) */\n  jsonHandler?: (data: unknown) => void;\n}\n\n/**\n * Internal config with resolved values and scope\n */\nexport interface InternalConfig {\n  level: Level;\n  handler?: Handler;\n  jsonHandler?: (data: unknown) => void;\n  scope: string[];\n}\n\n/**\n * Logger factory function type\n */\nexport type Factory = (config?: Config) => Instance;\n","import type { Collector, Destination, Logger, WalkerOS } from '.';\n\n/**\n * Shared mapping configuration interface.\n * Used by both Source.Config and Destination.Config.\n */\nexport interface Config<T = unknown> {\n  consent?: WalkerOS.Consent; // Required consent to process events\n  data?: Value | Values; // Global data transformation\n  include?: string[]; // Event sections to flatten into context.data\n  mapping?: Rules<Rule<T>>; // Event-specific mapping rules\n  policy?: Policy; // Pre-processing rules\n}\n\nexport interface Policy {\n  [key: string]: Value;\n}\n\nexport interface Rules<T = Rule> {\n  [entity: string]: Record<string, T | Array<T>> | undefined;\n}\n\nexport interface Rule<Settings = unknown> {\n  /**\n   * Batch scheduling for this event mapping. When present, it splits this\n   * event type into its own buffer, overriding `config.batch` per field\n   * (`rule ?? config ?? default`). A bare number is the debounce `wait`\n   * window. Object form supports `wait` (debounce ms), `size` (count cap),\n   * and `age` (max ms since first entry).\n   */\n  batch?: number | Destination.BatchOptions;\n  condition?: Condition; // Added condition\n  consent?: WalkerOS.Consent; // Required consent states process the event\n  settings?: Settings; // Arbitrary but protected configurations for custom event config\n  data?: Data; // Mapping of event data\n  include?: string[]; // Event sections to flatten into context.data\n  ignore?: boolean; // Choose to no process an event when set to true\n  silent?: boolean; // Process settings side effects, but suppress the destination's default push call\n  name?: string; // Use a custom event name\n  policy?: Policy; // Event-level policy applied after config-level policy\n  /**\n   * Merge mode (config layer): a partial Rule deep-merged onto the\n   * package-shipped default rule at the same key, instead of replacing it.\n   * Resolved at the consuming package's init via `mergeMappingRule`; not\n   * seen by the runtime evaluator. A `null` value clears an inherited field.\n   * Presence of `extend` or `remove` switches this rule from replace to merge.\n   */\n  extend?: RulePatch<Settings>;\n  /**\n   * Output layer: dotted paths stripped from the produced data payload\n   * after evaluation, regardless of how each field was produced. Applied\n   * last, so it always wins.\n   */\n  remove?: string[];\n}\n\n/**\n * A partial Rule used by `Rule.extend`. Every field is optional, and a\n * `null` value clears the inherited field (JSON merge-patch delete). The\n * control fields `extend` and `remove` are excluded: a patch models only\n * direct rule fields, matching what the runtime patch schema accepts.\n */\ntype RulePatchFields<Settings = unknown> = Omit<\n  Rule<Settings>,\n  'extend' | 'remove'\n>;\nexport type RulePatch<Settings = unknown> = {\n  [K in keyof RulePatchFields<Settings>]?: RulePatchFields<Settings>[K] | null;\n};\n\nexport interface Result {\n  eventMapping?: Rule;\n  mappingKey?: string;\n}\n\nexport type Data = Value | Values;\nexport type Value = ValueType | Array<ValueType>;\nexport type Values = Array<Value>;\nexport type ValueType = string | ValueConfig;\n\nexport interface ValueConfig {\n  condition?: Condition;\n  consent?: WalkerOS.Consent;\n  fn?: Fn;\n  key?: string;\n  loop?: Loop;\n  map?: Map;\n  set?: Value[];\n  validate?: Validate;\n  value?: WalkerOS.PropertyType;\n}\n\n// Per-event callback context. Distinct from Context.Base (lifecycle-time) because mappings have no config/env of their own.\nexport interface Context {\n  event: WalkerOS.DeepPartialEvent;\n  /** The surrounding mapping config: a Value (value-level) or a Rule (rule-level). */\n  mapping: Value | Rule;\n  collector: Collector.Instance;\n  logger: Logger.Instance;\n  consent?: WalkerOS.Consent;\n}\n\nexport type Fn = (\n  value: unknown,\n  context: Context,\n) => WalkerOS.PromiseOrValue<WalkerOS.Property | unknown>;\n\nexport type Condition = (\n  value: unknown,\n  context: Context,\n) => WalkerOS.PromiseOrValue<boolean>;\n\nexport type Validate = (\n  value: unknown,\n  context: Context,\n) => WalkerOS.PromiseOrValue<boolean>;\n\nexport type Loop = [Value, Value];\n\nexport type Map = { [key: string]: Value };\n","import type { Collector, Destination, Logger, WalkerOS } from './';\n\n/** Collector state mapping for the `on` actions. */\nexport type Config = {\n  config?: Array<GenericFn>;\n  consent?: Array<ConsentRule>;\n  custom?: Array<GenericFn>;\n  globals?: Array<GenericFn>;\n  ready?: Array<ReadyFn>;\n  run?: Array<RunFn>;\n  session?: Array<SessionFn>;\n  user?: Array<UserFn>;\n};\n\n/** Allow arbitrary string events via `(string & {})`. */\nexport type Types = keyof Config | (string & {});\n\n/** Map each event type to its expected data payload type. */\nexport interface EventDataMap {\n  config: Partial<Collector.Config>;\n  consent: WalkerOS.Consent;\n  custom: WalkerOS.Properties;\n  globals: WalkerOS.Properties;\n  ready: void;\n  run: void;\n  session: Collector.SessionData | undefined;\n  user: WalkerOS.User;\n}\n\n/** Extract the data type for a specific event. */\nexport type EventData<T extends keyof EventDataMap> = EventDataMap[T];\n\n/** Union of all possible data types. */\nexport type AnyEventData = EventDataMap[keyof EventDataMap];\n\n/**\n * Context provided to every `on` callback.\n * Same posture as Mapping.Context: collector + logger only;\n * subscriptions are a collector-level concern, not a stage-level one.\n */\nexport interface Context {\n  collector: Collector.Instance;\n  logger: Logger.Instance;\n}\n\n/** Unified subscription callback shape. */\nexport type Fn<TData = unknown> = (\n  data: TData,\n  context: Context,\n) => WalkerOS.PromiseOrValue<void>;\n\n/** Typed-data variants for readability and IntelliSense. All reduce to Fn<TData>. */\nexport type ConsentFn = Fn<WalkerOS.Consent>;\nexport type GenericFn = Fn<unknown>;\nexport type ReadyFn = Fn<void>;\nexport type RunFn = Fn<void>;\nexport type SessionFn = Fn<Collector.SessionData | undefined>;\nexport type UserFn = Fn<WalkerOS.User>;\n\n/**\n * Consent rule: a record of `{ [consentKey]: ConsentFn }`.\n * Only the consent action uses this shape (per-key handler dispatch).\n */\nexport interface ConsentRule {\n  [key: string]: ConsentFn;\n}\n\n/** Anything registerable via `walker.on(action, X)`: a typed callback or a consent rule record. */\nexport type Subscription =\n  | ConsentRule\n  | GenericFn\n  | ReadyFn\n  | RunFn\n  | SessionFn\n  | UserFn;\n\nexport interface OnConfig {\n  config?: GenericFn[];\n  consent?: ConsentRule[];\n  custom?: GenericFn[];\n  globals?: GenericFn[];\n  ready?: ReadyFn[];\n  run?: RunFn[];\n  session?: SessionFn[];\n  user?: UserFn[];\n  [key: string]:\n    | ConsentRule[]\n    | GenericFn[]\n    | ReadyFn[]\n    | RunFn[]\n    | SessionFn[]\n    | UserFn[]\n    | undefined;\n}\n\n/**\n * Destination `on` handler: receives the action type and a destination context.\n * Already context-style; kept for compatibility with the destination interface.\n */\nexport type OnFn<T extends Destination.TypesGeneric = Destination.Types> = (\n  type: Types,\n  context: Destination.Context<T>,\n) => WalkerOS.PromiseOrValue<void>;\n\nexport type OnFnRuntime = (\n  type: Types,\n  context: Destination.Context,\n) => WalkerOS.PromiseOrValue<void>;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Collector, Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn } from './lifecycle';\nimport type { Ingest } from './ingest';\nimport type { Config as MappingConfig } from './mapping';\nimport type { MatchExpression } from './matcher';\n\n/**\n * Unified route grammar for Flow v4. A `Route` is one of:\n * - a transformer ID string (`\"redact\"`)\n * - a sequence of routes (`[\"a\", \"b\", \"c\"]` — sugar for chained `.next`)\n * - a `RouteConfig` — a gated / dispatching node.\n *\n * `RouteConfig` is a disjoint union — set exactly one of `next`, `one`,\n * `many`, or neither (pure gate). The disjointness is enforced by `never`\n * sibling properties at the type level and `z.strictObject` at the schema\n * level.\n *\n * Operators:\n * - `next`: single continuation.\n * - `one`: first-match dispatch (walk entries, first whose match passes wins).\n * - `many`: all-match terminal fan-out (every matching entry spawns an\n *   independent flow; main chain terminates here). Restricted to\n *   pre-collector positions (source.next, transformer.next, transformer.before).\n */\nexport type Route = string | Route[] | RouteConfig;\n\nexport type RouteConfig =\n  | RouteNextConfig\n  | RouteOneConfig\n  | RouteManyConfig\n  | RouteGateConfig;\n\nexport interface RouteNextConfig {\n  match?: MatchExpression;\n  next: Route;\n  one?: never;\n  many?: never;\n}\n\nexport interface RouteOneConfig {\n  match?: MatchExpression;\n  one: Route[];\n  next?: never;\n  many?: never;\n}\n\nexport interface RouteManyConfig {\n  match?: MatchExpression;\n  many: Route[];\n  next?: never;\n  one?: never;\n}\n\nexport interface RouteGateConfig {\n  match: MatchExpression;\n  next?: never;\n  one?: never;\n  many?: never;\n}\n\n/**\n * Base environment interface for walkerOS transformers.\n *\n * Minimal like Destination - just an extensible object.\n * Transformers receive dependencies through context, not env.\n */\nexport interface BaseEnv {\n  [key: string]: unknown;\n}\n\n/**\n * Type bundle for transformer generics.\n * Groups Settings, InitSettings, and Env into a single type parameter.\n * Follows the Source/Destination pattern.\n *\n * @template S - Settings configuration type\n * @template E - Environment type\n * @template I - InitSettings configuration type (user input)\n */\nexport interface Types<S = unknown, E = BaseEnv, I = S> {\n  settings: S;\n  initSettings: I;\n  env: E;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access.\n */\nexport type TypesGeneric = {\n  settings: any;\n  initSettings: any;\n  env: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle.\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\n\n/**\n * Inference helper: Extract Types from Instance.\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\n/**\n * Transformer configuration.\n */\nexport interface Config<T extends TypesGeneric = Types> {\n  settings?: InitSettings<T>;\n  env?: Env<T>;\n  id?: string;\n  logger?: Logger.Config;\n  before?: Route; // Pre-transformer chain (runs before push)\n  next?: Route; // Graph wiring to next transformer\n  cache?: import('./cache').Cache; // Step-level cache config\n  /** Declarative store get/set operations applied around this transformer. */\n  state?: import('./state').State | import('./state').State[];\n  init?: boolean; // Track init state (like Destination)\n  disabled?: boolean; // Completely skip this transformer in chains\n  /** Return this value instead of calling push(). Global mock for all chains. */\n  mock?: unknown;\n  /** Path-specific mock values keyed by chain path (e.g., \"destination.ga4.before\"). Takes precedence over global mock. */\n  chainMocks?: Record<string, unknown>;\n  /**\n   * Declarative event-to-event mapping applied when this transformer step\n   * has no `code`. Same field name as on `Destination.Config`, but the\n   * semantic differs by position: on a destination, `mapping` produces a\n   * vendor-shaped payload; on a transformer step, it mutates the event\n   * itself. The collector synthesizes a push that runs\n   * `processEventMapping` and returns the transformed event (or drops it\n   * when a rule has `ignore: true`).\n   *\n   * At the transformer position, only event-mutating fields apply:\n   * `policy`, `mapping[].policy`, `mapping[].name`, `mapping[].ignore`,\n   * `mapping[].consent`, `include`. Vendor-payload fields (`data`,\n   * `mapping[].data`, `silent`) are ignored at this position with a\n   * one-time warning.\n   */\n  mapping?: MappingConfig;\n}\n\n/**\n * Context provided to transformer functions.\n * Extends base context with transformer-specific properties.\n */\nexport interface Context<\n  T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n  id: string;\n  ingest: Ingest;\n}\n\n/**\n * Unified result type for transformer functions.\n * Replaces the old union return type with a structured object.\n *\n * @field event - Modified event to continue with\n * @field respond - Wrapped respond function for downstream transformers\n * @field next - Branch to a different chain (replaces BranchResult)\n */\nexport interface Result<E = WalkerOS.DeepPartialEvent> {\n  event?: E;\n  respond?: import('../respond').RespondFn;\n  next?: Route;\n}\n\n/**\n * Result of running a transformer chain.\n * Returns the processed event (singular, fan-out array, or null if dropped)\n * alongside the potentially wrapped respond function.\n *\n * `stopped` signals pipeline-halt — when set, the caller MUST NOT propagate\n * the event further downstream (no destinations, no subsequent chains).\n * Used by `cache.stop: true` on pre-collector transformers so the documented\n * \"downstream transformers and destinations are skipped\" semantic holds.\n */\nexport interface ChainResult {\n  event: WalkerOS.DeepPartialEvent | WalkerOS.DeepPartialEvent[] | null;\n  respond?: import('../respond').RespondFn;\n  stopped?: true;\n}\n\n/**\n * The main transformer function.\n *\n * Pre-collector transformers use default E = DeepPartialEvent.\n * Post-collector transformers can use E = Event for type-safe access.\n * A transformer written for DeepPartialEvent works in both positions\n * because Event is a subtype of DeepPartialEvent.\n *\n * @returns Result - structured result with event, respond, next\n * @returns Result[] - fan-out: each Result continues independently through remaining chain\n * @returns void - continue with current event unchanged (passthrough)\n * @returns false - stop chain, cancel further processing\n */\nexport type Fn<\n  T extends TypesGeneric = Types,\n  E = WalkerOS.DeepPartialEvent,\n> = (\n  event: E,\n  context: Context<T>,\n) => WalkerOS.PromiseOrValue<Result<E> | Result<E>[] | false | void>;\n\n/**\n * Optional initialization function.\n * Called once before first push.\n *\n * @param context - Transformer context\n * @returns void - initialization successful\n * @returns false - initialization failed, skip this transformer\n * @returns Config<T> - return updated config\n */\nexport type InitFn<T extends TypesGeneric = Types> = (\n  context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\n/**\n * Transformer instance returned by Init function.\n */\nexport interface Instance<T extends TypesGeneric = Types> {\n  type: string;\n  config: Config<T>;\n  push: Fn<T>; // Named \"push\" for consistency with Source/Destination\n  init?: InitFn<T>; // Optional, called once before first push\n  destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\n/**\n * Transformer initialization function.\n * Creates a transformer instance from context.\n */\nexport type Init<T extends TypesGeneric = Types> = (\n  context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\n/**\n * Configuration for initializing a transformer.\n * Used in collector registration.\n */\nexport type InitTransformer<T extends TypesGeneric = Types> = {\n  /**\n   * Initialization function. When omitted, the entry is a pass-through step:\n   * - If `mapping` is present, the collector synthesizes a mapping-only\n   *   push using `processEventMapping`.\n   * - Otherwise it's a named hop that only hosts a `before` / `next` /\n   *   `cache` chain.\n   *\n   * Validation: an entry without `code` must declare at least one of\n   * `package`, `before`, `next`, `cache`, `state`, `mapping`. Enforced by\n   * `validateStepEntry` in `@walkeros/core`.\n   */\n  code?: Init<T>;\n  config?: Partial<Config<T>>;\n  env?: Partial<Env<T>>;\n  before?: Route;\n  next?: Route;\n  cache?: import('./cache').Cache;\n  state?: import('./state').State | import('./state').State[];\n  mapping?: MappingConfig;\n};\n\n/**\n * Transformers configuration for collector.\n * Maps transformer IDs to their initialization configurations.\n */\nexport interface InitTransformers {\n  [transformerId: string]: InitTransformer<any>;\n}\n\n/**\n * Active transformer instances registry.\n */\nexport interface Transformers {\n  [transformerId: string]: Instance;\n}\n\n/**\n * Typed accessor for transformers registered on a collector.\n *\n * The collector's `transformers` bag indexes to `Transformer.Instance`\n * (defaults erase the generic). Use this helper at the call site to recover\n * the narrow type without casts.\n *\n * @example\n * type MyTransformerTypes = Transformer.Types<MySettings>;\n * const tx = getTransformer<MyTransformerTypes>(collector, 'redact');\n * await tx.push(event, context);\n *\n * @throws Error with message `Transformer not found: <id>` when the id is unknown.\n */\nexport function getTransformer<T extends TypesGeneric = Types>(\n  collector: { transformers: { [id: string]: Instance<any> } },\n  id: string,\n): Instance<T> {\n  const transformer = collector.transformers[id];\n  if (!transformer) {\n    throw new Error(`Transformer not found: ${id}`);\n  }\n  return transformer as unknown as Instance<T>;\n}\n","export interface Context {\n  city?: string;\n  country?: string;\n  encoding?: string;\n  hash?: string;\n  ip?: string;\n  language?: string;\n  origin?: string;\n  region?: string;\n  userAgent?: string;\n  [key: string]: string | undefined;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n  Elb,\n  On,\n  Logger,\n  Mapping as WalkerOSMapping,\n  Collector,\n  Context as BaseContext,\n} from './index';\nimport type { Ingest } from './ingest';\nimport type { DestroyFn, SetupFn } from './lifecycle';\nimport type { RespondFn } from '../respond';\nimport type { Route } from './transformer';\n\n/**\n * Base Env interface for dependency injection into sources.\n *\n * Sources receive all their dependencies through this environment object,\n * making them platform-agnostic and easily testable.\n */\nexport interface BaseEnv {\n  [key: string]: unknown;\n  push: Collector.PushFn;\n  command: Collector.CommandFn;\n  sources?: Collector.Sources;\n  elb: Elb.Fn;\n  logger: Logger.Instance;\n}\n\n/**\n * Type bundle for source generics.\n * Groups Settings, Mapping, Push, Env, InitSettings, and Setup into a single type parameter.\n *\n * @template S - Settings configuration type\n * @template M - Mapping configuration type\n * @template P - Push function signature (flexible to support HTTP handlers, etc.)\n * @template E - Environment dependencies type\n * @template I - InitSettings configuration type (user input)\n * @template U - Setup options type (provisioning options for `walkeros setup`)\n */\nexport interface Types<\n  S = unknown,\n  M = unknown,\n  P = Elb.Fn,\n  E = BaseEnv,\n  I = S,\n  U = unknown,\n  C = unknown,\n> {\n  settings: S;\n  initSettings: I;\n  mapping: M;\n  push: P;\n  env: E;\n  setup: U;\n  credentials: C;\n}\n\n/**\n * Generic constraint for Types - ensures T has required properties for indexed access\n */\nexport type TypesGeneric = {\n  settings: any;\n  initSettings: any;\n  mapping: any;\n  push: any;\n  env: any;\n  setup: any;\n  credentials: any;\n};\n\n/**\n * Type extractors for consistent usage with Types bundle\n */\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Mapping<T extends TypesGeneric = Types> = T['mapping'];\nexport type Push<T extends TypesGeneric = Types> = T['push'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\nexport type SetupOptions<T extends TypesGeneric = Types> = T['setup'];\nexport type Credentials<T extends TypesGeneric = Types> = T['credentials'];\n\n/**\n * Inference helper: Extract Types from Instance\n */\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<\n  T extends TypesGeneric = Types,\n> extends WalkerOSMapping.Config<Mapping<T>> {\n  /** Implementation-specific configuration passed to the init function. */\n  settings?: InitSettings<T>;\n  /**\n   * Optional, strictly-typed credentials slot ($env-resolved). The package\n   * defines the shape via `Types['credentials']`. `settings.<sdk>` stays the\n   * escape hatch for raw SDK options.\n   */\n  credentials?: Credentials<T>;\n  /** Runtime dependencies injected by the collector (push, command, logger, etc.). */\n  env?: Env<T>;\n  /** Source identifier; defaults to the InitSources object key. */\n  id?: string;\n  /** Logger configuration (level, handler) to override the collector's defaults. */\n  logger?: Logger.Config;\n  /**\n   * Respond-first acknowledgement for response-producing server sources.\n   *\n   * When a source produces an HTTP response (express today; future fetch /\n   * lambda), `async: true` (the default for such sources) responds 2xx\n   * (\"accepted\") before the event is delivered to the collector, so the\n   * client is not blocked on backend delivery. `async: false` waits for\n   * delivery to settle before responding. A 2xx means \"accepted\", not\n   * \"delivered\".\n   *\n   * Browser and dataLayer sources have no HTTP response to defer and ignore\n   * this flag. The default is per source type.\n   */\n  async?: boolean;\n  /** Mark as primary source; its push function becomes the exported `elb` from startFlow. */\n  primary?: boolean;\n  /** Defer source initialization until these collector events fire (e.g., `['consent']`). */\n  require?: string[];\n  /**\n   * Provisioning options for `walkeros setup`. `boolean | object`.\n   * Triggered only by explicit CLI invocation; never automatic.\n   */\n  setup?: boolean | SetupOptions<T>;\n  /**\n   * Ingest metadata extraction mapping.\n   * Extracts values from raw request objects (Express req, Lambda event, etc.)\n   * using walkerOS mapping syntax. Extracted data flows to transformers/destinations.\n   *\n   * @example\n   * ingest: {\n   *   ip: 'req.ip',\n   *   ua: 'req.headers.user-agent',\n   *   origin: 'req.headers.origin'\n   * }\n   */\n  ingest?: WalkerOSMapping.Data;\n  /** Completely skip this source — no init, no event capture. */\n  disabled?: boolean;\n  /**\n   * Init lifecycle flag. Set by the collector to `true` after `Instance.init()`\n   * has been called. Used together with `require` to gate `on()` delivery:\n   * lifecycle events are queued in `Instance.queueOn` until both\n   * `config.init === true` and `config.require` is empty/absent, then replayed.\n   */\n  init?: boolean;\n  /** Declarative store get/set operations applied around this source. */\n  state?: import('./state').State | import('./state').State[];\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n  Types<\n    Partial<Settings<T>> | Settings<T>,\n    Partial<Mapping<T>> | Mapping<T>,\n    Push<T>,\n    Env<T>,\n    InitSettings<T>,\n    SetupOptions<T>,\n    Credentials<T>\n  >\n>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n  type: string;\n  config: Config<T>;\n  setup?: SetupFn<Config<T>, Env<T>>;\n  push: Push<T>;\n  destroy?: DestroyFn<Config<T>, Env<T>>;\n  on?(\n    event: On.Types,\n    context?: unknown,\n  ): void | boolean | Promise<void | boolean>;\n  /**\n   * Optional setup hook. Called by the collector eagerly after all source\n   * factories have run, regardless of `config.require`. Use for prep work\n   * such as draining a pre-init window queue or attaching DOM listeners.\n   * The collector still gates `on()` delivery, and `Collector.push`\n   * enforces `allowed`/consent at the destination layer.\n   */\n  init?: () => void | Promise<void>;\n  /**\n   * Lifecycle event queue. Populated by `onApply` when the source is not\n   * yet started (`config.init !== true` or `config.require` non-empty).\n   * Flushed by the collector when the source becomes started.\n   */\n  queueOn?: Array<{ type: On.Types; data: unknown }>;\n}\n\n/**\n * Per-scope environment passed to the body of `Source.Context.withScope`.\n *\n * Each call to `withScope` builds a fresh `ScopeEnv` whose `push` captures\n * the per-scope `ingest` and `respond`. Concurrent scopes cannot crosstalk:\n * each one carries its own ingest and respond all the way through the\n * pipeline. Server sources MUST use `withScope` per inbound request; sources\n * with a single logical scope (browser tab lifetime, dataLayer) may skip it\n * and use the factory-scope `env.push` directly.\n */\nexport type ScopeEnv<T extends TypesGeneric = Types> = Env<T> & {\n  /** Per-scope push: captures the scope's ingest and respond for this call. */\n  push: Collector.PushFn;\n  /** Ingest metadata extracted from the raw scope input (if config.ingest is set). */\n  ingest: Ingest;\n  /** Respond function bound to this scope (undefined for scopes without a response). */\n  respond?: RespondFn;\n};\n\n/**\n * Context provided to source init function.\n * Extends base context with source-specific properties.\n */\nexport interface Context<\n  T extends TypesGeneric = Types,\n> extends BaseContext.Base<Partial<Config<T>>, Env<T>> {\n  id: string;\n  /**\n   * Bind ingest and respond to a single scope of work (e.g. one inbound\n   * HTTP request, one queue message). Builds a fresh `Ingest` from the\n   * raw input via `config.ingest` mapping, wires the per-scope `respond`,\n   * and invokes `body(scopeEnv)` with a push function that captures both.\n   *\n   * Server sources call this once per inbound request:\n   *\n   * ```ts\n   * await context.withScope(req, createRespond(sender), async (env) => {\n   *   await env.push(parsedData);\n   * });\n   * ```\n   *\n   * Browser sources with a single tab-lifetime scope may skip `withScope`\n   * and use `env.push` directly.\n   *\n   * @param rawScope - Raw input for `config.ingest` mapping (Express req,\n   *   Lambda event, fetch Request, etc.). Pass `undefined` if no ingest\n   *   mapping applies.\n   * @param respond - Per-scope respond function, or `undefined` if the\n   *   scope produces no response.\n   * @param body - Async callback receiving the per-scope env.\n   * @returns The body's return value.\n   */\n  withScope: <R>(\n    rawScope: unknown,\n    respond: RespondFn | undefined,\n    body: (env: ScopeEnv<T>) => Promise<R>,\n  ) => Promise<R>;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n  context: Context<T>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitSource<T extends TypesGeneric = Types> = {\n  code: Init<T>;\n  config?: Partial<Config<T>>;\n  env?: Partial<Env<T>>;\n  primary?: boolean;\n  next?: Route;\n  before?: Route;\n  cache?: import('./cache').Cache;\n  state?: import('./state').State | import('./state').State[];\n};\n\n/**\n * Sources configuration for collector.\n * Maps source IDs to their initialization configurations.\n */\nexport interface InitSources {\n  [sourceId: string]: InitSource<any>;\n}\n\n/**\n * Renderer hint for source simulation UI.\n * - 'browser': Source needs a real DOM (iframe with live preview)\n * - 'codebox': Source uses a JSON/code editor (default)\n */\nexport type Renderer = 'browser' | 'codebox';\n\n/**\n * Typed accessor for sources registered on a collector.\n *\n * The collector's `sources` bag indexes to `Source.Instance` (defaults erase\n * the generic), which collapses the source's declared `push` signature to\n * `Elb.Fn`. Use this helper at the call site to recover the narrow type\n * without casts.\n *\n * @example\n * type TestSourceTypes = Source.Types<unknown, unknown, TestPushFn>;\n * const src = getSource<TestSourceTypes>(collector, 'testSource');\n * await src.push({ method: 'GET', path: '/api/data' }); // typed!\n *\n * @throws Error with message `Source not found: <id>` when the id is unknown.\n */\nexport function getSource<T extends TypesGeneric = Types>(\n  collector: { sources: { [id: string]: Instance<any> } },\n  id: string,\n): Instance<T> {\n  const source = collector.sources[id];\n  if (!source) {\n    throw new Error(`Source not found: ${id}`);\n  }\n  // Single, contained narrowing. The runtime instance was constructed with\n  // generic T at init time; the bag erased the parameter. We're restoring\n  // information that already exists at runtime.\n  return source as unknown as Instance<T>;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Logger, WalkerOS, Context as BaseContext } from '.';\nimport type { DestroyFn, SetupFn } from './lifecycle';\n\nexport interface BaseEnv {\n  [key: string]: unknown;\n}\n\nexport interface Types<\n  S = unknown,\n  E = BaseEnv,\n  I = S,\n  U = unknown,\n  C = unknown,\n> {\n  settings: S;\n  initSettings: I;\n  env: E;\n  setup: U;\n  credentials: C;\n}\n\nexport type TypesGeneric = {\n  settings: any;\n  initSettings: any;\n  env: any;\n  setup: any;\n  credentials: any;\n};\n\nexport type Settings<T extends TypesGeneric = Types> = T['settings'];\nexport type InitSettings<T extends TypesGeneric = Types> = T['initSettings'];\nexport type Env<T extends TypesGeneric = Types> = T['env'];\nexport type SetupOptions<T extends TypesGeneric = Types> = T['setup'];\nexport type Credentials<T extends TypesGeneric = Types> = T['credentials'];\n\nexport type TypesOf<I> = I extends Instance<infer T> ? T : never;\n\nexport interface Config<T extends TypesGeneric = Types> {\n  settings?: InitSettings<T>;\n  /**\n   * Optional, strictly-typed credentials slot ($env-resolved). The package\n   * defines the shape via `Types['credentials']`. `settings.<sdk>` stays the\n   * escape hatch for raw SDK options.\n   */\n  credentials?: Credentials<T>;\n  env?: Env<T>;\n  id?: string;\n  logger?: Logger.Config;\n  /**\n   * Provisioning options for `walkeros setup`. `boolean | object`.\n   * Triggered only by explicit CLI invocation; never automatic.\n   */\n  setup?: boolean | SetupOptions<T>;\n  /**\n   * Persist values as raw bytes, byte-exact, bypassing the structured codec.\n   * Default false: values are structured `StoreValue` and pass through the\n   * shared core serialization codec. Set true only on byte-native backends\n   * (fs/s3/gcs) whose consumer needs the exact bytes back, e.g. serving an\n   * asset such as walker.js. Structured-only backends (sheets) reject `file:\n   * true` at init. One store instance is exactly one mode.\n   */\n  file?: boolean;\n}\n\nexport type PartialConfig<T extends TypesGeneric = Types> = Config<\n  Types<\n    Partial<Settings<T>> | Settings<T>,\n    Env<T>,\n    InitSettings<T>,\n    SetupOptions<T>,\n    Credentials<T>\n  >\n>;\n\nexport interface Context<\n  T extends TypesGeneric = Types,\n> extends BaseContext.Base<Config<T>, Env<T>> {\n  id: string;\n}\n\n/**\n * Canonical structured value persisted by a store. Includes `null`, but\n * EXCLUDES `undefined`: `undefined` is the reserved \"miss\" sentinel returned\n * by `GetFn` for an absent key, so it must never be a stored value.\n * `Uint8Array` is the platform-neutral binary leaf (never Node `Buffer`).\n */\nexport type StoreValue =\n  | string\n  | number\n  | boolean\n  | null\n  | Uint8Array\n  | StoreValue[]\n  | { [key: string]: StoreValue };\n\nexport type GetFn<T extends StoreValue = StoreValue> = (\n  key: string,\n) => T | undefined | Promise<T | undefined>;\n\nexport type SetFn<T extends StoreValue = StoreValue> = (\n  key: string,\n  value: T,\n  /**\n   * Optional expiry hint in ms; honored only by TTL-native backends\n   * (in-memory, Redis). Byte/JSON backends may ignore it. Authoritative cache\n   * expiry lives in the cache wrapper's {value, exp} payload.\n   */\n  ttl?: number,\n) => void | Promise<void>;\n\nexport type DeleteFn = (key: string) => void | Promise<void>;\n\nexport interface Instance<T extends TypesGeneric = Types> {\n  type: string;\n  config: Config<T>;\n  get: GetFn;\n  set: SetFn;\n  delete: DeleteFn;\n  setup?: SetupFn<Config<T>, Env<T>>;\n  destroy?: DestroyFn<Config<T>, Env<T>>;\n}\n\nexport type Init<T extends TypesGeneric = Types> = (\n  context: Context<Types<Partial<Settings<T>>, Env<T>, InitSettings<T>>>,\n) => Instance<T> | Promise<Instance<T>>;\n\nexport type InitFn<T extends TypesGeneric = Types> = (\n  context: Context<T>,\n) => WalkerOS.PromiseOrValue<void | false | Config<T>>;\n\nexport type InitStore<T extends TypesGeneric = Types> = {\n  code: Init<T>;\n  config?: Partial<Config<T>>;\n  env?: Partial<Env<T>>;\n};\n\nexport interface InitStores {\n  [storeId: string]: InitStore<any>;\n}\n\nexport interface Stores {\n  [storeId: string]: Instance;\n}\n\n/**\n * Typed accessor for stores registered on a collector.\n *\n * The collector's `stores` bag indexes to `Store.Instance` (defaults erase\n * the generic). Use this helper at the call site to recover the narrow type\n * without casts.\n *\n * @example\n * type MyStoreTypes = Store.Types<MySettings>;\n * const store = getStore<MyStoreTypes>(collector, 'cache');\n * await store.set('key', 'value');\n *\n * @throws Error with message `Store not found: <id>` when the id is unknown.\n */\nexport function getStore<T extends TypesGeneric = Types>(\n  collector: { stores: { [id: string]: Instance<any> } },\n  id: string,\n): Instance<T> {\n  const store = collector.stores[id];\n  if (!store) {\n    throw new Error(`Store not found: ${id}`);\n  }\n  return store as unknown as Instance<T>;\n}\n\n/**\n * Read-site narrowing helper for store values.\n *\n * `Instance.get`/`set` stay value-agnostic at `StoreValue`, so callers\n * that know the concrete shape narrow here instead of threading a value type\n * through `Store.Types`. The single narrow `as` cast is justified: the store\n * channel is structurally `StoreValue`, and the caller asserts the concrete\n * sub-shape it stored. `undefined` is preserved as the miss sentinel.\n */\nexport async function getStoreValue<V extends StoreValue = StoreValue>(\n  store: Instance,\n  key: string,\n): Promise<V | undefined> {\n  return (await store.get(key)) as V | undefined;\n}\n","/**\n * Trigger — unified interface for invoking any walkerOS step in simulation\n * and testing. Every package exports a `createTrigger` factory from its\n * examples that conforms to `Trigger.CreateFn`.\n *\n * Usage:\n *   const { flow, trigger } = await createTrigger(initConfig);\n *   const result = await trigger(type?, options?)(content);\n *\n * @packageDocumentation\n */\n\nimport type { Collector, Elb } from '.';\n\n/** Flow access handle returned by createTrigger. */\nexport interface FlowHandle {\n  /** The collector instance created by startFlow. */\n  collector: Collector.Instance;\n  /** The elb push function for direct event injection. */\n  elb: Elb.Fn;\n}\n\n/** What createTrigger returns — a flow handle (lazy) and a trigger function. */\nexport interface Instance<TContent = unknown, TResult = unknown> {\n  /** Flow handle — undefined until first trigger() call, then stable. */\n  readonly flow: FlowHandle | undefined;\n  trigger: Fn<TContent, TResult>;\n}\n\n/**\n * Curried trigger function — always async.\n *\n * First call selects mechanism (type) and configures it (options).\n * Second call fires with content and returns result.\n *\n * @example\n * // Browser source — click trigger\n * trigger('click', 'button.cta')('<button data-elb=\"cta\">Sign Up</button>')\n *\n * // Express source — POST request\n * trigger('POST')({ path: '/collect', body: { name: 'page view' } })\n *\n * // DataLayer — default mechanism\n * trigger()(['event', 'purchase', { value: 25.42 }])\n */\nexport type Fn<TContent = unknown, TResult = unknown> = (\n  type?: string,\n  options?: unknown,\n) => (content: TContent) => Promise<TResult>;\n\n/**\n * Factory function exported by each package's examples.\n *\n * Receives full Collector.InitConfig. Does NOT call startFlow eagerly —\n * startFlow is deferred to the first trigger() invocation (lazy init).\n * The flow property uses a getter to read the closure variable live.\n * createTrigger itself stays async for consistency (other packages may\n * need await during setup). Config is passed through UNMODIFIED —\n * validation is startFlow's job.\n *\n * @example\n * // Package exports:\n * export const createTrigger: Trigger.CreateFn<HTMLContent, void> = async (config) => {\n *   let flow: Trigger.FlowHandle | undefined;\n *\n *   const trigger: Trigger.Fn<HTMLContent, void> = (type?, options?) => async (content) => {\n *     // Pre-startFlow work (e.g., inject HTML for browser source)\n *     // ...\n *\n *     // Lazy init — only on first call\n *     if (!flow) flow = await startFlow(config);\n *\n *     // Post-startFlow work (e.g., dispatch click event)\n *     // ...\n *   };\n *\n *   return {\n *     get flow() { return flow; },\n *     trigger,\n *   };\n * };\n */\nexport type CreateFn<TContent = unknown, TResult = unknown> = (\n  config: Collector.InitConfig,\n  options?: unknown,\n) => Promise<Instance<TContent, TResult>>;\n","// packages/core/src/types/lifecycle.ts\nimport type { Logger, WalkerOS } from '.';\n\n/**\n * Shared context for one-shot lifecycle hooks (setup, destroy).\n * No event pipeline machinery — just config, env, logger, and id.\n */\nexport interface LifecycleContext<C = unknown, E = unknown> {\n  id: string;\n  config: C;\n  env: E;\n  logger: Logger.Instance;\n}\n\n/**\n * Setup function signature. Called once via `walkeros setup <kind>.<name>`.\n * Packages own idempotency and error semantics. Return value (if any) is\n * JSON-stringified to stdout by the CLI for scripting use.\n */\nexport type SetupFn<C = unknown, E = unknown> = (\n  context: LifecycleContext<C, E>,\n) => WalkerOS.PromiseOrValue<unknown>;\n\n/**\n * Destroy function signature for step lifecycle cleanup.\n */\nexport type DestroyFn<C = unknown, E = unknown> = (\n  context: LifecycleContext<C, E>,\n) => WalkerOS.PromiseOrValue<void>;\n\n/**\n * @deprecated Use `LifecycleContext` instead. Kept as alias for one minor cycle.\n */\nexport type DestroyContext<C = unknown, E = unknown> = LifecycleContext<C, E>;\n","import type { Elb as ElbTypes } from '.';\n\nexport type AnyObject<T = unknown> = Record<string, T>;\nexport type Elb = ElbTypes.Fn;\nexport type AnyFunction = (...args: unknown[]) => unknown;\nexport type SingleOrArray<T> = T | Array<T>;\n\nexport type Events = Array<Event>;\nexport type PartialEvent = Partial<Event>;\nexport type DeepPartialEvent = DeepPartial<Event>;\nexport interface Event {\n  name: string;\n  data: Properties;\n  context: OrderedProperties;\n  globals: Properties;\n  custom: Properties;\n  user: User;\n  nested: Entities;\n  consent: Consent;\n  id: string;\n  trigger: string;\n  entity: string;\n  action: string;\n  timestamp: number;\n  timing: number;\n  source: Source;\n}\n\nexport interface Consent {\n  [name: string]: boolean; // name of consent group or tool\n}\n\nexport interface User extends Properties {\n  // IDs\n  id?: string;\n  device?: string;\n  session?: string;\n  hash?: string;\n  // User related\n  address?: string;\n  email?: string;\n  phone?: string;\n  userAgent?: string;\n  browser?: string;\n  browserVersion?: string;\n  deviceType?: string;\n  language?: string;\n  country?: string;\n  region?: string;\n  city?: string;\n  zip?: string;\n  timezone?: string;\n  os?: string;\n  osVersion?: string;\n  screenSize?: string;\n  ip?: string;\n  internal?: boolean;\n}\n\nexport type SourcePlatform =\n  | 'web'\n  | 'server'\n  | 'app'\n  | 'ios'\n  | 'android'\n  | 'terminal'\n  | string;\n\n/**\n * SourceMap is the discriminated-union registry for source kinds.\n * Each source package augments this interface via `declare module\n * '@walkeros/core'` to register its own `type` literal and any\n * source-specific fields. Conflicting declarations cause compile errors,\n * intentional, to surface naming collisions early.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface SourceMap {\n  collector: { type: 'collector' };\n}\n\nexport interface Source extends Properties {\n  type: string;\n  platform?: SourcePlatform;\n  /** Deployment version of the source emitter (string). */\n  version?: string;\n  /** Event-model spec version. Collector defaults to \"4\". */\n  schema?: string;\n  /** Emission sequence within the run. */\n  count?: number;\n  /** Trace id shared by every event of a run (W3C trace-id shape). */\n  trace?: string;\n  /** Walker-controlled standard suggestions (sources may set). */\n  url?: string;\n  referrer?: string;\n  tool?: string;\n  command?: string;\n}\n\nexport type PropertyType =\n  | boolean\n  | string\n  | number\n  | { [key: string]: Property };\n\nexport type Property = PropertyType | Array<PropertyType>;\n\nexport interface Properties {\n  [key: string]: Property | undefined;\n}\nexport interface OrderedProperties {\n  [key: string]: [Property, number] | undefined;\n}\n\nexport type Entities = Array<Entity>;\nexport interface Entity {\n  entity: string;\n  data: Properties;\n  nested?: Entities;\n  context?: OrderedProperties;\n}\n\nexport type ConsentHandler = Record<string, AnyFunction>;\nexport type ActionHandler = AnyFunction;\n\nexport type DeepPartial<T> = {\n  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type PromiseOrValue<T> = T | Promise<T>;\n","import type { WalkerOS } from '.';\n\n/**\n * A recorded function call made during simulation.\n * Captures what a destination called on its env (e.g., window.gtag).\n */\nexport interface Call {\n  /** Dot-path of the function called: \"window.gtag\", \"dataLayer.push\" */\n  fn: string;\n  /** Arguments passed to the function */\n  args: unknown[];\n  /** Unix timestamp in ms */\n  ts: number;\n}\n\n/**\n * Result of simulating a single step.\n * Same shape for source, transformer, collector, and destination.\n */\nexport interface Result {\n  /** Which step type was simulated */\n  step: 'source' | 'transformer' | 'destination' | 'collector';\n  /** Step name, e.g. \"gtag\", \"dataLayer\", \"enricher\" */\n  name: string;\n  /**\n   * Output events:\n   * - source: captured pre-collector events\n   * - transformer: [transformed event] or [] if filtered\n   * - collector: [enriched event] (createEvent applied)\n   * - destination: [] (destinations don't produce events)\n   */\n  events: WalkerOS.DeepPartialEvent[];\n  /** Intercepted env calls. Populated for destinations, empty [] for others. */\n  calls: Call[];\n  /** Execution time in ms */\n  duration: number;\n  /**\n   * Entity-action key of the matched mapping rule, e.g. \"product add\" or\n   * \"product *\". Populated for destination simulations when a mapping rule\n   * matched; absent when no rule matched or the step has no mapping.\n   * Also absent when the matched rule uses batched delivery (batching\n   * reports no per-event key) and on error results, where the key is not\n   * available.\n   */\n  mappingKey?: string;\n  /** Error if the step threw */\n  error?: Error;\n}\n","export type MatchExpression =\n  | MatchCondition\n  | { and: MatchExpression[] }\n  | { or: MatchExpression[] };\n\nexport interface MatchCondition {\n  key: string;\n  operator: MatchOperator;\n  value: string;\n  not?: boolean;\n}\n\nexport type MatchOperator =\n  | 'eq'\n  | 'contains'\n  | 'prefix'\n  | 'suffix'\n  | 'regex'\n  | 'gt'\n  | 'lt'\n  | 'exists';\n\n// Compiled matcher (internal)\nexport type CompiledMatcher = (context: Record<string, unknown>) => boolean;\n","export interface Code {\n  lang?: string;\n  code: string;\n}\n\nexport interface Hint {\n  text: string;\n  code?: Array<Code>;\n}\n\nexport type Hints = Record<string, Hint>;\n","export type StorageType = 'local' | 'session' | 'cookie';\n\nexport const Storage = {\n  Local: 'local' as const,\n  Session: 'session' as const,\n  Cookie: 'cookie' as const,\n} as const;\n\nexport const Const = {\n  Utils: {\n    Storage,\n  },\n} as const;\n","/**\n * Metadata managed by the runtime. Do not overwrite from step code.\n * The _ prefix signals \"runtime-managed.\"\n */\nexport interface IngestMeta {\n  /** Number of steps this data has passed through. */\n  hops: number;\n  /** Ordered list of step IDs visited. path[0] is always the source ID. */\n  path: string[];\n  /** Current chain context, e.g., \"destination.ga4.before\" or \"source.web.next\". */\n  chainPath?: string;\n}\n\n/**\n * Mutable shared context that accumulates knowledge as data flows through the graph.\n *\n * Event = strict schema (analytics data).\n * Ingest = wild west (pipeline context).\n *\n * Any step can read and write arbitrary keys. The `_meta` section is\n * managed by the runtime — increment hops and append to path before each step.\n */\nexport interface Ingest {\n  [key: string]: unknown;\n  _meta: IngestMeta;\n}\n\n/** Create a fresh Ingest for a new pipeline invocation. */\nexport function createIngest(sourceId: string): Ingest {\n  return {\n    _meta: {\n      hops: 0,\n      path: [sourceId],\n    },\n  };\n}\n","import type { Transformer, WalkerOS } from './types';\n\n/**\n * Creates a TransformerResult for dynamic chain routing.\n * Use this in transformer push functions to redirect the chain.\n */\nexport function branch(\n  event: WalkerOS.DeepPartialEvent,\n  next: Transformer.Route,\n): Transformer.Result {\n  return { event, next };\n}\n","/**\n * Anonymizes an IPv4 address by setting the last octet to 0.\n *\n * @param ip The IP address to anonymize.\n * @returns The anonymized IP address or an empty string if the IP is invalid.\n */\nexport function anonymizeIP(ip: string): string {\n  const ipv4Pattern = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\n\n  if (!ipv4Pattern.test(ip)) return '';\n\n  return ip.replace(/\\.\\d+$/, '.0'); // Set the last octet to 0\n}\n","/**\n * Throws an error.\n *\n * @param error The error to throw.\n */\nexport function throwError(error: unknown): never {\n  throw new Error(String(error));\n}\n","import type { Flow } from './types';\nimport { throwError } from './throwError';\n\n/** Annotation keys to strip from AJV-compatible schemas. */\nconst ANNOTATION_KEYS = new Set([\n  'description',\n  'examples',\n  'title',\n  '$comment',\n]);\n\n/** Options for {@link resolveContracts}. */\nexport interface ResolveContractsOptions {\n  /**\n   * When true (default), annotation keys (`description`, `examples`, `title`,\n   * `$comment`) are stripped from event schemas so the result is AJV-clean for\n   * runtime validation. Set to false to keep annotations (e.g. for IntelliSense\n   * that surfaces property descriptions).\n   */\n  stripAnnotations?: boolean;\n}\n\n/**\n * Resolve all named contracts: process extend chains, expand wildcards,\n * strip annotations from event schemas.\n *\n * Returns a fully resolved map where each contract entry has inherited\n * properties merged in and wildcards expanded into concrete actions.\n *\n * By default annotations are stripped (AJV-clean). Pass\n * `{ stripAnnotations: false }` to preserve `description`/`examples`/`title`\n * on event schemas.\n */\nexport function resolveContracts(\n  contracts: Flow.Contract,\n  options?: ResolveContractsOptions,\n): Record<string, Flow.ContractRule> {\n  const strip = options?.stripAnnotations !== false;\n  const resolved: Record<string, Flow.ContractRule> = {};\n  const resolving = new Set<string>(); // Circular detection\n\n  function resolve(name: string): Flow.ContractRule {\n    if (resolved[name]) return resolved[name];\n\n    if (resolving.has(name)) {\n      throwError(\n        `Circular extend chain detected: ${[...resolving, name].join(' → ')}`,\n      );\n    }\n\n    const entry = contracts[name];\n    if (!entry) {\n      throwError(`Contract \"${name}\" not found`);\n    }\n\n    resolving.add(name);\n\n    let result: Flow.ContractRule = {};\n\n    // 1. Resolve parent first (if extend)\n    if (entry.extend) {\n      const parent = resolve(entry.extend);\n      result = mergeContractEntries(parent, entry);\n    } else {\n      result = { ...entry };\n    }\n\n    // Remove extend from resolved entry\n    delete result.extend;\n\n    // 2. Expand wildcards in events\n    if (result.events) {\n      result.events = expandWildcards(result.events);\n    }\n\n    // 3. Strip annotations from event schemas (not from section schemas).\n    //    Skipped when stripAnnotations is false (annotation-preserving view).\n    if (result.events && strip) {\n      const stripped: Flow.ContractEvents = {};\n      for (const [entity, actions] of Object.entries(result.events)) {\n        stripped[entity] = {};\n        for (const [action, schema] of Object.entries(actions)) {\n          stripped[entity][action] = stripAnnotations(schema);\n        }\n      }\n      result.events = stripped;\n    }\n\n    resolving.delete(name);\n    resolved[name] = result;\n    return result;\n  }\n\n  // Resolve all contracts\n  for (const name of Object.keys(contracts)) {\n    resolve(name);\n  }\n\n  return resolved;\n}\n\n/**\n * Merge two contract entries additively.\n * Scalar metadata (tagging, description): child wins, otherwise inherited.\n * `schema`: deep additive merge via mergeContractSchemas.\n * `events`: per-entity-action merge.\n */\nfunction mergeContractEntries(\n  parent: Flow.ContractRule,\n  child: Flow.ContractRule,\n): Flow.ContractRule {\n  const result: Flow.ContractRule = {};\n\n  // Scalar metadata: child overrides if set, otherwise inherited.\n  if (parent.tagging !== undefined || child.tagging !== undefined) {\n    result.tagging = child.tagging ?? parent.tagging;\n  }\n  if (parent.description !== undefined || child.description !== undefined) {\n    result.description = child.description ?? parent.description;\n  }\n\n  // Schema: additive deep-merge via mergeContractSchemas.\n  if (parent.schema && child.schema) {\n    result.schema = mergeContractSchemas(\n      parent.schema as Record<string, unknown>,\n      child.schema as Record<string, unknown>,\n    ) as Flow.ContractRule['schema'];\n  } else if (parent.schema || child.schema) {\n    result.schema = {\n      ...((parent.schema || child.schema) as Record<string, unknown>),\n    } as Flow.ContractRule['schema'];\n  }\n\n  // Events: per-entity-action merge (unchanged semantics).\n  if (parent.events || child.events) {\n    const merged: Flow.ContractEvents = {};\n    const allEntities = new Set([\n      ...Object.keys(parent.events || {}),\n      ...Object.keys(child.events || {}),\n    ]);\n\n    for (const entity of allEntities) {\n      const pActions = parent.events?.[entity] || {};\n      const cActions = child.events?.[entity] || {};\n      const allActions = new Set([\n        ...Object.keys(pActions),\n        ...Object.keys(cActions),\n      ]);\n\n      merged[entity] = {};\n      for (const action of allActions) {\n        const pSchema = pActions[action];\n        const cSchema = cActions[action];\n        if (pSchema && cSchema) {\n          merged[entity][action] = mergeContractSchemas(\n            pSchema as Record<string, unknown>,\n            cSchema as Record<string, unknown>,\n          );\n        } else {\n          merged[entity][action] = {\n            ...((pSchema || cSchema) as Record<string, unknown>),\n          };\n        }\n      }\n    }\n\n    result.events = merged;\n  }\n\n  return result;\n}\n\n/**\n * Expand wildcards in an events map.\n * Merges *.* into all concrete actions, *.action into matching actions,\n * entity.* into all actions of that entity.\n */\nfunction expandWildcards(events: Flow.ContractEvents): Flow.ContractEvents {\n  const result: Flow.ContractEvents = {};\n\n  // For each concrete entity-action pair, merge all matching wildcard levels\n  for (const entity of Object.keys(events)) {\n    if (entity === '*') continue;\n    result[entity] = {};\n\n    for (const action of Object.keys(events[entity] || {})) {\n      let merged: Record<string, unknown> = {};\n\n      // Level 1: *.*\n      const globalWild = events['*']?.['*'];\n      if (globalWild)\n        merged = mergeContractSchemas(\n          merged,\n          globalWild as Record<string, unknown>,\n        );\n\n      // Level 2: *.action\n      const actionWild = events['*']?.[action];\n      if (actionWild && action !== '*')\n        merged = mergeContractSchemas(\n          merged,\n          actionWild as Record<string, unknown>,\n        );\n\n      // Level 3: entity.*\n      const entityWild = events[entity]?.['*'];\n      if (entityWild && action !== '*')\n        merged = mergeContractSchemas(\n          merged,\n          entityWild as Record<string, unknown>,\n        );\n\n      // Level 4: entity.action\n      const exact = events[entity]?.[action];\n      if (exact)\n        merged = mergeContractSchemas(merged, exact as Record<string, unknown>);\n\n      result[entity][action] = merged;\n    }\n  }\n\n  // Preserve * entries for reference\n  if (events['*']) {\n    result['*'] = { ...events['*'] };\n  }\n\n  return result;\n}\n\n/**\n * Deep merge two JSON Schema objects with additive semantics.\n * - `required` arrays: union (deduplicated)\n * - `properties`: deep merge (child wins on conflict for scalars)\n * - Scalars: child overrides parent\n */\nexport function mergeContractSchemas(\n  parent: Record<string, unknown>,\n  child: Record<string, unknown>,\n): Record<string, unknown> {\n  const result: Record<string, unknown> = { ...parent };\n\n  for (const key of Object.keys(child)) {\n    const parentVal = parent[key];\n    const childVal = child[key];\n\n    if (\n      key === 'required' &&\n      Array.isArray(parentVal) &&\n      Array.isArray(childVal)\n    ) {\n      result[key] = [...new Set([...parentVal, ...childVal])];\n    } else if (isPlainObject(parentVal) && isPlainObject(childVal)) {\n      result[key] = mergeContractSchemas(\n        parentVal as Record<string, unknown>,\n        childVal as Record<string, unknown>,\n      );\n    } else {\n      result[key] = childVal;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Strip annotation-only keys from a schema (deep).\n */\nfunction stripAnnotations(\n  schema: Record<string, unknown>,\n): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(schema)) {\n    if (ANNOTATION_KEYS.has(key)) continue;\n    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n      result[key] = stripAnnotations(value as Record<string, unknown>);\n    } else {\n      result[key] = value;\n    }\n  }\n  return result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * walkerOS reference-syntax regex constants — single source of truth.\n *\n * Rule:\n * - `.` = key or path (resolver walks it)\n * - `:` = literal value or raw-code payload (resolver uses it verbatim)\n *\n * Every tool that recognizes references (core resolver, CLI bundler,\n * app secrets service, explorer IntelliSense) imports these — no\n * inline regexes elsewhere.\n */\n\n// Anchored: matches only when the string is exactly \"$var.name(.deep.path)?\"\nexport const REF_VAR_FULL =\n  /^\\$var\\.([a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)*)$/;\n\n// Global inline: matches any \"$var.name(.deep.path)?\" inside a larger string.\n// Character class excludes `/`, `:`, `?`, `&`, etc. so URL contexts work.\nexport const REF_VAR_INLINE =\n  /\\$var\\.([a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g;\nexport const REF_ENV = /\\$env\\.([a-zA-Z_][a-zA-Z0-9_]*)(?::([^\"}\\s]*))?/g;\nexport const REF_CONTRACT = /^\\$contract\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.(.+))?$/;\n/** Whole-string `$flow.<name>(.<path>)?`: cross-flow value reference. */\nexport const REF_FLOW =\n  /^\\$flow\\.([a-zA-Z_][a-zA-Z0-9_]*)(?:\\.([a-zA-Z0-9_.]+))?$/;\nexport const REF_STORE = /^\\$store\\.([a-zA-Z_][a-zA-Z0-9_]*)$/;\nexport const REF_SECRET = /^\\$secret\\.([A-Z0-9_]+)$/;\nexport const REF_CODE_PREFIX = '$code:';\n\nconst FLOW_REF_PATTERN = /\\$flow\\.([a-zA-Z_][a-zA-Z0-9_]*)/g;\n\n/**\n * Canonical scanner for the `$flow.` reference grammar. Walks strings,\n * arrays, and objects and returns every referenced flow name. The returned\n * set is the same instance as `into` when one is supplied, so callers can\n * accumulate across multiple values.\n */\nexport function scanFlowRefs(value: unknown, into?: Set<string>): Set<string> {\n  const refs = into ?? new Set<string>();\n  if (typeof value === 'string') {\n    for (const m of value.matchAll(FLOW_REF_PATTERN)) refs.add(m[1]);\n    return refs;\n  }\n  if (value && typeof value === 'object') {\n    for (const v of Object.values(value as Record<string, unknown>))\n      scanFlowRefs(v, refs);\n  }\n  return refs;\n}\n","/**\n * Flow Configuration Utilities\n *\n * Functions for resolving and processing Flow configurations.\n *\n * @packageDocumentation\n */\n\nimport type { Flow } from './types';\nimport { resolveContracts } from './contract';\nimport {\n  REF_CONTRACT,\n  REF_ENV,\n  REF_FLOW,\n  REF_SECRET,\n  REF_VAR_FULL,\n  REF_VAR_INLINE,\n} from './references';\nimport { throwError } from './throwError';\n\n/**\n * Merge variables with cascade priority.\n * Later arguments have higher priority.\n */\nfunction mergeVariables(\n  ...sources: (Flow.Variables | undefined)[]\n): Flow.Variables {\n  const result: Flow.Variables = {};\n  for (const source of sources) {\n    if (source) {\n      Object.assign(result, source);\n    }\n  }\n  return result;\n}\n\n/** Sentinel prefix for deferred $env resolution. Shared with CLI bundler. */\nexport const ENV_MARKER_PREFIX = '__WALKEROS_ENV:';\n\n/** Sentinel prefix for deferred $secret resolution. Shared with CLI bundler. */\nexport const SECRET_MARKER_PREFIX = '__WALKEROS_SECRET:';\n\nexport interface ResolveOptions {\n  deferred?: boolean;\n  /**\n   * When false, unresolved `$flow.X.Y` refs (unknown flow, missing key,\n   * empty value) trigger {@link onWarning} and the original `$flow…` string\n   * is left in place. Cycles always throw regardless of this flag.\n   * Default: true (strict — throws as today).\n   */\n  strictFlowRefs?: boolean;\n  /** Called for each unresolved $flow ref when {@link strictFlowRefs} is false. */\n  onWarning?: (message: string) => void;\n}\n\n/** Format an actionable hint when `$flow.X.Y` cannot be resolved. */\nfunction formatUnresolvedFlowMessage(\n  flowName: string,\n  path: string | undefined,\n  reason: 'unknown-flow' | 'missing-key',\n): string {\n  const ref = `$flow.${flowName}${path ? `.${path}` : ''}`;\n  if (reason === 'unknown-flow') {\n    return `${ref} cannot resolve: flow \"${flowName}\" does not exist in this config.`;\n  }\n  // missing-key (includes empty url / missing settings.X)\n  const target = path\n    ? `flows.${flowName}.config.${path}`\n    : `flows.${flowName}.config`;\n  return `${ref} is empty. Set ${target}, or run \\`walkeros deploy ${flowName}\\` first.`;\n}\n\n/**\n * Walk a dot-separated path into a value.\n * Throws if any intermediate segment is missing or not an object.\n */\nexport function walkPath(\n  value: unknown,\n  path: string,\n  refPrefix: string,\n): unknown {\n  const segments = path.split('.');\n  let current = value;\n\n  for (let i = 0; i < segments.length; i++) {\n    const segment = segments[i];\n    if (\n      current === null ||\n      current === undefined ||\n      typeof current !== 'object'\n    ) {\n      const visited = segments.slice(0, i).join('.');\n      throwError(\n        `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n      );\n    }\n    const obj = current as Record<string, unknown>;\n    if (!(segment in obj)) {\n      const visited = segments.slice(0, i).join('.');\n      throwError(\n        `Path \"${path}\" not found in \"${refPrefix}\": \"${segment}\" does not exist${visited ? ` in \"${visited}\"` : ''}`,\n      );\n    }\n    current = obj[segment];\n  }\n\n  return current;\n}\n\n/**\n * Resolver callback for `$flow.X.Y` references.\n *\n * Given a sibling flow name, returns its fully resolved `Flow.Config` block\n * (with `$env`/`$var`/`$contract` already resolved) as `unknown` so that\n * {@link walkPath} can traverse it. Returns `undefined` if the flow does\n * not exist. Implementations are responsible for cycle detection across\n * recursive calls.\n */\nexport type FlowConfigResolver = (flowName: string) => unknown;\n\n/**\n * Resolve all dynamic patterns in a value.\n *\n * Patterns:\n * - $var.name (or $var.name.deep.path) → Look up variables[name], optional deep\n *   path walk. Whole-string match preserves the native type of the variable\n *   (object, array, number, boolean, string). Inline interpolation requires a\n *   scalar (string/number/boolean) and throws on objects/arrays. Resolution is\n *   recursive (variables may reference other variables) with cycle detection.\n * - $env.NAME or $env.NAME:default → Look up process.env[NAME]\n * - $contract.name(.path)? → Resolved contract value (when contracts available)\n * - $flow.name(.path)? → Sibling flow's resolved {@link Flow.Config} (when resolver available)\n *\n * Top-level object keys are preserved verbatim (only values are walked), so an\n * object input retains its declared shape after resolution. The overload below\n * lets callers pass a typed object (e.g. `Flow.Config`) and get the same type\n * back without an unsafe cast. Strings that are whole-pattern references may\n * resolve to arbitrary types — callers passing a typed object should not rely\n * on individual string fields being preserved as strings.\n */\nfunction resolvePatterns<T extends object>(\n  value: T,\n  variables: Flow.Variables,\n  options?: ResolveOptions,\n  resolvedContracts?: Record<string, Flow.ContractRule>,\n  resolveFlow?: FlowConfigResolver,\n  varVisiting?: Set<string>,\n): T;\nfunction resolvePatterns(\n  value: unknown,\n  variables: Flow.Variables,\n  options?: ResolveOptions,\n  resolvedContracts?: Record<string, Flow.ContractRule>,\n  resolveFlow?: FlowConfigResolver,\n  varVisiting?: Set<string>,\n): unknown;\nfunction resolvePatterns(\n  value: unknown,\n  variables: Flow.Variables,\n  options?: ResolveOptions,\n  resolvedContracts?: Record<string, Flow.ContractRule>,\n  resolveFlow?: FlowConfigResolver,\n  varVisiting?: Set<string>,\n): unknown {\n  if (typeof value === 'string') {\n    // Whole-string $var match: preserve native type, support deep paths\n    const fullMatch = value.match(REF_VAR_FULL);\n    if (fullMatch) {\n      const path = fullMatch[1]; // e.g. \"name\" or \"name.deep.path\"\n      const segments = path.split('.');\n      const varName = segments[0];\n      const deepPath = segments.slice(1).join('.');\n\n      if (variables[varName] === undefined) {\n        throwError(`Variable \"${varName}\" not found`);\n      }\n\n      const visiting = varVisiting ?? new Set<string>();\n      if (visiting.has(varName)) {\n        const chain = [...visiting, varName].join(' -> ');\n        throwError(`Cyclic $var reference: ${chain}`);\n      }\n\n      visiting.add(varName);\n      let resolved: unknown;\n      try {\n        resolved = resolvePatterns(\n          variables[varName],\n          variables,\n          options,\n          resolvedContracts,\n          resolveFlow,\n          visiting,\n        );\n      } finally {\n        visiting.delete(varName);\n      }\n\n      if (deepPath) {\n        resolved = walkPath(resolved, deepPath, `$var.${varName}`);\n      }\n\n      return resolved;\n    }\n\n    // Check if entire string is a $contract reference with path\n    const contractMatch = value.match(REF_CONTRACT);\n    if (contractMatch && resolvedContracts) {\n      const contractName = contractMatch[1];\n      const path = contractMatch[2];\n\n      if (!(contractName in resolvedContracts)) {\n        throwError(`Contract \"${contractName}\" not found`);\n      }\n\n      let resolved: unknown = resolvedContracts[contractName];\n\n      if (path) {\n        resolved = walkPath(resolved, path, `$contract.${contractName}`);\n      }\n\n      return resolved;\n    }\n\n    // Check if entire string is a $flow reference with optional path\n    const flowMatch = value.match(REF_FLOW);\n    if (flowMatch) {\n      const flowName = flowMatch[1];\n      const path = flowMatch[2]; // 'url' or 'settings.region' or undefined\n      const softMode = options?.strictFlowRefs === false;\n\n      if (!resolveFlow) {\n        throwError(\n          `$flow.${flowName}${path ? `.${path}` : ''} cannot be resolved without a flow resolver`,\n        );\n      }\n\n      // resolveFlow may throw on cycle — that always propagates (cycles are bugs).\n      const targetConfig = resolveFlow(flowName);\n      if (!targetConfig) {\n        if (softMode) {\n          options?.onWarning?.(\n            formatUnresolvedFlowMessage(flowName, path, 'unknown-flow'),\n          );\n          return value;\n        }\n        throwError(`Flow \"${flowName}\" not found in $flow.${flowName}`);\n      }\n\n      let resolved: unknown = targetConfig;\n      if (path) {\n        if (softMode) {\n          // Try to walk; if walk fails OR result is empty/undefined, soft-warn and keep original.\n          try {\n            resolved = walkPath(resolved, path, `$flow.${flowName}`);\n          } catch {\n            options?.onWarning?.(\n              formatUnresolvedFlowMessage(flowName, path, 'missing-key'),\n            );\n            return value;\n          }\n          if (resolved === undefined || resolved === null || resolved === '') {\n            options?.onWarning?.(\n              formatUnresolvedFlowMessage(flowName, path, 'missing-key'),\n            );\n            return value;\n          }\n        } else {\n          resolved = walkPath(resolved, path, `$flow.${flowName}`);\n        }\n      }\n\n      return resolved;\n    }\n\n    // Check if entire string is a $secret reference (whole-string only).\n    // Server (deferred) → emit a marker the bundler turns into a runtime\n    // process.env read. Web (non-deferred) → hard error: a secret must never\n    // be inlined into a browser bundle, and we never read its value here.\n    const secretMatch = value.match(REF_SECRET);\n    if (secretMatch) {\n      const name = secretMatch[1];\n      if (options?.deferred) {\n        return `${SECRET_MARKER_PREFIX}${name}`;\n      }\n      throwError(\n        `Secret \"$secret.${name}\" cannot be used in a web flow — secrets are never sent to the browser. Use a server flow.`,\n      );\n    }\n\n    // Inline $var: must resolve to scalar\n    let result = value.replace(REF_VAR_INLINE, (_match, path: string) => {\n      const segments = path.split('.');\n      const varName = segments[0];\n      const deepPath = segments.slice(1).join('.');\n\n      if (variables[varName] === undefined) {\n        throwError(`Variable \"${varName}\" not found`);\n      }\n\n      const visiting = varVisiting ?? new Set<string>();\n      if (visiting.has(varName)) {\n        const chain = [...visiting, varName].join(' -> ');\n        throwError(`Cyclic $var reference: ${chain}`);\n      }\n\n      visiting.add(varName);\n      let resolved: unknown;\n      try {\n        resolved = resolvePatterns(\n          variables[varName],\n          variables,\n          options,\n          resolvedContracts,\n          resolveFlow,\n          visiting,\n        );\n      } finally {\n        visiting.delete(varName);\n      }\n\n      if (deepPath) {\n        resolved = walkPath(resolved, deepPath, `$var.${varName}`);\n      }\n\n      if (\n        resolved === null ||\n        (typeof resolved !== 'string' &&\n          typeof resolved !== 'number' &&\n          typeof resolved !== 'boolean')\n      ) {\n        const type = Array.isArray(resolved) ? 'array' : typeof resolved;\n        throwError(\n          `Variable \"${path}\" resolves to non-scalar (${type}) and cannot be inlined into a string. Use it as a whole-string reference: \"$var.${path}\"`,\n        );\n      }\n\n      return String(resolved);\n    });\n\n    // Replace $env.NAME or $env.NAME:default patterns\n    result = result.replace(REF_ENV, (match, name, defaultValue) => {\n      if (options?.deferred) {\n        return defaultValue !== undefined\n          ? `${ENV_MARKER_PREFIX}${name}:${defaultValue}`\n          : `${ENV_MARKER_PREFIX}${name}`;\n      }\n      if (typeof process !== 'undefined' && process.env?.[name] !== undefined) {\n        return process.env[name]!;\n      }\n      if (defaultValue !== undefined) {\n        return defaultValue;\n      }\n      throwError(\n        `Environment variable \"${name}\" not found and no default provided`,\n      );\n    });\n\n    return result;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((item) =>\n      resolvePatterns(\n        item,\n        variables,\n        options,\n        resolvedContracts,\n        resolveFlow,\n        varVisiting,\n      ),\n    );\n  }\n\n  if (value !== null && typeof value === 'object') {\n    const result: Record<string, unknown> = {};\n    for (const [key, val] of Object.entries(value)) {\n      result[key] = resolvePatterns(\n        val,\n        variables,\n        options,\n        resolvedContracts,\n        resolveFlow,\n        varVisiting,\n      );\n    }\n    return result;\n  }\n\n  return value;\n}\n\n/**\n * Convert package name to valid JavaScript variable name.\n * Used for deterministic default import naming.\n * @example\n * packageNameToVariable('@walkeros/server-destination-api')\n * // → '_walkerosServerDestinationApi'\n */\nexport function packageNameToVariable(packageName: string): string {\n  const hasScope = packageName.startsWith('@');\n  const normalized = packageName\n    .replace('@', '')\n    .replace(/[/-]/g, '_')\n    .split('_')\n    .filter((part) => part.length > 0)\n    .map((part, i) =>\n      i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1),\n    )\n    .join('');\n\n  return hasScope ? '_' + normalized : normalized;\n}\n\n/**\n * Get resolved flow for a named flow.\n *\n * Resolution pass order:\n * 1. `$env` / `$var` resolve per-flow in isolation (no cross-flow context).\n *    `$var` resolves recursively (variables may reference other variables,\n *    `$env`, `$contract`, or `$flow`); cycles are detected via a visiting set.\n * 2. `$flow.X.Y` resolves against pass-1 outputs of sibling flows (so `$env`/`$var`\n *    inside the referenced flow are already resolved when `$flow` reads it).\n * 3. `$contract` resolves last (with `$flow` results available).\n *\n * In practice these passes are interleaved by the resolver: when `$flow.X.Y`\n * is encountered, the sibling flow X's `Flow.Config` block is recursively\n * resolved on demand (with all its own `$env`/`$var`/`$contract` references\n * resolved first), then the deep path is walked. Cycles are detected via a\n * visiting set.\n *\n * @param config - The complete Flow.Json (root multi-flow config)\n * @param flowName - Flow name (auto-selected if only one exists)\n * @param options - Resolution options\n * @returns Resolved {@link Flow} with $var, $env, $contract, and $flow patterns resolved\n * @throws Error if flow selection is required but not specified, or flow not found\n * @throws Error if a `$flow.X.Y` reference forms a cycle\n *\n * @example\n * ```typescript\n * import { getFlowSettings } from '@walkeros/core';\n *\n * const config = JSON.parse(fs.readFileSync('walkeros.config.json', 'utf8'));\n *\n * // Auto-select if only one flow\n * const flow = getFlowSettings(config);\n *\n * // Or specify flow\n * const prodFlow = getFlowSettings(config, 'production');\n * ```\n */\nexport function getFlowSettings(\n  config: Flow.Json,\n  flowName?: string,\n  options?: ResolveOptions,\n): Flow {\n  // Per-call shared state for cross-flow resolution.\n  const resolvedFlowConfigs = new Map<string, unknown>();\n  const visiting = new Set<string>();\n  const visitOrder: string[] = [];\n\n  /**\n   * Recursively resolve a sibling flow's `Flow.Config` block.\n   * Used by the resolver when it encounters `$flow.X.Y`.\n   * Throws on cycles. Returns undefined if the flow does not exist.\n   */\n  const resolveFlowConfig: FlowConfigResolver = (targetName): unknown => {\n    if (resolvedFlowConfigs.has(targetName)) {\n      return resolvedFlowConfigs.get(targetName);\n    }\n\n    const targetSettings = config.flows[targetName];\n    if (!targetSettings) return undefined;\n\n    if (visiting.has(targetName)) {\n      const chain = [...visitOrder, targetName].join(' -> ');\n      throwError(`Cyclic $flow reference: ${chain}`);\n    }\n\n    visiting.add(targetName);\n    visitOrder.push(targetName);\n    try {\n      const vars = mergeVariables(config.variables, targetSettings.variables);\n      // Resolve only the public config block: that is what $flow may read.\n      const resolved = resolvePatterns(\n        targetSettings.config ?? {},\n        vars,\n        options,\n        undefined, // contracts not consulted inside Flow.Config\n        resolveFlowConfig,\n      );\n      resolvedFlowConfigs.set(targetName, resolved);\n      return resolved;\n    } finally {\n      visiting.delete(targetName);\n      visitOrder.pop();\n    }\n  };\n\n  const flowNames = Object.keys(config.flows);\n\n  // Auto-select if only one flow\n  if (!flowName) {\n    if (flowNames.length === 1) {\n      flowName = flowNames[0];\n    } else {\n      throwError(\n        `Multiple flows found (${flowNames.join(', ')}). Please specify a flow.`,\n      );\n    }\n  }\n\n  // Check flow exists\n  const settings = config.flows[flowName];\n  if (!settings) {\n    throwError(\n      `Flow \"${flowName}\" not found. Available: ${flowNames.join(', ')}`,\n    );\n  }\n\n  // Cycle guard for the top-level flow being resolved as well.\n  // Without this, a cycle initiated from the entry flow (a → b → a) would\n  // not be detected when control returned to \"a\".\n  visiting.add(flowName);\n  visitOrder.push(flowName);\n\n  try {\n    return resolveFlowSettings(config, settings, options, resolveFlowConfig);\n  } finally {\n    visiting.delete(flowName);\n    visitOrder.pop();\n  }\n}\n\nfunction resolveFlowSettings(\n  config: Flow.Json,\n  settings: Flow,\n  options: ResolveOptions | undefined,\n  resolveFlow: FlowConfigResolver,\n): Flow {\n  // Deep clone to avoid mutations\n  const result = JSON.parse(JSON.stringify(settings)) as Flow;\n\n  // Pre-process contracts: resolve $var/$env inside contracts, then extend + wildcards\n  let resolvedContracts: Record<string, Flow.ContractRule> | undefined;\n  if (config.contract) {\n    // Two-pass: resolve $var/$env inside contract first\n    const vars = mergeVariables(config.variables, settings.variables);\n    const resolvedContractInput = resolvePatterns(\n      config.contract,\n      vars,\n      options,\n      undefined,\n      resolveFlow,\n    ) as Flow.Contract;\n\n    resolvedContracts = resolveContracts(resolvedContractInput);\n  }\n\n  // Process the flow's own config block so $flow/$env/$var refs inside\n  // it (e.g. settings.url = '$flow.server.url') are resolved.\n  if (result.config) {\n    const vars = mergeVariables(config.variables, settings.variables);\n    result.config = resolvePatterns(\n      result.config,\n      vars,\n      options,\n      resolvedContracts,\n      resolveFlow,\n    );\n  }\n\n  // Process sources with variable cascade\n  if (result.sources) {\n    for (const [name, source] of Object.entries(result.sources)) {\n      const vars = mergeVariables(\n        config.variables,\n        settings.variables,\n        source.variables,\n      );\n\n      const processedConfig = resolvePatterns(\n        source.config,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      const processedEnv = resolvePatterns(\n        source.env,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      result.sources[name] = {\n        package: source.package,\n        import: source.import,\n        config: processedConfig,\n        env: processedEnv,\n        primary: source.primary,\n        variables: source.variables,\n        before: source.before,\n        next: source.next,\n        cache: source.cache,\n        code: source.code,\n      } as Flow.Source;\n    }\n  }\n\n  // Process destinations with variable cascade\n  if (result.destinations) {\n    for (const [name, dest] of Object.entries(result.destinations)) {\n      const vars = mergeVariables(\n        config.variables,\n        settings.variables,\n        dest.variables,\n      );\n\n      const processedConfig = resolvePatterns(\n        dest.config,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      const processedEnv = resolvePatterns(\n        dest.env,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      result.destinations[name] = {\n        package: dest.package,\n        import: dest.import,\n        config: processedConfig,\n        env: processedEnv,\n        variables: dest.variables,\n        before: dest.before,\n        next: dest.next,\n        cache: dest.cache,\n        code: dest.code,\n      } as Flow.Destination;\n    }\n  }\n\n  // Process stores with variable cascade\n  if (result.stores) {\n    for (const [name, store] of Object.entries(result.stores)) {\n      const vars = mergeVariables(\n        config.variables,\n        settings.variables,\n        store.variables,\n      );\n\n      const processedConfig = resolvePatterns(\n        store.config,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      const processedEnv = resolvePatterns(\n        store.env,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      result.stores[name] = {\n        package: store.package,\n        import: store.import,\n        config: processedConfig,\n        env: processedEnv,\n        cache: store.cache,\n        variables: store.variables,\n        code: store.code,\n      } as Flow.Store;\n    }\n  }\n\n  // Process transformers with variable cascade\n  if (result.transformers) {\n    for (const [name, transformer] of Object.entries(result.transformers)) {\n      const vars = mergeVariables(\n        config.variables,\n        settings.variables,\n        transformer.variables,\n      );\n\n      const processedConfig = resolvePatterns(\n        transformer.config,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      const processedEnv = resolvePatterns(\n        transformer.env,\n        vars,\n        options,\n        resolvedContracts,\n        resolveFlow,\n      );\n\n      result.transformers[name] = {\n        package: transformer.package,\n        import: transformer.import,\n        config: processedConfig,\n        env: processedEnv,\n        variables: transformer.variables,\n        before: transformer.before,\n        next: transformer.next,\n        cache: transformer.cache,\n        code: transformer.code,\n      } as Flow.Transformer;\n    }\n  }\n\n  // Process collector config\n  if (result.collector) {\n    const vars = mergeVariables(config.variables, settings.variables);\n\n    const processedCollector = resolvePatterns(\n      result.collector,\n      vars,\n      options,\n      resolvedContracts,\n      resolveFlow,\n    );\n    result.collector = processedCollector as typeof result.collector;\n  }\n\n  return result;\n}\n\n/**\n * Get the platform of a flow ('web' or 'server').\n *\n * Reads from `flow.config.platform`.\n *\n * @param flow - Resolved flow (output of {@link getFlowSettings})\n * @returns \"web\" or \"server\"\n * @throws Error if `config.platform` is missing\n *\n * @example\n * ```typescript\n * import { getPlatform } from '@walkeros/core';\n *\n * const platform = getPlatform(flow);\n * // Returns \"web\" or \"server\"\n * ```\n */\nexport function getPlatform(flow: Flow): 'web' | 'server' {\n  const platform = flow.config?.platform;\n  if (platform === 'web' || platform === 'server') return platform;\n  throwError('Flow must have config.platform set to \"web\" or \"server\"');\n}\n","/**\n * @interface Assign\n * @description Options for the assign function.\n * @property merge - Merge array properties instead of overriding them.\n * @property shallow - Create a shallow copy instead of updating the target object.\n * @property extend - Extend the target with new properties instead of only updating existing ones.\n */\ninterface Assign {\n  merge?: boolean;\n  shallow?: boolean;\n  extend?: boolean;\n}\n\nconst defaultOptions: Assign = {\n  merge: true,\n  shallow: true,\n  extend: true,\n};\n\n/**\n * Merges objects with advanced options.\n *\n * @template T, U\n * @param target - The target object to merge into.\n * @param obj - The source object to merge from.\n * @param options - Options for merging.\n * @returns The merged object.\n */\nexport function assign<T extends object, U extends object>(\n  target: T,\n  obj: U = {} as U,\n  options: Assign = {},\n): T & U {\n  options = { ...defaultOptions, ...options };\n\n  const finalObj = Object.entries(obj).reduce((acc, [key, sourceProp]) => {\n    const targetProp = target[key as keyof typeof target];\n\n    // Only merge arrays\n    if (\n      options.merge &&\n      Array.isArray(targetProp) &&\n      Array.isArray(sourceProp)\n    ) {\n      acc[key as keyof typeof acc] = sourceProp.reduce(\n        (acc, item) => {\n          // Remove duplicates\n          return acc.includes(item) ? acc : [...acc, item];\n        },\n        [...targetProp],\n      );\n    } else if (options.extend || key in target) {\n      // Extend the target with new properties or update existing ones\n      acc[key as keyof typeof acc] = sourceProp;\n    }\n\n    return acc;\n  }, {} as U);\n\n  // Handle shallow or deep copy based on options\n  if (options.shallow) {\n    return { ...target, ...finalObj };\n  } else {\n    Object.assign(target, finalObj);\n    return target as T & U;\n  }\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if a value is an arguments object.\n *\n * @param value The value to check.\n * @returns True if the value is an arguments object, false otherwise.\n */\nexport function isArguments(value: unknown): value is IArguments {\n  return Object.prototype.toString.call(value) === '[object Arguments]';\n}\n\n/**\n * Checks if a value is an array.\n *\n * @param value The value to check.\n * @returns True if the value is an array, false otherwise.\n */\nexport function isArray<T>(value: unknown): value is T[] {\n  return Array.isArray(value);\n}\n\n/**\n * Checks if a value is a boolean.\n *\n * @param value The value to check.\n * @returns True if the value is a boolean, false otherwise.\n */\nexport function isBoolean(value: unknown): value is boolean {\n  return typeof value === 'boolean';\n}\n\n/**\n * Checks if an entity is a walker command.\n *\n * @param entity The entity to check.\n * @returns True if the entity is a walker command, false otherwise.\n */\nexport function isCommand(entity: string) {\n  return entity === 'walker';\n}\n\n/**\n * Checks if a value is defined.\n *\n * @param value The value to check.\n * @returns True if the value is defined, false otherwise.\n */\nexport function isDefined<T>(val: T | undefined): val is T {\n  return typeof val !== 'undefined';\n}\n\n/**\n * Checks if a value is an element or the document.\n *\n * @param elem The value to check.\n * @returns True if the value is an element or the document, false otherwise.\n */\nexport function isElementOrDocument(elem: unknown): elem is Element {\n  if (!elem || typeof elem !== 'object') return false;\n  // Property check: Document has 'body', Element has 'tagName'\n  return 'body' in elem || 'tagName' in elem;\n}\n\n/**\n * Checks if a value is a function.\n *\n * @param value The value to check.\n * @returns True if the value is a function, false otherwise.\n */\nexport function isFunction(value: unknown): value is Function {\n  return typeof value === 'function';\n}\n\n/**\n * Checks if a value is a number.\n *\n * @param value The value to check.\n * @returns True if the value is a number, false otherwise.\n */\nexport function isNumber(value: unknown): value is number {\n  return typeof value === 'number' && !Number.isNaN(value);\n}\n\n/**\n * Checks if a value is an object.\n *\n * @param value The value to check.\n * @returns True if the value is an object, false otherwise.\n */\nexport function isObject(value: unknown): value is WalkerOS.AnyObject {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !isArray(value) &&\n    Object.prototype.toString.call(value) === '[object Object]'\n  );\n}\n\n/**\n * Checks if two variables have the same type.\n *\n * @param variable The first variable.\n * @param type The second variable.\n * @returns True if the variables have the same type, false otherwise.\n */\nexport function isSameType<T>(\n  variable: unknown,\n  type: T,\n): variable is typeof type {\n  return typeof variable === typeof type;\n}\n\n/**\n * Checks if a value is a string.\n *\n * @param value The value to check.\n * @returns True if the value is a string, false otherwise.\n */\nexport function isString(value: unknown): value is string {\n  return typeof value === 'string';\n}\n","/**\n * Creates a deep clone of a value.\n * Supports primitive values, objects, arrays, dates, and regular expressions.\n * Handles circular references.\n *\n * @template T\n * @param org - The value to clone.\n * @param visited - A map of visited objects to handle circular references.\n * @returns The cloned value.\n */\nexport function clone<T>(\n  org: T,\n  visited: WeakMap<object, unknown> = new WeakMap(),\n): T {\n  // Handle primitive values and functions directly\n  if (typeof org !== 'object' || org === null) return org;\n\n  // Check for circular references\n  if (visited.has(org)) return visited.get(org) as T;\n\n  // Allow list of clonable types\n  const type = Object.prototype.toString.call(org);\n  if (type === '[object Object]') {\n    const clonedObj = {} as Record<string | symbol, unknown>;\n    visited.set(org as object, clonedObj); // Remember the reference\n\n    for (const key in org as Record<string | symbol, unknown>) {\n      if (Object.prototype.hasOwnProperty.call(org, key)) {\n        clonedObj[key] = clone(\n          (org as Record<string | symbol, unknown>)[key],\n          visited,\n        );\n      }\n    }\n    return clonedObj as T;\n  }\n\n  if (type === '[object Array]') {\n    const clonedArray = [] as unknown[];\n    visited.set(org as object, clonedArray); // Remember the reference\n\n    (org as unknown[]).forEach((item) => {\n      clonedArray.push(clone(item, visited));\n    });\n\n    return clonedArray as T;\n  }\n\n  if (type === '[object Date]') {\n    return new Date((org as unknown as Date).getTime()) as T;\n  }\n\n  if (type === '[object RegExp]') {\n    const reg = org as unknown as RegExp;\n    return new RegExp(reg.source, reg.flags) as T;\n  }\n\n  // Skip cloning for unsupported types and return reference\n  return org;\n}\n","import type { WalkerOS } from './types';\nimport { isArray, isDefined, isObject } from './is';\nimport { clone } from './clone';\n\n/**\n * Gets a value from an object by a dot-notation string.\n * Supports wildcards for arrays.\n *\n * @example\n * getByPath({ data: { id: 1 } }, \"data.id\") // Returns 1\n *\n * @param event - The object to get the value from.\n * @param key - The dot-notation string.\n * @param defaultValue - The default value to return if the key is not found.\n * @returns The value from the object or the default value.\n */\nexport function getByPath(\n  event: unknown,\n  key: string = '',\n  defaultValue?: unknown,\n): unknown {\n  const keys = key.split('.');\n  let values: unknown = event;\n\n  for (let index = 0; index < keys.length; index++) {\n    const k = keys[index];\n\n    if (k === '*' && isArray(values)) {\n      const remainingKeys = keys.slice(index + 1).join('.');\n      const result: unknown[] = [];\n\n      for (const item of values) {\n        const value = getByPath(item, remainingKeys, defaultValue);\n        result.push(value);\n      }\n\n      return result;\n    }\n\n    values =\n      isObject(values) || isArray(values)\n        ? values[k as keyof typeof values]\n        : undefined;\n\n    if (values === undefined) break;\n  }\n\n  return isDefined(values) ? values : defaultValue;\n}\n\n/**\n * Sets a value in an object by a dot-notation string.\n *\n * @param obj - The object to set the value in.\n * @param key - The dot-notation string.\n * @param value - The value to set.\n * @returns A new object with the updated value.\n */\nexport function setByPath<T = unknown>(obj: T, key: string, value: unknown): T {\n  if (!isObject(obj)) return obj;\n\n  const clonedObj = clone(obj);\n  const keys = key.split('.');\n  let current: WalkerOS.AnyObject = clonedObj;\n\n  for (let i = 0; i < keys.length; i++) {\n    const k = keys[i] as keyof typeof current;\n\n    // Set the value if it's the last key\n    if (i === keys.length - 1) {\n      current[k] = value;\n    } else {\n      // Traverse to the next level\n      if (\n        !(k in current) ||\n        typeof current[k] !== 'object' ||\n        current[k] === null\n      ) {\n        current[k] = {};\n      }\n\n      // Move deeper into the object\n      current = current[k] as WalkerOS.AnyObject;\n    }\n  }\n\n  return clonedObj as T;\n}\n\n/**\n * Deletes a value in an object by a dot-notation string.\n * Returns a new object; the input is not mutated. No-op when the path is\n * absent or the target is neither an object nor an array. Numeric segments\n * index into arrays; a final numeric segment splices the element out so no\n * empty slot is left behind.\n */\nexport function deleteByPath<T = unknown>(obj: T, key: string): T {\n  if (!isObject(obj) && !isArray(obj)) return obj;\n  const clonedObj = clone(obj);\n  const keys = key.split('.');\n  let current: WalkerOS.AnyObject | unknown[] = clonedObj;\n  for (let i = 0; i < keys.length; i++) {\n    const k = keys[i];\n    const isLast = i === keys.length - 1;\n\n    if (isArray(current)) {\n      const index = Number(k);\n      if (!Number.isInteger(index) || index < 0 || index >= current.length)\n        return clonedObj;\n      if (isLast) {\n        current.splice(index, 1);\n      } else {\n        const next = current[index];\n        if (!isObject(next) && !isArray(next)) return clonedObj;\n        current = next;\n      }\n    } else if (isLast) {\n      delete current[k];\n    } else {\n      const next = current[k];\n      if (!isObject(next) && !isArray(next)) return clonedObj;\n      current = next;\n    }\n  }\n  return clonedObj as T;\n}\n","import type { WalkerOS } from './types';\nimport { isObject } from './is';\n\nconst SECTIONS: Record<string, (e: WalkerOS.DeepPartialEvent) => unknown> = {\n  data: (e) => e.data,\n  globals: (e) => e.globals,\n  context: (e) => e.context,\n  user: (e) => e.user,\n  source: (e) => e.source,\n  event: (e) => ({\n    entity: e.entity,\n    action: e.action,\n    id: e.id,\n    timestamp: e.timestamp,\n    name: e.name,\n    trigger: e.trigger,\n    timing: (e as WalkerOS.Event).timing,\n  }),\n};\n\nexport function flattenIncludeSections(\n  event: WalkerOS.DeepPartialEvent,\n  sections: string[],\n): Record<string, unknown> {\n  const out: Record<string, unknown> = {};\n  const effective = sections.includes('all') ? Object.keys(SECTIONS) : sections;\n\n  for (const section of effective) {\n    const picker = SECTIONS[section];\n    if (!picker) continue;\n    const bag = picker(event);\n    if (!isObject(bag)) continue;\n\n    for (const [key, raw] of Object.entries(bag as Record<string, unknown>)) {\n      if (raw === undefined) continue;\n      // Context values are OrderedProperties tuples - extract the label.\n      const value = section === 'context' && Array.isArray(raw) ? raw[0] : raw;\n      out[`${section}_${key}`] = value;\n    }\n  }\n\n  return out;\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Casts a value to a specific type.\n *\n * @param value The value to cast.\n * @returns The casted value.\n */\nexport function castValue(value: unknown): WalkerOS.PropertyType {\n  if (value === 'true') return true;\n  if (value === 'false') return false;\n\n  const number = Number(value); // Converts \"\" to 0\n  if (value == number && value !== '') return number;\n\n  return String(value);\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Checks if the required consent is granted.\n *\n * @param required - The required consent states.\n * @param state - The current consent states.\n * @param individual - Individual consent states to prioritize.\n * @returns The granted consent states or false if not granted.\n */\nexport function getGrantedConsent(\n  required: WalkerOS.Consent | undefined,\n  state: WalkerOS.Consent = {},\n  individual: WalkerOS.Consent = {},\n): false | WalkerOS.Consent {\n  // Merge state and individual, prioritizing individual states\n  const states: WalkerOS.Consent = { ...state, ...individual };\n\n  const grantedStates: WalkerOS.Consent = {};\n  let hasRequiredConsent = !required || Object.keys(required).length === 0;\n\n  Object.keys(states).forEach((name) => {\n    if (states[name]) {\n      // consent granted\n      grantedStates[name] = true;\n\n      // Check if it's required and granted consent\n      if (required && required[name]) hasRequiredConsent = true;\n    }\n  });\n\n  return hasRequiredConsent ? grantedStates : false;\n}\n","import type { Destination } from './types';\nimport type { TypesOf, Config } from './types/destination';\nimport { assign } from './assign';\n\n/**\n * Creates a new destination instance by merging a base destination with additional configuration.\n *\n * This utility enables elegant destination configuration while avoiding config side-effects\n * that could occur when reusing destination objects across multiple collector instances.\n *\n * @param baseDestination - The base destination to extend\n * @param config - Additional configuration to merge with the base destination's config\n * @returns A new destination instance with merged configuration\n *\n * @example\n * ```typescript\n * // Types are inferred automatically from destinationGtag\n * elb('walker destination', createDestination(destinationGtag, {\n *   settings: { ga4: { measurementId: 'G-123' } }\n * }));\n * ```\n */\nexport function createDestination<I extends Destination.Instance>(\n  baseDestination: I,\n  config: Partial<Config<TypesOf<I>>>,\n): I {\n  // Create a shallow copy of the base destination to avoid mutations\n  const newDestination = { ...baseDestination };\n\n  // Deep merge the config, handling nested objects like settings and mapping\n  newDestination.config = assign(baseDestination.config, config, {\n    shallow: true, // Create new object, don't mutate original\n    merge: true, // Merge arrays\n    extend: true, // Allow new properties\n  });\n\n  // Handle nested settings merging if both have settings\n  if (baseDestination.config.settings && config.settings) {\n    newDestination.config.settings = assign(\n      baseDestination.config.settings as object,\n      config.settings as object,\n      { shallow: true, merge: true, extend: true },\n    ) as typeof newDestination.config.settings;\n  }\n\n  // Handle nested mapping merging if both have mapping\n  if (baseDestination.config.mapping && config.mapping) {\n    newDestination.config.mapping = assign(\n      baseDestination.config.mapping as object,\n      config.mapping as object,\n      { shallow: true, merge: true, extend: true },\n    ) as typeof newDestination.config.mapping;\n  }\n\n  return newDestination;\n}\n","import { isObject } from './is';\n\n/**\n * Deep merges source into target, mutating target in-place.\n * Recurses into plain objects; everything else is a leaf (replaced).\n * Skips undefined source values; null overwrites.\n */\nexport function deepMerge<T extends Record<string, unknown>>(\n  target: T,\n  source: Record<string, unknown>,\n): T {\n  if (!isObject(source)) return target;\n\n  for (const key of Object.keys(source)) {\n    const val = source[key];\n    if (val === undefined) continue;\n\n    if (isObject(val) && isObject(target[key])) {\n      deepMerge(target[key] as Record<string, unknown>, val);\n    } else {\n      (target as Record<string, unknown>)[key] = val;\n    }\n  }\n\n  return target;\n}\n","/**\n * Generates a random string of a given length.\n *\n * Draws from the platform CSPRNG (`crypto.getRandomValues`) when available,\n * with rejection sampling to keep the character distribution unbiased. Falls\n * back to `Math.random` only when no secure source is reachable.\n *\n * @param length - The length of the random string.\n * @param charset - Optional custom charset. Defaults to base-36 (0-9a-z).\n * @returns The random string.\n */\nconst defaultCharset = '0123456789abcdefghijklmnopqrstuvwxyz';\n\nexport function getId(length = 6, charset: string = defaultCharset): string {\n  const n = charset.length;\n  if (length <= 0 || n === 0) return '';\n\n  let str = '';\n\n  // Single-byte charsets can be sampled from the CSPRNG. Reject bytes above the\n  // largest multiple of n that fits in a byte so every character is equally likely.\n  if (n <= 256) {\n    const limit = 256 - (256 % n);\n    while (str.length < length) {\n      const need = length - str.length;\n      const buffer = new Uint8Array(Math.ceil(need * 1.3) + 4);\n      if (!secureBytes(buffer)) break; // No secure source, drop to fallback below\n      for (let i = 0; i < buffer.length && str.length < length; i++) {\n        if (buffer[i] < limit) str += charset[buffer[i] % n];\n      }\n    }\n  }\n\n  // Fallback for a missing CSPRNG or an oversized charset.\n  while (str.length < length) str += charset[(Math.random() * n) | 0];\n\n  return str;\n}\n\nfunction secureBytes(buffer: Uint8Array): boolean {\n  try {\n    const cryptoObj: Crypto | undefined = globalThis.crypto;\n    if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {\n      cryptoObj.getRandomValues(buffer);\n      return true;\n    }\n  } catch {\n    // Secure source unavailable, signal the caller to use the fallback.\n  }\n  return false;\n}\n","import { getId } from './getId';\n\nconst hexCharset = '0123456789abcdef';\n\n/**\n * Random lowercase-hex id of `length` characters via the CSPRNG-backed getId.\n * Regenerates on the all-zero value, which W3C Trace Context forbids for\n * trace-id and span-id (astronomically rare, but kept spec-correct).\n */\nexport function hexId(length: number): string {\n  let id = getId(length, hexCharset);\n  while (/^0+$/.test(id)) id = getId(length, hexCharset);\n  return id;\n}\n","import { hexId } from './hexId';\n\n/**\n * W3C span_id: 8 random bytes encoded as 16 lowercase hex characters.\n * Reference: W3C Trace Context (W3C Recommendation, January 2020).\n */\nexport function getSpanId(): string {\n  return hexId(16);\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\nimport { getSpanId } from './getSpanId';\n\n/**\n * Creates a complete event with default values.\n * Used for testing and debugging.\n *\n * Models a post-collector event: `source` always carries the run-stamped\n * `count` and `trace`, so a generated event matches one that has been pushed\n * through the collector. Override via `props.source` if needed.\n *\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function createEvent(\n  props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n  const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n  const id = props.id || getSpanId();\n\n  const defaultEvent: WalkerOS.Event = {\n    name: 'entity action',\n    data: {\n      string: 'foo',\n      number: 1,\n      boolean: true,\n      array: [0, 'text', false],\n      not: undefined,\n    },\n    context: { dev: ['test', 1] },\n    globals: { lang: 'elb' },\n    custom: { completely: 'random' },\n    user: { id: 'us3r', device: 'c00k13', session: 's3ss10n' },\n    nested: [\n      {\n        entity: 'child',\n        data: { is: 'subordinated' },\n      },\n    ],\n    consent: { functional: true },\n    id,\n    trigger: 'test',\n    entity: 'entity',\n    action: 'action',\n    timestamp,\n    timing: 3.14,\n    source: {\n      type: 'collector',\n      schema: '4',\n    },\n  };\n\n  // Note: Always prefer the props over the defaults\n\n  // Merge properties\n  const event = assign(defaultEvent, props, { merge: false });\n\n  // Mirror collector output: generated events always carry the run-stamped\n  // source fields (per-run count and a fixed, deterministic trace) so an event\n  // built from this helper matches a pushed event without tests having to\n  // assert them, and two generator calls produce equal events. Any source\n  // fields provided via props still win.\n  event.source = {\n    count: 1,\n    trace: '0a1b2c3d4e5f60718293a4b5c6d7e8f9',\n    ...event.source,\n  };\n\n  // Update conditions\n\n  // Entity and action from event\n  if (props.name) {\n    const [entity, action] = props.name.split(' ') ?? [];\n\n    if (entity && action) {\n      event.entity = entity;\n      event.action = action;\n    }\n  }\n\n  return event;\n}\n\n/**\n * Creates a complete event with default values based on the event name.\n * Used for testing and debugging.\n *\n * @param name - The name of the event to create.\n * @param props - Properties to override the default values.\n * @returns A complete event.\n */\nexport function getEvent(\n  name: string = 'entity action',\n  props: WalkerOS.DeepPartialEvent = {},\n): WalkerOS.Event {\n  const timestamp = props.timestamp || new Date().setHours(0, 13, 37, 0);\n\n  const quantity = 2;\n  const product1 = {\n    data: {\n      id: 'ers',\n      name: 'Everyday Ruck Snack',\n      color: 'black',\n      size: 'l',\n      price: 420,\n    },\n  };\n  const product2 = {\n    data: {\n      id: 'cc',\n      name: 'Cool Cap',\n      size: 'one size',\n      price: 42,\n    },\n  };\n\n  const defaultEvents: Record<string, WalkerOS.PartialEvent> = {\n    'cart view': {\n      data: {\n        currency: 'EUR',\n        value: product1.data.price * quantity,\n      },\n      context: { shopping: ['cart', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [\n        {\n          entity: 'product',\n          data: { ...product1.data, quantity },\n          context: { shopping: ['cart', 0] },\n          nested: [],\n        },\n      ],\n      trigger: 'load',\n    },\n    'checkout view': {\n      data: {\n        step: 'payment',\n        currency: 'EUR',\n        value: product1.data.price + product2.data.price,\n      },\n      context: { shopping: ['checkout', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [\n        {\n          entity: 'product',\n          ...product1,\n          context: { shopping: ['checkout', 0] },\n          nested: [],\n        },\n        {\n          entity: 'product',\n          ...product2,\n          context: { shopping: ['checkout', 0] },\n          nested: [],\n        },\n      ],\n      trigger: 'load',\n    },\n    'order complete': {\n      data: {\n        id: '0rd3r1d',\n        currency: 'EUR',\n        shipping: 5.22,\n        taxes: 73.76,\n        total: 555,\n      },\n      context: { shopping: ['complete', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [\n        {\n          entity: 'product',\n          ...product1,\n          context: { shopping: ['complete', 0] },\n          nested: [],\n        },\n        {\n          entity: 'product',\n          ...product2,\n          context: { shopping: ['complete', 0] },\n          nested: [],\n        },\n        {\n          entity: 'gift',\n          data: {\n            name: 'Surprise',\n          },\n          context: { shopping: ['complete', 0] },\n          nested: [],\n        },\n      ],\n      trigger: 'load',\n    },\n    'page view': {\n      data: {\n        domain: 'www.example.com',\n        title: 'walkerOS documentation',\n        referrer: 'https://www.walkeros.io/',\n        search: '?foo=bar',\n        hash: '#hash',\n        id: '/docs/',\n      },\n      globals: { pagegroup: 'docs' },\n      trigger: 'load',\n    },\n    'product add': {\n      ...product1,\n      context: { shopping: ['intent', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [],\n      trigger: 'click',\n    },\n    'product view': {\n      ...product1,\n      context: { shopping: ['detail', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [],\n      trigger: 'load',\n    },\n    'product visible': {\n      data: { ...product1.data, position: 3, promo: true },\n      context: { shopping: ['discover', 0] },\n      globals: { pagegroup: 'shop' },\n      nested: [],\n      trigger: 'load',\n    },\n    'promotion visible': {\n      data: {\n        name: 'Setting up tracking easily',\n        position: 'hero',\n      },\n      context: { ab_test: ['engagement', 0] },\n      globals: { pagegroup: 'homepage' },\n      trigger: 'visible',\n    },\n    'session start': {\n      data: {\n        id: 's3ss10n',\n        start: timestamp,\n        isNew: true,\n        count: 1,\n        runs: 1,\n        isStart: true,\n        storage: true,\n        referrer: '',\n        device: 'c00k13',\n      },\n      user: {\n        id: 'us3r',\n        device: 'c00k13',\n        session: 's3ss10n',\n        hash: 'h4sh',\n        address: 'street number',\n        email: 'user@example.com',\n        phone: '+49 123 456 789',\n        userAgent: 'Mozilla...',\n        browser: 'Chrome',\n        browserVersion: '90',\n        deviceType: 'desktop',\n        language: 'de-DE',\n        country: 'DE',\n        region: 'HH',\n        city: 'Hamburg',\n        zip: '20354',\n        timezone: 'Berlin',\n        os: 'walkerOS',\n        osVersion: '1.0',\n        screenSize: '1337x420',\n        ip: '127.0.0.0',\n        internal: true,\n        custom: 'value',\n      },\n    },\n  };\n\n  return createEvent({ ...defaultEvents[name], ...props, name: name });\n}\n","import { hexId } from './hexId';\n\n/**\n * W3C trace_id: 16 random bytes encoded as 32 lowercase hex characters.\n * Shared by every event of a collector run. Reference: W3C Trace Context.\n */\nexport function getTraceId(): string {\n  return hexId(32);\n}\n","import type { WalkerOS } from './types';\nimport { assign } from './assign';\n\nexport interface MarketingParameters {\n  [key: string]: string;\n}\n\n/**\n * Click-ID registry entry — maps a URL parameter name to a canonical platform.\n *\n * Runtime shape only; the corresponding Zod schema lives in\n * `@walkeros/core/dev` (schemas/marketing.ts) for dev tooling that needs\n * validation or JSON Schema generation.\n */\nexport interface ClickIdEntry {\n  param: string;\n  platform: string;\n}\n\n/**\n * Default click-ID registry.\n *\n * Ordered by priority: when a URL contains multiple click IDs, the entry\n * appearing earlier wins as the resolved `clickId` / `platform`. All matched\n * raw values are still preserved on the result.\n *\n * Extend via the third argument to {@link getMarketingParameters} or the\n * `clickIds` field in the session source settings.\n */\nexport const defaultClickIds: ClickIdEntry[] = [\n  // Google family — highest priority (most common globally)\n  { param: 'gclid', platform: 'google' },\n  { param: 'wbraid', platform: 'google' },\n  { param: 'gbraid', platform: 'google' },\n  { param: 'dclid', platform: 'google' },\n  { param: 'gclsrc', platform: 'google' },\n\n  // Meta\n  { param: 'fbclid', platform: 'meta' },\n  { param: 'igshid', platform: 'meta' },\n\n  // Microsoft / Bing\n  { param: 'msclkid', platform: 'microsoft' },\n\n  // TikTok\n  { param: 'ttclid', platform: 'tiktok' },\n\n  // X / Twitter\n  { param: 'twclid', platform: 'twitter' },\n\n  // LinkedIn\n  { param: 'li_fat_id', platform: 'linkedin' },\n\n  // Pinterest\n  { param: 'epik', platform: 'pinterest' },\n\n  // Snapchat — both spellings seen in the wild\n  { param: 'sclid', platform: 'snapchat' },\n  { param: 'sccid', platform: 'snapchat' },\n\n  // Reddit\n  { param: 'rdt_cid', platform: 'reddit' },\n\n  // Quora\n  { param: 'qclid', platform: 'quora' },\n\n  // Yandex (yclid collides with Yahoo Japan; Yandex chosen as default)\n  { param: 'yclid', platform: 'yandex' },\n  { param: 'ymclid', platform: 'yandex' },\n  { param: 'ysclid', platform: 'yandex' },\n\n  // Content discovery\n  { param: 'dicbo', platform: 'outbrain' },\n  { param: 'obclid', platform: 'outbrain' },\n  { param: 'tblci', platform: 'taboola' },\n\n  // Email service providers\n  { param: 'mc_cid', platform: 'mailchimp' },\n  { param: 'mc_eid', platform: 'mailchimp' },\n  { param: '_kx', platform: 'klaviyo' },\n  { param: '_hsenc', platform: 'hubspot' },\n  { param: '_hsmi', platform: 'hubspot' },\n\n  // Adobe / Marketo\n  { param: 's_kwcid', platform: 'adobe' },\n  { param: 'ef_id', platform: 'adobe' },\n  { param: 'mkt_tok', platform: 'adobe' },\n\n  // Affiliate\n  { param: 'irclickid', platform: 'impact' },\n  { param: 'cjevent', platform: 'cj' },\n\n  // Deep linking\n  { param: '_branch_match_id', platform: 'branch' },\n];\n\n/**\n * Extracts marketing parameters from a URL.\n *\n * - UTM and custom params are mapped to friendly names (`utm_source` → `source`).\n * - Known click IDs are detected case-insensitively; each raw value is stored\n *   under its canonical lowercase param name.\n * - `clickId` and `platform` reference the highest-priority match (first entry\n *   in the registry present in the URL).\n * - Custom `clickIds` override default platforms by `param` in place and\n *   append new params at the end of the priority list.\n */\nexport function getMarketingParameters(\n  url: URL,\n  custom: MarketingParameters = {},\n  clickIds: ClickIdEntry[] = [],\n): WalkerOS.Properties {\n  const data: WalkerOS.Properties = {};\n\n  // UTMs and custom mapped params\n  const utmParams: MarketingParameters = {\n    utm_campaign: 'campaign',\n    utm_content: 'content',\n    utm_medium: 'medium',\n    utm_source: 'source',\n    utm_term: 'term',\n  };\n  Object.entries(assign(utmParams, custom)).forEach(([key, name]) => {\n    const value = url.searchParams.get(key);\n    if (value) data[name] = value;\n  });\n\n  // Effective registry: defaults with user overrides applied in place,\n  // plus brand-new user params appended at the end. Reuses the defaults\n  // array when no customization is requested.\n  const registry = clickIds.length ? mergeRegistry(clickIds) : defaultClickIds;\n\n  // Lowercase URL params once for case-insensitive lookup\n  const lower = new Map<string, string>();\n  url.searchParams.forEach((value, key) => {\n    if (value) lower.set(key.toLowerCase(), value);\n  });\n\n  // Walk registry in priority order; first match wins as clickId/platform\n  for (const entry of registry) {\n    const value = lower.get(entry.param);\n    if (!value) continue;\n    data[entry.param] = value;\n    if (!data.clickId) {\n      data.clickId = entry.param;\n      data.platform = entry.platform;\n    }\n  }\n\n  return data;\n}\n\nfunction mergeRegistry(user: ClickIdEntry[]): ClickIdEntry[] {\n  const overrides = new Map(user.map((e) => [e.param, e.platform]));\n  const defaultParams = new Set(defaultClickIds.map((e) => e.param));\n  return [\n    ...defaultClickIds.map((e) =>\n      overrides.has(e.param)\n        ? { param: e.param, platform: overrides.get(e.param)! }\n        : e,\n    ),\n    ...user.filter((e) => !defaultParams.has(e.param)),\n  ];\n}\n","/**\n * Options for scheduling primitives ({@link debounce}, {@link throttle}).\n *\n * - `wait`: Debounce window in ms. Timer resets on every call.\n * - `size`: Hard call-count cap per window. Flush immediately when call\n *   count reaches this number. Useful for batch buffers that must not\n *   grow unbounded.\n * - `age`: Hard age cap in ms since the first call of the current window.\n *   Forces a flush even if calls keep arriving and reset the debounce.\n *   Prevents debounce starvation under sustained load.\n */\nexport interface ScheduleOptions {\n  wait?: number;\n  size?: number;\n  age?: number;\n}\n\n/**\n * Returned by {@link debounce}: a callable that schedules `fn` plus\n * deterministic `flush` / `cancel` controls.\n */\nexport interface Debounced<P extends unknown[], R> {\n  (...args: P): Promise<R | undefined>;\n  /** Force an immediate flush with the most recent args. Resolves after `fn` settles. */\n  flush(): Promise<R | undefined>;\n  /** Cancel any pending invocation. No `fn` call, pending promises resolve to undefined. */\n  cancel(): void;\n  /** Number of scheduled calls since the current window opened. */\n  size(): number;\n}\n\nfunction normalizeScheduleOptions(\n  opts: number | ScheduleOptions | undefined,\n  defaultWait: number,\n): { wait: number; size?: number; age?: number } {\n  if (typeof opts === 'number') return { wait: opts };\n  if (!opts) return { wait: defaultWait };\n  return {\n    wait: opts.wait ?? defaultWait,\n    size: opts.size,\n    age: opts.age,\n  };\n}\n\n/**\n * Creates a debounced function that delays invoking `fn` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `fn` invocations and a `flush` method to immediately invoke them.\n *\n * The second argument is either a `wait` number (legacy form) or a\n * {@link ScheduleOptions} object. The object form adds `size` (hard count\n * cap) and `age` (hard window-age cap) so the function flushes deterministically\n * under sustained load instead of letting the debounce reset forever.\n *\n * @template P, R\n * @param fn The function to debounce.\n * @param opts Either a wait-ms number or a {@link ScheduleOptions} object.\n * @param immediate Trigger the function on the leading edge, instead of the trailing.\n * @returns A {@link Debounced} callable with `flush`, `cancel`, and `size` methods.\n */\nexport function debounce<P extends unknown[], R>(\n  fn: (...args: P) => R,\n  opts: number | ScheduleOptions = 1000,\n  immediate = false,\n): Debounced<P, R> {\n  const {\n    wait,\n    size: maxSize,\n    age: maxAge,\n  } = normalizeScheduleOptions(opts, 1000);\n\n  let waitTimer: ReturnType<typeof setTimeout> | null = null;\n  let ageTimer: ReturnType<typeof setTimeout> | null = null;\n  let result: R | undefined;\n  let hasCalledImmediately = false;\n  let lastArgs: P | undefined;\n  let pending: Array<(value: R | undefined) => void> = [];\n  let count = 0;\n\n  const reset = (): void => {\n    if (waitTimer) {\n      clearTimeout(waitTimer);\n      waitTimer = null;\n    }\n    if (ageTimer) {\n      clearTimeout(ageTimer);\n      ageTimer = null;\n    }\n    count = 0;\n    lastArgs = undefined;\n  };\n\n  const fire = (): R | undefined => {\n    const args = lastArgs;\n    const settle = pending;\n    reset();\n    pending = [];\n    if (!args) {\n      // Nothing scheduled. Resolve waiters with undefined.\n      settle.forEach((r) => r(undefined));\n      return undefined;\n    }\n    result = fn(...args);\n    settle.forEach((r) => r(result));\n    return result;\n  };\n\n  const debounced = ((...args: P): Promise<R | undefined> => {\n    return new Promise<R | undefined>((resolve) => {\n      const callNow = immediate && !hasCalledImmediately;\n\n      lastArgs = args;\n      count += 1;\n      pending.push(resolve);\n\n      // Reset debounce timer on every call.\n      if (waitTimer) clearTimeout(waitTimer);\n      waitTimer = setTimeout(() => {\n        waitTimer = null;\n        if (!immediate || hasCalledImmediately) {\n          fire();\n        }\n      }, wait);\n\n      // Arm the age timer once per window (on first call).\n      if (maxAge !== undefined && !ageTimer) {\n        ageTimer = setTimeout(() => {\n          ageTimer = null;\n          fire();\n        }, maxAge);\n      }\n\n      // Size cap: flush synchronously when reached.\n      if (maxSize !== undefined && count >= maxSize) {\n        fire();\n        return;\n      }\n\n      if (callNow) {\n        hasCalledImmediately = true;\n        result = fn(...args);\n        // Drain pending promises (only this caller is pending at the\n        // immediate edge, but be safe).\n        const settle = pending;\n        pending = [];\n        settle.forEach((r) => r(result));\n      }\n    });\n  }) as Debounced<P, R>;\n\n  debounced.flush = (): Promise<R | undefined> => {\n    if (!lastArgs && pending.length === 0) {\n      // Nothing buffered, but an autonomous fire (wait/age/size cap) may have\n      // already drained the window and left its `fn` return in `result`. For a\n      // batch flush whose `fn` is async, that promise can still be in flight.\n      // Return it so a caller like graceful shutdown awaits the in-flight work\n      // instead of racing teardown (e.g. closing a writer mid-append). When\n      // the last fire was sync/settled, awaiting a resolved value is a no-op.\n      return Promise.resolve(result);\n    }\n    return new Promise<R | undefined>((resolve) => {\n      pending.push(resolve);\n      fire();\n    });\n  };\n\n  debounced.cancel = (): void => {\n    const settle = pending;\n    pending = [];\n    reset();\n    // Drop the last fire's retained return so a later empty flush() cannot\n    // surface a stale, cancelled-context result instead of undefined.\n    result = undefined;\n    settle.forEach((r) => r(undefined));\n  };\n\n  debounced.size = (): number => count;\n\n  return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `fn` at most once per\n * every `delay` milliseconds.\n *\n * The second argument is either a delay-ms number (legacy form) or a\n * {@link ScheduleOptions} object. The object form is accepted for\n * symmetry with {@link debounce}; the `wait` field is used as the\n * inter-invocation interval. `size` and `age` are accepted but have no\n * semantic role in throttle (no buffer is held) — they exist so the\n * primitive can be swapped with `debounce` behind a single config shape.\n *\n * @template P, R\n * @param fn The function to throttle.\n * @param opts Either a delay-ms number or a {@link ScheduleOptions} object.\n * @returns The new throttled function.\n */\n\ntype Timeout = ReturnType<typeof setTimeout>;\nexport function throttle<P extends unknown[], R>(\n  fn: (...args: P) => R | undefined,\n  opts: number | ScheduleOptions = 1000,\n): (...args: P) => R | undefined {\n  const { wait } = normalizeScheduleOptions(opts, 1000);\n  let isBlocked: Timeout | null = null;\n\n  return function (...args: P): R | undefined {\n    // Skip since function is still blocked by previous call\n    if (isBlocked !== null) return;\n\n    // Set a blocking timeout\n    isBlocked = setTimeout(() => {\n      // Unblock function\n      isBlocked = null;\n    }, wait) as Timeout;\n\n    // Call the function\n    return fn(...args);\n  };\n}\n","import type {\n  Config,\n  DefaultHandler,\n  ErrorContext,\n  Handler,\n  Instance,\n  InternalConfig,\n  LogContext,\n} from './types/logger';\nimport { Level } from './types/logger';\n\n/**\n * Normalize an Error object into ErrorContext\n */\nfunction normalizeError(err: Error): ErrorContext {\n  return {\n    message: err.message,\n    name: err.name,\n    stack: err.stack,\n    cause: (err as Error & { cause?: unknown }).cause,\n  };\n}\n\n/**\n * Normalize message and context parameters\n * Handles Error objects passed as message or context\n */\nfunction normalizeParams(\n  message: string | Error,\n  context?: unknown | Error,\n): { message: string; context: LogContext } {\n  let normalizedMessage: string;\n  let normalizedContext: LogContext = {};\n\n  // Handle message\n  if (message instanceof Error) {\n    normalizedMessage = message.message;\n    normalizedContext.error = normalizeError(message);\n  } else {\n    normalizedMessage = message;\n  }\n\n  // Handle context\n  if (context !== undefined) {\n    if (context instanceof Error) {\n      normalizedContext.error = normalizeError(context);\n    } else if (typeof context === 'object' && context !== null) {\n      normalizedContext = { ...normalizedContext, ...(context as object) };\n      // If context has an error property that's an Error, normalize it\n      if (\n        'error' in normalizedContext &&\n        normalizedContext.error instanceof Error\n      ) {\n        normalizedContext.error = normalizeError(\n          normalizedContext.error as unknown as Error,\n        );\n      }\n    } else {\n      normalizedContext.value = context;\n    }\n  }\n\n  return { message: normalizedMessage, context: normalizedContext };\n}\n\n/**\n * Default console-based log handler\n */\nconst defaultHandler: DefaultHandler = (level, message, context, scope) => {\n  const levelName = Level[level];\n  const scopePath = scope.length > 0 ? ` [${scope.join(':')}]` : '';\n  const prefix = `${levelName}${scopePath}`;\n\n  const hasContext = Object.keys(context).length > 0;\n\n  const consoleFn =\n    level === Level.ERROR\n      ? console.error\n      : level === Level.WARN\n        ? console.warn\n        : console.log;\n\n  if (hasContext) {\n    consoleFn(prefix, message, context);\n  } else {\n    consoleFn(prefix, message);\n  }\n};\n\n/**\n * Normalize log level from string or enum to enum value\n */\nfunction normalizeLevel(level: Level | keyof typeof Level): Level {\n  if (typeof level === 'string') {\n    return Level[level as keyof typeof Level];\n  }\n  return level;\n}\n\n/**\n * Create a logger instance\n *\n * @param config - Logger configuration\n * @returns Logger instance with all log methods and scoping support\n *\n * @example\n * ```typescript\n * // Basic usage\n * const logger = createLogger({ level: 'DEBUG' });\n * logger.info('Hello world');\n *\n * // With scoping\n * const destLogger = logger.scope('gtag').scope('myInstance');\n * destLogger.debug('Processing event'); // DEBUG [gtag:myInstance] Processing event\n *\n * // With custom handler\n * const logger = createLogger({\n *   handler: (level, message, context, scope, originalHandler) => {\n *     // Custom logic (e.g., send to Sentry)\n *     originalHandler(level, message, context, scope);\n *   }\n * });\n * ```\n *\n * // TODO: Consider compile-time stripping of debug logs in production builds\n * // e.g., if (__DEV__) { logger.debug(...) }\n */\nexport function createLogger(config: Config = {}): Instance {\n  const level =\n    config.level !== undefined ? normalizeLevel(config.level) : Level.ERROR;\n  const customHandler = config.handler;\n  const jsonHandler = config.jsonHandler;\n  const scope: string[] = [];\n\n  return createLoggerInternal({\n    level,\n    handler: customHandler,\n    jsonHandler,\n    scope,\n  });\n}\n\n/**\n * Internal logger creation with resolved config\n */\nfunction createLoggerInternal(config: InternalConfig): Instance {\n  const { level, handler, jsonHandler, scope } = config;\n\n  /**\n   * Internal log function that checks level and delegates to handler\n   */\n  const log = (\n    logLevel: Level,\n    message: string | Error,\n    context?: unknown | Error,\n  ): void => {\n    if (logLevel <= level) {\n      const normalized = normalizeParams(message, context);\n\n      if (handler) {\n        // Custom handler with access to default handler\n        handler(\n          logLevel,\n          normalized.message,\n          normalized.context,\n          scope,\n          defaultHandler,\n        );\n      } else {\n        defaultHandler(logLevel, normalized.message, normalized.context, scope);\n      }\n    }\n  };\n\n  /**\n   * Log and throw - combines logging and throwing\n   */\n  const logAndThrow = (message: string | Error, context?: unknown): never => {\n    // Always log errors regardless of level\n    const normalized = normalizeParams(message, context);\n\n    if (handler) {\n      handler(\n        Level.ERROR,\n        normalized.message,\n        normalized.context,\n        scope,\n        defaultHandler,\n      );\n    } else {\n      defaultHandler(\n        Level.ERROR,\n        normalized.message,\n        normalized.context,\n        scope,\n      );\n    }\n\n    // Throw with the message\n    throw new Error(normalized.message);\n  };\n\n  return {\n    error: (message, context) => log(Level.ERROR, message, context),\n    warn: (message, context) => log(Level.WARN, message, context),\n    info: (message, context) => log(Level.INFO, message, context),\n    debug: (message, context) => log(Level.DEBUG, message, context),\n    throw: logAndThrow,\n    json: (data: unknown) => {\n      if (jsonHandler) {\n        jsonHandler(data);\n      } else {\n        // eslint-disable-next-line no-console\n        console.log(JSON.stringify(data, null, 2));\n      }\n    },\n    scope: (name: string) =>\n      createLoggerInternal({\n        level,\n        handler,\n        jsonHandler,\n        scope: [...scope, name],\n      }),\n  };\n}\n\n// Re-export Level enum for convenience\nexport { Level };\n","import type { WalkerOS } from './types';\nimport {\n  isArguments,\n  isArray,\n  isBoolean,\n  isDefined,\n  isNumber,\n  isObject,\n  isString,\n} from './is';\n\n/**\n * Checks if a value is a valid property type.\n *\n * @param value The value to check.\n * @returns True if the value is a valid property type, false otherwise.\n */\nexport function isPropertyType(value: unknown): value is WalkerOS.PropertyType {\n  return (\n    isBoolean(value) ||\n    isString(value) ||\n    isNumber(value) ||\n    !isDefined(value) ||\n    (isArray(value) && value.every(isPropertyType)) ||\n    (isObject(value) && Object.values(value).every(isPropertyType))\n  );\n}\n\n/**\n * Filters a value to only include valid property types.\n *\n * @param value The value to filter.\n * @returns The filtered value or undefined.\n */\nexport function filterValues(value: unknown): WalkerOS.Property | undefined {\n  if (isBoolean(value) || isString(value) || isNumber(value)) return value;\n\n  if (isArguments(value)) return filterValues(Array.from(value));\n\n  if (isArray(value)) {\n    return value\n      .map((item) => filterValues(item))\n      .filter((item): item is WalkerOS.PropertyType => item !== undefined);\n  }\n\n  if (isObject(value)) {\n    return Object.entries(value).reduce<Record<string, WalkerOS.Property>>(\n      (acc, [key, val]) => {\n        const filteredValue = filterValues(val);\n        if (filteredValue !== undefined) acc[key] = filteredValue;\n        return acc;\n      },\n      {},\n    );\n  }\n\n  return;\n}\n\n/**\n * Casts a value to a valid property type.\n *\n * @param value The value to cast.\n * @returns The casted value or undefined.\n */\nexport function castToProperty(value: unknown): WalkerOS.Property | undefined {\n  return isPropertyType(value) ? value : undefined;\n}\n","/**\n * A utility function that wraps a function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatch<P extends unknown[], R, S>(\n  fn: (...args: P) => R | undefined,\n  onError: (err: unknown) => S,\n  onFinally?: () => void,\n): (...args: P) => R | S;\nexport function tryCatch<P extends unknown[], R>(\n  fn: (...args: P) => R | undefined,\n  onError?: undefined,\n  onFinally?: () => void,\n): (...args: P) => R | undefined;\n// Implementation\nexport function tryCatch<P extends unknown[], R, S>(\n  fn: (...args: P) => R | undefined,\n  onError?: (err: unknown) => S,\n  onFinally?: () => void,\n): (...args: P) => R | S | undefined {\n  return function (...args: P): R | S | undefined {\n    try {\n      return fn(...args);\n    } catch (err) {\n      if (!onError) return;\n      return onError(err);\n    } finally {\n      onFinally?.();\n    }\n  };\n}\n\n/**\n * A utility function that wraps an async function in a try-catch block.\n *\n * @template P, R, S\n * @param fn The async function to wrap.\n * @param onError A function to call when an error is caught.\n * @param onFinally A function to call in the finally block.\n * @returns The wrapped async function.\n */\n// Use function overload to support different return type depending on onError\n// Types\nexport function tryCatchAsync<P extends unknown[], R, S>(\n  fn: (...args: P) => R,\n  onError: (err: unknown) => S,\n  onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S>;\nexport function tryCatchAsync<P extends unknown[], R>(\n  fn: (...args: P) => R,\n  onError?: undefined,\n  onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | undefined>;\n// Implementation\nexport function tryCatchAsync<P extends unknown[], R, S>(\n  fn: (...args: P) => R,\n  onError?: (err: unknown) => S,\n  onFinally?: () => void | Promise<void>,\n): (...args: P) => Promise<R | S | undefined> {\n  return async function (...args: P): Promise<R | S | undefined> {\n    try {\n      return await fn(...args);\n    } catch (err) {\n      if (!onError) return;\n      return await onError(err);\n    } finally {\n      await onFinally?.();\n    }\n  };\n}\n","/**\n * Error subclass for invariant violations or operator-initiated aborts\n * that must escape the top-level boundary catches in `collector.push`\n * and `collector.command`.\n *\n * Standard `Error` instances are absorbed by the boundary, logged, and\n * counted on `collector.status.failed`. A `FatalError` rethrows so a\n * runtime supervisor (CLI runner, Express server, container orchestrator)\n * can terminate the process cleanly.\n *\n * Use sparingly. Most operational failures are recoverable and should\n * be plain `Error`. Reserve `FatalError` for programmer-error invariant\n * violations or explicit fail-stop signals.\n */\nexport class FatalError extends Error {\n  constructor(message: string, options?: ErrorOptions) {\n    super(message, options);\n    this.name = 'FatalError';\n\n    // Preserve prototype chain for `instanceof` checks across realms.\n    Object.setPrototypeOf(this, FatalError.prototype);\n  }\n}\n","import type { Mapping, WalkerOS, Collector } from './types';\nimport { deleteByPath, getByPath, setByPath } from './byPath';\nimport { isArray, isDefined, isString, isObject } from './is';\nimport { castToProperty } from './property';\nimport { tryCatchAsync } from './tryCatch';\nimport { FatalError } from './fatalError';\nimport { getGrantedConsent } from './consent';\nimport { assign } from './assign';\nimport { flattenIncludeSections } from './include';\n\n/**\n * Gets the mapping for an event.\n *\n * @param event The event to get the mapping for (can be partial or full).\n * @param mapping The mapping rules.\n * @param collector Required to evaluate rule-level conditions against the unified Context. Legacy callers may omit; rule-level conditions then run with `undefined as never` (defensive).\n * @returns The mapping result.\n */\nexport async function getMappingEvent(\n  event: WalkerOS.DeepPartialEvent | WalkerOS.PartialEvent | WalkerOS.Event,\n  mapping?: Mapping.Rules,\n  collector?: Collector.Instance,\n): Promise<Mapping.Result> {\n  const [entity, action] = (event.name || '').split(' ');\n  if (!mapping || !entity || !action) return {};\n\n  let eventMapping: Mapping.Rule | undefined;\n  let mappingKey = '';\n  let entityKey = entity;\n  let actionKey = action;\n\n  const resolveEventMapping = (\n    rules?: Mapping.Rule | Mapping.Rule[],\n  ): Mapping.Rule | undefined => {\n    if (!rules) return;\n    const list = isArray(rules) ? rules : [rules];\n    return list.find((rule) => {\n      if (!rule.condition) return true;\n      if (!collector) {\n        // Rule-level condition without a collector cannot be evaluated against\n        // the unified Context. Treat as match (legacy behavior) — internal\n        // callers should always pass collector; this branch is defensive.\n        return Boolean(rule.condition(event, undefined as never));\n      }\n      const ctx: Mapping.Context = {\n        event,\n        mapping: rule,\n        collector,\n        logger: collector.logger,\n        consent: ((isObject(event) &&\n          (event as WalkerOS.PartialEvent).consent) ||\n          collector.consent) as WalkerOS.Consent,\n      };\n      return Boolean(rule.condition(event, ctx));\n    });\n  };\n\n  if (!mapping[entityKey]) entityKey = '*';\n  const entityMapping = mapping[entityKey];\n\n  if (entityMapping) {\n    if (!entityMapping[actionKey]) actionKey = '*';\n    eventMapping = resolveEventMapping(entityMapping[actionKey]);\n  }\n\n  if (!eventMapping) {\n    entityKey = '*';\n    actionKey = '*';\n    eventMapping = resolveEventMapping(mapping[entityKey]?.[actionKey]);\n  }\n\n  if (eventMapping) mappingKey = `${entityKey} ${actionKey}`;\n\n  return { eventMapping, mappingKey };\n}\n\n/**\n * Gets a value from a mapping.\n *\n * @param value The value to get the mapping from.\n * @param data The mapping data.\n * @param options The mapping options.\n * @returns The mapped value.\n */\nexport async function getMappingValue(\n  value: WalkerOS.DeepPartialEvent | unknown | undefined,\n  data: Mapping.Data = {},\n  context: Partial<Mapping.Context> = {},\n): Promise<WalkerOS.Property | undefined> {\n  if (!isDefined(value)) return;\n\n  // Resolve consent in priority order: value.consent > context.consent > collector.consent\n  const consent =\n    ((isObject(value) && value.consent) as WalkerOS.Consent) ||\n    context.consent ||\n    context.collector?.consent;\n\n  // Resolve event: explicit context.event wins; else infer from value when it is an event-shaped object.\n  const event = (context.event ??\n    (isObject(value) ? value : {})) as WalkerOS.DeepPartialEvent;\n\n  if (!context.collector) {\n    // Internal sites (cache.ts, top-level callers) MUST pass a collector.\n    // This guard catches plumbing bugs early instead of silent type-narrowing.\n    throw new Error('getMappingValue: context.collector is required');\n  }\n\n  const baseContext: Mapping.Context = {\n    event,\n    mapping: data as Mapping.Value,\n    collector: context.collector,\n    logger: context.collector.logger,\n    consent,\n  };\n\n  const mappings = isArray(data) ? data : [data];\n  for (const mapping of mappings) {\n    const result = await tryCatchAsync(\n      processMappingValue,\n      (err: unknown): undefined => {\n        if (err instanceof FatalError) throw err;\n        if (context.collector) context.collector.status.failed++;\n        baseContext.logger.error('mapping processing failed', {\n          event,\n          error: err,\n        });\n        return undefined;\n      },\n    )(value, mapping, {\n      ...baseContext,\n      mapping,\n    });\n    if (isDefined(result)) return result;\n  }\n  return;\n}\n\nasync function processMappingValue(\n  value: WalkerOS.DeepPartialEvent | unknown,\n  mapping: Mapping.Value,\n  context: Mapping.Context,\n): Promise<WalkerOS.Property | undefined> {\n  const mappings = isArray(mapping) ? mapping : [mapping];\n\n  return mappings.reduce(\n    async (accPromise, mappingItem) => {\n      const acc = await accPromise;\n      if (acc) return acc;\n\n      const mapping = isString(mappingItem)\n        ? { key: mappingItem }\n        : mappingItem;\n\n      if (!Object.keys(mapping).length) return;\n\n      const {\n        condition,\n        consent,\n        fn,\n        key,\n        loop,\n        map,\n        set,\n        validate,\n        value: staticValue,\n      } = mapping;\n\n      // Per-mapping context — `mapping` reflects the current item.\n      const cbContext: Mapping.Context = { ...context, mapping: mappingItem };\n\n      if (\n        condition &&\n        !(await tryCatchAsync(condition, (err: unknown): boolean => {\n          if (err instanceof FatalError) throw err;\n          cbContext.logger.error('mapping condition failed', {\n            event: cbContext.event,\n            error: err,\n          });\n          return false; // Preserve \"skip this rule\" semantic on throw.\n        })(value, cbContext))\n      )\n        return;\n\n      if (consent && !getGrantedConsent(consent, cbContext.consent))\n        return staticValue;\n\n      let mappingValue: unknown = isDefined(staticValue) ? staticValue : value;\n\n      if (fn) {\n        mappingValue = await tryCatchAsync(fn, (err: unknown): undefined => {\n          if (err instanceof FatalError) throw err;\n          cbContext.logger.error('mapping fn failed', {\n            event: cbContext.event,\n            error: err,\n          });\n          return undefined; // No transform on error.\n        })(value, cbContext);\n      }\n\n      if (key) {\n        mappingValue = getByPath(value, key, staticValue);\n      }\n\n      if (loop) {\n        const [scope, itemMapping] = loop;\n        const data =\n          scope === 'this'\n            ? [value]\n            : await getMappingValue(value, scope, cbContext);\n\n        if (isArray(data)) {\n          mappingValue = (\n            await Promise.all(\n              data.map((item) => getMappingValue(item, itemMapping, cbContext)),\n            )\n          ).filter(isDefined);\n        }\n      } else if (map) {\n        mappingValue = await Object.entries(map).reduce(\n          async (mappedObjPromise, [mapKey, mapValue]) => {\n            const mappedObj = await mappedObjPromise;\n            const result = await getMappingValue(value, mapValue, cbContext);\n            if (isDefined(result)) mappedObj[mapKey] = result;\n            return mappedObj;\n          },\n          Promise.resolve({} as WalkerOS.AnyObject),\n        );\n      } else if (set) {\n        mappingValue = await Promise.all(\n          set.map((item) => processMappingValue(value, item, cbContext)),\n        );\n      }\n\n      if (\n        validate &&\n        !(await tryCatchAsync(validate, (err: unknown): boolean => {\n          if (err instanceof FatalError) throw err;\n          cbContext.logger.error('mapping validate failed', {\n            event: cbContext.event,\n            error: err,\n          });\n          return false; // Preserve \"validation failed\" semantic on throw.\n        })(mappingValue, cbContext))\n      )\n        mappingValue = undefined;\n\n      const property = castToProperty(mappingValue);\n      return isDefined(property) ? property : castToProperty(staticValue);\n    },\n    Promise.resolve(undefined as WalkerOS.Property | undefined),\n  );\n}\n\n/**\n * Processes an event through mapping configuration.\n *\n * This is the unified mapping logic used by both sources and destinations.\n * It applies transformations in this order:\n * 1. Config-level policy - modifies the event itself (global rules)\n * 2. Mapping rules - finds matching rule based on entity-action\n * 3. Event-level policy - modifies the event based on specific mapping rule\n * 4. Data transformation - creates context data\n * 5. Ignore check and name override\n *\n * Sources can pass partial events, destinations pass full events.\n * getMappingValue works with both partial and full events.\n *\n * @param event - The event to process (can be partial or full, will be mutated by policies)\n * @param config - Mapping configuration (mapping, data, policy, consent)\n * @param collector - Collector instance for context\n * @returns Object with transformed event, data, mapping rule, and ignore flag\n */\nexport async function processEventMapping<\n  T extends WalkerOS.DeepPartialEvent | WalkerOS.Event,\n>(\n  event: T,\n  config: Mapping.Config,\n  collector: Collector.Instance,\n): Promise<{\n  event: T;\n  data?: WalkerOS.Property;\n  mapping?: Mapping.Rule;\n  mappingKey?: string;\n  ignore: boolean;\n  silent: boolean;\n}> {\n  // Step 1: Apply config-level policy (modifies event)\n  if (config.policy) {\n    await Promise.all(\n      Object.entries(config.policy).map(async ([key, mapping]) => {\n        const value = await getMappingValue(event, mapping, {\n          collector,\n          event,\n        });\n        event = setByPath(event, key, value);\n      }),\n    );\n  }\n\n  // Step 2: Get event mapping rule\n  const { eventMapping, mappingKey } = await getMappingEvent(\n    event,\n    config.mapping,\n    collector,\n  );\n\n  // Step 2.5: Apply event-level policy (modifies event)\n  if (eventMapping?.policy) {\n    await Promise.all(\n      Object.entries(eventMapping.policy).map(async ([key, mapping]) => {\n        const value = await getMappingValue(event, mapping, {\n          collector,\n          event,\n        });\n        event = setByPath(event, key, value);\n      }),\n    );\n  }\n\n  // Step 3: Transform global data\n  let data =\n    config.data &&\n    (await getMappingValue(event, config.data, { collector, event }));\n\n  const silent = Boolean(eventMapping?.silent);\n\n  if (eventMapping) {\n    // Check if event should be ignored\n    if (eventMapping.ignore) {\n      return {\n        event,\n        data,\n        mapping: eventMapping,\n        mappingKey,\n        ignore: true,\n        silent,\n      };\n    }\n\n    // Override event name if specified\n    if (eventMapping.name) event.name = eventMapping.name;\n\n    // Transform event-specific data\n    if (eventMapping.data) {\n      const dataEvent =\n        eventMapping.data &&\n        (await getMappingValue(event, eventMapping.data, {\n          collector,\n          event,\n        }));\n      data =\n        isObject(data) && isObject(dataEvent) // Only merge objects\n          ? assign(data, dataEvent)\n          : dataEvent;\n    }\n  }\n\n  // Include: flatten event sections into data. Rule-level replaces config-level.\n  const effectiveInclude = eventMapping?.include ?? config.include;\n  if (effectiveInclude && effectiveInclude.length > 0) {\n    const includeData = flattenIncludeSections(event, effectiveInclude);\n    if (Object.keys(includeData).length > 0) {\n      // Include is the bottom layer - data wins on key conflict.\n      data = isObject(data)\n        ? (assign(\n            includeData,\n            data as Record<string, unknown>,\n          ) as unknown as WalkerOS.Property)\n        : (data ?? (includeData as unknown as WalkerOS.Property));\n    }\n  }\n\n  // Output layer: strip removed paths from the produced data. Applied last,\n  // after include, so remove always wins. Rooted at the produced payload.\n  if (eventMapping?.remove && isObject(data)) {\n    for (const path of eventMapping.remove) {\n      data = deleteByPath(data, path);\n    }\n  }\n\n  return {\n    event,\n    data,\n    mapping: eventMapping,\n    mappingKey,\n    ignore: false,\n    silent,\n  };\n}\n","import type { Mapping } from './types';\nimport { isObject } from './is';\nimport { clone } from './clone';\n\nfunction mergePatch(\n  target: Record<string, unknown>,\n  source: Record<string, unknown>,\n): Record<string, unknown> {\n  for (const key of Object.keys(source)) {\n    const val = source[key];\n    if (val === undefined) continue;\n    if (val === null) {\n      delete target[key];\n      continue;\n    }\n    const cur = target[key];\n    if (isObject(val) && isObject(cur)) {\n      mergePatch(cur, val);\n    } else {\n      target[key] = val;\n    }\n  }\n  return target;\n}\n\n/**\n * Resolve a user mapping rule against a package-shipped default rule.\n * - No extend/remove → replace (clone of override; today's behavior).\n * - extend → partial rule deep-merged onto base (null clears a field).\n * - remove → carried onto the merged rule for eval-time output stripping.\n * The returned rule never contains `extend`.\n */\nexport function mergeMappingRule(\n  base: Mapping.Rule,\n  override: Mapping.Rule,\n): Mapping.Rule {\n  if (override.extend === undefined && override.remove === undefined) {\n    return clone(override);\n  }\n  const merged: Record<string, unknown> = { ...clone(base) };\n  if (override.extend) {\n    const patch: Record<string, unknown> = { ...override.extend };\n    mergePatch(merged, patch);\n  }\n  delete merged.extend;\n  if (override.remove) merged.remove = [...override.remove];\n  else delete merged.remove;\n  return merged as Mapping.Rule;\n}\n","/**\n * Environment mocking utilities for walkerOS destinations\n *\n * Provides standardized tools for intercepting function calls in environment objects,\n * enabling consistent testing patterns across all destinations.\n */\n\ntype InterceptorFn = (\n  path: string[],\n  args: unknown[],\n  original?: Function,\n) => unknown;\n\n/**\n * Creates a proxied environment that intercepts function calls\n *\n * Uses Proxy to wrap environment objects and capture all function calls,\n * allowing for call recording, mocking, or simulation.\n *\n * @param env - The environment object to wrap\n * @param interceptor - Function called for each intercepted call\n * @returns Proxied environment with interceptor applied\n *\n * @example\n * ```typescript\n * const calls: Array<{ path: string[]; args: unknown[] }> = [];\n *\n * const testEnv = mockEnv(env.push, (path, args) => {\n *   calls.push({ path, args });\n * });\n *\n * // Use testEnv with destination\n * await destination.push(event, { env: testEnv });\n *\n * // Analyze captured calls\n * expect(calls).toContainEqual({\n *   path: ['window', 'gtag'],\n *   args: ['event', 'purchase', { value: 99.99 }]\n * });\n * ```\n */\nexport function mockEnv<T extends object>(\n  env: T,\n  interceptor: InterceptorFn,\n): T {\n  const createProxy = (obj: object, path: string[] = []): object => {\n    return new Proxy(obj, {\n      get(target, prop: string) {\n        const value = (target as Record<string, unknown>)[prop];\n        const currentPath = [...path, prop];\n\n        if (typeof value === 'function') {\n          // Preserve constructors (classes) so `new amp.Identify()` works\n          if (value.prototype && value.prototype.constructor === value) {\n            return value;\n          }\n          return (...args: unknown[]) => {\n            const result = interceptor(currentPath, args, value);\n            // If the function returns an object, proxy it so chained calls are intercepted\n            if (result && typeof result === 'object') {\n              return createProxy(result as object, currentPath);\n            }\n            // Fall back to calling the original and proxying its return if it's an object\n            const original = (value as Function)(...args);\n            if (original && typeof original === 'object') {\n              return createProxy(original as object, currentPath);\n            }\n            return result;\n          };\n        }\n\n        if (value && typeof value === 'object') {\n          return createProxy(value as object, currentPath);\n        }\n\n        return value;\n      },\n    });\n  };\n\n  return createProxy(env) as T;\n}\n\n/**\n * Traverses environment object and replaces values using a replacer function\n *\n * Alternative to mockEnv for environments where Proxy is not suitable.\n * Performs deep traversal and allows value transformation at each level.\n *\n * @param env - The environment object to traverse\n * @param replacer - Function to transform values during traversal\n * @returns New environment object with transformed values\n *\n * @example\n * ```typescript\n * const recordedCalls: APICall[] = [];\n *\n * const recordingEnv = traverseEnv(originalEnv, (value, path) => {\n *   if (typeof value === 'function') {\n *     return (...args: unknown[]) => {\n *       recordedCalls.push({\n *         path: path.join('.'),\n *         args: structuredClone(args)\n *       });\n *       return value(...args);\n *     };\n *   }\n *   return value;\n * });\n * ```\n */\nexport function traverseEnv<T extends object>(\n  env: T,\n  replacer: (value: unknown, path: string[]) => unknown,\n): T {\n  const traverse = (obj: unknown, path: string[] = []): unknown => {\n    if (!obj || typeof obj !== 'object') return obj;\n\n    const result: Record<string, unknown> | unknown[] = Array.isArray(obj)\n      ? []\n      : {};\n\n    for (const [key, value] of Object.entries(obj)) {\n      const currentPath = [...path, key];\n      if (Array.isArray(result)) {\n        result[Number(key)] = replacer(value, currentPath);\n      } else {\n        (result as Record<string, unknown>)[key] = replacer(value, currentPath);\n      }\n\n      if (value && typeof value === 'object' && typeof value !== 'function') {\n        if (Array.isArray(result)) {\n          result[Number(key)] = traverse(value, currentPath);\n        } else {\n          (result as Record<string, unknown>)[key] = traverse(\n            value,\n            currentPath,\n          );\n        }\n      }\n    }\n\n    return result;\n  };\n\n  return traverse(env) as T;\n}\n","import type { Instance } from './types/logger';\n\n/**\n * Mock logger instance for testing\n * Includes all logger methods as jest.fn() plus tracking of scoped loggers\n * Extends Instance to ensure type compatibility\n */\nexport interface MockLogger extends Instance {\n  error: jest.Mock;\n  warn: jest.Mock;\n  info: jest.Mock;\n  debug: jest.Mock;\n  throw: jest.Mock<never, [string | Error, unknown?]>;\n  json: jest.Mock;\n  scope: jest.Mock<MockLogger, [string]>;\n\n  /**\n   * Array of all scoped loggers created by this logger\n   * Useful for asserting on scoped logger calls in tests\n   */\n  scopedLoggers: MockLogger[];\n}\n\n/**\n * Create a mock logger for testing\n * All methods are jest.fn() that can be used for assertions\n *\n * @example\n * ```typescript\n * const mockLogger = createMockLogger();\n *\n * // Use in code under test\n * someFunction(mockLogger);\n *\n * // Assert on calls\n * expect(mockLogger.error).toHaveBeenCalledWith('error message');\n *\n * // Assert on scoped logger\n * const scoped = mockLogger.scopedLoggers[0];\n * expect(scoped.debug).toHaveBeenCalledWith('debug in scope');\n * ```\n */\nexport function createMockLogger(): MockLogger {\n  const scopedLoggers: MockLogger[] = [];\n\n  const mockThrow = jest.fn((message: string | Error): never => {\n    const msg = message instanceof Error ? message.message : message;\n    throw new Error(msg);\n  }) as jest.Mock<never, [string | Error, unknown?]>;\n\n  const mockScope = jest.fn((_name: string): MockLogger => {\n    const scoped = createMockLogger();\n    scopedLoggers.push(scoped);\n    return scoped;\n  }) as jest.Mock<MockLogger, [string]>;\n\n  const mockLogger: MockLogger = {\n    error: jest.fn(),\n    warn: jest.fn(),\n    info: jest.fn(),\n    debug: jest.fn(),\n    throw: mockThrow,\n    json: jest.fn(),\n    scope: mockScope,\n    scopedLoggers,\n  };\n\n  return mockLogger;\n}\n","import type { Collector, Transformer, Destination, Ingest } from './types';\nimport { createIngest } from './types/ingest';\nimport { createMockLogger } from './mockLogger';\n\n/**\n * Create a mock context for testing transformers and destinations.\n *\n * Provides sensible defaults for all required fields. Override only\n * what the test cares about. When context signatures change, only\n * this factory needs updating — not every test file.\n *\n * @example\n * ```typescript\n * // Transformer test — only specify config\n * const ctx = createMockContext({ config: { settings: { strict: true } } });\n * const result = await transformer.push(event, ctx);\n *\n * // Destination test — specify config and custom env\n * const ctx = createMockContext({ config: { settings: { url } }, env: { sendWeb } });\n * await destination.push(event, ctx);\n *\n * // With custom ingest data\n * const ctx = createMockContext({ ingest: { ...createIngest('test'), path: '/api' } });\n * ```\n */\nexport function createMockContext<\n  T extends Transformer.TypesGeneric = Transformer.Types,\n>(\n  overrides: Partial<\n    Omit<Transformer.Context<T>, 'config' | 'ingest'> & {\n      config?: Transformer.Config<T> | Destination.Config<Destination.TypesGeneric>;\n      ingest?: Ingest | (Record<string, unknown> & { _meta: Ingest['_meta'] });\n      data?: unknown;\n      rule?: unknown;\n    }\n  > = {},\n): Transformer.Context<T> & Destination.PushContext<Destination.TypesGeneric> {\n  return {\n    collector: {} as Collector.Instance,\n    config: {} as Transformer.Config<T>,\n    env: {} as Transformer.Env<T>,\n    logger: createMockLogger(),\n    id: 'test',\n    ingest: createIngest('test'),\n    ...overrides,\n  } as Transformer.Context<T> & Destination.PushContext<Destination.TypesGeneric>;\n}\n","import type { WalkerOS } from './types';\nimport { tryCatch } from './tryCatch';\nimport { castValue } from './castValue';\nimport { isArray, isObject } from './is';\n\n/**\n * Converts a request string to a data object.\n *\n * @param parameter The request string to convert.\n * @returns The data object or undefined.\n */\nexport function requestToData(\n  parameter: unknown,\n): WalkerOS.AnyObject | undefined {\n  const str = String(parameter);\n  const queryString = str.split('?')[1] || str;\n\n  return tryCatch(() => {\n    const params = new URLSearchParams(queryString);\n    const result: WalkerOS.AnyObject = {};\n\n    params.forEach((value, key) => {\n      const keys = key.split(/[[\\]]+/).filter(Boolean);\n      let current: unknown = result;\n\n      keys.forEach((k, i) => {\n        const isLast = i === keys.length - 1;\n\n        if (isArray(current)) {\n          const index = parseInt(k, 10);\n          if (isLast) {\n            (current as Array<unknown>)[index] = castValue(value);\n          } else {\n            (current as Array<unknown>)[index] =\n              (current as Array<unknown>)[index] ||\n              (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n            current = (current as Array<unknown>)[index];\n          }\n        } else if (isObject(current)) {\n          if (isLast) {\n            (current as WalkerOS.AnyObject)[k] = castValue(value);\n          } else {\n            (current as WalkerOS.AnyObject)[k] =\n              (current as WalkerOS.AnyObject)[k] ||\n              (isNaN(parseInt(keys[i + 1], 10)) ? {} : []);\n            current = (current as WalkerOS.AnyObject)[k];\n          }\n        }\n      });\n    });\n\n    return result;\n  })();\n}\n\n/**\n * Converts a data object to a request string.\n *\n * @param data The data object to convert.\n * @returns The request string.\n */\nexport function requestToParameter(\n  data: WalkerOS.AnyObject | WalkerOS.PropertyType,\n): string {\n  if (!data) return '';\n\n  const params: string[] = [];\n  const encode = encodeURIComponent;\n\n  function addParam(key: string, value: unknown) {\n    if (value === undefined || value === null) return;\n\n    if (isArray(value)) {\n      value.forEach((item, index) => addParam(`${key}[${index}]`, item));\n    } else if (isObject(value)) {\n      Object.entries(value).forEach(([subKey, subValue]) =>\n        addParam(`${key}[${subKey}]`, subValue),\n      );\n    } else {\n      params.push(`${encode(key)}=${encode(String(value))}`);\n    }\n  }\n\n  if (typeof data === 'object') {\n    Object.entries(data).forEach(([key, value]) => addParam(key, value));\n  } else {\n    return encode(data);\n  }\n\n  return params.join('&');\n}\n","import type { SendDataValue, SendHeaders } from './types/send';\nimport { isSameType } from './is';\nimport { assign } from './assign';\n\nexport type { SendDataValue, SendHeaders, SendResponse } from './types/send';\n\n/**\n * Transforms data to a string.\n *\n * @param data The data to transform.\n * @returns The transformed data.\n */\nexport function transformData(data?: SendDataValue): string | undefined {\n  if (data === undefined) return data;\n\n  return isSameType(data, '' as string) ? data : JSON.stringify(data);\n}\n\n/**\n * Gets the headers for a request.\n *\n * @param headers The headers to merge with the default headers.\n * @returns The merged headers.\n */\nexport function getHeaders(headers: SendHeaders = {}): SendHeaders {\n  return assign(\n    {\n      'Content-Type': 'application/json; charset=utf-8',\n    },\n    headers,\n  );\n}\n","// packages/core/src/setup.ts\n\n/**\n * Normalize `config.setup` into a concrete options object, or null when disabled.\n *\n * - `false` / `undefined` → null (no setup)\n * - `true` → `defaults` as-is\n * - object → shallow merge of defaults and overrides (overrides win)\n */\nexport function resolveSetup<T extends object>(\n  value: boolean | T | undefined,\n  defaults: T,\n): T | null {\n  if (value === false || value === undefined) return null;\n  if (value === true) return defaults;\n  return { ...defaults, ...value };\n}\n","/**\n * Trims quotes and whitespaces from a string.\n *\n * @param str The string to trim.\n * @returns The trimmed string.\n */\nexport function trim(str: string): string {\n  // Remove quotes and whitespaces\n  return str ? str.trim().replace(/^'|'$/g, '').trim() : '';\n}\n","import type { Hooks, Logger } from './types';\n\n/**\n * A utility function that wraps a function with hooks.\n *\n * Pre/post hooks are user-supplied and may throw. A throwing hook must not\n * crash the surrounding pipeline. On failure, fall back to calling the\n * original function (pre-hook) or keep the original result (post-hook).\n *\n * The generic `F` preserves the exact call shape of `fn`, including named\n * parameters and overloaded interfaces, so call sites can assign the result\n * to the same interface slot without a cast.\n *\n * @template F The exact function type being wrapped.\n * @param fn The function to wrap.\n * @param name The name of the function.\n * @param hooks The hooks to use.\n * @param logger Optional logger for hook failure warnings. Falls back to\n *   `console.warn` when not provided.\n * @returns The wrapped function with the same call shape as `fn`.\n */\nexport function useHooks<F extends Hooks.AnyFunction>(\n  fn: F,\n  name: string,\n  hooks: Hooks.Functions,\n  logger?: Logger.Instance,\n): F {\n  // Re-anchor `fn` to its structural call shape. The generic constraint\n  // `Hooks.AnyFunction` widens calls to `unknown`, so a locally-typed alias\n  // restores precise argument and return types inside the closure. Same\n  // bridging concern as the two hook-lookup casts below.\n  const inner = fn as (...args: Parameters<F>) => ReturnType<F>;\n  const wrapped = function (this: unknown, ...args: Parameters<F>) {\n    let result: ReturnType<F>;\n    const preHook = ('pre' + name) as keyof Hooks.Functions;\n    const postHook = ('post' + name) as keyof Hooks.Functions;\n    const preHookFn = hooks[preHook] as unknown as Hooks.HookFn<typeof inner>;\n    const postHookFn = hooks[postHook] as unknown as Hooks.HookFn<typeof inner>;\n\n    const warn = (message: string, error: unknown) => {\n      if (logger) {\n        logger.warn(message, { error });\n      } else {\n        console.warn(message, error);\n      }\n    };\n\n    if (preHookFn) {\n      try {\n        result = preHookFn({ fn: inner }, ...args);\n      } catch (error) {\n        warn(\n          `Hook ${String(preHook)} failed, falling back to original function`,\n          error,\n        );\n        result = inner(...args);\n      }\n    } else {\n      result = inner(...args);\n    }\n\n    if (postHookFn) {\n      try {\n        result = postHookFn({ fn: inner, result }, ...args);\n      } catch (error) {\n        warn(`Hook ${String(postHook)} failed, keeping original result`, error);\n      }\n    }\n\n    return result;\n  };\n  return wrapped as F;\n}\n","import type { FlowState } from './types/telemetry';\nimport type { ObserverFn } from './types/observer';\n\n/**\n * Telemetry level. Off disables emission entirely. Standard projects\n * structural state without inEvent or outEvent payloads (unless explicitly\n * opted in). Trace emits full payloads on every hop.\n */\nexport type TelemetryLevel = 'off' | 'standard' | 'trace';\n\n/**\n * Options that shape the telemetry projection strategy. Defaults are chosen\n * so a caller can pass `{ flowId }` and get sensible behavior.\n */\nexport interface TelemetryOptions {\n  /** Required flow identifier; observers may use this for cross-flow correlation. */\n  flowId: string;\n  /** Verbosity. Defaults to 'standard'. */\n  level?: TelemetryLevel;\n  /** Force-include the inbound event regardless of level. */\n  includeIn?: boolean;\n  /** Force-include the outbound event regardless of level. */\n  includeOut?: boolean;\n  /** Force-include the matched mapping key (only meaningful for transformers/destinations). */\n  includeMappingKey?: boolean;\n  /**\n   * Fraction of events to emit, between 0 and 1. Deterministic by eventId:\n   * the same eventId always falls on the same side of the threshold so\n   * paired in/out states either both emit or both drop.\n   */\n  sample?: number;\n}\n\nexport type EmitFn = (state: FlowState) => void;\n\n/**\n * Optional supplier form. When passed instead of static `TelemetryOptions`,\n * the observer evaluates the supplier on every emit so toggle-style runtime\n * overrides (e.g. `WALKEROS_TRACE_UNTIL`) reach the projection without\n * rebuilding the observer.\n */\nexport type TelemetryOptionsSupplier = () => TelemetryOptions | null;\n\n/**\n * Deterministic 32-bit FNV-1a hash of a string. Used for sampling so\n * identical eventIds always map to the same numeric bucket.\n */\nfunction fnv1a(input: string): number {\n  let hash = 0x811c9dc5;\n  for (let i = 0; i < input.length; i++) {\n    hash ^= input.charCodeAt(i);\n    hash =\n      (hash +\n        ((hash << 1) +\n          (hash << 4) +\n          (hash << 7) +\n          (hash << 8) +\n          (hash << 24))) >>>\n      0;\n  }\n  return hash >>> 0;\n}\n\n/**\n * Returns true when the eventId passes the sample gate. Sample of 1 always\n * passes; sample of 0 always fails. Anything in between buckets the eventId\n * deterministically so the in/out pair is consistent.\n */\nfunction passesSample(eventId: string, sample: number): boolean {\n  if (sample >= 1) return true;\n  if (sample <= 0) return false;\n  const hashed = fnv1a(eventId);\n  const ratio = hashed / 0xffffffff;\n  return ratio < sample;\n}\n\n/**\n * Build a telemetry observer that projects FlowState records according to\n * level/sample/include flags and forwards them to `emit`. The observer is\n * synchronous, never throws (a throwing emit is swallowed), and does no\n * IO of its own. Designed to be added to `collector.observers` so the\n * runtime self-emission loop drives it.\n *\n * Accepts either a static `TelemetryOptions` value or a supplier\n * `() => TelemetryOptions | null`. With a supplier, every emit reads the\n * current opts so toggles such as `WALKEROS_TRACE_UNTIL` reach the\n * projection without rebuilding the observer. A supplier returning `null`\n * suppresses the emit (telemetry off).\n */\nexport function createTelemetryObserver(\n  emit: EmitFn,\n  optsOrSupplier: TelemetryOptions | TelemetryOptionsSupplier,\n): ObserverFn {\n  const supply: TelemetryOptionsSupplier =\n    typeof optsOrSupplier === 'function'\n      ? optsOrSupplier\n      : () => optsOrSupplier;\n\n  return function project(state: FlowState): void {\n    const opts = supply();\n    if (!opts) return;\n\n    const level: TelemetryLevel = opts.level ?? 'standard';\n    if (level === 'off') return;\n\n    const rawSample = opts.sample;\n    const sample =\n      typeof rawSample === 'number' && Number.isFinite(rawSample)\n        ? rawSample\n        : 1;\n    if (state.eventId && !passesSample(state.eventId, sample)) return;\n\n    const includeIn = opts.includeIn ?? level === 'trace';\n    const includeOut = opts.includeOut ?? level === 'trace';\n    const includeMappingKey = opts.includeMappingKey ?? level === 'trace';\n\n    const projected: FlowState = { ...state };\n    if (!includeIn) delete projected.inEvent;\n    if (!includeOut) delete projected.outEvent;\n    if (!includeMappingKey) delete projected.mappingKey;\n\n    // Error message truncation: limit to 256 chars outside trace so stack\n    // fragments or echoed payloads do not leak verbosely. Trace keeps the\n    // full message.\n    if (\n      level !== 'trace' &&\n      projected.error?.message &&\n      projected.error.message.length > 256\n    ) {\n      projected.error = {\n        ...projected.error,\n        message: projected.error.message.slice(0, 256) + '…',\n      };\n    }\n\n    try {\n      emit(projected);\n    } catch {\n      // Downstream emit must not crash the pipeline. Logging would itself\n      // be observer-shaped, so swallow defensively.\n    }\n  };\n}\n\n/**\n * Convenience export: the internal sampling predicate so callers (and\n * tests) can verify the deterministic bucketing without importing the\n * private FNV-1a helper.\n */\nexport function isSampled(eventId: string, sample: number): boolean {\n  return passesSample(eventId, sample);\n}\n","/**\n * Runtime telemetry resolver.\n *\n * Converts a flow-side `Flow.Config.observe` block plus a runtime `traceUntil`\n * override into a concrete `TelemetryOptions` the collector hooks installer can\n * consume. Pure function of its inputs: it reads no environment.\n *\n * Resolution order (highest priority first):\n *   1. `traceUntil`, if a string that parses to a future ISO timestamp ->\n *      force level=trace, sample=1, include in/out payloads.\n *   2. The `observe` block.\n *   3. A tier default of `{ level: 'standard' }`.\n *\n * The `traceUntil` value can flip between emits, so trace turns on and off as\n * the timestamp comes and goes. The platform-specific caller owns the value\n * and supplies it per emit.\n */\nimport type { TelemetryLevel, TelemetryOptions } from './telemetry';\n\ninterface ResolveTelemetryInput {\n  flowId: string;\n  /** From `flow.config?.observe`. May be undefined. */\n  observe?: { level?: 'off' | 'standard' | 'trace'; sample?: number };\n  /** Runtime trace override. ISO timestamp parsing to a future time forces trace. */\n  traceUntil?: string | null;\n  /** Clock seam for tests. Defaults to `Date.now()`. */\n  now?: () => number;\n}\n\n/**\n * Returns `TelemetryOptions` ready to pass to `createTelemetryObserver`,\n * or `null` if telemetry is disabled (`level === 'off'` with no trace\n * override). Callers should skip observer installation when this returns\n * null.\n */\nexport function resolveTelemetryOptions(\n  input: ResolveTelemetryInput,\n): TelemetryOptions | null {\n  const now = input.now ?? (() => Date.now());\n\n  const { traceUntil } = input;\n  if (typeof traceUntil === 'string' && traceUntil.length > 0) {\n    const parsed = Date.parse(traceUntil);\n    if (!Number.isNaN(parsed) && parsed > now()) {\n      return {\n        flowId: input.flowId,\n        level: 'trace',\n        includeIn: true,\n        includeOut: true,\n        sample: 1,\n      };\n    }\n  }\n\n  const level: TelemetryLevel = input.observe?.level ?? 'standard';\n  if (level === 'off') return null;\n\n  const sample = input.observe?.sample ?? 1;\n  return {\n    flowId: input.flowId,\n    level,\n    sample,\n  };\n}\n","/**\n * Shared server-runtime holder for the active `traceUntil` value.\n *\n * The server trace-poller writes via `setTraceUntil`; the per-emit telemetry\n * supplier reads via `getTraceUntil` and passes the result to\n * `resolveTelemetryOptions`. The browser bundle does NOT use this module: it\n * keeps its own `traceUntil` variable inside its IIFE. Only\n * `resolveTelemetryOptions` is shared across platforms.\n */\nlet value: string | null = null;\n\nexport function getTraceUntil(): string | null {\n  return value;\n}\n\nexport function setTraceUntil(v: string | null): void {\n  value = v;\n}\n","import type { Collector } from './types';\nimport type { FlowState } from './types/telemetry';\n\n/**\n * Synchronously fans out a FlowState record to every registered observer\n * on the collector. Each call is wrapped in try/catch so a misbehaving\n * observer cannot crash the runtime; observers are advisory and must not\n * affect pipeline outcomes.\n *\n * Iterates a snapshot of the observer set so an observer adding or removing\n * another observer during the emit does not re-enter or skip in the same\n * pass. The early return on an empty set keeps the zero-observer hot path\n * allocation-free.\n */\nexport function emitStep(\n  collector: Collector.Instance,\n  state: FlowState,\n): void {\n  if (collector.observers.size === 0) return;\n  const snapshot = Array.from(collector.observers);\n  for (const observer of snapshot) {\n    try {\n      observer(state);\n    } catch {\n      // Observers must never crash the pipeline.\n    }\n  }\n}\n","/**\n * Batched FlowState poster.\n *\n * Buffers FlowState records and flushes them to an HTTP endpoint either when\n * `batchMs` elapses since the first queued record, or when `batchSize` is\n * reached. Returns the emit callback that `createTelemetryObserver` consumes.\n *\n * Errors from the underlying fetch are swallowed (or routed through the\n * optional `onError` callback) so a transient observer outage cannot crash\n * the runtime.\n *\n * Uses the global `fetch` so the same primitive works in Node 18+, browsers,\n * and Edge runtimes. Tests may inject a stub via `opts.fetch`.\n */\nimport type { FlowState } from './types/telemetry';\n\n/**\n * Minimum HTTP response surface the poster touches. Anything that exposes\n * `ok` and `status` works. Decoupling from the DOM `Response` type lets the\n * helper run in Edge, browser, and Node-only test environments without\n * requiring `lib: dom` or a polyfill.\n */\nexport interface PosterResponse {\n  ok: boolean;\n  status: number;\n}\n\n/**\n * Minimum fetch surface the poster needs. A subset of `typeof fetch` that\n * lets test harnesses pass a plain async function without dragging in the\n * Response/Request DOM types.\n */\nexport type PosterFetch = (\n  url: string,\n  init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<PosterResponse>;\n\nexport interface BatchedPosterOptions {\n  /** Absolute HTTP endpoint URL. POST with JSON array body. */\n  url: string;\n  /** Bearer token sent in the `Authorization` header. */\n  token: string;\n  /** Max time to wait before flushing the current batch. Default 50 ms. */\n  batchMs?: number;\n  /** Max records per batch. When reached, flushes immediately. Default 50. */\n  batchSize?: number;\n  /** Test seam. Defaults to the global `fetch`. */\n  fetch?: PosterFetch;\n  /** Called when the underlying POST rejects. Defaults to swallowing. */\n  onError?: (err: unknown) => void;\n}\n\n/**\n * Build a batched emit callback. The returned function is synchronous, never\n * throws, and schedules an async flush in the background.\n *\n * Concurrency model: a single in-memory buffer plus a single pending timer.\n * When the timer fires (or `batchSize` is hit) the buffer is moved into a\n * local variable and reset, then POSTed. New records arriving during the in-\n * flight POST land in the next batch.\n */\nexport function createBatchedPoster(\n  opts: BatchedPosterOptions,\n): (state: FlowState) => void {\n  // Narrow before use: nullish coalescing alone lets NaN, Infinity, 0, and\n  // negatives through, all of which break setTimeout or starve the flush.\n  // A garbage value falls back to the documented default rather than\n  // clamping to the smallest legal step.\n  const rawBatchMs = opts.batchMs;\n  const batchMs =\n    typeof rawBatchMs === 'number' &&\n    Number.isFinite(rawBatchMs) &&\n    rawBatchMs > 0\n      ? Math.floor(rawBatchMs)\n      : 50;\n\n  const rawBatchSize = opts.batchSize;\n  const batchSize =\n    typeof rawBatchSize === 'number' &&\n    Number.isFinite(rawBatchSize) &&\n    rawBatchSize >= 1\n      ? Math.floor(rawBatchSize)\n      : 50;\n  // Lazy lookup of the global `fetch` so the helper imports cleanly even in\n  // environments without one (it only fails when actually used). The cast\n  // is to the narrowed PosterFetch surface, not to a broader type.\n  const fetchImpl: PosterFetch =\n    opts.fetch ?? ((url, init) => (globalThis.fetch as PosterFetch)(url, init));\n  const onError =\n    opts.onError ??\n    (() => {\n      // swallow\n    });\n\n  let buffer: FlowState[] = [];\n  let timer: ReturnType<typeof setTimeout> | null = null;\n\n  function flush(): void {\n    if (buffer.length === 0) return;\n    const body = buffer;\n    buffer = [];\n    if (timer) {\n      clearTimeout(timer);\n      timer = null;\n    }\n    // Fire-and-forget. We deliberately do not await; the emit caller is\n    // synchronous and a slow observer must not block the pipeline.\n    Promise.resolve()\n      .then(() =>\n        fetchImpl(opts.url, {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${opts.token}`,\n          },\n          body: JSON.stringify(body),\n        }),\n      )\n      .then((res) => {\n        // 4xx/5xx is not an exception per fetch contract. Surface non-2xx\n        // through onError so callers can record telemetry-of-telemetry,\n        // but never throw out of this helper.\n        if (res && typeof res === 'object' && 'ok' in res && !res.ok) {\n          onError(new Error(`Observer responded ${res.status}`));\n        }\n      })\n      .catch((err) => {\n        onError(err);\n      });\n  }\n\n  return (state: FlowState): void => {\n    buffer.push(state);\n    if (buffer.length >= batchSize) {\n      flush();\n      return;\n    }\n    if (timer === null) {\n      timer = setTimeout(flush, batchMs);\n    }\n  };\n}\n","import type { WalkerOS } from './types';\n\n/**\n * Parses a user agent string to extract browser, OS, and device information.\n *\n * @param userAgent The user agent string to parse.\n * @returns An object containing the parsed user agent information.\n */\nexport function parseUserAgent(userAgent?: string): WalkerOS.User {\n  if (!userAgent) return {};\n\n  return {\n    userAgent,\n    browser: getBrowser(userAgent),\n    browserVersion: getBrowserVersion(userAgent),\n    os: getOS(userAgent),\n    osVersion: getOSVersion(userAgent),\n    deviceType: getDeviceType(userAgent),\n  };\n}\n\n/**\n * Gets the browser name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser name or undefined.\n */\nexport function getBrowser(userAgent: string): string | undefined {\n  const browsers = [\n    { name: 'Edge', substr: 'Edg' },\n    { name: 'Chrome', substr: 'Chrome' },\n    { name: 'Safari', substr: 'Safari', exclude: 'Chrome' },\n    { name: 'Firefox', substr: 'Firefox' },\n    { name: 'IE', substr: 'MSIE' },\n    { name: 'IE', substr: 'Trident' },\n  ];\n\n  for (const browser of browsers) {\n    if (\n      userAgent.includes(browser.substr) &&\n      (!browser.exclude || !userAgent.includes(browser.exclude))\n    ) {\n      return browser.name;\n    }\n  }\n\n  return;\n}\n\n/**\n * Gets the browser version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The browser version or undefined.\n */\nexport function getBrowserVersion(userAgent: string): string | undefined {\n  const rules = [\n    /Edg\\/([0-9]+)/, // Edge\n    /Chrome\\/([0-9]+)/, // Chrome\n    /Version\\/([0-9]+).*Safari/, // Safari\n    /Firefox\\/([0-9]+)/, // Firefox\n    /MSIE ([0-9]+)/, // IE 10 and older\n    /rv:([0-9]+).*Trident/, // IE 11\n  ];\n\n  for (const regex of rules) {\n    const match = userAgent.match(regex);\n    if (match) {\n      return match[1];\n    }\n  }\n\n  return;\n}\n\n/**\n * Gets the OS name from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS name or undefined.\n */\nexport function getOS(userAgent: string): string | undefined {\n  const osList = [\n    { name: 'Windows', substr: 'Windows NT' },\n    { name: 'macOS', substr: 'Mac OS X' },\n    { name: 'Android', substr: 'Android' },\n    { name: 'iOS', substr: 'iPhone OS' },\n    { name: 'Linux', substr: 'Linux' },\n  ];\n\n  for (const os of osList) {\n    if (userAgent.includes(os.substr)) {\n      return os.name;\n    }\n  }\n\n  return;\n}\n\n/**\n * Gets the OS version from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The OS version or undefined.\n */\nexport function getOSVersion(userAgent: string): string | undefined {\n  const osVersionRegex = /(?:Windows NT|Mac OS X|Android|iPhone OS) ([0-9._]+)/;\n  const match = userAgent.match(osVersionRegex);\n  return match ? match[1].replace(/_/g, '.') : undefined;\n}\n\n/**\n * Gets the device type from a user agent string.\n *\n * @param userAgent The user agent string.\n * @returns The device type or undefined.\n */\nexport function getDeviceType(userAgent: string): string | undefined {\n  let deviceType = 'Desktop';\n\n  if (/Tablet|iPad/i.test(userAgent)) {\n    deviceType = 'Tablet';\n  } else if (\n    /Mobi|Android|iPhone|iPod|BlackBerry|Opera Mini|IEMobile|WPDesktop/i.test(\n      userAgent,\n    )\n  ) {\n    deviceType = 'Mobile';\n  }\n\n  return deviceType;\n}\n","/**\n * Inline Code Wrapping Utilities\n *\n * Converts inline code strings to executable functions for the three mapping\n * callbacks: condition, fn, validate. All three share a single signature:\n *\n *   (value, context) => result\n *\n * Inside the inline body, the available bindings are:\n *   - value:    unknown - the value being mapped/validated/checked\n *   - context:  Mapping.Context with these fields:\n *       event:     WalkerOS.DeepPartialEvent\n *       mapping:   Mapping.Value | Mapping.Rule\n *       collector: Collector.Instance\n *       logger:    Logger.Instance\n *       consent?:  WalkerOS.Consent\n *\n * If the body has no explicit `return`, it is auto-wrapped with `return`.\n *\n * @packageDocumentation\n */\n\nimport type { Mapping } from './types';\n\nfunction hasReturn(code: string): boolean {\n  return /\\breturn\\b/.test(code);\n}\n\nfunction wrapCode(code: string): string {\n  return hasReturn(code) ? code : `return ${code}`;\n}\n\n/**\n * Wrap inline code as a Mapping.Condition.\n *\n * @example\n * ```ts\n * const c = wrapCondition('context.consent?.marketing === true');\n * c(value, context); // boolean\n * ```\n */\nexport function wrapCondition(code: string): Mapping.Condition {\n  const body = wrapCode(code);\n  // eslint-disable-next-line @typescript-eslint/no-implied-eval\n  return new Function('value', 'context', body) as Mapping.Condition;\n}\n\n/**\n * Wrap inline code as a Mapping.Fn.\n *\n * @example\n * ```ts\n * const fn = wrapFn('value.user.email.split(\"@\")[1]');\n * fn(value, context); // domain\n * ```\n */\nexport function wrapFn(code: string): Mapping.Fn {\n  const body = wrapCode(code);\n  // eslint-disable-next-line @typescript-eslint/no-implied-eval\n  return new Function('value', 'context', body) as Mapping.Fn;\n}\n\n/**\n * Wrap inline code as a Mapping.Validate.\n *\n * @example\n * ```ts\n * const v = wrapValidate('typeof value === \"string\" && value.length > 0');\n * v(value, context); // boolean\n * ```\n */\nexport function wrapValidate(code: string): Mapping.Validate {\n  const body = wrapCode(code);\n  // eslint-disable-next-line @typescript-eslint/no-implied-eval\n  return new Function('value', 'context', body) as Mapping.Validate;\n}\n","const JSDELIVR_BASE = 'https://cdn.jsdelivr.net/npm';\nconst DEFAULT_SCHEMA_PATH = 'dist/walkerOS.json';\n\nfunction parsePlatform(value: unknown): string | string[] | undefined {\n  if (typeof value === 'string') return value;\n  if (Array.isArray(value) && value.every((v) => typeof v === 'string'))\n    return value as string[];\n  return undefined;\n}\n\nexport interface ExampleSummary {\n  name: string;\n  description?: string;\n}\n\nexport interface WalkerOSPackageMeta {\n  packageName: string;\n  version: string;\n  description?: string;\n  type?: string;\n  platform?: string | string[];\n}\n\nexport interface WalkerOSPackageInfo {\n  packageName: string;\n  version: string;\n  type?: string;\n  platform?: string | string[];\n  schemas: Record<string, unknown>;\n  examples: Record<string, unknown>;\n  hints?: Record<string, unknown>;\n}\n\nexport interface WalkerOSPackage extends WalkerOSPackageInfo {\n  description?: string;\n  docs?: string;\n  source?: string;\n  hintKeys: string[];\n  exampleSummaries: ExampleSummary[];\n}\n\n/**\n * Local mirror of the app's `PackageDetailResult` shape for `expand=all`\n * responses. Decoupled from the app intentionally — `core` does not import\n * from `app`. Only the fields read by `shapeFromDetail` are typed.\n */\ninterface UnifiedPackageResponse {\n  package: string;\n  version: string;\n  description?: string;\n  type?: string;\n  platform?: string[];\n  docs?: string;\n  source?: string;\n  schemas?: Record<string, unknown>;\n  hints?: Record<string, unknown>;\n  hintKeys?: string[];\n  exampleSummaries?: ExampleSummary[];\n  examples?: Record<string, unknown>;\n}\n\nexport async function fetchPackage(\n  packageName: string,\n  options?: {\n    version?: string;\n    timeout?: number;\n    baseUrl?: string;\n    client?: string;\n  },\n): Promise<WalkerOSPackage> {\n  const ver = options?.version || 'latest';\n  const timeoutMs = options?.timeout || 10000;\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n  const signal = controller.signal;\n  const headers = options?.client\n    ? { 'X-Walkeros-Client': options.client }\n    : undefined;\n\n  try {\n    if (options?.baseUrl) {\n      // Single round-trip via the unified detail endpoint\n      // (`expand=all` returns hints + examples in one shot).\n      const url = `${options.baseUrl}/api/packages/${encodeURIComponent(packageName)}?version=${encodeURIComponent(ver)}&expand=all`;\n      const res = await fetch(url, { signal, ...(headers && { headers }) });\n      if (!res.ok)\n        throw new Error(`Failed to fetch ${url} (HTTP ${res.status})`);\n      const detail = (await res.json()) as UnifiedPackageResponse;\n      return shapeFromDetail(packageName, ver, detail);\n    }\n\n    // Direct jsdelivr fallback (offline-safe path) — keep two-fetch.\n    const base = `${JSDELIVR_BASE}/${packageName}@${ver}`;\n    const pkg = await fetchJson(`${base}/package.json`, signal, headers);\n    const walkerOSJson = await fetchJson(\n      `${base}/${DEFAULT_SCHEMA_PATH}`,\n      signal,\n      headers,\n    );\n    return parsePackage(packageName, ver, pkg, walkerOSJson);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\nfunction shapeFromDetail(\n  packageName: string,\n  ver: string,\n  detail: UnifiedPackageResponse,\n): WalkerOSPackage {\n  const schemas = (detail.schemas as Record<string, unknown> | undefined) || {};\n  const examples =\n    (detail.examples as Record<string, unknown> | undefined) || {};\n  const hints = detail.hints;\n  const hintKeys = detail.hintKeys ?? (hints ? Object.keys(hints) : []);\n  const exampleSummaries = detail.exampleSummaries ?? [];\n  const platform = detail.platform;\n\n  return {\n    packageName: detail.package || packageName,\n    version: typeof detail.version === 'string' ? detail.version : ver,\n    ...(detail.description !== undefined && {\n      description: detail.description,\n    }),\n    ...(detail.type !== undefined && { type: detail.type }),\n    ...(platform !== undefined && { platform }),\n    schemas,\n    examples,\n    ...(detail.docs !== undefined && { docs: detail.docs }),\n    ...(detail.source !== undefined && { source: detail.source }),\n    ...(hints && Object.keys(hints).length > 0 ? { hints } : {}),\n    hintKeys,\n    exampleSummaries,\n  };\n}\n\nasync function fetchJson(\n  url: string,\n  signal: AbortSignal,\n  headers?: Record<string, string>,\n): Promise<Record<string, unknown>> {\n  const res = await fetch(url, { signal, ...(headers && { headers }) });\n  if (!res.ok) throw new Error(`Failed to fetch ${url} (HTTP ${res.status})`);\n  return (await res.json()) as Record<string, unknown>;\n}\n\nfunction parsePackage(\n  packageName: string,\n  ver: string,\n  pkg: Record<string, unknown>,\n  walkerOSJson: Record<string, unknown>,\n): WalkerOSPackage {\n  const meta = (walkerOSJson.$meta as Record<string, unknown>) || {};\n  const schemas = (walkerOSJson.schemas as Record<string, unknown>) || {};\n  const examples = (walkerOSJson.examples as Record<string, unknown>) || {};\n  const hints = walkerOSJson.hints as Record<string, unknown> | undefined;\n  const hintKeys = hints ? Object.keys(hints) : [];\n\n  const exampleSummaries: ExampleSummary[] = [];\n  const stepExamples = (examples.step || {}) as Record<string, unknown>;\n  for (const [name, example] of Object.entries(stepExamples)) {\n    const ex = example as Record<string, unknown> | undefined;\n    const summary: ExampleSummary = { name };\n    if (typeof ex?.description === 'string')\n      summary.description = ex.description;\n    exampleSummaries.push(summary);\n  }\n\n  const docs = typeof meta.docs === 'string' ? meta.docs : undefined;\n  const source = typeof meta.source === 'string' ? meta.source : undefined;\n\n  return {\n    packageName,\n    version: typeof pkg.version === 'string' ? pkg.version : ver,\n    description:\n      typeof pkg.description === 'string' ? pkg.description : undefined,\n    type: typeof meta.type === 'string' ? meta.type : undefined,\n    platform: parsePlatform(meta.platform),\n    schemas,\n    examples,\n    ...(docs ? { docs } : {}),\n    ...(source ? { source } : {}),\n    ...(hints && Object.keys(hints).length > 0 ? { hints } : {}),\n    hintKeys,\n    exampleSummaries,\n  };\n}\n\n/**\n * @deprecated Use fetchPackage instead.\n * Still used by: entry.ts (validator), package-schemas.ts (MCP resource).\n */\nexport async function fetchPackageSchema(\n  packageName: string,\n  options?: {\n    version?: string;\n    timeout?: number;\n    baseUrl?: string;\n    client?: string;\n  },\n): Promise<WalkerOSPackageInfo> {\n  const pkg = await fetchPackage(packageName, options);\n  return {\n    packageName: pkg.packageName,\n    version: pkg.version,\n    type: pkg.type,\n    platform: pkg.platform,\n    schemas: pkg.schemas,\n    examples: pkg.examples,\n    ...(pkg.hints ? { hints: pkg.hints } : {}),\n  };\n}\n","export function mcpResult(\n  result: unknown,\n  hints?: { next?: string[]; warnings?: string[] },\n) {\n  const enriched = hints\n    ? { ...(result as Record<string, unknown>), _hints: hints }\n    : result;\n  return {\n    content: [\n      {\n        type: 'text' as const,\n        text: JSON.stringify(enriched, null, 2),\n      },\n    ],\n    structuredContent: enriched as Record<string, unknown>,\n  };\n}\n\nexport function mcpError(error: unknown, hint?: string) {\n  let message: string;\n  let path: string | undefined;\n  let code: string | undefined;\n  let details: unknown[] | undefined;\n\n  if (error instanceof Error) {\n    message = error.message;\n    // Detect ApiError (has code and/or details properties)\n    const err = error as Error & { code?: string; details?: unknown[] };\n    if (err.code) code = err.code;\n    if (Array.isArray(err.details)) details = err.details;\n  } else if (typeof error === 'string') {\n    message = error;\n  } else if (\n    error &&\n    typeof error === 'object' &&\n    'issues' in error &&\n    Array.isArray((error as { issues: unknown[] }).issues)\n  ) {\n    const issues = (\n      error as { issues: Array<{ path?: unknown[]; message: string }> }\n    ).issues;\n    message = issues.map((i) => i.message).join('; ');\n    path = issues[0]?.path?.join('.') || undefined;\n  } else if (error && typeof error === 'object' && 'message' in error) {\n    message = String((error as { message: unknown }).message);\n  } else {\n    message = 'Unknown error';\n  }\n\n  const structured: Record<string, unknown> = { error: message };\n  if (hint) structured.hint = hint;\n  if (path) structured.path = path;\n  if (code) structured.code = code;\n  if (details) structured.details = details;\n\n  return {\n    content: [\n      {\n        type: 'text' as const,\n        text: JSON.stringify(structured),\n      },\n    ],\n    structuredContent: structured,\n    isError: true as const,\n  };\n}\n","/**\n * Options for responding to an HTTP request.\n * Same interface for web and server — sources implement the handler.\n */\nexport interface RespondOptions {\n  /** Response body. Objects are JSON-serialized by source. */\n  body?: unknown;\n  /** HTTP status code (default: 200). Server-only, ignored by web sources. */\n  status?: number;\n  /** HTTP response headers. Server-only, ignored by web sources. */\n  headers?: Record<string, string>;\n}\n\n/**\n * Standardized response function available on env for every step.\n * Idempotent: first call wins, subsequent calls are no-ops.\n * Created by sources via createRespond(), consumed by any step.\n */\nexport type RespondFn = (options?: RespondOptions) => void;\n\n/**\n * Creates an idempotent respond function.\n * The sender callback is source-specific (Express wraps res, Fetch wraps Response, etc.).\n *\n * @param sender - Platform-specific function that actually sends the response\n * @returns Idempotent respond function (first call wins)\n */\nexport function createRespond(\n  sender: (options: RespondOptions) => void,\n): RespondFn {\n  let called = false;\n  return (options: RespondOptions = {}) => {\n    if (called) return;\n    called = true;\n    sender(options);\n  };\n}\n","import type {\n  MatchExpression,\n  MatchCondition,\n  MatchOperator,\n  CompiledMatcher,\n} from './types/matcher';\nimport { getByPath } from './byPath';\n\n/**\n * Compiles a match expression into a closure for fast runtime evaluation.\n * Regex patterns are compiled once. Numeric comparisons are parsed once.\n * Runtime evaluation is pure function calls with short-circuit logic.\n */\nexport function compileMatcher(\n  expr: MatchExpression | '*' | undefined,\n): CompiledMatcher {\n  if (expr === undefined || expr === '*') return () => true;\n\n  if ('and' in expr) {\n    const fns = expr.and.map(compileMatcher);\n    return (ingest) => fns.every((fn) => fn(ingest));\n  }\n\n  if ('or' in expr) {\n    const fns = expr.or.map(compileMatcher);\n    return (ingest) => fns.some((fn) => fn(ingest));\n  }\n\n  // Leaf condition\n  return compileCondition(expr);\n}\n\nfunction compileCondition(condition: MatchCondition): CompiledMatcher {\n  const { key, operator, value, not } = condition;\n  const test = compileOperator(operator, value);\n\n  return (context) => {\n    const raw = getByPath(context, key);\n    const result = test(raw);\n    return not ? !result : result;\n  };\n}\n\nfunction compileOperator(\n  operator: MatchOperator,\n  value: string,\n): (input: unknown) => boolean {\n  switch (operator) {\n    case 'eq':\n      return (input) => String(input ?? '') === value;\n    case 'contains':\n      return (input) => String(input ?? '').includes(value);\n    case 'prefix':\n      return (input) => String(input ?? '').startsWith(value);\n    case 'suffix':\n      return (input) => String(input ?? '').endsWith(value);\n    case 'regex': {\n      const re = new RegExp(value);\n      return (input) => re.test(String(input ?? ''));\n    }\n    case 'gt': {\n      const num = Number(value);\n      return (input) => Number(input) > num;\n    }\n    case 'lt': {\n      const num = Number(value);\n      return (input) => Number(input) < num;\n    }\n    case 'exists':\n      return (input) => input !== undefined && input !== null;\n  }\n}\n","import type { Route, RouteConfig } from './types/transformer';\nimport type { CompiledMatcher } from './types/matcher';\nimport { compileMatcher } from './matcher';\n\n/**\n * Internal: compiled route data. Not exported from the package's public\n * surface (`@walkeros/core`), but exported here so adjacent test files\n * inside the core package can probe compilation.\n */\nexport interface CompiledRoute {\n  match: CompiledMatcher;\n  next: CompiledNext;\n}\n\nexport type CompiledNext =\n  | { type: 'static'; value: string }\n  | { type: 'chain'; value: string[] }\n  | { type: 'one'; routes: CompiledRoute[] }\n  | { type: 'many'; routes: CompiledRoute[] }\n  | { type: 'gate'; match: CompiledMatcher; next?: CompiledNext }\n  | { type: 'sequence'; value: CompiledNext[] };\n\nexport function isRouteConfigEntry(entry: unknown): boolean {\n  return (\n    typeof entry === 'object' &&\n    entry !== null &&\n    !Array.isArray(entry) &&\n    ('match' in entry || 'next' in entry || 'one' in entry || 'many' in entry)\n  );\n}\n\n/**\n * Pure RouteConfig array — every element is a RouteConfig object.\n * Used to detect the legacy first-match shape (treated as implicit `one`).\n */\nexport function isRouteArray(next: Route): next is RouteConfig[] {\n  return (\n    Array.isArray(next) &&\n    next.length > 0 &&\n    next.every((entry) => isRouteConfigEntry(entry))\n  );\n}\n\nfunction compileRoutes(entries: Route[]): CompiledRoute[] {\n  return entries.map((entry) => {\n    if (typeof entry === 'string') {\n      return { match: () => true, next: { type: 'static', value: entry } };\n    }\n    if (Array.isArray(entry)) {\n      return {\n        match: () => true,\n        next: compileNext(entry) ?? { type: 'chain', value: [] },\n      };\n    }\n    const e = entry as RouteConfig;\n    return {\n      match: e.match ? compileMatcher(e.match) : () => true,\n      next: compileNext(e) ?? { type: 'chain', value: [] },\n    };\n  });\n}\n\nexport function compileNext(next: Route | undefined): CompiledNext | undefined {\n  if (next === undefined || next === null) return undefined;\n  if (typeof next === 'string') return { type: 'static', value: next };\n\n  if (Array.isArray(next)) {\n    if (next.length === 0) return undefined;\n    if (isRouteArray(next)) {\n      // Pure RouteConfig[] — legacy first-match shape, treat as implicit { one: [...] }\n      return compileNext({ one: next as RouteConfig[] });\n    }\n    if (next.every((entry) => typeof entry === 'string')) {\n      // Pure string[] — static chain\n      return { type: 'chain', value: next as string[] };\n    }\n    // Mixed array (strings + RouteConfig objects, possibly nested arrays) —\n    // sequence form: each segment resolves independently, results concatenated.\n    const segments: CompiledNext[] = [];\n    for (const entry of next) {\n      const compiled = compileNext(entry);\n      if (compiled !== undefined) segments.push(compiled);\n    }\n    if (segments.length === 0) return undefined;\n    return { type: 'sequence', value: segments };\n  }\n\n  // RouteConfig\n  const cfg = next as RouteConfig;\n  if ('next' in cfg && cfg.next !== undefined) {\n    // next operator (optionally gated)\n    if (cfg.match) {\n      return {\n        type: 'gate',\n        match: compileMatcher(cfg.match),\n        next: compileNext(cfg.next),\n      };\n    }\n    return compileNext(cfg.next);\n  }\n  if ('one' in cfg && cfg.one) {\n    const routes = compileRoutes(cfg.one);\n    if (cfg.match) {\n      // outer gate around the one\n      return {\n        type: 'gate',\n        match: compileMatcher(cfg.match),\n        next: { type: 'one', routes },\n      };\n    }\n    return { type: 'one', routes };\n  }\n  if ('many' in cfg && cfg.many) {\n    const routes = compileRoutes(cfg.many);\n    if (cfg.match) {\n      // outer gate around the many\n      return {\n        type: 'gate',\n        match: compileMatcher(cfg.match),\n        next: { type: 'many', routes },\n      };\n    }\n    return { type: 'many', routes };\n  }\n  // Bare gate { match } — no next/one/many\n  if (cfg.match) {\n    return { type: 'gate', match: compileMatcher(cfg.match) };\n  }\n\n  return undefined;\n}\n\nconst compileCache = new WeakMap<object, CompiledNext>();\n\n/**\n * Resolve a Route spec against a matcher context. Returns the immediate\n * next transformer IDs.\n *\n * Return shape:\n *   []          → terminate (gate failed, empty many, all matchers failed,\n *                  undefined spec).\n *   [\"x\"]       → continue main chain at x.\n *   [\"a\",\"b\",…] → fan-out, only produced by `many`. Main chain terminates\n *                  at this dispatch point; each branch is an independent\n *                  flow running to its own exit.\n *\n * Reachability vs prediction: `match` rules read arbitrary event fields.\n * `getNextSteps` is deterministic for the SUPPLIED context only. Static\n * analyzers without a real event must over-approximate by treating each\n * match as \"may pass or fail\" — see `flattenRouteTargets` in the CLI\n * validator. This function does NOT predict the path a future event will\n * take; it computes the path for the event you give it.\n */\nexport function getNextSteps(\n  spec: Route | undefined,\n  context: Record<string, unknown> = {},\n): string[] {\n  if (spec === undefined || spec === null) return [];\n  let compiled: CompiledNext | undefined;\n  if (typeof spec === 'object') {\n    const cached = compileCache.get(spec);\n    if (cached) {\n      compiled = cached;\n    } else {\n      compiled = compileNext(spec);\n      if (compiled) compileCache.set(spec, compiled);\n    }\n  } else {\n    compiled = compileNext(spec);\n  }\n  if (!compiled) return [];\n  const resolved = resolveNext(compiled, context);\n  if (resolved === undefined) return [];\n  return Array.isArray(resolved) ? resolved : [resolved];\n}\n\nexport function resolveNext(\n  compiled: CompiledNext | undefined,\n  context: Record<string, unknown> = {},\n): string | string[] | undefined {\n  if (!compiled) return undefined;\n  if (compiled.type === 'static') return compiled.value;\n  if (compiled.type === 'chain') return compiled.value;\n  if (compiled.type === 'gate') {\n    if (!compiled.match(context)) return undefined; // gate failed → fall through\n    return resolveNext(compiled.next, context);\n  }\n  if (compiled.type === 'sequence') {\n    const ids: string[] = [];\n    for (const segment of compiled.value) {\n      const resolved = resolveNext(segment, context);\n      if (resolved === undefined) continue;\n      if (Array.isArray(resolved)) ids.push(...resolved);\n      else ids.push(resolved);\n    }\n    return ids.length > 0 ? ids : undefined;\n  }\n  if (compiled.type === 'many') {\n    const ids: string[] = [];\n    for (const route of compiled.routes) {\n      if (!route.match(context)) continue;\n      const inner = resolveNext(route.next, context);\n      if (inner === undefined) continue;\n      if (Array.isArray(inner)) ids.push(...inner);\n      else ids.push(inner);\n    }\n    return ids.length > 0 ? ids : undefined;\n  }\n  // one: first-match dispatch\n  for (const route of compiled.routes) {\n    if (route.match(context)) {\n      return resolveNext(route.next, context);\n    }\n  }\n  return undefined;\n}\n","import type { StoreValue } from './types/store';\n\n/**\n * Shared cache envelope used by BOTH cache mechanisms (the event cache in\n * `./cache.ts` and the store-cache wrapper in\n * `@walkeros/collector/store-cache-wrapper`). A cached value is wrapped in a\n * plain `{value, exp}` structured object, not a Buffer: the backing store\n * serializes it through the shared store codec (`./store/codec`), so any\n * structured store can persist it byte-exact, and a TTL-native tier\n * (in-memory `__cache`, Redis) can additionally evict via the `ttl` arg.\n *\n * The envelope owns expiry interpretation, not the store contract:\n * `StoreValue` carries no TTL field. The physical envelope keys are\n * namespaced (`__walkeros_cache_v__` / `__walkeros_cache_exp__`) so a user\n * value that happens to be shaped `{ value, exp }` is never mistaken for an\n * envelope, and conversely a wrapped envelope is unambiguous on read.\n */\n\nconst ENVELOPE_VALUE = '__walkeros_cache_v__';\nconst ENVELOPE_EXP = '__walkeros_cache_exp__';\n\n/** A wrapped cache envelope as it is persisted into the backing store. */\nexport type CacheEnvelope = {\n  [ENVELOPE_VALUE]: StoreValue;\n  [ENVELOPE_EXP]?: number;\n};\n\nfunction isRecord(value: unknown): value is Record<string, StoreValue> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Wrap a value in a `{value, exp}` envelope. When `ttlMs` is given, `exp` is\n * `now() + ttlMs`; when omitted, `exp` is left off entirely (no expiry).\n *\n * `now` is injectable so tests do not depend on ambient wall-clock time;\n * production callers omit it and the helper falls back to `Date.now`.\n */\nexport function wrapCacheEnvelope(\n  value: StoreValue,\n  ttlMs?: number,\n  now: () => number = Date.now,\n): CacheEnvelope {\n  const envelope: CacheEnvelope = { [ENVELOPE_VALUE]: value };\n  if (ttlMs !== undefined) envelope[ENVELOPE_EXP] = now() + ttlMs;\n  return envelope;\n}\n\n/**\n * Read a stored envelope. Returns:\n * - `undefined` when the key is absent (`stored === undefined`).\n * - `{ expired: true }` when the envelope's `exp` has elapsed (caller should\n *   best-effort purge and treat as a MISS).\n * - `{ value }` otherwise.\n *\n * A stored value that is not a recognizable envelope (a raw live value, e.g.\n * a TTL-native tier that holds the value by reference, or a legacy entry) is\n * returned verbatim as `{ value: stored }`, so a non-enveloped HIT degrades\n * gracefully rather than being dropped.\n */\nexport function readCacheEnvelope(\n  stored: StoreValue | undefined,\n  now: () => number = Date.now,\n): { value: StoreValue } | { expired: true } | undefined {\n  if (stored === undefined) return undefined;\n  if (!isRecord(stored) || !(ENVELOPE_VALUE in stored))\n    return { value: stored };\n\n  const exp = stored[ENVELOPE_EXP];\n  if (typeof exp === 'number' && now() > exp) return { expired: true };\n  return { value: stored[ENVELOPE_VALUE] };\n}\n","import type { StoreValue } from '../types/store';\n\n/**\n * Shared structured codec for store values.\n *\n * Stateless, format-only: serializes a `StoreValue` to a UTF-8 JSON byte\n * payload and restores it, with no store-type branches. Binary leaves are\n * tagged base64 behind a reserved marker; user objects that happen to carry\n * the marker are escaped, so NO payload can be corrupted. On the store path\n * binary always decodes back to a platform-neutral `Uint8Array`, never a Node\n * `Buffer`.\n */\n\nconst CACHE_MARKER = '__walkeros_cache__';\n\n/**\n * Thrown when a value cannot be serialized (e.g. a cyclic structure that\n * `JSON.stringify` rejects). Catchable and distinguishable from a raw\n * `TypeError` leaking out of the platform JSON implementation.\n */\nexport class StoreCodecError extends Error {\n  constructor(message: string, options?: { cause?: unknown }) {\n    super(message, options);\n    this.name = 'StoreCodecError';\n  }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n// Precondition: the input is acyclic JSON-shaped data; binary leaves are the\n// only non-JSON values handled. A Node `Buffer`, any `Uint8Array` (e.g. a\n// Fetch-sourced body), and a raw `ArrayBuffer` all normalize to the same\n// base64 'buffer' tag and decode back through the caller-supplied binary\n// factory (see fromSerializableWith). A `Buffer` IS a `Uint8Array`, but under\n// split realms (jsdom test env) a Node `Buffer` fails the `instanceof\n// Uint8Array` check against the realm's `Uint8Array`, so the realm-independent\n// `Buffer.isBuffer` check stays FIRST. The `Uint8Array` branch then handles\n// typed-array views by slicing on byteOffset/byteLength so a subarray view\n// contributes only its own bytes.\nfunction toSerializable(value: unknown): unknown {\n  if (Buffer.isBuffer(value))\n    return { [CACHE_MARKER]: 'buffer', d: value.toString('base64') };\n  if (value instanceof Uint8Array)\n    return {\n      [CACHE_MARKER]: 'buffer',\n      d: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString(\n        'base64',\n      ),\n    };\n  if (value instanceof ArrayBuffer)\n    return {\n      [CACHE_MARKER]: 'buffer',\n      d: Buffer.from(value).toString('base64'),\n    };\n  if (Array.isArray(value)) return value.map(toSerializable);\n  if (isRecord(value)) {\n    if (CACHE_MARKER in value) {\n      const inner: Record<string, unknown> = {};\n      for (const [k, v] of Object.entries(value)) inner[k] = toSerializable(v);\n      return { [CACHE_MARKER]: 'escape', d: inner };\n    }\n    const out: Record<string, unknown> = {};\n    for (const [k, v] of Object.entries(value)) out[k] = toSerializable(v);\n    return out;\n  }\n  return value;\n}\n\n/**\n * Single traversal that restores the serialized form. The binary-leaf type is\n * supplied by the caller via `toBinary`; the store path constructs a plain\n * `Uint8Array`. Parametrizing the leaf factory keeps one implementation of the\n * walk while leaving the binary representation to the caller.\n */\nfunction fromSerializableWith(\n  value: unknown,\n  toBinary: (buf: Buffer) => Uint8Array,\n): unknown {\n  if (isRecord(value)) {\n    if (CACHE_MARKER in value) {\n      const tag = value[CACHE_MARKER];\n      const data = value.d;\n      if (tag === 'buffer' && typeof data === 'string')\n        return toBinary(Buffer.from(data, 'base64'));\n      if (tag === 'escape' && isRecord(data)) {\n        const out: Record<string, unknown> = {};\n        for (const [k, v] of Object.entries(data))\n          out[k] = fromSerializableWith(v, toBinary);\n        return out;\n      }\n      // Unrecognized tag (not 'buffer'/'escape'): fall through to default\n      // object traversal so a user object that merely carries the marker key,\n      // or a value from a future tag version, is preserved verbatim rather\n      // than coerced.\n    }\n    const out: Record<string, unknown> = {};\n    for (const [k, v] of Object.entries(value))\n      out[k] = fromSerializableWith(v, toBinary);\n    return out;\n  }\n  if (Array.isArray(value))\n    return value.map((v) => fromSerializableWith(v, toBinary));\n  return value;\n}\n\n// Store path: binary leaves become a plain, platform-neutral Uint8Array (a\n// standalone view over the exact decoded bytes), never a Node Buffer.\nfunction toStoreBinary(buf: Buffer): Uint8Array {\n  return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n}\n\n/**\n * Recursive type guard: the restored value is structurally a `StoreValue`.\n * The single restore walk (`fromSerializableWith`) is JSON-derived plus\n * `Uint8Array` binary leaves, so this always holds; the guard makes the\n * narrowing explicit and cast-free at the public boundary.\n *\n * The guard accepts exactly what the serializer can encode. An `undefined`\n * object property is dropped and an `undefined` array element becomes `null`\n * on `JSON.stringify`, so an `undefined` nested value does NOT disqualify the\n * containing value (matching the serializer's runtime tolerance at the\n * `unknown -> StoreValue` boundary). The `StoreValue` TYPE still excludes\n * `undefined`; this only mirrors what survives serialization.\n */\nfunction isStoreValue(value: unknown): value is StoreValue {\n  if (\n    value === null ||\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean' ||\n    value instanceof Uint8Array\n  )\n    return true;\n  if (Array.isArray(value))\n    return value.every((v) => v === undefined || isStoreValue(v));\n  if (isRecord(value))\n    return Object.values(value).every(\n      (v) => v === undefined || isStoreValue(v),\n    );\n  return false;\n}\n\n/**\n * Serialize a `StoreValue` to its UTF-8 JSON byte payload. Throws\n * `StoreCodecError` if the value cannot be encoded (e.g. a cyclic structure).\n */\nexport function serializeStoreValue(value: StoreValue): Uint8Array {\n  let json: string;\n  try {\n    json = JSON.stringify(toSerializable(value));\n  } catch (cause) {\n    throw new StoreCodecError(\n      'Failed to serialize store value (likely a cyclic structure).',\n      { cause },\n    );\n  }\n  return new Uint8Array(Buffer.from(json, 'utf8'));\n}\n\n/**\n * Restore a `StoreValue` from its UTF-8 JSON byte payload (or a JSON string).\n */\nexport function deserializeStoreValue(raw: Uint8Array | string): StoreValue {\n  const text =\n    typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8');\n  const restored = fromSerializableWith(JSON.parse(text), toStoreBinary);\n  if (!isStoreValue(restored))\n    throw new StoreCodecError('Restored value is not a valid StoreValue.');\n  return restored;\n}\n\n// Internal format helpers shared with the cache envelope codec (cache.ts) so\n// there is exactly one implementation of the structured transform.\n// `isStoreValue` lets boundary callers (the event cache) narrow a wide\n// `unknown` payload to `StoreValue` without a cast before wrapping it.\nexport {\n  toSerializable,\n  fromSerializableWith,\n  CACHE_MARKER,\n  isRecord,\n  isStoreValue,\n};\n","import type { Cache, EventCacheRule } from './types/cache';\nimport type { Collector, Mapping, Store } from './types';\nimport type { StoreValue } from './types/store';\nimport type { CompiledMatcher } from './types/matcher';\nimport { compileMatcher } from './matcher';\nimport { getByPath, setByPath } from './byPath';\nimport { getMappingValue } from './mapping';\nimport { wrapCacheEnvelope, readCacheEnvelope } from './cache-envelope';\nimport { isStoreValue } from './store/codec';\n\ninterface CompiledCacheRule {\n  match: CompiledMatcher;\n  key: string[];\n  ttl: number;\n  update?: EventCacheRule['update'];\n}\n\nexport interface CompiledCache {\n  stop: boolean;\n  storeId?: string;\n  namespace?: string;\n  rules: CompiledCacheRule[];\n}\n\nexport interface CacheResult {\n  status: 'HIT' | 'MISS';\n  key: string;\n  value?: StoreValue;\n  rule: CompiledCacheRule;\n}\n\n/**\n * Builds a structured context object for cache and routing operations.\n * Normalizes ingest (defaulting to {}) and optionally includes event.\n */\nexport function buildCacheContext(\n  ingest?: unknown,\n  event?: unknown,\n): Record<string, unknown> {\n  const ctx: Record<string, unknown> = {\n    ingest: (ingest ?? {}) as Record<string, unknown>,\n  };\n  if (event !== undefined) {\n    ctx.event = event as Record<string, unknown>;\n  }\n  return ctx;\n}\n\nexport function compileCache(cache: Cache<EventCacheRule>): CompiledCache {\n  return {\n    stop: cache.stop ?? false,\n    storeId: cache.store,\n    namespace: cache.namespace,\n    rules: cache.rules.map((rule) => ({\n      match: rule.match ? compileMatcher(rule.match) : () => true,\n      key: rule.key,\n      ttl: rule.ttl,\n      update: rule.update,\n    })),\n  };\n}\n\nexport async function checkCache(\n  compiled: CompiledCache,\n  store: Store.Instance,\n  context: Record<string, unknown>,\n  namespace?: string,\n): Promise<CacheResult | null> {\n  const rule = compiled.rules.find((r) => r.match(context));\n  if (!rule) return null;\n\n  const keyParts = rule.key.map((field) =>\n    String(getByPath(context, field) ?? ''),\n  );\n\n  if (keyParts.every((p) => p === '')) return null;\n\n  const keyValue = keyParts.join(':');\n  const ns = namespace ?? compiled.namespace;\n  const namespacedKey = ns ? `${ns}:${keyValue}` : keyValue;\n\n  // `Store.GetFn` permits sync or async returns (`T | undefined |\n  // Promise<T | undefined>`). Always await so a Promise return from an\n  // async store (Redis, fs, the cache wrapper) never lands in the HIT\n  // path as the cached \"value\".\n  const decoded = readCacheEnvelope(await store.get(namespacedKey));\n\n  if (decoded === undefined)\n    return { status: 'MISS', key: namespacedKey, rule };\n  if ('expired' in decoded) {\n    try {\n      await store.delete(namespacedKey);\n    } catch {\n      /* best-effort purge; degrade to MISS rather than throw into the request */\n    }\n    return { status: 'MISS', key: namespacedKey, rule };\n  }\n  return { status: 'HIT', key: namespacedKey, value: decoded.value, rule };\n}\n\nexport function storeCache(\n  store: Store.Instance,\n  key: string,\n  value: unknown,\n  ttlSeconds: number,\n): void {\n  // Callers (source RespondOptions, destination push result, transformer\n  // processed event) hold values typed wider than `StoreValue` but that are\n  // structurally a `StoreValue` at runtime (JSON-shaped + binary leaves). The\n  // guard narrows cast-free; a value that is genuinely not a `StoreValue` is\n  // not cacheable, and the cache is advisory, so silently skip rather than\n  // throw into the request path.\n  if (!isStoreValue(value)) return;\n\n  const ttlMs = ttlSeconds * 1000;\n  // Store the plain {value, exp} envelope, not a pre-serialized Buffer: the\n  // backing store serializes it through the shared store codec, so binary\n  // leaves come back as Uint8Array. `exp` inside the envelope gives\n  // uniform expiry for stores that ignore the ttl arg (fs/s3/gcs); the ttl\n  // arg lets TTL-native stores (in-memory) evict instead of retaining until\n  // read.\n  // `Store.SetFn` returns `void | Promise<void>`. The write is fire-and-forget\n  // (the HTTP response is sent before it lands), so an async store that rejects\n  // (network error, EACCES) would otherwise surface as an unhandled rejection\n  // and crash the process. Swallow it: a failed cache persist must never crash\n  // the request path. Matches the best-effort silent catch on the checkCache purge.\n  const result = store.set(key, wrapCacheEnvelope(value, ttlMs), ttlMs);\n  if (result instanceof Promise) result.catch(() => {});\n}\n\nexport async function applyUpdate(\n  value: unknown,\n  update: Record<string, unknown> | undefined,\n  context: Record<string, unknown>,\n  collector: Collector.Instance,\n): Promise<unknown> {\n  if (!update) return value;\n\n  let result = value;\n  for (const [path, valueConfig] of Object.entries(update)) {\n    const resolved = await getMappingValue(\n      context,\n      valueConfig as Mapping.Data,\n      { collector },\n    );\n    result = setByPath(result, path, resolved);\n  }\n  return result;\n}\n","import type { Collector, Mapping, State, Store, WalkerOS } from './types';\nimport { getMappingValue } from './mapping';\nimport { FatalError } from './fatalError';\nimport { setByPath } from './byPath';\nimport { isArray, isDefined, isObject, isString } from './is';\nimport { tryCatchAsync } from './tryCatch';\n\n/**\n * Resolve a store by id. An `undefined` id falls back to the default\n * in-memory `__cache` store. Returns `undefined` when the id is unknown.\n */\nexport type GetStore = (id: string | undefined) => Store.Instance | undefined;\n\n/** Normalize a single State or an array of States to an array. */\nexport function compileState(state: State | State[]): State[] {\n  return isArray(state) ? state : [state];\n}\n\n/** Extract the event write-target path for a `get`. */\nfunction resolveTargetPath(\n  value: Mapping.Value | undefined,\n): string | undefined {\n  if (isString(value)) return value;\n  if (isObject(value) && isString(value.key)) return value.key;\n  return undefined;\n}\n\n/**\n * Apply declarative store operations against an event, in array order,\n * sequentially. `get` reads from the store and writes the fetched value to\n * the event's value path; `set` writes the resolved value to the store. Each\n * entry is fail-open: a store or resolution error is logged and the event is\n * left unmutated, the chain continues. Only `FatalError` rethrows (via\n * `getMappingValue`).\n */\nexport async function applyState<E extends WalkerOS.DeepPartialEvent>(\n  states: State[],\n  getStore: GetStore,\n  event: E,\n  collector: Collector.Instance,\n): Promise<E> {\n  let result = event;\n  for (const entry of states) {\n    await tryCatchAsync(\n      async () => {\n        const store = getStore(entry.store);\n        if (!store) return; // unknown store is rejected at validation; guard anyway\n\n        const rawKey = await getMappingValue(result, entry.key, {\n          collector,\n          event: result,\n        });\n        if (!isString(rawKey)) return;\n        // namespace state keys on the shared default store to avoid cache collisions\n        const key = entry.store ? rawKey : `state:${rawKey}`;\n\n        if (entry.mode === 'set') {\n          const payload = await getMappingValue(result, entry.value, {\n            collector,\n            event: result,\n          });\n          if (!isDefined(payload)) return; // skip writing undefined\n          await store.set(key, payload);\n        } else {\n          const targetPath = resolveTargetPath(entry.value);\n          if (!targetPath) return; // validation already rejects this\n          const fetched = await store.get(key);\n          if (!isDefined(fetched)) return; // miss: leave event unchanged\n          result = setByPath(result, targetPath, fetched);\n        }\n      },\n      (error) => {\n        if (error instanceof FatalError) throw error;\n        collector.logger?.error?.('[state] operation failed', error);\n      },\n    )();\n  }\n  return result;\n}\n","import type { Flow } from './types/flow';\n\n/**\n * Single source of truth for step-entry validation across all four kinds.\n *\n * An empty entry (no `code`, no `package`, no `import`) is a valid no-op\n * step for all four kinds. The bundler emits no code; the runtime skips\n * registration. No error is raised for empty steps.\n *\n * Error codes:\n * - UNKNOWN_KEY          unknown top-level key on a step entry\n * - CONFLICT             two of {code, package, import} together, or other mutually exclusive pairs\n * - MISSING_PACKAGE      `import` set without `package`\n * - OBSOLETE_CODE_STRING `code` is a string (legacy named-export shape; use `import` instead)\n * - INVALID_IMPORT       `import` is set but is not a valid JS identifier\n * - INVALID_CODE_SHAPE   `code` is present but is neither an object nor a string\n */\n\nexport const STEP_OPERATIVE_FIELDS: Record<Flow.StepKind, readonly string[]> = {\n  Source: ['code', 'package', 'import', 'before', 'next', 'cache', 'state'],\n  Transformer: [\n    'code',\n    'package',\n    'import',\n    'before',\n    'next',\n    'cache',\n    'state',\n    'mapping',\n  ],\n  Destination: [\n    'code',\n    'package',\n    'import',\n    'before',\n    'next',\n    'cache',\n    'state',\n  ],\n  Store: ['code', 'package', 'import', 'cache'],\n} as const;\n\nconst COMMON_NON_OPERATIVE = [\n  'config',\n  'env',\n  'variables',\n  'examples',\n  'disabled',\n  'id',\n  'logger',\n  'mock',\n  'chainMocks',\n] as const;\n\nconst KIND_EXTRA: Record<Flow.StepKind, readonly string[]> = {\n  Source: ['primary'],\n  Transformer: [],\n  Destination: [],\n  Store: [],\n};\n\nconst IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nexport type StepEntryErrorCode =\n  | 'UNKNOWN_KEY'\n  | 'CONFLICT'\n  | 'MISSING_PACKAGE'\n  | 'OBSOLETE_CODE_STRING'\n  | 'INVALID_IMPORT'\n  | 'INVALID_CODE_SHAPE';\n\nexport interface StepEntryValidation {\n  ok: boolean;\n  reason?: string;\n  code?: StepEntryErrorCode;\n  key?: string;\n}\n\nfunction allowedKeys(kind: Flow.StepKind): Set<string> {\n  return new Set<string>([\n    ...STEP_OPERATIVE_FIELDS[kind],\n    ...COMMON_NON_OPERATIVE,\n    ...KIND_EXTRA[kind],\n  ]);\n}\n\nexport function validateStepEntry(\n  entry: Record<string, unknown>,\n  kind: Flow.StepKind,\n): StepEntryValidation {\n  const allowed = allowedKeys(kind);\n\n  for (const key of Object.keys(entry)) {\n    if (!allowed.has(key)) {\n      return {\n        ok: false,\n        code: 'UNKNOWN_KEY',\n        key,\n        reason: `Unknown key \"${key}\" on ${kind}. Allowed: ${[...allowed].sort().join(', ')}.`,\n      };\n    }\n  }\n\n  const hasPackage = entry.package !== undefined;\n  const hasImport = entry.import !== undefined;\n  const hasCode = entry.code !== undefined;\n\n  if (hasCode && typeof entry.code === 'string') {\n    return {\n      ok: false,\n      code: 'OBSOLETE_CODE_STRING',\n      key: 'code',\n      reason: `code: \"<name>\" is no longer supported. Use import: \"${entry.code}\" with the package field instead.`,\n    };\n  }\n\n  if (\n    hasCode &&\n    ((typeof entry.code !== 'object' && typeof entry.code !== 'function') ||\n      entry.code === null ||\n      Array.isArray(entry.code))\n  ) {\n    return {\n      ok: false,\n      code: 'INVALID_CODE_SHAPE',\n      key: 'code',\n      reason: `code must be an object ({ push, type?, init? }) or a resolved function value.`,\n    };\n  }\n\n  if (hasCode && hasPackage) {\n    return {\n      ok: false,\n      code: 'CONFLICT',\n      key: 'package',\n      reason: 'Cannot specify both `code` and `package`. Use one or the other.',\n    };\n  }\n  if (hasCode && hasImport) {\n    return {\n      ok: false,\n      code: 'CONFLICT',\n      key: 'import',\n      reason: 'Cannot specify both `code` and `import`.',\n    };\n  }\n  if (hasImport && !hasPackage) {\n    return {\n      ok: false,\n      code: 'MISSING_PACKAGE',\n      key: 'import',\n      reason: '`import` requires `package` to be set.',\n    };\n  }\n  if (hasImport) {\n    if (typeof entry.import !== 'string' || !IDENT_RE.test(entry.import)) {\n      return {\n        ok: false,\n        code: 'INVALID_IMPORT',\n        key: 'import',\n        reason: `import must match ${IDENT_RE.source}. Got: ${JSON.stringify(entry.import)}.`,\n      };\n    }\n  }\n\n  // Empty entry (no code, no package, no import) is a valid no-op step\n  // for all four kinds. Bundler emits nothing, runtime skips registration.\n\n  return { ok: true };\n}\n\nexport function isPathStepEntry(\n  entry: Record<string, unknown>,\n  kind: Flow.StepKind,\n): boolean {\n  if (kind !== 'Transformer') return false;\n  if (\n    entry.code !== undefined ||\n    entry.package !== undefined ||\n    entry.import !== undefined\n  ) {\n    return false;\n  }\n  return (\n    entry.before !== undefined ||\n    entry.next !== undefined ||\n    entry.cache !== undefined ||\n    entry.state !== undefined ||\n    entry.mapping !== undefined\n  );\n}\n","import type { Flow } from '../types/flow';\n\ntype StepOut = Flow.StepOut;\ntype StepEffect = Flow.StepEffect;\n\n/**\n * Format a step example's `out` as readable code for docs/app rendering.\n *\n * - Empty `out` → `// no output`.\n * - `['return', value]` → `return <value>` (no parentheses).\n * - `[callable, ...args]` → `callable(<args>)`.\n * - Primitive args render as JSON (strings quoted, numbers/booleans/null bare).\n * - `undefined` renders as the literal token `undefined`.\n * - Objects/arrays render as `JSON.stringify(v, null, 2)`.\n * - Functions render as `[Function]` (rare in outs; safe fallback).\n *\n * Pure function. No runtime dependencies. Used by the website\n * `<StepExample>` renderer and the app `OutputPanel` for a single source of truth.\n */\nexport function formatOut(out: StepOut): string {\n  if (out.length === 0) return '// no output';\n  return out.map(formatEffect).join(';\\n\\n');\n}\n\nfunction formatEffect(effect: StepEffect): string {\n  const [callable, ...args] = effect;\n  const argStr = args.map(formatValue).join(', ');\n  if (callable === 'return') return argStr ? `return ${argStr}` : 'return';\n  return `${callable}(${argStr})`;\n}\n\nfunction formatValue(v: unknown): string {\n  if (v === undefined) return 'undefined';\n  if (v === null) return 'null';\n  if (typeof v === 'function') return '[Function]';\n  return JSON.stringify(v, null, 2);\n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;AACpB;AAEO,SAAS,gBACd,OACA,MACS;AACT,MAAI,SAAS,cAAe,QAAO;AACnC,MACE,MAAM,SAAS,UACf,MAAM,YAAY,UAClB,MAAM,WAAW,QACjB;AACA,WAAO;AAAA,EACT;AACA,SACE,MAAM,WAAW,UACjB,MAAM,SAAS,UACf,MAAM,UAAU,UAChB,MAAM,UAAU,UAChB,MAAM,YAAY;AAEtB;;;AC3KO,SAAS,UAAU,KAAsB;AAC9C,MAAI,IAAI,WAAW,EAAG,QAAO;AAC7B,SAAO,IAAI,IAAI,YAAY,EAAE,KAAK,OAAO;AAC3C;AAEA,SAAS,aAAa,QAA4B;AAChD,QAAM,CAAC,UAAU,GAAG,IAAI,IAAI;AAC5B,QAAM,SAAS,KAAK,IAAI,WAAW,EAAE,KAAK,IAAI;AAC9C,MAAI,aAAa,SAAU,QAAO,SAAS,UAAU,MAAM,KAAK;AAChE,SAAO,GAAG,QAAQ,IAAI,MAAM;AAC9B;AAEA,SAAS,YAAY,GAAoB;AACvC,MAAI,MAAM,OAAW,QAAO;AAC5B,MAAI,MAAM,KAAM,QAAO;AACvB,MAAI,OAAO,MAAM,WAAY,QAAO;AACpC,SAAO,KAAK,UAAU,GAAG,MAAM,CAAC;AAClC;","names":["Level","value","value","value","acc","value","value","value","value","value","value","value","mapping","value","value","value","value","value","value","isRecord","value","out","compileCache","value","value","getStore"]}