@be-link/cls-logger 1.0.1-beta.2 → 1.0.1-beta.21

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.
Files changed (53) hide show
  1. package/README.md +356 -32
  2. package/dist/ClsLogger.d.ts +15 -96
  3. package/dist/ClsLogger.d.ts.map +1 -1
  4. package/dist/ClsLoggerCore.d.ts +177 -0
  5. package/dist/ClsLoggerCore.d.ts.map +1 -0
  6. package/dist/behaviorMonitor.d.ts.map +1 -1
  7. package/dist/clsSdkTypes.d.ts +18 -0
  8. package/dist/clsSdkTypes.d.ts.map +1 -0
  9. package/dist/deviceInfo.d.ts.map +1 -1
  10. package/dist/errorMonitor.d.ts.map +1 -1
  11. package/dist/index.esm.js +2246 -1396
  12. package/dist/index.js +2246 -1396
  13. package/dist/index.umd.js +2249 -1399
  14. package/dist/mini/ClsLogger.d.ts +14 -0
  15. package/dist/mini/ClsLogger.d.ts.map +1 -0
  16. package/dist/mini/behaviorMonitor.d.ts +5 -0
  17. package/dist/mini/behaviorMonitor.d.ts.map +1 -0
  18. package/dist/mini/deviceInfo.d.ts +3 -0
  19. package/dist/mini/deviceInfo.d.ts.map +1 -0
  20. package/dist/mini/errorMonitor.d.ts +5 -0
  21. package/dist/mini/errorMonitor.d.ts.map +1 -0
  22. package/dist/mini/performanceMonitor.d.ts +5 -0
  23. package/dist/mini/performanceMonitor.d.ts.map +1 -0
  24. package/dist/mini/requestMonitor.d.ts +9 -0
  25. package/dist/mini/requestMonitor.d.ts.map +1 -0
  26. package/dist/mini.d.ts +6 -0
  27. package/dist/mini.d.ts.map +1 -0
  28. package/dist/mini.esm.js +1945 -0
  29. package/dist/mini.js +1970 -0
  30. package/dist/performanceMonitor.d.ts.map +1 -1
  31. package/dist/requestMonitor.d.ts +1 -5
  32. package/dist/requestMonitor.d.ts.map +1 -1
  33. package/dist/sdkUtils.d.ts +3 -0
  34. package/dist/sdkUtils.d.ts.map +1 -0
  35. package/dist/types.d.ts +99 -14
  36. package/dist/types.d.ts.map +1 -1
  37. package/dist/web/ClsLogger.d.ts +14 -0
  38. package/dist/web/ClsLogger.d.ts.map +1 -0
  39. package/dist/web/behaviorMonitor.d.ts +5 -0
  40. package/dist/web/behaviorMonitor.d.ts.map +1 -0
  41. package/dist/web/deviceInfo.d.ts +3 -0
  42. package/dist/web/deviceInfo.d.ts.map +1 -0
  43. package/dist/web/errorMonitor.d.ts +5 -0
  44. package/dist/web/errorMonitor.d.ts.map +1 -0
  45. package/dist/web/performanceMonitor.d.ts +5 -0
  46. package/dist/web/performanceMonitor.d.ts.map +1 -0
  47. package/dist/web/requestMonitor.d.ts +5 -0
  48. package/dist/web/requestMonitor.d.ts.map +1 -0
  49. package/dist/web.d.ts +6 -0
  50. package/dist/web.d.ts.map +1 -0
  51. package/dist/web.esm.js +2094 -0
  52. package/dist/web.js +2119 -0
  53. package/package.json +36 -2
@@ -0,0 +1,2094 @@
1
+ import * as tencentcloudClsSdkJsWeb from 'tencentcloud-cls-sdk-js-web';
2
+ import { onFCP, onLCP, onCLS, onINP, onTTFB } from 'web-vitals';
3
+
4
+ function isPlainObject(value) {
5
+ return Object.prototype.toString.call(value) === '[object Object]';
6
+ }
7
+ function isFlatFieldValue(value) {
8
+ return (value === null ||
9
+ value === undefined ||
10
+ typeof value === 'string' ||
11
+ typeof value === 'number' ||
12
+ typeof value === 'boolean' ||
13
+ typeof value === 'bigint');
14
+ }
15
+ /**
16
+ * 把任意对象字段“规范化”为一维对象:
17
+ * - 原始值保持不变
18
+ * - 非原始值(对象/数组/函数等)会被 stringify 成 string
19
+ * - 若发现非一维字段,会触发一次 warn(避免刷屏)
20
+ */
21
+ function normalizeFlatFields(fields, warnOnceKey) {
22
+ const out = {};
23
+ let hasNonFlat = false;
24
+ for (const k of Object.keys(fields ?? {})) {
25
+ const v = fields[k];
26
+ if (isFlatFieldValue(v)) {
27
+ out[k] = v;
28
+ continue;
29
+ }
30
+ hasNonFlat = true;
31
+ out[k] = stringifyLogValue(v);
32
+ }
33
+ if (hasNonFlat && warnOnceKey) {
34
+ const g = globalThis;
35
+ if (!g.__beLinkClsLoggerWarned__)
36
+ g.__beLinkClsLoggerWarned__ = {};
37
+ if (!g.__beLinkClsLoggerWarned__?.[warnOnceKey]) {
38
+ g.__beLinkClsLoggerWarned__[warnOnceKey] = true;
39
+ // eslint-disable-next-line no-console
40
+ console.warn(`ClsLogger:检测到非一维字段(嵌套对象/数组等),已自动 stringify;key=${warnOnceKey}`);
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+ function safeJsonParse(value, fallback) {
46
+ if (!value)
47
+ return fallback;
48
+ try {
49
+ return JSON.parse(value);
50
+ }
51
+ catch {
52
+ return fallback;
53
+ }
54
+ }
55
+ function canUseStorage() {
56
+ try {
57
+ if (typeof window === 'undefined')
58
+ return false;
59
+ if (!window.localStorage)
60
+ return false;
61
+ const k = '__be_link_cls_logger__';
62
+ window.localStorage.setItem(k, '1');
63
+ window.localStorage.removeItem(k);
64
+ return true;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ function isMiniProgramEnv() {
71
+ const wxAny = globalThis.wx;
72
+ return !!(wxAny && typeof wxAny.getSystemInfoSync === 'function');
73
+ }
74
+ function readQueue(storageKey) {
75
+ if (!canUseStorage())
76
+ return [];
77
+ const raw = window.localStorage.getItem(storageKey);
78
+ const parsed = safeJsonParse(raw, []);
79
+ return Array.isArray(parsed) ? parsed : [];
80
+ }
81
+ function writeQueue(storageKey, queue) {
82
+ if (!canUseStorage())
83
+ return;
84
+ window.localStorage.setItem(storageKey, JSON.stringify(queue));
85
+ }
86
+ function readStringStorage(key) {
87
+ if (isMiniProgramEnv()) {
88
+ const wxAny = globalThis.wx;
89
+ try {
90
+ const v = wxAny.getStorageSync(key);
91
+ return typeof v === 'string' ? v : v ? String(v) : null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ if (!canUseStorage())
98
+ return null;
99
+ return window.localStorage.getItem(key);
100
+ }
101
+ function writeStringStorage(key, value) {
102
+ if (isMiniProgramEnv()) {
103
+ const wxAny = globalThis.wx;
104
+ try {
105
+ wxAny.setStorageSync(key, value);
106
+ }
107
+ catch {
108
+ // ignore
109
+ }
110
+ return;
111
+ }
112
+ if (!canUseStorage())
113
+ return;
114
+ window.localStorage.setItem(key, value);
115
+ }
116
+ function mergeFields(base, fields) {
117
+ if (!base || !isPlainObject(base))
118
+ return fields;
119
+ // base 覆盖 fields:保证基础字段优先级更高(兼容历史行为)
120
+ return { ...fields, ...base };
121
+ }
122
+ function stringifyLogValue(v) {
123
+ if (v === null || v === undefined)
124
+ return '';
125
+ if (typeof v === 'string')
126
+ return v;
127
+ if (typeof v === 'number' || typeof v === 'boolean' || typeof v === 'bigint')
128
+ return String(v);
129
+ try {
130
+ return JSON.stringify(v);
131
+ }
132
+ catch {
133
+ return String(v);
134
+ }
135
+ }
136
+
137
+ function enterClsSendingGuard() {
138
+ const g = globalThis;
139
+ const next = (g.__beLinkClsLoggerSendingCount__ ?? 0) + 1;
140
+ g.__beLinkClsLoggerSendingCount__ = next;
141
+ return () => {
142
+ const cur = g.__beLinkClsLoggerSendingCount__ ?? 0;
143
+ g.__beLinkClsLoggerSendingCount__ = cur > 0 ? cur - 1 : 0;
144
+ };
145
+ }
146
+ /**
147
+ * CLS Logger 核心基类
148
+ * - 负责所有上报、队列、监控逻辑
149
+ * - 不包含具体的 SDK 加载实现(由子类负责)
150
+ * - 这样可以把 web/mini 的 SDK 依赖彻底解耦到子入口
151
+ */
152
+ class ClsLoggerCore {
153
+ constructor() {
154
+ this.sdk = null;
155
+ this.sdkPromise = null;
156
+ this.sdkOverride = null;
157
+ this.sdkLoaderOverride = null;
158
+ this.client = null;
159
+ this.clientPromise = null;
160
+ this.topicId = '17475bcd-6315-4b20-859c-e7b087fb3683';
161
+ this.endpoint = 'https://ap-shanghai.cls.tencentcs.com';
162
+ this.retryTimes = 3;
163
+ this.source = '127.0.0.1';
164
+ this.enabled = true;
165
+ this.projectId = '';
166
+ this.projectName = '';
167
+ this.appId = '';
168
+ this.appVersion = '';
169
+ this.envType = 'browser';
170
+ this.userGenerateBaseFields = null;
171
+ this.autoGenerateBaseFields = null;
172
+ this.storageKey = 'beLink_logs';
173
+ this.batchSize = 15;
174
+ // 参考文档:内存队列批量发送(500ms 或 20 条触发)
175
+ this.memoryQueue = [];
176
+ this.batchMaxSize = 20;
177
+ this.batchIntervalMs = 500;
178
+ this.batchTimer = null;
179
+ this.batchTimerDueAt = null;
180
+ this.initTs = 0;
181
+ this.startupDelayMs = 0;
182
+ this.useIdleCallback = false;
183
+ this.idleTimeout = 3000;
184
+ this.visibilityCleanup = null;
185
+ // 参考文档:失败缓存 + 重试
186
+ this.failedCacheKey = 'cls_failed_logs';
187
+ this.failedCacheMax = 200;
188
+ this.requestMonitorStarted = false;
189
+ this.errorMonitorStarted = false;
190
+ this.performanceMonitorStarted = false;
191
+ this.behaviorMonitorStarted = false;
192
+ this.behaviorMonitorCleanup = null;
193
+ }
194
+ /**
195
+ * 子类可按需重写(默认检测 wx)
196
+ */
197
+ detectEnvType() {
198
+ const g = globalThis;
199
+ // 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
200
+ if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
201
+ (g.my && typeof g.my.getSystemInfoSync === 'function') ||
202
+ (g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
203
+ (g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
204
+ return 'miniprogram';
205
+ }
206
+ return 'browser';
207
+ }
208
+ init(options) {
209
+ this.initTs = Date.now();
210
+ const topicId = options?.tencentCloud?.topicID ?? options?.topic_id ?? options?.topicID ?? this.topicId;
211
+ const endpoint = options?.tencentCloud?.endpoint ?? options?.endpoint ?? this.endpoint;
212
+ const retryTimes = options?.tencentCloud?.retry_times ?? options?.retry_times ?? this.retryTimes;
213
+ const source = options?.source ?? this.source;
214
+ if (!topicId) {
215
+ // eslint-disable-next-line no-console
216
+ console.warn('ClsLogger.init 没有传 topicID/topic_id');
217
+ return;
218
+ }
219
+ const nextEnvType = options.envType ?? this.detectEnvType();
220
+ // envType/endpoint/retryTimes 变化时:重置 client(以及可能的 sdk)
221
+ const envChanged = nextEnvType !== this.envType;
222
+ const endpointChanged = endpoint !== this.endpoint;
223
+ const retryChanged = retryTimes !== this.retryTimes;
224
+ if (envChanged || endpointChanged || retryChanged) {
225
+ this.client = null;
226
+ this.clientPromise = null;
227
+ }
228
+ if (envChanged) {
229
+ this.sdk = null;
230
+ this.sdkPromise = null;
231
+ }
232
+ this.topicId = topicId;
233
+ this.endpoint = endpoint;
234
+ this.retryTimes = retryTimes;
235
+ this.source = source;
236
+ this.userId = options.userId ?? this.userId;
237
+ this.userName = options.userName ?? this.userName;
238
+ this.projectId = options.projectId ?? this.projectId;
239
+ this.projectName = options.projectName ?? this.projectName;
240
+ this.appId = options.appId ?? this.appId;
241
+ this.appVersion = options.appVersion ?? this.appVersion;
242
+ this.envType = nextEnvType;
243
+ this.enabled = options.enabled ?? true;
244
+ // 可选:外部注入 SDK(优先级:sdkLoader > sdk)
245
+ this.sdkLoaderOverride = options.sdkLoader ?? this.sdkLoaderOverride;
246
+ this.sdkOverride = options.sdk ?? this.sdkOverride;
247
+ this.userGenerateBaseFields = options.generateBaseFields ?? this.userGenerateBaseFields;
248
+ this.autoGenerateBaseFields = this.createDeviceInfoBaseFields(options.deviceInfo);
249
+ this.storageKey = options.storageKey ?? this.storageKey;
250
+ this.batchSize = options.batchSize ?? this.batchSize;
251
+ this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
252
+ this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
253
+ this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
254
+ this.useIdleCallback = options.batch?.useIdleCallback ?? this.useIdleCallback;
255
+ this.idleTimeout = options.batch?.idleTimeout ?? this.idleTimeout;
256
+ this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
257
+ this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
258
+ // 预热(避免首条日志触发 import/初始化开销)
259
+ void this.getInstance().catch(() => {
260
+ // ignore
261
+ });
262
+ if (this.enabled) {
263
+ // 启动时尝试发送失败缓存
264
+ this.flushFailed();
265
+ // 添加页面可见性监听(确保页面关闭时数据不丢失)
266
+ this.setupVisibilityListener();
267
+ // 初始化后立即启动请求监听
268
+ this.startRequestMonitor(options.requestMonitor);
269
+ // 初始化后立即启动错误监控/性能监控
270
+ this.startErrorMonitor(options.errorMonitor);
271
+ this.startPerformanceMonitor(options.performanceMonitor);
272
+ // 初始化后立即启动行为埋点(PV/UV/点击)
273
+ this.startBehaviorMonitor(options.behaviorMonitor);
274
+ }
275
+ }
276
+ getBaseFields() {
277
+ let auto = undefined;
278
+ let user = undefined;
279
+ try {
280
+ const autoRaw = this.autoGenerateBaseFields ? this.autoGenerateBaseFields() : undefined;
281
+ if (autoRaw && isPlainObject(autoRaw))
282
+ auto = normalizeFlatFields(autoRaw, 'deviceInfo');
283
+ }
284
+ catch {
285
+ auto = undefined;
286
+ }
287
+ try {
288
+ const userRaw = this.userGenerateBaseFields ? this.userGenerateBaseFields() : undefined;
289
+ if (userRaw && isPlainObject(userRaw))
290
+ user = normalizeFlatFields({ ...userRaw }, 'generateBaseFields');
291
+ }
292
+ catch {
293
+ user = undefined;
294
+ }
295
+ if (auto && user)
296
+ return mergeFields(user, auto);
297
+ if (user)
298
+ return user;
299
+ if (auto)
300
+ return auto;
301
+ return undefined;
302
+ }
303
+ /**
304
+ * 设置页面可见性监听
305
+ * - visibilitychange: 页面隐藏时使用 sendBeacon 发送队列
306
+ * - pagehide: 作为移动端 fallback
307
+ */
308
+ setupVisibilityListener() {
309
+ if (typeof document === 'undefined' || typeof window === 'undefined')
310
+ return;
311
+ // 避免重复监听
312
+ if (this.visibilityCleanup)
313
+ return;
314
+ const handleVisibilityChange = () => {
315
+ if (document.visibilityState === 'hidden') {
316
+ this.flushBatchSync();
317
+ }
318
+ };
319
+ const handlePageHide = () => {
320
+ this.flushBatchSync();
321
+ };
322
+ document.addEventListener('visibilitychange', handleVisibilityChange);
323
+ window.addEventListener('pagehide', handlePageHide);
324
+ this.visibilityCleanup = () => {
325
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
326
+ window.removeEventListener('pagehide', handlePageHide);
327
+ };
328
+ }
329
+ /**
330
+ * 同步发送内存队列(使用 sendBeacon)
331
+ * - 用于页面关闭时确保数据发送
332
+ * - sendBeacon 不可用时降级为缓存到 localStorage
333
+ */
334
+ flushBatchSync() {
335
+ if (this.memoryQueue.length === 0)
336
+ return;
337
+ // 清除定时器
338
+ if (this.batchTimer) {
339
+ try {
340
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
341
+ cancelIdleCallback(this.batchTimer);
342
+ }
343
+ else {
344
+ clearTimeout(this.batchTimer);
345
+ }
346
+ }
347
+ catch {
348
+ // ignore
349
+ }
350
+ this.batchTimer = null;
351
+ }
352
+ this.batchTimerDueAt = null;
353
+ const logs = [...this.memoryQueue];
354
+ this.memoryQueue = [];
355
+ // 优先使用 sendBeacon(页面关闭时可靠发送)
356
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
357
+ try {
358
+ const payload = this.buildSendBeaconPayload(logs);
359
+ const blob = new Blob([payload], { type: 'application/json' });
360
+ const url = `${this.endpoint}/structuredlog?topic_id=${this.topicId}`;
361
+ const success = navigator.sendBeacon(url, blob);
362
+ if (!success) {
363
+ // sendBeacon 返回 false 时,降级缓存
364
+ this.cacheFailedReportLogs(logs);
365
+ }
366
+ }
367
+ catch {
368
+ this.cacheFailedReportLogs(logs);
369
+ }
370
+ }
371
+ else {
372
+ // 不支持 sendBeacon,降级缓存到 localStorage
373
+ this.cacheFailedReportLogs(logs);
374
+ }
375
+ }
376
+ /**
377
+ * 构建 sendBeacon 的 payload
378
+ */
379
+ buildSendBeaconPayload(logs) {
380
+ const logList = logs.map((log) => this.buildReportFields(log));
381
+ return JSON.stringify({
382
+ source: this.source,
383
+ logs: logList,
384
+ });
385
+ }
386
+ startRequestMonitor(requestMonitor) {
387
+ if (this.requestMonitorStarted)
388
+ return;
389
+ // 默认开启;传 false 则关闭
390
+ const enabled = requestMonitor === undefined ? true : !!requestMonitor;
391
+ if (!enabled)
392
+ return;
393
+ const opts = typeof requestMonitor === 'object' && requestMonitor ? requestMonitor : {};
394
+ this.requestMonitorStarted = true;
395
+ this.installRequestMonitor((type, data) => {
396
+ this.track(type, data);
397
+ }, {
398
+ ...opts,
399
+ enabled: opts.enabled ?? true,
400
+ clsEndpoint: this.endpoint,
401
+ });
402
+ }
403
+ startErrorMonitor(errorMonitor) {
404
+ if (this.errorMonitorStarted)
405
+ return;
406
+ const enabled = errorMonitor === undefined ? true : !!errorMonitor;
407
+ if (!enabled)
408
+ return;
409
+ this.errorMonitorStarted = true;
410
+ this.installErrorMonitor((type, data) => this.track(type, data), errorMonitor ?? true);
411
+ }
412
+ startPerformanceMonitor(performanceMonitor) {
413
+ if (this.performanceMonitorStarted)
414
+ return;
415
+ const enabled = performanceMonitor === undefined ? true : !!performanceMonitor;
416
+ if (!enabled)
417
+ return;
418
+ this.performanceMonitorStarted = true;
419
+ this.installPerformanceMonitor((type, data) => this.track(type, data), performanceMonitor ?? true);
420
+ }
421
+ startBehaviorMonitor(behaviorMonitor) {
422
+ if (this.behaviorMonitorStarted)
423
+ return;
424
+ const enabled = behaviorMonitor === undefined ? true : !!behaviorMonitor;
425
+ if (!enabled)
426
+ return;
427
+ this.behaviorMonitorStarted = true;
428
+ this.behaviorMonitorCleanup = this.installBehaviorMonitor((type, data) => {
429
+ this.track(type, data);
430
+ }, behaviorMonitor ?? true);
431
+ }
432
+ /**
433
+ * 停止行为埋点监听(PV/UV/点击)
434
+ * - 如需重启:可再次调用 init(或自行调用 init 后的默认启动逻辑)
435
+ */
436
+ stopBehaviorMonitor() {
437
+ try {
438
+ this.behaviorMonitorCleanup?.();
439
+ }
440
+ catch {
441
+ // ignore
442
+ }
443
+ this.behaviorMonitorCleanup = null;
444
+ this.behaviorMonitorStarted = false;
445
+ }
446
+ /**
447
+ * 获取 CLS client(按环境懒加载 SDK)
448
+ */
449
+ async getInstance() {
450
+ if (this.client)
451
+ return this.client;
452
+ if (this.clientPromise)
453
+ return this.clientPromise;
454
+ this.clientPromise = this.loadSdk()
455
+ .then(({ AsyncClient }) => {
456
+ const client = new AsyncClient({
457
+ endpoint: this.endpoint,
458
+ retry_times: this.retryTimes,
459
+ });
460
+ this.client = client;
461
+ return client;
462
+ })
463
+ .catch((err) => {
464
+ // 失败后允许下次重试
465
+ this.clientPromise = null;
466
+ throw err;
467
+ });
468
+ return this.clientPromise;
469
+ }
470
+ /**
471
+ * 直接上报:埋点入参必须是一维(扁平)Object
472
+ * - 非原始值(对象/数组等)会被自动 stringify 成 string
473
+ * - 最终会把 fields 展开成 CLS 的 content(key/value 都会转成 string)
474
+ */
475
+ put(fields, options = {}) {
476
+ if (!this.enabled)
477
+ return;
478
+ if (!fields)
479
+ return;
480
+ if (!this.topicId) {
481
+ // eslint-disable-next-line no-console
482
+ console.warn('ClsLogger.put:未初始化 topic_id');
483
+ return;
484
+ }
485
+ const mergeBaseFields = options.mergeBaseFields ?? true;
486
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
487
+ const normalizedFields = normalizeFlatFields(fields, 'put');
488
+ const finalFields = mergeFields(base, {
489
+ projectId: this.projectId || undefined,
490
+ projectName: this.projectName || undefined,
491
+ envType: this.envType,
492
+ appId: this.appId || undefined,
493
+ appVersion: this.appVersion || undefined,
494
+ ...normalizedFields,
495
+ });
496
+ // 同步 API:内部异步发送,避免把网络异常冒泡到业务(尤其小程序)
497
+ void this.putAsync(finalFields).catch(() => {
498
+ // ignore
499
+ });
500
+ }
501
+ async putAsync(finalFields) {
502
+ if (!this.topicId)
503
+ return;
504
+ const sdk = await this.loadSdk();
505
+ const client = await this.getInstance();
506
+ const logGroup = new sdk.LogGroup('127.0.0.1');
507
+ logGroup.setSource(this.source);
508
+ const log = new sdk.Log(Date.now());
509
+ for (const key of Object.keys(finalFields)) {
510
+ log.addContent(key, stringifyLogValue(finalFields[key]));
511
+ }
512
+ logGroup.addLog(log);
513
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
514
+ const exit = enterClsSendingGuard();
515
+ let p;
516
+ try {
517
+ p = client.PutLogs(request);
518
+ }
519
+ finally {
520
+ exit();
521
+ }
522
+ await p;
523
+ }
524
+ /**
525
+ * 直接上报:把 data 序列化后放入指定 key(默认 “日志内容”)
526
+ */
527
+ putJson(data, clsLoggerKey = '日志内容', options = {}) {
528
+ // put 的入参要求扁平;这里直接把数据序列化为 string
529
+ this.put({ [clsLoggerKey]: stringifyLogValue(data) }, options);
530
+ }
531
+ /**
532
+ * 入队:写入 localStorage 队列;达到 batchSize 自动 flush
533
+ * - 埋点入参必须是一维(扁平)Object,非原始值会被 stringify
534
+ */
535
+ enqueue(fields, options = {}) {
536
+ if (!this.enabled)
537
+ return;
538
+ if (!fields)
539
+ return;
540
+ const time = Date.now();
541
+ const mergeBaseFields = options.mergeBaseFields ?? true;
542
+ const base = mergeBaseFields ? this.getBaseFields() : undefined;
543
+ const normalizedFields = normalizeFlatFields(fields, 'enqueue');
544
+ const finalFields = mergeFields(base, {
545
+ projectId: this.projectId || undefined,
546
+ projectName: this.projectName || undefined,
547
+ envType: this.envType,
548
+ appId: this.appId || undefined,
549
+ appVersion: this.appVersion || undefined,
550
+ ...normalizedFields,
551
+ });
552
+ const queue = readQueue(this.storageKey);
553
+ const next = [...queue, { time, data: finalFields }];
554
+ if (next.length < this.batchSize) {
555
+ writeQueue(this.storageKey, next);
556
+ return;
557
+ }
558
+ // 达到阈值:flush + 写入新的队列(避免并发下丢失,按“先 flush 旧的”策略)
559
+ this.putBatch(queue);
560
+ writeQueue(this.storageKey, [{ time, data: finalFields }]);
561
+ }
562
+ /**
563
+ * 从 localStorage 读取队列并批量上报
564
+ */
565
+ flush() {
566
+ const queue = readQueue(this.storageKey);
567
+ if (queue.length === 0)
568
+ return;
569
+ this.putBatch(queue);
570
+ writeQueue(this.storageKey, []);
571
+ }
572
+ /**
573
+ * 批量上报(每条 item.data 展开为 log content)
574
+ */
575
+ putBatch(queue) {
576
+ if (!this.enabled)
577
+ return;
578
+ if (!queue || queue.length === 0)
579
+ return;
580
+ if (!this.topicId) {
581
+ // eslint-disable-next-line no-console
582
+ console.warn('ClsLogger.putBatch:未初始化 topic_id');
583
+ return;
584
+ }
585
+ void this.putBatchAsync(queue).catch(() => {
586
+ // ignore
587
+ });
588
+ }
589
+ async putBatchAsync(queue) {
590
+ if (!this.topicId)
591
+ return;
592
+ const sdk = await this.loadSdk();
593
+ const client = await this.getInstance();
594
+ const logGroup = new sdk.LogGroup('127.0.0.1');
595
+ logGroup.setSource(this.source);
596
+ for (const item of queue) {
597
+ const log = new sdk.Log(item.time);
598
+ const data = item.data ?? {};
599
+ for (const key of Object.keys(data)) {
600
+ log.addContent(key, stringifyLogValue(data[key]));
601
+ }
602
+ logGroup.addLog(log);
603
+ }
604
+ if (logGroup.getLogs().length === 0)
605
+ return;
606
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
607
+ const exit = enterClsSendingGuard();
608
+ let p;
609
+ try {
610
+ p = client.PutLogs(request);
611
+ }
612
+ finally {
613
+ exit();
614
+ }
615
+ await p;
616
+ }
617
+ /**
618
+ * 参考《一、概述》:统一上报入口(内存队列 + 批量发送)
619
+ */
620
+ report(log) {
621
+ if (!this.enabled)
622
+ return;
623
+ if (!log?.type)
624
+ return;
625
+ if (!this.topicId) {
626
+ // eslint-disable-next-line no-console
627
+ console.warn('ClsLogger.report:未初始化 topicID/topic_id');
628
+ return;
629
+ }
630
+ this.memoryQueue.push(log);
631
+ if (this.memoryQueue.length >= this.batchMaxSize) {
632
+ void this.flushBatch();
633
+ return;
634
+ }
635
+ const now = Date.now();
636
+ const desiredDueAt = this.getDesiredBatchFlushDueAt(now);
637
+ const desiredDelay = Math.max(0, desiredDueAt - now);
638
+ if (!this.batchTimer) {
639
+ this.batchTimerDueAt = desiredDueAt;
640
+ this.scheduleFlush(desiredDelay);
641
+ return;
642
+ }
643
+ // 启动合并窗口内:如果当前 timer 会"更早"触发,则延后到窗口结束,尽量减少多次发送
644
+ if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
645
+ this.cancelScheduledFlush();
646
+ this.batchTimerDueAt = desiredDueAt;
647
+ this.scheduleFlush(desiredDelay);
648
+ }
649
+ }
650
+ /**
651
+ * 调度批量发送
652
+ * - 支持 requestIdleCallback(浏览器空闲时执行)
653
+ * - 降级为 setTimeout
654
+ */
655
+ scheduleFlush(desiredDelay) {
656
+ if (this.useIdleCallback && typeof requestIdleCallback !== 'undefined') {
657
+ // 使用 requestIdleCallback,设置 timeout 保证最终执行
658
+ const idleId = requestIdleCallback(() => {
659
+ void this.flushBatch();
660
+ }, { timeout: Math.max(desiredDelay, this.idleTimeout) });
661
+ // 存储 idleId 以便清理(类型兼容处理)
662
+ this.batchTimer = idleId;
663
+ }
664
+ else {
665
+ this.batchTimer = setTimeout(() => {
666
+ void this.flushBatch();
667
+ }, desiredDelay);
668
+ }
669
+ }
670
+ /**
671
+ * 取消已调度的批量发送
672
+ */
673
+ cancelScheduledFlush() {
674
+ if (!this.batchTimer)
675
+ return;
676
+ try {
677
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
678
+ cancelIdleCallback(this.batchTimer);
679
+ }
680
+ else {
681
+ clearTimeout(this.batchTimer);
682
+ }
683
+ }
684
+ catch {
685
+ // ignore
686
+ }
687
+ this.batchTimer = null;
688
+ }
689
+ getDesiredBatchFlushDueAt(nowTs) {
690
+ const start = this.initTs || nowTs;
691
+ const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
692
+ if (startupDelay > 0) {
693
+ const end = start + startupDelay;
694
+ if (nowTs < end)
695
+ return end;
696
+ }
697
+ return nowTs + this.batchIntervalMs;
698
+ }
699
+ info(message, data = {}, options) {
700
+ let msg = '';
701
+ let extra = {};
702
+ if (message instanceof Error) {
703
+ msg = message.message;
704
+ extra = {
705
+ stack: message.stack,
706
+ name: message.name,
707
+ ...data,
708
+ };
709
+ }
710
+ else {
711
+ msg = String(message);
712
+ extra = data;
713
+ }
714
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
715
+ const log = { type: 'info', data: payload, timestamp: Date.now() };
716
+ // info 默认走批量队列,支持 immediate 选项立即发送
717
+ if (options?.immediate) {
718
+ void this.sendReportLogs([log]).catch(() => {
719
+ this.cacheFailedReportLogs([log]);
720
+ });
721
+ }
722
+ else {
723
+ this.report(log);
724
+ }
725
+ }
726
+ warn(message, data = {}, options) {
727
+ let msg = '';
728
+ let extra = {};
729
+ if (message instanceof Error) {
730
+ msg = message.message;
731
+ extra = {
732
+ stack: message.stack,
733
+ name: message.name,
734
+ ...data,
735
+ };
736
+ }
737
+ else {
738
+ msg = String(message);
739
+ extra = data;
740
+ }
741
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
742
+ const log = { type: 'warn', data: payload, timestamp: Date.now() };
743
+ // warn 默认走批量队列,支持 immediate 选项立即发送
744
+ if (options?.immediate) {
745
+ void this.sendReportLogs([log]).catch(() => {
746
+ this.cacheFailedReportLogs([log]);
747
+ });
748
+ }
749
+ else {
750
+ this.report(log);
751
+ }
752
+ }
753
+ error(message, data = {}, options) {
754
+ let msg = '';
755
+ let extra = {};
756
+ if (message instanceof Error) {
757
+ msg = message.message;
758
+ extra = {
759
+ stack: message.stack,
760
+ name: message.name,
761
+ ...data,
762
+ };
763
+ }
764
+ else {
765
+ msg = String(message);
766
+ extra = data;
767
+ }
768
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
769
+ const log = { type: 'error', data: payload, timestamp: Date.now() };
770
+ // error 默认即时上报,除非显式指定 immediate: false
771
+ const immediate = options?.immediate ?? true;
772
+ if (immediate) {
773
+ void this.sendReportLogs([log]).catch(() => {
774
+ this.cacheFailedReportLogs([log]);
775
+ });
776
+ }
777
+ else {
778
+ this.report(log);
779
+ }
780
+ }
781
+ track(trackType, data = {}) {
782
+ if (!trackType)
783
+ return;
784
+ this.report({
785
+ type: trackType,
786
+ data: normalizeFlatFields(data, `track:${trackType}`),
787
+ timestamp: Date.now(),
788
+ });
789
+ }
790
+ /**
791
+ * 立即发送内存队列
792
+ */
793
+ async flushBatch() {
794
+ this.cancelScheduledFlush();
795
+ this.batchTimerDueAt = null;
796
+ if (this.memoryQueue.length === 0)
797
+ return;
798
+ const logs = [...this.memoryQueue];
799
+ this.memoryQueue = [];
800
+ try {
801
+ await this.sendReportLogs(logs);
802
+ }
803
+ catch {
804
+ this.retrySendReportLogs(logs, 1);
805
+ }
806
+ }
807
+ buildReportFields(log) {
808
+ const ts = log.timestamp ?? Date.now();
809
+ const base = this.getBaseFields();
810
+ const data = normalizeFlatFields(log.data ?? {}, 'report:data');
811
+ const mergedData = mergeFields(base, data);
812
+ return {
813
+ timestamp: ts,
814
+ type: log.type,
815
+ envType: this.envType,
816
+ projectId: this.projectId || undefined,
817
+ projectName: this.projectName || undefined,
818
+ appId: this.appId || undefined,
819
+ appVersion: this.appVersion || undefined,
820
+ // 保证“一维字段”:业务数据以 JSON 字符串形式落到 CLS
821
+ ...mergedData,
822
+ };
823
+ }
824
+ async sendReportLogs(logs) {
825
+ if (!this.topicId)
826
+ return;
827
+ const sdk = await this.loadSdk();
828
+ const client = await this.getInstance();
829
+ const logGroup = new sdk.LogGroup('127.0.0.1');
830
+ logGroup.setSource(this.source);
831
+ for (const item of logs) {
832
+ const fields = this.buildReportFields(item);
833
+ const log = new sdk.Log(fields.timestamp);
834
+ for (const key of Object.keys(fields)) {
835
+ if (key === 'timestamp')
836
+ continue;
837
+ log.addContent(key, stringifyLogValue(fields[key]));
838
+ }
839
+ logGroup.addLog(log);
840
+ }
841
+ const request = new sdk.PutLogsRequest(this.topicId, logGroup);
842
+ // 只在“发起网络请求”的同步阶段打标记,避免 requestMonitor 监控 CLS 上报请求导致递归
843
+ const exit = enterClsSendingGuard();
844
+ let p;
845
+ try {
846
+ p = client.PutLogs(request);
847
+ }
848
+ finally {
849
+ exit();
850
+ }
851
+ await p;
852
+ }
853
+ retrySendReportLogs(logs, retryCount) {
854
+ if (retryCount > this.retryTimes) {
855
+ this.cacheFailedReportLogs(logs);
856
+ return;
857
+ }
858
+ const delayMs = Math.pow(2, retryCount) * 1000;
859
+ setTimeout(async () => {
860
+ try {
861
+ await this.sendReportLogs(logs);
862
+ }
863
+ catch {
864
+ this.retrySendReportLogs(logs, retryCount + 1);
865
+ }
866
+ }, delayMs);
867
+ }
868
+ cacheFailedReportLogs(logs) {
869
+ const raw = readStringStorage(this.failedCacheKey);
870
+ let current = [];
871
+ try {
872
+ const parsed = raw ? JSON.parse(raw) : [];
873
+ current = Array.isArray(parsed) ? parsed : [];
874
+ }
875
+ catch {
876
+ current = [];
877
+ }
878
+ const next = [...current, ...logs].slice(-this.failedCacheMax);
879
+ writeStringStorage(this.failedCacheKey, JSON.stringify(next));
880
+ }
881
+ flushFailed() {
882
+ if (!this.enabled)
883
+ return;
884
+ const raw = readStringStorage(this.failedCacheKey);
885
+ if (!raw)
886
+ return;
887
+ let logs = [];
888
+ try {
889
+ const parsed = JSON.parse(raw);
890
+ logs = Array.isArray(parsed) ? parsed : [];
891
+ }
892
+ catch {
893
+ logs = [];
894
+ }
895
+ if (logs.length === 0)
896
+ return;
897
+ // 先清空,再尝试发送
898
+ writeStringStorage(this.failedCacheKey, JSON.stringify([]));
899
+ this.memoryQueue.unshift(...logs);
900
+ void this.flushBatch();
901
+ }
902
+ /**
903
+ * 统计/计数类日志:按字段展开上报(若 data 为空默认 1)
904
+ */
905
+ stat(param) {
906
+ if (!param)
907
+ return;
908
+ const payload = normalizeFlatFields({
909
+ pagePath: typeof window !== 'undefined' ? window.location?.pathname : '',
910
+ projectId: this.projectId,
911
+ projectName: this.projectName,
912
+ ...param,
913
+ data: param.data ?? 1,
914
+ }, 'stat');
915
+ this.report({ type: 'stat', data: payload, timestamp: Date.now() });
916
+ }
917
+ }
918
+
919
+ function readGlobal(key) {
920
+ try {
921
+ const g = globalThis;
922
+ return g[key] ?? null;
923
+ }
924
+ catch {
925
+ return null;
926
+ }
927
+ }
928
+
929
+ const DEFAULT_IGNORE$1 = ['cls.tencentcs.com', /\/cls\//i];
930
+ function isClsSendingNow() {
931
+ const g = globalThis;
932
+ return (g.__beLinkClsLoggerSendingCount__ ?? 0) > 0;
933
+ }
934
+ function shouldIgnoreUrl$1(url, ignoreUrls) {
935
+ for (const rule of ignoreUrls) {
936
+ if (typeof rule === 'string') {
937
+ if (url.includes(rule))
938
+ return true;
939
+ continue;
940
+ }
941
+ try {
942
+ if (rule.test(url))
943
+ return true;
944
+ }
945
+ catch {
946
+ // ignore invalid regex
947
+ }
948
+ }
949
+ return false;
950
+ }
951
+ function sampleHit$2(sampleRate) {
952
+ if (sampleRate >= 1)
953
+ return true;
954
+ if (sampleRate <= 0)
955
+ return false;
956
+ return Math.random() < sampleRate;
957
+ }
958
+ function truncate$3(s, maxLen) {
959
+ if (!s)
960
+ return s;
961
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
962
+ }
963
+ function buildPayload(params) {
964
+ const { url, method, query, body, duration, startTime, status, success, error, options } = params;
965
+ if (!url)
966
+ return null;
967
+ if (shouldIgnoreUrl$1(url, options.ignoreUrls))
968
+ return null;
969
+ if (!sampleHit$2(options.sampleRate))
970
+ return null;
971
+ const payload = { url };
972
+ if (options.includeMethod && method)
973
+ payload.method = method;
974
+ if (options.includeQuery && query !== undefined)
975
+ payload.query = truncate$3(String(query), options.maxParamLength);
976
+ if (options.includeBody && body !== undefined)
977
+ payload.params = truncate$3(stringifyLogValue(body), options.maxParamLength);
978
+ if (typeof startTime === 'number')
979
+ payload.startTime = startTime;
980
+ if (typeof duration === 'number')
981
+ payload.duration = duration;
982
+ if (typeof status === 'number')
983
+ payload.status = status;
984
+ if (typeof success === 'boolean')
985
+ payload.success = success ? 1 : 0;
986
+ if (error !== undefined)
987
+ payload.error = truncate$3(stringifyLogValue(error), options.maxParamLength);
988
+ return payload;
989
+ }
990
+ function getAbsoluteUrlMaybe(url) {
991
+ try {
992
+ if (typeof window === 'undefined')
993
+ return url;
994
+ return new URL(url, window.location?.href).toString();
995
+ }
996
+ catch {
997
+ return url;
998
+ }
999
+ }
1000
+ function installBrowserFetch(report, options) {
1001
+ if (typeof window === 'undefined')
1002
+ return;
1003
+ const w = window;
1004
+ if (w.__beLinkClsLoggerFetchInstalled__)
1005
+ return;
1006
+ if (typeof w.fetch !== 'function')
1007
+ return;
1008
+ w.__beLinkClsLoggerFetchInstalled__ = true;
1009
+ w.__beLinkClsLoggerRawFetch__ = w.fetch;
1010
+ w.fetch = async (input, init) => {
1011
+ // 避免 CLS SDK 上报请求被 requestMonitor 捕获后递归上报(尤其在跨域失败时会“上报失败→再上报”)
1012
+ if (isClsSendingNow())
1013
+ return w.__beLinkClsLoggerRawFetch__(input, init);
1014
+ let url = '';
1015
+ let method = '';
1016
+ let body = undefined;
1017
+ const startTs = Date.now();
1018
+ try {
1019
+ if (typeof input === 'string')
1020
+ url = input;
1021
+ else if (input instanceof URL)
1022
+ url = input.toString();
1023
+ else
1024
+ url = input.url ?? '';
1025
+ method = (init?.method ?? input?.method ?? 'GET');
1026
+ body = init?.body;
1027
+ }
1028
+ catch {
1029
+ // ignore
1030
+ }
1031
+ const absUrl = getAbsoluteUrlMaybe(url);
1032
+ const query = (() => {
1033
+ try {
1034
+ const u = new URL(absUrl);
1035
+ return u.search ? u.search.slice(1) : '';
1036
+ }
1037
+ catch {
1038
+ return '';
1039
+ }
1040
+ })();
1041
+ try {
1042
+ const res = await w.__beLinkClsLoggerRawFetch__(input, init);
1043
+ const duration = Date.now() - startTs;
1044
+ const status = typeof res?.status === 'number' ? res.status : undefined;
1045
+ const ok = typeof res?.ok === 'boolean' ? res.ok : status !== undefined ? status >= 200 && status < 400 : true;
1046
+ const payload = buildPayload({
1047
+ url: absUrl,
1048
+ method,
1049
+ query,
1050
+ body,
1051
+ startTime: startTs,
1052
+ duration,
1053
+ status,
1054
+ success: ok,
1055
+ options,
1056
+ });
1057
+ if (payload)
1058
+ report(options.reportType, payload);
1059
+ return res;
1060
+ }
1061
+ catch (err) {
1062
+ const duration = Date.now() - startTs;
1063
+ const payload = buildPayload({
1064
+ url: absUrl,
1065
+ method,
1066
+ query,
1067
+ body,
1068
+ startTime: startTs,
1069
+ duration,
1070
+ success: false,
1071
+ error: err,
1072
+ options,
1073
+ });
1074
+ if (payload)
1075
+ report(options.reportType, payload);
1076
+ throw err;
1077
+ }
1078
+ };
1079
+ }
1080
+ function installBrowserXhr(report, options) {
1081
+ if (typeof window === 'undefined')
1082
+ return;
1083
+ const w = window;
1084
+ if (w.__beLinkClsLoggerXhrInstalled__)
1085
+ return;
1086
+ if (!w.XMLHttpRequest || !w.XMLHttpRequest.prototype)
1087
+ return;
1088
+ w.__beLinkClsLoggerXhrInstalled__ = true;
1089
+ const XHR = w.XMLHttpRequest;
1090
+ const rawOpen = XHR.prototype.open;
1091
+ const rawSend = XHR.prototype.send;
1092
+ XHR.prototype.open = function (...args) {
1093
+ try {
1094
+ this.__beLinkClsLoggerMethod__ = String(args[0] ?? 'GET');
1095
+ this.__beLinkClsLoggerUrl__ = String(args[1] ?? '');
1096
+ }
1097
+ catch {
1098
+ // ignore
1099
+ }
1100
+ return rawOpen.apply(this, args);
1101
+ };
1102
+ XHR.prototype.send = function (...args) {
1103
+ // CLS SDK 发起上报时:跳过监控,避免递归上报
1104
+ if (isClsSendingNow())
1105
+ return rawSend.apply(this, args);
1106
+ const startTs = Date.now();
1107
+ try {
1108
+ const method = String(this.__beLinkClsLoggerMethod__ ?? 'GET');
1109
+ const url = getAbsoluteUrlMaybe(String(this.__beLinkClsLoggerUrl__ ?? ''));
1110
+ const query = (() => {
1111
+ try {
1112
+ const u = new URL(url);
1113
+ return u.search ? u.search.slice(1) : '';
1114
+ }
1115
+ catch {
1116
+ return '';
1117
+ }
1118
+ })();
1119
+ const body = args?.[0];
1120
+ this.__beLinkClsLoggerStartTs__ = startTs;
1121
+ this.__beLinkClsLoggerBody__ = body;
1122
+ const onDone = (success, error) => {
1123
+ try {
1124
+ const st = this.__beLinkClsLoggerStartTs__ ?? startTs;
1125
+ const duration = Date.now() - st;
1126
+ const status = typeof this.status === 'number' ? this.status : undefined;
1127
+ const payload = buildPayload({
1128
+ url,
1129
+ method,
1130
+ query,
1131
+ body: this.__beLinkClsLoggerBody__,
1132
+ startTime: st,
1133
+ duration,
1134
+ status,
1135
+ success,
1136
+ error,
1137
+ options,
1138
+ });
1139
+ if (payload)
1140
+ report(options.reportType, payload);
1141
+ }
1142
+ catch {
1143
+ // ignore
1144
+ }
1145
+ };
1146
+ // 避免重复绑定
1147
+ if (!this.__beLinkClsLoggerBound__) {
1148
+ this.__beLinkClsLoggerBound__ = true;
1149
+ this.addEventListener('loadend', () => {
1150
+ try {
1151
+ const status = typeof this.status === 'number' ? this.status : 0;
1152
+ onDone(status >= 200 && status < 400);
1153
+ }
1154
+ catch {
1155
+ onDone(true);
1156
+ }
1157
+ });
1158
+ this.addEventListener('error', (e) => onDone(false, e));
1159
+ this.addEventListener('timeout', () => onDone(false, 'timeout'));
1160
+ this.addEventListener('abort', () => onDone(false, 'abort'));
1161
+ }
1162
+ }
1163
+ catch {
1164
+ // ignore
1165
+ }
1166
+ return rawSend.apply(this, args);
1167
+ };
1168
+ }
1169
+ function installWebRequestMonitor(report, opts = {}) {
1170
+ const enabled = opts.enabled ?? true;
1171
+ if (!enabled)
1172
+ return;
1173
+ const ignoreUrls = [...DEFAULT_IGNORE$1, ...(opts.ignoreUrls ?? [])];
1174
+ if (opts.clsEndpoint)
1175
+ ignoreUrls.push(opts.clsEndpoint);
1176
+ const options = {
1177
+ enabled: true,
1178
+ reportType: opts.reportType ?? 'http',
1179
+ sampleRate: opts.sampleRate ?? 1,
1180
+ ignoreUrls,
1181
+ includeMethod: opts.includeMethod ?? true,
1182
+ includeQuery: opts.includeQuery ?? true,
1183
+ includeBody: opts.includeBody ?? true,
1184
+ maxParamLength: opts.maxParamLength ?? 2000,
1185
+ clsEndpoint: opts.clsEndpoint ?? '',
1186
+ };
1187
+ installBrowserFetch(report, options);
1188
+ installBrowserXhr(report, options);
1189
+ }
1190
+
1191
+ const DEFAULT_MAX_TEXT = 4000;
1192
+ const DEFAULT_DEDUPE_WINDOW_MS = 3000;
1193
+ const DEFAULT_DEDUPE_MAX_KEYS = 200;
1194
+ /** 默认忽略的无意义错误信息 */
1195
+ const DEFAULT_IGNORE_MESSAGES = [
1196
+ 'Script error.',
1197
+ 'Script error',
1198
+ /^ResizeObserver loop/,
1199
+ 'Permission was denied',
1200
+ ];
1201
+ function truncate$2(s, maxLen) {
1202
+ if (!s)
1203
+ return s;
1204
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1205
+ }
1206
+ function sampleHit$1(sampleRate) {
1207
+ if (sampleRate >= 1)
1208
+ return true;
1209
+ if (sampleRate <= 0)
1210
+ return false;
1211
+ return Math.random() < sampleRate;
1212
+ }
1213
+ /** 检查消息是否应该被忽略 */
1214
+ function shouldIgnoreMessage(message, ignorePatterns) {
1215
+ if (!message || ignorePatterns.length === 0)
1216
+ return false;
1217
+ return ignorePatterns.some((pattern) => {
1218
+ if (typeof pattern === 'string') {
1219
+ return message === pattern || message.includes(pattern);
1220
+ }
1221
+ return pattern.test(message);
1222
+ });
1223
+ }
1224
+ function getPagePath$1() {
1225
+ try {
1226
+ if (typeof window === 'undefined')
1227
+ return '';
1228
+ return window.location?.href ?? '';
1229
+ }
1230
+ catch {
1231
+ return '';
1232
+ }
1233
+ }
1234
+ function normalizeErrorLike(err, maxTextLength) {
1235
+ if (err && typeof err === 'object') {
1236
+ const anyErr = err;
1237
+ let rawMsg = anyErr.message;
1238
+ if (!rawMsg) {
1239
+ const str = anyErr.toString?.();
1240
+ if (!str || str === '[object Object]') {
1241
+ rawMsg = stringifyLogValue(anyErr);
1242
+ }
1243
+ else {
1244
+ rawMsg = str;
1245
+ }
1246
+ }
1247
+ const message = truncate$2(String(rawMsg ?? ''), maxTextLength);
1248
+ const name = truncate$2(String(anyErr.name ?? ''), 200);
1249
+ const stack = truncate$2(String(anyErr.stack ?? ''), maxTextLength);
1250
+ return { message, name, stack };
1251
+ }
1252
+ const message = truncate$2(stringifyLogValue(err), maxTextLength);
1253
+ return { message, name: '', stack: '' };
1254
+ }
1255
+ function createDedupeGuard(options) {
1256
+ const cache = new Map(); // key -> lastReportAt
1257
+ const maxKeys = Math.max(0, options.dedupeMaxKeys);
1258
+ const windowMs = Math.max(0, options.dedupeWindowMs);
1259
+ function touch(key, now) {
1260
+ if (cache.has(key))
1261
+ cache.delete(key);
1262
+ cache.set(key, now);
1263
+ if (maxKeys > 0) {
1264
+ while (cache.size > maxKeys) {
1265
+ const first = cache.keys().next().value;
1266
+ if (!first)
1267
+ break;
1268
+ cache.delete(first);
1269
+ }
1270
+ }
1271
+ }
1272
+ return (key) => {
1273
+ if (!key)
1274
+ return true;
1275
+ if (windowMs <= 0 || maxKeys === 0)
1276
+ return true;
1277
+ const now = Date.now();
1278
+ const last = cache.get(key);
1279
+ if (typeof last === 'number' && now - last < windowMs)
1280
+ return false;
1281
+ touch(key, now);
1282
+ return true;
1283
+ };
1284
+ }
1285
+ function buildErrorKey(type, payload) {
1286
+ const parts = [
1287
+ type,
1288
+ String(payload.source ?? ''),
1289
+ String(payload.pagePath ?? ''),
1290
+ String(payload.message ?? ''),
1291
+ String(payload.errorName ?? ''),
1292
+ String(payload.stack ?? ''),
1293
+ String(payload.filename ?? ''),
1294
+ String(payload.lineno ?? ''),
1295
+ String(payload.colno ?? ''),
1296
+ String(payload.tagName ?? ''),
1297
+ String(payload.resourceUrl ?? ''),
1298
+ ];
1299
+ return parts.join('|');
1300
+ }
1301
+ function installBrowserErrorMonitor(report, options) {
1302
+ if (typeof window === 'undefined')
1303
+ return;
1304
+ const w = window;
1305
+ if (w.__beLinkClsLoggerErrorInstalled__)
1306
+ return;
1307
+ w.__beLinkClsLoggerErrorInstalled__ = true;
1308
+ const shouldReport = createDedupeGuard(options);
1309
+ window.addEventListener('error', (event) => {
1310
+ try {
1311
+ if (!sampleHit$1(options.sampleRate))
1312
+ return;
1313
+ const payload = {
1314
+ pagePath: getPagePath$1(),
1315
+ source: 'window.error',
1316
+ };
1317
+ if (event && typeof event === 'object' && 'message' in event) {
1318
+ payload.message = truncate$2(String(event.message ?? ''), options.maxTextLength);
1319
+ // 检查是否应该忽略此错误
1320
+ if (shouldIgnoreMessage(String(event.message ?? ''), options.ignoreMessages))
1321
+ return;
1322
+ payload.filename = truncate$2(String(event.filename ?? ''), 500);
1323
+ payload.lineno = typeof event.lineno === 'number' ? event.lineno : undefined;
1324
+ payload.colno = typeof event.colno === 'number' ? event.colno : undefined;
1325
+ const err = event.error;
1326
+ if (err) {
1327
+ const e = normalizeErrorLike(err, options.maxTextLength);
1328
+ if (e.name)
1329
+ payload.errorName = e.name;
1330
+ if (e.stack)
1331
+ payload.stack = e.stack;
1332
+ }
1333
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1334
+ return;
1335
+ report(options.reportType, payload);
1336
+ return;
1337
+ }
1338
+ if (options.captureResourceError) {
1339
+ const target = event?.target || event?.srcElement;
1340
+ const tagName = target?.tagName ? String(target.tagName) : '';
1341
+ const url = String(target?.src || target?.href || '');
1342
+ payload.source = 'resource.error';
1343
+ payload.tagName = tagName;
1344
+ payload.resourceUrl = truncate$2(url, 2000);
1345
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1346
+ return;
1347
+ report(options.reportType, payload);
1348
+ }
1349
+ }
1350
+ catch {
1351
+ // ignore
1352
+ }
1353
+ }, true);
1354
+ window.addEventListener('unhandledrejection', (event) => {
1355
+ try {
1356
+ if (!sampleHit$1(options.sampleRate))
1357
+ return;
1358
+ const reason = event?.reason;
1359
+ const e = normalizeErrorLike(reason, options.maxTextLength);
1360
+ // 检查是否应该忽略此错误
1361
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1362
+ return;
1363
+ const payload = {
1364
+ pagePath: getPagePath$1(),
1365
+ source: 'unhandledrejection',
1366
+ message: e.message,
1367
+ errorName: e.name,
1368
+ stack: e.stack,
1369
+ };
1370
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1371
+ return;
1372
+ report(options.reportType, payload);
1373
+ }
1374
+ catch {
1375
+ // ignore
1376
+ }
1377
+ });
1378
+ }
1379
+ function installWebErrorMonitor(report, opts = {}) {
1380
+ const enabled = opts === undefined ? true : !!opts;
1381
+ if (!enabled)
1382
+ return;
1383
+ const raw = typeof opts === 'object' && opts ? opts : {};
1384
+ const options = {
1385
+ enabled: true,
1386
+ reportType: raw.reportType ?? 'error',
1387
+ sampleRate: raw.sampleRate ?? 1,
1388
+ captureResourceError: raw.captureResourceError ?? true,
1389
+ maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
1390
+ dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
1391
+ dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
1392
+ ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES,
1393
+ };
1394
+ installBrowserErrorMonitor(report, options);
1395
+ }
1396
+
1397
+ const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
1398
+ function truncate$1(s, maxLen) {
1399
+ if (!s)
1400
+ return s;
1401
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1402
+ }
1403
+ function sampleHit(sampleRate) {
1404
+ if (sampleRate >= 1)
1405
+ return true;
1406
+ if (sampleRate <= 0)
1407
+ return false;
1408
+ return Math.random() < sampleRate;
1409
+ }
1410
+ function shouldIgnoreUrl(url, ignoreUrls) {
1411
+ for (const rule of ignoreUrls) {
1412
+ if (typeof rule === 'string') {
1413
+ if (url.includes(rule))
1414
+ return true;
1415
+ continue;
1416
+ }
1417
+ try {
1418
+ if (rule.test(url))
1419
+ return true;
1420
+ }
1421
+ catch {
1422
+ // ignore invalid regex
1423
+ }
1424
+ }
1425
+ return false;
1426
+ }
1427
+ function getPagePath() {
1428
+ try {
1429
+ if (typeof window === 'undefined')
1430
+ return '';
1431
+ return window.location?.href ?? '';
1432
+ }
1433
+ catch {
1434
+ return '';
1435
+ }
1436
+ }
1437
+ /**
1438
+ * 安装浏览器性能监控
1439
+ * 使用 Google web-vitals 库实现 Core Web Vitals 指标采集
1440
+ */
1441
+ function installBrowserPerformanceMonitor(report, options) {
1442
+ if (typeof window === 'undefined')
1443
+ return;
1444
+ const w = window;
1445
+ if (w.__beLinkClsLoggerPerfInstalled__)
1446
+ return;
1447
+ w.__beLinkClsLoggerPerfInstalled__ = true;
1448
+ const ignoreUrls = [...DEFAULT_IGNORE, ...(options.ignoreUrls ?? [])];
1449
+ // Web Vitals: 使用 Google web-vitals 库
1450
+ // 这个库会自动处理:
1451
+ // - LCP 在用户交互后停止观察
1452
+ // - firstHiddenTime 过滤(页面隐藏后的数据不计入)
1453
+ // - CLS 5秒会话窗口算法
1454
+ // - BFCache 恢复时自动重置指标
1455
+ if (options.webVitals) {
1456
+ // FCP
1457
+ try {
1458
+ onFCP((metric) => {
1459
+ report(options.reportType, {
1460
+ pagePath: getPagePath(),
1461
+ metric: 'FCP',
1462
+ value: metric.value,
1463
+ unit: 'ms',
1464
+ rating: metric.rating,
1465
+ id: metric.id,
1466
+ navigationType: metric.navigationType,
1467
+ });
1468
+ });
1469
+ }
1470
+ catch {
1471
+ // ignore
1472
+ }
1473
+ // LCP(自动处理用户交互后停止)
1474
+ try {
1475
+ onLCP((metric) => {
1476
+ report(options.reportType, {
1477
+ pagePath: getPagePath(),
1478
+ metric: 'LCP',
1479
+ value: metric.value,
1480
+ unit: 'ms',
1481
+ rating: metric.rating,
1482
+ id: metric.id,
1483
+ navigationType: metric.navigationType,
1484
+ });
1485
+ });
1486
+ }
1487
+ catch {
1488
+ // ignore
1489
+ }
1490
+ // CLS(自动处理会话窗口)
1491
+ try {
1492
+ onCLS((metric) => {
1493
+ report(options.reportType, {
1494
+ pagePath: getPagePath(),
1495
+ metric: 'CLS',
1496
+ value: metric.value,
1497
+ unit: 'score',
1498
+ rating: metric.rating,
1499
+ id: metric.id,
1500
+ navigationType: metric.navigationType,
1501
+ });
1502
+ });
1503
+ }
1504
+ catch {
1505
+ // ignore
1506
+ }
1507
+ // INP(替代 FID,2024年3月起成为核心指标)
1508
+ try {
1509
+ onINP((metric) => {
1510
+ report(options.reportType, {
1511
+ pagePath: getPagePath(),
1512
+ metric: 'INP',
1513
+ value: metric.value,
1514
+ unit: 'ms',
1515
+ rating: metric.rating,
1516
+ id: metric.id,
1517
+ navigationType: metric.navigationType,
1518
+ });
1519
+ });
1520
+ }
1521
+ catch {
1522
+ // ignore
1523
+ }
1524
+ // TTFB
1525
+ try {
1526
+ onTTFB((metric) => {
1527
+ report(options.reportType, {
1528
+ pagePath: getPagePath(),
1529
+ metric: 'TTFB',
1530
+ value: metric.value,
1531
+ unit: 'ms',
1532
+ rating: metric.rating,
1533
+ id: metric.id,
1534
+ navigationType: metric.navigationType,
1535
+ });
1536
+ });
1537
+ }
1538
+ catch {
1539
+ // ignore
1540
+ }
1541
+ }
1542
+ // Resource timing:资源加载耗时(web-vitals 不包含此功能,保留原有实现)
1543
+ if (options.resourceTiming && typeof globalThis.PerformanceObserver === 'function') {
1544
+ try {
1545
+ const po = new PerformanceObserver((list) => {
1546
+ try {
1547
+ if (!sampleHit(options.sampleRate))
1548
+ return;
1549
+ for (const entry of list.getEntries()) {
1550
+ const name = String(entry?.name ?? '');
1551
+ if (!name || shouldIgnoreUrl(name, ignoreUrls))
1552
+ continue;
1553
+ const initiatorType = String(entry?.initiatorType ?? '');
1554
+ // 关注 fetch/xhr/img/script(同时允许 css/other 但不强制)
1555
+ if (!['xmlhttprequest', 'fetch', 'img', 'script', 'css'].includes(initiatorType))
1556
+ continue;
1557
+ // 时序分解(便于定位慢在哪个阶段)
1558
+ const domainLookupStart = entry.domainLookupStart ?? 0;
1559
+ const domainLookupEnd = entry.domainLookupEnd ?? 0;
1560
+ const connectStart = entry.connectStart ?? 0;
1561
+ const connectEnd = entry.connectEnd ?? 0;
1562
+ const requestStart = entry.requestStart ?? 0;
1563
+ const responseStart = entry.responseStart ?? 0;
1564
+ const responseEnd = entry.responseEnd ?? 0;
1565
+ const dns = domainLookupEnd - domainLookupStart;
1566
+ const tcp = connectEnd - connectStart;
1567
+ const ttfb = responseStart - requestStart;
1568
+ const download = responseEnd - responseStart;
1569
+ // 缓存检测:transferSize=0 且 decodedBodySize>0 表示缓存命中
1570
+ const transferSize = entry.transferSize ?? 0;
1571
+ const decodedBodySize = entry.decodedBodySize ?? 0;
1572
+ const cached = transferSize === 0 && decodedBodySize > 0;
1573
+ const payload = {
1574
+ pagePath: getPagePath(),
1575
+ metric: 'resource',
1576
+ initiatorType,
1577
+ url: truncate$1(name, options.maxTextLength),
1578
+ startTime: typeof entry?.startTime === 'number' ? entry.startTime : undefined,
1579
+ duration: typeof entry?.duration === 'number' ? entry.duration : undefined,
1580
+ // 时序分解(跨域资源可能为 0)
1581
+ dns: dns > 0 ? Math.round(dns) : undefined,
1582
+ tcp: tcp > 0 ? Math.round(tcp) : undefined,
1583
+ ttfb: ttfb > 0 ? Math.round(ttfb) : undefined,
1584
+ download: download > 0 ? Math.round(download) : undefined,
1585
+ // 缓存标记
1586
+ cached,
1587
+ };
1588
+ // 尺寸字段(跨域资源可能为 0)
1589
+ if (transferSize > 0)
1590
+ payload.transferSize = transferSize;
1591
+ if (typeof entry?.encodedBodySize === 'number' && entry.encodedBodySize > 0) {
1592
+ payload.encodedBodySize = entry.encodedBodySize;
1593
+ }
1594
+ if (decodedBodySize > 0)
1595
+ payload.decodedBodySize = decodedBodySize;
1596
+ // 协议和状态
1597
+ if (typeof entry?.nextHopProtocol === 'string' && entry.nextHopProtocol) {
1598
+ payload.nextHopProtocol = entry.nextHopProtocol;
1599
+ }
1600
+ if (typeof entry?.responseStatus === 'number')
1601
+ payload.status = entry.responseStatus;
1602
+ report(options.reportType, payload);
1603
+ }
1604
+ }
1605
+ catch {
1606
+ // ignore
1607
+ }
1608
+ });
1609
+ po.observe({ type: 'resource', buffered: true });
1610
+ }
1611
+ catch {
1612
+ // ignore
1613
+ }
1614
+ }
1615
+ }
1616
+ function installWebPerformanceMonitor(report, opts = {}) {
1617
+ const enabled = opts === undefined ? true : !!opts;
1618
+ if (!enabled)
1619
+ return;
1620
+ const raw = typeof opts === 'object' && opts ? opts : {};
1621
+ const options = {
1622
+ enabled: true,
1623
+ reportType: raw.reportType ?? 'perf',
1624
+ sampleRate: raw.sampleRate ?? 1,
1625
+ ignoreUrls: raw.ignoreUrls ?? [],
1626
+ webVitals: raw.webVitals ?? true,
1627
+ resourceTiming: raw.resourceTiming ?? true,
1628
+ maxTextLength: raw.maxTextLength ?? 2000,
1629
+ };
1630
+ installBrowserPerformanceMonitor(report, options);
1631
+ }
1632
+
1633
+ function shouldSample(sampleRate) {
1634
+ const r = sampleRate ?? 1;
1635
+ if (r >= 1)
1636
+ return true;
1637
+ if (r <= 0)
1638
+ return false;
1639
+ return Math.random() < r;
1640
+ }
1641
+ function generateUUID() {
1642
+ const g = globalThis;
1643
+ if (g.crypto?.randomUUID)
1644
+ return g.crypto.randomUUID();
1645
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1646
+ const r = Math.random() * 16 || 0;
1647
+ const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
1648
+ return v.toString(16);
1649
+ });
1650
+ }
1651
+ function safeReadUvMeta(key) {
1652
+ const raw = readStringStorage(key);
1653
+ if (!raw)
1654
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1655
+ try {
1656
+ const parsed = JSON.parse(raw);
1657
+ if (!parsed || typeof parsed !== 'object')
1658
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1659
+ const p = parsed;
1660
+ const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
1661
+ const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
1662
+ const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
1663
+ const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
1664
+ return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
1665
+ }
1666
+ catch {
1667
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1668
+ }
1669
+ }
1670
+ function writeUvMeta(key, meta) {
1671
+ writeStringStorage(key, JSON.stringify(meta));
1672
+ }
1673
+ function getWebPagePath() {
1674
+ if (typeof window === 'undefined')
1675
+ return '';
1676
+ return window.location?.href || '';
1677
+ }
1678
+ function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
1679
+ return {
1680
+ uvId,
1681
+ isFirstVisit,
1682
+ firstVisitTs: uvMeta.firstVisitTs,
1683
+ visitCount: uvMeta.visitCount,
1684
+ };
1685
+ }
1686
+ function getAttr(el, attrName) {
1687
+ try {
1688
+ return el.getAttribute(attrName) ?? '';
1689
+ }
1690
+ catch {
1691
+ return '';
1692
+ }
1693
+ }
1694
+ function truncateText(s, maxLen) {
1695
+ if (!s)
1696
+ return '';
1697
+ if (s.length <= maxLen)
1698
+ return s;
1699
+ return s.slice(0, maxLen);
1700
+ }
1701
+ function installWebBehaviorMonitor(report, options = {}) {
1702
+ const enableTrack = options.enableTrack ?? options.enabled ?? true;
1703
+ if (!enableTrack)
1704
+ return () => { };
1705
+ const pvEnabled = options.pv ?? true;
1706
+ const uvEnabled = options.uv ?? true;
1707
+ const clickEnabled = options.click ?? true;
1708
+ const pvReportType = options.pvReportType ?? 'pv';
1709
+ const uvReportType = options.uvReportType ?? 'uv';
1710
+ const clickReportType = options.clickReportType ?? 'click';
1711
+ const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
1712
+ const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
1713
+ const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
1714
+ const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
1715
+ const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
1716
+ const clickWhiteList = (options.trackOptions?.clickWhiteList ?? options.clickWhiteList ?? ['body', 'html']).map((s) => String(s).toLowerCase());
1717
+ const clickTrackIdAttr = options.clickTrackIdAttr ?? 'data-track-id';
1718
+ const clickMaxTextLength = options.clickMaxTextLength ?? 120;
1719
+ const getPagePath = options.getPagePath ?? getWebPagePath;
1720
+ let destroyed = false;
1721
+ let firstVisitFlag = false;
1722
+ let firstVisitConsumed = false;
1723
+ const uvStatePromise = (async () => {
1724
+ let existingUvId = readStringStorage(uvIdStorageKey);
1725
+ let isFirstVisit = false;
1726
+ const now = Date.now();
1727
+ const metaBefore = safeReadUvMeta(uvMetaStorageKey);
1728
+ const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
1729
+ const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
1730
+ if (expired) {
1731
+ existingUvId = null;
1732
+ writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
1733
+ writeStringStorage(uvIdStorageKey, '');
1734
+ }
1735
+ try {
1736
+ if (options.getUvId) {
1737
+ const maybe = options.getUvId();
1738
+ const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
1739
+ if (resolved && typeof resolved === 'string')
1740
+ existingUvId = resolved;
1741
+ }
1742
+ }
1743
+ catch {
1744
+ /* ignore */
1745
+ }
1746
+ if (!existingUvId) {
1747
+ existingUvId = generateUUID();
1748
+ isFirstVisit = true;
1749
+ }
1750
+ writeStringStorage(uvIdStorageKey, existingUvId);
1751
+ const meta = safeReadUvMeta(uvMetaStorageKey);
1752
+ const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
1753
+ const firstVisit = meta.firstVisitTs || now;
1754
+ const nextMeta = {
1755
+ firstVisitTs: firstVisit,
1756
+ visitCount: (meta.visitCount || 0) + 1,
1757
+ createdAtTs: createdAt,
1758
+ lastSeenTs: now,
1759
+ };
1760
+ if (isFirstVisit) {
1761
+ nextMeta.firstVisitTs = now;
1762
+ nextMeta.createdAtTs = now;
1763
+ }
1764
+ writeUvMeta(uvMetaStorageKey, nextMeta);
1765
+ firstVisitFlag = isFirstVisit;
1766
+ return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
1767
+ })();
1768
+ function safeReport(type, data) {
1769
+ if (destroyed)
1770
+ return;
1771
+ if (!shouldSample(options.sampleRate))
1772
+ return;
1773
+ report(type, data);
1774
+ }
1775
+ function buildUvFieldsOnce(uvId, meta) {
1776
+ const once = firstVisitFlag && !firstVisitConsumed;
1777
+ if (once)
1778
+ firstVisitConsumed = true;
1779
+ return buildCommonUvFields(uvId, meta, once);
1780
+ }
1781
+ function reportPv(pagePath) {
1782
+ if (!pvEnabled)
1783
+ return;
1784
+ void uvStatePromise.then(({ uvId, meta }) => {
1785
+ if (destroyed)
1786
+ return;
1787
+ const payload = {
1788
+ ...buildUvFieldsOnce(uvId, meta),
1789
+ timestamp: Date.now(),
1790
+ pagePath,
1791
+ referrer: typeof document !== 'undefined' ? document.referrer || '' : '',
1792
+ };
1793
+ safeReport(pvReportType, payload);
1794
+ });
1795
+ }
1796
+ // Web PV Listeners
1797
+ let removeWebPvListeners = null;
1798
+ if (pvEnabled && typeof window !== 'undefined' && typeof history !== 'undefined') {
1799
+ const originalPushState = window.history.pushState?.bind(window.history);
1800
+ const originalReplaceState = window.history.replaceState?.bind(window.history);
1801
+ const onRouteChanged = () => reportPv(getPagePath());
1802
+ onRouteChanged();
1803
+ if (originalPushState) {
1804
+ window.history.pushState = ((...args) => {
1805
+ const r = originalPushState.apply(window.history, args);
1806
+ onRouteChanged();
1807
+ return r;
1808
+ });
1809
+ }
1810
+ if (originalReplaceState) {
1811
+ window.history.replaceState = ((...args) => {
1812
+ const r = originalReplaceState.apply(window.history, args);
1813
+ onRouteChanged();
1814
+ return r;
1815
+ });
1816
+ }
1817
+ window.addEventListener('popstate', onRouteChanged);
1818
+ removeWebPvListeners = () => {
1819
+ window.removeEventListener('popstate', onRouteChanged);
1820
+ if (originalPushState)
1821
+ window.history.pushState = originalPushState;
1822
+ if (originalReplaceState)
1823
+ window.history.replaceState = originalReplaceState;
1824
+ };
1825
+ }
1826
+ // Web Click Listener
1827
+ let removeWebClickListener = null;
1828
+ if (clickEnabled && typeof document !== 'undefined') {
1829
+ const onClick = (e) => {
1830
+ if (destroyed)
1831
+ return;
1832
+ const target = e.target;
1833
+ if (!target)
1834
+ return;
1835
+ const closestWithTrackId = typeof target.closest === 'function'
1836
+ ? target.closest(`[${clickTrackIdAttr}]`)
1837
+ : null;
1838
+ const el = closestWithTrackId || target;
1839
+ const tag = (el.tagName || '').toLowerCase();
1840
+ const trackId = getAttr(el, clickTrackIdAttr);
1841
+ if (clickWhiteList.includes(tag) || !trackId)
1842
+ return;
1843
+ void uvStatePromise.then(({ uvId, meta }) => {
1844
+ if (destroyed)
1845
+ return;
1846
+ safeReport(clickReportType, {
1847
+ ...buildUvFieldsOnce(uvId, meta),
1848
+ timestamp: Date.now(),
1849
+ pagePath: getPagePath(),
1850
+ elementTag: el.tagName || '',
1851
+ elementId: el.id || '',
1852
+ elementClass: stringifyLogValue(el.className ?? ''),
1853
+ trackId: trackId || '',
1854
+ elementText: truncateText((el.textContent ?? '').trim(), clickMaxTextLength),
1855
+ clickX: Number.isFinite(e.clientX) ? e.clientX : 0,
1856
+ clickY: Number.isFinite(e.clientY) ? e.clientY : 0,
1857
+ });
1858
+ });
1859
+ };
1860
+ document.addEventListener('click', onClick, true);
1861
+ removeWebClickListener = () => document.removeEventListener('click', onClick, true);
1862
+ }
1863
+ // UV Initial Report
1864
+ if (uvEnabled) {
1865
+ void uvStatePromise.then(({ uvId, meta }) => {
1866
+ if (destroyed)
1867
+ return;
1868
+ safeReport(uvReportType, {
1869
+ ...buildUvFieldsOnce(uvId, meta),
1870
+ timestamp: Date.now(),
1871
+ pagePath: getPagePath(),
1872
+ });
1873
+ });
1874
+ }
1875
+ return () => {
1876
+ destroyed = true;
1877
+ removeWebPvListeners?.();
1878
+ removeWebClickListener?.();
1879
+ };
1880
+ }
1881
+
1882
+ function truncate(s, maxLen) {
1883
+ if (!s)
1884
+ return s;
1885
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1886
+ }
1887
+ function parseUserAgent(uaRaw) {
1888
+ const ua = uaRaw ?? '';
1889
+ const isMobile = /Mobile|Android|iPhone|iPad|iPod/i.test(ua);
1890
+ // OS
1891
+ let osName = 'unknown';
1892
+ let osVersion = '';
1893
+ const ios = ua.match(/OS (\d+[_\d]*) like Mac OS X/i);
1894
+ const android = ua.match(/Android (\d+(\.\d+)*)/i);
1895
+ const mac = ua.match(/Mac OS X (\d+[_\d]*)/i);
1896
+ const win = ua.match(/Windows NT (\d+(\.\d+)*)/i);
1897
+ if (ios) {
1898
+ osName = 'iOS';
1899
+ osVersion = ios[1].replace(/_/g, '.');
1900
+ }
1901
+ else if (android) {
1902
+ osName = 'Android';
1903
+ osVersion = android[1];
1904
+ }
1905
+ else if (win) {
1906
+ osName = 'Windows';
1907
+ osVersion = win[1];
1908
+ }
1909
+ else if (mac) {
1910
+ osName = 'macOS';
1911
+ osVersion = mac[1].replace(/_/g, '.');
1912
+ }
1913
+ // Browser
1914
+ let browserName = 'unknown';
1915
+ let browserVersion = '';
1916
+ const edge = ua.match(/Edg\/(\d+(\.\d+)*)/);
1917
+ const chrome = ua.match(/Chrome\/(\d+(\.\d+)*)/);
1918
+ const safari = ua.match(/Version\/(\d+(\.\d+)*) Safari\//);
1919
+ const firefox = ua.match(/Firefox\/(\d+(\.\d+)*)/);
1920
+ if (edge) {
1921
+ browserName = 'Edge';
1922
+ browserVersion = edge[1];
1923
+ }
1924
+ else if (chrome) {
1925
+ browserName = 'Chrome';
1926
+ browserVersion = chrome[1];
1927
+ }
1928
+ else if (firefox) {
1929
+ browserName = 'Firefox';
1930
+ browserVersion = firefox[1];
1931
+ }
1932
+ else if (safari) {
1933
+ browserName = 'Safari';
1934
+ browserVersion = safari[1];
1935
+ }
1936
+ return { browserName, browserVersion, osName, osVersion, isMobile };
1937
+ }
1938
+ function getBrowserDeviceInfo(options) {
1939
+ const out = {
1940
+ envType: 'browser',
1941
+ };
1942
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
1943
+ return out;
1944
+ const ua = String(navigator.userAgent ?? '');
1945
+ const uaParsed = parseUserAgent(ua);
1946
+ if (options.includeUserAgent)
1947
+ out.ua = truncate(ua, 2000);
1948
+ out.browserName = uaParsed.browserName;
1949
+ out.browserVersion = uaParsed.browserVersion;
1950
+ out.osName = uaParsed.osName;
1951
+ out.osVersion = uaParsed.osVersion;
1952
+ out.isMobile = uaParsed.isMobile ? 1 : 0;
1953
+ out.language = String(navigator.language ?? '');
1954
+ out.platform = String(navigator.platform ?? '');
1955
+ try {
1956
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
1957
+ out.timezone = typeof tz === 'string' ? tz : '';
1958
+ }
1959
+ catch {
1960
+ out.timezone = '';
1961
+ }
1962
+ try {
1963
+ const s = window.screen;
1964
+ out.screenWidth = s?.width ?? undefined;
1965
+ out.screenHeight = s?.height ?? undefined;
1966
+ }
1967
+ catch {
1968
+ // ignore
1969
+ }
1970
+ try {
1971
+ out.dpr = typeof window.devicePixelRatio === 'number' ? window.devicePixelRatio : undefined;
1972
+ }
1973
+ catch {
1974
+ // ignore
1975
+ }
1976
+ try {
1977
+ const navAny = navigator;
1978
+ out.hardwareConcurrency = typeof navAny.hardwareConcurrency === 'number' ? navAny.hardwareConcurrency : undefined;
1979
+ out.deviceMemory = typeof navAny.deviceMemory === 'number' ? navAny.deviceMemory : undefined;
1980
+ }
1981
+ catch {
1982
+ // ignore
1983
+ }
1984
+ if (options.includeNetwork) {
1985
+ try {
1986
+ const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
1987
+ if (conn && isPlainObject(conn)) {
1988
+ if (typeof conn.effectiveType === 'string')
1989
+ out.netEffectiveType = conn.effectiveType;
1990
+ if (typeof conn.downlink === 'number')
1991
+ out.netDownlink = conn.downlink;
1992
+ if (typeof conn.rtt === 'number')
1993
+ out.netRtt = conn.rtt;
1994
+ if (typeof conn.saveData === 'boolean')
1995
+ out.netSaveData = conn.saveData ? 1 : 0;
1996
+ }
1997
+ }
1998
+ catch {
1999
+ // ignore
2000
+ }
2001
+ }
2002
+ return out;
2003
+ }
2004
+ function createWebDeviceInfoBaseFields(opts) {
2005
+ const enabled = opts === undefined ? true : !!opts;
2006
+ if (!enabled)
2007
+ return null;
2008
+ const raw = typeof opts === 'object' && opts ? opts : {};
2009
+ const options = {
2010
+ includeUserAgent: raw.includeUserAgent ?? true,
2011
+ includeNetwork: raw.includeNetwork ?? true,
2012
+ includeNetworkType: raw.includeNetworkType ?? true,
2013
+ };
2014
+ let base = null;
2015
+ const globalKey = '__beLinkClsLoggerDeviceInfo__';
2016
+ return () => {
2017
+ if (!base) {
2018
+ base = getBrowserDeviceInfo(options);
2019
+ try {
2020
+ const g = globalThis;
2021
+ if (!g[globalKey])
2022
+ g[globalKey] = { ...base };
2023
+ }
2024
+ catch {
2025
+ // ignore
2026
+ }
2027
+ }
2028
+ try {
2029
+ const g = globalThis;
2030
+ const extra = g[globalKey];
2031
+ if (extra && isPlainObject(extra))
2032
+ return { ...base, ...extra };
2033
+ }
2034
+ catch {
2035
+ // ignore
2036
+ }
2037
+ return base;
2038
+ };
2039
+ }
2040
+
2041
+ // @ts-ignore
2042
+ // 移除动态加载,在 Web 入口直接静态引用以确保稳定性
2043
+ class ClsLoggerWeb extends ClsLoggerCore {
2044
+ constructor() {
2045
+ super(...arguments);
2046
+ this.envType = 'browser';
2047
+ }
2048
+ async loadSdk() {
2049
+ if (this.sdk)
2050
+ return this.sdk;
2051
+ // 1) 优先用 UMD 全局变量(如果存在)
2052
+ const g = readGlobal('tencentcloudClsSdkJsWeb');
2053
+ if (g && g.AsyncClient) {
2054
+ this.sdk = this.normalize(g);
2055
+ return this.sdk;
2056
+ }
2057
+ // 2) 使用静态导入
2058
+ const sdk = this.normalize(tencentcloudClsSdkJsWeb);
2059
+ if (sdk) {
2060
+ this.sdk = sdk;
2061
+ return sdk;
2062
+ }
2063
+ console.warn('[ClsLogger] SDK "tencentcloud-cls-sdk-js-web" not found or invalid. Logging will be disabled.');
2064
+ throw new Error('SDK not found');
2065
+ }
2066
+ installRequestMonitor(report, options) {
2067
+ installWebRequestMonitor(report, options);
2068
+ }
2069
+ installErrorMonitor(report, options) {
2070
+ installWebErrorMonitor(report, options);
2071
+ }
2072
+ installPerformanceMonitor(report, options) {
2073
+ installWebPerformanceMonitor(report, options);
2074
+ }
2075
+ installBehaviorMonitor(report, options) {
2076
+ return installWebBehaviorMonitor(report, typeof options === 'boolean' ? {} : options);
2077
+ }
2078
+ createDeviceInfoBaseFields(options) {
2079
+ return createWebDeviceInfoBaseFields(options);
2080
+ }
2081
+ normalize(m) {
2082
+ const mod = (m?.default && m.default.AsyncClient ? m.default : m);
2083
+ return {
2084
+ AsyncClient: mod.AsyncClient,
2085
+ Log: mod.Log,
2086
+ LogGroup: mod.LogGroup,
2087
+ PutLogsRequest: mod.PutLogsRequest,
2088
+ };
2089
+ }
2090
+ }
2091
+
2092
+ const clsLogger = new ClsLoggerWeb();
2093
+
2094
+ export { ClsLoggerWeb as ClsLogger, clsLogger, clsLogger as default };