@reticlehq/engine 3.8.2 → 3.10.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.
Files changed (46) hide show
  1. package/dist/disagreement/body-failures.js +16 -2
  2. package/dist/disagreement/contradiction-evidence.d.ts +119 -0
  3. package/dist/disagreement/contradiction-evidence.js +360 -48
  4. package/dist/disagreement/contradiction-types.d.ts +25 -0
  5. package/dist/disagreement/contradictions.d.ts +17 -1
  6. package/dist/disagreement/contradictions.js +146 -78
  7. package/dist/disagreement/echo-mismatch.js +205 -32
  8. package/dist/disagreement/stale-response.d.ts +10 -1
  9. package/dist/disagreement/stale-response.js +122 -47
  10. package/dist/evidence/already-true.d.ts +1 -1
  11. package/dist/evidence/already-true.js +13 -7
  12. package/dist/evidence/baseline.d.ts +1 -0
  13. package/dist/evidence/baseline.js +28 -12
  14. package/dist/evidence/blind-spots.d.ts +20 -3
  15. package/dist/evidence/blind-spots.js +127 -21
  16. package/dist/evidence/step-effect.d.ts +5 -0
  17. package/dist/evidence/step-effect.js +5 -2
  18. package/dist/evidence/verified.d.ts +23 -0
  19. package/dist/evidence/verified.js +53 -2
  20. package/dist/question/declared.d.ts +27 -0
  21. package/dist/question/declared.js +64 -13
  22. package/dist/question/predicate/net-blind-spots.d.ts +40 -1
  23. package/dist/question/predicate/net-blind-spots.js +110 -1
  24. package/dist/question/predicate/predicate-animation.d.ts +52 -0
  25. package/dist/question/predicate/predicate-animation.js +258 -0
  26. package/dist/question/predicate/predicate-compare.js +53 -26
  27. package/dist/question/predicate/predicate-element.d.ts +20 -2
  28. package/dist/question/predicate/predicate-element.js +207 -45
  29. package/dist/question/predicate/predicate-eval-kit.d.ts +2 -0
  30. package/dist/question/predicate/predicate-eval-kit.js +19 -0
  31. package/dist/question/predicate/predicate-eval.d.ts +1 -4
  32. package/dist/question/predicate/predicate-eval.js +41 -47
  33. package/dist/question/predicate/predicate-parse.js +132 -4
  34. package/dist/question/predicate/predicate-route.js +81 -27
  35. package/dist/question/predicate/predicate-schema.js +84 -34
  36. package/dist/question/predicate/predicate-session.d.ts +5 -0
  37. package/dist/question/predicate/predicate.js +119 -50
  38. package/dist/question/predicate/truncated-body-advice.d.ts +5 -0
  39. package/dist/question/predicate/truncated-body-advice.js +25 -0
  40. package/dist/state-bookkeeping.d.ts +24 -0
  41. package/dist/state-bookkeeping.js +31 -0
  42. package/dist/window/event-filters.d.ts +64 -0
  43. package/dist/window/event-filters.js +149 -20
  44. package/dist/window/network-detail-merge.d.ts +6 -0
  45. package/dist/window/network-detail-merge.js +43 -2
  46. package/package.json +3 -3
@@ -44,6 +44,122 @@ const GENERIC_EXAMPLE = '{ kind: "text", contains: "Saved" }';
44
44
  function exampleFor(kind) {
45
45
  return EXAMPLES[kind] ?? GENERIC_EXAMPLE;
46
46
  }
47
+ /** The one example a refusal ends with: the agent's own predicate corrected, else the kind's sample. */
48
+ function exampleSentence(kind, corrected) {
49
+ return corrected === undefined
50
+ ? `A valid ${kind} predicate looks like: ${exampleFor(kind)}`
51
+ : `The corrected ${kind} predicate from your call: ${corrected}`;
52
+ }
53
+ /**
54
+ * The field that holds the value a kind checks. An unknown field's string value goes here when the
55
+ * agent left it empty. `element` holds it in `query.text`. Kinds not listed get no correction.
56
+ */
57
+ const PRIMARY_FIELD = {
58
+ [PredicateKind.TEXT]: 'contains',
59
+ [PredicateKind.ROUTE]: 'pathname',
60
+ [PredicateKind.NET]: 'urlContains',
61
+ [PredicateKind.SIGNAL]: 'name',
62
+ [PredicateKind.ANIMATION]: 'name',
63
+ [PredicateKind.CONSOLE]: 'contains',
64
+ [PredicateKind.STATE]: 'path',
65
+ };
66
+ /** `"200"` → 200 and `"true"` → true, the two type mistakes with one reading. */
67
+ const NUMERIC = /^-?\d+(\.\d+)?$/;
68
+ const BOOLEANS = { true: true, false: false };
69
+ /** A string value as the number or boolean the schema wanted, or undefined when it is not one. */
70
+ function readTyped(value, expected) {
71
+ if ('string' !== typeof value) {
72
+ return undefined;
73
+ }
74
+ if ('number' === expected && NUMERIC.test(value)) {
75
+ return Number(value);
76
+ }
77
+ if ('boolean' === expected) {
78
+ return BOOLEANS[value];
79
+ }
80
+ return undefined;
81
+ }
82
+ /** The predicate with the kind's check value set to `text`, or undefined for a kind with none. */
83
+ function withPrimary(kind, candidate, text) {
84
+ if (PredicateKind.ELEMENT === kind) {
85
+ return candidate['query'] === undefined ? { ...candidate, query: { text } } : undefined;
86
+ }
87
+ const field = PRIMARY_FIELD[kind];
88
+ if (field === undefined || candidate[field] !== undefined) {
89
+ return undefined;
90
+ }
91
+ return { ...candidate, [field]: text };
92
+ }
93
+ /**
94
+ * One corrected predicate built from the agent's own values, as JSON, or undefined.
95
+ *
96
+ * Unknown fields are removed, and the first one that holds a string becomes the kind's check value.
97
+ * A number or boolean written as a string is read as one. Call arguments (`ref`, `action`) are never
98
+ * used as the check value. When any value the agent wrote would be lost, there is no correction:
99
+ * a predicate that checks less than the agent asked for is not a correction.
100
+ */
101
+ function correctedFromCall(input, issues) {
102
+ if ('object' !== typeof input || null === input || Array.isArray(input)) {
103
+ return undefined;
104
+ }
105
+ const kind = kindAsWritten(input);
106
+ if ('string' !== typeof kind || 0 === predicateFieldsFor(kind).length) {
107
+ return undefined;
108
+ }
109
+ // On `element` a `ref` is the target. Removed, the check would find any element, not that one.
110
+ if (PredicateKind.ELEMENT === kind && input['ref'] !== undefined) {
111
+ return undefined;
112
+ }
113
+ let candidate = { ...input };
114
+ delete candidate[KIND_ALIAS];
115
+ candidate['kind'] = kind;
116
+ const donors = [];
117
+ for (const issue of issues) {
118
+ const field = issue.path[0];
119
+ if (z.ZodIssueCode.unrecognized_keys === issue.code && 0 === issue.path.length) {
120
+ for (const key of issue.keys) {
121
+ const value = candidate[key];
122
+ delete candidate[key];
123
+ if (CALL_LEVEL_FIELDS.includes(key)) {
124
+ continue;
125
+ }
126
+ if ('string' !== typeof value) {
127
+ return undefined;
128
+ }
129
+ donors.push(value);
130
+ }
131
+ continue;
132
+ }
133
+ // A refinement on the whole predicate, or a missing field: the parse at the end decides.
134
+ if (0 === issue.path.length || ('string' === typeof field && candidate[field] === undefined)) {
135
+ continue;
136
+ }
137
+ if (1 !== issue.path.length || 'string' !== typeof field) {
138
+ return undefined;
139
+ }
140
+ const typed = readTyped(candidate[field], 'expected' in issue ? issue.expected : undefined);
141
+ if (typed === undefined) {
142
+ return undefined;
143
+ }
144
+ candidate[field] = typed;
145
+ }
146
+ for (const field of CALL_LEVEL_FIELDS) {
147
+ delete candidate[field];
148
+ }
149
+ if (1 < donors.length) {
150
+ return undefined;
151
+ }
152
+ const [donor] = donors;
153
+ if (donor !== undefined) {
154
+ const filled = withPrimary(kind, candidate, donor);
155
+ if (filled === undefined) {
156
+ return undefined;
157
+ }
158
+ candidate = filled;
159
+ }
160
+ const parsed = PredicateSchema.safeParse(candidate);
161
+ return parsed.success ? JSON.stringify(parsed.data) : undefined;
162
+ }
47
163
  /** `path: ["net","urlContains"]` → `net.urlContains`; an empty path means the object itself. */
48
164
  function pathOf(issue) {
49
165
  return 0 === issue.path.length ? 'the predicate' : issue.path.map(String).join('.');
@@ -110,6 +226,7 @@ function onlyChildBlamed(input, issues) {
110
226
  const value = undefined === index ? container : container?.[Number(index)];
111
227
  return undefined === value ? undefined : { path: head, value };
112
228
  }
229
+ const NOTHING_RAN = 'Nothing ran — the predicate was not evaluated, so no verdict was produced.';
113
230
  export function parsePredicate(input) {
114
231
  const unfilled = placeholderValue(input);
115
232
  if (unfilled !== undefined) {
@@ -132,15 +249,20 @@ export function parsePredicate(input) {
132
249
  throw new Error(`${child.path}: ${error.message}`);
133
250
  }
134
251
  }
252
+ // A refused bare string carries its own readings, so nothing about kinds is added to it.
253
+ if ('string' === typeof input) {
254
+ const said = parsed.error.issues.map((issue) => issue.message).join('; ');
255
+ throw new Error(`that predicate did not parse: ${said}. ${NOTHING_RAN}`);
256
+ }
135
257
  const asWritten = kindAsWritten(input);
136
258
  const kind = 'string' === typeof asWritten ? asWritten : 'unknown';
137
259
  // Bounded on purpose: a union rejection can produce one issue per member, and pasting all of them
138
260
  // back is how the zod array became unreadable in the first place.
139
261
  const issues = parsed.error.issues.slice(0, 3).map(describeIssue).join('; ');
140
- throw new Error(`that predicate did not parse (kind "${kind}"): ${issues}. Nothing ran — the predicate was ` +
141
- `not evaluated, so no verdict was produced. ${accepted(kind, parsed.error.issues)}` +
262
+ throw new Error(`that predicate did not parse (kind "${kind}"): ${issues}. ${NOTHING_RAN} ` +
263
+ `${accepted(kind, parsed.error.issues)}` +
142
264
  `${misplacedCallFields(input)} ` +
143
- `A valid ${kind} predicate looks like: ${exampleFor(kind)}`);
265
+ exampleSentence(kind, correctedFromCall(input, parsed.error.issues)));
144
266
  }
145
267
  /**
146
268
  * Arguments of the CALL that agents write inside the predicate instead.
@@ -310,5 +432,11 @@ function accepted(kind, issues) {
310
432
  .join('');
311
433
  return `${kind} accepts: ${fields.join(', ')}.${nested}`;
312
434
  }
313
- return `"${kind}" is not a predicate kind — use one of: ${Object.values(PredicateKind).join(', ')}.`;
435
+ const kinds = Object.values(PredicateKind);
436
+ // `absent` is listed beside the kinds in the grammar, but it is a field. Say where it goes.
437
+ const takenBy = kinds.filter((each) => predicateFieldsFor(each).includes(kind));
438
+ const asField = 0 === takenBy.length
439
+ ? ''
440
+ : ` "${kind}" is a field of ${takenBy.join(', ')}: { kind: "${takenBy[0] ?? ''}", ..., ${kind}: … }.`;
441
+ return `"${kind}" is not a predicate kind — use one of: ${kinds.join(', ')}.${asField}`;
314
442
  }
@@ -31,29 +31,34 @@ export const RouteDecidedBy = {
31
31
  * about where the app is, which is the failure this predicate exists to prevent.
32
32
  */
33
33
  export function routePathOf(pathname, hash) {
34
- if (!hash.startsWith('#/'))
34
+ if (!hash.startsWith('#/')) {
35
35
  return pathname;
36
+ }
36
37
  const withoutHash = hash.slice(1);
37
38
  const query = withoutHash.indexOf('?');
38
39
  return -1 === query ? withoutHash : withoutHash.slice(0, query);
39
40
  }
40
41
  function asPayload(value) {
41
- if (null === value || 'object' !== typeof value || Array.isArray(value))
42
+ if (null === value || 'object' !== typeof value || Array.isArray(value)) {
42
43
  return undefined;
44
+ }
43
45
  return value;
44
46
  }
45
47
  function payloadOf(eventOrData) {
46
- if (eventOrData['type'] === EventType.ROUTE_CHANGE)
48
+ if (eventOrData['type'] === EventType.ROUTE_CHANGE) {
47
49
  return asPayload(eventOrData['data']);
50
+ }
48
51
  // A different event: refuse rather than read whatever happened to sit in `data`.
49
- if (undefined !== eventOrData['type'] && undefined !== eventOrData['data'])
52
+ if (undefined !== eventOrData['type'] && undefined !== eventOrData['data']) {
50
53
  return undefined;
54
+ }
51
55
  return eventOrData;
52
56
  }
53
57
  function partsFromPayload(data) {
54
58
  const docPath = str(data['pathname']) ?? str(data['to']);
55
- if (docPath === undefined)
59
+ if (docPath === undefined) {
56
60
  return undefined;
61
+ }
57
62
  const hash = str(data['hash']) ?? '';
58
63
  const search = str(data['search']) ?? '';
59
64
  return {
@@ -83,21 +88,25 @@ export function routeOfEvent(eventOrData) {
83
88
  * parse is returned untouched rather than lost.
84
89
  */
85
90
  function withoutIdentityParams(value) {
86
- if ('string' !== typeof value)
91
+ if ('string' !== typeof value) {
87
92
  return value;
93
+ }
88
94
  const isSearch = value.startsWith('?');
89
95
  if (isSearch) {
90
96
  const params = new URLSearchParams(value);
91
- for (const name of Object.values(RETICLE_URL_PARAM))
97
+ for (const name of Object.values(RETICLE_URL_PARAM)) {
92
98
  params.delete(name);
99
+ }
93
100
  const rest = params.toString();
94
101
  return 0 === rest.length ? '' : `?${rest}`;
95
102
  }
96
- if (!URL.canParse(value))
103
+ if (!URL.canParse(value)) {
97
104
  return value;
105
+ }
98
106
  const parsed = new URL(value);
99
- for (const name of Object.values(RETICLE_URL_PARAM))
107
+ for (const name of Object.values(RETICLE_URL_PARAM)) {
100
108
  parsed.searchParams.delete(name);
109
+ }
101
110
  return parsed.toString();
102
111
  }
103
112
  /**
@@ -107,15 +116,50 @@ function withoutIdentityParams(value) {
107
116
  */
108
117
  function searchWithoutIdentityParams(search) {
109
118
  const query = search.startsWith('?') ? search.slice(1) : search;
110
- if ('' === query)
119
+ if ('' === query) {
111
120
  return '';
121
+ }
112
122
  // Pair by pair, not through URLSearchParams: its round trip re-encodes what it keeps (`%20` comes
113
123
  // back as `+`), so a hand-written startPath `/search?q=red%20shirt` would stop matching a tab on
114
124
  // exactly that URL. Only Reticle's own pairs are removed; the rest keep their spelling.
115
125
  const ours = new Set(Object.values(RETICLE_URL_PARAM));
116
- const kept = query.split('&').filter((pair) => !ours.has(paramNameOf(pair)));
126
+ const kept = query
127
+ .split('&')
128
+ .filter((pair) => !ours.has(paramNameOf(pair)))
129
+ .map((pair) => withoutNestedIdentityParams(pair, ours));
117
130
  return 0 === kept.length ? '' : `?${kept.join('&')}`;
118
131
  }
132
+ /**
133
+ * An app pair whose value is itself a path with a query (`redirect=%2F%3F__reticle_session%3D…`),
134
+ * with our params taken out of that inner query. A login redirect carries the page the tab came
135
+ * from, lease param and all, and a saved startPath sent the replay back to an old lease. A pair
136
+ * with none of our params keeps its spelling.
137
+ */
138
+ function withoutNestedIdentityParams(pair, ours) {
139
+ const at = pair.indexOf('=');
140
+ if (at < 0) {
141
+ return pair;
142
+ }
143
+ let value;
144
+ try {
145
+ value = decodeURIComponent(pair.slice(at + 1).replaceAll('+', ' '));
146
+ }
147
+ catch {
148
+ return pair;
149
+ }
150
+ const q = value.indexOf('?');
151
+ if (q < 0) {
152
+ return pair;
153
+ }
154
+ const inner = value.slice(q + 1).split('&');
155
+ const keptInner = inner.filter((p) => !ours.has(paramNameOf(p)));
156
+ if (keptInner.length === inner.length) {
157
+ return pair;
158
+ }
159
+ const path = value.slice(0, q);
160
+ const rebuilt = 0 === keptInner.length ? path : `${path}?${keptInner.join('&')}`;
161
+ return `${pair.slice(0, at)}=${encodeURIComponent(rebuilt)}`;
162
+ }
119
163
  /** The decoded name of one `name=value` query pair, or the raw text when it does not decode. */
120
164
  function paramNameOf(pair) {
121
165
  const raw = pair.split('=', 1)[0] ?? '';
@@ -136,8 +180,9 @@ function routeEvidence(data) {
136
180
  }
137
181
  /** Same shape from a session URL (the fallback when the tab hard-loaded and emitted no route event). */
138
182
  export function routeOfUrl(url) {
139
- if (!URL.canParse(url))
183
+ if (!URL.canParse(url)) {
140
184
  return undefined;
185
+ }
141
186
  const parsed = new URL(url);
142
187
  return partsFromPayload({
143
188
  pathname: parsed.pathname,
@@ -164,6 +209,23 @@ function readCurrentRoute(url) {
164
209
  data: routeEvidence({ pathname, search, hash, url, decidedBy: RouteDecidedBy.CURRENT }),
165
210
  };
166
211
  }
212
+ /** The route from the last route change in the window, else from the session's URL, else none. */
213
+ function latestRouteReading(last, currentUrl) {
214
+ const changed = last === undefined ? undefined : routeOfEvent(last);
215
+ if (changed !== undefined && last !== undefined) {
216
+ return {
217
+ pathname: changed.docPath,
218
+ routePath: changed.routePath,
219
+ full: changed.full,
220
+ decidedBy: RouteDecidedBy.CHANGE,
221
+ data: routeEvidence({ ...last.data, decidedBy: RouteDecidedBy.CHANGE }),
222
+ };
223
+ }
224
+ if (currentUrl === undefined || 0 === currentUrl.length) {
225
+ return undefined;
226
+ }
227
+ return readCurrentRoute(currentUrl);
228
+ }
167
229
  /** Name the source in the prose too — the structured `decidedBy` is for the agent, this is for a log. */
168
230
  function describeRouteSource(reading) {
169
231
  return reading.decidedBy === RouteDecidedBy.CHANGE
@@ -185,18 +247,7 @@ currentUrl,
185
247
  since = 0) {
186
248
  const routes = events.filter((e) => e.type === EventType.ROUTE_CHANGE);
187
249
  const last = routes.at(-1);
188
- const changed = last === undefined ? undefined : routeOfEvent(last);
189
- const reading = changed !== undefined && last !== undefined
190
- ? {
191
- pathname: changed.docPath,
192
- routePath: changed.routePath,
193
- full: changed.full,
194
- decidedBy: RouteDecidedBy.CHANGE,
195
- data: routeEvidence({ ...last.data, decidedBy: RouteDecidedBy.CHANGE }),
196
- }
197
- : currentUrl === undefined || 0 === currentUrl.length
198
- ? undefined
199
- : readCurrentRoute(currentUrl);
250
+ const reading = latestRouteReading(last, currentUrl);
200
251
  if (reading === undefined) {
201
252
  // A navigation the SERVER never answered reads exactly like one the APP prevented, and only one
202
253
  // of those is the user's bug. See unansweredIn.
@@ -308,13 +359,16 @@ const ROUTE_SETTLE_ACTIVITY = new Set([
308
359
  */
309
360
  function unansweredIn(events, since) {
310
361
  const settled = new Set();
311
- for (const e of events)
312
- if (e.type === EventType.NET_REQUEST)
362
+ for (const e of events) {
363
+ if (e.type === EventType.NET_REQUEST) {
313
364
  settled.add(e.data['id']);
365
+ }
366
+ }
314
367
  const open = events.filter((e) => e.type === EventType.NET_PENDING && e.t >= since && !settled.has(e.data['id']));
315
368
  const first = open[0];
316
- if (first === undefined)
369
+ if (first === undefined) {
317
370
  return undefined;
371
+ }
318
372
  return {
319
373
  count: open.length,
320
374
  url: str(first.data['url']) ?? '(unknown url)',
@@ -48,45 +48,55 @@ function usedQueryFields(query) {
48
48
  // returns before `findBySource` is reached, so the predicate could pass for an element other than
49
49
  // the one the caller's source location identified. Unclaimed, it falls through to the residual
50
50
  // walk and is refused — exactly as `component` already is in the same position.
51
- if (query.scope !== undefined)
51
+ if (query.scope !== undefined) {
52
52
  used.add('scope');
53
- if (query.attrs !== undefined)
53
+ }
54
+ if (query.attrs !== undefined) {
54
55
  used.add('attrs');
55
- if (query.self !== undefined)
56
+ }
57
+ if (query.self !== undefined) {
56
58
  used.add('self');
59
+ }
57
60
  // A modifier of the text rule, not a locator: the browser honours it wherever it reads `text`, and
58
61
  // the residual text check below is already case-exact.
59
- if (query.matchCase !== undefined)
62
+ if (query.matchCase !== undefined) {
60
63
  used.add('matchCase');
64
+ }
61
65
  // The browser's `self` branch checks subtree text when supplied, but skips every other locator.
62
66
  // Mark only text as consumed so role/name/etc. remain residual checks on the returned descriptor.
63
- if (true === query.self)
67
+ if (true === query.self) {
64
68
  return query.text === undefined ? used : used.add('text');
69
+ }
65
70
  if (query.by !== undefined && query.value !== undefined) {
66
71
  used.add('by').add('value');
67
- if (QueryBy.ROLE === query.by)
72
+ if (QueryBy.ROLE === query.by) {
68
73
  used.add('name');
74
+ }
69
75
  // `by: "component"` resolves through `findByComponent`, which tries the source stamp first and
70
76
  // falls back to the component name — so a `source` written here IS consumed.
71
77
  if (QueryBy.COMPONENT === query.by) {
72
78
  used.add('component');
73
- if (query.source !== undefined)
79
+ if (query.source !== undefined) {
74
80
  used.add('source');
81
+ }
75
82
  }
76
83
  return used;
77
84
  }
78
85
  // The auto-anchor branch, reached only without `by`+`value`: `source` (precise) then `component`.
79
86
  if (query.component !== undefined || query.source !== undefined) {
80
87
  used.add('component');
81
- if (query.source !== undefined)
88
+ if (query.source !== undefined) {
82
89
  used.add('source');
90
+ }
83
91
  return used;
84
92
  }
85
- if (query.role !== undefined)
93
+ if (query.role !== undefined) {
86
94
  return used.add('role').add('name');
95
+ }
87
96
  for (const field of ['text', 'label', 'placeholder', 'testid', 'alt']) {
88
- if (query[field] !== undefined)
97
+ if (query[field] !== undefined) {
89
98
  return used.add(field);
99
+ }
90
100
  }
91
101
  return used;
92
102
  }
@@ -132,17 +142,39 @@ function isImage(element) {
132
142
  * keep matching it as well, so existing flows and recorded steps using `textbox` continue to match.
133
143
  */
134
144
  function matchesRole(actual, queried) {
135
- if (actual === queried)
145
+ if (actual === queried) {
136
146
  return true;
137
- if ('textbox' === queried && 'searchbox' === actual)
147
+ }
148
+ if ('textbox' === queried && 'searchbox' === actual) {
138
149
  return true;
150
+ }
139
151
  return false;
140
152
  }
153
+ /**
154
+ * The one name rule, on this side of the wire (#1839). The browser compares a name it CAN match
155
+ * through `exactVisibleText` - trim, collapse inner whitespace, compare in NFC - so a name the
156
+ * locator dropped and the engine enforces back here must answer the same question the same way,
157
+ * or a check flips its answer with the locator that carried it. Kept in step with
158
+ * `adapters/realm/browser/src/dom/text-match.ts` by hand: the engine cannot import the browser
159
+ * adapter, and moving the rule into core would move the wire contract for two lines.
160
+ */
161
+ function normaliseName(value) {
162
+ return withoutInvisibleFormat(value).replace(/\s+/g, ' ').trim().normalize('NFC');
163
+ }
164
+ /**
165
+ * The format characters a screen does not paint, the same set as `INVISIBLE_FORMAT` in the
166
+ * browser's `text-match.ts`. Keep the two in step for the reason above: a name or text the browser
167
+ * matched without them must not miss here.
168
+ */
169
+ const INVISIBLE_FORMAT = /[\u00ad\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;
170
+ function withoutInvisibleFormat(value) {
171
+ return value.replace(INVISIBLE_FORMAT, '');
172
+ }
141
173
  const RESIDUAL_CHECKS = {
142
174
  value: (element, want) => (element.value ?? '').trim() === want.trim(),
143
175
  role: (element, want) => matchesRole(element.role, want),
144
- name: (element, want) => element.name.trim() === want.trim(),
145
- text: (element, want) => (element.text ?? element.name).includes(want),
176
+ name: (element, want) => normaliseName(element.name) === normaliseName(want),
177
+ text: (element, want) => withoutInvisibleFormat(element.text ?? element.name).includes(withoutInvisibleFormat(want)),
146
178
  [ALT_FIELD]: (element, want) => {
147
179
  const alt = element.attrs?.[ALT_FIELD];
148
180
  return isImage(element) && alt !== undefined && alt.trim() === want.trim();
@@ -151,8 +183,9 @@ const RESIDUAL_CHECKS = {
151
183
  /** The query to send, asking the browser to project `alt` when this side has to check it. */
152
184
  export function withAltProjected(query, checks) {
153
185
  const attrs = query.attrs ?? [];
154
- if (!checks.some(([field]) => ALT_FIELD === field) || attrs.includes(ALT_FIELD))
186
+ if (!checks.some(([field]) => ALT_FIELD === field) || attrs.includes(ALT_FIELD)) {
155
187
  return query;
188
+ }
156
189
  return { ...query, attrs: [...attrs, ALT_FIELD] };
157
190
  }
158
191
  /**
@@ -165,8 +198,9 @@ export function withAltProjected(query, checks) {
165
198
  */
166
199
  export function describeAltOnNonImage(checks, elements) {
167
200
  const wantsAlt = checks.some(([field]) => ALT_FIELD === field);
168
- if (!wantsAlt || 0 === elements.length || elements.some(isImage))
201
+ if (!wantsAlt || 0 === elements.length || elements.some(isImage)) {
169
202
  return undefined;
203
+ }
170
204
  const roles = [...new Set(elements.map((element) => element.role))].join(', ');
171
205
  return `${ALT_IMAGE_ONLY}, and the element matched is ${roles}, not ${IMAGE_ROLE}. ${ALT_USE_NAME}`;
172
206
  }
@@ -187,12 +221,15 @@ export function residualQueryChecks(query) {
187
221
  // question. Reading them off the query also means the set cannot drift from `ElementQuerySchema`.
188
222
  for (const field of Object.keys(query)) {
189
223
  const want = query[field];
190
- if (want === undefined || used.has(field))
224
+ if (want === undefined || used.has(field)) {
191
225
  continue;
192
- if ('string' === typeof want && RESIDUAL_CHECKS[field] !== undefined)
226
+ }
227
+ if ('string' === typeof want && RESIDUAL_CHECKS[field] !== undefined) {
193
228
  checks.push([field, want]);
194
- else
229
+ }
230
+ else {
195
231
  unusable.push(field);
232
+ }
196
233
  }
197
234
  return { checks, unusable };
198
235
  }
@@ -214,15 +251,22 @@ export function satisfiesResiduals(element, checks) {
214
251
  }
215
252
  /** How the element's own reading of a dropped field should be REPORTED back on a failure. */
216
253
  export function describeResidual(element, field) {
217
- const reading = 'value' === field
218
- ? (element.value ?? '')
219
- : 'text' === field
220
- ? (element.text ?? element.name)
221
- : 'role' === field
222
- ? element.role
223
- : ALT_FIELD === field
224
- ? (element.attrs?.[ALT_FIELD] ?? NO_ALT_ATTRIBUTE)
225
- : element.name;
254
+ let reading;
255
+ if ('value' === field) {
256
+ reading = element.value ?? '';
257
+ }
258
+ else if ('text' === field) {
259
+ reading = element.text ?? element.name;
260
+ }
261
+ else if ('role' === field) {
262
+ reading = element.role;
263
+ }
264
+ else if (ALT_FIELD === field) {
265
+ reading = element.attrs?.[ALT_FIELD] ?? NO_ALT_ATTRIBUTE;
266
+ }
267
+ else {
268
+ reading = element.name;
269
+ }
226
270
  return `${element.role} "${element.name}" ${field}=${JSON.stringify(reading)}`;
227
271
  }
228
272
  /**
@@ -234,8 +278,9 @@ export function describeResidual(element, field) {
234
278
  */
235
279
  export function predicateFieldsFor(kind) {
236
280
  const shape = shapeForKind(kind);
237
- if (null === shape)
281
+ if (null === shape) {
238
282
  return [];
283
+ }
239
284
  return Object.keys(shape).filter((field) => 'kind' !== field);
240
285
  }
241
286
  /**
@@ -301,8 +346,9 @@ export function predicateGrammar() {
301
346
  * none of these paths; that is exactly why they are worth a case each.
302
347
  */
303
348
  export function nestedKeysOf(schema) {
304
- if (undefined === schema)
349
+ if (undefined === schema) {
305
350
  return [];
351
+ }
306
352
  const inner = unwrapSchema(schema);
307
353
  // `instanceof z.ZodObject` narrows to ZodObject<any>, whose `.shape` is `any`. Name the shape
308
354
  // type so the keys are read off something typed rather than laundering an `any` through
@@ -313,8 +359,9 @@ export function nestedKeysOf(schema) {
313
359
  const options = inner.options;
314
360
  return [...new Set(options.flatMap((option) => nestedKeysOf(option)))];
315
361
  }
316
- if (!(inner instanceof z.ZodObject))
362
+ if (!(inner instanceof z.ZodObject)) {
317
363
  return [];
364
+ }
318
365
  return Object.keys(inner.shape);
319
366
  }
320
367
  /** Peel optional/nullable/default/pipe wrappers off a field to reach the schema underneath. */
@@ -348,15 +395,18 @@ function unwrapSchema(schema) {
348
395
  */
349
396
  export function predicateNestedFieldsFor(kind) {
350
397
  const shape = shapeForKind(kind);
351
- if (null === shape)
398
+ if (null === shape) {
352
399
  return {};
400
+ }
353
401
  const nested = {};
354
402
  for (const [field, schema] of Object.entries(shape)) {
355
- if ('kind' === field)
403
+ if ('kind' === field) {
356
404
  continue;
405
+ }
357
406
  const keys = nestedKeysOf(schema);
358
- if (0 < keys.length)
407
+ if (0 < keys.length) {
359
408
  nested[field] = keys;
409
+ }
360
410
  }
361
411
  return nested;
362
412
  }
@@ -87,6 +87,11 @@ export interface PredicateSession {
87
87
  * Optional: a fake that omits it gets its callback back unchanged.
88
88
  */
89
89
  keepCallerContext?: KeepCallerContextFn;
90
+ /**
91
+ * The commands the page DECLARED it can serve, from its hello. Undefined means the SDK is too old
92
+ * to declare anything, so silence is unknown — read to refuse an unserved command (#1990).
93
+ */
94
+ commands?: readonly string[] | undefined;
90
95
  }
91
96
  /**
92
97
  * The least time a page read is given, even at the very end of a budget: the final read at the