@be-link/cls-logger 1.0.7 → 1.0.8
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 +94 -76
- package/dist/ClsLogger.d.ts +6 -0
- package/dist/ClsLogger.d.ts.map +1 -1
- package/dist/ClsLoggerCore.d.ts +21 -1
- package/dist/ClsLoggerCore.d.ts.map +1 -1
- package/dist/behaviorMonitor.d.ts.map +1 -1
- package/dist/deviceInfo.d.ts.map +1 -1
- package/dist/errorMonitor.d.ts.map +1 -1
- package/dist/index.esm.js +2485 -2125
- package/dist/index.js +2485 -2125
- package/dist/index.umd.js +2485 -2125
- 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 +1 -1
- package/dist/mini.d.ts.map +1 -1
- package/dist/mini.esm.js +1427 -2217
- package/dist/mini.js +1427 -2217
- 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/types.d.ts +10 -0
- 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 +1 -1
- package/dist/web.d.ts.map +1 -1
- package/dist/web.esm.js +1586 -2194
- package/dist/web.js +1586 -2194
- package/package.json +1 -1
- package/dist/ClsLoggerMini.d.ts +0 -8
- package/dist/ClsLoggerMini.d.ts.map +0 -1
- package/dist/ClsLoggerWeb.d.ts +0 -8
- package/dist/ClsLoggerWeb.d.ts.map +0 -1
package/dist/web.js
CHANGED
|
@@ -156,2385 +156,1762 @@ function stringifyLogValue(v) {
|
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
|
|
160
|
-
function isClsSendingNow() {
|
|
159
|
+
function enterClsSendingGuard() {
|
|
161
160
|
const g = globalThis;
|
|
162
|
-
|
|
161
|
+
const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
|
|
162
|
+
g.__beLinkClsLoggerSendingCount__ = next;
|
|
163
|
+
return () => {
|
|
164
|
+
const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
|
|
165
|
+
g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
|
|
166
|
+
};
|
|
163
167
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
168
|
+
/**
|
|
169
|
+
* CLS Logger 核心基类
|
|
170
|
+
* - 负责所有上报、队列、监控逻辑
|
|
171
|
+
* - 不包含具体的 SDK 加载实现(由子类负责)
|
|
172
|
+
* - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
|
|
173
|
+
*/
|
|
174
|
+
class ClsLoggerCore {
|
|
175
|
+
constructor() {
|
|
176
|
+
this.sdk = null;
|
|
177
|
+
this.sdkPromise = null;
|
|
178
|
+
this.sdkOverride = null;
|
|
179
|
+
this.sdkLoaderOverride = null;
|
|
180
|
+
this.client = null;
|
|
181
|
+
this.clientPromise = null;
|
|
182
|
+
this.topicId = null;
|
|
183
|
+
this.endpoint = 'ap-shanghai.cls.tencentcs.com';
|
|
184
|
+
this.retryTimes = 10;
|
|
185
|
+
this.source = '127.0.0.1';
|
|
186
|
+
this.enabled = true;
|
|
187
|
+
this.projectId = '';
|
|
188
|
+
this.projectName = '';
|
|
189
|
+
this.appId = '';
|
|
190
|
+
this.appVersion = '';
|
|
191
|
+
this.envType = 'browser';
|
|
192
|
+
this.userGenerateBaseFields = null;
|
|
193
|
+
this.autoGenerateBaseFields = null;
|
|
194
|
+
this.storageKey = 'beLink_logs';
|
|
195
|
+
this.batchSize = 15;
|
|
196
|
+
// 参考文档:内存队列批量发送(500ms 或 20 条触发)
|
|
197
|
+
this.memoryQueue = [];
|
|
198
|
+
this.batchMaxSize = 20;
|
|
199
|
+
this.batchIntervalMs = 500;
|
|
200
|
+
this.batchTimer = null;
|
|
201
|
+
this.batchTimerDueAt = null;
|
|
202
|
+
this.initTs = 0;
|
|
203
|
+
this.startupDelayMs = 0;
|
|
204
|
+
// 参考文档:失败缓存 + 重试
|
|
205
|
+
this.failedCacheKey = 'cls_failed_logs';
|
|
206
|
+
this.failedCacheMax = 200;
|
|
207
|
+
this.requestMonitorStarted = false;
|
|
208
|
+
this.errorMonitorStarted = false;
|
|
209
|
+
this.performanceMonitorStarted = false;
|
|
210
|
+
this.behaviorMonitorStarted = false;
|
|
211
|
+
this.behaviorMonitorCleanup = null;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 子类可按需重写(默认检测 wx)
|
|
215
|
+
*/
|
|
216
|
+
detectEnvType() {
|
|
217
|
+
const g = globalThis;
|
|
218
|
+
// 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
|
|
219
|
+
if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
|
|
220
|
+
(g.my && typeof g.my.getSystemInfoSync === 'function') ||
|
|
221
|
+
(g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
|
|
222
|
+
(g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
|
|
223
|
+
return 'miniprogram';
|
|
170
224
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
225
|
+
return 'browser';
|
|
226
|
+
}
|
|
227
|
+
init(options) {
|
|
228
|
+
this.initTs = Date.now();
|
|
229
|
+
const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId ?? null;
|
|
230
|
+
const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
|
|
231
|
+
const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
|
|
232
|
+
const source = options?.tencentCloud?.source ?? options?.source ?? this.source;
|
|
233
|
+
if (!topicId) {
|
|
234
|
+
// eslint-disable-next-line no-console
|
|
235
|
+
console.warn('ClsLogger.init 没有传 topicID/topic_id');
|
|
236
|
+
return;
|
|
174
237
|
}
|
|
175
|
-
|
|
176
|
-
|
|
238
|
+
const nextEnvType = options.envType ?? this.detectEnvType();
|
|
239
|
+
// envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
|
|
240
|
+
const envChanged = nextEnvType !== this.envType;
|
|
241
|
+
const endpointChanged = endpoint !== this.endpoint;
|
|
242
|
+
const retryChanged = retryTimes !== this.retryTimes;
|
|
243
|
+
if (envChanged || endpointChanged || retryChanged) {
|
|
244
|
+
this.client = null;
|
|
245
|
+
this.clientPromise = null;
|
|
246
|
+
}
|
|
247
|
+
if (envChanged) {
|
|
248
|
+
this.sdk = null;
|
|
249
|
+
this.sdkPromise = null;
|
|
250
|
+
}
|
|
251
|
+
this.topicId = topicId;
|
|
252
|
+
this.endpoint = endpoint;
|
|
253
|
+
this.retryTimes = retryTimes;
|
|
254
|
+
this.source = source;
|
|
255
|
+
this.userId = options.userId ?? this.userId;
|
|
256
|
+
this.userName = options.userName ?? this.userName;
|
|
257
|
+
this.projectId = options.projectId ?? this.projectId;
|
|
258
|
+
this.projectName = options.projectName ?? this.projectName;
|
|
259
|
+
this.appId = options.appId ?? this.appId;
|
|
260
|
+
this.appVersion = options.appVersion ?? this.appVersion;
|
|
261
|
+
this.envType = nextEnvType;
|
|
262
|
+
this.enabled = options.enabled ?? true;
|
|
263
|
+
// 可选:外部注入 SDK(优先级:sdkLoader > sdk)
|
|
264
|
+
this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
|
|
265
|
+
this.sdkOverride = options.sdk ?? this.sdkOverride;
|
|
266
|
+
this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
|
|
267
|
+
this.autoGenerateBaseFields = this.createDeviceInfoBaseFields(options.deviceInfo);
|
|
268
|
+
this.storageKey = options.storageKey ?? this.storageKey;
|
|
269
|
+
this.batchSize = options.batchSize ?? this.batchSize;
|
|
270
|
+
this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
|
|
271
|
+
this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
|
|
272
|
+
this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
|
|
273
|
+
this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
|
|
274
|
+
this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
|
|
275
|
+
// 预热(避免首条日志触发 import/初始化开销)
|
|
276
|
+
void this.getInstance().catch(() => {
|
|
277
|
+
// ignore
|
|
278
|
+
});
|
|
279
|
+
if (this.enabled) {
|
|
280
|
+
// 启动时尝试发送失败缓存
|
|
281
|
+
this.flushFailed();
|
|
282
|
+
// 初始化后立即启动请求监听
|
|
283
|
+
this.startRequestMonitor(options.requestMonitor);
|
|
284
|
+
// 初始化后立即启动错误监控/性能监控
|
|
285
|
+
this.startErrorMonitor(options.errorMonitor);
|
|
286
|
+
this.startPerformanceMonitor(options.performanceMonitor);
|
|
287
|
+
// 初始化后立即启动行为埋点(PV/UV/点击)
|
|
288
|
+
this.startBehaviorMonitor(options.behaviorMonitor);
|
|
177
289
|
}
|
|
178
290
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (sampleRate >= 1)
|
|
183
|
-
return true;
|
|
184
|
-
if (sampleRate <= 0)
|
|
185
|
-
return false;
|
|
186
|
-
return Math.random() < sampleRate;
|
|
187
|
-
}
|
|
188
|
-
function truncate$3(s, maxLen) {
|
|
189
|
-
if (!s)
|
|
190
|
-
return s;
|
|
191
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
192
|
-
}
|
|
193
|
-
function buildPayload(params) {
|
|
194
|
-
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
195
|
-
if (!url)
|
|
196
|
-
return null;
|
|
197
|
-
if (shouldIgnoreUrl$1(url, options.ignoreUrls))
|
|
198
|
-
return null;
|
|
199
|
-
if (!sampleHit$2(options.sampleRate))
|
|
200
|
-
return null;
|
|
201
|
-
const payload = { url };
|
|
202
|
-
if (options.includeMethod && method)
|
|
203
|
-
payload.method = method;
|
|
204
|
-
if (options.includeQuery && query !== undefined)
|
|
205
|
-
payload.query = truncate$3(String(query), options.maxParamLength);
|
|
206
|
-
if (options.includeBody && body !== undefined)
|
|
207
|
-
payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
|
|
208
|
-
if (typeof startTime === 'number')
|
|
209
|
-
payload.startTime = startTime;
|
|
210
|
-
if (typeof duration === 'number')
|
|
211
|
-
payload.duration = duration;
|
|
212
|
-
if (typeof status === 'number')
|
|
213
|
-
payload.status = status;
|
|
214
|
-
if (typeof success === 'boolean')
|
|
215
|
-
payload.success = success ? 1 : 0;
|
|
216
|
-
if (error !== undefined)
|
|
217
|
-
payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
|
|
218
|
-
return payload;
|
|
219
|
-
}
|
|
220
|
-
function getAbsoluteUrlMaybe(url) {
|
|
221
|
-
try {
|
|
222
|
-
if (typeof window === 'undefined')
|
|
223
|
-
return url;
|
|
224
|
-
return new URL(url, window.location?.href).toString();
|
|
225
|
-
}
|
|
226
|
-
catch {
|
|
227
|
-
return url;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
function installBrowserFetch(report, options) {
|
|
231
|
-
if (typeof window === 'undefined')
|
|
232
|
-
return;
|
|
233
|
-
const w = window;
|
|
234
|
-
if (w.__beLinkClsLoggerFetchInstalled__)
|
|
235
|
-
return;
|
|
236
|
-
if (typeof w.fetch !== 'function')
|
|
237
|
-
return;
|
|
238
|
-
w.__beLinkClsLoggerFetchInstalled__ = true;
|
|
239
|
-
w.__beLinkClsLoggerRawFetch__ = w.fetch;
|
|
240
|
-
w.fetch = async (input, init) => {
|
|
241
|
-
// 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
|
|
242
|
-
if (isClsSendingNow())
|
|
243
|
-
return w.__beLinkClsLoggerRawFetch__(input, init);
|
|
244
|
-
let url = '';
|
|
245
|
-
let method = '';
|
|
246
|
-
let body = undefined;
|
|
247
|
-
const startTs = Date.now();
|
|
291
|
+
getBaseFields() {
|
|
292
|
+
let auto = undefined;
|
|
293
|
+
let user = undefined;
|
|
248
294
|
try {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
url = input.toString();
|
|
253
|
-
else
|
|
254
|
-
url = input.url ?? '';
|
|
255
|
-
method = (init?.method ?? input?.method ?? 'GET');
|
|
256
|
-
body = init?.body;
|
|
295
|
+
const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
|
|
296
|
+
if (autoRaw && isPlainObject(autoRaw))
|
|
297
|
+
auto = normalizeFlatFields(autoRaw, 'deviceInfo');
|
|
257
298
|
}
|
|
258
299
|
catch {
|
|
259
|
-
|
|
300
|
+
auto = undefined;
|
|
260
301
|
}
|
|
261
|
-
const absUrl = getAbsoluteUrlMaybe(url);
|
|
262
|
-
const query = (() => {
|
|
263
|
-
try {
|
|
264
|
-
const u = new URL(absUrl);
|
|
265
|
-
return u.search ? u.search.slice(1) : '';
|
|
266
|
-
}
|
|
267
|
-
catch {
|
|
268
|
-
return '';
|
|
269
|
-
}
|
|
270
|
-
})();
|
|
271
302
|
try {
|
|
272
|
-
const
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
|
|
276
|
-
const payload = buildPayload({
|
|
277
|
-
url: absUrl,
|
|
278
|
-
method,
|
|
279
|
-
query,
|
|
280
|
-
body,
|
|
281
|
-
startTime: startTs,
|
|
282
|
-
duration,
|
|
283
|
-
status,
|
|
284
|
-
success: ok,
|
|
285
|
-
options,
|
|
286
|
-
});
|
|
287
|
-
if (payload)
|
|
288
|
-
report(options.reportType, payload);
|
|
289
|
-
return res;
|
|
303
|
+
const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
|
|
304
|
+
if (userRaw && isPlainObject(userRaw))
|
|
305
|
+
user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
|
|
290
306
|
}
|
|
291
|
-
catch
|
|
292
|
-
|
|
293
|
-
const payload = buildPayload({
|
|
294
|
-
url: absUrl,
|
|
295
|
-
method,
|
|
296
|
-
query,
|
|
297
|
-
body,
|
|
298
|
-
startTime: startTs,
|
|
299
|
-
duration,
|
|
300
|
-
success: false,
|
|
301
|
-
error: err,
|
|
302
|
-
options,
|
|
303
|
-
});
|
|
304
|
-
if (payload)
|
|
305
|
-
report(options.reportType, payload);
|
|
306
|
-
throw err;
|
|
307
|
+
catch {
|
|
308
|
+
user = undefined;
|
|
307
309
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
310
|
+
if (auto && user)
|
|
311
|
+
return mergeFields(user, auto);
|
|
312
|
+
if (user)
|
|
313
|
+
return user;
|
|
314
|
+
if (auto)
|
|
315
|
+
return auto;
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
startRequestMonitor(requestMonitor) {
|
|
319
|
+
if (this.requestMonitorStarted)
|
|
320
|
+
return;
|
|
321
|
+
// 默认开启;传 false 则关闭
|
|
322
|
+
const enabled = requestMonitor === undefined ? true : !!requestMonitor;
|
|
323
|
+
if (!enabled)
|
|
324
|
+
return;
|
|
325
|
+
const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
|
|
326
|
+
this.requestMonitorStarted = true;
|
|
327
|
+
this.installRequestMonitor((type, data) => {
|
|
328
|
+
this.track(type, data);
|
|
329
|
+
}, {
|
|
330
|
+
...opts,
|
|
331
|
+
enabled: opts.enabled ?? true,
|
|
332
|
+
clsEndpoint: this.endpoint,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
startErrorMonitor(errorMonitor) {
|
|
336
|
+
if (this.errorMonitorStarted)
|
|
337
|
+
return;
|
|
338
|
+
const enabled = errorMonitor === undefined ? true : !!errorMonitor;
|
|
339
|
+
if (!enabled)
|
|
340
|
+
return;
|
|
341
|
+
this.errorMonitorStarted = true;
|
|
342
|
+
this.installErrorMonitor((type, data) => this.track(type, data), errorMonitor ?? true);
|
|
343
|
+
}
|
|
344
|
+
startPerformanceMonitor(performanceMonitor) {
|
|
345
|
+
if (this.performanceMonitorStarted)
|
|
346
|
+
return;
|
|
347
|
+
const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
|
|
348
|
+
if (!enabled)
|
|
349
|
+
return;
|
|
350
|
+
this.performanceMonitorStarted = true;
|
|
351
|
+
this.installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor ?? true);
|
|
352
|
+
}
|
|
353
|
+
startBehaviorMonitor(behaviorMonitor) {
|
|
354
|
+
if (this.behaviorMonitorStarted)
|
|
355
|
+
return;
|
|
356
|
+
const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
|
|
357
|
+
if (!enabled)
|
|
358
|
+
return;
|
|
359
|
+
this.behaviorMonitorStarted = true;
|
|
360
|
+
this.behaviorMonitorCleanup = this.installBehaviorMonitor((type, data) => {
|
|
361
|
+
this.track(type, data);
|
|
362
|
+
}, behaviorMonitor ?? true);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* 停止行为埋点监听(PV/UV/点击)
|
|
366
|
+
* - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
|
|
367
|
+
*/
|
|
368
|
+
stopBehaviorMonitor() {
|
|
323
369
|
try {
|
|
324
|
-
this.
|
|
325
|
-
this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
|
|
370
|
+
this.behaviorMonitorCleanup?.();
|
|
326
371
|
}
|
|
327
372
|
catch {
|
|
328
373
|
// ignore
|
|
329
374
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
catch {
|
|
373
|
-
// ignore
|
|
374
|
-
}
|
|
375
|
-
};
|
|
376
|
-
// 避免重复绑定
|
|
377
|
-
if (!this.__beLinkClsLoggerBound__) {
|
|
378
|
-
this.__beLinkClsLoggerBound__ = true;
|
|
379
|
-
this.addEventListener('loadend', () => {
|
|
380
|
-
try {
|
|
381
|
-
const status = typeof this.status === 'number' ? this.status : 0;
|
|
382
|
-
onDone(status >= 200 && status < 400);
|
|
383
|
-
}
|
|
384
|
-
catch {
|
|
385
|
-
onDone(true);
|
|
386
|
-
}
|
|
387
|
-
});
|
|
388
|
-
this.addEventListener('error', (e) => onDone(false, e));
|
|
389
|
-
this.addEventListener('timeout', () => onDone(false, 'timeout'));
|
|
390
|
-
this.addEventListener('abort', () => onDone(false, 'abort'));
|
|
391
|
-
}
|
|
375
|
+
this.behaviorMonitorCleanup = null;
|
|
376
|
+
this.behaviorMonitorStarted = false;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* 获取 CLS client(按环境懒加载 SDK)
|
|
380
|
+
*/
|
|
381
|
+
async getInstance() {
|
|
382
|
+
if (this.client)
|
|
383
|
+
return this.client;
|
|
384
|
+
if (this.clientPromise)
|
|
385
|
+
return this.clientPromise;
|
|
386
|
+
this.clientPromise = this.loadSdk()
|
|
387
|
+
.then(({ AsyncClient }) => {
|
|
388
|
+
const client = new AsyncClient({
|
|
389
|
+
endpoint: this.endpoint,
|
|
390
|
+
retry_times: this.retryTimes,
|
|
391
|
+
});
|
|
392
|
+
this.client = client;
|
|
393
|
+
return client;
|
|
394
|
+
})
|
|
395
|
+
.catch((err) => {
|
|
396
|
+
// 失败后允许下次重试
|
|
397
|
+
this.clientPromise = null;
|
|
398
|
+
throw err;
|
|
399
|
+
});
|
|
400
|
+
return this.clientPromise;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* 直接上报:埋点入参必须是一维(扁平)Object
|
|
404
|
+
* - 非原始值(对象/数组等)会被自动 stringify 成 string
|
|
405
|
+
* - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
|
|
406
|
+
*/
|
|
407
|
+
put(fields, options = {}) {
|
|
408
|
+
if (!this.enabled)
|
|
409
|
+
return;
|
|
410
|
+
if (!fields)
|
|
411
|
+
return;
|
|
412
|
+
if (!this.topicId) {
|
|
413
|
+
// eslint-disable-next-line no-console
|
|
414
|
+
console.warn('ClsLogger.put:未初始化 topic_id');
|
|
415
|
+
return;
|
|
392
416
|
}
|
|
393
|
-
|
|
417
|
+
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
418
|
+
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
419
|
+
const normalizedFields = normalizeFlatFields(fields, 'put');
|
|
420
|
+
const finalFields = mergeFields(base, {
|
|
421
|
+
projectId: this.projectId || undefined,
|
|
422
|
+
projectName: this.projectName || undefined,
|
|
423
|
+
envType: this.envType,
|
|
424
|
+
appId: this.appId || undefined,
|
|
425
|
+
appVersion: this.appVersion || undefined,
|
|
426
|
+
...normalizedFields,
|
|
427
|
+
});
|
|
428
|
+
// 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
|
|
429
|
+
void this.putAsync(finalFields).catch(() => {
|
|
394
430
|
// ignore
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
async putAsync(finalFields) {
|
|
434
|
+
if (!this.topicId)
|
|
435
|
+
return;
|
|
436
|
+
const sdk = await this.loadSdk();
|
|
437
|
+
const client = await this.getInstance();
|
|
438
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
439
|
+
logGroup.setSource(this.source);
|
|
440
|
+
const log = new sdk.Log(Date.now());
|
|
441
|
+
for (const key of Object.keys(finalFields)) {
|
|
442
|
+
log.addContent(key, stringifyLogValue(finalFields[key]));
|
|
395
443
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
const wxAny = globalThis.wx;
|
|
401
|
-
if (!wxAny || typeof wxAny.request !== 'function')
|
|
402
|
-
return;
|
|
403
|
-
if (wxAny.__beLinkClsLoggerWxRequestInstalled__)
|
|
404
|
-
return;
|
|
405
|
-
wxAny.__beLinkClsLoggerWxRequestInstalled__ = true;
|
|
406
|
-
const rawRequest = wxAny.request.bind(wxAny);
|
|
407
|
-
wxAny.request = (reqOptions) => {
|
|
408
|
-
const startTs = Date.now();
|
|
444
|
+
logGroup.addLog(log);
|
|
445
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
446
|
+
const exit = enterClsSendingGuard();
|
|
447
|
+
let p;
|
|
409
448
|
try {
|
|
410
|
-
|
|
411
|
-
const method = String(reqOptions?.method ?? 'GET');
|
|
412
|
-
const data = reqOptions?.data;
|
|
413
|
-
const wrapCb = (cb, success) => {
|
|
414
|
-
return (res) => {
|
|
415
|
-
try {
|
|
416
|
-
const duration = Date.now() - startTs;
|
|
417
|
-
const status = typeof res?.statusCode === 'number'
|
|
418
|
-
? res.statusCode
|
|
419
|
-
: typeof res?.status === 'number'
|
|
420
|
-
? res.status
|
|
421
|
-
: undefined;
|
|
422
|
-
const payload = buildPayload({
|
|
423
|
-
url,
|
|
424
|
-
method,
|
|
425
|
-
query: '',
|
|
426
|
-
body: data,
|
|
427
|
-
startTime: startTs,
|
|
428
|
-
duration,
|
|
429
|
-
status,
|
|
430
|
-
success,
|
|
431
|
-
error: success ? undefined : res,
|
|
432
|
-
options,
|
|
433
|
-
});
|
|
434
|
-
if (payload)
|
|
435
|
-
report(options.reportType, payload);
|
|
436
|
-
}
|
|
437
|
-
catch {
|
|
438
|
-
// ignore
|
|
439
|
-
}
|
|
440
|
-
if (typeof cb === 'function')
|
|
441
|
-
return cb(res);
|
|
442
|
-
return undefined;
|
|
443
|
-
};
|
|
444
|
-
};
|
|
445
|
-
const next = { ...(reqOptions ?? {}) };
|
|
446
|
-
next.success = wrapCb(next.success, true);
|
|
447
|
-
next.fail = wrapCb(next.fail, false);
|
|
448
|
-
return rawRequest(next);
|
|
449
|
+
p = client.PutLogs(request);
|
|
449
450
|
}
|
|
450
|
-
|
|
451
|
-
|
|
451
|
+
finally {
|
|
452
|
+
exit();
|
|
452
453
|
}
|
|
453
|
-
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
function installMiniProgramWxCloudCallFunction(report, options) {
|
|
457
|
-
const wxAny = globalThis.wx;
|
|
458
|
-
const cloud = wxAny?.cloud;
|
|
459
|
-
if (!cloud || typeof cloud.callFunction !== 'function')
|
|
460
|
-
return;
|
|
461
|
-
if (cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__)
|
|
462
|
-
return;
|
|
463
|
-
cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__ = true;
|
|
464
|
-
const rawCallFunction = cloud.callFunction.bind(cloud);
|
|
465
|
-
cloud.callFunction = (callOptions) => {
|
|
466
|
-
const startTs = Date.now();
|
|
467
|
-
const name = (() => {
|
|
468
|
-
try {
|
|
469
|
-
return String(callOptions?.name ?? '');
|
|
470
|
-
}
|
|
471
|
-
catch {
|
|
472
|
-
return '';
|
|
473
|
-
}
|
|
474
|
-
})();
|
|
475
|
-
const data = callOptions?.data;
|
|
476
|
-
let reported = false;
|
|
477
|
-
const onDone = (success, err) => {
|
|
478
|
-
if (reported)
|
|
479
|
-
return;
|
|
480
|
-
reported = true;
|
|
481
|
-
try {
|
|
482
|
-
const duration = Date.now() - startTs;
|
|
483
|
-
const payload = buildPayload({
|
|
484
|
-
// 统一走 url 字段,便于和 http 一起检索/聚合
|
|
485
|
-
url: `cloud.callFunction/${name || 'unknown'}`,
|
|
486
|
-
method: 'callFunction',
|
|
487
|
-
query: '',
|
|
488
|
-
body: data,
|
|
489
|
-
startTime: startTs,
|
|
490
|
-
duration,
|
|
491
|
-
success,
|
|
492
|
-
error: success ? undefined : err,
|
|
493
|
-
options,
|
|
494
|
-
});
|
|
495
|
-
if (payload) {
|
|
496
|
-
payload.requestType = 'cloud-function';
|
|
497
|
-
payload.name = name || 'unknown';
|
|
498
|
-
report(options.reportType, payload);
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
catch {
|
|
502
|
-
// ignore
|
|
503
|
-
}
|
|
504
|
-
};
|
|
505
|
-
try {
|
|
506
|
-
const next = { ...(callOptions ?? {}) };
|
|
507
|
-
const rawSuccess = next.success;
|
|
508
|
-
const rawFail = next.fail;
|
|
509
|
-
next.success = (res) => {
|
|
510
|
-
onDone(true);
|
|
511
|
-
if (typeof rawSuccess === 'function')
|
|
512
|
-
return rawSuccess(res);
|
|
513
|
-
return undefined;
|
|
514
|
-
};
|
|
515
|
-
next.fail = (err) => {
|
|
516
|
-
onDone(false, err?.message ?? err);
|
|
517
|
-
if (typeof rawFail === 'function')
|
|
518
|
-
return rawFail(err);
|
|
519
|
-
return undefined;
|
|
520
|
-
};
|
|
521
|
-
const ret = rawCallFunction(next);
|
|
522
|
-
// 兼容 Promise 风格(有些版本/写法不传 success/fail)
|
|
523
|
-
if (ret && typeof ret.then === 'function') {
|
|
524
|
-
ret.then(() => onDone(true), (err) => onDone(false, err?.message ?? err));
|
|
525
|
-
}
|
|
526
|
-
return ret;
|
|
527
|
-
}
|
|
528
|
-
catch (err) {
|
|
529
|
-
onDone(false, err);
|
|
530
|
-
throw err;
|
|
531
|
-
}
|
|
532
|
-
};
|
|
533
|
-
}
|
|
534
|
-
function installRequestMonitor(report, opts = {}) {
|
|
535
|
-
const enabled = opts.enabled ?? true;
|
|
536
|
-
if (!enabled)
|
|
537
|
-
return;
|
|
538
|
-
const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
|
|
539
|
-
if (opts.clsEndpoint)
|
|
540
|
-
ignoreUrls.push(opts.clsEndpoint);
|
|
541
|
-
const options = {
|
|
542
|
-
enabled: true,
|
|
543
|
-
reportType: opts.reportType ?? 'http',
|
|
544
|
-
sampleRate: opts.sampleRate ?? 1,
|
|
545
|
-
ignoreUrls,
|
|
546
|
-
includeMethod: opts.includeMethod ?? true,
|
|
547
|
-
includeQuery: opts.includeQuery ?? true,
|
|
548
|
-
includeBody: opts.includeBody ?? true,
|
|
549
|
-
maxParamLength: opts.maxParamLength ?? 2000,
|
|
550
|
-
clsEndpoint: opts.clsEndpoint ?? '',
|
|
551
|
-
};
|
|
552
|
-
if (isMiniProgramEnv()) {
|
|
553
|
-
installMiniProgramWxRequest(report, options);
|
|
554
|
-
installMiniProgramWxCloudCallFunction(report, options);
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
installBrowserFetch(report, options);
|
|
558
|
-
installBrowserXhr(report, options);
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
const DEFAULT_MAX_TEXT = 4000;
|
|
562
|
-
const DEFAULT_DEDUPE_WINDOW_MS = 3000;
|
|
563
|
-
const DEFAULT_DEDUPE_MAX_KEYS = 200;
|
|
564
|
-
function truncate$2(s, maxLen) {
|
|
565
|
-
if (!s)
|
|
566
|
-
return s;
|
|
567
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
568
|
-
}
|
|
569
|
-
function sampleHit$1(sampleRate) {
|
|
570
|
-
if (sampleRate >= 1)
|
|
571
|
-
return true;
|
|
572
|
-
if (sampleRate <= 0)
|
|
573
|
-
return false;
|
|
574
|
-
return Math.random() < sampleRate;
|
|
575
|
-
}
|
|
576
|
-
function getPagePath$1() {
|
|
577
|
-
try {
|
|
578
|
-
if (typeof window === 'undefined')
|
|
579
|
-
return '';
|
|
580
|
-
return window.location?.pathname ?? '';
|
|
454
|
+
await p;
|
|
581
455
|
}
|
|
582
|
-
|
|
583
|
-
|
|
456
|
+
/**
|
|
457
|
+
* 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
|
|
458
|
+
*/
|
|
459
|
+
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
460
|
+
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
461
|
+
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
584
462
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
return
|
|
463
|
+
/**
|
|
464
|
+
* 入队:写入 localStorage 队列;达到 batchSize 自动 flush
|
|
465
|
+
* - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
|
|
466
|
+
*/
|
|
467
|
+
enqueue(fields, options = {}) {
|
|
468
|
+
if (!this.enabled)
|
|
469
|
+
return;
|
|
470
|
+
if (!fields)
|
|
471
|
+
return;
|
|
472
|
+
const time = Date.now();
|
|
473
|
+
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
474
|
+
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
475
|
+
const normalizedFields = normalizeFlatFields(fields, 'enqueue');
|
|
476
|
+
const finalFields = mergeFields(base, {
|
|
477
|
+
projectId: this.projectId || undefined,
|
|
478
|
+
projectName: this.projectName || undefined,
|
|
479
|
+
envType: this.envType,
|
|
480
|
+
appId: this.appId || undefined,
|
|
481
|
+
appVersion: this.appVersion || undefined,
|
|
482
|
+
...normalizedFields,
|
|
483
|
+
});
|
|
484
|
+
const queue = readQueue(this.storageKey);
|
|
485
|
+
const next = [...queue, { time, data: finalFields }];
|
|
486
|
+
if (next.length < this.batchSize) {
|
|
487
|
+
writeQueue(this.storageKey, next);
|
|
488
|
+
return;
|
|
592
489
|
}
|
|
593
|
-
|
|
490
|
+
// 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
|
|
491
|
+
this.putBatch(queue);
|
|
492
|
+
writeQueue(this.storageKey, [{ time, data: finalFields }]);
|
|
594
493
|
}
|
|
595
|
-
|
|
596
|
-
|
|
494
|
+
/**
|
|
495
|
+
* 从 localStorage 读取队列并批量上报
|
|
496
|
+
*/
|
|
497
|
+
flush() {
|
|
498
|
+
const queue = readQueue(this.storageKey);
|
|
499
|
+
if (queue.length === 0)
|
|
500
|
+
return;
|
|
501
|
+
this.putBatch(queue);
|
|
502
|
+
writeQueue(this.storageKey, []);
|
|
597
503
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
}
|
|
504
|
+
/**
|
|
505
|
+
* 批量上报(每条 item.data 展开为 log content)
|
|
506
|
+
*/
|
|
507
|
+
putBatch(queue) {
|
|
508
|
+
if (!this.enabled)
|
|
509
|
+
return;
|
|
510
|
+
if (!queue || queue.length === 0)
|
|
511
|
+
return;
|
|
512
|
+
if (!this.topicId) {
|
|
513
|
+
// eslint-disable-next-line no-console
|
|
514
|
+
console.warn('ClsLogger.putBatch:未初始化 topic_id');
|
|
515
|
+
return;
|
|
611
516
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
return { message, name, stack };
|
|
517
|
+
void this.putBatchAsync(queue).catch(() => {
|
|
518
|
+
// ignore
|
|
519
|
+
});
|
|
616
520
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
if (maxKeys > 0) {
|
|
630
|
-
while (cache.size > maxKeys) {
|
|
631
|
-
const first = cache.keys().next().value;
|
|
632
|
-
if (!first)
|
|
633
|
-
break;
|
|
634
|
-
cache.delete(first);
|
|
521
|
+
async putBatchAsync(queue) {
|
|
522
|
+
if (!this.topicId)
|
|
523
|
+
return;
|
|
524
|
+
const sdk = await this.loadSdk();
|
|
525
|
+
const client = await this.getInstance();
|
|
526
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
527
|
+
logGroup.setSource(this.source);
|
|
528
|
+
for (const item of queue) {
|
|
529
|
+
const log = new sdk.Log(item.time);
|
|
530
|
+
const data = item.data ?? {};
|
|
531
|
+
for (const key of Object.keys(data)) {
|
|
532
|
+
log.addContent(key, stringifyLogValue(data[key]));
|
|
635
533
|
}
|
|
534
|
+
logGroup.addLog(log);
|
|
636
535
|
}
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
return true;
|
|
643
|
-
const now = Date.now();
|
|
644
|
-
const last = cache.get(key);
|
|
645
|
-
if (typeof last === 'number' && now - last < windowMs)
|
|
646
|
-
return false;
|
|
647
|
-
touch(key, now);
|
|
648
|
-
return true;
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
function buildErrorKey(type, payload) {
|
|
652
|
-
// 使用最核心、最稳定的字段构造签名,避免把瞬态字段(如 time)带入导致失效
|
|
653
|
-
const parts = [
|
|
654
|
-
type,
|
|
655
|
-
String(payload.source ?? ''),
|
|
656
|
-
String(payload.pagePath ?? ''),
|
|
657
|
-
String(payload.message ?? ''),
|
|
658
|
-
String(payload.errorName ?? ''),
|
|
659
|
-
String(payload.stack ?? ''),
|
|
660
|
-
String(payload.filename ?? ''),
|
|
661
|
-
String(payload.lineno ?? ''),
|
|
662
|
-
String(payload.colno ?? ''),
|
|
663
|
-
String(payload.tagName ?? ''),
|
|
664
|
-
String(payload.resourceUrl ?? ''),
|
|
665
|
-
];
|
|
666
|
-
return parts.join('|');
|
|
667
|
-
}
|
|
668
|
-
function installBrowserErrorMonitor(report, options) {
|
|
669
|
-
if (typeof window === 'undefined')
|
|
670
|
-
return;
|
|
671
|
-
const w = window;
|
|
672
|
-
if (w.__beLinkClsLoggerErrorInstalled__)
|
|
673
|
-
return;
|
|
674
|
-
w.__beLinkClsLoggerErrorInstalled__ = true;
|
|
675
|
-
const shouldReport = createDedupeGuard(options);
|
|
676
|
-
window.addEventListener('error', (event) => {
|
|
536
|
+
if (logGroup.getLogs().length === 0)
|
|
537
|
+
return;
|
|
538
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
539
|
+
const exit = enterClsSendingGuard();
|
|
540
|
+
let p;
|
|
677
541
|
try {
|
|
678
|
-
|
|
679
|
-
return;
|
|
680
|
-
const payload = {
|
|
681
|
-
pagePath: getPagePath$1(),
|
|
682
|
-
source: 'window.error',
|
|
683
|
-
};
|
|
684
|
-
// JS runtime error
|
|
685
|
-
if (event && typeof event === 'object' && 'message' in event) {
|
|
686
|
-
payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
|
|
687
|
-
payload.filename = truncate$2(String(event.filename ?? ''), 500);
|
|
688
|
-
payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
|
|
689
|
-
payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
|
|
690
|
-
const err = event.error;
|
|
691
|
-
if (err) {
|
|
692
|
-
const e = normalizeErrorLike(err, options.maxTextLength);
|
|
693
|
-
if (e.name)
|
|
694
|
-
payload.errorName = e.name;
|
|
695
|
-
if (e.stack)
|
|
696
|
-
payload.stack = e.stack;
|
|
697
|
-
}
|
|
698
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
699
|
-
return;
|
|
700
|
-
report(options.reportType, payload);
|
|
701
|
-
return;
|
|
702
|
-
}
|
|
703
|
-
// Resource error (img/script/link)
|
|
704
|
-
if (options.captureResourceError) {
|
|
705
|
-
const target = event?.target || event?.srcElement;
|
|
706
|
-
const tagName = target?.tagName ? String(target.tagName) : '';
|
|
707
|
-
const url = String(target?.src || target?.href || '');
|
|
708
|
-
payload.source = 'resource.error';
|
|
709
|
-
payload.tagName = tagName;
|
|
710
|
-
payload.resourceUrl = truncate$2(url, 2000);
|
|
711
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
712
|
-
return;
|
|
713
|
-
report(options.reportType, payload);
|
|
714
|
-
}
|
|
542
|
+
p = client.PutLogs(request);
|
|
715
543
|
}
|
|
716
|
-
|
|
717
|
-
|
|
544
|
+
finally {
|
|
545
|
+
exit();
|
|
718
546
|
}
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
734
|
-
return;
|
|
735
|
-
report(options.reportType, payload);
|
|
547
|
+
await p;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
|
|
551
|
+
*/
|
|
552
|
+
report(log) {
|
|
553
|
+
if (!this.enabled)
|
|
554
|
+
return;
|
|
555
|
+
if (!log?.type)
|
|
556
|
+
return;
|
|
557
|
+
if (!this.topicId) {
|
|
558
|
+
// eslint-disable-next-line no-console
|
|
559
|
+
console.warn('ClsLogger.report:未初始化 topicID/topic_id');
|
|
560
|
+
return;
|
|
736
561
|
}
|
|
737
|
-
|
|
738
|
-
|
|
562
|
+
this.memoryQueue.push(log);
|
|
563
|
+
if (this.memoryQueue.length >= this.batchMaxSize) {
|
|
564
|
+
void this.flushBatch();
|
|
565
|
+
return;
|
|
739
566
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
if (
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
stack: e.stack,
|
|
763
|
-
};
|
|
764
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
765
|
-
return;
|
|
766
|
-
report(options.reportType, payload);
|
|
767
|
-
}
|
|
768
|
-
catch {
|
|
769
|
-
// ignore
|
|
770
|
-
}
|
|
771
|
-
});
|
|
567
|
+
const now = Date.now();
|
|
568
|
+
const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
|
|
569
|
+
const desiredDelay = Math.max(0, desiredDueAt - now);
|
|
570
|
+
if (!this.batchTimer) {
|
|
571
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
572
|
+
this.batchTimer = setTimeout(() => {
|
|
573
|
+
void this.flushBatch();
|
|
574
|
+
}, desiredDelay);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
// 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
|
|
578
|
+
if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
|
|
579
|
+
try {
|
|
580
|
+
clearTimeout(this.batchTimer);
|
|
581
|
+
}
|
|
582
|
+
catch {
|
|
583
|
+
// ignore
|
|
584
|
+
}
|
|
585
|
+
this.batchTimerDueAt = desiredDueAt;
|
|
586
|
+
this.batchTimer = setTimeout(() => {
|
|
587
|
+
void this.flushBatch();
|
|
588
|
+
}, desiredDelay);
|
|
772
589
|
}
|
|
773
590
|
}
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
if (!sampleHit$1(options.sampleRate))
|
|
782
|
-
return;
|
|
783
|
-
const e = normalizeErrorLike(res?.reason, options.maxTextLength);
|
|
784
|
-
const payload = {
|
|
785
|
-
pagePath: getMpPagePath(),
|
|
786
|
-
source: 'wx.onUnhandledRejection',
|
|
787
|
-
message: e.message,
|
|
788
|
-
errorName: e.name,
|
|
789
|
-
stack: e.stack,
|
|
790
|
-
};
|
|
791
|
-
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
792
|
-
return;
|
|
793
|
-
report(options.reportType, payload);
|
|
794
|
-
}
|
|
795
|
-
catch {
|
|
796
|
-
// ignore
|
|
797
|
-
}
|
|
798
|
-
});
|
|
591
|
+
getDesiredBatchFlushDueAt(nowTs) {
|
|
592
|
+
const start = this.initTs || nowTs;
|
|
593
|
+
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
594
|
+
if (startupDelay > 0) {
|
|
595
|
+
const end = start + startupDelay;
|
|
596
|
+
if (nowTs < end)
|
|
597
|
+
return end;
|
|
799
598
|
}
|
|
599
|
+
return nowTs + this.batchIntervalMs;
|
|
800
600
|
}
|
|
801
|
-
|
|
802
|
-
|
|
601
|
+
info(message, data = {}) {
|
|
602
|
+
let msg = '';
|
|
603
|
+
let extra = {};
|
|
604
|
+
if (message instanceof Error) {
|
|
605
|
+
msg = message.message;
|
|
606
|
+
extra = {
|
|
607
|
+
stack: message.stack,
|
|
608
|
+
name: message.name,
|
|
609
|
+
...data,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
msg = String(message);
|
|
614
|
+
extra = data;
|
|
615
|
+
}
|
|
616
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
|
|
617
|
+
this.report({ type: 'info', data: payload, timestamp: Date.now() });
|
|
803
618
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
try {
|
|
814
|
-
if (sampleHit$1(options.sampleRate)) {
|
|
815
|
-
const e = normalizeErrorLike(args?.[0], options.maxTextLength);
|
|
816
|
-
const payload = {
|
|
817
|
-
pagePath: getMpPagePath(),
|
|
818
|
-
source: 'App.onError',
|
|
819
|
-
message: e.message,
|
|
820
|
-
errorName: e.name,
|
|
821
|
-
stack: e.stack,
|
|
822
|
-
};
|
|
823
|
-
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
824
|
-
report(options.reportType, payload);
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
catch {
|
|
828
|
-
// ignore
|
|
829
|
-
}
|
|
830
|
-
if (typeof rawOnError === 'function')
|
|
831
|
-
return rawOnError.apply(this, args);
|
|
832
|
-
return undefined;
|
|
833
|
-
};
|
|
834
|
-
const rawOnUnhandled = next.onUnhandledRejection;
|
|
835
|
-
next.onUnhandledRejection = function (...args) {
|
|
836
|
-
try {
|
|
837
|
-
if (sampleHit$1(options.sampleRate)) {
|
|
838
|
-
const reason = args?.[0]?.reason ?? args?.[0];
|
|
839
|
-
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
840
|
-
const payload = {
|
|
841
|
-
pagePath: getMpPagePath(),
|
|
842
|
-
source: 'App.onUnhandledRejection',
|
|
843
|
-
message: e.message,
|
|
844
|
-
errorName: e.name,
|
|
845
|
-
stack: e.stack,
|
|
846
|
-
};
|
|
847
|
-
if (shouldReport(buildErrorKey(options.reportType, payload)))
|
|
848
|
-
report(options.reportType, payload);
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
catch {
|
|
852
|
-
// ignore
|
|
853
|
-
}
|
|
854
|
-
if (typeof rawOnUnhandled === 'function')
|
|
855
|
-
return rawOnUnhandled.apply(this, args);
|
|
856
|
-
return undefined;
|
|
857
|
-
};
|
|
858
|
-
return rawApp(next);
|
|
619
|
+
warn(message, data = {}) {
|
|
620
|
+
let msg = '';
|
|
621
|
+
let extra = {};
|
|
622
|
+
if (message instanceof Error) {
|
|
623
|
+
msg = message.message;
|
|
624
|
+
extra = {
|
|
625
|
+
stack: message.stack,
|
|
626
|
+
name: message.name,
|
|
627
|
+
...data,
|
|
859
628
|
};
|
|
860
629
|
}
|
|
630
|
+
else {
|
|
631
|
+
msg = String(message);
|
|
632
|
+
extra = data;
|
|
633
|
+
}
|
|
634
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
|
|
635
|
+
this.report({ type: 'warn', data: payload, timestamp: Date.now() });
|
|
861
636
|
}
|
|
862
|
-
|
|
863
|
-
|
|
637
|
+
error(message, data = {}) {
|
|
638
|
+
let msg = '';
|
|
639
|
+
let extra = {};
|
|
640
|
+
if (message instanceof Error) {
|
|
641
|
+
msg = message.message;
|
|
642
|
+
extra = {
|
|
643
|
+
stack: message.stack,
|
|
644
|
+
name: message.name,
|
|
645
|
+
...data,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
else {
|
|
649
|
+
msg = String(message);
|
|
650
|
+
extra = data;
|
|
651
|
+
}
|
|
652
|
+
const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
|
|
653
|
+
this.report({ type: 'error', data: payload, timestamp: Date.now() });
|
|
864
654
|
}
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
reportType: raw.reportType ?? 'error',
|
|
874
|
-
sampleRate: raw.sampleRate ?? 1,
|
|
875
|
-
captureResourceError: raw.captureResourceError ?? true,
|
|
876
|
-
maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
|
|
877
|
-
dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
|
|
878
|
-
dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
|
|
879
|
-
};
|
|
880
|
-
if (isMiniProgramEnv()) {
|
|
881
|
-
installMiniProgramErrorMonitor(report, options);
|
|
882
|
-
return;
|
|
655
|
+
track(trackType, data = {}) {
|
|
656
|
+
if (!trackType)
|
|
657
|
+
return;
|
|
658
|
+
this.report({
|
|
659
|
+
type: trackType,
|
|
660
|
+
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
661
|
+
timestamp: Date.now(),
|
|
662
|
+
});
|
|
883
663
|
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
892
|
-
}
|
|
893
|
-
function sampleHit(sampleRate) {
|
|
894
|
-
if (sampleRate >= 1)
|
|
895
|
-
return true;
|
|
896
|
-
if (sampleRate <= 0)
|
|
897
|
-
return false;
|
|
898
|
-
return Math.random() < sampleRate;
|
|
899
|
-
}
|
|
900
|
-
function shouldIgnoreUrl(url, ignoreUrls) {
|
|
901
|
-
for (const rule of ignoreUrls) {
|
|
902
|
-
if (typeof rule === 'string') {
|
|
903
|
-
if (url.includes(rule))
|
|
904
|
-
return true;
|
|
905
|
-
continue;
|
|
664
|
+
/**
|
|
665
|
+
* 立即发送内存队列
|
|
666
|
+
*/
|
|
667
|
+
async flushBatch() {
|
|
668
|
+
if (this.batchTimer) {
|
|
669
|
+
clearTimeout(this.batchTimer);
|
|
670
|
+
this.batchTimer = null;
|
|
906
671
|
}
|
|
672
|
+
this.batchTimerDueAt = null;
|
|
673
|
+
if (this.memoryQueue.length === 0)
|
|
674
|
+
return;
|
|
675
|
+
const logs = [...this.memoryQueue];
|
|
676
|
+
this.memoryQueue = [];
|
|
907
677
|
try {
|
|
908
|
-
|
|
909
|
-
return true;
|
|
678
|
+
await this.sendReportLogs(logs);
|
|
910
679
|
}
|
|
911
680
|
catch {
|
|
912
|
-
|
|
681
|
+
this.retrySendReportLogs(logs, 1);
|
|
913
682
|
}
|
|
914
683
|
}
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
684
|
+
buildReportFields(log) {
|
|
685
|
+
const ts = log.timestamp ?? Date.now();
|
|
686
|
+
const base = this.getBaseFields();
|
|
687
|
+
const data = normalizeFlatFields(log.data ?? {}, 'report:data');
|
|
688
|
+
const mergedData = mergeFields(base, data);
|
|
689
|
+
return {
|
|
690
|
+
timestamp: ts,
|
|
691
|
+
type: log.type,
|
|
692
|
+
envType: this.envType,
|
|
693
|
+
projectId: this.projectId || undefined,
|
|
694
|
+
projectName: this.projectName || undefined,
|
|
695
|
+
appId: this.appId || undefined,
|
|
696
|
+
appVersion: this.appVersion || undefined,
|
|
697
|
+
// 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
|
|
698
|
+
...mergedData,
|
|
699
|
+
};
|
|
925
700
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
return;
|
|
941
|
-
w.__beLinkClsLoggerPerfInstalled__ = true;
|
|
942
|
-
const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
|
|
943
|
-
// Navigation timing: TTFB 等
|
|
944
|
-
if (options.navigationTiming) {
|
|
945
|
-
try {
|
|
946
|
-
const navEntries = performance.getEntriesByType?.('navigation');
|
|
947
|
-
const nav = Array.isArray(navEntries) ? navEntries[0] : undefined;
|
|
948
|
-
if (nav && typeof nav === 'object') {
|
|
949
|
-
const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
|
|
950
|
-
? nav.responseStart - nav.requestStart
|
|
951
|
-
: -1;
|
|
952
|
-
if (ttfb >= 0 && sampleHit(options.sampleRate))
|
|
953
|
-
reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
|
|
701
|
+
async sendReportLogs(logs) {
|
|
702
|
+
if (!this.topicId)
|
|
703
|
+
return;
|
|
704
|
+
const sdk = await this.loadSdk();
|
|
705
|
+
const client = await this.getInstance();
|
|
706
|
+
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
707
|
+
logGroup.setSource(this.source);
|
|
708
|
+
for (const item of logs) {
|
|
709
|
+
const fields = this.buildReportFields(item);
|
|
710
|
+
const log = new sdk.Log(fields.timestamp);
|
|
711
|
+
for (const key of Object.keys(fields)) {
|
|
712
|
+
if (key === 'timestamp')
|
|
713
|
+
continue;
|
|
714
|
+
log.addContent(key, stringifyLogValue(fields[key]));
|
|
954
715
|
}
|
|
716
|
+
logGroup.addLog(log);
|
|
955
717
|
}
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
// Web Vitals: FCP/LCP/CLS/FID
|
|
961
|
-
if (options.webVitals && typeof globalThis.PerformanceObserver === 'function') {
|
|
962
|
-
// FCP
|
|
718
|
+
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
719
|
+
// 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
|
|
720
|
+
const exit = enterClsSendingGuard();
|
|
721
|
+
let p;
|
|
963
722
|
try {
|
|
964
|
-
|
|
965
|
-
try {
|
|
966
|
-
if (!sampleHit(options.sampleRate))
|
|
967
|
-
return;
|
|
968
|
-
for (const entry of list.getEntries()) {
|
|
969
|
-
if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
|
|
970
|
-
reportMetric(report, options.reportType, 'FCP', entry.startTime, { unit: 'ms' });
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
catch {
|
|
975
|
-
// ignore
|
|
976
|
-
}
|
|
977
|
-
});
|
|
978
|
-
po.observe({ type: 'paint', buffered: true });
|
|
723
|
+
p = client.PutLogs(request);
|
|
979
724
|
}
|
|
980
|
-
|
|
981
|
-
|
|
725
|
+
finally {
|
|
726
|
+
exit();
|
|
982
727
|
}
|
|
983
|
-
|
|
984
|
-
|
|
728
|
+
await p;
|
|
729
|
+
}
|
|
730
|
+
retrySendReportLogs(logs, retryCount) {
|
|
731
|
+
if (retryCount > this.retryTimes) {
|
|
732
|
+
this.cacheFailedReportLogs(logs);
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const delayMs = Math.pow(2, retryCount) * 1000;
|
|
736
|
+
setTimeout(async () => {
|
|
737
|
+
try {
|
|
738
|
+
await this.sendReportLogs(logs);
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
this.retrySendReportLogs(logs, retryCount + 1);
|
|
742
|
+
}
|
|
743
|
+
}, delayMs);
|
|
744
|
+
}
|
|
745
|
+
cacheFailedReportLogs(logs) {
|
|
746
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
747
|
+
let current = [];
|
|
985
748
|
try {
|
|
986
|
-
const
|
|
987
|
-
|
|
988
|
-
const entries = list.getEntries();
|
|
989
|
-
if (entries && entries.length)
|
|
990
|
-
lastLcp = entries[entries.length - 1];
|
|
991
|
-
}
|
|
992
|
-
catch {
|
|
993
|
-
// ignore
|
|
994
|
-
}
|
|
995
|
-
});
|
|
996
|
-
po.observe({ type: 'largest-contentful-paint', buffered: true });
|
|
997
|
-
const flushLcp = () => {
|
|
998
|
-
try {
|
|
999
|
-
if (!lastLcp)
|
|
1000
|
-
return;
|
|
1001
|
-
if (!sampleHit(options.sampleRate))
|
|
1002
|
-
return;
|
|
1003
|
-
if (typeof lastLcp.startTime === 'number')
|
|
1004
|
-
reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
|
|
1005
|
-
lastLcp = null;
|
|
1006
|
-
}
|
|
1007
|
-
catch {
|
|
1008
|
-
// ignore
|
|
1009
|
-
}
|
|
1010
|
-
};
|
|
1011
|
-
window.addEventListener('pagehide', flushLcp, { once: true });
|
|
1012
|
-
document.addEventListener('visibilitychange', () => {
|
|
1013
|
-
if (document.visibilityState === 'hidden')
|
|
1014
|
-
flushLcp();
|
|
1015
|
-
}, { once: true });
|
|
749
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
750
|
+
current = Array.isArray(parsed) ? parsed : [];
|
|
1016
751
|
}
|
|
1017
752
|
catch {
|
|
1018
|
-
|
|
753
|
+
current = [];
|
|
1019
754
|
}
|
|
1020
|
-
|
|
755
|
+
const next = [...current, ...logs].slice(-this.failedCacheMax);
|
|
756
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify(next));
|
|
757
|
+
}
|
|
758
|
+
flushFailed() {
|
|
759
|
+
if (!this.enabled)
|
|
760
|
+
return;
|
|
761
|
+
const raw = readStringStorage(this.failedCacheKey);
|
|
762
|
+
if (!raw)
|
|
763
|
+
return;
|
|
764
|
+
let logs = [];
|
|
1021
765
|
try {
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
try {
|
|
1025
|
-
for (const entry of list.getEntries()) {
|
|
1026
|
-
if (entry && entry.hadRecentInput)
|
|
1027
|
-
continue;
|
|
1028
|
-
if (typeof entry.value === 'number')
|
|
1029
|
-
clsValue += entry.value;
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
catch {
|
|
1033
|
-
// ignore
|
|
1034
|
-
}
|
|
1035
|
-
});
|
|
1036
|
-
po.observe({ type: 'layout-shift', buffered: true });
|
|
1037
|
-
const flushCls = () => {
|
|
1038
|
-
try {
|
|
1039
|
-
if (!sampleHit(options.sampleRate))
|
|
1040
|
-
return;
|
|
1041
|
-
reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
|
|
1042
|
-
}
|
|
1043
|
-
catch {
|
|
1044
|
-
// ignore
|
|
1045
|
-
}
|
|
1046
|
-
};
|
|
1047
|
-
window.addEventListener('pagehide', flushCls, { once: true });
|
|
1048
|
-
document.addEventListener('visibilitychange', () => {
|
|
1049
|
-
if (document.visibilityState === 'hidden')
|
|
1050
|
-
flushCls();
|
|
1051
|
-
}, { once: true });
|
|
766
|
+
const parsed = JSON.parse(raw);
|
|
767
|
+
logs = Array.isArray(parsed) ? parsed : [];
|
|
1052
768
|
}
|
|
1053
769
|
catch {
|
|
1054
|
-
|
|
770
|
+
logs = [];
|
|
771
|
+
}
|
|
772
|
+
if (logs.length === 0)
|
|
773
|
+
return;
|
|
774
|
+
// 先清空,再尝试发送
|
|
775
|
+
writeStringStorage(this.failedCacheKey, JSON.stringify([]));
|
|
776
|
+
this.memoryQueue.unshift(...logs);
|
|
777
|
+
void this.flushBatch();
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
|
|
781
|
+
*/
|
|
782
|
+
stat(param) {
|
|
783
|
+
if (!param)
|
|
784
|
+
return;
|
|
785
|
+
const payload = normalizeFlatFields({
|
|
786
|
+
pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
|
|
787
|
+
projectId: this.projectId,
|
|
788
|
+
projectName: this.projectName,
|
|
789
|
+
...param,
|
|
790
|
+
data: param.data ?? 1,
|
|
791
|
+
}, 'stat');
|
|
792
|
+
this.report({ type: 'stat', data: payload, timestamp: Date.now() });
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function readGlobal(key) {
|
|
797
|
+
try {
|
|
798
|
+
const g = globalThis;
|
|
799
|
+
return g[key] ?? null;
|
|
800
|
+
}
|
|
801
|
+
catch {
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
|
|
807
|
+
function isClsSendingNow() {
|
|
808
|
+
const g = globalThis;
|
|
809
|
+
return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
|
|
810
|
+
}
|
|
811
|
+
function shouldIgnoreUrl$1(url, ignoreUrls) {
|
|
812
|
+
for (const rule of ignoreUrls) {
|
|
813
|
+
if (typeof rule === 'string') {
|
|
814
|
+
if (url.includes(rule))
|
|
815
|
+
return true;
|
|
816
|
+
continue;
|
|
1055
817
|
}
|
|
1056
|
-
// FID
|
|
1057
818
|
try {
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
if (!sampleHit(options.sampleRate))
|
|
1061
|
-
return;
|
|
1062
|
-
for (const entry of list.getEntries()) {
|
|
1063
|
-
const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
|
|
1064
|
-
const processingStart = typeof entry.processingStart === 'number' ? entry.processingStart : -1;
|
|
1065
|
-
if (startTime >= 0 && processingStart >= 0) {
|
|
1066
|
-
reportMetric(report, options.reportType, 'FID', processingStart - startTime, { unit: 'ms' });
|
|
1067
|
-
break;
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
catch {
|
|
1072
|
-
// ignore
|
|
1073
|
-
}
|
|
1074
|
-
});
|
|
1075
|
-
po.observe({ type: 'first-input', buffered: true });
|
|
819
|
+
if (rule.test(url))
|
|
820
|
+
return true;
|
|
1076
821
|
}
|
|
1077
822
|
catch {
|
|
1078
|
-
// ignore
|
|
823
|
+
// ignore invalid regex
|
|
1079
824
|
}
|
|
1080
825
|
}
|
|
1081
|
-
|
|
1082
|
-
if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
|
|
1083
|
-
try {
|
|
1084
|
-
const po = new PerformanceObserver((list) => {
|
|
1085
|
-
try {
|
|
1086
|
-
if (!sampleHit(options.sampleRate))
|
|
1087
|
-
return;
|
|
1088
|
-
for (const entry of list.getEntries()) {
|
|
1089
|
-
const name = String(entry?.name ?? '');
|
|
1090
|
-
if (!name || shouldIgnoreUrl(name, ignoreUrls))
|
|
1091
|
-
continue;
|
|
1092
|
-
const initiatorType = String(entry?.initiatorType ?? '');
|
|
1093
|
-
// 对齐文档:关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
|
|
1094
|
-
if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
|
|
1095
|
-
continue;
|
|
1096
|
-
const payload = {
|
|
1097
|
-
pagePath: getPagePath(),
|
|
1098
|
-
metric: 'resource',
|
|
1099
|
-
initiatorType,
|
|
1100
|
-
url: truncate$1(name, options.maxTextLength),
|
|
1101
|
-
startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
|
|
1102
|
-
duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
|
|
1103
|
-
};
|
|
1104
|
-
// 兼容字段(部分浏览器支持)
|
|
1105
|
-
if (typeof entry?.transferSize === 'number')
|
|
1106
|
-
payload.transferSize = entry.transferSize;
|
|
1107
|
-
if (typeof entry?.encodedBodySize === 'number')
|
|
1108
|
-
payload.encodedBodySize = entry.encodedBodySize;
|
|
1109
|
-
if (typeof entry?.decodedBodySize === 'number')
|
|
1110
|
-
payload.decodedBodySize = entry.decodedBodySize;
|
|
1111
|
-
if (typeof entry?.nextHopProtocol === 'string')
|
|
1112
|
-
payload.nextHopProtocol = entry.nextHopProtocol;
|
|
1113
|
-
if (typeof entry?.responseStatus === 'number')
|
|
1114
|
-
payload.status = entry.responseStatus;
|
|
1115
|
-
report(options.reportType, payload);
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
catch {
|
|
1119
|
-
// ignore
|
|
1120
|
-
}
|
|
1121
|
-
});
|
|
1122
|
-
po.observe({ type: 'resource', buffered: true });
|
|
1123
|
-
}
|
|
1124
|
-
catch {
|
|
1125
|
-
// ignore
|
|
1126
|
-
}
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
function installMiniProgramPerformanceMonitor(report, options) {
|
|
1130
|
-
const g = globalThis;
|
|
1131
|
-
const ctx = g.wx || g.Taro;
|
|
1132
|
-
if (!ctx || typeof ctx.getPerformance !== 'function')
|
|
1133
|
-
return;
|
|
1134
|
-
if (g.__beLinkClsLoggerMpPerfInstalled__)
|
|
1135
|
-
return;
|
|
1136
|
-
g.__beLinkClsLoggerMpPerfInstalled__ = true;
|
|
1137
|
-
try {
|
|
1138
|
-
const perf = ctx.getPerformance();
|
|
1139
|
-
if (!perf || typeof perf.createObserver !== 'function')
|
|
1140
|
-
return;
|
|
1141
|
-
const observer = perf.createObserver((entryList) => {
|
|
1142
|
-
try {
|
|
1143
|
-
const entries = entryList.getEntries();
|
|
1144
|
-
for (const entry of entries) {
|
|
1145
|
-
if (!sampleHit(options.sampleRate))
|
|
1146
|
-
continue;
|
|
1147
|
-
// Page Render: firstRender
|
|
1148
|
-
if (entry.entryType === 'render' && entry.name === 'firstRender') {
|
|
1149
|
-
const duration = typeof entry.duration === 'number'
|
|
1150
|
-
? entry.duration
|
|
1151
|
-
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
1152
|
-
? entry.endTime - entry.startTime
|
|
1153
|
-
: 0;
|
|
1154
|
-
report(options.reportType, {
|
|
1155
|
-
metric: 'page-render',
|
|
1156
|
-
duration,
|
|
1157
|
-
pagePath: entry.path || '',
|
|
1158
|
-
unit: 'ms',
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
// Route Switch: route
|
|
1162
|
-
else if (entry.entryType === 'navigation' && entry.name === 'route') {
|
|
1163
|
-
const duration = typeof entry.duration === 'number'
|
|
1164
|
-
? entry.duration
|
|
1165
|
-
: typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
|
|
1166
|
-
? entry.endTime - entry.startTime
|
|
1167
|
-
: 0;
|
|
1168
|
-
report(options.reportType, {
|
|
1169
|
-
metric: 'route',
|
|
1170
|
-
duration,
|
|
1171
|
-
pagePath: entry.path || '',
|
|
1172
|
-
unit: 'ms',
|
|
1173
|
-
});
|
|
1174
|
-
}
|
|
1175
|
-
// App Launch: appLaunch (Cold)
|
|
1176
|
-
else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
|
|
1177
|
-
report(options.reportType, {
|
|
1178
|
-
metric: 'app-launch',
|
|
1179
|
-
duration: entry.duration,
|
|
1180
|
-
launchType: 'cold',
|
|
1181
|
-
unit: 'ms',
|
|
1182
|
-
});
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
catch {
|
|
1187
|
-
// ignore
|
|
1188
|
-
}
|
|
1189
|
-
});
|
|
1190
|
-
observer.observe({ entryTypes: ['navigation', 'render'] });
|
|
1191
|
-
}
|
|
1192
|
-
catch {
|
|
1193
|
-
// ignore
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
function installPerformanceMonitor(report, opts = {}) {
|
|
1197
|
-
const enabled = opts === undefined ? true : !!opts;
|
|
1198
|
-
if (!enabled)
|
|
1199
|
-
return;
|
|
1200
|
-
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1201
|
-
const options = {
|
|
1202
|
-
enabled: true,
|
|
1203
|
-
reportType: raw.reportType ?? 'perf',
|
|
1204
|
-
sampleRate: raw.sampleRate ?? 1,
|
|
1205
|
-
ignoreUrls: raw.ignoreUrls ?? [],
|
|
1206
|
-
webVitals: raw.webVitals ?? true,
|
|
1207
|
-
navigationTiming: raw.navigationTiming ?? true,
|
|
1208
|
-
resourceTiming: raw.resourceTiming ?? true,
|
|
1209
|
-
maxTextLength: raw.maxTextLength ?? 2000,
|
|
1210
|
-
};
|
|
1211
|
-
if (isMiniProgramEnv()) {
|
|
1212
|
-
installMiniProgramPerformanceMonitor(report, options);
|
|
1213
|
-
return;
|
|
1214
|
-
}
|
|
1215
|
-
installBrowserPerformanceMonitor(report, options);
|
|
826
|
+
return false;
|
|
1216
827
|
}
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
const r = sampleRate ?? 1;
|
|
1220
|
-
if (r >= 1)
|
|
828
|
+
function sampleHit$2(sampleRate) {
|
|
829
|
+
if (sampleRate >= 1)
|
|
1221
830
|
return true;
|
|
1222
|
-
if (
|
|
831
|
+
if (sampleRate <= 0)
|
|
1223
832
|
return false;
|
|
1224
|
-
return Math.random() <
|
|
1225
|
-
}
|
|
1226
|
-
function generateUUID() {
|
|
1227
|
-
// 优先使用更安全的 crypto.randomUUID
|
|
1228
|
-
const g = globalThis;
|
|
1229
|
-
if (g.crypto?.randomUUID)
|
|
1230
|
-
return g.crypto.randomUUID();
|
|
1231
|
-
// fallback
|
|
1232
|
-
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
1233
|
-
const r = Math.random() * 16 || 0;
|
|
1234
|
-
const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
|
|
1235
|
-
return v.toString(16);
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
function safeReadUvMeta(key) {
|
|
1239
|
-
const raw = readStringStorage(key);
|
|
1240
|
-
if (!raw)
|
|
1241
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1242
|
-
try {
|
|
1243
|
-
const parsed = JSON.parse(raw);
|
|
1244
|
-
if (!parsed || typeof parsed !== 'object')
|
|
1245
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1246
|
-
const p = parsed;
|
|
1247
|
-
const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
|
|
1248
|
-
const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
|
|
1249
|
-
const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
|
|
1250
|
-
const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
|
|
1251
|
-
return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
|
|
1252
|
-
}
|
|
1253
|
-
catch {
|
|
1254
|
-
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1257
|
-
function writeUvMeta(key, meta) {
|
|
1258
|
-
writeStringStorage(key, JSON.stringify(meta));
|
|
1259
|
-
}
|
|
1260
|
-
function getWebPagePath() {
|
|
1261
|
-
if (typeof window === 'undefined')
|
|
1262
|
-
return '';
|
|
1263
|
-
return window.location?.pathname || '';
|
|
833
|
+
return Math.random() < sampleRate;
|
|
1264
834
|
}
|
|
1265
|
-
function
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
|
|
1270
|
-
const route = (last?.route || last?.__route__);
|
|
1271
|
-
return typeof route === 'string' ? route : '';
|
|
1272
|
-
}
|
|
1273
|
-
catch {
|
|
1274
|
-
return '';
|
|
1275
|
-
}
|
|
835
|
+
function truncate$3(s, maxLen) {
|
|
836
|
+
if (!s)
|
|
837
|
+
return s;
|
|
838
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1276
839
|
}
|
|
1277
|
-
function
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
840
|
+
function buildPayload(params) {
|
|
841
|
+
const { url, method, query, body, duration, startTime, status, success, error, options } = params;
|
|
842
|
+
if (!url)
|
|
843
|
+
return null;
|
|
844
|
+
if (shouldIgnoreUrl$1(url, options.ignoreUrls))
|
|
845
|
+
return null;
|
|
846
|
+
if (!sampleHit$2(options.sampleRate))
|
|
847
|
+
return null;
|
|
848
|
+
const payload = { url };
|
|
849
|
+
if (options.includeMethod && method)
|
|
850
|
+
payload.method = method;
|
|
851
|
+
if (options.includeQuery && query !== undefined)
|
|
852
|
+
payload.query = truncate$3(String(query), options.maxParamLength);
|
|
853
|
+
if (options.includeBody && body !== undefined)
|
|
854
|
+
payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
|
|
855
|
+
if (typeof startTime === 'number')
|
|
856
|
+
payload.startTime = startTime;
|
|
857
|
+
if (typeof duration === 'number')
|
|
858
|
+
payload.duration = duration;
|
|
859
|
+
if (typeof status === 'number')
|
|
860
|
+
payload.status = status;
|
|
861
|
+
if (typeof success === 'boolean')
|
|
862
|
+
payload.success = success ? 1 : 0;
|
|
863
|
+
if (error !== undefined)
|
|
864
|
+
payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
|
|
865
|
+
return payload;
|
|
1284
866
|
}
|
|
1285
|
-
function
|
|
867
|
+
function getAbsoluteUrlMaybe(url) {
|
|
1286
868
|
try {
|
|
1287
|
-
|
|
869
|
+
if (typeof window === 'undefined')
|
|
870
|
+
return url;
|
|
871
|
+
return new URL(url, window.location?.href).toString();
|
|
1288
872
|
}
|
|
1289
873
|
catch {
|
|
1290
|
-
return
|
|
874
|
+
return url;
|
|
1291
875
|
}
|
|
1292
876
|
}
|
|
1293
|
-
function
|
|
1294
|
-
if (
|
|
1295
|
-
return
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
|
|
1312
|
-
const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
|
|
1313
|
-
const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
|
|
1314
|
-
const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
|
|
1315
|
-
const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
|
|
1316
|
-
const defaultClickWhiteList = envType === 'miniprogram' || isMiniProgramEnv() ? ['view', 'scroll-view'] : ['body', 'html'];
|
|
1317
|
-
const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? defaultClickWhiteList).map((s) => String(s).toLowerCase());
|
|
1318
|
-
const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
|
|
1319
|
-
const clickMaxTextLength = options.clickMaxTextLength ?? 120;
|
|
1320
|
-
const getPagePath = options.getPagePath ??
|
|
1321
|
-
(() => {
|
|
1322
|
-
if (envType === 'miniprogram' || isMiniProgramEnv())
|
|
1323
|
-
return getMiniProgramPagePath();
|
|
1324
|
-
return getWebPagePath();
|
|
1325
|
-
});
|
|
1326
|
-
let destroyed = false;
|
|
1327
|
-
// UV 状态:可能异步(openid/指纹)
|
|
1328
|
-
let firstVisitFlag = false;
|
|
1329
|
-
let firstVisitConsumed = false;
|
|
1330
|
-
const uvStatePromise = (async () => {
|
|
1331
|
-
let existingUvId = readStringStorage(uvIdStorageKey);
|
|
1332
|
-
let isFirstVisit = false;
|
|
1333
|
-
// 先读 meta,做过期判断(过期则清空 uvId + 重置 meta)
|
|
1334
|
-
const now = Date.now();
|
|
1335
|
-
const metaBefore = safeReadUvMeta(uvMetaStorageKey);
|
|
1336
|
-
const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
|
|
1337
|
-
const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
|
|
1338
|
-
if (expired) {
|
|
1339
|
-
existingUvId = null;
|
|
1340
|
-
// 重置 meta(visitCount 会在后续 +1)
|
|
1341
|
-
writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
1342
|
-
writeStringStorage(uvIdStorageKey, '');
|
|
1343
|
-
}
|
|
1344
|
-
// 如果外部提供 getUvId,优先使用;否则本地生成
|
|
877
|
+
function installBrowserFetch(report, options) {
|
|
878
|
+
if (typeof window === 'undefined')
|
|
879
|
+
return;
|
|
880
|
+
const w = window;
|
|
881
|
+
if (w.__beLinkClsLoggerFetchInstalled__)
|
|
882
|
+
return;
|
|
883
|
+
if (typeof w.fetch !== 'function')
|
|
884
|
+
return;
|
|
885
|
+
w.__beLinkClsLoggerFetchInstalled__ = true;
|
|
886
|
+
w.__beLinkClsLoggerRawFetch__ = w.fetch;
|
|
887
|
+
w.fetch = async (input, init) => {
|
|
888
|
+
// 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
|
|
889
|
+
if (isClsSendingNow())
|
|
890
|
+
return w.__beLinkClsLoggerRawFetch__(input, init);
|
|
891
|
+
let url = '';
|
|
892
|
+
let method = '';
|
|
893
|
+
let body = undefined;
|
|
894
|
+
const startTs = Date.now();
|
|
1345
895
|
try {
|
|
1346
|
-
if (
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
896
|
+
if (typeof input === 'string')
|
|
897
|
+
url = input;
|
|
898
|
+
else if (input instanceof URL)
|
|
899
|
+
url = input.toString();
|
|
900
|
+
else
|
|
901
|
+
url = input.url ?? '';
|
|
902
|
+
method = (init?.method ?? input?.method ?? 'GET');
|
|
903
|
+
body = init?.body;
|
|
1352
904
|
}
|
|
1353
905
|
catch {
|
|
1354
906
|
// ignore
|
|
1355
907
|
}
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
const wxAny = globalThis.wx;
|
|
908
|
+
const absUrl = getAbsoluteUrlMaybe(url);
|
|
909
|
+
const query = (() => {
|
|
1359
910
|
try {
|
|
1360
|
-
const
|
|
1361
|
-
|
|
1362
|
-
existingUvId = String(userInfo.openid);
|
|
911
|
+
const u = new URL(absUrl);
|
|
912
|
+
return u.search ? u.search.slice(1) : '';
|
|
1363
913
|
}
|
|
1364
914
|
catch {
|
|
1365
|
-
|
|
1366
|
-
}
|
|
1367
|
-
if (!existingUvId) {
|
|
1368
|
-
try {
|
|
1369
|
-
const sys = wxAny?.getSystemInfoSync?.();
|
|
1370
|
-
const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
|
|
1371
|
-
const model = sys?.model ? String(sys.model) : '';
|
|
1372
|
-
const system = sys?.system ? String(sys.system) : '';
|
|
1373
|
-
const base = [deviceId || model, system].filter(Boolean).join('_');
|
|
1374
|
-
if (base)
|
|
1375
|
-
existingUvId = `${base}_${Date.now()}`;
|
|
1376
|
-
}
|
|
1377
|
-
catch {
|
|
1378
|
-
// ignore
|
|
1379
|
-
}
|
|
915
|
+
return '';
|
|
1380
916
|
}
|
|
1381
|
-
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
};
|
|
1398
|
-
// 如果是首次访问,刷新 firstVisitTs
|
|
1399
|
-
if (isFirstVisit) {
|
|
1400
|
-
nextMeta.firstVisitTs = now;
|
|
1401
|
-
nextMeta.createdAtTs = now;
|
|
1402
|
-
}
|
|
1403
|
-
writeUvMeta(uvMetaStorageKey, nextMeta);
|
|
1404
|
-
firstVisitFlag = isFirstVisit;
|
|
1405
|
-
return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
|
|
1406
|
-
})();
|
|
1407
|
-
function safeReport(type, data) {
|
|
1408
|
-
if (destroyed)
|
|
1409
|
-
return;
|
|
1410
|
-
if (!shouldSample(options.sampleRate))
|
|
1411
|
-
return;
|
|
1412
|
-
report(type, data);
|
|
1413
|
-
}
|
|
1414
|
-
function buildUvFieldsOnce(uvId, meta) {
|
|
1415
|
-
const once = firstVisitFlag && !firstVisitConsumed;
|
|
1416
|
-
if (once)
|
|
1417
|
-
firstVisitConsumed = true;
|
|
1418
|
-
return buildCommonUvFields(uvId, meta, once);
|
|
1419
|
-
}
|
|
1420
|
-
function reportUvOncePerSession() {
|
|
1421
|
-
if (!uvEnabled)
|
|
1422
|
-
return;
|
|
1423
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1424
|
-
if (destroyed)
|
|
1425
|
-
return;
|
|
1426
|
-
safeReport(uvReportType, {
|
|
1427
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1428
|
-
timestamp: Date.now(),
|
|
1429
|
-
pagePath: getPagePath(),
|
|
1430
|
-
});
|
|
1431
|
-
});
|
|
1432
|
-
}
|
|
1433
|
-
function reportPv(pagePath) {
|
|
1434
|
-
if (!pvEnabled)
|
|
1435
|
-
return;
|
|
1436
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1437
|
-
if (destroyed)
|
|
1438
|
-
return;
|
|
1439
|
-
const payload = {
|
|
1440
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1441
|
-
timestamp: Date.now(),
|
|
1442
|
-
pagePath,
|
|
1443
|
-
};
|
|
1444
|
-
// Web referrer(小程序为空串)
|
|
1445
|
-
if (typeof document !== 'undefined') {
|
|
1446
|
-
payload.referrer = document.referrer || '';
|
|
1447
|
-
}
|
|
1448
|
-
else if (envType === 'miniprogram' || isMiniProgramEnv()) {
|
|
1449
|
-
payload.referrer = readStringStorage(lastPagePathStorageKey) || '';
|
|
1450
|
-
writeStringStorage(lastPagePathStorageKey, pagePath);
|
|
1451
|
-
}
|
|
1452
|
-
safeReport(pvReportType, payload);
|
|
1453
|
-
});
|
|
1454
|
-
}
|
|
1455
|
-
// --- Web: PV ---
|
|
1456
|
-
let removeWebPvListeners = null;
|
|
1457
|
-
if (!destroyed && pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
|
|
1458
|
-
const originalPushState = window.history.pushState?.bind(window.history);
|
|
1459
|
-
const originalReplaceState = window.history.replaceState?.bind(window.history);
|
|
1460
|
-
const onRouteChanged = () => reportPv(getPagePath());
|
|
1461
|
-
// 首次进入页面上报 PV
|
|
1462
|
-
onRouteChanged();
|
|
1463
|
-
// patch pushState/replaceState
|
|
1464
|
-
if (originalPushState) {
|
|
1465
|
-
window.history.pushState = ((...args) => {
|
|
1466
|
-
const r = originalPushState.apply(window.history, args);
|
|
1467
|
-
onRouteChanged();
|
|
1468
|
-
return r;
|
|
917
|
+
})();
|
|
918
|
+
try {
|
|
919
|
+
const res = await w.__beLinkClsLoggerRawFetch__(input, init);
|
|
920
|
+
const duration = Date.now() - startTs;
|
|
921
|
+
const status = typeof res?.status === 'number' ? res.status : undefined;
|
|
922
|
+
const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
|
|
923
|
+
const payload = buildPayload({
|
|
924
|
+
url: absUrl,
|
|
925
|
+
method,
|
|
926
|
+
query,
|
|
927
|
+
body,
|
|
928
|
+
startTime: startTs,
|
|
929
|
+
duration,
|
|
930
|
+
status,
|
|
931
|
+
success: ok,
|
|
932
|
+
options,
|
|
1469
933
|
});
|
|
934
|
+
if (payload)
|
|
935
|
+
report(options.reportType, payload);
|
|
936
|
+
return res;
|
|
1470
937
|
}
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
938
|
+
catch (err) {
|
|
939
|
+
const duration = Date.now() - startTs;
|
|
940
|
+
const payload = buildPayload({
|
|
941
|
+
url: absUrl,
|
|
942
|
+
method,
|
|
943
|
+
query,
|
|
944
|
+
body,
|
|
945
|
+
startTime: startTs,
|
|
946
|
+
duration,
|
|
947
|
+
success: false,
|
|
948
|
+
error: err,
|
|
949
|
+
options,
|
|
1476
950
|
});
|
|
951
|
+
if (payload)
|
|
952
|
+
report(options.reportType, payload);
|
|
953
|
+
throw err;
|
|
1477
954
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
const
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
const originalPage = typeof g.Page === 'function' ? g.Page : null;
|
|
1551
|
-
if (originalPage) {
|
|
1552
|
-
g.Page = function patchedPage(conf) {
|
|
1553
|
-
const originalOnShow = conf?.onShow;
|
|
1554
|
-
conf.onShow = function (...args) {
|
|
1555
|
-
if (pvEnabled) {
|
|
1556
|
-
const pagePath = getPagePath();
|
|
1557
|
-
if (pagePath?.length > 0) {
|
|
1558
|
-
reportPv(pagePath);
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
|
|
1562
|
-
};
|
|
1563
|
-
// 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
|
|
1564
|
-
if (clickEnabled && conf && typeof conf === 'object') {
|
|
1565
|
-
for (const key of Object.keys(conf)) {
|
|
1566
|
-
const fn = conf[key];
|
|
1567
|
-
if (typeof fn !== 'function')
|
|
1568
|
-
continue;
|
|
1569
|
-
if (fn.__beLinkWrapped__)
|
|
1570
|
-
continue;
|
|
1571
|
-
conf[key] = function (...args) {
|
|
1572
|
-
try {
|
|
1573
|
-
const e = args?.[0];
|
|
1574
|
-
const type = e?.type;
|
|
1575
|
-
const currentTarget = e?.currentTarget;
|
|
1576
|
-
const dataset = currentTarget?.dataset;
|
|
1577
|
-
const isTap = type === 'tap' || type === 'click';
|
|
1578
|
-
if (clickEnabled && isTap && currentTarget && dataset) {
|
|
1579
|
-
const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
|
|
1580
|
-
const tagName = String(tagNameRaw || '').toLowerCase();
|
|
1581
|
-
const trackId = dataset?.trackId ? String(dataset.trackId) : '';
|
|
1582
|
-
if (!(clickWhiteList.includes(tagName) && !trackId)) {
|
|
1583
|
-
const x = typeof e?.detail?.x === 'number'
|
|
1584
|
-
? e.detail.x
|
|
1585
|
-
: typeof e?.touches?.[0]?.pageX === 'number'
|
|
1586
|
-
? e.touches[0].pageX
|
|
1587
|
-
: 0;
|
|
1588
|
-
const y = typeof e?.detail?.y === 'number'
|
|
1589
|
-
? e.detail.y
|
|
1590
|
-
: typeof e?.touches?.[0]?.pageY === 'number'
|
|
1591
|
-
? e.touches[0].pageY
|
|
1592
|
-
: 0;
|
|
1593
|
-
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1594
|
-
if (destroyed)
|
|
1595
|
-
return;
|
|
1596
|
-
safeReport(clickReportType, {
|
|
1597
|
-
...buildUvFieldsOnce(uvId, meta),
|
|
1598
|
-
timestamp: Date.now(),
|
|
1599
|
-
pagePath: getPagePath(),
|
|
1600
|
-
elementTag: tagNameRaw ? String(tagNameRaw) : '',
|
|
1601
|
-
elementId: currentTarget?.id ? String(currentTarget.id) : '',
|
|
1602
|
-
elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
|
|
1603
|
-
trackId,
|
|
1604
|
-
elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
|
|
1605
|
-
clickX: x,
|
|
1606
|
-
clickY: y,
|
|
1607
|
-
});
|
|
1608
|
-
});
|
|
1609
|
-
}
|
|
1610
|
-
}
|
|
1611
|
-
}
|
|
1612
|
-
catch {
|
|
1613
|
-
// ignore
|
|
1614
|
-
}
|
|
1615
|
-
return fn.apply(this, args);
|
|
1616
|
-
};
|
|
1617
|
-
conf[key].__beLinkWrapped__ = true;
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
return originalPage(conf);
|
|
1621
|
-
};
|
|
1622
|
-
restoreMiniProgramPatch = () => {
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
function installBrowserXhr(report, options) {
|
|
958
|
+
if (typeof window === 'undefined')
|
|
959
|
+
return;
|
|
960
|
+
const w = window;
|
|
961
|
+
if (w.__beLinkClsLoggerXhrInstalled__)
|
|
962
|
+
return;
|
|
963
|
+
if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
|
|
964
|
+
return;
|
|
965
|
+
w.__beLinkClsLoggerXhrInstalled__ = true;
|
|
966
|
+
const XHR = w.XMLHttpRequest;
|
|
967
|
+
const rawOpen = XHR.prototype.open;
|
|
968
|
+
const rawSend = XHR.prototype.send;
|
|
969
|
+
XHR.prototype.open = function (...args) {
|
|
970
|
+
try {
|
|
971
|
+
this.__beLinkClsLoggerMethod__ = String(args[0] ?? 'GET');
|
|
972
|
+
this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
|
|
973
|
+
}
|
|
974
|
+
catch {
|
|
975
|
+
// ignore
|
|
976
|
+
}
|
|
977
|
+
return rawOpen.apply(this, args);
|
|
978
|
+
};
|
|
979
|
+
XHR.prototype.send = function (...args) {
|
|
980
|
+
// CLS SDK 发起上报时:跳过监控,避免递归上报
|
|
981
|
+
if (isClsSendingNow())
|
|
982
|
+
return rawSend.apply(this, args);
|
|
983
|
+
const startTs = Date.now();
|
|
984
|
+
try {
|
|
985
|
+
const method = String(this.__beLinkClsLoggerMethod__ ?? 'GET');
|
|
986
|
+
const url = getAbsoluteUrlMaybe(String(this.__beLinkClsLoggerUrl__ ?? ''));
|
|
987
|
+
const query = (() => {
|
|
988
|
+
try {
|
|
989
|
+
const u = new URL(url);
|
|
990
|
+
return u.search ? u.search.slice(1) : '';
|
|
991
|
+
}
|
|
992
|
+
catch {
|
|
993
|
+
return '';
|
|
994
|
+
}
|
|
995
|
+
})();
|
|
996
|
+
const body = args?.[0];
|
|
997
|
+
this.__beLinkClsLoggerStartTs__ = startTs;
|
|
998
|
+
this.__beLinkClsLoggerBody__ = body;
|
|
999
|
+
const onDone = (success, error) => {
|
|
1000
|
+
try {
|
|
1001
|
+
const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
|
|
1002
|
+
const duration = Date.now() - st;
|
|
1003
|
+
const status = typeof this.status === 'number' ? this.status : undefined;
|
|
1004
|
+
const payload = buildPayload({
|
|
1005
|
+
url,
|
|
1006
|
+
method,
|
|
1007
|
+
query,
|
|
1008
|
+
body: this.__beLinkClsLoggerBody__,
|
|
1009
|
+
startTime: st,
|
|
1010
|
+
duration,
|
|
1011
|
+
status,
|
|
1012
|
+
success,
|
|
1013
|
+
error,
|
|
1014
|
+
options,
|
|
1015
|
+
});
|
|
1016
|
+
if (payload)
|
|
1017
|
+
report(options.reportType, payload);
|
|
1018
|
+
}
|
|
1019
|
+
catch {
|
|
1020
|
+
// ignore
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
// 避免重复绑定
|
|
1024
|
+
if (!this.__beLinkClsLoggerBound__) {
|
|
1025
|
+
this.__beLinkClsLoggerBound__ = true;
|
|
1026
|
+
this.addEventListener('loadend', () => {
|
|
1623
1027
|
try {
|
|
1624
|
-
|
|
1625
|
-
|
|
1028
|
+
const status = typeof this.status === 'number' ? this.status : 0;
|
|
1029
|
+
onDone(status >= 200 && status < 400);
|
|
1626
1030
|
}
|
|
1627
1031
|
catch {
|
|
1628
|
-
|
|
1032
|
+
onDone(true);
|
|
1629
1033
|
}
|
|
1630
|
-
};
|
|
1034
|
+
});
|
|
1035
|
+
this.addEventListener('error', (e) => onDone(false, e));
|
|
1036
|
+
this.addEventListener('timeout', () => onDone(false, 'timeout'));
|
|
1037
|
+
this.addEventListener('abort', () => onDone(false, 'abort'));
|
|
1631
1038
|
}
|
|
1632
1039
|
}
|
|
1633
|
-
// 启动时也尝试报一次(避免 Page patch 未生效的场景)
|
|
1634
|
-
if (pvEnabled)
|
|
1635
|
-
reportPv(getPagePath());
|
|
1636
|
-
}
|
|
1637
|
-
// UV:每次启动上报一次(可关闭)
|
|
1638
|
-
reportUvOncePerSession();
|
|
1639
|
-
return () => {
|
|
1640
|
-
if (destroyed)
|
|
1641
|
-
return;
|
|
1642
|
-
destroyed = true;
|
|
1643
|
-
try {
|
|
1644
|
-
removeWebPvListeners?.();
|
|
1645
|
-
removeWebClickListener?.();
|
|
1646
|
-
restoreMiniProgramPatch?.();
|
|
1647
|
-
}
|
|
1648
1040
|
catch {
|
|
1649
1041
|
// ignore
|
|
1650
1042
|
}
|
|
1043
|
+
return rawSend.apply(this, args);
|
|
1651
1044
|
};
|
|
1652
1045
|
}
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
if (!
|
|
1656
|
-
return
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
const
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
osName = 'iOS';
|
|
1671
|
-
osVersion = ios[1].replace(/_/g, '.');
|
|
1672
|
-
}
|
|
1673
|
-
else if (android) {
|
|
1674
|
-
osName = 'Android';
|
|
1675
|
-
osVersion = android[1];
|
|
1676
|
-
}
|
|
1677
|
-
else if (win) {
|
|
1678
|
-
osName = 'Windows';
|
|
1679
|
-
osVersion = win[1];
|
|
1680
|
-
}
|
|
1681
|
-
else if (mac) {
|
|
1682
|
-
osName = 'macOS';
|
|
1683
|
-
osVersion = mac[1].replace(/_/g, '.');
|
|
1684
|
-
}
|
|
1685
|
-
// Browser
|
|
1686
|
-
let browserName = 'unknown';
|
|
1687
|
-
let browserVersion = '';
|
|
1688
|
-
const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
|
|
1689
|
-
const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
|
|
1690
|
-
const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
|
|
1691
|
-
const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
|
|
1692
|
-
if (edge) {
|
|
1693
|
-
browserName = 'Edge';
|
|
1694
|
-
browserVersion = edge[1];
|
|
1695
|
-
}
|
|
1696
|
-
else if (chrome) {
|
|
1697
|
-
browserName = 'Chrome';
|
|
1698
|
-
browserVersion = chrome[1];
|
|
1699
|
-
}
|
|
1700
|
-
else if (firefox) {
|
|
1701
|
-
browserName = 'Firefox';
|
|
1702
|
-
browserVersion = firefox[1];
|
|
1703
|
-
}
|
|
1704
|
-
else if (safari) {
|
|
1705
|
-
browserName = 'Safari';
|
|
1706
|
-
browserVersion = safari[1];
|
|
1707
|
-
}
|
|
1708
|
-
return { browserName, browserVersion, osName, osVersion, isMobile };
|
|
1709
|
-
}
|
|
1710
|
-
function getBrowserDeviceInfo(options) {
|
|
1711
|
-
const out = {
|
|
1712
|
-
envType: 'browser',
|
|
1046
|
+
function installWebRequestMonitor(report, opts = {}) {
|
|
1047
|
+
const enabled = opts.enabled ?? true;
|
|
1048
|
+
if (!enabled)
|
|
1049
|
+
return;
|
|
1050
|
+
const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
|
|
1051
|
+
if (opts.clsEndpoint)
|
|
1052
|
+
ignoreUrls.push(opts.clsEndpoint);
|
|
1053
|
+
const options = {
|
|
1054
|
+
enabled: true,
|
|
1055
|
+
reportType: opts.reportType ?? 'http',
|
|
1056
|
+
sampleRate: opts.sampleRate ?? 1,
|
|
1057
|
+
ignoreUrls,
|
|
1058
|
+
includeMethod: opts.includeMethod ?? true,
|
|
1059
|
+
includeQuery: opts.includeQuery ?? true,
|
|
1060
|
+
includeBody: opts.includeBody ?? true,
|
|
1061
|
+
maxParamLength: opts.maxParamLength ?? 2000,
|
|
1062
|
+
clsEndpoint: opts.clsEndpoint ?? '',
|
|
1713
1063
|
};
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
const ua = String(navigator.userAgent ?? '');
|
|
1717
|
-
const uaParsed = parseUserAgent(ua);
|
|
1718
|
-
if (options.includeUserAgent)
|
|
1719
|
-
out.ua = truncate(ua, 2000);
|
|
1720
|
-
out.browserName = uaParsed.browserName;
|
|
1721
|
-
out.browserVersion = uaParsed.browserVersion;
|
|
1722
|
-
out.osName = uaParsed.osName;
|
|
1723
|
-
out.osVersion = uaParsed.osVersion;
|
|
1724
|
-
out.isMobile = uaParsed.isMobile ? 1 : 0;
|
|
1725
|
-
out.language = String(navigator.language ?? '');
|
|
1726
|
-
out.platform = String(navigator.platform ?? '');
|
|
1727
|
-
try {
|
|
1728
|
-
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1729
|
-
out.timezone = typeof tz === 'string' ? tz : '';
|
|
1730
|
-
}
|
|
1731
|
-
catch {
|
|
1732
|
-
out.timezone = '';
|
|
1733
|
-
}
|
|
1734
|
-
try {
|
|
1735
|
-
const s = window.screen;
|
|
1736
|
-
out.screenWidth = s?.width ?? undefined;
|
|
1737
|
-
out.screenHeight = s?.height ?? undefined;
|
|
1738
|
-
}
|
|
1739
|
-
catch {
|
|
1740
|
-
// ignore
|
|
1741
|
-
}
|
|
1742
|
-
try {
|
|
1743
|
-
out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
|
|
1744
|
-
}
|
|
1745
|
-
catch {
|
|
1746
|
-
// ignore
|
|
1747
|
-
}
|
|
1748
|
-
try {
|
|
1749
|
-
const navAny = navigator;
|
|
1750
|
-
out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
|
|
1751
|
-
out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
|
|
1752
|
-
}
|
|
1753
|
-
catch {
|
|
1754
|
-
// ignore
|
|
1755
|
-
}
|
|
1756
|
-
if (options.includeNetwork) {
|
|
1757
|
-
try {
|
|
1758
|
-
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
|
|
1759
|
-
if (conn && isPlainObject(conn)) {
|
|
1760
|
-
if (typeof conn.effectiveType === 'string')
|
|
1761
|
-
out.netEffectiveType = conn.effectiveType;
|
|
1762
|
-
if (typeof conn.downlink === 'number')
|
|
1763
|
-
out.netDownlink = conn.downlink;
|
|
1764
|
-
if (typeof conn.rtt === 'number')
|
|
1765
|
-
out.netRtt = conn.rtt;
|
|
1766
|
-
if (typeof conn.saveData === 'boolean')
|
|
1767
|
-
out.netSaveData = conn.saveData ? 1 : 0;
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
catch {
|
|
1771
|
-
// ignore
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
return out;
|
|
1064
|
+
installBrowserFetch(report, options);
|
|
1065
|
+
installBrowserXhr(report, options);
|
|
1775
1066
|
}
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
if (!
|
|
1782
|
-
return
|
|
1067
|
+
|
|
1068
|
+
const DEFAULT_MAX_TEXT = 4000;
|
|
1069
|
+
const DEFAULT_DEDUPE_WINDOW_MS = 3000;
|
|
1070
|
+
const DEFAULT_DEDUPE_MAX_KEYS = 200;
|
|
1071
|
+
function truncate$2(s, maxLen) {
|
|
1072
|
+
if (!s)
|
|
1073
|
+
return s;
|
|
1074
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1075
|
+
}
|
|
1076
|
+
function sampleHit$1(sampleRate) {
|
|
1077
|
+
if (sampleRate >= 1)
|
|
1078
|
+
return true;
|
|
1079
|
+
if (sampleRate <= 0)
|
|
1080
|
+
return false;
|
|
1081
|
+
return Math.random() < sampleRate;
|
|
1082
|
+
}
|
|
1083
|
+
function getPagePath$1() {
|
|
1783
1084
|
try {
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
out.mpSystem = sys?.system ? String(sys.system) : '';
|
|
1788
|
-
out.mpPlatform = sys?.platform ? String(sys.platform) : '';
|
|
1789
|
-
out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
|
|
1790
|
-
out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
|
|
1791
|
-
out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
|
|
1792
|
-
out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
|
|
1793
|
-
out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
|
|
1794
|
-
out.language = sys?.language ? String(sys.language) : '';
|
|
1085
|
+
if (typeof window === 'undefined')
|
|
1086
|
+
return '';
|
|
1087
|
+
return window.location?.pathname ?? '';
|
|
1795
1088
|
}
|
|
1796
1089
|
catch {
|
|
1797
|
-
|
|
1090
|
+
return '';
|
|
1798
1091
|
}
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
success: (res) => {
|
|
1809
|
-
try {
|
|
1810
|
-
const g = globalThis;
|
|
1811
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1812
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1813
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1814
|
-
}
|
|
1815
|
-
catch {
|
|
1816
|
-
// ignore
|
|
1817
|
-
}
|
|
1818
|
-
},
|
|
1819
|
-
});
|
|
1092
|
+
}
|
|
1093
|
+
function normalizeErrorLike(err, maxTextLength) {
|
|
1094
|
+
if (err && typeof err === 'object') {
|
|
1095
|
+
const anyErr = err;
|
|
1096
|
+
let rawMsg = anyErr.message;
|
|
1097
|
+
if (!rawMsg) {
|
|
1098
|
+
const str = anyErr.toString?.();
|
|
1099
|
+
if (!str || str === '[object Object]') {
|
|
1100
|
+
rawMsg = stringifyLogValue(anyErr);
|
|
1820
1101
|
}
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
// ignore
|
|
1824
|
-
}
|
|
1825
|
-
try {
|
|
1826
|
-
if (typeof wxAny.onNetworkStatusChange === 'function') {
|
|
1827
|
-
wxAny.onNetworkStatusChange((res) => {
|
|
1828
|
-
try {
|
|
1829
|
-
const g = globalThis;
|
|
1830
|
-
if (!g.__beLinkClsLoggerDeviceInfo__)
|
|
1831
|
-
g.__beLinkClsLoggerDeviceInfo__ = {};
|
|
1832
|
-
g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
|
|
1833
|
-
}
|
|
1834
|
-
catch {
|
|
1835
|
-
// ignore
|
|
1836
|
-
}
|
|
1837
|
-
});
|
|
1102
|
+
else {
|
|
1103
|
+
rawMsg = str;
|
|
1838
1104
|
}
|
|
1839
1105
|
}
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1106
|
+
const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
|
|
1107
|
+
const name = truncate$2(String(anyErr.name ?? ''), 200);
|
|
1108
|
+
const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
|
|
1109
|
+
return { message, name, stack };
|
|
1843
1110
|
}
|
|
1844
|
-
|
|
1111
|
+
const message = truncate$2(stringifyLogValue(err), maxTextLength);
|
|
1112
|
+
return { message, name: '', stack: '' };
|
|
1845
1113
|
}
|
|
1846
|
-
function
|
|
1847
|
-
const
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
if (!base) {
|
|
1861
|
-
base =
|
|
1862
|
-
envType === 'miniprogram' || isMiniProgramEnv()
|
|
1863
|
-
? getMiniProgramDeviceInfo(options)
|
|
1864
|
-
: getBrowserDeviceInfo(options);
|
|
1865
|
-
try {
|
|
1866
|
-
const g = globalThis;
|
|
1867
|
-
if (!g[globalKey])
|
|
1868
|
-
g[globalKey] = { ...base };
|
|
1869
|
-
}
|
|
1870
|
-
catch {
|
|
1871
|
-
// ignore
|
|
1114
|
+
function createDedupeGuard(options) {
|
|
1115
|
+
const cache = new Map(); // key -> lastReportAt
|
|
1116
|
+
const maxKeys = Math.max(0, options.dedupeMaxKeys);
|
|
1117
|
+
const windowMs = Math.max(0, options.dedupeWindowMs);
|
|
1118
|
+
function touch(key, now) {
|
|
1119
|
+
if (cache.has(key))
|
|
1120
|
+
cache.delete(key);
|
|
1121
|
+
cache.set(key, now);
|
|
1122
|
+
if (maxKeys > 0) {
|
|
1123
|
+
while (cache.size > maxKeys) {
|
|
1124
|
+
const first = cache.keys().next().value;
|
|
1125
|
+
if (!first)
|
|
1126
|
+
break;
|
|
1127
|
+
cache.delete(first);
|
|
1872
1128
|
}
|
|
1873
1129
|
}
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1130
|
+
}
|
|
1131
|
+
return (key) => {
|
|
1132
|
+
if (!key)
|
|
1133
|
+
return true;
|
|
1134
|
+
if (windowMs <= 0 || maxKeys === 0)
|
|
1135
|
+
return true;
|
|
1136
|
+
const now = Date.now();
|
|
1137
|
+
const last = cache.get(key);
|
|
1138
|
+
if (typeof last === 'number' && now - last < windowMs)
|
|
1139
|
+
return false;
|
|
1140
|
+
touch(key, now);
|
|
1141
|
+
return true;
|
|
1884
1142
|
};
|
|
1885
1143
|
}
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1144
|
+
function buildErrorKey(type, payload) {
|
|
1145
|
+
const parts = [
|
|
1146
|
+
type,
|
|
1147
|
+
String(payload.source ?? ''),
|
|
1148
|
+
String(payload.pagePath ?? ''),
|
|
1149
|
+
String(payload.message ?? ''),
|
|
1150
|
+
String(payload.errorName ?? ''),
|
|
1151
|
+
String(payload.stack ?? ''),
|
|
1152
|
+
String(payload.filename ?? ''),
|
|
1153
|
+
String(payload.lineno ?? ''),
|
|
1154
|
+
String(payload.colno ?? ''),
|
|
1155
|
+
String(payload.tagName ?? ''),
|
|
1156
|
+
String(payload.resourceUrl ?? ''),
|
|
1157
|
+
];
|
|
1158
|
+
return parts.join('|');
|
|
1895
1159
|
}
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
/**
|
|
1942
|
-
* 子类可按需重写(默认检测 wx)
|
|
1943
|
-
*/
|
|
1944
|
-
detectEnvType() {
|
|
1945
|
-
const g = globalThis;
|
|
1946
|
-
// 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
|
|
1947
|
-
if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
|
|
1948
|
-
(g.my && typeof g.my.getSystemInfoSync === 'function') ||
|
|
1949
|
-
(g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
|
|
1950
|
-
(g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
|
|
1951
|
-
return 'miniprogram';
|
|
1952
|
-
}
|
|
1953
|
-
return 'browser';
|
|
1954
|
-
}
|
|
1955
|
-
init(options) {
|
|
1956
|
-
this.initTs = Date.now();
|
|
1957
|
-
const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId ?? null;
|
|
1958
|
-
const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
|
|
1959
|
-
const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
|
|
1960
|
-
const source = options?.tencentCloud?.source ?? options?.source ?? this.source;
|
|
1961
|
-
if (!topicId) {
|
|
1962
|
-
// eslint-disable-next-line no-console
|
|
1963
|
-
console.warn('ClsLogger.init 没有传 topicID/topic_id');
|
|
1964
|
-
return;
|
|
1965
|
-
}
|
|
1966
|
-
const nextEnvType = options.envType ?? this.detectEnvType();
|
|
1967
|
-
// envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
|
|
1968
|
-
const envChanged = nextEnvType !== this.envType;
|
|
1969
|
-
const endpointChanged = endpoint !== this.endpoint;
|
|
1970
|
-
const retryChanged = retryTimes !== this.retryTimes;
|
|
1971
|
-
if (envChanged || endpointChanged || retryChanged) {
|
|
1972
|
-
this.client = null;
|
|
1973
|
-
this.clientPromise = null;
|
|
1974
|
-
}
|
|
1975
|
-
if (envChanged) {
|
|
1976
|
-
this.sdk = null;
|
|
1977
|
-
this.sdkPromise = null;
|
|
1160
|
+
function installBrowserErrorMonitor(report, options) {
|
|
1161
|
+
if (typeof window === 'undefined')
|
|
1162
|
+
return;
|
|
1163
|
+
const w = window;
|
|
1164
|
+
if (w.__beLinkClsLoggerErrorInstalled__)
|
|
1165
|
+
return;
|
|
1166
|
+
w.__beLinkClsLoggerErrorInstalled__ = true;
|
|
1167
|
+
const shouldReport = createDedupeGuard(options);
|
|
1168
|
+
window.addEventListener('error', (event) => {
|
|
1169
|
+
try {
|
|
1170
|
+
if (!sampleHit$1(options.sampleRate))
|
|
1171
|
+
return;
|
|
1172
|
+
const payload = {
|
|
1173
|
+
pagePath: getPagePath$1(),
|
|
1174
|
+
source: 'window.error',
|
|
1175
|
+
};
|
|
1176
|
+
if (event && typeof event === 'object' && 'message' in event) {
|
|
1177
|
+
payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
|
|
1178
|
+
payload.filename = truncate$2(String(event.filename ?? ''), 500);
|
|
1179
|
+
payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
|
|
1180
|
+
payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
|
|
1181
|
+
const err = event.error;
|
|
1182
|
+
if (err) {
|
|
1183
|
+
const e = normalizeErrorLike(err, options.maxTextLength);
|
|
1184
|
+
if (e.name)
|
|
1185
|
+
payload.errorName = e.name;
|
|
1186
|
+
if (e.stack)
|
|
1187
|
+
payload.stack = e.stack;
|
|
1188
|
+
}
|
|
1189
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1190
|
+
return;
|
|
1191
|
+
report(options.reportType, payload);
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
if (options.captureResourceError) {
|
|
1195
|
+
const target = event?.target || event?.srcElement;
|
|
1196
|
+
const tagName = target?.tagName ? String(target.tagName) : '';
|
|
1197
|
+
const url = String(target?.src || target?.href || '');
|
|
1198
|
+
payload.source = 'resource.error';
|
|
1199
|
+
payload.tagName = tagName;
|
|
1200
|
+
payload.resourceUrl = truncate$2(url, 2000);
|
|
1201
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1202
|
+
return;
|
|
1203
|
+
report(options.reportType, payload);
|
|
1204
|
+
}
|
|
1978
1205
|
}
|
|
1979
|
-
|
|
1980
|
-
this.endpoint = endpoint;
|
|
1981
|
-
this.retryTimes = retryTimes;
|
|
1982
|
-
this.source = source;
|
|
1983
|
-
this.userId = options.userId ?? this.userId;
|
|
1984
|
-
this.userName = options.userName ?? this.userName;
|
|
1985
|
-
this.projectId = options.projectId ?? this.projectId;
|
|
1986
|
-
this.projectName = options.projectName ?? this.projectName;
|
|
1987
|
-
this.appId = options.appId ?? this.appId;
|
|
1988
|
-
this.appVersion = options.appVersion ?? this.appVersion;
|
|
1989
|
-
this.envType = nextEnvType;
|
|
1990
|
-
this.enabled = options.enabled ?? true;
|
|
1991
|
-
// 可选:外部注入 SDK(优先级:sdkLoader > sdk)
|
|
1992
|
-
this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
|
|
1993
|
-
this.sdkOverride = options.sdk ?? this.sdkOverride;
|
|
1994
|
-
this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
|
|
1995
|
-
this.autoGenerateBaseFields = createAutoDeviceInfoBaseFields(this.envType, options.deviceInfo);
|
|
1996
|
-
this.storageKey = options.storageKey ?? this.storageKey;
|
|
1997
|
-
this.batchSize = options.batchSize ?? this.batchSize;
|
|
1998
|
-
this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
|
|
1999
|
-
this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
|
|
2000
|
-
this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
|
|
2001
|
-
this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
|
|
2002
|
-
this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
|
|
2003
|
-
// 预热(避免首条日志触发 import/初始化开销)
|
|
2004
|
-
void this.getInstance().catch(() => {
|
|
1206
|
+
catch {
|
|
2005
1207
|
// ignore
|
|
2006
|
-
});
|
|
2007
|
-
if (this.enabled) {
|
|
2008
|
-
// 启动时尝试发送失败缓存
|
|
2009
|
-
this.flushFailed();
|
|
2010
|
-
// 初始化后立即启动请求监听
|
|
2011
|
-
this.startRequestMonitor(options.requestMonitor);
|
|
2012
|
-
// 初始化后立即启动错误监控/性能监控
|
|
2013
|
-
this.startErrorMonitor(options.errorMonitor);
|
|
2014
|
-
this.startPerformanceMonitor(options.performanceMonitor);
|
|
2015
|
-
// 初始化后立即启动行为埋点(PV/UV/点击)
|
|
2016
|
-
this.startBehaviorMonitor(options.behaviorMonitor);
|
|
2017
1208
|
}
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
|
-
let auto = undefined;
|
|
2021
|
-
let user = undefined;
|
|
1209
|
+
}, true);
|
|
1210
|
+
window.addEventListener('unhandledrejection', (event) => {
|
|
2022
1211
|
try {
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
1212
|
+
if (!sampleHit$1(options.sampleRate))
|
|
1213
|
+
return;
|
|
1214
|
+
const reason = event?.reason;
|
|
1215
|
+
const e = normalizeErrorLike(reason, options.maxTextLength);
|
|
1216
|
+
const payload = {
|
|
1217
|
+
pagePath: getPagePath$1(),
|
|
1218
|
+
source: 'unhandledrejection',
|
|
1219
|
+
message: e.message,
|
|
1220
|
+
errorName: e.name,
|
|
1221
|
+
stack: e.stack,
|
|
1222
|
+
};
|
|
1223
|
+
if (!shouldReport(buildErrorKey(options.reportType, payload)))
|
|
1224
|
+
return;
|
|
1225
|
+
report(options.reportType, payload);
|
|
2026
1226
|
}
|
|
2027
1227
|
catch {
|
|
2028
|
-
|
|
1228
|
+
// ignore
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
function installWebErrorMonitor(report, opts = {}) {
|
|
1233
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1234
|
+
if (!enabled)
|
|
1235
|
+
return;
|
|
1236
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1237
|
+
const options = {
|
|
1238
|
+
enabled: true,
|
|
1239
|
+
reportType: raw.reportType ?? 'error',
|
|
1240
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
1241
|
+
captureResourceError: raw.captureResourceError ?? true,
|
|
1242
|
+
maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
|
|
1243
|
+
dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
|
|
1244
|
+
dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
|
|
1245
|
+
};
|
|
1246
|
+
installBrowserErrorMonitor(report, options);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
|
|
1250
|
+
function truncate$1(s, maxLen) {
|
|
1251
|
+
if (!s)
|
|
1252
|
+
return s;
|
|
1253
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1254
|
+
}
|
|
1255
|
+
function sampleHit(sampleRate) {
|
|
1256
|
+
if (sampleRate >= 1)
|
|
1257
|
+
return true;
|
|
1258
|
+
if (sampleRate <= 0)
|
|
1259
|
+
return false;
|
|
1260
|
+
return Math.random() < sampleRate;
|
|
1261
|
+
}
|
|
1262
|
+
function shouldIgnoreUrl(url, ignoreUrls) {
|
|
1263
|
+
for (const rule of ignoreUrls) {
|
|
1264
|
+
if (typeof rule === 'string') {
|
|
1265
|
+
if (url.includes(rule))
|
|
1266
|
+
return true;
|
|
1267
|
+
continue;
|
|
2029
1268
|
}
|
|
2030
1269
|
try {
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
|
|
1270
|
+
if (rule.test(url))
|
|
1271
|
+
return true;
|
|
2034
1272
|
}
|
|
2035
1273
|
catch {
|
|
2036
|
-
|
|
1274
|
+
// ignore invalid regex
|
|
2037
1275
|
}
|
|
2038
|
-
if (auto && user)
|
|
2039
|
-
return mergeFields(user, auto);
|
|
2040
|
-
if (user)
|
|
2041
|
-
return user;
|
|
2042
|
-
if (auto)
|
|
2043
|
-
return auto;
|
|
2044
|
-
return undefined;
|
|
2045
|
-
}
|
|
2046
|
-
startRequestMonitor(requestMonitor) {
|
|
2047
|
-
if (this.requestMonitorStarted)
|
|
2048
|
-
return;
|
|
2049
|
-
// 默认开启;传 false 则关闭
|
|
2050
|
-
const enabled = requestMonitor === undefined ? true : !!requestMonitor;
|
|
2051
|
-
if (!enabled)
|
|
2052
|
-
return;
|
|
2053
|
-
const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
|
|
2054
|
-
this.requestMonitorStarted = true;
|
|
2055
|
-
installRequestMonitor((type, data) => {
|
|
2056
|
-
this.track(type, data);
|
|
2057
|
-
}, {
|
|
2058
|
-
...opts,
|
|
2059
|
-
enabled: opts.enabled ?? true,
|
|
2060
|
-
clsEndpoint: this.endpoint,
|
|
2061
|
-
});
|
|
2062
|
-
}
|
|
2063
|
-
startErrorMonitor(errorMonitor) {
|
|
2064
|
-
if (this.errorMonitorStarted)
|
|
2065
|
-
return;
|
|
2066
|
-
const enabled = errorMonitor === undefined ? true : !!errorMonitor;
|
|
2067
|
-
if (!enabled)
|
|
2068
|
-
return;
|
|
2069
|
-
this.errorMonitorStarted = true;
|
|
2070
|
-
installErrorMonitor((type, data) => this.track(type, data), errorMonitor);
|
|
2071
1276
|
}
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
if (
|
|
2077
|
-
return;
|
|
2078
|
-
|
|
2079
|
-
installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor);
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
function getPagePath() {
|
|
1280
|
+
try {
|
|
1281
|
+
if (typeof window === 'undefined')
|
|
1282
|
+
return '';
|
|
1283
|
+
return window.location?.pathname ?? '';
|
|
2080
1284
|
}
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
return;
|
|
2084
|
-
const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
|
|
2085
|
-
if (!enabled)
|
|
2086
|
-
return;
|
|
2087
|
-
const opts = typeof behaviorMonitor === 'object' && behaviorMonitor
|
|
2088
|
-
? behaviorMonitor
|
|
2089
|
-
: {};
|
|
2090
|
-
this.behaviorMonitorStarted = true;
|
|
2091
|
-
this.behaviorMonitorCleanup = installBehaviorMonitor((type, data) => {
|
|
2092
|
-
this.track(type, data);
|
|
2093
|
-
}, this.envType, {
|
|
2094
|
-
...opts,
|
|
2095
|
-
enabled: opts.enabled ?? true,
|
|
2096
|
-
});
|
|
1285
|
+
catch {
|
|
1286
|
+
return '';
|
|
2097
1287
|
}
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
1288
|
+
}
|
|
1289
|
+
function reportMetric(report, reportType, metric, value, extra = {}) {
|
|
1290
|
+
report(reportType, {
|
|
1291
|
+
pagePath: getPagePath(),
|
|
1292
|
+
metric,
|
|
1293
|
+
value,
|
|
1294
|
+
...extra,
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
function installBrowserPerformanceMonitor(report, options) {
|
|
1298
|
+
if (typeof window === 'undefined')
|
|
1299
|
+
return;
|
|
1300
|
+
const w = window;
|
|
1301
|
+
if (w.__beLinkClsLoggerPerfInstalled__)
|
|
1302
|
+
return;
|
|
1303
|
+
w.__beLinkClsLoggerPerfInstalled__ = true;
|
|
1304
|
+
const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
|
|
1305
|
+
// Navigation timing: TTFB 等
|
|
1306
|
+
if (options.navigationTiming) {
|
|
2103
1307
|
try {
|
|
2104
|
-
|
|
1308
|
+
const navEntries = performance.getEntriesByType?.('navigation');
|
|
1309
|
+
const nav = Array.isArray(navEntries) ? navEntries[0] : undefined;
|
|
1310
|
+
if (nav && typeof nav === 'object') {
|
|
1311
|
+
const ttfb = typeof nav.responseStart === 'number' && typeof nav.requestStart === 'number'
|
|
1312
|
+
? nav.responseStart - nav.requestStart
|
|
1313
|
+
: -1;
|
|
1314
|
+
if (ttfb >= 0 && sampleHit(options.sampleRate))
|
|
1315
|
+
reportMetric(report, options.reportType, 'TTFB', ttfb, { unit: 'ms' });
|
|
1316
|
+
}
|
|
2105
1317
|
}
|
|
2106
1318
|
catch {
|
|
2107
1319
|
// ignore
|
|
2108
1320
|
}
|
|
2109
|
-
this.behaviorMonitorCleanup = null;
|
|
2110
|
-
this.behaviorMonitorStarted = false;
|
|
2111
1321
|
}
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
1322
|
+
// Web Vitals: FCP/LCP/CLS/FID
|
|
1323
|
+
if (options.webVitals && typeof globalThis.PerformanceObserver === 'function') {
|
|
1324
|
+
// FCP
|
|
1325
|
+
try {
|
|
1326
|
+
const po = new PerformanceObserver((list) => {
|
|
1327
|
+
try {
|
|
1328
|
+
if (!sampleHit(options.sampleRate))
|
|
1329
|
+
return;
|
|
1330
|
+
for (const entry of list.getEntries()) {
|
|
1331
|
+
if (entry?.name === 'first-contentful-paint' && typeof entry.startTime === 'number') {
|
|
1332
|
+
reportMetric(report, options.reportType, 'FCP', entry.startTime, { unit: 'ms' });
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
catch {
|
|
1337
|
+
// ignore
|
|
1338
|
+
}
|
|
2125
1339
|
});
|
|
2126
|
-
|
|
2127
|
-
return client;
|
|
2128
|
-
})
|
|
2129
|
-
.catch((err) => {
|
|
2130
|
-
// 失败后允许下次重试
|
|
2131
|
-
this.clientPromise = null;
|
|
2132
|
-
throw err;
|
|
2133
|
-
});
|
|
2134
|
-
return this.clientPromise;
|
|
2135
|
-
}
|
|
2136
|
-
/**
|
|
2137
|
-
* 直接上报:埋点入参必须是一维(扁平)Object
|
|
2138
|
-
* - 非原始值(对象/数组等)会被自动 stringify 成 string
|
|
2139
|
-
* - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
|
|
2140
|
-
*/
|
|
2141
|
-
put(fields, options = {}) {
|
|
2142
|
-
if (!this.enabled)
|
|
2143
|
-
return;
|
|
2144
|
-
if (!fields)
|
|
2145
|
-
return;
|
|
2146
|
-
if (!this.topicId) {
|
|
2147
|
-
// eslint-disable-next-line no-console
|
|
2148
|
-
console.warn('ClsLogger.put:未初始化 topic_id');
|
|
2149
|
-
return;
|
|
1340
|
+
po.observe({ type: 'paint', buffered: true });
|
|
2150
1341
|
}
|
|
2151
|
-
|
|
2152
|
-
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
2153
|
-
const normalizedFields = normalizeFlatFields(fields, 'put');
|
|
2154
|
-
const finalFields = mergeFields(base, {
|
|
2155
|
-
projectId: this.projectId || undefined,
|
|
2156
|
-
projectName: this.projectName || undefined,
|
|
2157
|
-
envType: this.envType,
|
|
2158
|
-
appId: this.appId || undefined,
|
|
2159
|
-
appVersion: this.appVersion || undefined,
|
|
2160
|
-
...normalizedFields,
|
|
2161
|
-
});
|
|
2162
|
-
// 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
|
|
2163
|
-
void this.putAsync(finalFields).catch(() => {
|
|
1342
|
+
catch {
|
|
2164
1343
|
// ignore
|
|
2165
|
-
});
|
|
2166
|
-
}
|
|
2167
|
-
async putAsync(finalFields) {
|
|
2168
|
-
if (!this.topicId)
|
|
2169
|
-
return;
|
|
2170
|
-
const sdk = await this.loadSdk();
|
|
2171
|
-
const client = await this.getInstance();
|
|
2172
|
-
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
2173
|
-
logGroup.setSource(this.source);
|
|
2174
|
-
const log = new sdk.Log(Date.now());
|
|
2175
|
-
for (const key of Object.keys(finalFields)) {
|
|
2176
|
-
log.addContent(key, stringifyLogValue(finalFields[key]));
|
|
2177
1344
|
}
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
const exit = enterClsSendingGuard();
|
|
2181
|
-
let p;
|
|
1345
|
+
// LCP(最后一次为准)
|
|
1346
|
+
let lastLcp = null;
|
|
2182
1347
|
try {
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
1348
|
+
const po = new PerformanceObserver((list) => {
|
|
1349
|
+
try {
|
|
1350
|
+
const entries = list.getEntries();
|
|
1351
|
+
if (entries && entries.length)
|
|
1352
|
+
lastLcp = entries[entries.length - 1];
|
|
1353
|
+
}
|
|
1354
|
+
catch {
|
|
1355
|
+
// ignore
|
|
1356
|
+
}
|
|
1357
|
+
});
|
|
1358
|
+
po.observe({ type: 'largest-contentful-paint', buffered: true });
|
|
1359
|
+
const flushLcp = () => {
|
|
1360
|
+
try {
|
|
1361
|
+
if (!lastLcp)
|
|
1362
|
+
return;
|
|
1363
|
+
if (!sampleHit(options.sampleRate))
|
|
1364
|
+
return;
|
|
1365
|
+
if (typeof lastLcp.startTime === 'number')
|
|
1366
|
+
reportMetric(report, options.reportType, 'LCP', lastLcp.startTime, { unit: 'ms' });
|
|
1367
|
+
lastLcp = null;
|
|
1368
|
+
}
|
|
1369
|
+
catch {
|
|
1370
|
+
// ignore
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
window.addEventListener('pagehide', flushLcp, { once: true });
|
|
1374
|
+
document.addEventListener('visibilitychange', () => {
|
|
1375
|
+
if (document.visibilityState === 'hidden')
|
|
1376
|
+
flushLcp();
|
|
1377
|
+
}, { once: true });
|
|
2187
1378
|
}
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
/**
|
|
2191
|
-
* 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
|
|
2192
|
-
*/
|
|
2193
|
-
putJson(data, clsLoggerKey = '日志内容', options = {}) {
|
|
2194
|
-
// put 的入参要求扁平;这里直接把数据序列化为 string
|
|
2195
|
-
this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
|
|
2196
|
-
}
|
|
2197
|
-
/**
|
|
2198
|
-
* 入队:写入 localStorage 队列;达到 batchSize 自动 flush
|
|
2199
|
-
* - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
|
|
2200
|
-
*/
|
|
2201
|
-
enqueue(fields, options = {}) {
|
|
2202
|
-
if (!this.enabled)
|
|
2203
|
-
return;
|
|
2204
|
-
if (!fields)
|
|
2205
|
-
return;
|
|
2206
|
-
const time = Date.now();
|
|
2207
|
-
const mergeBaseFields = options.mergeBaseFields ?? true;
|
|
2208
|
-
const base = mergeBaseFields ? this.getBaseFields() : undefined;
|
|
2209
|
-
const normalizedFields = normalizeFlatFields(fields, 'enqueue');
|
|
2210
|
-
const finalFields = mergeFields(base, {
|
|
2211
|
-
projectId: this.projectId || undefined,
|
|
2212
|
-
projectName: this.projectName || undefined,
|
|
2213
|
-
envType: this.envType,
|
|
2214
|
-
appId: this.appId || undefined,
|
|
2215
|
-
appVersion: this.appVersion || undefined,
|
|
2216
|
-
...normalizedFields,
|
|
2217
|
-
});
|
|
2218
|
-
const queue = readQueue(this.storageKey);
|
|
2219
|
-
const next = [...queue, { time, data: finalFields }];
|
|
2220
|
-
if (next.length < this.batchSize) {
|
|
2221
|
-
writeQueue(this.storageKey, next);
|
|
2222
|
-
return;
|
|
1379
|
+
catch {
|
|
1380
|
+
// ignore
|
|
2223
1381
|
}
|
|
2224
|
-
//
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
1382
|
+
// CLS
|
|
1383
|
+
try {
|
|
1384
|
+
let clsValue = 0;
|
|
1385
|
+
const po = new PerformanceObserver((list) => {
|
|
1386
|
+
try {
|
|
1387
|
+
for (const entry of list.getEntries()) {
|
|
1388
|
+
if (entry && entry.hadRecentInput)
|
|
1389
|
+
continue;
|
|
1390
|
+
if (typeof entry.value === 'number')
|
|
1391
|
+
clsValue += entry.value;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
catch {
|
|
1395
|
+
// ignore
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
po.observe({ type: 'layout-shift', buffered: true });
|
|
1399
|
+
const flushCls = () => {
|
|
1400
|
+
try {
|
|
1401
|
+
if (!sampleHit(options.sampleRate))
|
|
1402
|
+
return;
|
|
1403
|
+
reportMetric(report, options.reportType, 'CLS', clsValue, { unit: 'score' });
|
|
1404
|
+
}
|
|
1405
|
+
catch {
|
|
1406
|
+
// ignore
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
window.addEventListener('pagehide', flushCls, { once: true });
|
|
1410
|
+
document.addEventListener('visibilitychange', () => {
|
|
1411
|
+
if (document.visibilityState === 'hidden')
|
|
1412
|
+
flushCls();
|
|
1413
|
+
}, { once: true });
|
|
2250
1414
|
}
|
|
2251
|
-
|
|
1415
|
+
catch {
|
|
2252
1416
|
// ignore
|
|
2253
|
-
});
|
|
2254
|
-
}
|
|
2255
|
-
async putBatchAsync(queue) {
|
|
2256
|
-
if (!this.topicId)
|
|
2257
|
-
return;
|
|
2258
|
-
const sdk = await this.loadSdk();
|
|
2259
|
-
const client = await this.getInstance();
|
|
2260
|
-
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
2261
|
-
logGroup.setSource(this.source);
|
|
2262
|
-
for (const item of queue) {
|
|
2263
|
-
const log = new sdk.Log(item.time);
|
|
2264
|
-
const data = item.data ?? {};
|
|
2265
|
-
for (const key of Object.keys(data)) {
|
|
2266
|
-
log.addContent(key, stringifyLogValue(data[key]));
|
|
2267
|
-
}
|
|
2268
|
-
logGroup.addLog(log);
|
|
2269
1417
|
}
|
|
2270
|
-
|
|
2271
|
-
return;
|
|
2272
|
-
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
2273
|
-
const exit = enterClsSendingGuard();
|
|
2274
|
-
let p;
|
|
1418
|
+
// FID
|
|
2275
1419
|
try {
|
|
2276
|
-
|
|
1420
|
+
const po = new PerformanceObserver((list) => {
|
|
1421
|
+
try {
|
|
1422
|
+
if (!sampleHit(options.sampleRate))
|
|
1423
|
+
return;
|
|
1424
|
+
for (const entry of list.getEntries()) {
|
|
1425
|
+
const startTime = typeof entry.startTime === 'number' ? entry.startTime : -1;
|
|
1426
|
+
const processingStart = typeof entry.processingStart === 'number' ? entry.processingStart : -1;
|
|
1427
|
+
if (startTime >= 0 && processingStart >= 0) {
|
|
1428
|
+
reportMetric(report, options.reportType, 'FID', processingStart - startTime, { unit: 'ms' });
|
|
1429
|
+
break;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
catch {
|
|
1434
|
+
// ignore
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
po.observe({ type: 'first-input', buffered: true });
|
|
2277
1438
|
}
|
|
2278
|
-
|
|
2279
|
-
|
|
1439
|
+
catch {
|
|
1440
|
+
// ignore
|
|
2280
1441
|
}
|
|
2281
|
-
await p;
|
|
2282
1442
|
}
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
1443
|
+
// Resource timing:资源加载耗时
|
|
1444
|
+
if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
|
|
1445
|
+
try {
|
|
1446
|
+
const po = new PerformanceObserver((list) => {
|
|
1447
|
+
try {
|
|
1448
|
+
if (!sampleHit(options.sampleRate))
|
|
1449
|
+
return;
|
|
1450
|
+
for (const entry of list.getEntries()) {
|
|
1451
|
+
const name = String(entry?.name ?? '');
|
|
1452
|
+
if (!name || shouldIgnoreUrl(name, ignoreUrls))
|
|
1453
|
+
continue;
|
|
1454
|
+
const initiatorType = String(entry?.initiatorType ?? '');
|
|
1455
|
+
// 对齐文档:关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
|
|
1456
|
+
if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
|
|
1457
|
+
continue;
|
|
1458
|
+
const payload = {
|
|
1459
|
+
pagePath: getPagePath(),
|
|
1460
|
+
metric: 'resource',
|
|
1461
|
+
initiatorType,
|
|
1462
|
+
url: truncate$1(name, options.maxTextLength),
|
|
1463
|
+
startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
|
|
1464
|
+
duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
|
|
1465
|
+
};
|
|
1466
|
+
// 兼容字段(部分浏览器支持)
|
|
1467
|
+
if (typeof entry?.transferSize === 'number')
|
|
1468
|
+
payload.transferSize = entry.transferSize;
|
|
1469
|
+
if (typeof entry?.encodedBodySize === 'number')
|
|
1470
|
+
payload.encodedBodySize = entry.encodedBodySize;
|
|
1471
|
+
if (typeof entry?.decodedBodySize === 'number')
|
|
1472
|
+
payload.decodedBodySize = entry.decodedBodySize;
|
|
1473
|
+
if (typeof entry?.nextHopProtocol === 'string')
|
|
1474
|
+
payload.nextHopProtocol = entry.nextHopProtocol;
|
|
1475
|
+
if (typeof entry?.responseStatus === 'number')
|
|
1476
|
+
payload.status = entry.responseStatus;
|
|
1477
|
+
report(options.reportType, payload);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
catch {
|
|
1481
|
+
// ignore
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
po.observe({ type: 'resource', buffered: true });
|
|
2295
1485
|
}
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
void this.flushBatch();
|
|
2299
|
-
return;
|
|
1486
|
+
catch {
|
|
1487
|
+
// ignore
|
|
2300
1488
|
}
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
function installWebPerformanceMonitor(report, opts = {}) {
|
|
1492
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1493
|
+
if (!enabled)
|
|
1494
|
+
return;
|
|
1495
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1496
|
+
const options = {
|
|
1497
|
+
enabled: true,
|
|
1498
|
+
reportType: raw.reportType ?? 'perf',
|
|
1499
|
+
sampleRate: raw.sampleRate ?? 1,
|
|
1500
|
+
ignoreUrls: raw.ignoreUrls ?? [],
|
|
1501
|
+
webVitals: raw.webVitals ?? true,
|
|
1502
|
+
navigationTiming: raw.navigationTiming ?? true,
|
|
1503
|
+
resourceTiming: raw.resourceTiming ?? true,
|
|
1504
|
+
maxTextLength: raw.maxTextLength ?? 2000,
|
|
1505
|
+
};
|
|
1506
|
+
installBrowserPerformanceMonitor(report, options);
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
function shouldSample(sampleRate) {
|
|
1510
|
+
const r = sampleRate ?? 1;
|
|
1511
|
+
if (r >= 1)
|
|
1512
|
+
return true;
|
|
1513
|
+
if (r <= 0)
|
|
1514
|
+
return false;
|
|
1515
|
+
return Math.random() < r;
|
|
1516
|
+
}
|
|
1517
|
+
function generateUUID() {
|
|
1518
|
+
const g = globalThis;
|
|
1519
|
+
if (g.crypto?.randomUUID)
|
|
1520
|
+
return g.crypto.randomUUID();
|
|
1521
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
1522
|
+
const r = Math.random() * 16 || 0;
|
|
1523
|
+
const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
|
|
1524
|
+
return v.toString(16);
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
function safeReadUvMeta(key) {
|
|
1528
|
+
const raw = readStringStorage(key);
|
|
1529
|
+
if (!raw)
|
|
1530
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1531
|
+
try {
|
|
1532
|
+
const parsed = JSON.parse(raw);
|
|
1533
|
+
if (!parsed || typeof parsed !== 'object')
|
|
1534
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1535
|
+
const p = parsed;
|
|
1536
|
+
const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
|
|
1537
|
+
const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
|
|
1538
|
+
const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
|
|
1539
|
+
const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
|
|
1540
|
+
return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
|
|
1541
|
+
}
|
|
1542
|
+
catch {
|
|
1543
|
+
return { firstVisitTs: Date.now(), visitCount: 0 };
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
function writeUvMeta(key, meta) {
|
|
1547
|
+
writeStringStorage(key, JSON.stringify(meta));
|
|
1548
|
+
}
|
|
1549
|
+
function getWebPagePath() {
|
|
1550
|
+
if (typeof window === 'undefined')
|
|
1551
|
+
return '';
|
|
1552
|
+
return window.location?.pathname || '';
|
|
1553
|
+
}
|
|
1554
|
+
function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
|
|
1555
|
+
return {
|
|
1556
|
+
uvId,
|
|
1557
|
+
isFirstVisit,
|
|
1558
|
+
firstVisitTs: uvMeta.firstVisitTs,
|
|
1559
|
+
visitCount: uvMeta.visitCount,
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
function getAttr(el, attrName) {
|
|
1563
|
+
try {
|
|
1564
|
+
return el.getAttribute(attrName) ?? '';
|
|
1565
|
+
}
|
|
1566
|
+
catch {
|
|
1567
|
+
return '';
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
function truncateText(s, maxLen) {
|
|
1571
|
+
if (!s)
|
|
1572
|
+
return '';
|
|
1573
|
+
if (s.length <= maxLen)
|
|
1574
|
+
return s;
|
|
1575
|
+
return s.slice(0, maxLen);
|
|
1576
|
+
}
|
|
1577
|
+
function installWebBehaviorMonitor(report, options = {}) {
|
|
1578
|
+
const enableTrack = options.enableTrack ?? options.enabled ?? true;
|
|
1579
|
+
if (!enableTrack)
|
|
1580
|
+
return () => { };
|
|
1581
|
+
const pvEnabled = options.pv ?? true;
|
|
1582
|
+
const uvEnabled = options.uv ?? true;
|
|
1583
|
+
const clickEnabled = options.click ?? true;
|
|
1584
|
+
const pvReportType = options.pvReportType ?? 'pv';
|
|
1585
|
+
const uvReportType = options.uvReportType ?? 'uv';
|
|
1586
|
+
const clickReportType = options.clickReportType ?? 'click';
|
|
1587
|
+
const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
|
|
1588
|
+
const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
|
|
1589
|
+
const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
|
|
1590
|
+
const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
|
|
1591
|
+
const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
|
|
1592
|
+
const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? ['body', 'html']).map((s) => String(s).toLowerCase());
|
|
1593
|
+
const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
|
|
1594
|
+
const clickMaxTextLength = options.clickMaxTextLength ?? 120;
|
|
1595
|
+
const getPagePath = options.getPagePath ?? getWebPagePath;
|
|
1596
|
+
let destroyed = false;
|
|
1597
|
+
let firstVisitFlag = false;
|
|
1598
|
+
let firstVisitConsumed = false;
|
|
1599
|
+
const uvStatePromise = (async () => {
|
|
1600
|
+
let existingUvId = readStringStorage(uvIdStorageKey);
|
|
1601
|
+
let isFirstVisit = false;
|
|
2301
1602
|
const now = Date.now();
|
|
2302
|
-
const
|
|
2303
|
-
const
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
return;
|
|
1603
|
+
const metaBefore = safeReadUvMeta(uvMetaStorageKey);
|
|
1604
|
+
const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
|
|
1605
|
+
const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
|
|
1606
|
+
if (expired) {
|
|
1607
|
+
existingUvId = null;
|
|
1608
|
+
writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
|
|
1609
|
+
writeStringStorage(uvIdStorageKey, '');
|
|
2310
1610
|
}
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
// ignore
|
|
1611
|
+
try {
|
|
1612
|
+
if (options.getUvId) {
|
|
1613
|
+
const maybe = options.getUvId();
|
|
1614
|
+
const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
|
|
1615
|
+
if (resolved && typeof resolved === 'string')
|
|
1616
|
+
existingUvId = resolved;
|
|
2318
1617
|
}
|
|
2319
|
-
this.batchTimerDueAt = desiredDueAt;
|
|
2320
|
-
this.batchTimer = setTimeout(() => {
|
|
2321
|
-
void this.flushBatch();
|
|
2322
|
-
}, desiredDelay);
|
|
2323
1618
|
}
|
|
1619
|
+
catch {
|
|
1620
|
+
/* ignore */
|
|
1621
|
+
}
|
|
1622
|
+
if (!existingUvId) {
|
|
1623
|
+
existingUvId = generateUUID();
|
|
1624
|
+
isFirstVisit = true;
|
|
1625
|
+
}
|
|
1626
|
+
writeStringStorage(uvIdStorageKey, existingUvId);
|
|
1627
|
+
const meta = safeReadUvMeta(uvMetaStorageKey);
|
|
1628
|
+
const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
|
|
1629
|
+
const firstVisit = meta.firstVisitTs || now;
|
|
1630
|
+
const nextMeta = {
|
|
1631
|
+
firstVisitTs: firstVisit,
|
|
1632
|
+
visitCount: (meta.visitCount || 0) + 1,
|
|
1633
|
+
createdAtTs: createdAt,
|
|
1634
|
+
lastSeenTs: now,
|
|
1635
|
+
};
|
|
1636
|
+
if (isFirstVisit) {
|
|
1637
|
+
nextMeta.firstVisitTs = now;
|
|
1638
|
+
nextMeta.createdAtTs = now;
|
|
1639
|
+
}
|
|
1640
|
+
writeUvMeta(uvMetaStorageKey, nextMeta);
|
|
1641
|
+
firstVisitFlag = isFirstVisit;
|
|
1642
|
+
return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
|
|
1643
|
+
})();
|
|
1644
|
+
function safeReport(type, data) {
|
|
1645
|
+
if (destroyed)
|
|
1646
|
+
return;
|
|
1647
|
+
if (!shouldSample(options.sampleRate))
|
|
1648
|
+
return;
|
|
1649
|
+
report(type, data);
|
|
1650
|
+
}
|
|
1651
|
+
function buildUvFieldsOnce(uvId, meta) {
|
|
1652
|
+
const once = firstVisitFlag && !firstVisitConsumed;
|
|
1653
|
+
if (once)
|
|
1654
|
+
firstVisitConsumed = true;
|
|
1655
|
+
return buildCommonUvFields(uvId, meta, once);
|
|
1656
|
+
}
|
|
1657
|
+
function reportPv(pagePath) {
|
|
1658
|
+
if (!pvEnabled)
|
|
1659
|
+
return;
|
|
1660
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1661
|
+
if (destroyed)
|
|
1662
|
+
return;
|
|
1663
|
+
const payload = {
|
|
1664
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1665
|
+
timestamp: Date.now(),
|
|
1666
|
+
pagePath,
|
|
1667
|
+
referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
|
|
1668
|
+
};
|
|
1669
|
+
safeReport(pvReportType, payload);
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
// Web PV Listeners
|
|
1673
|
+
let removeWebPvListeners = null;
|
|
1674
|
+
if (pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
|
|
1675
|
+
const originalPushState = window.history.pushState?.bind(window.history);
|
|
1676
|
+
const originalReplaceState = window.history.replaceState?.bind(window.history);
|
|
1677
|
+
const onRouteChanged = () => reportPv(getPagePath());
|
|
1678
|
+
onRouteChanged();
|
|
1679
|
+
if (originalPushState) {
|
|
1680
|
+
window.history.pushState = ((...args) => {
|
|
1681
|
+
const r = originalPushState.apply(window.history, args);
|
|
1682
|
+
onRouteChanged();
|
|
1683
|
+
return r;
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
if (originalReplaceState) {
|
|
1687
|
+
window.history.replaceState = ((...args) => {
|
|
1688
|
+
const r = originalReplaceState.apply(window.history, args);
|
|
1689
|
+
onRouteChanged();
|
|
1690
|
+
return r;
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1693
|
+
window.addEventListener('popstate', onRouteChanged);
|
|
1694
|
+
removeWebPvListeners = () => {
|
|
1695
|
+
window.removeEventListener('popstate', onRouteChanged);
|
|
1696
|
+
if (originalPushState)
|
|
1697
|
+
window.history.pushState = originalPushState;
|
|
1698
|
+
if (originalReplaceState)
|
|
1699
|
+
window.history.replaceState = originalReplaceState;
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
// Web Click Listener
|
|
1703
|
+
let removeWebClickListener = null;
|
|
1704
|
+
if (clickEnabled && typeof document !== 'undefined') {
|
|
1705
|
+
const onClick = (e) => {
|
|
1706
|
+
if (destroyed)
|
|
1707
|
+
return;
|
|
1708
|
+
const target = e.target;
|
|
1709
|
+
if (!target)
|
|
1710
|
+
return;
|
|
1711
|
+
const closestWithTrackId = typeof target.closest === 'function'
|
|
1712
|
+
? target.closest(`[${clickTrackIdAttr}]`)
|
|
1713
|
+
: null;
|
|
1714
|
+
const el = closestWithTrackId || target;
|
|
1715
|
+
const tag = (el.tagName || '').toLowerCase();
|
|
1716
|
+
const trackId = getAttr(el, clickTrackIdAttr);
|
|
1717
|
+
if (clickWhiteList.includes(tag) || !trackId)
|
|
1718
|
+
return;
|
|
1719
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1720
|
+
if (destroyed)
|
|
1721
|
+
return;
|
|
1722
|
+
safeReport(clickReportType, {
|
|
1723
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1724
|
+
timestamp: Date.now(),
|
|
1725
|
+
pagePath: getPagePath(),
|
|
1726
|
+
elementTag: el.tagName || '',
|
|
1727
|
+
elementId: el.id || '',
|
|
1728
|
+
elementClass: stringifyLogValue(el.className ?? ''),
|
|
1729
|
+
trackId: trackId || '',
|
|
1730
|
+
elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
|
|
1731
|
+
clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
|
|
1732
|
+
clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
|
|
1733
|
+
});
|
|
1734
|
+
});
|
|
1735
|
+
};
|
|
1736
|
+
document.addEventListener('click', onClick, true);
|
|
1737
|
+
removeWebClickListener = () => document.removeEventListener('click', onClick, true);
|
|
1738
|
+
}
|
|
1739
|
+
// UV Initial Report
|
|
1740
|
+
if (uvEnabled) {
|
|
1741
|
+
void uvStatePromise.then(({ uvId, meta }) => {
|
|
1742
|
+
if (destroyed)
|
|
1743
|
+
return;
|
|
1744
|
+
safeReport(uvReportType, {
|
|
1745
|
+
...buildUvFieldsOnce(uvId, meta),
|
|
1746
|
+
timestamp: Date.now(),
|
|
1747
|
+
pagePath: getPagePath(),
|
|
1748
|
+
});
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
return () => {
|
|
1752
|
+
destroyed = true;
|
|
1753
|
+
removeWebPvListeners?.();
|
|
1754
|
+
removeWebClickListener?.();
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
function truncate(s, maxLen) {
|
|
1759
|
+
if (!s)
|
|
1760
|
+
return s;
|
|
1761
|
+
return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
|
|
1762
|
+
}
|
|
1763
|
+
function parseUserAgent(uaRaw) {
|
|
1764
|
+
const ua = uaRaw ?? '';
|
|
1765
|
+
const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
|
|
1766
|
+
// OS
|
|
1767
|
+
let osName = 'unknown';
|
|
1768
|
+
let osVersion = '';
|
|
1769
|
+
const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
|
|
1770
|
+
const android = ua.match(/Android (\d+(\.\d+)*)/i);
|
|
1771
|
+
const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
|
|
1772
|
+
const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
|
|
1773
|
+
if (ios) {
|
|
1774
|
+
osName = 'iOS';
|
|
1775
|
+
osVersion = ios[1].replace(/_/g, '.');
|
|
1776
|
+
}
|
|
1777
|
+
else if (android) {
|
|
1778
|
+
osName = 'Android';
|
|
1779
|
+
osVersion = android[1];
|
|
1780
|
+
}
|
|
1781
|
+
else if (win) {
|
|
1782
|
+
osName = 'Windows';
|
|
1783
|
+
osVersion = win[1];
|
|
1784
|
+
}
|
|
1785
|
+
else if (mac) {
|
|
1786
|
+
osName = 'macOS';
|
|
1787
|
+
osVersion = mac[1].replace(/_/g, '.');
|
|
1788
|
+
}
|
|
1789
|
+
// Browser
|
|
1790
|
+
let browserName = 'unknown';
|
|
1791
|
+
let browserVersion = '';
|
|
1792
|
+
const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
|
|
1793
|
+
const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
|
|
1794
|
+
const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
|
|
1795
|
+
const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
|
|
1796
|
+
if (edge) {
|
|
1797
|
+
browserName = 'Edge';
|
|
1798
|
+
browserVersion = edge[1];
|
|
1799
|
+
}
|
|
1800
|
+
else if (chrome) {
|
|
1801
|
+
browserName = 'Chrome';
|
|
1802
|
+
browserVersion = chrome[1];
|
|
1803
|
+
}
|
|
1804
|
+
else if (firefox) {
|
|
1805
|
+
browserName = 'Firefox';
|
|
1806
|
+
browserVersion = firefox[1];
|
|
1807
|
+
}
|
|
1808
|
+
else if (safari) {
|
|
1809
|
+
browserName = 'Safari';
|
|
1810
|
+
browserVersion = safari[1];
|
|
1811
|
+
}
|
|
1812
|
+
return { browserName, browserVersion, osName, osVersion, isMobile };
|
|
1813
|
+
}
|
|
1814
|
+
function getBrowserDeviceInfo(options) {
|
|
1815
|
+
const out = {
|
|
1816
|
+
envType: 'browser',
|
|
1817
|
+
};
|
|
1818
|
+
if (typeof window === 'undefined' || typeof navigator === 'undefined')
|
|
1819
|
+
return out;
|
|
1820
|
+
const ua = String(navigator.userAgent ?? '');
|
|
1821
|
+
const uaParsed = parseUserAgent(ua);
|
|
1822
|
+
if (options.includeUserAgent)
|
|
1823
|
+
out.ua = truncate(ua, 2000);
|
|
1824
|
+
out.browserName = uaParsed.browserName;
|
|
1825
|
+
out.browserVersion = uaParsed.browserVersion;
|
|
1826
|
+
out.osName = uaParsed.osName;
|
|
1827
|
+
out.osVersion = uaParsed.osVersion;
|
|
1828
|
+
out.isMobile = uaParsed.isMobile ? 1 : 0;
|
|
1829
|
+
out.language = String(navigator.language ?? '');
|
|
1830
|
+
out.platform = String(navigator.platform ?? '');
|
|
1831
|
+
try {
|
|
1832
|
+
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1833
|
+
out.timezone = typeof tz === 'string' ? tz : '';
|
|
2324
1834
|
}
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
|
|
2328
|
-
if (startupDelay > 0) {
|
|
2329
|
-
const end = start + startupDelay;
|
|
2330
|
-
if (nowTs < end)
|
|
2331
|
-
return end;
|
|
2332
|
-
}
|
|
2333
|
-
return nowTs + this.batchIntervalMs;
|
|
1835
|
+
catch {
|
|
1836
|
+
out.timezone = '';
|
|
2334
1837
|
}
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
msg = message.message;
|
|
2340
|
-
extra = {
|
|
2341
|
-
stack: message.stack,
|
|
2342
|
-
name: message.name,
|
|
2343
|
-
...data,
|
|
2344
|
-
};
|
|
2345
|
-
}
|
|
2346
|
-
else {
|
|
2347
|
-
msg = String(message);
|
|
2348
|
-
extra = data;
|
|
2349
|
-
}
|
|
2350
|
-
const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
|
|
2351
|
-
this.report({ type: 'info', data: payload, timestamp: Date.now() });
|
|
1838
|
+
try {
|
|
1839
|
+
const s = window.screen;
|
|
1840
|
+
out.screenWidth = s?.width ?? undefined;
|
|
1841
|
+
out.screenHeight = s?.height ?? undefined;
|
|
2352
1842
|
}
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
let extra = {};
|
|
2356
|
-
if (message instanceof Error) {
|
|
2357
|
-
msg = message.message;
|
|
2358
|
-
extra = {
|
|
2359
|
-
stack: message.stack,
|
|
2360
|
-
name: message.name,
|
|
2361
|
-
...data,
|
|
2362
|
-
};
|
|
2363
|
-
}
|
|
2364
|
-
else {
|
|
2365
|
-
msg = String(message);
|
|
2366
|
-
extra = data;
|
|
2367
|
-
}
|
|
2368
|
-
const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
|
|
2369
|
-
this.report({ type: 'warn', data: payload, timestamp: Date.now() });
|
|
1843
|
+
catch {
|
|
1844
|
+
// ignore
|
|
2370
1845
|
}
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
let extra = {};
|
|
2374
|
-
if (message instanceof Error) {
|
|
2375
|
-
msg = message.message;
|
|
2376
|
-
extra = {
|
|
2377
|
-
stack: message.stack,
|
|
2378
|
-
name: message.name,
|
|
2379
|
-
...data,
|
|
2380
|
-
};
|
|
2381
|
-
}
|
|
2382
|
-
else {
|
|
2383
|
-
msg = String(message);
|
|
2384
|
-
extra = data;
|
|
2385
|
-
}
|
|
2386
|
-
const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
|
|
2387
|
-
this.report({ type: 'error', data: payload, timestamp: Date.now() });
|
|
1846
|
+
try {
|
|
1847
|
+
out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
|
|
2388
1848
|
}
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
return;
|
|
2392
|
-
this.report({
|
|
2393
|
-
type: trackType,
|
|
2394
|
-
data: normalizeFlatFields(data, `track:${trackType}`),
|
|
2395
|
-
timestamp: Date.now(),
|
|
2396
|
-
});
|
|
1849
|
+
catch {
|
|
1850
|
+
// ignore
|
|
2397
1851
|
}
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
if (this.batchTimer) {
|
|
2403
|
-
clearTimeout(this.batchTimer);
|
|
2404
|
-
this.batchTimer = null;
|
|
2405
|
-
}
|
|
2406
|
-
this.batchTimerDueAt = null;
|
|
2407
|
-
if (this.memoryQueue.length === 0)
|
|
2408
|
-
return;
|
|
2409
|
-
const logs = [...this.memoryQueue];
|
|
2410
|
-
this.memoryQueue = [];
|
|
2411
|
-
try {
|
|
2412
|
-
await this.sendReportLogs(logs);
|
|
2413
|
-
}
|
|
2414
|
-
catch {
|
|
2415
|
-
this.retrySendReportLogs(logs, 1);
|
|
2416
|
-
}
|
|
1852
|
+
try {
|
|
1853
|
+
const navAny = navigator;
|
|
1854
|
+
out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
|
|
1855
|
+
out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
|
|
2417
1856
|
}
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
const base = this.getBaseFields();
|
|
2421
|
-
const data = normalizeFlatFields(log.data ?? {}, 'report:data');
|
|
2422
|
-
const mergedData = mergeFields(base, data);
|
|
2423
|
-
return {
|
|
2424
|
-
timestamp: ts,
|
|
2425
|
-
type: log.type,
|
|
2426
|
-
envType: this.envType,
|
|
2427
|
-
projectId: this.projectId || undefined,
|
|
2428
|
-
projectName: this.projectName || undefined,
|
|
2429
|
-
appId: this.appId || undefined,
|
|
2430
|
-
appVersion: this.appVersion || undefined,
|
|
2431
|
-
// 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
|
|
2432
|
-
...mergedData,
|
|
2433
|
-
};
|
|
1857
|
+
catch {
|
|
1858
|
+
// ignore
|
|
2434
1859
|
}
|
|
2435
|
-
|
|
2436
|
-
if (!this.topicId)
|
|
2437
|
-
return;
|
|
2438
|
-
const sdk = await this.loadSdk();
|
|
2439
|
-
const client = await this.getInstance();
|
|
2440
|
-
const logGroup = new sdk.LogGroup('127.0.0.1');
|
|
2441
|
-
logGroup.setSource(this.source);
|
|
2442
|
-
for (const item of logs) {
|
|
2443
|
-
const fields = this.buildReportFields(item);
|
|
2444
|
-
const log = new sdk.Log(fields.timestamp);
|
|
2445
|
-
for (const key of Object.keys(fields)) {
|
|
2446
|
-
if (key === 'timestamp')
|
|
2447
|
-
continue;
|
|
2448
|
-
log.addContent(key, stringifyLogValue(fields[key]));
|
|
2449
|
-
}
|
|
2450
|
-
logGroup.addLog(log);
|
|
2451
|
-
}
|
|
2452
|
-
const request = new sdk.PutLogsRequest(this.topicId, logGroup);
|
|
2453
|
-
// 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
|
|
2454
|
-
const exit = enterClsSendingGuard();
|
|
2455
|
-
let p;
|
|
1860
|
+
if (options.includeNetwork) {
|
|
2456
1861
|
try {
|
|
2457
|
-
|
|
1862
|
+
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
|
|
1863
|
+
if (conn && isPlainObject(conn)) {
|
|
1864
|
+
if (typeof conn.effectiveType === 'string')
|
|
1865
|
+
out.netEffectiveType = conn.effectiveType;
|
|
1866
|
+
if (typeof conn.downlink === 'number')
|
|
1867
|
+
out.netDownlink = conn.downlink;
|
|
1868
|
+
if (typeof conn.rtt === 'number')
|
|
1869
|
+
out.netRtt = conn.rtt;
|
|
1870
|
+
if (typeof conn.saveData === 'boolean')
|
|
1871
|
+
out.netSaveData = conn.saveData ? 1 : 0;
|
|
1872
|
+
}
|
|
2458
1873
|
}
|
|
2459
|
-
|
|
2460
|
-
|
|
1874
|
+
catch {
|
|
1875
|
+
// ignore
|
|
2461
1876
|
}
|
|
2462
|
-
await p;
|
|
2463
1877
|
}
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
1878
|
+
return out;
|
|
1879
|
+
}
|
|
1880
|
+
function createWebDeviceInfoBaseFields(opts) {
|
|
1881
|
+
const enabled = opts === undefined ? true : !!opts;
|
|
1882
|
+
if (!enabled)
|
|
1883
|
+
return null;
|
|
1884
|
+
const raw = typeof opts === 'object' && opts ? opts : {};
|
|
1885
|
+
const options = {
|
|
1886
|
+
includeUserAgent: raw.includeUserAgent ?? true,
|
|
1887
|
+
includeNetwork: raw.includeNetwork ?? true,
|
|
1888
|
+
includeNetworkType: raw.includeNetworkType ?? true,
|
|
1889
|
+
};
|
|
1890
|
+
let base = null;
|
|
1891
|
+
const globalKey = '__beLinkClsLoggerDeviceInfo__';
|
|
1892
|
+
return () => {
|
|
1893
|
+
if (!base) {
|
|
1894
|
+
base = getBrowserDeviceInfo(options);
|
|
2471
1895
|
try {
|
|
2472
|
-
|
|
1896
|
+
const g = globalThis;
|
|
1897
|
+
if (!g[globalKey])
|
|
1898
|
+
g[globalKey] = { ...base };
|
|
2473
1899
|
}
|
|
2474
1900
|
catch {
|
|
2475
|
-
|
|
1901
|
+
// ignore
|
|
2476
1902
|
}
|
|
2477
|
-
}, delayMs);
|
|
2478
|
-
}
|
|
2479
|
-
cacheFailedReportLogs(logs) {
|
|
2480
|
-
const raw = readStringStorage(this.failedCacheKey);
|
|
2481
|
-
let current = [];
|
|
2482
|
-
try {
|
|
2483
|
-
const parsed = raw ? JSON.parse(raw) : [];
|
|
2484
|
-
current = Array.isArray(parsed) ? parsed : [];
|
|
2485
1903
|
}
|
|
2486
|
-
catch {
|
|
2487
|
-
current = [];
|
|
2488
|
-
}
|
|
2489
|
-
const next = [...current, ...logs].slice(-this.failedCacheMax);
|
|
2490
|
-
writeStringStorage(this.failedCacheKey, JSON.stringify(next));
|
|
2491
|
-
}
|
|
2492
|
-
flushFailed() {
|
|
2493
|
-
if (!this.enabled)
|
|
2494
|
-
return;
|
|
2495
|
-
const raw = readStringStorage(this.failedCacheKey);
|
|
2496
|
-
if (!raw)
|
|
2497
|
-
return;
|
|
2498
|
-
let logs = [];
|
|
2499
1904
|
try {
|
|
2500
|
-
const
|
|
2501
|
-
|
|
1905
|
+
const g = globalThis;
|
|
1906
|
+
const extra = g[globalKey];
|
|
1907
|
+
if (extra && isPlainObject(extra))
|
|
1908
|
+
return { ...base, ...extra };
|
|
2502
1909
|
}
|
|
2503
1910
|
catch {
|
|
2504
|
-
|
|
1911
|
+
// ignore
|
|
2505
1912
|
}
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
// 先清空,再尝试发送
|
|
2509
|
-
writeStringStorage(this.failedCacheKey, JSON.stringify([]));
|
|
2510
|
-
this.memoryQueue.unshift(...logs);
|
|
2511
|
-
void this.flushBatch();
|
|
2512
|
-
}
|
|
2513
|
-
/**
|
|
2514
|
-
* 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
|
|
2515
|
-
*/
|
|
2516
|
-
stat(param) {
|
|
2517
|
-
if (!param)
|
|
2518
|
-
return;
|
|
2519
|
-
const payload = normalizeFlatFields({
|
|
2520
|
-
pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
|
|
2521
|
-
projectId: this.projectId,
|
|
2522
|
-
projectName: this.projectName,
|
|
2523
|
-
...param,
|
|
2524
|
-
data: param.data ?? 1,
|
|
2525
|
-
}, 'stat');
|
|
2526
|
-
this.report({ type: 'stat', data: payload, timestamp: Date.now() });
|
|
2527
|
-
}
|
|
2528
|
-
}
|
|
2529
|
-
|
|
2530
|
-
function readGlobal(key) {
|
|
2531
|
-
try {
|
|
2532
|
-
const g = globalThis;
|
|
2533
|
-
return g[key] ?? null;
|
|
2534
|
-
}
|
|
2535
|
-
catch {
|
|
2536
|
-
return null;
|
|
2537
|
-
}
|
|
1913
|
+
return base;
|
|
1914
|
+
};
|
|
2538
1915
|
}
|
|
2539
1916
|
|
|
2540
1917
|
// 静态引用 web sdk
|
|
@@ -2556,6 +1933,21 @@ class ClsLoggerWeb extends ClsLoggerCore {
|
|
|
2556
1933
|
this.sdk = this.normalize(WebSdk__namespace);
|
|
2557
1934
|
return this.sdk;
|
|
2558
1935
|
}
|
|
1936
|
+
installRequestMonitor(report, options) {
|
|
1937
|
+
installWebRequestMonitor(report, options);
|
|
1938
|
+
}
|
|
1939
|
+
installErrorMonitor(report, options) {
|
|
1940
|
+
installWebErrorMonitor(report, options);
|
|
1941
|
+
}
|
|
1942
|
+
installPerformanceMonitor(report, options) {
|
|
1943
|
+
installWebPerformanceMonitor(report, options);
|
|
1944
|
+
}
|
|
1945
|
+
installBehaviorMonitor(report, options) {
|
|
1946
|
+
return installWebBehaviorMonitor(report, typeof options === 'boolean' ? {} : options);
|
|
1947
|
+
}
|
|
1948
|
+
createDeviceInfoBaseFields(options) {
|
|
1949
|
+
return createWebDeviceInfoBaseFields(options);
|
|
1950
|
+
}
|
|
2559
1951
|
normalize(m) {
|
|
2560
1952
|
const mod = (m?.default && m.default.AsyncClient ? m.default : m);
|
|
2561
1953
|
return {
|