npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

events-sdk

v0.0.2

Published

Typed event tracking with consent-governed routing for TypeScript apps

Readme

events-sdk

Typed event tracking for TypeScript apps, where consent decides which destination each event may reach.

You declare each event once, with a schema, the purposes it serves, and the routes it can take. Each route names the purposes it requires. client.track() validates the properties, checks every route against the current consent decision, and returns one receipt per route, so you can see that an event committed to analytics and was dropped from advertising, and why.

The package is at 0.0.x. Read Project status before you adopt it.

Install

nub add events-sdk zod

Any Standard Schema validator works for event schemas. The examples use Zod, and Valibot and ArkType work the same way.

Requirements and limits

  • ESM only. There is no CommonJS build, so require("events-sdk") fails.
  • Node.js 24.18.0 or newer, per the package's engines field. Browser code reaches the package through a bundler.
  • The code needs an ES2023 runtime and ships no polyfills: Chrome and Edge 110, Firefox 115, Safari 16, Node.js 20, Deno 1.31, or another runtime on V8 11 or newer. The bundled docs/index.md says what that floor covers.
  • No runtime dependencies. react and c15t are optional peers, needed only for the entry points that use them. The PostHog destination does not use posthog-js.
  • Events wait in memory, not in durable storage. Work still pending when a page unloads or a server process exits can be lost, so flush at the boundary.
  • Events leave the process only through a destination you configure: an events-sdk collector, or PostHog's /batch/ endpoint through events-sdk/destinations/posthog.

Quickstart

Declare the events:

import { defineEvents } from "events-sdk"
import { z } from "zod"

export const events = defineEvents({
  "order.completed": {
    schema: z.object({ orderId: z.string(), revenue: z.number().positive() }),
    declaredPurposes: ["measurement", "marketing"],
    routes: {
      productAnalytics: { requiredPurposes: ["measurement"] },
      salesConversions: { requiredPurposes: ["marketing"] },
    },
  },
})

Bind them to destinations and track one:

import { assumed, createCaptureDestination, createClient } from "events-sdk"
import { events } from "./events.js"

const client = createClient({
  events,
  consent: assumed({
    basis: "Contractual necessity; recorded in policy decision PD-142",
    purposes: ["measurement"],
  }),
  destinations: {
    productAnalytics: createCaptureDestination(),
    salesConversions: createCaptureDestination(),
  },
})

const result = await client.track("order.completed", {
  orderId: "order_123",
  revenue: 42,
})

if (result.ok) {
  // "committed": measurement is asserted.
  console.log(result.routes.productAnalytics.outcome)
  // "dropped" with route/purpose-denied: marketing is not.
  console.log(result.routes.salesConversions.outcome)
} else {
  console.log(result.error.code, result.error.remediation)
}

track() never rejects. Invalid properties come back as { ok: false, error }, and TypeScript catches a misspelled event name, a missing property, or a destination map that leaves out a route.

assumed() records purposes your organization asserts and the basis it recorded for them. It is an organization assertion, not a record that a visitor consented. For visitor choices, use c15t.

createCaptureDestination() keeps events in memory for tests and local inspection.

Field handling

A field can be declared hash, redact, or omit. The client applies it to each route right before that route commits, so one tracked event can reach one destination with a digest and another without the field.

import { defineEvents } from "events-sdk"
import { z } from "zod"

export const signupEvents = defineEvents({
  "signup.completed": {
    schema: z.object({ email: z.string(), note: z.string(), plan: z.string() }),
    declaredPurposes: ["measurement"],
    fields: {
      email: { classification: "contact", handling: "hash" },
      note: { classification: "free-text", handling: "redact" },
    },
    routes: {
      crm: { requiredPurposes: ["measurement"] },
      productAnalytics: {
        requiredPurposes: ["measurement"],
        fields: { email: "omit" },
      },
    },
  },
})

Tracking { email: " [email protected] ", note: "call me", plan: "pro" } commits this to each route:

| Route | email | note | | --- | --- | --- | | crm | sha256:eb2b6c0d…, the digest of [email protected] | "events-sdk:redacted" | | productAnalytics | absent | "events-sdk:redacted" |

  • A route's fields entry replaces the event's handling for that path on that route. It does not add to it.
  • hash applies Unicode NFC to a string, trims ASCII whitespace from both ends, lowercases it, and writes sha256: followed by 64 hex characters. defineEvents throws config/unhashable-field-path when the schema shows a path can never hold a string. If a non-string value still reaches a hashed path at runtime, that route is dropped with route/field-handling-failed and other routes still commit.
  • redact writes the string events-sdk:redacted whatever the value was. omit removes the field.
  • The hash is unsalted SHA-256. A hashed email can still be personal data, and anyone with a list of candidates can recover it. Use redact or omit when no destination needs to match on the value.

Entry points

| Import | What it gives you | | --- | --- | | events-sdk | defineEvents, createClient, assumed, createCaptureDestination, createCollectorDestination, generateRegistry, serializeRegistry, and EventsConfigurationError | | events-sdk/destinations/posthog | posthog() and posthogServer(), which send events straight to PostHog | | events-sdk/c15t | c15t(), which governs routes by the c15t a page or request already runs | | events-sdk/react | createAnalytics(events), which returns AnalyticsProvider, useAnalytics, useTrackPageview, and useIdentity | | events-sdk/react/c15t | c15t() for React, which binds to the c15t provider rendered above it | | events-sdk/server | createServerCollectorDestination(), the collector destination for server and edge runtimes, plus pageContextFromRequest() and readIdentityCookie() | | events-sdk/inspect | createTraceRecorder() and formatters for a record of every routing decision |

Each entry also exports the types its return values reach, such as EventCatalog, SchemaInput, and JsonValue from events-sdk, so a library that compiles with declaration: true can export a catalog, a client, or the React binding without writing a type annotation.

Send events to a collector with c15t

On a page that loads c15t's script tag, c15t() binds to window.c15t. A collector destination needs a consent provider, because every request carries the decision that allowed it.

import { createClient, createCollectorDestination } from "events-sdk"
import { c15t } from "events-sdk/c15t"
import { events } from "./events.js"

const collector = createCollectorDestination({
  endpoint: "https://collector.example.com",
  publishableKey: "epk_your_publishable_key",
})

export const client = createClient({
  events,
  consent: c15t(),
  destinations: { productAnalytics: collector, salesConversions: collector },
})

An event tracked before the visitor chooses waits in a bounded memory buffer. Accepting replays it with its original event ID, and rejecting purges it.

List every purpose your routes require in c15t's consentCategories, as the React example below does. If you leave one out, the client registers it with c15t when it starts. A visitor who already answered the banner then sees it again, and events needing that purpose wait as route/purpose-pending until they answer. Nothing is lost or wrongly denied, but the second prompt is avoidable.

Send events to PostHog and identify users

posthog() sends events to PostHog's /batch/ endpoint, on the EU host unless you set host. A PostHog destination needs a consent provider, and every event needs an identity, which the client's identity option gives a browser client.

import { assumed, createCaptureDestination, createClient } from "events-sdk"
import { posthog } from "events-sdk/destinations/posthog"
import { z } from "zod"
import { events } from "./events.js"

export const client = createClient({
  events,
  consent: assumed({
    basis: "Contractual necessity; recorded in policy decision PD-142",
    purposes: ["measurement"],
  }),
  destinations: {
    productAnalytics: posthog({ apiKey: "phc_your_project_key" }),
    salesConversions: createCaptureDestination(),
  },
  identity: {
    traits: z.object({ email: z.string(), plan: z.string() }),
  },
})

await client.identify("user_123", { email: "[email protected]", plan: "pro" })
await client.track("order.completed", { orderId: "order_123", revenue: 42 })

identity gives the client an anonymous ID and a session, kept in two first-party cookies only while the identity purpose, measurement unless you set purpose, is allowed. identify, group, and reset never reject, and the schemas you declare check their traits. PostHog receives traits as $set and $group_set with no field handling, so keep a value your catalog would hash, redact, or omit out of them. An event declared requires: "identified" waits in memory until identify runs.

On a server, use posthogServer() and name each event's identity with a subject in track's options, or read the browser's cookies with readIdentityCookie() from events-sdk/server. The queue is memory-only, so flush it before the request ends.

Common properties and page context

import {
  assumed,
  createCaptureDestination,
  createClient,
  defineEvents,
} from "events-sdk"
import { z } from "zod"

const pageEvents = defineEvents({
  "pricing.viewed": {
    schema: z.object({ plan: z.string(), surface: z.string() }),
    declaredPurposes: ["measurement"],
    routes: {
      productAnalytics: {
        requiredPurposes: ["measurement"],
        fields: { "$context.page.referrer": "omit" },
      },
    },
  },
})

const client = createClient({
  events: pageEvents,
  consent: assumed({
    basis: "Contractual necessity; recorded in policy decision PD-142",
    purposes: ["measurement"],
  }),
  context: { page: true },
  destinations: { productAnalytics: createCaptureDestination() },
  properties: { surface: "web" },
})

await client.track("pricing.viewed", { plan: "team" })

properties merges static JSON values into every track call before the schema validates it, so track takes surface as optional. Declare every common key at the top level of every event's schema, or createClient throws config/undeclared-common-property.

context: { page: true } attaches allowlisted page context to each event: the URL and path without the query or fragment, the referrer's origin and path, the utm_* values, the preferred locale, the user agent, and in a browser the viewport size. A route declares handling for $context.page.<field> paths as it does for properties. On a server, pass pageContextFromRequest(request) from events-sdk/server to track as { context: { page } }. Collector destinations do not receive page context, because wire protocol version 1 has no field for it.

React

Import c15t from events-sdk/react/c15t and render AnalyticsProvider inside c15t's provider. ConsentRoot from c15t/next works the same way.

import { ConsentBanner, ConsentDialog, ConsentProvider, hosted } from "c15t/react"
import { createCaptureDestination, createClient } from "events-sdk"
import { createAnalytics } from "events-sdk/react"
import { c15t } from "events-sdk/react/c15t"
import type { ReactNode } from "react"
import { events } from "./events.js"

const client = createClient({
  events,
  consent: c15t(),
  destinations: {
    productAnalytics: createCaptureDestination(),
    salesConversions: createCaptureDestination(),
  },
})

const { AnalyticsProvider, useAnalytics } = createAnalytics(events)

export const App = ({ children }: { children: ReactNode }) => (
  <ConsentProvider
    options={{
      consentCategories: ["necessary", "measurement", "marketing"],
      mode: hosted({ backendURL: "/api/c15t" }),
    }}
  >
    <AnalyticsProvider client={client}>{children}</AnalyticsProvider>
    <ConsentBanner />
    <ConsentDialog />
  </ConsentProvider>
)

export const BuyButton = ({ orderId }: { orderId: string }) => {
  const { track } = useAnalytics()

  return (
    <button
      onClick={() => void track("order.completed", { orderId, revenue: 42 })}
      type="button"
    >
      Buy
    </button>
  )
}

createAnalytics() needs no generic argument. The hooks take their types from the catalog you pass it.

Server

The server destination presents a secret esk_ key. It reads no environment variable itself, so pass the key in. A server has no unload signal, and after() or waitUntil() only extend a request, so flush before the response completes.

import { assumed, createClient } from "events-sdk"
import { createServerCollectorDestination } from "events-sdk/server"
import { events } from "./events.js"

const secretKey = process.env.COLLECTOR_SECRET_KEY

if (secretKey === undefined) {
  throw new Error("Set COLLECTOR_SECRET_KEY to the collector's esk_ key.")
}

const collector = createServerCollectorDestination({
  endpoint: "https://collector.example.com",
  secretKey,
})

const client = createClient({
  events,
  consent: assumed({
    basis: "Contractual necessity; recorded in policy decision PD-142",
    purposes: ["measurement"],
  }),
  destinations: { productAnalytics: collector, salesConversions: collector },
})

export const recordOrder = async (orderId: string, revenue: number) => {
  await client.track("order.completed", { orderId, revenue })
  await collector.flush()
}

To follow the visitor's c15t choice on a server, create one client per request with c15t({ state }) from events-sdk/c15t, where state is what c15t's resolveConsent() returned for that request.

Inspect routing decisions

import { assumed, createCaptureDestination, createClient } from "events-sdk"
import { createTraceRecorder, formatTraceRecords } from "events-sdk/inspect"
import { events } from "./events.js"

const trace = createTraceRecorder()

const client = createClient({
  events,
  consent: assumed({
    basis: "Contractual necessity; recorded in policy decision PD-142",
    purposes: ["measurement"],
  }),
  destinations: {
    productAnalytics: createCaptureDestination(),
    salesConversions: createCaptureDestination(),
  },
  inspect: trace,
})

await client.track("order.completed", { orderId: "order_123", revenue: 42 })

console.log(formatTraceRecords(trace.records()))

A trace record names events, routes, purposes, and reason codes. It never carries a property value. The recorder lives only behind this entry, so a bundle that doesn't import events-sdk/inspect carries none of its code.

Documentation

The package ships documentation that matches the installed version:

  • AGENTS.md lists every topic file, for coding agents working in a project that uses events-sdk.
  • SKILL.md is an agent skill that points at the same files.
  • docs/index.md is the overview, and docs/specs holds the behavioral specifications.

After install they are in node_modules/events-sdk/.

License

Apache-2.0