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