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