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

@teogoulois/analytics-sdk

v0.1.0

Published

One typed analytics API over PostHog, Umami, and custom providers, with validation, redaction, consent, and routing.

Readme

@teogoulois/analytics-sdk

One TypeScript API over PostHog, Umami, and custom analytics providers. Define events once, then apply validation, redaction, consent, and routing before adapters send them. Adapters declare capabilities and expose their native clients for provider-specific work.

Install

Install the SDK and, for schemas beyond the built-in migration helpers, a Standard Schema validator:

pnpm add @teogoulois/analytics-sdk zod

Install the optional peers for the subpaths you use:

pnpm add posthog-js       # @teogoulois/analytics-sdk/posthog
pnpm add posthog-node     # @teogoulois/analytics-sdk/posthog-node
pnpm add @orpc/server@^1.16.0  # @teogoulois/analytics-sdk/orpc (oRPC 1.x)

@teogoulois/analytics-sdk/umami loads a browser script. @teogoulois/analytics-sdk/umami-node sends HTTP requests with fetch, with no dependencies or provider package. @teogoulois/analytics-sdk/memory needs no provider package. PostHog SDKs load through dynamic imports in their own subpaths; the core never imports them. The oRPC subpath uses only types from its optional peer.

Server quick start

PostHog Node requires a distinctId on every event and page view. Without it, that adapter drops the call and reports an adapter error. In serverless code, serverless: true sets flushAt: 1 and flushInterval: 0; await flush() before the invocation ends.

import { z } from "zod";
import { createAnalytics, defineEvents } from "@teogoulois/analytics-sdk";
import { posthogNode } from "@teogoulois/analytics-sdk/posthog-node";

const events = defineEvents({
  invoice_sent: z.object({ amount_bucket: z.enum(["<100", "100-1k", ">1k"]) }),
});
const analytics = createAnalytics({
  events,
  adapters: [posthogNode({ token: process.env.POSTHOG_TOKEN ?? "", serverless: true })],
  context: { surface: "api", environment: "production" },
});

void analytics.track("invoice_sent", { amount_bucket: "100-1k" }, { distinctId: "user-123" });
await analytics.flush();

flush() waits for all accepted track, page, identify, reset, and consent calls, including asynchronous schema validation, before flushing adapters. You can start tracking without awaiting it and then await flush(). Calls started while it is draining are also awaited. Neither flush() nor shutdown() rejects.

Use shutdown() during shutdown of a long-lived Node process. It drains accepted calls and any running flush before closing adapters once. Repeated calls share the same promise. New calls, including context and consent changes, are dropped as soon as shutdown starts. Missing credentials make an adapter inert and report one init error when first used. Adapters initialize lazily; enabled: false never initializes them.

Server-side Umami

Use umamiNode from Node, Electron's main process, or another runtime with fetch. hostUrl, websiteId, and hostname are required; a missing or blank value makes the adapter inert and reports exactly one init error. The adapter posts JSON to ${hostUrl}/api/send, without authentication.

import { createAnalytics } from "@teogoulois/analytics-sdk";
import { posthogNode } from "@teogoulois/analytics-sdk/posthog-node";
import { umamiNode } from "@teogoulois/analytics-sdk/umami-node";
import { events } from "./events";

const analytics = createAnalytics({
  events,
  adapters: [
    umamiNode({
      hostUrl: "https://analytics.teogoulois.com",
      websiteId: "website-id",
      hostname: "desktop.tippo.app",
    }),
    posthogNode({ token: process.env.POSTHOG_TOKEN ?? "" }),
  ],
  routes: {
    default: ["posthog"],
    page: ["umami"],
    events: { app_active: ["umami"] },
  },
  context: { surface: "desktop", appVersion: "1.4.0" },
});

await analytics.track("app_active", {}, { distinctId: "install-123", context: { surface: "cli" } });
await analytics.flush();

Pair @teogoulois/analytics-sdk/umami on the landing page with @teogoulois/analytics-sdk/umami-node in the app's main process. Both adapters are named "umami", so the same routing rules work in each runtime. Use one per analytics instance; adapter names must be unique. Route basic stats to Umami and detailed product events to PostHog. Choose the website ID and hostname for each surface in your application.

Options: hostUrl: string, websiteId: string, hostname: string, url?: string (default "/"), userAgent?: string, language?: string, screen?: string, timeoutMs?: number (default 10_000), fetch?: typeof fetch, and sendDistinctId?: boolean (default true). The configured URL is sanitized with the default URL rules; explicit page URLs use the core's configured rules. raw.umami exposes { config, send(payload) } for typed provider-specific calls; raw calls bypass the pipeline and can reject.

Umami requires a proper User-Agent. The fallback is a browser-shaped desktop UA, which avoids its bot filter but produces generic browser/OS statistics. Apps should pass their real UA; in Electron, use session.defaultSession.getUserAgent() after Electron is ready. The adapter sends Content-Type: application/json and User-Agent. Umami's collection handler uses isbot unless DISABLE_BOT_CHECK is set, and returns HTTP 200 with {"beep":"boop"} for ignored traffic. The adapter detects that response and throws, so the core reports an adapter error. HTTP failures, network errors, and timeouts are also isolated adapter errors. flush() waits for in-flight requests without rejecting; shutdown() does the same. Neither retries failed sends nor persists an outbox.

Events send name and data; page views omit name and send the sanitized URL, title, referrer, and context data. Distinct IDs use payload.id (Umami limits it to 50 characters). sendDistinctId: false omits IDs from events, pages, and identify calls. Identify sends type: "identify" with the ID and redacted traits in payload.data, following the tracker identify mapping. Identity is per call and is never retained for subsequent users; pass distinctId on each event/page.

Current Umami documents timestamp overrides as Unix seconds in payload.timestamp. The server adapter converts track/page timestamps with Math.floor(date.getTime() / 1000), preserving buffered/outbox event times to second precision. Identify uses receive time. Check timestamp support on older self-hosted versions before relying on historical dates; browser adapter calls do not forward SDK timestamps.

Browser setup

Import the registry from events.ts below. This routes page views to Umami, product events to PostHog, and page_ready to Umami.

import { createAnalytics } from "@teogoulois/analytics-sdk";
import { posthog } from "@teogoulois/analytics-sdk/posthog";
import { umami } from "@teogoulois/analytics-sdk/umami";
import { events } from "./events";

const analytics = createAnalytics({
  events,
  adapters: [umami({ websiteId: "website-id" }), posthog({ token: "posthog-token" })],
  routes: {
    default: ["posthog"],
    page: ["umami"],
    events: { page_ready: ["umami"] },
  },
  context: { surface: "web", appVersion: "1.4.0" },
});

await analytics.page({
  url: window.location.href,
  title: document.title,
  referrer: document.referrer,
});
await analytics.track("page_ready");
await analytics.track("checkout_completed", { plan: "pro", invoice_id: "invoice-123" });

Routes accept configured adapter names and registered event names. default handles events without an override, page handles page views, and events overrides individual events. An empty route sends nowhere.

Browser adapters are inert during SSR. client reuses an existing PostHog instance without initializing or reconfiguring it. injectScript: false waits for an Umami tracker installed by your application. Configure pageview collection yourself when reusing either provider.

PostHog clients and native events

posthogNode({ client }) accepts the exported PostHogNodeClient structural interface: capture, identify, flush, and shutdown. Compatible posthog-node 5.x clients can be reused across package versions without a cast. Browser posthog({ client }) similarly accepts PostHogBrowserClient, containing capture, identity, reset, consent, register, and unregister methods. Both adapters expose these minimal types through raw.posthog; keep your original client reference for other provider-specific methods.

After lazy initialization, the browser adapter registers the full base context as PostHog super properties, so native $exception and $pageleave events carry it too. setContext() updates those properties and unregisters removed keys, preserving unrelated provider properties. Context is restored after reset(). Per-call context overrides apply only to SDK calls. Events captured by PostHog itself bypass SDK validation, redaction, routing, and timestamps; configure native collection in PostHog.

Page views

The SDK never captures page views by itself. Call analytics.page() from your router or page lifecycle. It does not fill page fields from the browser; Umami can use its tracker defaults when fields are omitted.

Browser adapters disable native page views by default. With autoPageviews: true, the provider handles page views and the adapter's page() does nothing. PostHog sets capture_pageview; Umami sets data-auto-track. Umami's false setting disables its automatic tracker initialization, including automatic click/path tracking, and allows manual tracker calls. See the Umami configuration docs.

PostHog Node accepts page views with { distinctId } as the second argument. Browser Umami preserves documented tracker defaults and overrides url, title, referrer, and data; it does not forward SDK distinctId, properties, or timestamp fields.

Event registry

Save this as events.ts. defineEvents accepts Standard Schema validators and preserves their input types. Events with an empty-object schema, such as app_active, can omit properties.

import { z } from "zod";
import { defineEvents } from "@teogoulois/analytics-sdk";

export const events = defineEvents({
  app_active: z.object({}),
  page_ready: z.object({}),
  checkout_completed: z.object({
    plan: z.enum(["free", "pro"]),
    invoice_id: z.string(),
  }),
});

Unknown names and invalid properties fail type checking. Untyped calls are also checked at runtime and dropped with a validate error. Properties whose value is undefined are omitted after schema validation and before shape rules, including the property-count limit. Other values must be scalars. Event properties must be a flat object with at most 20 scalar values (string, number, boolean, or null). Strings are limited to 120 characters. Violations drop the whole event; event properties are never truncated. limits can override these defaults.

track() and page() default to the time of the call, captured before validation or adapter initialization. An explicit timestamp preserves the original time of a buffered event.

context is merged after event properties, followed by per-call TrackOptions.context, so event props cannot override configured context keys. Both context layers map appVersion to app_version; per-call context overrides the base for track and page without changing later calls. Undefined per-call values are ignored. Context is added to events and page views, never to identify traits. Both base and per-call context are trusted application configuration and bypass event validation and redaction; keep it short and free of personal data.

Migrating existing event lists and changing context

defineEventNames(names) keeps names from a readonly tuple while allowing free-form scalar properties. Spread its registry into defineEvents alongside stricter schemas. anyProperties() provides the same schema for a single event: it accepts plain objects (or undefined as {}); the core still applies shape rules, limits, and redaction. Its TypeScript input is Record<string, Scalar | undefined>. Unknown event names and nested properties remain compile errors.

import { z } from "zod";
import {
  anyProperties,
  createAnalytics,
  defineEventNames,
  defineEvents,
} from "@teogoulois/analytics-sdk";
import { memory } from "@teogoulois/analytics-sdk/memory";

const legacyNames = ["install", "activation", "download_clicked"] as const;
const events = defineEvents({
  ...defineEventNames(legacyNames),
  details: anyProperties(),
  checkout: z.object({ plan: z.enum(["free", "pro"]) }),
});
const analytics = createAnalytics({
  events,
  adapters: [memory()],
  context: { surface: "desktop", locale: "fr", appVersion: "1.4.0" },
});

await analytics.track(
  "activation",
  { version: "1.4.0", optional: undefined },
  { context: { surface: "mcp" } },
);
analytics.setContext({ locale: "en", appVersion: "1.4.1" });
await analytics.page({ url: "/home" }, { context: { surface: "web" } });
analytics.setContext({ locale: undefined });

setContext(patch: Partial<AnalyticsContext>): void updates the base context for later calls: add or replace values, and pass undefined to remove a key. Calls already waiting on async schema validation retain their original context. Standard and extra context values remain scalar-only. Context does not go into identify traits.

Privacy and redaction

The event pipeline runs in this order:

  1. Drop disabled or opted-out calls.
  2. Check the registered name and run Standard Schema validation.
  3. Omit undefined properties, then enforce the flat-object, scalar-value, key-count, and string-length rules.
  4. Replace sensitive property values with "[redacted]".
  5. Merge base context, then per-call context.
  6. Select routes and isolate each adapter call.

Default exact redaction keys: text, content, message, body, email, name, firstname, lastname, phone, address, ip. Keys containing password, secret, token, apikey, authorization, cookie, or session also match. Default matching ignores case, hyphens, and underscores.

import { createAnalytics } from "@teogoulois/analytics-sdk";
import { memory } from "@teogoulois/analytics-sdk/memory";
import { events } from "./events";

const analytics = createAnalytics({
  events,
  adapters: [memory()],
  redact: { keys: ["request_id", /^private_/] },
});

await analytics.track("app_active");

Custom strings match case-insensitively; regular expressions are also accepted. redact: { replace: true, keys: [...] } replaces the defaults. redact: { allow: [...] } exempts keys that a rule would otherwise catch, such as an installToken that must reach PostHog to tie a download to an install; allowed keys also stay in page URLs.

Page url and referrer query parameters use the same key rules. Sensitive parameters are removed, other parameters remain, and hashes are dropped. Absolute and relative URLs are supported. Unparsable URLs lose their entire query. URLs are capped at 2,000 characters. sanitizeUrl() is exported from the core. Umami's fallback tracker URLs use the default sanitization rules; pass explicit page fields to apply custom URL rules.

These rules cover data passed through this SDK. Native provider capture, automatic page views, and calls through raw use provider behavior and bypass the shared pipeline. Configure those features separately. Avoid collecting names, email addresses, tokens, content, or free text in analytics properties.

Consent

The application owns consent persistence. Pass the stored state when creating analytics:

import { createAnalytics } from "@teogoulois/analytics-sdk";
import { posthog } from "@teogoulois/analytics-sdk/posthog";
import { events } from "./events";

const storedConsent = window.localStorage.getItem("analytics-consent");
const analytics = createAnalytics({
  events,
  adapters: [posthog({ token: "posthog-token" })],
  optedOut: storedConsent !== "granted",
});

await analytics.optOut();
await analytics.optIn();
analytics.isOptedOut();

optOut() changes state immediately and drops later events, page views, and identify calls. They are never replayed after optIn(). Consent is not retroactive: work already accepted can still complete. Both methods return resolving promises so you can await provider consent operations. isOptedOut() reads the state synchronously. The SDK does not save consent or change an independently configured tracker.

Testing with memory

The memory adapter records calls without a provider SDK:

import { expect } from "vitest";
import { createAnalytics } from "@teogoulois/analytics-sdk";
import { memory } from "@teogoulois/analytics-sdk/memory";
import { events } from "./events";

const adapter = memory();
const analytics = createAnalytics({ events, adapters: [adapter] });

await analytics.track("app_active");
expect(adapter.events[0]?.name).toBe("app_active");
adapter.clear();

Use names such as memory("product") to test routes with several adapters.

oRPC middleware

For oRPC 1.x, os.$meta() types the event and its properties. eventProperties receives the validated input and successful handler output. Type the context selector to declare the context it needs.

import { os } from "@orpc/server";
import { z } from "zod";
import { createAnalytics } from "@teogoulois/analytics-sdk";
import { analyticsMiddleware, type AnalyticsMeta } from "@teogoulois/analytics-sdk/orpc";
import { posthogNode } from "@teogoulois/analytics-sdk/posthog-node";
import { events } from "./events";

type ProcedureContext = { distinctId?: string };
const analytics = createAnalytics({
  events,
  adapters: [posthogNode({ token: process.env.POSTHOG_TOKEN ?? "" })],
});

export const procedure = os
  .$context<ProcedureContext>()
  .$meta<AnalyticsMeta<typeof events, { plan: "free" | "pro" }, { invoiceId: string }>>({
    event: "checkout_completed",
    eventProperties: (input, output) => ({ plan: input.plan, invoice_id: output.invoiceId }),
  })
  .input(z.object({ plan: z.enum(["free", "pro"]) }))
  .use(
    analyticsMiddleware(analytics, {
      distinctId: (context: ProcedureContext) => context.distinctId,
    }),
  )
  .handler(async ({ input }) => ({ invoiceId: `invoice-${input.plan}` }));

Tracking starts after a successful handler and does not delay the response. Failed handlers and procedures without event metadata are ignored. In serverless code, await flush() after the handler completes and before the invocation ends. It drains tracking already started by the middleware; it does not wait for handlers that are still running.

Writing an adapter

defineAdapter preserves the literal name and raw client type:

import { defineAdapter, type Properties } from "@teogoulois/analytics-sdk";

interface AcmeClient {
  setContext(properties: Properties): void;
  capture(name: string, properties: Properties): void;
  flush(): Promise<void>;
}

export function acme(client: AcmeClient) {
  return defineAdapter<"acme", AcmeClient>({
    name: "acme",
    capabilities: { page: false, identify: false, reset: false, flush: true, optOut: false },
    raw: client,
    setContext(properties) {
      client.setContext(properties);
    },
    track(event) {
      client.capture(event.name, event.properties);
    },
    async flush() {
      await client.flush();
    },
  });
}

Names must be unique within one analytics instance. track is required; init, setContext, page, identify, reset, optOut, optIn, flush, and shutdown are optional. Declare capabilities accurately so unsupported operations are skipped.

Use a dynamic import in init to load an optional provider SDK. On missing credentials or fatal setup failure, become inert and report one error through ctx.onError. raw may be a getter returning undefined until initialization.

The optional synchronous setContext(properties: Properties): void hook receives a fresh full context snapshot after init resolves and after every later analytics.setContext() call. Before initialization, patches update the snapshot without initializing the adapter. Undefined values are removed and appVersion becomes app_version. Use this hook to synchronize provider-generated events; remove previously registered keys absent from the new snapshot. Hook throws are isolated and reported as adapter errors. Per-call context is not sent to the hook.

Calls start independently for each adapter. Operational analytics methods return promises that catch adapter throws and rejections and report them through onError; a slow adapter can still keep an awaited call pending. The oRPC middleware deliberately does not await tracking.

Development

Requires Node 22 or newer and pnpm 10.

pnpm install --frozen-lockfile
pnpm build
pnpm typecheck
pnpm test
pnpm lint
pnpm format:check

The stack is Turborepo, pnpm, TypeScript 7 (strict), tsdown, Vitest 5, oxlint, and oxfmt, with no stack deviations. happy-dom supplies browser APIs for adapter tests; providers are mocked and no credentials are needed. The core has no runtime dependencies. Standard Schema types are fully inlined in declarations, so @standard-schema/spec remains a development dependency. Provider SDKs and oRPC are optional peers and development dependencies for local checks.

Every TypeScript snippet above matches a file in packages/analytics-sdk/examples/. Those files compile through the public package exports, and a test detects README drift. pnpm typecheck includes src, tests, and examples, so unused @ts-expect-error assertions fail. Run pnpm format to apply formatting.