@sixb/client 0.1.20 → 0.1.21
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/activity-attribution.d.ts +29 -0
- package/dist/activity-attribution.d.ts.map +1 -0
- package/dist/activity-tracker.d.ts +105 -0
- package/dist/activity-tracker.d.ts.map +1 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +513 -11
- package/dist/browser.js.map +6 -4
- package/dist/{chunk-g05ar78c.js → chunk-3b154p8n.js} +3 -3
- package/dist/{chunk-tkjkrcdt.js → chunk-3f2pjdzk.js} +155 -2
- package/dist/chunk-3f2pjdzk.js.map +19 -0
- package/dist/{chunk-awbb496e.js → chunk-9wd8x2em.js} +1 -1
- package/dist/{chunk-3aa3m9z6.js → chunk-ana8rtgb.js} +2 -2
- package/dist/{chunk-95bnb04n.js → chunk-qdq5gfqx.js} +1 -1
- package/dist/{chunk-12s8gbwj.js → chunk-s5zamywm.js} +2 -2
- package/dist/generated/@tanstack/react-query.gen.d.ts +2281 -591
- package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
- package/dist/generated/index.d.ts +2 -2
- package/dist/generated/index.d.ts.map +1 -1
- package/dist/generated/sdk.gen.d.ts +89 -1
- package/dist/generated/sdk.gen.d.ts.map +1 -1
- package/dist/generated/types.gen.d.ts +1669 -448
- package/dist/generated/types.gen.d.ts.map +1 -1
- package/dist/hooks.js +299 -6
- package/dist/hooks.js.map +3 -3
- package/dist/index.js +40 -6
- package/dist/index.js.map +1 -1
- package/dist/logs.js +3 -3
- package/dist/models.js +36 -2
- package/dist/models.js.map +1 -1
- package/dist/query.js +3 -3
- package/package.json +2 -2
- package/src/activity-attribution.ts +211 -0
- package/src/activity-tracker.ts +527 -0
- package/src/browser.ts +14 -1
- package/src/generated/@tanstack/react-query.gen.ts +580 -0
- package/src/generated/index.ts +101 -0
- package/src/generated/sdk.gen.ts +389 -0
- package/src/generated/types.gen.ts +2405 -1090
- package/dist/chunk-tkjkrcdt.js.map +0 -19
- /package/dist/{chunk-g05ar78c.js.map → chunk-3b154p8n.js.map} +0 -0
- /package/dist/{chunk-awbb496e.js.map → chunk-9wd8x2em.js.map} +0 -0
- /package/dist/{chunk-3aa3m9z6.js.map → chunk-ana8rtgb.js.map} +0 -0
- /package/dist/{chunk-95bnb04n.js.map → chunk-qdq5gfqx.js.map} +0 -0
- /package/dist/{chunk-12s8gbwj.js.map → chunk-s5zamywm.js.map} +0 -0
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { clearActivityArrival, takeActivityArrival } from "./activity-attribution"
|
|
2
|
+
import { captureActivity, getActivityCaptureConfig } from "./generated/sdk.gen"
|
|
3
|
+
import type { CaptureActivityData, GetActivityCaptureConfigResponse } from "./generated/types.gen"
|
|
4
|
+
|
|
5
|
+
type EventInput = CaptureActivityData["body"]["events"][number]
|
|
6
|
+
type VisitEventInput = Exclude<EventInput, { readonly type: "ui.interaction" }>
|
|
7
|
+
export type ActivityAttribution = NonNullable<VisitEventInput["attribution"]>
|
|
8
|
+
|
|
9
|
+
interface QueuedEvent {
|
|
10
|
+
readonly event: EventInput
|
|
11
|
+
readonly queuedAt: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A response that refused a batch: its status, and the wait a 429 asked for. */
|
|
15
|
+
export class ActivityDeliveryError extends Error {
|
|
16
|
+
readonly name = "ActivityDeliveryError"
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
readonly status: number,
|
|
20
|
+
readonly retryAfterMs?: number
|
|
21
|
+
) {
|
|
22
|
+
super(`[SixbClient] Activity delivery was refused with status ${status}.`)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ActivityTrackerOptions {
|
|
27
|
+
readonly document: Pick<
|
|
28
|
+
Document,
|
|
29
|
+
"visibilityState" | "addEventListener" | "removeEventListener"
|
|
30
|
+
> | null
|
|
31
|
+
readonly load: (signal: AbortSignal) => Promise<GetActivityCaptureConfigResponse>
|
|
32
|
+
/** Rejects with an `ActivityDeliveryError` when the API answers, with anything else when not. */
|
|
33
|
+
readonly send: (events: EventInput[], signal: AbortSignal) => Promise<void>
|
|
34
|
+
/** How this document was reached; sent once, with its first event. */
|
|
35
|
+
readonly attribution?: ActivityAttribution
|
|
36
|
+
readonly now?: () => number
|
|
37
|
+
readonly warn?: (message: string) => void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const MAX_QUEUE = 100
|
|
41
|
+
const MAX_BATCH = 20
|
|
42
|
+
const MAX_AGE_MS = 60_000
|
|
43
|
+
const MAX_ATTEMPTS = 3
|
|
44
|
+
const REQUEST_TIMEOUT_MS = 10_000
|
|
45
|
+
const FLUSH_DELAY_MS = 500
|
|
46
|
+
const PULSE_INTERVAL_MS = 30_000
|
|
47
|
+
const INPUT_EVENTS = ["pointerdown", "keydown", "touchstart", "scroll"] as const
|
|
48
|
+
const TRACK_ATTRIBUTE = "data-sixb-track"
|
|
49
|
+
/** The same name again within this long is the same interaction: a double click, a burst. */
|
|
50
|
+
const COALESCE_MS = 1_000
|
|
51
|
+
const MAX_REPORTED_NAMES = 20
|
|
52
|
+
const REPORTED_NAME_LENGTH = 40
|
|
53
|
+
|
|
54
|
+
// The server's rule, from the activity policy: lowercase dotted segments, each starting with a
|
|
55
|
+
// letter, at most 40 characters and without a run of four digits, 100 in all.
|
|
56
|
+
export const INTERACTION_NAME_PATTERN =
|
|
57
|
+
/^(?!.*\d{4})[a-z][a-z0-9_-]{0,39}(?:\.[a-z][a-z0-9_-]{0,39})*$/
|
|
58
|
+
export const INTERACTION_NAME_MAX_LENGTH = 100
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Sends page views, foreground activity and marked interactions for one authority. Events live in
|
|
62
|
+
* memory only: they are never persisted, and never carried across a sign-in or another shared link.
|
|
63
|
+
*/
|
|
64
|
+
export class ActivityTracker {
|
|
65
|
+
private readonly abort = new AbortController()
|
|
66
|
+
private readonly now: () => number
|
|
67
|
+
private readonly warn: (message: string) => void
|
|
68
|
+
private enabled = false
|
|
69
|
+
private idleTimeoutMs = 30 * 60_000
|
|
70
|
+
private route: string | null = null
|
|
71
|
+
private queue: QueuedEvent[] = []
|
|
72
|
+
private flushTimer: ReturnType<typeof setTimeout> | undefined
|
|
73
|
+
private pulseTimer: ReturnType<typeof setInterval> | undefined
|
|
74
|
+
private pending: Promise<void> | undefined
|
|
75
|
+
private failedAttempts = 0
|
|
76
|
+
/** Epoch milliseconds before which a 429 asked not to send again. */
|
|
77
|
+
private throttledUntil = 0
|
|
78
|
+
/** Input since the last event: the next pulse reports it. */
|
|
79
|
+
private active = false
|
|
80
|
+
/** A navigation happened while hidden; it counts once the tab is visible. */
|
|
81
|
+
private hiddenNavigation = false
|
|
82
|
+
private lastInputAt = 0
|
|
83
|
+
private arrivalSent = false
|
|
84
|
+
/** Invalid names already reported, so a misnamed button warns once; at most twenty. */
|
|
85
|
+
private readonly invalidNames = new Set<string>()
|
|
86
|
+
private moreInvalidNames = false
|
|
87
|
+
private lastInteraction: { readonly name: string; readonly at: number } | undefined
|
|
88
|
+
|
|
89
|
+
constructor(private readonly options: ActivityTrackerOptions) {
|
|
90
|
+
this.now = options.now ?? Date.now
|
|
91
|
+
this.warn = options.warn ?? ((message) => console.warn(message))
|
|
92
|
+
void this.start()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The route pattern now shown, or `null` on a page that is not recorded. */
|
|
96
|
+
page(route: string | null): void {
|
|
97
|
+
this.route = route
|
|
98
|
+
this.hiddenNavigation = route !== null
|
|
99
|
+
if (!this.enabled || !this.visible() || route === null) {
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
this.hiddenNavigation = false
|
|
104
|
+
this.active = false
|
|
105
|
+
this.lastInputAt = this.now()
|
|
106
|
+
this.enqueue("page.view")
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* An interaction code reports, on the page now shown. A call is not the person's input: once
|
|
111
|
+
* they have been idle for the idle timeout it is dropped, so background code cannot keep their
|
|
112
|
+
* visit going.
|
|
113
|
+
*/
|
|
114
|
+
interaction(name: string): void {
|
|
115
|
+
if (this.now() - this.lastInputAt >= this.idleTimeoutMs) {
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
this.record(name)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
dispose(): void {
|
|
123
|
+
this.enabled = false
|
|
124
|
+
this.abort.abort()
|
|
125
|
+
clearTimeout(this.flushTimer)
|
|
126
|
+
clearInterval(this.pulseTimer)
|
|
127
|
+
|
|
128
|
+
for (const type of INPUT_EVENTS) {
|
|
129
|
+
this.options.document?.removeEventListener(type, this.onInput, { capture: true })
|
|
130
|
+
}
|
|
131
|
+
this.options.document?.removeEventListener("click", this.onClick, { capture: true })
|
|
132
|
+
this.options.document?.removeEventListener("visibilitychange", this.onVisibility)
|
|
133
|
+
|
|
134
|
+
this.queue = []
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Sends the next batch. Concurrent calls share one request; tests call it directly. */
|
|
138
|
+
flush(): Promise<void> {
|
|
139
|
+
clearTimeout(this.flushTimer)
|
|
140
|
+
this.flushTimer = undefined
|
|
141
|
+
|
|
142
|
+
if (this.pending) {
|
|
143
|
+
return this.pending
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
this.pending = this.sendBatch().finally(() => {
|
|
147
|
+
this.pending = undefined
|
|
148
|
+
if (this.queue.length > 0 && !this.abort.signal.aborted) {
|
|
149
|
+
this.schedule(this.nextDelay())
|
|
150
|
+
}
|
|
151
|
+
})
|
|
152
|
+
return this.pending
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private nextDelay(): number {
|
|
156
|
+
const throttled = this.throttledUntil - this.now()
|
|
157
|
+
if (throttled > 0) {
|
|
158
|
+
return throttled
|
|
159
|
+
}
|
|
160
|
+
return this.failedAttempts > 0 ? retryDelay(this.failedAttempts) : FLUSH_DELAY_MS
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private async start(): Promise<void> {
|
|
164
|
+
let config: GetActivityCaptureConfigResponse
|
|
165
|
+
try {
|
|
166
|
+
config = await this.request((signal) => this.options.load(signal))
|
|
167
|
+
} catch {
|
|
168
|
+
if (!this.abort.signal.aborted) {
|
|
169
|
+
this.warn(
|
|
170
|
+
"[SixbClient] Activity capture settings are unavailable; this visit is not recorded."
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (this.abort.signal.aborted || !config.enabled) {
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
this.enabled = true
|
|
181
|
+
this.idleTimeoutMs = config.idleTimeoutMs
|
|
182
|
+
|
|
183
|
+
for (const type of INPUT_EVENTS) {
|
|
184
|
+
this.options.document?.addEventListener(type, this.onInput, { capture: true, passive: true })
|
|
185
|
+
}
|
|
186
|
+
// One listener for every marked element, present or rendered later.
|
|
187
|
+
this.options.document?.addEventListener("click", this.onClick, { capture: true, passive: true })
|
|
188
|
+
this.options.document?.addEventListener("visibilitychange", this.onVisibility)
|
|
189
|
+
this.pulseTimer = setInterval(this.onPulse, PULSE_INTERVAL_MS)
|
|
190
|
+
|
|
191
|
+
if (this.route !== null) {
|
|
192
|
+
this.page(this.route)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private onPulse = (): void => {
|
|
197
|
+
if (this.active && this.visible()) {
|
|
198
|
+
this.active = false
|
|
199
|
+
this.enqueue("visit.activity")
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private onInput = (event: Event): void => {
|
|
204
|
+
// Synthetic events are scripts, not someone using the page.
|
|
205
|
+
if (!event.isTrusted || !this.visible()) {
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const resumed = this.now() - this.lastInputAt >= this.idleTimeoutMs
|
|
210
|
+
this.lastInputAt = this.now()
|
|
211
|
+
|
|
212
|
+
if (resumed) {
|
|
213
|
+
this.active = false
|
|
214
|
+
this.enqueue("visit.activity")
|
|
215
|
+
} else {
|
|
216
|
+
this.active = true
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private onClick = (event: Event): void => {
|
|
221
|
+
// A script's click is not someone using the page.
|
|
222
|
+
if (!event.isTrusted) {
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// The composed path reaches a marked element across shadow roots, as `closest` cannot.
|
|
227
|
+
const path = event.composedPath()
|
|
228
|
+
const markedAt = path.findIndex(
|
|
229
|
+
(target) => isElement(target) && target.hasAttribute(TRACK_ATTRIBUTE)
|
|
230
|
+
)
|
|
231
|
+
const marked = path[markedAt]
|
|
232
|
+
if (!isElement(marked)) {
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const within = path.slice(0, markedAt + 1).filter(isElement)
|
|
237
|
+
if (within.some((element) => isDisabled(element) || forwardsClick(element, marked, path))) {
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// A marked click is the person's input, and the interaction reports it.
|
|
242
|
+
this.lastInputAt = this.now()
|
|
243
|
+
this.active = false
|
|
244
|
+
this.record(marked.getAttribute(TRACK_ATTRIBUTE) ?? "")
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Queues an interaction. Before the settings load, on a page that is not recorded or in a
|
|
249
|
+
* hidden tab, it is dropped: someone acts on a page they see.
|
|
250
|
+
*/
|
|
251
|
+
private record(name: string): void {
|
|
252
|
+
if (!this.enabled || !this.visible() || this.route === null) {
|
|
253
|
+
return
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (!isInteractionName(name)) {
|
|
257
|
+
this.invalidName(name)
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const now = this.now()
|
|
262
|
+
if (this.lastInteraction?.name === name && now - this.lastInteraction.at < COALESCE_MS) {
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
this.lastInteraction = { name, at: now }
|
|
266
|
+
|
|
267
|
+
this.push((route) => ({ id: crypto.randomUUID(), type: "ui.interaction", name, route }))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private onVisibility = (): void => {
|
|
271
|
+
if (this.visible()) {
|
|
272
|
+
this.lastInputAt = this.now()
|
|
273
|
+
this.active = false
|
|
274
|
+
// A navigation made while hidden is a page view; returning to the same page is activity.
|
|
275
|
+
this.enqueue(this.hiddenNavigation ? "page.view" : "visit.activity")
|
|
276
|
+
this.hiddenNavigation = false
|
|
277
|
+
return
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (this.active) {
|
|
281
|
+
this.active = false
|
|
282
|
+
this.enqueue("visit.activity")
|
|
283
|
+
}
|
|
284
|
+
void this.flush()
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private visible(): boolean {
|
|
288
|
+
return this.options.document?.visibilityState === "visible"
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private enqueue(type: VisitEventInput["type"]): void {
|
|
292
|
+
this.push((route) => ({ id: crypto.randomUUID(), type, route, ...this.nextAttribution() }))
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Queues the event `build` makes for the route shown, unless it would not be recorded. */
|
|
296
|
+
private push(build: (route: string) => EventInput): void {
|
|
297
|
+
if (!this.enabled || this.route === null || this.abort.signal.aborted) {
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (this.queue.length >= MAX_QUEUE) {
|
|
302
|
+
this.dropped(1)
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
this.queue.push({ event: build(this.route), queuedAt: this.now() })
|
|
307
|
+
this.schedule(FLUSH_DELAY_MS)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* The arrival travels with the first event only; later events say `{}`, so a visit started by
|
|
312
|
+
* inactivity reads as direct rather than inheriting an old campaign.
|
|
313
|
+
*/
|
|
314
|
+
private nextAttribution(): { attribution?: ActivityAttribution } {
|
|
315
|
+
const first = !this.arrivalSent
|
|
316
|
+
this.arrivalSent = true
|
|
317
|
+
|
|
318
|
+
if (!first) {
|
|
319
|
+
return { attribution: {} }
|
|
320
|
+
}
|
|
321
|
+
return this.options.attribution === undefined ? {} : { attribution: this.options.attribution }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private schedule(delay: number): void {
|
|
325
|
+
if (this.flushTimer !== undefined) {
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
this.flushTimer = setTimeout(() => {
|
|
330
|
+
this.flushTimer = undefined
|
|
331
|
+
void this.flush()
|
|
332
|
+
}, delay)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private async sendBatch(): Promise<void> {
|
|
336
|
+
if (!this.enabled || this.abort.signal.aborted) {
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const fresh = this.queue.filter((item) => this.now() - item.queuedAt <= MAX_AGE_MS)
|
|
341
|
+
if (fresh.length < this.queue.length) {
|
|
342
|
+
this.dropped(this.queue.length - fresh.length)
|
|
343
|
+
this.queue = fresh
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const batch = this.queue.slice(0, MAX_BATCH)
|
|
347
|
+
if (batch.length === 0 || this.now() < this.throttledUntil) {
|
|
348
|
+
return
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
await this.request((signal) =>
|
|
353
|
+
this.options.send(
|
|
354
|
+
batch.map((item) => item.event),
|
|
355
|
+
signal
|
|
356
|
+
)
|
|
357
|
+
)
|
|
358
|
+
if (this.abort.signal.aborted) {
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
this.queue.splice(0, batch.length)
|
|
363
|
+
this.failedAttempts = 0
|
|
364
|
+
} catch (error) {
|
|
365
|
+
if (this.abort.signal.aborted) {
|
|
366
|
+
return
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (error instanceof ActivityDeliveryError && error.status === 429) {
|
|
370
|
+
// Wait as asked, at most as long as the events are kept.
|
|
371
|
+
this.throttledUntil = this.now() + Math.min(error.retryAfterMs ?? MAX_AGE_MS, MAX_AGE_MS)
|
|
372
|
+
return
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Another refusal would answer the same again: the batch is dropped, not retried.
|
|
376
|
+
if (error instanceof ActivityDeliveryError && error.status >= 400 && error.status < 500) {
|
|
377
|
+
this.queue.splice(0, batch.length)
|
|
378
|
+
this.dropped(batch.length)
|
|
379
|
+
this.failedAttempts = 0
|
|
380
|
+
return
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// A retry resends the same ids, so the server recognizes page views it already has.
|
|
384
|
+
this.failedAttempts++
|
|
385
|
+
if (this.failedAttempts >= MAX_ATTEMPTS) {
|
|
386
|
+
this.queue.splice(0, batch.length)
|
|
387
|
+
this.dropped(batch.length)
|
|
388
|
+
this.failedAttempts = 0
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async request<T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
|
394
|
+
const controller = new AbortController()
|
|
395
|
+
const abort = () => controller.abort()
|
|
396
|
+
this.abort.signal.addEventListener("abort", abort, { once: true })
|
|
397
|
+
const timeout = setTimeout(abort, REQUEST_TIMEOUT_MS)
|
|
398
|
+
|
|
399
|
+
try {
|
|
400
|
+
return await run(controller.signal)
|
|
401
|
+
} finally {
|
|
402
|
+
clearTimeout(timeout)
|
|
403
|
+
this.abort.signal.removeEventListener("abort", abort)
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private invalidName(name: string): void {
|
|
408
|
+
if (this.invalidNames.has(name)) {
|
|
409
|
+
return
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (this.invalidNames.size >= MAX_REPORTED_NAMES) {
|
|
413
|
+
if (!this.moreInvalidNames) {
|
|
414
|
+
this.moreInvalidNames = true
|
|
415
|
+
this.warn("[SixbClient] More interaction names are invalid; they are not reported.")
|
|
416
|
+
}
|
|
417
|
+
return
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// A prefix only: a misused name may hold a value.
|
|
421
|
+
const text = String(name)
|
|
422
|
+
const shown =
|
|
423
|
+
text.length > REPORTED_NAME_LENGTH ? `${text.slice(0, REPORTED_NAME_LENGTH)}…` : text
|
|
424
|
+
|
|
425
|
+
this.invalidNames.add(name)
|
|
426
|
+
this.warn(
|
|
427
|
+
`[SixbClient] ${JSON.stringify(shown)} is not an interaction name, so it is not recorded. Use lowercase dotted identifiers such as "invoices.export".`
|
|
428
|
+
)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private dropped(count: number): void {
|
|
432
|
+
// Never the route or ids: the warning is for the console, not a record of the visit.
|
|
433
|
+
this.warn(
|
|
434
|
+
`[SixbClient] Activity capture dropped ${count} event(s); visit history may be incomplete.`
|
|
435
|
+
)
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function isInteractionName(value: unknown): value is string {
|
|
440
|
+
return (
|
|
441
|
+
typeof value === "string" &&
|
|
442
|
+
value.length <= INTERACTION_NAME_MAX_LENGTH &&
|
|
443
|
+
INTERACTION_NAME_PATTERN.test(value)
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function isElement(value: unknown): value is Element {
|
|
448
|
+
return (
|
|
449
|
+
typeof value === "object" &&
|
|
450
|
+
value !== null &&
|
|
451
|
+
typeof Reflect.get(value, "hasAttribute") === "function"
|
|
452
|
+
)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function isDisabled(element: Element): boolean {
|
|
456
|
+
return element.getAttribute("aria-disabled") === "true" || element.matches(":disabled")
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* A click on a label whose control is inside the same marked element, but not on the control:
|
|
461
|
+
* the browser forwards it to the control, and that click records the interaction.
|
|
462
|
+
*/
|
|
463
|
+
function forwardsClick(element: Element, marked: Element, path: readonly EventTarget[]): boolean {
|
|
464
|
+
const control: unknown = Reflect.get(element, "control")
|
|
465
|
+
return (
|
|
466
|
+
element.tagName === "LABEL" &&
|
|
467
|
+
isElement(control) &&
|
|
468
|
+
marked.contains(control) &&
|
|
469
|
+
!path.includes(control)
|
|
470
|
+
)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function retryDelay(failedAttempts: number): number {
|
|
474
|
+
return Math.min(10_000, 1_000 * 2 ** failedAttempts)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Reads a `Retry-After` in seconds; a date or anything else leaves the default wait. */
|
|
478
|
+
function retryAfterMs(value: string | null): number | undefined {
|
|
479
|
+
const seconds = value === null ? Number.NaN : Number(value)
|
|
480
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1_000 : undefined
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
let active: ActivityTracker | undefined
|
|
484
|
+
// The page shown, kept across a start so the order of start and first render does not matter.
|
|
485
|
+
let shownRoute: string | null = null
|
|
486
|
+
|
|
487
|
+
/** Starts recording for the authority the bootstrap just established. */
|
|
488
|
+
export function startSixbActivityCapture(): void {
|
|
489
|
+
const attribution = takeActivityArrival()
|
|
490
|
+
active?.dispose()
|
|
491
|
+
active = new ActivityTracker({
|
|
492
|
+
attribution,
|
|
493
|
+
document: typeof document === "undefined" ? null : document,
|
|
494
|
+
load: async (signal) => (await getActivityCaptureConfig({ signal, throwOnError: true })).data,
|
|
495
|
+
send: async (events, signal) => {
|
|
496
|
+
const { response } = await captureActivity({ body: { events }, signal, keepalive: true })
|
|
497
|
+
if (!response.ok) {
|
|
498
|
+
throw new ActivityDeliveryError(
|
|
499
|
+
response.status,
|
|
500
|
+
retryAfterMs(response.headers.get("retry-after"))
|
|
501
|
+
)
|
|
502
|
+
}
|
|
503
|
+
},
|
|
504
|
+
})
|
|
505
|
+
active.page(shownRoute)
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Reports the route pattern now shown, or `null` on a page that is not recorded. */
|
|
509
|
+
export function recordSixbPageView(route: string | null): void {
|
|
510
|
+
shownRoute = route
|
|
511
|
+
active?.page(route)
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Records an interaction that is not a click, such as `invoices.filter.applied`, on the page now
|
|
516
|
+
* shown. Names are lowercase dotted identifiers and never carry a value. Does nothing while
|
|
517
|
+
* activity is off, on a page that is not recorded, or before its settings load.
|
|
518
|
+
*/
|
|
519
|
+
export function trackSixbEvent(name: string): void {
|
|
520
|
+
active?.interaction(name)
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export function stopSixbActivityCapture(): void {
|
|
524
|
+
clearActivityArrival()
|
|
525
|
+
active?.dispose()
|
|
526
|
+
active = undefined
|
|
527
|
+
}
|
package/src/browser.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { prepareActivityArrival, preserveSixbActivityArrival } from "./activity-attribution"
|
|
2
|
+
import { stopSixbActivityCapture } from "./activity-tracker"
|
|
1
3
|
import {
|
|
2
4
|
configureSixbClient as configureGeneratedSixbClient,
|
|
3
5
|
normalizeSixbApiBaseUrl,
|
|
@@ -10,6 +12,8 @@ import {
|
|
|
10
12
|
} from "./client-authority"
|
|
11
13
|
import { client } from "./generated/client.gen"
|
|
12
14
|
|
|
15
|
+
export { preserveSixbActivityArrival } from "./activity-attribution"
|
|
16
|
+
export { recordSixbPageView, startSixbActivityCapture, trackSixbEvent } from "./activity-tracker"
|
|
13
17
|
export type { SixbApiErrorCode, SixbApiErrorInit } from "./api"
|
|
14
18
|
export { isSixbApiError, SixbApiError } from "./api"
|
|
15
19
|
|
|
@@ -111,6 +115,7 @@ export function configureSixbBrowserClient(
|
|
|
111
115
|
options: SixbBrowserClientOptions = {}
|
|
112
116
|
): SixbBrowserClientController {
|
|
113
117
|
activeBrowserController?.dispose()
|
|
118
|
+
prepareActivityArrival(config.api.baseUrl, "app")
|
|
114
119
|
|
|
115
120
|
let csrfToken: string | null = null
|
|
116
121
|
let disposed = false
|
|
@@ -161,6 +166,7 @@ export function configureSixbBrowserClient(
|
|
|
161
166
|
((url: string) => {
|
|
162
167
|
if (typeof window !== "undefined") window.location.assign(url)
|
|
163
168
|
})
|
|
169
|
+
preserveSixbActivityArrival()
|
|
164
170
|
redirect(createSixbSignInUrl(config, currentUrl))
|
|
165
171
|
} catch {
|
|
166
172
|
// Allow a later response to retry navigation without replacing the original API error.
|
|
@@ -179,6 +185,7 @@ export function configureSixbBrowserClient(
|
|
|
179
185
|
dispose() {
|
|
180
186
|
if (disposed) return
|
|
181
187
|
disposed = true
|
|
188
|
+
stopSixbActivityCapture()
|
|
182
189
|
csrfToken = null
|
|
183
190
|
disposeActivity()
|
|
184
191
|
client.interceptors.response.eject(authResponseInterceptorId)
|
|
@@ -203,6 +210,7 @@ export function configureSixbSharedBrowserClient(
|
|
|
203
210
|
): SixbSharedBrowserClientController {
|
|
204
211
|
activeBrowserController?.dispose()
|
|
205
212
|
assertSharedAccessGrantId(options.grantId)
|
|
213
|
+
prepareActivityArrival(config.api.baseUrl, `share:${options.grantId}`)
|
|
206
214
|
|
|
207
215
|
const previousConfig = client.getConfig()
|
|
208
216
|
const previousSharedAuthority = getClientSharedGrantId(client)
|
|
@@ -265,6 +273,7 @@ export function configureSixbSharedBrowserClient(
|
|
|
265
273
|
dispose() {
|
|
266
274
|
if (disposed) return
|
|
267
275
|
disposed = true
|
|
276
|
+
stopSixbActivityCapture()
|
|
268
277
|
csrfToken = null
|
|
269
278
|
disposeActivity()
|
|
270
279
|
client.interceptors.response.eject(responseInterceptorId)
|
|
@@ -425,10 +434,13 @@ function isAuthRedirectExcludedRequest(
|
|
|
425
434
|
const apiUrl = new URL(normalizeSixbApiBaseUrl(config.api.baseUrl), requestUrl)
|
|
426
435
|
const apiPath = apiUrl.pathname.replace(/\/+$/, "")
|
|
427
436
|
const method = request.method.toUpperCase()
|
|
437
|
+
// Activity is background traffic: an expired session shows on the user's next real request.
|
|
428
438
|
return (
|
|
429
439
|
requestUrl.origin === apiUrl.origin &&
|
|
430
440
|
((method === "GET" && requestUrl.pathname === `${apiPath}/api/auth/session`) ||
|
|
431
|
-
(method === "POST" && requestUrl.pathname === `${apiPath}/api/auth/sign-out`)
|
|
441
|
+
(method === "POST" && requestUrl.pathname === `${apiPath}/api/auth/sign-out`) ||
|
|
442
|
+
(method === "GET" && requestUrl.pathname === `${apiPath}/api/activity/capture-config`) ||
|
|
443
|
+
(method === "POST" && requestUrl.pathname === `${apiPath}/api/activity/events`))
|
|
432
444
|
)
|
|
433
445
|
}
|
|
434
446
|
|
|
@@ -469,6 +481,7 @@ export async function requireSixbBrowserAuthSession(
|
|
|
469
481
|
}
|
|
470
482
|
const returnTo = options.returnTo ?? window.location.href
|
|
471
483
|
const redirect = options.redirect ?? ((url: string) => window.location.assign(url))
|
|
484
|
+
preserveSixbActivityArrival()
|
|
472
485
|
redirect(createSixbSignInUrl(config, returnTo))
|
|
473
486
|
return data
|
|
474
487
|
}
|