All files / src/utils field-encoder.ts

100% Statements 88/88
100% Branches 15/15
100% Functions 2/2
100% Lines 88/88

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 891x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 6x 6x 10x 23x 23x 23x 6x 6x 1x 1x 1x 1x 1x 1x 9x 5x 5x 9x 18x 18x 18x 5x 5x  
/**
 * 字段短编码映射
 * 
 * 将常用字段名编码为 2-3 个字符的短码,减少上报体积
 * 
 * 编码前:{ "type": "error", "level": "error", "message": "..." }
 * 编码后:{ "t": "e", "l": "e", "m": "..." }
 * 
 * 注意:只对最外层高频字段编码,不对嵌套对象深度编码
 * 避免复杂嵌套带来的解析问题和兼容性风险
 */
 
// SDK 端:字段名编码映射(只包含最外层高频字段)
export const FIELD_ENCODE_MAP: Record<string, string> = {
  // 基础字段
  event_id: 'eid',
  timestamp: 'ts',
  start_timestamp: 'sts',
  type: 't',
  level: 'l',
  message: 'm',
  platform: 'p',
  release: 'r',
  environment: 'e',
  fingerprint: 'fp',
  context_id: 'cid',
 
  // 用户
  user: 'u',
 
  // 标签
  tags: 'tg',
 
  // 异常
  exception: 'ex',
 
  // 请求
  request: 'req',
 
  // 上下文
  contexts: 'ctx',
 
  // 面包屑
  breadcrumbs: 'bc',
 
  // Transaction
  transaction: 'tx',
  duration: 'd',
  spans: 'sp',
 
  // 额外信息
  extra: 'xt',
};
 
// 服务端:字段名解码映射(反向)
export const FIELD_DECODE_MAP: Record<string, string> = Object.fromEntries(
  Object.entries(FIELD_ENCODE_MAP).map(([k, v]) => [v, k])
);
 
/**
 * 编码事件字段名(SDK 端使用)
 * 只对最外层字段编码,避免深度编码的复杂性
 */
export function encodeFields(obj: Record<string, unknown>): Record<string, unknown> {
  if (!obj || typeof obj !== 'object') return obj;
 
  const result: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(obj)) {
    const shortKey = FIELD_ENCODE_MAP[key] || key;
    result[shortKey] = value;
  }
  return result;
}
 
/**
 * 解码事件字段名(服务端使用)
 * 只对最外层字段解码
 */
export function decodeFields(obj: Record<string, unknown>): Record<string, unknown> {
  if (!obj || typeof obj !== 'object') return obj;
 
  const result: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(obj)) {
    const fullKey = FIELD_DECODE_MAP[key] || key;
    result[fullKey] = value;
  }
  return result;
}