@djangocfg/analytics 2.1.665 → 2.1.667

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/analytics",
3
- "version": "2.1.665",
3
+ "version": "2.1.667",
4
4
  "description": "First-party analytics for django-cfg apps: one route listener, N transports (self-hosted + GA4). Pageviews, sessions, and authenticated-user attribution.",
5
5
  "keywords": [
6
6
  "django",
@@ -63,7 +63,7 @@
63
63
  }
64
64
  },
65
65
  "devDependencies": {
66
- "@djangocfg/typescript-config": "^2.1.665",
66
+ "@djangocfg/typescript-config": "^2.1.667",
67
67
  "@types/node": "^25.9.5",
68
68
  "@types/react": "19.3.0",
69
69
  "next": "^16.4.5",
@@ -36,6 +36,18 @@ export class AnalyticsClient {
36
36
  private flushHandler?: () => void
37
37
  private pagehideHandler?: () => void
38
38
 
39
+ // Engagement: did a person act, and for how long was the page visible and in use.
40
+ // A crawler that executes JavaScript still sends pageviews but never fires one of
41
+ // these input events, which is what separates it from a reader on the server.
42
+ private interacted = false
43
+ private interactionReported = false
44
+ private activeMs = 0
45
+ private lastTick = 0
46
+ private lastInteractionAt = 0
47
+ private reportedSec = 0
48
+ private tickTimer?: number
49
+ private engagementHandlers: Array<[EventTarget, string, EventListener, AddEventListenerOptions]> = []
50
+
39
51
  constructor(options: AnalyticsOptions) {
40
52
  this.transports = options.transports ?? []
41
53
  this.debug = options.debug ?? true
@@ -55,6 +67,7 @@ export class AnalyticsClient {
55
67
  }
56
68
 
57
69
  this.registerFlushListeners()
70
+ this.registerEngagementListeners()
58
71
  }
59
72
 
60
73
  /**
@@ -101,6 +114,11 @@ export class AnalyticsClient {
101
114
  }
102
115
 
103
116
  destroy(): void {
117
+ for (const [target, type, handler, opts] of this.engagementHandlers) {
118
+ target.removeEventListener(type, handler, opts)
119
+ }
120
+ this.engagementHandlers = []
121
+ if (this.tickTimer !== undefined) window.clearInterval(this.tickTimer)
104
122
  if (this.flushHandler) {
105
123
  document.removeEventListener('visibilitychange', this.flushHandler)
106
124
  }
@@ -119,14 +137,102 @@ export class AnalyticsClient {
119
137
  // iOS Safari may never fire it at all — so a beforeunload-only flush loses
120
138
  // every mobile Safari session.
121
139
  this.flushHandler = () => {
122
- if (document.visibilityState === 'hidden') this.flush(true)
140
+ if (document.visibilityState === 'hidden') {
141
+ this.reportEngagement()
142
+ this.flush(true)
143
+ }
144
+ }
145
+ this.pagehideHandler = () => {
146
+ this.reportEngagement()
147
+ this.flush(true)
123
148
  }
124
- this.pagehideHandler = () => this.flush(true)
125
149
 
126
150
  document.addEventListener('visibilitychange', this.flushHandler)
127
151
  window.addEventListener('pagehide', this.pagehideHandler)
128
152
  }
129
153
 
154
+ /**
155
+ * Listen for input, once per document, passively. Time counts only while the tab
156
+ * is visible and the visitor acted in the last 30 s, so a forgotten background
157
+ * tab does not read as a ten-minute visit.
158
+ */
159
+ private registerEngagementListeners(): void {
160
+ const IDLE_MS = 30_000
161
+ const add = (target: EventTarget, type: string, handler: EventListener) => {
162
+ const opts: AddEventListenerOptions = { passive: true, capture: true }
163
+ target.addEventListener(type, handler, opts)
164
+ this.engagementHandlers.push([target, type, handler, opts])
165
+ }
166
+
167
+ const tick = () => {
168
+ const now = Date.now()
169
+ if (this.lastTick && document.visibilityState === 'visible' && now - this.lastInteractionAt < IDLE_MS) {
170
+ this.activeMs += Math.min(now - this.lastTick, 5_000)
171
+ }
172
+ this.lastTick = now
173
+ }
174
+
175
+ const onInput = () => {
176
+ tick()
177
+ this.lastInteractionAt = Date.now()
178
+ this.interacted = true
179
+ if (!this.interactionReported) {
180
+ // Report the first action at once, so a visit that is never closed cleanly
181
+ // (a phone locked mid-read) is still known to be a person.
182
+ this.interactionReported = true
183
+ this.sendEngagement(0)
184
+ }
185
+ }
186
+ for (const type of ['pointerdown', 'pointermove', 'keydown', 'scroll', 'touchstart', 'wheel']) {
187
+ add(window, type, onInput)
188
+ }
189
+ add(document, 'click', (e) => this.trackOutbound(e as MouseEvent))
190
+
191
+ this.tickTimer = window.setInterval(tick, 2_000)
192
+ this.lastTick = Date.now()
193
+ }
194
+
195
+ /** Send the seconds accumulated since the last report. No-op when nothing new. */
196
+ private reportEngagement(): void {
197
+ if (!this.interacted) return
198
+ const total = Math.round(this.activeMs / 1000)
199
+ const delta = total - this.reportedSec
200
+ if (delta <= 0) return
201
+ this.reportedSec = total
202
+ this.sendEngagement(delta)
203
+ }
204
+
205
+ private sendEngagement(seconds: number): void {
206
+ this.firstParty((t) =>
207
+ t.event({
208
+ event_name: 'engagement',
209
+ pathname: window.location.pathname,
210
+ props: { interacted: this.interacted, seconds },
211
+ }),
212
+ )
213
+ }
214
+
215
+ /** A click on a link that leaves the site: the "went to the source listing" signal. */
216
+ private trackOutbound(e: MouseEvent): void {
217
+ const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null
218
+ if (!a || !a.host || a.host === window.location.host) return
219
+ if (a.protocol !== 'http:' && a.protocol !== 'https:') return
220
+ this.firstParty((t) =>
221
+ t.event({
222
+ event_name: 'outbound_click',
223
+ pathname: window.location.pathname,
224
+ props: { host: a.host },
225
+ }),
226
+ )
227
+ }
228
+
229
+ /** Engagement is first-party telemetry; GA4 has its own, so it is not forwarded there. */
230
+ private firstParty(fn: (t: AnalyticsTransport) => void): void {
231
+ this.fanOut((t) => {
232
+ if (t.name === 'djangocfg') fn(t)
233
+ })
234
+ }
235
+
130
236
  private fanOut(fn: (t: AnalyticsTransport) => void): void {
131
237
  for (const t of this.transports) {
132
238
  try {
@@ -25,6 +25,15 @@ export interface DjangoCfgTransportOptions {
25
25
  /** Which registered AnalyticsSite these events belong to. */
26
26
  site?: string
27
27
 
28
+ /**
29
+ * The signed-in user's access token, read at send time.
30
+ *
31
+ * The beacon cannot set an Authorization header, so the token travels in the body.
32
+ * The server verifies it like a Bearer token, keeps only the user id, and treats a
33
+ * bad or expired one as an anonymous hit. Return null when signed out.
34
+ */
35
+ getAuthToken?: () => string | null | undefined
36
+
28
37
  /** Max events per request. The server caps at 25. */
29
38
  batchSize?: number
30
39
  }
@@ -42,7 +51,15 @@ export function djangocfg(options: DjangoCfgTransportOptions = {}): AnalyticsTra
42
51
  // credentials:'include' is what lets the server resolve request.user and
43
52
  // attribute the event to a signed-in account — the differentiator.
44
53
  credentials: 'include',
45
- serialize: (events) => JSON.stringify({ site, events }),
54
+ serialize: (events) => {
55
+ let auth = ''
56
+ try {
57
+ auth = options.getAuthToken?.() || ''
58
+ } catch {
59
+ // Telemetry must never throw into the page.
60
+ }
61
+ return JSON.stringify(auth ? { site, events, auth } : { site, events })
62
+ },
46
63
  })
47
64
 
48
65
  const enqueue = (event: AnalyticsEventPayload) => {