mirror of
https://github.com/priyanshujain/sanderling.git
synced 2026-10-03 03:27:10 +00:00
ci: dispatch workflows for folio and the replay ui (#73)
* feat(runner): stop the step loop at the first violation on request
* feat(testrun): report violations as a typed error under exit-on-violation
* feat(cli): add --exit-on-violation and exit 2 when it fires
* docs(cli): document --exit-on-violation, --max-steps, and exit codes
* fix(web): enumerate and query across shadow roots in both producers
* test(chrome): compare both producers on a shadow-dom parity page
* test(browser): drive a canvas-under-shadow-root fixture end to end
* fix(web): select the focused field inside a shadow root before typing
* fix(web): report the pathname as the screen when there is no hash route
* fix(web): settle on dom quiescence instead of returning at body ready
* feat(replay-ui): add data-testid hooks the dogfood spec drives
* feat(replay-ui): add the dogfood spec sanderling runs against the replay ui
* fix(replay-ui): scope the screenshot property to the named state panel
* chore(make): add per-platform sanderling build targets
* ci: add dispatch workflows for folio and the replay ui
* docs: describe the dispatch workflows and how to read a failure
* ci(folio): give the ios leg its jdk, android sdk, just, and a clean app start
* refactor(web): use max for the settle budget
* ci: pin calibrated seeds, skip the flaky ios reinstall, bound every job
* ci: authenticate and pin the buf setup step
the anonymous release download hit the shared runner ip rate limit and
failed the job with 'socket hang up' after three retries.
* docs: record that canvas apps need a dom proxy to be text-fuzzable
* fix(ios): bound lifecycle rpcs and claim the target device
a launch the simulator rejects sent the xctest session into a recovery
chain that answered minutes late or never, and the rpc had no deadline,
so the run hung with no trace and no error. also take a per-udid flock:
a second run's reinstall lands under the first's live automation session
and wedges it.
* docs(ci): correct the ios hang wording and note the device lock
* refactor(verifier): derive the lastAction shape from one field list
both hosts must show a spec the same lastAction. one ordered list now
feeds the goja object and the json the web host installs, so they
cannot drift.
* fix(web): install lastAction in the page before extractors read it
state.lastAction was hardcoded null on web, so every property reading it
was silently vacuous: a correct property passed without ever firing.
* fix(web): carry element identity on actions and fix findAll on paths
an action's target was coordinates only, so a property matching on which
element was acted upon could never fire. ax.findAll([a,b]) also returned
nothing on web.
* fix(chrome): wait out a route transition before sampling facts
the tree stays byte-identical and quiet across a cross-fade, so both the
quiet timer and the unchanged-tree escape called it settled mid-flight
and extractors read two screens at once.
* fix: bound the pre-run app launch
launch happens before the runner starts, so --duration never covered it
and a wedged driver hung with no trace and no error.
* fix(folio): read balances from merged cards and treat unreadable as unknown
compose for web merges the whole accountcard subtree, so the balance
child never exists there and every card parsed as 0. the property then
compared 0 to 0 and fired on any submit, which is a false positive
generator. unknown is now null and null is vacuously true.
* test(folio): cover merged-card parsing and unknown balances
* ci(folio): make web an expect-the-bug leg
the web runtime can observe the double submit now, so the health gate
understates it. seed 1 finds it at step 109, 3 runs out of 3.
* docs(ci): explain why a submit tap landing on home is the bug
* fix(ios): read a StaticText's label as its text
AXValue was the only source for text, but a StaticText carries its
string in AXLabel, so nothing on screen had .text on ios: a spec reading
it saw everything on android and nothing here.
* docs(ci): correct the calibrated step ranges
* fix(folio): stop convicting on arithmetic float64 cannot hold
past 2^53 cents the gap between representable values is 128, so a real
1600-cent move reads back as something else and the equality is false
for a healthy submit as readily as a double one. also match parseCents:
a sign or an oversized amount is rejected, not read as an amount.
* test(folio): pin the safe-integer guard and its boundary
* docs: stop teaching the zero-default that caused a false alarm
* docs: write down the silent-vacuity failure modes
* feat(folio): tag the home total and the card transaction count
the total was the only untagged node on the screen, so the spec had to
sum cards and a clipped card broke the sum.
* fix(folio): read the app's own total and refuse contaminated windows
summing cards went null when one was clipped, and the null poisoned the
carrier for the rest of the run. the balance window also spanned every
transaction since the last home visit, so the property convicted on
deltas it could not attribute: the old web witness was 3.16x the typed
amount, not 2x.
* test(folio): pin the window rules and the count invariant
* fix(folio): never read a frame that shows two screens
android dumps a cross-fade with both screens in the tree. the route said
add-transaction while an unscoped find said home, so the oracle took a
half-rendered total as fresh and convicted on a tap that committed
nothing. one function now decides the route and returns null when the
frame is ambiguous.
* test(folio): cover transition frames, card readings and creation
* fix(folio): only disambiguate counts that came from merged text
the equal-length digit rule exists because web merges the card and an
account named -1 makes '12' ambiguous. a dedicated count node has
nothing to disambiguate, so applying it there threw away real evidence.
* ci(folio): pin the recalibrated seeds and drop android to a health gate
web 3 and ios 7 convict 3 runs out of 3 with an exactly 2x witness.
android convicts 2 in 5 because the same seed does not walk the same
trajectory there, so it proves the app runs instead.
* docs(ci): describe the two properties and why android cannot convict
* fix(android): wait out a route cross-fade before snapshotting
the dump could hold two screens at once, and the runner refuses to act
on such a tree, so a quarter of android steps applied no action and the
count varied per run: the same seed never walked the same trajectory.
the ios companion and the chrome driver already do this.
* ci(folio): let the android leg run far enough to see its conviction
* docs: only the repo owner merges
* ci(folio): a thrown predicate is not a conviction
exit 2 means the run recorded a violation, and a predicate that throws
is recorded as one too. so was newAccountBalanceIsZero, an unrelated
property in the same spec. the gate read the exit code and went green
with detection dead.
* ci: install idb-companion from its tap and stop interpolating inputs
idb-companion is not in homebrew-core, so the ios leg died before it
built anything. replay-ui expanded dispatch inputs into the shell.
* docs: correct the snippets and numbers that drifted from the code
* test(sidecar): pin that a slow read counts toward the stability streak
* fix(web): read the page's extractors only on steps that count
the page advances the spec's carriers when it evaluates, but the runner
applied the result only on non-transitional steps. a discarded step
moved the window forward anyway, so the next accepted pair bracketed two
transactions while counting one submit, and convicted a healthy app.
extractor errors now fail the run instead of leaving goja's values in
current against v8's in previous.
* fix(chrome): anchor the transition deadline when the dom goes quiet
it was anchored at script start, so a page that churned past the window
reached the check already expired and returned mid cross-fade. the
driver now publishes the idle timeout it needs, since the caller's 1s
could never spend the 800ms window.
* fix(web): fail on a partial extractor override
same mixed-producer hazard as the install error: some extractors hold
the page's value and the rest hold goja's, and a property comparing
across that split fires on a healthy app.
* docs: six of seven, the seventh is the stock property
* fix(folio): drop a name two cards answer to
homeTxnCountsOf keyed on the account name and let the last card win, so
two accounts the fuzzer named the same collapsed into one entry. a
reading that saw one Travel card and a later one that saw both then
subtracted two different accounts' counts, and
submitCommitsOneTransactionPerAction convicted a healthy app of
double-submitting. it is a gated property in folio-run.sh, so that reads
as "found the submit bug" over a card scrolling into view.
same rule createdAccountHasNonZeroBalance already applies: a name
nothing can attribute is no evidence. counted over every card, since an
unreadable twin spoils the identity too.
* perf(folio): read each frame once
every extractor asked routeOf, and routeOf does five ax.find calls. on
web each find walks the document and every shadow root beneath it, so
the spec cost 110 tree walks a step; homeCards was parsed four times
over. now 5 and once.
keyed on the identity of the state object because both hosts build a new
one per step and hand that one object to every getter, so it cannot
outlive its frame. holding the reference is what keeps that true rather
than likely.
* fix(web): keep an undefined reading's index through JSON
json has no undefined, so an extractor whose getter returned one had its
whole index dropped by JSON.stringify. that index then kept goja's
dump-derived value while its neighbours held the page's, and a property
comparing previous to current across the split fires on a healthy app.
folio has nine on(route, tag) extractors, so this was most extractors on
most steps.
each reading is wrapped in a {value} envelope: the drop now happens
inside the entry, and an absent value means the getter returned
undefined, which is what the goja host records for the same getter. a
json null would instead claim it returned null and x.current ===
undefined would answer differently on the two hosts.
* feat(verifier): report the registered extractor count
the web path needs it to check the page sent one reading per extractor.
* fix(runner): fail when the page reports fewer readings than extractors
the comment here already claimed a partial override was fatal. it was
not: the skipped check only catches indices outside the extractor list,
so a page reporting values for some extractors and not others left the
rest holding goja's reading of the dump with nothing said.
* test(browser): drive an undefined reading through the whole web path
four layers carry it: the page's envelope, the driver's unwrap, the
runner's count check and the verifier's decode. each has a unit test and
only a run proves they compose. goes red both ways, decoding an absent
value as null and dropping the envelope.
* fix(web): offer the aria roles a user activates
only role=button was in the tappable set, so link, checkbox, radio,
switch, tab, option, the menuitems and treeitem were invisible to the
enumeration however plain the control looked. the replay ui builds its
step rows as <li role="option">, and the spec dogfooding it had to
hand-write an action to reach them because no default verb could see a
single row.
both producers build the set from the same role list, since the parity
test compares them element by element.
* test(browser): tap a role-based control end to end
every control on the page is an <li role="option">, the shape the
replay ui gives its step rows, and the spec carries no action of its
own: the property firing is the evidence the default enumeration offered
a tap on one.
* fix(web): read aria-disabled as disabled
the enabled fact came off the disabled property, which only real form
controls have. it reads undefined on the role-based controls the
tappable set now covers, so every one of them looked enabled however
plainly it was marked otherwise, and the fuzzer would spend actions on
inert ones.
both producers answer the same two ways, and the parity fixture carries
a disabled row so the comparison covers it: reverting one side alone
names the element and the fact.
* docs(replay-ui): the enumeration reaches step rows now
the comment said role="option" is not in the tappable selector set,
which stopped being true a few commits ago. selectAStep stays, for the
reason the tab weight below it stays: one row among the page's clickable
elements is a thin chance, and both step-facing properties go vacuous on
a run that never selects one.
* test(runner): bound the last-action test by steps, not wall clock
100ms of wall clock against an assertion that two steps ran fatals under
load with "the web path never installed it", which reads as a
regression. every sibling test in the package uses a long duration and
MaxSteps.
* ci: run the kotlin tests in make test
RouteTransitionTest and the stability poll cover the android settle and
nothing in ci ran them. :sidecar:test needs no android sdk, checked by
running it with ANDROID_HOME pointed at nothing.
* fix(sidecar): measure the stability streak as observed quiet
parameterising pollUntilStable also moved the clock to the start of the
read that opened a run of identical snapshots, so a read's own duration
counted as quiet. the pre-existing caller polls a real uiautomator dump:
at 400ms a read, 750ms of required quiet became 250ms of observed quiet
and the poll settled in two reads instead of four.
the parameters stay, the semantics go back.
* test(sidecar): pin the transition cap by driving it
it asserted 1500 >= 700 + 300, two constants, which can only fail if
someone edits a constant. it now drives awaitSettledTree against a fade
that lands after 700ms and asserts it hands back the settled tree before
the cap. cut the cap to 1000 and it goes red.
* ci: pin buf-setup-action to a commit
it takes a token now, so a floating tag is a token handed to whatever
that tag moves to. note v1 there is a branch, not a tag, so the ref
lookup that resolves it is matching-refs/heads/v1.
* ci: declare least-privilege permissions
none of the three declared any, so each got the repository default.
release.yml and docs.yml already do this. all three only check out,
build, test and upload artifacts.
* ci: fail fast when a server never comes up
the readiness loops fell through silently after 30 tries, so a server
that never started surfaced as an opaque driver failure minutes later.
each now says what did not answer and on which port.
* ci(folio): a missing trace is not a verdict
with no trace the android gate ran its grep against ./trace.jsonl and
reported "never reached AddTransactionScreen, so it never got past
login", which is not what happened. the web and ios branches had the
same misdiagnosis on exit 0.
same class, one line up: the classifier's own failure was swallowed, so
with the evidence reader dead the gate printed a healthy run and exited
0.
* ci(replay-ui): skip a run directory with no trace
the summarise step is if: always(), and under github's bash -eo pipefail
an unmatched glob stays literal, the redirect fails, pipefail carries it
into the assignment and -e kills the step. so a failed fuzz run went red
twice, once for the real reason.
This commit is contained in:
70 files changed
+6656
-430
No files matched your search
+211
-27
@@ -188,13 +188,32 @@ function selectorFromString(selector: string): { css?: string; xpath?: string }
|
||||
return selectorFromObject({ [kind]: value });
|
||||
}
|
||||
|
||||
// deepQueryAll resolves a CSS selector against a root AND every shadow root
|
||||
// beneath it. querySelectorAll stops dead at a shadow boundary, and a canvas app
|
||||
// (Compose for Web mounts its canvas and its whole accessibility tree inside a
|
||||
// shadow root on the mount element) keeps its entire UI on the far side of one:
|
||||
// without this a spec sees four nodes and can neither enumerate a target nor
|
||||
// resolve a testTag. Light-DOM matches come first, then shadow content in walk
|
||||
// order. XPath has no equivalent, so `text:` selectors stop at the boundary.
|
||||
function deepQueryAll(selector: string, root: ParentNode): Element[] {
|
||||
const found: Element[] = [];
|
||||
const visit = (scope: ParentNode): void => {
|
||||
for (const element of Array.from(scope.querySelectorAll(selector))) found.push(element);
|
||||
for (const element of Array.from(scope.querySelectorAll<HTMLElement>("*"))) {
|
||||
if (element.shadowRoot) visit(element.shadowRoot);
|
||||
}
|
||||
};
|
||||
visit(root);
|
||||
return found;
|
||||
}
|
||||
|
||||
function queryElement(
|
||||
root: ParentNode,
|
||||
selector: unknown,
|
||||
): Element | null {
|
||||
if (typeof selector === "string") {
|
||||
const { css, xpath } = selectorFromString(selector);
|
||||
if (css) return root.querySelector(css);
|
||||
if (css) return deepQueryAll(css, root)[0] ?? null;
|
||||
if (xpath) {
|
||||
const result = document.evaluate(
|
||||
xpath,
|
||||
@@ -219,7 +238,7 @@ function queryElement(
|
||||
}
|
||||
if (selector && typeof selector === "object") {
|
||||
const { css, xpath } = selectorFromObject(selector as Record<string, string | boolean | undefined>);
|
||||
if (css) return root.querySelector(css);
|
||||
if (css) return deepQueryAll(css, root)[0] ?? null;
|
||||
if (xpath) {
|
||||
const result = document.evaluate(
|
||||
xpath,
|
||||
@@ -237,13 +256,27 @@ function queryElement(
|
||||
function queryAllElements(root: ParentNode, selector: unknown): Element[] {
|
||||
if (typeof selector === "string") {
|
||||
const { css, xpath } = selectorFromString(selector);
|
||||
if (css) return Array.from(root.querySelectorAll(css));
|
||||
if (css) return deepQueryAll(css, root);
|
||||
if (xpath) return evaluateXPathAll(xpath, root as Node);
|
||||
return [];
|
||||
}
|
||||
// A selector path: every match of the first segment is searched for the rest,
|
||||
// concatenated in walk order, mirroring FindAllBySelectorPath in
|
||||
// internal/hierarchy. Falling through to the object branch (as this did)
|
||||
// returned NOTHING for a path on web while native returned matches, so a spec
|
||||
// reading state.ax.findAll([{screen}, {row}]) saw an empty list on web and
|
||||
// every property over it passed by having nothing to check.
|
||||
if (Array.isArray(selector)) {
|
||||
const head = selector[0];
|
||||
if (head === undefined) return [];
|
||||
const heads = queryAllElements(root, head);
|
||||
if (selector.length === 1) return heads;
|
||||
const rest = selector.slice(1);
|
||||
return heads.flatMap((element) => queryAllElements(element, rest));
|
||||
}
|
||||
if (selector && typeof selector === "object" && !Array.isArray(selector)) {
|
||||
const { css, xpath } = selectorFromObject(selector as Record<string, string | boolean | undefined>);
|
||||
if (css) return Array.from(root.querySelectorAll(css));
|
||||
if (css) return deepQueryAll(css, root);
|
||||
if (xpath) return evaluateXPathAll(xpath, root as Node);
|
||||
}
|
||||
return [];
|
||||
@@ -265,7 +298,47 @@ function evaluateXPathAll(xpath: string, root: Node): Element[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
function elementHandle(element: Element): Record<string, unknown> {
|
||||
// SELECTOR_TAG is the key an ax element carries the selector it was found by,
|
||||
// the same key the goja host writes (internal/verifier/bindings.go tagSelector).
|
||||
// The shared serializer (runtime-entry.ts pointOf) reads it off an author
|
||||
// target, so a spec's Tap({ on: state.ax.find(...) }) reaches the runner naming
|
||||
// the control it acted on instead of a bare pair of coordinates. Without it
|
||||
// `lastAction.on` is empty on web for exactly the actions a spec authored.
|
||||
const SELECTOR_TAG = "__sanderlingSelector";
|
||||
|
||||
// selectorTag renders a selector argument in the canonical "k:v" grammar the
|
||||
// hierarchy package parses, chains joined by " > ". It mirrors
|
||||
// selectorStringFromJS in internal/verifier/marshal.go, so an element found by
|
||||
// the same selector is labelled with the SAME string on both hosts.
|
||||
function selectorTag(selector: unknown): string {
|
||||
if (typeof selector === "string") return selector;
|
||||
if (Array.isArray(selector)) {
|
||||
return selector
|
||||
.map(selectorTag)
|
||||
.filter((segment) => segment !== "")
|
||||
.join(" > ");
|
||||
}
|
||||
if (selector && typeof selector === "object") {
|
||||
const source = selector as Record<string, unknown>;
|
||||
return Object.keys(source)
|
||||
.filter((key) => key !== SELECTOR_TAG && source[key] !== undefined && source[key] !== null)
|
||||
.map((key) => `${key}:${String(source[key])}`)
|
||||
.join(" ");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// isEnabled answers the `enabled` fact. `.disabled` is a property only real form
|
||||
// controls have, so it reads undefined on the role-based controls the tappable
|
||||
// set now covers, and every one of them looked enabled however plainly it was
|
||||
// marked otherwise. internal/driver/chrome/driver.go answers the same two ways
|
||||
// for the dump the goja host reads.
|
||||
function isEnabled(element: Element): boolean {
|
||||
if ((element as HTMLButtonElement).disabled) return false;
|
||||
return element.getAttribute("aria-disabled") !== "true";
|
||||
}
|
||||
|
||||
function elementHandle(element: Element, selector: unknown): Record<string, unknown> {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const x = Math.round(rect.left + rect.width / 2);
|
||||
const y = Math.round(rect.top + rect.height / 2);
|
||||
@@ -283,7 +356,7 @@ function elementHandle(element: Element): Record<string, unknown> {
|
||||
desc: ariaLabel,
|
||||
class: (element as HTMLElement).className ?? "",
|
||||
clickable: true,
|
||||
enabled: !(element as HTMLButtonElement).disabled,
|
||||
enabled: isEnabled(element),
|
||||
focused: document.activeElement === element,
|
||||
x,
|
||||
y,
|
||||
@@ -299,12 +372,15 @@ function elementHandle(element: Element): Record<string, unknown> {
|
||||
...datasetCopy,
|
||||
},
|
||||
dataset: datasetCopy,
|
||||
find(selector: unknown): unknown {
|
||||
const child = queryElement(element, selector);
|
||||
return child ? elementHandle(child) : undefined;
|
||||
[SELECTOR_TAG]: selectorTag(selector),
|
||||
find(childSelector: unknown): unknown {
|
||||
const child = queryElement(element, childSelector);
|
||||
return child ? elementHandle(child, childSelector) : undefined;
|
||||
},
|
||||
findAll(selector: unknown): unknown[] {
|
||||
return queryAllElements(element, selector).map(elementHandle);
|
||||
findAll(childSelector: unknown): unknown[] {
|
||||
return queryAllElements(element, childSelector).map((child) =>
|
||||
elementHandle(child, childSelector),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -313,10 +389,12 @@ function buildAx(): unknown {
|
||||
return {
|
||||
find(selector: unknown): unknown {
|
||||
const element = queryElement(document, selector);
|
||||
return element ? elementHandle(element) : undefined;
|
||||
return element ? elementHandle(element, selector) : undefined;
|
||||
},
|
||||
findAll(selector: unknown): unknown[] {
|
||||
return queryAllElements(document, selector).map(elementHandle);
|
||||
return queryAllElements(document, selector).map((element) =>
|
||||
elementHandle(element, selector),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -353,13 +431,22 @@ if (typeof globalThis.addEventListener === "function") {
|
||||
});
|
||||
}
|
||||
|
||||
// lastAction is what the previous step actually did, pushed in by the Go runner
|
||||
// (internal/runner, via __sanderlingSetLastAction__) before each extractor
|
||||
// evaluation, in the shape internal/verifier/marshal.go builds for goja. The
|
||||
// page cannot derive it: only the runner knows whether the action it picked was
|
||||
// really applied, and under --generator llm the action is not picked here at
|
||||
// all. Hardcoding null here, as this file used to, makes every spec property
|
||||
// that reads state.lastAction vacuously true on web.
|
||||
let lastAction: unknown = null;
|
||||
|
||||
function buildState(): unknown {
|
||||
return {
|
||||
snapshots: {},
|
||||
ax: buildAx(),
|
||||
document,
|
||||
window,
|
||||
lastAction: null,
|
||||
lastAction,
|
||||
time: 0,
|
||||
logs: [],
|
||||
exceptions: capturedExceptions.slice(),
|
||||
@@ -405,6 +492,11 @@ const runtime = {
|
||||
// the host invoking the extractor/next-action callbacks.
|
||||
defineLockedGlobal("__sanderling__", runtime);
|
||||
|
||||
// The host calls this once per step, before __sanderlingExtractors__.
|
||||
defineLockedGlobal("__sanderlingSetLastAction__", (value: unknown) => {
|
||||
lastAction = value ?? null;
|
||||
});
|
||||
|
||||
// writable:false stops a page script from shadowing the runtime via plain
|
||||
// assignment (the realistic in-page threat). configurable:true is required so
|
||||
// unit tests sharing one process can reinstall a fake via defineProperty; a
|
||||
@@ -419,9 +511,18 @@ function defineLockedGlobal(name: string, value: unknown): void {
|
||||
});
|
||||
}
|
||||
|
||||
function evaluateExtractors(): Record<number, unknown> {
|
||||
// Each reading is wrapped in a {value} envelope because JSON has no undefined.
|
||||
// Written straight into the map, an extractor whose getter returned undefined
|
||||
// (folio's on(route, tag) off its own screen, which is most extractors on most
|
||||
// steps) had its whole INDEX dropped by JSON.stringify, and the host kept goja's
|
||||
// dump-derived reading for it while the rest held the page's. Inside the
|
||||
// envelope the same drop means "this getter returned undefined", which is what
|
||||
// the goja host records for the same getter; a JSON null would instead claim it
|
||||
// returned null, and `x.current === undefined` would answer differently on the
|
||||
// two hosts.
|
||||
function evaluateExtractors(): Record<number, { value?: unknown }> {
|
||||
const state = buildState();
|
||||
const result: Record<number, unknown> = {};
|
||||
const result: Record<number, { value?: unknown }> = {};
|
||||
for (let i = 0; i < extractors.length; i++) {
|
||||
const entry = extractors[i];
|
||||
if (!entry) continue;
|
||||
@@ -438,7 +539,7 @@ function evaluateExtractors(): Record<number, unknown> {
|
||||
extracting = false;
|
||||
}
|
||||
entry.currentValue = value;
|
||||
result[i] = sanitize(value);
|
||||
result[i] = { value: sanitize(value) };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -478,7 +579,22 @@ function sanitizeAt(value: unknown, depth: number, seen: WeakSet<object>): unkno
|
||||
// only how the DOM answers "is this clickable" / "is this editable", the two
|
||||
// facts with no direct DOM equivalent of the accessibility attributes native
|
||||
// platforms expose.
|
||||
const TAPPABLE_SELECTOR = 'a, button, input, select, textarea, [role="button"], [onclick]';
|
||||
//
|
||||
// TAPPABLE_ROLES are the ARIA roles whose whole contract is that a user
|
||||
// activates the element. Covering only role="button" left every other one
|
||||
// invisible to the enumeration, however plain the control looked: the replay UI
|
||||
// builds its step rows as <li role="option">, and the spec dogfooding it had to
|
||||
// hand-write an action to reach them because no default verb could see a single
|
||||
// row. internal/driver/chrome/driver.go resolves the same set for the hierarchy
|
||||
// dump the goja host reads, and the two are compared element by element by
|
||||
// TestHierarchy_DerivesTheSameFactsAsTheWebRuntime.
|
||||
const TAPPABLE_ROLES = [
|
||||
"button", "link", "checkbox", "radio", "switch", "tab", "option",
|
||||
"menuitem", "menuitemcheckbox", "menuitemradio", "treeitem",
|
||||
];
|
||||
const TAPPABLE_SELECTOR = `a, button, input, select, textarea, ${
|
||||
TAPPABLE_ROLES.map((role) => `[role="${role}"]`).join(", ")
|
||||
}, [onclick]`;
|
||||
const EDITABLE_SELECTOR = "input, textarea, [contenteditable]";
|
||||
|
||||
const NON_TEXT_INPUT_TYPES = [
|
||||
@@ -521,12 +637,78 @@ function pointOf(element: Element): Candidate {
|
||||
const HEAD_SELECTOR = "head, head *";
|
||||
|
||||
// targetElements is the walk the target list is built from: the document in
|
||||
// pre-order, minus the head subtree.
|
||||
// pre-order, minus the head subtree, with each shadow host's content spliced in
|
||||
// directly after the host. That is buildTree's order in
|
||||
// internal/driver/chrome/driver.go, and the two producers are compared element
|
||||
// by element in enumeration order.
|
||||
function targetElements(): HTMLElement[] {
|
||||
const inHead = new Set<Element>(Array.from(document.querySelectorAll(HEAD_SELECTOR)));
|
||||
return Array.from(document.querySelectorAll<HTMLElement>("*")).filter(
|
||||
(element) => !inHead.has(element),
|
||||
const walked: HTMLElement[] = [];
|
||||
expandShadowContent(
|
||||
Array.from(document.querySelectorAll<HTMLElement>("*")).filter(
|
||||
(element) => !inHead.has(element),
|
||||
),
|
||||
walked,
|
||||
);
|
||||
return walked;
|
||||
}
|
||||
|
||||
// expandShadowContent copies a tree-ordered element list into `into`, following
|
||||
// each host into its shadow root (and into nested hosts) as it goes.
|
||||
function expandShadowContent(elements: HTMLElement[], into: HTMLElement[]): void {
|
||||
for (const element of elements) {
|
||||
into.push(element);
|
||||
const shadow = element.shadowRoot;
|
||||
if (!shadow) continue;
|
||||
expandShadowContent(Array.from(shadow.querySelectorAll<HTMLElement>("*")), into);
|
||||
}
|
||||
}
|
||||
|
||||
// IDENTITY_KEYS is the ladder a target's selector is built from, mirroring
|
||||
// selectorForElement in internal/verifier/worker.go: the id first (where
|
||||
// Compose for Web lands a testTag), then data-testid, then the description.
|
||||
// Every key here is one the goja host's selector grammar already understands,
|
||||
// so the runner can re-resolve the target it names. `desc` reads the same three
|
||||
// attributes, in the same order, that the hierarchy dump folds into
|
||||
// content-desc (internal/driver/chrome/driver.go); reading fewer of them would
|
||||
// let a selector this side calls unique resolve to a different element on the
|
||||
// Go side, which re-routes the action to whatever the dump matched first.
|
||||
const IDENTITY_KEYS: ReadonlyArray<readonly [string, (element: HTMLElement) => string]> = [
|
||||
["id", (element) => element.id],
|
||||
["data-testid", (element) => element.dataset.testid ?? ""],
|
||||
[
|
||||
"desc",
|
||||
(element) =>
|
||||
element.getAttribute("aria-label") ||
|
||||
element.getAttribute("alt") ||
|
||||
element.getAttribute("title") ||
|
||||
"",
|
||||
],
|
||||
];
|
||||
|
||||
// selectorsFor names each enumerated element, or leaves it unnamed. A value is
|
||||
// only used when it occurs ONCE across the enumeration, so an action carrying
|
||||
// the selector can never be re-resolved onto a sibling that shares the value
|
||||
// (folio's Home screen has many AccountCards under one testTag). Unnamed
|
||||
// elements keep the coordinates-only behaviour the web host always had.
|
||||
function selectorsFor(elements: readonly HTMLElement[]): Array<string | undefined> {
|
||||
const counts = IDENTITY_KEYS.map(() => new Map<string, number>());
|
||||
for (const element of elements) {
|
||||
IDENTITY_KEYS.forEach(([, read], index) => {
|
||||
const value = read(element);
|
||||
if (!value) return;
|
||||
const seen = counts[index]!;
|
||||
seen.set(value, (seen.get(value) ?? 0) + 1);
|
||||
});
|
||||
}
|
||||
return elements.map((element) => {
|
||||
for (let index = 0; index < IDENTITY_KEYS.length; index++) {
|
||||
const [key, read] = IDENTITY_KEYS[index]!;
|
||||
const value = read(element);
|
||||
if (value && counts[index]!.get(value) === 1) return `${key}:${value}`;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
// collectTargets walks the document ONCE and reports every element with the facts
|
||||
@@ -534,16 +716,17 @@ function targetElements(): HTMLElement[] {
|
||||
// resolved by selector first so the DOM's answer to "clickable" and "editable"
|
||||
// stays expressed in CSS, as it always was.
|
||||
function collectTargets(): TargetElement[] {
|
||||
const clickable = new Set<Element>(Array.from(document.querySelectorAll(TAPPABLE_SELECTOR)));
|
||||
const clickable = new Set<Element>(deepQueryAll(TAPPABLE_SELECTOR, document));
|
||||
const editable = new Set<Element>(
|
||||
Array.from(document.querySelectorAll<HTMLElement>(EDITABLE_SELECTOR)).filter(
|
||||
isEditableElement,
|
||||
),
|
||||
(deepQueryAll(EDITABLE_SELECTOR, document) as HTMLElement[]).filter(isEditableElement),
|
||||
);
|
||||
return targetElements().map((element) => ({
|
||||
const elements = targetElements();
|
||||
const selectors = selectorsFor(elements);
|
||||
return elements.map((element, index) => ({
|
||||
...pointOf(element),
|
||||
selector: selectors[index],
|
||||
clickable: clickable.has(element),
|
||||
enabled: !(element as HTMLButtonElement).disabled,
|
||||
enabled: isEnabled(element),
|
||||
editable: editable.has(element),
|
||||
scrollable: isScrollable(element),
|
||||
}));
|
||||
@@ -601,6 +784,7 @@ export const __testing__ = {
|
||||
evaluateExtractors,
|
||||
selectorFromString,
|
||||
selectorFromObject,
|
||||
selectorTag,
|
||||
xpathStringLiteral,
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user