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