@protoyard/analytics
v1.9.4
Published
Framework-agnostic analytics engine for Protoyard prototypes: event and metric contracts, date ranges, funnels, cohorts and deterministic analytics generators (no Svelte).
Maintainers
Readme
@protoyard/analytics
Framework-agnostic analytics engine for Protoyard prototypes
(ADR-021): event and metric contracts, date ranges
with comparison, bucketing, aggregations, filters and segments, dashboard
layouts, funnels, cohorts and deterministic analytics generators. The
platform guide (data flow, template, flagship, measured numbers, limits) is
docs/ANALYTICS.md. No Svelte; everything is plain TypeScript and zod,
tested in Node. The Svelte kit is @protoyard/analytics-ui.
Entry points
sideEffects: false; import a subpath to pull in only that module.
| Import | Contents today |
| --- | --- |
| @protoyard/analytics | AnalyticsEventSchema (id, lowercase type, userId, ISO at, primitive properties), GranularitySchema (hour/day/week/month), MetricPoint |
| @protoyard/analytics (ranges) | resolveDateRange(input, now) for presets today, yesterday, last-7-days, last-30-days, last-90-days, month-to-date, quarter-to-date, year-to-date, last-month, or custom days (inclusive) / instants (half-open); comparisonRange(range, 'previous-period' \| 'previous-year'); DateRangeInputSchema, ComparisonSchema, PRESET_LABELS |
| @protoyard/analytics (buckets) | bucketStart, nextBucket, bucketStarts(range, granularity, { weekStartsOn }), bucketize(rows, { range, granularity, at, aggregate, value }) → every bucket, empty ones included |
| @protoyard/analytics (aggregates) | aggregate(values, kind) for count, sum, unique, avg, min, max, p50, p90, p95; percentile (linear interpolation); createAccumulator; delta(current, previous) → { absolute, relative } |
| @protoyard/analytics (filters) | FilterSchema / SegmentSchema (data-only AND/OR trees, up to 4 levels and 500 nodes, measured without recursion before the schema runs so oversized trees fail validation instead of throwing; measureFilterInput), 14 operators with OPERATORS_BY_TYPE, filterSchemaFor(catalog) (unknown properties and type-mismatched operators become field errors), compileFilter(filter) → (row) => boolean, readProperty |
| @protoyard/analytics (layouts) | DashboardWidgetSchema / DashboardLayoutSchema ({ id, widget, title?, x, y, w, h } on 12 columns), compactLayout (no overlaps, upward gravity), moveWidget(layout, id, 'up' \| 'down' \| 'left' \| 'right'), resizeWidget(layout, id, { dw, dh }), readingOrder, layoutRows |
| @protoyard/analytics/generators | generateTimeSeries, generateMetrics, generateProductEvents, generateFunnelJourneys, generateCohorts, liveCounterEvents, analyticsFragments (launchSpike, outageDip, seasonal, empty, massive), analyticsScenarioOptions, isoString, ANALYTICS_GENERATOR_VERSION (see SCENARIOS → Analytics data) |
| @protoyard/analytics/funnel | FunnelStepSchema, FunnelDefinitionSchema (2–12 steps, unique ids); computeFunnel(events, steps, { window, breakdown, range }) → per-step count, conversion, stepConversion, dropOff, medianTimeToConvert, plus a breakdown per property value; eventsByUser |
| @protoyard/analytics/cohort | RetentionIntervalSchema, RetentionPeriodsSchema; computeRetention(events, { cohortEvent, returnEvent, interval, periods, now, mode }) → cohorts × periods with count, rate, incomplete, plus size-weighted average |
Every entry in this table exists and is tested.
Funnels and retention, precisely:
- Funnel: a user enters at their earliest first-step event. Each later
step must be a later event (in time order) within
windowms of entering; steps out of order do not count.medianTimeToConvertis the median time from the previous step.breakdownreads a property path on the entry event; users without it fall in(none). - Retention: a user's cohort is the UTC bucket (day, week from
weekStartsOn, or month) of theircohortEvent, or of their first event. Period N is the Nth bucket after it.bounded(the default) counts users active during period N.unboundedcounts users active in period N or any later one (not churned yet), so rates never rise.- A period that has not finished at
nowisincomplete. One that has not started hascount: null. averageweighs complete cells by cohort size.
Speed: a funnel over 100k events from 10k users (with a breakdown) takes a
median of 27–45 ms, and weekly retention over the same events 30–32 ms, in
Node on the Apple M1 Max under heavy machine load. (The opt-in
PROTOYARD_BENCH=1 case that asserted the 50 ms funnel budget was removed in
PLAN_009.) Size: computeFunnel 1.9 KB,
computeRetention 1.6 KB gzip (zod external).
Semantics worth knowing:
- Ranges are half-open
[start, end)in UTC epoch ms. "Last N days" is today plus the N − 1 days before it, ending atnow. "To date" presets also end atnow;yesterdayandlast-monthend at their calendar boundary. Previous year clamps Feb 29 to Feb 28. - Empty buckets are
0for count/sum/unique andnullfor avg/min/max/percentiles (nothing to measure). More than 10,000 buckets throws aRangeError(use a coarser granularity). delta().relativeisnullwhen the previous value is 0, so a tile never shows "+∞%".- Filters are data: missing,
nulland''count as "not set";neqandnot_inmatch rows without the property; text operators ignore case; ISO date strings compare by time. Paths only read own properties, and__proto__/prototype/constructorsegments are rejected.
Size (esbuild minify + gzip -9, zod external): the whole entry is 3.8 KB;
ranges + buckets + delta are 1.8 KB, filters 1.5 KB. bucketize puts 50k
events into 90 daily buckets in about 5.5 ms in Node (Apple M1 Max, under
heavy machine load). The opt-in analytics generators bench owns the
10 ms budget.
Rules
- "Now" always comes from the caller (the simulated clock), never
Date.now(). - Generators use only the scenario context (
ctx.rng,ctx.ids,ctx.time,ctx.scale) and bumpANALYTICS_GENERATOR_VERSIONwhen output changes. - Bucketing is UTC. Money is integer cents.
Tests
pnpm vitest run packages/analytics
pnpm --filter @protoyard/analytics typecheckPackage output
The manifest keeps TypeScript source exports for workspace development. pnpm build:packages --filter engine creates the ESM and declaration files under dist/ that the packed manifest exposes.
