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