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

@cherrystudio/analytics-client

v1.4.0

Published

Analytics client for Cherry Studio applications

Readme

@cherrystudio/analytics-client

Analytics client SDK for Cherry Studio applications. Supports batch event tracking with automatic buffering and flush.

Installation

npm install @cherrystudio/analytics-client
# or
pnpm add @cherrystudio/analytics-client
# or
yarn add @cherrystudio/analytics-client

Quick Start

import { AnalyticsClient } from '@cherrystudio/analytics-client'

// Initialize the client
const analytics = new AnalyticsClient({
  clientId: 'user-uuid-here',
  channel: 'cherry-studio',
})

// Track token usage
analytics.trackTokenUsage({
  provider: 'openai',
  model: 'gpt-4',
  input_tokens: 100,
  output_tokens: 200,
})

// Drain within the shutdown budget before app exit
await analytics.destroy()

API

Constructor Options

interface AnalyticsClientOptions {
  /** Analytics service base URL (default: https://analytics.cherry-ai.com) */
  baseUrl?: string
  /** Client unique identifier (UUID) */
  clientId: string
  /** Channel/application name */
  channel: string
  /** Enable automatic batching (default: true) */
  autoBatch?: boolean
  /** Auto-flush threshold and maximum events per request (default: 10) */
  batchSize?: number
  /** Maximum queued events; newest events drop on overflow (default: 1000) */
  maxQueueSize?: number
  /** Queued plus active requests across all endpoints (default: 100), concurrency: 1 */
  maxPendingRequests?: number
  /** Maximum serialized bytes per event (default: 65536) */
  maxEventBytes?: number
  /** Maximum serialized bytes per event request (default: 262144) */
  maxBatchBytes?: number
  /** Batch flush interval in milliseconds (default: 5000) */
  flushInterval?: number
  /** Request timeout in milliseconds (default: 10000) */
  timeout?: number
  /** Custom fetch function (for Node.js or custom implementations) */
  fetch?: typeof fetch
  /** Retry/backoff settings; defaults to three retries */
  retry?: RetryOptions
  /** Additional request headers */
  headers?: Record<string, string>
  /** Called when an error occurs */
  onError?: (error: Error) => void
}

Methods

trackTokenUsage(data, timestamp?)

Track AI token usage.

Events whose provider is local-embedding, or whose input and output token counts are both zero, are ignored and are not queued or sent to the analytics service.

analytics.trackTokenUsage({
  provider: 'openai',      // AI provider name
  model: 'gpt-4',          // Model name
  input_tokens: 100,       // Input token count
  output_tokens: 200,      // Output token count
})

// With custom timestamp (for offline tracking)
analytics.trackTokenUsage(data, new Date('2025-01-15T10:30:00Z'))

track(eventType, data, timestamp?)

Track a generic event. Useful for custom event types. Data is validated and snapshotted on entry, together with the current client ID and event time. Non-JSON data, null/undefined data, invalid dates and oversized events are rejected individually through onError, without poisoning the batch.

analytics.track('custom_event', {
  action: 'button_click',
  value: 42,
})

flush()

Flush events queued at the start of the call in requests of at most batchSize events. Returns the combined acknowledged count, or null if the queue is empty. Concurrent callers share the active flush. Events added during a flush wait for the next flush.

const result = await analytics.flush()
// { success: true, count: 5 }

sendImmediate(eventType, data, timestamp?)

Send an event immediately without batching.

await analytics.sendImmediate('token_usage', {
  provider: 'anthropic',
  model: 'claude-3',
  input_tokens: 50,
  output_tokens: 150,
})

setClientId(clientId)

Update the client ID for future events (e.g., after user login). Queued events retain their original identity; different identities are sent in separate batches. A custom Client-Id header follows the identity of each request.

analytics.setClientId('new-user-uuid')

getQueueSize()

Get the current number of pending events in the queue.

const pending = analytics.getQueueSize()

destroy(options?)

Close the client, stop accepting new work and wait for all endpoints to settle. The default is a graceful drain with a 30-second total budget, including cooldowns and retries. On expiry, requests are aborted and remaining data is locally discarded. The result reports lifetime delivery counters and timedOut. Repeated calls return the same promise. An immediate cancellation can also interrupt an already-running graceful shutdown.

const result = await analytics.destroy({ timeoutMs: 30000 })
// { acknowledgedEvents, discardedEvents, pendingEvents: 0, pendingRequests: 0, timedOut }

// Consent revocation: cancel in-flight requests and cooldowns, discard queued data.
await analytics.destroy({ flush: false })

Applications revoking consent must use flush: false; merely cancelling their fetch wrapper cannot interrupt an SDK cooldown. After closing starts, track() reports rejection through onError; immediate/activity sends reject their promises. Do not reuse a closed client.

getDeliveryStats()

Returns lifetime local counters: acknowledgedEvents, discardedEvents, pendingEvents (including in-flight events) and pendingRequests. Activity requests contribute only to the request count. Ignored token events are excluded. discardedEvents means the SDK no longer retains the event; an ambiguous network failure may mean the server already accepted it. These counters are not a billing or server persistence guarantee. getQueueSize() counts only queued batch events.

Examples

Electron App

import { AnalyticsClient } from '@cherrystudio/analytics-client'
import { app } from 'electron'

const analytics = new AnalyticsClient({
  clientId: getMachineId(),
  channel: 'cherry-studio',
  onError: (error) => console.error('Analytics error:', error),
})

// Track usage
analytics.trackTokenUsage({
  provider: 'openai',
  model: 'gpt-4',
  input_tokens: 100,
  output_tokens: 200,
})

// Flush on app quit
app.on('before-quit', async (event) => {
  event.preventDefault()
  await analytics.destroy()
  app.exit()
})

Node.js with node-fetch

import { AnalyticsClient } from '@cherrystudio/analytics-client'
import fetch from 'node-fetch'

const analytics = new AnalyticsClient({
  clientId: 'server-instance-id',
  channel: 'cherryin-backend',
  fetch: fetch as unknown as typeof globalThis.fetch,
})

Disable Auto Batching

const analytics = new AnalyticsClient({
  clientId: 'user-uuid',
  channel: 'cherry-studio',
  autoBatch: false, // Disable auto batching
})

// Manually send each event
await analytics.sendImmediate('token_usage', { ... })

Custom Batch Settings

const analytics = new AnalyticsClient({
  clientId: 'user-uuid',
  channel: 'cherry-studio',
  batchSize: 50,        // Flush when 50 events accumulated
  flushInterval: 10000, // Or every 10 seconds
})

License

MIT

Delivery and retry limits

This SDK provides best-effort, in-memory telemetry. Each batch gets at most 1 + retry.maxRetries request attempts (default: four total). Once that budget is exhausted, or a non-retriable error occurs, the attempted batch is dropped, not put back into the queue. A manual flush() rejects; automatic flushes report through onError. Failed flushes throw AnalyticsFlushError with a result snapshot of lifetime delivery counters. A flush continues through the other batches in its initial snapshot before reporting the first failure; one bad batch cannot block valid data behind it. Events added during a flush wait for the next flush.

HTTP 408, 429 and 5xx responses and supported network errors are retriable by default; other HTTP errors are not. retryAllErrors defaults to false. Retry-After (seconds or HTTP date) sets a client-wide cooldown shared by batched events, immediate events, and activity requests. Batches stay in memory while waiting, and waiting does not consume attempts. retry.maxDelay (default 30 seconds) caps exponential backoff only; a longer server cooldown is honored, including after the current batch exhausts its retries. Transient failures also apply backoff to subsequent batches. HTTP 204 acknowledges the request without a JSON body and counts all submitted events as acknowledged. Invalid bodies on successful HTTP responses are reported without retrying, since the server may already have accepted the events.

batchSize is both the automatic flush threshold and the maximum request batch size. maxQueueSize defaults to 1000 pending events, excluding the in-flight batch. When full, the newest event is dropped and reported through onError. All endpoints use a single request lane. maxPendingRequests bounds queued plus active requests (default 100); immediate/activity requests reject on overflow. Batch flushing waits for capacity instead of discarding a normal batch. batchSize and maxBatchBytes both constrain batches, and maxEventBytes constrains individual events. All byte limits are UTF-8 serialized sizes.

destroy() drains valid batches behind rejected ones within its total time budget. A timeout cancels work; it does not bypass the server cooldown. Callers must await shutdown before exiting. Pending events are not saved to disk.

These bounds prevent indefinite queue replay, but do not provide exactly-once delivery: a network timeout after server acceptance can still cause a bounded retry. Reliable deduplication requires stable event IDs and server-side idempotency. Failed/overflowed events are not persisted for later recovery.