@vitrinka/web 0.10.0 → 0.11.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.
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The test round this browser is in (recorder report mode, vt-3094): one
3
+ * person's reports from one sitting on one site, grouped in vitrinka. The
4
+ * first report opens a round and vitrinka hands back its token; every later
5
+ * report sends the token and joins the round while it stands. vitrinka
6
+ * decides when a round is over (the reporter ended it, or it was quiet too
7
+ * long): the report then opens a new one and `rotated` says so. This module
8
+ * only keeps the token.
9
+ *
10
+ * Kept in the recorder storage (localStorage: every tab of the site shares
11
+ * it, a reload keeps it), one key per vitrinka and report key: two widgets
12
+ * for two projects never share a round, and never rewrite each other's (a
13
+ * shared map would be read and written whole by tabs that do not exclude
14
+ * one another).
15
+ */
16
+ import { api, VitrinkaApiError } from '../recorder/api';
17
+ import { getRecorderStorage } from '../recorder/storage';
18
+ /** The keys' prefix; `roundStorageKey` names a target's own. */
19
+ export const ROUND_STORAGE_KEY = 'report.round';
20
+ /** The storage key of the round held for this vitrinka and report key. */
21
+ export function roundStorageKey(target) {
22
+ return `${ROUND_STORAGE_KEY}:${target.url}|${target.key}`;
23
+ }
24
+ /** What the store holds for a target, as stored: whatever another script or version wrote there, so nothing is trusted. */
25
+ function read(target) {
26
+ try {
27
+ return JSON.parse(getRecorderStorage().getString(roundStorageKey(target)) ?? 'null');
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /**
34
+ * Storage can refuse a write long after it took the first (a full quota, a
35
+ * browser that withdrew it): a round then simply is not kept — the report
36
+ * that was just filed never fails for it, and the next one opens a new round.
37
+ */
38
+ function write(target, round) {
39
+ try {
40
+ const s = getRecorderStorage();
41
+ if (round)
42
+ s.set(roundStorageKey(target), JSON.stringify(round));
43
+ else
44
+ s.remove(roundStorageKey(target));
45
+ }
46
+ catch (e) {
47
+ console.warn('vitrinka: the test round could not be kept in this browser — the next report opens a new one', e);
48
+ }
49
+ }
50
+ /** One stored entry as a round, field by field; null for anything that is not one. */
51
+ function heldOf(v) {
52
+ if (typeof v !== 'object' || v === null)
53
+ return null;
54
+ const r = v;
55
+ if (typeof r.token !== 'string' || !r.token)
56
+ return null;
57
+ return {
58
+ token: r.token,
59
+ reports: typeof r.reports === 'number' && Number.isFinite(r.reports) && r.reports > 0 ? Math.floor(r.reports) : 0,
60
+ openedAt: typeof r.openedAt === 'string' ? r.openedAt : '',
61
+ };
62
+ }
63
+ /** The round held for this vitrinka and key; null on a first report. */
64
+ export function roundFor(target) {
65
+ return heldOf(read(target));
66
+ }
67
+ /** Forget the round (it ended, or vitrinka no longer knows it). */
68
+ export function forgetRound(target) {
69
+ if (read(target) !== null)
70
+ write(target, null);
71
+ }
72
+ /** Forget `token`'s round only while it is still the one held: another tab may have been handed a new one since. */
73
+ function forgetToken(target, token) {
74
+ if (roundFor(target)?.token === token)
75
+ forgetRound(target);
76
+ }
77
+ /**
78
+ * Keep what a create answered as `round` ({token, reports?, openedAt?,
79
+ * rotated?}); anything else leaves the held round as it is. `sent` is the
80
+ * token that create carried ('' on a first report): the reply is kept only
81
+ * while the browser still holds what the request started from. Another tab
82
+ * may have been answered meanwhile — then its round stands and this late
83
+ * reply is dropped, never restoring a token the browser moved on from. A
84
+ * reply for the round still held keeps the higher count of the two. Returns
85
+ * the round now held and whether vitrinka opened a new one in place of the
86
+ * token sent; null when nothing was kept.
87
+ */
88
+ export function keepRound(target, reply, sent = '') {
89
+ if (typeof reply !== 'object' || reply === null)
90
+ return null;
91
+ const r = reply;
92
+ if (typeof r.token !== 'string' || !r.token)
93
+ return null;
94
+ const round = {
95
+ token: r.token,
96
+ reports: typeof r.reports === 'number' && Number.isFinite(r.reports) && r.reports > 0 ? Math.floor(r.reports) : 1,
97
+ openedAt: typeof r.openedAt === 'string' ? r.openedAt : '',
98
+ };
99
+ const held = roundFor(target);
100
+ if ((held?.token ?? '') !== sent) {
101
+ // The browser moved on while this request was in flight. Its own round's reply still counts.
102
+ if (held?.token !== round.token)
103
+ return null;
104
+ }
105
+ if (held?.token === round.token)
106
+ round.reports = Math.max(round.reports, held.reports);
107
+ write(target, round);
108
+ return { round, rotated: r.rotated === true };
109
+ }
110
+ /**
111
+ * End the round this browser holds: vitrinka closes it and the next report
112
+ * opens a new one. The token is forgotten once vitrinka ended the round or
113
+ * no longer knows it; a failure it may recover from (offline, a 5xx) keeps
114
+ * the token and rejects, so End can be pressed again. Only the round the
115
+ * request named is forgotten: a new one another tab was handed meanwhile
116
+ * stays. False when there was no round to end.
117
+ */
118
+ export async function endRound(target, signal) {
119
+ const held = roundFor(target);
120
+ if (!held)
121
+ return false;
122
+ try {
123
+ await api('POST', '/api/v1/report/round/end', { round: held.token }, { target, signal });
124
+ }
125
+ catch (e) {
126
+ // 404: vitrinka knows no such round (or predates rounds) — nothing left to end.
127
+ if (!(e instanceof VitrinkaApiError) || e.status !== 404)
128
+ throw e;
129
+ }
130
+ forgetToken(target, held.token);
131
+ return true;
132
+ }
@@ -49,6 +49,7 @@ import { listMine, openSession, sessionKey, sessionLive } from './reader';
49
49
  import { noteSent, readSent } from './sent';
50
50
  import { COACH_KEY, readCoach, readSize, SIZE_KEY, SIZE_SCALE, SIZES, techDetails, writePref } from './settings';
51
51
  import { REPORT_CSS } from './styles';
52
+ import { roundFor } from './round';
52
53
  import { EMPTY_CAPTURE, prepareCapture, ReportJob } from './wire';
53
54
  const SVG_NS = 'http://www.w3.org/2000/svg';
54
55
  const TITLE_CAP = 100;
@@ -1692,6 +1693,8 @@ export class ReportWidget {
1692
1693
  envelope(description, capture) {
1693
1694
  const who = this.who();
1694
1695
  const member = memberTokenFor(this.opts.base);
1696
+ // The test round this browser is in (vt-3094): the report joins it while vitrinka says it stands.
1697
+ const round = roundFor({ url: this.opts.base, key: this.opts.key });
1695
1698
  const loc = globalThis.location;
1696
1699
  return {
1697
1700
  title: titleOf(description),
@@ -1709,6 +1712,7 @@ export class ReportWidget {
1709
1712
  markers: toWire(this.markers),
1710
1713
  locale: this.locale,
1711
1714
  ...(this.kind ? { type: this.kind } : {}),
1715
+ ...(round ? { round: round.token } : {}),
1712
1716
  // A member linked on this base co-owns the report; the `vkb_` key stays the bearer.
1713
1717
  ...(member ? { memberToken: member } : {}),
1714
1718
  ...contextField(this.context),
@@ -69,6 +69,8 @@ export interface ReportEnvelope {
69
69
  memberToken?: string;
70
70
  /** The host's claimed context (context.ts, vt-9515), already validated; absent when the map is empty. */
71
71
  context?: ReportContext;
72
+ /** The test round this browser holds (round.ts, vt-3094), absent on its first report: the report joins it while it stands. */
73
+ round?: string;
72
74
  }
73
75
  export interface SubmitReply {
74
76
  status: 'filed' | 'quarantined';
@@ -146,7 +148,7 @@ export declare class ReportJob {
146
148
  * The create leg, answering with the member link the accepted body carried
147
149
  * ('' none). A vitrinka older than an optional field refuses it by name;
148
150
  * the reporter's word (`type`), the member link (`memberToken`) and the host's context (`context`) are
149
- * optional, the report is not, so it goes again without each field named,
151
+ * optional, and so is the test round (`round`); the report is not, so it goes again without each field named,
150
152
  * once. A refusal naming nothing still in the body fails the leg.
151
153
  */
152
154
  private create;
@@ -35,6 +35,7 @@
35
35
  */
36
36
  import { api, permanentStatus, uploadTo, VitrinkaApiError } from '../recorder/api';
37
37
  import { EVENTS_PER_POST } from './engine';
38
+ import { keepRound } from './round';
38
39
  /**
39
40
  * The top-level field a vitrinka refused as unknown — a 400 whose body names
40
41
  * it (`json: unknown field "<name>"`, its quotes escaped once more inside the
@@ -78,7 +79,7 @@ export async function deadline(what, ms, work) {
78
79
  }
79
80
  }
80
81
  /** What a report carries when its capture could not be prepared. */
81
- export const EMPTY_CAPTURE = { chunks: [], truncated: false, console: [], network: [] };
82
+ export const EMPTY_CAPTURE = { chunks: [], truncated: false, console: [], network: [], journey: [] };
82
83
  /**
83
84
  * The capture a report sends, under its deadline like every leg (reading an
84
85
  * earlier load's stored windows can hang): past it, or failed, the report
@@ -138,12 +139,14 @@ export class ReportJob {
138
139
  const edits = { title: env.title, description: env.description, markers: env.markers, notify: env.notify ?? false };
139
140
  const editsKey = JSON.stringify(edits);
140
141
  if (!this.id) {
141
- const { res, memberSent } = await this.create(env);
142
+ const { res, memberSent, roundSent } = await this.create(env);
142
143
  if (typeof res.id !== 'string' || !res.id)
143
144
  throw new Error('vitrinka: the server filed the report without an id');
144
145
  this.id = res.id;
145
146
  this.custody = res.custody === 'direct' ? 'direct' : 'quarantined';
146
147
  this.sent = editsKey;
148
+ // The round the report was filed into: its token rides the next report.
149
+ keepRound(this.target, res.round, roundSent);
147
150
  if (typeof res.memberError === 'string' && res.memberError)
148
151
  onMemberRefusal?.(res.memberError, memberSent);
149
152
  }
@@ -173,7 +176,7 @@ export class ReportJob {
173
176
  * The create leg, answering with the member link the accepted body carried
174
177
  * ('' none). A vitrinka older than an optional field refuses it by name;
175
178
  * the reporter's word (`type`), the member link (`memberToken`) and the host's context (`context`) are
176
- * optional, the report is not, so it goes again without each field named,
179
+ * optional, and so is the test round (`round`); the report is not, so it goes again without each field named,
177
180
  * once. A refusal naming nothing still in the body fails the leg.
178
181
  */
179
182
  async create(env) {
@@ -181,7 +184,7 @@ export class ReportJob {
181
184
  for (;;) {
182
185
  try {
183
186
  const res = await this.call('POST', '/api/v1/reports', body);
184
- return { res, memberSent: body.memberToken ?? '' };
187
+ return { res, memberSent: body.memberToken ?? '', roundSent: body.round ?? '' };
185
188
  }
186
189
  catch (e) {
187
190
  const field = refusedField(e);
@@ -195,6 +198,12 @@ export class ReportJob {
195
198
  const { memberToken: _dropped, ...rest } = body;
196
199
  body = rest;
197
200
  }
201
+ else if (field === 'round' && body.round !== undefined) {
202
+ // A vitrinka before test rounds (vt-3094): the report files on its own.
203
+ console.warn('vitrinka: this server keeps no test rounds yet — sending the report without one');
204
+ const { round: _dropped, ...rest } = body;
205
+ body = rest;
206
+ }
198
207
  else if (field === 'context' && body.context !== undefined) {
199
208
  // The host's claimed context is optional like the rest (vt-9515); a signed `ctx` claim rides the token and is not dropped.
200
209
  console.warn('vitrinka: this server takes no report context yet; sending the report without it');
@@ -225,7 +234,7 @@ export class ReportJob {
225
234
  }
226
235
  async sendCapture() {
227
236
  const id = encodeURIComponent(this.id);
228
- const { chunks, truncated } = this.capture;
237
+ const { chunks, truncated, journey } = this.capture;
229
238
  for (const c of chunks) {
230
239
  if (this.blobKeys.has(c.seq))
231
240
  continue;
@@ -242,6 +251,13 @@ export class ReportJob {
242
251
  payload: { count: c.count, source: 'replay', truncated },
243
252
  blobKey: this.blobKeys.get(c.seq) ?? '',
244
253
  }));
254
+ // The journey's rows follow the replay's (vt-3094), each at its own time:
255
+ // vitrinka walks a report's session by time. Without a replay there is no
256
+ // session to walk, so they stay behind.
257
+ if (chunks.length) {
258
+ for (const j of journey)
259
+ rows.push({ seq: rows.length + 1, ts: j.ts, tabHost: this.tabHost, kind: j.kind, payload: j.payload, blobKey: '' });
260
+ }
245
261
  while (this.rowsPosted < rows.length) {
246
262
  const batch = rows.slice(this.rowsPosted, this.rowsPosted + EVENTS_PER_POST);
247
263
  await this.call('POST', `/api/v1/reports/${id}/events`, { events: batch });