@cherrystudio/analytics-client

中文文档
1.4.0发布于 2026/09/20MITTypeScriptESM + CJS零依赖近 30 天下载 1.9万

Analytics client for Cherry Studio applications

原始使用文档
文档目录12 节
  1. Installation
  2. Quick Start
  3. API
  4. Constructor Options
  5. Methods
  6. Examples
  7. Electron App
  8. Node.js with node-fetch
  9. Disable Auto Batching
  10. Custom Batch Settings
  11. License
  12. Delivery and retry limits

@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.

版本与发布记录

@cherrystudio/analytics-client 共发布 9 个版本,首次发布于 2026/02/08;过去 12 个月发布了 9 个版本。

版本发布日期距今
1.4.0latest2026/09/201 个月前
1.3.12026/08/252 个月前
1.3.02026/04/097 个月前
1.2.02026/03/227 个月前
1.1.32026/03/098 个月前
1.1.22026/03/098 个月前

关于 @cherrystudio/analytics-client 的常见问题

@cherrystudio/analytics-client 是什么?

Analytics client for Cherry Studio applications

如何安装 @cherrystudio/analytics-client?

在项目目录运行 npm install @cherrystudio/analytics-client,或使用 pnpm add / yarn add / bun add。

@cherrystudio/analytics-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cherrystudio/analytics-client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cherrystudio/analytics-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cherrystudio/analytics-client 可以商用吗?

@cherrystudio/analytics-client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cherrystudio/analytics-client 的下载量有多少?

根据 npm 官方下载统计,@cherrystudio/analytics-client 在 2026/10/10 – 2026/11/08 这 30 天内被下载 19,085 次,日均约 636 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cherrystudio/analytics-client 还在维护吗?

最新版本 1.4.0 发布于 2026/09/20(1 个月前);至今共发布 9 个版本,其中过去 12 个月发布了 9 个;首次发布于 2026/02/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。