@yysports/tools 3.0.3 → 3.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,3 @@
1
1
  @yysports/tools
2
+
3
+ 常用工具函数库
@@ -2,21 +2,18 @@ import { type TrackV3Event } from '../interfaces/protocol';
2
2
  /**
3
3
  * 批量日志队列(通道 1)。
4
4
  *
5
- * 发送语义:sendBeacon 返回值只表示浏览器是否成功入队,无法感知服务端 4xx/413——
6
- * 因此只对「入队失败」重试,被服务端拒绝的丢数由服务端侧计数告警补偿。
5
+ * 发送语义是**尽力而为**:`sendBeacon` / `fetch` 都无法感知服务端 4xx/413,因此不做队列
6
+ * 驻留与重试,入队失败即丢弃该批,被拒的丢数由服务端侧计数告警补偿。
7
7
  * 无 sendBeacon 环境(部分 WebView / 老浏览器)降级用 fetch(keepalive) 发送。
8
8
  */
9
9
  export default class Beacon {
10
10
  private static _queue;
11
11
  private static _timer;
12
- /** 连续发送失败次数,超过重试上限后丢弃当前批次,避免队列无限增长 */
13
- private static _failCount;
14
- private static readonly MAX_RETRIES;
15
12
  /** 启动定时 flush(Track.init 时调用) */
16
13
  static start(): void;
17
14
  /** 入队,达到 batchSize 立即 flush */
18
15
  static push(event: TrackV3Event): void;
19
- /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
16
+ /** 按批发送并出队;发送失败同样出队(尽力而为,不驻留重试) */
20
17
  static flush(): void;
21
18
  private static sendBatch;
22
19
  private static trySendBeacon;
@@ -6,12 +6,11 @@ import { TRACK_CONTENT_TYPE, TRACK_LIMITS } from "../interfaces/protocol";
6
6
  import Config from "./Config";
7
7
  import { buildEnvelopeBase, trackUrl } from "./envelope";
8
8
 
9
- /** 发送结果:sent 已发出;retry 保留队列下次重试;drop 超过重试上限丢弃该批 */
10
9
  /**
11
10
  * 批量日志队列(通道 1)。
12
11
  *
13
- * 发送语义:sendBeacon 返回值只表示浏览器是否成功入队,无法感知服务端 4xx/413——
14
- * 因此只对「入队失败」重试,被服务端拒绝的丢数由服务端侧计数告警补偿。
12
+ * 发送语义是**尽力而为**:`sendBeacon` / `fetch` 都无法感知服务端 4xx/413,因此不做队列
13
+ * 驻留与重试,入队失败即丢弃该批,被拒的丢数由服务端侧计数告警补偿。
15
14
  * 无 sendBeacon 环境(部分 WebView / 老浏览器)降级用 fetch(keepalive) 发送。
16
15
  */
17
16
  var Beacon = /*#__PURE__*/function () {
@@ -35,13 +34,18 @@ var Beacon = /*#__PURE__*/function () {
35
34
  key: "push",
36
35
  value: function push(event) {
37
36
  var _Config$data$batchSiz;
37
+ // 未 init(appId 为空)时报出的数据无归属、必被服务端 403/400 拒,直接丢弃并提示调用方
38
+ if (!Config.data.appId) {
39
+ console.warn('[Track] 尚未调用 Track.init(appId 为空),该条上报已丢弃');
40
+ return;
41
+ }
38
42
  this._queue.push(event);
39
43
  if (this._queue.length >= ((_Config$data$batchSiz = Config.data.batchSize) !== null && _Config$data$batchSiz !== void 0 ? _Config$data$batchSiz : TRACK_LIMITS.maxItems)) {
40
44
  this.flush();
41
45
  }
42
46
  }
43
47
 
44
- /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
48
+ /** 按批发送并出队;发送失败同样出队(尽力而为,不驻留重试) */
45
49
  }, {
46
50
  key: "flush",
47
51
  value: function flush() {
@@ -52,8 +56,7 @@ var Beacon = /*#__PURE__*/function () {
52
56
  var payload = _objectSpread(_objectSpread({}, buildEnvelopeBase()), {}, {
53
57
  events: batch
54
58
  });
55
- if (this.sendBatch(JSON.stringify(payload)) === 'retry') return;
56
- // sent / drop 都出队
59
+ this.sendBatch(JSON.stringify(payload));
57
60
  this._queue.splice(0, batch.length);
58
61
  }
59
62
  }
@@ -61,17 +64,9 @@ var Beacon = /*#__PURE__*/function () {
61
64
  key: "sendBatch",
62
65
  value: function sendBatch(payload) {
63
66
  // 优先 sendBeacon(页面卸载场景仍可送达);不可用或入队失败时降级 fetch(keepalive)
64
- var sent = this.trySendBeacon(payload) || this.trySendKeepalive(payload);
65
- if (sent) {
66
- this._failCount = 0;
67
- return 'sent';
68
- }
69
- this._failCount += 1;
70
- if (this._failCount > this.MAX_RETRIES) {
71
- this._failCount = 0;
72
- return 'drop';
67
+ if (!this.trySendBeacon(payload)) {
68
+ this.trySendKeepalive(payload);
73
69
  }
74
- return 'retry';
75
70
  }
76
71
  }, {
77
72
  key: "trySendBeacon",
@@ -90,7 +85,7 @@ var Beacon = /*#__PURE__*/function () {
90
85
  }, {
91
86
  key: "trySendKeepalive",
92
87
  value: function trySendKeepalive(payload) {
93
- if (typeof fetch !== 'function') return false;
88
+ if (typeof fetch !== 'function') return;
94
89
  try {
95
90
  void fetch(trackUrl('/batch'), {
96
91
  method: 'POST',
@@ -102,9 +97,8 @@ var Beacon = /*#__PURE__*/function () {
102
97
  }).catch(function () {
103
98
  return undefined;
104
99
  });
105
- return true;
106
100
  } catch (error) {
107
- return false;
101
+ // 同步抛错(如 URL 非法)时同样丢弃该批:尽力而为,不重试
108
102
  }
109
103
  }
110
104
  }]);
@@ -112,7 +106,4 @@ var Beacon = /*#__PURE__*/function () {
112
106
  }();
113
107
  _defineProperty(Beacon, "_queue", []);
114
108
  _defineProperty(Beacon, "_timer", null);
115
- /** 连续发送失败次数,超过重试上限后丢弃当前批次,避免队列无限增长 */
116
- _defineProperty(Beacon, "_failCount", 0);
117
- _defineProperty(Beacon, "MAX_RETRIES", 3);
118
109
  export { Beacon as default };
@@ -1,3 +1,4 @@
1
+ import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
1
2
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
2
3
  import _createClass from "@babel/runtime/helpers/esm/createClass";
3
4
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
@@ -16,7 +17,14 @@ var Config = /*#__PURE__*/function () {
16
17
  if (!((_config$domain = config.domain) !== null && _config$domain !== void 0 && _config$domain.trim())) {
17
18
  throw new Error('Config: domain is required');
18
19
  }
19
- Object.assign(this._data, config);
20
+ // 过滤显式 undefined 的键:`Object.assign` 会把 undefined 写进配置、清空已有值
21
+ // (如重复 init 时 `appVersion: undefined` 会抹掉先前设置的版本号)
22
+ var defined = Object.fromEntries(Object.entries(config).filter(function (_ref) {
23
+ var _ref2 = _slicedToArray(_ref, 2),
24
+ value = _ref2[1];
25
+ return value !== undefined;
26
+ }));
27
+ Object.assign(this._data, defined);
20
28
  }
21
29
  }, {
22
30
  key: "data",
@@ -4,6 +4,22 @@ import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
4
4
  import Beacon from "./Beacon";
5
5
  import Config from "./Config";
6
6
  import Log from "./Log";
7
+
8
+ /**
9
+ * 归一化错误描述。
10
+ *
11
+ * 资源加载错误的 `event.message` 常为空串或缺省,而服务端 `message` 为必填(空值整条 400)。
12
+ * 这类错误能拿到失败资源的地址,用它兜底生成可读 message,避免错误整条丢失;
13
+ * 两者都取不到时返回空串,由 `Log.errorLog` 统一丢弃并告警。
14
+ */
15
+ function resolveErrorMessage(event) {
16
+ var _event$message, _target$src;
17
+ var message = (_event$message = event.message) === null || _event$message === void 0 ? void 0 : _event$message.trim();
18
+ if (message) return message;
19
+ var target = event.target;
20
+ var failedUrl = (_target$src = target === null || target === void 0 ? void 0 : target.src) !== null && _target$src !== void 0 ? _target$src : target === null || target === void 0 ? void 0 : target.href;
21
+ return failedUrl ? "\u8D44\u6E90\u52A0\u8F7D\u5931\u8D25\uFF1A".concat(failedUrl) : '';
22
+ }
7
23
  var Listener = /*#__PURE__*/function () {
8
24
  function Listener() {
9
25
  _classCallCheck(this, Listener);
@@ -16,7 +32,9 @@ var Listener = /*#__PURE__*/function () {
16
32
  return;
17
33
  }
18
34
 
19
- // 监听全局未捕获的错误,同时进行防抖处理,高频报错时只上报最后一条
35
+ // 监听全局未捕获的错误,同时进行防抖处理,高频报错时只上报最后一条。
36
+ // capture: true 必须保留——资源加载错误(img / script / link)不冒泡,
37
+ // 只有捕获阶段才能在 window 上监听到,否则这类错误完全采集不到
20
38
  window.addEventListener('error', function (event) {
21
39
  if (_this._reporter) {
22
40
  clearTimeout(_this._reporter);
@@ -25,10 +43,10 @@ var Listener = /*#__PURE__*/function () {
25
43
  var _event$error;
26
44
  // 立即触发上报当前剩余的 Beacon 数据
27
45
  Beacon.flush();
28
- Log.errorLog(event.message, (_event$error = event.error) === null || _event$error === void 0 ? void 0 : _event$error.stack);
46
+ Log.errorLog(resolveErrorMessage(event), (_event$error = event.error) === null || _event$error === void 0 ? void 0 : _event$error.stack);
29
47
  _this._reporter = null;
30
48
  }, 1000);
31
- });
49
+ }, true);
32
50
 
33
51
  // 页面隐藏 / 卸载前兜底 flush,保证队列数据送达
34
52
  document.addEventListener('visibilitychange', function () {
@@ -7,6 +7,13 @@
7
7
  export default class Log {
8
8
  private static _module;
9
9
  static get module(): string;
10
+ /**
11
+ * 条级业务内容超列宽时丢弃该条。
12
+ *
13
+ * `content` 是接入方传入的业务内容:截断会改变语义、把「数据丢失」伪装成「数据完整」,
14
+ * 故选择丢弃 + `console.warn`——联调期即可暴露,且不会让同批其他条一起被 400 拒掉。
15
+ */
16
+ private static isContentOverlong;
10
17
  static visitLog(module: string): void;
11
18
  static eventLog(content: string): void;
12
19
  static apiLog(log: string): void;
package/dist/Track/Log.js CHANGED
@@ -4,9 +4,9 @@ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
4
4
  import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
5
5
  import _createClass from "@babel/runtime/helpers/esm/createClass";
6
6
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
7
- import { TRACK_CONTENT_TYPE } from "../interfaces/protocol";
7
+ import { TRACK_CONTENT_TYPE, TRACK_LIMITS } from "../interfaces/protocol";
8
8
  import Beacon from "./Beacon";
9
- import { buildEnvelopeBase, buildEventBase, trackUrl } from "./envelope";
9
+ import { buildEnvelopeBase, buildEventBase, trackUrl, truncate } from "./envelope";
10
10
  import Replay from "./Replay";
11
11
 
12
12
  /**
@@ -26,20 +26,39 @@ var Log = /*#__PURE__*/function () {
26
26
  function get() {
27
27
  return this._module;
28
28
  }
29
+
30
+ /**
31
+ * 条级业务内容超列宽时丢弃该条。
32
+ *
33
+ * `content` 是接入方传入的业务内容:截断会改变语义、把「数据丢失」伪装成「数据完整」,
34
+ * 故选择丢弃 + `console.warn`——联调期即可暴露,且不会让同批其他条一起被 400 拒掉。
35
+ */
36
+ }, {
37
+ key: "isContentOverlong",
38
+ value: function isContentOverlong(content) {
39
+ if (typeof content !== 'string' || content.length <= TRACK_LIMITS.content) {
40
+ return false;
41
+ }
42
+ console.warn("[Track] content \u957F\u5EA6 ".concat(content.length, " \u8D85\u8FC7\u4E0A\u9650 ").concat(TRACK_LIMITS.content, "\uFF08\u670D\u52A1\u7AEF\u4F1A\u6574\u6279 400\uFF09\uFF0C\u5DF2\u4E22\u5F03\u8BE5\u6761\u65E5\u5FD7"));
43
+ return true;
44
+ }
29
45
  }, {
30
46
  key: "visitLog",
31
47
  value: function visitLog(module) {
32
- this._module = module;
48
+ // module 会缓存在 _module 上被后续 event / api 事件复用,超列宽时截断而非丢弃:
49
+ // 丢弃不仅丢掉本次访问,还会让后续所有带 module 的事件一并消失
50
+ this._module = truncate(module, TRACK_LIMITS.module);
33
51
  var lastModule = this._module.split('-').pop();
34
52
  Beacon.push(_objectSpread(_objectSpread({}, buildEventBase()), {}, {
35
53
  type: 'visit',
36
- module: module,
54
+ module: this._module,
37
55
  content: "\u8BBF\u95EE\u9875\u9762\uFF1A".concat(lastModule)
38
56
  }));
39
57
  }
40
58
  }, {
41
59
  key: "eventLog",
42
60
  value: function eventLog(content) {
61
+ if (this.isContentOverlong(content)) return;
43
62
  Beacon.push(_objectSpread(_objectSpread({}, buildEventBase()), {}, {
44
63
  type: 'event',
45
64
  module: this._module,
@@ -69,6 +88,13 @@ var Log = /*#__PURE__*/function () {
69
88
  return _regeneratorRuntime().wrap(function _callee$(_context) {
70
89
  while (1) switch (_context.prev = _context.next) {
71
90
  case 0:
91
+ if (!(typeof message !== 'string' || !message.trim())) {
92
+ _context.next = 3;
93
+ break;
94
+ }
95
+ console.warn('[Track] errorLog 的 message 为空(服务端会整条 400),已丢弃该条错误上报');
96
+ return _context.abrupt("return");
97
+ case 3:
72
98
  replay = Replay.snapshot();
73
99
  pureError = _objectSpread(_objectSpread({}, buildEnvelopeBase()), {}, {
74
100
  error: _objectSpread(_objectSpread({}, buildEventBase()), {}, {
@@ -80,8 +106,8 @@ var Log = /*#__PURE__*/function () {
80
106
  payload = replay.length ? _objectSpread(_objectSpread({}, pureError), {}, {
81
107
  replay: replay
82
108
  }) : pureError;
83
- _context.prev = 3;
84
- _context.next = 6;
109
+ _context.prev = 6;
110
+ _context.next = 9;
85
111
  return fetch(trackUrl('/error'), {
86
112
  method: 'POST',
87
113
  headers: {
@@ -89,21 +115,21 @@ var Log = /*#__PURE__*/function () {
89
115
  },
90
116
  body: JSON.stringify(payload)
91
117
  });
92
- case 6:
118
+ case 9:
93
119
  res = _context.sent;
94
120
  if (res.ok) {
95
- _context.next = 9;
121
+ _context.next = 12;
96
122
  break;
97
123
  }
98
124
  throw new Error("HTTP ".concat(res.status));
99
- case 9:
125
+ case 12:
100
126
  // 上报成功后才移除已携带的回放事件,继续录制(不 stop)
101
127
  Replay.commitSnapshot(replay);
102
- _context.next = 15;
128
+ _context.next = 18;
103
129
  break;
104
- case 12:
105
- _context.prev = 12;
106
- _context.t0 = _context["catch"](3);
130
+ case 15:
131
+ _context.prev = 15;
132
+ _context.t0 = _context["catch"](6);
107
133
  try {
108
134
  (_navigator = navigator) === null || _navigator === void 0 || (_navigator$sendBeacon = _navigator.sendBeacon) === null || _navigator$sendBeacon === void 0 || _navigator$sendBeacon.call(_navigator, trackUrl('/error'), new Blob([JSON.stringify(pureError)], {
109
135
  type: TRACK_CONTENT_TYPE
@@ -111,11 +137,11 @@ var Log = /*#__PURE__*/function () {
111
137
  } catch (beaconError) {
112
138
  // beacon 也不可用(如页面已卸载),放弃本次错误上报,不阻断业务
113
139
  }
114
- case 15:
140
+ case 18:
115
141
  case "end":
116
142
  return _context.stop();
117
143
  }
118
- }, _callee, this, [[3, 12]]);
144
+ }, _callee, this, [[6, 15]]);
119
145
  }));
120
146
  function errorLog(_x, _x2) {
121
147
  return _errorLog.apply(this, arguments);
@@ -2,6 +2,7 @@ type RRWebEvent = any;
2
2
  export default class Replay {
3
3
  private static _events;
4
4
  private static _stop;
5
+ private static _record;
5
6
  private static _loading;
6
7
  private static _bytes;
7
8
  /**
@@ -13,11 +14,34 @@ export default class Replay {
13
14
  * 错误本体的上报不受影响)。
14
15
  */
15
16
  static run(): Promise<void>;
16
- /** 截断到体积上限,保留最近片段 */
17
+ /**
18
+ * 停止录制并清空缓存。
19
+ *
20
+ * `Replay.run` 的幂等只看 `_stop`,`init({ enableReplay: false })` 不会让已启动的录制停下,
21
+ * 因此 `Track.run` 在关闭回放时显式调用本方法。
22
+ */
23
+ static stop(): void;
24
+ /**
25
+ * 截断到体积上限:整体重开一段,并请求一张新的完整快照。
26
+ *
27
+ * 片段必须自带播放起点(在缓冲区头部),丢掉起点整段就无法播放,而起点之后的事件
28
+ * 全是增量、丢了画面又不完整,所以这里不做「从头丢事件」,直接重开一段。
29
+ */
17
30
  private static truncate;
31
+ /** 缓冲区头部的起点事件(Meta / FullSnapshot);无起点时返回空数组 */
32
+ private static replayStartEvents;
33
+ /** 请求 rrweb 立刻产出一张 FullSnapshot(失败静默,仅影响回放可用性) */
34
+ private static requestFullSnapshot;
35
+ /** 事件数组的近似序列化体积(与 emit 中的累计口径一致) */
36
+ private static bytesOf;
18
37
  /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
19
38
  static snapshot(): RRWebEvent[];
20
- /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
39
+ /**
40
+ * 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段。
41
+ *
42
+ * 起点事件(Meta / FullSnapshot)保留在缓冲区:随本次上报一起移除后,下一段回放
43
+ * 只剩增量事件、播放器无法独立渲染。
44
+ */
21
45
  static commitSnapshot(snapshot: RRWebEvent[]): void;
22
46
  }
23
47
  export {};
@@ -7,6 +7,19 @@ import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
7
7
  import _createClass from "@babel/runtime/helpers/esm/createClass";
8
8
  import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
9
9
  import Config from "./Config";
10
+ /** rrweb 事件类型:4 = Meta(播放器元信息),2 = FullSnapshot(片段起点) */
11
+ var RRWEB_META = 4;
12
+ var RRWEB_FULL_SNAPSHOT = 2;
13
+
14
+ /**
15
+ * 播放起点判定:rrweb 播放器必须有 `Meta` + `FullSnapshot` 才能独立渲染,
16
+ * 只剩增量事件时画面空白/报错。
17
+ */
18
+ var isReplayStartEvent = function isReplayStartEvent(event) {
19
+ return (event === null || event === void 0 ? void 0 : event.type) === RRWEB_META || (event === null || event === void 0 ? void 0 : event.type) === RRWEB_FULL_SNAPSHOT;
20
+ };
21
+
22
+ /** rrweb record 函数(带命名空间成员 takeFullSnapshot) */
10
23
  var Replay = /*#__PURE__*/function () {
11
24
  function Replay() {
12
25
  _classCallCheck(this, Replay);
@@ -44,6 +57,7 @@ var Replay = /*#__PURE__*/function () {
44
57
  _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
45
58
  startRecord = _yield$Promise$all2[0].record;
46
59
  getRecordConsolePlugin = _yield$Promise$all2[1].getRecordConsolePlugin;
60
+ this._record = startRecord;
47
61
  this._stop = startRecord(_objectSpread(_objectSpread({
48
62
  emit: function emit(e) {
49
63
  _this._events.push(e);
@@ -62,39 +76,101 @@ var Replay = /*#__PURE__*/function () {
62
76
  level: ['log', 'info', 'warn', 'error', 'debug']
63
77
  })]
64
78
  }));
65
- _context.next = 16;
79
+ _context.next = 18;
66
80
  break;
67
- case 13:
68
- _context.prev = 13;
81
+ case 14:
82
+ _context.prev = 14;
69
83
  _context.t0 = _context["catch"](3);
70
84
  // 加载或启动失败:静默降级,仅回放不可用
71
85
  this._stop = undefined;
72
- case 16:
73
- _context.prev = 16;
86
+ this._record = undefined;
87
+ case 18:
88
+ _context.prev = 18;
74
89
  this._loading = false;
75
- return _context.finish(16);
76
- case 19:
90
+ return _context.finish(18);
91
+ case 21:
77
92
  case "end":
78
93
  return _context.stop();
79
94
  }
80
- }, _callee, this, [[3, 13, 16, 19]]);
95
+ }, _callee, this, [[3, 14, 18, 21]]);
81
96
  }));
82
97
  function run() {
83
98
  return _run.apply(this, arguments);
84
99
  }
85
100
  return run;
86
- }() /** 截断到体积上限,保留最近片段 */)
101
+ }()
102
+ /**
103
+ * 停止录制并清空缓存。
104
+ *
105
+ * `Replay.run` 的幂等只看 `_stop`,`init({ enableReplay: false })` 不会让已启动的录制停下,
106
+ * 因此 `Track.run` 在关闭回放时显式调用本方法。
107
+ */
108
+ )
109
+ }, {
110
+ key: "stop",
111
+ value: function stop() {
112
+ if (this._stop) {
113
+ this._stop();
114
+ }
115
+ this._stop = undefined;
116
+ this._events = [];
117
+ this._bytes = 0;
118
+ }
119
+
120
+ /**
121
+ * 截断到体积上限:整体重开一段,并请求一张新的完整快照。
122
+ *
123
+ * 片段必须自带播放起点(在缓冲区头部),丢掉起点整段就无法播放,而起点之后的事件
124
+ * 全是增量、丢了画面又不完整,所以这里不做「从头丢事件」,直接重开一段。
125
+ */
87
126
  }, {
88
127
  key: "truncate",
89
128
  value: function truncate() {
90
129
  var _Config$data$replayMa;
91
130
  var maxBytes = (_Config$data$replayMa = Config.data.replayMaxBytes) !== null && _Config$data$replayMa !== void 0 ? _Config$data$replayMa : 1024 * 1024;
92
- while (this._bytes > maxBytes && this._events.length > 1) {
93
- var removed = this._events.shift();
94
- this._bytes -= removed ? JSON.stringify(removed).length : 0;
131
+ if (this._bytes <= maxBytes) return;
132
+
133
+ // 起点自身就超过上限时重开也降不下来(新快照同样大):放弃截断,
134
+ // 否则每次 emit 都会重开一段、回放数据全被冲掉
135
+ var startBytes = Replay.bytesOf(Replay.replayStartEvents(this._events));
136
+ if (startBytes > maxBytes) return;
137
+
138
+ // Meta 体积很小但播放器渲染要用,保留它,再请求一张新的 FullSnapshot 组成新片段
139
+ this._events = this._events.filter(function (e) {
140
+ return (e === null || e === void 0 ? void 0 : e.type) === RRWEB_META;
141
+ }).slice(0, 1);
142
+ this._bytes = Replay.bytesOf(this._events);
143
+ Replay.requestFullSnapshot();
144
+ }
145
+
146
+ /** 缓冲区头部的起点事件(Meta / FullSnapshot);无起点时返回空数组 */
147
+ }, {
148
+ key: "replayStartEvents",
149
+ value: function replayStartEvents(events) {
150
+ return events.slice(0, 2).filter(isReplayStartEvent);
151
+ }
152
+
153
+ /** 请求 rrweb 立刻产出一张 FullSnapshot(失败静默,仅影响回放可用性) */
154
+ }, {
155
+ key: "requestFullSnapshot",
156
+ value: function requestFullSnapshot() {
157
+ try {
158
+ var _Replay$_record, _Replay$_record$takeF;
159
+ (_Replay$_record = Replay._record) === null || _Replay$_record === void 0 || (_Replay$_record$takeF = _Replay$_record.takeFullSnapshot) === null || _Replay$_record$takeF === void 0 || _Replay$_record$takeF.call(_Replay$_record, true);
160
+ } catch (err) {
161
+ // 忽略:下一张快照产出前,回放片段不可独立播放
95
162
  }
96
163
  }
97
164
 
165
+ /** 事件数组的近似序列化体积(与 emit 中的累计口径一致) */
166
+ }, {
167
+ key: "bytesOf",
168
+ value: function bytesOf(events) {
169
+ return events.reduce(function (sum, e) {
170
+ return sum + JSON.stringify(e).length;
171
+ }, 0);
172
+ }
173
+
98
174
  /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
99
175
  }, {
100
176
  key: "snapshot",
@@ -102,16 +178,22 @@ var Replay = /*#__PURE__*/function () {
102
178
  return this._stop ? _toConsumableArray(this._events) : [];
103
179
  }
104
180
 
105
- /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
181
+ /**
182
+ * 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段。
183
+ *
184
+ * 起点事件(Meta / FullSnapshot)保留在缓冲区:随本次上报一起移除后,下一段回放
185
+ * 只剩增量事件、播放器无法独立渲染。
186
+ */
106
187
  }, {
107
188
  key: "commitSnapshot",
108
189
  value: function commitSnapshot(snapshot) {
109
190
  var _this2 = this;
110
191
  if (!snapshot.length) return;
111
192
  var sent = new Set(snapshot);
112
- this._events = this._events.filter(function (e) {
113
- if (sent.has(e)) {
114
- _this2._bytes -= JSON.stringify(e).length;
193
+ this._events = this._events.filter(function (event) {
194
+ if (isReplayStartEvent(event)) return true;
195
+ if (sent.has(event)) {
196
+ _this2._bytes -= JSON.stringify(event).length;
115
197
  return false;
116
198
  }
117
199
  return true;
@@ -121,10 +203,13 @@ var Replay = /*#__PURE__*/function () {
121
203
  }]);
122
204
  return Replay;
123
205
  }();
206
+ // 缓冲区:起点事件(Meta / FullSnapshot)始终保留在头部
124
207
  _defineProperty(Replay, "_events", []);
125
208
  _defineProperty(Replay, "_stop", void 0);
209
+ // rrweb 模块引用:截断重开时需要 takeFullSnapshot 立刻补一张完整快照
210
+ _defineProperty(Replay, "_record", void 0);
126
211
  // rrweb 异步加载中的标记:避免 init 被重复调用时启动两个录制实例
127
212
  _defineProperty(Replay, "_loading", false);
128
- // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后从最早事件开始截断
213
+ // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后整体重开一段
129
214
  _defineProperty(Replay, "_bytes", 0);
130
215
  export { Replay as default };
@@ -1,7 +1,24 @@
1
- import type { TrackV3Envelope, TrackV3Event } from '../interfaces/protocol';
1
+ import { type TrackV3Envelope, type TrackV3Event } from '../interfaces/protocol';
2
+ /**
3
+ * 按列宽截断。
4
+ *
5
+ * 只用于「接入方拿不到也改不了」的字段:请求级信封字段(`imei` / `sdkVersion` /
6
+ * `appVersion` / `user.*`)、逐条自动采集的 `href`、以及会话级缓存的 `module`。
7
+ * 这些值一旦超列宽,服务端会因 `@MaxLength` 直接 400(整批 / 整请求被拒),
8
+ * 丢弃等于让该应用或该页面的上报整体消失;截断至少保住定位信息。
9
+ *
10
+ * 反之,接入方自己传的业务内容(`content`)超限时**丢弃该条**而不是截断,
11
+ * 见 `Log.isContentOverlong`——截断会把「数据丢失」伪装成「数据完整」。
12
+ */
13
+ export declare function truncate(value: string, limit: number): string;
14
+ export declare function truncate(value: string | undefined, limit: number): string | undefined;
2
15
  /** 请求级公共段(信封):字段与实体属性同名(camelCase),每次请求仅一份 */
3
16
  export declare function buildEnvelopeBase(): TrackV3Envelope;
4
17
  /** 条级事件公共字段:href / 视口 / 毫秒时间戳在批量窗口内会变,逐条携带 */
5
18
  export declare function buildEventBase(): Pick<TrackV3Event, 'systemTime' | 'href' | 'innerWidth' | 'innerHeight'>;
6
- /** V3 上报地址:鉴权参数位统一走 URL query(sendBeacon 无法自定义 header) */
19
+ /**
20
+ * V3 上报地址:鉴权**仅 appId**,走 URL query(sendBeacon 无法自定义 header)。
21
+ * 刻意不实现 `ts` / `nonce` / `sign`:探针运行在公开前端页面,密钥无法保密,签名不构成防线;
22
+ * 准入由服务端 TrackAuthGuard(appId 在册 + 停收开关 + 限流)负责。
23
+ */
7
24
  export declare function trackUrl(path: '/batch' | '/error'): string;
@@ -1,26 +1,44 @@
1
1
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
2
  import packageJson from "../../package.json";
3
+ import { TRACK_LIMITS } from "../interfaces/protocol";
3
4
  import Config from "./Config";
4
5
  import System from "./System";
5
6
  import User from "./User";
6
7
 
8
+ /**
9
+ * 按列宽截断。
10
+ *
11
+ * 只用于「接入方拿不到也改不了」的字段:请求级信封字段(`imei` / `sdkVersion` /
12
+ * `appVersion` / `user.*`)、逐条自动采集的 `href`、以及会话级缓存的 `module`。
13
+ * 这些值一旦超列宽,服务端会因 `@MaxLength` 直接 400(整批 / 整请求被拒),
14
+ * 丢弃等于让该应用或该页面的上报整体消失;截断至少保住定位信息。
15
+ *
16
+ * 反之,接入方自己传的业务内容(`content`)超限时**丢弃该条**而不是截断,
17
+ * 见 `Log.isContentOverlong`——截断会把「数据丢失」伪装成「数据完整」。
18
+ */
19
+
20
+ export function truncate(value, limit) {
21
+ if (value === null || value === undefined) return undefined;
22
+ return value.length > limit ? value.slice(0, limit) : value;
23
+ }
24
+
7
25
  /** 请求级公共段(信封):字段与实体属性同名(camelCase),每次请求仅一份 */
8
26
  export function buildEnvelopeBase() {
9
27
  var profile = User.profile;
10
28
  return _objectSpread({
11
29
  appId: Config.data.appId,
12
- sdkVersion: packageJson.version,
30
+ sdkVersion: truncate(packageJson.version, TRACK_LIMITS.sdkVersion),
13
31
  // 调用方应用版本:未配置时为 undefined,JSON.stringify 会丢弃该键(服务端落 NULL)
14
- appVersion: Config.data.appVersion,
15
- imei: System.imei
32
+ appVersion: truncate(Config.data.appVersion, TRACK_LIMITS.appVersion),
33
+ imei: truncate(System.imei, TRACK_LIMITS.imei)
16
34
  }, profile ? {
17
35
  user: {
18
- userId: profile.userId,
19
- userName: profile.userName,
20
- orgCode: profile.orgCode,
21
- orgTitle: profile.orgTitle,
22
- dataScopeZonePermissions: profile.dataScopeZonePermissions,
23
- dataScopeRoles: profile.dataScopeRoles
36
+ userId: truncate(profile.userId, TRACK_LIMITS.userField),
37
+ userName: truncate(profile.userName, TRACK_LIMITS.userField),
38
+ orgCode: truncate(profile.orgCode, TRACK_LIMITS.userField),
39
+ orgTitle: truncate(profile.orgTitle, TRACK_LIMITS.userField),
40
+ dataScopeZonePermissions: truncate(profile.dataScopeZonePermissions, TRACK_LIMITS.userField),
41
+ dataScopeRoles: truncate(profile.dataScopeRoles, TRACK_LIMITS.userField)
24
42
  }
25
43
  } : {});
26
44
  }
@@ -29,14 +47,20 @@ export function buildEnvelopeBase() {
29
47
  export function buildEventBase() {
30
48
  return {
31
49
  systemTime: Date.now(),
32
- href: typeof location !== 'undefined' ? location.href : '',
50
+ href: truncate(typeof location !== 'undefined' ? location.href : '', TRACK_LIMITS.href),
33
51
  innerWidth: typeof window !== 'undefined' ? window.innerWidth : 0,
34
52
  innerHeight: typeof window !== 'undefined' ? window.innerHeight : 0
35
53
  };
36
54
  }
37
55
 
38
- /** V3 上报地址:鉴权参数位统一走 URL query(sendBeacon 无法自定义 header) */
56
+ /**
57
+ * V3 上报地址:鉴权**仅 appId**,走 URL query(sendBeacon 无法自定义 header)。
58
+ * 刻意不实现 `ts` / `nonce` / `sign`:探针运行在公开前端页面,密钥无法保密,签名不构成防线;
59
+ * 准入由服务端 TrackAuthGuard(appId 在册 + 停收开关 + 限流)负责。
60
+ */
39
61
  export function trackUrl(path) {
40
62
  var appId = encodeURIComponent(Config.data.appId);
41
- return "".concat(Config.data.domain, "/pousheng-guard/api/track/v3").concat(path, "?appId=").concat(appId);
63
+ // 去掉 domain 尾斜杠,避免拼出 `https://host//pousheng-guard/...` 这类双斜杠地址
64
+ var domain = Config.data.domain.replace(/\/+$/, '');
65
+ return "".concat(domain, "/pousheng-guard/api/track/v3").concat(path, "?appId=").concat(appId);
42
66
  }