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