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