@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/mini.js ADDED
@@ -0,0 +1,1971 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var tencentcloudClsSdkJsMini = require('tencentcloud-cls-sdk-js-mini');
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 tencentcloudClsSdkJsMini__namespace = /*#__PURE__*/_interopNamespaceDefault(tencentcloudClsSdkJsMini);
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
+ const DEFAULT_IGNORE = ['cls.tencentcs.com', /\/cls\//i];
942
+ function shouldIgnoreUrl(url, ignoreUrls) {
943
+ for (const rule of ignoreUrls) {
944
+ if (typeof rule === 'string') {
945
+ if (url.includes(rule))
946
+ return true;
947
+ continue;
948
+ }
949
+ try {
950
+ if (rule.test(url))
951
+ return true;
952
+ }
953
+ catch {
954
+ // ignore invalid regex
955
+ }
956
+ }
957
+ return false;
958
+ }
959
+ function sampleHit$2(sampleRate) {
960
+ if (sampleRate >= 1)
961
+ return true;
962
+ if (sampleRate <= 0)
963
+ return false;
964
+ return Math.random() < sampleRate;
965
+ }
966
+ function truncate$1(s, maxLen) {
967
+ if (!s)
968
+ return s;
969
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
970
+ }
971
+ function buildPayload(params) {
972
+ const { url, method, query, body, duration, startTime, status, success, error, options } = params;
973
+ if (!url)
974
+ return null;
975
+ if (shouldIgnoreUrl(url, options.ignoreUrls))
976
+ return null;
977
+ if (!sampleHit$2(options.sampleRate))
978
+ return null;
979
+ const payload = { url };
980
+ if (options.includeMethod && method)
981
+ payload.method = method;
982
+ if (options.includeQuery && query !== undefined)
983
+ payload.query = truncate$1(String(query), options.maxParamLength);
984
+ if (options.includeBody && body !== undefined)
985
+ payload.params = truncate$1(stringifyLogValue(body), options.maxParamLength);
986
+ if (typeof startTime === 'number')
987
+ payload.startTime = startTime;
988
+ if (typeof duration === 'number')
989
+ payload.duration = duration;
990
+ if (typeof status === 'number')
991
+ payload.status = status;
992
+ if (typeof success === 'boolean')
993
+ payload.success = success ? 1 : 0;
994
+ if (error !== undefined)
995
+ payload.error = truncate$1(stringifyLogValue(error), options.maxParamLength);
996
+ return payload;
997
+ }
998
+ function installMiniProgramWxRequest(report, options) {
999
+ const wxAny = globalThis.wx;
1000
+ if (!wxAny || typeof wxAny.request !== 'function')
1001
+ return;
1002
+ if (wxAny.__beLinkClsLoggerWxRequestInstalled__)
1003
+ return;
1004
+ wxAny.__beLinkClsLoggerWxRequestInstalled__ = true;
1005
+ const rawRequest = wxAny.request.bind(wxAny);
1006
+ wxAny.request = (reqOptions) => {
1007
+ const startTs = Date.now();
1008
+ try {
1009
+ const url = String(reqOptions?.url ?? '');
1010
+ const method = String(reqOptions?.method ?? 'GET');
1011
+ const data = reqOptions?.data;
1012
+ const wrapCb = (cb, success) => {
1013
+ return (res) => {
1014
+ try {
1015
+ const duration = Date.now() - startTs;
1016
+ const status = typeof res?.statusCode === 'number'
1017
+ ? res.statusCode
1018
+ : typeof res?.status === 'number'
1019
+ ? res.status
1020
+ : undefined;
1021
+ const payload = buildPayload({
1022
+ url,
1023
+ method,
1024
+ query: '',
1025
+ body: data,
1026
+ startTime: startTs,
1027
+ duration,
1028
+ status,
1029
+ success,
1030
+ error: success ? undefined : res,
1031
+ options,
1032
+ });
1033
+ if (payload)
1034
+ report(options.reportType, payload);
1035
+ }
1036
+ catch {
1037
+ // ignore
1038
+ }
1039
+ if (typeof cb === 'function')
1040
+ return cb(res);
1041
+ return undefined;
1042
+ };
1043
+ };
1044
+ const next = { ...(reqOptions ?? {}) };
1045
+ next.success = wrapCb(next.success, true);
1046
+ next.fail = wrapCb(next.fail, false);
1047
+ return rawRequest(next);
1048
+ }
1049
+ catch {
1050
+ // ignore
1051
+ }
1052
+ return rawRequest(reqOptions);
1053
+ };
1054
+ }
1055
+ function installMiniProgramWxCloudCallFunction(report, options) {
1056
+ const wxAny = globalThis.wx;
1057
+ const cloud = wxAny?.cloud;
1058
+ if (!cloud || typeof cloud.callFunction !== 'function')
1059
+ return;
1060
+ if (cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__)
1061
+ return;
1062
+ cloud.__beLinkClsLoggerWxCloudCallFunctionInstalled__ = true;
1063
+ const rawCallFunction = cloud.callFunction.bind(cloud);
1064
+ cloud.callFunction = (callOptions) => {
1065
+ const startTs = Date.now();
1066
+ const name = (() => {
1067
+ try {
1068
+ return String(callOptions?.name ?? '');
1069
+ }
1070
+ catch {
1071
+ return '';
1072
+ }
1073
+ })();
1074
+ const data = callOptions?.data;
1075
+ let reported = false;
1076
+ const onDone = (success, err) => {
1077
+ if (reported)
1078
+ return;
1079
+ reported = true;
1080
+ try {
1081
+ const duration = Date.now() - startTs;
1082
+ const payload = buildPayload({
1083
+ // 统一走 url 字段,便于和 http 一起检索/聚合
1084
+ url: `cloud.callFunction/${name || 'unknown'}`,
1085
+ method: 'callFunction',
1086
+ query: '',
1087
+ body: data,
1088
+ startTime: startTs,
1089
+ duration,
1090
+ success,
1091
+ error: success ? undefined : err,
1092
+ options,
1093
+ });
1094
+ if (payload) {
1095
+ payload.requestType = 'cloud-function';
1096
+ payload.name = name || 'unknown';
1097
+ report(options.reportType, payload);
1098
+ }
1099
+ }
1100
+ catch {
1101
+ // ignore
1102
+ }
1103
+ };
1104
+ try {
1105
+ const next = { ...(callOptions ?? {}) };
1106
+ const rawSuccess = next.success;
1107
+ const rawFail = next.fail;
1108
+ next.success = (res) => {
1109
+ onDone(true);
1110
+ if (typeof rawSuccess === 'function')
1111
+ return rawSuccess(res);
1112
+ return undefined;
1113
+ };
1114
+ next.fail = (err) => {
1115
+ onDone(false, err?.message ?? err);
1116
+ if (typeof rawFail === 'function')
1117
+ return rawFail(err);
1118
+ return undefined;
1119
+ };
1120
+ const ret = rawCallFunction(next);
1121
+ // 兼容 Promise 风格(有些版本/写法不传 success/fail)
1122
+ if (ret && typeof ret.then === 'function') {
1123
+ ret.then(() => onDone(true), (err) => onDone(false, err?.message ?? err));
1124
+ }
1125
+ return ret;
1126
+ }
1127
+ catch (err) {
1128
+ onDone(false, err);
1129
+ throw err;
1130
+ }
1131
+ };
1132
+ }
1133
+ function installMiniRequestMonitor(report, opts = {}) {
1134
+ const enabled = opts.enabled ?? true;
1135
+ if (!enabled)
1136
+ return;
1137
+ const ignoreUrls = [...DEFAULT_IGNORE, ...(opts.ignoreUrls ?? [])];
1138
+ if (opts.clsEndpoint)
1139
+ ignoreUrls.push(opts.clsEndpoint);
1140
+ const options = {
1141
+ enabled: true,
1142
+ reportType: opts.reportType ?? 'http',
1143
+ sampleRate: opts.sampleRate ?? 1,
1144
+ ignoreUrls,
1145
+ includeMethod: opts.includeMethod ?? true,
1146
+ includeQuery: opts.includeQuery ?? true,
1147
+ includeBody: opts.includeBody ?? true,
1148
+ maxParamLength: opts.maxParamLength ?? 2000,
1149
+ clsEndpoint: opts.clsEndpoint ?? '',
1150
+ };
1151
+ installMiniProgramWxRequest(report, options);
1152
+ installMiniProgramWxCloudCallFunction(report, options);
1153
+ }
1154
+
1155
+ const DEFAULT_MAX_TEXT = 4000;
1156
+ const DEFAULT_DEDUPE_WINDOW_MS = 3000;
1157
+ const DEFAULT_DEDUPE_MAX_KEYS = 200;
1158
+ /** 默认忽略的无意义错误信息 */
1159
+ const DEFAULT_IGNORE_MESSAGES = [
1160
+ 'Script error.',
1161
+ 'Script error',
1162
+ /^ResizeObserver loop/,
1163
+ 'Permission was denied',
1164
+ ];
1165
+ function truncate(s, maxLen) {
1166
+ if (!s)
1167
+ return s;
1168
+ return s.length > maxLen ? `${s.slice(0, maxLen)}...` : s;
1169
+ }
1170
+ function sampleHit$1(sampleRate) {
1171
+ if (sampleRate >= 1)
1172
+ return true;
1173
+ if (sampleRate <= 0)
1174
+ return false;
1175
+ return Math.random() < sampleRate;
1176
+ }
1177
+ /** 检查消息是否应该被忽略 */
1178
+ function shouldIgnoreMessage(message, ignorePatterns) {
1179
+ if (!message || ignorePatterns.length === 0)
1180
+ return false;
1181
+ return ignorePatterns.some((pattern) => {
1182
+ if (typeof pattern === 'string') {
1183
+ return message === pattern || message.includes(pattern);
1184
+ }
1185
+ return pattern.test(message);
1186
+ });
1187
+ }
1188
+ function getMpPagePath() {
1189
+ try {
1190
+ const pages = globalThis.getCurrentPages?.();
1191
+ if (Array.isArray(pages) && pages.length > 0) {
1192
+ const page = pages[pages.length - 1];
1193
+ const route = page.route || page.__route__;
1194
+ if (typeof route === 'string') {
1195
+ let path = route.startsWith('/') ? route : `/${route}`;
1196
+ const options = page.options || {};
1197
+ const keys = Object.keys(options);
1198
+ if (keys.length > 0) {
1199
+ const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
1200
+ path = `${path}?${qs}`;
1201
+ }
1202
+ return path;
1203
+ }
1204
+ }
1205
+ return '';
1206
+ }
1207
+ catch {
1208
+ return '';
1209
+ }
1210
+ }
1211
+ function normalizeErrorLike(err, maxTextLength) {
1212
+ if (err && typeof err === 'object') {
1213
+ const anyErr = err;
1214
+ let rawMsg = anyErr.message;
1215
+ if (!rawMsg) {
1216
+ const str = anyErr.toString?.();
1217
+ if (!str || str === '[object Object]') {
1218
+ rawMsg = stringifyLogValue(anyErr);
1219
+ }
1220
+ else {
1221
+ rawMsg = str;
1222
+ }
1223
+ }
1224
+ const message = truncate(String(rawMsg ?? ''), maxTextLength);
1225
+ const name = truncate(String(anyErr.name ?? ''), 200);
1226
+ const stack = truncate(String(anyErr.stack ?? ''), maxTextLength);
1227
+ return { message, name, stack };
1228
+ }
1229
+ const message = truncate(stringifyLogValue(err), maxTextLength);
1230
+ return { message, name: '', stack: '' };
1231
+ }
1232
+ function createDedupeGuard(options) {
1233
+ const cache = new Map(); // key -> lastReportAt
1234
+ const maxKeys = Math.max(0, options.dedupeMaxKeys);
1235
+ const windowMs = Math.max(0, options.dedupeWindowMs);
1236
+ function touch(key, now) {
1237
+ if (cache.has(key))
1238
+ cache.delete(key);
1239
+ cache.set(key, now);
1240
+ if (maxKeys > 0) {
1241
+ while (cache.size > maxKeys) {
1242
+ const first = cache.keys().next().value;
1243
+ if (!first)
1244
+ break;
1245
+ cache.delete(first);
1246
+ }
1247
+ }
1248
+ }
1249
+ return (key) => {
1250
+ if (!key)
1251
+ return true;
1252
+ if (windowMs <= 0 || maxKeys === 0)
1253
+ return true;
1254
+ const now = Date.now();
1255
+ const last = cache.get(key);
1256
+ if (typeof last === 'number' && now - last < windowMs)
1257
+ return false;
1258
+ touch(key, now);
1259
+ return true;
1260
+ };
1261
+ }
1262
+ function buildErrorKey(type, payload) {
1263
+ const parts = [
1264
+ type,
1265
+ String(payload.source ?? ''),
1266
+ String(payload.pagePath ?? ''),
1267
+ String(payload.message ?? ''),
1268
+ String(payload.errorName ?? ''),
1269
+ String(payload.stack ?? ''),
1270
+ String(payload.filename ?? ''),
1271
+ String(payload.lineno ?? ''),
1272
+ String(payload.colno ?? ''),
1273
+ String(payload.tagName ?? ''),
1274
+ String(payload.resourceUrl ?? ''),
1275
+ ];
1276
+ return parts.join('|');
1277
+ }
1278
+ function installMiniProgramErrorMonitor(report, options) {
1279
+ const g = globalThis;
1280
+ if (g.__beLinkClsLoggerMpErrorInstalled__)
1281
+ return;
1282
+ g.__beLinkClsLoggerMpErrorInstalled__ = true;
1283
+ const shouldReport = createDedupeGuard(options);
1284
+ const wxAny = globalThis.wx;
1285
+ try {
1286
+ if (wxAny && typeof wxAny.onError === 'function') {
1287
+ wxAny.onError((msg) => {
1288
+ try {
1289
+ if (!sampleHit$1(options.sampleRate))
1290
+ return;
1291
+ const e = normalizeErrorLike(msg, options.maxTextLength);
1292
+ // 检查是否应该忽略此错误
1293
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1294
+ return;
1295
+ const payload = {
1296
+ pagePath: getMpPagePath(),
1297
+ source: 'wx.onError',
1298
+ message: e.message,
1299
+ errorName: e.name,
1300
+ stack: e.stack,
1301
+ };
1302
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1303
+ return;
1304
+ report(options.reportType, payload);
1305
+ }
1306
+ catch {
1307
+ // ignore
1308
+ }
1309
+ });
1310
+ }
1311
+ }
1312
+ catch {
1313
+ // ignore
1314
+ }
1315
+ try {
1316
+ if (wxAny && typeof wxAny.onUnhandledRejection === 'function') {
1317
+ wxAny.onUnhandledRejection((res) => {
1318
+ try {
1319
+ if (!sampleHit$1(options.sampleRate))
1320
+ return;
1321
+ const e = normalizeErrorLike(res?.reason, options.maxTextLength);
1322
+ // 检查是否应该忽略此错误
1323
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1324
+ return;
1325
+ const payload = {
1326
+ pagePath: getMpPagePath(),
1327
+ source: 'wx.onUnhandledRejection',
1328
+ message: e.message,
1329
+ errorName: e.name,
1330
+ stack: e.stack,
1331
+ };
1332
+ if (!shouldReport(buildErrorKey(options.reportType, payload)))
1333
+ return;
1334
+ report(options.reportType, payload);
1335
+ }
1336
+ catch {
1337
+ // ignore
1338
+ }
1339
+ });
1340
+ }
1341
+ }
1342
+ catch {
1343
+ // ignore
1344
+ }
1345
+ try {
1346
+ if (typeof g.App === 'function' && !g.__beLinkClsLoggerAppWrapped__) {
1347
+ g.__beLinkClsLoggerAppWrapped__ = true;
1348
+ const rawApp = g.App;
1349
+ g.App = (appOptions) => {
1350
+ const next = { ...(appOptions ?? {}) };
1351
+ const rawOnError = next.onError;
1352
+ next.onError = function (...args) {
1353
+ try {
1354
+ if (sampleHit$1(options.sampleRate)) {
1355
+ const e = normalizeErrorLike(args?.[0], options.maxTextLength);
1356
+ // 检查是否应该忽略此错误
1357
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1358
+ const payload = {
1359
+ pagePath: getMpPagePath(),
1360
+ source: 'App.onError',
1361
+ message: e.message,
1362
+ errorName: e.name,
1363
+ stack: e.stack,
1364
+ };
1365
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1366
+ report(options.reportType, payload);
1367
+ }
1368
+ }
1369
+ }
1370
+ catch {
1371
+ // ignore
1372
+ }
1373
+ if (typeof rawOnError === 'function')
1374
+ return rawOnError.apply(this, args);
1375
+ return undefined;
1376
+ };
1377
+ const rawOnUnhandled = next.onUnhandledRejection;
1378
+ next.onUnhandledRejection = function (...args) {
1379
+ try {
1380
+ if (sampleHit$1(options.sampleRate)) {
1381
+ const reason = args?.[0]?.reason ?? args?.[0];
1382
+ const e = normalizeErrorLike(reason, options.maxTextLength);
1383
+ // 检查是否应该忽略此错误
1384
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1385
+ const payload = {
1386
+ pagePath: getMpPagePath(),
1387
+ source: 'App.onUnhandledRejection',
1388
+ message: e.message,
1389
+ errorName: e.name,
1390
+ stack: e.stack,
1391
+ };
1392
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1393
+ report(options.reportType, payload);
1394
+ }
1395
+ }
1396
+ }
1397
+ catch {
1398
+ // ignore
1399
+ }
1400
+ if (typeof rawOnUnhandled === 'function')
1401
+ return rawOnUnhandled.apply(this, args);
1402
+ return undefined;
1403
+ };
1404
+ return rawApp(next);
1405
+ };
1406
+ }
1407
+ }
1408
+ catch {
1409
+ // ignore
1410
+ }
1411
+ }
1412
+ function installMiniErrorMonitor(report, opts = {}) {
1413
+ const enabled = opts === undefined ? true : !!opts;
1414
+ if (!enabled)
1415
+ return;
1416
+ const raw = typeof opts === 'object' && opts ? opts : {};
1417
+ const options = {
1418
+ enabled: true,
1419
+ reportType: raw.reportType ?? 'error',
1420
+ sampleRate: raw.sampleRate ?? 1,
1421
+ captureResourceError: raw.captureResourceError ?? true,
1422
+ maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
1423
+ dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
1424
+ dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
1425
+ ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES,
1426
+ };
1427
+ installMiniProgramErrorMonitor(report, options);
1428
+ }
1429
+
1430
+ function sampleHit(sampleRate) {
1431
+ if (sampleRate >= 1)
1432
+ return true;
1433
+ if (sampleRate <= 0)
1434
+ return false;
1435
+ return Math.random() < sampleRate;
1436
+ }
1437
+ function installMiniProgramPerformanceMonitor(report, options) {
1438
+ const g = globalThis;
1439
+ const ctx = g.wx || g.Taro;
1440
+ if (!ctx || typeof ctx.getPerformance !== 'function')
1441
+ return;
1442
+ if (g.__beLinkClsLoggerMpPerfInstalled__)
1443
+ return;
1444
+ g.__beLinkClsLoggerMpPerfInstalled__ = true;
1445
+ try {
1446
+ const perf = ctx.getPerformance();
1447
+ if (!perf || typeof perf.createObserver !== 'function')
1448
+ return;
1449
+ const observer = perf.createObserver((entryList) => {
1450
+ try {
1451
+ const entries = entryList.getEntries();
1452
+ for (const entry of entries) {
1453
+ if (!sampleHit(options.sampleRate))
1454
+ continue;
1455
+ // Page Render: firstRender
1456
+ if (entry.entryType === 'render' && entry.name === 'firstRender') {
1457
+ const duration = typeof entry.duration === 'number'
1458
+ ? entry.duration
1459
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1460
+ ? entry.endTime - entry.startTime
1461
+ : 0;
1462
+ report(options.reportType, {
1463
+ metric: 'page-render',
1464
+ duration,
1465
+ pagePath: entry.path || '',
1466
+ unit: 'ms',
1467
+ });
1468
+ }
1469
+ // Route Switch: route
1470
+ else if (entry.entryType === 'navigation' && entry.name === 'route') {
1471
+ const duration = typeof entry.duration === 'number'
1472
+ ? entry.duration
1473
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1474
+ ? entry.endTime - entry.startTime
1475
+ : 0;
1476
+ report(options.reportType, {
1477
+ metric: 'route',
1478
+ duration,
1479
+ pagePath: entry.path || '',
1480
+ unit: 'ms',
1481
+ });
1482
+ }
1483
+ // App Launch: appLaunch (Cold)
1484
+ else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
1485
+ report(options.reportType, {
1486
+ metric: 'app-launch',
1487
+ duration: entry.duration,
1488
+ launchType: 'cold',
1489
+ unit: 'ms',
1490
+ });
1491
+ }
1492
+ }
1493
+ }
1494
+ catch {
1495
+ // ignore
1496
+ }
1497
+ });
1498
+ observer.observe({ entryTypes: ['navigation', 'render'] });
1499
+ }
1500
+ catch {
1501
+ // ignore
1502
+ }
1503
+ }
1504
+ function installMiniPerformanceMonitor(report, opts = {}) {
1505
+ const enabled = opts === undefined ? true : !!opts;
1506
+ if (!enabled)
1507
+ return;
1508
+ const raw = typeof opts === 'object' && opts ? opts : {};
1509
+ const options = {
1510
+ enabled: true,
1511
+ reportType: raw.reportType ?? 'perf',
1512
+ sampleRate: raw.sampleRate ?? 1,
1513
+ ignoreUrls: raw.ignoreUrls ?? [],
1514
+ webVitals: raw.webVitals ?? true,
1515
+ navigationTiming: raw.navigationTiming ?? true,
1516
+ resourceTiming: raw.resourceTiming ?? true,
1517
+ maxTextLength: raw.maxTextLength ?? 2000,
1518
+ };
1519
+ installMiniProgramPerformanceMonitor(report, options);
1520
+ }
1521
+
1522
+ function shouldSample(sampleRate) {
1523
+ const r = sampleRate ?? 1;
1524
+ if (r >= 1)
1525
+ return true;
1526
+ if (r <= 0)
1527
+ return false;
1528
+ return Math.random() < r;
1529
+ }
1530
+ function generateUUID() {
1531
+ const g = globalThis;
1532
+ if (g.crypto?.randomUUID)
1533
+ return g.crypto.randomUUID();
1534
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
1535
+ const r = Math.random() * 16 || 0;
1536
+ const v = c === 'x' ? r | 0 : ((r | 0) & 0x3) | 0x8;
1537
+ return v.toString(16);
1538
+ });
1539
+ }
1540
+ function safeReadUvMeta(key) {
1541
+ const raw = readStringStorage(key);
1542
+ if (!raw)
1543
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1544
+ try {
1545
+ const parsed = JSON.parse(raw);
1546
+ if (!parsed || typeof parsed !== 'object')
1547
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1548
+ const p = parsed;
1549
+ const firstVisitTs = typeof p.firstVisitTs === 'number' && Number.isFinite(p.firstVisitTs) ? p.firstVisitTs : Date.now();
1550
+ const visitCount = typeof p.visitCount === 'number' && Number.isFinite(p.visitCount) ? p.visitCount : 0;
1551
+ const createdAtTs = typeof p.createdAtTs === 'number' && Number.isFinite(p.createdAtTs) ? p.createdAtTs : undefined;
1552
+ const lastSeenTs = typeof p.lastSeenTs === 'number' && Number.isFinite(p.lastSeenTs) ? p.lastSeenTs : undefined;
1553
+ return { firstVisitTs, visitCount, createdAtTs, lastSeenTs };
1554
+ }
1555
+ catch {
1556
+ return { firstVisitTs: Date.now(), visitCount: 0 };
1557
+ }
1558
+ }
1559
+ function writeUvMeta(key, meta) {
1560
+ writeStringStorage(key, JSON.stringify(meta));
1561
+ }
1562
+ function getMiniProgramPagePath() {
1563
+ const g = globalThis;
1564
+ try {
1565
+ const pages = typeof g.getCurrentPages === 'function' ? g.getCurrentPages() : [];
1566
+ const last = Array.isArray(pages) ? pages[pages.length - 1] : undefined;
1567
+ const route = (last?.route || last?.__route__);
1568
+ if (typeof route !== 'string')
1569
+ return '';
1570
+ let path = route.startsWith('/') ? route : `/${route}`;
1571
+ const options = last?.options || {};
1572
+ const keys = Object.keys(options);
1573
+ if (keys.length > 0) {
1574
+ const qs = keys.map((k) => `${k}=${options[k]}`).join('&');
1575
+ path = `${path}?${qs}`;
1576
+ }
1577
+ return path;
1578
+ }
1579
+ catch {
1580
+ return '';
1581
+ }
1582
+ }
1583
+ function buildCommonUvFields(uvId, uvMeta, isFirstVisit) {
1584
+ return {
1585
+ uvId,
1586
+ isFirstVisit,
1587
+ firstVisitTs: uvMeta.firstVisitTs,
1588
+ visitCount: uvMeta.visitCount,
1589
+ };
1590
+ }
1591
+ function truncateText(s, maxLen) {
1592
+ if (!s)
1593
+ return '';
1594
+ if (s.length <= maxLen)
1595
+ return s;
1596
+ return s.slice(0, maxLen);
1597
+ }
1598
+ function installMiniBehaviorMonitor(report, options = {}) {
1599
+ const enableTrack = options.enableTrack ?? options.enabled ?? true;
1600
+ if (!enableTrack)
1601
+ return () => { };
1602
+ const pvEnabled = options.pv ?? true;
1603
+ const uvEnabled = options.uv ?? true;
1604
+ const clickEnabled = options.click ?? true;
1605
+ const pvReportType = options.pvReportType ?? 'pv';
1606
+ const uvReportType = options.uvReportType ?? 'uv';
1607
+ const clickReportType = options.clickReportType ?? 'click';
1608
+ const uvIdStorageKey = options.uvIdStorageKey ?? 'cls_uv_id';
1609
+ const uvMetaStorageKey = options.uvMetaStorageKey ?? 'cls_uv_meta';
1610
+ const lastPagePathStorageKey = options.lastPagePathStorageKey ?? 'cls_last_page_path';
1611
+ const uvExpireDaysRaw = options.trackOptions?.uvExpireDays ?? options.uvExpireDays ?? 30;
1612
+ const uvExpireDays = Number.isFinite(uvExpireDaysRaw) ? Math.max(0, uvExpireDaysRaw) : 30;
1613
+ const uvExpireMs = uvExpireDays * 24 * 60 * 60 * 1000;
1614
+ const clickWhiteList = (options.trackOptions?.clickWhiteList ??
1615
+ options.clickWhiteList ?? ['view', 'scroll-view']).map((s) => String(s).toLowerCase());
1616
+ const clickMaxTextLength = options.clickMaxTextLength ?? 120;
1617
+ const getPagePath = options.getPagePath ?? getMiniProgramPagePath;
1618
+ let destroyed = false;
1619
+ let firstVisitFlag = false;
1620
+ let firstVisitConsumed = false;
1621
+ const uvStatePromise = (async () => {
1622
+ let existingUvId = readStringStorage(uvIdStorageKey);
1623
+ let isFirstVisit = false;
1624
+ const now = Date.now();
1625
+ const metaBefore = safeReadUvMeta(uvMetaStorageKey);
1626
+ const lastSeenForExpire = metaBefore.lastSeenTs ?? metaBefore.createdAtTs ?? metaBefore.firstVisitTs ?? now;
1627
+ const expired = uvExpireMs > 0 && now - lastSeenForExpire > uvExpireMs;
1628
+ if (expired) {
1629
+ existingUvId = null;
1630
+ writeUvMeta(uvMetaStorageKey, { firstVisitTs: now, visitCount: 0, createdAtTs: now, lastSeenTs: now });
1631
+ writeStringStorage(uvIdStorageKey, '');
1632
+ }
1633
+ try {
1634
+ if (options.getUvId) {
1635
+ const maybe = options.getUvId();
1636
+ const resolved = typeof maybe?.then === 'function' ? await maybe : maybe;
1637
+ if (resolved && typeof resolved === 'string')
1638
+ existingUvId = resolved;
1639
+ }
1640
+ }
1641
+ catch {
1642
+ /* ignore */
1643
+ }
1644
+ if (!existingUvId) {
1645
+ const wxAny = globalThis.wx;
1646
+ try {
1647
+ const userInfo = wxAny?.getStorageSync?.('userInfo');
1648
+ if (userInfo?.openid)
1649
+ existingUvId = String(userInfo.openid);
1650
+ }
1651
+ catch {
1652
+ /* ignore */
1653
+ }
1654
+ if (!existingUvId) {
1655
+ try {
1656
+ const sys = wxAny?.getSystemInfoSync?.();
1657
+ const deviceId = sys?.deviceId ? String(sys.deviceId) : '';
1658
+ const model = sys?.model ? String(sys.model) : '';
1659
+ const system = sys?.system ? String(sys.system) : '';
1660
+ const base = [deviceId || model, system].filter(Boolean).join('_');
1661
+ if (base)
1662
+ existingUvId = `${base}_${Date.now()}`;
1663
+ }
1664
+ catch {
1665
+ /* ignore */
1666
+ }
1667
+ }
1668
+ }
1669
+ if (!existingUvId) {
1670
+ existingUvId = generateUUID();
1671
+ isFirstVisit = true;
1672
+ }
1673
+ writeStringStorage(uvIdStorageKey, existingUvId);
1674
+ const meta = safeReadUvMeta(uvMetaStorageKey);
1675
+ const createdAt = meta.createdAtTs ?? meta.firstVisitTs ?? now;
1676
+ const firstVisit = meta.firstVisitTs || now;
1677
+ const nextMeta = {
1678
+ firstVisitTs: firstVisit,
1679
+ visitCount: (meta.visitCount || 0) + 1,
1680
+ createdAtTs: createdAt,
1681
+ lastSeenTs: now,
1682
+ };
1683
+ if (isFirstVisit) {
1684
+ nextMeta.firstVisitTs = now;
1685
+ nextMeta.createdAtTs = now;
1686
+ }
1687
+ writeUvMeta(uvMetaStorageKey, nextMeta);
1688
+ firstVisitFlag = isFirstVisit;
1689
+ return { uvId: existingUvId, isFirstVisit, meta: nextMeta };
1690
+ })();
1691
+ function safeReport(type, data) {
1692
+ if (destroyed)
1693
+ return;
1694
+ if (!shouldSample(options.sampleRate))
1695
+ return;
1696
+ report(type, data);
1697
+ }
1698
+ function buildUvFieldsOnce(uvId, meta) {
1699
+ const once = firstVisitFlag && !firstVisitConsumed;
1700
+ if (once)
1701
+ firstVisitConsumed = true;
1702
+ return buildCommonUvFields(uvId, meta, once);
1703
+ }
1704
+ function reportPv(pagePath) {
1705
+ if (!pvEnabled)
1706
+ return;
1707
+ void uvStatePromise.then(({ uvId, meta }) => {
1708
+ if (destroyed)
1709
+ return;
1710
+ const payload = {
1711
+ ...buildUvFieldsOnce(uvId, meta),
1712
+ timestamp: Date.now(),
1713
+ pagePath,
1714
+ referrer: readStringStorage(lastPagePathStorageKey) || '',
1715
+ };
1716
+ writeStringStorage(lastPagePathStorageKey, pagePath);
1717
+ safeReport(pvReportType, payload);
1718
+ });
1719
+ }
1720
+ // MiniProgram Page Patch
1721
+ let restoreMiniProgramPatch = null;
1722
+ const g = globalThis;
1723
+ const patchedKey = '__beLinkClsLoggerBehaviorPatched__';
1724
+ if (!g[patchedKey]) {
1725
+ g[patchedKey] = true;
1726
+ const originalPage = typeof g.Page === 'function' ? g.Page : null;
1727
+ if (originalPage) {
1728
+ g.Page = function patchedPage(conf) {
1729
+ const originalOnShow = conf?.onShow;
1730
+ conf.onShow = function (...args) {
1731
+ if (pvEnabled) {
1732
+ const pagePath = getPagePath();
1733
+ if (pagePath?.length > 0)
1734
+ reportPv(pagePath);
1735
+ }
1736
+ return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
1737
+ };
1738
+ if (clickEnabled && conf && typeof conf === 'object') {
1739
+ for (const key of Object.keys(conf)) {
1740
+ const fn = conf[key];
1741
+ if (typeof fn !== 'function')
1742
+ continue;
1743
+ if (fn.__beLinkWrapped__)
1744
+ continue;
1745
+ conf[key] = function (...args) {
1746
+ try {
1747
+ const e = args?.[0];
1748
+ const type = e?.type;
1749
+ const currentTarget = e?.currentTarget;
1750
+ const dataset = currentTarget?.dataset;
1751
+ const isTap = type === 'tap' || type === 'click';
1752
+ if (isTap && currentTarget && dataset) {
1753
+ const tagNameRaw = dataset?.tagName ?? dataset?.tag ?? currentTarget?.tagName ?? '';
1754
+ const tagName = String(tagNameRaw || '').toLowerCase();
1755
+ const trackId = dataset?.trackId ? String(dataset.trackId) : '';
1756
+ if (!(clickWhiteList.includes(tagName) && !trackId)) {
1757
+ const x = typeof e?.detail?.x === 'number' ? e.detail.x : (e?.touches?.[0]?.pageX ?? 0);
1758
+ const y = typeof e?.detail?.y === 'number' ? e.detail.y : (e?.touches?.[0]?.pageY ?? 0);
1759
+ void uvStatePromise.then(({ uvId, meta }) => {
1760
+ if (destroyed)
1761
+ return;
1762
+ safeReport(clickReportType, {
1763
+ ...buildUvFieldsOnce(uvId, meta),
1764
+ timestamp: Date.now(),
1765
+ pagePath: getPagePath(),
1766
+ elementTag: tagNameRaw ? String(tagNameRaw) : '',
1767
+ elementId: currentTarget?.id ? String(currentTarget.id) : '',
1768
+ elementClass: dataset?.className ? stringifyLogValue(dataset.className) : '',
1769
+ trackId,
1770
+ elementText: dataset?.text ? truncateText(String(dataset.text), clickMaxTextLength) : '',
1771
+ clickX: x,
1772
+ clickY: y,
1773
+ });
1774
+ });
1775
+ }
1776
+ }
1777
+ }
1778
+ catch {
1779
+ /* ignore */
1780
+ }
1781
+ return fn.apply(this, args);
1782
+ };
1783
+ conf[key].__beLinkWrapped__ = true;
1784
+ }
1785
+ }
1786
+ return originalPage(conf);
1787
+ };
1788
+ restoreMiniProgramPatch = () => {
1789
+ g.Page = originalPage;
1790
+ g[patchedKey] = false;
1791
+ };
1792
+ }
1793
+ }
1794
+ if (pvEnabled)
1795
+ reportPv(getPagePath());
1796
+ if (uvEnabled) {
1797
+ void uvStatePromise.then(({ uvId, meta }) => {
1798
+ if (destroyed)
1799
+ return;
1800
+ safeReport(uvReportType, {
1801
+ ...buildUvFieldsOnce(uvId, meta),
1802
+ timestamp: Date.now(),
1803
+ pagePath: getPagePath(),
1804
+ });
1805
+ });
1806
+ }
1807
+ return () => {
1808
+ destroyed = true;
1809
+ restoreMiniProgramPatch?.();
1810
+ };
1811
+ }
1812
+
1813
+ function getMiniProgramDeviceInfo(options) {
1814
+ const out = {
1815
+ envType: 'miniprogram',
1816
+ };
1817
+ const wxAny = globalThis.wx;
1818
+ if (!wxAny || typeof wxAny.getSystemInfoSync !== 'function')
1819
+ return out;
1820
+ try {
1821
+ const sys = wxAny.getSystemInfoSync();
1822
+ out.mpBrand = sys?.brand ? String(sys.brand) : '';
1823
+ out.mpModel = sys?.model ? String(sys.model) : '';
1824
+ out.mpSystem = sys?.system ? String(sys.system) : '';
1825
+ out.mpPlatform = sys?.platform ? String(sys.platform) : '';
1826
+ out.mpWeChatVersion = sys?.version ? String(sys.version) : '';
1827
+ out.mpSDKVersion = sys?.SDKVersion ? String(sys.SDKVersion) : '';
1828
+ out.mpScreenWidth = typeof sys?.screenWidth === 'number' ? sys.screenWidth : undefined;
1829
+ out.mpScreenHeight = typeof sys?.screenHeight === 'number' ? sys.screenHeight : undefined;
1830
+ out.mpPixelRatio = typeof sys?.pixelRatio === 'number' ? sys.pixelRatio : undefined;
1831
+ out.language = sys?.language ? String(sys.language) : '';
1832
+ }
1833
+ catch {
1834
+ // ignore
1835
+ }
1836
+ if (options.includeNetworkType) {
1837
+ try {
1838
+ if (typeof wxAny.getNetworkTypeSync === 'function') {
1839
+ const n = wxAny.getNetworkTypeSync();
1840
+ out.networkType = n?.networkType ? String(n.networkType) : '';
1841
+ }
1842
+ else if (typeof wxAny.getNetworkType === 'function') {
1843
+ // 异步更新:先不阻塞初始化
1844
+ wxAny.getNetworkType({
1845
+ success: (res) => {
1846
+ try {
1847
+ const g = globalThis;
1848
+ if (!g.__beLinkClsLoggerDeviceInfo__)
1849
+ g.__beLinkClsLoggerDeviceInfo__ = {};
1850
+ g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1851
+ }
1852
+ catch {
1853
+ // ignore
1854
+ }
1855
+ },
1856
+ });
1857
+ }
1858
+ }
1859
+ catch {
1860
+ // ignore
1861
+ }
1862
+ try {
1863
+ if (typeof wxAny.onNetworkStatusChange === 'function') {
1864
+ wxAny.onNetworkStatusChange((res) => {
1865
+ try {
1866
+ const g = globalThis;
1867
+ if (!g.__beLinkClsLoggerDeviceInfo__)
1868
+ g.__beLinkClsLoggerDeviceInfo__ = {};
1869
+ g.__beLinkClsLoggerDeviceInfo__.networkType = res?.networkType ? String(res.networkType) : '';
1870
+ }
1871
+ catch {
1872
+ // ignore
1873
+ }
1874
+ });
1875
+ }
1876
+ }
1877
+ catch {
1878
+ // ignore
1879
+ }
1880
+ }
1881
+ return out;
1882
+ }
1883
+ function createMiniDeviceInfoBaseFields(opts) {
1884
+ const enabled = opts === undefined ? true : !!opts;
1885
+ if (!enabled)
1886
+ return null;
1887
+ const raw = typeof opts === 'object' && opts ? opts : {};
1888
+ const options = {
1889
+ includeUserAgent: raw.includeUserAgent ?? true,
1890
+ includeNetwork: raw.includeNetwork ?? true,
1891
+ includeNetworkType: raw.includeNetworkType ?? true,
1892
+ };
1893
+ let base = null;
1894
+ const globalKey = '__beLinkClsLoggerDeviceInfo__';
1895
+ return () => {
1896
+ if (!base) {
1897
+ base = getMiniProgramDeviceInfo(options);
1898
+ try {
1899
+ const g = globalThis;
1900
+ if (!g[globalKey])
1901
+ g[globalKey] = { ...base };
1902
+ }
1903
+ catch {
1904
+ // ignore
1905
+ }
1906
+ }
1907
+ try {
1908
+ const g = globalThis;
1909
+ const extra = g[globalKey];
1910
+ if (extra && isPlainObject(extra))
1911
+ return { ...base, ...extra };
1912
+ }
1913
+ catch {
1914
+ // ignore
1915
+ }
1916
+ return base;
1917
+ };
1918
+ }
1919
+
1920
+ // @ts-ignore
1921
+ // 移除动态加载,在 Mini 入口直接静态引用以确保小程序环境下的稳定性
1922
+ class ClsLoggerMini extends ClsLoggerCore {
1923
+ constructor() {
1924
+ super(...arguments);
1925
+ this.envType = 'miniprogram';
1926
+ }
1927
+ async loadSdk() {
1928
+ if (this.sdk)
1929
+ return this.sdk;
1930
+ const sdk = this.normalize(tencentcloudClsSdkJsMini__namespace);
1931
+ if (sdk) {
1932
+ this.sdk = sdk;
1933
+ return sdk;
1934
+ }
1935
+ console.warn('[ClsLogger] SDK "tencentcloud-cls-sdk-js-mini" not found or invalid. Logging will be disabled.');
1936
+ throw new Error('SDK not found');
1937
+ }
1938
+ installRequestMonitor(report, options) {
1939
+ installMiniRequestMonitor(report, options);
1940
+ }
1941
+ installErrorMonitor(report, options) {
1942
+ installMiniErrorMonitor(report, options);
1943
+ }
1944
+ installPerformanceMonitor(report, options) {
1945
+ installMiniPerformanceMonitor(report, options);
1946
+ }
1947
+ installBehaviorMonitor(report, options) {
1948
+ return installMiniBehaviorMonitor(report, typeof options === 'boolean' ? {} : options);
1949
+ }
1950
+ createDeviceInfoBaseFields(options) {
1951
+ return createMiniDeviceInfoBaseFields(options);
1952
+ }
1953
+ normalize(m) {
1954
+ const mod = (m?.default && m.default.AsyncClient ? m.default : m);
1955
+ if (mod?.AsyncClient) {
1956
+ return {
1957
+ AsyncClient: mod.AsyncClient,
1958
+ Log: mod.Log,
1959
+ LogGroup: mod.LogGroup,
1960
+ PutLogsRequest: mod.PutLogsRequest,
1961
+ };
1962
+ }
1963
+ return null;
1964
+ }
1965
+ }
1966
+
1967
+ const clsLogger = new ClsLoggerMini();
1968
+
1969
+ exports.ClsLogger = ClsLoggerMini;
1970
+ exports.clsLogger = clsLogger;
1971
+ exports.default = clsLogger;