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

@bayonai/offline

v0.15.1

Published

Reusable offline read-cache, pending-write, and silent recovery primitives.

Readme

@bayonai/offline

Reusable offline read-cache, pending-write, and silent browser-recovery primitives.

This package owns generic browser and memory storage behavior. Host apps own their domain records, remote APIs, cache prefixes, database names, and sync functions.

The package uses idb internally for IndexedDB access, but consumers should use the exported cache and pending-write APIs rather than depending on the storage implementation.

Install

pnpm add @bayonai/offline

Read Cache

import {
  createBrowserReadCache,
  createReadCacheKey,
  loadReadCacheResource,
  pruneReadCache,
  type ReadCachePolicy,
} from "@bayonai/offline";

const policy: ReadCachePolicy = {
  freshForMs: 30_000,
  retainForMs: 7 * 24 * 60 * 60_000,
  refreshFailure: "use-retained",
};

const cache = createBrowserReadCache({
  databaseName: "my-app:v1",
  storeName: "read-cache",
});

const key = createReadCacheKey({
  namespace: "projects",
  params: { limit: 20 },
  prefix: "my-app:v1",
  scope: "user-1",
});

const projects = await loadReadCacheResource({
  cache,
  key,
  loadFresh: () => fetchProjects(),
  onOutcome: (outcome) => telemetry.record("offline-read", { outcome }),
  policy,
  onUpdate: ({ data, status, fromCache }) => {
    renderProjects(data, { fromCache, status });
  },
});

freshForMs controls how long a cached value can avoid a remote read. retainForMs independently controls how long it can be shown as an offline fallback. A stale-but-retained value is emitted immediately and revalidated; an expired value is not emitted and cannot mask a loader failure. The status is fresh, stale, or miss: a stale update is retained data while refreshing or after a failed refresh, and a miss is a successful loader result with no retained cache. Successful remote results are fresh when replacing stale data and miss when there was no usable retained data.

onOutcome emits only a fixed event name (fresh-hit, stale-hit, cache-miss, forced-refresh, loader-success, or loader-failure). It never includes cache keys, user identifiers, payloads, or error messages. Callback exceptions are logged and isolated from the read.

When refresh fails, refreshFailure: "use-retained" returns retained data with status: "stale" and the error; "throw" propagates the loader error. An opt-in callback can classify the original failure as "use-retained", "throw", or "retire". Retire propagates the original failure and conditionally removes the captured snapshot; a later confirmation is preserved. Built-in memory and IndexedDB drivers support atomic snapshot comparison. loadReadCacheResource({ deliveryPolicy: "cache-current", ... }) opts into awaiting an atomic commit receipt before presenting the canonical retained cache snapshot. Canonical updates carry cache-hit provenance and their stored age, including when this call wrote that snapshot. The returned promise still settles with this call's source result. A lost ownership comparison may adopt another instance's eligible confirmation; local invalidation suppresses delivery. This fences confirmations committed before the comparison, not future writes or cross-tab notifications. The default immediate policy keeps nonblocking writes. With requireSource, only the successfully committed source result can be presented as source-confirmed; a lost ownership comparison suppresses delivery. Opted-in presentation callback errors are logged independently of source success. Custom caches must implement commitIfVersion, returning { written, version } with the generation captured inside the atomic commit after its own invalidation. Built-in caches require the driver's atomic setIf for this mode. Missing atomic support or storage failure logs an error and suppresses uncertain presentation. Custom adapters must implement deleteIfVersion with equivalent atomic ownership checks; without it, retirement is logged and cannot be guaranteed. New envelopes carry an opaque snapshot identifier. Existing version-one envelopes remain readable; legacy comparison is limited to serializable values and cannot distinguish identical writes by older, identifier-unaware clients. This also applies to forced refresh. Set forceFresh: true on loadReadCacheResource or readThroughCache to bypass freshness, retain eligible data as the failure fallback, and advance the cache generation so an older in-flight load cannot overwrite the refresh. readThroughCache returns the status field alongside its existing fromCache, stale, and error fields.

Set includeProvenance: true to receive cache-hit, source-confirmed, or retained-fallback provenance. Cache-derived results include their original savedAt; fallback also carries originalError without normalizing it. Layered adapters may use loadFreshResult to pass a provenance-bearing readThroughCache result. Cached and fallback values from an inner layer are not persisted as fresh outer confirmations. requireSource: true rejects cached or fallback results and preserves a fallback's original failure. The host still owns authorization, account scoping and retention durations. Source confirmations include confirmedAt when provenance is requested; the built-in cache preserves that time on outer writes. Custom adapters may implement setIfVersionAt to preserve it. Without that capability, layered confirmations are delivered but not persisted by the outer adapter.

For compatibility, callers that omit policy retain the previous maxAgeMs freshness behavior and have no age-based fallback expiry. New callers should use policy; when supplied it takes precedence over the legacy maxAgeMs.

Overlapping fresh reads coalesce only within the same cache generation, including through host wrappers that delegate invalidation. A forced refresh cannot join an older generation's pending loader or let that response replace its result.

After a successful write, use readThroughCache({ forceFresh: true }) when the next read must be server-confirmed rather than a pre-write cached or in-flight response. Concurrent ordinary reads for the same cache/key share one fresh load; a forced-fresh read starts a new load after invalidating the key.

Read-cache retention is deliberately opt-in. It removes only valid cache envelopes older than the chosen lifetime; it never affects pending writes.

const removed = await pruneReadCache({
  cache,
  maxAgeMs: 7 * 24 * 60 * 60_000,
});

Pending Writes

import {
  createBrowserPendingWriteStore,
  syncPendingWrite,
} from "@bayonai/offline";

type Draft = {
  body: string;
  title: string;
};

const store = createBrowserPendingWriteStore<Draft>({
  databaseName: "my-app:pending-writes:v1",
  keyPrefix: "my-app:v1:pending-draft",
  storeName: "pending-writes",
});

await store.set({
  id: "draft-1",
  payload: { body: "Local text", title: "Local draft" },
  savedAt: new Date().toISOString(),
  syncStatus: "pending",
});

await syncPendingWrite({
  id: "draft-1",
  store,
  sync: (draft) => saveDraftRemotely(draft),
});

Failed sync results include a safe persisted error string and the original non-persisted failure value. Hosts may use failure for structured logging or domain error classification; it is never written into the pending-write store.

keyPrefix is an isolation boundary inside a shared object store. Listing, recovery, and clearAll() affect only that prefix, so independent logical queues may safely share the same IndexedDB database and store when their prefixes are distinct.

For a browser application that wants durable, silent recovery, mount the headless controller once for the active account or workspace:

import {
  createBrowserPendingWriteRecovery,
  createBrowserPendingWriteRecoveryCoordination,
  createOrderedPendingWriteExecutor,
  summarizePendingWrites,
} from "@bayonai/offline";

const coordination = createBrowserPendingWriteRecoveryCoordination({
  // Scope names must be stable per user/workspace and unique to this app.
  channelName: `my-app:pending-recovery:${currentUser.id}`,
  leaseName: `my-app:pending-recovery:${currentUser.id}`,
});

const writes = createOrderedPendingWriteExecutor({
  scopeKey: currentUser.id,
  select: (record) => record.payload.userId === currentUser.id,
  store,
  sync: (mutation) => replayMutation(mutation),
});

const recovery = createBrowserPendingWriteRecovery({
  coordination,
  recover: writes.recover,
  store,
  onError: (error) => console.error("Pending replay failed", { error }),
});

recovery.start(); // silent initial, focus, online, and local-set recovery

const result = await writes.run({
  isOnline: () => navigator.onLine,
  write: () => saveRemotely(),
  shouldQueue: isRetryableNetworkError,
  enqueue: () => store.set(createPendingMutation()),
});

// On unmount or account change:
recovery.stop();
coordination.close();

The controller never creates product UI. It preserves failed writes locally, retries remaining selected writes with bounded exponential backoff, and exposes only onResult/onError callbacks for host diagnostics or telemetry. Stores also expose a local-instance subscribe API; it is not a cross-tab delivery mechanism.

When coordination is supplied, a queued write wakes peer tabs through BroadcastChannel, and each recovery attempt acquires a non-blocking navigator.locks lease when supported. Browsers without either API recover in the current tab as before. A contested lease retries silently with bounded backoff. Remote write handlers must remain idempotent because leases do not cover other devices or every browser failure mode.

Recovery is application work

Follow the package-owned automatic recovery contract. Never ask users to Retry/Try again or review and retry unchanged operations. Keep normal pending writes silent through the existing bounded background recovery owner. Use getPendingChangesGuidance with host-projected hasReadyChanges, hasDrafts, hasErrors and isOffline flags for shared status copy. Use isTransientOfflineError for known transport/service failures, retaining host validation, account scoping and idempotency policy. Unknown and explicit terminal errors must not become blind replay.

Static Offline Fallback Recovery

Pull-down and reconnect request a safe refresh; no refresh button is required.

import { createBrowserOfflineFallbackRecovery } from "@bayonai/offline";

const recovery = createBrowserOfflineFallbackRecovery({
  // Read current storage health on every attempt. Never discard work to refresh.
  canReload: async () => await hostCanProveLocalDurability(),
  retryEvent: "my-app:network-restored",
});
recovery.start();
// On unmount:
// recovery.stop();

An unsafe/rejected proof retains the same request and rechecks with capped backoff, so a person never needs to repeat the gesture. Only one proof and one timer may run at once. Stop cancels rechecks and fences late proof results. The default top-of-page pull threshold is 72px; pullThreshold: null lets a host own gesture recognition and call recovery.refresh() instead. Supply the actual scroll region through the environment when the fallback has a scrolling modal. Static documents must bundle this package code rather than use bare npm imports. The optional legacy control, reload() and retry() APIs remain compatible.

Strict pending reads and acknowledged corrections

Browser pending stores throw OfflineStorageError on read failure or timeout; never interpret uncertainty as an empty queue. Cache reads remain best-effort. Custom pending-write drivers must throw on failed reads too. Retain last-known pending state while the existing browser recovery controller rechecks storage.

Use clearSupersededPendingWriteFailures({ acknowledged, store, getSupersessionKey, isRejected }) only after confirmed remote acknowledgment. Hosts map an explicit account/entity/field key for supersedable setters and null for effectful operations. The helper clears only older failed unclaimed matching snapshots through compare-and-clear; it never blindly removes all rejected work.

Use createOrderedPendingWriteExecutor when a new write must never overtake a previously queued write in the same user, workspace, or other durable scope. Its recover and run methods share one lane: an unresolved predecessor keeps the later write queued until the predecessor is delivered. This protects remote write order; it does not replace idempotent server-side mutation handling for ambiguous request outcomes.

Overlapping syncPendingWrites calls for the same store and scope share a single replay only when their selection and sync callbacks, clock, and stop-on-failure setting are identical. Different requests run in arrival order and each receives results for its own selection. Use stable callback references when callers intentionally share a run. Separate scopes remain independent. A failed storage operation rejects its own call and does not prevent a later queued recovery from attempting a fresh read. Migration: callers that previously relied on scope-only coalescing with newly created inline callbacks should either keep stable callback references or expect each serialized call to report its own attempts and remaining count.

Durable Command Store

Use createDurableCommandStore when a host needs one client-side owner for base data, optimistic projection, durable commands, and remote reconciliation. The host supplies its domain projection and authenticated transport; this package never imports an application model, database SDK, or framework.

const commands = createDurableCommandStore({
  initialState: workspace,
  load: (scope) => workspaceApi.load(scope),
  execute: (command, { operationId }) =>
    workspaceApi.execute(command, { operationId }),
  project: (state, pending) => projectWorkspace(state, pending),
  reconcile: (state, command, result) =>
    reconcileWorkspace(state, command, result),
  shouldRetry: (category) => category === "connectivity",
  store,
});

const { accepted, operationId } = commands.dispatch(command);
await accepted; // locally durable; remote confirmation continues in background

// A delayed command stays ordered and can be cancelled before its deadline.
const deferred = commands.dispatch(deleteCommand, { notBefore: deadline });
await commands.cancel(deferred.operationId);

getSnapshot and subscribe expose projected state and command status to any UI framework. refresh ignores older read results, recover replays durable commands in order, and close releases the local subscription and delayed deadline timer. Local-storage failure rejects accepted; hosts must show that failure instead of claiming the command will recover. Once the pending write commits, accepted resolves even if the follow-up local list or projection fails. The prior optimistic snapshot remains visible, and background recovery still runs under the original operation ID. Hosts must not dispatch a new operation just because a local view refresh failed.

Browser pending-write mutations reject with OfflineStorageError when IndexedDB is unavailable, rejects an operation, or cancels a timed-out transaction. This is intentional: successful queue acceptance always means the command was durably stored. Read-cache access remains best-effort, and a fresh remote result is still returned when optional cache invalidation or persistence fails.

The executor receives the durable operationId on every attempt so the remote handler can use it as an idempotency key. When execution succeeds, reconcile folds the authoritative result into base state before the command is removed; any later optimistic commands are projected over that confirmed state. A read that started before this confirmation cannot replace it when it finishes. Reconciliation is deliberately a host-owned, synchronous state transformation. If it throws, the package logs the local bug and removes the already-confirmed command rather than risking a duplicate remote effect.

classifyError and shouldRetry let a host distinguish recoverable failures from terminal validation, authentication, permission, or conflict outcomes. Retryable failures retain their optimistic projection while awaiting recovery. Terminal failures roll back, stay available in operations for host feedback or dismissal, and are excluded from later recovery lanes, so they neither retry nor block a newer command. Because recovery survives restart, classification must work from the package's persisted safe error message rather than relying only on a non-serializable error object.

Use generic record summaries when an app needs to render its own status:

const summary = summarizePendingWrites(await store.list());
// { pendingCount, syncingCount, failedCount, totalCount }

Each call to set assigns a unique snapshotId. A replay first atomically claims a fresh snapshot identity before calling the remote sink, then compares that identity during status updates and cleanup. This prevents concurrent workers or an older sync from overwriting or deleting a newer local write. Interrupted sync claims expire after one minute so recovery can resume. Records created before snapshot identities were introduced remain readable; they receive a stable compatibility identity and are upgraded when next updated.

Conditional IndexedDB mutations are cancelled when their storage deadline is exceeded, so an operation cannot report failure and then commit later. Ordered replay also stops at an active older claim; it never delivers a later record whose remote effect could subsequently be overwritten by that predecessor.

Host apps that change their pending-write payload shape can normalize current records while keeping domain logic outside the package:

const store = createBrowserPendingWriteStore<Draft>({
  databaseName: "my-app:pending-writes:v1",
  keyPrefix: "my-app:v1:pending-draft",
  storeName: "pending-writes",
  normalizePayload(value) {
    return isDraft(value) ? normalizeDraft(value) : null;
  },
});

Boundary

@bayonai/offline has no Firebase, Firestore, Next.js, React, or application domain dependencies. Host apps provide remote loaders and sync functions.

Host apps are also responsible for:

  • Choosing database names, store names, and key prefixes.
  • Scoping storage by user, tenant, workspace, or other app identity.
  • Validating and migrating app-specific payloads.
  • Deciding when to clear browser storage, such as on sign-out.
  • Providing remote read and write functions.

Use a separate IndexedDB database for independently initialized stores unless the host coordinates a database-version upgrade that creates every required object store. IndexedDB cannot add a missing store when an existing database is opened at the same version.

Package Scripts

pnpm --filter @bayonai/offline test
pnpm --filter @bayonai/offline test:coverage
pnpm --filter @bayonai/offline run build
pnpm --filter @bayonai/offline pack:smoke

Publish Checklist

  1. Run the package tests and build.
  2. Run the 100% coverage gate and production dependency audit.
  3. Run pnpm --filter @bayonai/offline pack:smoke and confirm the tarball includes only package.json, dist, dist-cjs, README.md, CHANGELOG.md, RECOVERY.md, and LICENSE.
  4. Install the generated tarball into an isolated consumer and verify ESM, CommonJS, and TypeScript declaration imports.
  5. Confirm package.json metadata, version, repository, license, and publishConfig.access are correct.
  6. Publish from the package directory or with the package filter after the workspace lockfile is current.

Enforcing consumer read boundaries

assertReadBoundary is a framework-free architecture-test utility. The host parses its actual source into a module graph and supplies provider policy:

assertReadBoundary({
  modules: parsedRuntimeDependencies,
  roots: featureEntryModuleIds,
  allowedAdapters: trustedCacheAdapterModuleIds,
  isForbidden: (id) => forbiddenReadProviders.has(id),
});

Supply all reachable local runtime imports, re-exports and dynamic imports; reject unresolved or non-static local dependencies in the host parser. Absent nodes are external leaves. Exact allowed adapter IDs stop traversal; verify those adapters' cache-first behavior separately. Cycles terminate safely, and a bypass throws an error containing its dependency path. The package imports no TypeScript parser, Firebase SDK, or host-domain module. Bounded's real catalog read-family recipe lives in src/lib/lists/catalogReadBoundary.test.ts and works with its existing cache behavior tests. This locally added export requires an intentional future package release before registry consumers can adopt it.

Consolidate unsent absolute state

store.consolidate(getSupersessionKey) atomically retires earlier unclaimed absolute setters with the same explicit account/entity/field key. Call after acceptance and before recovery to compact historical queue records too. Keep the latest setter even when the remote baseline is unknown. This capability is optional on custom stores; built-in stores always expose it. Legacy custom drivers without atomic deleteSelected retain records and return zero.

await store.set(nextIntent);
await store.consolidate?.((record) =>
  record.payload.kind === "setCompleted"
    ? JSON.stringify([
        record.payload.accountId,
        record.payload.taskId,
        "completed",
      ])
    : null,
);

Return null for effects, partial patches, overlapping fields, moves/access changes, assignments with notifications and commands that observe earlier state. Null keys, syncing records (including expired claims), explicit syncingAt and any notBefore deadline fence both sides of the ordered lane. Distinct recurrence occurrences must not share a setter key. Hosts own the keys and their proof of independence. All ordinary setters between barriers must commute with the omitted older setters; do not key commands merely because they target the same entity.

projectPendingWriteFinalState(records, getSupersessionKey) provides the same pure ordered view for display/capture overlays. It does not establish durability and must not justify dropping live optimistic receipts before storage succeeds. Consolidation emits clear events only after the deletion transaction commits. No envelope schema or database upgrade is required. Driver implementations of deleteSelected must select and delete in one atomic transaction and propagate failures without partial mutation. Policy callbacks are synchronous and pure.

Related effects may explicitly depend on an unsent setter: supply getDependencyKey(effect) returning that setter's key and optionally isDependencySatisfied(effect, state). When a later setter supersedes the prerequisite, its pending dependent effects retire with it. A false dependency check retires an effect attached to a cancelling latest setter. Without an unclaimed prerequisite in the same barrier-bounded lane, effects remain ordered. Use this only for dependent consequences that the host explicitly wants to cancel with superseded intent (for example, an award for a cancelled completion). Independent effects can opt out of being barriers with isBarrier; they stay in the queue. Claims and cancellation deadlines always fence both sides regardless of these callbacks. All callbacks are synchronous, pure host policy.

Observe pending changes without owning another queue

createPendingChangeTracker<T>() observes host-supplied load(accountKey) and optional synchronous capture(accountKey) sources. Supply subscribe(notify) for existing command-store, draft and browser source notifications. It refreshes immediately, exposes stable getSnapshot/subscribe methods for external-store consumers, and releases its source subscription with close().

Hosts project real rows into PendingChangeItem (account, group, label, status and attention/storage/sending flags); generic host fields survive projection. createPendingChangeSnapshot also supports standalone synchronous consumers. Captured rows replace same-ID durable rows, groups preserve host order, and all counts and guidance derive from the resulting account-scoped rows. IDs must be unique across the host's sources unless replacement is intended.

setAccountKey clears the previous account immediately and fences late reads. Read failures retain the current account's last known rows and expose readError; provide onError for host diagnostics (otherwise the tracker logs to console). Call setOffline when connectivity changes. The tracker never persists, executes, consolidates or retires operations, and adds no schema, jobs or provider imports.

Mounted read presentation

createReadResourceObserver<T, Snapshot> owns mounted refresh presentation over the host's existing cache and shared source reader. The host calls accept(update, confirmedAt) for its initial delivery; the timestamp must be the original cache/source confirmation time. The controller stores age and eligibility, not another copy of the value. canRetain(data) excludes mutation affordances or other values requiring a strict contract.

refresh() explicitly forces a confirmation; wake subscriptions invoke ordinary freshness checks. A fresh canonical host snapshot may satisfy ordinary recovery without a source request. A host-classified superseded read adopts that snapshot immediately. Transient failures preserve the mounted value and original age; terminal failures call retireSnapshot with the exact token captured before the read, clear confirmation, and emit failed. The host must condition retirement on token ownership and current authority. Failed cleanup is logged separately and does not hide the terminal failure.

The host owns initial force versus persistent strict mode, identity, authorization, connectivity/visibility, read eligibility, TTLs and transport sharing. Set enabled: false for strict/noncacheable/command observations; their initial data can still be accepted but they never subscribe or refresh. The controller uses no timer or retry engine. subscribeWake returns an unsubscribe function; dispose() silently fences callbacks and detaches it. retire() emits one safe invalidation even after scope changes. Neither cancels an already-running shared source promise.

observeReadResourceBatch<T> composes host child observations into one mounted presentation barrier. It retains child order, duplicate positions and explicit undefined results. Children retain all source/cache ownership; the barrier records only their current presentation values and source ages. During refresh, a temporary failure keeps the last complete array visible. A terminal child failure retires the whole presentation immediately, including while another child stalls, and later sibling completions cannot revive it.

The initial presentation follows accepted child callbacks, filling positions without a callback from settled child promises. The batch promise preserves the original child promise results, which may differ from newer canonical callback values. Use child callbacks for presentation and promise results for source-call settlement. Forced refresh, ordinary freshness checks, strict-value exclusion, scope checks and disposal follow the scalar contract. No second cache, automatic write replay, schema change or scheduling service is introduced.

bindBrowserReadLifecycle({ window, document }, notify) forwards native focus, online and visibility-change events and returns idempotent cleanup. Hosts keep visibility/connectivity checks and transport coordination inside notify. Synchronous throws and rejected wake promises are logged without escaping the native event callback. This binding does not acquire pending-write replay ownership.