@jasolar/tracker-sdk 1.0.2 → 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.
@@ -0,0 +1,877 @@
1
+ 'use strict';
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
+
105
+ /**
106
+ * 数据上报队列,支持批量发送和定时发送。
107
+ */
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
+ }
140
+
141
+ // 如果没有定时器,则设置一个定时器在延迟后发送
142
+ if (!this.timer) {
143
+ this.timer = setTimeout(function () {
144
+ _this.flush();
145
+ }, this.delay);
146
+ }
147
+ }
148
+
149
+ /**
150
+ * 立即发送队列中的所有数据。
151
+ * @param {boolean} isFlush - 是否为强制刷新(如页面关闭)
152
+ */
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
+ }
161
+
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
+ }
177
+ }
178
+ }]);
179
+ }();
180
+
181
+ /**
182
+ * 发送数据到服务器。
183
+ *
184
+ * 优化逻辑:
185
+ * 1. 优先使用 fetch + keepalive,以支持自定义 Authorization Header。
186
+ * 2. 如果 fetch 不可用或由于 payload 过大导致失败,回退到 navigator.sendBeacon。
187
+ * 3. 由于 sendBeacon 不支持 Headers,Token 会被附加到 URL 参数中。
188
+ */
189
+
190
+ /*
191
+ @param {string} url - 服务器地址
192
+ @param {Object} data - 要发送的数据
193
+ @param {Object} token - 认证令牌
194
+ @param {boolean} useBeacon - 是否强制使用 sendBeacon(用于页面关闭场景)
195
+ */
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
+ }
209
+
210
+ // 1. 如果强制使用 Beacon 或 fetch 不可用,直接使用 sendBeacon
211
+ if (useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
212
+ var beaconUrl = url;
213
+ if (token) {
214
+ var separator = url.includes('?') ? '&' : '?';
215
+ beaconUrl = "".concat(url).concat(separator, "token=").concat(encodeURIComponent(token));
216
+ }
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);
238
+ }
239
+ }
240
+
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));
247
+ }
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.');
255
+ }
256
+
257
+ function uuid() {
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;
261
+ return v.toString(16);
262
+ });
263
+ }
264
+
265
+ /**
266
+ * 简单的本地存储封装
267
+ */
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);
284
+ }
285
+ },
286
+ remove: function remove(key) {
287
+ localStorage.removeItem(key);
288
+ }
289
+ };
290
+
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
+ }
314
+
315
+ // src/core/session.js
316
+
317
+
318
+ var SESSION_KEY = 'TRACKER_SESSION_ID';
319
+ var SESSION_TIME_KEY = 'TRACKER_SESSION_TIME';
320
+
321
+ // 默认 30 分钟过期
322
+ var SESSION_EXPIRE = 30 * 60 * 1000;
323
+
324
+ /**
325
+ * 获取或创建 session_id。
326
+ * 如果 session 不存在或已过期,则生成新的 session_id。
327
+ * @returns {string} 当前的 session_id
328
+ */
329
+ function getSessionId() {
330
+ var sid = storage.get(SESSION_KEY);
331
+ var lastTime = Number(storage.get(SESSION_TIME_KEY) || 0); // 确保是数字
332
+
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;
341
+ }
342
+
343
+ /**
344
+ * 刷新 session 的活跃时间(用户活跃时调用),延长 session 生命周期。
345
+ */
346
+ function refreshSession() {
347
+ storage.set(SESSION_TIME_KEY, now());
348
+ }
349
+
350
+ /**
351
+ * 节流函数:在指定的时间间隔内,无论触发多少次,函数只执行一次。
352
+ * 包含最后一次触发的延迟执行(trailing edge)。
353
+ *
354
+ * @param {Function} fn - 需要节流的函数
355
+ * @param {number} delay - 间隔时间(毫秒)
356
+ * @returns {Function} - 节流后的函数
357
+ */
358
+ function throttle(fn, delay) {
359
+ var lastTime = 0;
360
+ var timer = null;
361
+ return function () {
362
+ var context = this;
363
+ var args = arguments;
364
+ var now = Date.now();
365
+ if (now - lastTime >= delay) {
366
+ // 如果距离上次执行时间超过了延迟时间,立即执行
367
+ if (timer) {
368
+ clearTimeout(timer);
369
+ timer = null;
370
+ }
371
+ fn.apply(context, args);
372
+ lastTime = now;
373
+ } else if (!timer) {
374
+ // 否则,如果没有设置定时器,则设置一个定时器在剩余时间后执行
375
+ // 这保证了最后一次触发一定会被执行(trailing edge)
376
+ timer = setTimeout(function () {
377
+ fn.apply(context, args);
378
+ lastTime = Date.now();
379
+ timer = null;
380
+ }, delay - (now - lastTime));
381
+ }
382
+ };
383
+ }
384
+
385
+ var _excluded = ["system", "module", "sub_module"];
386
+
387
+ /**
388
+ * Tracker 核心类
389
+ */
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.");
404
+ }
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);
444
+ } else {
445
+ plugin(this);
446
+ }
447
+ this.plugins.push(plugin);
448
+ } else {
449
+ console.warn("[Tracker SDK] Plugin must be a function.");
450
+ }
451
+ }
452
+
453
+ /***********用户**********/
454
+ /**
455
+ * 设置用户 ID
456
+ * @param {string|number} userId
457
+ */
458
+ }, {
459
+ key: "setUser",
460
+ value: function setUser(userId) {
461
+ this.userId = userId;
462
+ }
463
+
464
+ /**
465
+ * 设置全局扩展参数
466
+ * @param {Object} ext
467
+ */
468
+ }, {
469
+ key: "setExt",
470
+ value: function setExt(ext) {
471
+ this.globalExt = _objectSpread2(_objectSpread2({}, this.globalExt), ext);
472
+ }
473
+
474
+ /***********行为**********/
475
+ /**
476
+ * 记录进入模块
477
+ * @param {Object} module
478
+ */
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
+ });
489
+ }
490
+
491
+ /**
492
+ * 记录离开模块
493
+ * @param {boolean} force - 是否强制使用当前时间作为结束时间(用于页面卸载等场景)
494
+ */
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;
526
+ }
527
+
528
+ /**
529
+ * 上报自定义事件
530
+ * @param {string} eventName
531
+ * @param {Object} params - 扩展参数,可包含 system, module, sub_module
532
+ */
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
+ });
565
+ }
566
+
567
+ /***********活跃检测**********/
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
580
+ });
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
+ });
590
+ }
591
+
592
+ /***********生命周期**********/
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
637
+ };
638
+ }
639
+ if (performanceData) {
640
+ tracker.track('performance', performanceData);
641
+ }
642
+ }, 0);
643
+ });
644
+ }
645
+
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
+ }
683
+
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);
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); // 使用捕获模式,确保能更早捕获事件
837
+ }
838
+
839
+ var instance = null;
840
+
841
+ /**
842
+ * 初始化 Tracker SDK。
843
+ * 如果 SDK 已经被初始化,将抛出错误。
844
+ * @param {Object} options - 初始化选项
845
+ * @returns {Tracker} Tracker 实例
846
+ * @throws {Error} 如果 SDK 已经被初始化
847
+ */
848
+ function initTracker(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.");
852
+ return instance;
853
+ }
854
+ instance = new Tracker(options);
855
+ console.log('[Tracker SDK] Initialized successfully, instance:', instance);
856
+ return instance;
857
+ }
858
+
859
+ /**
860
+ * 获取 Tracker SDK 实例。
861
+ * 如果 SDK 尚未初始化,将抛出错误。
862
+ * @returns {Tracker} Tracker 实例
863
+ * @throws {Error} 如果 SDK 尚未初始化
864
+ */
865
+ function getTracker() {
866
+ if (!instance) {
867
+ throw new Error("[Tracker SDK] Tracker has not been initialized. Call initTracker() first.");
868
+ }
869
+ return instance;
870
+ }
871
+
872
+ exports.autoTracker = autoTrackPlugin;
873
+ exports.errorPlugin = errorPlugin;
874
+ exports.getTracker = getTracker;
875
+ exports.initTracker = initTracker;
876
+ exports.performancePlugin = performancePlugin;
877
+ exports.routerPlugin = routerPlugin;