{"files": {"main.ts": "import {run} from './core.ts';\nimport {POLICY} from './policy.ts';\nexport function evaluate(payload: any): any { return run(payload, POLICY); }\n", "core.ts": "import { parseDecimal, addDecimal, formatDecimal } from './helpers.ts';\nexport function run(payload: any, policy: any): any {\n  const p: any = policy || {};\n  const scopeKey: string = p.scope_key;\n  const latestByRaw: string = p.latest_by;\n  const sortField: string = (latestByRaw === 'timestamp' || latestByRaw === 'ts') ? 'ts' : 'seq';\n  const tiePolicy: string = p.tie_policy;\n  const deleteWins: boolean = !!p.delete_wins;\n  const allowResurrection: boolean = !!p.allow_resurrection;\n  const amountMode: string = p.amount_mode;\n  const precision: number = typeof p.precision === 'number' ? p.precision : 0;\n  const gapPolicy: string = p.gap_policy;\n  const auditDuplicate: boolean = !!p.audit_duplicate;\n  const order: string = p.order;\n  const maxAge: any = p.max_age;\n  const inclusiveAge: boolean = !!p.inclusive_age;\n  if (!payload) return { entities: [], duplicates: [] };\n  const now: any = payload.now;\n  const rawEvents: any[] = Array.isArray(payload) ? payload : (Array.isArray(payload.events) ? payload.events : []);\n  const wrapped: any[] = rawEvents.map((ev: any, idx: number) => ({ ev: ev, idx: idx }));\n  const ageFiltered: any[] = [];\n  for (const w of wrapped) {\n    if (typeof maxAge === 'number' && typeof now === 'number') {\n      const age: number = now - w.ev.ts;\n      if (age > maxAge) continue;\n      if (age === maxAge && !inclusiveAge) continue;\n    }\n    ageFiltered.push(w);\n  }\n  const seen: Set<string> = new Set<string>();\n  const duplicates: any[] = [];\n  const deduped: any[] = [];\n  for (const w of ageFiltered) {\n    const key: string = scopeKey === 'tenant' ? String(w.ev.tenant) + '\\u0000' + String(w.ev.id) : String(w.ev.id);\n    if (seen.has(key)) {\n      if (auditDuplicate) duplicates.push(w.ev.id);\n      continue;\n    }\n    seen.add(key);\n    deduped.push(w);\n  }\n  const groups: Map<string, any> = new Map<string, any>();\n  for (const w of deduped) {\n    const gk: string = String(w.ev.tenant) + '\\u0000' + String(w.ev.entity);\n    let g: any = groups.get(gk);\n    if (!g) { g = { tenant: w.ev.tenant, entity: w.ev.entity, items: [], firstIdx: w.idx }; groups.set(gk, g); }\n    g.items.push(w);\n  }\n  const entities: any[] = [];\n  for (const g of groups.values()) {\n    const tieMap: Map<string, any> = new Map<string, any>();\n    for (const w of g.items) {\n      const tk: string = String(w.ev[sortField]);\n      if (!tieMap.has(tk)) tieMap.set(tk, w);\n      else if (tiePolicy === 'last') tieMap.set(tk, w);\n    }\n    const retained: any[] = Array.from(tieMap.values());\n    const hasDelete: boolean = retained.some((w: any) => w.ev.kind === 'delete');\n    const sorted: any[] = retained.slice().sort((a: any, b: any) => {\n      const av: number = a.ev[sortField]; const bv: number = b.ev[sortField];\n      return av < bv ? -1 : (av > bv ? 1 : 0);\n    });\n    let seqTracker: number = 0;\n    let value: any = { int: 0n, scale: 0 };\n    let deleted: boolean = false;\n    for (const w of sorted) {\n      const ev: any = w.ev;\n      if (gapPolicy === 'ignore') {\n        if (ev.seq !== seqTracker + 1) continue;\n      }\n      seqTracker = ev.seq;\n      if (ev.kind === 'delete') {\n        deleted = true;\n      } else {\n        if (!deleted || allowResurrection) {\n          deleted = false;\n          const amt: any = parseDecimal(ev.amount === undefined || ev.amount === null ? '0' : ev.amount);\n          if (amountMode === 'delta') value = addDecimal(value, amt); else value = amt;\n        }\n      }\n    }\n    if (deleteWins && hasDelete) deleted = true;\n    entities.push({ tenant: g.tenant, entity: g.entity, value: formatDecimal(value, precision), deleted: deleted, _firstIdx: g.firstIdx });\n  }\n  if (order === 'key') {\n    entities.sort((a: any, b: any) => {\n      const at: string = String(a.tenant); const bt: string = String(b.tenant);\n      if (at !== bt) return at < bt ? -1 : 1;\n      const ae: string = String(a.entity); const be: string = String(b.entity);\n      if (ae !== be) return ae < be ? -1 : 1;\n      return 0;\n    });\n  } else {\n    entities.sort((a: any, b: any) => a._firstIdx - b._firstIdx);\n  }\n  const outEntities: any[] = entities.map((e: any) => ({ tenant: e.tenant, entity: e.entity, value: e.value, deleted: e.deleted }));\n  return { entities: outEntities, duplicates: duplicates };\n}\n", "policy.ts": "export const POLICY: any = {\"scope_key\": \"tenant\", \"latest_by\": \"sequence\", \"tie_policy\": \"first\", \"delete_wins\": true, \"allow_resurrection\": true, \"amount_mode\": \"absolute\", \"precision\": 0, \"gap_policy\": \"accept\", \"audit_duplicate\": true, \"order\": \"key\", \"max_age\": 60, \"inclusive_age\": true};\n", "helpers.ts": "export function parseDecimal(input: any): any {\n  let s: string = String(input).trim();\n  let neg: boolean = false;\n  if (s.startsWith('-')) { neg = true; s = s.slice(1); }\n  else if (s.startsWith('+')) { s = s.slice(1); }\n  const parts: string[] = s.split('.');\n  const intPart: string = parts[0] === '' ? '0' : parts[0];\n  const fracPart: string = parts.length > 1 ? parts[1] : '';\n  const digits: string = (intPart + fracPart).replace(/^0+(?=\\d)/, '');\n  let v: bigint = BigInt(digits === '' ? '0' : digits);\n  if (neg) v = -v;\n  return { int: v, scale: fracPart.length };\n}\nexport function addDecimal(a: any, b: any): any {\n  const scale: number = Math.max(a.scale, b.scale);\n  const av: bigint = a.int * (10n ** BigInt(scale - a.scale));\n  const bv: bigint = b.int * (10n ** BigInt(scale - b.scale));\n  return { int: av + bv, scale: scale };\n}\nexport function formatDecimal(dec: any, precision: number): string {\n  let v: bigint = dec.int;\n  const scale: number = dec.scale;\n  const neg: boolean = v < 0n;\n  if (neg) v = -v;\n  let scaled: bigint;\n  if (scale <= precision) {\n    scaled = v * (10n ** BigInt(precision - scale));\n  } else {\n    const divisor: bigint = 10n ** BigInt(scale - precision);\n    const q: bigint = v / divisor;\n    const r: bigint = v % divisor;\n    scaled = (r * 2n >= divisor) ? q + 1n : q;\n  }\n  let s: string = scaled.toString();\n  if (precision === 0) return (neg && scaled !== 0n ? '-' : '') + s;\n  if (s.length <= precision) s = '0'.repeat(precision - s.length + 1) + s;\n  const intPart: string = s.slice(0, s.length - precision);\n  const fracPart: string = s.slice(s.length - precision);\n  return (neg && scaled !== 0n ? '-' : '') + intPart + '.' + fracPart;\n}\n"}}