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