@clipto/reporter 0.1.0 → 0.2.0

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/index.js CHANGED
@@ -11,30 +11,7 @@ var QUEUE_KEY = "pending";
11
11
  var LS_KEY = "clipto_report_pending_queue";
12
12
  function buildPayload(events) {
13
13
  return {
14
- // attempts 为 SDK 内部字段,不上报;name 输出为 eventName(对齐旧 SDK)
15
- events: events.map(
16
- ({
17
- id,
18
- name,
19
- timestamp,
20
- sessionId,
21
- userId,
22
- deviceId,
23
- properties,
24
- category,
25
- context
26
- }) => ({
27
- id,
28
- eventName: name,
29
- timestamp,
30
- sessionId,
31
- userId,
32
- deviceId,
33
- properties,
34
- category,
35
- context
36
- })
37
- ),
14
+ events,
38
15
  metadata: {
39
16
  sdkVersion: SDK_VERSION,
40
17
  timestamp: Date.now(),
@@ -43,17 +20,26 @@ function buildPayload(events) {
43
20
  }
44
21
  };
45
22
  }
46
- function createBrowserTransport(endpoint, headers) {
23
+ async function signHeaders(payload, signer) {
24
+ if (!signer) return {};
25
+ return signer(JSON.stringify(payload));
26
+ }
27
+ function createBrowserTransport(endpoint, headers, signer) {
47
28
  const commonHeaders = {
48
29
  "Content-Type": "application/json",
49
30
  ...headers ?? {}
50
31
  };
51
32
  return {
52
33
  async send(events) {
34
+ const payload = buildPayload(events);
35
+ const requestHeaders = {
36
+ ...commonHeaders,
37
+ ...await signHeaders(payload, signer)
38
+ };
53
39
  const response = await fetch(endpoint, {
54
40
  method: "POST",
55
- headers: commonHeaders,
56
- body: JSON.stringify(buildPayload(events)),
41
+ headers: requestHeaders,
42
+ body: JSON.stringify(payload),
57
43
  keepalive: true
58
44
  });
59
45
  if (!response.ok) {
@@ -61,7 +47,7 @@ function createBrowserTransport(endpoint, headers) {
61
47
  }
62
48
  },
63
49
  sendSync(events) {
64
- if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") {
50
+ if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function" || signer) {
65
51
  return false;
66
52
  }
67
53
  try {
@@ -75,12 +61,16 @@ function createBrowserTransport(endpoint, headers) {
75
61
  }
76
62
  };
77
63
  }
78
- async function createNodeTransport(endpoint, headers) {
64
+ async function createNodeTransport(endpoint, headers, signer) {
79
65
  const { default: axios } = await import("axios");
80
66
  return {
81
67
  async send(events) {
82
- await axios.post(endpoint, buildPayload(events), {
83
- headers,
68
+ const payload = buildPayload(events);
69
+ await axios.post(endpoint, payload, {
70
+ headers: {
71
+ ...headers ?? {},
72
+ ...await signHeaders(payload, signer)
73
+ },
84
74
  timeout: 1e4
85
75
  });
86
76
  }
@@ -158,6 +148,167 @@ async function createNodeStorage(persistDir) {
158
148
  };
159
149
  }
160
150
 
151
+ // src/collect.ts
152
+ import { UAParser } from "ua-parser-js";
153
+ function parseUserAgent(ua) {
154
+ const parsed = new UAParser(ua);
155
+ const browser = parsed.getBrowser();
156
+ const os = parsed.getOS();
157
+ const info = {};
158
+ if (browser.name) {
159
+ info.browserName = browser.name === "Mobile Safari" ? "Safari" : browser.name === "Mobile Chrome" ? "Chrome" : browser.name;
160
+ }
161
+ if (browser.version) info.browserVersion = browser.version;
162
+ if (os.name) info.osName = os.name === "Mac OS" ? "macOS" : os.name;
163
+ if (os.version) info.osVersion = os.version;
164
+ return info;
165
+ }
166
+ function collectBrowserDevice() {
167
+ if (typeof navigator === "undefined") return {};
168
+ const { browserName, browserVersion, osName, osVersion } = parseUserAgent(
169
+ navigator.userAgent || ""
170
+ );
171
+ const device = {};
172
+ if (browserName) device.browserName = browserName;
173
+ if (browserVersion) device.browserVersion = browserVersion;
174
+ if (osName) device.osName = osName;
175
+ if (osVersion) device.osVersion = osVersion;
176
+ const uaData = navigator.userAgentData;
177
+ if (uaData?.platform) device.platform = uaData.platform;
178
+ else if (navigator.platform) device.platform = navigator.platform;
179
+ if (navigator.language) device.language = navigator.language;
180
+ return device;
181
+ }
182
+ async function collectNodeDevice() {
183
+ try {
184
+ const os = await import("os");
185
+ const device = {
186
+ platform: os.platform(),
187
+ osVersion: os.release(),
188
+ arch: os.arch(),
189
+ memSize: Math.round(os.totalmem() / 1024 ** 3)
190
+ // 统一 GB
191
+ };
192
+ const type = os.type();
193
+ device.osName = type === "Darwin" ? "macOS" : type === "Windows_NT" ? "Windows" : type;
194
+ const cpu = os.cpus()[0]?.model;
195
+ if (cpu) device.cpu = cpu;
196
+ return device;
197
+ } catch {
198
+ return {};
199
+ }
200
+ }
201
+ function collectPageSnapshot() {
202
+ if (typeof document === "undefined") return {};
203
+ const page = {};
204
+ if (location.href) page.url = location.href;
205
+ if (document.title) page.title = document.title;
206
+ if (document.referrer) page.referrer = document.referrer;
207
+ return page;
208
+ }
209
+
210
+ // src/page.ts
211
+ var SCROLL_GESTURE_GAP_MS = 500;
212
+ var IDLE_PAUSE_MS = 6e4;
213
+ var METRIC_TICK_MS = 1e3;
214
+ function createPageTracker(onActivity) {
215
+ let visit = null;
216
+ let interval = null;
217
+ const touch = () => {
218
+ if (!visit) return;
219
+ visit.lastActivityAt = Date.now();
220
+ onActivity();
221
+ };
222
+ const updateMaxDepth = () => {
223
+ if (!visit) return;
224
+ const doc = document.documentElement;
225
+ if (!doc) return;
226
+ const total = Math.max(doc.scrollHeight, 1);
227
+ const depth = Math.round(
228
+ (window.scrollY + window.innerHeight) / total * 100
229
+ );
230
+ visit.maxScrollDepthPct = Math.max(
231
+ visit.maxScrollDepthPct,
232
+ Math.min(depth, 100)
233
+ );
234
+ };
235
+ const onScroll = () => {
236
+ if (!visit) return;
237
+ const now = Date.now();
238
+ if (now - visit.lastScrollAt > SCROLL_GESTURE_GAP_MS) {
239
+ visit.scrollCount += 1;
240
+ }
241
+ visit.lastScrollAt = now;
242
+ touch();
243
+ updateMaxDepth();
244
+ };
245
+ const onInput = () => touch();
246
+ const tick = () => {
247
+ if (!visit) return;
248
+ if (document.visibilityState === "visible" && Date.now() - visit.lastActivityAt <= IDLE_PAUSE_MS) {
249
+ visit.activeMs += METRIC_TICK_MS;
250
+ }
251
+ updateMaxDepth();
252
+ };
253
+ const removeListeners = () => {
254
+ window.removeEventListener("scroll", onScroll);
255
+ window.removeEventListener("pointerdown", onInput, { capture: true });
256
+ window.removeEventListener("keydown", onInput, { capture: true });
257
+ if (interval) {
258
+ clearInterval(interval);
259
+ interval = null;
260
+ }
261
+ };
262
+ const startVisit = () => {
263
+ if (visit) return;
264
+ const now = Date.now();
265
+ visit = {
266
+ pageViewId: `pv_${generateEventId()}`,
267
+ enteredAt: now,
268
+ snapshot: collectPageSnapshot(),
269
+ activeMs: 0,
270
+ scrollCount: 0,
271
+ maxScrollDepthPct: 0,
272
+ lastActivityAt: now,
273
+ lastScrollAt: 0
274
+ };
275
+ window.addEventListener("scroll", onScroll, { passive: true });
276
+ window.addEventListener("pointerdown", onInput, {
277
+ capture: true,
278
+ passive: true
279
+ });
280
+ window.addEventListener("keydown", onInput, { capture: true, passive: true });
281
+ interval = setInterval(tick, METRIC_TICK_MS);
282
+ };
283
+ const endVisit = (reason) => {
284
+ if (!visit) return void 0;
285
+ removeListeners();
286
+ const finished = visit;
287
+ visit = null;
288
+ if (document.title) {
289
+ finished.snapshot.title = document.title;
290
+ }
291
+ return {
292
+ ...finished.snapshot,
293
+ pageViewId: finished.pageViewId,
294
+ durationMs: Date.now() - finished.enteredAt,
295
+ activeMs: finished.activeMs,
296
+ scrollCount: finished.scrollCount,
297
+ maxScrollDepthPct: finished.maxScrollDepthPct,
298
+ endReason: reason
299
+ };
300
+ };
301
+ return {
302
+ get active() {
303
+ return visit !== null;
304
+ },
305
+ startVisit,
306
+ endVisit,
307
+ pageViewId: () => visit?.pageViewId,
308
+ dispose: removeListeners
309
+ };
310
+ }
311
+
161
312
  // src/reporter.ts
162
313
  var DEFAULT_FLUSH_INTERVAL = 2e3;
163
314
  var DEFAULT_MAX_BATCH_SIZE = 10;
@@ -166,11 +317,33 @@ var DEFAULT_MAX_QUEUE_SIZE = 1e3;
166
317
  var DEFAULT_MAX_ATTEMPTS = 3;
167
318
  var DEFAULT_BACKOFF_MS = 1e3;
168
319
  var STORAGE_WRITE_THROTTLE_MS = 500;
320
+ var VISIT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
321
+ var SESSION_SAVE_THROTTLE_MS = 1e4;
322
+ var ANONYMOUS_ID_KEY = "clipto_report_anonymous_id";
323
+ var CLIENT_ID_KEY = "clipto_report_client_id";
324
+ var SESSION_KEY = "clipto_report_session";
325
+ function normalizeContext(context) {
326
+ if (typeof context === "function") return context;
327
+ return () => context ?? {};
328
+ }
329
+ function stripAttempts(events) {
330
+ return events.map((event) => {
331
+ const { attempts: _attempts, ...rest } = event;
332
+ return rest;
333
+ });
334
+ }
169
335
  var Reporter = class {
170
336
  constructor(options) {
171
- /** 会话 / 设备 id 兜底:enrich 未提供时按实例生成(对齐旧 SDK 格式) */
172
- this.sessionId = `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
173
- this.deviceId = `device_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
337
+ /** 会话落盘时间戳(节流用);声明在 session 之前:session 初始化会触发强制落盘 */
338
+ this.sessionSaveAt = 0;
339
+ /** 会话共享读时间戳(节流用):多 tab 共享会话,活动时定期重读 localStorage 最新值 */
340
+ this.sessionReadAt = 0;
341
+ /** Node 端设备快照(init 时采集一次,避免每次入队动态加载 os) */
342
+ this.nodeDevice = {};
343
+ /** 页面访问跟踪(browser + autoPageView 时启用) */
344
+ this.pageTracker = null;
345
+ /** history 补丁的原始引用(dispose 时还原) */
346
+ this.historyPatch = null;
174
347
  /** 待发队列(内存中的事实源,持久化是它的影子) */
175
348
  this.queue = [];
176
349
  this.flushTimer = null;
@@ -183,13 +356,31 @@ var Reporter = class {
183
356
  this.fire(this.dispose());
184
357
  };
185
358
  this.onPageHide = () => {
359
+ this.endPageVisit(this.session.visitId, "close");
186
360
  this.fire(this.dispose());
187
361
  };
362
+ this.onPageShow = () => {
363
+ if (document.visibilityState === "visible") {
364
+ this.pageTracker?.startVisit();
365
+ }
366
+ };
188
367
  this.onVisibilityChange = () => {
189
368
  if (document.visibilityState === "hidden") {
369
+ this.endPageVisit(this.session.visitId, "background");
190
370
  this.fire(this.flush());
191
- } else if (this.opts.autoPageView) {
192
- this.track("page_view");
371
+ } else {
372
+ this.pageTracker?.startVisit();
373
+ }
374
+ };
375
+ this.onPopState = () => {
376
+ this.endPageVisit(this.session.visitId, "back");
377
+ this.pageTracker?.startVisit();
378
+ };
379
+ this.onStorage = (event) => {
380
+ if (event.key !== SESSION_KEY || !event.newValue) return;
381
+ try {
382
+ this.adoptSharedSession(JSON.parse(event.newValue));
383
+ } catch {
193
384
  }
194
385
  };
195
386
  if (!options.endpoint) {
@@ -197,6 +388,7 @@ var Reporter = class {
197
388
  }
198
389
  this.opts = options;
199
390
  this.platform = options.platform ?? (typeof window !== "undefined" ? "browser" : "node");
391
+ this.contextFn = normalizeContext(options.context);
200
392
  this.flushInterval = options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
201
393
  this.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
202
394
  this.maxBatchBytes = options.maxBatchBytes ?? DEFAULT_MAX_BATCH_BYTES;
@@ -205,16 +397,20 @@ var Reporter = class {
205
397
  this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
206
398
  this.backoffMs = options.backoffMs ?? DEFAULT_BACKOFF_MS;
207
399
  this.flushOnExit = options.flushOnExit ?? true;
400
+ this._anonymousId = this.loadOrCreateAnonymousId();
401
+ this._clientId = this.loadOrCreateClientId();
402
+ this.session = this.loadOrCreateSession();
208
403
  if (options.transport) {
209
404
  this.transportPromise = Promise.resolve(options.transport);
210
405
  } else if (this.platform === "browser") {
211
406
  this.transportPromise = Promise.resolve(
212
- createBrowserTransport(options.endpoint, options.headers)
407
+ createBrowserTransport(options.endpoint, options.headers, options.signer)
213
408
  );
214
409
  } else {
215
410
  this.transportPromise = createNodeTransport(
216
411
  options.endpoint,
217
- options.headers
412
+ options.headers,
413
+ options.signer
218
414
  );
219
415
  }
220
416
  if (options.storage) {
@@ -230,35 +426,20 @@ var Reporter = class {
230
426
  }
231
427
  this.fire(this.init());
232
428
  }
233
- track(name, properties, options) {
429
+ track(eventName, properties, options) {
234
430
  if (this.disposed) {
235
- this.log("dispose \u540E\u5FFD\u7565\u65B0\u4E8B\u4EF6:", name);
431
+ this.log("dispose \u540E\u5FFD\u7565\u65B0\u4E8B\u4EF6:", eventName);
236
432
  return "";
237
433
  }
238
- const enriched = this.opts.enrich?.() ?? {};
239
- const event = {
240
- id: generateEventId(),
241
- name,
242
- properties: {
243
- ...this.opts.baseProperties ?? {},
244
- ...this.opts.context?.() ?? {},
245
- ...properties ?? {}
246
- },
247
- timestamp: options?.timestamp ?? Date.now(),
248
- attempts: 0,
249
- sessionId: enriched.sessionId ?? this.sessionId,
250
- userId: enriched.userId ?? null,
251
- deviceId: enriched.deviceId ?? this.deviceId,
252
- category: options?.category ?? "custom",
253
- context: enriched.context ?? {}
254
- };
255
- if (typeof name !== "string" || name.length === 0) {
256
- this.opts.onDropped?.([event], "invalid");
434
+ if (typeof eventName !== "string" || eventName.length === 0) {
435
+ this.opts.onDropped?.([this.buildEvent("", properties)], "invalid");
257
436
  return "";
258
437
  }
438
+ this.touchSession();
439
+ const event = this.buildEvent(eventName, properties);
259
440
  if (options?.immediate) {
260
- this.fire(this.sendBatch([event]));
261
- return event.id;
441
+ this.fire(this.sendBatch([{ ...event, attempts: 0 }]));
442
+ return event.eventId;
262
443
  }
263
444
  this.enqueue(event);
264
445
  if (this.flushInterval <= 0) {
@@ -266,7 +447,7 @@ var Reporter = class {
266
447
  } else {
267
448
  this.scheduleFlush();
268
449
  }
269
- return event.id;
450
+ return event.eventId;
270
451
  }
271
452
  flush() {
272
453
  if (!this.flushPromise) {
@@ -283,6 +464,22 @@ var Reporter = class {
283
464
  get size() {
284
465
  return this.queue.length;
285
466
  }
467
+ /** 匿名 id(只读):首次生成后持久化不变;供外部转化跟踪等场景读取 */
468
+ get anonymousId() {
469
+ return this._anonymousId;
470
+ }
471
+ /** 设备 / 安装实例 id(只读):Web&PC 与 google client id 一致;供外部转化跟踪等场景读取 */
472
+ get clientId() {
473
+ return this._clientId;
474
+ }
475
+ /** 当前会话 id(只读):会话轮换后返回新值;供外部转化跟踪等场景读取 */
476
+ get visitId() {
477
+ return this.session.visitId;
478
+ }
479
+ /** 当前登录账号 id(只读):实时调用 userId provider,未提供恒为 null */
480
+ get userId() {
481
+ return this.opts.userId?.() ?? null;
482
+ }
286
483
  async dispose() {
287
484
  if (this.disposed) return;
288
485
  this.disposed = true;
@@ -300,7 +497,16 @@ var Reporter = class {
300
497
  }
301
498
  if (this.platform === "browser") {
302
499
  window.removeEventListener("pagehide", this.onPageHide);
500
+ window.removeEventListener("pageshow", this.onPageShow);
501
+ window.removeEventListener("storage", this.onStorage);
303
502
  document.removeEventListener("visibilitychange", this.onVisibilityChange);
503
+ this.restoreHistory();
504
+ if (this.pageTracker) {
505
+ this.endPageVisit(this.session.visitId, "unknown");
506
+ this.pageTracker.dispose();
507
+ this.pageTracker = null;
508
+ }
509
+ this.saveSession(true);
304
510
  } else {
305
511
  const exitProcess = this.getExitProcess();
306
512
  exitProcess.off("beforeExit", this.onExit);
@@ -316,17 +522,18 @@ var Reporter = class {
316
522
  }
317
523
  if (this.flushOnExit) {
318
524
  const pending = this.queue.splice(0);
319
- if (transport.sendSync?.(pending) ?? false) {
320
- this.opts.onFlushed?.(pending);
525
+ const wire = stripAttempts(pending);
526
+ if (transport.sendSync?.(wire) ?? false) {
527
+ this.opts.onFlushed?.(wire);
321
528
  await this.persistNow([]);
322
529
  return;
323
530
  }
324
531
  try {
325
- await transport.send(pending);
326
- this.opts.onFlushed?.(pending);
532
+ await transport.send(wire);
533
+ this.opts.onFlushed?.(wire);
327
534
  await this.persistNow([]);
328
535
  } catch (error) {
329
- this.opts.onFailed?.(pending, error);
536
+ this.opts.onFailed?.(wire, error);
330
537
  this.queue.push(...pending);
331
538
  await this.persistNow();
332
539
  }
@@ -336,9 +543,12 @@ var Reporter = class {
336
543
  await this.persistNow();
337
544
  }
338
545
  }
339
- /** 异步初始化:创建内置持久化、恢复上次会话队列、挂载退出兜底 */
546
+ /** 异步初始化:创建内置持久化、采集 Node 设备快照、恢复上次会话队列、挂载退出兜底 */
340
547
  async init() {
341
548
  this.storage = await this.storagePromise;
549
+ if (this.platform === "node") {
550
+ this.nodeDevice = await collectNodeDevice();
551
+ }
342
552
  if (this.disposed) return;
343
553
  if (this.storage) {
344
554
  try {
@@ -352,6 +562,7 @@ var Reporter = class {
352
562
  }
353
563
  if (this.disposed) return;
354
564
  if (this.platform === "browser") {
565
+ window.addEventListener("storage", this.onStorage);
355
566
  if (this.flushOnExit) {
356
567
  window.addEventListener("pagehide", this.onPageHide);
357
568
  }
@@ -359,7 +570,10 @@ var Reporter = class {
359
570
  document.addEventListener("visibilitychange", this.onVisibilityChange);
360
571
  }
361
572
  if (this.opts.autoPageView) {
362
- this.track("page_view");
573
+ this.pageTracker = createPageTracker(() => this.touchSession());
574
+ this.pageTracker.startVisit();
575
+ this.patchHistory();
576
+ window.addEventListener("pageshow", this.onPageShow);
363
577
  }
364
578
  } else if (this.flushOnExit) {
365
579
  const exitProcess = this.getExitProcess();
@@ -372,9 +586,118 @@ var Reporter = class {
372
586
  this.schedulePersist();
373
587
  }
374
588
  }
375
- /** 恢复队列入队:历史事件放队头保证先到先发,超限按溢出丢弃 */
589
+ /** 组装上报事件:身份字段由 SDK 填充,业务节点 = SDK 采集 + context 合并(接入方值优先) */
590
+ buildEvent(eventName, properties, overrides) {
591
+ const context = this.contextFn();
592
+ const device = {
593
+ ...this.nodeDevice,
594
+ ...collectBrowserDevice(),
595
+ ...context.device ?? {}
596
+ };
597
+ const page = {
598
+ ...collectPageSnapshot(),
599
+ ...this.pageSnapshot(),
600
+ ...context.page ?? {}
601
+ };
602
+ const mergedProperties = { ...context.properties ?? {}, ...properties ?? {} };
603
+ if (!context.app) {
604
+ this.log("context \u672A\u63D0\u4F9B app \u8282\u70B9,\u4EE5\u7A7A\u5BF9\u8C61\u4E0A\u62A5");
605
+ }
606
+ return {
607
+ eventId: generateEventId(),
608
+ eventName,
609
+ userId: this.opts.userId?.() ?? null,
610
+ anonymousId: this._anonymousId,
611
+ visitId: this.session.visitId,
612
+ clientId: this._clientId,
613
+ timestamp: Date.now(),
614
+ app: context.app ?? {},
615
+ ...Object.keys(device).length > 0 ? { device } : {},
616
+ ...Object.keys(page).length > 0 ? { page } : {},
617
+ ...context.user ? { user: context.user } : {},
618
+ ...Object.keys(mergedProperties).length > 0 ? { properties: mergedProperties } : {},
619
+ ...overrides
620
+ };
621
+ }
622
+ /** 进行中页面访问的 pageViewId(非访问期返回空) */
623
+ pageSnapshot() {
624
+ if (!this.pageTracker?.active) return {};
625
+ const pageViewId = this.pageTracker.pageViewId();
626
+ return pageViewId ? { pageViewId } : {};
627
+ }
628
+ /** 会话活跃:track 调用与页面交互均触发;超时轮换 visitId 并结束旧页面访问 */
629
+ touchSession() {
630
+ const now = Date.now();
631
+ if (now - this.sessionReadAt >= SESSION_SAVE_THROTTLE_MS) {
632
+ this.sessionReadAt = now;
633
+ this.refreshSessionFromShared();
634
+ }
635
+ if (now - this.session.lastActivityMs > VISIT_IDLE_TIMEOUT_MS) {
636
+ const oldVisitId = this.session.visitId;
637
+ this.endPageVisit(oldVisitId, "sessionTimeout");
638
+ this.session = { visitId: this.newId("visit"), lastActivityMs: now };
639
+ this.saveSession(true);
640
+ this.pageTracker?.startVisit();
641
+ } else {
642
+ this.session.lastActivityMs = now;
643
+ this.saveSession();
644
+ }
645
+ }
646
+ /** 结束当前页面访问并上报 pageView 汇总事件(复用进入页面时的 visitId) */
647
+ endPageVisit(visitId, reason) {
648
+ if (!this.pageTracker?.active) return;
649
+ const summary = this.pageTracker.endVisit(reason);
650
+ if (!summary) return;
651
+ const context = this.contextFn();
652
+ this.enqueue(
653
+ this.buildEvent("pageView", void 0, {
654
+ visitId,
655
+ page: { ...summary, ...context.page ?? {} }
656
+ })
657
+ );
658
+ this.scheduleFlush();
659
+ }
660
+ /** SPA 路由变化检测:pushState / replaceState 视为 routeChange,popstate 视为 back */
661
+ patchHistory() {
662
+ if (this.historyPatch) return;
663
+ const endVisit = (reason) => {
664
+ this.endPageVisit(this.session.visitId, reason);
665
+ this.pageTracker?.startVisit();
666
+ };
667
+ const pushState = history.pushState.bind(history);
668
+ const replaceState = history.replaceState.bind(history);
669
+ history.pushState = function(...args) {
670
+ const result = pushState(...args);
671
+ endVisit("routeChange");
672
+ return result;
673
+ };
674
+ history.replaceState = function(...args) {
675
+ const result = replaceState(...args);
676
+ endVisit("routeChange");
677
+ return result;
678
+ };
679
+ window.addEventListener("popstate", this.onPopState);
680
+ this.historyPatch = { pushState, replaceState };
681
+ }
682
+ restoreHistory() {
683
+ if (!this.historyPatch) return;
684
+ history.pushState = this.historyPatch.pushState;
685
+ history.replaceState = this.historyPatch.replaceState;
686
+ window.removeEventListener("popstate", this.onPopState);
687
+ this.historyPatch = null;
688
+ }
689
+ /** 恢复队列入队:历史事件放队头保证先到先发,超限按溢出丢弃;过滤旧格式(无 eventId)事件 */
376
690
  enqueueRestored(events) {
377
- let accepted = events;
691
+ let accepted = events.filter(
692
+ (event) => typeof event.eventId === "string" && typeof event.eventName === "string"
693
+ );
694
+ if (accepted.length < events.length) {
695
+ this.log(`\u8DF3\u8FC7 ${events.length - accepted.length} \u6761\u65E7\u683C\u5F0F\u6301\u4E45\u5316\u4E8B\u4EF6`);
696
+ }
697
+ accepted = accepted.map((event) => ({
698
+ ...event,
699
+ attempts: typeof event.attempts === "number" ? event.attempts : 0
700
+ }));
378
701
  if (accepted.length > this.maxQueueSize) {
379
702
  this.opts.onDropped?.(accepted.slice(this.maxQueueSize), "overflow");
380
703
  accepted = accepted.slice(0, this.maxQueueSize);
@@ -382,6 +705,7 @@ var Reporter = class {
382
705
  this.queue.unshift(...accepted);
383
706
  }
384
707
  enqueue(event) {
708
+ const queued = { ...event, attempts: 0 };
385
709
  if (this.queue.length >= this.maxQueueSize) {
386
710
  if (this.overflowPolicy === "drop-newest") {
387
711
  this.opts.onDropped?.([event], "overflow");
@@ -393,7 +717,7 @@ var Reporter = class {
393
717
  this.fire(this.flush());
394
718
  }
395
719
  }
396
- this.queue.push(event);
720
+ this.queue.push(queued);
397
721
  this.schedulePersist();
398
722
  }
399
723
  /** 攒批定时:延迟上报的实现,窗口内事件合并为一批 */
@@ -426,12 +750,13 @@ var Reporter = class {
426
750
  }
427
751
  async sendBatch(batch) {
428
752
  const transport = await this.transportPromise;
753
+ const wire = stripAttempts(batch);
429
754
  try {
430
- await transport.send(batch);
431
- this.opts.onFlushed?.(batch);
755
+ await transport.send(wire);
756
+ this.opts.onFlushed?.(wire);
432
757
  this.schedulePersist();
433
758
  } catch (error) {
434
- this.opts.onFailed?.(batch, error);
759
+ this.opts.onFailed?.(wire, error);
435
760
  this.log("send batch failed:", error);
436
761
  const updated = batch.map((event) => ({
437
762
  ...event,
@@ -485,6 +810,99 @@ var Reporter = class {
485
810
  this.log("persist queue failed:", error);
486
811
  }
487
812
  }
813
+ // ============================================================
814
+ // 身份与会话持久化(browser: localStorage;Node: 进程内)。
815
+ // 会话存 localStorage 而非 sessionStorage:同源多 tab 共享一个会话,
816
+ // "连续 30 分钟无活动"是用户级语义,不应按 tab 拆分;跨 tab 同步靠
817
+ // storage 事件(实时)+ 活动时重读(兜底)。
818
+ // ============================================================
819
+ /** 匿名 id:localStorage 持久化,首次匿名访问生成后保留;Node 无持久化介质,进程内生成 */
820
+ loadOrCreateAnonymousId() {
821
+ const stored = this.readPersistent(ANONYMOUS_ID_KEY);
822
+ if (stored) return stored;
823
+ const fresh = this.newId("anonymous");
824
+ this.writePersistent(ANONYMOUS_ID_KEY, fresh);
825
+ return fresh;
826
+ }
827
+ /** clientId:Web&PC 与 google client id(_ga cookie)一致;否则本地生成并持久化 */
828
+ loadOrCreateClientId() {
829
+ if (typeof document !== "undefined") {
830
+ const ga = document.cookie.match(/(?:^|;\s*)_ga=GA1\.\d\.([^;]+)/);
831
+ if (ga?.[1]) return ga[1];
832
+ const stored = this.readPersistent(CLIENT_ID_KEY);
833
+ if (stored) return stored;
834
+ }
835
+ const fresh = this.newId("client");
836
+ this.writePersistent(CLIENT_ID_KEY, fresh);
837
+ return fresh;
838
+ }
839
+ /** 会话恢复:localStorage(同源多 tab 共享)中 30 分钟窗口内的会话复用,否则新建 */
840
+ loadOrCreateSession() {
841
+ const now = Date.now();
842
+ try {
843
+ const text = this.readPersistent(SESSION_KEY);
844
+ if (text) {
845
+ const stored = JSON.parse(text);
846
+ if (stored.visitId && now - stored.lastActivityMs <= VISIT_IDLE_TIMEOUT_MS) {
847
+ return stored;
848
+ }
849
+ }
850
+ } catch {
851
+ }
852
+ const fresh = { visitId: this.newId("visit"), lastActivityMs: now };
853
+ this.session = fresh;
854
+ this.saveSession(true);
855
+ return fresh;
856
+ }
857
+ /** 会话落盘(localStorage):节流 10s,避免滚动等高频活动频繁写;force 用于轮换 / 退出兜底 */
858
+ saveSession(force = false) {
859
+ const now = Date.now();
860
+ if (!force && this.sessionSaveAt > 0 && now - this.sessionSaveAt < SESSION_SAVE_THROTTLE_MS) {
861
+ return;
862
+ }
863
+ this.sessionSaveAt = now;
864
+ this.writePersistent(SESSION_KEY, JSON.stringify(this.session));
865
+ }
866
+ /** 采纳共享会话:visitId 变化视为其他 tab 轮换了会话,结束本 tab 旧页面访问并开启新访问 */
867
+ adoptSharedSession(stored) {
868
+ if (!stored.visitId || stored.visitId === this.session.visitId) {
869
+ if (stored.visitId) this.session = stored;
870
+ return;
871
+ }
872
+ const oldVisitId = this.session.visitId;
873
+ this.endPageVisit(oldVisitId, "sessionTimeout");
874
+ this.pageTracker?.startVisit();
875
+ this.session = stored;
876
+ }
877
+ /** 活动时重读共享会话(兜底 storage 事件丢失):storage 事件只在其他 tab 触发 */
878
+ refreshSessionFromShared() {
879
+ try {
880
+ const text = this.readPersistent(SESSION_KEY);
881
+ if (text) {
882
+ this.adoptSharedSession(JSON.parse(text));
883
+ }
884
+ } catch {
885
+ }
886
+ }
887
+ readPersistent(key) {
888
+ if (this.platform !== "browser") return null;
889
+ try {
890
+ return localStorage.getItem(key);
891
+ } catch {
892
+ return null;
893
+ }
894
+ }
895
+ writePersistent(key, value) {
896
+ if (this.platform !== "browser") return;
897
+ try {
898
+ localStorage.setItem(key, value);
899
+ } catch {
900
+ }
901
+ }
902
+ /** 生成带前缀的实例 id(格式对齐旧 SDK session_ / device_) */
903
+ newId(prefix) {
904
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
905
+ }
488
906
  log(...args) {
489
907
  if (this.opts.debug) {
490
908
  console.log("[reporter]", ...args);