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

@billdog.io/core

v1.2.0-beta.1

Published

Platform-agnostic core for BillDog SDK

Readme

@billdog.io/core

Platform-agnostic core of the BillDog web SDK. Every statement below is taken from src/BillDog.ts, src/OfferingManager.ts, src/deviceProof.ts, src/serverErrors.ts and src/types/index.ts.

Overview

BillDogCore holds the configuration, the API client, the offering, wall, customer and purchase managers, and the event bus. Platform packages extend it: @billdog.io/web adds a purchase delegate (web checkout), storage and presenters.

Installation

npm install @billdog.io/core

This package is usually installed through a platform package:

  • @billdog.io/web for browsers
  • @billdog.io/react-native / @billdog.io/expo for React Native (native SDKs underneath; they do not extend this class)

Configure

import { BillDogCore } from '@billdog.io/core';

const sdk = new BillDogCore();

sdk.configure({
  apiKey: 'bd_public_live_xxxxxxxx',   // a PUBLIC key; the prefix selects the environment
  enableLogging: true,
});

The constructor takes no arguments; configure(config) sets the key.

Device proof (automatic)

On first use the SDK generates the install's anonymous id ($BillDogAnonymousID:…) and a device key (bdk_ + 43 base64url characters from 32 random bytes), stores the pair through the configured storage (config.storage, else localStorage where one exists), and sends both on every request in the X-BillDog-Device and X-BillDog-Device-Key headers. The key is never logged and never placed in a body or a URL. Purchases and customer reads are attributed to the proven device customer; an app_user_id in a request body is a label, not a proof.

  • peekDeviceProof(): DeviceProof | null — the current pair without generating one.
  • rotateDeviceProof(): Promise<DeviceProof> — abandon the guest identity and start a new one. For a host reacting to PROOF_INVALID with reason unclaimable or revoked (shouldRotateDeviceProof(err)). Whatever the old guest owned stays with the old id; the SDK never rotates on its own.

There is ONE device identity per API key per page (JS realm): DeviceIdentityStore.for(apiKey, storage?). Core, web, analytics, notifications, surveys, A/B testing, virtual currency and session replay all resolve the same instance (the registry lives on globalThis, so a second bundled copy of core shares it too), so concurrent packages mint one id and one key. The first registration's storage wins; a later caller passing a different storage adapter gets the registered identity and a console warning. onChange(listener) reports a new pair (first resolution, rotation, an id another tab rotated). A stored id that is not $BillDogAnonymousID: + 32 hex (an old anon_… id) is replaced on load by a new conforming id and key.

The pair (and the BillDog Auth session) is sent ONLY to BillDog's API (https://api.billdog.io, and its fallback https://direct.billdog.io; isBillDogApiUrl). A base URL, projectUrl, apiBaseUrl or replay endpoint on any other origin is called without them, with a one-time console warning.

Without a DeviceProofStorage (Node / SSR with no host storage) the pair is kept in memory for the process: ONE guest for every visitor that process renders. Do not rely on the device proof when rendering on behalf of visitors.

Offerings (headless)

import { PlacementNotFoundError, BillDogApiError } from '@billdog.io/core';

// The project's default offering read: no placement identifier is sent.
const offerings = await sdk.getOfferings();          // Offering[] — [] when nothing was selected
const current = await sdk.getCurrentOffering();      // Offering | null — the server's selection

// One placement.
try {
  const result = await sdk.getOffering('onboarding'); // OfferingResult
  if (result.offering && !result.presentation.holdout && !result.presentation.withheld) {
    show(result.offering);
  }
} catch (e) {
  if (e instanceof PlacementNotFoundError) { /* the placement does not exist (404 PLACEMENT_NOT_FOUND) */ }
  else if (e instanceof BillDogApiError) { /* e.code is the wire code: PROOF_REQUIRED, PROOF_INVALID, … */ }
}

OfferingResult is { offering, offerings, placement, presentation, experiment, campaign, entitlements }:

  • offering is THE offering the server selected for this caller, or null. null is an answer: show nothing, never pick an entry of offerings in its place.
  • presentation is { gated, holdout, withheld, withheldReason, requiredEntitlement, interpretable }. gated: reaching this placement requires access (the app owns the gate); requiredEntitlement names the entitlement it requires, or is null when any active entitlement grants access. holdout: present nothing. withheld with withheldReason (audience_excluded, holdout, …): offering is null because this caller was excluded.
  • entitlements is the project's entitlement catalogue (snake_case wire objects), not the caller's grants.
  • Offering is { id, identifier, displayName, description, isCurrent, isDefault, packages, metadata }; each package is { identifier, packageType, product } and product.identifier is the store SKU for the platform (stripe_price_id on web). There is no paywall on an offering: a headless read never returns a wall.

getOffering never substitutes the default offering for the one asked for.

Typed errors

Every refusal is thrown as BillDogApiError with the server's wire code, status, reason and details:

| code | Status | Meaning | |---|---|---| | PROOF_REQUIRED | 403 | The operation needs a proof the request lacks | | PROOF_INVALID | 401 | A presented proof failed (reason: signature, absent, revoked, unclaimable, …) | | REAUTH_REQUIRED | 403 | The session's sign-in is too old for a sensitive operation | | ACCESS_DENIED | 403 | reason: 'target_mismatch' — the body names another customer | | PURCHASE_OWNER_CONFLICT | 409 | The store purchase belongs to another customer | | PLACEMENT_NOT_FOUND | 404 | Thrown as PlacementNotFoundError | | PLACEMENT_ACCESS_WITHHELD | 403 | Thrown as PlacementAccessWithheldError (hosted mode) |

BILLDOG_AUTHORITY_ERROR_CODES, toAuthorityError(body) and shouldRotateDeviceProof(err) are exported for hosts that handle these themselves.

Hosted walls

const wall = await sdk.fetchPaywall('onboarding'); // PaywallConfiguration | null

Customer info and entitlements

const customer = await sdk.getCustomerInfo('user-123');
const hasPremium = sdk.hasEntitlement('premium');   // from the cached customer info

hasEntitlement answers synchronously from the customer last read, and the server is authoritative for access. To gate an action, await sdk.checkEntitlement('premium'): it reads first when the cache is older than five minutes (checkEntitlement(id, 0) reads now), where hasEntitlement would answer the click that finds the cache stale from the stale cache. In a browser the SDK keeps that answer current: whenever the page is used again (the tab becomes visible, its window gains focus, it is restored from the back/forward cache, the network comes back, or the person clicks or types), it re-reads the customer once the last read is five minutes old (on the wall clock or a monotonic one, whichever is larger: a clock set back or a machine asleep does not delay it), so a refund, an expiry or a revoke reaches a tab left open for hours. A page nobody uses reads nothing, and only a customer or guest the app has read (logIn, getCustomerInfo, checkEntitlement, refreshEntitlementsIfStale) is refreshed: without a BillDog Auth session a read answers the device's own customer and creates it on the first read, so the SDK never makes that read on its own. After a failed read, these automatic reads (and checkEntitlement) wait 30 seconds, doubling up to five minutes; the network coming back ends the wait. Every failure, a 401 or 403 included, keeps the cached access (as RevenueCat does): it changes only when a read answers otherwise or the identity changes. Call refreshEntitlementsIfStale(maxAgeMs?) where the page knows access may have changed, e.g. back from the billing portal: refreshEntitlementsIfStale(0) answers from a read issued after the call, and it is never held back.

entitlements_changed is published when access changes: a customer read (by the host, a purchase or restore confirmation, or a refresh) whose active entitlements differ from what subscribers were last told, every setEntitlements push, and [] at logOut(). On a switch to another customer, subscribers keep the previous customer's access until the new one's first read answers (the SDK reads them unless the caller does), then hear the new access only if it differs ([] if they hold none or cannot be read), so a log-in does not flash access off. Reads that land out of order never undo a newer answer: a read issued before another read or a push that is already cached is not cached. With BillDog Auth attached (auth.attachTo(sdk.apiClient), or configure({ auth }) on @billdog.io/web), the session decides whose customer the server answers, so the cache follows it as an identity change: a sign-in reads the person (no flash for the same access), a sign-out withdraws their access at once, and a token that rotates for the same person changes nothing. A session whose access token has expired but not yet been renewed is still signed in: requests wait for the renewal (up to 10 seconds) rather than going out as the device's. entitlements_changed reports changes, not the current state: a subscriber added later reads hasEntitlement (or await checkEntitlement) for where things stand.

Purchases

purchaseProduct(productId): Promise<boolean> and restorePurchases(): Promise<boolean> run through the platform's PurchaseDelegate (config.purchaseAdapter). On the web the delegate starts a web checkout and true means the visitor was handed to it, not that they paid.

restorePurchases() resolves true when the restore restored something, false when it restored nothing or could not run here (no delegate, a restricted customer, the customer changed while it ran), and throws a server refusal as BillDogApiError. restore(): Promise<RestoreResult> runs the same restore and answers what it did, without throwing:

const result = await sdk.restore();
if (result.type === 'restored') {
  result.items;         // RestoredPurchase[]: { productId, transactionId }, possibly empty
  result.customerInfo;  // the customer read after the restore (also cached), or null
} else {
  result.error.code;    // server code, or NOT_CONFIGURED | NO_CUSTOMER | RESTORE_FAILED | ACCESS_RESTRICTED | IDENTITY_CHANGED
}

A PurchaseDelegate keeps restorePurchases(): Promise<boolean> (true = something was restored) and may add an optional typed restore(): Promise<DelegateRestoreResult> ({ type: 'restored', items } / { type: 'failed', error }), which BillDog prefers when present. Without it, a true restores without naming items.

A PurchaseAdapter's onEntitlementsChange pushes are ignored while its setIdentity switches the vendor to another customer; when the switch resolves, BillDog reads getEntitlements() once (implement it if your vendor pushes during its login). A failed switch is retried on the next setCustomerId or logOut. Calling setCustomerId again with the same customer does not pause pushes. A push applies at once but is not a server read: the next stale refresh replaces it with the server's answer.

The cached customer (hasEntitlement) belongs to the identity the SDK acts for: a customer read issued before a logOut() or a switch to another customer, or for an id other than the current one, is never cached. An identity change clears only identity-scoped caches (walls, offerings, the customer, surveys), never consent, the analytics opt-out, the device identity or the SDK config.

Events

await sdk.trackEvent('level_completed', { level: 12 });

// Impressions of a paywall the host drew itself. No paywall_id is sent.
sdk.trackPaywallPresented(result.offering, result.placement);
sdk.trackPaywallDismissed(result.offering, result.placement);

Modules

sdk.configure({ apiKey: 'bd_public_live_xxxxxxxx', modules: [Analytics] });
// or after configuration
sdk.use(Analytics);

Account deletion

Account deletion is deleteAccount() on @billdog.io/auth; it needs a BillDog Auth session. See that package.

License

MIT