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