@yysports/tools 3.0.4 → 3.1.0

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.
Files changed (43) hide show
  1. package/README.md +2 -0
  2. package/dist/Track/Beacon.d.ts +12 -8
  3. package/dist/Track/Beacon.js +37 -29
  4. package/dist/Track/Config.d.ts +5 -1
  5. package/dist/Track/Config.js +25 -3
  6. package/dist/Track/Listener.d.ts +13 -0
  7. package/dist/Track/Listener.js +57 -25
  8. package/dist/Track/Log.d.ts +14 -1
  9. package/dist/Track/Log.js +55 -17
  10. package/dist/Track/Replay.d.ts +27 -2
  11. package/dist/Track/Replay.js +127 -22
  12. package/dist/Track/envelope.d.ts +19 -2
  13. package/dist/Track/envelope.js +36 -12
  14. package/dist/Track/index.js +14 -3
  15. package/dist/Utils/index.d.ts +2 -2
  16. package/dist/Utils/index.js +3 -3
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +2 -2
  19. package/dist/interfaces/protocol.d.ts +1 -1
  20. package/dist/interfaces/protocol.js +1 -1
  21. package/dist/interfaces/track.interface.d.ts +1 -1
  22. package/dist/interfaces/track.interface.js +1 -1
  23. package/lib/Track/Beacon.d.ts +12 -8
  24. package/lib/Track/Beacon.js +31 -24
  25. package/lib/Track/Config.d.ts +5 -1
  26. package/lib/Track/Config.js +26 -4
  27. package/lib/Track/Listener.d.ts +13 -0
  28. package/lib/Track/Listener.js +44 -20
  29. package/lib/Track/Log.d.ts +14 -1
  30. package/lib/Track/Log.js +40 -4
  31. package/lib/Track/Replay.d.ts +27 -2
  32. package/lib/Track/Replay.js +75 -11
  33. package/lib/Track/envelope.d.ts +19 -2
  34. package/lib/Track/envelope.js +31 -13
  35. package/lib/Track/index.js +10 -2
  36. package/lib/Utils/index.d.ts +2 -2
  37. package/lib/Utils/index.js +5 -5
  38. package/lib/index.d.ts +1 -1
  39. package/lib/index.js +3 -3
  40. package/lib/interfaces/protocol.d.ts +1 -1
  41. package/lib/interfaces/protocol.js +1 -1
  42. package/lib/interfaces/track.interface.d.ts +1 -1
  43. package/package.json +23 -26
@@ -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);
@@ -29,21 +42,37 @@ var Replay = /*#__PURE__*/function () {
29
42
  return _regeneratorRuntime().wrap(function _callee$(_context) {
30
43
  while (1) switch (_context.prev = _context.next) {
31
44
  case 0:
32
- if (!(this._stop || this._loading || !Config.data.enableReplay)) {
45
+ if (Config.data.enableReplay) {
33
46
  _context.next = 2;
34
47
  break;
35
48
  }
36
49
  return _context.abrupt("return");
37
50
  case 2:
51
+ // 复位必须在 `_loading` 判断之前:加载中关掉再打开时,入口会被 `_loading` 挡回,
52
+ // 复位不到标志,加载完成后就会误判为「已请求停止」而放弃启动
53
+ this._stopRequested = false;
54
+ if (!(this._stop || this._loading)) {
55
+ _context.next = 5;
56
+ break;
57
+ }
58
+ return _context.abrupt("return");
59
+ case 5:
38
60
  this._loading = true;
39
- _context.prev = 3;
40
- _context.next = 6;
61
+ _context.prev = 6;
62
+ _context.next = 9;
41
63
  return Promise.all([import('@rrweb/record'), import('@rrweb/rrweb-plugin-console-record')]);
42
- case 6:
64
+ case 9:
43
65
  _yield$Promise$all = _context.sent;
44
66
  _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
45
67
  startRecord = _yield$Promise$all2[0].record;
46
68
  getRecordConsolePlugin = _yield$Promise$all2[1].getRecordConsolePlugin;
69
+ if (!(this._stopRequested || !Config.data.enableReplay)) {
70
+ _context.next = 15;
71
+ break;
72
+ }
73
+ return _context.abrupt("return");
74
+ case 15:
75
+ this._record = startRecord;
47
76
  this._stop = startRecord(_objectSpread(_objectSpread({
48
77
  emit: function emit(e) {
49
78
  _this._events.push(e);
@@ -62,39 +91,104 @@ var Replay = /*#__PURE__*/function () {
62
91
  level: ['log', 'info', 'warn', 'error', 'debug']
63
92
  })]
64
93
  }));
65
- _context.next = 16;
94
+ _context.next = 23;
66
95
  break;
67
- case 13:
68
- _context.prev = 13;
69
- _context.t0 = _context["catch"](3);
96
+ case 19:
97
+ _context.prev = 19;
98
+ _context.t0 = _context["catch"](6);
70
99
  // 加载或启动失败:静默降级,仅回放不可用
71
100
  this._stop = undefined;
72
- case 16:
73
- _context.prev = 16;
101
+ this._record = undefined;
102
+ case 23:
103
+ _context.prev = 23;
74
104
  this._loading = false;
75
- return _context.finish(16);
76
- case 19:
105
+ return _context.finish(23);
106
+ case 26:
77
107
  case "end":
78
108
  return _context.stop();
79
109
  }
80
- }, _callee, this, [[3, 13, 16, 19]]);
110
+ }, _callee, this, [[6, 19, 23, 26]]);
81
111
  }));
82
112
  function run() {
83
113
  return _run.apply(this, arguments);
84
114
  }
85
115
  return run;
86
- }() /** 截断到体积上限,保留最近片段 */)
116
+ }()
117
+ /**
118
+ * 停止录制并清空缓存。
119
+ *
120
+ * `Replay.run` 的幂等只看 `_stop`,`init({ enableReplay: false })` 不会让已启动的录制停下,
121
+ * 因此 `Track.run` 在关闭回放时显式调用本方法。
122
+ */
123
+ )
124
+ }, {
125
+ key: "stop",
126
+ value: function stop() {
127
+ // 先置标志:rrweb 仍在加载时 `_stop` 还不存在,只有它能拦住随后的启动
128
+ this._stopRequested = true;
129
+ if (this._stop) {
130
+ this._stop();
131
+ }
132
+ this._stop = undefined;
133
+ this._record = undefined;
134
+ this._events = [];
135
+ this._bytes = 0;
136
+ }
137
+
138
+ /**
139
+ * 截断到体积上限:整体重开一段,并请求一张新的完整快照。
140
+ *
141
+ * 片段必须自带播放起点(在缓冲区头部),丢掉起点整段就无法播放,而起点之后的事件
142
+ * 全是增量、丢了画面又不完整,所以这里不做「从头丢事件」,直接重开一段。
143
+ */
87
144
  }, {
88
145
  key: "truncate",
89
146
  value: function truncate() {
90
147
  var _Config$data$replayMa;
91
148
  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;
149
+ if (this._bytes <= maxBytes) return;
150
+
151
+ // 起点自身就超过上限时重开也降不下来(新快照同样大):放弃截断,
152
+ // 否则每次 emit 都会重开一段、回放数据全被冲掉
153
+ var startBytes = Replay.bytesOf(Replay.replayStartEvents(this._events));
154
+ if (startBytes > maxBytes) return;
155
+
156
+ // Meta 体积很小但播放器渲染要用,保留它,再请求一张新的 FullSnapshot 组成新片段
157
+ this._events = this._events.filter(function (e) {
158
+ return (e === null || e === void 0 ? void 0 : e.type) === RRWEB_META;
159
+ }).slice(0, 1);
160
+ this._bytes = Replay.bytesOf(this._events);
161
+ Replay.requestFullSnapshot();
162
+ }
163
+
164
+ /** 缓冲区头部的起点事件(Meta / FullSnapshot);无起点时返回空数组 */
165
+ }, {
166
+ key: "replayStartEvents",
167
+ value: function replayStartEvents(events) {
168
+ return events.slice(0, 2).filter(isReplayStartEvent);
169
+ }
170
+
171
+ /** 请求 rrweb 立刻产出一张 FullSnapshot(失败静默,仅影响回放可用性) */
172
+ }, {
173
+ key: "requestFullSnapshot",
174
+ value: function requestFullSnapshot() {
175
+ try {
176
+ var _Replay$_record, _Replay$_record$takeF;
177
+ (_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);
178
+ } catch (err) {
179
+ // 忽略:下一张快照产出前,回放片段不可独立播放
95
180
  }
96
181
  }
97
182
 
183
+ /** 事件数组的近似序列化体积(与 emit 中的累计口径一致) */
184
+ }, {
185
+ key: "bytesOf",
186
+ value: function bytesOf(events) {
187
+ return events.reduce(function (sum, e) {
188
+ return sum + JSON.stringify(e).length;
189
+ }, 0);
190
+ }
191
+
98
192
  /** 快照当前回放片段(不移除,待上报成功后 commitSnapshot) */
99
193
  }, {
100
194
  key: "snapshot",
@@ -102,16 +196,22 @@ var Replay = /*#__PURE__*/function () {
102
196
  return this._stop ? _toConsumableArray(this._events) : [];
103
197
  }
104
198
 
105
- /** 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段 */
199
+ /**
200
+ * 上报成功后移除已携带的事件,继续录制——不调用 stop,避免下一个错误重复携带上一段。
201
+ *
202
+ * 起点事件(Meta / FullSnapshot)保留在缓冲区:随本次上报一起移除后,下一段回放
203
+ * 只剩增量事件、播放器无法独立渲染。
204
+ */
106
205
  }, {
107
206
  key: "commitSnapshot",
108
207
  value: function commitSnapshot(snapshot) {
109
208
  var _this2 = this;
110
209
  if (!snapshot.length) return;
111
210
  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;
211
+ this._events = this._events.filter(function (event) {
212
+ if (isReplayStartEvent(event)) return true;
213
+ if (sent.has(event)) {
214
+ _this2._bytes -= JSON.stringify(event).length;
115
215
  return false;
116
216
  }
117
217
  return true;
@@ -121,10 +221,15 @@ var Replay = /*#__PURE__*/function () {
121
221
  }]);
122
222
  return Replay;
123
223
  }();
224
+ // 缓冲区:起点事件(Meta / FullSnapshot)始终保留在头部
124
225
  _defineProperty(Replay, "_events", []);
125
226
  _defineProperty(Replay, "_stop", void 0);
227
+ // rrweb 模块引用:截断重开时需要 takeFullSnapshot 立刻补一张完整快照
228
+ _defineProperty(Replay, "_record", void 0);
126
229
  // rrweb 异步加载中的标记:避免 init 被重复调用时启动两个录制实例
127
230
  _defineProperty(Replay, "_loading", false);
128
- // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后从最早事件开始截断
231
+ // 加载窗口内被 stop 的标记:rrweb 就绪后据此放弃启动
232
+ _defineProperty(Replay, "_stopRequested", false);
233
+ // 录制阶段的累计体积(近似值),达到 replayMaxBytes 后整体重开一段
129
234
  _defineProperty(Replay, "_bytes", 0);
130
235
  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
  }
@@ -43,9 +43,20 @@ var Track = /*#__PURE__*/function () {
43
43
  }, {
44
44
  key: "run",
45
45
  value: function run() {
46
- Listener.run();
47
- // 回放为异步启动(rrweb 懒加载),不阻塞 init;未开回放时不会加载 rrweb
48
- void Replay.run();
46
+ // 布尔项可热更新:关掉时显式卸载监听,打开时(幂等标志已复位)重新注册
47
+ if (Config.data.autoReportError) {
48
+ Listener.run();
49
+ } else {
50
+ Listener.stop();
51
+ }
52
+ if (Config.data.enableReplay) {
53
+ // 回放为异步启动(rrweb 懒加载),不阻塞 init;未开回放时不会加载 rrweb
54
+ void Replay.run();
55
+ } else {
56
+ // 已启动录制后再 init({ enableReplay: false }):Replay.run 的幂等只看 _stop,
57
+ // 这里显式停止,否则回放仍在录制并随错误上报
58
+ Replay.stop();
59
+ }
49
60
  // 版本上报已并入信封 sdkVersion,不再有独立请求
50
61
  Beacon.start();
51
62
  }
@@ -1,6 +1,6 @@
1
+ export * from './auth';
1
2
  export * from './common';
2
3
  export * from './file';
4
+ export * from './route';
3
5
  export * from './url';
4
6
  export * from './wx';
5
- export * from './route';
6
- export * from './auth';
@@ -1,6 +1,6 @@
1
+ export * from "./auth";
1
2
  export * from "./common";
2
3
  export * from "./file";
3
- export * from "./url";
4
- export * from "./wx";
5
4
  export * from "./route";
6
- export * from "./auth";
5
+ export * from "./url";
6
+ export * from "./wx";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { default as Track } from './Track';
2
2
  export * as Utils from './Utils';
3
- export * from './interfaces/track.interface';
4
3
  export * from './interfaces/protocol';
4
+ export * from './interfaces/track.interface';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { default as Track } from "./Track";
2
2
  import * as _Utils from "./Utils";
3
3
  export { _Utils as Utils };
4
- export * from "./interfaces/track.interface";
5
- export * from "./interfaces/protocol";
4
+ export * from "./interfaces/protocol";
5
+ export * from "./interfaces/track.interface";
@@ -18,7 +18,7 @@ export declare const TrackTypeLabel: Record<TrackType, string>;
18
18
  * 不做无依据的额外限制——超长字段本身即会写入失败。
19
19
  */
20
20
  export declare const TRACK_LIMITS: {
21
- /** 单次批量 events[] 条数上限(SDK batchSize 与服务端 DTO 共用) */
21
+ /** 单次批量 events[] 条数上限(SDK 切批与服务端 DTO 共用,双方都不可调) */
22
22
  readonly maxItems: 20;
23
23
  /** 探针版本号,guard_conf.version varchar(20) */
24
24
  readonly sdkVersion: 20;
@@ -26,7 +26,7 @@ export var TrackTypeLabel = {
26
26
  * 不做无依据的额外限制——超长字段本身即会写入失败。
27
27
  */
28
28
  export var TRACK_LIMITS = {
29
- /** 单次批量 events[] 条数上限(SDK batchSize 与服务端 DTO 共用) */
29
+ /** 单次批量 events[] 条数上限(SDK 切批与服务端 DTO 共用,双方都不可调) */
30
30
  maxItems: 20,
31
31
  /** 探针版本号,guard_conf.version varchar(20) */
32
32
  sdkVersion: 20,
@@ -1,4 +1,4 @@
1
- export { TrackTypeLabel, TRACK_TYPE_VALUES } from './protocol';
1
+ export { TRACK_TYPE_VALUES, TrackTypeLabel } from './protocol';
2
2
  export type { TrackType } from './protocol';
3
3
  export interface UserProfile {
4
4
  userId: string;
@@ -1,6 +1,6 @@
1
1
  // 上报类型取值与展示标签统一由 protocol.ts 维护(唯一真源),此处仅做出口。
2
2
  // 类型必须用 `export type` 再导出:值语法会让构建产物出现运行时再导出(TrackType 在运行时不存在)
3
- export { TrackTypeLabel, TRACK_TYPE_VALUES } from "./protocol";
3
+ export { TRACK_TYPE_VALUES, TrackTypeLabel } from "./protocol";
4
4
 
5
5
  // 用户信息
6
6
 
@@ -2,21 +2,25 @@ 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
- /** 启动定时 flush(Track.init 时调用) */
12
+ /**
13
+ * 启动定时 flush 与卸载兜底(Track.init 时调用,重复调用无副作用)。
14
+ *
15
+ * 兜底 flush 放在这里、不放 `Listener`:那会让「是否采集错误」与「通道能否送达」耦合,
16
+ * 关掉 `autoReportError` 会连带丢掉所有不满一批的数据。
17
+ *
18
+ * `flushInterval` 只在首次创建定时器时读取,热更新重建留待 3.2.0(P1-6)。
19
+ */
16
20
  static start(): void;
17
- /** 入队,达到 batchSize 立即 flush */
21
+ /** 入队,达到协议上限立即 flush */
18
22
  static push(event: TrackV3Event): void;
19
- /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
23
+ /** 按批发送并出队;发送失败同样出队(尽力而为,不驻留重试) */
20
24
  static flush(): void;
21
25
  private static sendBatch;
22
26
  private static trySendBeacon;
@@ -36,7 +36,14 @@ var import_protocol = require("../interfaces/protocol");
36
36
  var import_Config = __toESM(require("./Config"));
37
37
  var import_envelope = require("./envelope");
38
38
  var Beacon = class {
39
- /** 启动定时 flush(Track.init 时调用) */
39
+ /**
40
+ * 启动定时 flush 与卸载兜底(Track.init 时调用,重复调用无副作用)。
41
+ *
42
+ * 兜底 flush 放在这里、不放 `Listener`:那会让「是否采集错误」与「通道能否送达」耦合,
43
+ * 关掉 `autoReportError` 会连带丢掉所有不满一批的数据。
44
+ *
45
+ * `flushInterval` 只在首次创建定时器时读取,热更新重建留待 3.2.0(P1-6)。
46
+ */
40
47
  static start() {
41
48
  if (this._timer)
42
49
  return;
@@ -44,40 +51,45 @@ var Beacon = class {
44
51
  () => this.flush(),
45
52
  import_Config.default.data.flushInterval ?? 1e4
46
53
  );
54
+ if (typeof document === "undefined" || typeof window === "undefined") {
55
+ return;
56
+ }
57
+ document.addEventListener("visibilitychange", () => {
58
+ if (document.visibilityState === "hidden") {
59
+ this.flush();
60
+ }
61
+ });
62
+ window.addEventListener("pagehide", () => {
63
+ this.flush();
64
+ });
47
65
  }
48
- /** 入队,达到 batchSize 立即 flush */
66
+ /** 入队,达到协议上限立即 flush */
49
67
  static push(event) {
68
+ if (!import_Config.default.data.appId) {
69
+ console.warn("[Track] 尚未调用 Track.init(appId 为空),该条上报已丢弃");
70
+ return;
71
+ }
50
72
  this._queue.push(event);
51
- if (this._queue.length >= (import_Config.default.data.batchSize ?? import_protocol.TRACK_LIMITS.maxItems)) {
73
+ if (this._queue.length >= import_protocol.TRACK_LIMITS.maxItems) {
52
74
  this.flush();
53
75
  }
54
76
  }
55
- /** 发送成功后再出队;失败保留队列等待下次 flush 重试 */
77
+ /** 按批发送并出队;发送失败同样出队(尽力而为,不驻留重试) */
56
78
  static flush() {
57
79
  while (this._queue.length > 0) {
58
- const batchSize = import_Config.default.data.batchSize ?? import_protocol.TRACK_LIMITS.maxItems;
59
- const batch = this._queue.slice(0, batchSize);
80
+ const batch = this._queue.slice(0, import_protocol.TRACK_LIMITS.maxItems);
60
81
  const payload = {
61
82
  ...(0, import_envelope.buildEnvelopeBase)(),
62
83
  events: batch
63
84
  };
64
- if (this.sendBatch(JSON.stringify(payload)) === "retry")
65
- return;
85
+ this.sendBatch(JSON.stringify(payload));
66
86
  this._queue.splice(0, batch.length);
67
87
  }
68
88
  }
69
89
  static sendBatch(payload) {
70
- const sent = this.trySendBeacon(payload) || this.trySendKeepalive(payload);
71
- if (sent) {
72
- this._failCount = 0;
73
- return "sent";
90
+ if (!this.trySendBeacon(payload)) {
91
+ this.trySendKeepalive(payload);
74
92
  }
75
- this._failCount += 1;
76
- if (this._failCount > this.MAX_RETRIES) {
77
- this._failCount = 0;
78
- return "drop";
79
- }
80
- return "retry";
81
93
  }
82
94
  static trySendBeacon(payload) {
83
95
  if (typeof navigator === "undefined" || !navigator.sendBeacon)
@@ -94,7 +106,7 @@ var Beacon = class {
94
106
  /** fetch keepalive:无 sendBeacon 环境的主要通道,已发出即视为送达(不等响应、不阻塞队列) */
95
107
  static trySendKeepalive(payload) {
96
108
  if (typeof fetch !== "function")
97
- return false;
109
+ return;
98
110
  try {
99
111
  void fetch((0, import_envelope.trackUrl)("/batch"), {
100
112
  method: "POST",
@@ -102,14 +114,9 @@ var Beacon = class {
102
114
  body: payload,
103
115
  keepalive: true
104
116
  }).catch(() => void 0);
105
- return true;
106
117
  } catch (error) {
107
- return false;
108
118
  }
109
119
  }
110
120
  };
111
121
  Beacon._queue = [];
112
122
  Beacon._timer = null;
113
- /** 连续发送失败次数,超过重试上限后丢弃当前批次,避免队列无限增长 */
114
- Beacon._failCount = 0;
115
- Beacon.MAX_RETRIES = 3;
@@ -9,7 +9,6 @@ export interface IConfig {
9
9
  appVersion?: string;
10
10
  autoReportError?: boolean;
11
11
  enableReplay?: boolean;
12
- batchSize?: number;
13
12
  flushInterval?: number;
14
13
  replayMaxBytes?: number;
15
14
  replayMaskTextClass?: string | RegExp;
@@ -17,5 +16,10 @@ export interface IConfig {
17
16
  export default class Config {
18
17
  private static _data;
19
18
  static validate(config: IConfig): void;
19
+ /**
20
+ * `0` / 非数字 / `null` 回落默认值,其余小于下限的收敛到下限。
21
+ * `0` 按非法处理而非下限:`Number(null)` 也是 0,混在一起会让 `replayMaxBytes` 变成 1 字节。
22
+ */
23
+ private static normalize;
20
24
  static get data(): IConfig;
21
25
  }
@@ -22,8 +22,7 @@ __export(Config_exports, {
22
22
  default: () => Config
23
23
  });
24
24
  module.exports = __toCommonJS(Config_exports);
25
- var import_protocol = require("../interfaces/protocol");
26
- var Config = class {
25
+ var _Config = class {
27
26
  static validate(config) {
28
27
  var _a, _b;
29
28
  if (!((_a = config.appId) == null ? void 0 : _a.trim())) {
@@ -32,18 +31,41 @@ var Config = class {
32
31
  if (!((_b = config.domain) == null ? void 0 : _b.trim())) {
33
32
  throw new Error("Config: domain is required");
34
33
  }
35
- Object.assign(this._data, config);
34
+ const defined = Object.fromEntries(
35
+ Object.entries(config).filter(([, value]) => value !== void 0)
36
+ );
37
+ Object.assign(this._data, defined);
38
+ this._data.flushInterval = _Config.normalize(
39
+ this._data.flushInterval,
40
+ 1e4,
41
+ 1e3
42
+ );
43
+ this._data.replayMaxBytes = _Config.normalize(
44
+ this._data.replayMaxBytes,
45
+ 1024 * 1024,
46
+ 1
47
+ );
48
+ }
49
+ /**
50
+ * `0` / 非数字 / `null` 回落默认值,其余小于下限的收敛到下限。
51
+ * `0` 按非法处理而非下限:`Number(null)` 也是 0,混在一起会让 `replayMaxBytes` 变成 1 字节。
52
+ */
53
+ static normalize(value, fallback, min) {
54
+ const num = Math.floor(Number(value));
55
+ if (!Number.isFinite(num) || num <= 0)
56
+ return fallback;
57
+ return num < min ? min : num;
36
58
  }
37
59
  static get data() {
38
60
  return this._data;
39
61
  }
40
62
  };
63
+ var Config = _Config;
41
64
  Config._data = {
42
65
  appId: "",
43
66
  domain: "",
44
67
  autoReportError: true,
45
68
  enableReplay: true,
46
- batchSize: import_protocol.TRACK_LIMITS.maxItems,
47
69
  flushInterval: 1e4,
48
70
  replayMaxBytes: 1024 * 1024
49
71
  };
@@ -1,5 +1,18 @@
1
1
  export default class Listener {
2
2
  private static _loaded;
3
3
  private static _reporter;
4
+ /**
5
+ * 具名 handler:`removeEventListener` 必须拿到与注册时相同的函数引用,
6
+ * 匿名函数会让 `stop()` 失效(`autoReportError` 从 true 改 false 后仍在采集)。
7
+ */
8
+ private static readonly _onError;
4
9
  static run(): void;
10
+ /**
11
+ * 停止自动上报,供 `init({ autoReportError: false })` 热关闭。
12
+ *
13
+ * 必须复位 `_loaded`:否则再次 `init({ autoReportError: true })` 时 `run()`
14
+ * 直接命中幂等判断返回,监听再也装不回来。挂起的防抖定时器同样要清掉,
15
+ * 否则关闭后仍会补报一条。
16
+ */
17
+ static stop(): void;
5
18
  }