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

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