@be-link/cls-logger 1.0.1-beta.11 → 1.0.1-beta.13

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