@kronor/dtv 9.4.3 → 9.5.1

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.
@@ -0,0 +1,779 @@
1
+ # Analytics
2
+
3
+ A table can report what happens in it: what users do, how long its requests take, and what
4
+ fails. DTV only reports. Storing the events and analysing them is up to the app.
5
+
6
+ - [Setting up](#setting-up)
7
+ - [The envelope](#the-envelope): what every event carries
8
+ - [Events](#events): every event and its fields
9
+ - [Lifecycle](#lifecycle): `sessionStarted`, `viewMounted`, `viewUnmounted`, `viewSelected`
10
+ - [Filters](#filters): `filtersApplied`, `filterSearch`
11
+ - [The table](#the-table): `orderingChanged`, `rowsPerPageChanged`, `hiddenColumnsChanged`, `panelShown`, `rowExpansionToggled`
12
+ - [Saved filters and links](#saved-filters-and-links): `savedFilterSaved`, `savedFilterDeleted`, `shareLinkCreated`
13
+ - [Spans](#spans): `fetch`, `userDataLoad`, `action`, `rowExpansionLoad`, `aiFilter`
14
+ - [Problems](#problems): `userDataSaveFailed`, `userDataConflict`, `userDataReadOnly`, `filtersChangedSinceSnapshot`, `suggestionsFailed`
15
+ - [Shared types](#shared-types)
16
+ - [Order and guarantees](#order-and-guarantees)
17
+ - [Putting events together](#putting-events-together)
18
+ - [Reading old events](#reading-old-events)
19
+ - [What is not reported](#what-is-not-reported)
20
+ - [Privacy](#privacy)
21
+ - [Compatibility](#compatibility)
22
+
23
+ ## Setting up
24
+
25
+ ```tsx
26
+ import { App, type DTVAnalyticsEvent } from '@kronor/dtv';
27
+
28
+ <App
29
+ analytics={{ onEvent: (event: DTVAnalyticsEvent) => queue.push(event) }}
30
+ …
31
+ />
32
+ ```
33
+
34
+ - `onEvent` is called synchronously, as each event happens, as a method of `analytics`, so a
35
+ class instance with an `onEvent` method works as it is.
36
+ - Keep it cheap: queue the event and send batches.
37
+ - What it throws is logged and otherwise ignored, so analytics can never break a table.
38
+ - Without `analytics`, nothing is reported, and tables do no work for it.
39
+ - `analytics` may change between renders: each event goes to the handler of the latest one.
40
+
41
+ A sink that sends batches, and what is left when the page is hidden:
42
+
43
+ ```ts
44
+ const queue: DTVAnalyticsEvent[] = [];
45
+
46
+ function flush(): void {
47
+ const batch = queue.splice(0);
48
+ // keepalive lets the request finish while the page unloads
49
+ if (batch.length > 0) void fetch('/analytics', { method: 'POST', body: JSON.stringify(batch), keepalive: true });
50
+ }
51
+
52
+ setInterval(flush, 10_000);
53
+ addEventListener('pagehide', flush);
54
+ addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flush(); });
55
+
56
+ const analytics = { onEvent: (event: DTVAnalyticsEvent) => queue.push(event) };
57
+ ```
58
+
59
+ Types are exported from `@kronor/dtv`: `DTVAnalytics`, `DTVAnalyticsEvent` (narrow it by
60
+ `type`), `DTVAnalyticsEventType`, `DTVAnalyticsEventBase`, `DTVAnalyticsEventPayload`,
61
+ `DTVAnalyticsSpan`, and the [shared types](#shared-types).
62
+
63
+ ## The envelope
64
+
65
+ Every event has these fields besides its own:
66
+
67
+ | Field | Type | |
68
+ |---|---|---|
69
+ | `type` | string | Which event it is; see [Events](#events). |
70
+ | `sessionId` | string | The page session, a UUID: from when DTV was loaded until the page is loaded again. All tables of the page share it, however many and whenever they mount; moving between pages of a single-page app keeps it. Another tab has another one. |
71
+ | `instanceId` | string | One mounted table, a UUID. A popout of it is another one, and so is each table on a page. |
72
+ | `seq` | number | Numbers the instance's events from 1, without gaps, in the order they were reported. |
73
+ | `at` | number | When the event was reported, in milliseconds since the epoch, by the browser's clock. |
74
+ | `viewId` | string | The view the event is of. |
75
+ | `definition` | string | The view's definition: the id its [migrations](view-migrations.md) are kept under. Views built per record (`asset-list-7`) share it. Without migrations, the view id. |
76
+ | `definitionRevision` | number | The revision of the definition the table runs with; 1 without migrations. Filter states in events are written for it (see [Reading old events](#reading-old-events)). |
77
+
78
+ Spans, things with a duration, are reported once, when they end, and also have:
79
+
80
+ | Field | Type | |
81
+ |---|---|---|
82
+ | `startedAt` | number | When it started, in milliseconds since the epoch. |
83
+ | `durationMs` | number | How long it took, in whole milliseconds, measured with `performance.now()`, which a changed clock does not affect. |
84
+
85
+ A whole event, as `onEvent` receives it:
86
+
87
+ ```json
88
+ {
89
+ "sessionId": "9c2d7a41-6b3e-4f8a-a1d5-0e4b7c9f2a63",
90
+ "instanceId": "4b1f0e2c-9a57-4d1e-8f0a-2c6f1d3e7b90",
91
+ "seq": 4,
92
+ "at": 1793875200345,
93
+ "viewId": "journal-list",
94
+ "definition": "journal-list",
95
+ "definitionRevision": 3,
96
+ "type": "fetch",
97
+ "startedAt": 1793875200120,
98
+ "durationMs": 225,
99
+ "reason": "filters",
100
+ "page": 0,
101
+ "rowsPerPage": 50,
102
+ "ordering": { "field": "date", "direction": "DESC" },
103
+ "filtersSeq": 3,
104
+ "outcome": "succeeded",
105
+ "rowCount": 50,
106
+ "hasMore": true
107
+ }
108
+ ```
109
+
110
+ The examples below show each event's own fields only.
111
+
112
+ ## Events
113
+
114
+ Fields marked *optional* are left out, not `null`, when they do not apply.
115
+
116
+ ### Lifecycle
117
+
118
+ #### `sessionStarted`
119
+
120
+ The page session started. Reported once per session, by the table that reports an event first,
121
+ as its first event, before its `viewMounted`.
122
+
123
+ | Field | Type | |
124
+ |---|---|---|
125
+ | `dtvVersion` | string | The version of `@kronor/dtv` running; `development` in a build that is not the library's, such as tests. |
126
+
127
+ ```json
128
+ { "type": "sessionStarted", "dtvVersion": "9.5.0" }
129
+ ```
130
+
131
+ The version is the same for the whole session, so it is reported here only: an event's
132
+ version is its session's.
133
+
134
+ #### `viewMounted`
135
+
136
+ The table mounted. The instance's first event, but in the table that starts the session,
137
+ where `sessionStarted` comes before it.
138
+
139
+ | Field | Type | |
140
+ |---|---|---|
141
+ | `popout` | boolean | The table is the popout of another one. |
142
+
143
+ ```json
144
+ { "type": "viewMounted", "popout": false }
145
+ ```
146
+
147
+ #### `viewUnmounted`
148
+
149
+ The table unmounted: the user left the page, or the app stopped showing it. No fields.
150
+ Spans still running then end after it, as `aborted` (see [Order and guarantees](#order-and-guarantees)).
151
+
152
+ ```json
153
+ { "type": "viewUnmounted" }
154
+ ```
155
+
156
+ #### `viewSelected`
157
+
158
+ The user switched views in the views menu (`showViewsMenu`). The event is of the new view;
159
+ the table then opens it as it opens any view, with a `filtersApplied`.
160
+
161
+ | Field | Type | |
162
+ |---|---|---|
163
+ | `previousViewId` | string | The view left. |
164
+
165
+ ```json
166
+ { "type": "viewSelected", "previousViewId": "payments" }
167
+ ```
168
+
169
+ ### Filters
170
+
171
+ #### `filtersApplied`
172
+
173
+ Filters were applied and rows are requested for them, the table opening with them included.
174
+ Every `fetch` names the `filtersApplied` its filters come from (`filtersSeq`), so the filter
175
+ state is reported here only, not with every request.
176
+
177
+ | Field | Type | |
178
+ |---|---|---|
179
+ | `trigger` | [`FiltersAppliedTrigger`](#filtersappliedtrigger) | What applied them. |
180
+ | `filters` | [filter state](#filter-state) | The filters applied. Empty filters are left out: a filter that is not there was not used. |
181
+ | `aiAssisted` | boolean | The AI filter assistant filled the draft since filters were last applied. Edits after it keep this; loading a saved filter clears it. Only `submit` and `api` can be AI-assisted. |
182
+ | `savedFilter` | `{ id: string; name: string }`, *optional* | The saved filter applied, for `trigger: 'savedFilter'`. `id` is the one `savedFilterSaved` reported. |
183
+ | `link` | `{ definitionRevision: number }`, *optional* | For `trigger: 'link'` and `'url'`: the revision of the definition the link was made for. Lower than `definitionRevision`: the link was older than the view, and was migrated. |
184
+
185
+ The same filters applied again are reported again: re-running a search is worth knowing.
186
+
187
+ ```json
188
+ {
189
+ "type": "filtersApplied",
190
+ "trigger": "submit",
191
+ "filters": {
192
+ "status": { "type": "leaf", "value": { "type": "value", "value": ["OPEN"] } },
193
+ "due-date": {
194
+ "type": "and",
195
+ "children": [
196
+ { "type": "leaf", "value": { "type": "value", "value": "2026-10-01T00:00:00.000Z" } },
197
+ { "type": "leaf", "value": { "type": "empty" } }
198
+ ]
199
+ }
200
+ },
201
+ "aiAssisted": false
202
+ }
203
+ ```
204
+
205
+ #### `filterSearch`
206
+
207
+ The user searched the view's filters with "Search filters…", reported once typing paused for a
208
+ second, or as the table unmounts. A search cleared sooner is not reported.
209
+
210
+ | Field | Type | |
211
+ |---|---|---|
212
+ | `query` | string | What was typed, trimmed. |
213
+
214
+ ```json
215
+ { "type": "filterSearch", "query": "due date" }
216
+ ```
217
+
218
+ ### The table
219
+
220
+ #### `orderingChanged`
221
+
222
+ The user sorted by a column, or removed the sorting. Not reported for the sorting a view opens
223
+ with: that is on each `fetch`.
224
+
225
+ | Field | Type | |
226
+ |---|---|---|
227
+ | `ordering` | [`DataOrdering`](#dataordering) \| `null` | The new sorting; `null` when it was removed. |
228
+
229
+ ```json
230
+ { "type": "orderingChanged", "ordering": { "field": "amount", "direction": "ASC" } }
231
+ ```
232
+
233
+ #### `rowsPerPageChanged`
234
+
235
+ The user picked another number of rows per page. Not reported for the number a view opens
236
+ with, nor when another tab changes it: those are on each `fetch`.
237
+
238
+ | Field | Type | |
239
+ |---|---|---|
240
+ | `rowsPerPage` | number | The new number. |
241
+
242
+ ```json
243
+ { "type": "rowsPerPageChanged", "rowsPerPage": 100 }
244
+ ```
245
+
246
+ #### `hiddenColumnsChanged`
247
+
248
+ The user changed which columns are hidden, in the preferences.
249
+
250
+ | Field | Type | |
251
+ |---|---|---|
252
+ | `hiddenColumns` | string[] | The ids of all columns hidden after the change. |
253
+
254
+ ```json
255
+ { "type": "hiddenColumnsChanged", "hiddenColumns": ["memo", "created-by"] }
256
+ ```
257
+
258
+ #### `panelShown`
259
+
260
+ A panel was shown or hidden.
261
+
262
+ | Field | Type | |
263
+ |---|---|---|
264
+ | `panel` | [`DTVAnalyticsPanel`](#dtvanalyticspanel) | Which. |
265
+ | `shown` | boolean | Shown, or hidden. |
266
+
267
+ `filters`, `savedFilters` and `preferences` are shown one at a time: showing another reports
268
+ the one hidden first, then the one shown. Typing a filter search shows `filters`. The AI
269
+ assistant and the popout are shown independently.
270
+
271
+ ```json
272
+ { "type": "panelShown", "panel": "savedFilters", "shown": true }
273
+ ```
274
+
275
+ #### `rowExpansionToggled`
276
+
277
+ The user expanded or collapsed a row: with the row's toggler, or through a row expansion
278
+ renderer's `toggle` or `collapse`. The table's API (`rowExpansion.expandAll`, `collapseAll`)
279
+ is not reported.
280
+
281
+ | Field | Type | |
282
+ |---|---|---|
283
+ | `expanded` | boolean | Expanded, or collapsed. |
284
+
285
+ ```json
286
+ { "type": "rowExpansionToggled", "expanded": true }
287
+ ```
288
+
289
+ ### Saved filters and links
290
+
291
+ #### `savedFilterSaved`
292
+
293
+ The user saved the filters, as a new saved filter or over an existing one. Reported even when
294
+ writing the user's data failed: the saved filter is kept locally, and the failure is a
295
+ `userDataSaveFailed` of its own.
296
+
297
+ | Field | Type | |
298
+ |---|---|---|
299
+ | `savedFilterId` | string | The saved filter's id, a UUID; `filtersApplied` names it when it is applied. |
300
+ | `name` | string | The name the user gave it. |
301
+ | `created` | boolean | A new saved filter; `false` when one was overwritten. |
302
+ | `filters` | [filter state](#filter-state) | What it holds. |
303
+
304
+ ```json
305
+ {
306
+ "type": "savedFilterSaved",
307
+ "savedFilterId": "0f8e6a4c-2d1b-4c3a-9e5f-7a6b8c9d0e1f",
308
+ "name": "Open, this month",
309
+ "created": true,
310
+ "filters": { "status": { "type": "leaf", "value": { "type": "value", "value": ["OPEN"] } } }
311
+ }
312
+ ```
313
+
314
+ #### `savedFilterDeleted`
315
+
316
+ The user deleted a saved filter.
317
+
318
+ | Field | Type | |
319
+ |---|---|---|
320
+ | `savedFilterId` | string | Which. |
321
+
322
+ ```json
323
+ { "type": "savedFilterDeleted", "savedFilterId": "0f8e6a4c-2d1b-4c3a-9e5f-7a6b8c9d0e1f" }
324
+ ```
325
+
326
+ #### `shareLinkCreated`
327
+
328
+ The user copied a link to filters. Whoever opens it reports a `filtersApplied` with
329
+ `trigger: 'link'`.
330
+
331
+ | Field | Type | |
332
+ |---|---|---|
333
+ | `from` | `'filterForm'` \| `'savedFilter'` | The filter form's filters, or a saved filter's. |
334
+
335
+ ```json
336
+ { "type": "shareLinkCreated", "from": "filterForm" }
337
+ ```
338
+
339
+ ### Spans
340
+
341
+ Spans also have `startedAt` and `durationMs` (see [The envelope](#the-envelope)).
342
+
343
+ #### `fetch`
344
+
345
+ A request for the table's rows ended.
346
+
347
+ | Field | Type | |
348
+ |---|---|---|
349
+ | `reason` | [`FetchReason`](#fetchreason) | Why the rows were requested. |
350
+ | `page` | number | The page index: 0 for the first page. |
351
+ | `rowsPerPage` | number | The rows asked for. |
352
+ | `ordering` | [`DataOrdering`](#dataordering) \| `null` | The sorting asked for; `null` for the view's own. |
353
+ | `filtersSeq` | number \| `null` | The `seq` of the `filtersApplied` event the request's filters come from, in the same instance. `null` only when the handler was set after that event. |
354
+ | `outcome` | `'succeeded'` \| `'failed'` \| `'aborted'` | `aborted`: superseded by a newer request (the user changed filters before rows arrived), or the table unmounted. Rows that arrive for an aborted request are discarded. |
355
+ | `rowCount` | number, *optional* | When `succeeded`: the rows that arrived. |
356
+ | `hasMore` | boolean, *optional* | When `succeeded`: a full page arrived, so there may be a next one. Pages are fetched by cursor, without a total count. |
357
+ | `error` | [`FetchErrorInfo`](#fetcherrorinfo), *optional* | When `failed`: what went wrong. |
358
+
359
+ `durationMs` covers resolving the request headers, the request, and flattening the rows.
360
+
361
+ ```json
362
+ {
363
+ "type": "fetch",
364
+ "startedAt": 1793875300000,
365
+ "durationMs": 30012,
366
+ "reason": "nextPage",
367
+ "page": 3,
368
+ "rowsPerPage": 50,
369
+ "ordering": null,
370
+ "filtersSeq": 7,
371
+ "outcome": "failed",
372
+ "error": {
373
+ "kind": "timeout",
374
+ "message": "canceling statement due to statement timeout",
375
+ "status": 200,
376
+ "codes": ["postgres-error"]
377
+ }
378
+ }
379
+ ```
380
+
381
+ A failed request still shows the table empty, as before analytics; only the event tells it apart
382
+ from a request that found no rows.
383
+
384
+ #### `userDataLoad`
385
+
386
+ The user's data was loaded and read, once per mounted table: from the app's `userData.onLoad`,
387
+ or from localStorage alone without one. Reading includes migrating each view's data to its
388
+ definition's current revision.
389
+
390
+ | Field | Type | |
391
+ |---|---|---|
392
+ | `outcome` | `'succeeded'` \| `'failed'` | `failed`: the app's loader failed or returned what could not be read. The table goes on with the local copy. |
393
+ | `source` | `'remote'` \| `'local'` | The copy the table started from: the loader's, or localStorage's when that was newer, the load failed, or there is no loader. |
394
+ | `migrated` | boolean | Migrations changed what is stored. |
395
+ | `resets` | [`DTVAnalyticsResets`](#dtvanalyticsresets)[] | Filters whose stored state was dropped while reading: the cost of definition changes to users. Empty when nothing was. |
396
+ | `retainedViews` | [`DTVAnalyticsRetainedView`](#dtvanalyticsretainedview)[] | Views of this table whose stored data was left as it was, unread. |
397
+ | `error` | [`DTVAnalyticsUserDataError`](#dtvanalyticsuserdataerror), *optional* | When `failed`: why. |
398
+
399
+ When the stored data is in a format this version cannot read, the table reports
400
+ `userDataReadOnly` instead.
401
+
402
+ ```json
403
+ {
404
+ "type": "userDataLoad",
405
+ "startedAt": 1793875199900,
406
+ "durationMs": 180,
407
+ "outcome": "succeeded",
408
+ "source": "remote",
409
+ "migrated": true,
410
+ "resets": [{ "viewId": "journal-list", "persistedFilterState": ["amount"], "savedFilters": [{ "name": "Big ones", "filterIds": ["amount"] }] }],
411
+ "retainedViews": []
412
+ }
413
+ ```
414
+
415
+ #### `action`
416
+
417
+ An action button's `onClick` ended: its promise settled, or it threw.
418
+
419
+ | Field | Type | |
420
+ |---|---|---|
421
+ | `action` | string | The action's `id`, or its label when it has none. Give actions an `id`: labels change with wording. |
422
+ | `selectedRows` | number | The rows selected when it was clicked. |
423
+ | `outcome` | `'succeeded'` \| `'failed'` | `failed`: it threw or rejected. |
424
+ | `error` | [`DTVAnalyticsError`](#dtvanalyticserror), *optional* | When `failed`: what it threw. |
425
+
426
+ ```json
427
+ { "type": "action", "startedAt": 1793875400000, "durationMs": 1200, "action": "csv-export", "selectedRows": 0, "outcome": "succeeded" }
428
+ ```
429
+
430
+ #### `rowExpansionLoad`
431
+
432
+ The data of a lazily expanded row (`rowExpansion.lazy`) was loaded, the first time the row was
433
+ expanded. Rows expanded again use what was loaded and report nothing; a row whose data failed
434
+ to load is loaded, and reported, again.
435
+
436
+ | Field | Type | |
437
+ |---|---|---|
438
+ | `outcome` | `'succeeded'` \| `'failed'` | |
439
+ | `error` | [`DTVAnalyticsError`](#dtvanalyticserror), *optional* | When `failed`. |
440
+
441
+ ```json
442
+ { "type": "rowExpansionLoad", "startedAt": 1793875500000, "durationMs": 95, "outcome": "succeeded" }
443
+ ```
444
+
445
+ #### `aiFilter`
446
+
447
+ The AI filter assistant was asked to fill the filters. It fills the draft; applying it is a
448
+ `filtersApplied` with `aiAssisted: true`.
449
+
450
+ | Field | Type | |
451
+ |---|---|---|
452
+ | `prompt` | string | What the user asked, as typed. |
453
+ | `outcome` | `'succeeded'` \| `'failed'` | `succeeded`: it filled the filters. |
454
+ | `error` | [`DTVAnalyticsError`](#dtvanalyticserror), *optional* | When `failed`: the provider's error, or that its answer could not be read. |
455
+
456
+ ```json
457
+ { "type": "aiFilter", "startedAt": 1793875600000, "durationMs": 2400, "prompt": "unpaid invoices from october", "outcome": "succeeded" }
458
+ ```
459
+
460
+ ### Problems
461
+
462
+ #### `userDataSaveFailed`
463
+
464
+ Writing the user's data failed: to the app's `userData.onSave`, or to localStorage. The change
465
+ is kept in the table, and written again with the next change.
466
+
467
+ | Field | Type | |
468
+ |---|---|---|
469
+ | `error` | [`DTVAnalyticsUserDataError`](#dtvanalyticsuserdataerror) | Why. |
470
+
471
+ ```json
472
+ { "type": "userDataSaveFailed", "error": { "kind": "externalSaveFailed", "message": "Stale revision: user data was not updated" } }
473
+ ```
474
+
475
+ The `message` of `external…` errors is what the app's callback returned or threw.
476
+
477
+ #### `userDataConflict`
478
+
479
+ The app's `onSave` rejected a write because another tab or device wrote first. The table loaded
480
+ theirs, applied the change on top, and wrote again.
481
+
482
+ | Field | Type | |
483
+ |---|---|---|
484
+ | `resolved` | boolean | Writing again succeeded. When not, a `userDataSaveFailed` follows. |
485
+
486
+ ```json
487
+ { "type": "userDataConflict", "resolved": true }
488
+ ```
489
+
490
+ #### `userDataReadOnly`
491
+
492
+ The stored user data is in a format this version cannot read, e.g. one a newer version wrote in
493
+ another tab. The table works from defaults and saves nothing, so the newer data is not lost.
494
+
495
+ | Field | Type | |
496
+ |---|---|---|
497
+ | `message` | string | What could not be read. |
498
+
499
+ ```json
500
+ { "type": "userDataReadOnly", "message": "User-data migration cannot proceed from an unknown revision. Current revision: 2027-01-10T00:00:00.000Z …" }
501
+ ```
502
+
503
+ #### `filtersChangedSinceSnapshot`
504
+
505
+ The view's filters differ from its latest definition snapshot: the definition changed and
506
+ `dtv definitions snapshot` was not run for it, so no migration covers the change. Reported as
507
+ the table opens the view. `dtv definitions check` in CI prevents it; in production it should
508
+ never be reported.
509
+
510
+ | Field | Type | |
511
+ |---|---|---|
512
+ | `changed` | string[] | Filters in both, defined differently. Their stored state is reset rather than misread. |
513
+ | `added` | string[] | Filters only the view has. |
514
+ | `removed` | string[] | Filters only the snapshot has. |
515
+
516
+ ```json
517
+ { "type": "filtersChangedSinceSnapshot", "changed": ["amount"], "added": ["currency"], "removed": [] }
518
+ ```
519
+
520
+ #### `suggestionsFailed`
521
+
522
+ A filter's suggestion fetcher (an autocomplete) failed. The filter shows no suggestions. Each
523
+ failed lookup is reported, so one broken fetcher can report once per keystroke.
524
+
525
+ | Field | Type | |
526
+ |---|---|---|
527
+ | `error` | [`DTVAnalyticsError`](#dtvanalyticserror) | What it threw. |
528
+
529
+ ```json
530
+ { "type": "suggestionsFailed", "error": { "name": "ClientError", "message": "field 'vendors' not found in type: 'query_root'" } }
531
+ ```
532
+
533
+ ## Shared types
534
+
535
+ ### `FiltersAppliedTrigger`
536
+
537
+ | Value | The filters were applied by |
538
+ |---|---|
539
+ | `submit` | Submitting the filter form. |
540
+ | `reset` | "Reset All" in the filter form. |
541
+ | `pillRemoved` | Removing an applied filter's pill. |
542
+ | `savedFilter` | Using a saved filter. |
543
+ | `api` | App code: `applyFilters` from a cell renderer, row expansion renderer, no-rows component or action. |
544
+ | `link` | The table opening with a link: one shared from a table, or made elsewhere, e.g. by the app. |
545
+ | `url` | The table opening with the filter state it keeps in its URL (`syncFilterStateToUrl`): a reload, its popout, or that URL copied from the address bar. |
546
+ | `restored` | The table opening with the filter state persisted in the user's data. |
547
+ | `initial` | The table opening with the view's initial filter values. |
548
+
549
+ ### `FetchReason`
550
+
551
+ | Value | The rows were requested because |
552
+ |---|---|
553
+ | `filters` | Filters were applied; see the `filtersApplied` of `filtersSeq`. The table opening is one. |
554
+ | `ordering` | The user sorted. The first page is requested. |
555
+ | `rowsPerPage` | The user picked another number of rows per page. The first page is requested. |
556
+ | `nextPage`, `previousPage` | The user paged. |
557
+ | `refresh` | The app asked for fresh rows (`DTVAPI.fetchData`, an action's `refetch`), e.g. after a mutation. |
558
+ | `userData` | The rows per page or the sorting changed in the user's data, e.g. in another tab. |
559
+
560
+ ### `DTVAnalyticsPanel`
561
+
562
+ `'filters'`, `'savedFilters'`, `'preferences'`, `'aiAssistant'` or `'popout'`.
563
+
564
+ ### `DataOrdering`
565
+
566
+ ```ts
567
+ { field: string; direction: 'ASC' | 'DESC' }
568
+ ```
569
+
570
+ `field` is the field the rows are sorted by, as a column's `orderBy` names it, not a column id.
571
+
572
+ ### Filter state
573
+
574
+ Filter states (`filtersApplied.filters`, `savedFilterSaved.filters`) are written as the user's
575
+ data stores them, and as links carry them: by filter id, each filter's state a tree that
576
+ follows the shape of its expression.
577
+
578
+ ```ts
579
+ type FilterState = Record<FilterId, Node>;
580
+
581
+ type Node =
582
+ | { type: 'leaf'; value: { type: 'empty' } | { type: 'value'; value: Json } }
583
+ | { type: 'and' | 'or'; children: Node[] }
584
+ | { type: 'not'; child: Node };
585
+ ```
586
+
587
+ - A filter that is left empty is not in the state at all.
588
+ - A filter with several parts, like a date range, keeps its empty parts: a range with only a
589
+ start has an `empty` end.
590
+ - Values are what the filter's control holds: text, a number, a list of dropdown or multiselect
591
+ values, a boolean.
592
+ - Dates are ISO 8601 strings.
593
+ - A custom operator's value is `{ operator, value }`, where `value` is again `{ type: 'empty' }`
594
+ or `{ type: 'value', value }`. A date in it is still a `Date` until the event is serialized:
595
+ `JSON.stringify` writes it as an ISO string.
596
+ - Values are as the control holds them, before a filter's query transforms change them. A filter
597
+ whose transform turns major units into minor ones reports what the user typed.
598
+
599
+ ```json
600
+ {
601
+ "customer-email": { "type": "leaf", "value": { "type": "value", "value": "a@example.com" } },
602
+ "status": { "type": "leaf", "value": { "type": "value", "value": ["PAID", "VOID"] } },
603
+ "reference": {
604
+ "type": "leaf",
605
+ "value": { "type": "value", "value": { "operator": "_ilike", "value": { "type": "value", "value": "%INV%" } } }
606
+ },
607
+ "created": {
608
+ "type": "and",
609
+ "children": [
610
+ { "type": "leaf", "value": { "type": "value", "value": "2026-10-01T00:00:00.000Z" } },
611
+ { "type": "leaf", "value": { "type": "empty" } }
612
+ ]
613
+ },
614
+ "not-voided": { "type": "not", "child": { "type": "leaf", "value": { "type": "value", "value": true } } }
615
+ }
616
+ ```
617
+
618
+ The type is exported as `UndecodedFilterState`.
619
+
620
+ ### `FetchErrorInfo`
621
+
622
+ ```ts
623
+ { kind: FetchErrorKind; message: string; status?: number; codes?: string[] }
624
+ ```
625
+
626
+ | `kind` | What failed | Told by |
627
+ |---|---|---|
628
+ | `timeout` | The database cancelled the query, e.g. on its statement timeout, or a gateway timed out. Narrower filters may help. | HTTP 504, or an error message about a statement timeout or cancelled statement. |
629
+ | `unauthorized` | The API rejected the token or the role. | HTTP 401 or 403, or a Hasura code such as `invalid-jwt` or `access-denied`. |
630
+ | `graphql` | The API answered with errors, e.g. a field the role may not read. | GraphQL errors in the response. |
631
+ | `http` | The API answered with an error status and no GraphQL errors. | Any other HTTP error status. |
632
+ | `network` | No answer arrived: offline, DNS, CORS, a dropped connection. | fetch's `TypeError`, in each browser's words. |
633
+ | `unexpectedResponse` | The answer has no rows where the view's root field should be. | The response. |
634
+ | `internal` | Code failed: the app's `requestHeaders`, building the query's variables, flattening the rows. | Anything else. |
635
+
636
+ - `message`: the GraphQL errors' messages joined with `; `, `HTTP <status>`, or the error's
637
+ message.
638
+ - `status`: the HTTP status, when an answer arrived. A GraphQL error usually comes with 200.
639
+ - `codes`: the GraphQL errors' `extensions.code`, when they have one.
640
+
641
+ ### `DTVAnalyticsError`
642
+
643
+ ```ts
644
+ { name: string; message: string }
645
+ ```
646
+
647
+ An error's `name` (`TypeError`, `ClientError`, …) and `message`. What is thrown that is not an
648
+ `Error` has the name `Error` and itself as the message.
649
+
650
+ ### `DTVAnalyticsResets`
651
+
652
+ ```ts
653
+ {
654
+ viewId: string;
655
+ persistedFilterState: string[]; // filters reset in the filters the view opens with
656
+ savedFilters: { name: string; filterIds: string[] }[]; // filters reset in each saved filter
657
+ }
658
+ ```
659
+
660
+ ### `DTVAnalyticsRetainedView`
661
+
662
+ ```ts
663
+ { viewId: string; reason: 'newerRevision' | 'decodeFailed' }
664
+ ```
665
+
666
+ - `newerRevision`: written for a revision of the definition this table does not know yet, by a
667
+ newer version in another tab, or before a rollback.
668
+ - `decodeFailed`: it could not be read.
669
+
670
+ The data is kept as stored, for whoever can read it.
671
+
672
+ ### `DTVAnalyticsUserDataError`
673
+
674
+ ```ts
675
+ { kind: 'externalLoadFailed' | 'externalSaveFailed' | 'localStorageFailed'; message: string }
676
+ ```
677
+
678
+ `external…` failures come from the app's `userData.onLoad` and `onSave`; `message` is what
679
+ they returned or threw.
680
+
681
+ ## Order and guarantees
682
+
683
+ - **One session per page load.** Every table of the page has the same `sessionId`, and the
684
+ first to report anything reports `sessionStarted`. Events are numbered per table, not per
685
+ session: order a session's tables by their `viewMounted.at`.
686
+ - **One instance per mounted table.** Each `App` has its own `instanceId`, numbering, and user
687
+ data load. Several tables on a page are several instances, and so is a popout. The popout is
688
+ mounted without the app's actions and user data callbacks, so it reports no `action`, and its
689
+ `userDataLoad` reads localStorage alone.
690
+ - **`seq` has no gaps.** Within an instance, events are numbered from 1 in the order they were
691
+ reported. A gap means events were lost on the way, not that the table skipped one. Events are
692
+ numbered only while there is a handler: one set after the table mounted starts the
693
+ numbering then.
694
+ - **`viewMounted` comes first, `viewUnmounted` last.** The exceptions: `sessionStarted` comes
695
+ before `viewMounted` in the session's first table, and spans that were running as the table
696
+ unmounted end after it, as `aborted`, or as they settle.
697
+ - **Filters before requests.** The `filtersApplied` a request's filters come from is reported
698
+ before the request starts, so `filtersSeq` always points back.
699
+ - **Spans are reported when they end.** A `fetch` that started before another event can come
700
+ after it.
701
+ - **Events as the table unmounts are not lost.** What the table reports while it unmounts is
702
+ reported before `viewUnmounted`, and so is a filter search still waiting for its pause.
703
+ - **StrictMode adds nothing.** React's StrictMode mounts tables twice in development builds.
704
+ The table still reports one `viewMounted`, one `userDataLoad`, and `viewUnmounted` only when
705
+ it unmounts.
706
+ - **Clocks.** `at` and `startedAt` are the browser's clock, which may be wrong; order events by
707
+ `instanceId` and `seq`, and store the time they arrived beside them. `durationMs` is measured
708
+ with `performance.now()`, which a clock change does not affect. Browsers slow timers in
709
+ background tabs: spans that ran there can be longer than the work took.
710
+
711
+ ## Putting events together
712
+
713
+ - **A page session:** its events by `sessionId`, each table's by `instanceId` and `seq`: the
714
+ views a user opened, one after another, between two page loads. Its `sessionStarted` says
715
+ which DTV version all of them ran.
716
+ - **A table's life:** its events by `instanceId`, ordered by `seq`. Time on the view is
717
+ `viewUnmounted.at - viewMounted.at`.
718
+ - **The filters a request ran with:** the `filtersApplied` with the same `instanceId` and
719
+ `seq = fetch.filtersSeq`. Slow and failing filter combinations come out of this.
720
+ - **How a view opens:** the first `filtersApplied` after `viewMounted` (or `viewSelected`)
721
+ says where its filters came from, and the `fetch` that names it how long the first rows took.
722
+ `userDataLoad` says how long the user's data took. It can come before or after: a table opens
723
+ from the local copy when that is enough, without waiting for the load.
724
+ - **Saved filter use:** `savedFilterSaved` and `savedFilterDeleted` by `savedFilterId`, and the
725
+ `filtersApplied` whose `savedFilter.id` names it.
726
+ - **How long a panel was open:** a `panelShown` with `shown: true` and the next one of the same
727
+ panel with `shown: false`, or `viewUnmounted`.
728
+ - **AI assistance:** `aiFilter` and the next `filtersApplied` with `aiAssisted: true`, or none
729
+ when the user dropped what the assistant filled in.
730
+
731
+ ## Reading old events
732
+
733
+ Filter states and filter ids in events are written for the definition revision the table ran
734
+ with (`definitionRevision`). When the definition changed since, read them in terms of the
735
+ current one with the view's migrations, the chain its `dtv-migrations` folder exports:
736
+
737
+ ```ts
738
+ import { currentDefinitionRevision, latestFilterId, migrateFilterState } from '@kronor/dtv';
739
+ import journalListMigrations from './dtv-migrations/journal-list';
740
+
741
+ // A whole filter state, e.g. to see which values users filter by
742
+ const filters = migrateFilterState(journalListMigrations, event.definitionRevision, event.filters);
743
+
744
+ // One filter id, e.g. when counting how often each filter is used: 'amount', or null when dropped
745
+ const filterId = latestFilterId(journalListMigrations, event.definitionRevision, 'amt');
746
+
747
+ // Whether an event is of the current revision
748
+ const current = event.definitionRevision === currentDefinitionRevision(journalListMigrations);
749
+ ```
750
+
751
+ `latestFilterId` follows renames; a filter that was reset keeps its id, though what was stored
752
+ for it may have meant something else. Group events by `definition`, not `viewId`: views built
753
+ per record share a definition and its migrations.
754
+
755
+ ## What is not reported
756
+
757
+ - Editing the draft: typing in the filter form. Only applying it is.
758
+ - Selecting rows. `action` reports how many were selected when it ran.
759
+ - The "Export page to CSV" button (`showCsvExportButton`).
760
+ - The preferences other than hidden columns: syncing filters or sorting to user data, syncing
761
+ filters to the URL, closing the filter panel on apply.
762
+ - The table's API: `DTVAPI.rowSelection`, `rowExpansion` (its `fetchData` is a `fetch` with
763
+ `reason: 'refresh'`).
764
+ - The sorting, rows per page and filters a view opens with are not changes: they are on the
765
+ `fetch` and the `filtersApplied` it names.
766
+
767
+ ## Privacy
768
+
769
+ Events carry what users typed and chose: filter values (names, emails, amounts, references),
770
+ saved filter names, AI prompts, filter searches, and the error messages of the API, which can
771
+ quote values. Treat them as the data the table shows. DTV sends events to the app's handler only;
772
+ what is stored, for how long, and who may read it is the app's to decide.
773
+
774
+ ## Compatibility
775
+
776
+ - New events and new fields may come in minor releases; existing ones keep their meaning.
777
+ Handle event types you do not know, e.g. with a `default` that stores them as they are.
778
+ - Optional fields are left out, not `null`, when they do not apply.
779
+ - Filter states follow the user data format; links and saved filters use the same one.