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