@jasolar/tracker-sdk 1.0.3 → 1.0.4

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/dist/index.esm.js CHANGED
@@ -1,66 +1,180 @@
1
+ function _arrayLikeToArray(r, a) {
2
+ (null == a || a > r.length) && (a = r.length);
3
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
4
+ return n;
5
+ }
6
+ function _arrayWithoutHoles(r) {
7
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
8
+ }
9
+ function _classCallCheck(a, n) {
10
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
11
+ }
12
+ function _defineProperties(e, r) {
13
+ for (var t = 0; t < r.length; t++) {
14
+ var o = r[t];
15
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
16
+ }
17
+ }
18
+ function _createClass(e, r, t) {
19
+ return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
20
+ writable: false
21
+ }), e;
22
+ }
23
+ function _defineProperty(e, r, t) {
24
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
25
+ value: t,
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true
29
+ }) : e[r] = t, e;
30
+ }
31
+ function _iterableToArray(r) {
32
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
33
+ }
34
+ function _nonIterableSpread() {
35
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
36
+ }
37
+ function ownKeys(e, r) {
38
+ var t = Object.keys(e);
39
+ if (Object.getOwnPropertySymbols) {
40
+ var o = Object.getOwnPropertySymbols(e);
41
+ r && (o = o.filter(function (r) {
42
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
43
+ })), t.push.apply(t, o);
44
+ }
45
+ return t;
46
+ }
47
+ function _objectSpread2(e) {
48
+ for (var r = 1; r < arguments.length; r++) {
49
+ var t = null != arguments[r] ? arguments[r] : {};
50
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
51
+ _defineProperty(e, r, t[r]);
52
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
53
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
54
+ });
55
+ }
56
+ return e;
57
+ }
58
+ function _objectWithoutProperties(e, t) {
59
+ if (null == e) return {};
60
+ var o,
61
+ r,
62
+ i = _objectWithoutPropertiesLoose(e, t);
63
+ if (Object.getOwnPropertySymbols) {
64
+ var n = Object.getOwnPropertySymbols(e);
65
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
66
+ }
67
+ return i;
68
+ }
69
+ function _objectWithoutPropertiesLoose(r, e) {
70
+ if (null == r) return {};
71
+ var t = {};
72
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
73
+ if (-1 !== e.indexOf(n)) continue;
74
+ t[n] = r[n];
75
+ }
76
+ return t;
77
+ }
78
+ function _toConsumableArray(r) {
79
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
80
+ }
81
+ function _toPrimitive(t, r) {
82
+ if ("object" != typeof t || !t) return t;
83
+ var e = t[Symbol.toPrimitive];
84
+ if (void 0 !== e) {
85
+ var i = e.call(t, r);
86
+ if ("object" != typeof i) return i;
87
+ throw new TypeError("@@toPrimitive must return a primitive value.");
88
+ }
89
+ return ("string" === r ? String : Number)(t);
90
+ }
91
+ function _toPropertyKey(t) {
92
+ var i = _toPrimitive(t, "string");
93
+ return "symbol" == typeof i ? i : i + "";
94
+ }
95
+ function _unsupportedIterableToArray(r, a) {
96
+ if (r) {
97
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
98
+ var t = {}.toString.call(r).slice(8, -1);
99
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
100
+ }
101
+ }
102
+
1
103
  /**
2
104
  * 数据上报队列,支持批量发送和定时发送。
3
105
  */
4
- class Queue {
5
- /**
6
- * @param {Function} flushFn - 实际发送数据的函数,接收一个数据数组作为参数。
7
- * @param {Object} options - 配置项
8
- * @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
9
- * @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
10
- */
11
- constructor(flushFn, options = {}) {
12
- this.list = [];
13
- this.flushFn = flushFn;
14
- this.timer = null;
15
- this.delay = options.delay || 1000;
16
- this.maxBatchSize = options.maxBatchSize || 10;
17
- }
18
-
19
- /**
20
- * 将数据推入队列。
21
- * @param {Object} data - 要推入队列的数据。
22
- */
23
- push(data) {
24
- this.list.push(data);
25
-
26
- // 如果达到最大批量大小,立即发送
27
- if (this.list.length >= this.maxBatchSize) {
28
- this.flush();
29
- return;
30
- }
106
+ var Queue = /*#__PURE__*/function () {
107
+ /**
108
+ * @param {Function} flushFn - 实际发送数据的函数,接收一个数据数组作为参数。
109
+ * @param {Object} options - 配置项
110
+ * @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
111
+ * @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
112
+ */
113
+ function Queue(flushFn) {
114
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
115
+ _classCallCheck(this, Queue);
116
+ this.list = [];
117
+ this.flushFn = flushFn;
118
+ this.timer = null;
119
+ this.delay = options.delay || 1000;
120
+ this.maxBatchSize = options.maxBatchSize || 10;
121
+ }
122
+
123
+ /**
124
+ * 将数据推入队列。
125
+ * @param {Object} data - 要推入队列的数据。
126
+ */
127
+ return _createClass(Queue, [{
128
+ key: "push",
129
+ value: function push(data) {
130
+ var _this = this;
131
+ this.list.push(data);
132
+
133
+ // 如果达到最大批量大小,立即发送
134
+ if (this.list.length >= this.maxBatchSize) {
135
+ this.flush();
136
+ return;
137
+ }
31
138
 
32
- // 如果没有定时器,则设置一个定时器在延迟后发送
33
- if (!this.timer) {
34
- this.timer = setTimeout(() => {
35
- this.flush();
36
- }, this.delay);
37
- }
139
+ // 如果没有定时器,则设置一个定时器在延迟后发送
140
+ if (!this.timer) {
141
+ this.timer = setTimeout(function () {
142
+ _this.flush();
143
+ }, this.delay);
144
+ }
38
145
  }
39
146
 
40
147
  /**
41
148
  * 立即发送队列中的所有数据。
149
+ * @param {boolean} isFlush - 是否为强制刷新(如页面关闭)
42
150
  */
43
- flush() {
44
- if (!this.list.length) {
45
- return;
46
- }
151
+ }, {
152
+ key: "flush",
153
+ value: function flush() {
154
+ var _this2 = this;
155
+ var isFlush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
156
+ if (!this.list.length) {
157
+ return;
158
+ }
47
159
 
48
- // 复制一份数据列表,防止在发送过程中 list 被修改
49
- const dataToSend = [...this.list];
50
- this.list = []; // 清空队列
51
-
52
- try {
53
- this.flushFn(dataToSend);
54
- } catch (error) {
55
- console.error("[Tracker SDK] Failed to flush data:", error);
56
- // 可以在这里实现简单的重试逻辑,例如将 dataToSend 重新放回队列
57
- // 但为了简单起见,目前仅打印错误
58
- } finally {
59
- clearTimeout(this.timer);
60
- this.timer = null;
61
- }
160
+ // 复制一份数据列表,防止在发送过程中 list 被修改
161
+ var dataToSend = _toConsumableArray(this.list);
162
+ this.list = []; // 清空队列
163
+
164
+ try {
165
+ // 逐条发送数据,而不是批量发送
166
+ dataToSend.forEach(function (item) {
167
+ _this2.flushFn(item, isFlush);
168
+ });
169
+ } catch (error) {
170
+ console.error("[Tracker SDK] Failed to flush data:", error);
171
+ } finally {
172
+ clearTimeout(this.timer);
173
+ this.timer = null;
174
+ }
62
175
  }
63
- }
176
+ }]);
177
+ }();
64
178
 
65
179
  /**
66
180
  * 发送数据到服务器。
@@ -75,68 +189,73 @@ class Queue {
75
189
  @param {string} url - 服务器地址
76
190
  @param {Object} data - 要发送的数据
77
191
  @param {Object} token - 认证令牌
192
+ @param {boolean} useBeacon - 是否强制使用 sendBeacon(用于页面关闭场景)
78
193
  */
79
- function send(url, data, token = {}) {
80
- if (!url) return;
81
-
82
- const body = JSON.stringify(data);
194
+ function send(url, data) {
195
+ var token = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
196
+ var useBeacon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
197
+ if (!url) return;
198
+ var body = JSON.stringify(data);
199
+
200
+ // 构造请求头
201
+ var headers = {
202
+ 'Content-Type': 'application/json'
203
+ };
204
+ if (token) {
205
+ headers['Authorization'] = "Bearer ".concat(token);
206
+ }
83
207
 
84
- // 构造请求头
85
- const headers = {
86
- 'Content-Type': 'application/json'
87
- };
208
+ // 1. 如果强制使用 Beacon 或 fetch 不可用,直接使用 sendBeacon
209
+ if (useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
210
+ var beaconUrl = url;
88
211
  if (token) {
89
- headers['Authorization'] = `Bearer ${token}`;
212
+ var separator = url.includes('?') ? '&' : '?';
213
+ beaconUrl = "".concat(url).concat(separator, "token=").concat(encodeURIComponent(token));
90
214
  }
91
-
92
- // 1. 尝试使用 fetch + keepalive (现代浏览器推荐方案)
93
- // keepalive: true 允许请求在页面进入后台或卸载后继续执行
94
- if (typeof fetch === 'function') {
95
- try {
96
- fetch(url, {
97
- method: 'POST',
98
- body,
99
- headers,
100
- keepalive: true, // 关键:模拟 sendBeacon 行为但支持 headers
101
- mode: 'cors'
102
- }).catch(err => {
103
- console.warn('[Tracker SDK] fetch report failed:', err);
104
- });
105
-
106
- // 如果 fetch 成功启动,直接返回
107
- return;
108
- } catch (e) {
109
- // 如果 fetch 抛出异常(例如 payload 超过 64KB 限制),进入下方的 fallback
110
- console.warn('[Tracker SDK] fetch keepalive failed, trying sendBeacon:', e);
111
- }
215
+ var blob = new Blob([body], {
216
+ type: 'application/json'
217
+ });
218
+ return navigator.sendBeacon(beaconUrl, blob);
219
+ }
220
+
221
+ // 2. 正常场景优先使用 fetch + keepalive
222
+ if (typeof fetch === 'function') {
223
+ try {
224
+ fetch(url, {
225
+ method: 'POST',
226
+ body: body,
227
+ headers: headers,
228
+ keepalive: true,
229
+ mode: 'cors'
230
+ }).catch(function (err) {
231
+ console.warn('[Tracker SDK] fetch report failed:', err);
232
+ });
233
+ return;
234
+ } catch (e) {
235
+ console.warn('[Tracker SDK] fetch keepalive failed, trying sendBeacon:', e);
112
236
  }
237
+ }
113
238
 
114
- // 2. 备选方案:navigator.sendBeacon (兼容性 fallback)
115
- // 限制:该 API 无法设置 Headers
116
- if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
117
- let beaconUrl = url;
118
-
119
- // 由于无法设置 Header,只能将 token 放在 URL 参数中
120
- // 需要后端配合,同时支持 Header 和 Query 参数接收 Token
121
- if (token) {
122
- const separator = url.includes('?') ? '&' : '?';
123
- beaconUrl = `${url}${separator}token=${encodeURIComponent(token)}`;
124
- }
125
-
126
- // 使用 Blob 确保后端能识别到 application/json 格式
127
- const blob = new Blob([body], {type: 'application/json'});
128
- const success = navigator.sendBeacon(beaconUrl, blob);
129
-
130
- if (success) return;
239
+ // 3. 备选方案:navigator.sendBeacon
240
+ if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
241
+ var _beaconUrl = url;
242
+ if (token) {
243
+ var _separator = url.includes('?') ? '&' : '?';
244
+ _beaconUrl = "".concat(url).concat(_separator, "token=").concat(encodeURIComponent(token));
131
245
  }
132
-
133
- // 3. 兜底逻辑:如果以上方法都不支持
134
- console.warn('[Tracker SDK] No available transport method.');
246
+ var _blob = new Blob([body], {
247
+ type: 'application/json'
248
+ });
249
+ var success = navigator.sendBeacon(_beaconUrl, _blob);
250
+ if (success) return;
251
+ }
252
+ console.warn('[Tracker SDK] No available transport method.');
135
253
  }
136
254
 
137
255
  function uuid() {
138
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
139
- const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
256
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
257
+ var r = Math.random() * 16 | 0,
258
+ v = c === 'x' ? r : r & 0x3 | 0x8;
140
259
  return v.toString(16);
141
260
  });
142
261
  }
@@ -144,39 +263,61 @@ function uuid() {
144
263
  /**
145
264
  * 简单的本地存储封装
146
265
  */
147
- const storage = {
148
- get(key) {
149
- try {
150
- const val = localStorage.getItem(key);
151
- if (!val) return null;
152
- return JSON.parse(val);
153
- } catch (e) {
154
- console.warn(`[Tracker SDK] Error parsing storage key "${key}":`, e);
155
- return null;
156
- }
157
- },
158
- set(key, value) {
159
- try {
160
- localStorage.setItem(key, JSON.stringify(value));
161
- } catch (e) {
162
- console.warn(`[Tracker SDK] Error saving to storage key "${key}":`, e);
163
- }
164
- },
165
- remove(key) {
166
- localStorage.removeItem(key);
266
+ var storage = {
267
+ get: function get(key) {
268
+ try {
269
+ var val = localStorage.getItem(key);
270
+ if (!val) return null;
271
+ return JSON.parse(val);
272
+ } catch (e) {
273
+ console.warn("[Tracker SDK] Error parsing storage key \"".concat(key, "\":"), e);
274
+ return null;
275
+ }
276
+ },
277
+ set: function set(key, value) {
278
+ try {
279
+ localStorage.setItem(key, JSON.stringify(value));
280
+ } catch (e) {
281
+ console.warn("[Tracker SDK] Error saving to storage key \"".concat(key, "\":"), e);
167
282
  }
283
+ },
284
+ remove: function remove(key) {
285
+ localStorage.removeItem(key);
286
+ }
168
287
  };
169
288
 
170
- const now = () => Date.now();
289
+ /**
290
+ * 获取当前时间戳(毫秒)
291
+ */
292
+ var now = function now() {
293
+ return Date.now();
294
+ };
295
+
296
+ /**
297
+ * 格式化时间为 YYYY-MM-DD HH:mm:ss 格式
298
+ * @param {number} timestamp - 时间戳(毫秒),默认为当前时间
299
+ * @returns {string} 格式化后的时间字符串
300
+ */
301
+ function formatTime() {
302
+ var timestamp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Date.now();
303
+ var date = new Date(timestamp);
304
+ var year = date.getFullYear();
305
+ var month = String(date.getMonth() + 1).padStart(2, '0');
306
+ var day = String(date.getDate()).padStart(2, '0');
307
+ var hours = String(date.getHours()).padStart(2, '0');
308
+ var minutes = String(date.getMinutes()).padStart(2, '0');
309
+ var seconds = String(date.getSeconds()).padStart(2, '0');
310
+ return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds);
311
+ }
171
312
 
172
313
  // src/core/session.js
173
314
 
174
315
 
175
- const SESSION_KEY = 'TRACKER_SESSION_ID';
176
- const SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
316
+ var SESSION_KEY = 'TRACKER_SESSION_ID';
317
+ var SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
177
318
 
178
319
  // 默认 30 分钟过期
179
- const SESSION_EXPIRE = 30 * 60 * 1000;
320
+ var SESSION_EXPIRE = 30 * 60 * 1000;
180
321
 
181
322
  /**
182
323
  * 获取或创建 session_id。
@@ -184,25 +325,24 @@ const SESSION_EXPIRE = 30 * 60 * 1000;
184
325
  * @returns {string} 当前的 session_id
185
326
  */
186
327
  function getSessionId() {
187
- const sid = storage.get(SESSION_KEY);
188
- const lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
189
-
190
- // 如果不存在 或 已过期
191
- if (!sid || now() - lastTime > SESSION_EXPIRE) {
192
- const newSid = uuid();
193
- storage.set(SESSION_KEY, newSid);
194
- storage.set(SESSION_TIME_KEY, now());
195
- return newSid;
196
- }
328
+ var sid = storage.get(SESSION_KEY);
329
+ var lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
197
330
 
198
- return sid;
331
+ // 如果不存在 或 已过期
332
+ if (!sid || now() - lastTime > SESSION_EXPIRE) {
333
+ var newSid = uuid();
334
+ storage.set(SESSION_KEY, newSid);
335
+ storage.set(SESSION_TIME_KEY, now());
336
+ return newSid;
337
+ }
338
+ return sid;
199
339
  }
200
340
 
201
341
  /**
202
342
  * 刷新 session 的活跃时间(用户活跃时调用),延长 session 生命周期。
203
343
  */
204
344
  function refreshSession() {
205
- storage.set(SESSION_TIME_KEY, now());
345
+ storage.set(SESSION_TIME_KEY, now());
206
346
  }
207
347
 
208
348
  /**
@@ -216,12 +356,10 @@ function refreshSession() {
216
356
  function throttle(fn, delay) {
217
357
  var lastTime = 0;
218
358
  var timer = null;
219
-
220
- return function() {
359
+ return function () {
221
360
  var context = this;
222
361
  var args = arguments;
223
362
  var now = Date.now();
224
-
225
363
  if (now - lastTime >= delay) {
226
364
  // 如果距离上次执行时间超过了延迟时间,立即执行
227
365
  if (timer) {
@@ -233,7 +371,7 @@ function throttle(fn, delay) {
233
371
  } else if (!timer) {
234
372
  // 否则,如果没有设置定时器,则设置一个定时器在剩余时间后执行
235
373
  // 这保证了最后一次触发一定会被执行(trailing edge)
236
- timer = setTimeout(function() {
374
+ timer = setTimeout(function () {
237
375
  fn.apply(context, args);
238
376
  lastTime = Date.now();
239
377
  timer = null;
@@ -242,65 +380,72 @@ function throttle(fn, delay) {
242
380
  };
243
381
  }
244
382
 
383
+ var _excluded = ["system", "module", "sub_module"];
384
+
245
385
  /**
246
386
  * Tracker 核心类
247
387
  */
248
- class Tracker {
249
- /**
250
- * @param {Object} options - 初始化配置项
251
- * @param {string} options.endPoint - 数据上报接口地址
252
- * @param {number} [options.delay=1000] - 批量上报延迟
253
- * @param {number} [options.maxBatchSize=10] - 批量上报最大条数
254
- * @param {string} [options.token] - 数据上报接口的 Token
255
- */
256
- constructor(options = {}) {
257
- if (!options.endPoint) {
258
- console.error("[Tracker SDK] endPoint is required for initialization.");
259
- }
260
-
261
- this.options = {
262
- delay: 1000,
263
- maxBatchSize: 10,
264
- ...options
265
- };
266
-
267
- this.deviceId = uuid();
268
- this.sessionId = getSessionId();
269
-
270
- this.userId = null;
271
- this.globalExt = {};
272
-
273
- this.current = null;
274
- this.lastActiveTime = now();
275
-
276
- this.queue = new Queue((data) => {
277
- if (this.options.endPoint) {
278
- send(this.options.endPoint, data, this.options.token);
279
- }
280
- }, {
281
- delay: this.options.delay,
282
- maxBatchSize: this.options.maxBatchSize
283
- });
284
-
285
- this.plugins = [];
286
-
287
- // 自动绑定活跃检测和生命周期监听
288
- this._bindActivity();
289
- this._bindLifecycle();
388
+ var Tracker = /*#__PURE__*/function () {
389
+ /**
390
+ * @param {Object} options - 初始化配置项
391
+ * @param {string} options.endPoint - 数据上报接口地址
392
+ * @param {number} [options.delay=1000] - 批量上报延迟
393
+ * @param {number} [options.maxBatchSize=10] - 批量上报最大条数
394
+ * @param {string} [options.token] - 数据上报接口的 Token
395
+ */
396
+ function Tracker() {
397
+ var _this = this;
398
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
399
+ _classCallCheck(this, Tracker);
400
+ if (!options.endPoint) {
401
+ console.error("[Tracker SDK] endPoint is required for initialization.");
290
402
  }
291
-
292
- /***********插件**********/
293
- /**
294
- * 使用插件扩展 SDK 功能
295
- * @param {Function} plugin - 插件函数
296
- */
297
- use(plugin) {
298
- if (typeof plugin === 'function') {
299
- plugin(this);
300
- this.plugins.push(plugin);
403
+ this.options = _objectSpread2({
404
+ delay: 1000,
405
+ maxBatchSize: 10
406
+ }, options);
407
+ this.deviceId = uuid();
408
+ this.sessionId = getSessionId();
409
+ this.userId = null;
410
+ this.globalExt = {};
411
+ this.current = null;
412
+ this.lastActiveTime = now();
413
+ this.queue = new Queue(function (data, isFlush) {
414
+ if (_this.options.endPoint) {
415
+ // 如果是 flush 触发的(通常是页面关闭),强制使用 sendBeacon
416
+ send(_this.options.endPoint, data, _this.options.token, isFlush);
417
+ }
418
+ }, {
419
+ delay: this.options.delay,
420
+ maxBatchSize: this.options.maxBatchSize
421
+ });
422
+ this.plugins = [];
423
+
424
+ // 自动绑定活跃检测和生命周期监听
425
+ this._bindActivity();
426
+ this._bindLifecycle();
427
+ }
428
+
429
+ /***********插件**********/
430
+ /**
431
+ * 使用插件扩展 SDK 功能
432
+ * @param {Function} plugin - 插件函数
433
+ * @param {Object} [options] - 插件配置项(可选)
434
+ */
435
+ return _createClass(Tracker, [{
436
+ key: "use",
437
+ value: function use(plugin, options) {
438
+ if (typeof plugin === 'function') {
439
+ // 如果提供了 options,传递给插件函数
440
+ if (options !== undefined) {
441
+ plugin(this, options);
301
442
  } else {
302
- console.warn("[Tracker SDK] Plugin must be a function.");
443
+ plugin(this);
303
444
  }
445
+ this.plugins.push(plugin);
446
+ } else {
447
+ console.warn("[Tracker SDK] Plugin must be a function.");
448
+ }
304
449
  }
305
450
 
306
451
  /***********用户**********/
@@ -308,19 +453,20 @@ class Tracker {
308
453
  * 设置用户 ID
309
454
  * @param {string|number} userId
310
455
  */
311
- setUser(userId) {
312
- this.userId = userId;
456
+ }, {
457
+ key: "setUser",
458
+ value: function setUser(userId) {
459
+ this.userId = userId;
313
460
  }
314
461
 
315
462
  /**
316
463
  * 设置全局扩展参数
317
464
  * @param {Object} ext
318
465
  */
319
- setExt(ext) {
320
- this.globalExt = {
321
- ...this.globalExt,
322
- ...ext
323
- };
466
+ }, {
467
+ key: "setExt",
468
+ value: function setExt(ext) {
469
+ this.globalExt = _objectSpread2(_objectSpread2({}, this.globalExt), ext);
324
470
  }
325
471
 
326
472
  /***********行为**********/
@@ -328,104 +474,367 @@ class Tracker {
328
474
  * 记录进入模块
329
475
  * @param {Object} module
330
476
  */
331
- enter(module) {
332
- // 如果当前已经在某个模块中,先触发离开逻辑
333
- if (this.current) {
334
- this.leave();
335
- }
336
-
337
- this.current = {
338
- ...module,
339
- enterTime: now()
340
- };
477
+ }, {
478
+ key: "enter",
479
+ value: function enter(module) {
480
+ // 如果当前已经在某个模块中,先触发离开逻辑
481
+ if (this.current) {
482
+ this.leave();
483
+ }
484
+ this.current = _objectSpread2(_objectSpread2({}, module), {}, {
485
+ enterTime: now()
486
+ });
341
487
  }
342
488
 
343
489
  /**
344
490
  * 记录离开模块
345
491
  * @param {boolean} force - 是否强制使用当前时间作为结束时间(用于页面卸载等场景)
346
492
  */
347
- leave(force = false) {
348
- if (!this.current) {
349
- return;
350
- }
351
-
352
- const endTime = force ? now() : this.lastActiveTime;
353
- const duration = Math.max(0, endTime - this.current.enterTime);
354
-
355
- const event = {
356
- event: 'module_leave',
357
- timeStamp: now(),
358
- session_id: this.sessionId,
359
- user_id: this.userId,
360
- device_id: this.deviceId,
361
- context: {
362
- system: this.current.system,
363
- module: this.current.module,
364
- sub_module: this.current.sub_module,
365
- },
366
- duration,
367
- ext: this.globalExt
368
- };
369
-
370
- this.queue.push(event);
371
- this.current = null;
493
+ }, {
494
+ key: "leave",
495
+ value: function leave() {
496
+ var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
497
+ if (!this.current) {
498
+ return;
499
+ }
500
+ var endTime = force ? now() : this.lastActiveTime;
501
+ var duration = Math.max(0, endTime - this.current.enterTime);
502
+
503
+ // 构建 context 对象
504
+ var context = {
505
+ device_id: this.deviceId,
506
+ session_id: this.sessionId,
507
+ user_id: this.userId
508
+ };
509
+
510
+ // 构建 ext 对象(合并全局扩展参数和当前模块的额外信息)
511
+ var extData = _objectSpread2(_objectSpread2({}, this.globalExt), this.current.ext);
512
+ var event = {
513
+ system: this.current.system || '',
514
+ module: this.current.module || '',
515
+ sub_module: this.current.sub_module || '',
516
+ duration: duration,
517
+ event: 'module_leave',
518
+ timestamp: formatTime(now()),
519
+ context: context,
520
+ ext: extData
521
+ };
522
+ this.queue.push(event);
523
+ this.current = null;
372
524
  }
373
525
 
374
526
  /**
375
527
  * 上报自定义事件
376
528
  * @param {string} eventName
377
- * @param {Object} params
529
+ * @param {Object} params - 扩展参数,可包含 system, module, sub_module
378
530
  */
379
- track(eventName, params = {}) {
380
- this.queue.push({
381
- event: eventName,
382
- timeStamp: now(),
383
- session_id: this.sessionId,
384
- user_id: this.userId,
385
- device_id: this.deviceId,
386
- ext: {
387
- ...this.globalExt,
388
- ...params
389
- }
390
- });
531
+ }, {
532
+ key: "track",
533
+ value: function track(eventName) {
534
+ var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
535
+ // 从 params 中提取模块信息(如果存在)
536
+ var _params$system = params.system,
537
+ system = _params$system === void 0 ? '' : _params$system,
538
+ _params$module = params.module,
539
+ module = _params$module === void 0 ? '' : _params$module,
540
+ _params$sub_module = params.sub_module,
541
+ sub_module = _params$sub_module === void 0 ? '' : _params$sub_module,
542
+ restParams = _objectWithoutProperties(params, _excluded);
543
+
544
+ // 构建 context 对象
545
+ var context = {
546
+ device_id: this.deviceId,
547
+ session_id: this.sessionId,
548
+ user_id: this.userId
549
+ };
550
+
551
+ // 构建 ext 对象(合并全局扩展参数和剩余的事件参数)
552
+ var extData = _objectSpread2(_objectSpread2({}, this.globalExt), restParams);
553
+ this.queue.push({
554
+ system: system,
555
+ module: module,
556
+ sub_module: sub_module,
557
+ duration: 0,
558
+ event: eventName,
559
+ timestamp: formatTime(now()),
560
+ context: context,
561
+ ext: extData
562
+ });
391
563
  }
392
564
 
393
565
  /***********活跃检测**********/
394
- _bindActivity() {
395
- const update = () => {
396
- this.lastActiveTime = now();
397
- refreshSession(); // 用户活跃时刷新 Session 有效期
398
- };
399
-
400
- const events = ['click', 'keydown', 'touchstart'];
401
- events.forEach(event => {
402
- document.addEventListener(event, update, { passive: true });
566
+ }, {
567
+ key: "_bindActivity",
568
+ value: function _bindActivity() {
569
+ var _this2 = this;
570
+ var update = function update() {
571
+ _this2.lastActiveTime = now();
572
+ refreshSession(); // 用户活跃时刷新 Session 有效期
573
+ };
574
+ var events = ['click', 'keydown', 'touchstart'];
575
+ events.forEach(function (event) {
576
+ document.addEventListener(event, update, {
577
+ passive: true
403
578
  });
404
-
405
- // 对高频事件进行节流
406
- document.addEventListener('mousemove', throttle(update, 5000), { passive: true });
407
- document.addEventListener('scroll', throttle(update, 500), { passive: true });
579
+ });
580
+
581
+ // 对高频事件进行节流
582
+ document.addEventListener('mousemove', throttle(update, 5000), {
583
+ passive: true
584
+ });
585
+ document.addEventListener('scroll', throttle(update, 500), {
586
+ passive: true
587
+ });
408
588
  }
409
589
 
410
590
  /***********生命周期**********/
411
- _bindLifecycle() {
412
- // 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
413
- const flushData = () => {
414
- this.leave(true);
415
- this.queue.flush();
591
+ }, {
592
+ key: "_bindLifecycle",
593
+ value: function _bindLifecycle() {
594
+ var _this3 = this;
595
+ // 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
596
+ var flushData = function flushData() {
597
+ _this3.leave(true);
598
+ _this3.queue.flush(true); // 传入 true,标记为页面关闭场景
599
+ };
600
+ window.addEventListener('beforeunload', flushData);
601
+ document.addEventListener('visibilitychange', function () {
602
+ if (document.visibilityState === 'hidden') {
603
+ flushData();
604
+ }
605
+ });
606
+ }
607
+ }]);
608
+ }();
609
+
610
+ function performancePlugin(tracker) {
611
+ window.addEventListener('load', function () {
612
+ // 使用 setTimeout 确保 loadEventEnd 等指标已完成采集
613
+ setTimeout(function () {
614
+ var performanceData = null;
615
+
616
+ // 优先使用 Navigation Timing Level 2 API
617
+ if (typeof performance.getEntriesByType === 'function') {
618
+ var navEntry = performance.getEntriesByType('navigation')[0];
619
+ if (navEntry) {
620
+ performanceData = {
621
+ // loadEventEnd 已经是相对于 startTime 的时长
622
+ load: navEntry.loadEventEnd,
623
+ // 使用 domComplete - domInteractive 作为 DOM 解析完成的耗时指标
624
+ dom: navEntry.domComplete - navEntry.domInteractive
625
+ };
626
+ }
627
+ }
628
+
629
+ // 如果不支持新 API,则回退到 performance.timing
630
+ if (!performanceData && performance.timing) {
631
+ var timing = performance.timing;
632
+ performanceData = {
633
+ load: timing.loadEventEnd - timing.navigationStart,
634
+ dom: timing.domComplete - timing.domLoading
416
635
  };
636
+ }
637
+ if (performanceData) {
638
+ tracker.track('performance', performanceData);
639
+ }
640
+ }, 0);
641
+ });
642
+ }
417
643
 
418
- window.addEventListener('beforeunload', flushData);
644
+ /**
645
+ * 错误监控插件
646
+ * 捕获运行时 JS 错误、未处理的 Promise 拒绝以及资源加载错误。
647
+ */
648
+ function errorPlugin(tracker) {
649
+ // 捕获 JS 运行时错误和资源加载错误
650
+ window.addEventListener('error', function (event) {
651
+ // 如果是资源加载错误(如 img, script 标签加载失败)
652
+ if (event.target && (event.target.src || event.target.href)) {
653
+ tracker.track('resource_error', {
654
+ target: event.target.tagName,
655
+ url: event.target.src || event.target.href,
656
+ pageUrl: window.location.href
657
+ });
658
+ } else {
659
+ // 普通 JS 运行时错误
660
+ tracker.track('js_error', {
661
+ message: event.message,
662
+ url: event.filename,
663
+ line: event.lineno,
664
+ col: event.colno,
665
+ stack: event.error && event.error.stack,
666
+ pageUrl: window.location.href
667
+ });
668
+ }
669
+ }, true); // 使用捕获阶段以捕获资源加载错误
670
+
671
+ // 捕获未处理的 Promise 拒绝
672
+ window.addEventListener('unhandledrejection', function (event) {
673
+ var reason = event.reason || {};
674
+ tracker.track('promise_error', {
675
+ reason: reason.message || reason,
676
+ stack: reason.stack,
677
+ pageUrl: window.location.href
678
+ });
679
+ });
680
+ }
419
681
 
420
- document.addEventListener('visibilitychange', () => {
421
- if (document.visibilityState === 'hidden') {
422
- flushData();
423
- }
424
- });
682
+ /**
683
+ * 路由监控插件
684
+ * 自动追踪页面路由变化,支持 History API 和 Hash 模式。
685
+ *
686
+ * @param tracker - Tracker 实例
687
+ * @param {Object} options - 插件配置项
688
+ * @param {string} [options.system='router'] - 系统标识,默认为 'router'
689
+ * @param {Function} [options.moduleMapper] - 自定义模块名称映射函数,接收路径作为参数,返回模块名称
690
+ */
691
+ function routerPlugin(tracker) {
692
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
693
+ var _options$system = options.system,
694
+ system = _options$system === void 0 ? 'router' : _options$system,
695
+ _options$moduleMapper = options.moduleMapper,
696
+ moduleMapper = _options$moduleMapper === void 0 ? null : _options$moduleMapper;
697
+
698
+ // 获取完整路径:pathname + search + hash
699
+ var lastPath = window.location.pathname + window.location.search + window.location.hash;
700
+
701
+ /**
702
+ * 根据路径获取模块名称
703
+ */
704
+ var getModuleName = function getModuleName(path) {
705
+ // 如果提供了自定义映射函数,使用它
706
+ if (typeof moduleMapper === 'function') {
707
+ return moduleMapper(path);
425
708
  }
709
+ // 否则使用完整路径
710
+ return path;
711
+ };
712
+
713
+ /**
714
+ * 追踪页面视图变化
715
+ */
716
+ var trackPageView = function trackPageView() {
717
+ // 使用 setTimeout 确保在路由更新完成后再获取 location
718
+ setTimeout(function () {
719
+ var currentPath = window.location.pathname + window.location.search + window.location.hash;
720
+ console.log('[Tracker SDK] Checking route change:', {
721
+ lastPath: lastPath,
722
+ currentPath: currentPath,
723
+ trackerCurrent: tracker.current
724
+ });
725
+
726
+ // 避免重复追踪相同的路径
727
+ if (currentPath === lastPath) {
728
+ console.log('[Tracker SDK] Route unchanged:', currentPath, moduleMapper ? moduleMapper(currentPath) : currentPath);
729
+
730
+ // 如果路径没变,但 tracker.current 为空(可能被生命周期清空了),需要重新 enter
731
+ if (!tracker.current) {
732
+ console.log('[Tracker SDK] Tracker current is null, re-entering current route');
733
+ tracker.enter({
734
+ module: getModuleName(currentPath),
735
+ system: system
736
+ });
737
+ }
738
+ return;
739
+ }
740
+ console.log('[Tracker SDK] Route changed:', lastPath, '->', currentPath, moduleMapper ? moduleMapper(currentPath) : currentPath);
741
+
742
+ // 如果 tracker.current 存在,先 leave
743
+ if (tracker.current) {
744
+ tracker.leave();
745
+ }
746
+ tracker.enter({
747
+ module: getModuleName(currentPath),
748
+ // 使用映射后的模块名
749
+ system: system // 使用配置的 system
750
+ });
751
+ lastPath = currentPath;
752
+ }, 0);
753
+ };
754
+
755
+ // 1. 追踪初始页面加载(延迟执行,确保 DOM 和路由已就绪)
756
+ setTimeout(function () {
757
+ var initialPath = window.location.pathname + window.location.search + window.location.hash;
758
+ lastPath = initialPath; // 更新 lastPath 为实际初始路径
759
+
760
+ tracker.enter({
761
+ module: getModuleName(initialPath),
762
+ system: system
763
+ });
764
+ console.log('[Tracker SDK] Initial route tracked:', initialPath);
765
+ }, 0);
766
+
767
+ // 2. 监听 Hash 模式路由变化
768
+ window.addEventListener('hashchange', trackPageView);
769
+
770
+ // 3. 监听 History API 模式路由变化 (pushState, replaceState, popstate)
771
+
772
+ // 劫持 history.pushState 和 history.replaceState
773
+ var patchHistoryMethod = function patchHistoryMethod(method) {
774
+ var original = history[method];
775
+ history[method] = function () {
776
+ var rv = original.apply(this, arguments);
777
+ // 派发一个自定义事件,以便外部监听
778
+ var event = new CustomEvent(method, {
779
+ detail: {
780
+ args: arguments
781
+ }
782
+ });
783
+ window.dispatchEvent(event);
784
+ return rv;
785
+ };
786
+ };
787
+ patchHistoryMethod('pushState');
788
+ patchHistoryMethod('replaceState');
789
+
790
+ // 监听劫持后派发的自定义事件
791
+ window.addEventListener('pushState', trackPageView);
792
+ window.addEventListener('replaceState', trackPageView);
793
+
794
+ // 监听浏览器前进/后退按钮 (popstate)
795
+ window.addEventListener('popstate', trackPageView);
796
+ }
797
+
798
+ /**
799
+ * 自动埋点插件
800
+ * 自动收集带有 data-track 属性的元素点击事件。
801
+ */
802
+ function autoTrackPlugin(tracker) {
803
+ document.addEventListener('click', function (e) {
804
+ var el = e.target;
805
+
806
+ // 向外寻找第一个带有 data-track 属性的元素,直到 body
807
+ while (el && el !== document.body) {
808
+ var eventName = el.getAttribute('data-track');
809
+ if (eventName) {
810
+ // 提取所有以 data-track- 开头的自定义属性
811
+ var params = {};
812
+ var attributes = el.attributes;
813
+ for (var i = 0; i < attributes.length; i++) {
814
+ var attr = attributes[i];
815
+ if (attr.name.startsWith('data-track-')) {
816
+ var key = attr.name.replace('data-track-', '');
817
+ params[key] = attr.value;
818
+ }
819
+ }
820
+
821
+ // 上报事件
822
+ tracker.track(eventName, _objectSpread2({
823
+ tag: el.tagName.toLowerCase(),
824
+ id: el.id || undefined,
825
+ class: el.className || undefined,
826
+ text: el.innerText ? el.innerText.slice(0, 50) : undefined
827
+ }, params));
828
+
829
+ // 找到第一个符合条件的就停止寻找
830
+ break;
831
+ }
832
+ el = el.parentElement;
833
+ }
834
+ }, true); // 使用捕获模式,确保能更早捕获事件
426
835
  }
427
836
 
428
- let instance = null;
837
+ var instance = null;
429
838
 
430
839
  /**
431
840
  * 初始化 Tracker SDK。
@@ -435,12 +844,14 @@ let instance = null;
435
844
  * @throws {Error} 如果 SDK 已经被初始化
436
845
  */
437
846
  function initTracker(options) {
438
- if (instance) {
439
- console.warn("[Tracker SDK] Tracker has already been initialized. Returning existing instance.");
440
- return instance;
441
- }
442
- instance = new Tracker(options);
847
+ console.log('[Tracker SDK] Initializing with options:', options);
848
+ if (instance) {
849
+ console.warn("[Tracker SDK] Tracker has already been initialized. Returning existing instance.");
443
850
  return instance;
851
+ }
852
+ instance = new Tracker(options);
853
+ console.log('[Tracker SDK] Initialized successfully, instance:', instance);
854
+ return instance;
444
855
  }
445
856
 
446
857
  /**
@@ -450,10 +861,10 @@ function initTracker(options) {
450
861
  * @throws {Error} 如果 SDK 尚未初始化
451
862
  */
452
863
  function getTracker() {
453
- if (!instance) {
454
- throw new Error("[Tracker SDK] Tracker has not been initialized. Call initTracker() first.");
455
- }
456
- return instance;
864
+ if (!instance) {
865
+ throw new Error("[Tracker SDK] Tracker has not been initialized. Call initTracker() first.");
866
+ }
867
+ return instance;
457
868
  }
458
869
 
459
- export { getTracker, initTracker };
870
+ export { autoTrackPlugin as autoTracker, errorPlugin, getTracker, initTracker, performancePlugin, routerPlugin };