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

@bazariodev/baton

v0.2.0

Published

Coordinate one browser resource owner per origin and key with the Web Locks API.

Readme

@bazariodev/baton

Baton lets one cooperating application instance own a browser resource for one key and origin. It uses the Web Locks API and does not start or display the resource for you.

Install

pnpm add @bazariodev/baton

The package uses @bazariodev/coordination as a runtime dependency. Browser use needs the DOM type declarations when you use TypeScript.

Usage

Create one stable key from the application, environment, and tenant IDs. Call take() before protected startup. Put resource cleanup in beforeRelease.

import { createBaton } from '@bazariodev/baton';

const environmentId = 'production';
const tenantId = 'tenant-a';
let timer = null;
let pendingStartup = Promise.resolve();
const baton = createBaton({
  key: JSON.stringify(['example-app', environmentId, tenantId]),
  beforeRelease: async () => {
    await pendingStartup.catch(() => undefined);
    if (timer !== null) clearInterval(timer);
    timer = null;
  },
});

async function startOwnedTimer() {
  const result = await baton.take();
  if (result.state !== 'owner') return result;

  const { signal } = result.lease;
  const setup = (async () => {
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (signal.aborted) return;
    const nextTimer = setInterval(() => updateResource(), 1000);
    if (signal.aborted) {
      clearInterval(nextTimer);
    } else {
      timer = nextTimer;
    }
  })();
  pendingStartup = setup;
  try {
    await setup;
  } catch (error) {
    await baton.pass();
    throw error;
  } finally {
    if (pendingStartup === setup) pendingStartup = Promise.resolve();
  }
  return result;
}

const result = await startOwnedTimer();
if (result.state === 'blocked') showBlockedScreen();
if (result.state === 'unavailable') showUnavailableState(result.error);

updateResource, showBlockedScreen, and showUnavailableState belong to the application. Check the lease signal after each asynchronous step and before each side effect. Keep the startup promise visible to beforeRelease, as in this example. The runnable browser example shows a blocked screen, explicit retry, cleanup, and page restoration.

Behavior

  • The key is an opaque, non-empty string. Baton uses it unchanged as the native lock name. Baton does not read the URL.
  • A browser lock is unique to the origin: scheme, host, and port. A different origin can own the same key.
  • A granted lease has an AbortSignal. It is aborted before cleanup starts. A later grant has a new lease and signal.
  • A new take() request settles as owner, blocked, or unavailable. Calls during acquisition share one native request, and each caller receives a separate state copy. If pass() or stop() cancels that request, it settles with a no-lease state. A call during release returns a copy of the current no-lease state. After stop(), new calls reject. Read getState() for states such as idle, acquiring, releasing, and stopped. A later grant always has a new lease.
  • Returned state objects are mutable copies. Each read, take result, and listener delivery gets a separate record. You can change fields on your copy without changing Baton state or another delivered copy. Copies are shallow: lease and error references are shared. The lease remains immutable and its signal stays live.
  • A blocked result does not retry by itself. Call take() again after a user action. A consumer can also offer a new explicit request from idle.
  • unavailable means the browser has no usable Web Locks API or denied the request. The application decides whether to stop or start an unprotected resource. Baton does not claim ownership for that resource.
  • On normal release, pass() waits for beforeRelease and native lock release. A cleanup failure rejects the call and keeps the lock. Call pass() again to retry cleanup. If native ownership is lost, the lock is already gone; cleanup still blocks another request from this Baton until it finishes.
  • stop() closes admission at once. It waits for cleanup and then removes Baton listeners. A failed cleanup can be retried with stop().
  • By default, Baton reads browser globals only when it needs them. target: null disables page lifecycle handling. On pagehide, Baton aborts the lease and starts cleanup. A page restored from the back-forward cache must complete cleanup and acquire a fresh lease before it starts the resource again.
  • Baton has no logging dependency and does not choose an unprotected-startup policy.

API

The root also exports the frozen BATON_STATES and RELEASE_REASONS maps. Use these values when you check ownership results and cleanup reasons.

| Factory option | Type | Default | Purpose | | --- | --- | --- | --- | | key | non-empty string | Required | Stable application, environment, and tenant scope. | | locks | Pick<LockManager, 'request'> | Current navigator.locks | Inject a lock manager for a controlled runtime or test. | | target | event target or null | Current window, when available | Receive the pagehide event. Use null when the caller owns lifecycle cleanup. | | beforeRelease | (reason) => void \| Promise<void> | No callback | Stop producers and finish resource cleanup before lock release. | | logger | { error(message, { error }): void } | No logger | Receive contained listener and automatic cleanup errors. |

| Method | Result | Purpose | | --- | --- | --- | | take() | Promise<BatonState> | Try once to acquire the key. A blocked or unavailable result can be retried by a later call. | | getState() | BatonState | Read a mutable copy of the current state. | | subscribe(listener) | () => void | Listen for state changes. The listener is not called during subscription. | | pass() | Promise<void> | Release the current lease after cleanup. It is safe to call more than once. | | stop() | Promise<void> | Close admission and stop this Baton permanently. |

beforeRelease receives one of release, pagehide, stop, or lost. Make cleanup safe to repeat. On a normal release or stop, a cleanup failure keeps the native lock until a later pass() or stop() succeeds. If the reason is lost, the browser has already released the native lock. Baton still blocks another request from that instance until cleanup succeeds.

Framework adapters

State reference identity is not stable. Do not pass this getState directly to React's useSyncExternalStore. An adapter must cache a state object until a subscription reports a state change. The adapter owns that cached value; the caller-owned copies supplied by Baton remain mutable.

Scope and rollout

Use the same key across every route and entry point for one application, environment, and tenant. Keep it stable across releases. A release that does not use Baton can still start a second resource, so retire older versions before you claim single-instance protection.

The browser lock covers one origin only. Use server coordination if the resource needs one owner across origins, profiles, or devices.

Navigation and unavailable state

Before intentional navigation in the same tab, await pass(). Navigate only after it succeeds. If cleanup rejects, keep the page open and let the user retry cleanup. A return page must acquire a fresh lease before it starts protected work.

If acquisition is unavailable, the application can stop startup or choose an unprotected resource. Baton has no allowUnprotected or logging-policy option. Stop this Baton before you start an unprotected resource. Before a later protected attempt, stop and clean up the unprotected resource, then create a new Baton with the same key. blocked is not an unavailable result and must not start an unprotected resource.

Errors

An unavailable state has one of these error codes:

| Code | Meaning | | --- | --- | | unsupported | Web Locks are missing. | | access | Reading or using the lock manager raised a security error. | | request | The native lock request failed. | | lost | The native lock request ended unexpectedly after Baton granted a lease. Baton aborts the lease and starts cleanup. |

blocked has no error. A failed beforeRelease rejects pass() or stop() and publishes releasing with code cleanup. A call to take() after stop() rejects.

TypeScript

Baton ships ESM and CommonJS declarations. Its public types use the DOM LockManager, Window, and AbortSignal interfaces. Add the DOM library to your TypeScript configuration when your project does not already include it.

BatonState is a discriminated union. Check state before reading lease:

import { createBaton } from '@bazariodev/baton';

const baton = createBaton({ key: 'example-app:production:tenant-a' });
const currentState = await baton.take();
const stopResource = () => {};

if (currentState.state === 'owner') {
  currentState.lease.signal.addEventListener('abort', stopResource, {
    once: true,
  });
}

Limits and security

Baton coordinates cooperating pages in one browser origin and storage scope. It does not coordinate different origins, browser profiles, or devices. Use server coordination when a resource needs one owner across those boundaries.

The Web Locks API needs a secure context in browsers. Browsers can report the API as missing or deny access. Baton returns unavailable in those cases.

The lease is a cooperative lifecycle signal, not a security boundary. Code that ignores the lease can still start work. Acquire ownership before authentication side effects, history writes, network connections, or other protected work. Do not start a second resource when a result is blocked. The browser may release a lock when it destroys a document; Baton cannot prove when a server has stopped processing work already sent by that document.

License

MIT