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

@comprehend/telemetry-browser

v0.2.4

Published

Integration of comprehend.dev with OpenTelemetry in browser environments.

Readme

@comprehend/telemetry-browser

Integration of comprehend.dev in browser environments, for both architectural and product metrics. This builds upon OpenTelemetry for what it provides, and adds some additinal mechanisms for what isn't yet standardized or doesn't fit naturally with OpenTelmetry.

Functionality includes automatic collection of network request telemetry data, collection of custom metrics (configured on comprehend.dev), view tracking, and user flows (for tracking, for instance, signup flows or user behavior in a given area of the application; these are also configured on comprehend.dev).

Installation

npm install @comprehend/telemetry-browser

Peer Dependencies

npm install @opentelemetry/api @opentelemetry/sdk-trace-web @opentelemetry/core @opentelemetry/sdk-metrics

Quick Start

import { ComprehendSDK } from '@comprehend/telemetry-browser';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';

// Initialize the SDK
const sdk = new ComprehendSDK({
    organization: 'your-org-name',
    token: 'your-api-token',
    serviceName: 'web-frontend',
    // serviceNamespace: 'production',  // Optional
    // environment: 'prod',             // Optional
    // debug: true,                     // Optional: enable debug logging
});

// Set up tracing
const provider = new WebTracerProvider({
    spanProcessors: [sdk.getSpanProcessor()]
});
provider.register();

// Set up metrics (optional)
const meterProvider = new MeterProvider({
    readers: [
        new PeriodicExportingMetricReader({
            exporter: sdk.getMetricsExporter(),
            exportIntervalMillis: 30000,
        }),
    ],
});

// Enable automatic instrumentation for browser
registerInstrumentations({
    instrumentations: [
        getWebAutoInstrumentations({
            '@opentelemetry/instrumentation-fetch': {},
            '@opentelemetry/instrumentation-xml-http-request': {},
        }),
    ],
});

Features

Automatic View Tracking

The SDK automatically tracks page navigations by hooking into the History API (pushState, replaceState) and the popstate event. Each navigation creates a new view context with the current URL, enabling per-page telemetry analysis.

View durations reflect the time the user had the page visible — the view context is ended when the tab becomes hidden (via the Page Visibility API) and a new one starts when it becomes visible again. This means idle time in a background tab is not counted. Telemetry from background work (e.g., in-flight requests that complete while the tab is hidden) is still captured under the application context, making it possible to distinguish activity the user was actively watching from activity that happened in the background.

You can optionally provide a viewAttributes function to extract structured data from URLs and attach it to view contexts:

const sdk = new ComprehendSDK({
    organization: 'your-org-name',
    token: 'your-api-token',
    serviceName: 'web-frontend',
    viewAttributes: (url) => {
        const path = new URL(url).pathname;
        const parts = path.split('/').filter(Boolean);
        // e.g. /acme-corp/settings -> { org: 'acme-corp', section: 'settings' }
        return {
            ...(parts[0] ? { org: parts[0] } : {}),
            ...(parts[1] ? { section: parts[1] } : {}),
        };
    },
});

The function is called for every view (initial page load and subsequent navigations). It can return attributes synchronously or as a Promise for async use cases (e.g., looking up a route definition).

URL Redaction

The SDK sends the page URL with the application context and every view. If your URLs can carry secrets, such as one-time codes on an OAuth callback page, provide a redactUrl function to clean them up first:

const sdk = new ComprehendSDK({
    organization: 'your-org-name',
    token: 'your-api-token',
    serviceName: 'web-frontend',
    redactUrl: (url) => {
        const parsed = new URL(url);
        parsed.searchParams.delete('code');
        parsed.searchParams.delete('state');
        return parsed.toString();
    },
});

viewAttributes receives the redacted URL too.

User Flow Context

Track user flows (e.g., checkout, onboarding, account setup) to correlate telemetry with what the user is trying to accomplish:

// Start a user flow
sdk.startUserFlow('checkout', { cartSize: 3 });

// Start a session-persisted user flow (survives page reloads)
sdk.startUserFlow('onboarding', { plan: 'pro' }, 'session');

// End the current user flow
sdk.endUserFlow();

The user flow ID and attributes are to be defined in the comprehend.dev product document. Actions taken on the UI are recorded as custom metrics, and correlated automatically with the ongoing user flow.

Session-persisted user flows are stored in sessionStorage and automatically resumed when the SDK initializes. This is not the default, but is useful for tracking flows where the user has to leave the application for some time, for example to complete an OAuth flow in a third party system.

Custom Metrics

The SDK supports server-driven custom metric collection. Custom metric specifications are received from comprehend.dev and automatically applied to both the span processor (for span-based observations) and the metrics exporter (for timeseries/cumulative metrics).

Trace Spans

Every span processed by the SDK is reported as a trace span, enabling distributed trace visualization.

Browser Attributes

The SDK automatically collects browser attributes per OpenTelemetry semantic conventions:

  • user_agent.original - The full user agent string
  • browser.language - The browser's language setting
  • browser.platform - The platform (via navigator.userAgentData)
  • browser.mobile - Whether the browser is on a mobile device
  • browser.brands - Browser brand information

What it Tracks

  • Network Requests: HTTP calls made via fetch() and XMLHttpRequest
  • Service Discovery: Identifies your browser application as a service
  • Request Metrics: Duration, status codes, request/response sizes
  • Error Information: Captures and reports network errors
  • Trace Spans: Full distributed tracing support with span/trace IDs
  • Custom Observations: Server-driven span matching for custom metrics
  • View Navigation: Automatic tracking of page navigations
  • User Flow Context: User flow correlation

API Reference

ComprehendSDK

const sdk = new ComprehendSDK({
    organization: string;          // Your comprehend.dev organization name
    token: string;                 // Your API token
    serviceName: string;           // Name for your browser application
    serviceNamespace?: string;     // Optional service namespace
    environment?: string;          // Optional deployment environment
    debug?: boolean | ((message: string) => void); // Debug logging
    viewAttributes?: (url: string) => Record<string, AttributeType> | Promise<Record<string, AttributeType>>;
    redactUrl?: (url: string) => string; // Clean the page URL before it is sent
});

sdk.getSpanProcessor();     // Returns a SpanProcessor for OpenTelemetry
sdk.getMetricsExporter();   // Returns a PushMetricExporter for OpenTelemetry

sdk.startUserFlow(userFlowId: string, attributes?: Record<string, AttributeType>, lifetime?: 'session');
sdk.endUserFlow();

await sdk.shutdown();       // Clean shutdown: ends contexts, closes connection

Debug Mode

// Boolean debug (logs to console)
const sdk = new ComprehendSDK({
    organization: 'my-org',
    token: 'token-123',
    serviceName: 'my-app',
    debug: true
});

// Custom debug function
const sdk = new ComprehendSDK({
    organization: 'my-org',
    token: 'token-123',
    serviceName: 'my-app',
    debug: (message) => console.log('[Telemetry]', message)
});

Browser Compatibility

This package supports modern browsers with:

  • ECMAScript 2022 features
  • WebSocket API
  • crypto.randomUUID() support
  • Fetch API and XMLHttpRequest

Security

  • Only architectural patterns and performance metrics are collected
  • No application data or personal information is transmitted

TypeScript Support

This package includes full TypeScript definitions and supports TypeScript projects out of the box.

License

LicenseRef-Proprietary-Audit

Support

For support and questions, visit comprehend.dev or check the documentation.