All files / src/utils identity.ts

100% Statements 70/70
100% Branches 15/15
100% Functions 4/4
100% Lines 70/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 711x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 1x 1x 19x 19x 19x 19x 20x 8x 8x 8x 18x 18x 20x 1x 1x 1x 20x 1x 1x 1x 1x 1x 1x 6x 1x 1x 5x 5x 5x 5x 6x 1x 1x 6x 1x 1x 1x 1x 1x 1x 5x 1x 1x 4x 4x 4x 4x 5x 1x 1x 5x 1x 1x 1x 1x 1x 16x 16x 16x  
import { uuid } from './helper';
 
const ANONYMOUS_ID_KEY = 'light_sentry_aid';
 
/**
 * 获取匿名用户ID
 * 优先从 localStorage 获取已存在的ID,不存在则生成并存储
 */
export function getAnonymousId(): string | null {
  // 浏览器环境检查
  if (typeof localStorage === 'undefined') {
    return null;
  }
 
  try {
    let anonymousId = localStorage.getItem(ANONYMOUS_ID_KEY);
 
    if (!anonymousId) {
      anonymousId = uuid();
      localStorage.setItem(ANONYMOUS_ID_KEY, anonymousId);
    }
 
    return anonymousId;
  } catch {
    // localStorage 不可用(如隐私模式、跨域限制等)
    return null;
  }
}
 
/**
 * 设置匿名用户ID
 * 用于覆盖自动生成的ID
 */
export function setAnonymousId(id: string): boolean {
  if (typeof localStorage === 'undefined') {
    return false;
  }
 
  try {
    localStorage.setItem(ANONYMOUS_ID_KEY, id);
    return true;
  } catch {
    return false;
  }
}
 
/**
 * 清除匿名用户ID
 * 通常在用户登出后调用
 */
export function clearAnonymousId(): boolean {
  if (typeof localStorage === 'undefined') {
    return false;
  }
 
  try {
    localStorage.removeItem(ANONYMOUS_ID_KEY);
    return true;
  } catch {
    return false;
  }
}
 
/**
 * 检查是否启用了匿名用户追踪
 */
export function isAnonymousTrackingEnabled(config: { trackAnonymousUsers?: boolean }): boolean {
  // 默认为 true,除非明确设置为 false
  return config.trackAnonymousUsers !== false;
}