@jasolar/tracker-sdk 1.0.11 → 1.0.12
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 → index.cjs} +532 -357
- package/dist/index.d.ts +63 -0
- package/dist/index.esm.js +529 -358
- package/package.json +12 -3
package/dist/index.esm.js
CHANGED
|
@@ -92,6 +92,15 @@ function _toPropertyKey(t) {
|
|
|
92
92
|
var i = _toPrimitive(t, "string");
|
|
93
93
|
return "symbol" == typeof i ? i : i + "";
|
|
94
94
|
}
|
|
95
|
+
function _typeof(o) {
|
|
96
|
+
"@babel/helpers - typeof";
|
|
97
|
+
|
|
98
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
99
|
+
return typeof o;
|
|
100
|
+
} : function (o) {
|
|
101
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
102
|
+
}, _typeof(o);
|
|
103
|
+
}
|
|
95
104
|
function _unsupportedIterableToArray(r, a) {
|
|
96
105
|
if (r) {
|
|
97
106
|
if ("string" == typeof r) return _arrayLikeToArray(r, a);
|
|
@@ -109,6 +118,7 @@ var Queue = /*#__PURE__*/function () {
|
|
|
109
118
|
* @param {Object} options - 配置项
|
|
110
119
|
* @param {number} [options.delay=1000] - 批量发送的延迟时间(毫秒)。
|
|
111
120
|
* @param {number} [options.maxBatchSize=10] - 最大批量大小,达到此数量时立即发送。
|
|
121
|
+
* @param {Function} [options.log] - debug 日志函数。
|
|
112
122
|
*/
|
|
113
123
|
function Queue(flushFn) {
|
|
114
124
|
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
@@ -118,6 +128,7 @@ var Queue = /*#__PURE__*/function () {
|
|
|
118
128
|
this.timer = null;
|
|
119
129
|
this.delay = options.delay || 1000;
|
|
120
130
|
this.maxBatchSize = options.maxBatchSize || 10;
|
|
131
|
+
this.log = options.log || function () {};
|
|
121
132
|
}
|
|
122
133
|
|
|
123
134
|
/**
|
|
@@ -151,27 +162,22 @@ var Queue = /*#__PURE__*/function () {
|
|
|
151
162
|
}, {
|
|
152
163
|
key: "flush",
|
|
153
164
|
value: function flush() {
|
|
154
|
-
var _this2 = this;
|
|
155
165
|
var isFlush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
|
|
156
166
|
if (!this.list.length) {
|
|
157
|
-
|
|
167
|
+
this.log("Queue flush called but queue is empty");
|
|
158
168
|
return;
|
|
159
169
|
}
|
|
160
|
-
|
|
170
|
+
this.log("Flushing queue, items:", this.list.length, "isFlush:", isFlush);
|
|
161
171
|
|
|
162
172
|
// 复制一份数据列表,防止在发送过程中 list 被修改
|
|
163
173
|
var dataToSend = _toConsumableArray(this.list);
|
|
164
174
|
this.list = []; // 清空队列
|
|
165
175
|
|
|
166
176
|
try {
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
console.log("[Tracker SDK] Sending event ".concat(index + 1, "/").concat(dataToSend.length, ":"), item.event);
|
|
170
|
-
_this2.flushFn(item, isFlush);
|
|
171
|
-
});
|
|
172
|
-
console.log('[Tracker SDK] All events sent successfully');
|
|
177
|
+
// 一次把整批交给 transport;是否真正合并成一个请求由 transport 的 batch 选项决定。
|
|
178
|
+
this.flushFn(dataToSend, isFlush);
|
|
173
179
|
} catch (error) {
|
|
174
|
-
|
|
180
|
+
this.log("Failed to flush data:", error);
|
|
175
181
|
} finally {
|
|
176
182
|
clearTimeout(this.timer);
|
|
177
183
|
this.timer = null;
|
|
@@ -183,90 +189,129 @@ var Queue = /*#__PURE__*/function () {
|
|
|
183
189
|
/**
|
|
184
190
|
* 发送数据到服务器。
|
|
185
191
|
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
192
|
+
* 兼容两种调用方式:
|
|
193
|
+
* - send(url, data, token, useBeacon) 旧签名(内部兼容)
|
|
194
|
+
* - send(url, data, { token, headers, batch, ... }) 新签名
|
|
195
|
+
*
|
|
196
|
+
* 安全默认值:
|
|
197
|
+
* - sendBeacon 默认不把 token 拼进 URL(beaconAuth: "none"),依赖同源网关注入身份;
|
|
198
|
+
* 确需 query 认证时显式设置 beaconAuth: "query"。
|
|
199
|
+
* - debug 关闭时不打印任何事件数据或初始化参数。
|
|
190
200
|
*/
|
|
191
201
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
@param {Object} token - 认证令牌
|
|
196
|
-
@param {boolean} useBeacon - 是否强制使用 sendBeacon(用于页面关闭场景)
|
|
197
|
-
*/
|
|
198
|
-
function send(url, data) {
|
|
199
|
-
var token = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
200
|
-
var useBeacon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
|
|
201
|
-
if (!url) {
|
|
202
|
-
console.warn('[Tracker SDK] Send called without URL');
|
|
203
|
-
return;
|
|
202
|
+
function normalizeOptions(options, legacyUseBeacon) {
|
|
203
|
+
if (options && _typeof(options) === "object" && !Array.isArray(options) && ("token" in options || "headers" in options || "batch" in options || "debug" in options || "beaconAuth" in options || "useBeacon" in options)) {
|
|
204
|
+
return options;
|
|
204
205
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
module: data.module,
|
|
209
|
-
useBeacon: useBeacon,
|
|
210
|
-
hasToken: !!token
|
|
211
|
-
});
|
|
212
|
-
var body = JSON.stringify(data);
|
|
213
|
-
|
|
214
|
-
// 构造请求头
|
|
215
|
-
var headers = {
|
|
216
|
-
'Content-Type': 'application/json'
|
|
206
|
+
return {
|
|
207
|
+
token: options,
|
|
208
|
+
useBeacon: Boolean(legacyUseBeacon)
|
|
217
209
|
};
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
210
|
+
}
|
|
211
|
+
function appendBeaconToken(url, token) {
|
|
212
|
+
if (!token) return url;
|
|
213
|
+
var separator = url.includes("?") ? "&" : "?";
|
|
214
|
+
return "".concat(url).concat(separator, "Authorization=").concat(encodeURIComponent("Bearer " + token));
|
|
215
|
+
}
|
|
216
|
+
function sendOne(url, payload, options) {
|
|
217
|
+
var token = options.token,
|
|
218
|
+
_options$headers = options.headers,
|
|
219
|
+
extraHeaders = _options$headers === void 0 ? {} : _options$headers,
|
|
220
|
+
_options$useBeacon = options.useBeacon,
|
|
221
|
+
useBeacon = _options$useBeacon === void 0 ? false : _options$useBeacon,
|
|
222
|
+
_options$debug = options.debug,
|
|
223
|
+
debug = _options$debug === void 0 ? false : _options$debug,
|
|
224
|
+
_options$beaconAuth = options.beaconAuth,
|
|
225
|
+
beaconAuth = _options$beaconAuth === void 0 ? "none" : _options$beaconAuth,
|
|
226
|
+
_options$maxKeepalive = options.maxKeepaliveBytes,
|
|
227
|
+
maxKeepaliveBytes = _options$maxKeepalive === void 0 ? 60 * 1024 : _options$maxKeepalive,
|
|
228
|
+
_options$credentials = options.credentials,
|
|
229
|
+
credentials = _options$credentials === void 0 ? "same-origin" : _options$credentials;
|
|
230
|
+
var log = function log() {
|
|
231
|
+
var _console;
|
|
232
|
+
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
233
|
+
args[_key] = arguments[_key];
|
|
229
234
|
}
|
|
235
|
+
if (debug) (_console = console).log.apply(_console, ["[Tracker SDK]"].concat(args));
|
|
236
|
+
};
|
|
237
|
+
var body = JSON.stringify(payload);
|
|
238
|
+
if (useBeacon && typeof navigator !== "undefined" && navigator.sendBeacon) {
|
|
239
|
+
var beaconUrl = beaconAuth === "query" ? appendBeaconToken(url, token) : url;
|
|
230
240
|
var blob = new Blob([body], {
|
|
231
|
-
type:
|
|
241
|
+
type: "application/json"
|
|
232
242
|
});
|
|
233
243
|
var result = navigator.sendBeacon(beaconUrl, blob);
|
|
234
|
-
|
|
244
|
+
log("sendBeacon", {
|
|
245
|
+
ok: result,
|
|
246
|
+
beaconAuth: beaconAuth
|
|
247
|
+
});
|
|
235
248
|
return result;
|
|
236
249
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
250
|
+
if (typeof fetch === "function") {
|
|
251
|
+
var headers = _objectSpread2({
|
|
252
|
+
"Content-Type": "application/json"
|
|
253
|
+
}, extraHeaders);
|
|
254
|
+
if (token) headers.Authorization = "Bearer ".concat(token);
|
|
255
|
+
var canKeepalive = body.length <= maxKeepaliveBytes;
|
|
240
256
|
try {
|
|
241
257
|
fetch(url, {
|
|
242
|
-
method:
|
|
258
|
+
method: "POST",
|
|
243
259
|
body: body,
|
|
244
260
|
headers: headers,
|
|
245
|
-
|
|
246
|
-
mode:
|
|
261
|
+
credentials: credentials,
|
|
262
|
+
mode: "cors",
|
|
263
|
+
keepalive: canKeepalive
|
|
247
264
|
}).catch(function (err) {
|
|
248
|
-
|
|
265
|
+
log("fetch report failed:", (err === null || err === void 0 ? void 0 : err.message) || err);
|
|
266
|
+
});
|
|
267
|
+
log("fetch report", {
|
|
268
|
+
bytes: body.length,
|
|
269
|
+
keepalive: canKeepalive
|
|
249
270
|
});
|
|
250
271
|
return;
|
|
251
272
|
} catch (e) {
|
|
252
|
-
|
|
273
|
+
log("fetch keepalive failed, trying sendBeacon:", (e === null || e === void 0 ? void 0 : e.message) || e);
|
|
253
274
|
}
|
|
254
275
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
|
|
258
|
-
var _beaconUrl = url;
|
|
259
|
-
if (token) {
|
|
260
|
-
var _separator = url.includes('?') ? '&' : '?';
|
|
261
|
-
_beaconUrl = "".concat(url).concat(_separator, "Authorization=").concat(encodeURIComponent('Bearer ' + token));
|
|
262
|
-
}
|
|
276
|
+
if (typeof navigator !== "undefined" && navigator.sendBeacon) {
|
|
277
|
+
var _beaconUrl = beaconAuth === "query" ? appendBeaconToken(url, token) : url;
|
|
263
278
|
var _blob = new Blob([body], {
|
|
264
|
-
type:
|
|
279
|
+
type: "application/json"
|
|
265
280
|
});
|
|
266
281
|
var success = navigator.sendBeacon(_beaconUrl, _blob);
|
|
282
|
+
log("sendBeacon fallback", {
|
|
283
|
+
ok: success,
|
|
284
|
+
beaconAuth: beaconAuth
|
|
285
|
+
});
|
|
267
286
|
if (success) return;
|
|
268
287
|
}
|
|
269
|
-
|
|
288
|
+
log("No available transport method.");
|
|
289
|
+
}
|
|
290
|
+
function send(url, data) {
|
|
291
|
+
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
292
|
+
var legacyUseBeacon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
|
|
293
|
+
if (!url) {
|
|
294
|
+
console.warn("[Tracker SDK] Send called without URL");
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
var normalized = normalizeOptions(options, legacyUseBeacon);
|
|
298
|
+
var _normalized$batch = normalized.batch,
|
|
299
|
+
batch = _normalized$batch === void 0 ? true : _normalized$batch;
|
|
300
|
+
if (Array.isArray(data)) {
|
|
301
|
+
if (batch) {
|
|
302
|
+
sendOne(url, {
|
|
303
|
+
events: data
|
|
304
|
+
}, normalized);
|
|
305
|
+
} else {
|
|
306
|
+
data.forEach(function (item) {
|
|
307
|
+
return sendOne(url, item, _objectSpread2(_objectSpread2({}, normalized), {}, {
|
|
308
|
+
batch: true
|
|
309
|
+
}));
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
sendOne(url, data, normalized);
|
|
270
315
|
}
|
|
271
316
|
|
|
272
317
|
function uuid() {
|
|
@@ -278,30 +323,45 @@ function uuid() {
|
|
|
278
323
|
}
|
|
279
324
|
|
|
280
325
|
/**
|
|
281
|
-
*
|
|
326
|
+
* 简单的本地存储封装。
|
|
327
|
+
* 存储不可用(隐私模式、iframe 限制)时静默回退,不影响业务。
|
|
282
328
|
*/
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
329
|
+
function createStore(getStorage) {
|
|
330
|
+
return {
|
|
331
|
+
get: function get(key) {
|
|
332
|
+
try {
|
|
333
|
+
var store = getStorage();
|
|
334
|
+
if (!store) return null;
|
|
335
|
+
var val = store.getItem(key);
|
|
336
|
+
if (!val) return null;
|
|
337
|
+
return JSON.parse(val);
|
|
338
|
+
} catch (e) {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
set: function set(key, value) {
|
|
343
|
+
try {
|
|
344
|
+
var store = getStorage();
|
|
345
|
+
if (!store) return;
|
|
346
|
+
store.setItem(key, JSON.stringify(value));
|
|
347
|
+
} catch (e) {
|
|
348
|
+
// ignore
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
remove: function remove(key) {
|
|
352
|
+
try {
|
|
353
|
+
var store = getStorage();
|
|
354
|
+
if (store) store.removeItem(key);
|
|
355
|
+
} catch (e) {
|
|
356
|
+
// ignore
|
|
357
|
+
}
|
|
299
358
|
}
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
var storage = createStore(function () {
|
|
362
|
+
if (typeof localStorage === "undefined") return null;
|
|
363
|
+
return localStorage;
|
|
364
|
+
});
|
|
305
365
|
|
|
306
366
|
/**
|
|
307
367
|
* 获取当前时间戳(毫秒)
|
|
@@ -329,30 +389,42 @@ function formatTime() {
|
|
|
329
389
|
|
|
330
390
|
// src/core/session.js
|
|
331
391
|
|
|
332
|
-
|
|
333
|
-
var
|
|
334
|
-
var
|
|
392
|
+
var SESSION_KEY = "TRACKER_SESSION_ID";
|
|
393
|
+
var SESSION_TIME_KEY = "TRACKER_SESSION_TIME";
|
|
394
|
+
var DEVICE_KEY = "TRACKER_DEVICE_ID";
|
|
335
395
|
|
|
336
396
|
// 默认 30 分钟过期
|
|
337
397
|
var SESSION_EXPIRE = 30 * 60 * 1000;
|
|
398
|
+
function readOrCreate(store, key, timeKey, expireMs) {
|
|
399
|
+
var id = store.get(key);
|
|
400
|
+
var lastTime = Number(store.get(timeKey) || 0);
|
|
401
|
+
if (!id || now() - lastTime > expireMs) {
|
|
402
|
+
var next = uuid();
|
|
403
|
+
store.set(key, next);
|
|
404
|
+
store.set(timeKey, now());
|
|
405
|
+
return next;
|
|
406
|
+
}
|
|
407
|
+
return id;
|
|
408
|
+
}
|
|
338
409
|
|
|
339
410
|
/**
|
|
340
|
-
*
|
|
341
|
-
*
|
|
342
|
-
* @returns {string} 当前的 session_id
|
|
411
|
+
* 获取或创建会话 ID(localStorage,跨 tab 共享)。
|
|
412
|
+
* @param {number} [expireMs] - 过期时间,默认 30 分钟
|
|
343
413
|
*/
|
|
344
414
|
function getSessionId() {
|
|
345
|
-
var
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
415
|
+
var expireMs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SESSION_EXPIRE;
|
|
416
|
+
return readOrCreate(storage, SESSION_KEY, SESSION_TIME_KEY, expireMs);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* 获取稳定的设备 ID(localStorage 持久化)。
|
|
421
|
+
*/
|
|
422
|
+
function getDeviceId() {
|
|
423
|
+
var saved = storage.get(DEVICE_KEY);
|
|
424
|
+
if (saved) return saved;
|
|
425
|
+
var id = uuid();
|
|
426
|
+
storage.set(DEVICE_KEY, id);
|
|
427
|
+
return id;
|
|
356
428
|
}
|
|
357
429
|
|
|
358
430
|
/**
|
|
@@ -408,7 +480,39 @@ function throttle(fn, delay) {
|
|
|
408
480
|
};
|
|
409
481
|
}
|
|
410
482
|
|
|
411
|
-
|
|
483
|
+
/**
|
|
484
|
+
* 统一日志开关。
|
|
485
|
+
* 生产环境(debug=false)不打印任何事件数据或初始化参数,避免 token/业务属性进控制台。
|
|
486
|
+
*/
|
|
487
|
+
function createLogger() {
|
|
488
|
+
var debug = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
|
|
489
|
+
var enabled = debug === true;
|
|
490
|
+
return {
|
|
491
|
+
log: function log() {
|
|
492
|
+
var _console;
|
|
493
|
+
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
494
|
+
args[_key] = arguments[_key];
|
|
495
|
+
}
|
|
496
|
+
if (enabled) (_console = console).log.apply(_console, ["[Tracker SDK]"].concat(args));
|
|
497
|
+
},
|
|
498
|
+
warn: function warn() {
|
|
499
|
+
var _console2;
|
|
500
|
+
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
|
501
|
+
args[_key2] = arguments[_key2];
|
|
502
|
+
}
|
|
503
|
+
if (enabled) (_console2 = console).warn.apply(_console2, ["[Tracker SDK]"].concat(args));
|
|
504
|
+
},
|
|
505
|
+
error: function error() {
|
|
506
|
+
var _console3;
|
|
507
|
+
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
|
|
508
|
+
args[_key3] = arguments[_key3];
|
|
509
|
+
}
|
|
510
|
+
(_console3 = console).error.apply(_console3, ["[Tracker SDK]"].concat(args));
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
var _excluded = ["system", "module", "sub_module", "duration", "event_id", "schema_version", "occurred_at"],
|
|
412
516
|
_excluded2 = ["enterTime"];
|
|
413
517
|
|
|
414
518
|
/**
|
|
@@ -418,10 +522,19 @@ var Tracker = /*#__PURE__*/function () {
|
|
|
418
522
|
/**
|
|
419
523
|
* @param {Object} options - 初始化配置项
|
|
420
524
|
* @param {string} options.endPoint - 数据上报接口地址
|
|
525
|
+
* @param {string} [options.appId] - 应用标识
|
|
421
526
|
* @param {number} [options.delay=1000] - 批量上报延迟
|
|
422
527
|
* @param {number} [options.maxBatchSize=10] - 批量上报最大条数
|
|
423
528
|
* @param {string} [options.token] - 数据上报接口的 Token
|
|
424
529
|
* @param {number} [options.sessionTimeout=1800000] - Session 超时时间(毫秒),默认30分钟
|
|
530
|
+
* @param {boolean} [options.debug=false] - 是否输出 SDK 调试日志
|
|
531
|
+
* @param {Object} [options.headers] - 额外请求头
|
|
532
|
+
* @param {boolean} [options.batch=false] - 是否把同批事件合并成 { events: [...] }
|
|
533
|
+
* @param {"none"|"query"} [options.beaconAuth="none"] - beacon 是否把 token 拼到 URL
|
|
534
|
+
* @param {number} [options.maxKeepaliveBytes=61440] - 超过该字节数时不使用 keepalive
|
|
535
|
+
* @param {"emit"|"silent"|"ignore"} [options.visibilityBehavior="emit"] - 页面恢复可见时的行为
|
|
536
|
+
* @param {boolean} [options.enableActivityTimeout=true] - 是否启用不活跃自动 leave
|
|
537
|
+
* @param {Function} [options.beforeSend] - 发送前最后一道过滤;返回 false 丢弃事件
|
|
425
538
|
*/
|
|
426
539
|
function Tracker() {
|
|
427
540
|
var _this = this;
|
|
@@ -433,50 +546,59 @@ var Tracker = /*#__PURE__*/function () {
|
|
|
433
546
|
this.options = _objectSpread2({
|
|
434
547
|
delay: 1000,
|
|
435
548
|
maxBatchSize: 10,
|
|
436
|
-
sessionTimeout: 30 * 60 * 1000
|
|
549
|
+
sessionTimeout: 30 * 60 * 1000,
|
|
550
|
+
appId: "",
|
|
551
|
+
debug: false,
|
|
552
|
+
headers: {},
|
|
553
|
+
batch: false,
|
|
554
|
+
beaconAuth: "none",
|
|
555
|
+
maxKeepaliveBytes: 60 * 1024,
|
|
556
|
+
credentials: "same-origin",
|
|
557
|
+
visibilityBehavior: "emit",
|
|
558
|
+
enableActivityTimeout: true,
|
|
559
|
+
persistDeviceId: true,
|
|
560
|
+
beforeSend: null
|
|
437
561
|
}, options);
|
|
438
|
-
this.
|
|
439
|
-
this.
|
|
562
|
+
this.log = createLogger(this.options.debug);
|
|
563
|
+
this.deviceId = this.options.deviceId || (this.options.persistDeviceId !== false ? getDeviceId() : uuid());
|
|
564
|
+
this.sessionId = getSessionId(this.options.sessionTimeout);
|
|
440
565
|
this.userId = null;
|
|
441
566
|
this.globalExt = {};
|
|
442
567
|
this.current = null;
|
|
443
568
|
this.lastActiveTime = now();
|
|
444
|
-
|
|
445
|
-
// 超时检测定时器
|
|
446
569
|
this.timeoutTimer = null;
|
|
447
|
-
|
|
448
|
-
// 标记是否因超时而离开(用于重新激活时判断)
|
|
449
570
|
this.isTimedOut = false;
|
|
571
|
+
this._isFlushing = false;
|
|
572
|
+
this._cleanupFns = [];
|
|
450
573
|
this.queue = new Queue(function (data, isFlush) {
|
|
451
574
|
if (_this.options.endPoint) {
|
|
452
|
-
|
|
453
|
-
|
|
575
|
+
send(_this.options.endPoint, data, {
|
|
576
|
+
token: _this.options.token,
|
|
577
|
+
headers: _this.options.headers,
|
|
578
|
+
useBeacon: isFlush,
|
|
579
|
+
debug: _this.options.debug,
|
|
580
|
+
batch: _this.options.batch,
|
|
581
|
+
beaconAuth: _this.options.beaconAuth,
|
|
582
|
+
maxKeepaliveBytes: _this.options.maxKeepaliveBytes,
|
|
583
|
+
credentials: _this.options.credentials
|
|
584
|
+
});
|
|
454
585
|
}
|
|
455
586
|
}, {
|
|
456
587
|
delay: this.options.delay,
|
|
457
|
-
maxBatchSize: this.options.maxBatchSize
|
|
588
|
+
maxBatchSize: this.options.maxBatchSize,
|
|
589
|
+
log: this.log.log
|
|
458
590
|
});
|
|
459
591
|
this.plugins = [];
|
|
460
|
-
|
|
461
|
-
// 自动绑定活跃检测和生命周期监听
|
|
462
592
|
this._bindActivity();
|
|
463
593
|
this._bindLifecycle();
|
|
464
|
-
|
|
465
|
-
// 启动超时检测
|
|
466
594
|
this._startTimeoutCheck();
|
|
467
595
|
}
|
|
468
596
|
|
|
469
597
|
/***********插件**********/
|
|
470
|
-
/**
|
|
471
|
-
* 使用插件扩展 SDK 功能
|
|
472
|
-
* @param {Function} plugin - 插件函数
|
|
473
|
-
* @param {Object} [options] - 插件配置项(可选)
|
|
474
|
-
*/
|
|
475
598
|
return _createClass(Tracker, [{
|
|
476
599
|
key: "use",
|
|
477
600
|
value: function use(plugin, options) {
|
|
478
|
-
if (typeof plugin ===
|
|
479
|
-
// 如果提供了 options,传递给插件函数
|
|
601
|
+
if (typeof plugin === "function") {
|
|
480
602
|
if (options !== undefined) {
|
|
481
603
|
plugin(this, options);
|
|
482
604
|
} else {
|
|
@@ -484,173 +606,161 @@ var Tracker = /*#__PURE__*/function () {
|
|
|
484
606
|
}
|
|
485
607
|
this.plugins.push(plugin);
|
|
486
608
|
} else {
|
|
487
|
-
|
|
609
|
+
this.log.warn("Plugin must be a function.");
|
|
488
610
|
}
|
|
489
611
|
}
|
|
490
612
|
|
|
491
613
|
/***********用户**********/
|
|
492
|
-
/**
|
|
493
|
-
* 设置用户 ID
|
|
494
|
-
* @param {string|number} userId
|
|
495
|
-
*/
|
|
496
614
|
}, {
|
|
497
615
|
key: "setUser",
|
|
498
616
|
value: function setUser(userId) {
|
|
499
617
|
this.userId = userId;
|
|
500
618
|
}
|
|
501
|
-
|
|
502
|
-
/**
|
|
503
|
-
* 设置全局扩展参数
|
|
504
|
-
* @param {Object} ext
|
|
505
|
-
*/
|
|
506
619
|
}, {
|
|
507
620
|
key: "setExt",
|
|
508
621
|
value: function setExt(ext) {
|
|
509
622
|
this.globalExt = _objectSpread2(_objectSpread2({}, this.globalExt), ext);
|
|
510
623
|
}
|
|
511
624
|
|
|
625
|
+
/***********事件信封**********/
|
|
626
|
+
}, {
|
|
627
|
+
key: "_context",
|
|
628
|
+
value: function _context() {
|
|
629
|
+
return {
|
|
630
|
+
device_id: this.deviceId,
|
|
631
|
+
session_id: this.sessionId,
|
|
632
|
+
user_id: this.userId
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
}, {
|
|
636
|
+
key: "_buildEvent",
|
|
637
|
+
value: function _buildEvent(eventName) {
|
|
638
|
+
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
|
639
|
+
_ref$system = _ref.system,
|
|
640
|
+
system = _ref$system === void 0 ? "" : _ref$system,
|
|
641
|
+
_ref$module = _ref.module,
|
|
642
|
+
module = _ref$module === void 0 ? "" : _ref$module,
|
|
643
|
+
_ref$sub_module = _ref.sub_module,
|
|
644
|
+
sub_module = _ref$sub_module === void 0 ? "" : _ref$sub_module,
|
|
645
|
+
_ref$duration = _ref.duration,
|
|
646
|
+
duration = _ref$duration === void 0 ? 0 : _ref$duration,
|
|
647
|
+
event_id = _ref.event_id,
|
|
648
|
+
schema_version = _ref.schema_version,
|
|
649
|
+
occurred_at = _ref.occurred_at,
|
|
650
|
+
_ref$ext = _ref.ext,
|
|
651
|
+
ext = _ref$ext === void 0 ? {} : _ref$ext;
|
|
652
|
+
return {
|
|
653
|
+
app_id: this.options.appId || "",
|
|
654
|
+
event_id: event_id || uuid(),
|
|
655
|
+
schema_version: schema_version || 1,
|
|
656
|
+
occurred_at: occurred_at || new Date().toISOString(),
|
|
657
|
+
system: system,
|
|
658
|
+
module: module,
|
|
659
|
+
sub_module: sub_module,
|
|
660
|
+
duration: duration,
|
|
661
|
+
event: eventName,
|
|
662
|
+
// 保留旧字段,兼容已有服务端解析
|
|
663
|
+
timestamp: formatTime(now()),
|
|
664
|
+
context: this._context(),
|
|
665
|
+
ext: _objectSpread2(_objectSpread2({}, this.globalExt), ext)
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
}, {
|
|
669
|
+
key: "_enqueue",
|
|
670
|
+
value: function _enqueue(event) {
|
|
671
|
+
try {
|
|
672
|
+
if (typeof this.options.beforeSend === "function") {
|
|
673
|
+
var result = this.options.beforeSend(event);
|
|
674
|
+
if (result === false) {
|
|
675
|
+
this.log.log("Event dropped by beforeSend:", event.event);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
this.queue.push(event);
|
|
680
|
+
} catch (error) {
|
|
681
|
+
this.log.warn("Failed to enqueue event:", error);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
512
685
|
/***********行为**********/
|
|
513
|
-
/**
|
|
514
|
-
* 记录进入模块
|
|
515
|
-
* @param {Object} module
|
|
516
|
-
*/
|
|
517
686
|
}, {
|
|
518
687
|
key: "enter",
|
|
519
688
|
value: function enter(module) {
|
|
520
|
-
// 如果当前已经在某个模块中,先触发离开逻辑
|
|
521
689
|
if (this.current) {
|
|
522
690
|
this.leave();
|
|
523
691
|
}
|
|
524
692
|
this.current = _objectSpread2(_objectSpread2({}, module), {}, {
|
|
525
693
|
enterTime: now()
|
|
526
694
|
});
|
|
527
|
-
|
|
528
|
-
// 清除超时标记
|
|
529
695
|
this.isTimedOut = false;
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
session_id: this.sessionId,
|
|
535
|
-
user_id: this.userId
|
|
536
|
-
};
|
|
537
|
-
|
|
538
|
-
// 构建 ext 对象(合并全局扩展参数和当前模块的额外信息)
|
|
539
|
-
var extData = _objectSpread2(_objectSpread2({}, this.globalExt), this.current.ext);
|
|
540
|
-
|
|
541
|
-
// 上报 module_enter 事件
|
|
542
|
-
var event = {
|
|
543
|
-
system: this.current.system || '',
|
|
544
|
-
module: this.current.module || '',
|
|
545
|
-
sub_module: this.current.sub_module || '',
|
|
696
|
+
this._enqueue(this._buildEvent("module_enter", {
|
|
697
|
+
system: this.current.system || "",
|
|
698
|
+
module: this.current.module || "",
|
|
699
|
+
sub_module: this.current.sub_module || "",
|
|
546
700
|
duration: 0,
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
context: context,
|
|
550
|
-
ext: extData
|
|
551
|
-
};
|
|
552
|
-
this.queue.push(event);
|
|
701
|
+
ext: _objectSpread2({}, this.current.ext)
|
|
702
|
+
}));
|
|
553
703
|
}
|
|
554
704
|
|
|
555
705
|
/**
|
|
556
|
-
*
|
|
557
|
-
* @param {boolean}
|
|
558
|
-
* @param {
|
|
559
|
-
* @param {string} reason - 离开原因(可选):'timeout' | 'visibility' | 'normal'
|
|
706
|
+
* @param {boolean} force - 是否强制使用当前时间作为结束时间
|
|
707
|
+
* @param {boolean} isTimeout - 是否因超时离开
|
|
708
|
+
* @param {string} reason - normal | visibility | timeout
|
|
560
709
|
*/
|
|
561
710
|
}, {
|
|
562
711
|
key: "leave",
|
|
563
712
|
value: function leave() {
|
|
564
713
|
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
|
|
565
714
|
var isTimeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
|
566
|
-
var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] :
|
|
715
|
+
var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "normal";
|
|
567
716
|
if (!this.current) {
|
|
568
|
-
|
|
717
|
+
this.log.log("Leave called but no current module");
|
|
569
718
|
return;
|
|
570
719
|
}
|
|
571
720
|
var endTime = force ? now() : this.lastActiveTime;
|
|
572
721
|
var duration = Math.max(0, endTime - this.current.enterTime);
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
force: force,
|
|
578
|
-
isTimeout: isTimeout,
|
|
579
|
-
reason: reason
|
|
580
|
-
});
|
|
581
|
-
|
|
582
|
-
// 构建 context 对象
|
|
583
|
-
var context = {
|
|
584
|
-
device_id: this.deviceId,
|
|
585
|
-
session_id: this.sessionId,
|
|
586
|
-
user_id: this.userId
|
|
587
|
-
};
|
|
588
|
-
|
|
589
|
-
// 构建 ext 对象(合并全局扩展参数和当前模块的额外信息)
|
|
590
|
-
var extData = _objectSpread2(_objectSpread2({}, this.globalExt), this.current.ext);
|
|
591
|
-
var event = {
|
|
592
|
-
system: this.current.system || '',
|
|
593
|
-
module: this.current.module || '',
|
|
594
|
-
sub_module: this.current.sub_module || '',
|
|
722
|
+
this._enqueue(this._buildEvent("module_leave", {
|
|
723
|
+
system: this.current.system || "",
|
|
724
|
+
module: this.current.module || "",
|
|
725
|
+
sub_module: this.current.sub_module || "",
|
|
595
726
|
duration: duration,
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
context: context,
|
|
599
|
-
ext: _objectSpread2(_objectSpread2({}, extData), {}, {
|
|
600
|
-
leave_reason: reason // 添加离开原因
|
|
727
|
+
ext: _objectSpread2(_objectSpread2({}, this.current.ext), {}, {
|
|
728
|
+
leave_reason: reason
|
|
601
729
|
})
|
|
602
|
-
};
|
|
603
|
-
console.log('[Tracker SDK] Pushing module_leave event to queue:', event);
|
|
604
|
-
this.queue.push(event);
|
|
605
|
-
|
|
606
|
-
// 如果是因为超时而离开,保留 current 信息以便重新激活时使用
|
|
730
|
+
}));
|
|
607
731
|
if (isTimeout) {
|
|
608
732
|
this.isTimedOut = true;
|
|
609
|
-
console.log('[Tracker SDK] Module info preserved for re-activation');
|
|
610
733
|
} else {
|
|
611
|
-
// 正常离开,清除 current
|
|
612
734
|
this.current = null;
|
|
613
735
|
this.isTimedOut = false;
|
|
614
736
|
}
|
|
615
737
|
}
|
|
616
|
-
|
|
617
|
-
/**
|
|
618
|
-
* 上报自定义事件
|
|
619
|
-
* @param {string} eventName
|
|
620
|
-
* @param {Object} params - 扩展参数,可包含 system, module, sub_module
|
|
621
|
-
*/
|
|
622
738
|
}, {
|
|
623
739
|
key: "track",
|
|
624
740
|
value: function track(eventName) {
|
|
625
741
|
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
626
|
-
// 从 params 中提取模块信息(如果存在)
|
|
627
742
|
var _params$system = params.system,
|
|
628
|
-
system = _params$system === void 0 ?
|
|
743
|
+
system = _params$system === void 0 ? "" : _params$system,
|
|
629
744
|
_params$module = params.module,
|
|
630
|
-
module = _params$module === void 0 ?
|
|
745
|
+
module = _params$module === void 0 ? "" : _params$module,
|
|
631
746
|
_params$sub_module = params.sub_module,
|
|
632
|
-
sub_module = _params$sub_module === void 0 ?
|
|
747
|
+
sub_module = _params$sub_module === void 0 ? "" : _params$sub_module,
|
|
748
|
+
_params$duration = params.duration,
|
|
749
|
+
duration = _params$duration === void 0 ? 0 : _params$duration,
|
|
750
|
+
event_id = params.event_id,
|
|
751
|
+
schema_version = params.schema_version,
|
|
752
|
+
occurred_at = params.occurred_at,
|
|
633
753
|
restParams = _objectWithoutProperties(params, _excluded);
|
|
634
|
-
|
|
635
|
-
// 构建 context 对象
|
|
636
|
-
var context = {
|
|
637
|
-
device_id: this.deviceId,
|
|
638
|
-
session_id: this.sessionId,
|
|
639
|
-
user_id: this.userId
|
|
640
|
-
};
|
|
641
|
-
|
|
642
|
-
// 构建 ext 对象(合并全局扩展参数和剩余的事件参数)
|
|
643
|
-
var extData = _objectSpread2(_objectSpread2({}, this.globalExt), restParams);
|
|
644
|
-
this.queue.push({
|
|
754
|
+
this._enqueue(this._buildEvent(eventName, {
|
|
645
755
|
system: system,
|
|
646
756
|
module: module,
|
|
647
757
|
sub_module: sub_module,
|
|
648
|
-
duration:
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
ext:
|
|
653
|
-
});
|
|
758
|
+
duration: duration,
|
|
759
|
+
event_id: event_id,
|
|
760
|
+
schema_version: schema_version,
|
|
761
|
+
occurred_at: occurred_at,
|
|
762
|
+
ext: restParams
|
|
763
|
+
}));
|
|
654
764
|
}
|
|
655
765
|
|
|
656
766
|
/***********活跃检测**********/
|
|
@@ -660,107 +770,68 @@ var Tracker = /*#__PURE__*/function () {
|
|
|
660
770
|
var _this2 = this;
|
|
661
771
|
var update = function update() {
|
|
662
772
|
var wasInactive = _this2._checkInactive();
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
if (wasInactive && !_this2.isTimedOut && _this2.current) {
|
|
667
|
-
console.log('[Tracker SDK] Activity detected after long inactivity, forcing timeout leave');
|
|
668
|
-
_this2.leave(false, true, 'timeout');
|
|
669
|
-
_this2.sessionId = resetSession();
|
|
773
|
+
if (_this2.options.enableActivityTimeout && wasInactive && !_this2.isTimedOut && _this2.current) {
|
|
774
|
+
_this2.leave(false, true, "timeout");
|
|
775
|
+
_this2.sessionId = resetSession(_this2.options.sessionTimeout);
|
|
670
776
|
}
|
|
671
777
|
_this2.lastActiveTime = now();
|
|
672
|
-
refreshSession();
|
|
673
|
-
|
|
674
|
-
// 如果之前因为超时而离开了,现在重新激活,需要重新 enter
|
|
675
|
-
if (wasInactive && _this2.isTimedOut && _this2.current) {
|
|
676
|
-
console.log('[Tracker SDK] User became active again after timeout');
|
|
677
|
-
|
|
678
|
-
// 重置超时标记
|
|
778
|
+
refreshSession(_this2.options.sessionTimeout);
|
|
779
|
+
if (_this2.options.enableActivityTimeout && wasInactive && _this2.isTimedOut && _this2.current) {
|
|
679
780
|
_this2.isTimedOut = false;
|
|
680
|
-
|
|
681
|
-
// 重新记录进入时间
|
|
682
781
|
_this2.current.enterTime = now();
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
session_id: _this2.sessionId,
|
|
688
|
-
user_id: _this2.userId
|
|
689
|
-
};
|
|
690
|
-
|
|
691
|
-
// 构建 ext 对象
|
|
692
|
-
var extData = _objectSpread2(_objectSpread2({}, _this2.globalExt), _this2.current.ext);
|
|
693
|
-
|
|
694
|
-
// 上报 module_enter 事件
|
|
695
|
-
var event = {
|
|
696
|
-
system: _this2.current.system || '',
|
|
697
|
-
module: _this2.current.module || '',
|
|
698
|
-
sub_module: _this2.current.sub_module || '',
|
|
782
|
+
_this2._enqueue(_this2._buildEvent("module_enter", {
|
|
783
|
+
system: _this2.current.system || "",
|
|
784
|
+
module: _this2.current.module || "",
|
|
785
|
+
sub_module: _this2.current.sub_module || "",
|
|
699
786
|
duration: 0,
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
ext: extData
|
|
704
|
-
};
|
|
705
|
-
_this2.queue.push(event);
|
|
706
|
-
console.log('[Tracker SDK] Re-entered module after inactivity:', _this2.current.module);
|
|
787
|
+
ext: _objectSpread2({}, _this2.current.ext)
|
|
788
|
+
}));
|
|
789
|
+
_this2.log.log("Re-entered module after inactivity:", _this2.current.module);
|
|
707
790
|
}
|
|
708
791
|
};
|
|
709
|
-
var events = [
|
|
792
|
+
var events = ["click", "keydown", "touchstart"];
|
|
710
793
|
events.forEach(function (event) {
|
|
711
|
-
|
|
794
|
+
var handler = update;
|
|
795
|
+
document.addEventListener(event, handler, {
|
|
712
796
|
passive: true
|
|
713
797
|
});
|
|
798
|
+
_this2._cleanupFns.push(function () {
|
|
799
|
+
return document.removeEventListener(event, handler);
|
|
800
|
+
});
|
|
714
801
|
});
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
document.addEventListener(
|
|
802
|
+
var moveHandler = throttle(update, 5000);
|
|
803
|
+
var scrollHandler = throttle(update, 500);
|
|
804
|
+
document.addEventListener("mousemove", moveHandler, {
|
|
718
805
|
passive: true
|
|
719
806
|
});
|
|
720
|
-
document.addEventListener(
|
|
807
|
+
document.addEventListener("scroll", scrollHandler, {
|
|
721
808
|
passive: true
|
|
722
809
|
});
|
|
810
|
+
this._cleanupFns.push(function () {
|
|
811
|
+
document.removeEventListener("mousemove", moveHandler);
|
|
812
|
+
document.removeEventListener("scroll", scrollHandler);
|
|
813
|
+
});
|
|
723
814
|
}
|
|
724
|
-
|
|
725
|
-
/**
|
|
726
|
-
* 检查用户是否处于非活跃状态(超过超时时间)
|
|
727
|
-
* @returns {boolean} 是否是非活跃状态
|
|
728
|
-
*/
|
|
729
815
|
}, {
|
|
730
816
|
key: "_checkInactive",
|
|
731
817
|
value: function _checkInactive() {
|
|
732
|
-
|
|
733
|
-
return
|
|
818
|
+
if (!this.options.enableActivityTimeout) return false;
|
|
819
|
+
return now() - this.lastActiveTime >= this.options.sessionTimeout;
|
|
734
820
|
}
|
|
735
|
-
|
|
736
|
-
/**
|
|
737
|
-
* 启动超时检测定时器
|
|
738
|
-
*/
|
|
739
821
|
}, {
|
|
740
822
|
key: "_startTimeoutCheck",
|
|
741
823
|
value: function _startTimeoutCheck() {
|
|
742
824
|
var _this3 = this;
|
|
743
|
-
this._stopTimeoutCheck();
|
|
744
|
-
|
|
745
|
-
// 动态计算检测间隔:超时时间的 1/6,但不超过 30 秒,不少于 5 秒
|
|
825
|
+
this._stopTimeoutCheck();
|
|
826
|
+
if (!this.options.enableActivityTimeout) return;
|
|
746
827
|
var checkInterval = Math.min(Math.max(this.options.sessionTimeout / 6, 5 * 1000), 30 * 1000);
|
|
747
|
-
console.log('[Tracker SDK] Timeout check interval:', (checkInterval / 1000).toFixed(1), 's');
|
|
748
828
|
this.timeoutTimer = setInterval(function () {
|
|
749
|
-
// 只要有 current 且未处于超时状态,就检测是否超时
|
|
750
829
|
if (_this3.current && !_this3.isTimedOut && _this3._checkInactive()) {
|
|
751
|
-
|
|
752
|
-
_this3.
|
|
753
|
-
|
|
754
|
-
// 重置 Session,认为会话结束
|
|
755
|
-
_this3.sessionId = resetSession();
|
|
756
|
-
console.log('[Tracker SDK] Session reset due to inactivity, new sessionId:', _this3.sessionId);
|
|
830
|
+
_this3.leave(false, true, "timeout");
|
|
831
|
+
_this3.sessionId = resetSession(_this3.options.sessionTimeout);
|
|
757
832
|
}
|
|
758
833
|
}, checkInterval);
|
|
759
834
|
}
|
|
760
|
-
|
|
761
|
-
/**
|
|
762
|
-
* 停止超时检测
|
|
763
|
-
*/
|
|
764
835
|
}, {
|
|
765
836
|
key: "_stopTimeoutCheck",
|
|
766
837
|
value: function _stopTimeoutCheck() {
|
|
@@ -775,59 +846,80 @@ var Tracker = /*#__PURE__*/function () {
|
|
|
775
846
|
key: "_bindLifecycle",
|
|
776
847
|
value: function _bindLifecycle() {
|
|
777
848
|
var _this4 = this;
|
|
778
|
-
// 用于保存页面隐藏前的模块信息
|
|
779
849
|
var hiddenModule = null;
|
|
780
|
-
|
|
781
|
-
// 页面卸载或隐藏时,上报当前模块的停留时间并强制刷新队列
|
|
782
850
|
var flushData = function flushData() {
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
console.log('[Tracker SDK] Queue length:', _this4.queue.list.length);
|
|
786
|
-
|
|
787
|
-
// 停止超时检测
|
|
851
|
+
if (_this4._isFlushing) return;
|
|
852
|
+
_this4._isFlushing = true;
|
|
788
853
|
_this4._stopTimeoutCheck();
|
|
789
|
-
|
|
790
|
-
// 保存当前模块信息,以便页面恢复时重新 enter
|
|
791
854
|
if (_this4.current) {
|
|
792
855
|
hiddenModule = _objectSpread2({}, _this4.current);
|
|
793
|
-
console.log('[Tracker SDK] Saved module info for restoration:', hiddenModule.module);
|
|
794
856
|
}
|
|
795
|
-
_this4.leave(true, false,
|
|
796
|
-
_this4.queue.flush(true);
|
|
797
|
-
|
|
798
|
-
console.log('[Tracker SDK] Data flushed successfully');
|
|
857
|
+
_this4.leave(true, false, "visibility");
|
|
858
|
+
_this4.queue.flush(true);
|
|
799
859
|
};
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
860
|
+
var onPageHide = function onPageHide() {
|
|
861
|
+
return flushData();
|
|
862
|
+
};
|
|
863
|
+
var onBeforeUnload = function onBeforeUnload() {
|
|
864
|
+
return flushData();
|
|
865
|
+
};
|
|
866
|
+
var onVisibilityChange = function onVisibilityChange() {
|
|
867
|
+
if (_this4.options.visibilityBehavior === "ignore") return;
|
|
868
|
+
if (document.visibilityState === "hidden") {
|
|
805
869
|
flushData();
|
|
806
|
-
|
|
807
|
-
console.log('[Tracker SDK] Page is now visible');
|
|
808
|
-
|
|
809
|
-
// 重新启动超时检测
|
|
810
|
-
_this4._startTimeoutCheck();
|
|
811
|
-
|
|
812
|
-
// 如果之前有保存的模块信息,重新 enter
|
|
813
|
-
if (hiddenModule) {
|
|
814
|
-
console.log('[Tracker SDK] Restoring module:', hiddenModule.module);
|
|
815
|
-
|
|
816
|
-
// 清除 enterTime,使用当前时间作为新的进入时间
|
|
817
|
-
var _hiddenModule = hiddenModule;
|
|
818
|
-
_hiddenModule.enterTime;
|
|
819
|
-
var moduleInfo = _objectWithoutProperties(_hiddenModule, _excluded2);
|
|
820
|
-
_this4.enter(moduleInfo);
|
|
821
|
-
|
|
822
|
-
// 重置 hiddenModule
|
|
823
|
-
hiddenModule = null;
|
|
824
|
-
console.log('[Tracker SDK] Module restored successfully');
|
|
825
|
-
} else {
|
|
826
|
-
console.log('[Tracker SDK] No module to restore');
|
|
827
|
-
}
|
|
870
|
+
return;
|
|
828
871
|
}
|
|
872
|
+
if (document.visibilityState !== "visible") return;
|
|
873
|
+
_this4._isFlushing = false;
|
|
874
|
+
_this4._startTimeoutCheck();
|
|
875
|
+
if (!hiddenModule) return;
|
|
876
|
+
var _hiddenModule = hiddenModule;
|
|
877
|
+
_hiddenModule.enterTime;
|
|
878
|
+
var moduleInfo = _objectWithoutProperties(_hiddenModule, _excluded2);
|
|
879
|
+
hiddenModule = null;
|
|
880
|
+
if (_this4.options.visibilityBehavior === "emit") {
|
|
881
|
+
_this4.enter(moduleInfo);
|
|
882
|
+
} else if (_this4.options.visibilityBehavior === "silent") {
|
|
883
|
+
// 恢复当前模块,但不再上报一次 module_enter,避免切 tab 造成页面曝光重复计数。
|
|
884
|
+
_this4.current = _objectSpread2(_objectSpread2({}, moduleInfo), {}, {
|
|
885
|
+
enterTime: now()
|
|
886
|
+
});
|
|
887
|
+
_this4.isTimedOut = false;
|
|
888
|
+
_this4.lastActiveTime = now();
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
window.addEventListener("pagehide", onPageHide);
|
|
892
|
+
window.addEventListener("beforeunload", onBeforeUnload);
|
|
893
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
894
|
+
this._cleanupFns.push(function () {
|
|
895
|
+
window.removeEventListener("pagehide", onPageHide);
|
|
896
|
+
window.removeEventListener("beforeunload", onBeforeUnload);
|
|
897
|
+
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
829
898
|
});
|
|
830
899
|
}
|
|
900
|
+
|
|
901
|
+
/***********公开方法**********/
|
|
902
|
+
}, {
|
|
903
|
+
key: "flush",
|
|
904
|
+
value: function flush() {
|
|
905
|
+
this.queue.flush(false);
|
|
906
|
+
}
|
|
907
|
+
}, {
|
|
908
|
+
key: "destroy",
|
|
909
|
+
value: function destroy() {
|
|
910
|
+
var _this5 = this;
|
|
911
|
+
this._stopTimeoutCheck();
|
|
912
|
+
this._cleanupFns.forEach(function (fn) {
|
|
913
|
+
try {
|
|
914
|
+
fn();
|
|
915
|
+
} catch (error) {
|
|
916
|
+
_this5.log.warn("Cleanup failed:", error);
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
this._cleanupFns = [];
|
|
920
|
+
this.flush();
|
|
921
|
+
this.current = null;
|
|
922
|
+
}
|
|
831
923
|
}]);
|
|
832
924
|
}();
|
|
833
925
|
|
|
@@ -1146,31 +1238,97 @@ function autoTrackPlugin(tracker) {
|
|
|
1146
1238
|
}, true); // 使用捕获模式,确保能更早捕获事件
|
|
1147
1239
|
}
|
|
1148
1240
|
|
|
1241
|
+
/**
|
|
1242
|
+
* 脱敏错误上报插件。
|
|
1243
|
+
*
|
|
1244
|
+
* 与旧 errorPlugin 的区别:
|
|
1245
|
+
* - 不上报 pageUrl(可能带 token 等查询参数)
|
|
1246
|
+
* - 不上报 stack
|
|
1247
|
+
* - 默认不上报原始 message,只上报错误类型 + 哈希
|
|
1248
|
+
*/
|
|
1249
|
+
|
|
1250
|
+
function hash(input) {
|
|
1251
|
+
var value = 0x811c9dc5;
|
|
1252
|
+
var text = String(input || "");
|
|
1253
|
+
for (var i = 0; i < text.length; i += 1) {
|
|
1254
|
+
value ^= text.charCodeAt(i);
|
|
1255
|
+
value = Math.imul(value, 0x01000193);
|
|
1256
|
+
}
|
|
1257
|
+
return (value >>> 0).toString(16);
|
|
1258
|
+
}
|
|
1259
|
+
function safeErrorPlugin(tracker) {
|
|
1260
|
+
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1261
|
+
var _options$captureMessa = options.captureMessage,
|
|
1262
|
+
captureMessage = _options$captureMessa === void 0 ? false : _options$captureMessa,
|
|
1263
|
+
_options$maxMessageLe = options.maxMessageLength,
|
|
1264
|
+
maxMessageLength = _options$maxMessageLe === void 0 ? 200 : _options$maxMessageLe;
|
|
1265
|
+
var report = function report(payload) {
|
|
1266
|
+
try {
|
|
1267
|
+
tracker.track("client.error", _objectSpread2({
|
|
1268
|
+
result: "fail"
|
|
1269
|
+
}, payload));
|
|
1270
|
+
} catch (e) {
|
|
1271
|
+
// 埋点失败不影响业务
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
window.addEventListener("error", function (event) {
|
|
1275
|
+
var target = event.target;
|
|
1276
|
+
if (target && (target.src || target.href)) {
|
|
1277
|
+
report({
|
|
1278
|
+
error_type: "resource_error",
|
|
1279
|
+
error_name: target.tagName,
|
|
1280
|
+
error_hash: hash(target.src || target.href)
|
|
1281
|
+
});
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
var message = event.message || "";
|
|
1285
|
+
var payload = {
|
|
1286
|
+
error_type: "uncaught_exception",
|
|
1287
|
+
error_name: event.error && event.error.name ? event.error.name : "Error",
|
|
1288
|
+
error_hash: hash("".concat(message, "|").concat(event.filename || "", "|").concat(event.lineno || 0, "|").concat(event.colno || 0))
|
|
1289
|
+
};
|
|
1290
|
+
if (captureMessage && message) {
|
|
1291
|
+
payload.error_message = message.slice(0, maxMessageLength);
|
|
1292
|
+
}
|
|
1293
|
+
report(payload);
|
|
1294
|
+
}, true);
|
|
1295
|
+
window.addEventListener("unhandledrejection", function (event) {
|
|
1296
|
+
var reason = event.reason || {};
|
|
1297
|
+
var message = reason.message || String(reason);
|
|
1298
|
+
var payload = {
|
|
1299
|
+
error_type: "unhandled_rejection",
|
|
1300
|
+
error_name: reason.name || "Error",
|
|
1301
|
+
error_hash: hash(message)
|
|
1302
|
+
};
|
|
1303
|
+
if (captureMessage && message) {
|
|
1304
|
+
payload.error_message = message.slice(0, maxMessageLength);
|
|
1305
|
+
}
|
|
1306
|
+
report(payload);
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
var TRACKER_VERSION = "1.0.12";
|
|
1149
1311
|
var instance = null;
|
|
1150
1312
|
|
|
1151
1313
|
/**
|
|
1152
1314
|
* 初始化 Tracker SDK。
|
|
1153
|
-
* 如果 SDK 已经被初始化,将抛出错误。
|
|
1154
1315
|
* @param {Object} options - 初始化选项
|
|
1155
1316
|
* @returns {Tracker} Tracker 实例
|
|
1156
|
-
* @throws {Error} 如果 SDK 已经被初始化
|
|
1157
1317
|
*/
|
|
1158
|
-
function initTracker(
|
|
1159
|
-
|
|
1318
|
+
function initTracker() {
|
|
1319
|
+
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1320
|
+
var log = createLogger(options.debug);
|
|
1160
1321
|
if (instance) {
|
|
1161
|
-
|
|
1322
|
+
log.warn("Tracker already initialized, returning existing instance.");
|
|
1162
1323
|
return instance;
|
|
1163
1324
|
}
|
|
1164
1325
|
instance = new Tracker(options);
|
|
1165
|
-
console.log('[Tracker SDK] Initialized successfully, instance:', instance);
|
|
1166
1326
|
return instance;
|
|
1167
1327
|
}
|
|
1168
1328
|
|
|
1169
1329
|
/**
|
|
1170
1330
|
* 获取 Tracker SDK 实例。
|
|
1171
|
-
* 如果 SDK 尚未初始化,将抛出错误。
|
|
1172
1331
|
* @returns {Tracker} Tracker 实例
|
|
1173
|
-
* @throws {Error} 如果 SDK 尚未初始化
|
|
1174
1332
|
*/
|
|
1175
1333
|
function getTracker() {
|
|
1176
1334
|
if (!instance) {
|
|
@@ -1179,4 +1337,17 @@ function getTracker() {
|
|
|
1179
1337
|
return instance;
|
|
1180
1338
|
}
|
|
1181
1339
|
|
|
1182
|
-
|
|
1340
|
+
/** 立即发送当前队列。 */
|
|
1341
|
+
function flushTracker() {
|
|
1342
|
+
if (instance) instance.flush();
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/** 清理监听与定时器,并发送剩余队列。 */
|
|
1346
|
+
function destroyTracker() {
|
|
1347
|
+
if (instance) {
|
|
1348
|
+
instance.destroy();
|
|
1349
|
+
instance = null;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
export { TRACKER_VERSION, autoTrackPlugin as autoTracker, destroyTracker, errorPlugin, flushTracker, getTracker, initTracker, performancePlugin, routerPlugin, safeErrorPlugin };
|