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

@optima-chat/analytics-sdk

v0.1.1

Published

Optima Analytics SDK - Browser-based user behavior tracking

Downloads

183

Readme

@optima-chat/analytics-sdk

Optima Analytics SDK - 用于电商网站的用户行为追踪。

安装

npm install @optima-chat/analytics-sdk

快速开始

import { Analytics } from '@optima-chat/analytics-sdk';

const analytics = new Analytics({
  environment: 'production', // 'production' | 'stage'
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  merchantId: 'your-merchant-id',
});

analytics.init();

// 追踪页面浏览
analytics.page();

// 追踪商品浏览
analytics.productViewed('product-123', { name: 'iPhone 15', price: 999 });

// 追踪加入购物车
analytics.productAddedToCart('product-123', 1);

配置选项

interface AnalyticsConfig {
  // 必填
  clientId: string; // OAuth Client ID
  clientSecret: string; // OAuth Client Secret
  merchantId: string; // 商户 ID

  // 可选
  environment?: 'production' | 'stage' | 'development'; // 默认 'production'
  productId?: string; // 数据来源标识,如 'optima-store'
  autoTrack?: boolean; // 自动追踪页面浏览,默认 true
  debug?: boolean; // 开启调试日志,默认 false
  batchSize?: number; // 批量发送阈值,默认 10
  flushInterval?: number; // 自动发送间隔(ms),默认 5000
  sessionTimeout?: number; // 会话超时(ms),默认 30 分钟
}

环境配置

SDK 根据 environment 自动选择正确的服务端点:

| 环境 | Auth URL | Collect Endpoint | | ----------- | ----------------------------- | --------------------------------------- | | production | https://auth.optima.onl | https://bi-api.optima.onl/collect | | stage | https://auth.stage.optima.onl | https://bi-api.stage.optima.onl/collect | | development | https://auth.optima.chat | https://bi-api.optima.chat/collect |

OAuth 凭据获取

联系管理员获取 clientIdclientSecret,凭据存储在 .env.analytics 文件中。

追踪方法

页面浏览

// 基础页面浏览(自动获取页面信息)
analytics.page();

// 带自定义属性
analytics.page({ category: 'products', section: 'electronics' });

商品相关

// 商品浏览
analytics.productViewed('product-id', {
  name: 'Product Name',
  price: 99.99,
  category: 'Electronics',
});

// 商品列表浏览
analytics.productListViewed('category-page', [
  { product_id: 'prod-1', name: 'Product 1' },
  { product_id: 'prod-2', name: 'Product 2' },
]);

// 加入购物车
analytics.productAddedToCart('product-id', 2, { variant: 'blue' });

// 从购物车移除
analytics.productRemovedFromCart('product-id', 1);

// 加入心愿单
analytics.productAddedToWishlist('product-id');

购物流程

// 查看购物车
analytics.cartViewed(
  [
    { product_id: 'prod-1', quantity: 2 },
    { product_id: 'prod-2', quantity: 1 },
  ],
  299.99 // 购物车总价
);

// 开始结账
analytics.checkoutStarted({ step: 1, payment_method: 'credit_card' });

// 完成订单
analytics.orderCompleted('order-123', 299.99, {
  currency: 'USD',
  products_count: 3,
});

搜索

// 执行搜索
analytics.searchPerformed('iphone', 15); // 关键词, 结果数

// 点击搜索结果
analytics.searchResultClicked('iphone', 'product-123', 3); // 关键词, 商品ID, 位置

自定义事件

analytics.track('custom_event', {
  custom_property: 'value',
  another_property: 123,
});

用户识别

// 用户登录后调用
analytics.identify('user-123');

手动控制

// 立即发送队列中的事件
await analytics.flushAsync();

// 重置 SDK 状态(如用户登出)
analytics.reset();

// 获取 SDK 指标
const metrics = analytics.getMetrics();
console.log(metrics);
// {
//   eventsTracked: 50,
//   eventsSent: 48,
//   eventsFailed: 2,
//   eventsPending: 0,
//   sendSuccessRate: 0.96,
//   retries: 3,
//   storageUsed: 1024,
// }

SPA 支持

SDK 自动监听 history.pushStatehistory.replaceStatepopstate 事件,在 SPA 路由变化时自动追踪页面浏览。

如需关闭自动追踪:

const analytics = new Analytics({
  // ...
  autoTrack: false,
});

// 手动追踪
router.afterEach((to) => {
  analytics.page({ path: to.path });
});

离线支持

SDK 使用 localStorage 持久化未发送的事件,在网络恢复后自动重试发送。

在 React 中使用

// analytics.ts
import { Analytics } from '@optima-chat/analytics-sdk';

export const analytics = new Analytics({
  environment: process.env.NODE_ENV === 'production' ? 'production' : 'stage',
  clientId: process.env.REACT_APP_ANALYTICS_CLIENT_ID!,
  clientSecret: process.env.REACT_APP_ANALYTICS_CLIENT_SECRET!,
  merchantId: process.env.REACT_APP_MERCHANT_ID!,
});

// App.tsx
import { useEffect } from 'react';
import { analytics } from './analytics';

function App() {
  useEffect(() => {
    analytics.init();
  }, []);

  return <div>...</div>;
}

// ProductPage.tsx
import { analytics } from './analytics';

function ProductPage({ product }) {
  useEffect(() => {
    analytics.productViewed(product.id, {
      name: product.name,
      price: product.price,
    });
  }, [product.id]);

  const handleAddToCart = () => {
    analytics.productAddedToCart(product.id, 1);
    // ... add to cart logic
  };

  return <button onClick={handleAddToCart}>Add to Cart</button>;
}

在 Vue 中使用

// plugins/analytics.ts
import { Analytics } from '@optima-chat/analytics-sdk';

export const analytics = new Analytics({
  environment: import.meta.env.PROD ? 'production' : 'stage',
  clientId: import.meta.env.VITE_ANALYTICS_CLIENT_ID,
  clientSecret: import.meta.env.VITE_ANALYTICS_CLIENT_SECRET,
  merchantId: import.meta.env.VITE_MERCHANT_ID,
});

// main.ts
import { analytics } from './plugins/analytics';
analytics.init();

// composables/useAnalytics.ts
import { analytics } from '../plugins/analytics';

export function useAnalytics() {
  return analytics;
}

// ProductView.vue
<script setup>
import { onMounted } from 'vue';
import { useAnalytics } from '@/composables/useAnalytics';

const props = defineProps(['product']);
const analytics = useAnalytics();

onMounted(() => {
  analytics.productViewed(props.product.id, {
    name: props.product.name,
    price: props.product.price,
  });
});
</script>

调试

开启 debug 模式查看详细日志:

const analytics = new Analytics({
  // ...
  debug: true,
});

控制台输出示例:

[Analytics] Analytics initialized { clientId: '...', merchantId: '...', endpoint: '...' }
[Analytics] Event tracked { eventName: 'page_viewed', queueSize: 1 }
[Analytics] Access token obtained { expiresIn: 3600 }
[Analytics] Flushing events { count: 5 }
[Analytics] Events sent successfully { count: 5 }

数据查看

使用 bi-cli 查看收集的数据:

# 安装
npm install -g @optima-chat/bi-cli

# 登录
bi-cli auth login

# 查看流量概览
bi-cli traffic overview

# 查看转化漏斗
bi-cli traffic funnel

License

MIT