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

@ccserv/event-tracker

v1.0.4

Published

Cocos Event Tracker SDK - A JavaScript/TypeScript SDK for tracking and sending events

Downloads

16

Readme

@ccserv/event-tracker

npm version License: MIT

Cocos Event Tracker SDK 是一个用于追踪和发送事件的 JavaScript/TypeScript SDK,具有内置的时间同步和重试机制。

特性

  • 🚀 轻量级 - 小巧的包体积,无外部依赖
  • 📊 高性能 - 支持批量发送和异步处理
  • 🔄 自动重试 - 内置重试机制,确保数据可靠传输
  • 时间同步 - 自动与服务器时间同步,确保时间准确性
  • 📦 多格式 - 支持 ESM、CommonJS 和 UMD 格式
  • 🎯 TypeScript 支持 - 完整的类型定义
  • 🌐 浏览器兼容 - 支持所有现代浏览器
  • 🐛 调试模式 - 内置详细的调试日志

安装

npm

npm install @ccserv/event-tracker

yarn

yarn add @ccserv/event-tracker

CDN

<script src="https://unpkg.com/@ccserv/event-tracker/dist/index.umd.js"></script>

快速开始

ES6 模块

import CocosEventTracker from '@ccserv/event-tracker';

const tracker = new CocosEventTracker({
  apiEndpoint: 'https://your-api-domain.com/api/v1/events',
  timestampEndpoint: 'https://your-api-domain.com/api/v1/timestamp',
  appId: 'your-app-id as number',
  bundle: 'your-app-bundle',
  debug: true
});

await tracker.init('user123', 'session456');

await tracker.track('user.login', {
  login_method: 'password',
  success: true
});

CommonJS

const { CocosEventTracker } = require('@ccserv/event-tracker');

const tracker = new CocosEventTracker({
  apiEndpoint: 'https://your-api-domain.com/api/v1/events',
  appId: 'your-app-id as number',
  bundle: 'your-app-bundle'
});

await tracker.init();
await tracker.track('page.view', { page: '/dashboard' });

浏览器直接引用

<script src="./node_modules/@ccserv/event-tracker/dist/index.umd.js"></script>
<script>
  const tracker = new CocosEventTracker({
    apiEndpoint: '/api/v1/events',
    appId: 123,
    bundle: 'example.com'
  });

  tracker.init().then(() => {
    tracker.track('user.click', { button: 'signup' });
  });
</script>

配置选项

interface CocosEventTrackerConfig {
  apiEndpoint?: string;           // 事件上报 API 地址,默认: '/api/v1/events'
  timestampEndpoint?: string;     // 时间戳同步 API 地址,默认: '/api/v1/timestamp'
  appId?: number;                 // 应用 ID
  bundle?: string;                // 应用包名/域名,默认: 'unknown-app'
  language?: string;              // 语言代码,默认: 'zh-CN'
  network?: string;               // 网络类型,默认: 'unknown'
  appVersion?: string;            // 应用版本,默认: '1.0.0'
  osVersion?: string;             // 操作系统版本
  enableAutoTimestamp?: boolean;  // 启用自动时间同步,默认: true
  enableRetry?: boolean;          // 启用重试机制,默认: true
  maxRetries?: number;            // 最大重试次数,默认: 3
  retryDelay?: number;            // 重试延迟(毫秒),默认: 1000
  batchSize?: number;             // 批量发送大小,默认: 10
  batchInterval?: number;         // 批量发送间隔(毫秒),默认: 5000
  enableBatching?: boolean;       // 启用批量处理,默认: false
  debug?: boolean;                // 启用调试日志,默认: false
}

API 文档

构造函数

new CocosEventTracker(config?: CocosEventTrackerConfig)

创建一个新的 CocosEventTracker 实例。

init(userId?, sessionId?)

初始化 SDK 并同步服务器时间。

参数:

  • userId (string, optional): 用户 ID
  • sessionId (string, optional): 会话 ID

返回值: Promise<boolean> - 初始化是否成功

track(eventType, fields?, eventTimestamp?)

发送单个事件。

参数:

  • eventType (string): 事件类型
  • fields (object, optional): 事件字段
  • eventTimestamp (string, optional): 事件时间戳

返回值: Promise<boolean> - 发送是否成功

trackBatch(events)

批量发送事件。

参数:

  • events (EventInput[]): 事件数组

返回值: Promise<boolean> - 发送是否成功

setUser(userId, sessionId?)

设置当前用户信息。

参数:

  • userId (string): 用户 ID
  • sessionId (string, optional): 会话 ID

getStats()

获取 SDK 统计信息。

返回值: TrackerStats

resetStats()

重置统计信息。

flushQueue()

立即发送队列中的所有事件。

返回值: Promise<boolean> - 发送是否成功

destroy()

销毁 SDK 并清理资源。

批量处理

启用批量处理可以显著提高性能:

const tracker = new CocosEventTracker({
  apiEndpoint: '/api/v1/events',
  appId: 123,
  bundle: 'example.com',
  enableBatching: true,
  batchSize: 20,        // 20 个事件一批
  batchInterval: 5000   // 或每 5 秒一批
});

await tracker.init();

// 事件会被自动批量发送
await tracker.track('user.click', { button: 'signup' });
await tracker.track('page.view', { page: '/dashboard' });
await tracker.track('user.action', { action: 'scroll' });

错误处理

const tracker = new CocosEventTracker({
  apiEndpoint: '/api/v1/events',
  appId: 123,
  bundle: 'example.com',
  debug: true
});

const success = await tracker.init();
if (!success) {
  console.error('SDK 初始化失败');
  return;
}

const result = await tracker.track('user.login', {
  method: 'password'
});

if (!result) {
  const stats = tracker.getStats();
  console.error('事件发送失败', stats);
}

统计信息

const stats = tracker.getStats();
console.log('发送统计:', {
  总发送数: stats.totalSent,
  成功数: stats.successCount,
  失败数: stats.errorCount,
  平均响应时间: stats.avgResponseTime + 'ms',
  队列大小: stats.queueSize,
  已初始化: stats.isInitialized
});

生命周期管理

// 页面加载时初始化
let tracker;

async function initializeApp() {
  tracker = new CocosEventTracker({
    apiEndpoint: '/api/v1/events',
    appId: 123,
    bundle: 'example.com'
  });

  await tracker.init();
}

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
  if (tracker) {
    tracker.destroy();
  }
});

完整示例

import CocosEventTracker from '@ccserv/event-tracker';

class AppAnalytics {
  constructor() {
    this.tracker = new CocosEventTracker({
      apiEndpoint: 'https://api.example.com/v1/events',
      timestampEndpoint: 'https://api.example.com/v1/timestamp',
      appId: 618115551,
      bundle: 'app.example.com',
      appVersion: '1.0.0',
      language: 'zh-CN',
      enableBatching: true,
      batchSize: 10,
      batchInterval: 3000,
      debug: process.env.NODE_ENV === 'development'
    });
  }

  async initialize(userId, sessionId) {
    try {
      const success = await this.tracker.init(userId, sessionId);
      if (!success) {
        throw new Error('SDK 初始化失败');
      }

      // 追踪应用启动
      await this.trackAppStartup();

      // 追踪页面访问
      this.trackPageView();

    } catch (error) {
      console.error('Analytics 初始化失败:', error);
    }
  }

  async trackAppStartup() {
    const startTime = performance.now();
    await this.tracker.track('timing.app_startup', {
      startup_time: Math.round(startTime / 1000),
      initialization_time: Math.round(startTime * 0.3 / 1000),
      resource_load_time: Math.round(startTime * 0.7 / 1000),
      success: true
    });
  }

  trackPageView(page = window.location.pathname) {
    this.tracker.track('page.view', {
      page: page,
      title: document.title,
      referrer: document.referrer,
      timestamp: new Date().toISOString()
    });
  }

  trackUserAction(action, properties = {}) {
    this.tracker.track('user.action', {
      action: action,
      ...properties,
      timestamp: new Date().toISOString()
    });
  }

  trackError(error, context = {}) {
    this.tracker.track('error.javascript', {
      error_message: error.message,
      error_stack: error.stack,
      context: context,
      timestamp: new Date().toISOString()
    });
  }

  destroy() {
    if (this.tracker) {
      this.tracker.destroy();
    }
  }
}

// 使用示例
const analytics = new AppAnalytics();

// 应用启动时初始化
analytics.initialize('user123', 'session456');

// 追踪各种事件
analytics.trackUserAction('button_click', { button: 'signup' });
analytics.trackUserAction('form_submit', { form: 'login' });

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
  analytics.destroy();
});

开发

环境要求

  • Node.js: v22.17.1+
  • npm: v10.9.2+
  • TypeScript: v5.3.3+

开发命令

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm test

# 复制到开发环境
npm run copy:dev

许可证

MIT License

支持

如有问题或建议,请联系开发团队。