mirror of
https://github.com/priyanshujain/sanderling.git
synced 2026-10-04 03:57:09 +00:00
UX refactor (#52)
* feat(ltl): bound fields on AlwaysFormula and named thunks Add StepBound/Duration/Deadline to AlwaysFormula as the dual of bounded Eventually, give ThunkFormula a Name for stable identity, add ThunkNamed, and surface both in describe() and MarshalJSON. * feat(ltl): negation normal form pass nnf/pushNot rewrite a formula so every Not wraps only a Thunk or Error leaf, dualizing Always<->Eventually and preserving bounds. * feat(ltl): NNF in NewEvaluator, bounded-always, Finalize, collapse Apply nnf on construction, reduce bounded Always symmetric to bounded Eventually (vacuous holds once the window closes), add Finalize to resolve undischarged liveness obligations to Violated at run end, and collapse structurally-identical pending obligations. * test(ltl): property-based NNF laws Lock double-negation identity, Always/Eventually duality with bound preservation, leaf pushdown, and not(always true) reaching Violated. * test(ltl): Finalize, bounded eventually, latch, collapse Property tests for monotonic violation latch and eventually-within violating iff n consecutive false, plus Finalize and collapse cases. * feat(inspect): within clause on always residual node A negated bounded eventually serializes as a bounded always; render its bound instead of dropping it. * feat(ltl): witness violations and (bool,error) predicate thunks * test(ltl): migrate thunk call sites to (bool,error) * feat(ltl): flag thrown-predicate witnesses with IsError * refactor(verifier): replace predicate err side-channel with violation witness * test(verifier): witness API for thrown predicates * feat(trace): witnesses map and skipped-verification marker on Step * feat(runner): thread violation witnesses, finalize, skip marker into trace * test(ltl): lock violation witness reason, IsError, and step * test(verifier): finalize surfaces unmet eventually with witness * fix(ltl): eliminate implies and bounded-always false-negatives Rewrite a -> b to (not a) or b in NNF so a pending temporal antecedent can no longer defer the whole implication and drop a consequent that was false at the current step. Carry a pending inner past a bounded-Always window close instead of dropping it to holds, so a deferred obligation is resolved by a later step or Finalize. * test(ltl): lock implies and bounded-always false-negative regressions * fix(web-runtime): seed PRNG for reproducible runs and align weighted pick * feat(testrun): inject seed into web bundle via SANDERLING_SEED define * test: cover web-runtime seeded PRNG, weighted pick, and seed define wiring * test(spec): add Go math/rand/v2 PCG oracle and golden fixture * feat(spec): bit-exact PCG port of Go math/rand/v2 * test(spec): assert pcg.ts matches the PCG golden fixture * feat(spec): shared input corpus and press-key pools * feat(spec): action-tree types and Host interface * feat(spec): verb support matrix and warn-once helper * feat(spec): deterministic shared action picker * test(spec): verb matrix and warn-once semantics * test(spec): picker draw-order and determinism * refactor(spec): actions.ts returns pure GeneratorNode data trees * refactor(spec): wire from() sampling through the picker rng * feat(spec): shared runtime-entry installs next-action over pick.ts * feat(spec): export LongPress/Scroll/longPresses/scrolls factories * test(spec): assert data-tree shapes for action factories * test(spec): runtime-entry serializeAction wire-contract round-trip * refactor(spec): bridge data-tree nodes to the legacy goja picker tags * fix(spec): web runtime walks the spec's globalThis.actions data tree * test(spec): tolerate legacy bridge fields on builtin nodes * refactor(spec): installRuntime accepts a lazy root resolver The web bundle imports the runtime before the spec, so the action root on globalThis.actions only exists after the spec evaluates. Accept a function form so the goja and web hosts resolve the root per tick. * refactor(spec): web-runtime becomes the WEB Host, delegates to shared picker Delete the duplicate picker (resolveGenerator/pickWeighted/randomTap/ randomInput/randomSwipe/randomPressKey/pickFromArray, the mulberry32 PRNG, and the snake_case serializeAction) plus the __sanderling__ action factory binds. web-runtime now implements Host (platform/seedHi/seedLo from the injected 64-bit seed via BigInt, queryCandidates over the live DOM with a per-tick cache, reportUnsupported) and calls installRuntime so both engines run pick.ts over the same Pcg. Swipe/longPress/scroll follow the verbs.ts matrix instead of silently returning null. Keeps the DOM helpers (selector translation, queryElement, elementHandle, buildState, sanitize, extractors) and the global locking. Net -214 lines (741 -> 527). * test(spec): cover the WEB Host surface and seed precision Replace the deleted-picker tests with Host coverage: platform()==web, seedHi() parsing a 64-bit seed without Number precision loss, seedLo()==0, reportUnsupported warning, the installed next-action/extractor globals, and queryCandidates verb routing + per-tick caching over a querySelectorAll stub. * refactor(spec): picker emits native selector + scroll endpoints, setup precedence * feat(spec): goja runtime entry wires the shared picker over the Go host * feat(bundler): optional RuntimeFile prepends a runtime-entry import via stdin * feat(testrun): bundle the goja runtime entry so the verifier runs the shared picker * refactor(spec): drop the legacy goja bridge fields from action factories * feat(spec): serialize selector-only string targets for the runner to re-resolve * refactor(verifier): one DecodeAction reads the unified flat wire contract * refactor(verifier): goja host + shared picker replace the duplicate Go picker * refactor(runner): decode V8 actions via the unified DecodeAction; wire goja runtime * test(verifier): author specs through the shared picker path * test(runner): bundle authored specs with the goja runtime entry * feat(verifier): collect unsupported verbs for the run report * refactor(runner): collapse WebDriver forks behind ActionSource/ExtractorSource * feat(testrun): surface unsupported verbs in run report * test(verifier): cross-runtime goja/node parity gate on the shared picker * test(verifier): unsupported verbs collected deduped in first-seen order * test(runner): summary reports no unsupported verbs on a clean run * test(spec): golden-fixture cross-runtime parity gate for the node picker Replace the env-driven parity harness with a shared scenario module and a committed golden the node picker asserts independently. The goja side asserts the same golden, so neither runtime invokes the other at test time. * test(verifier): assert goja picker against the same cross-runtime golden Drop the node-subprocess coupling: the goja side now installs a stub __sanderlingHost__ with the fixed candidate list and asserts the committed golden, matching pkg/spec/test/parity.test.ts. * refactor(spec): rename pressKey generator export to pressKeys * refactor(spec): update barrel re-exports for pressKeys * test(spec): update pressKeys generator export name * docs(spec): rename pressKey generator to pressKeys * refactor(spec): extract samplerRng into shared sampler-rng module * feat(spec): add fluent seeded value generators (strings/integers/emails/edgeCaseText) * test(spec): cover fluent value generators determinism and chaining * refactor(bundler): inject globalThis trailer from spec named exports * refactor(bundler): reuse registration trailer in web bundler * test(bundler): cover named-export globalThis registration * feat(spec): add named() to Extracted handle type * feat(web-runtime): named() and cross-extractor read guard * feat(verifier): named() and cross-extractor read guard in goja * test(verifier): cross-extractor read guard and named() * test(web-runtime): export runtime and extractors for tests * test(web-runtime): named() and cross-extractor read guard * refactor(folio): drop manual globalThis trailer (bundler injects it) * refactor(folio): seed txn amounts via integers().between(1,500) * refactor(folio-web): drop manual globalThis trailer (bundler injects it) * fix(folio-web): seed card/txn-type selection via from().generate() for reproducible runs * refactor(folio-web): weight valid generators against edgeCaseText for names/amounts * refactor(folio-web): name extractors so violation witnesses are readable * fix(web-runtime): propagate extractor getter throws and unpoison locked global Stop swallowing getter errors in evaluateExtractors so the cross-extractor read guard aborts loudly, matching goja's PushSnapshot. Make the __sanderling__ lock configurable (still non-writable) so a shared test process can reinstall a fake. * test(spec): install fake runtime via defineProperty to survive locked global * test(web-runtime): assert uncaught cross-extractor read aborts evaluateExtractors * feat(runner): add MaxSteps bound to Options * test(runner): MaxSteps stops after exactly N steps * test(driverpb): drop proto getter round-trip tautology * test(sidecar): drop stub-mode placeholder tautology tests * test(mock): drop default-field-value assertion test * test(ltl): drop Verdict.String tautology tests * refactor(runner): extract RenderSummary for snapshot testing * test(runner): golden snapshots for trace stream and violation summary * feat(web-runtime): capture uncaught errors into state.exceptions * test(integration): add throwing and counter web fixtures * test(integration): add specs for the web fixtures * test(integration): drive web fixtures through the real pipeline in headless Chrome * chore(make): add test-browser target for the Chrome-driven suite * ci: run the Chrome-driven browser suite in a separate job * refactor(test): relocate browser suite to test/browser * refactor(permissions): delete dead internal/permissions package * refactor(test): rename package to browser_test * refactor(sidecarassets): rename internal/sidecar to internal/sidecarassets * chore(make): point test-browser at test/browser * docs(decisions): record internal/permissions deletion * refactor(doctor): use sidecarassets package * refactor(testrun): use sidecarassets package * fix(test): resolve testdata relative to browser_test.go * refactor(verifier): remove dead __sanderlingIndex compat alias * refactor(bundler): use encoding/json for JS string literals * docs(action-space): use vendor-neutral native driver wording * refactor(hierarchy): scrub backend tool name from comments * refactor(driver): scrub backend tool name from comments * refactor(driver): add DoubleTap and DoubleTapSelector to DeviceDriver * refactor(sidecar): implement DoubleTap with the sub-100ms inter-tap gap * refactor(chrome): implement DoubleTap as two taps with the gap * refactor(mock): record DoubleTap and DoubleTapSelector actions * refactor(runner): delegate double-tap to driver, drop gesture timing * test(runner): assert double-tap delegates to driver DoubleTap * docs(cmd): add package docs to CLI and developer tools * docs(driver): add package docs to driver interface and chrome backend * docs(driver): add package docs to mock and sidecar backends * docs(platform): add package docs to android and ios device prep * docs: add package docs to bundler and inspect * docs(ltl): add package doc to temporal logic evaluator * docs: add package docs to runner and testrun pipeline * docs: add package docs to trace and verifier * docs(sidecarassets): add package doc for embedded JAR loader * fix(chrome): add disable-dev-shm-usage so Chrome starts in CI * test(chrome): gate real-Chrome driver tests behind the browser tag * chore(make): run chrome driver tests in the browser job * fix(web-runtime): guard global error listeners for non-browser hosts The module registered window error/unhandledrejection listeners at top level, which threw under Node (the spec-api test runner) where globalThis.addEventListener is absent. Register only when the API exists; the real browser run is unaffected. * ci(browser): re-enable unprivileged user namespaces for headless Chrome ubuntu-latest moved to 24.04, whose AppArmor restriction on unprivileged user namespaces stops headless Chrome from opening its DevTools socket even with --no-sandbox, surfacing as the driver's 'websocket url timeout'. Relax the sysctl for the job and add a direct launch check so a future breakage shows Chrome's own stderr rather than an opaque driver timeout. * ci(browser): pin stable Chrome for the driver tests setup-chrome's default latest pulled a dev Chromium (150) whose remote debugging socket never came up under chromedp, while plain --dump-dom worked. Pin the stable channel, which the driver is tested against. * feat(defaults): add scroll and rebalance action weights Use relative-integer weights (taps/typing co-primary 100, scrolls 50, swipes 25, doubleTaps 10); the picker normalizes by their total. Adds scrolls to defaultActions as a first-class reveal behavior. * feat(defaults): trim scroll action weight wiring * fix(build): point sidecar jar ignore and embed paths at sidecarassets * test(defaults): drop stale longPresses re-export assertion longPresses is opt-in vocabulary, no longer re-exported from defaults/actions.ts since e0d3b20; its builtin resolution is already covered by api.test.ts. Trim the defaults test to scrolls, which is an actual default export. * fix(chrome): raise DevTools websocket read timeout to 60s Chrome cold-start on a loaded CI runner can exceed chromedp's 20s default for reading the DevTools websocket URL, flaking the browser tests with "websocket url timeout reached". Give launch more headroom.
This commit is contained in:
98 files changed
+6898
-2227
No files matched your search
+228
-300
@@ -2,36 +2,75 @@
|
||||
|
||||
// V8-side runtime for `sanderling test --platform web`.
|
||||
//
|
||||
// The user spec is bundled with this file as the first import so that
|
||||
// globalThis.__sanderling__ is installed before the spec evaluates. The host
|
||||
// invokes window.__sanderlingExtractors__() and window.__sanderlingNextAction__()
|
||||
// over CDP each tick. LTL predicates are intentionally stubbed: properties
|
||||
// run host-side in goja, which loads its own bundle of the same spec.
|
||||
// This file is the WEB Host. It installs globalThis.__sanderling__ (extract +
|
||||
// LTL formula binds) before the spec evaluates, implements the Host interface
|
||||
// (platform/seed/queryCandidates/reportUnsupported) over the live DOM, and then
|
||||
// delegates ALL action generation to the shared picker via installRuntime
|
||||
// (runtime-entry.ts -> pick.ts). The goja verifier runs the SAME picker over the
|
||||
// SAME Pcg, so a given seed yields an identical action stream by construction.
|
||||
//
|
||||
// Element references never cross V8/host. Action targets that reference an
|
||||
// AccessibilityElement collapse to `{x, y}` from getBoundingClientRect()
|
||||
// before serialization.
|
||||
// The host invokes window.__sanderlingExtractors__() and
|
||||
// window.__sanderlingNextAction__() over CDP each tick. LTL predicates are
|
||||
// stubbed: properties run host-side in goja, which loads its own bundle.
|
||||
//
|
||||
// Element references never cross V8/host. queryCandidates resolves each element
|
||||
// to a {x, y} Point via getBoundingClientRect before the picker sees it.
|
||||
|
||||
import { installRuntime } from "./runtime-entry.ts";
|
||||
import type { BuiltinVerb, Candidate, Host } from "./action-tree.ts";
|
||||
|
||||
interface Handle {
|
||||
current: unknown;
|
||||
previous: unknown;
|
||||
readonly current: unknown;
|
||||
readonly previous: unknown;
|
||||
named(name: string): Handle;
|
||||
}
|
||||
|
||||
interface ExtractorEntry {
|
||||
getter: (state: unknown) => unknown;
|
||||
handle: Handle;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ActionGeneratorHandle {
|
||||
__sanderlingActionGenerator: true;
|
||||
__sanderlingKind: string;
|
||||
generate?: () => unknown;
|
||||
entries?: readonly [number, ActionGeneratorHandle][];
|
||||
currentValue: unknown;
|
||||
previousValue: unknown;
|
||||
}
|
||||
|
||||
const extractors: ExtractorEntry[] = [];
|
||||
let actionsRoot: ActionGeneratorHandle | null = null;
|
||||
|
||||
// extracting is true only while an extractor getter is running. The current/
|
||||
// previous accessors consult it so a getter that reaches into another
|
||||
// extractor's handle throws instead of reading a stale cross-extractor value.
|
||||
let extracting = false;
|
||||
|
||||
function checkNotExtracting(slot: "current" | "previous"): void {
|
||||
if (extracting) {
|
||||
throw new Error(
|
||||
`reading .${slot} of an extractor inside another extractor is not allowed; extractor getters may read only from the state argument`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// SANDERLING_SEED is the host-computed 64-bit seed, injected as a decimal
|
||||
// string via the bundle define. We parse it into a BigInt without ever going
|
||||
// through a JS Number (which loses precision above 2^53), matching the goja
|
||||
// side's rand.NewPCG(seed, 0): hi = seed, lo = 0.
|
||||
function injectedSeed(): string | undefined {
|
||||
try {
|
||||
return process.env.SANDERLING_SEED;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function seedBigInt(): bigint {
|
||||
const raw = injectedSeed();
|
||||
if (!raw) return 0n;
|
||||
try {
|
||||
return BigInt(raw);
|
||||
} catch {
|
||||
return 0n;
|
||||
}
|
||||
}
|
||||
|
||||
const SEED_HI = seedBigInt();
|
||||
|
||||
function noopFormula(): unknown {
|
||||
const formula: Record<string, unknown> = { __sanderlingFormula: true };
|
||||
@@ -277,6 +316,38 @@ function buildAx(): unknown {
|
||||
};
|
||||
}
|
||||
|
||||
// Uncaught errors and unhandled rejections are buffered here as they fire, so
|
||||
// the default noUncaughtExceptions property can observe them. Without this the
|
||||
// web state.exceptions would always be empty and a page that throws would
|
||||
// silently pass.
|
||||
interface CapturedException {
|
||||
class: string;
|
||||
message: string;
|
||||
stackTrace: string;
|
||||
unixMillis: number;
|
||||
}
|
||||
|
||||
const capturedExceptions: CapturedException[] = [];
|
||||
|
||||
function recordException(error: unknown): void {
|
||||
const asError = error instanceof Error ? error : undefined;
|
||||
capturedExceptions.push({
|
||||
class: asError?.name ?? "Error",
|
||||
message: asError?.message ?? String(error),
|
||||
stackTrace: asError?.stack ?? "",
|
||||
unixMillis: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof globalThis.addEventListener === "function") {
|
||||
globalThis.addEventListener("error", (event: ErrorEvent) => {
|
||||
recordException(event.error ?? event.message);
|
||||
});
|
||||
globalThis.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) => {
|
||||
recordException(event.reason);
|
||||
});
|
||||
}
|
||||
|
||||
function buildState(): unknown {
|
||||
return {
|
||||
snapshots: {},
|
||||
@@ -286,91 +357,42 @@ function buildState(): unknown {
|
||||
lastAction: null,
|
||||
time: 0,
|
||||
logs: [],
|
||||
exceptions: [],
|
||||
exceptions: capturedExceptions.slice(),
|
||||
};
|
||||
}
|
||||
|
||||
const runtime = {
|
||||
extract<T>(getter: (state: unknown) => T, name?: string): Handle {
|
||||
const handle: Handle = { current: undefined, previous: undefined };
|
||||
const resolvedName = name && name.length > 0 ? name : `extractor_${extractors.length}`;
|
||||
extractors.push({
|
||||
const entry: ExtractorEntry = {
|
||||
getter: getter as (s: unknown) => unknown,
|
||||
handle,
|
||||
handle: undefined as unknown as Handle,
|
||||
name: resolvedName,
|
||||
});
|
||||
currentValue: undefined,
|
||||
previousValue: undefined,
|
||||
};
|
||||
const handle: Handle = {
|
||||
get current() {
|
||||
checkNotExtracting("current");
|
||||
return entry.currentValue;
|
||||
},
|
||||
get previous() {
|
||||
checkNotExtracting("previous");
|
||||
return entry.previousValue;
|
||||
},
|
||||
named(name: string): Handle {
|
||||
entry.name = name;
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
entry.handle = handle;
|
||||
extractors.push(entry);
|
||||
return handle;
|
||||
},
|
||||
always: noopFormula,
|
||||
now: noopFormula,
|
||||
next: noopFormula,
|
||||
eventually: noopFormula,
|
||||
actions(generator: () => unknown): ActionGeneratorHandle {
|
||||
const handle: ActionGeneratorHandle = {
|
||||
__sanderlingActionGenerator: true,
|
||||
__sanderlingKind: "actions",
|
||||
generate: generator,
|
||||
};
|
||||
if (!actionsRoot) actionsRoot = handle;
|
||||
return handle;
|
||||
},
|
||||
weighted(...entries: [number, ActionGeneratorHandle][]): ActionGeneratorHandle {
|
||||
const handle: ActionGeneratorHandle = {
|
||||
__sanderlingActionGenerator: true,
|
||||
__sanderlingKind: "weighted",
|
||||
entries,
|
||||
};
|
||||
actionsRoot = handle;
|
||||
return handle;
|
||||
},
|
||||
from<T>(items: readonly T[]): { generate: () => T | undefined } {
|
||||
return {
|
||||
generate(): T | undefined {
|
||||
if (items.length === 0) return undefined;
|
||||
return items[Math.floor(Math.random() * items.length)];
|
||||
},
|
||||
};
|
||||
},
|
||||
tap(p: { on: unknown }): unknown {
|
||||
return { kind: "Tap", on: p.on };
|
||||
},
|
||||
doubleTap(p: { on: unknown }): unknown {
|
||||
return { kind: "DoubleTap", on: p.on };
|
||||
},
|
||||
longPress(): unknown {
|
||||
// Why: web has no long-press gesture for v1; the factory returns null so LongPress() calls no-op.
|
||||
return null;
|
||||
},
|
||||
scroll(): unknown {
|
||||
// Why: web has no native scroll gesture for v1; the factory returns null so Scroll() calls no-op.
|
||||
return null;
|
||||
},
|
||||
inputText(p: { into: unknown; text: string }): unknown {
|
||||
return { kind: "InputText", into: p.into, text: p.text };
|
||||
},
|
||||
swipe(_p: { from: unknown; to: unknown; durationMillis?: number }): unknown {
|
||||
// Why: web has no swipe gesture; the factory returns null so Swipe() calls in specs no-op.
|
||||
return null;
|
||||
},
|
||||
pressKey(p: { key: string }): unknown {
|
||||
if (!WEB_PRESS_KEYS.includes(p.key)) {
|
||||
throw new Error(
|
||||
`pressKey: unsupported key ${JSON.stringify(p.key)} (allowed: ${WEB_PRESS_KEYS.join(", ")})`,
|
||||
);
|
||||
}
|
||||
return { kind: "PressKey", key: p.key };
|
||||
},
|
||||
wait(p: { durationMillis: number }): unknown {
|
||||
return { kind: "Wait", durationMillis: p.durationMillis };
|
||||
},
|
||||
taps: { __sanderlingActionGenerator: true, __sanderlingKind: "taps" } as ActionGeneratorHandle,
|
||||
doubleTaps: { __sanderlingActionGenerator: true, __sanderlingKind: "doubleTaps" } as ActionGeneratorHandle,
|
||||
longPresses: { __sanderlingActionGenerator: true, __sanderlingKind: "longPresses" } as ActionGeneratorHandle,
|
||||
scrolls: { __sanderlingActionGenerator: true, __sanderlingKind: "scrolls" } as ActionGeneratorHandle,
|
||||
typing: { __sanderlingActionGenerator: true, __sanderlingKind: "typing" } as ActionGeneratorHandle,
|
||||
swipes: { __sanderlingActionGenerator: true, __sanderlingKind: "swipes" } as ActionGeneratorHandle,
|
||||
waitOnce: { __sanderlingActionGenerator: true, __sanderlingKind: "waitOnce" } as ActionGeneratorHandle,
|
||||
pressKeys: { __sanderlingActionGenerator: true, __sanderlingKind: "pressKey" } as ActionGeneratorHandle,
|
||||
};
|
||||
|
||||
// Lock the runtime globals so a misbehaving (or malicious) page script can't
|
||||
@@ -378,11 +400,16 @@ const runtime = {
|
||||
// the host invoking the extractor/next-action callbacks.
|
||||
defineLockedGlobal("__sanderling__", runtime);
|
||||
|
||||
// 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
|
||||
// non-configurable lock would poison globalThis.__sanderling__ for every later
|
||||
// test in the run.
|
||||
function defineLockedGlobal(name: string, value: unknown): void {
|
||||
Object.defineProperty(globalThis, name, {
|
||||
value,
|
||||
writable: false,
|
||||
configurable: false,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
});
|
||||
}
|
||||
@@ -393,14 +420,19 @@ function evaluateExtractors(): Record<number, unknown> {
|
||||
for (let i = 0; i < extractors.length; i++) {
|
||||
const entry = extractors[i];
|
||||
if (!entry) continue;
|
||||
entry.handle.previous = entry.handle.current;
|
||||
entry.previousValue = entry.currentValue;
|
||||
// Let getter throws propagate, matching the goja side, where a getter
|
||||
// error aborts PushSnapshot rather than yielding undefined. Swallowing
|
||||
// here would silence the cross-extractor read guard (and every other
|
||||
// author error) on web only, breaking cross-engine parity.
|
||||
let value: unknown;
|
||||
extracting = true;
|
||||
try {
|
||||
value = entry.getter(state);
|
||||
} catch {
|
||||
value = undefined;
|
||||
} finally {
|
||||
extracting = false;
|
||||
}
|
||||
entry.handle.current = value;
|
||||
entry.currentValue = value;
|
||||
result[i] = sanitize(value);
|
||||
}
|
||||
return result;
|
||||
@@ -435,96 +467,21 @@ function sanitizeAt(value: unknown, depth: number, seen: WeakSet<object>): unkno
|
||||
return out;
|
||||
}
|
||||
|
||||
function pickWeighted(handle: ActionGeneratorHandle): ActionGeneratorHandle | null {
|
||||
const entries = handle.entries ?? [];
|
||||
if (entries.length === 0) return null;
|
||||
let total = 0;
|
||||
for (const [weight] of entries) total += Math.max(0, weight);
|
||||
if (total <= 0) return null;
|
||||
let pick = Math.random() * total;
|
||||
for (const [weight, generator] of entries) {
|
||||
pick -= Math.max(0, weight);
|
||||
if (pick <= 0) return generator;
|
||||
}
|
||||
return entries[entries.length - 1]?.[1] ?? null;
|
||||
}
|
||||
|
||||
function resolveGenerator(handle: ActionGeneratorHandle): unknown {
|
||||
switch (handle.__sanderlingKind) {
|
||||
case "actions": {
|
||||
const generated = handle.generate?.();
|
||||
return pickFromArray(generated);
|
||||
}
|
||||
case "weighted": {
|
||||
const inner = pickWeighted(handle);
|
||||
if (!inner) return null;
|
||||
return resolveGenerator(inner);
|
||||
}
|
||||
case "taps":
|
||||
return randomTap("Tap");
|
||||
case "doubleTaps":
|
||||
return randomTap("DoubleTap");
|
||||
case "typing":
|
||||
return randomInput();
|
||||
case "swipes":
|
||||
return randomSwipe();
|
||||
case "longPresses":
|
||||
case "scrolls":
|
||||
// Why: web has no long-press or native scroll gesture for v1; both no-op.
|
||||
return null;
|
||||
case "waitOnce":
|
||||
return { kind: "Wait", durationMillis: 500 };
|
||||
case "pressKey":
|
||||
return randomPressKey();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Per-tick cache so the 16-attempt retry loop in __sanderlingNextAction__
|
||||
// doesn't re-walk the DOM and re-flush layout on every iteration.
|
||||
let randomTapCandidates: HTMLElement[] | null = null;
|
||||
|
||||
function randomTap(kind: "Tap" | "DoubleTap"): unknown {
|
||||
if (!randomTapCandidates) {
|
||||
randomTapCandidates = Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
'a, button, input, select, textarea, [role="button"], [onclick]',
|
||||
),
|
||||
).filter((element) => {
|
||||
if ((element as HTMLButtonElement).disabled) return false;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
});
|
||||
}
|
||||
const candidates = randomTapCandidates;
|
||||
if (candidates.length === 0) return null;
|
||||
const picked = candidates[Math.floor(Math.random() * candidates.length)];
|
||||
if (!picked) return null;
|
||||
const rect = picked.getBoundingClientRect();
|
||||
return {
|
||||
kind,
|
||||
on: {
|
||||
x: Math.round(rect.left + rect.width / 2),
|
||||
y: Math.round(rect.top + rect.height / 2),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Per-tick cache mirroring randomTapCandidates, reset each NextAction tick.
|
||||
let randomInputCandidates: HTMLElement[] | null = null;
|
||||
// Per-verb DOM selector sets. The tappable set backs taps/doubleTaps/longPresses
|
||||
// (every tappable element is also a valid long-press target); the editable set
|
||||
// backs typing; swipes/scrolls target the scrollable element.
|
||||
const TAPPABLE_SELECTOR = 'a, button, input, select, textarea, [role="button"], [onclick]';
|
||||
const EDITABLE_SELECTOR = "input, textarea, [contenteditable]";
|
||||
|
||||
const NON_TEXT_INPUT_TYPES = [
|
||||
"button", "submit", "checkbox", "radio", "range", "color", "file", "image", "reset",
|
||||
];
|
||||
|
||||
// Edge-case input pool mirroring the goja-side inputCorpus: empty, whitespace,
|
||||
// overflow length, unicode, numeric boundaries, and common injection payloads.
|
||||
const WEB_INPUT_CORPUS = [
|
||||
"", "a", "a".repeat(4096), "🙂🔥💸", " ", "\t\n", "-1",
|
||||
"999999999999999999999", "0.0000001", "1e10", "'; DROP TABLE--",
|
||||
"<script>alert(1)</script>", "../../etc/passwd", "%s%n", "NaN",
|
||||
];
|
||||
function isVisible(element: HTMLElement): boolean {
|
||||
if ((element as HTMLButtonElement).disabled) return false;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
}
|
||||
|
||||
function isEditableElement(element: HTMLElement): boolean {
|
||||
if (element.isContentEditable) return true;
|
||||
@@ -537,141 +494,112 @@ function isEditableElement(element: HTMLElement): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function randomInput(): unknown {
|
||||
if (!randomInputCandidates) {
|
||||
randomInputCandidates = Array.from(
|
||||
document.querySelectorAll<HTMLElement>("input, textarea, [contenteditable]"),
|
||||
).filter((element) => {
|
||||
if (!isEditableElement(element)) return false;
|
||||
if ((element as HTMLInputElement).disabled) return false;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
});
|
||||
}
|
||||
const candidates = randomInputCandidates;
|
||||
if (candidates.length === 0) return null;
|
||||
const picked = candidates[Math.floor(Math.random() * candidates.length)];
|
||||
if (!picked) return null;
|
||||
const rect = picked.getBoundingClientRect();
|
||||
const text = WEB_INPUT_CORPUS[Math.floor(Math.random() * WEB_INPUT_CORPUS.length)];
|
||||
function pointOf(element: Element): Candidate {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
kind: "InputText",
|
||||
into: {
|
||||
x: Math.round(rect.left + rect.width / 2),
|
||||
y: Math.round(rect.top + rect.height / 2),
|
||||
},
|
||||
text,
|
||||
x: Math.round(rect.left + rect.width / 2),
|
||||
y: Math.round(rect.top + rect.height / 2),
|
||||
width: Math.round(rect.width),
|
||||
height: Math.round(rect.height),
|
||||
};
|
||||
}
|
||||
|
||||
function randomSwipe(): unknown {
|
||||
// Why: web has no swipe gesture; pointer drags into empty divs are noise.
|
||||
return null;
|
||||
function tappableCandidates(): Candidate[] {
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(TAPPABLE_SELECTOR))
|
||||
.filter(isVisible)
|
||||
.map(pointOf);
|
||||
}
|
||||
|
||||
const WEB_PRESS_KEYS = ["enter", "tab", "escape", "up", "down", "left", "right"];
|
||||
|
||||
function randomPressKey(): unknown {
|
||||
// Why: only emit keys with meaningful browser semantics; "back"/"home" don't navigate.
|
||||
const key = WEB_PRESS_KEYS[Math.floor(Math.random() * WEB_PRESS_KEYS.length)];
|
||||
return { kind: "PressKey", key };
|
||||
function editableCandidates(): Candidate[] {
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(EDITABLE_SELECTOR))
|
||||
.filter((element) => isEditableElement(element) && isVisible(element))
|
||||
.map(pointOf);
|
||||
}
|
||||
|
||||
function pickFromArray(value: unknown): unknown {
|
||||
if (!value) return null;
|
||||
if (!Array.isArray(value)) return value;
|
||||
if (value.length === 0) return null;
|
||||
return value[Math.floor(Math.random() * value.length)];
|
||||
}
|
||||
|
||||
function serializeAction(action: unknown): unknown {
|
||||
if (!action || typeof action !== "object") return null;
|
||||
const obj = action as Record<string, unknown>;
|
||||
switch (obj.kind) {
|
||||
case "Tap": {
|
||||
const point = pointOf(obj.on);
|
||||
if (!point) {
|
||||
console.warn("[sanderling] Tap target did not resolve to coordinates");
|
||||
return null;
|
||||
}
|
||||
return { kind: "Tap", x: point.x, y: point.y };
|
||||
// Scrollable candidates back swipe/scroll: elements that overflow their box,
|
||||
// plus the scrolling root so a page-level scroll always has a target.
|
||||
function scrollableCandidates(): Candidate[] {
|
||||
const root = document.scrollingElement ?? document.documentElement;
|
||||
const candidates: Candidate[] = root ? [pointOf(root)] : [];
|
||||
for (const element of Array.from(document.querySelectorAll<HTMLElement>("*"))) {
|
||||
if (element === root) continue;
|
||||
if (element.scrollHeight <= element.clientHeight && element.scrollWidth <= element.clientWidth) {
|
||||
continue;
|
||||
}
|
||||
case "DoubleTap": {
|
||||
const point = pointOf(obj.on);
|
||||
if (!point) {
|
||||
console.warn("[sanderling] DoubleTap target did not resolve to coordinates");
|
||||
return null;
|
||||
}
|
||||
return { kind: "DoubleTap", x: point.x, y: point.y };
|
||||
}
|
||||
case "InputText": {
|
||||
const point = pointOf(obj.into);
|
||||
if (!point) {
|
||||
console.warn("[sanderling] InputText target did not resolve to coordinates");
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "InputText",
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
text: obj.text ?? "",
|
||||
};
|
||||
}
|
||||
case "Swipe": {
|
||||
const from = pointOf(obj.from);
|
||||
const to = pointOf(obj.to);
|
||||
if (!from || !to) {
|
||||
console.warn("[sanderling] Swipe endpoints did not resolve to coordinates");
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "Swipe",
|
||||
from_x: from.x,
|
||||
from_y: from.y,
|
||||
to_x: to.x,
|
||||
to_y: to.y,
|
||||
duration_millis: obj.durationMillis ?? 250,
|
||||
};
|
||||
}
|
||||
case "LongPress":
|
||||
case "Scroll":
|
||||
// Why: web has no long-press or native scroll gesture for v1; drop the action.
|
||||
return null;
|
||||
case "PressKey":
|
||||
return { kind: "PressKey", key: obj.key };
|
||||
case "Wait":
|
||||
return { kind: "Wait", duration_millis: obj.durationMillis ?? 0 };
|
||||
default:
|
||||
return null;
|
||||
if (!isVisible(element)) continue;
|
||||
candidates.push(pointOf(element));
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function pointOf(value: unknown): { x: number; y: number } | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if (typeof obj.x === "number" && typeof obj.y === "number") {
|
||||
return { x: obj.x, y: obj.y };
|
||||
}
|
||||
return undefined;
|
||||
// Per-tick candidate cache: the picker's 16-attempt retry re-queries the same
|
||||
// verb, so we avoid re-walking the DOM and re-flushing layout within one tick.
|
||||
// installRuntime resets it before each __sanderlingNextAction__ invocation.
|
||||
const candidateCache = new Map<BuiltinVerb, Candidate[]>();
|
||||
|
||||
function resetCandidateCache(): void {
|
||||
candidateCache.clear();
|
||||
}
|
||||
|
||||
defineLockedGlobal("__sanderlingExtractors__", function (): Record<number, unknown> {
|
||||
return evaluateExtractors();
|
||||
});
|
||||
const host: Host = {
|
||||
platform: () => "web",
|
||||
seedHi: () => SEED_HI,
|
||||
// lo = 0 matches the goja side's rand.NewPCG(seed, 0).
|
||||
seedLo: () => 0n,
|
||||
queryCandidates(verb: BuiltinVerb): Candidate[] {
|
||||
const cached = candidateCache.get(verb);
|
||||
if (cached) return cached;
|
||||
let candidates: Candidate[];
|
||||
switch (verb) {
|
||||
case "taps":
|
||||
case "doubleTaps":
|
||||
case "longPresses":
|
||||
candidates = tappableCandidates();
|
||||
break;
|
||||
case "typing":
|
||||
candidates = editableCandidates();
|
||||
break;
|
||||
case "swipes":
|
||||
case "scrolls":
|
||||
candidates = scrollableCandidates();
|
||||
break;
|
||||
default:
|
||||
candidates = [];
|
||||
}
|
||||
candidateCache.set(verb, candidates);
|
||||
return candidates;
|
||||
},
|
||||
reportUnsupported(verb: BuiltinVerb): void {
|
||||
console.warn(`[sanderling] verb ${verb} is unsupported on web`);
|
||||
},
|
||||
};
|
||||
|
||||
defineLockedGlobal("__sanderlingNextAction__", function (): unknown {
|
||||
if (!actionsRoot) return null;
|
||||
// Reset per-tick caches so each invocation gets a fresh DOM scan.
|
||||
randomTapCandidates = null;
|
||||
randomInputCandidates = null;
|
||||
// Match the goja runtime: retry up to 16 times when a weighted entry's
|
||||
// generator returns []. Otherwise on routes where most generators are
|
||||
// gated to other pages, ~80% of ticks would emit no action.
|
||||
for (let attempt = 0; attempt < 16; attempt++) {
|
||||
const action = serializeAction(resolveGenerator(actionsRoot));
|
||||
if (action !== null) return action;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
// The spec assigns its action root to globalThis.actions, and it runs AFTER
|
||||
// this module (the web bundle imports the runtime first). Resolve the root
|
||||
// lazily so installRuntime captures it once the spec has evaluated. The root
|
||||
// resolver runs once per __sanderlingNextAction__ tick (before the retry loop),
|
||||
// so it is also where we reset the per-tick candidate cache.
|
||||
installRuntime(
|
||||
host,
|
||||
() => {
|
||||
resetCandidateCache();
|
||||
return (globalThis as { actions?: import("./action-tree.ts").GeneratorNode }).actions ?? null;
|
||||
},
|
||||
evaluateExtractors,
|
||||
);
|
||||
|
||||
// Test-only exports. The IIFE bundle the host installs has no export surface,
|
||||
// so these are stripped from production output; they only exist for unit tests.
|
||||
export const __testing__ = {
|
||||
host,
|
||||
seedBigInt,
|
||||
tappableCandidates,
|
||||
editableCandidates,
|
||||
scrollableCandidates,
|
||||
resetCandidateCache,
|
||||
runtime,
|
||||
extractors,
|
||||
evaluateExtractors,
|
||||
};
|
||||
|
||||
export {};
|
||||
Reference in new issue
Block a user