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

@dofek/whoop-ble

v0.1.72

Published

Reverse-engineered WHOOP strap BLE protocol and Expo iOS client

Readme

@dofek/whoop-ble

Unofficial Expo iOS client for the reverse-engineered WHOOP strap Bluetooth Low Energy protocol.

The package discovers bonded WHOOP straps, parses proprietary framed packets, captures reported heart rate, real-time R-R intervals and inertial samples, and exposes connection and orientation events through Expo Modules.

Additional background sensor records use the same durable native upload system. Complete packets retain their capture identity, reception time and observed device information. The server decodes capture-backed R18 temperature and retains unverified optical layouts as raw records, following the protocol evidence boundaries. The WHOOP BLE provider detail screen shows uploaded temperature and raw records on both clients. This does not start ECG capture or change persistent strap configuration.

Install

npx expo install @dofek/whoop-ble expo-modules-core

This package currently supports iOS 16.4 or later. It is not affiliated with, endorsed by, or supported by WHOOP. The protocol is undocumented and may change without notice.

Library development uses the same expo-modules-core version as the Dofek app. Consumers supply the compatible runtime through their Expo SDK, following Expo's native library dependency guidance.

Protocol details and provenance are documented in docs/whoop-ble-protocol.md. Native Swift applications can use the separately tagged WhoopBLE Swift package.

Buffered realtime samples expose heartRateBpm independently of rrIntervalMs. WHOOP can report BPM when beat intervals are unavailable during movement; see its research FAQ, page 4. Captured R18/R21 fractional clock words use 1/32768-second ticks, and buffer timestamps use that scale; see the capture-backed protocol reference. The serializer preserves device time, including early and future values. The server filter rejects future samples individually; an acknowledged batch removes those rows from the queue too. Reported times determine sample identities. Native changes require a new iOS build, following Expo's native development workflow.

This native module requires a development build; it does not run in Expo Go. The consuming iOS app must provide NSBluetoothAlwaysUsageDescription. Background capture additionally requires the bluetooth-central background mode. See Expo's local app development guide and Apple's NSBluetoothAlwaysUsageDescription documentation.

Usage

Battery percentage and charging

getDeviceSummary() and addDeviceStateListener() expose a battery object with nullable percentage and isCharging fields. The mobile Bluetooth device list and WHOOP details render the same compact badge. An observed 0 is empty; false means not charging, while null means unknown. Older native binaries that omit battery status decode as unknown values.

Percentage is read from the optional standard Bluetooth Battery Service and updated through supported notifications. Charging comes from supported WHOOP events, independently of the percentage; connecting alone does not establish whether the strap is charging. Each valid update preserves the other known fact, and disconnect/replacement clears both. Unsupported or missing battery channels leave sensor collection available. See the protocol and provenance reference and Bluetooth's Battery Service specification. The Harvard/WHOOP 4 standard battery characteristic is excluded because recorded upstream evidence shows an incorrect level. This change does not add Harvard-specific battery commands or framing; unsupported readings stay unavailable.

Live acquisition requires a rebuilt native iOS binary. A JavaScript OTA update cannot install the Swift acquisition code; Expo describes that boundary in its native development workflow. Swift/bridge tests establish decoding and state propagation, not physical strap notification delivery or firmware compatibility. Verify plugging/unplugging the charger and reconnecting on a physical strap with the matching binary.

Start capture

import {
  connect,
  findWhoop,
  configureUpload,
  flushUploads,
  startRealtimeHr,
} from "@dofek/whoop-ble";

// Supply the authenticated account and its current session from your app.
await configureUpload({ userId, serverURL, token: sessionToken, headers: {} });
const device = await findWhoop();
if (device) {
  await connect(device.id);
  await startRealtimeHr();
  await flushUploads();
}

The root module also exports connection-state diagnostics, IMU and optical stream controls, orientation events, and reconnect support. The native transactional queue is the canonical sample store. The uploader removes reserved rows only after a valid server acknowledgment; failures retain the rows. SQLite provides atomic commits.

configureUpload(), flushUploads(), disableUploads(), purgeAccountState(), getDataPathStats() and getDeviceSummary() return Promises. They share one module-owned serial queue through Expo's stock AsyncFunction to keep queue waits and disk work off the JavaScript thread and other modules' async queue. Erasure runs in the same FIFO and holds its queue item until the store mutation succeeds or its failure is fenced. Await configuration before starting capture and await disable before completing session cleanup. Disable resolves only after the existing native purge and body removal return; failures reject and block later configuration until an explicit successful disable. Capture starts suspended until configuration succeeds. This does not change synchronous sample persistence.

Session persistence can adopt replacement credentials after removing the old credentials and persisting an opaque cleanup intent through the Dofek app's private WHOOP upload-session policy, without waiting for the bulk purge. The SDK's public bridge remains independent of app storage policy. Live replacement configuration queues behind native cleanup. After an app restart, the app resumes unfinished cleanup once from asynchronous WHOOP initialization, awaiting the existing native disable before configuration. Authentication, splash dismissal and navigation do not await this work. The intent uses SecureStore and clears only for its matching successful cleanup, serialized with replacement intents. Concurrent initialization shares recovery; only the latest configuration can proceed. Failure retains the marker and is reported without another automatic attempt in the same JavaScript lifetime; explicit sign-out cleanup remains available. The app hook uses React's effect lifecycle, independently of the app startup gate. Account deletion retains its separate awaited cleanup lease. Native cleanup and credential failures remain awaited and reported.

The Dofek collection lifecycle starts discovery and streaming after upload configuration on both foreground and background launches. Moving the app to the background during startup does not cancel collection; retiring the authenticated session still does. Discovery uses the native Bluetooth power-readiness wait, and background refresh does not start a competing retry while that connection setup is running. This lets the existing restoration-enabled central be recreated after background launch; actual relaunch eligibility follows Apple's Bluetooth restoration rules.

Automatic reconnection keeps the Core Bluetooth connection request pending while the strap is unavailable. Service discovery and notification subscription have a ten-second deadline after Bluetooth connects. Apple describes the system's pending connection behavior.

connect() for the same strap returns immediately if it is ready or streaming. During native connection setup, including a restored connection, it waits for notification readiness. If that caller's wait expires, native recovery and any setup deadline continue. When automatic recovery is cancelling a failed setup, a call for the same strap also waits for the reconnect. The matching Core Bluetooth disconnect callback leaves the caller pending until notifications are ready, setup fails, or the caller's own deadline expires. A new explicit connection has ten seconds to reach readiness. retryConnection() acknowledges an existing or newly initiated connection. To confirm capture has resumed, check new data notifications and parsed sample timestamps. See Apple's Core Bluetooth state restoration guide.

Explicit Disconnect stops active scanning before completing cleanup.

Requested IMU capture survives unsuccessful automatic reconnect attempts and resumes after notification readiness. Explicit Stop and Disconnect cancel pending capture restoration, including when the strap is disconnected. The connection manager owns that intent; the disconnect transition preserves it only for automatic recovery, and the Expo stop handler applies cancellation even without a command characteristic.

Dofek saves historical samples it receives during WHOOP sync by default. To manage history with Dofek, open the strap's Bluetooth device details on the iPhone and enable Dofek-managed history after removing WHOOP's access to that strap. The setting applies when capture starts on the next connection. Disabling immediately stops Dofek from issuing history requests and acknowledgments. Dofek continues to save any historical samples it receives. Format and storage limits are described in the WHOOP protocol reference.

getDataPathStats() also exposes lastKnownDeviceId, capture timestamps, and a typed buffers snapshot containing bufferInstanceId, bufferCreatedAt, checkpointAt, imu, realtime, sensorRecords, activeUploadCount, blockedUploadStreams, and lastUploadError. It also includes the latest lastUploadOutcome, correlating a durable batch with its stream, sample count, URLSession task/path, HTTP status, validated acknowledgment, and whether the batch remains in the outbox. Native upload exceptions carry the same metadata in the whoop_upload Sentry context while preserving the original error domain and code. These fields contain no sample values or request bodies. Stream counters describe persisted queue changes. The buffer identity is the persisted account/server generation; it survives ordinary process recreation. Creation/checkpoint times describe the current native uploader and snapshot. Capture timestamps distinguish phone-observed notifications from the strap's latest valid reported heart rate; see the bridge contract.

Upload completion adds a Sentry breadcrumb with the opaque durable batch identity, stream, route, outcome stage, HTTP status when present, origin and acknowledgment validation, and whether the reservation remains pending or was retired. This lets statusless URLSession errors be correlated with their batch and later outcome. Breadcrumbs omit credentials, account identifiers, and sample bodies. Validated HTTP 5xx outcomes remain in the existing operational counter and are omitted from these breadcrumbs. Transport and origin-validation errors remain reportable even if the task exposes a raw 5xx status.

All streams decoded from one BLE notification commit to SQLite in a single FULL synchronous transaction before the capture callback returns. The transaction writes one unindexed inbox row per retained stream. Each row holds timestamps and validated sample payloads in a binary property list compressed with Foundation's LZFSE. An invalid stream rolls back the entire notification.

Startup, configuration, explicit flush, and the existing five-second capture schedule move inbox rows into the indexed upload queue. The move inserts samples in capture order, updates received totals, and deletes the inbox rows in one transaction. Upload acknowledgments work on the indexed queue. Diagnostics include committed inbox rows immediately, including their oldest and newest timestamps. Grouping index updates follows Apple's disk-write guidance.

The queue uses 1 KiB SQLite pages to reduce bytes written per notification. Automatic checkpoints start at 4,000 pages, preserving the approximately 4 MiB target used before the page-size reduction. This lets SQLite combine more updates to the same page before writing it back to the database. SQLite automatic checkpoints. Opening an older queue rebuilds it in place once, before capture or upload uses it, then restores WAL mode. If startup is interrupted, the next open resumes from the persisted page size. The one-time rebuild requires temporary free space and preserves pending batches, account ownership, and the erasure cutoff. SQLite WAL format and SQLite database rebuilds. Rows survive app recreation and can wait offline. Account changes and sign-out purge both the inbox and indexed queue and cancel their tasks. The SQLite ownership trigger also clears inbox rows when an older build rotates the queue generation. The store reapplies the retained device cutoff to staged rows on reopen. Whole-account cleanup can delete unreadable inbox contents without decoding them, including on a cold launch.

Queue files and transport bodies are excluded from backups and use locked-device-accessible iOS file protection.

For stalled session cleanup, query Sentry's dofek-mobile logs with operation:disableUploads and group by operationId. The native bridge records entry to ble_suspend, disconnect, uploader_bootstrap, and uploader_disable, followed by completed or failed with failedStage. Inside uploader_disable, uploader_queue_wait records entry before waiting for the uploader's serial queue; uploader_cancel_tasks records entry after acquiring it, before requesting transfer cancellation and reading reserved identities. When a device erasure cutoff is retained, uploader_advance_erasure_cutoff marks its transactional SQLite update after cancellation and before uploader_store_purge. uploader_remove_bodies precedes file cleanup. Within the store, store_lock_wait precedes the mutex wait, store_begin follows lock acquisition before BEGIN IMMEDIATE, and store_reset_stats, store_delete_samples, store_delete_batches, store_clear_binding and store_rotate_generation precede the corresponding writes. store_commit precedes COMMIT; store_completed establishes that commit returned successfully. store_vacuum precedes VACUUM; store_wal_checkpoint and store_wal_checkpoint_completed bracket the explicit truncating WAL checkpoint after that commit. The completion log includes SQLite's busy, log, and checkpointed frame counts as checkpointBusy, checkpointLogFrames, and checkpointedFrames. These values describe only this explicit checkpoint after VACUUM; they do not measure bytes written by SQLite's automatic checkpoint during COMMIT or the operating system's per-function disk-write share. The stage logs also include sqliteCacheWritePages, the running count of dirty SQLite cache pages written to the WAL since uploader_cancel_tasks, which marks the cleanup after its uploader queue is acquired. Compare adjacent stage values to measure writes between stages. It does not measure the later checkpoint's main-database writes or physical device bytes; it uses SQLite's SQLITE_DBSTATUS_CACHE_WRITE. The purge deletes rows with secure_delete set to FAST, so SQLite does not rewrite each freed page through the WAL; VACUUM then removes the freed pages and shrinks the file. The purge implementation commits a purge_pending record in the existing metadata table with the deletion. It clears that record only after compaction and a successful truncating checkpoint. Store initialization completes pending cleanup before returning; later writes and explicit cleanup retries also complete it before proceeding. Failed recovery rejects configuration and capture instead of losing the cleanup intent. The prior connection-local secure-delete mode is restored with checked SQL on success and failure, including the FAST literal for mode 2. An unsuccessful restoration blocks later writes until that original mode is restored. Transaction failures retain the existing rollback and error propagation, following SQLite's transaction semantics. The existing capture_snapshot diagnostic includes a fixed-size reservation write summary: the number of successfully measured new reservations since this uploader instance started, total WAL pages written and spilled, the maximum pages written by one reservation, and a bounded count of failed counter reads. The aggregate resets when the native uploader is recreated and is read at the existing snapshot cadence; it does not emit one event per reservation. SQLite's connection status counters are sampled before and after each new-reservation transaction to measure page deltas written to WAL and spilled from cache. These counts are not total disk bytes or MetricKit attribution, and exclude body-file writes and pending-purge recovery. Older native builds omit the optional summary and remain valid to the bridge. Each entry includes isMainThread and the current native threadId, captured at that boundary rather than inherited from the initial caller. Apple's hang investigation guidance explains why UI-thread evidence is distinct from a pending background operation. These stages share the original operation ID and elapsed clock; the next entry establishes that the preceding operation returned. durationMs is elapsed time since cleanup began; a stage entry alone does not establish completion or confirm that an asynchronously requested transfer cancellation has finished. These use the installed SDK's native structured logger, independent of JavaScript log-export timers. Attributes contain no credentials or sample payloads. Native changes require a new iOS build.

During native Sentry initialization, call WhoopBleModule.configureCleanupLogAttribution(options) from RNSentrySDK.start(configureOptions:). It uses the supported log callback to remove user.id, user.name and user.email from disableUploads logs, while preserving the previous callback and attribution of unrelated logs. Cleanup stages remain correlated by their operation ID across account changes.

The native uploader uses independent 500-sample batches for IMU and realtime streams. Sensor-record batches contain at most 16 records and 262,144 encoded bytes, following the queue reservation limits. Each stream uses its existing authenticated ingestion route. Actual BLE arrivals coalesce scheduling checks to five seconds, and partial batches become eligible after 30 seconds or a lifecycle flush. Each reservation uses one file-backed background URLSession transfer for process-independent delivery. Foreground-started tasks are eligible for immediate transfer. iOS schedules background-started tasks at its discretion, including history captured while the phone is locked. Capture retains the same immutable SQLite reservation and retries a terminal network failure after the existing 30-second backoff. Responses are bounded to 64 KiB per task identifier. The session disables shared cookies, credentials and caching. Tokens remain in application memory and iOS owns submitted request headers.

Native callbacks can acknowledge restored batches before React loads. Credential changes cancel the old task and wait for its terminal callback before starting a replacement. A refresh with matching credentials keeps the active task, including a gzip transfer restored after relaunch. A completed task holds its reservation until the uploader handles the result. Queued callbacks carry an in-memory attempt number so retired results cannot block a newer submission. Account retirement cancels its tasks. The uploader submits the next eligible reservation before releasing the background-session completion callback. Canonical mutation endpoints must serve directly because the background service follows redirects. An acknowledgment requires a response from the configured server origin.

Each upload route starts with JSON. After a direct acknowledgment advertises Accept-Encoding: gzip, later requests on that route use gzip when the body fits the 262,144-byte decoded limit and compression reduces its size. Sample limits and reservation identities stay the same. A server that rejects gzip with HTTP 400 or 415 and omits the capability header receives the same reservation again as JSON. This uses standard HTTP request content negotiation. RFC 9110

Runtime preparation and background-session attachment use a serial utility queue, so opening or upgrading the durable database does not block the application lifecycle callback. Synchronous capture consumers wait for that same runtime, including its first database open or upgrade. A failed open remains visible through capture diagnostics or Sentry before releasing the OS completion. This follows Apple's guidance to avoid immediate main-thread file I/O: file-system performance.

(await getDataPathStats()).connectionDiagnostics exposes the latest 64 native connection events and a cumulative overflowCount for older events removed from that bounded history. The native connection journal retains metadata in UserDefaults before JavaScript reporting: stable event IDs, native occurrence times, native session and process identity, connection and central-manager states, reconnect intent, and Bluetooth error domain/code/description. It also records restoration and application handshake failures, distinguishing those failures from an upstream Bluetooth disconnect. The history contains no sensor samples, reads do not consume events, and account erasure clears it. The app diagnostics reporter sends each unseen event through the existing logger when JavaScript takes a snapshot; replays after restart retain the same event IDs and mark account provenance unknown. This is diagnostic evidence, not proof of uninterrupted capture.

Changes to the native bridge require a new native build, as described in Expo's native development workflow. The app uses the fingerprint runtime policy in app.json, following Expo runtime compatibility guidance. The diagnostic procedure describes correlation with upload and server events.

Automatic recovery and queue diagnostics

Automatic collection retains reconnect intent after transient setup timeouts, discovery errors, and notification subscription errors. It waits for the cancelled peripheral's disconnect callback before reconnecting, following CoreBluetooth's cancellation contract. Explicit connection requests still reject with their typed error; explicit Disconnect and structurally incompatible services remain terminal. Stop prevents IMU restoration during recovery.

If discovery finds none of the supported WHOOP services, Bluetooth Devices shows Unsupported device after an automatic or manual connection attempt. The app handles the native NO_SERVICE result without a Sentry exception. The native connection journal retains the abort reason for diagnosis.

Queue counts use the sample store's existing transactional lifecycle counters. Oldest and newest sample times use separate lookups through the stream/time covering index, following SQLite's covering-index and MIN/MAX optimizations. The index is created on the first open after a native upgrade. On the copied October 30 incident queue (3,427,798 IMU rows and 39,411 realtime rows), that open took 5.85 seconds on the investigation Mac; subsequent diagnostics plus unlimited count took 0.04–0.38 ms. These measurements are not device latency guarantees; see the incident evidence. Both corrections require a new native iOS build.

Validated HTTP 500–599 upload responses increment the uploader-lifetime http5xxResponseCount and remain visible in lastUploadError; they follow the existing retry and durable-queue behavior without creating Sentry exception events. The count is included in the existing capture_snapshot structured OpenTelemetry log through getDataPathStats(). It is cumulative for one native uploader lifetime, is not persisted, and appears on the next normal diagnostics snapshot; repeated snapshots report the same running total and must not be summed as separate failures. Older native builds may omit this optional field. Unexpected validation, storage, authentication, and acknowledgment failures continue through Sentry. HTTP 408 and transport failures follow the reporting rules below. This field uses the standard log record attribute model described by OpenTelemetry's Logs Data Model.

Same-origin HTTP 408 responses increment http408ResponseCount and retain the upload outcome breadcrumb and last error. A valid acknowledgment that commits retirement of the affected reservation increments http408RecoveredBatchCount once. Both counters are cumulative for the native uploader's lifetime and appear in the next normal capture_snapshot. Compare successive snapshots from the same uploader as deltas. Older native builds may omit both fields, and a process restart resets recovery attribution.

The native uploader records whoop.upload.connection_loss for each accepted URLSession path callback with NSURLErrorNetworkConnectionLost. A drop with a pending sibling keeps its diagnostic outcome and breadcrumb. Terminal drops and unexpected transport errors also report an exception. When the affected reservation's acknowledgment commits, the uploader emits whoop.upload.connection_loss.recovered once and records whoop.upload.connection_loss.recovery_duration in seconds from its first observed drop. Swift's ContinuousClock includes time when the phone is asleep. A process restart resets the timing so a restored reservation can be measured from a newly observed drop. The metrics use the Sentry Cocoa metrics API.

Upload acknowledgments find their reserved sample rows through a partial index on non-null batch identities, rather than scanning the entire queued backlog. Unreserved rows are excluded from this index, following SQLite's partial-index rules. The store creates the index on the first open after upgrading; that initial creation still scans existing rows once. The store regression tests exercise an acknowledgment with unrelated queued samples under a SQLite instruction budget.

TestFlight queue write diagnostics

In Sentry Logs, search for WHOOP queue write summary. The stage values are stage_samples, drain_inbox, reserve_batch, write_upload_body, and acknowledge_batch. Compare logical_write_bytes and signpost_count by period_start, period_end, and report_build when MetricKit supplies a build. Compare stage totals across devices by build and report window. For capture_snapshot, calculate reservation WAL page deltas within each uploader instance (bufferCreatedAt). Calculate received and confirmed sample deltas within each queue generation (bufferInstanceId), including across uploader restarts. Aggregate each set of deltas by build and report window. MetricKit reports daily logical writes during signpost intervals. It provides no per-file or per-checkpoint physical byte counts. Apple MetricKit signpost measurements · Sentry Cocoa structured logging

Native bridge tests

On macOS with Xcode and an installed iPhone Simulator runtime, run from packages/mobile:

EXPO_APP_ID=00000000-0000-4000-8000-000000000000 \
EXPO_PUBLIC_SENTRY_DSN=https://[email protected]/project-id \
  pnpm prebuild --no-install
pnpm test:ios:bridge

The fixture app ID satisfies the app configuration requirement for this isolated bridge-test host; release builds must use the real app ID. The public DSN placeholder follows the app's local simulator setup. The bridge suite runs the real Expo registration and JavaScript promise path in a UIKit test host. CocoaPods generates its host and XCTest target from the module's test specification. The test host declares a window scene so it can launch on iOS 27 when built with the iOS 27 SDK. See Apple's UIKit scene lifecycle requirements. It uses Expo's official TestAppContext with a Hermes runtime and JavaScript scheduling. The runner installs source Expo modules because that helper imports ExpoModulesCore with @testable. This changes the generated local Pods installation; ordinary pnpm prebuild regenerates the normal app project. No Metro server or authenticated account is needed. The test cases exercise bridge state transitions; validate physical strap capture and background Bluetooth delivery separately on a device.

The transport tests use real URLSession tasks with a stock URLProtocol network boundary to exercise single-task delivery, credential replacement, response bounds, restoration and cancellation races. Physical acceptance with a matching native build covers foreground latency, locked-phone capture and eventual confirmation, retention across process recreation, and cancellation across account changes.

The standalone swift test suite remains separate: its target excludes the Expo bridge and the app-hosted tests, as declared in Package.swift. Central-manager tests use the production central boundary instead of unsupported Core Bluetooth subclassing. Its peripheral callback regressions exercise ownership, stale callbacks, cancellation and reconnect through the same peripheral interface used by the native adapter. The adapter preserves the underlying peripheral's notification identity across callbacks, and handshake deadlines retain their adapter until settlement. These tests cover the manager's callback policy; physical strap capture and background delivery still require a device, following Apple's CoreBluetooth background guidance.

The workspace's React Native patch preserves build-flavor markers during CocoaPods source cleanup. This retains the configuration metadata needed to select Debug frameworks after a Release archive and a test-dependency installation.

Runtime, Stability, and Errors

  • Node.js 22.14 or later is required by the package tooling.
  • iOS 16.4 or later is required by the Expo pod.
  • Connection and readiness failures reject with specific error codes and messages from the native module.
  • WHOOP firmware updates may change the private protocol without notice.

License and Contributions

Licensed under the MIT License. Source is maintained in the Dofek repository. Report issues or propose changes through GitHub.