@be-link/cls-logger 1.0.1-beta.2 → 1.0.1-beta.20
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/README.md +144 -32
- package/dist/ClsLogger.d.ts +15 -96
- package/dist/ClsLogger.d.ts.map +1 -1
- package/dist/ClsLoggerCore.d.ts +177 -0
- package/dist/ClsLoggerCore.d.ts.map +1 -0
- package/dist/behaviorMonitor.d.ts.map +1 -1
- package/dist/clsSdkTypes.d.ts +18 -0
- package/dist/clsSdkTypes.d.ts.map +1 -0
- package/dist/deviceInfo.d.ts.map +1 -1
- package/dist/errorMonitor.d.ts.map +1 -1
- package/dist/index.esm.js +2148 -1275
- package/dist/index.js +2148 -1275
- package/dist/index.umd.js +2153 -1278
- package/dist/mini/ClsLogger.d.ts +14 -0
- package/dist/mini/ClsLogger.d.ts.map +1 -0
- package/dist/mini/behaviorMonitor.d.ts +5 -0
- package/dist/mini/behaviorMonitor.d.ts.map +1 -0
- package/dist/mini/deviceInfo.d.ts +3 -0
- package/dist/mini/deviceInfo.d.ts.map +1 -0
- package/dist/mini/errorMonitor.d.ts +5 -0
- package/dist/mini/errorMonitor.d.ts.map +1 -0
- package/dist/mini/performanceMonitor.d.ts +5 -0
- package/dist/mini/performanceMonitor.d.ts.map +1 -0
- package/dist/mini/requestMonitor.d.ts +9 -0
- package/dist/mini/requestMonitor.d.ts.map +1 -0
- package/dist/mini.d.ts +6 -0
- package/dist/mini.d.ts.map +1 -0
- package/dist/mini.esm.js +1946 -0
- package/dist/mini.js +1971 -0
- package/dist/performanceMonitor.d.ts.map +1 -1
- package/dist/requestMonitor.d.ts +1 -5
- package/dist/requestMonitor.d.ts.map +1 -1
- package/dist/sdkUtils.d.ts +3 -0
- package/dist/sdkUtils.d.ts.map +1 -0
- package/dist/types.d.ts +90 -11
- package/dist/types.d.ts.map +1 -1
- package/dist/web/ClsLogger.d.ts +14 -0
- package/dist/web/ClsLogger.d.ts.map +1 -0
- package/dist/web/behaviorMonitor.d.ts +5 -0
- package/dist/web/behaviorMonitor.d.ts.map +1 -0
- package/dist/web/deviceInfo.d.ts +3 -0
- package/dist/web/deviceInfo.d.ts.map +1 -0
- package/dist/web/errorMonitor.d.ts +5 -0
- package/dist/web/errorMonitor.d.ts.map +1 -0
- package/dist/web/performanceMonitor.d.ts +5 -0
- package/dist/web/performanceMonitor.d.ts.map +1 -0
- package/dist/web/requestMonitor.d.ts +5 -0
- package/dist/web/requestMonitor.d.ts.map +1 -0
- package/dist/web.d.ts +6 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/web.esm.js +2117 -0
- package/dist/web.js +2142 -0
- package/package.json +35 -2
package/dist/index.umd.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
(function (global, factory) {
|
|
2
|
-
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports
|
|
3
|
-
typeof define === 'function' && define.amd ? define(['exports'
|
|
4
|
-
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BeLinkClsLogger = {}
|
|
5
|
-
})(this, (function (exports
|
|
2
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
3
|
+
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
|
4
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BeLinkClsLogger = {}));
|
|
5
|
+
})(this, (function (exports) { 'use strict';
|
|
6
6
|
|
|
7
7
|
function isPlainObject(value) {
|
|
8
8
|
return Object.prototype.toString.call(value) === '[object Object]';
|
|
@@ -137,163 +137,979 @@
|
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
-
|
|
141
|
-
function isClsSendingNow() {
|
|
140
|
+
function enterClsSendingGuard() {
|
|
142
141
|
const g = globalThis;
|
|
143
|
-
|
|
142
|
+
const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
|
|
143
|
+
g.__beLinkClsLoggerSendingCount__ = next;
|
|
144
|
+
return () => {
|
|
145
|
+
const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
|
|
146
|
+
g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
|
|
147
|
+
};
|
|
144
148
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
/**
|
|
150
|
+
* CLS Logger 核心基类
|
|
151
|
+
* - 负责所有上报、队列、监控逻辑
|
|
152
|
+
* - 不包含具体的 SDK 加载实现(由子类负责)
|
|
153
|
+
* - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
|
|
154
|
+
*/
|
|
155
|
+
class ClsLoggerCore {
|
|
156
|
+
constructor() {
|
|
157
|
+
this.sdk = null;
|
|
158
|
+
this.sdkPromise = null;
|
|
159
|
+
this.sdkOverride = null;
|
|
160
|
+
this.sdkLoaderOverride = null;
|
|
161
|
+
this.client = null;
|
|
162
|
+
this.clientPromise = null;
|
|
163
|
+
this.topicId = '17475bcd-6315-4b20-859c-e7b087fb3683';
|
|
164
|
+
this.endpoint = 'https://ap-shanghai.cls.tencentcs.com';
|
|
165
|
+
this.retryTimes = 3;
|
|
166
|
+
this.source = '127.0.0.1';
|
|
167
|
+
this.enabled = true;
|
|
168
|
+
this.projectId = '';
|
|
169
|
+
this.projectName = '';
|
|
170
|
+
this.appId = '';
|
|
171
|
+
this.appVersion = '';
|
|
172
|
+
this.envType = 'browser';
|
|
173
|
+
this.userGenerateBaseFields = null;
|
|
174
|
+
this.autoGenerateBaseFields = null;
|
|
175
|
+
this.storageKey = 'beLink_logs';
|
|
176
|
+
this.batchSize = 15;
|
|
177
|
+
// 参考文档:内存队列批量发送(500ms 或 20 条触发)
|
|
178
|
+
this.memoryQueue = [];
|
|
179
|
+
this.batchMaxSize = 20;
|
|
180
|
+
this.batchIntervalMs = 500;
|
|
181
|
+
this.batchTimer = null;
|
|
182
|
+
this.batchTimerDueAt = null;
|
|
183
|
+
this.initTs = 0;
|
|
184
|
+
this.startupDelayMs = 0;
|
|
185
|
+
this.useIdleCallback = false;
|
|
186
|
+
this.idleTimeout = 3000;
|
|
187
|
+
this.visibilityCleanup = null;
|
|
188
|
+
// 参考文档:失败缓存 + 重试
|
|
189
|
+
this.failedCacheKey = 'cls_failed_logs';
|
|
190
|
+
this.failedCacheMax = 200;
|
|
191
|
+
this.requestMonitorStarted = false;
|
|
192
|
+
this.errorMonitorStarted = false;
|
|
193
|
+
this.performanceMonitorStarted = false;
|
|
194
|
+
this.behaviorMonitorStarted = false;
|
|
195
|
+
this.behaviorMonitorCleanup = null;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* 子类可按需重写(默认检测 wx)
|
|
199
|
+
*/
|
|
200
|
+
detectEnvType() {
|
|
201
|
+
const g = globalThis;
|
|
202
|
+
// 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
|
|
203
|
+
if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
|
|
204
|
+
(g.my && typeof g.my.getSystemInfoSync === 'function') ||
|
|
205
|
+
(g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
|
|
206
|
+
(g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
|
|
207
|
+
return 'miniprogram';
|
|
208
|
+
}
|
|
209
|
+
return 'browser';
|
|
210
|
+
}
|
|
211
|
+
init(options) {
|
|
212
|
+
this.initTs = Date.now();
|
|
213
|
+
const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId;
|
|
214
|
+
const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
|
|
215
|
+
const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
|
|
216
|
+
const source = options?.source ?? this.source;
|
|
217
|
+
if (!topicId) {
|
|
218
|
+
// eslint-disable-next-line no-console
|
|
219
|
+
console.warn('ClsLogger.init 没有传 topicID/topic_id');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const nextEnvType = options.envType ?? this.detectEnvType();
|
|
223
|
+
// envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
|
|
224
|
+
const envChanged = nextEnvType !== this.envType;
|
|
225
|
+
const endpointChanged = endpoint !== this.endpoint;
|
|
226
|
+
const retryChanged = retryTimes !== this.retryTimes;
|
|
227
|
+
if (envChanged || endpointChanged || retryChanged) {
|
|
228
|
+
this.client = null;
|
|
229
|
+
this.clientPromise = null;
|
|
151
230
|
}
|
|
231
|
+
if (envChanged) {
|
|
232
|
+
this.sdk = null;
|
|
233
|
+
this.sdkPromise = null;
|
|
234
|
+
}
|
|
235
|
+
this.topicId = topicId;
|
|
236
|
+
this.endpoint = endpoint;
|
|
237
|
+
this.retryTimes = retryTimes;
|
|
238
|
+
this.source = source;
|
|
239
|
+
this.userId = options.userId ?? this.userId;
|
|
240
|
+
this.userName = options.userName ?? this.userName;
|
|
241
|
+
this.projectId = options.projectId ?? this.projectId;
|
|
242
|
+
this.projectName = options.projectName ?? this.projectName;
|
|
243
|
+
this.appId = options.appId ?? this.appId;
|
|
244
|
+
this.appVersion = options.appVersion ?? this.appVersion;
|
|
245
|
+
this.envType = nextEnvType;
|
|
246
|
+
this.enabled = options.enabled ?? true;
|
|
247
|
+
// 可选:外部注入 SDK(优先级:sdkLoader > sdk)
|
|
248
|
+
this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
|
|
249
|
+
this.sdkOverride = options.sdk ?? this.sdkOverride;
|
|
250
|
+
this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
|
|
251
|
+
this.autoGenerateBaseFields = this.createDeviceInfoBaseFields(options.deviceInfo);
|
|
252
|
+
this.storageKey = options.storageKey ?? this.storageKey;
|
|
253
|
+
this.batchSize = options.batchSize ?? this.batchSize;
|
|
254
|
+
this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
|
|
255
|
+
this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
|
|
256
|
+
this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
|
|
257
|
+
this.useIdleCallback = options.batch?.useIdleCallback ?? this.useIdleCallback;
|
|
258
|
+
this.idleTimeout = options.batch?.idleTimeout ?? this.idleTimeout;
|
|
259
|
+
this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
|
|
260
|
+
this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
|
|
261
|
+
// 预热(避免首条日志触发 import/初始化开销)
|
|
262
|
+
void this.getInstance().catch(() => {
|
|
263
|
+
// ignore
|
|
264
|
+
});
|
|
265
|
+
if (this.enabled) {
|
|
266
|
+
// 启动时尝试发送失败缓存
|
|
267
|
+
this.flushFailed();
|
|
268
|
+
// 添加页面可见性监听(确保页面关闭时数据不丢失)
|
|
269
|
+
this.setupVisibilityListener();
|
|
270
|
+
// 初始化后立即启动请求监听
|
|
271
|
+
this.startRequestMonitor(options.requestMonitor);
|
|
272
|
+
// 初始化后立即启动错误监控/性能监控
|
|
273
|
+
this.startErrorMonitor(options.errorMonitor);
|
|
274
|
+
this.startPerformanceMonitor(options.performanceMonitor);
|
|
275
|
+
// 初始化后立即启动行为埋点(PV/UV/点击)
|
|
276
|
+
this.startBehaviorMonitor(options.behaviorMonitor);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
getBaseFields() {
|
|
280
|
+
let auto = undefined;
|
|
281
|
+
let user = undefined;
|
|
152
282
|
try {
|
|
153
|
-
|
|
154
|
-
|
|
283
|
+
const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
|
|
284
|
+
if (autoRaw && isPlainObject(autoRaw))
|
|
285
|
+
auto = normalizeFlatFields(autoRaw, 'deviceInfo');
|
|
155
286
|
}
|
|
156
287
|
catch {
|
|
157
|
-
|
|
288
|
+
auto = undefined;
|
|
158
289
|
}
|
|
159
|
-
}
|
|
160
|
-
return false;
|
|
161
|
-
}
|
|
162
|
-
function sampleHit$2(sampleRate) {
|
|
163
|
-
if (sampleRate >= 1)
|
|
164
|
-
return true;
|
|
165
|
-
if (sampleRate <= 0)
|
|
166
|
-
return false;
|
|
167
|
-
return Math.random() < sampleRate;
|
|
168
|
-
}
|
|
169
|
-
function truncate$3(s, maxLen) {
|
|
170
|
-
if (!s)
|
|
171
|
-
return s;
|
|
172
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
173
|
-
}
|
|
174
|
-
function buildPayload(params) {
|
|
175
|
-
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
176
|
-
if (!url)
|
|
177
|
-
return null;
|
|
178
|
-
if (shouldIgnoreUrl$1(url, options.ignoreUrls))
|
|
179
|
-
return null;
|
|
180
|
-
if (!sampleHit$2(options.sampleRate))
|
|
181
|
-
return null;
|
|
182
|
-
const payload = { url };
|
|
183
|
-
if (options.includeMethod && method)
|
|
184
|
-
payload.method = method;
|
|
185
|
-
if (options.includeQuery && query !== undefined)
|
|
186
|
-
payload.query = truncate$3(String(query), options.maxParamLength);
|
|
187
|
-
if (options.includeBody && body !== undefined)
|
|
188
|
-
payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
|
|
189
|
-
if (typeof startTime === 'number')
|
|
190
|
-
payload.startTime = startTime;
|
|
191
|
-
if (typeof duration === 'number')
|
|
192
|
-
payload.duration = duration;
|
|
193
|
-
if (typeof status === 'number')
|
|
194
|
-
payload.status = status;
|
|
195
|
-
if (typeof success === 'boolean')
|
|
196
|
-
payload.success = success ? 1 : 0;
|
|
197
|
-
if (error !== undefined)
|
|
198
|
-
payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
|
|
199
|
-
return payload;
|
|
200
|
-
}
|
|
201
|
-
function getAbsoluteUrlMaybe(url) {
|
|
202
|
-
try {
|
|
203
|
-
if (typeof window === 'undefined')
|
|
204
|
-
return url;
|
|
205
|
-
return new URL(url, window.location?.href).toString();
|
|
206
|
-
}
|
|
207
|
-
catch {
|
|
208
|
-
return url;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
function installBrowserFetch(report, options) {
|
|
212
|
-
if (typeof window === 'undefined')
|
|
213
|
-
return;
|
|
214
|
-
const w = window;
|
|
215
|
-
if (w.__beLinkClsLoggerFetchInstalled__)
|
|
216
|
-
return;
|
|
217
|
-
if (typeof w.fetch !== 'function')
|
|
218
|
-
return;
|
|
219
|
-
w.__beLinkClsLoggerFetchInstalled__ = true;
|
|
220
|
-
w.__beLinkClsLoggerRawFetch__ = w.fetch;
|
|
221
|
-
w.fetch = async (input, init) => {
|
|
222
|
-
// 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
|
|
223
|
-
if (isClsSendingNow())
|
|
224
|
-
return w.__beLinkClsLoggerRawFetch__(input, init);
|
|
225
|
-
let url = '';
|
|
226
|
-
let method = '';
|
|
227
|
-
let body = undefined;
|
|
228
|
-
const startTs = Date.now();
|
|
229
290
|
try {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
url = input.toString();
|
|
234
|
-
else
|
|
235
|
-
url = input.url ?? '';
|
|
236
|
-
method = (init?.method ?? input?.method ?? 'GET');
|
|
237
|
-
body = init?.body;
|
|
291
|
+
const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
|
|
292
|
+
if (userRaw && isPlainObject(userRaw))
|
|
293
|
+
user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
|
|
238
294
|
}
|
|
239
295
|
catch {
|
|
240
|
-
|
|
296
|
+
user = undefined;
|
|
241
297
|
}
|
|
242
|
-
|
|
243
|
-
|
|
298
|
+
if (auto && user)
|
|
299
|
+
return mergeFields(user, auto);
|
|
300
|
+
if (user)
|
|
301
|
+
return user;
|
|
302
|
+
if (auto)
|
|
303
|
+
return auto;
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* 设置页面可见性监听
|
|
308
|
+
* - visibilitychange: 页面隐藏时使用 sendBeacon 发送队列
|
|
309
|
+
* - pagehide: 作为移动端 fallback
|
|
310
|
+
*/
|
|
311
|
+
setupVisibilityListener() {
|
|
312
|
+
if (typeof document === 'undefined' || typeof window === 'undefined')
|
|
313
|
+
return;
|
|
314
|
+
// 避免重复监听
|
|
315
|
+
if (this.visibilityCleanup)
|
|
316
|
+
return;
|
|
317
|
+
const handleVisibilityChange = () => {
|
|
318
|
+
if (document.visibilityState === 'hidden') {
|
|
319
|
+
this.flushBatchSync();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
const handlePageHide = () => {
|
|
323
|
+
this.flushBatchSync();
|
|
324
|
+
};
|
|
325
|
+
document.addEventListener('visibilitychange', handleVisibilityChange);
|
|
326
|
+
window.addEventListener('pagehide', handlePageHide);
|
|
327
|
+
this.visibilityCleanup = () => {
|
|
328
|
+
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
|
329
|
+
window.removeEventListener('pagehide', handlePageHide);
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* 同步发送内存队列(使用 sendBeacon)
|
|
334
|
+
* - 用于页面关闭时确保数据发送
|
|
335
|
+
* - sendBeacon 不可用时降级为缓存到 localStorage
|
|
336
|
+
*/
|
|
337
|
+
flushBatchSync() {
|
|
338
|
+
if (this.memoryQueue.length === 0)
|
|
339
|
+
return;
|
|
340
|
+
// 清除定时器
|
|
341
|
+
if (this.batchTimer) {
|
|
244
342
|
try {
|
|
245
|
-
|
|
246
|
-
|
|
343
|
+
if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
|
|
344
|
+
cancelIdleCallback(this.batchTimer);
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
clearTimeout(this.batchTimer);
|
|
348
|
+
}
|
|
247
349
|
}
|
|
248
350
|
catch {
|
|
249
|
-
|
|
351
|
+
// ignore
|
|
250
352
|
}
|
|
251
|
-
|
|
252
|
-
try {
|
|
253
|
-
const res = await w.__beLinkClsLoggerRawFetch__(input, init);
|
|
254
|
-
const duration = Date.now() - startTs;
|
|
255
|
-
const status = typeof res?.status === 'number' ? res.status : undefined;
|
|
256
|
-
const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
|
|
257
|
-
const payload = buildPayload({
|
|
258
|
-
url: absUrl,
|
|
259
|
-
method,
|
|
260
|
-
query,
|
|
261
|
-
body,
|
|
262
|
-
startTime: startTs,
|
|
263
|
-
duration,
|
|
264
|
-
status,
|
|
265
|
-
success: ok,
|
|
266
|
-
options,
|
|
267
|
-
});
|
|
268
|
-
if (payload)
|
|
269
|
-
report(options.reportType, payload);
|
|
270
|
-
return res;
|
|
353
|
+
this.batchTimer = null;
|
|
271
354
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
success
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
355
|
+
this.batchTimerDueAt = null;
|
|
356
|
+
const logs = [...this.memoryQueue];
|
|
357
|
+
this.memoryQueue = [];
|
|
358
|
+
// 优先使用 sendBeacon(页面关闭时可靠发送)
|
|
359
|
+
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
360
|
+
try {
|
|
361
|
+
const payload = this.buildSendBeaconPayload(logs);
|
|
362
|
+
const blob = new Blob([payload], { type: 'application/json' });
|
|
363
|
+
const url = `${this.endpoint}/structuredlog?topic_id=${this.topicId}`;
|
|
364
|
+
const success = navigator.sendBeacon(url, blob);
|
|
365
|
+
if (!success) {
|
|
366
|
+
// sendBeacon 返回 false 时,降级缓存
|
|
367
|
+
this.cacheFailedReportLogs(logs);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
this.cacheFailedReportLogs(logs);
|
|
372
|
+
}
|
|
288
373
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
374
|
+
else {
|
|
375
|
+
// 不支持 sendBeacon,降级缓存到 localStorage
|
|
376
|
+
this.cacheFailedReportLogs(logs);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* 构建 sendBeacon 的 payload
|
|
381
|
+
*/
|
|
382
|
+
buildSendBeaconPayload(logs) {
|
|
383
|
+
const logList = logs.map((log) => this.buildReportFields(log));
|
|
384
|
+
return JSON.stringify({
|
|
385
|
+
source: this.source,
|
|
386
|
+
logs: logList,
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
startRequestMonitor(requestMonitor) {
|
|
390
|
+
if (this.requestMonitorStarted)
|
|
391
|
+
return;
|
|
392
|
+
// 默认开启;传 false 则关闭
|
|
393
|
+
const enabled = requestMonitor === undefined ? true : !!requestMonitor;
|
|
394
|
+
if (!enabled)
|
|
395
|
+
return;
|
|
396
|
+
const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
|
|
397
|
+
this.requestMonitorStarted = true;
|
|
398
|
+
this.installRequestMonitor((type, data) => {
|
|
399
|
+
this.track(type, data);
|
|
400
|
+
}, {
|
|
401
|
+
...opts,
|
|
402
|
+
enabled: opts.enabled ?? true,
|
|
403
|
+
clsEndpoint: this.endpoint,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
startErrorMonitor(errorMonitor) {
|
|
407
|
+
if (this.errorMonitorStarted)
|
|
408
|
+
return;
|
|
409
|
+
const enabled = errorMonitor === undefined ? true : !!errorMonitor;
|
|
410
|
+
if (!enabled)
|
|
411
|
+
return;
|
|
412
|
+
this.errorMonitorStarted = true;
|
|
413
|
+
this.installErrorMonitor((type, data) => this.track(type, data), errorMonitor ?? true);
|
|
414
|
+
}
|
|
415
|
+
startPerformanceMonitor(performanceMonitor) {
|
|
416
|
+
if (this.performanceMonitorStarted)
|
|
417
|
+
return;
|
|
418
|
+
const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
|
|
419
|
+
if (!enabled)
|
|
420
|
+
return;
|
|
421
|
+
this.performanceMonitorStarted = true;
|
|
422
|
+
this.installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor ?? true);
|
|
423
|
+
}
|
|
424
|
+
startBehaviorMonitor(behaviorMonitor) {
|
|
425
|
+
if (this.behaviorMonitorStarted)
|
|
426
|
+
return;
|
|
427
|
+
const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
|
|
428
|
+
if (!enabled)
|
|
429
|
+
return;
|
|
430
|
+
this.behaviorMonitorStarted = true;
|
|
431
|
+
this.behaviorMonitorCleanup = this.installBehaviorMonitor((type, data) => {
|
|
432
|
+
this.track(type, data);
|
|
433
|
+
}, behaviorMonitor ?? true);
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* 停止行为埋点监听(PV/UV/点击)
|
|
437
|
+
* - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
|
|
438
|
+
*/
|
|
439
|
+
stopBehaviorMonitor() {
|
|
440
|
+
try {
|
|
441
|
+
this.behaviorMonitorCleanup?.();
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
// ignore
|
|
445
|
+
}
|
|
446
|
+
this.behaviorMonitorCleanup = null;
|
|
447
|
+
this.behaviorMonitorStarted = false;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* 获取 CLS client(按环境懒加载 SDK)
|
|
451
|
+
*/
|
|
452
|
+
async getInstance() {
|
|
453
|
+
if (this.client)
|
|
454
|
+
return this.client;
|
|
455
|
+
if (this.clientPromise)
|
|
456
|
+
return this.clientPromise;
|
|
457
|
+
this.clientPromise = this.loadSdk()
|
|
458
|
+
.then(({ AsyncClient }) => {
|
|
459
|
+
const client = new AsyncClient({
|
|
460
|
+
endpoint: this.endpoint,
|
|
461
|
+
retry_times: this.retryTimes,
|
|
462
|
+
});
|
|
463
|
+
this.client = client;
|
|
464
|
+
return client;
|
|
465
|
+
})
|
|
466
|
+
.catch((err) => {
|
|
467
|
+
// 失败后允许下次重试
|
|
468
|
+
this.clientPromise = null;
|
|
469
|
+
throw err;
|
|
470
|
+
});
|
|
471
|
+
return this.clientPromise;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* 直接上报:埋点入参必须是一维(扁平)Object
|
|
475
|
+
* - 非原始值(对象/数组等)会被自动 stringify 成 string
|
|
476
|
+
* - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
|
|
477
|
+
*/
|
|
478
|
+
put(fields, options = {}) {
|
|
479
|
+
if (!this.enabled)
|
|
480
|
+
return;
|
|
481
|
+
if (!fields)
|
|
482
|
+
return;
|
|
483
|
+
if (!this.topicId) {
|
|
484
|
+
// eslint-disable-next-line no-console
|
|
485
|
+
console.warn('ClsLogger.put:未初始化 topic_id');
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
489
|
+
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
490
|
+
const normalizedFields = normalizeFlatFields(fields, 'put');
|
|
491
|
+
const finalFields = mergeFields(base, {
|
|
492
|
+
projectId: this.projectId || undefined,
|
|
493
|
+
projectName: this.projectName || undefined,
|
|
494
|
+
envType: this.envType,
|
|
495
|
+
appId: this.appId || undefined,
|
|
496
|
+
appVersion: this.appVersion || undefined,
|
|
497
|
+
...normalizedFields,
|
|
498
|
+
});
|
|
499
|
+
// 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
|
|
500
|
+
void this.putAsync(finalFields).catch(() => {
|
|
501
|
+
// ignore
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
async putAsync(finalFields) {
|
|
505
|
+
if (!this.topicId)
|
|
506
|
+
return;
|
|
507
|
+
const sdk = await this.loadSdk();
|
|
508
|
+
const client = await this.getInstance();
|
|
509
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
510
|
+
logGroup.setSource(this.source);
|
|
511
|
+
const log = new sdk.Log(Date.now());
|
|
512
|
+
for (const key of Object.keys(finalFields)) {
|
|
513
|
+
log.addContent(key, stringifyLogValue(finalFields[key]));
|
|
514
|
+
}
|
|
515
|
+
logGroup.addLog(log);
|
|
516
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
517
|
+
const exit = enterClsSendingGuard();
|
|
518
|
+
let p;
|
|
519
|
+
try {
|
|
520
|
+
p = client.PutLogs(request);
|
|
521
|
+
}
|
|
522
|
+
finally {
|
|
523
|
+
exit();
|
|
524
|
+
}
|
|
525
|
+
await p;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
|
|
529
|
+
*/
|
|
530
|
+
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
531
|
+
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
532
|
+
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* 入队:写入 localStorage 队列;达到 batchSize 自动 flush
|
|
536
|
+
* - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
|
|
537
|
+
*/
|
|
538
|
+
enqueue(fields, options = {}) {
|
|
539
|
+
if (!this.enabled)
|
|
540
|
+
return;
|
|
541
|
+
if (!fields)
|
|
542
|
+
return;
|
|
543
|
+
const time = Date.now();
|
|
544
|
+
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
545
|
+
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
546
|
+
const normalizedFields = normalizeFlatFields(fields, 'enqueue');
|
|
547
|
+
const finalFields = mergeFields(base, {
|
|
548
|
+
projectId: this.projectId || undefined,
|
|
549
|
+
projectName: this.projectName || undefined,
|
|
550
|
+
envType: this.envType,
|
|
551
|
+
appId: this.appId || undefined,
|
|
552
|
+
appVersion: this.appVersion || undefined,
|
|
553
|
+
...normalizedFields,
|
|
554
|
+
});
|
|
555
|
+
const queue = readQueue(this.storageKey);
|
|
556
|
+
const next = [...queue, { time, data: finalFields }];
|
|
557
|
+
if (next.length < this.batchSize) {
|
|
558
|
+
writeQueue(this.storageKey, next);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
// 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
|
|
562
|
+
this.putBatch(queue);
|
|
563
|
+
writeQueue(this.storageKey, [{ time, data: finalFields }]);
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* 从 localStorage 读取队列并批量上报
|
|
567
|
+
*/
|
|
568
|
+
flush() {
|
|
569
|
+
const queue = readQueue(this.storageKey);
|
|
570
|
+
if (queue.length === 0)
|
|
571
|
+
return;
|
|
572
|
+
this.putBatch(queue);
|
|
573
|
+
writeQueue(this.storageKey, []);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* 批量上报(每条 item.data 展开为 log content)
|
|
577
|
+
*/
|
|
578
|
+
putBatch(queue) {
|
|
579
|
+
if (!this.enabled)
|
|
580
|
+
return;
|
|
581
|
+
if (!queue || queue.length === 0)
|
|
582
|
+
return;
|
|
583
|
+
if (!this.topicId) {
|
|
584
|
+
// eslint-disable-next-line no-console
|
|
585
|
+
console.warn('ClsLogger.putBatch:未初始化 topic_id');
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
void this.putBatchAsync(queue).catch(() => {
|
|
589
|
+
// ignore
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
async putBatchAsync(queue) {
|
|
593
|
+
if (!this.topicId)
|
|
594
|
+
return;
|
|
595
|
+
const sdk = await this.loadSdk();
|
|
596
|
+
const client = await this.getInstance();
|
|
597
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
598
|
+
logGroup.setSource(this.source);
|
|
599
|
+
for (const item of queue) {
|
|
600
|
+
const log = new sdk.Log(item.time);
|
|
601
|
+
const data = item.data ?? {};
|
|
602
|
+
for (const key of Object.keys(data)) {
|
|
603
|
+
log.addContent(key, stringifyLogValue(data[key]));
|
|
604
|
+
}
|
|
605
|
+
logGroup.addLog(log);
|
|
606
|
+
}
|
|
607
|
+
if (logGroup.getLogs().length === 0)
|
|
608
|
+
return;
|
|
609
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
610
|
+
const exit = enterClsSendingGuard();
|
|
611
|
+
let p;
|
|
612
|
+
try {
|
|
613
|
+
p = client.PutLogs(request);
|
|
614
|
+
}
|
|
615
|
+
finally {
|
|
616
|
+
exit();
|
|
617
|
+
}
|
|
618
|
+
await p;
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
|
|
622
|
+
*/
|
|
623
|
+
report(log) {
|
|
624
|
+
if (!this.enabled)
|
|
625
|
+
return;
|
|
626
|
+
if (!log?.type)
|
|
627
|
+
return;
|
|
628
|
+
if (!this.topicId) {
|
|
629
|
+
// eslint-disable-next-line no-console
|
|
630
|
+
console.warn('ClsLogger.report:未初始化 topicID/topic_id');
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
this.memoryQueue.push(log);
|
|
634
|
+
if (this.memoryQueue.length >= this.batchMaxSize) {
|
|
635
|
+
void this.flushBatch();
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const now = Date.now();
|
|
639
|
+
const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
|
|
640
|
+
const desiredDelay = Math.max(0, desiredDueAt - now);
|
|
641
|
+
if (!this.batchTimer) {
|
|
642
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
643
|
+
this.scheduleFlush(desiredDelay);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
// 启动合并窗口内:如果当前 timer 会"更早"触发,则延后到窗口结束,尽量减少多次发送
|
|
647
|
+
if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
|
|
648
|
+
this.cancelScheduledFlush();
|
|
649
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
650
|
+
this.scheduleFlush(desiredDelay);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* 调度批量发送
|
|
655
|
+
* - 支持 requestIdleCallback(浏览器空闲时执行)
|
|
656
|
+
* - 降级为 setTimeout
|
|
657
|
+
*/
|
|
658
|
+
scheduleFlush(desiredDelay) {
|
|
659
|
+
if (this.useIdleCallback && typeof requestIdleCallback !== 'undefined') {
|
|
660
|
+
// 使用 requestIdleCallback,设置 timeout 保证最终执行
|
|
661
|
+
const idleId = requestIdleCallback(() => {
|
|
662
|
+
void this.flushBatch();
|
|
663
|
+
}, { timeout: Math.max(desiredDelay, this.idleTimeout) });
|
|
664
|
+
// 存储 idleId 以便清理(类型兼容处理)
|
|
665
|
+
this.batchTimer = idleId;
|
|
666
|
+
}
|
|
667
|
+
else {
|
|
668
|
+
this.batchTimer = setTimeout(() => {
|
|
669
|
+
void this.flushBatch();
|
|
670
|
+
}, desiredDelay);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* 取消已调度的批量发送
|
|
675
|
+
*/
|
|
676
|
+
cancelScheduledFlush() {
|
|
677
|
+
if (!this.batchTimer)
|
|
678
|
+
return;
|
|
679
|
+
try {
|
|
680
|
+
if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
|
|
681
|
+
cancelIdleCallback(this.batchTimer);
|
|
682
|
+
}
|
|
683
|
+
else {
|
|
684
|
+
clearTimeout(this.batchTimer);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
// ignore
|
|
689
|
+
}
|
|
690
|
+
this.batchTimer = null;
|
|
691
|
+
}
|
|
692
|
+
getDesiredBatchFlushDueAt(nowTs) {
|
|
693
|
+
const start = this.initTs || nowTs;
|
|
694
|
+
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
695
|
+
if (startupDelay > 0) {
|
|
696
|
+
const end = start + startupDelay;
|
|
697
|
+
if (nowTs < end)
|
|
698
|
+
return end;
|
|
699
|
+
}
|
|
700
|
+
return nowTs + this.batchIntervalMs;
|
|
701
|
+
}
|
|
702
|
+
info(message, data = {}, options) {
|
|
703
|
+
let msg = '';
|
|
704
|
+
let extra = {};
|
|
705
|
+
if (message instanceof Error) {
|
|
706
|
+
msg = message.message;
|
|
707
|
+
extra = {
|
|
708
|
+
stack: message.stack,
|
|
709
|
+
name: message.name,
|
|
710
|
+
...data,
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
msg = String(message);
|
|
715
|
+
extra = data;
|
|
716
|
+
}
|
|
717
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
|
|
718
|
+
const log = { type: 'info', data: payload, timestamp: Date.now() };
|
|
719
|
+
// info 默认走批量队列,支持 immediate 选项立即发送
|
|
720
|
+
if (options?.immediate) {
|
|
721
|
+
void this.sendReportLogs([log]).catch(() => {
|
|
722
|
+
this.cacheFailedReportLogs([log]);
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
else {
|
|
726
|
+
this.report(log);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
warn(message, data = {}, options) {
|
|
730
|
+
let msg = '';
|
|
731
|
+
let extra = {};
|
|
732
|
+
if (message instanceof Error) {
|
|
733
|
+
msg = message.message;
|
|
734
|
+
extra = {
|
|
735
|
+
stack: message.stack,
|
|
736
|
+
name: message.name,
|
|
737
|
+
...data,
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
else {
|
|
741
|
+
msg = String(message);
|
|
742
|
+
extra = data;
|
|
743
|
+
}
|
|
744
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
|
|
745
|
+
const log = { type: 'warn', data: payload, timestamp: Date.now() };
|
|
746
|
+
// warn 默认走批量队列,支持 immediate 选项立即发送
|
|
747
|
+
if (options?.immediate) {
|
|
748
|
+
void this.sendReportLogs([log]).catch(() => {
|
|
749
|
+
this.cacheFailedReportLogs([log]);
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
this.report(log);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
error(message, data = {}, options) {
|
|
757
|
+
let msg = '';
|
|
758
|
+
let extra = {};
|
|
759
|
+
if (message instanceof Error) {
|
|
760
|
+
msg = message.message;
|
|
761
|
+
extra = {
|
|
762
|
+
stack: message.stack,
|
|
763
|
+
name: message.name,
|
|
764
|
+
...data,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
else {
|
|
768
|
+
msg = String(message);
|
|
769
|
+
extra = data;
|
|
770
|
+
}
|
|
771
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
|
|
772
|
+
const log = { type: 'error', data: payload, timestamp: Date.now() };
|
|
773
|
+
// error 默认即时上报,除非显式指定 immediate: false
|
|
774
|
+
const immediate = options?.immediate ?? true;
|
|
775
|
+
if (immediate) {
|
|
776
|
+
void this.sendReportLogs([log]).catch(() => {
|
|
777
|
+
this.cacheFailedReportLogs([log]);
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
this.report(log);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
track(trackType, data = {}) {
|
|
785
|
+
if (!trackType)
|
|
786
|
+
return;
|
|
787
|
+
this.report({
|
|
788
|
+
type: trackType,
|
|
789
|
+
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
790
|
+
timestamp: Date.now(),
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* 立即发送内存队列
|
|
795
|
+
*/
|
|
796
|
+
async flushBatch() {
|
|
797
|
+
this.cancelScheduledFlush();
|
|
798
|
+
this.batchTimerDueAt = null;
|
|
799
|
+
if (this.memoryQueue.length === 0)
|
|
800
|
+
return;
|
|
801
|
+
const logs = [...this.memoryQueue];
|
|
802
|
+
this.memoryQueue = [];
|
|
803
|
+
try {
|
|
804
|
+
await this.sendReportLogs(logs);
|
|
805
|
+
}
|
|
806
|
+
catch {
|
|
807
|
+
this.retrySendReportLogs(logs, 1);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
buildReportFields(log) {
|
|
811
|
+
const ts = log.timestamp ?? Date.now();
|
|
812
|
+
const base = this.getBaseFields();
|
|
813
|
+
const data = normalizeFlatFields(log.data ?? {}, 'report:data');
|
|
814
|
+
const mergedData = mergeFields(base, data);
|
|
815
|
+
return {
|
|
816
|
+
timestamp: ts,
|
|
817
|
+
type: log.type,
|
|
818
|
+
envType: this.envType,
|
|
819
|
+
projectId: this.projectId || undefined,
|
|
820
|
+
projectName: this.projectName || undefined,
|
|
821
|
+
appId: this.appId || undefined,
|
|
822
|
+
appVersion: this.appVersion || undefined,
|
|
823
|
+
// 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
|
|
824
|
+
...mergedData,
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
async sendReportLogs(logs) {
|
|
828
|
+
if (!this.topicId)
|
|
829
|
+
return;
|
|
830
|
+
const sdk = await this.loadSdk();
|
|
831
|
+
const client = await this.getInstance();
|
|
832
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
833
|
+
logGroup.setSource(this.source);
|
|
834
|
+
for (const item of logs) {
|
|
835
|
+
const fields = this.buildReportFields(item);
|
|
836
|
+
const log = new sdk.Log(fields.timestamp);
|
|
837
|
+
for (const key of Object.keys(fields)) {
|
|
838
|
+
if (key === 'timestamp')
|
|
839
|
+
continue;
|
|
840
|
+
log.addContent(key, stringifyLogValue(fields[key]));
|
|
841
|
+
}
|
|
842
|
+
logGroup.addLog(log);
|
|
843
|
+
}
|
|
844
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
845
|
+
// 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
|
|
846
|
+
const exit = enterClsSendingGuard();
|
|
847
|
+
let p;
|
|
848
|
+
try {
|
|
849
|
+
p = client.PutLogs(request);
|
|
850
|
+
}
|
|
851
|
+
finally {
|
|
852
|
+
exit();
|
|
853
|
+
}
|
|
854
|
+
await p;
|
|
855
|
+
}
|
|
856
|
+
retrySendReportLogs(logs, retryCount) {
|
|
857
|
+
if (retryCount > this.retryTimes) {
|
|
858
|
+
this.cacheFailedReportLogs(logs);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const delayMs = Math.pow(2, retryCount) * 1000;
|
|
862
|
+
setTimeout(async () => {
|
|
863
|
+
try {
|
|
864
|
+
await this.sendReportLogs(logs);
|
|
865
|
+
}
|
|
866
|
+
catch {
|
|
867
|
+
this.retrySendReportLogs(logs, retryCount + 1);
|
|
868
|
+
}
|
|
869
|
+
}, delayMs);
|
|
870
|
+
}
|
|
871
|
+
cacheFailedReportLogs(logs) {
|
|
872
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
873
|
+
let current = [];
|
|
874
|
+
try {
|
|
875
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
876
|
+
current = Array.isArray(parsed) ? parsed : [];
|
|
877
|
+
}
|
|
878
|
+
catch {
|
|
879
|
+
current = [];
|
|
880
|
+
}
|
|
881
|
+
const next = [...current, ...logs].slice(-this.failedCacheMax);
|
|
882
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify(next));
|
|
883
|
+
}
|
|
884
|
+
flushFailed() {
|
|
885
|
+
if (!this.enabled)
|
|
886
|
+
return;
|
|
887
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
888
|
+
if (!raw)
|
|
889
|
+
return;
|
|
890
|
+
let logs = [];
|
|
891
|
+
try {
|
|
892
|
+
const parsed = JSON.parse(raw);
|
|
893
|
+
logs = Array.isArray(parsed) ? parsed : [];
|
|
894
|
+
}
|
|
895
|
+
catch {
|
|
896
|
+
logs = [];
|
|
897
|
+
}
|
|
898
|
+
if (logs.length === 0)
|
|
899
|
+
return;
|
|
900
|
+
// 先清空,再尝试发送
|
|
901
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify([]));
|
|
902
|
+
this.memoryQueue.unshift(...logs);
|
|
903
|
+
void this.flushBatch();
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
|
|
907
|
+
*/
|
|
908
|
+
stat(param) {
|
|
909
|
+
if (!param)
|
|
910
|
+
return;
|
|
911
|
+
const payload = normalizeFlatFields({
|
|
912
|
+
pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
|
|
913
|
+
projectId: this.projectId,
|
|
914
|
+
projectName: this.projectName,
|
|
915
|
+
...param,
|
|
916
|
+
data: param.data ?? 1,
|
|
917
|
+
}, 'stat');
|
|
918
|
+
this.report({ type: 'stat', data: payload, timestamp: Date.now() });
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function readGlobal(key) {
|
|
923
|
+
try {
|
|
924
|
+
const g = globalThis;
|
|
925
|
+
return g[key] ?? null;
|
|
926
|
+
}
|
|
927
|
+
catch {
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
function tryRequire(moduleName) {
|
|
932
|
+
try {
|
|
933
|
+
// 说明:
|
|
934
|
+
// - ESM 构建(exports.import/module)里通常不存在模块作用域的 require
|
|
935
|
+
// - 一些小程序运行时/构建链路会把 require 挂到 globalThis 上
|
|
936
|
+
// 因此这里同时探测“模块作用域 require”与 “globalThis.require”
|
|
937
|
+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
938
|
+
const localReq = (typeof require === 'function' ? require : null);
|
|
939
|
+
const globalReq = readGlobal('require');
|
|
940
|
+
const candidates = [localReq, globalReq].filter((fn) => typeof fn === 'function');
|
|
941
|
+
for (const fn of candidates) {
|
|
942
|
+
try {
|
|
943
|
+
return fn(moduleName);
|
|
944
|
+
}
|
|
945
|
+
catch {
|
|
946
|
+
// continue
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
return null;
|
|
950
|
+
}
|
|
951
|
+
catch {
|
|
952
|
+
return null;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
const DEFAULT_IGNORE$2 = ['cls.tencentcs.com', /\/cls\//i];
|
|
957
|
+
function isClsSendingNow() {
|
|
958
|
+
const g = globalThis;
|
|
959
|
+
return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
|
|
960
|
+
}
|
|
961
|
+
function shouldIgnoreUrl$2(url, ignoreUrls) {
|
|
962
|
+
for (const rule of ignoreUrls) {
|
|
963
|
+
if (typeof rule === 'string') {
|
|
964
|
+
if (url.includes(rule))
|
|
965
|
+
return true;
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
try {
|
|
969
|
+
if (rule.test(url))
|
|
970
|
+
return true;
|
|
971
|
+
}
|
|
972
|
+
catch {
|
|
973
|
+
// ignore invalid regex
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
function sampleHit$5(sampleRate) {
|
|
979
|
+
if (sampleRate >= 1)
|
|
980
|
+
return true;
|
|
981
|
+
if (sampleRate <= 0)
|
|
982
|
+
return false;
|
|
983
|
+
return Math.random() < sampleRate;
|
|
984
|
+
}
|
|
985
|
+
function truncate$5(s, maxLen) {
|
|
986
|
+
if (!s)
|
|
987
|
+
return s;
|
|
988
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
989
|
+
}
|
|
990
|
+
function buildPayload$1(params) {
|
|
991
|
+
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
992
|
+
if (!url)
|
|
993
|
+
return null;
|
|
994
|
+
if (shouldIgnoreUrl$2(url, options.ignoreUrls))
|
|
995
|
+
return null;
|
|
996
|
+
if (!sampleHit$5(options.sampleRate))
|
|
997
|
+
return null;
|
|
998
|
+
const payload = { url };
|
|
999
|
+
if (options.includeMethod && method)
|
|
1000
|
+
payload.method = method;
|
|
1001
|
+
if (options.includeQuery && query !== undefined)
|
|
1002
|
+
payload.query = truncate$5(String(query), options.maxParamLength);
|
|
1003
|
+
if (options.includeBody && body !== undefined)
|
|
1004
|
+
payload.params = truncate$5(stringifyLogValue(body), options.maxParamLength);
|
|
1005
|
+
if (typeof startTime === 'number')
|
|
1006
|
+
payload.startTime = startTime;
|
|
1007
|
+
if (typeof duration === 'number')
|
|
1008
|
+
payload.duration = duration;
|
|
1009
|
+
if (typeof status === 'number')
|
|
1010
|
+
payload.status = status;
|
|
1011
|
+
if (typeof success === 'boolean')
|
|
1012
|
+
payload.success = success ? 1 : 0;
|
|
1013
|
+
if (error !== undefined)
|
|
1014
|
+
payload.error = truncate$5(stringifyLogValue(error), options.maxParamLength);
|
|
1015
|
+
return payload;
|
|
1016
|
+
}
|
|
1017
|
+
function getAbsoluteUrlMaybe(url) {
|
|
1018
|
+
try {
|
|
1019
|
+
if (typeof window === 'undefined')
|
|
1020
|
+
return url;
|
|
1021
|
+
return new URL(url, window.location?.href).toString();
|
|
1022
|
+
}
|
|
1023
|
+
catch {
|
|
1024
|
+
return url;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
function installBrowserFetch(report, options) {
|
|
1028
|
+
if (typeof window === 'undefined')
|
|
1029
|
+
return;
|
|
1030
|
+
const w = window;
|
|
1031
|
+
if (w.__beLinkClsLoggerFetchInstalled__)
|
|
1032
|
+
return;
|
|
1033
|
+
if (typeof w.fetch !== 'function')
|
|
1034
|
+
return;
|
|
1035
|
+
w.__beLinkClsLoggerFetchInstalled__ = true;
|
|
1036
|
+
w.__beLinkClsLoggerRawFetch__ = w.fetch;
|
|
1037
|
+
w.fetch = async (input, init) => {
|
|
1038
|
+
// 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
|
|
1039
|
+
if (isClsSendingNow())
|
|
1040
|
+
return w.__beLinkClsLoggerRawFetch__(input, init);
|
|
1041
|
+
let url = '';
|
|
1042
|
+
let method = '';
|
|
1043
|
+
let body = undefined;
|
|
1044
|
+
const startTs = Date.now();
|
|
1045
|
+
try {
|
|
1046
|
+
if (typeof input === 'string')
|
|
1047
|
+
url = input;
|
|
1048
|
+
else if (input instanceof URL)
|
|
1049
|
+
url = input.toString();
|
|
1050
|
+
else
|
|
1051
|
+
url = input.url ?? '';
|
|
1052
|
+
method = (init?.method ?? input?.method ?? 'GET');
|
|
1053
|
+
body = init?.body;
|
|
1054
|
+
}
|
|
1055
|
+
catch {
|
|
1056
|
+
// ignore
|
|
1057
|
+
}
|
|
1058
|
+
const absUrl = getAbsoluteUrlMaybe(url);
|
|
1059
|
+
const query = (() => {
|
|
1060
|
+
try {
|
|
1061
|
+
const u = new URL(absUrl);
|
|
1062
|
+
return u.search ? u.search.slice(1) : '';
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
return '';
|
|
1066
|
+
}
|
|
1067
|
+
})();
|
|
1068
|
+
try {
|
|
1069
|
+
const res = await w.__beLinkClsLoggerRawFetch__(input, init);
|
|
1070
|
+
const duration = Date.now() - startTs;
|
|
1071
|
+
const status = typeof res?.status === 'number' ? res.status : undefined;
|
|
1072
|
+
const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
|
|
1073
|
+
const payload = buildPayload$1({
|
|
1074
|
+
url: absUrl,
|
|
1075
|
+
method,
|
|
1076
|
+
query,
|
|
1077
|
+
body,
|
|
1078
|
+
startTime: startTs,
|
|
1079
|
+
duration,
|
|
1080
|
+
status,
|
|
1081
|
+
success: ok,
|
|
1082
|
+
options,
|
|
1083
|
+
});
|
|
1084
|
+
if (payload)
|
|
1085
|
+
report(options.reportType, payload);
|
|
1086
|
+
return res;
|
|
1087
|
+
}
|
|
1088
|
+
catch (err) {
|
|
1089
|
+
const duration = Date.now() - startTs;
|
|
1090
|
+
const payload = buildPayload$1({
|
|
1091
|
+
url: absUrl,
|
|
1092
|
+
method,
|
|
1093
|
+
query,
|
|
1094
|
+
body,
|
|
1095
|
+
startTime: startTs,
|
|
1096
|
+
duration,
|
|
1097
|
+
success: false,
|
|
1098
|
+
error: err,
|
|
1099
|
+
options,
|
|
1100
|
+
});
|
|
1101
|
+
if (payload)
|
|
1102
|
+
report(options.reportType, payload);
|
|
1103
|
+
throw err;
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
function installBrowserXhr(report, options) {
|
|
1108
|
+
if (typeof window === 'undefined')
|
|
1109
|
+
return;
|
|
1110
|
+
const w = window;
|
|
1111
|
+
if (w.__beLinkClsLoggerXhrInstalled__)
|
|
1112
|
+
return;
|
|
297
1113
|
if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
|
|
298
1114
|
return;
|
|
299
1115
|
w.__beLinkClsLoggerXhrInstalled__ = true;
|
|
@@ -335,7 +1151,7 @@
|
|
|
335
1151
|
const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
|
|
336
1152
|
const duration = Date.now() - st;
|
|
337
1153
|
const status = typeof this.status === 'number' ? this.status : undefined;
|
|
338
|
-
const payload = buildPayload({
|
|
1154
|
+
const payload = buildPayload$1({
|
|
339
1155
|
url,
|
|
340
1156
|
method,
|
|
341
1157
|
query,
|
|
@@ -377,6 +1193,85 @@
|
|
|
377
1193
|
return rawSend.apply(this, args);
|
|
378
1194
|
};
|
|
379
1195
|
}
|
|
1196
|
+
function installWebRequestMonitor(report, opts = {}) {
|
|
1197
|
+
const enabled = opts.enabled ?? true;
|
|
1198
|
+
if (!enabled)
|
|
1199
|
+
return;
|
|
1200
|
+
const ignoreUrls = [...DEFAULT_IGNORE$2, ...(opts.ignoreUrls ?? [])];
|
|
1201
|
+
if (opts.clsEndpoint)
|
|
1202
|
+
ignoreUrls.push(opts.clsEndpoint);
|
|
1203
|
+
const options = {
|
|
1204
|
+
enabled: true,
|
|
1205
|
+
reportType: opts.reportType ?? 'http',
|
|
1206
|
+
sampleRate: opts.sampleRate ?? 1,
|
|
1207
|
+
ignoreUrls,
|
|
1208
|
+
includeMethod: opts.includeMethod ?? true,
|
|
1209
|
+
includeQuery: opts.includeQuery ?? true,
|
|
1210
|
+
includeBody: opts.includeBody ?? true,
|
|
1211
|
+
maxParamLength: opts.maxParamLength ?? 2000,
|
|
1212
|
+
clsEndpoint: opts.clsEndpoint ?? '',
|
|
1213
|
+
};
|
|
1214
|
+
installBrowserFetch(report, options);
|
|
1215
|
+
installBrowserXhr(report, options);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
|
|
1219
|
+
function shouldIgnoreUrl$1(url, ignoreUrls) {
|
|
1220
|
+
for (const rule of ignoreUrls) {
|
|
1221
|
+
if (typeof rule === 'string') {
|
|
1222
|
+
if (url.includes(rule))
|
|
1223
|
+
return true;
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
try {
|
|
1227
|
+
if (rule.test(url))
|
|
1228
|
+
return true;
|
|
1229
|
+
}
|
|
1230
|
+
catch {
|
|
1231
|
+
// ignore invalid regex
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
function sampleHit$4(sampleRate) {
|
|
1237
|
+
if (sampleRate >= 1)
|
|
1238
|
+
return true;
|
|
1239
|
+
if (sampleRate <= 0)
|
|
1240
|
+
return false;
|
|
1241
|
+
return Math.random() < sampleRate;
|
|
1242
|
+
}
|
|
1243
|
+
function truncate$4(s, maxLen) {
|
|
1244
|
+
if (!s)
|
|
1245
|
+
return s;
|
|
1246
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1247
|
+
}
|
|
1248
|
+
function buildPayload(params) {
|
|
1249
|
+
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
1250
|
+
if (!url)
|
|
1251
|
+
return null;
|
|
1252
|
+
if (shouldIgnoreUrl$1(url, options.ignoreUrls))
|
|
1253
|
+
return null;
|
|
1254
|
+
if (!sampleHit$4(options.sampleRate))
|
|
1255
|
+
return null;
|
|
1256
|
+
const payload = { url };
|
|
1257
|
+
if (options.includeMethod && method)
|
|
1258
|
+
payload.method = method;
|
|
1259
|
+
if (options.includeQuery && query !== undefined)
|
|
1260
|
+
payload.query = truncate$4(String(query), options.maxParamLength);
|
|
1261
|
+
if (options.includeBody && body !== undefined)
|
|
1262
|
+
payload.params = truncate$4(stringifyLogValue(body), options.maxParamLength);
|
|
1263
|
+
if (typeof startTime === 'number')
|
|
1264
|
+
payload.startTime = startTime;
|
|
1265
|
+
if (typeof duration === 'number')
|
|
1266
|
+
payload.duration = duration;
|
|
1267
|
+
if (typeof status === 'number')
|
|
1268
|
+
payload.status = status;
|
|
1269
|
+
if (typeof success === 'boolean')
|
|
1270
|
+
payload.success = success ? 1 : 0;
|
|
1271
|
+
if (error !== undefined)
|
|
1272
|
+
payload.error = truncate$4(stringifyLogValue(error), options.maxParamLength);
|
|
1273
|
+
return payload;
|
|
1274
|
+
}
|
|
380
1275
|
function installMiniProgramWxRequest(report, options) {
|
|
381
1276
|
const wxAny = globalThis.wx;
|
|
382
1277
|
if (!wxAny || typeof wxAny.request !== 'function')
|
|
@@ -512,7 +1407,7 @@
|
|
|
512
1407
|
}
|
|
513
1408
|
};
|
|
514
1409
|
}
|
|
515
|
-
function
|
|
1410
|
+
function installMiniRequestMonitor(report, opts = {}) {
|
|
516
1411
|
const enabled = opts.enabled ?? true;
|
|
517
1412
|
if (!enabled)
|
|
518
1413
|
return;
|
|
@@ -530,49 +1425,127 @@
|
|
|
530
1425
|
maxParamLength: opts.maxParamLength ?? 2000,
|
|
531
1426
|
clsEndpoint: opts.clsEndpoint ?? '',
|
|
532
1427
|
};
|
|
1428
|
+
installMiniProgramWxRequest(report, options);
|
|
1429
|
+
installMiniProgramWxCloudCallFunction(report, options);
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
function installRequestMonitor(report, opts = {}) {
|
|
533
1433
|
if (isMiniProgramEnv()) {
|
|
534
|
-
|
|
535
|
-
installMiniProgramWxCloudCallFunction(report, options);
|
|
536
|
-
return;
|
|
1434
|
+
return installMiniRequestMonitor(report, opts);
|
|
537
1435
|
}
|
|
538
|
-
|
|
539
|
-
installBrowserXhr(report, options);
|
|
1436
|
+
return installWebRequestMonitor(report, opts);
|
|
540
1437
|
}
|
|
541
1438
|
|
|
542
|
-
const DEFAULT_MAX_TEXT = 4000;
|
|
543
|
-
|
|
1439
|
+
const DEFAULT_MAX_TEXT$1 = 4000;
|
|
1440
|
+
const DEFAULT_DEDUPE_WINDOW_MS$1 = 3000;
|
|
1441
|
+
const DEFAULT_DEDUPE_MAX_KEYS$1 = 200;
|
|
1442
|
+
/** 默认忽略的无意义错误信息 */
|
|
1443
|
+
const DEFAULT_IGNORE_MESSAGES$1 = [
|
|
1444
|
+
'Script error.',
|
|
1445
|
+
'Script error',
|
|
1446
|
+
/^ResizeObserver loop/,
|
|
1447
|
+
'Permission was denied',
|
|
1448
|
+
];
|
|
1449
|
+
function truncate$3(s, maxLen) {
|
|
544
1450
|
if (!s)
|
|
545
1451
|
return s;
|
|
546
1452
|
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
547
1453
|
}
|
|
548
|
-
function sampleHit$
|
|
1454
|
+
function sampleHit$3(sampleRate) {
|
|
549
1455
|
if (sampleRate >= 1)
|
|
550
1456
|
return true;
|
|
551
1457
|
if (sampleRate <= 0)
|
|
552
1458
|
return false;
|
|
553
1459
|
return Math.random() < sampleRate;
|
|
554
1460
|
}
|
|
1461
|
+
/** 检查消息是否应该被忽略 */
|
|
1462
|
+
function shouldIgnoreMessage$1(message, ignorePatterns) {
|
|
1463
|
+
if (!message || ignorePatterns.length === 0)
|
|
1464
|
+
return false;
|
|
1465
|
+
return ignorePatterns.some((pattern) => {
|
|
1466
|
+
if (typeof pattern === 'string') {
|
|
1467
|
+
return message === pattern || message.includes(pattern);
|
|
1468
|
+
}
|
|
1469
|
+
return pattern.test(message);
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
555
1472
|
function getPagePath$1() {
|
|
556
1473
|
try {
|
|
557
1474
|
if (typeof window === 'undefined')
|
|
558
1475
|
return '';
|
|
559
|
-
return window.location?.
|
|
1476
|
+
return window.location?.href ?? '';
|
|
560
1477
|
}
|
|
561
1478
|
catch {
|
|
562
1479
|
return '';
|
|
563
1480
|
}
|
|
564
1481
|
}
|
|
565
|
-
function normalizeErrorLike(err, maxTextLength) {
|
|
1482
|
+
function normalizeErrorLike$1(err, maxTextLength) {
|
|
566
1483
|
if (err && typeof err === 'object') {
|
|
567
1484
|
const anyErr = err;
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
1485
|
+
let rawMsg = anyErr.message;
|
|
1486
|
+
if (!rawMsg) {
|
|
1487
|
+
const str = anyErr.toString?.();
|
|
1488
|
+
if (!str || str === '[object Object]') {
|
|
1489
|
+
rawMsg = stringifyLogValue(anyErr);
|
|
1490
|
+
}
|
|
1491
|
+
else {
|
|
1492
|
+
rawMsg = str;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
const message = truncate$3(String(rawMsg ?? ''), maxTextLength);
|
|
1496
|
+
const name = truncate$3(String(anyErr.name ?? ''), 200);
|
|
1497
|
+
const stack = truncate$3(String(anyErr.stack ?? ''), maxTextLength);
|
|
571
1498
|
return { message, name, stack };
|
|
572
1499
|
}
|
|
573
|
-
const message = truncate$
|
|
1500
|
+
const message = truncate$3(stringifyLogValue(err), maxTextLength);
|
|
574
1501
|
return { message, name: '', stack: '' };
|
|
575
1502
|
}
|
|
1503
|
+
function createDedupeGuard$1(options) {
|
|
1504
|
+
const cache = new Map(); // key -> lastReportAt
|
|
1505
|
+
const maxKeys = Math.max(0, options.dedupeMaxKeys);
|
|
1506
|
+
const windowMs = Math.max(0, options.dedupeWindowMs);
|
|
1507
|
+
function touch(key, now) {
|
|
1508
|
+
if (cache.has(key))
|
|
1509
|
+
cache.delete(key);
|
|
1510
|
+
cache.set(key, now);
|
|
1511
|
+
if (maxKeys > 0) {
|
|
1512
|
+
while (cache.size > maxKeys) {
|
|
1513
|
+
const first = cache.keys().next().value;
|
|
1514
|
+
if (!first)
|
|
1515
|
+
break;
|
|
1516
|
+
cache.delete(first);
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
return (key) => {
|
|
1521
|
+
if (!key)
|
|
1522
|
+
return true;
|
|
1523
|
+
if (windowMs <= 0 || maxKeys === 0)
|
|
1524
|
+
return true;
|
|
1525
|
+
const now = Date.now();
|
|
1526
|
+
const last = cache.get(key);
|
|
1527
|
+
if (typeof last === 'number' && now - last < windowMs)
|
|
1528
|
+
return false;
|
|
1529
|
+
touch(key, now);
|
|
1530
|
+
return true;
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
function buildErrorKey$1(type, payload) {
|
|
1534
|
+
const parts = [
|
|
1535
|
+
type,
|
|
1536
|
+
String(payload.source ?? ''),
|
|
1537
|
+
String(payload.pagePath ?? ''),
|
|
1538
|
+
String(payload.message ?? ''),
|
|
1539
|
+
String(payload.errorName ?? ''),
|
|
1540
|
+
String(payload.stack ?? ''),
|
|
1541
|
+
String(payload.filename ?? ''),
|
|
1542
|
+
String(payload.lineno ?? ''),
|
|
1543
|
+
String(payload.colno ?? ''),
|
|
1544
|
+
String(payload.tagName ?? ''),
|
|
1545
|
+
String(payload.resourceUrl ?? ''),
|
|
1546
|
+
];
|
|
1547
|
+
return parts.join('|');
|
|
1548
|
+
}
|
|
576
1549
|
function installBrowserErrorMonitor(report, options) {
|
|
577
1550
|
if (typeof window === 'undefined')
|
|
578
1551
|
return;
|
|
@@ -580,39 +1553,45 @@
|
|
|
580
1553
|
if (w.__beLinkClsLoggerErrorInstalled__)
|
|
581
1554
|
return;
|
|
582
1555
|
w.__beLinkClsLoggerErrorInstalled__ = true;
|
|
1556
|
+
const shouldReport = createDedupeGuard$1(options);
|
|
583
1557
|
window.addEventListener('error', (event) => {
|
|
584
1558
|
try {
|
|
585
|
-
if (!sampleHit$
|
|
1559
|
+
if (!sampleHit$3(options.sampleRate))
|
|
586
1560
|
return;
|
|
587
1561
|
const payload = {
|
|
588
1562
|
pagePath: getPagePath$1(),
|
|
589
1563
|
source: 'window.error',
|
|
590
1564
|
};
|
|
591
|
-
// JS runtime error
|
|
592
1565
|
if (event && typeof event === 'object' && 'message' in event) {
|
|
593
|
-
payload.message = truncate$
|
|
594
|
-
|
|
1566
|
+
payload.message = truncate$3(String(event.message ?? ''), options.maxTextLength);
|
|
1567
|
+
// 检查是否应该忽略此错误
|
|
1568
|
+
if (shouldIgnoreMessage$1(String(event.message ?? ''), options.ignoreMessages))
|
|
1569
|
+
return;
|
|
1570
|
+
payload.filename = truncate$3(String(event.filename ?? ''), 500);
|
|
595
1571
|
payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
|
|
596
1572
|
payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
|
|
597
1573
|
const err = event.error;
|
|
598
1574
|
if (err) {
|
|
599
|
-
const e = normalizeErrorLike(err, options.maxTextLength);
|
|
1575
|
+
const e = normalizeErrorLike$1(err, options.maxTextLength);
|
|
600
1576
|
if (e.name)
|
|
601
1577
|
payload.errorName = e.name;
|
|
602
1578
|
if (e.stack)
|
|
603
1579
|
payload.stack = e.stack;
|
|
604
1580
|
}
|
|
1581
|
+
if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
|
|
1582
|
+
return;
|
|
605
1583
|
report(options.reportType, payload);
|
|
606
1584
|
return;
|
|
607
1585
|
}
|
|
608
|
-
// Resource error (img/script/link)
|
|
609
1586
|
if (options.captureResourceError) {
|
|
610
1587
|
const target = event?.target || event?.srcElement;
|
|
611
1588
|
const tagName = target?.tagName ? String(target.tagName) : '';
|
|
612
1589
|
const url = String(target?.src || target?.href || '');
|
|
613
1590
|
payload.source = 'resource.error';
|
|
614
1591
|
payload.tagName = tagName;
|
|
615
|
-
payload.resourceUrl = truncate$
|
|
1592
|
+
payload.resourceUrl = truncate$3(url, 2000);
|
|
1593
|
+
if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
|
|
1594
|
+
return;
|
|
616
1595
|
report(options.reportType, payload);
|
|
617
1596
|
}
|
|
618
1597
|
}
|
|
@@ -622,10 +1601,13 @@
|
|
|
622
1601
|
}, true);
|
|
623
1602
|
window.addEventListener('unhandledrejection', (event) => {
|
|
624
1603
|
try {
|
|
625
|
-
if (!sampleHit$
|
|
1604
|
+
if (!sampleHit$3(options.sampleRate))
|
|
626
1605
|
return;
|
|
627
1606
|
const reason = event?.reason;
|
|
628
|
-
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
1607
|
+
const e = normalizeErrorLike$1(reason, options.maxTextLength);
|
|
1608
|
+
// 检查是否应该忽略此错误
|
|
1609
|
+
if (shouldIgnoreMessage$1(e.message, options.ignoreMessages))
|
|
1610
|
+
return;
|
|
629
1611
|
const payload = {
|
|
630
1612
|
pagePath: getPagePath$1(),
|
|
631
1613
|
source: 'unhandledrejection',
|
|
@@ -633,6 +1615,8 @@
|
|
|
633
1615
|
errorName: e.name,
|
|
634
1616
|
stack: e.stack,
|
|
635
1617
|
};
|
|
1618
|
+
if (!shouldReport(buildErrorKey$1(options.reportType, payload)))
|
|
1619
|
+
return;
|
|
636
1620
|
report(options.reportType, payload);
|
|
637
1621
|
}
|
|
638
1622
|
catch {
|
|
@@ -640,23 +1624,174 @@
|
|
|
640
1624
|
}
|
|
641
1625
|
});
|
|
642
1626
|
}
|
|
1627
|
+
function installWebErrorMonitor(report, opts = {}) {
|
|
1628
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1629
|
+
if (!enabled)
|
|
1630
|
+
return;
|
|
1631
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1632
|
+
const options = {
|
|
1633
|
+
enabled: true,
|
|
1634
|
+
reportType: raw.reportType ?? 'error',
|
|
1635
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
1636
|
+
captureResourceError: raw.captureResourceError ?? true,
|
|
1637
|
+
maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT$1,
|
|
1638
|
+
dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS$1,
|
|
1639
|
+
dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS$1,
|
|
1640
|
+
ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES$1,
|
|
1641
|
+
};
|
|
1642
|
+
installBrowserErrorMonitor(report, options);
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
const DEFAULT_MAX_TEXT = 4000;
|
|
1646
|
+
const DEFAULT_DEDUPE_WINDOW_MS = 3000;
|
|
1647
|
+
const DEFAULT_DEDUPE_MAX_KEYS = 200;
|
|
1648
|
+
/** 默认忽略的无意义错误信息 */
|
|
1649
|
+
const DEFAULT_IGNORE_MESSAGES = [
|
|
1650
|
+
'Script error.',
|
|
1651
|
+
'Script error',
|
|
1652
|
+
/^ResizeObserver loop/,
|
|
1653
|
+
'Permission was denied',
|
|
1654
|
+
];
|
|
1655
|
+
function truncate$2(s, maxLen) {
|
|
1656
|
+
if (!s)
|
|
1657
|
+
return s;
|
|
1658
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1659
|
+
}
|
|
1660
|
+
function sampleHit$2(sampleRate) {
|
|
1661
|
+
if (sampleRate >= 1)
|
|
1662
|
+
return true;
|
|
1663
|
+
if (sampleRate <= 0)
|
|
1664
|
+
return false;
|
|
1665
|
+
return Math.random() < sampleRate;
|
|
1666
|
+
}
|
|
1667
|
+
/** 检查消息是否应该被忽略 */
|
|
1668
|
+
function shouldIgnoreMessage(message, ignorePatterns) {
|
|
1669
|
+
if (!message || ignorePatterns.length === 0)
|
|
1670
|
+
return false;
|
|
1671
|
+
return ignorePatterns.some((pattern) => {
|
|
1672
|
+
if (typeof pattern === 'string') {
|
|
1673
|
+
return message === pattern || message.includes(pattern);
|
|
1674
|
+
}
|
|
1675
|
+
return pattern.test(message);
|
|
1676
|
+
});
|
|
1677
|
+
}
|
|
1678
|
+
function getMpPagePath() {
|
|
1679
|
+
try {
|
|
1680
|
+
const pages = globalThis.getCurrentPages?.();
|
|
1681
|
+
if (Array.isArray(pages) && pages.length > 0) {
|
|
1682
|
+
const page = pages[pages.length - 1];
|
|
1683
|
+
const route = page.route || page.__route__;
|
|
1684
|
+
if (typeof route === 'string') {
|
|
1685
|
+
let path = route.startsWith('/') ? route : `/${route}`;
|
|
1686
|
+
const options = page.options || {};
|
|
1687
|
+
const keys = Object.keys(options);
|
|
1688
|
+
if (keys.length > 0) {
|
|
1689
|
+
const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
|
|
1690
|
+
path = `${path}?${qs}`;
|
|
1691
|
+
}
|
|
1692
|
+
return path;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
return '';
|
|
1696
|
+
}
|
|
1697
|
+
catch {
|
|
1698
|
+
return '';
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
function normalizeErrorLike(err, maxTextLength) {
|
|
1702
|
+
if (err && typeof err === 'object') {
|
|
1703
|
+
const anyErr = err;
|
|
1704
|
+
let rawMsg = anyErr.message;
|
|
1705
|
+
if (!rawMsg) {
|
|
1706
|
+
const str = anyErr.toString?.();
|
|
1707
|
+
if (!str || str === '[object Object]') {
|
|
1708
|
+
rawMsg = stringifyLogValue(anyErr);
|
|
1709
|
+
}
|
|
1710
|
+
else {
|
|
1711
|
+
rawMsg = str;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
|
|
1715
|
+
const name = truncate$2(String(anyErr.name ?? ''), 200);
|
|
1716
|
+
const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
|
|
1717
|
+
return { message, name, stack };
|
|
1718
|
+
}
|
|
1719
|
+
const message = truncate$2(stringifyLogValue(err), maxTextLength);
|
|
1720
|
+
return { message, name: '', stack: '' };
|
|
1721
|
+
}
|
|
1722
|
+
function createDedupeGuard(options) {
|
|
1723
|
+
const cache = new Map(); // key -> lastReportAt
|
|
1724
|
+
const maxKeys = Math.max(0, options.dedupeMaxKeys);
|
|
1725
|
+
const windowMs = Math.max(0, options.dedupeWindowMs);
|
|
1726
|
+
function touch(key, now) {
|
|
1727
|
+
if (cache.has(key))
|
|
1728
|
+
cache.delete(key);
|
|
1729
|
+
cache.set(key, now);
|
|
1730
|
+
if (maxKeys > 0) {
|
|
1731
|
+
while (cache.size > maxKeys) {
|
|
1732
|
+
const first = cache.keys().next().value;
|
|
1733
|
+
if (!first)
|
|
1734
|
+
break;
|
|
1735
|
+
cache.delete(first);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
return (key) => {
|
|
1740
|
+
if (!key)
|
|
1741
|
+
return true;
|
|
1742
|
+
if (windowMs <= 0 || maxKeys === 0)
|
|
1743
|
+
return true;
|
|
1744
|
+
const now = Date.now();
|
|
1745
|
+
const last = cache.get(key);
|
|
1746
|
+
if (typeof last === 'number' && now - last < windowMs)
|
|
1747
|
+
return false;
|
|
1748
|
+
touch(key, now);
|
|
1749
|
+
return true;
|
|
1750
|
+
};
|
|
1751
|
+
}
|
|
1752
|
+
function buildErrorKey(type, payload) {
|
|
1753
|
+
const parts = [
|
|
1754
|
+
type,
|
|
1755
|
+
String(payload.source ?? ''),
|
|
1756
|
+
String(payload.pagePath ?? ''),
|
|
1757
|
+
String(payload.message ?? ''),
|
|
1758
|
+
String(payload.errorName ?? ''),
|
|
1759
|
+
String(payload.stack ?? ''),
|
|
1760
|
+
String(payload.filename ?? ''),
|
|
1761
|
+
String(payload.lineno ?? ''),
|
|
1762
|
+
String(payload.colno ?? ''),
|
|
1763
|
+
String(payload.tagName ?? ''),
|
|
1764
|
+
String(payload.resourceUrl ?? ''),
|
|
1765
|
+
];
|
|
1766
|
+
return parts.join('|');
|
|
1767
|
+
}
|
|
643
1768
|
function installMiniProgramErrorMonitor(report, options) {
|
|
644
1769
|
const g = globalThis;
|
|
645
1770
|
if (g.__beLinkClsLoggerMpErrorInstalled__)
|
|
646
1771
|
return;
|
|
647
1772
|
g.__beLinkClsLoggerMpErrorInstalled__ = true;
|
|
1773
|
+
const shouldReport = createDedupeGuard(options);
|
|
648
1774
|
const wxAny = globalThis.wx;
|
|
649
|
-
// wx.* 事件(兼容在 App 已经创建后的场景)
|
|
650
1775
|
try {
|
|
651
1776
|
if (wxAny && typeof wxAny.onError === 'function') {
|
|
652
1777
|
wxAny.onError((msg) => {
|
|
653
1778
|
try {
|
|
654
|
-
if (!sampleHit$
|
|
1779
|
+
if (!sampleHit$2(options.sampleRate))
|
|
655
1780
|
return;
|
|
656
|
-
|
|
1781
|
+
const e = normalizeErrorLike(msg, options.maxTextLength);
|
|
1782
|
+
// 检查是否应该忽略此错误
|
|
1783
|
+
if (shouldIgnoreMessage(e.message, options.ignoreMessages))
|
|
1784
|
+
return;
|
|
1785
|
+
const payload = {
|
|
1786
|
+
pagePath: getMpPagePath(),
|
|
657
1787
|
source: 'wx.onError',
|
|
658
|
-
message:
|
|
659
|
-
|
|
1788
|
+
message: e.message,
|
|
1789
|
+
errorName: e.name,
|
|
1790
|
+
stack: e.stack,
|
|
1791
|
+
};
|
|
1792
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1793
|
+
return;
|
|
1794
|
+
report(options.reportType, payload);
|
|
660
1795
|
}
|
|
661
1796
|
catch {
|
|
662
1797
|
// ignore
|
|
@@ -671,15 +1806,22 @@
|
|
|
671
1806
|
if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
|
|
672
1807
|
wxAny.onUnhandledRejection((res) => {
|
|
673
1808
|
try {
|
|
674
|
-
if (!sampleHit$
|
|
1809
|
+
if (!sampleHit$2(options.sampleRate))
|
|
675
1810
|
return;
|
|
676
1811
|
const e = normalizeErrorLike(res?.reason, options.maxTextLength);
|
|
677
|
-
|
|
1812
|
+
// 检查是否应该忽略此错误
|
|
1813
|
+
if (shouldIgnoreMessage(e.message, options.ignoreMessages))
|
|
1814
|
+
return;
|
|
1815
|
+
const payload = {
|
|
1816
|
+
pagePath: getMpPagePath(),
|
|
678
1817
|
source: 'wx.onUnhandledRejection',
|
|
679
1818
|
message: e.message,
|
|
680
1819
|
errorName: e.name,
|
|
681
1820
|
stack: e.stack,
|
|
682
|
-
}
|
|
1821
|
+
};
|
|
1822
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1823
|
+
return;
|
|
1824
|
+
report(options.reportType, payload);
|
|
683
1825
|
}
|
|
684
1826
|
catch {
|
|
685
1827
|
// ignore
|
|
@@ -690,7 +1832,6 @@
|
|
|
690
1832
|
catch {
|
|
691
1833
|
// ignore
|
|
692
1834
|
}
|
|
693
|
-
// 包装 App({...}) 注入 onError/onUnhandledRejection(推荐)
|
|
694
1835
|
try {
|
|
695
1836
|
if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
|
|
696
1837
|
g.__beLinkClsLoggerAppWrapped__ = true;
|
|
@@ -700,11 +1841,20 @@
|
|
|
700
1841
|
const rawOnError = next.onError;
|
|
701
1842
|
next.onError = function (...args) {
|
|
702
1843
|
try {
|
|
703
|
-
if (sampleHit$
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
1844
|
+
if (sampleHit$2(options.sampleRate)) {
|
|
1845
|
+
const e = normalizeErrorLike(args?.[0], options.maxTextLength);
|
|
1846
|
+
// 检查是否应该忽略此错误
|
|
1847
|
+
if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
|
|
1848
|
+
const payload = {
|
|
1849
|
+
pagePath: getMpPagePath(),
|
|
1850
|
+
source: 'App.onError',
|
|
1851
|
+
message: e.message,
|
|
1852
|
+
errorName: e.name,
|
|
1853
|
+
stack: e.stack,
|
|
1854
|
+
};
|
|
1855
|
+
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1856
|
+
report(options.reportType, payload);
|
|
1857
|
+
}
|
|
708
1858
|
}
|
|
709
1859
|
}
|
|
710
1860
|
catch {
|
|
@@ -717,15 +1867,21 @@
|
|
|
717
1867
|
const rawOnUnhandled = next.onUnhandledRejection;
|
|
718
1868
|
next.onUnhandledRejection = function (...args) {
|
|
719
1869
|
try {
|
|
720
|
-
if (sampleHit$
|
|
1870
|
+
if (sampleHit$2(options.sampleRate)) {
|
|
721
1871
|
const reason = args?.[0]?.reason ?? args?.[0];
|
|
722
1872
|
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1873
|
+
// 检查是否应该忽略此错误
|
|
1874
|
+
if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
|
|
1875
|
+
const payload = {
|
|
1876
|
+
pagePath: getMpPagePath(),
|
|
1877
|
+
source: 'App.onUnhandledRejection',
|
|
1878
|
+
message: e.message,
|
|
1879
|
+
errorName: e.name,
|
|
1880
|
+
stack: e.stack,
|
|
1881
|
+
};
|
|
1882
|
+
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1883
|
+
report(options.reportType, payload);
|
|
1884
|
+
}
|
|
729
1885
|
}
|
|
730
1886
|
}
|
|
731
1887
|
catch {
|
|
@@ -743,7 +1899,7 @@
|
|
|
743
1899
|
// ignore
|
|
744
1900
|
}
|
|
745
1901
|
}
|
|
746
|
-
function
|
|
1902
|
+
function installMiniErrorMonitor(report, opts = {}) {
|
|
747
1903
|
const enabled = opts === undefined ? true : !!opts;
|
|
748
1904
|
if (!enabled)
|
|
749
1905
|
return;
|
|
@@ -754,12 +1910,18 @@
|
|
|
754
1910
|
sampleRate: raw.sampleRate ?? 1,
|
|
755
1911
|
captureResourceError: raw.captureResourceError ?? true,
|
|
756
1912
|
maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
|
|
1913
|
+
dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
|
|
1914
|
+
dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
|
|
1915
|
+
ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES,
|
|
757
1916
|
};
|
|
1917
|
+
installMiniProgramErrorMonitor(report, options);
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
function installErrorMonitor(report, opts = {}) {
|
|
758
1921
|
if (isMiniProgramEnv()) {
|
|
759
|
-
|
|
760
|
-
return;
|
|
1922
|
+
return installMiniErrorMonitor(report, opts);
|
|
761
1923
|
}
|
|
762
|
-
|
|
1924
|
+
return installWebErrorMonitor(report, opts);
|
|
763
1925
|
}
|
|
764
1926
|
|
|
765
1927
|
const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
|
|
@@ -768,7 +1930,7 @@
|
|
|
768
1930
|
return s;
|
|
769
1931
|
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
770
1932
|
}
|
|
771
|
-
function sampleHit(sampleRate) {
|
|
1933
|
+
function sampleHit$1(sampleRate) {
|
|
772
1934
|
if (sampleRate >= 1)
|
|
773
1935
|
return true;
|
|
774
1936
|
if (sampleRate <= 0)
|
|
@@ -796,7 +1958,7 @@
|
|
|
796
1958
|
try {
|
|
797
1959
|
if (typeof window === 'undefined')
|
|
798
1960
|
return '';
|
|
799
|
-
return window.location?.
|
|
1961
|
+
return window.location?.href ?? '';
|
|
800
1962
|
}
|
|
801
1963
|
catch {
|
|
802
1964
|
return '';
|
|
@@ -827,7 +1989,7 @@
|
|
|
827
1989
|
const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
|
|
828
1990
|
? nav.responseStart - nav.requestStart
|
|
829
1991
|
: -1;
|
|
830
|
-
if (ttfb >= 0 && sampleHit(options.sampleRate))
|
|
1992
|
+
if (ttfb >= 0 && sampleHit$1(options.sampleRate))
|
|
831
1993
|
reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
|
|
832
1994
|
}
|
|
833
1995
|
}
|
|
@@ -841,7 +2003,7 @@
|
|
|
841
2003
|
try {
|
|
842
2004
|
const po = new PerformanceObserver((list) => {
|
|
843
2005
|
try {
|
|
844
|
-
if (!sampleHit(options.sampleRate))
|
|
2006
|
+
if (!sampleHit$1(options.sampleRate))
|
|
845
2007
|
return;
|
|
846
2008
|
for (const entry of list.getEntries()) {
|
|
847
2009
|
if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
|
|
@@ -876,7 +2038,7 @@
|
|
|
876
2038
|
try {
|
|
877
2039
|
if (!lastLcp)
|
|
878
2040
|
return;
|
|
879
|
-
if (!sampleHit(options.sampleRate))
|
|
2041
|
+
if (!sampleHit$1(options.sampleRate))
|
|
880
2042
|
return;
|
|
881
2043
|
if (typeof lastLcp.startTime === 'number')
|
|
882
2044
|
reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
|
|
@@ -914,7 +2076,7 @@
|
|
|
914
2076
|
po.observe({ type: 'layout-shift', buffered: true });
|
|
915
2077
|
const flushCls = () => {
|
|
916
2078
|
try {
|
|
917
|
-
if (!sampleHit(options.sampleRate))
|
|
2079
|
+
if (!sampleHit$1(options.sampleRate))
|
|
918
2080
|
return;
|
|
919
2081
|
reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
|
|
920
2082
|
}
|
|
@@ -935,7 +2097,7 @@
|
|
|
935
2097
|
try {
|
|
936
2098
|
const po = new PerformanceObserver((list) => {
|
|
937
2099
|
try {
|
|
938
|
-
if (!sampleHit(options.sampleRate))
|
|
2100
|
+
if (!sampleHit$1(options.sampleRate))
|
|
939
2101
|
return;
|
|
940
2102
|
for (const entry of list.getEntries()) {
|
|
941
2103
|
const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
|
|
@@ -961,7 +2123,7 @@
|
|
|
961
2123
|
try {
|
|
962
2124
|
const po = new PerformanceObserver((list) => {
|
|
963
2125
|
try {
|
|
964
|
-
if (!sampleHit(options.sampleRate))
|
|
2126
|
+
if (!sampleHit$1(options.sampleRate))
|
|
965
2127
|
return;
|
|
966
2128
|
for (const entry of list.getEntries()) {
|
|
967
2129
|
const name = String(entry?.name ?? '');
|
|
@@ -1004,146 +2166,99 @@
|
|
|
1004
2166
|
}
|
|
1005
2167
|
}
|
|
1006
2168
|
}
|
|
1007
|
-
function
|
|
1008
|
-
const
|
|
1009
|
-
if (!
|
|
1010
|
-
return;
|
|
1011
|
-
const flagKey = `__beLinkClsLoggerMpRouteWrapped__${apiName}`;
|
|
1012
|
-
if (wxAny[flagKey])
|
|
2169
|
+
function installWebPerformanceMonitor(report, opts = {}) {
|
|
2170
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
2171
|
+
if (!enabled)
|
|
1013
2172
|
return;
|
|
1014
|
-
|
|
1015
|
-
const
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
metric: 'route',
|
|
1025
|
-
api: apiName,
|
|
1026
|
-
url,
|
|
1027
|
-
duration: Date.now() - start,
|
|
1028
|
-
success: success ? 1 : 0,
|
|
1029
|
-
error: success ? '' : truncate$1(stringifyLogValue(args?.[0]), options.maxTextLength),
|
|
1030
|
-
unit: 'ms',
|
|
1031
|
-
});
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
catch {
|
|
1035
|
-
// ignore
|
|
1036
|
-
}
|
|
1037
|
-
if (typeof cb === 'function')
|
|
1038
|
-
return cb(...args);
|
|
1039
|
-
return undefined;
|
|
1040
|
-
};
|
|
1041
|
-
};
|
|
1042
|
-
const next = { ...(opts ?? {}) };
|
|
1043
|
-
next.success = wrapCb(next.success, true);
|
|
1044
|
-
next.fail = wrapCb(next.fail, false);
|
|
1045
|
-
return raw(next);
|
|
2173
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
2174
|
+
const options = {
|
|
2175
|
+
enabled: true,
|
|
2176
|
+
reportType: raw.reportType ?? 'perf',
|
|
2177
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
2178
|
+
ignoreUrls: raw.ignoreUrls ?? [],
|
|
2179
|
+
webVitals: raw.webVitals ?? true,
|
|
2180
|
+
navigationTiming: raw.navigationTiming ?? true,
|
|
2181
|
+
resourceTiming: raw.resourceTiming ?? true,
|
|
2182
|
+
maxTextLength: raw.maxTextLength ?? 2000,
|
|
1046
2183
|
};
|
|
2184
|
+
installBrowserPerformanceMonitor(report, options);
|
|
1047
2185
|
}
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
if (
|
|
1051
|
-
return;
|
|
1052
|
-
if (
|
|
1053
|
-
return;
|
|
1054
|
-
|
|
1055
|
-
const rawPage = g.Page;
|
|
1056
|
-
g.Page = (pageOptions) => {
|
|
1057
|
-
const next = { ...(pageOptions ?? {}) };
|
|
1058
|
-
const rawOnLoad = next.onLoad;
|
|
1059
|
-
const rawOnReady = next.onReady;
|
|
1060
|
-
next.onLoad = function (...args) {
|
|
1061
|
-
try {
|
|
1062
|
-
this.__beLinkClsLoggerPageLoadTs__ = Date.now();
|
|
1063
|
-
}
|
|
1064
|
-
catch {
|
|
1065
|
-
// ignore
|
|
1066
|
-
}
|
|
1067
|
-
if (typeof rawOnLoad === 'function')
|
|
1068
|
-
return rawOnLoad.apply(this, args);
|
|
1069
|
-
return undefined;
|
|
1070
|
-
};
|
|
1071
|
-
next.onReady = function (...args) {
|
|
1072
|
-
try {
|
|
1073
|
-
const start = this.__beLinkClsLoggerPageLoadTs__;
|
|
1074
|
-
if (typeof start === 'number' && sampleHit(options.sampleRate)) {
|
|
1075
|
-
report(reportType, {
|
|
1076
|
-
metric: 'page-render',
|
|
1077
|
-
route: this?.route ? String(this.route) : '',
|
|
1078
|
-
duration: Date.now() - start,
|
|
1079
|
-
unit: 'ms',
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
catch {
|
|
1084
|
-
// ignore
|
|
1085
|
-
}
|
|
1086
|
-
if (typeof rawOnReady === 'function')
|
|
1087
|
-
return rawOnReady.apply(this, args);
|
|
1088
|
-
return undefined;
|
|
1089
|
-
};
|
|
1090
|
-
return rawPage(next);
|
|
1091
|
-
};
|
|
2186
|
+
|
|
2187
|
+
function sampleHit(sampleRate) {
|
|
2188
|
+
if (sampleRate >= 1)
|
|
2189
|
+
return true;
|
|
2190
|
+
if (sampleRate <= 0)
|
|
2191
|
+
return false;
|
|
2192
|
+
return Math.random() < sampleRate;
|
|
1092
2193
|
}
|
|
1093
2194
|
function installMiniProgramPerformanceMonitor(report, options) {
|
|
1094
2195
|
const g = globalThis;
|
|
2196
|
+
const ctx = g.wx || g.Taro;
|
|
2197
|
+
if (!ctx || typeof ctx.getPerformance !== 'function')
|
|
2198
|
+
return;
|
|
1095
2199
|
if (g.__beLinkClsLoggerMpPerfInstalled__)
|
|
1096
2200
|
return;
|
|
1097
2201
|
g.__beLinkClsLoggerMpPerfInstalled__ = true;
|
|
1098
|
-
// 路由切换耗时(用 API 回调近似)
|
|
1099
|
-
for (const apiName of ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch']) {
|
|
1100
|
-
try {
|
|
1101
|
-
wrapMiniProgramRouteApi(report, options.reportType, apiName, options);
|
|
1102
|
-
}
|
|
1103
|
-
catch {
|
|
1104
|
-
// ignore
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
// 页面渲染耗时(onLoad -> onReady)
|
|
1108
|
-
try {
|
|
1109
|
-
installMiniProgramPageRenderMonitor(report, options.reportType, options);
|
|
1110
|
-
}
|
|
1111
|
-
catch {
|
|
1112
|
-
// ignore
|
|
1113
|
-
}
|
|
1114
|
-
// wx.getPerformance()(若可用,尝试读取已有 entries)
|
|
1115
2202
|
try {
|
|
1116
|
-
const
|
|
1117
|
-
if (
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
2203
|
+
const perf = ctx.getPerformance();
|
|
2204
|
+
if (!perf || typeof perf.createObserver !== 'function')
|
|
2205
|
+
return;
|
|
2206
|
+
const observer = perf.createObserver((entryList) => {
|
|
2207
|
+
try {
|
|
2208
|
+
const entries = entryList.getEntries();
|
|
2209
|
+
for (const entry of entries) {
|
|
2210
|
+
if (!sampleHit(options.sampleRate))
|
|
2211
|
+
continue;
|
|
2212
|
+
// Page Render: firstRender
|
|
2213
|
+
if (entry.entryType === 'render' && entry.name === 'firstRender') {
|
|
2214
|
+
const duration = typeof entry.duration === 'number'
|
|
2215
|
+
? entry.duration
|
|
2216
|
+
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
2217
|
+
? entry.endTime - entry.startTime
|
|
2218
|
+
: 0;
|
|
1130
2219
|
report(options.reportType, {
|
|
1131
|
-
metric: '
|
|
1132
|
-
|
|
2220
|
+
metric: 'page-render',
|
|
2221
|
+
duration,
|
|
2222
|
+
pagePath: entry.path || '',
|
|
2223
|
+
unit: 'ms',
|
|
1133
2224
|
});
|
|
1134
2225
|
}
|
|
1135
|
-
|
|
1136
|
-
|
|
2226
|
+
// Route Switch: route
|
|
2227
|
+
else if (entry.entryType === 'navigation' && entry.name === 'route') {
|
|
2228
|
+
const duration = typeof entry.duration === 'number'
|
|
2229
|
+
? entry.duration
|
|
2230
|
+
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
2231
|
+
? entry.endTime - entry.startTime
|
|
2232
|
+
: 0;
|
|
2233
|
+
report(options.reportType, {
|
|
2234
|
+
metric: 'route',
|
|
2235
|
+
duration,
|
|
2236
|
+
pagePath: entry.path || '',
|
|
2237
|
+
unit: 'ms',
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
// App Launch: appLaunch (Cold)
|
|
2241
|
+
else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
|
|
2242
|
+
report(options.reportType, {
|
|
2243
|
+
metric: 'app-launch',
|
|
2244
|
+
duration: entry.duration,
|
|
2245
|
+
launchType: 'cold',
|
|
2246
|
+
unit: 'ms',
|
|
2247
|
+
});
|
|
1137
2248
|
}
|
|
1138
|
-
}
|
|
2249
|
+
}
|
|
1139
2250
|
}
|
|
1140
|
-
|
|
2251
|
+
catch {
|
|
2252
|
+
// ignore
|
|
2253
|
+
}
|
|
2254
|
+
});
|
|
2255
|
+
observer.observe({ entryTypes: ['navigation', 'render'] });
|
|
1141
2256
|
}
|
|
1142
2257
|
catch {
|
|
1143
2258
|
// ignore
|
|
1144
2259
|
}
|
|
1145
2260
|
}
|
|
1146
|
-
function
|
|
2261
|
+
function installMiniPerformanceMonitor(report, opts = {}) {
|
|
1147
2262
|
const enabled = opts === undefined ? true : !!opts;
|
|
1148
2263
|
if (!enabled)
|
|
1149
2264
|
return;
|
|
@@ -1158,14 +2273,17 @@
|
|
|
1158
2273
|
resourceTiming: raw.resourceTiming ?? true,
|
|
1159
2274
|
maxTextLength: raw.maxTextLength ?? 2000,
|
|
1160
2275
|
};
|
|
2276
|
+
installMiniProgramPerformanceMonitor(report, options);
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
function installPerformanceMonitor(report, opts = {}) {
|
|
1161
2280
|
if (isMiniProgramEnv()) {
|
|
1162
|
-
|
|
1163
|
-
return;
|
|
2281
|
+
return installMiniPerformanceMonitor(report, opts);
|
|
1164
2282
|
}
|
|
1165
|
-
|
|
2283
|
+
return installWebPerformanceMonitor(report, opts);
|
|
1166
2284
|
}
|
|
1167
2285
|
|
|
1168
|
-
function shouldSample(sampleRate) {
|
|
2286
|
+
function shouldSample$1(sampleRate) {
|
|
1169
2287
|
const r = sampleRate ?? 1;
|
|
1170
2288
|
if (r >= 1)
|
|
1171
2289
|
return true;
|
|
@@ -1173,19 +2291,17 @@
|
|
|
1173
2291
|
return false;
|
|
1174
2292
|
return Math.random() < r;
|
|
1175
2293
|
}
|
|
1176
|
-
function generateUUID() {
|
|
1177
|
-
// 优先使用更安全的 crypto.randomUUID
|
|
2294
|
+
function generateUUID$1() {
|
|
1178
2295
|
const g = globalThis;
|
|
1179
2296
|
if (g.crypto?.randomUUID)
|
|
1180
2297
|
return g.crypto.randomUUID();
|
|
1181
|
-
// fallback
|
|
1182
2298
|
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
1183
2299
|
const r = Math.random() * 16 || 0;
|
|
1184
2300
|
const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
|
|
1185
2301
|
return v.toString(16);
|
|
1186
2302
|
});
|
|
1187
2303
|
}
|
|
1188
|
-
function safeReadUvMeta(key) {
|
|
2304
|
+
function safeReadUvMeta$1(key) {
|
|
1189
2305
|
const raw = readStringStorage(key);
|
|
1190
2306
|
if (!raw)
|
|
1191
2307
|
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
@@ -1204,27 +2320,15 @@
|
|
|
1204
2320
|
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1205
2321
|
}
|
|
1206
2322
|
}
|
|
1207
|
-
function writeUvMeta(key, meta) {
|
|
2323
|
+
function writeUvMeta$1(key, meta) {
|
|
1208
2324
|
writeStringStorage(key, JSON.stringify(meta));
|
|
1209
2325
|
}
|
|
1210
2326
|
function getWebPagePath() {
|
|
1211
2327
|
if (typeof window === 'undefined')
|
|
1212
2328
|
return '';
|
|
1213
|
-
return window.location?.
|
|
1214
|
-
}
|
|
1215
|
-
function getMiniProgramPagePath() {
|
|
1216
|
-
const g = globalThis;
|
|
1217
|
-
try {
|
|
1218
|
-
const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
|
|
1219
|
-
const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
|
|
1220
|
-
const route = (last?.route || last?.__route__);
|
|
1221
|
-
return typeof route === 'string' ? route : '';
|
|
1222
|
-
}
|
|
1223
|
-
catch {
|
|
1224
|
-
return '';
|
|
1225
|
-
}
|
|
2329
|
+
return window.location?.href || '';
|
|
1226
2330
|
}
|
|
1227
|
-
function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
|
|
2331
|
+
function buildCommonUvFields$1(uvId, uvMeta, isFirstVisit) {
|
|
1228
2332
|
return {
|
|
1229
2333
|
uvId,
|
|
1230
2334
|
isFirstVisit,
|
|
@@ -1240,14 +2344,14 @@
|
|
|
1240
2344
|
return '';
|
|
1241
2345
|
}
|
|
1242
2346
|
}
|
|
1243
|
-
function truncateText(s, maxLen) {
|
|
2347
|
+
function truncateText$1(s, maxLen) {
|
|
1244
2348
|
if (!s)
|
|
1245
2349
|
return '';
|
|
1246
2350
|
if (s.length <= maxLen)
|
|
1247
2351
|
return s;
|
|
1248
2352
|
return s.slice(0, maxLen);
|
|
1249
2353
|
}
|
|
1250
|
-
function
|
|
2354
|
+
function installWebBehaviorMonitor(report, options = {}) {
|
|
1251
2355
|
const enableTrack = options.enableTrack ?? options.enabled ?? true;
|
|
1252
2356
|
if (!enableTrack)
|
|
1253
2357
|
return () => { };
|
|
@@ -1259,39 +2363,28 @@
|
|
|
1259
2363
|
const clickReportType = options.clickReportType ?? 'click';
|
|
1260
2364
|
const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
|
|
1261
2365
|
const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
|
|
1262
|
-
const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
|
|
1263
2366
|
const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
|
|
1264
2367
|
const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
|
|
1265
2368
|
const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
|
|
1266
|
-
const
|
|
1267
|
-
const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? defaultClickWhiteList).map((s) => String(s).toLowerCase());
|
|
2369
|
+
const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? ['body', 'html']).map((s) => String(s).toLowerCase());
|
|
1268
2370
|
const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
|
|
1269
2371
|
const clickMaxTextLength = options.clickMaxTextLength ?? 120;
|
|
1270
|
-
const getPagePath = options.getPagePath ??
|
|
1271
|
-
(() => {
|
|
1272
|
-
if (envType === 'miniprogram' || isMiniProgramEnv())
|
|
1273
|
-
return getMiniProgramPagePath();
|
|
1274
|
-
return getWebPagePath();
|
|
1275
|
-
});
|
|
2372
|
+
const getPagePath = options.getPagePath ?? getWebPagePath;
|
|
1276
2373
|
let destroyed = false;
|
|
1277
|
-
// UV 状态:可能异步(openid/指纹)
|
|
1278
2374
|
let firstVisitFlag = false;
|
|
1279
2375
|
let firstVisitConsumed = false;
|
|
1280
2376
|
const uvStatePromise = (async () => {
|
|
1281
2377
|
let existingUvId = readStringStorage(uvIdStorageKey);
|
|
1282
2378
|
let isFirstVisit = false;
|
|
1283
|
-
// 先读 meta,做过期判断(过期则清空 uvId + 重置 meta)
|
|
1284
2379
|
const now = Date.now();
|
|
1285
|
-
const metaBefore = safeReadUvMeta(uvMetaStorageKey);
|
|
2380
|
+
const metaBefore = safeReadUvMeta$1(uvMetaStorageKey);
|
|
1286
2381
|
const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
|
|
1287
2382
|
const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
|
|
1288
2383
|
if (expired) {
|
|
1289
2384
|
existingUvId = null;
|
|
1290
|
-
|
|
1291
|
-
writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
2385
|
+
writeUvMeta$1(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
1292
2386
|
writeStringStorage(uvIdStorageKey, '');
|
|
1293
2387
|
}
|
|
1294
|
-
// 如果外部提供 getUvId,优先使用;否则本地生成
|
|
1295
2388
|
try {
|
|
1296
2389
|
if (options.getUvId) {
|
|
1297
2390
|
const maybe = options.getUvId();
|
|
@@ -1301,42 +2394,14 @@
|
|
|
1301
2394
|
}
|
|
1302
2395
|
}
|
|
1303
2396
|
catch {
|
|
1304
|
-
|
|
1305
|
-
}
|
|
1306
|
-
// 小程序:默认尝试 openid / 设备标识(兼容你给的参考实现)
|
|
1307
|
-
if (!existingUvId && (envType === 'miniprogram' || isMiniProgramEnv())) {
|
|
1308
|
-
const wxAny = globalThis.wx;
|
|
1309
|
-
try {
|
|
1310
|
-
const userInfo = wxAny?.getStorageSync?.('userInfo');
|
|
1311
|
-
if (userInfo?.openid)
|
|
1312
|
-
existingUvId = String(userInfo.openid);
|
|
1313
|
-
}
|
|
1314
|
-
catch {
|
|
1315
|
-
// ignore
|
|
1316
|
-
}
|
|
1317
|
-
if (!existingUvId) {
|
|
1318
|
-
try {
|
|
1319
|
-
const sys = wxAny?.getSystemInfoSync?.();
|
|
1320
|
-
const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
|
|
1321
|
-
const model = sys?.model ? String(sys.model) : '';
|
|
1322
|
-
const system = sys?.system ? String(sys.system) : '';
|
|
1323
|
-
const base = [deviceId || model, system].filter(Boolean).join('_');
|
|
1324
|
-
if (base)
|
|
1325
|
-
existingUvId = `${base}_${Date.now()}`;
|
|
1326
|
-
}
|
|
1327
|
-
catch {
|
|
1328
|
-
// ignore
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
2397
|
+
/* ignore */
|
|
1331
2398
|
}
|
|
1332
2399
|
if (!existingUvId) {
|
|
1333
|
-
existingUvId = generateUUID();
|
|
2400
|
+
existingUvId = generateUUID$1();
|
|
1334
2401
|
isFirstVisit = true;
|
|
1335
2402
|
}
|
|
1336
|
-
// 只要拿到了 uvId,就写入持久化(便于下次启动复用)
|
|
1337
2403
|
writeStringStorage(uvIdStorageKey, existingUvId);
|
|
1338
|
-
const meta = safeReadUvMeta(uvMetaStorageKey);
|
|
1339
|
-
// 每次启动都 +1(“累计访问次数”)
|
|
2404
|
+
const meta = safeReadUvMeta$1(uvMetaStorageKey);
|
|
1340
2405
|
const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
|
|
1341
2406
|
const firstVisit = meta.firstVisitTs || now;
|
|
1342
2407
|
const nextMeta = {
|
|
@@ -1345,19 +2410,18 @@
|
|
|
1345
2410
|
createdAtTs: createdAt,
|
|
1346
2411
|
lastSeenTs: now,
|
|
1347
2412
|
};
|
|
1348
|
-
// 如果是首次访问,刷新 firstVisitTs
|
|
1349
2413
|
if (isFirstVisit) {
|
|
1350
2414
|
nextMeta.firstVisitTs = now;
|
|
1351
2415
|
nextMeta.createdAtTs = now;
|
|
1352
2416
|
}
|
|
1353
|
-
writeUvMeta(uvMetaStorageKey, nextMeta);
|
|
2417
|
+
writeUvMeta$1(uvMetaStorageKey, nextMeta);
|
|
1354
2418
|
firstVisitFlag = isFirstVisit;
|
|
1355
2419
|
return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
|
|
1356
2420
|
})();
|
|
1357
2421
|
function safeReport(type, data) {
|
|
1358
2422
|
if (destroyed)
|
|
1359
2423
|
return;
|
|
1360
|
-
if (!shouldSample(options.sampleRate))
|
|
2424
|
+
if (!shouldSample$1(options.sampleRate))
|
|
1361
2425
|
return;
|
|
1362
2426
|
report(type, data);
|
|
1363
2427
|
}
|
|
@@ -1365,20 +2429,7 @@
|
|
|
1365
2429
|
const once = firstVisitFlag && !firstVisitConsumed;
|
|
1366
2430
|
if (once)
|
|
1367
2431
|
firstVisitConsumed = true;
|
|
1368
|
-
return buildCommonUvFields(uvId, meta, once);
|
|
1369
|
-
}
|
|
1370
|
-
function reportUvOncePerSession() {
|
|
1371
|
-
if (!uvEnabled)
|
|
1372
|
-
return;
|
|
1373
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1374
|
-
if (destroyed)
|
|
1375
|
-
return;
|
|
1376
|
-
safeReport(uvReportType, {
|
|
1377
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1378
|
-
timestamp: Date.now(),
|
|
1379
|
-
pagePath: getPagePath(),
|
|
1380
|
-
});
|
|
1381
|
-
});
|
|
2432
|
+
return buildCommonUvFields$1(uvId, meta, once);
|
|
1382
2433
|
}
|
|
1383
2434
|
function reportPv(pagePath) {
|
|
1384
2435
|
if (!pvEnabled)
|
|
@@ -1390,956 +2441,780 @@
|
|
|
1390
2441
|
...buildUvFieldsOnce(uvId, meta),
|
|
1391
2442
|
timestamp: Date.now(),
|
|
1392
2443
|
pagePath,
|
|
2444
|
+
referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
|
|
1393
2445
|
};
|
|
1394
|
-
// Web referrer(小程序为空串)
|
|
1395
|
-
if (typeof document !== 'undefined') {
|
|
1396
|
-
payload.referrer = document.referrer || '';
|
|
1397
|
-
}
|
|
1398
|
-
else if (envType === 'miniprogram' || isMiniProgramEnv()) {
|
|
1399
|
-
payload.referrer = readStringStorage(lastPagePathStorageKey) || '';
|
|
1400
|
-
writeStringStorage(lastPagePathStorageKey, pagePath);
|
|
1401
|
-
}
|
|
1402
2446
|
safeReport(pvReportType, payload);
|
|
1403
2447
|
});
|
|
1404
2448
|
}
|
|
1405
|
-
//
|
|
2449
|
+
// Web PV Listeners
|
|
1406
2450
|
let removeWebPvListeners = null;
|
|
1407
|
-
if (
|
|
2451
|
+
if (pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
|
|
1408
2452
|
const originalPushState = window.history.pushState?.bind(window.history);
|
|
1409
2453
|
const originalReplaceState = window.history.replaceState?.bind(window.history);
|
|
1410
|
-
const onRouteChanged = () => reportPv(getPagePath());
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
// ignore
|
|
1435
|
-
}
|
|
1436
|
-
try {
|
|
1437
|
-
if (originalPushState)
|
|
1438
|
-
window.history.pushState = originalPushState;
|
|
1439
|
-
if (originalReplaceState)
|
|
1440
|
-
window.history.replaceState = originalReplaceState;
|
|
1441
|
-
}
|
|
1442
|
-
catch {
|
|
1443
|
-
// ignore
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
1446
|
-
}
|
|
1447
|
-
// --- Web: Click ---
|
|
1448
|
-
let removeWebClickListener = null;
|
|
1449
|
-
if (!destroyed && clickEnabled && typeof document !== 'undefined') {
|
|
1450
|
-
const onClick = (e) => {
|
|
1451
|
-
if (destroyed)
|
|
1452
|
-
return;
|
|
1453
|
-
const target = e.target;
|
|
1454
|
-
if (!target)
|
|
1455
|
-
return;
|
|
1456
|
-
// 向上找最接近的带 trackId 的元素(优先)
|
|
1457
|
-
const closestWithTrackId = typeof target.closest === 'function'
|
|
1458
|
-
? target.closest(`[${clickTrackIdAttr}]`)
|
|
1459
|
-
: null;
|
|
1460
|
-
const el = closestWithTrackId || target;
|
|
1461
|
-
const tag = (el.tagName || '').toLowerCase();
|
|
1462
|
-
const trackId = getAttr(el, clickTrackIdAttr);
|
|
1463
|
-
// 过滤无效点击:白名单 tag + 没有 trackId
|
|
1464
|
-
if (clickWhiteList.includes(tag) && !trackId)
|
|
1465
|
-
return;
|
|
1466
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1467
|
-
if (destroyed)
|
|
1468
|
-
return;
|
|
1469
|
-
safeReport(clickReportType, {
|
|
1470
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1471
|
-
timestamp: Date.now(),
|
|
1472
|
-
pagePath: getPagePath(),
|
|
1473
|
-
elementTag: el.tagName || '',
|
|
1474
|
-
elementId: el.id || '',
|
|
1475
|
-
elementClass: stringifyLogValue(el.className ?? ''),
|
|
1476
|
-
trackId: trackId || '',
|
|
1477
|
-
elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
|
|
1478
|
-
clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
|
|
1479
|
-
clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
|
|
1480
|
-
});
|
|
1481
|
-
});
|
|
1482
|
-
};
|
|
1483
|
-
document.addEventListener('click', onClick, true);
|
|
1484
|
-
removeWebClickListener = () => {
|
|
1485
|
-
try {
|
|
1486
|
-
document.removeEventListener('click', onClick, true);
|
|
1487
|
-
}
|
|
1488
|
-
catch {
|
|
1489
|
-
// ignore
|
|
1490
|
-
}
|
|
1491
|
-
};
|
|
1492
|
-
}
|
|
1493
|
-
// --- MiniProgram: PV (best-effort) ---
|
|
1494
|
-
let restoreMiniProgramPatch = null;
|
|
1495
|
-
if (!destroyed && (envType === 'miniprogram' || isMiniProgramEnv())) {
|
|
1496
|
-
const g = globalThis;
|
|
1497
|
-
const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
|
|
1498
|
-
if (!g[patchedKey]) {
|
|
1499
|
-
g[patchedKey] = true;
|
|
1500
|
-
const originalPage = typeof g.Page === 'function' ? g.Page : null;
|
|
1501
|
-
if (originalPage) {
|
|
1502
|
-
g.Page = function patchedPage(conf) {
|
|
1503
|
-
const originalOnShow = conf?.onShow;
|
|
1504
|
-
conf.onShow = function (...args) {
|
|
1505
|
-
if (pvEnabled)
|
|
1506
|
-
reportPv(getPagePath());
|
|
1507
|
-
return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
|
|
1508
|
-
};
|
|
1509
|
-
// 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
|
|
1510
|
-
if (clickEnabled && conf && typeof conf === 'object') {
|
|
1511
|
-
for (const key of Object.keys(conf)) {
|
|
1512
|
-
const fn = conf[key];
|
|
1513
|
-
if (typeof fn !== 'function')
|
|
1514
|
-
continue;
|
|
1515
|
-
if (fn.__beLinkWrapped__)
|
|
1516
|
-
continue;
|
|
1517
|
-
conf[key] = function (...args) {
|
|
1518
|
-
try {
|
|
1519
|
-
const e = args?.[0];
|
|
1520
|
-
const type = e?.type;
|
|
1521
|
-
const currentTarget = e?.currentTarget;
|
|
1522
|
-
const dataset = currentTarget?.dataset;
|
|
1523
|
-
const isTap = type === 'tap' || type === 'click';
|
|
1524
|
-
if (clickEnabled && isTap && currentTarget && dataset) {
|
|
1525
|
-
const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
|
|
1526
|
-
const tagName = String(tagNameRaw || '').toLowerCase();
|
|
1527
|
-
const trackId = dataset?.trackId ? String(dataset.trackId) : '';
|
|
1528
|
-
if (!(clickWhiteList.includes(tagName) && !trackId)) {
|
|
1529
|
-
const x = typeof e?.detail?.x === 'number'
|
|
1530
|
-
? e.detail.x
|
|
1531
|
-
: typeof e?.touches?.[0]?.pageX === 'number'
|
|
1532
|
-
? e.touches[0].pageX
|
|
1533
|
-
: 0;
|
|
1534
|
-
const y = typeof e?.detail?.y === 'number'
|
|
1535
|
-
? e.detail.y
|
|
1536
|
-
: typeof e?.touches?.[0]?.pageY === 'number'
|
|
1537
|
-
? e.touches[0].pageY
|
|
1538
|
-
: 0;
|
|
1539
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1540
|
-
if (destroyed)
|
|
1541
|
-
return;
|
|
1542
|
-
safeReport(clickReportType, {
|
|
1543
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1544
|
-
timestamp: Date.now(),
|
|
1545
|
-
pagePath: getPagePath(),
|
|
1546
|
-
elementTag: tagNameRaw ? String(tagNameRaw) : '',
|
|
1547
|
-
elementId: currentTarget?.id ? String(currentTarget.id) : '',
|
|
1548
|
-
elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
|
|
1549
|
-
trackId,
|
|
1550
|
-
elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
|
|
1551
|
-
clickX: x,
|
|
1552
|
-
clickY: y,
|
|
1553
|
-
});
|
|
1554
|
-
});
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
catch {
|
|
1559
|
-
// ignore
|
|
1560
|
-
}
|
|
1561
|
-
return fn.apply(this, args);
|
|
1562
|
-
};
|
|
1563
|
-
conf[key].__beLinkWrapped__ = true;
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
return originalPage(conf);
|
|
1567
|
-
};
|
|
1568
|
-
restoreMiniProgramPatch = () => {
|
|
1569
|
-
try {
|
|
1570
|
-
g.Page = originalPage;
|
|
1571
|
-
g[patchedKey] = false;
|
|
1572
|
-
}
|
|
1573
|
-
catch {
|
|
1574
|
-
// ignore
|
|
1575
|
-
}
|
|
1576
|
-
};
|
|
1577
|
-
}
|
|
1578
|
-
}
|
|
1579
|
-
// 启动时也尝试报一次(避免 Page patch 未生效的场景)
|
|
1580
|
-
if (pvEnabled)
|
|
1581
|
-
reportPv(getPagePath());
|
|
1582
|
-
}
|
|
1583
|
-
// UV:每次启动上报一次(可关闭)
|
|
1584
|
-
reportUvOncePerSession();
|
|
1585
|
-
return () => {
|
|
1586
|
-
if (destroyed)
|
|
1587
|
-
return;
|
|
1588
|
-
destroyed = true;
|
|
1589
|
-
try {
|
|
1590
|
-
removeWebPvListeners?.();
|
|
1591
|
-
removeWebClickListener?.();
|
|
1592
|
-
restoreMiniProgramPatch?.();
|
|
1593
|
-
}
|
|
1594
|
-
catch {
|
|
1595
|
-
// ignore
|
|
1596
|
-
}
|
|
1597
|
-
};
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
function truncate(s, maxLen) {
|
|
1601
|
-
if (!s)
|
|
1602
|
-
return s;
|
|
1603
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1604
|
-
}
|
|
1605
|
-
function parseUserAgent(uaRaw) {
|
|
1606
|
-
const ua = uaRaw ?? '';
|
|
1607
|
-
const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
|
|
1608
|
-
// OS
|
|
1609
|
-
let osName = 'unknown';
|
|
1610
|
-
let osVersion = '';
|
|
1611
|
-
const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
|
|
1612
|
-
const android = ua.match(/Android (\d+(\.\d+)*)/i);
|
|
1613
|
-
const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
|
|
1614
|
-
const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
|
|
1615
|
-
if (ios) {
|
|
1616
|
-
osName = 'iOS';
|
|
1617
|
-
osVersion = ios[1].replace(/_/g, '.');
|
|
1618
|
-
}
|
|
1619
|
-
else if (android) {
|
|
1620
|
-
osName = 'Android';
|
|
1621
|
-
osVersion = android[1];
|
|
1622
|
-
}
|
|
1623
|
-
else if (win) {
|
|
1624
|
-
osName = 'Windows';
|
|
1625
|
-
osVersion = win[1];
|
|
1626
|
-
}
|
|
1627
|
-
else if (mac) {
|
|
1628
|
-
osName = 'macOS';
|
|
1629
|
-
osVersion = mac[1].replace(/_/g, '.');
|
|
1630
|
-
}
|
|
1631
|
-
// Browser
|
|
1632
|
-
let browserName = 'unknown';
|
|
1633
|
-
let browserVersion = '';
|
|
1634
|
-
const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
|
|
1635
|
-
const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
|
|
1636
|
-
const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
|
|
1637
|
-
const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
|
|
1638
|
-
if (edge) {
|
|
1639
|
-
browserName = 'Edge';
|
|
1640
|
-
browserVersion = edge[1];
|
|
1641
|
-
}
|
|
1642
|
-
else if (chrome) {
|
|
1643
|
-
browserName = 'Chrome';
|
|
1644
|
-
browserVersion = chrome[1];
|
|
1645
|
-
}
|
|
1646
|
-
else if (firefox) {
|
|
1647
|
-
browserName = 'Firefox';
|
|
1648
|
-
browserVersion = firefox[1];
|
|
1649
|
-
}
|
|
1650
|
-
else if (safari) {
|
|
1651
|
-
browserName = 'Safari';
|
|
1652
|
-
browserVersion = safari[1];
|
|
1653
|
-
}
|
|
1654
|
-
return { browserName, browserVersion, osName, osVersion, isMobile };
|
|
1655
|
-
}
|
|
1656
|
-
function getBrowserDeviceInfo(options) {
|
|
1657
|
-
const out = {
|
|
1658
|
-
envType: 'browser',
|
|
1659
|
-
};
|
|
1660
|
-
if (typeof window === 'undefined' || typeof navigator === 'undefined')
|
|
1661
|
-
return out;
|
|
1662
|
-
const ua = String(navigator.userAgent ?? '');
|
|
1663
|
-
const uaParsed = parseUserAgent(ua);
|
|
1664
|
-
if (options.includeUserAgent)
|
|
1665
|
-
out.ua = truncate(ua, 2000);
|
|
1666
|
-
out.browserName = uaParsed.browserName;
|
|
1667
|
-
out.browserVersion = uaParsed.browserVersion;
|
|
1668
|
-
out.osName = uaParsed.osName;
|
|
1669
|
-
out.osVersion = uaParsed.osVersion;
|
|
1670
|
-
out.isMobile = uaParsed.isMobile ? 1 : 0;
|
|
1671
|
-
out.language = String(navigator.language ?? '');
|
|
1672
|
-
out.platform = String(navigator.platform ?? '');
|
|
1673
|
-
try {
|
|
1674
|
-
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1675
|
-
out.timezone = typeof tz === 'string' ? tz : '';
|
|
1676
|
-
}
|
|
1677
|
-
catch {
|
|
1678
|
-
out.timezone = '';
|
|
1679
|
-
}
|
|
1680
|
-
try {
|
|
1681
|
-
const s = window.screen;
|
|
1682
|
-
out.screenWidth = s?.width ?? undefined;
|
|
1683
|
-
out.screenHeight = s?.height ?? undefined;
|
|
1684
|
-
}
|
|
1685
|
-
catch {
|
|
1686
|
-
// ignore
|
|
2454
|
+
const onRouteChanged = () => reportPv(getPagePath());
|
|
2455
|
+
onRouteChanged();
|
|
2456
|
+
if (originalPushState) {
|
|
2457
|
+
window.history.pushState = ((...args) => {
|
|
2458
|
+
const r = originalPushState.apply(window.history, args);
|
|
2459
|
+
onRouteChanged();
|
|
2460
|
+
return r;
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
if (originalReplaceState) {
|
|
2464
|
+
window.history.replaceState = ((...args) => {
|
|
2465
|
+
const r = originalReplaceState.apply(window.history, args);
|
|
2466
|
+
onRouteChanged();
|
|
2467
|
+
return r;
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
window.addEventListener('popstate', onRouteChanged);
|
|
2471
|
+
removeWebPvListeners = () => {
|
|
2472
|
+
window.removeEventListener('popstate', onRouteChanged);
|
|
2473
|
+
if (originalPushState)
|
|
2474
|
+
window.history.pushState = originalPushState;
|
|
2475
|
+
if (originalReplaceState)
|
|
2476
|
+
window.history.replaceState = originalReplaceState;
|
|
2477
|
+
};
|
|
1687
2478
|
}
|
|
1688
|
-
|
|
1689
|
-
|
|
2479
|
+
// Web Click Listener
|
|
2480
|
+
let removeWebClickListener = null;
|
|
2481
|
+
if (clickEnabled && typeof document !== 'undefined') {
|
|
2482
|
+
const onClick = (e) => {
|
|
2483
|
+
if (destroyed)
|
|
2484
|
+
return;
|
|
2485
|
+
const target = e.target;
|
|
2486
|
+
if (!target)
|
|
2487
|
+
return;
|
|
2488
|
+
const closestWithTrackId = typeof target.closest === 'function'
|
|
2489
|
+
? target.closest(`[${clickTrackIdAttr}]`)
|
|
2490
|
+
: null;
|
|
2491
|
+
const el = closestWithTrackId || target;
|
|
2492
|
+
const tag = (el.tagName || '').toLowerCase();
|
|
2493
|
+
const trackId = getAttr(el, clickTrackIdAttr);
|
|
2494
|
+
if (clickWhiteList.includes(tag) || !trackId)
|
|
2495
|
+
return;
|
|
2496
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
2497
|
+
if (destroyed)
|
|
2498
|
+
return;
|
|
2499
|
+
safeReport(clickReportType, {
|
|
2500
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
2501
|
+
timestamp: Date.now(),
|
|
2502
|
+
pagePath: getPagePath(),
|
|
2503
|
+
elementTag: el.tagName || '',
|
|
2504
|
+
elementId: el.id || '',
|
|
2505
|
+
elementClass: stringifyLogValue(el.className ?? ''),
|
|
2506
|
+
trackId: trackId || '',
|
|
2507
|
+
elementText: truncateText$1((el.textContent ?? '').trim(), clickMaxTextLength),
|
|
2508
|
+
clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
|
|
2509
|
+
clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
|
|
2510
|
+
});
|
|
2511
|
+
});
|
|
2512
|
+
};
|
|
2513
|
+
document.addEventListener('click', onClick, true);
|
|
2514
|
+
removeWebClickListener = () => document.removeEventListener('click', onClick, true);
|
|
1690
2515
|
}
|
|
1691
|
-
|
|
1692
|
-
|
|
2516
|
+
// UV Initial Report
|
|
2517
|
+
if (uvEnabled) {
|
|
2518
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
2519
|
+
if (destroyed)
|
|
2520
|
+
return;
|
|
2521
|
+
safeReport(uvReportType, {
|
|
2522
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
2523
|
+
timestamp: Date.now(),
|
|
2524
|
+
pagePath: getPagePath(),
|
|
2525
|
+
});
|
|
2526
|
+
});
|
|
1693
2527
|
}
|
|
2528
|
+
return () => {
|
|
2529
|
+
destroyed = true;
|
|
2530
|
+
removeWebPvListeners?.();
|
|
2531
|
+
removeWebClickListener?.();
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
function shouldSample(sampleRate) {
|
|
2536
|
+
const r = sampleRate ?? 1;
|
|
2537
|
+
if (r >= 1)
|
|
2538
|
+
return true;
|
|
2539
|
+
if (r <= 0)
|
|
2540
|
+
return false;
|
|
2541
|
+
return Math.random() < r;
|
|
2542
|
+
}
|
|
2543
|
+
function generateUUID() {
|
|
2544
|
+
const g = globalThis;
|
|
2545
|
+
if (g.crypto?.randomUUID)
|
|
2546
|
+
return g.crypto.randomUUID();
|
|
2547
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
2548
|
+
const r = Math.random() * 16 || 0;
|
|
2549
|
+
const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
|
|
2550
|
+
return v.toString(16);
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
function safeReadUvMeta(key) {
|
|
2554
|
+
const raw = readStringStorage(key);
|
|
2555
|
+
if (!raw)
|
|
2556
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1694
2557
|
try {
|
|
1695
|
-
const
|
|
1696
|
-
|
|
1697
|
-
|
|
2558
|
+
const parsed = JSON.parse(raw);
|
|
2559
|
+
if (!parsed || typeof parsed !== 'object')
|
|
2560
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
2561
|
+
const p = parsed;
|
|
2562
|
+
const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
|
|
2563
|
+
const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
|
|
2564
|
+
const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
|
|
2565
|
+
const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
|
|
2566
|
+
return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
|
|
1698
2567
|
}
|
|
1699
2568
|
catch {
|
|
1700
|
-
|
|
1701
|
-
}
|
|
1702
|
-
if (options.includeNetwork) {
|
|
1703
|
-
try {
|
|
1704
|
-
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
|
|
1705
|
-
if (conn && isPlainObject(conn)) {
|
|
1706
|
-
if (typeof conn.effectiveType === 'string')
|
|
1707
|
-
out.netEffectiveType = conn.effectiveType;
|
|
1708
|
-
if (typeof conn.downlink === 'number')
|
|
1709
|
-
out.netDownlink = conn.downlink;
|
|
1710
|
-
if (typeof conn.rtt === 'number')
|
|
1711
|
-
out.netRtt = conn.rtt;
|
|
1712
|
-
if (typeof conn.saveData === 'boolean')
|
|
1713
|
-
out.netSaveData = conn.saveData ? 1 : 0;
|
|
1714
|
-
}
|
|
1715
|
-
}
|
|
1716
|
-
catch {
|
|
1717
|
-
// ignore
|
|
1718
|
-
}
|
|
2569
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1719
2570
|
}
|
|
1720
|
-
return out;
|
|
1721
2571
|
}
|
|
1722
|
-
function
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
const
|
|
1727
|
-
if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
|
|
1728
|
-
return out;
|
|
2572
|
+
function writeUvMeta(key, meta) {
|
|
2573
|
+
writeStringStorage(key, JSON.stringify(meta));
|
|
2574
|
+
}
|
|
2575
|
+
function getMiniProgramPagePath() {
|
|
2576
|
+
const g = globalThis;
|
|
1729
2577
|
try {
|
|
1730
|
-
const
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
2578
|
+
const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
|
|
2579
|
+
const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
|
|
2580
|
+
const route = (last?.route || last?.__route__);
|
|
2581
|
+
if (typeof route !== 'string')
|
|
2582
|
+
return '';
|
|
2583
|
+
let path = route.startsWith('/') ? route : `/${route}`;
|
|
2584
|
+
const options = last?.options || {};
|
|
2585
|
+
const keys = Object.keys(options);
|
|
2586
|
+
if (keys.length > 0) {
|
|
2587
|
+
const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
|
|
2588
|
+
path = `${path}?${qs}`;
|
|
2589
|
+
}
|
|
2590
|
+
return path;
|
|
1741
2591
|
}
|
|
1742
2592
|
catch {
|
|
1743
|
-
|
|
1744
|
-
}
|
|
1745
|
-
if (options.includeNetworkType) {
|
|
1746
|
-
try {
|
|
1747
|
-
if (typeof wxAny.getNetworkTypeSync === 'function') {
|
|
1748
|
-
const n = wxAny.getNetworkTypeSync();
|
|
1749
|
-
out.networkType = n?.networkType ? String(n.networkType) : '';
|
|
1750
|
-
}
|
|
1751
|
-
else if (typeof wxAny.getNetworkType === 'function') {
|
|
1752
|
-
// 异步更新:先不阻塞初始化
|
|
1753
|
-
wxAny.getNetworkType({
|
|
1754
|
-
success: (res) => {
|
|
1755
|
-
try {
|
|
1756
|
-
const g = globalThis;
|
|
1757
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1758
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1759
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1760
|
-
}
|
|
1761
|
-
catch {
|
|
1762
|
-
// ignore
|
|
1763
|
-
}
|
|
1764
|
-
},
|
|
1765
|
-
});
|
|
1766
|
-
}
|
|
1767
|
-
}
|
|
1768
|
-
catch {
|
|
1769
|
-
// ignore
|
|
1770
|
-
}
|
|
1771
|
-
try {
|
|
1772
|
-
if (typeof wxAny.onNetworkStatusChange === 'function') {
|
|
1773
|
-
wxAny.onNetworkStatusChange((res) => {
|
|
1774
|
-
try {
|
|
1775
|
-
const g = globalThis;
|
|
1776
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1777
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1778
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1779
|
-
}
|
|
1780
|
-
catch {
|
|
1781
|
-
// ignore
|
|
1782
|
-
}
|
|
1783
|
-
});
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
catch {
|
|
1787
|
-
// ignore
|
|
1788
|
-
}
|
|
2593
|
+
return '';
|
|
1789
2594
|
}
|
|
1790
|
-
return out;
|
|
1791
2595
|
}
|
|
1792
|
-
function
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
includeUserAgent: raw.includeUserAgent ?? true,
|
|
1799
|
-
includeNetwork: raw.includeNetwork ?? true,
|
|
1800
|
-
includeNetworkType: raw.includeNetworkType ?? true,
|
|
2596
|
+
function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
|
|
2597
|
+
return {
|
|
2598
|
+
uvId,
|
|
2599
|
+
isFirstVisit,
|
|
2600
|
+
firstVisitTs: uvMeta.firstVisitTs,
|
|
2601
|
+
visitCount: uvMeta.visitCount,
|
|
1801
2602
|
};
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
2603
|
+
}
|
|
2604
|
+
function truncateText(s, maxLen) {
|
|
2605
|
+
if (!s)
|
|
2606
|
+
return '';
|
|
2607
|
+
if (s.length <= maxLen)
|
|
2608
|
+
return s;
|
|
2609
|
+
return s.slice(0, maxLen);
|
|
2610
|
+
}
|
|
2611
|
+
function installMiniBehaviorMonitor(report, options = {}) {
|
|
2612
|
+
const enableTrack = options.enableTrack ?? options.enabled ?? true;
|
|
2613
|
+
if (!enableTrack)
|
|
2614
|
+
return () => { };
|
|
2615
|
+
const pvEnabled = options.pv ?? true;
|
|
2616
|
+
const uvEnabled = options.uv ?? true;
|
|
2617
|
+
const clickEnabled = options.click ?? true;
|
|
2618
|
+
const pvReportType = options.pvReportType ?? 'pv';
|
|
2619
|
+
const uvReportType = options.uvReportType ?? 'uv';
|
|
2620
|
+
const clickReportType = options.clickReportType ?? 'click';
|
|
2621
|
+
const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
|
|
2622
|
+
const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
|
|
2623
|
+
const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
|
|
2624
|
+
const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
|
|
2625
|
+
const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
|
|
2626
|
+
const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
|
|
2627
|
+
const clickWhiteList = (options.trackOptions?.clickWhiteList ??
|
|
2628
|
+
options.clickWhiteList ?? ['view', 'scroll-view']).map((s) => String(s).toLowerCase());
|
|
2629
|
+
const clickMaxTextLength = options.clickMaxTextLength ?? 120;
|
|
2630
|
+
const getPagePath = options.getPagePath ?? getMiniProgramPagePath;
|
|
2631
|
+
let destroyed = false;
|
|
2632
|
+
let firstVisitFlag = false;
|
|
2633
|
+
let firstVisitConsumed = false;
|
|
2634
|
+
const uvStatePromise = (async () => {
|
|
2635
|
+
let existingUvId = readStringStorage(uvIdStorageKey);
|
|
2636
|
+
let isFirstVisit = false;
|
|
2637
|
+
const now = Date.now();
|
|
2638
|
+
const metaBefore = safeReadUvMeta(uvMetaStorageKey);
|
|
2639
|
+
const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
|
|
2640
|
+
const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
|
|
2641
|
+
if (expired) {
|
|
2642
|
+
existingUvId = null;
|
|
2643
|
+
writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
2644
|
+
writeStringStorage(uvIdStorageKey, '');
|
|
2645
|
+
}
|
|
2646
|
+
try {
|
|
2647
|
+
if (options.getUvId) {
|
|
2648
|
+
const maybe = options.getUvId();
|
|
2649
|
+
const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
|
|
2650
|
+
if (resolved && typeof resolved === 'string')
|
|
2651
|
+
existingUvId = resolved;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
catch {
|
|
2655
|
+
/* ignore */
|
|
2656
|
+
}
|
|
2657
|
+
if (!existingUvId) {
|
|
2658
|
+
const wxAny = globalThis.wx;
|
|
1811
2659
|
try {
|
|
1812
|
-
const
|
|
1813
|
-
if (
|
|
1814
|
-
|
|
2660
|
+
const userInfo = wxAny?.getStorageSync?.('userInfo');
|
|
2661
|
+
if (userInfo?.openid)
|
|
2662
|
+
existingUvId = String(userInfo.openid);
|
|
1815
2663
|
}
|
|
1816
2664
|
catch {
|
|
1817
|
-
|
|
2665
|
+
/* ignore */
|
|
2666
|
+
}
|
|
2667
|
+
if (!existingUvId) {
|
|
2668
|
+
try {
|
|
2669
|
+
const sys = wxAny?.getSystemInfoSync?.();
|
|
2670
|
+
const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
|
|
2671
|
+
const model = sys?.model ? String(sys.model) : '';
|
|
2672
|
+
const system = sys?.system ? String(sys.system) : '';
|
|
2673
|
+
const base = [deviceId || model, system].filter(Boolean).join('_');
|
|
2674
|
+
if (base)
|
|
2675
|
+
existingUvId = `${base}_${Date.now()}`;
|
|
2676
|
+
}
|
|
2677
|
+
catch {
|
|
2678
|
+
/* ignore */
|
|
2679
|
+
}
|
|
1818
2680
|
}
|
|
1819
2681
|
}
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
if (extra && isPlainObject(extra))
|
|
1824
|
-
return { ...base, ...extra };
|
|
2682
|
+
if (!existingUvId) {
|
|
2683
|
+
existingUvId = generateUUID();
|
|
2684
|
+
isFirstVisit = true;
|
|
1825
2685
|
}
|
|
1826
|
-
|
|
1827
|
-
|
|
2686
|
+
writeStringStorage(uvIdStorageKey, existingUvId);
|
|
2687
|
+
const meta = safeReadUvMeta(uvMetaStorageKey);
|
|
2688
|
+
const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
|
|
2689
|
+
const firstVisit = meta.firstVisitTs || now;
|
|
2690
|
+
const nextMeta = {
|
|
2691
|
+
firstVisitTs: firstVisit,
|
|
2692
|
+
visitCount: (meta.visitCount || 0) + 1,
|
|
2693
|
+
createdAtTs: createdAt,
|
|
2694
|
+
lastSeenTs: now,
|
|
2695
|
+
};
|
|
2696
|
+
if (isFirstVisit) {
|
|
2697
|
+
nextMeta.firstVisitTs = now;
|
|
2698
|
+
nextMeta.createdAtTs = now;
|
|
1828
2699
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
2700
|
+
writeUvMeta(uvMetaStorageKey, nextMeta);
|
|
2701
|
+
firstVisitFlag = isFirstVisit;
|
|
2702
|
+
return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
|
|
2703
|
+
})();
|
|
2704
|
+
function safeReport(type, data) {
|
|
2705
|
+
if (destroyed)
|
|
2706
|
+
return;
|
|
2707
|
+
if (!shouldSample(options.sampleRate))
|
|
2708
|
+
return;
|
|
2709
|
+
report(type, data);
|
|
2710
|
+
}
|
|
2711
|
+
function buildUvFieldsOnce(uvId, meta) {
|
|
2712
|
+
const once = firstVisitFlag && !firstVisitConsumed;
|
|
2713
|
+
if (once)
|
|
2714
|
+
firstVisitConsumed = true;
|
|
2715
|
+
return buildCommonUvFields(uvId, meta, once);
|
|
2716
|
+
}
|
|
2717
|
+
function reportPv(pagePath) {
|
|
2718
|
+
if (!pvEnabled)
|
|
2719
|
+
return;
|
|
2720
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
2721
|
+
if (destroyed)
|
|
2722
|
+
return;
|
|
2723
|
+
const payload = {
|
|
2724
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
2725
|
+
timestamp: Date.now(),
|
|
2726
|
+
pagePath,
|
|
2727
|
+
referrer: readStringStorage(lastPagePathStorageKey) || '',
|
|
2728
|
+
};
|
|
2729
|
+
writeStringStorage(lastPagePathStorageKey, pagePath);
|
|
2730
|
+
safeReport(pvReportType, payload);
|
|
2731
|
+
});
|
|
2732
|
+
}
|
|
2733
|
+
// MiniProgram Page Patch
|
|
2734
|
+
let restoreMiniProgramPatch = null;
|
|
1834
2735
|
const g = globalThis;
|
|
1835
|
-
const
|
|
1836
|
-
g
|
|
2736
|
+
const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
|
|
2737
|
+
if (!g[patchedKey]) {
|
|
2738
|
+
g[patchedKey] = true;
|
|
2739
|
+
const originalPage = typeof g.Page === 'function' ? g.Page : null;
|
|
2740
|
+
if (originalPage) {
|
|
2741
|
+
g.Page = function patchedPage(conf) {
|
|
2742
|
+
const originalOnShow = conf?.onShow;
|
|
2743
|
+
conf.onShow = function (...args) {
|
|
2744
|
+
if (pvEnabled) {
|
|
2745
|
+
const pagePath = getPagePath();
|
|
2746
|
+
if (pagePath?.length > 0)
|
|
2747
|
+
reportPv(pagePath);
|
|
2748
|
+
}
|
|
2749
|
+
return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
|
|
2750
|
+
};
|
|
2751
|
+
if (clickEnabled && conf && typeof conf === 'object') {
|
|
2752
|
+
for (const key of Object.keys(conf)) {
|
|
2753
|
+
const fn = conf[key];
|
|
2754
|
+
if (typeof fn !== 'function')
|
|
2755
|
+
continue;
|
|
2756
|
+
if (fn.__beLinkWrapped__)
|
|
2757
|
+
continue;
|
|
2758
|
+
conf[key] = function (...args) {
|
|
2759
|
+
try {
|
|
2760
|
+
const e = args?.[0];
|
|
2761
|
+
const type = e?.type;
|
|
2762
|
+
const currentTarget = e?.currentTarget;
|
|
2763
|
+
const dataset = currentTarget?.dataset;
|
|
2764
|
+
const isTap = type === 'tap' || type === 'click';
|
|
2765
|
+
if (isTap && currentTarget && dataset) {
|
|
2766
|
+
const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
|
|
2767
|
+
const tagName = String(tagNameRaw || '').toLowerCase();
|
|
2768
|
+
const trackId = dataset?.trackId ? String(dataset.trackId) : '';
|
|
2769
|
+
if (!(clickWhiteList.includes(tagName) && !trackId)) {
|
|
2770
|
+
const x = typeof e?.detail?.x === 'number' ? e.detail.x : (e?.touches?.[0]?.pageX ?? 0);
|
|
2771
|
+
const y = typeof e?.detail?.y === 'number' ? e.detail.y : (e?.touches?.[0]?.pageY ?? 0);
|
|
2772
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
2773
|
+
if (destroyed)
|
|
2774
|
+
return;
|
|
2775
|
+
safeReport(clickReportType, {
|
|
2776
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
2777
|
+
timestamp: Date.now(),
|
|
2778
|
+
pagePath: getPagePath(),
|
|
2779
|
+
elementTag: tagNameRaw ? String(tagNameRaw) : '',
|
|
2780
|
+
elementId: currentTarget?.id ? String(currentTarget.id) : '',
|
|
2781
|
+
elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
|
|
2782
|
+
trackId,
|
|
2783
|
+
elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
|
|
2784
|
+
clickX: x,
|
|
2785
|
+
clickY: y,
|
|
2786
|
+
});
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
catch {
|
|
2792
|
+
/* ignore */
|
|
2793
|
+
}
|
|
2794
|
+
return fn.apply(this, args);
|
|
2795
|
+
};
|
|
2796
|
+
conf[key].__beLinkWrapped__ = true;
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
return originalPage(conf);
|
|
2800
|
+
};
|
|
2801
|
+
restoreMiniProgramPatch = () => {
|
|
2802
|
+
g.Page = originalPage;
|
|
2803
|
+
g[patchedKey] = false;
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
if (pvEnabled)
|
|
2808
|
+
reportPv(getPagePath());
|
|
2809
|
+
if (uvEnabled) {
|
|
2810
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
2811
|
+
if (destroyed)
|
|
2812
|
+
return;
|
|
2813
|
+
safeReport(uvReportType, {
|
|
2814
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
2815
|
+
timestamp: Date.now(),
|
|
2816
|
+
pagePath: getPagePath(),
|
|
2817
|
+
});
|
|
2818
|
+
});
|
|
2819
|
+
}
|
|
1837
2820
|
return () => {
|
|
1838
|
-
|
|
1839
|
-
|
|
2821
|
+
destroyed = true;
|
|
2822
|
+
restoreMiniProgramPatch?.();
|
|
1840
2823
|
};
|
|
1841
2824
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
this.endpoint = 'ap-shanghai.cls.tencentcs.com';
|
|
1847
|
-
this.retryTimes = 10;
|
|
1848
|
-
this.source = '127.0.0.1';
|
|
1849
|
-
this.projectId = '';
|
|
1850
|
-
this.projectName = '';
|
|
1851
|
-
this.appId = '';
|
|
1852
|
-
this.appVersion = '';
|
|
1853
|
-
this.envType = 'browser';
|
|
1854
|
-
this.userGenerateBaseFields = null;
|
|
1855
|
-
this.autoGenerateBaseFields = null;
|
|
1856
|
-
this.storageKey = 'beLink_logs';
|
|
1857
|
-
this.batchSize = 15;
|
|
1858
|
-
// 参考文档:内存队列批量发送(500ms 或 20 条触发)
|
|
1859
|
-
this.memoryQueue = [];
|
|
1860
|
-
this.batchMaxSize = 20;
|
|
1861
|
-
this.batchIntervalMs = 500;
|
|
1862
|
-
this.batchTimer = null;
|
|
1863
|
-
this.batchTimerDueAt = null;
|
|
1864
|
-
this.initTs = 0;
|
|
1865
|
-
this.startupDelayMs = 0;
|
|
1866
|
-
// 参考文档:失败缓存 + 重试
|
|
1867
|
-
this.failedCacheKey = 'cls_failed_logs';
|
|
1868
|
-
this.failedCacheMax = 200;
|
|
1869
|
-
this.requestMonitorStarted = false;
|
|
1870
|
-
this.errorMonitorStarted = false;
|
|
1871
|
-
this.performanceMonitorStarted = false;
|
|
1872
|
-
this.behaviorMonitorStarted = false;
|
|
1873
|
-
this.behaviorMonitorCleanup = null;
|
|
2825
|
+
|
|
2826
|
+
function installBehaviorMonitor(report, envType, options = {}) {
|
|
2827
|
+
if (envType === 'miniprogram' || isMiniProgramEnv()) {
|
|
2828
|
+
return installMiniBehaviorMonitor(report, options);
|
|
1874
2829
|
}
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
this.envType = options.envType ?? this.detectEnvType();
|
|
1897
|
-
this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
|
|
1898
|
-
this.autoGenerateBaseFields = createAutoDeviceInfoBaseFields(this.envType, options.deviceInfo);
|
|
1899
|
-
this.storageKey = options.storageKey ?? this.storageKey;
|
|
1900
|
-
this.batchSize = options.batchSize ?? this.batchSize;
|
|
1901
|
-
this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
|
|
1902
|
-
this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
|
|
1903
|
-
this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
|
|
1904
|
-
this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
|
|
1905
|
-
this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
|
|
1906
|
-
// 预热 client
|
|
1907
|
-
this.getInstance();
|
|
1908
|
-
// 启动时尝试发送失败缓存
|
|
1909
|
-
this.flushFailed();
|
|
1910
|
-
// 初始化后立即启动请求监听
|
|
1911
|
-
this.startRequestMonitor(options.requestMonitor);
|
|
1912
|
-
// 初始化后立即启动错误监控/性能监控
|
|
1913
|
-
this.startErrorMonitor(options.errorMonitor);
|
|
1914
|
-
this.startPerformanceMonitor(options.performanceMonitor);
|
|
1915
|
-
// 初始化后立即启动行为埋点(PV/UV/点击)
|
|
1916
|
-
this.startBehaviorMonitor(options.behaviorMonitor);
|
|
2830
|
+
return installWebBehaviorMonitor(report, options);
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
function truncate(s, maxLen) {
|
|
2834
|
+
if (!s)
|
|
2835
|
+
return s;
|
|
2836
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
2837
|
+
}
|
|
2838
|
+
function parseUserAgent(uaRaw) {
|
|
2839
|
+
const ua = uaRaw ?? '';
|
|
2840
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
|
|
2841
|
+
// OS
|
|
2842
|
+
let osName = 'unknown';
|
|
2843
|
+
let osVersion = '';
|
|
2844
|
+
const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
|
|
2845
|
+
const android = ua.match(/Android (\d+(\.\d+)*)/i);
|
|
2846
|
+
const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
|
|
2847
|
+
const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
|
|
2848
|
+
if (ios) {
|
|
2849
|
+
osName = 'iOS';
|
|
2850
|
+
osVersion = ios[1].replace(/_/g, '.');
|
|
1917
2851
|
}
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
try {
|
|
1922
|
-
const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
|
|
1923
|
-
if (autoRaw && isPlainObject(autoRaw))
|
|
1924
|
-
auto = normalizeFlatFields(autoRaw, 'deviceInfo');
|
|
1925
|
-
}
|
|
1926
|
-
catch {
|
|
1927
|
-
auto = undefined;
|
|
1928
|
-
}
|
|
1929
|
-
try {
|
|
1930
|
-
const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
|
|
1931
|
-
if (userRaw && isPlainObject(userRaw))
|
|
1932
|
-
user = normalizeFlatFields({ ...userRaw, userId: this.userId, userName: this.userName }, 'generateBaseFields');
|
|
1933
|
-
}
|
|
1934
|
-
catch {
|
|
1935
|
-
user = undefined;
|
|
1936
|
-
}
|
|
1937
|
-
if (auto && user)
|
|
1938
|
-
return mergeFields(user, auto);
|
|
1939
|
-
if (user)
|
|
1940
|
-
return user;
|
|
1941
|
-
if (auto)
|
|
1942
|
-
return auto;
|
|
1943
|
-
return undefined;
|
|
2852
|
+
else if (android) {
|
|
2853
|
+
osName = 'Android';
|
|
2854
|
+
osVersion = android[1];
|
|
1944
2855
|
}
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
2856
|
+
else if (win) {
|
|
2857
|
+
osName = 'Windows';
|
|
2858
|
+
osVersion = win[1];
|
|
2859
|
+
}
|
|
2860
|
+
else if (mac) {
|
|
2861
|
+
osName = 'macOS';
|
|
2862
|
+
osVersion = mac[1].replace(/_/g, '.');
|
|
2863
|
+
}
|
|
2864
|
+
// Browser
|
|
2865
|
+
let browserName = 'unknown';
|
|
2866
|
+
let browserVersion = '';
|
|
2867
|
+
const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
|
|
2868
|
+
const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
|
|
2869
|
+
const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
|
|
2870
|
+
const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
|
|
2871
|
+
if (edge) {
|
|
2872
|
+
browserName = 'Edge';
|
|
2873
|
+
browserVersion = edge[1];
|
|
1961
2874
|
}
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
const enabled = errorMonitor === undefined ? true : !!errorMonitor;
|
|
1966
|
-
if (!enabled)
|
|
1967
|
-
return;
|
|
1968
|
-
this.errorMonitorStarted = true;
|
|
1969
|
-
installErrorMonitor((type, data) => this.track(type, data), errorMonitor);
|
|
2875
|
+
else if (chrome) {
|
|
2876
|
+
browserName = 'Chrome';
|
|
2877
|
+
browserVersion = chrome[1];
|
|
1970
2878
|
}
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
|
|
1975
|
-
if (!enabled)
|
|
1976
|
-
return;
|
|
1977
|
-
this.performanceMonitorStarted = true;
|
|
1978
|
-
installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor);
|
|
2879
|
+
else if (firefox) {
|
|
2880
|
+
browserName = 'Firefox';
|
|
2881
|
+
browserVersion = firefox[1];
|
|
1979
2882
|
}
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
|
|
1984
|
-
if (!enabled)
|
|
1985
|
-
return;
|
|
1986
|
-
const opts = typeof behaviorMonitor === 'object' && behaviorMonitor
|
|
1987
|
-
? behaviorMonitor
|
|
1988
|
-
: {};
|
|
1989
|
-
this.behaviorMonitorStarted = true;
|
|
1990
|
-
this.behaviorMonitorCleanup = installBehaviorMonitor((type, data) => {
|
|
1991
|
-
this.track(type, data);
|
|
1992
|
-
}, this.envType, {
|
|
1993
|
-
...opts,
|
|
1994
|
-
enabled: opts.enabled ?? true,
|
|
1995
|
-
});
|
|
2883
|
+
else if (safari) {
|
|
2884
|
+
browserName = 'Safari';
|
|
2885
|
+
browserVersion = safari[1];
|
|
1996
2886
|
}
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2887
|
+
return { browserName, browserVersion, osName, osVersion, isMobile };
|
|
2888
|
+
}
|
|
2889
|
+
function getBrowserDeviceInfo(options) {
|
|
2890
|
+
const out = {
|
|
2891
|
+
envType: 'browser',
|
|
2892
|
+
};
|
|
2893
|
+
if (typeof window === 'undefined' || typeof navigator === 'undefined')
|
|
2894
|
+
return out;
|
|
2895
|
+
const ua = String(navigator.userAgent ?? '');
|
|
2896
|
+
const uaParsed = parseUserAgent(ua);
|
|
2897
|
+
if (options.includeUserAgent)
|
|
2898
|
+
out.ua = truncate(ua, 2000);
|
|
2899
|
+
out.browserName = uaParsed.browserName;
|
|
2900
|
+
out.browserVersion = uaParsed.browserVersion;
|
|
2901
|
+
out.osName = uaParsed.osName;
|
|
2902
|
+
out.osVersion = uaParsed.osVersion;
|
|
2903
|
+
out.isMobile = uaParsed.isMobile ? 1 : 0;
|
|
2904
|
+
out.language = String(navigator.language ?? '');
|
|
2905
|
+
out.platform = String(navigator.platform ?? '');
|
|
2906
|
+
try {
|
|
2907
|
+
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
2908
|
+
out.timezone = typeof tz === 'string' ? tz : '';
|
|
2010
2909
|
}
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
return this.client;
|
|
2014
|
-
this.client = new tencentcloudClsSdkJsWeb.AsyncClient({
|
|
2015
|
-
endpoint: this.endpoint,
|
|
2016
|
-
retry_times: this.retryTimes,
|
|
2017
|
-
});
|
|
2018
|
-
return this.client;
|
|
2910
|
+
catch {
|
|
2911
|
+
out.timezone = '';
|
|
2019
2912
|
}
|
|
2020
|
-
|
|
2021
|
-
const
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
return 'browser';
|
|
2913
|
+
try {
|
|
2914
|
+
const s = window.screen;
|
|
2915
|
+
out.screenWidth = s?.width ?? undefined;
|
|
2916
|
+
out.screenHeight = s?.height ?? undefined;
|
|
2025
2917
|
}
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
* - 非原始值(对象/数组等)会被自动 stringify 成 string
|
|
2029
|
-
* - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
|
|
2030
|
-
*/
|
|
2031
|
-
put(fields, options = {}) {
|
|
2032
|
-
if (!fields)
|
|
2033
|
-
return;
|
|
2034
|
-
if (!this.topicId) {
|
|
2035
|
-
// eslint-disable-next-line no-console
|
|
2036
|
-
console.warn('ClsLogger.put:未初始化 topic_id');
|
|
2037
|
-
return;
|
|
2038
|
-
}
|
|
2039
|
-
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
2040
|
-
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
2041
|
-
const normalizedFields = normalizeFlatFields(fields, 'put');
|
|
2042
|
-
const finalFields = mergeFields(base, {
|
|
2043
|
-
projectId: this.projectId || undefined,
|
|
2044
|
-
projectName: this.projectName || undefined,
|
|
2045
|
-
envType: this.envType,
|
|
2046
|
-
appId: this.appId || undefined,
|
|
2047
|
-
appVersion: this.appVersion || undefined,
|
|
2048
|
-
...normalizedFields,
|
|
2049
|
-
});
|
|
2050
|
-
const client = this.getInstance();
|
|
2051
|
-
const logGroup = new tencentcloudClsSdkJsWeb.LogGroup('127.0.0.1');
|
|
2052
|
-
logGroup.setSource(this.source);
|
|
2053
|
-
const log = new tencentcloudClsSdkJsWeb.Log(Date.now());
|
|
2054
|
-
for (const key of Object.keys(finalFields)) {
|
|
2055
|
-
log.addContent(key, stringifyLogValue(finalFields[key]));
|
|
2056
|
-
}
|
|
2057
|
-
logGroup.addLog(log);
|
|
2058
|
-
const request = new tencentcloudClsSdkJsWeb.PutLogsRequest(this.topicId, logGroup);
|
|
2059
|
-
const exit = enterClsSendingGuard();
|
|
2060
|
-
try {
|
|
2061
|
-
client.PutLogs(request);
|
|
2062
|
-
}
|
|
2063
|
-
finally {
|
|
2064
|
-
exit();
|
|
2065
|
-
}
|
|
2918
|
+
catch {
|
|
2919
|
+
// ignore
|
|
2066
2920
|
}
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
*/
|
|
2070
|
-
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
2071
|
-
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
2072
|
-
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
2921
|
+
try {
|
|
2922
|
+
out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
|
|
2073
2923
|
}
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
* - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
|
|
2077
|
-
*/
|
|
2078
|
-
enqueue(fields, options = {}) {
|
|
2079
|
-
if (!fields)
|
|
2080
|
-
return;
|
|
2081
|
-
const time = Date.now();
|
|
2082
|
-
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
2083
|
-
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
2084
|
-
const normalizedFields = normalizeFlatFields(fields, 'enqueue');
|
|
2085
|
-
const finalFields = mergeFields(base, {
|
|
2086
|
-
projectId: this.projectId || undefined,
|
|
2087
|
-
projectName: this.projectName || undefined,
|
|
2088
|
-
envType: this.envType,
|
|
2089
|
-
appId: this.appId || undefined,
|
|
2090
|
-
appVersion: this.appVersion || undefined,
|
|
2091
|
-
...normalizedFields,
|
|
2092
|
-
});
|
|
2093
|
-
const queue = readQueue(this.storageKey);
|
|
2094
|
-
const next = [...queue, { time, data: finalFields }];
|
|
2095
|
-
if (next.length < this.batchSize) {
|
|
2096
|
-
writeQueue(this.storageKey, next);
|
|
2097
|
-
return;
|
|
2098
|
-
}
|
|
2099
|
-
// 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
|
|
2100
|
-
this.putBatch(queue);
|
|
2101
|
-
writeQueue(this.storageKey, [{ time, data: finalFields }]);
|
|
2924
|
+
catch {
|
|
2925
|
+
// ignore
|
|
2102
2926
|
}
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
const queue = readQueue(this.storageKey);
|
|
2108
|
-
if (queue.length === 0)
|
|
2109
|
-
return;
|
|
2110
|
-
this.putBatch(queue);
|
|
2111
|
-
writeQueue(this.storageKey, []);
|
|
2927
|
+
try {
|
|
2928
|
+
const navAny = navigator;
|
|
2929
|
+
out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
|
|
2930
|
+
out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
|
|
2112
2931
|
}
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
if (!queue || queue.length === 0)
|
|
2118
|
-
return;
|
|
2119
|
-
if (!this.topicId) {
|
|
2120
|
-
// eslint-disable-next-line no-console
|
|
2121
|
-
console.warn('ClsLogger.putBatch:未初始化 topic_id');
|
|
2122
|
-
return;
|
|
2123
|
-
}
|
|
2124
|
-
const client = this.getInstance();
|
|
2125
|
-
const logGroup = new tencentcloudClsSdkJsWeb.LogGroup('127.0.0.1');
|
|
2126
|
-
logGroup.setSource(this.source);
|
|
2127
|
-
for (const item of queue) {
|
|
2128
|
-
const log = new tencentcloudClsSdkJsWeb.Log(item.time);
|
|
2129
|
-
const data = item.data ?? {};
|
|
2130
|
-
for (const key of Object.keys(data)) {
|
|
2131
|
-
log.addContent(key, stringifyLogValue(data[key]));
|
|
2132
|
-
}
|
|
2133
|
-
logGroup.addLog(log);
|
|
2134
|
-
}
|
|
2135
|
-
if (logGroup.getLogs().length === 0)
|
|
2136
|
-
return;
|
|
2137
|
-
const request = new tencentcloudClsSdkJsWeb.PutLogsRequest(this.topicId, logGroup);
|
|
2138
|
-
const exit = enterClsSendingGuard();
|
|
2932
|
+
catch {
|
|
2933
|
+
// ignore
|
|
2934
|
+
}
|
|
2935
|
+
if (options.includeNetwork) {
|
|
2139
2936
|
try {
|
|
2140
|
-
|
|
2937
|
+
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
|
|
2938
|
+
if (conn && isPlainObject(conn)) {
|
|
2939
|
+
if (typeof conn.effectiveType === 'string')
|
|
2940
|
+
out.netEffectiveType = conn.effectiveType;
|
|
2941
|
+
if (typeof conn.downlink === 'number')
|
|
2942
|
+
out.netDownlink = conn.downlink;
|
|
2943
|
+
if (typeof conn.rtt === 'number')
|
|
2944
|
+
out.netRtt = conn.rtt;
|
|
2945
|
+
if (typeof conn.saveData === 'boolean')
|
|
2946
|
+
out.netSaveData = conn.saveData ? 1 : 0;
|
|
2947
|
+
}
|
|
2141
2948
|
}
|
|
2142
|
-
|
|
2143
|
-
|
|
2949
|
+
catch {
|
|
2950
|
+
// ignore
|
|
2144
2951
|
}
|
|
2145
2952
|
}
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
|
|
2164
|
-
const desiredDelay = Math.max(0, desiredDueAt - now);
|
|
2165
|
-
if (!this.batchTimer) {
|
|
2166
|
-
this.batchTimerDueAt = desiredDueAt;
|
|
2167
|
-
this.batchTimer = setTimeout(() => {
|
|
2168
|
-
void this.flushBatch();
|
|
2169
|
-
}, desiredDelay);
|
|
2170
|
-
return;
|
|
2171
|
-
}
|
|
2172
|
-
// 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
|
|
2173
|
-
if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
|
|
2953
|
+
return out;
|
|
2954
|
+
}
|
|
2955
|
+
function createWebDeviceInfoBaseFields(opts) {
|
|
2956
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
2957
|
+
if (!enabled)
|
|
2958
|
+
return null;
|
|
2959
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
2960
|
+
const options = {
|
|
2961
|
+
includeUserAgent: raw.includeUserAgent ?? true,
|
|
2962
|
+
includeNetwork: raw.includeNetwork ?? true,
|
|
2963
|
+
includeNetworkType: raw.includeNetworkType ?? true,
|
|
2964
|
+
};
|
|
2965
|
+
let base = null;
|
|
2966
|
+
const globalKey = '__beLinkClsLoggerDeviceInfo__';
|
|
2967
|
+
return () => {
|
|
2968
|
+
if (!base) {
|
|
2969
|
+
base = getBrowserDeviceInfo(options);
|
|
2174
2970
|
try {
|
|
2175
|
-
|
|
2971
|
+
const g = globalThis;
|
|
2972
|
+
if (!g[globalKey])
|
|
2973
|
+
g[globalKey] = { ...base };
|
|
2176
2974
|
}
|
|
2177
2975
|
catch {
|
|
2178
2976
|
// ignore
|
|
2179
2977
|
}
|
|
2180
|
-
this.batchTimerDueAt = desiredDueAt;
|
|
2181
|
-
this.batchTimer = setTimeout(() => {
|
|
2182
|
-
void this.flushBatch();
|
|
2183
|
-
}, desiredDelay);
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
getDesiredBatchFlushDueAt(nowTs) {
|
|
2187
|
-
const start = this.initTs || nowTs;
|
|
2188
|
-
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
2189
|
-
if (startupDelay > 0) {
|
|
2190
|
-
const end = start + startupDelay;
|
|
2191
|
-
if (nowTs < end)
|
|
2192
|
-
return end;
|
|
2193
|
-
}
|
|
2194
|
-
return nowTs + this.batchIntervalMs;
|
|
2195
|
-
}
|
|
2196
|
-
info(message, data = {}) {
|
|
2197
|
-
const payload = normalizeFlatFields({ message, ...data }, 'info');
|
|
2198
|
-
this.report({ type: 'info', data: payload, timestamp: Date.now() });
|
|
2199
|
-
}
|
|
2200
|
-
warn(message, data = {}) {
|
|
2201
|
-
const payload = normalizeFlatFields({ message, ...data }, 'warn');
|
|
2202
|
-
this.report({ type: 'warn', data: payload, timestamp: Date.now() });
|
|
2203
|
-
}
|
|
2204
|
-
error(message, data = {}) {
|
|
2205
|
-
const payload = normalizeFlatFields({ message, ...data }, 'error');
|
|
2206
|
-
this.report({ type: 'error', data: payload, timestamp: Date.now() });
|
|
2207
|
-
}
|
|
2208
|
-
track(trackType, data = {}) {
|
|
2209
|
-
if (!trackType)
|
|
2210
|
-
return;
|
|
2211
|
-
this.report({
|
|
2212
|
-
type: trackType,
|
|
2213
|
-
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
2214
|
-
timestamp: Date.now(),
|
|
2215
|
-
});
|
|
2216
|
-
}
|
|
2217
|
-
/**
|
|
2218
|
-
* 立即发送内存队列
|
|
2219
|
-
*/
|
|
2220
|
-
async flushBatch() {
|
|
2221
|
-
if (this.batchTimer) {
|
|
2222
|
-
clearTimeout(this.batchTimer);
|
|
2223
|
-
this.batchTimer = null;
|
|
2224
2978
|
}
|
|
2225
|
-
this.batchTimerDueAt = null;
|
|
2226
|
-
if (this.memoryQueue.length === 0)
|
|
2227
|
-
return;
|
|
2228
|
-
const logs = [...this.memoryQueue];
|
|
2229
|
-
this.memoryQueue = [];
|
|
2230
2979
|
try {
|
|
2231
|
-
|
|
2980
|
+
const g = globalThis;
|
|
2981
|
+
const extra = g[globalKey];
|
|
2982
|
+
if (extra && isPlainObject(extra))
|
|
2983
|
+
return { ...base, ...extra };
|
|
2232
2984
|
}
|
|
2233
2985
|
catch {
|
|
2234
|
-
|
|
2986
|
+
// ignore
|
|
2235
2987
|
}
|
|
2988
|
+
return base;
|
|
2989
|
+
};
|
|
2990
|
+
}
|
|
2991
|
+
|
|
2992
|
+
function getMiniProgramDeviceInfo(options) {
|
|
2993
|
+
const out = {
|
|
2994
|
+
envType: 'miniprogram',
|
|
2995
|
+
};
|
|
2996
|
+
const wxAny = globalThis.wx;
|
|
2997
|
+
if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
|
|
2998
|
+
return out;
|
|
2999
|
+
try {
|
|
3000
|
+
const sys = wxAny.getSystemInfoSync();
|
|
3001
|
+
out.mpBrand = sys?.brand ? String(sys.brand) : '';
|
|
3002
|
+
out.mpModel = sys?.model ? String(sys.model) : '';
|
|
3003
|
+
out.mpSystem = sys?.system ? String(sys.system) : '';
|
|
3004
|
+
out.mpPlatform = sys?.platform ? String(sys.platform) : '';
|
|
3005
|
+
out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
|
|
3006
|
+
out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
|
|
3007
|
+
out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
|
|
3008
|
+
out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
|
|
3009
|
+
out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
|
|
3010
|
+
out.language = sys?.language ? String(sys.language) : '';
|
|
2236
3011
|
}
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
const base = this.getBaseFields();
|
|
2240
|
-
const data = normalizeFlatFields(log.data ?? {}, 'report:data');
|
|
2241
|
-
const mergedData = mergeFields(base, data);
|
|
2242
|
-
return {
|
|
2243
|
-
timestamp: ts,
|
|
2244
|
-
type: log.type,
|
|
2245
|
-
envType: this.envType,
|
|
2246
|
-
projectId: this.projectId || undefined,
|
|
2247
|
-
projectName: this.projectName || undefined,
|
|
2248
|
-
appId: this.appId || undefined,
|
|
2249
|
-
appVersion: this.appVersion || undefined,
|
|
2250
|
-
// 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
|
|
2251
|
-
...mergedData,
|
|
2252
|
-
};
|
|
3012
|
+
catch {
|
|
3013
|
+
// ignore
|
|
2253
3014
|
}
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
3015
|
+
if (options.includeNetworkType) {
|
|
3016
|
+
try {
|
|
3017
|
+
if (typeof wxAny.getNetworkTypeSync === 'function') {
|
|
3018
|
+
const n = wxAny.getNetworkTypeSync();
|
|
3019
|
+
out.networkType = n?.networkType ? String(n.networkType) : '';
|
|
3020
|
+
}
|
|
3021
|
+
else if (typeof wxAny.getNetworkType === 'function') {
|
|
3022
|
+
// 异步更新:先不阻塞初始化
|
|
3023
|
+
wxAny.getNetworkType({
|
|
3024
|
+
success: (res) => {
|
|
3025
|
+
try {
|
|
3026
|
+
const g = globalThis;
|
|
3027
|
+
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
3028
|
+
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
3029
|
+
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
3030
|
+
}
|
|
3031
|
+
catch {
|
|
3032
|
+
// ignore
|
|
3033
|
+
}
|
|
3034
|
+
},
|
|
3035
|
+
});
|
|
2267
3036
|
}
|
|
2268
|
-
logGroup.addLog(log);
|
|
2269
3037
|
}
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
let p;
|
|
3038
|
+
catch {
|
|
3039
|
+
// ignore
|
|
3040
|
+
}
|
|
2274
3041
|
try {
|
|
2275
|
-
|
|
3042
|
+
if (typeof wxAny.onNetworkStatusChange === 'function') {
|
|
3043
|
+
wxAny.onNetworkStatusChange((res) => {
|
|
3044
|
+
try {
|
|
3045
|
+
const g = globalThis;
|
|
3046
|
+
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
3047
|
+
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
3048
|
+
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
3049
|
+
}
|
|
3050
|
+
catch {
|
|
3051
|
+
// ignore
|
|
3052
|
+
}
|
|
3053
|
+
});
|
|
3054
|
+
}
|
|
2276
3055
|
}
|
|
2277
|
-
|
|
2278
|
-
|
|
3056
|
+
catch {
|
|
3057
|
+
// ignore
|
|
2279
3058
|
}
|
|
2280
|
-
await p;
|
|
2281
3059
|
}
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
3060
|
+
return out;
|
|
3061
|
+
}
|
|
3062
|
+
function createMiniDeviceInfoBaseFields(opts) {
|
|
3063
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
3064
|
+
if (!enabled)
|
|
3065
|
+
return null;
|
|
3066
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
3067
|
+
const options = {
|
|
3068
|
+
includeUserAgent: raw.includeUserAgent ?? true,
|
|
3069
|
+
includeNetwork: raw.includeNetwork ?? true,
|
|
3070
|
+
includeNetworkType: raw.includeNetworkType ?? true,
|
|
3071
|
+
};
|
|
3072
|
+
let base = null;
|
|
3073
|
+
const globalKey = '__beLinkClsLoggerDeviceInfo__';
|
|
3074
|
+
return () => {
|
|
3075
|
+
if (!base) {
|
|
3076
|
+
base = getMiniProgramDeviceInfo(options);
|
|
2289
3077
|
try {
|
|
2290
|
-
|
|
3078
|
+
const g = globalThis;
|
|
3079
|
+
if (!g[globalKey])
|
|
3080
|
+
g[globalKey] = { ...base };
|
|
2291
3081
|
}
|
|
2292
3082
|
catch {
|
|
2293
|
-
|
|
3083
|
+
// ignore
|
|
2294
3084
|
}
|
|
2295
|
-
}
|
|
2296
|
-
}
|
|
2297
|
-
cacheFailedReportLogs(logs) {
|
|
2298
|
-
const raw = readStringStorage(this.failedCacheKey);
|
|
2299
|
-
let current = [];
|
|
3085
|
+
}
|
|
2300
3086
|
try {
|
|
2301
|
-
const
|
|
2302
|
-
|
|
3087
|
+
const g = globalThis;
|
|
3088
|
+
const extra = g[globalKey];
|
|
3089
|
+
if (extra && isPlainObject(extra))
|
|
3090
|
+
return { ...base, ...extra };
|
|
2303
3091
|
}
|
|
2304
3092
|
catch {
|
|
2305
|
-
|
|
3093
|
+
// ignore
|
|
2306
3094
|
}
|
|
2307
|
-
|
|
2308
|
-
|
|
3095
|
+
return base;
|
|
3096
|
+
};
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
function createAutoDeviceInfoBaseFields(envType, opts) {
|
|
3100
|
+
if (envType === 'miniprogram' || isMiniProgramEnv()) {
|
|
3101
|
+
return createMiniDeviceInfoBaseFields(opts);
|
|
2309
3102
|
}
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
3103
|
+
return createWebDeviceInfoBaseFields(opts);
|
|
3104
|
+
}
|
|
3105
|
+
|
|
3106
|
+
/**
|
|
3107
|
+
* 兼容版 ClsLogger(默认入口)
|
|
3108
|
+
* - 保留了自动识别环境 + 动态 import 的逻辑
|
|
3109
|
+
* - 如果业务想瘦身,建议改用 @be-link/cls-logger/web 或 /mini
|
|
3110
|
+
*/
|
|
3111
|
+
class ClsLogger extends ClsLoggerCore {
|
|
3112
|
+
async loadSdk() {
|
|
3113
|
+
if (this.sdk)
|
|
3114
|
+
return this.sdk;
|
|
3115
|
+
if (this.sdkPromise)
|
|
3116
|
+
return this.sdkPromise;
|
|
3117
|
+
const normalizeSdk = (m) => {
|
|
3118
|
+
const mod = (m?.default && m.default.AsyncClient ? m.default : m);
|
|
3119
|
+
if (mod?.AsyncClient && mod?.Log && mod?.LogGroup && mod?.PutLogsRequest) {
|
|
3120
|
+
return {
|
|
3121
|
+
AsyncClient: mod.AsyncClient,
|
|
3122
|
+
Log: mod.Log,
|
|
3123
|
+
LogGroup: mod.LogGroup,
|
|
3124
|
+
PutLogsRequest: mod.PutLogsRequest,
|
|
3125
|
+
};
|
|
3126
|
+
}
|
|
3127
|
+
return null;
|
|
3128
|
+
};
|
|
3129
|
+
// 1) 外部注入的 loader(最高优先级)
|
|
3130
|
+
if (this.sdkLoaderOverride) {
|
|
3131
|
+
try {
|
|
3132
|
+
const loaded = await this.sdkLoaderOverride();
|
|
3133
|
+
const sdk = normalizeSdk(loaded);
|
|
3134
|
+
if (sdk) {
|
|
3135
|
+
this.sdk = sdk;
|
|
3136
|
+
return sdk;
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
catch {
|
|
3140
|
+
// ignore and fallback
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
// 2) 外部直接注入的 sdk
|
|
3144
|
+
if (this.sdkOverride) {
|
|
3145
|
+
const sdk = normalizeSdk(this.sdkOverride);
|
|
3146
|
+
if (sdk) {
|
|
3147
|
+
this.sdk = sdk;
|
|
3148
|
+
return sdk;
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
const isMini = this.envType === 'miniprogram';
|
|
3152
|
+
// 3) 尝试使用 tryRequire / 全局变量
|
|
3153
|
+
if (isMini) {
|
|
3154
|
+
const reqMod = tryRequire('tencentcloud-cls-sdk-js-mini');
|
|
3155
|
+
const reqSdk = normalizeSdk(reqMod);
|
|
3156
|
+
if (reqSdk) {
|
|
3157
|
+
this.sdk = reqSdk;
|
|
3158
|
+
return reqSdk;
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
else {
|
|
3162
|
+
// Web: 优先读全局变量 (UMD)
|
|
3163
|
+
const g = readGlobal('tencentcloudClsSdkJsWeb');
|
|
3164
|
+
const sdk = normalizeSdk(g);
|
|
3165
|
+
if (sdk) {
|
|
3166
|
+
this.sdk = sdk;
|
|
3167
|
+
return sdk;
|
|
3168
|
+
}
|
|
3169
|
+
// Web: 尝试 require
|
|
3170
|
+
const reqMod = tryRequire('tencentcloud-cls-sdk-js-web');
|
|
3171
|
+
const reqSdk = normalizeSdk(reqMod);
|
|
3172
|
+
if (reqSdk) {
|
|
3173
|
+
this.sdk = reqSdk;
|
|
3174
|
+
return reqSdk;
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
// 4) 动态导入(兜底方案)
|
|
3178
|
+
// 注意:在某些严格的小程序 ESM 环境下,动态 import 可能失效
|
|
2315
3179
|
try {
|
|
2316
|
-
|
|
2317
|
-
|
|
3180
|
+
if (isMini) {
|
|
3181
|
+
const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-mini');
|
|
3182
|
+
const sdk = normalizeSdk(m);
|
|
3183
|
+
if (sdk) {
|
|
3184
|
+
this.sdk = sdk;
|
|
3185
|
+
return sdk;
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
else {
|
|
3189
|
+
const m = await import(/* @vite-ignore */ 'tencentcloud-cls-sdk-js-web');
|
|
3190
|
+
const sdk = normalizeSdk(m);
|
|
3191
|
+
if (sdk) {
|
|
3192
|
+
this.sdk = sdk;
|
|
3193
|
+
return sdk;
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
2318
3196
|
}
|
|
2319
3197
|
catch {
|
|
2320
|
-
|
|
3198
|
+
// ignore
|
|
2321
3199
|
}
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
writeStringStorage(this.failedCacheKey, JSON.stringify([]));
|
|
2326
|
-
this.memoryQueue.unshift(...logs);
|
|
2327
|
-
void this.flushBatch();
|
|
3200
|
+
// 5) 最终失败警告
|
|
3201
|
+
console.warn(`[ClsLogger] SDK "${isMini ? 'tencentcloud-cls-sdk-js-mini' : 'tencentcloud-cls-sdk-js-web'}" not found. Logging will be disabled.`);
|
|
3202
|
+
throw new Error('SDK not found');
|
|
2328
3203
|
}
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
this.
|
|
3204
|
+
installRequestMonitor(report, options) {
|
|
3205
|
+
installRequestMonitor(report, options);
|
|
3206
|
+
}
|
|
3207
|
+
installErrorMonitor(report, options) {
|
|
3208
|
+
installErrorMonitor(report, options);
|
|
3209
|
+
}
|
|
3210
|
+
installPerformanceMonitor(report, options) {
|
|
3211
|
+
installPerformanceMonitor(report, options);
|
|
3212
|
+
}
|
|
3213
|
+
installBehaviorMonitor(report, options) {
|
|
3214
|
+
return installBehaviorMonitor(report, this.envType, typeof options === 'boolean' ? {} : options);
|
|
3215
|
+
}
|
|
3216
|
+
createDeviceInfoBaseFields(options) {
|
|
3217
|
+
return createAutoDeviceInfoBaseFields(this.envType, options);
|
|
2343
3218
|
}
|
|
2344
3219
|
}
|
|
2345
3220
|
|