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

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