@be-link/cls-logger 1.0.7 → 1.0.9

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