diff --git a/.changeset/browser-ui-tracker.md b/.changeset/browser-ui-tracker.md new file mode 100644 index 00000000..67aa4cb4 --- /dev/null +++ b/.changeset/browser-ui-tracker.md @@ -0,0 +1,7 @@ +--- +'@bugsee/browser': minor +'@bugsee/webview': minor +'@bugsee/trackers': minor +--- + +Browser and WebView `orientation`, `screen_size` and `fps` traces and the `orientation_changed` / `dark_mode_changed` events are now fed by one per-window singleton `UiTracker` (new in `@bugsee/trackers/browser`), which also exposes `viewport`, `colorScheme`, `reducedMotion` and `displayMode` stages. Trace and event names and wire shapes are unchanged. `orientation_changed` is now de-duplicated (one event per real orientation change) and also fires when only `screen.orientation` emits `change`. In `@bugsee/trackers`, `ApplicationEvents` loses its `orientationchange` key (a type change: the UiTracker owns it) and the emitter base gains `listenerCount` and an `onListenersChanged` hook. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 4404f983..af9a2c93 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -18,7 +18,7 @@ Read this first; then `docs/design/sdk-design.md` (Draft v3) for the full archit | `@bugsee/logger` | Debug logger (`debug.warn` etc.); platforms route `onError` here. | | `@bugsee/protocol` | Wire types (`RequestJson`, `EnvironmentEnvelope`, `NetworkEvent` superset incl. `'http'` mechanism, `NetworkStage`, `FileType`, `Mechanism`), `Severity` enum + level conversions, header/JSON/params sanitizers, shape redaction, **`BugseeOption` canonical identifiers + `optionsToWire` (dots → colons)**. | | `@bugsee/service` | The DI/IoC container: `createServiceContainer`/`defineService`/`Provider` (Firebase-component model, LAZY/EXPLICIT, lazy resolution, deps-via-container, `onInit`, late registration). The backbone of the **internal aggregated object** (see DI note below). | -| `@bugsee/trackers` | Tracker foundation below core (core imports + re-exports): `MultiKeyEmitterBase`/`createMultiKeyEmitter`, `Interceptor`/`EventSubscribable`, `InterceptorBase`, `createTrackerRegistry` (per-window singletons, `rebind`). Portable root; platform subpaths `./browser` (`PowerTracker`, `powerTrackerFor`, `resetPowerTracker`, `ConnectivityTracker`, `connectivityTrackerFor`, `resetConnectivityTracker`, `StorageTracker`, `storageTrackerFor`, `resetStorageTracker`, `hostRead`), plus reserved empty `./node` and `./electron`. | +| `@bugsee/trackers` | Tracker foundation below core (core imports + re-exports): `MultiKeyEmitterBase`/`createMultiKeyEmitter`, `Interceptor`/`EventSubscribable`, `InterceptorBase`, `createTrackerRegistry` (per-window singletons, `rebind`). Portable root; platform subpaths `./browser` (`PowerTracker`, `powerTrackerFor`, `resetPowerTracker`, `ConnectivityTracker`, `connectivityTrackerFor`, `resetConnectivityTracker`, `StorageTracker`, `storageTrackerFor`, `resetStorageTracker`, `UiTracker`, `uiTrackerFor`, `resetUiTracker`, `hostRead`), plus reserved empty `./node` and `./electron`. | ### Kernel — `@bugsee/core` (the thin kernel; runtime-portable) - **`Client`** (`createClient`) — composition root: identity/attributes via the single global `Environment`, manual capture (`addBreadcrumb`/`log`/`event`/`trace`/`logException`), provider/extension registration, lifecycle (`launch`/`isLaunched`/`stop`/`flush`). `flush()`/`stop()` await both `uploadPipeline.flush` AND in-flight **report promises** (the path that lets crash flush-then-exit deliver), bounded by an unref'd deadline. **Identity reaches the wire (audit fix A):** `setUserIdentifier` → `request.json.email` at assemble time (Android maps the user identifier to the `email` field — "email from global scope"; no separate `user` field, no `setEmail`). **Internal object / DI (Phase 1, `docs/design/internal-object-di.md`):** the Client now owns a per-process `ServiceContainer` (the "BugseeInternal" — the internal aggregated object); `addService`/`getService`/`getServiceProvider` (a typed `ServiceToken` facade over the generic `@bugsee/service` container — see §7 "DI token migration") + `getInternal(carrier)` reach it process-wide via the singleton client. **Phase 2 (delivers E) — redaction filters as the first real service:** a `filters` service (`FilterStore`) registered in the container; the facade `setNetworkEventFilter`/`setLogEventFilter`/`setBreadcrumbFilter`/`setReportHandler` mutate it; the capture pipeline (network/log providers, `addBreadcrumb`, the report path) reads it LIVE via `getFilters()` (the singleton client on the carrier). Filter = mutate or return null to DROP; a throwing filter drops (privacy-safe) + one `onError`. The user network filter REPLACES the built-in sanitizer (Android XOR); the default sanitizer is now gated on `CaptureNetworkDefaultSanitizer`. Report `before` mutates/vetoes before assembly. **Phase 3 (COMPLETE) — every platform seam is a container service, resolved by a typed `ServiceToken`:** Node `launch` creates the `ServiceContainer`, registers the HTTP `transport` (and the rest of the seams), resolves it to build the pipeline, and hands the SAME container to `createClient`; the client exposes `getService(TransportToken)`. Behavior-preserving (the `internalTagged`/override path is unchanged). The full token set, the `ServiceToken` migration (replacing the old `NameServiceMapping` declaration-merge), and the carrier-hosted service-manifest auto-registration path are in §7 "DI Phase 3 / token migration". **Lifecycle (audit fix B):** `logException` after `stop()` is a silent no-op (§1501) until re-launch (a `stopped` flag distinct from `!launched`, so pre-launch capture is unaffected). **Kill-state (audit fix D, §1435/§1504; REVISED — see the note below):** the collector's `KILL_SDK` code (`99099`) — and ONLY that — sets `BugseeError.fatal`, which `track()` observes on any report result and which flips the client PERMANENTLY dead: one-time `onError`, capture+detection halt, all capture/`logException` no-op, and `launch()` won't re-arm a killed client. **An HTTP 401/403 no longer kills the client.** It used to, on the theory that a 401/403 on session create meant an invalid app token — but the collector never answers that way: the appserver returns HTTP **200** with an envelope error code (`error.router.js:50` calls `res.code(200)` unconditionally), so an invalid token arrives as code `14019`, which classifies as `permanent` (drop this bundle) and not as `kill_sdk`. A raw 401/403 is therefore an infrastructure answer — a proxy, a WAF, an expiring session mid-upload — and killing the SDK on one silently ended capture for the rest of the process. It is now RETRYABLE. The collector-code namespace (`classifyServerErrorCode`, `transport.ts`) is disjoint from HTTP statuses and is the only thing that carries a control verdict; `BugseeError.code` is the HTTP status (`0` when no response was reached) and `BugseeError.serverCode` is the collector code. @@ -397,17 +397,18 @@ solid), in slices: are deleted** (`systemMetricsSampler` stays as a legacy override that REPLACES the heap/connection/orientation traces, as on Node; battery still runs). New `InterceptorBase` trackers in `packages/browser/src/trackers/`: `MemoryTracker` (the one `performance.memory` poll timer, started only on a subscriber and never where the engine has no `performance.memory`), `ConnectionTracker` (`online`/`offline` + `navigator.connection` - `change`; SUPERSEDED by the domain `ConnectivityTracker`, TR3: it owns its own window listeners and no longer subscribes to the lifecycle tracker), `OrientationTracker` (`screen.orientation` `change` + `orientationchange`). Producers: `MemoryProducer` + `change`; SUPERSEDED by the domain `ConnectivityTracker`, TR3: it owns its own window listeners and no longer subscribes to the lifecycle tracker), `OrientationTracker` (SUPERSEDED by the domain `UiTracker`, TR2; `screen.orientation` `change` + `orientationchange`). Producers: `MemoryProducer` (`ram_js_heap_*`, polled), `AdvertisedMemoryProducer` (`ram_system_advertised`), `ConnectionProducer`, `OrientationProducer` (event-driven, de-duplicated, held so the provider refresh keeps them in a rolling window). The producers read the LIVE `navigator`/`performance`/`screen`/`window` (`defaultBrowserTraceEnv()`); the old sampler copied `navigator` with a spread, which drops the prototype accessors (`onLine`, `connection`, `deviceMemory`) on a real browser. Launch passes its injected `window` and `scheduler`. The shared `PageLifecycleTracker` is done: the events source and the orientation tracker subscribe to it (connectivity no longer does: TR3 `ConnectivityTracker` owns its own window listeners). - **ST6a (DONE, `feat/electron-gpu-hardware-extras`):** GPU info is ENVIRONMENT data (`environment.hardware.gpu`), through a new `@bugsee/node` launch option `hardwareExtras` (`() => {gpu?: {vendor?, renderer?, gl_version?, gl_extensions?}} | undefined`), read LIVE on every `getEnvironment()` and merged by `buildNodeEnvironment` (typed key only, sanitized, closed fields always win, undefined/empty/throw adds nothing, a throw goes to `onError`). `@bugsee/electron` `launchMain` passes a `GpuInfoCache` closure: `app.getGPUInfo('basic')` is kicked once after the first launch (optional on `ElectronAppLike`), `.catch` omits + reports (no unhandledRejection), a generation token drops a late resolve after `client.stop()`. Mapping is DEFENSIVE and UNVERIFIED against a real Electron: the active device (or the sole device) `vendorString` -> `vendor`, `deviceString` -> `renderer`, then `auxAttributes` (`glVendor`/`glRenderer`/`glVersion`/`glExtensions` -> `vendor`/`renderer`/`gl_version`/`gl_extensions`, all strings, trimmed, blanks dropped) fills the gaps; never a name from a numeric id; nothing usable -> no field. `launchMain({gpuInfoType: 'basic' | 'complete'})` (default `'basic'`; `'complete'` is expected to carry the `auxAttributes` GL strings but is heavier — also unverified) picks the `getGPUInfo` argument. A caller `hardwareExtras` gpu overrides the cache FIELD-WISE (its non-empty fields win; a gpu that cleans to nothing or a throw leaves the cache's). `hardwareExtras` is a KEPT relaunch option (a public node/bun/deno seam, like `systemProbe`); A node/umbrella `relaunch()` in an Electron main keeps the `launchMain` wrapper: it keeps serving the cached GPU after a relaunch (`stop()` aborts the in-flight read but never clears a resolved value, so reports draining during stop still carry it); a GPU that had not yet resolved before the relaunch is not re-requested. On macOS/Linux `'basic'` commonly yields only numeric ids, so `hardware.gpu` may be ABSENT until confirmed on a real Electron; the default stays `'basic'` (unverifiable here) and `'complete'` is available via `gpuInfoType`. Still open: the ST6 Electron trace/event producers. -- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). ST4 has nothing left open (ST4c below). -- **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px — NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker — no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation — a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace — a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end − the first due time the block covered), so a block B ≥ 1 s reads between B−1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability ≈ 1 − B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor — sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag — UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned — a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design §13.3). +- **ST4a (DONE, `feat/browser-app-state-fps`):** `app_state` (`AppStateProducer`: `foreground`/`background`, held step trace; the viewer's table is `started`/`foreground`/`background`) and `fps` (`FpsTracker` (SUPERSEDED by the domain `UiTracker`, TR2) + `FpsProducer`: a `requestAnimationFrame` counter that runs ONLY while the page is visible — loop and timer torn down on hidden, a fresh window on visible, a zero-length window or no rAF emits nothing; nothing is reported before the first frame of a run, since rAF can be paused while the page says visible; afterwards the first frameless window is reported as 0 and a continuing stall goes quiet; no lifecycle = omitted). The traces env is now built from the INJECTED window + document (`browserTraceEnvFrom`; no fallback to `globalThis`, so a window without `performance.memory` omits the heap). **ST4b (DONE, `feat/browser-dark-freeze-events`):** `events.system` gains `dark_mode_changed` (`{dark}`; `matchMedia` taken from the INJECTED window, bound to it, per-attach guarded) and Page Lifecycle `freeze`/`resume` (document listeners via the shared `PageLifecycleTracker`). ST4 has nothing left open (ST4c below). +- **ST4c (DONE, `feat/browser-screen-size-main-thread-lag`):** `screen_size` (`ScreenSizeTracker` (SUPERSEDED by the domain `UiTracker`, TR2) + `ScreenSizeProducer`: value shape `{width, height, dpr}` in CSS px — NOT `displays`; held, de-duplicated step trace; initial value at start; re-read on `resize` (listened for on the injected window by the tracker — no new shared-lifecycle event, since nothing else consumes it and it would change every lifecycle subscriber's listener count) and `orientationchange` (via the shared lifecycle); omitted entirely when `screen` or `devicePixelRatio` is not a finite positive number; known staleness: moving the window to a monitor with the same DPR but a different size fires no `resize`, and iOS Safari's `screen.width/height` do not swap on rotation — a `(resolution: Xdppx)` matchMedia/`screen` change listener is a follow-up) and `main_thread_lag_ms` (`MainThreadLagTracker` + `MainThreadLagProducer`: TIMER DRIFT: on each 1 s scheduler tick on the page's main thread, `lag = max(0, now - (previousTickTime + intervalMs))` with the injected `performance.now`; the first tick compares against the run's start + interval; emitted EVERY tick as a polled (`hold:false`) trace — a measured ~0 is a true value. **What a reading means (measured in Chromium):** a tick fires late by (block end − the first due time the block covered), so a block B ≥ 1 s reads between B−1000 and B (1800 ms read 907..1797; 2500 ms read 1807), while a block shorter than 1 s that crosses no due tick reads exactly 0 (probability ≈ 1 − B/1000: ~30% for 700 ms, ~90% for 100 ms); one block is reported once (the next tick clamps to 0). It is NOT Node's ~10 ms event-loop monitor — sampling every 1000 ms is why short blocks can go unseen. Measured ONLY while visible: hidden tears the timer down and every visible start takes a FRESH baseline, so a hidden stretch never counts as lag. A throwing clock/scheduler at start rolls back; a throwing or non-finite clock at a tick is reported/skipped without reading the skipped interval as lag. No clock (`performance.now` must be a function), lifecycle, or a hidden page = omitted, no timer. **Honest limit:** long freezes are reported reliably, short jank only by luck; follow-ups if short jank matters: a finer internal timer reporting the MAX drift per 1 s window, or `PerformanceObserver('longtask')` where supported. Timer throttling the browser applies to a page that still says `visible` (occluded/minimised window, background tab without a `visibilitychange`) may also read as lag — UNVERIFIED, it could not be reproduced headless. **History:** a `MessageChannel` ping (re-arm on receipt, then once per tick) was built and rejected after measuring real Chromium: re-arming on receipt was a ~2.2M/s task loop, and a ping per tick reads ~0.1 ms for a block that starts after the ping returned — a plausible-healthy lie; it was deleted entirely, no `MessageChannel` in the traces env). Both are built under the same `env.lifecycle` gate as `app_state`/`fps`, so a `systemMetricsSampler` (`sensors:false`) replaces them too. Open: the viewer has no definition for either name yet (generic value block, design §13.3). +- **TR2 (DONE, `feat/ui-tracker`):** the domain **`UiTracker`** (`packages/trackers/src/browser/ui-tracker.ts`) absorbs and REPLACES the per-signal `OrientationTracker`/`ScreenSizeTracker`/`FpsTracker` (files + tests deleted from `@bugsee/browser`; `MainThreadLagTracker`/`MemoryTracker` stay for the Process tracker). Singleton per window via the registry (`uiTrackerFor(env, onError)`, keyed on `env.window`, else `env.screen`, else the env; `rebind` MERGES: defined env fields replace, undefined never clobber, a changed field re-attaches the affected sources; env fields are copied through `hostRead`, so a hostile getter costs only that field). Stages (notification kinds / payloads): `orientation` `{type?, angle?}` (invalid fields omitted; a bare `{}` when an orientation event fires but nothing is readable), `screenSize` `{width,height,dpr}`, `viewport` `{width,height}` (inner size), `colorScheme` `{dark}`, `reducedMotion` `{reduce}`, `displayMode` `{mode: fullscreen|standalone|minimal-ui|browser}`, `frameRate` (number, fps; same 1 s window / visible-only / first-frameless-window-is-0 semantics as the old FpsTracker). `current(stage)` reads LIVE (guarded, undefined when unavailable). **Per-stage activation:** the emitter gained `listenerCount(name)` + an `onListenersChanged()` hook; each source (window `resize`, `orientationchange` + `screen.orientation` `change`, `screen` `change`, one matchMedia query per scheme/motion/display-mode, and the rAF loop + interval + `visibilitychange` for `frameRate`) exists only while some subscriber wants a stage it feeds. **Retention rule:** only the env seams and the per-stage de-duplication baseline survive the last unsubscribe, and the baseline is silently RE-READ whenever a stage goes from no listener to one (even when its source stayed attached for a sibling stage) and when a rebind swaps the sources; a stage with no listener is never computed; frame-rate window state is dropped on stop. **Rebind:** a rebind onto new sources re-baselines every stage that still has listeners from the NEW sources (the swap itself is never announced as a change). Only a change of a SOURCE (window/screen/document/scheduler/intervalMs) re-attaches — detaching with the OLD seams first, and the interval is always cleared on the scheduler that armed it, with a loop-id guard on ticks; the function seams (matchMedia, rAF, cancelAnimationFrame, now) are swapped in place because every launch rebuilds them as fresh closures, so a repeated `uiTrackerFor` never resets a running fps window. `displayMode` is omitted (not 'browser') when a query failed and none of the answered ones matched. Own `visibilitychange` (NO page-lifecycle dependency), so the `ApplicationTracker` (ex page-lifecycle tracker) no longer has an `orientationchange` stage (removed once the UiTracker owned it; orientation, screen size, fps and dark mode do not subscribe to the lifecycle at all). Producers `orientation`/`screen_size`/`fps` and the `orientation_changed` / `dark_mode_changed` events now subscribe to the tracker (trace/event names and wire shapes unchanged; the producers keep their `env.lifecycle` gate for screen_size/fps). Behaviour notes: `orientation_changed` now also fires on a `screen.orientation` `change` (not only the window `orientationchange`), `ApplicationEvents` loses its `orientationchange` key (a type change), a document-only injected events env still takes the host `screen` (as before); `orientation_changed` is now de-duplicated (one event per real change instead of one per `orientationchange`), and the events source takes `screen` from the injected window (never the host's global when a window is injected). `dark_mode_changed` now also reads the baseline once at attach (a hostile `matchMedia` reports per read). No new traces yet for viewport/reducedMotion/displayMode (stages exist for producers to adopt). Known gap: a monitor change with the same DPR fires no `resize` (a `screen` `change` listener covers engines that emit it). - **TR4 (DONE, `feat/power-tracker`):** `BatteryTracker` became the domain **`PowerTracker`** (`packages/trackers/src/browser/power-tracker.ts`), a singleton per window via `createTrackerRegistry` (`powerTrackerFor(env, onError)`, keyed on `env.window`, else `env.navigator`, else the env object; host key reads are guarded and reported). It takes ONLY `getBattery` from the env; every call (a relaunch included) goes through the registry `rebind`, handing the shared tracker the latest launch's `onError` (a defined one replaces, undefined keeps; the reporter is a mutable indirection) and `getBattery` (a defined one replaces; a tracker that had none kicks the request at once if running). It exposes a SINGLE `state` stage (rather than one per Battery Status event): `{level?, charging, chargingTimeS?, dischargingTimeS?}`, published on `levelchange`/`chargingchange`/`chargingtimechange`/`dischargingtimechange`. Omitted, never fabricated: a `level` that is not a number in [0,1] (so no `battery` trace, never NaN); non-finite or negative times; a zero `chargingTime` when full and charging (a battery-less desktop reports level 1, charging, 0); a zero `dischargingTime`. A throwing time getter costs only that field. **Retention rule (tested):** the resolved BatteryManager and the last snapshot survive the last unsubscribe (no second `getBattery()`); the DOM listeners do not, and re-attach with a fresh snapshot on the next subscriber. A `getBattery()` in flight at stop is ignored and re-requested next activation. `BatteryProducer` keeps `battery`/`charging` unchanged and adds `battery_charging_time_s`/`battery_discharging_time_s` (integer seconds). **Held-value disappearance rule:** the provider's held values cannot be retracted (it re-records them every `refreshMs`), so the two time traces use plain non-held `emit` with a producer-side change-only guard; a vanished time records nothing and is forgotten (a stale estimate is never refreshed). Consequence: an unchanged time AGES OUT of the rolling capture window; owner decision pending on a retract/release or end-marker mechanism. -- **TR1 (DONE, `feat/application-tracker`; design §15):** `PageLifecycleTracker` is now the domain **`ApplicationTracker`** (`packages/trackers/src/browser/application-tracker.ts`). Stages: `pagehide`, `visibility`, `freeze`, `resume`, plus the NEW aggregated `state` (`{state: 'foreground'|'background'}`, Android vocabulary, emitted when a visibility change CHANGES it) and `current()` (read live from the document, else the retained value; undefined when never known — an unreadable document emits no `state`, never a fabricated background). **Singleton per key** via `createTrackerRegistry`: `applicationTrackerFor(env, onError?)` keys by the document, else the window, else one shared key; a window-only env and a window+document env are DISTINCT trackers (pair a document with its own window); `resetApplicationTracker(env)` is exported from `@bugsee/trackers/browser` for internal/test use and is NOT re-exported by `@bugsee/browser`. Browser + webview launch and the events-source fallback obtain it through the registry. **Retention rule (tested):** DOM listeners attach on the first subscriber and detach on the last, the last known `state` is retained and recomputed silently from the document on re-activation, so the first subscriber after a gap is correct at once and the de-dup baseline is never stale. `AppStateProducer` now takes the tracker only (`on('state')` + `current()` for the initial value); trace/event names and wire shapes are unchanged. **Keying rule:** document, else window, else one module key (design §15.1 #5 will be amended from "one per window" to this). **Latest launch wins** through the registry `rebind`: a defined `onError` replaces the shared reporter (undefined keeps it); while IDLE the window/document are merged (a target the request omits is kept), while ACTIVE the binding is kept and a window/document mismatch (only a target the request supplies is compared; the error names which) is reported once. The shared sink is never released on stop: a relaunch with no `onError` keeps the previous launch's (accepted limitation). `resetApplicationTracker` is `@internal` test/teardown use: exported from `@bugsee/trackers/browser` but not re-exported by `@bugsee/browser` (`reset()` removes all subscribers). An unreadable document emits neither `visibility` nor `state` (no fabricated `process_background`/fps pause). **Stays for later:** `online`/`offline` (move to Connectivity, TR3) and `orientationchange` (UI/Display, TR2) remain stages on this tracker so ConnectionTracker/OrientationTracker are untouched. +- **TR1 (DONE, `feat/application-tracker`; design §15):** `PageLifecycleTracker` is now the domain **`ApplicationTracker`** (`packages/trackers/src/browser/application-tracker.ts`). Stages: `pagehide`, `visibility`, `freeze`, `resume`, plus the NEW aggregated `state` (`{state: 'foreground'|'background'}`, Android vocabulary, emitted when a visibility change CHANGES it) and `current()` (read live from the document, else the retained value; undefined when never known — an unreadable document emits no `state`, never a fabricated background). **Singleton per key** via `createTrackerRegistry`: `applicationTrackerFor(env, onError?)` keys by the document, else the window, else one shared key; a window-only env and a window+document env are DISTINCT trackers (pair a document with its own window); `resetApplicationTracker(env)` is exported from `@bugsee/trackers/browser` for internal/test use and is NOT re-exported by `@bugsee/browser`. Browser + webview launch and the events-source fallback obtain it through the registry. **Retention rule (tested):** DOM listeners attach on the first subscriber and detach on the last, the last known `state` is retained and recomputed silently from the document on re-activation, so the first subscriber after a gap is correct at once and the de-dup baseline is never stale. `AppStateProducer` now takes the tracker only (`on('state')` + `current()` for the initial value); trace/event names and wire shapes are unchanged. **Keying rule:** document, else window, else one module key (design §15.1 #5 will be amended from "one per window" to this). **Latest launch wins** through the registry `rebind`: a defined `onError` replaces the shared reporter (undefined keeps it); while IDLE the window/document are merged (a target the request omits is kept), while ACTIVE the binding is kept and a window/document mismatch (only a target the request supplies is compared; the error names which) is reported once. The shared sink is never released on stop: a relaunch with no `onError` keeps the previous launch's (accepted limitation). `resetApplicationTracker` is `@internal` test/teardown use: exported from `@bugsee/trackers/browser` but not re-exported by `@bugsee/browser` (`reset()` removes all subscribers). An unreadable document emits neither `visibility` nor `state` (no fabricated `process_background`/fps pause). **Stays for later:** `online`/`offline` (move to Connectivity, TR3) and `orientationchange` was a stage here until TR2: the UiTracker owns it now and it is removed from this tracker. - **TR3 (DONE, `feat/connectivity-tracker`):** the per-signal `ConnectionTracker` (and its test) is deleted; the domain **`ConnectivityTracker`** (`packages/trackers/src/browser/connectivity-tracker.ts`, `connectivityTrackerFor(env, onError)`, `resetConnectivityTracker`) is a per-window singleton via the registry (keyed on `env.window`, else `env.navigator`, else the env object) with `rebind` (latest `onError` wins; a defined `window`/`navigator` replaces ours, a partial env never drops them; a RUNNING tracker moves its listeners to a changed window/navigator and re-reads). It owns ALL connectivity listeners (window `online`/`offline` + `navigator.connection` `change`) and does NOT depend on the page-lifecycle tracker. Stages: `online` `{online}`, `networkInfo` `{type?, effectiveType?, downlink?, downlinkMax?, rtt?, saveData?}` and the aggregate `state` `{online, networkInfo?}`; activation emits a baseline of every stage. Fields are omitted when absent/invalid; zero/non-finite `downlink`/`downlinkMax`/`rtt` count as "no estimate" (Chromium reports 0 offline and rounds `rtt` to 25 ms, so a 0 rtt is an unmeasured one; the spec reports `downlinkMax` 0 for type `none`) and are omitted, `saveData` only when boolean. Every host read goes through `hostRead` (a hostile getter costs only its field; reported). The emitter's reporter and every DOM listener are guarded, so a throwing subscriber plus a throwing `onError` never escapes a dispatch or `on()`. A refused `addEventListener` is reported once and the listeners that did attach stay attached (no silent death; released on deactivation). A THROWING `navigator.onLine` getter is NOT online: `online` is omitted from the state (no `online` emission, no fabricated true; `ConnectionProducer` writes no row), unless the window `online`/`offline` event that triggered the read supplies the value (the event is evidence; a READABLE `onLine` always wins), and an absent `onLine` property still counts as online. `connectivityTrackerFor` reads `window`/`navigator` once per call (a flaky getter is reported once and the key matches the host it built); `resetConnectivityTracker` is best-effort for such envs (first of window/navigator/env that has a tracker). The `addEventListener` READ itself is guarded too (cross-origin proxies). `state.online` is therefore optional. **Retention:** there is no cached snapshot to lose: state lives in `navigator`, which the tracker keeps and READS LIVE (`current()` and a fresh baseline on each activation); only the listeners are released on the last unsubscribe. `ConnectionProducer` is rewired onto it with UNCHANGED trace name/wire (`connection`: `type`, `effective_type`, `link_downstream_kbps`, `rtt`, `save_data`); `downlinkMax` is added to the open trace data as `link_downstream_max_kbps` (the connection trace is a free-form object with no schema, so this is additive). Consequence: `online`/`offline` are now bound twice on a window while capturing (the lifecycle tracker still serves the events source; the connectivity tracker owns its own), until the Application tracker absorbs the events source. - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index faec043f..e4abd27d 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -46,7 +46,9 @@ import { applicationTrackerFor, connectivityTrackerFor, resetStorageTracker, + resetUiTracker, storageTrackerFor, + uiTrackerFor, } from '@bugsee/trackers/browser'; import { strFromU8, unzipSync } from '@bugsee/util'; import { IDBFactory } from 'fake-indexeddb'; @@ -606,7 +608,8 @@ describe('launch', () => { 'tok', baseOptions({ window: w.win, captureStore: store }), ); - expect(m.thisSeen).toEqual([w.win]); // called as a method of ITS window + expect(m.thisSeen).toHaveLength(2); // the baseline read + the change watch + expect(m.thisSeen.every((t) => t === w.win)).toBe(true); // always called as a method of ITS window for (const f of [...m.l]) f({ matches: true }); expect((await names(store)).filter((e) => e.name === 'dark_mode_changed')).toEqual([ expect.objectContaining({ name: 'dark_mode_changed', params: { dark: true } }), @@ -1464,6 +1467,26 @@ describe('launch', () => { expect(w.count('orientationchange')).toBe(0); }); + it('goes through the per-window UiTracker singleton (orientation/screen_size/fps/events share ONE set of listeners)', async () => { + stubSensors(); + const w = fakeWindow(); + const client = await launchTracked( + 'tok', + noSampler({ window: w.win, captureStore: memStore() }), + ); + const before = w.count('orientationchange'); + expect(before).toBe(1); // traces' orientation + the events source's orientation_changed: one listener + // Asking for the window's tracker returns the SAME one: subscribing adds no new window listener. + const ui = uiTrackerFor({ window: w.win }); + const seen: unknown[] = []; + const off = ui.on('orientation', (s) => seen.push(s)); + expect(w.count('orientationchange')).toBe(before); + off(); + await client.stop(); + expect(w.count('orientationchange')).toBe(0); + resetUiTracker({ window: w.win }); + }); + it('launch goes through the per-window ConnectivityTracker singleton: a second consumer shares its listeners, and downlinkMax reaches the trace', async () => { vi.stubGlobal('navigator', { onLine: true, diff --git a/packages/browser/src/launch.ts b/packages/browser/src/launch.ts index f60d6b5f..1f8909c2 100644 --- a/packages/browser/src/launch.ts +++ b/packages/browser/src/launch.ts @@ -876,8 +876,9 @@ async function buildLaunch( const maxBodyBytes = resolved.options.get(BugseeOption.CaptureNetworkBodySizeLimit, 20480); const network = installNetworkCapture({ carrier, captureBodies, maxBodyBytes }); client.addCaptureProvider(network.provider); - // ONE lifecycle tracker over the injected window+document, shared by the traces' connection/orientation - // producers and the events source: the listeners are bound in a single place. + // ONE lifecycle tracker over the injected window+document, shared by the traces' connection/app_state + // producers and the events source: the listeners are bound in a single place. (Orientation, screen size, fps and + // dark mode come from the per-window UiTracker, not from here.) const lifecycle = applicationTrackerFor( { window: win, ...(domDocument !== undefined ? { document: domDocument } : {}) }, options.onError, diff --git a/packages/browser/src/system-events.test.ts b/packages/browser/src/system-events.test.ts index 470dd9e3..e9dbe7c7 100644 --- a/packages/browser/src/system-events.test.ts +++ b/packages/browser/src/system-events.test.ts @@ -80,7 +80,7 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () => const { env } = fakeEnv(); const m = fakeMedia(); const { events } = activate({ ...env, matchMedia: m.matchMedia }); - expect(m.queries).toEqual(['(prefers-color-scheme: dark)']); + expect(new Set(m.queries)).toEqual(new Set(['(prefers-color-scheme: dark)'])); // baseline read + watch m.fire(true); m.fire(false); expect(events.filter((e) => e.name === 'dark_mode_changed')).toEqual([ @@ -89,6 +89,31 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () => ]); }); + it('a throwing onError never escapes into the tracker-fed event dispatch', () => { + const { env, win, orientation } = fakeEnv(); + const m = fakeMedia(); + const { events } = activate({ + ...env, + matchMedia: m.matchMedia, + onError: () => { + throw new Error('reporter'); + }, + }); + const source = createBrowserSystemEventsSource({ + ...env, + matchMedia: m.matchMedia, + onError: () => { + throw new Error('reporter'); + }, + }); + source.on('event', () => { + throw new Error('consumer'); + }); + orientation.angle = 90; + expect(() => win.emit('orientationchange', {})).not.toThrow(); + expect(events.map((e) => e.name)).toContain('orientation_changed'); + }); + it('removes the media listener on deactivate', () => { const { env } = fakeEnv(); const m = fakeMedia(); @@ -116,7 +141,10 @@ describe('createBrowserSystemEventsSource: dark mode, freeze and resume', () => }); win.emit('online', {}); expect(events.map((e) => e.name)).toEqual(['process_started', 'online']); - expect(errors.map((e) => (e as Error).message)).toEqual(['matchMedia blocked']); + expect(errors.length).toBeGreaterThan(0); + expect(new Set(errors.map((e) => (e as Error).message))).toEqual( + new Set(['matchMedia blocked']), + ); }); it('a media list without addEventListener is a plain absence: skipped silently, other signals unaffected', () => { @@ -257,13 +285,13 @@ describe('createBrowserSystemEventsSource', () => { 'screen blocked', 'window blocked', ]); - // a supplied lifecycle owns the window/document: they are not read (or reported) again + // a supplied lifecycle owns the DOCUMENT (not read again); the window is still read for the UI tracker const none: unknown[] = []; createBrowserSystemEventsSource({ lifecycle: { on: () => () => {} }, onError: (e) => none.push(e), }); - expect(none.map((e) => (e as Error).message)).toEqual(['screen blocked']); // only screen is still read + expect(none.map((e) => (e as Error).message)).toEqual(['window blocked', 'screen blocked']); } finally { for (const [key, d] of originals) { if (d !== undefined) Object.defineProperty(globalThis, key, d); @@ -302,6 +330,37 @@ describe('createBrowserSystemEventsSource', () => { off(); }); + it('without an injected window the UI tracker gets the host window (and its screen), like the lifecycle tracker', () => { + const win = target(); + const screen = { orientation: { type: 'portrait-primary', angle: 0 } }; + vi.stubGlobal('window', win); + vi.stubGlobal('screen', screen); + const source = createBrowserSystemEventsSource(); + const events: SystemEvent[] = []; + const off = source.onAny((_s, e) => events.push(e)); + expect(win.count('orientationchange')).toBe(1); + screen.orientation = { type: 'landscape-primary', angle: 90 }; + win.emit('orientationchange', {}); + expect(events.at(-1)).toEqual({ + name: 'orientation_changed', + params: { type: 'landscape-primary', angle: 90 }, + }); + off(); + expect(win.count('orientationchange')).toBe(0); + }); + + it('an injected window never borrows the host window or screen', () => { + const hostWin = target(); + vi.stubGlobal('window', hostWin); + vi.stubGlobal('screen', { orientation: { type: 'portrait-primary', angle: 0 } }); + const injected = target(); + const { events, off } = activate({ window: injected as never }); + expect(hostWin.count('orientationchange')).toBe(0); + injected.emit('orientationchange', {}); + expect(events.at(-1)).toEqual({ name: 'orientation_changed' }); // the host's screen was not used + off(); + }); + it('without an injected tracker, two sources over the same document share the registry singleton (one listener set)', () => { const { env, win, doc } = fakeEnv(); const a = activate({ ...env, window: win as never }); diff --git a/packages/browser/src/system-events.ts b/packages/browser/src/system-events.ts index ea0842d5..01b86603 100644 --- a/packages/browser/src/system-events.ts +++ b/packages/browser/src/system-events.ts @@ -1,8 +1,13 @@ import type { SystemEvent } from '@bugsee/capture'; import { type Interceptor, InterceptorBase } from '@bugsee/core'; -import { type ApplicationTracker, applicationTrackerFor } from '@bugsee/trackers/browser'; +import { + type ApplicationTracker, + applicationTrackerFor, + type UiTracker, + uiTrackerFor, +} from '@bugsee/trackers/browser'; import type { WindowEvents } from './detection-providers'; -import { hostGlobal } from './host-global'; +import { hostGlobal, hostRead } from './host-global'; // Browser system-event SOURCE for @bugsee/capture's systemEventsProvider (the node lifecycle-source // analog). A listenable InterceptorBase: on activate it emits a 'process_started' marker and subscribes @@ -11,7 +16,8 @@ import { hostGlobal } from './host-global'; // pagehide → process_exiting (the best "about to unload — flush now" signal + bfcache flag) // visibilitychange → process_foreground / process_background (app fg/bg, from document.visibilityState) // online / offline → online / offline (connectivity transitions) -// orientationchange → orientation_changed ({type, angle} from screen.orientation) +// orientation (UiTracker: screen.orientation change + orientationchange) → orientation_changed ({type, angle}) +// colorScheme (UiTracker) → dark_mode_changed ({dark} from prefers-color-scheme) // Each signal degrades gracefully where its global is absent (e.g. no document/screen in a worker). /** The document surface the source needs: visibilitychange + the current visibility state. */ @@ -23,6 +29,8 @@ interface ScreenLike { readonly orientation?: { readonly type: OrientationType; readonly angle: number }; } +type UiEnvWindow = NonNullable[0]['window']>; + /** The slice of a `MediaQueryList` the dark-mode event needs. */ interface MediaQueryLike { readonly matches: boolean; @@ -51,15 +59,12 @@ export interface BrowserSystemEventsEnv { class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> { readonly name = 'browser-system-events'; readonly #lifecycle: Pick; - readonly #screen: ScreenLike | undefined; - readonly #matchMedia: ((query: string) => MediaQueryLike) | undefined; - readonly #onError: (error: unknown) => void; + readonly #ui: Pick; #unsubscribe: Array<() => void> = []; constructor( lifecycle: Pick, - screenLike: ScreenLike | undefined, - matchMedia?: (query: string) => MediaQueryLike, + ui: Pick, onError?: (error: unknown) => void, ) { // A throwing reporter must not escape into the browser's event dispatch or abort activation. @@ -72,9 +77,7 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> }; super(report); this.#lifecycle = lifecycle; - this.#screen = screenLike; - this.#matchMedia = matchMedia; - this.#onError = report; + this.#ui = ui; } protected onActivate(): void { @@ -91,44 +94,18 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> l.on('resume', () => this.emit('event', { name: 'resume' })), l.on('online', () => this.emit('event', { name: 'online' })), l.on('offline', () => this.emit('event', { name: 'offline' })), - l.on('orientationchange', () => { - const orientation = this.#screen?.orientation; + // The UiTracker de-duplicates the double delivery (screen.orientation change + window orientationchange); an + // engine without a readable orientation still announces the bare event. + this.#ui.on('orientation', ({ type, angle }) => this.emit('event', { name: 'orientation_changed', - ...(orientation !== undefined - ? { params: { type: orientation.type, angle: orientation.angle } } - : {}), - }); - }), + ...(type !== undefined && angle !== undefined ? { params: { type, angle } } : {}), + }), + ), + this.#ui.on('colorScheme', ({ dark }) => + this.emit('event', { name: 'dark_mode_changed', params: { dark } }), + ), ]; - this.#watchDarkMode(); - } - - // `prefers-color-scheme` is a MediaQueryList you listen on (not a window event). Attached on its own, guarded: - // an unguarded throw here would abort the capture coordinator's start and every provider registered after - // the events source (input, viewtree, ...). - #watchDarkMode(): void { - try { - const list = this.#matchMedia?.('(prefers-color-scheme: dark)'); - if (list === undefined || typeof list.addEventListener !== 'function') return; - const onChange = (event: { readonly matches: boolean }): void => { - try { - this.emit('event', { name: 'dark_mode_changed', params: { dark: event.matches } }); - } catch (error) { - this.#onError(error); // never throw into the browser's event dispatch - } - }; - list.addEventListener('change', onChange); - this.#unsubscribe.push(() => { - try { - list.removeEventListener?.('change', onChange); - } catch { - /* best-effort */ - } - }); - } catch (error) { - this.#onError(error); - } } protected override onDeactivate(): void { @@ -141,13 +118,14 @@ class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> export function createBrowserSystemEventsSource( env: BrowserSystemEventsEnv = {}, ): Interceptor<{ event: SystemEvent }> { - // The host globals are read only when no lifecycle tracker was supplied: a supplied one already owns them. + // Host globals (window, document) only when NEITHER window nor document was injected: an injected env never + // borrows the host's window or document. ONE read of the window serves the lifecycle tracker and the UI tracker. + const injected = env.window !== undefined || env.document !== undefined; + const win = injected ? env.window : hostGlobal('window', env.onError); + // The document is read only when no lifecycle tracker was supplied: a supplied one already owns it. const lifecycle = env.lifecycle ?? ((): ApplicationTracker => { - // Host globals only when NEITHER was injected: an injected window never borrows the host's document. - const injected = env.window !== undefined || env.document !== undefined; - const win = injected ? env.window : hostGlobal('window', env.onError); const doc = injected ? env.document : hostGlobal('document', env.onError); return applicationTrackerFor( { @@ -157,10 +135,23 @@ export function createBrowserSystemEventsSource( env.onError, ); })(); - return new BrowserSystemEventsSource( - lifecycle, - env.screen ?? hostGlobal('screen', env.onError), - env.matchMedia, + // An injected WINDOW brings ITS screen (read guarded), so a window whose `screen` is blocked never borrows the + // host's into the shared per-window UI tracker. Without an injected window — including an env that injected only a + // document, as before — the host's screen global applies. + const screen = + env.screen ?? + (env.window !== undefined + ? hostRead(() => (env.window as { screen?: ScreenLike }).screen, env.onError) + : hostGlobal('screen', env.onError)); + // The SAME per-window tracker the traces use (keyed on the window; a relaunch's seams merge into it). Without an + // injected window it gets the host's, exactly as the lifecycle tracker does above. + const ui = uiTrackerFor( + { + ...(win !== undefined ? { window: win as UiEnvWindow } : {}), + ...(screen !== undefined ? { screen } : {}), + ...(env.matchMedia !== undefined ? { matchMedia: env.matchMedia } : {}), + }, env.onError, ); + return new BrowserSystemEventsSource(lifecycle, ui, env.onError); } diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index 03d3fdb8..38c5b61d 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -1,5 +1,5 @@ import type { TraceProducer } from '@bugsee/capture'; -import { ApplicationTracker } from '@bugsee/trackers/browser'; +import { ApplicationTracker, UiTracker } from '@bugsee/trackers/browser'; import { describe, expect, it } from 'vitest'; import { browserTraceEnvFrom, @@ -8,7 +8,6 @@ import { ScreenSizeProducer, } from './trace-producers'; import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; -import { ScreenSizeTracker } from './trackers/screen-size-tracker'; function mkTarget() { const l = new Map void>>(); @@ -36,7 +35,7 @@ const names = (ps: TraceProducer[]) => ps.map((p) => p.name); describe('ScreenSizeProducer', () => { const mk = (screen: unknown = { width: 390, height: 844 }) => { const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); - const tracker = new ScreenSizeTracker({ window: win, screen: screen as never }); + const tracker = new UiTracker({ window: win, screen: screen as never }); return { win, tracker }; }; @@ -62,9 +61,9 @@ describe('ScreenSizeProducer', () => { for (const screen of [undefined, { width: 0, height: 844 }, { width: 390 }]) { const win = Object.assign(mkTarget(), { devicePixelRatio: 2 }); const out: Emit[] = []; - new ScreenSizeProducer( - new ScreenSizeTracker({ window: win, ...(screen ? { screen } : {}) }), - ).start(sinkOf(out)); + new ScreenSizeProducer(new UiTracker({ window: win, ...(screen ? { screen } : {}) })).start( + sinkOf(out), + ); expect(out).toEqual([]); } }); diff --git a/packages/browser/src/trace-producers.sensors.test.ts b/packages/browser/src/trace-producers.sensors.test.ts index 35a2c7a8..893febd0 100644 --- a/packages/browser/src/trace-producers.sensors.test.ts +++ b/packages/browser/src/trace-producers.sensors.test.ts @@ -1,5 +1,5 @@ import type { TraceProducer } from '@bugsee/capture'; -import { ConnectivityTracker } from '@bugsee/trackers/browser'; +import { ConnectivityTracker, UiTracker } from '@bugsee/trackers/browser'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { AdvertisedMemoryProducer, @@ -9,7 +9,6 @@ import { OrientationProducer, } from './trace-producers'; import { MemoryTracker } from './trackers/memory-tracker'; -import { OrientationTracker } from './trackers/orientation-tracker'; type Row = { name: string; value: unknown }; const startAll = (producers: readonly TraceProducer[]) => { @@ -240,9 +239,7 @@ describe('ConnectionProducer', () => { describe('OrientationProducer', () => { it('emits the Android-enum INT, never the browser {type, angle} object', () => { const orientation = Object.assign(mkTarget(), { type: 'landscape-primary', angle: 90 }); - const { out } = startAll([ - new OrientationProducer(new OrientationTracker({ screen: { orientation } })), - ]); + const { out } = startAll([new OrientationProducer(new UiTracker({ screen: { orientation } }))]); expect(out).toEqual([{ name: 'orientation', value: 3 }]); // LandscapeLeft orientation.type = 'portrait-primary'; orientation.angle = 0; @@ -254,7 +251,7 @@ describe('OrientationProducer', () => { const win = mkTarget(); const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); const { out } = startAll([ - new OrientationProducer(new OrientationTracker({ window: win, screen: { orientation } })), + new OrientationProducer(new UiTracker({ window: win, screen: { orientation } })), ]); orientation.type = 'landscape-secondary'; orientation.angle = 270; @@ -263,10 +260,15 @@ describe('OrientationProducer', () => { expect(out.map((r) => r.value)).toEqual([1, 4]); }); + it('ignores a bare orientation notification (an orientationchange the engine cannot read)', () => { + const win = mkTarget(); + const { out } = startAll([new OrientationProducer(new UiTracker({ window: win, screen: {} }))]); + win.fire('orientationchange'); + expect(out).toEqual([]); + }); + it('emits nothing where the engine has no screen.orientation', () => { - expect(startAll([new OrientationProducer(new OrientationTracker({ screen: {} }))]).out).toEqual( - [], - ); + expect(startAll([new OrientationProducer(new UiTracker({ screen: {} }))]).out).toEqual([]); }); }); @@ -419,9 +421,7 @@ describe('createBrowserSystemTraceProducers (sensors)', () => { it('an unrecognised orientation type is Unknown even when the angle alone would say Portrait', () => { const orientation = { type: 'sideways', angle: 0 }; - const { out } = startAll([ - new OrientationProducer(new OrientationTracker({ screen: { orientation } })), - ]); + const { out } = startAll([new OrientationProducer(new UiTracker({ screen: { orientation } }))]); expect(out).toEqual([{ name: 'orientation', value: 0 }]); }); diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index ab04b5af..bc0c9c9d 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -9,27 +9,22 @@ import { type ConnectivityState, type ConnectivityTracker, connectivityTrackerFor, + type OrientationState, type PowerTracker, powerTrackerFor, + type ScreenSizeState, type StorageEstimate, type StorageManagerLike, type StorageTracker, storageTrackerFor, + type UiEnv, + type UiTracker, + uiTrackerFor, } from '@bugsee/trackers/browser'; +import { boundMatchMedia } from './host-global'; import { chargingToWire, connectionTypeToWire, orientationToWire } from './system-trace-values'; -import { type FpsEnv, FpsTracker } from './trackers/fps-tracker'; import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; import { type MemoryReading, type MemoryState, MemoryTracker } from './trackers/memory-tracker'; -import { - type OrientationEnv, - type OrientationState, - OrientationTracker, -} from './trackers/orientation-tracker'; -import { - type ScreenSizeEnv, - type ScreenSizeState, - ScreenSizeTracker, -} from './trackers/screen-size-tracker'; // Browser `traces.system` producers (mirrors the mobile tracker/producer split). Each producer subscribes to // one shared tracker in start() and turns its state into the Android-vocabulary wire values; the trackers own @@ -232,17 +227,17 @@ export class ConnectionProducer extends TraceProducerBase { export class OrientationProducer extends TraceProducerBase { readonly name = 'orientation'; - readonly #tracker: OrientationTracker; + readonly #tracker: UiTracker; #off: (() => void) | undefined; - constructor(tracker: OrientationTracker) { + constructor(tracker: UiTracker) { super(); this.#tracker = tracker; } protected onStart(): void { - this.#off = this.#tracker.on('state', (s) => this.#publish(s)); - const cur = this.#tracker.current(); + this.#off = this.#tracker.on('orientation', (s) => this.#publish(s)); + const cur = this.#tracker.current('orientation'); if (cur !== undefined) this.#publish(cur); } @@ -252,6 +247,8 @@ export class OrientationProducer extends TraceProducerBase { } #publish(s: OrientationState): void { + // A bare notification (the engine could not read an orientation) has nothing to report. + if (s.type === undefined || s.angle === undefined) return; this.emitIfChanged('orientation', orientationToWire(s.type, s.angle)); } } @@ -291,16 +288,16 @@ export class AppStateProducer extends TraceProducerBase { /** `fps` (Android parity): polled, so each window's rate is emitted and never held or refreshed. */ export class FpsProducer extends TraceProducerBase { readonly name = 'fps'; - readonly #tracker: FpsTracker; + readonly #tracker: UiTracker; #off: (() => void) | undefined; - constructor(tracker: FpsTracker) { + constructor(tracker: UiTracker) { super(); this.#tracker = tracker; } protected onStart(): void { - this.#off = this.#tracker.on('fps', (fps) => this.emit('fps', fps)); + this.#off = this.#tracker.on('frameRate', (fps) => this.emit('fps', fps)); } protected override onStop(): void { @@ -311,27 +308,27 @@ export class FpsProducer extends TraceProducerBase { /** * `screen_size` (JS-specific; deliberately NOT Android's `displays`, a display LIST): `{ width, height, dpr }` in - * CSS px, re-read on `resize` / `orientationchange`. A step curve, so it is held and de-duplicated (a resize that + * CSS px, re-read on `resize` / `orientationchange` / `screen` `change` (UiTracker). A step curve, so it is held and de-duplicated (a resize that * moved nothing is dropped); the initial value is emitted at start. Omitted entirely when the screen or the pixel * ratio cannot be read as finite positive numbers. * * Known staleness: moving the window to another monitor with the SAME pixel ratio but a different size fires no - * `resize`, so the value can go stale until the next one (a `(resolution: Xdppx)` media-query / `screen` - * change listener is a follow-up); and iOS Safari's `screen.width/height` do not swap on rotation. + * `resize`, so the value can go stale until the next one, unless the engine fires the `screen` `change` event the + * tracker listens for (a `(resolution: Xdppx)` media-query listener is a follow-up); and iOS Safari's `screen.width/height` do not swap on rotation. */ export class ScreenSizeProducer extends TraceProducerBase { readonly name = 'screen-size'; - readonly #tracker: ScreenSizeTracker; + readonly #tracker: UiTracker; #off: (() => void) | undefined; - constructor(tracker: ScreenSizeTracker) { + constructor(tracker: UiTracker) { super(); this.#tracker = tracker; } protected onStart(): void { - this.#off = this.#tracker.on('state', (s) => this.#publish(s)); // subscribing attaches the listeners - const cur = this.#tracker.current(); + this.#off = this.#tracker.on('screenSize', (s) => this.#publish(s)); // subscribing attaches the listeners + const cur = this.#tracker.current('screenSize'); if (cur !== undefined) this.#publish(cur); } @@ -389,14 +386,16 @@ export interface BrowserTraceEnv extends BatteryEnv { /** NetworkInformation (read by the ConnectivityTracker). */ readonly connection?: object; }; - screen?: OrientationEnv['screen'] & ScreenSizeEnv['screen']; + screen?: UiEnv['screen']; /** Source of `online` / `offline` / `orientationchange` / `resize`, and the live `devicePixelRatio`. */ - window?: OrientationEnv['window'] & ScreenSizeEnv['window']; + window?: UiEnv['window']; /** The document the SDK is bound to: visibility for `app_state` and `fps`. */ - document?: FpsEnv['document']; + document?: UiEnv['document'] & { readonly visibilityState?: string }; /** `window.requestAnimationFrame` / `cancelAnimationFrame` (bound to that window): drive `fps`. */ - requestAnimationFrame?: FpsEnv['requestAnimationFrame']; - cancelAnimationFrame?: FpsEnv['cancelAnimationFrame']; + requestAnimationFrame?: UiEnv['requestAnimationFrame']; + cancelAnimationFrame?: UiEnv['cancelAnimationFrame']; + /** `window.matchMedia` bound to that window: colour scheme / reduced motion / display mode (UiTracker). */ + matchMedia?: UiEnv['matchMedia']; /** * `false` builds the battery producer ONLY: a caller-supplied `systemMetricsSampler` replaces the heap, * connection, orientation, `app_state`, `fps`, `screen_size` and `main_thread_lag_ms` traces (as on Node), so the sensor producers must not also emit them. @@ -404,7 +403,11 @@ export interface BrowserTraceEnv extends BatteryEnv { sensors?: boolean; /** Drives the heap poll; default the global timers. */ scheduler?: Scheduler; - /** The shared ApplicationTracker feeding orientation, app_state and fps; when absent orientation listens on `window` and app_state/fps are omitted. */ + /** + * The shared ApplicationTracker feeding `app_state`. Its presence also GATES the `app_state`, `screen_size`, `fps` + * and `main_thread_lag_ms` producers (they are omitted without it); `screen_size`, `fps` and `orientation` get their + * sources from the per-window UiTracker, not from this. + */ lifecycle?: Pick; } @@ -449,7 +452,9 @@ export function browserTraceEnvFrom( const getBattery = nav === undefined ? undefined : read(() => nav.getBattery); const raf = read(() => win.requestAnimationFrame); const caf = read(() => win.cancelAnimationFrame); + const matchMedia = boundMatchMedia(win, onError); return { + ...(matchMedia !== undefined ? { matchMedia } : {}), ...(nav !== undefined ? { navigator: nav } : {}), ...(performance !== undefined ? { performance } : {}), ...(screen !== undefined ? { screen } : {}), @@ -524,6 +529,28 @@ export function createBrowserSystemTraceProducers( if (env.sensors === false) return [battery]; // Read ONCE: a hostile `performance.now` getter must report one error, not one per consumer. const clock = safePerformanceNow(env, onError); + // ONE UI/display tracker per window serves orientation, screen_size and fps (and the events source). + const ui = uiTrackerFor( + { + ...(env.window !== undefined ? { window: env.window } : {}), + ...(env.screen !== undefined ? { screen: env.screen } : {}), + ...(env.matchMedia !== undefined ? { matchMedia: env.matchMedia } : {}), + ...(env.document !== undefined ? { document: env.document } : {}), + ...(env.requestAnimationFrame !== undefined + ? { requestAnimationFrame: env.requestAnimationFrame } + : {}), + ...(env.cancelAnimationFrame !== undefined + ? { cancelAnimationFrame: env.cancelAnimationFrame } + : {}), + ...(clock !== undefined + ? // A clock that becomes unreadable later THROWS (the tracker's tick reports and skips the window) + // rather than answering a made-up 0. + { now: () => (env.performance as { now(): number }).now() } + : {}), + ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), + }, + onError, + ); return [ battery, new MemoryProducer( @@ -547,29 +574,11 @@ export function createBrowserSystemTraceProducers( ), ), new ConnectionProducer(connectivityTrackerFor(env, onError)), - new OrientationProducer( - new OrientationTracker( - { - ...(env.lifecycle !== undefined ? { lifecycle: env.lifecycle } : {}), - ...(env.window !== undefined ? { window: env.window } : {}), - ...(env.screen !== undefined ? { screen: env.screen } : {}), - }, - onError, - ), - ), + new OrientationProducer(ui), ...(env.lifecycle !== undefined ? [ new AppStateProducer(env.lifecycle), - new ScreenSizeProducer( - new ScreenSizeTracker( - { - lifecycle: env.lifecycle, - ...(env.window !== undefined ? { window: env.window } : {}), - ...(env.screen !== undefined ? { screen: env.screen } : {}), - }, - onError, - ), - ), + new ScreenSizeProducer(ui), new MainThreadLagProducer( new MainThreadLagTracker( { @@ -584,27 +593,7 @@ export function createBrowserSystemTraceProducers( onError, ), ), - new FpsProducer( - new FpsTracker( - { - lifecycle: env.lifecycle, - ...(env.document !== undefined ? { document: env.document } : {}), - ...(env.requestAnimationFrame !== undefined - ? { requestAnimationFrame: env.requestAnimationFrame } - : {}), - ...(env.cancelAnimationFrame !== undefined - ? { cancelAnimationFrame: env.cancelAnimationFrame } - : {}), - ...(clock !== undefined - ? // A clock that becomes unreadable later THROWS (the tracker's tick reports and skips the window) - // rather than answering a made-up 0. - { now: () => (env.performance as { now(): number }).now() } - : {}), - ...(env.scheduler !== undefined ? { scheduler: env.scheduler } : {}), - }, - onError, - ), - ), + new FpsProducer(ui), ] : []), ]; diff --git a/packages/browser/src/trace-producers.visibility.test.ts b/packages/browser/src/trace-producers.visibility.test.ts index e31ac2f5..bd0498e5 100644 --- a/packages/browser/src/trace-producers.visibility.test.ts +++ b/packages/browser/src/trace-producers.visibility.test.ts @@ -1,5 +1,10 @@ import type { TraceProducer } from '@bugsee/capture'; -import { ApplicationTracker } from '@bugsee/trackers/browser'; +import { + ApplicationTracker, + resetUiTracker, + UiTracker, + uiTrackerFor, +} from '@bugsee/trackers/browser'; import { describe, expect, it } from 'vitest'; import { AppStateProducer, @@ -8,7 +13,6 @@ import { defaultBrowserTraceEnv, FpsProducer, } from './trace-producers'; -import { FpsTracker } from './trackers/fps-tracker'; function mkTarget() { const l = new Map void>>(); @@ -129,8 +133,7 @@ describe('FpsProducer', () => { let timer: (() => void) | undefined; let now = 0; const cbs: Array<() => void> = []; - const tracker = new FpsTracker({ - lifecycle: page.lifecycle, + const tracker = new UiTracker({ document: page.doc, requestAnimationFrame: (cb) => { cbs.push(() => cb(0)); @@ -153,7 +156,7 @@ describe('FpsProducer', () => { cbs[0]?.(); timer?.(); expect(out).toEqual([{ name: 'fps', value: 1, hold: false }]); - expect(page.doc.count()).toBe(3); // subscribed: visibilitychange + freeze + resume + expect(page.doc.count()).toBe(1); // subscribed: the tracker's own visibilitychange (no page-lifecycle tracker) p.stop(); expect(page.doc.count()).toBe(0); // the tracker was released with the last subscriber now = 2000; @@ -250,6 +253,41 @@ describe('browserTraceEnvFrom', () => { ]); }); + it("matchMedia is the window's own, bound to it; absent or throwing means none", () => { + const calls: unknown[] = []; + const win = { + matchMedia(this: unknown, query: string) { + calls.push(this, query); + return { matches: true }; + }, + }; + const env = browserTraceEnvFrom(win, undefined); + expect(env.matchMedia?.('(x)')).toEqual({ matches: true }); + expect(calls).toEqual([win, '(x)']); + expect(browserTraceEnvFrom({}, undefined).matchMedia).toBeUndefined(); + const errors: unknown[] = []; + const hostile = {}; + Object.defineProperty(hostile, 'matchMedia', { + get(): never { + throw new Error('matchMedia blocked'); + }, + }); + expect( + browserTraceEnvFrom(hostile, undefined, (e) => errors.push(e)).matchMedia, + ).toBeUndefined(); + expect(errors).toHaveLength(1); + }); + + it("createBrowserSystemTraceProducers hands the env's matchMedia/screen to the window's UiTracker", () => { + const win = { addEventListener() {}, removeEventListener() {} }; + createBrowserSystemTraceProducers({ + window: win, + matchMedia: () => ({ matches: true }), + }); + expect(uiTrackerFor({ window: win }).current('colorScheme')).toEqual({ dark: true }); + resetUiTracker({ window: win }); + }); + it('one throwing surface does not take the others with it, and onError is optional', () => { const screen = { orientation: { type: 'portrait-primary', angle: 0 } }; const win = { screen }; diff --git a/packages/browser/src/trackers/fps-tracker.test.ts b/packages/browser/src/trackers/fps-tracker.test.ts deleted file mode 100644 index bf7696fd..00000000 --- a/packages/browser/src/trackers/fps-tracker.test.ts +++ /dev/null @@ -1,544 +0,0 @@ -import type { Scheduler } from '@bugsee/core'; -import { describe, expect, it, vi } from 'vitest'; -import { FpsTracker } from './fps-tracker'; - -// A controllable page: manual rAF queue, manual clock, a visibility lifecycle, a manual interval. -function mkEnv(over: { visible?: boolean; noRaf?: boolean; noCancel?: boolean } = {}) { - let now = 0; - let nextId = 1; - const rafs = new Map void>(); - const cancelled: number[] = []; - const doc = { visibilityState: over.visible === false ? 'hidden' : 'visible' }; - const visListeners = new Set<(e: { visible: boolean }) => void>(); - let timerCb: (() => void) | undefined; - const timers = { set: 0, cleared: 0, live: 0 }; - const scheduler: Scheduler = { - setInterval: (cb) => { - timerCb = cb; - timers.set += 1; - timers.live += 1; - return { id: timers.set }; - }, - clearInterval: () => { - timers.cleared += 1; - timers.live -= 1; - }, - }; - const env = { - document: doc, - lifecycle: { - on: (type: string, fn: (e: never) => void) => { - expect(type).toBe('visibility'); - visListeners.add(fn as never); - return () => void visListeners.delete(fn as never); - }, - }, - ...(over.noRaf - ? {} - : { - requestAnimationFrame: (cb: (t: number) => void) => { - const id = nextId++; - rafs.set(id, cb); - return id; - }, - }), - ...(over.noCancel - ? {} - : { - cancelAnimationFrame: (id: number) => { - cancelled.push(id); - rafs.delete(id); - }, - }), - now: () => now, - scheduler, - }; - const frame = () => { - // run the pending callbacks (each re-arms itself) - const cbs = [...rafs.entries()]; - rafs.clear(); - for (const [, cb] of cbs) cb(now); - }; - return { - env, - doc, - cancelled, - timers, - rafs, - frame, - advance: (ms: number) => { - now += ms; - }, - tick: () => timerCb?.(), - setVisible: (visible: boolean) => { - doc.visibilityState = visible ? 'visible' : 'hidden'; - for (const l of [...visListeners]) l({ visible }); - }, - listeners: () => visListeners.size, - }; -} - -describe('FpsTracker', () => { - it('attaches nothing until the first subscriber', () => { - const e = mkEnv(); - new FpsTracker(e.env); - expect(e.rafs.size).toBe(0); - expect(e.timers.set).toBe(0); - expect(e.listeners()).toBe(0); - }); - - it('while visible: counts frames and reports frames/second over the window on each tick', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - expect(e.rafs.size).toBe(1); - for (let i = 0; i < 30; i++) { - e.advance(1000 / 60); - e.frame(); - } - e.advance(1); - e.tick(); // 30 frames over ~501 ms - expect(got).toHaveLength(1); - expect(got[0]).toBeCloseTo(59.9, 1); - // the window restarts: 2 frames in the next 1000 ms - e.advance(500); - e.frame(); - e.advance(500); - e.frame(); - e.tick(); - expect(got[1]).toBe(2); - }); - - it('once frames have been seen, a window with none is a true 0 (the main thread stopped painting)', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(500); - e.frame(); - e.advance(500); - e.tick(); - e.advance(1000); - e.tick(); - expect(got).toEqual([1, 0]); - }); - - it('a mid-run rAF pause reports the drop to 0 ONCE, not a run of zeros, and measuring resumes cleanly', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(1000); - for (let i = 0; i < 60; i++) e.frame(); // 60 frames in the first second - e.tick(); - e.advance(1000); - e.tick(); // the first frameless window: reported as the drop - e.advance(1000); - e.tick(); // still frameless: paused, not a fresh zero - e.advance(1000); - e.tick(); - expect(got).toEqual([60, 0]); - // rAF resumes after the stall: the first report covers only the time since the last tick, not the stall - e.advance(500); - for (let i = 0; i < 30; i++) e.frame(); - e.advance(500); - e.tick(); - expect(got).toEqual([60, 0, 30]); - }); - - it('frameless ticks before the first frame move the window forward, so the stall never dilutes the first measurement', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - for (let i = 0; i < 3; i++) { - e.advance(1000); - e.tick(); // nothing yet - } - for (let i = 0; i < 60; i++) e.frame(); - e.advance(1000); - e.tick(); - expect(got).toEqual([60]); // not 15 (60 frames over 4000 ms) - }); - - it('a visible page that has never produced a frame reports nothing (rAF can be paused while visibility stays visible)', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(1000); - e.tick(); - e.advance(1000); - e.tick(); - expect(got).toEqual([]); - }); - - it('a hide/show restarts that rule: no frame yet in the new run means nothing is reported', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(500); - e.frame(); - e.setVisible(false); - e.setVisible(true); - e.advance(1000); - e.tick(); - expect(got).toEqual([]); - }); - - it('a stale frame callback from before a hide never joins the loop started after the show (no cancelAnimationFrame)', () => { - const e = mkEnv({ noCancel: true }); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - const stale = [...e.rafs.values()]; - e.setVisible(false); - e.setVisible(true); - e.rafs.delete(1); // the first loop's handle is not cancellable: it stays queued in a real browser - for (const cb of stale) cb(0); // the old frame fires after the restart - expect(e.rafs.size).toBe(1); // only the NEW loop's frame is pending: the old one did not re-arm - e.advance(1000); - e.frame(); - e.tick(); - expect(got).toEqual([1]); - }); - - it('a zero-length window reports nothing (never a division by zero)', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.tick(); - expect(got).toEqual([]); - }); - - it('hidden at start: no rAF loop, no timer, nothing emitted', () => { - const e = mkEnv({ visible: false }); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - expect(e.rafs.size).toBe(0); - expect(e.timers.live).toBe(0); - e.advance(1000); - e.tick(); - expect(got).toEqual([]); - }); - - it('going hidden cancels the pending frame and the timer; showing again starts a FRESH window', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(400); - e.frame(); - e.setVisible(false); - expect(e.rafs.size).toBe(0); - expect(e.cancelled).toHaveLength(1); - expect(e.timers.live).toBe(0); - e.advance(60_000); // a long hidden stretch must not leak into the next window - e.setVisible(true); - expect(e.timers.live).toBe(1); - expect(e.rafs.size).toBe(1); - e.advance(500); - e.frame(); - e.advance(500); - e.tick(); - expect(got).toEqual([1]); - }); - - it('a duplicate visible/hidden event does not stack loops or timers', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - t.on('fps', () => {}); - e.setVisible(true); - e.setVisible(true); - expect(e.timers.live).toBe(1); - expect(e.rafs.size).toBe(1); - e.setVisible(false); - e.setVisible(false); - expect(e.timers.live).toBe(0); - expect(e.cancelled).toHaveLength(1); - }); - - it('the last unsubscribe stops the loop, the timer and the visibility subscription; a re-subscribe restarts', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env); - const off = t.on('fps', () => {}); - expect(e.listeners()).toBe(1); - off(); - expect(e.rafs.size).toBe(0); - expect(e.timers.live).toBe(0); - expect(e.listeners()).toBe(0); - t.on('fps', () => {}); - expect(e.rafs.size).toBe(1); - expect(e.timers.live).toBe(1); - }); - - it('a frame callback that fires after the loop stopped is ignored and does not re-arm', () => { - const e = mkEnv({ noCancel: true }); - const t = new FpsTracker(e.env); - const off = t.on('fps', () => {}); - const pending = [...e.rafs.values()]; - off(); - e.rafs.clear(); - for (const cb of pending) cb(0); - expect(e.rafs.size).toBe(0); - }); - - it('a runtime without requestAnimationFrame is omitted: no timer, no subscription', () => { - const e = mkEnv({ noRaf: true }); - const t = new FpsTracker(e.env); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - expect(e.timers.set).toBe(0); - e.advance(1000); - e.tick(); - expect(got).toEqual([]); - }); - - it('works without cancelAnimationFrame', () => { - const e = mkEnv({ noCancel: true }); - const t = new FpsTracker(e.env); - t.on('fps', () => {}); - expect(() => e.setVisible(false)).not.toThrow(); - }); - - it('with no lifecycle it measures nothing: without visibility events a hidden tab could not be gated', () => { - const e = mkEnv(); - const { lifecycle: _l, ...rest } = e.env; - const errors: unknown[] = []; - const t = new FpsTracker(rest, (err) => errors.push(err)); - t.on('fps', () => {}); - expect(e.rafs.size).toBe(0); - expect(e.timers.set).toBe(0); - expect(errors).toEqual([]); // a deliberate omission, not a failure - }); - - it('a throwing requestAnimationFrame is reported and the tracker stays usable', () => { - const errors: unknown[] = []; - const e = mkEnv(); - const t = new FpsTracker( - { - ...e.env, - requestAnimationFrame: () => { - throw new Error('raf'); - }, - }, - (err) => errors.push(err), - ); - expect(() => t.on('fps', () => {})).not.toThrow(); - expect((errors[0] as Error).message).toBe('raf'); - expect(() => e.setVisible(false)).not.toThrow(); - }); - - it('a start that failed halfway is cleaned up, so the next visible event can start the loop again', () => { - const e = mkEnv({ visible: false }); - let failures = 1; - const errors: unknown[] = []; - const t = new FpsTracker( - { - ...e.env, - requestAnimationFrame: (cb) => { - if (failures-- > 0) throw new Error('raf once'); - return e.env.requestAnimationFrame?.(cb) ?? 0; - }, - }, - (err) => errors.push(err), - ); - t.on('fps', () => {}); - e.setVisible(true); // fails: nothing may be left half started - expect(errors).toHaveLength(1); - expect(e.timers.live).toBe(0); - e.setVisible(true); // the next event (no hide in between) starts it properly - expect(e.rafs.size).toBe(1); - expect(e.timers.live).toBe(1); - }); - - it('samples every second by default and honors intervalMs', () => { - const seen: number[] = []; - const scheduler: Scheduler = { - setInterval: (_cb, ms) => { - seen.push(ms); - return 1; - }, - clearInterval: () => {}, - }; - const e = mkEnv(); - new FpsTracker({ ...e.env, scheduler }).on('fps', () => {}); - new FpsTracker({ ...e.env, scheduler, intervalMs: 250 }).on('fps', () => {}); - expect(seen).toEqual([1000, 250]); - }); - - it('a lifecycle that throws on subscribe is reported, not thrown out of on()', () => { - const errors: unknown[] = []; - const e = mkEnv(); - const t = new FpsTracker( - { - ...e.env, - lifecycle: { - on: () => { - throw new Error('lifecycle'); - }, - }, - }, - (err) => errors.push(err), - ); - expect(() => t.on('fps', () => {})).not.toThrow(); - expect((errors[0] as Error).message).toBe('lifecycle'); - }); - - it('a requestAnimationFrame that throws while re-arming is reported, not thrown into the frame callback', () => { - const errors: unknown[] = []; - const e = mkEnv(); - let calls = 0; - const t = new FpsTracker( - { - ...e.env, - requestAnimationFrame: (cb) => { - calls += 1; - if (calls > 1) throw new Error('rearm'); - return e.env.requestAnimationFrame?.(cb) ?? 0; - }, - }, - (err) => errors.push(err), - ); - t.on('fps', () => {}); - expect(() => e.frame()).not.toThrow(); - expect((errors[0] as Error).message).toBe('rearm'); - }); - - it('a clock that throws skips that window (reported) and the next one recovers', () => { - const errors: unknown[] = []; - const e = mkEnv(); - let boom = false; - const t = new FpsTracker( - { - ...e.env, - now: () => { - if (boom) throw new Error('clock'); - return e.env.now(); - }, - }, - (err) => errors.push(err), - ); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - e.advance(500); - e.frame(); - boom = true; - expect(() => e.tick()).not.toThrow(); - expect((errors[0] as Error).message).toBe('clock'); - expect(got).toEqual([]); - boom = false; - e.advance(500); - e.tick(); - expect(got).toEqual([1]); // the failed window was not consumed: its 1 frame counts over the full 1000 ms - }); - - it('a clock that throws while the loop starts rolls the start back, so the next visible event can start it', () => { - const errors: unknown[] = []; - const e = mkEnv({ visible: false }); - let boom = true; - const t = new FpsTracker( - { - ...e.env, - now: () => { - if (boom) throw new Error('clock at start'); - return e.env.now(); - }, - }, - (err) => errors.push(err), - ); - t.on('fps', () => {}); - e.setVisible(true); // the clock throws: nothing may be left half started - expect((errors[0] as Error).message).toBe('clock at start'); - expect(e.rafs.size).toBe(0); - expect(e.timers.live).toBe(0); - boom = false; - e.setVisible(true); // no hide in between: the tracker is not wedged in `running` - expect(e.rafs.size).toBe(1); - expect(e.timers.live).toBe(1); - }); - - it('a throwing visibilityState read is treated as hidden and reported', () => { - const errors: unknown[] = []; - const e = mkEnv(); - const doc = {}; - Object.defineProperty(doc, 'visibilityState', { - get(): never { - throw new Error('vis'); - }, - }); - const t = new FpsTracker({ ...e.env, document: doc }, (err) => errors.push(err)); - t.on('fps', () => {}); - expect(e.rafs.size).toBe(0); - expect((errors[0] as Error).message).toBe('vis'); - }); - - it('a throwing consumer or reporter never breaks the tick', () => { - const e = mkEnv(); - const t = new FpsTracker(e.env, () => { - throw new Error('reporter'); - }); - t.on('fps', () => { - throw new Error('consumer'); - }); - e.advance(1000); - expect(() => e.tick()).not.toThrow(); - }); - - it('falls back to the wall clock when the runtime has no performance.now', () => { - vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'Date'] }); - vi.stubGlobal('performance', {}); - try { - vi.setSystemTime(0); - const frames: Array<() => void> = []; - const t = new FpsTracker({ - lifecycle: { on: () => () => {} }, - document: { visibilityState: 'visible' }, - requestAnimationFrame: (cb) => { - frames.push(() => cb(0)); - return frames.length; - }, - }); - const got: number[] = []; - t.on('fps', (v) => got.push(v)); - frames[0]?.(); - vi.advanceTimersByTime(1000); - expect(got).toEqual([1]); - } finally { - vi.unstubAllGlobals(); - vi.useRealTimers(); - } - }); - - it('uses performance.now and the global timers by default', () => { - vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); - let ms = 0; - const nowSpy = vi.spyOn(performance, 'now').mockImplementation(() => ms); - try { - const frames: Array<() => void> = []; - const t = new FpsTracker({ - lifecycle: { on: () => () => {} }, - document: { visibilityState: 'visible' }, - requestAnimationFrame: (cb) => { - frames.push(() => cb(0)); - return frames.length; - }, - }); - const got: number[] = []; - const off = t.on('fps', (v) => got.push(v)); - frames[0]?.(); - ms = 500; - vi.advanceTimersByTime(1000); - expect(got).toEqual([2]); // 1 frame over a 500 ms performance.now window - off(); - expect(vi.getTimerCount()).toBe(0); - } finally { - nowSpy.mockRestore(); - vi.useRealTimers(); - } - }); -}); diff --git a/packages/browser/src/trackers/fps-tracker.ts b/packages/browser/src/trackers/fps-tracker.ts deleted file mode 100644 index b303afee..00000000 --- a/packages/browser/src/trackers/fps-tracker.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { InterceptorBase, type Scheduler } from '@bugsee/core'; -import type { ApplicationTracker } from '@bugsee/trackers/browser'; - -// Browser frame-rate TRACKER (Android `fps` parity): counts `requestAnimationFrame` callbacks and reports -// frames/second once per window. It runs ONLY while the page is visible — a hidden tab gets no animation -// frames, and a permanent rAF loop there would burn battery and keep the page awake — so the loop and the -// timer are torn down on `hidden` and a fresh window starts on `visible` (a long hidden stretch must never -// leak into the next window). Hidden, unmeasurable, or without rAF it emits NOTHING: omit, never zero. -// Once frames have flowed, the first window without any is reported as 0 (the main thread stopped painting) and a -// continuing stall then goes quiet; before the first frame nothing is reported. rAF can be paused while the page -// still says `visible`, so a run of zeros would be invented. - -export interface FpsEnv { - /** Shared lifecycle tracker for visibility changes. */ - lifecycle?: Pick; - /** Visibility is read here at activation; unknown (absent) counts as not visible. */ - document?: { readonly visibilityState?: string }; - requestAnimationFrame?: (callback: (timestamp: number) => void) => number; - cancelAnimationFrame?: (handle: number) => void; - /** Monotonic ms. Default `performance.now()`. */ - now?: () => number; - scheduler?: Scheduler; - intervalMs?: number; -} - -const defaultScheduler: Scheduler = { - setInterval: (cb, ms) => setInterval(cb, ms), - clearInterval: (h) => clearInterval(h as ReturnType), -}; - -// `performance.now()` where it exists (monotonic), else the wall clock: a window is a few hundred ms to seconds, -// so a clock step is the lesser evil next to reporting nothing. -const defaultNow = (): number => { - const p = (globalThis as { performance?: { now?: () => number } }).performance; - return typeof p?.now === 'function' ? p.now() : Date.now(); -}; - -export class FpsTracker extends InterceptorBase<{ fps: number }> { - readonly name = 'browser-fps'; - readonly #env: FpsEnv; - readonly #report: (error: unknown) => void; - readonly #scheduler: Scheduler; - readonly #now: () => number; - #subscription: (() => void) | undefined; - #timer: unknown = null; - #raf: number | undefined; - #running = false; - #frames = 0; - #seenFrame = false; - #windowStart = 0; - #loop = 0; - - constructor(env: FpsEnv, onError?: (error: unknown) => void) { - // A throwing reporter must not escape into the host's frame/timer dispatch. - const report = (error: unknown): void => { - try { - onError?.(error); - } catch { - /* the reporter itself failed; nothing left to tell */ - } - }; - super(report); - this.#env = env; - this.#report = report; - this.#scheduler = env.scheduler ?? defaultScheduler; - this.#now = env.now ?? defaultNow; - } - - // Guarded: the tracker is already marked active before this runs, so a throwing environment must be - // reported here rather than leak out of `on()`. - protected onActivate(): void { - // No frames to count, or no visibility events to gate on (a hidden tab must never keep a frame loop): omit. - if (typeof this.#env.requestAnimationFrame !== 'function' || this.#env.lifecycle === undefined) - return; - try { - this.#subscription = this.#env.lifecycle.on('visibility', ({ visible }) => - visible ? this.#startLoop() : this.#stopLoop(), - ); - if (this.#isVisible()) this.#startLoop(); - } catch (error) { - this.#report(error); - } - } - - protected override onDeactivate(): void { - this.#subscription?.(); - this.#stopLoop(); - } - - #isVisible(): boolean { - try { - return this.#env.document?.visibilityState === 'visible'; - } catch (error) { - this.#report(error); - return false; - } - } - - #startLoop(): void { - if (this.#running) return; - this.#running = true; - this.#loop += 1; - this.#seenFrame = false; - this.#frames = 0; - try { - // The clock read is inside the guarded setup: a throwing clock must roll the run back like any other setup - // failure, or `#running` would stay true with no loop and block every later start. - this.#windowStart = this.#now(); - this.#arm(); - this.#timer = this.#scheduler.setInterval(() => this.#tick(), this.#env.intervalMs ?? 1000); - } catch (error) { - this.#report(error); - this.#stopLoop(); // never leave a half-started loop behind - } - } - - #stopLoop(): void { - this.#running = false; - if (this.#timer !== null) this.#scheduler.clearInterval(this.#timer); - this.#timer = null; - const raf = this.#raf; - this.#raf = undefined; - if (raf !== undefined) { - try { - this.#env.cancelAnimationFrame?.(raf); - } catch { - /* best-effort */ - } - } - } - - #arm(): void { - const loop = this.#loop; - this.#raf = this.#env.requestAnimationFrame?.(() => { - // A frame already in flight when its loop stopped (cancelAnimationFrame missing or failed) must not count - // or re-arm — not even after a restart, or two loops would run and fps would read double. - if (!this.#running || loop !== this.#loop) return; - this.#seenFrame = true; - this.#frames += 1; - try { - this.#arm(); - } catch (error) { - this.#report(error); - } - }); - } - - #tick(): void { - let now: number; - try { - now = this.#now(); - } catch (error) { - this.#report(error); // an unreadable clock skips this window; it runs inside the host's timer dispatch - return; - } - const elapsed = now - this.#windowStart; - if (!(elapsed > 0)) return; // a zero-length window has no rate - // No frame EVER in this run: rAF may be paused while the page still reports `visible` (an offscreen - // cross-origin iframe, an occluded window), so a 0 would be invented. Once frames have flowed, 0 is true. - if (!this.#seenFrame) { - this.#windowStart = now; // the stalled stretch must not dilute the first measured window - return; - } - const fps = Math.round(((this.#frames * 1000) / elapsed) * 10) / 10; - // A window with no frames after frames had flowed is reported (the drop to 0) ONCE; rAF can also be paused - // while the page still says `visible`, so a continuing stall goes quiet instead of a run of fabricated zeros. - if (this.#frames === 0) this.#seenFrame = false; - this.#frames = 0; - this.#windowStart = now; - this.emit('fps', fps); // the emitter isolates and reports a throwing consumer - } -} diff --git a/packages/browser/src/trackers/orientation-tracker.test.ts b/packages/browser/src/trackers/orientation-tracker.test.ts deleted file mode 100644 index 0607b7fd..00000000 --- a/packages/browser/src/trackers/orientation-tracker.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { ApplicationTracker } from '@bugsee/trackers/browser'; -import { describe, expect, it, vi } from 'vitest'; -import { OrientationTracker } from './orientation-tracker'; - -function mkTarget() { - const l = new Map void>>(); - return { - addEventListener: (t: string, f: () => void) => { - const s = l.get(t) ?? new Set<() => void>(); - s.add(f); - l.set(t, s); - }, - removeEventListener: (t: string, f: () => void) => void l.get(t)?.delete(f), - fire: (t: string) => - l.get(t)?.forEach((f) => { - f(); - }), - count: () => [...l.values()].reduce((n, s) => n + s.size, 0), - }; -} - -describe('OrientationTracker', () => { - it('attaches nothing until the first subscriber', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - new OrientationTracker({ window: win, screen: { orientation } }); - expect(win.count() + orientation.count()).toBe(0); - }); - - it('listens to screen.orientation change AND window orientationchange; releases both on the last unsubscribe', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - const t = new OrientationTracker({ window: win, screen: { orientation } }); - const offA = t.on('state', () => {}); - const offB = t.on('state', () => {}); - expect(orientation.count()).toBe(1); - expect(win.count()).toBe(1); - offA(); - expect(orientation.count() + win.count()).toBe(2); - offB(); - expect(orientation.count() + win.count()).toBe(0); - }); - - it('emits the current {type, angle} on each change', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - const t = new OrientationTracker({ window: win, screen: { orientation } }); - const seen: unknown[] = []; - t.on('state', (s) => seen.push(s)); - orientation.type = 'landscape-primary'; - orientation.angle = 90; - orientation.fire('change'); - orientation.type = 'landscape-secondary'; - orientation.angle = 270; - win.fire('orientationchange'); - expect(seen).toEqual([ - { type: 'landscape-primary', angle: 90 }, - { type: 'landscape-secondary', angle: 270 }, - ]); - }); - - it('current() is the live orientation; undefined when the engine has no screen.orientation', () => { - expect( - new OrientationTracker({ - screen: { orientation: { type: 'portrait-secondary', angle: 180 } }, - }).current(), - ).toEqual({ type: 'portrait-secondary', angle: 180 }); - expect(new OrientationTracker({ screen: {} }).current()).toBeUndefined(); - expect(new OrientationTracker({}).current()).toBeUndefined(); - }); - - it('tolerates an orientation object that cannot take listeners', () => { - const win = mkTarget(); - const t = new OrientationTracker({ - window: win, - screen: { orientation: { type: 'portrait-primary', angle: 0 } }, - }); - const off = t.on('state', () => {}); - expect(win.count()).toBe(1); - off(); - expect(win.count()).toBe(0); - }); - - it('a throwing getter in the event path is reported, not thrown; current() likewise', () => { - const win = mkTarget(); - const onError = vi.fn(); - const screen = { - get orientation(): never { - throw new Error('getter'); - }, - }; - const t = new OrientationTracker({ window: win, screen }, onError); - t.on('state', () => {}); - expect(() => win.fire('orientationchange')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - expect(t.current()).toBeUndefined(); - expect(onError).toHaveBeenCalledTimes(2); - }); - - it('a throwing removeEventListener does not leak the other listener', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - orientation.removeEventListener = () => { - throw new Error('detached'); - }; - const t = new OrientationTracker({ window: win, screen: { orientation } }); - const off = t.on('state', () => {}); - expect(() => off()).not.toThrow(); - expect(win.count()).toBe(0); - }); - - it('an event whose read throws (orientation getter fails after activation) is reported, never thrown', () => { - const win = mkTarget(); - const onError = vi.fn(); - let reads = 0; - const live = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - const screen = { - get orientation() { - reads += 1; - if (reads > 1) throw new Error('getter'); // activation reads it once - return live; - }, - }; - const t = new OrientationTracker({ window: win, screen }, onError); - const seen: unknown[] = []; - t.on('state', (s) => seen.push(s)); - expect(() => live.fire('change')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - expect(seen).toEqual([]); - }); - - it('an event that finds no orientation anymore emits nothing', () => { - const win = mkTarget(); - const live = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - let gone = false; - const screen = { - get orientation() { - return gone ? undefined : live; - }, - }; - const t = new OrientationTracker({ window: win, screen }); - const seen: unknown[] = []; - t.on('state', (s) => seen.push(s)); - gone = true; - live.fire('change'); - win.fire('orientationchange'); - expect(seen).toEqual([]); - }); - - it('removes each listener exactly once per activation cycle (no stale entries replayed on a later stop)', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - const removes = vi.fn(); - const realRemove = orientation.removeEventListener; - orientation.removeEventListener = (t, f) => { - removes(t); - realRemove(t, f); - }; - const t = new OrientationTracker({ window: win, screen: { orientation } }); - t.on('state', () => {})(); - t.on('state', () => {})(); - expect(removes).toHaveBeenCalledTimes(2); - }); - - it('with a shared lifecycle it takes orientationchange from it and releases the subscription on stop', () => { - const win = mkTarget(); - const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); - const lifecycle = new ApplicationTracker({ window: win as never }); - const t = new OrientationTracker({ lifecycle, window: win, screen: { orientation } }); - const seen: unknown[] = []; - const off = t.on('state', (s) => seen.push(s)); - expect(win.count()).toBe(4); // lifecycle's own four window listeners; the tracker added none - win.fire('orientationchange'); - expect(seen).toEqual([{ type: 'portrait-primary', angle: 0 }]); - off(); - expect(win.count() + orientation.count()).toBe(0); - }); -}); diff --git a/packages/browser/src/trackers/orientation-tracker.ts b/packages/browser/src/trackers/orientation-tracker.ts deleted file mode 100644 index ff145e4e..00000000 --- a/packages/browser/src/trackers/orientation-tracker.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { InterceptorBase } from '@bugsee/core'; -import type { ApplicationTracker } from '@bugsee/trackers/browser'; - -// Browser screen-orientation TRACKER (mirrors the mobile tracker/producer split): reports the current -// `screen.orientation` {type, angle} on every change. Both `screen.orientation` `change` and the window's -// legacy `orientationchange` are listened to (engines differ in which they fire); the producer's -// de-duplication collapses the double delivery. Attached on the first subscriber, removed on the last. - -export interface OrientationState { - type: string; - angle: number; -} -interface TargetLike { - addEventListener(type: string, listener: () => void): void; - removeEventListener(type: string, listener: () => void): void; -} -export interface OrientationEnv { - /** Shared lifecycle tracker for `orientationchange`; when absent it is listened for on `window`. */ - lifecycle?: Pick; - window?: TargetLike; - screen?: { - orientation?: { type: string; angle: number } & Partial; - }; -} - -export class OrientationTracker extends InterceptorBase<{ state: OrientationState }> { - readonly name = 'browser-orientation'; - readonly #env: OrientationEnv; - readonly #onError: ((error: unknown) => void) | undefined; - #attached: Array<{ target: Partial; type: string }> = []; - #subscriptions: Array<() => void> = []; - - readonly #onChange = (): void => { - try { - const state = this.#read(); - if (state !== undefined) this.emit('state', state); - } catch (error) { - this.#onError?.(error); // never throw into the browser's event dispatch - } - }; - - constructor(env: OrientationEnv, onError?: (error: unknown) => void) { - super(onError); - this.#env = env; - this.#onError = onError; - } - - /** The live orientation, or undefined where the engine has no `screen.orientation`. */ - current(): OrientationState | undefined { - try { - return this.#read(); - } catch (error) { - this.#onError?.(error); - return undefined; - } - } - - // Guarded: the tracker is already marked active (and the subscriber registered) before this runs, so a - // throwing `screen.orientation` getter must be reported here, not leak out of `on()`. Whatever attached - // before the throw is still removed on deactivation. - protected onActivate(): void { - try { - this.#listen(this.#env.screen?.orientation, 'change'); - const lifecycle = this.#env.lifecycle; - if (lifecycle !== undefined) { - this.#subscriptions.push(lifecycle.on('orientationchange', this.#onChange)); - } else { - this.#listen(this.#env.window, 'orientationchange'); - } - } catch (error) { - this.#onError?.(error); - } - } - - protected override onDeactivate(): void { - const subscriptions = this.#subscriptions; - this.#subscriptions = []; - for (const off of subscriptions) off(); - const attached = this.#attached; - this.#attached = []; - for (const { target, type } of attached) { - try { - target.removeEventListener?.(type, this.#onChange); - } catch { - /* best-effort: one detached target must not leak the other */ - } - } - } - - #listen(target: Partial | undefined, type: string): void { - if (typeof target?.addEventListener !== 'function') return; - target.addEventListener(type, this.#onChange); - this.#attached.push({ target, type }); - } - - #read(): OrientationState | undefined { - const o = this.#env.screen?.orientation; - return o === undefined ? undefined : { type: o.type, angle: o.angle }; - } -} diff --git a/packages/browser/src/trackers/screen-size-tracker.test.ts b/packages/browser/src/trackers/screen-size-tracker.test.ts deleted file mode 100644 index 5b79285a..00000000 --- a/packages/browser/src/trackers/screen-size-tracker.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { ScreenSizeTracker } from './screen-size-tracker'; - -function mkWin(over: { screen?: unknown; dpr?: unknown } = {}) { - const l = new Map void>>(); - const win: Record = { - devicePixelRatio: 'dpr' in over ? over.dpr : 2, - addEventListener: (t: string, f: () => void) => { - const s = l.get(t) ?? new Set<() => void>(); - s.add(f); - l.set(t, s); - }, - removeEventListener: (t: string, f: () => void) => void l.get(t)?.delete(f), - }; - const screen = 'screen' in over ? over.screen : { width: 390, height: 844 }; - return { - win: win as never, - screen: screen as never, - set: (k: string, v: unknown) => { - win[k] = v; - }, - fire: (t: string) => - l.get(t)?.forEach((f) => { - f(); - }), - count: () => [...l.values()].reduce((n, s) => n + s.size, 0), - types: () => - [...l.entries()] - .filter(([, s]) => s.size > 0) - .map(([t]) => t) - .sort(), - }; -} - -describe('ScreenSizeTracker', () => { - it('attaches nothing until the first subscriber, then resize + orientationchange on the injected window', () => { - const w = mkWin(); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); - expect(w.count()).toBe(0); - const off = t.on('state', () => {}); - expect(w.types()).toEqual(['orientationchange', 'resize']); - off(); - expect(w.count()).toBe(0); - }); - - it('with a shared lifecycle, orientationchange comes from IT (no extra window listener); resize stays on the window', () => { - const w = mkWin(); - const subs = new Set<() => void>(); - const lifecycle = { - on: (type: string, fn: () => void) => { - expect(type).toBe('orientationchange'); - subs.add(fn); - return () => void subs.delete(fn); - }, - }; - const t = new ScreenSizeTracker({ - lifecycle: lifecycle as never, - window: w.win, - screen: w.screen, - }); - const got: unknown[] = []; - const off = t.on('state', (s) => got.push(s)); - expect(w.types()).toEqual(['resize']); - expect(subs.size).toBe(1); - w.set('devicePixelRatio', 3); - for (const f of subs) f(); - expect(got).toEqual([{ width: 390, height: 844, dpr: 3 }]); - off(); - expect(subs.size).toBe(0); - expect(w.count()).toBe(0); - }); - - it('current() reads {width, height, dpr} live', () => { - const w = mkWin(); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); - expect(t.current()).toEqual({ width: 390, height: 844, dpr: 2 }); - w.set('devicePixelRatio', 3); - expect(t.current()).toEqual({ width: 390, height: 844, dpr: 3 }); - }); - - it('emits the new state on resize and on orientationchange', () => { - const w = mkWin(); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); - const got: unknown[] = []; - t.on('state', (s) => got.push(s)); - w.set('devicePixelRatio', 1.5); - w.fire('resize'); - w.set('devicePixelRatio', 2); - w.fire('orientationchange'); - expect(got).toEqual([ - { width: 390, height: 844, dpr: 1.5 }, - { width: 390, height: 844, dpr: 2 }, - ]); - }); - - it('omits (never 0 / NaN) when screen is absent or any value is not a finite positive number', () => { - const bad: unknown[] = [0, -1, NaN, Infinity, '390', null, undefined]; - for (const v of bad) { - for (const field of ['width', 'height'] as const) { - const w = mkWin({ screen: { width: 390, height: 844, [field]: v } }); - expect( - new ScreenSizeTracker({ window: w.win, screen: w.screen }).current(), - ).toBeUndefined(); - } - const w = mkWin({ dpr: v }); - expect(new ScreenSizeTracker({ window: w.win, screen: w.screen }).current()).toBeUndefined(); - } - const noScreen = mkWin(); - expect(new ScreenSizeTracker({ window: noScreen.win }).current()).toBeUndefined(); - expect(new ScreenSizeTracker({}).current()).toBeUndefined(); - }); - - it('an unreadable change emits nothing', () => { - const w = mkWin(); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); - const got: unknown[] = []; - t.on('state', (s) => got.push(s)); - w.set('devicePixelRatio', 0); - w.fire('resize'); - expect(got).toEqual([]); - }); - - it('hostile getters are reported, never thrown (current and the event path)', () => { - const errors: unknown[] = []; - const hostile = { - get width(): number { - throw new Error('w'); - }, - height: 1, - }; - const w = mkWin({ screen: hostile }); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, (e) => errors.push(e)); - expect(t.current()).toBeUndefined(); - expect(errors).toHaveLength(1); - t.on('state', () => {}); - expect(() => w.fire('resize')).not.toThrow(); - expect(errors).toHaveLength(2); - const dprBlocked = mkWin(); - Object.defineProperty(dprBlocked.win, 'devicePixelRatio', { - get(): never { - throw new Error('dpr'); - }, - }); - const t2 = new ScreenSizeTracker({ window: dprBlocked.win, screen: dprBlocked.screen }, (e) => - errors.push(e), - ); - expect(t2.current()).toBeUndefined(); - expect((errors[2] as Error).message).toBe('dpr'); - }); - - it('a throwing addEventListener is reported, and what attached is still released', () => { - const errors: unknown[] = []; - const w = mkWin(); - const real = (w.win as { addEventListener: (t: string, f: () => void) => void }) - .addEventListener; - let n = 0; - (w.win as { addEventListener: unknown }).addEventListener = (t: string, f: () => void) => { - if (n++ === 1) throw new Error('add'); - real(t, f); - }; - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, (e) => errors.push(e)); - const off = t.on('state', () => {}); - expect((errors[0] as Error).message).toBe('add'); - expect(w.count()).toBe(1); - off(); - expect(w.count()).toBe(0); - }); - - it('a throwing reporter never escapes on() or the event path', () => { - const w = mkWin(); - (w.win as { addEventListener: unknown }).addEventListener = () => { - throw new Error('add'); - }; - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, () => { - throw new Error('reporter'); - }); - expect(() => t.on('state', () => {})).not.toThrow(); - const hostile = mkWin({ - screen: { - get width(): number { - throw new Error('w'); - }, - height: 1, - }, - }); - expect( - new ScreenSizeTracker({ window: hostile.win, screen: hostile.screen }, () => { - throw new Error('reporter'); - }).current(), - ).toBeUndefined(); - }); - - it('a throwing subscriber with a throwing reporter does not escape the event dispatch', () => { - const w = mkWin(); - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }, () => { - throw new Error('reporter'); - }); - t.on('state', () => { - throw new Error('subscriber'); - }); - expect(() => w.fire('resize')).not.toThrow(); - }); - - it('a throwing removeEventListener does not leak the other listener', () => { - const w = mkWin(); - const real = (w.win as { removeEventListener: (t: string, f: () => void) => void }) - .removeEventListener; - let first = true; - (w.win as { removeEventListener: unknown }).removeEventListener = ( - t: string, - f: () => void, - ) => { - if (first) { - first = false; - throw new Error('rm'); - } - real(t, f); - }; - const t = new ScreenSizeTracker({ window: w.win, screen: w.screen }); - const off = t.on('state', () => {}); - expect(() => off()).not.toThrow(); - expect(w.count()).toBe(1); // only the one whose removal threw stays - }); - - it('works on a window with no addEventListener (initial value only)', () => { - const t = new ScreenSizeTracker({ - window: { devicePixelRatio: 1 }, - screen: { width: 1, height: 2 }, - }); - expect(() => t.on('state', () => {})).not.toThrow(); - expect(t.current()).toEqual({ width: 1, height: 2, dpr: 1 }); - }); -}); diff --git a/packages/browser/src/trackers/screen-size-tracker.ts b/packages/browser/src/trackers/screen-size-tracker.ts deleted file mode 100644 index 782e9099..00000000 --- a/packages/browser/src/trackers/screen-size-tracker.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { InterceptorBase } from '@bugsee/core'; -import type { ApplicationTracker } from '@bugsee/trackers/browser'; - -// Browser screen-size TRACKER (the producer is `screen_size`; deliberately NOT Android's `displays`, which is a -// display LIST): reports `{ width, height, dpr }` — CSS px of `screen.width/height` and `devicePixelRatio` — on -// every `resize` and `orientationchange` of the injected window. `resize` is also what a page-zoom (a dpr -// change) fires, and the producer's de-duplication drops a resize that moved neither. `orientationchange` comes -// from the shared ApplicationTracker (like the orientation tracker; without one, from the window), but `resize` -// is listened for here, on the injected window: nothing else consumes it, and a new lifecycle event would -// change the listener count of every lifecycle subscriber for one trace. Attached on the first subscriber, -// removed on the last. Any non-finite-positive value omits the whole reading (never 0). -// -// Known staleness: moving the window to a monitor with the SAME pixel ratio but a different size fires no -// `resize`, so the value can go stale (a `(resolution: Xdppx)` media-query / `screen` change listener is a -// follow-up); and iOS Safari's `screen.width/height` do not swap on rotation. - -export interface ScreenSizeState { - width: number; - height: number; - dpr: number; -} -interface TargetLike { - addEventListener(type: string, listener: () => void): void; - removeEventListener(type: string, listener: () => void): void; -} -export interface ScreenSizeEnv { - /** Shared lifecycle tracker for `orientationchange`; when absent it is listened for on `window`. */ - lifecycle?: Pick; - /** The injected window: `resize`/`orientationchange` source AND the LIVE `devicePixelRatio` (zoom changes it). */ - window?: Partial & { readonly devicePixelRatio?: unknown }; - screen?: { readonly width?: unknown; readonly height?: unknown }; -} - -const positive = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v > 0; - -export class ScreenSizeTracker extends InterceptorBase<{ state: ScreenSizeState }> { - readonly name = 'browser-screen-size'; - readonly #env: ScreenSizeEnv; - readonly #report: (error: unknown) => void; - #attached: Array<{ target: Partial; type: string }> = []; - #subscriptions: Array<() => void> = []; - - readonly #onChange = (): void => { - const state = this.current(); // reports its own failures; never throws into the browser's event dispatch - if (state !== undefined) this.emit('state', state); - }; - - constructor(env: ScreenSizeEnv, onError?: (error: unknown) => void) { - // A throwing reporter must not escape into the host's event dispatch or out of `on()`. - const report = (error: unknown): void => { - try { - onError?.(error); - } catch { - /* the reporter itself failed; nothing left to tell */ - } - }; - super(report); - this.#env = env; - this.#report = report; - } - - /** The live size, or undefined when the screen or the pixel ratio is absent / not a finite positive number. */ - current(): ScreenSizeState | undefined { - try { - const screen = this.#env.screen; - if (screen === undefined) return undefined; - const width = screen.width; - const height = screen.height; - const dpr = this.#env.window?.devicePixelRatio; - return positive(width) && positive(height) && positive(dpr) - ? { width, height, dpr } - : undefined; - } catch (error) { - this.#report(error); - return undefined; - } - } - - // Guarded: the tracker is already marked active before this runs; whatever attached before a throw is still - // removed on deactivation. - protected onActivate(): void { - try { - this.#listen('resize'); - const lifecycle = this.#env.lifecycle; - if (lifecycle !== undefined) { - this.#subscriptions.push(lifecycle.on('orientationchange', this.#onChange)); - } else { - this.#listen('orientationchange'); - } - } catch (error) { - this.#report(error); - } - } - - protected override onDeactivate(): void { - const subscriptions = this.#subscriptions; - this.#subscriptions = []; - for (const off of subscriptions) off(); - const attached = this.#attached; - this.#attached = []; - for (const { target, type } of attached) { - try { - target.removeEventListener?.(type, this.#onChange); - } catch { - /* best-effort: one failed removal must not leak the other */ - } - } - } - - #listen(type: string): void { - const target = this.#env.window; - if (typeof target?.addEventListener !== 'function') return; - target.addEventListener(type, this.#onChange); - this.#attached.push({ target, type }); - } -} diff --git a/packages/trackers/README.md b/packages/trackers/README.md index a0a4f279..24c72556 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -22,7 +22,7 @@ Trackers are the abstraction over system and runtime APIs. The package root is r - `@bugsee/trackers/node` (`src/node/`) - `@bugsee/trackers/electron` (`src/electron/`) -The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying) and `hostRead`; `./node` and `./electron` are reserved in `exports` and currently export nothing. Its API is internal and may change between releases. +The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, `resetApplicationTracker`), the `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`), the `ConnectivityTracker` (`connectivityTrackerFor`, `resetConnectivityTracker`), the UI/display `UiTracker` (`uiTrackerFor`, `resetUiTracker`: orientation, screenSize, viewport, colorScheme, reducedMotion, displayMode, frameRate), the `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; an approximate origin quota estimate, not device free space: browsers may pad `usage`, and `quota` can roughly reveal the device's disk size, so treat it as potentially identifying) and `hostRead`; `./node` and `./electron` are reserved in `exports` and currently export nothing. Its API is internal and may change between releases. ## Links diff --git a/packages/trackers/package.json b/packages/trackers/package.json index 66b0ce68..9676e939 100644 --- a/packages/trackers/package.json +++ b/packages/trackers/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/trackers" }, - "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, StorageTracker, hostRead) and reserved ./node and ./electron platform entries", + "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, StorageTracker, UiTracker, hostRead) and reserved ./node and ./electron platform entries", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/packages/trackers/src/browser/application-tracker.test.ts b/packages/trackers/src/browser/application-tracker.test.ts index f1e67f55..75834394 100644 --- a/packages/trackers/src/browser/application-tracker.test.ts +++ b/packages/trackers/src/browser/application-tracker.test.ts @@ -36,13 +36,14 @@ describe('ApplicationTracker', () => { expect(win.count() + doc.count()).toBe(0); }); - it('attaches pagehide/online/offline/orientationchange on window and visibilitychange on document', () => { + it('attaches pagehide/online/offline on window (orientationchange belongs to the UiTracker) and visibilitychange on document', () => { const { win, doc } = mkEnv(); const t = new ApplicationTracker({ window: win, document: doc }); t.on('online', () => {}); - for (const type of ['pagehide', 'online', 'offline', 'orientationchange']) { + for (const type of ['pagehide', 'online', 'offline']) { expect(win.count(type)).toBe(1); } + expect(win.count('orientationchange')).toBe(0); expect(doc.count('visibilitychange')).toBe(1); }); @@ -71,7 +72,7 @@ describe('ApplicationTracker', () => { }).not.toThrow(); expect(win.count('freeze')).toBe(0); // checked while SUBSCRIBED expect(win.count('resume')).toBe(0); - expect(win.count()).toBe(4); // only the window's own pagehide/online/offline/orientationchange + expect(win.count()).toBe(3); // only the window's own pagehide/online/offline off?.(); }); @@ -98,11 +99,11 @@ describe('ApplicationTracker', () => { const offA = t.on('online', () => {}); const offB = t.on('offline', () => {}); offA(); - expect(win.count() + doc.count()).toBe(7); + expect(win.count() + doc.count()).toBe(6); offB(); expect(win.count() + doc.count()).toBe(0); t.on('online', () => {}); - expect(win.count() + doc.count()).toBe(7); + expect(win.count() + doc.count()).toBe(6); }); it('removes each listener exactly once per activation cycle (no stale entries replayed on a later stop)', () => { @@ -116,7 +117,7 @@ describe('ApplicationTracker', () => { const t = new ApplicationTracker({ window: win, document: doc }); t.on('online', () => {})(); t.on('online', () => {})(); - expect(removes).toHaveBeenCalledTimes(8); + expect(removes).toHaveBeenCalledTimes(6); }); it('emits typed events', () => { @@ -127,7 +128,6 @@ describe('ApplicationTracker', () => { t.on('visibility', (e) => seen.push(['visibility', e])); t.on('online', () => seen.push(['online'])); t.on('offline', () => seen.push(['offline'])); - t.on('orientationchange', () => seen.push(['orientationchange'])); win.fire('pagehide', { persisted: true }); win.fire('pagehide', {}); doc.visibilityState = 'hidden'; @@ -136,7 +136,6 @@ describe('ApplicationTracker', () => { doc.fire('visibilitychange'); win.fire('online'); win.fire('offline'); - win.fire('orientationchange'); expect(seen).toEqual([ ['pagehide', { persisted: true }], ['pagehide', { persisted: false }], @@ -144,7 +143,6 @@ describe('ApplicationTracker', () => { ['visibility', { visible: true }], ['online'], ['offline'], - ['orientationchange'], ]); }); @@ -605,7 +603,7 @@ describe('applicationTrackerFor (singleton per key)', () => { const { win, doc } = mkEnv(); const a = applicationTrackerFor({ window: win, document: doc }); a.on('online', () => {}); - expect(win.count()).toBe(4); + expect(win.count()).toBe(3); resetApplicationTracker({ window: win, document: doc }); expect(win.count() + doc.count()).toBe(0); expect(applicationTrackerFor({ window: win, document: doc })).not.toBe(a); diff --git a/packages/trackers/src/browser/application-tracker.ts b/packages/trackers/src/browser/application-tracker.ts index 50535967..00a9097a 100644 --- a/packages/trackers/src/browser/application-tracker.ts +++ b/packages/trackers/src/browser/application-tracker.ts @@ -17,8 +17,8 @@ import { hostRead } from './host-read'; // LATEST request wins (see `rebind`): a defined onError replaces the reporter; while idle the window/document are // re-bound, while active the binding is kept and a differing window/document (only a target the request supplies counts) is reported once. // -// `online`/`offline`/`orientationchange` stay here for now so ConnectionTracker/OrientationTracker keep working -// unchanged; they move to the Connectivity (TR3) and UI/Display (TR2) trackers in those slices. +// `online`/`offline` stay here for now (the Connectivity tracker owns its own copies); `orientationchange` belongs to +// the UI/Display tracker and is NOT bound here. /** The Android app-state vocabulary (the viewer's table also has `started`, which the web never reports). */ export type ApplicationState = 'foreground' | 'background'; @@ -35,7 +35,6 @@ export interface ApplicationEvents { resume: undefined; online: undefined; offline: undefined; - orientationchange: undefined; } interface TargetLike { addEventListener(type: string, listener: (event: unknown) => void): void; @@ -87,7 +86,7 @@ export class ApplicationTracker extends InterceptorBase { this.emit('pagehide', { persisted: (e as { persisted?: boolean }).persisted === true }), ), ); - for (const type of ['online', 'offline', 'orientationchange'] as const) { + for (const type of ['online', 'offline'] as const) { this.#listen(win, type, () => this.#guard(() => this.emit(type, undefined))); } this.#listen(doc, 'visibilitychange', () => this.#guard(() => this.#onVisibility())); diff --git a/packages/trackers/src/browser/index.ts b/packages/trackers/src/browser/index.ts index a40a0b37..ef386e74 100644 --- a/packages/trackers/src/browser/index.ts +++ b/packages/trackers/src/browser/index.ts @@ -36,3 +36,21 @@ export { type StorageTrackerEnv, storageTrackerFor, } from './storage-tracker'; +export { + type ColorSchemeState, + type DisplayModeName, + type DisplayModeState, + type MediaQueryListLike, + type OrientationState, + type ReducedMotionState, + resetUiTracker, + type ScreenSizeState, + type UiEnv, + type UiSchedulerLike, + type UiStage, + type UiStages, + type UiStateStage, + UiTracker, + uiTrackerFor, + type ViewportState, +} from './ui-tracker'; diff --git a/packages/trackers/src/browser/ui-tracker.test.ts b/packages/trackers/src/browser/ui-tracker.test.ts new file mode 100644 index 00000000..95916293 --- /dev/null +++ b/packages/trackers/src/browser/ui-tracker.test.ts @@ -0,0 +1,935 @@ +import { describe, expect, it, vi } from 'vitest'; +import { resetUiTracker, type UiEnv, UiTracker, uiTrackerFor } from './ui-tracker'; + +function mkTarget() { + const listeners = new Map void>>(); + const set = (t: string) => { + let s = listeners.get(t); + if (s === undefined) { + s = new Set(); + listeners.set(t, s); + } + return s; + }; + return { + addEventListener: (t: string, l: (e?: unknown) => void) => void set(t).add(l), + removeEventListener: (t: string, l: (e?: unknown) => void) => void listeners.get(t)?.delete(l), + fire: (t: string, e?: unknown) => + void [...(listeners.get(t) ?? [])].forEach((l) => { + l(e); + }), + count: (t: string) => listeners.get(t)?.size ?? 0, + total: () => [...listeners.values()].reduce((n, s) => n + s.size, 0), + }; +} + +function mkWorld(init: { visible?: boolean } = {}) { + const win = Object.assign(mkTarget(), { devicePixelRatio: 2, innerWidth: 800, innerHeight: 600 }); + const orientation = Object.assign(mkTarget(), { type: 'portrait-primary', angle: 0 }); + const screen = Object.assign(mkTarget(), { width: 1000, height: 2000, orientation }); + const doc = Object.assign(mkTarget(), { + visibilityState: init.visible === false ? 'hidden' : 'visible', + }); + const queries = new Map>(); + const mkMql = () => Object.assign(mkTarget(), { matches: false }); + const matchMedia = vi.fn((q: string) => { + let m = queries.get(q); + if (m === undefined) { + m = mkMql(); + queries.set(q, m); + } + return m; + }); + let t = 0; + const frames: Array<() => void> = []; + const intervals: Array<() => void> = []; + const cleared: unknown[] = []; + const env = { + window: win, + screen, + document: doc, + matchMedia: matchMedia as unknown as NonNullable, + requestAnimationFrame: vi.fn((cb: (t: number) => void) => frames.push(() => cb(0))), + cancelAnimationFrame: vi.fn(), + now: () => t, + scheduler: { + setInterval: vi.fn((cb: () => void) => intervals.push(cb)), + clearInterval: vi.fn((h: unknown) => void cleared.push(h)), + }, + } satisfies UiEnv; + return { + env, + win, + screen, + orientation, + doc, + queries, + advance: (ms: number) => { + t += ms; + }, + frame: () => + void frames.splice(0).forEach((f) => { + f(); + }), + pendingFrames: () => frames.length, + tick: () => + void intervals.forEach((f) => { + f(); + }), + cleared, + }; +} + +/** The media query list the tracker asked `matchMedia` for (a missing one is a test failure, not an undefined). */ +function q(w: ReturnType, query: string) { + const list = w.queries.get(query); + if (list === undefined) throw new Error(`no query ${query}`); + return list; +} + +describe('UiTracker orientation', () => { + it('reads live, emits on screen.orientation change and orientationchange, deduped', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + expect(t.current('orientation')).toEqual({ type: 'portrait-primary', angle: 0 }); + const got: unknown[] = []; + const off = t.on('orientation', (s) => got.push(s)); + expect(w.orientation.count('change')).toBe(1); + expect(w.win.count('orientationchange')).toBe(1); + w.orientation.type = 'landscape-primary'; + w.orientation.angle = 90; + w.orientation.fire('change'); + w.win.fire('orientationchange'); // double delivery collapses + expect(got).toEqual([{ type: 'landscape-primary', angle: 90 }]); + off(); + expect(w.orientation.total() + w.win.total()).toBe(0); + }); + + it('omits invalid fields; emits a bare {} only when nothing is readable', () => { + const w = mkWorld(); + const t = new UiTracker({ + ...w.env, + screen: { orientation: { type: 3, angle: Number.NaN } } as never, + }); + expect(t.current('orientation')).toBeUndefined(); + const got: unknown[] = []; + t.on('orientation', (s) => got.push(s)); + w.win.fire('orientationchange'); + w.win.fire('orientationchange'); + expect(got).toEqual([{}, {}]); + const t2 = new UiTracker({ screen: { orientation: { type: 'x', angle: Infinity } } as never }); + expect(t2.current('orientation')).toEqual({ type: 'x' }); + const t3 = new UiTracker({ screen: { orientation: { type: 1, angle: 5 } } as never }); + expect(t3.current('orientation')).toEqual({ angle: 5 }); + expect(new UiTracker({ screen: {} }).current('orientation')).toBeUndefined(); + }); + + it('re-reads the baseline on re-attach so a change made while idle is not swallowed', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: unknown[] = []; + const off = t.on('orientation', (s) => got.push(s)); + w.orientation.angle = 90; + w.win.fire('orientationchange'); + off(); + w.orientation.angle = 0; // changed while idle, back to the first value + t.on('orientation', (s) => got.push(s)); + w.orientation.angle = 90; + w.win.fire('orientationchange'); + expect(got).toEqual([ + { type: 'portrait-primary', angle: 90 }, + { type: 'portrait-primary', angle: 90 }, + ]); + }); +}); + +describe('UiTracker screenSize and viewport', () => { + it('emits on resize, orientationchange and screen change; deduped; only subscribed stages', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const sizes: unknown[] = []; + const views: unknown[] = []; + const offSize = t.on('screenSize', (s) => sizes.push(s)); + expect(w.win.count('resize')).toBe(1); + expect(w.screen.count('change')).toBe(1); + w.win.fire('resize'); // nothing moved + expect(sizes).toEqual([]); + w.win.devicePixelRatio = 3; + w.win.fire('resize'); + w.screen.width = 1200; + w.screen.fire('change'); + w.screen.height = 1; + w.win.fire('orientationchange'); + expect(sizes).toEqual([ + { width: 1000, height: 2000, dpr: 3 }, + { width: 1200, height: 2000, dpr: 3 }, + { width: 1200, height: 1, dpr: 3 }, + ]); + expect(views).toEqual([]); // viewport had no listener: not computed + const offView = t.on('viewport', (s) => views.push(s)); + w.win.innerWidth = 500; + w.win.fire('resize'); + expect(views).toEqual([{ width: 500, height: 600 }]); + offSize(); + expect(w.screen.count('change')).toBe(0); + expect(w.win.count('resize')).toBe(1); + offView(); + expect(w.win.total()).toBe(0); + }); + + it('omits an unusable reading, never zero', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + w.win.devicePixelRatio = 0; + w.win.innerHeight = Number.NaN; + expect(t.current('screenSize')).toBeUndefined(); + expect(t.current('viewport')).toBeUndefined(); + w.win.devicePixelRatio = 2; + w.screen.width = Infinity; + expect(t.current('screenSize')).toBeUndefined(); + expect(new UiTracker({}).current('screenSize')).toBeUndefined(); + expect(new UiTracker({}).current('viewport')).toBeUndefined(); + const got: unknown[] = []; + t.on('screenSize', (s) => got.push(s)); + w.win.fire('resize'); + expect(got).toEqual([]); + }); +}); + +describe('UiTracker media-query stages', () => { + it('colorScheme and reducedMotion: live read, change events, listeners only while subscribed', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + expect(t.current('colorScheme')).toEqual({ dark: false }); + expect(t.current('reducedMotion')).toEqual({ reduce: false }); + const dark: unknown[] = []; + const reduce: unknown[] = []; + const offD = t.on('colorScheme', (s) => dark.push(s)); + const offR = t.on('reducedMotion', (s) => reduce.push(s)); + const d = q(w, '(prefers-color-scheme: dark)'); + const r = q(w, '(prefers-reduced-motion: reduce)'); + expect(d.count('change')).toBe(1); + d.fire('change', { matches: true }); + d.fire('change', { matches: true }); + d.fire('change', { matches: 'x' }); // invalid: omitted + r.fire('change', { matches: 7 }); // invalid: omitted + r.fire('change', { matches: true }); + expect(dark).toEqual([{ dark: true }]); + expect(reduce).toEqual([{ reduce: true }]); + offD(); + offR(); + expect(d.count('change') + r.count('change')).toBe(0); + }); + + it('displayMode resolves the matching mode, else browser; undefined when nothing answers', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + expect(t.current('displayMode')).toEqual({ mode: 'browser' }); + q(w, '(display-mode: standalone)').matches = true; + expect(t.current('displayMode')).toEqual({ mode: 'standalone' }); + const got: unknown[] = []; + const off = t.on('displayMode', (s) => got.push(s)); + q(w, '(display-mode: fullscreen)').matches = true; + q(w, '(display-mode: fullscreen)').fire('change', {}); + q(w, '(display-mode: fullscreen)').fire('change', {}); + expect(got).toEqual([{ mode: 'fullscreen' }]); + off(); + expect( + ['fullscreen', 'standalone', 'minimal-ui'].every( + (m) => q(w, `(display-mode: ${m})`).count('change') === 0, + ), + ).toBe(true); + expect(new UiTracker({}).current('displayMode')).toBeUndefined(); + const bad = new UiTracker({ matchMedia: () => ({ matches: 'no' }) }); + expect(bad.current('displayMode')).toBeUndefined(); + expect(bad.current('colorScheme')).toBeUndefined(); + expect( + new UiTracker({ matchMedia: () => null as never }).current('colorScheme'), + ).toBeUndefined(); + }); + + it('a query list without addEventListener attaches nothing (and does not throw)', () => { + const t = new UiTracker({ matchMedia: () => ({ matches: true }) }); + const off = t.on('colorScheme', () => {}); + expect(() => off()).not.toThrow(); + t.on('displayMode', () => {}); + }); +}); + +describe('UiTracker frameRate', () => { + it('counts rAF frames per window while visible; emits nothing before the first frame', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + expect(w.doc.count('visibilitychange')).toBe(1); + w.advance(1000); + w.tick(); // no frame yet + expect(got).toEqual([]); + for (let i = 0; i < 3; i++) w.frame(); + w.advance(1000); + w.tick(); + expect(got).toEqual([3]); + w.advance(1000); + w.tick(); // first frameless window after frames: 0 + w.advance(1000); + w.tick(); // continuing stall: quiet + expect(got).toEqual([3, 0]); + }); + + it('rounds to one decimal and skips a zero-length window', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + w.frame(); + w.frame(); + w.frame(); + w.tick(); // elapsed 0 + expect(got).toEqual([]); + w.advance(900); + w.tick(); + expect(got).toEqual([3.3]); + }); + + it('tears the loop down on hidden and starts a fresh window on visible', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + w.frame(); + w.doc.visibilityState = 'hidden'; + w.doc.fire('visibilitychange'); + expect(w.env.cancelAnimationFrame).toHaveBeenCalledTimes(1); + expect(w.env.scheduler.clearInterval).toHaveBeenCalledTimes(1); + w.advance(60_000); + w.doc.visibilityState = 'visible'; + w.doc.fire('visibilitychange'); + w.doc.fire('visibilitychange'); // already running: no second loop + expect(w.env.scheduler.setInterval).toHaveBeenCalledTimes(2); + w.frame(); + w.advance(1000); + w.tick(); + expect(got).toEqual([1]); + }); + + it('a frame in flight from a stopped loop neither counts nor re-arms', () => { + const w = mkWorld(); + const t = new UiTracker({ ...w.env, cancelAnimationFrame: undefined }); + const off = t.on('frameRate', () => {}); + off(); // loop stopped, one frame callback still queued + const before = w.env.requestAnimationFrame.mock.calls.length; + w.frame(); + expect(w.env.requestAnimationFrame.mock.calls.length).toBe(before); + }); + + it('starts nothing while hidden, without rAF, or without a visibility source; releases on unsubscribe', () => { + const hidden = mkWorld({ visible: false }); + new UiTracker(hidden.env).on('frameRate', () => {}); + expect(hidden.env.scheduler.setInterval).not.toHaveBeenCalled(); + expect(hidden.doc.count('visibilitychange')).toBe(1); + const noRaf = mkWorld(); + new UiTracker({ ...noRaf.env, requestAnimationFrame: undefined }).on('frameRate', () => {}); + expect(noRaf.doc.total()).toBe(0); + const noDoc = mkWorld(); + new UiTracker({ ...noDoc.env, document: {} }).on('frameRate', () => {}); + expect(noDoc.env.requestAnimationFrame).not.toHaveBeenCalled(); + const w = mkWorld(); + const off = new UiTracker(w.env).on('frameRate', () => {}); + off(); + expect(w.doc.total()).toBe(0); + expect(w.env.cancelAnimationFrame).toHaveBeenCalled(); + expect(w.env.scheduler.clearInterval).toHaveBeenCalled(); + }); + + it('rolls back a start whose clock throws, reports it, and can start again', () => { + const w = mkWorld(); + const errors: unknown[] = []; + let broken = true; + const t = new UiTracker( + { + ...w.env, + now: () => { + if (broken) throw new Error('clock'); + return 0; + }, + }, + (e) => errors.push(e), + ); + t.on('frameRate', () => {}); + expect(errors).toHaveLength(1); + broken = false; + w.doc.fire('visibilitychange'); + expect(w.env.scheduler.setInterval).toHaveBeenCalledTimes(1); + }); + + it('reports a throwing clock at a tick and skips the window; a throwing rAF re-arm is reported', () => { + const w = mkWorld(); + const errors: unknown[] = []; + let broken = false; + let armFails = false; + const t = new UiTracker( + { + ...w.env, + now: () => { + if (broken) throw new Error('clock'); + return 0; + }, + requestAnimationFrame: (cb: (t: number) => void) => { + if (armFails) throw new Error('raf'); + return w.env.requestAnimationFrame(cb); + }, + }, + (e) => errors.push(e), + ); + t.on('frameRate', () => {}); + broken = true; + w.tick(); + expect(errors).toHaveLength(1); + armFails = true; + w.frame(); + expect(errors).toHaveLength(2); + }); + + it('uses the default scheduler and clock when none are injected, and tolerates a failing clearInterval/cancel', () => { + vi.useFakeTimers(); + try { + const w = mkWorld(); + const t = new UiTracker({ + ...w.env, + scheduler: undefined, + now: undefined, + intervalMs: 50, + cancelAnimationFrame: () => { + throw new Error('cancel'); + }, + }); + const got: number[] = []; + const off = t.on('frameRate', (f) => got.push(f)); + w.frame(); + vi.advanceTimersByTime(50); + expect(got).toHaveLength(1); + expect(() => off()).not.toThrow(); + const t2 = new UiTracker({ + ...w.env, + scheduler: { + setInterval: () => 1, + clearInterval: () => { + throw new Error('clear'); + }, + }, + }); + const off2 = t2.on('frameRate', () => {}); + expect(() => off2()).not.toThrow(); + } finally { + vi.useRealTimers(); + } + }); + + it('falls back to Date.now when performance.now is absent', () => { + vi.useFakeTimers(); + const perf = Object.getOwnPropertyDescriptor(globalThis, 'performance'); + Object.defineProperty(globalThis, 'performance', { value: undefined, configurable: true }); + try { + const w = mkWorld(); + const t = new UiTracker({ ...w.env, scheduler: undefined, now: undefined, intervalMs: 100 }); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + w.frame(); + vi.advanceTimersByTime(100); + expect(got).toEqual([10]); + } finally { + if (perf !== undefined) Object.defineProperty(globalThis, 'performance', perf); + vi.useRealTimers(); + } + }); +}); + +describe('UiTracker failure isolation', () => { + it('guards every read: a hostile env is reported, nothing throws', () => { + const errors: unknown[] = []; + const boom = (): never => { + throw new Error('hostile'); + }; + const hostile = { + get window() { + return boom(); + }, + get screen() { + return boom(); + }, + get matchMedia() { + return boom(); + }, + } as unknown as UiEnv; + const t = new UiTracker(hostile, (e) => errors.push(e)); + for (const s of [ + 'orientation', + 'screenSize', + 'viewport', + 'colorScheme', + 'displayMode', + ] as const) { + expect(t.current(s)).toBeUndefined(); + } + expect(errors).toHaveLength(3); // the three hostile fields, reported once at the copy + for (const s of [ + 'orientation', + 'screenSize', + 'viewport', + 'colorScheme', + 'reducedMotion', + 'displayMode', + ] as const) { + expect(() => t.on(s, () => {})).not.toThrow(); + } + }); + + it('guards the inner reads (getters on the window/screen/orientation/query list) and a throwing matchMedia call', () => { + const errors: unknown[] = []; + const boom = (): never => { + throw new Error('hostile'); + }; + const t = new UiTracker( + { + window: { + get devicePixelRatio() { + return boom(); + }, + get innerWidth() { + return boom(); + }, + get innerHeight() { + return boom(); + }, + }, + screen: { + get width() { + return boom(); + }, + get height() { + return boom(); + }, + orientation: { + get type() { + return boom(); + }, + get angle() { + return boom(); + }, + }, + }, + matchMedia: boom, + }, + (e) => errors.push(e), + ); + for (const s of ['orientation', 'screenSize', 'viewport', 'colorScheme'] as const) { + expect(t.current(s)).toBeUndefined(); + } + expect(errors.length).toBeGreaterThanOrEqual(7); + const t2 = new UiTracker( + { + matchMedia: () => ({ + get matches() { + return boom(); + }, + }), + }, + (e) => errors.push(e), + ); + expect(t2.current('colorScheme')).toBeUndefined(); + }); + + it('a throwing onError never escapes (read, DOM listener, and attach paths)', () => { + const w = mkWorld(); + const t = new UiTracker( + { + ...w.env, + window: Object.assign(mkTarget(), { + devicePixelRatio: 1, + addEventListener: () => { + throw new Error('attach'); + }, + }) as never, + }, + () => { + throw new Error('reporter'); + }, + ); + expect(() => t.on('screenSize', () => {})).not.toThrow(); + const w2 = mkWorld(); + const t2 = new UiTracker(w2.env, () => { + throw new Error('reporter'); + }); + t2.on('orientation', () => { + throw new Error('consumer'); + }); + w2.orientation.angle = 90; + expect(() => w2.win.fire('orientationchange')).not.toThrow(); + // a throwing read inside a DOM listener is reported, not thrown + t2.on('viewport', () => {}); + Object.defineProperty(w2.win, 'innerWidth', { + get() { + throw new Error('read'); + }, + }); + expect(() => w2.win.fire('resize')).not.toThrow(); + // a listener body that itself throws (screen getter in refresh) is caught by the wrapper + const t3 = new UiTracker(w2.env, () => {}); + t3.on('screenSize', () => {}); + expect(() => w2.win.fire('resize')).not.toThrow(); + }); + + it('the guarded wrapper reports a throw from inside the listener body', () => { + const w = mkWorld(); + const errors: unknown[] = []; + const t = new UiTracker(w.env, (e) => errors.push(e)); + t.on('colorScheme', () => {}); + const d = q(w, '(prefers-color-scheme: dark)'); + d.fire('change', null); // event.matches on null throws inside the guarded listener + expect(errors).toHaveLength(1); + }); + + it('removal failures are swallowed and do not leak the other listeners', () => { + const w = mkWorld(); + const removed: string[] = []; + const win = { + devicePixelRatio: 1, + addEventListener: () => {}, + removeEventListener: (type: string) => { + removed.push(type); + throw new Error('remove'); + }, + }; + const t = new UiTracker({ ...w.env, window: win }); + const off = t.on('orientation', () => {}); + expect(() => off()).not.toThrow(); + expect(removed).toEqual(['orientationchange']); + }); +}); + +describe('UiTracker reset and listener hooks', () => { + it('reset releases everything (listeners, timers) and forgets baselines', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + t.on('frameRate', () => {}); + t.on('orientation', () => {}); + t.reset(); + expect(w.doc.total() + w.win.total() + w.orientation.total()).toBe(0); + expect(w.env.scheduler.clearInterval).toHaveBeenCalled(); + }); + + it('onAny and once participate in per-stage activation', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const off = t.onAny(() => {}); + expect(w.win.count('resize')).toBe(1); + expect(w.doc.count('visibilitychange')).toBe(1); + off(); + expect(w.win.total()).toBe(0); + const offOnce = t.once('viewport', () => {}); + expect(w.win.count('resize')).toBe(1); + offOnce(); + expect(w.win.count('resize')).toBe(0); + }); +}); + +describe('uiTrackerFor registry + rebind', () => { + it('is a singleton per window; latest onError wins; env merges not drops', () => { + const w = mkWorld(); + const first: unknown[] = []; + const second: unknown[] = []; + const a = uiTrackerFor({ window: w.win }, (e) => first.push(e)); + const b = uiTrackerFor({ window: w.win, screen: w.screen }, (e) => second.push(e)); + expect(a).toBe(b); + expect(b.current('screenSize')).toEqual({ width: 1000, height: 2000, dpr: 2 }); + const c = uiTrackerFor({ window: w.win }); // partial relaunch: keeps screen and the reporter + expect(c.current('screenSize')).toBeDefined(); + resetUiTracker({ window: w.win }); + expect(uiTrackerFor({ window: w.win })).not.toBe(a); + }); + + it('rebind of an attached tracker re-attaches the changed source to the new object', () => { + const w = mkWorld(); + const t = uiTrackerFor({ window: w.win, screen: w.screen }); + const got: unknown[] = []; + t.on('screenSize', (s) => got.push(s)); + const screen2 = Object.assign(mkTarget(), { width: 4, height: 6 }); + uiTrackerFor({ window: w.win, screen: screen2 }); + expect(w.screen.count('change')).toBe(0); + expect(screen2.count('change')).toBe(1); + screen2.width = 5; + screen2.fire('change'); + expect(got).toEqual([{ width: 5, height: 6, dpr: 2 }]); + uiTrackerFor({ window: w.win, screen: screen2 }); // identical env: nothing re-attached + expect(screen2.count('change')).toBe(1); + resetUiTracker({ window: w.win }); + expect(screen2.count('change')).toBe(0); + }); + + it('keys on the screen without a window, and privately on a bare env', () => { + const screen = Object.assign(mkTarget(), { width: 1, height: 1 }); + expect(uiTrackerFor({ screen })).toBe(uiTrackerFor({ screen })); + resetUiTracker({ screen }); + const env = {}; + expect(uiTrackerFor(env)).toBe(uiTrackerFor(env)); + expect(uiTrackerFor({})).not.toBe(uiTrackerFor({})); + resetUiTracker(env); + }); + + it('keying survives a throwing window/screen read (reported)', () => { + const errors: unknown[] = []; + const env = { + get window(): never { + throw new Error('w'); + }, + get screen(): never { + throw new Error('s'); + }, + } as unknown as UiEnv; + expect(uiTrackerFor(env, (e) => errors.push(e))).toBeInstanceOf(UiTracker); + expect(errors.length).toBeGreaterThanOrEqual(2); + }); +}); + +describe('UiTracker review fixes', () => { + const mkScheduler = () => { + const cbs: Array<() => void> = []; + const cleared: number[] = []; + return { + cbs, + cleared, + scheduler: { + setInterval: (cb: () => void) => cbs.push(cb) - 1, + clearInterval: (h: unknown) => void cleared.push(h as number), + }, + }; + }; + + it('a rebind that swaps the scheduler clears the OLD interval on the OLD scheduler and runs one interval', () => { + const w = mkWorld(); + const a = mkScheduler(); + const b = mkScheduler(); + const t = uiTrackerFor({ ...w.env, scheduler: a.scheduler }); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + expect(a.cbs).toHaveLength(1); + uiTrackerFor({ window: w.win, scheduler: b.scheduler }); + expect(a.cleared).toEqual([0]); // cleared with the handle A handed out, on A + expect(b.cleared).toEqual([]); + expect(b.cbs).toHaveLength(1); + w.frame(); + w.frame(); + w.advance(1000); + a.cbs[0]?.(); // a stale tick from the old interval is ignored (loop guard) + expect(got).toEqual([]); + b.cbs[0]?.(); + expect(got).toEqual([2]); + resetUiTracker({ window: w.win }); + }); + + it('a stale interval whose clear failed never touches the live window', () => { + const w = mkWorld(); + const cbs: Array<() => void> = []; + const t = new UiTracker({ + ...w.env, + scheduler: { setInterval: (cb) => cbs.push(cb), clearInterval: () => {} }, + }); + const got: number[] = []; + const off = t.on('frameRate', (f) => got.push(f)); + off(); + t.on('frameRate', (f) => got.push(f)); + w.frame(); + w.advance(1000); + cbs[0]?.(); // old loop's tick: ignored + expect(got).toEqual([]); + cbs[1]?.(); + expect(got).toEqual([1]); + }); + + it('a tick from a loop stopped by a hidden page is ignored even when the clear is a no-op (running guard)', () => { + const w = mkWorld(); + const cbs: Array<() => void> = []; + const t = new UiTracker({ + ...w.env, + scheduler: { setInterval: (cb) => cbs.push(cb), clearInterval: () => {} }, + }); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); // stays subscribed + w.frame(); + w.doc.visibilityState = 'hidden'; + w.doc.fire('visibilitychange'); // the loop stops; the interval callback is still callable + w.advance(1000); + cbs[0]?.(); + expect(got).toEqual([]); + }); + + it('a stage whose re-read yields nothing forgets its baseline', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: unknown[] = []; + const off = t.on('screenSize', (s) => got.push(s)); + off(); + w.screen.width = Number.NaN; // unreadable while nobody listens + t.on('screenSize', (s) => got.push(s)); // baseline re-read: nothing -> forgotten + w.screen.width = 1000; // back to the value the OLD baseline held + w.win.fire('resize'); + expect(got).toEqual([{ width: 1000, height: 2000, dpr: 2 }]); + }); + + it('frameRate with a document that cannot deliver visibilitychange never starts a loop', () => { + const w = mkWorld(); + new UiTracker({ ...w.env, document: { visibilityState: 'visible' } }).on('frameRate', () => {}); + expect(w.env.requestAnimationFrame).not.toHaveBeenCalled(); + expect(w.env.scheduler.setInterval).not.toHaveBeenCalled(); + }); + + it('reset() forgets which stages were listened, so a later subscriber re-baselines', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + const got: unknown[] = []; + t.on('orientation', (s) => got.push(s)); // stays subscribed across the reset + t.reset(); + t.on('viewport', () => {}); // any listener change re-syncs: orientation re-attaches + w.win.fire('orientationchange'); // nothing moved + expect(got).toEqual([]); + }); + + it('repeated uiTrackerFor calls with FRESH function closures do not reset a running fps window', () => { + const w = mkWorld(); + const fresh = () => ({ + window: w.win, + screen: w.screen, + document: w.doc, + scheduler: w.env.scheduler, + matchMedia: (q: string) => w.env.matchMedia(q), + requestAnimationFrame: (cb: (t: number) => void) => w.env.requestAnimationFrame(cb), + cancelAnimationFrame: (h: number) => w.env.cancelAnimationFrame(h), + now: () => w.env.now(), + }); + const t = uiTrackerFor(fresh()); + const got: number[] = []; + t.on('frameRate', (f) => got.push(f)); + w.frame(); + uiTrackerFor(fresh()); + uiTrackerFor(fresh()); + expect(w.env.scheduler.setInterval).toHaveBeenCalledTimes(1); + expect(w.env.scheduler.clearInterval).not.toHaveBeenCalled(); + w.frame(); + w.advance(1000); + w.tick(); + expect(got).toEqual([2]); // the frame counted before the relaunches is kept + expect(w.doc.count('visibilitychange')).toBe(1); + resetUiTracker({ window: w.win }); + }); + + it('a rebind onto new sources re-baselines from them (no spurious announcement of the swap)', () => { + const w = mkWorld(); + const t = uiTrackerFor({ window: w.win, screen: w.screen }); + const got: unknown[] = []; + t.on('screenSize', (s) => got.push(s)); + const screen2 = Object.assign(mkTarget(), { width: 4, height: 6 }); + uiTrackerFor({ window: w.win, screen: screen2 }); + screen2.fire('change'); // nothing moved on the NEW screen + expect(got).toEqual([]); + resetUiTracker({ window: w.win }); + }); + + it('a swapped function seam is used from then on (no re-attach)', () => { + const w = mkWorld(); + const t = uiTrackerFor({ window: w.win, screen: w.screen }); + t.on('colorScheme', () => {}); + const swapped = vi.fn(() => ({ matches: true })); + uiTrackerFor({ window: w.win, matchMedia: swapped }); + expect(t.current('colorScheme')).toEqual({ dark: true }); + resetUiTracker({ window: w.win }); + }); + + it('a stage that gains its first listener re-baselines even when its source is attached for a sibling', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + t.on('orientation', () => {}); // the orientation source is attached; screenSize is NOT being computed + w.screen.width = 1; + w.win.fire('orientationchange'); + const sizes: unknown[] = []; + t.on('screenSize', (s) => sizes.push(s)); // baseline is now width 1 + w.screen.width = 1000; // back to the value it had before the first listener + w.win.fire('orientationchange'); + expect(sizes).toEqual([{ width: 1000, height: 2000, dpr: 2 }]); + }); + + it('screenSize/viewport siblings on the shared resize source re-baseline too', () => { + const w = mkWorld(); + const t = new UiTracker(w.env); + t.on('screenSize', () => {}); + w.win.innerWidth = 500; + w.win.fire('resize'); // viewport has no listener: not computed + const views: unknown[] = []; + t.on('viewport', (v) => views.push(v)); + w.win.innerWidth = 800; + w.win.fire('resize'); + expect(views).toEqual([{ width: 800, height: 600 }]); + }); + + it('a stage without listeners is not even read on an event of a sibling source', () => { + const w = mkWorld(); + const reads = vi.fn(() => 600); + Object.defineProperty(w.win, 'innerHeight', { get: reads }); + const t = new UiTracker(w.env); + t.on('screenSize', () => {}); + const before = reads.mock.calls.length; + w.win.devicePixelRatio = 3; + w.win.fire('resize'); + expect(reads.mock.calls.length).toBe(before); + }); + + it('displayMode is omitted when a query failed and none of the answered ones matched', () => { + const w = mkWorld(); + let failing = true; + const t = new UiTracker({ + matchMedia: (q) => { + if (failing && q.includes('standalone')) throw new Error('q'); + return w.env.matchMedia(q); + }, + }); + expect(t.current('displayMode')).toBeUndefined(); + q(w, '(display-mode: fullscreen)').matches = true; + expect(t.current('displayMode')).toEqual({ mode: 'fullscreen' }); + failing = false; + q(w, '(display-mode: fullscreen)').matches = false; + expect(t.current('displayMode')).toEqual({ mode: 'browser' }); + }); + + it('only a visible document runs the frame loop (prerender / missing state do not)', () => { + for (const state of ['prerender', 'hidden', undefined]) { + const w = mkWorld(); + Object.assign(w.doc, { visibilityState: state }); + new UiTracker(w.env).on('frameRate', () => {}); + expect(w.env.scheduler.setInterval).not.toHaveBeenCalled(); + expect(w.doc.count('visibilitychange')).toBe(1); // still gated on later changes + } + }); + + it('latest onError wins; a relaunch without one keeps it', () => { + const w = mkWorld(); + const first: unknown[] = []; + const second: unknown[] = []; + const win = mkTarget(); + Object.defineProperty(win, 'devicePixelRatio', { + get(): never { + throw new Error('dpr'); + }, + }); + const t = uiTrackerFor({ window: win, screen: w.screen }, (e) => first.push(e)); + t.current('screenSize'); + expect(first).toHaveLength(1); + uiTrackerFor({ window: win }, (e) => second.push(e)); + t.current('screenSize'); + expect(first).toHaveLength(1); + expect(second).toHaveLength(1); + uiTrackerFor({ window: win }); // undefined onError keeps the second + t.current('screenSize'); + expect(second).toHaveLength(2); + resetUiTracker({ window: win }); + }); +}); diff --git a/packages/trackers/src/browser/ui-tracker.ts b/packages/trackers/src/browser/ui-tracker.ts new file mode 100644 index 00000000..4cd3e9d8 --- /dev/null +++ b/packages/trackers/src/browser/ui-tracker.ts @@ -0,0 +1,666 @@ +import { MultiKeyEmitterBase } from '../emitter'; +import { createTrackerRegistry } from '../tracker-registry'; +import { hostRead } from './host-read'; + +// Browser UI / DISPLAY tracker (domain tracker; Android reference: BugseeTrackerUI/Display). ONE class +// owns every window-side display signal and exposes them as notification kinds ("stages"): +// +// orientation {type?, angle?} screen.orientation `change` + window `orientationchange` (engines differ in which fire) +// screenSize {width,height,dpr} CSS px of screen.* and devicePixelRatio; window `resize`/`orientationchange`, screen `change` +// viewport {width,height} window.innerWidth/innerHeight; window `resize`/`orientationchange` +// colorScheme {dark} matchMedia (prefers-color-scheme: dark) +// reducedMotion {reduce} matchMedia (prefers-reduced-motion: reduce) +// displayMode {mode} matchMedia (display-mode: fullscreen | standalone | minimal-ui), else 'browser' +// frameRate number requestAnimationFrame callbacks per second, only while the page is visible +// +// It does NOT use the page-lifecycle tracker: the frame-rate gate listens for `visibilitychange` itself. +// +// PER-STAGE ACTIVATION. A listener/timer exists only while some subscriber wants a stage it feeds (window `resize` +// while screenSize or viewport has a listener, the rAF loop + interval + visibilitychange only while frameRate does, +// ...). Subscribing attaches, the last unsubscribe detaches, through the emitter's `onListenersChanged` hook. +// +// RETENTION. Nothing survives the last unsubscribe except (a) the env seams and (b) the per-stage DE-DUPLICATION +// baseline (the last emitted value, so a repeated reading is not re-announced). The baseline is RE-READ silently +// whenever a stage goes from no listener to one (and when a rebind swaps the sources under running stages), so a +// change that happened while nobody listened to THAT stage — even if its source stayed attached for a sibling +// stage — is never mistaken for "unchanged" later. A stage with no listener is not computed at all. `current(stage)` always reads live (never a stale value) and is `undefined` when the reading is +// unavailable or invalid. Invalid values (non-finite / non-positive sizes, a non-boolean query) are OMITTED, never +// zeroed. Only the frame-rate window state (frames counted, timer) is dropped on stop: a later window starts fresh. +// +// Failure isolation: every host read goes through `hostRead` and is reported via `onError`; a throwing `onError` never +// escapes; every DOM listener and timer/rAF callback is wrapped so nothing throws into the host's event dispatch. + +export interface OrientationState { + /** The engine's `screen.orientation.type`. Omitted when it is not a string. */ + type?: string; + /** `screen.orientation.angle`. Omitted when it is not a finite number. */ + angle?: number; +} +export interface ScreenSizeState { + width: number; + height: number; + dpr: number; +} +export interface ViewportState { + width: number; + height: number; +} +export interface ColorSchemeState { + dark: boolean; +} +export interface ReducedMotionState { + reduce: boolean; +} +export type DisplayModeName = 'fullscreen' | 'standalone' | 'minimal-ui' | 'browser'; +export interface DisplayModeState { + mode: DisplayModeName; +} + +/** Notification kinds -> payloads. */ +export interface UiStages { + orientation: OrientationState; + screenSize: ScreenSizeState; + viewport: ViewportState; + colorScheme: ColorSchemeState; + reducedMotion: ReducedMotionState; + displayMode: DisplayModeState; + frameRate: number; +} +export type UiStage = keyof UiStages; +/** The stages that have a readable current state (everything but the polled frame rate). */ +export type UiStateStage = Exclude; + +interface TargetLike { + addEventListener(type: string, listener: (event?: unknown) => void): void; + removeEventListener(type: string, listener: (event?: unknown) => void): void; +} +export interface MediaQueryListLike { + readonly matches?: unknown; + addEventListener?( + type: 'change', + listener: (event: { readonly matches?: unknown }) => void, + ): void; + removeEventListener?( + type: 'change', + listener: (event: { readonly matches?: unknown }) => void, + ): void; +} +export interface UiSchedulerLike { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +} + +/** The seams a launch hands the tracker. Every field is optional: an absent surface just omits its stages. */ +export interface UiEnv { + /** The window the SDK is bound to: `resize`/`orientationchange`, the LIVE `devicePixelRatio`, inner size. */ + window?: Partial & { + readonly devicePixelRatio?: unknown; + readonly innerWidth?: unknown; + readonly innerHeight?: unknown; + }; + screen?: Partial & { + readonly width?: unknown; + readonly height?: unknown; + readonly orientation?: Partial & { + readonly type?: unknown; + readonly angle?: unknown; + }; + }; + /** `window.matchMedia` BOUND to that window (never the host's). */ + matchMedia?: (query: string) => MediaQueryListLike; + /** Visibility source and `visibilitychange` target of the frame-rate gate. */ + document?: Partial & { readonly visibilityState?: unknown }; + requestAnimationFrame?: (callback: (timestamp: number) => void) => number; + cancelAnimationFrame?: (handle: number) => void; + /** Monotonic ms. Default `performance.now()`, else `Date.now()`. */ + now?: () => number; + scheduler?: UiSchedulerLike; + /** Frame-rate window length. Default 1000. */ + intervalMs?: number; +} + +// This package has no DOM/Node lib: the global timers are reached through a cast. +const timers = globalThis as unknown as { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +}; +const defaultScheduler: UiSchedulerLike = { + setInterval: (cb, ms) => timers.setInterval(cb, ms), + clearInterval: (h) => timers.clearInterval(h), +}; +const defaultNow = (): number => { + const p = (globalThis as { performance?: { now?: () => number } }).performance; + return typeof p?.now === 'function' ? p.now() : Date.now(); +}; + +const positive = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v > 0; +const UI_STAGES: readonly UiStage[] = [ + 'orientation', + 'screenSize', + 'viewport', + 'colorScheme', + 'reducedMotion', + 'displayMode', + 'frameRate', +]; +const DARK = '(prefers-color-scheme: dark)'; +const REDUCED = '(prefers-reduced-motion: reduce)'; +const DISPLAY_MODES = ['fullscreen', 'standalone', 'minimal-ui'] as const; + +const FUNCTION_SEAMS: ReadonlySet = new Set([ + 'matchMedia', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'now', +]); + +const ENV_KEYS = [ + 'window', + 'screen', + 'matchMedia', + 'document', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'now', + 'scheduler', + 'intervalMs', +] as const; + +interface Binding { + readonly id: string; + readonly kinds: readonly UiStage[]; + /** Attach the source(s); push each undo onto `offs` BEFORE doing anything that may throw. */ + attach(offs: Array<() => void>): void; +} + +export class UiTracker extends MultiKeyEmitterBase { + readonly name = 'browser-ui'; + readonly #env: UiEnv; + // Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. + readonly #reporter: { fn: ((error: unknown) => void) | undefined }; + readonly #report: (error: unknown) => void; + /** De-duplication baselines (serialized last emitted value) per stage. */ + readonly #last = new Map(); + /** The stages that had a listener at the last sync (a stage entering it re-baselines). */ + readonly #wanted = new Set(); + readonly #attached = new Map void>>(); + readonly #bindings: readonly Binding[]; + // frame-rate machinery (alive only inside the frameRate binding) + #timer: unknown = null; + #raf: number | undefined; + #running = false; + #frames = 0; + #seenFrame = false; + #windowStart = 0; + #loop = 0; + + constructor(env: UiEnv, onError?: (error: unknown) => void) { + const reporter = { fn: onError }; + // A throwing reporter must not escape into the host's event dispatch, a timer, or `on()`. + const report = (error: unknown): void => { + try { + reporter.fn?.(error); + } catch { + /* the reporter itself failed; nothing left to tell */ + } + }; + super(report); + this.#reporter = reporter; + this.#report = report; + // Copied field by field through `hostRead`: an env with a hostile getter costs only that field (reported). + this.#env = {}; + Object.assign(this.#env, this.#pending(env)); + this.#bindings = this.#makeBindings(); + } + + /** + * Hand the latest launch's seams to this shared tracker (latest launch wins, MERGE not drop). A defined `onError` + * replaces the reporter; a defined env field replaces ours; an undefined one never clobbers it. If a replaced + * field changes a source that is currently attached, those sources are re-attached to the new objects. + */ + rebind(env: UiEnv, onError?: (error: unknown) => void): void { + if (onError !== undefined) this.#reporter.fn = onError; + const pending = this.#pending(env); + // Only a change of a SOURCE (window/screen/document/scheduler/interval) re-attaches. The function seams + // (matchMedia, rAF, cancelAnimationFrame, now) are rebuilt as fresh closures by every launch for the same + // window, so they are swapped in place and a running frame-rate window is left alone. + const resource = Object.keys(pending).some((key) => !FUNCTION_SEAMS.has(key)); + // Detach with the OLD seams (the old scheduler clears its own interval) BEFORE the new ones are applied: the + // interval is cleared on `#env.scheduler`, so this ORDER is what keeps it on the scheduler that armed it. + if (resource) { + this.#detachAll(); + // The sources moved: every stage that STILL has listeners re-baselines silently from the new sources (a swap + // is not announced as a change; a real change made while the old sources were detached is not announced + // either, the new subscriber-visible value simply becomes the reference). + this.#wanted.clear(); + } + Object.assign(this.#env, pending); + if (resource) this.#sync(); + } + + /** The env's defined fields that differ from ours (a hostile getter is reported and skipped). */ + #pending(env: UiEnv): Record { + const pending: Record = {}; + const current = this.#env as Record; + for (const key of ENV_KEYS) { + const next = hostRead(() => (env as Record)[key], this.#report); + if (next !== undefined && next !== current[key]) pending[key] = next; + } + return pending; + } + + /** The LIVE reading of a stage (guarded, reported); undefined when unavailable or invalid. */ + current(stage: K): UiStages[K] | undefined { + return this.#read(stage) as UiStages[K] | undefined; + } + + /** Test/teardown: release every listener, timer and baseline. */ + reset(): void { + this.#detachAll(); + this.#last.clear(); + this.#wanted.clear(); + } + + protected override onListenersChanged(): void { + this.#sync(); + } + + #sync(): void { + // A stage that just gained its first listener re-reads its baseline silently — even when its source is already + // attached for a sibling stage, which may have moved the value while this one was not being computed. + for (const stage of UI_STAGES) { + const listened = this.listenerCount(stage) > 0; + if (!listened) this.#wanted.delete(stage); + else if (!this.#wanted.has(stage)) { + this.#wanted.add(stage); + if (stage !== 'frameRate') this.#remember(stage, this.#read(stage)); + } + } + for (const binding of this.#bindings) { + const want = binding.kinds.some((kind) => this.listenerCount(kind) > 0); + const has = this.#attached.has(binding.id); + if (want && !has) this.#attach(binding); + else if (!want && has) this.#detach(binding.id); + } + } + + #attach(binding: Binding): void { + const offs: Array<() => void> = []; + this.#attached.set(binding.id, offs); // recorded first: a throw below still leaves something to undo + try { + binding.attach(offs); + } catch (error) { + this.#report(error); + } + } + + #detach(id: string): void { + const offs = this.#attached.get(id) ?? []; + this.#attached.delete(id); + for (const off of offs) { + try { + off(); + } catch { + /* best-effort: one failed removal must not leak the others */ + } + } + } + + #detachAll(): void { + for (const id of [...this.#attached.keys()]) this.#detach(id); + } + + // ---- readers (each value validated; undefined = omit) ------------------------------------------------------- + + #read(stage: UiStateStage): UiStages[UiStateStage] | undefined { + const report = this.#report; + switch (stage) { + case 'orientation': { + const o = hostRead(() => this.#env.screen?.orientation, report); + if (o === undefined) return undefined; + const type = hostRead(() => o.type, report); + const angle = hostRead(() => o.angle, report); + const state: OrientationState = { + ...(typeof type === 'string' ? { type } : {}), + ...(typeof angle === 'number' && Number.isFinite(angle) ? { angle } : {}), + }; + return Object.keys(state).length === 0 ? undefined : state; + } + case 'screenSize': { + const screen = hostRead(() => this.#env.screen, report); + if (screen === undefined) return undefined; + const width = hostRead(() => screen.width, report); + const height = hostRead(() => screen.height, report); + const dpr = hostRead(() => this.#env.window?.devicePixelRatio, report); + return positive(width) && positive(height) && positive(dpr) + ? { width, height, dpr } + : undefined; + } + case 'viewport': { + const win = hostRead(() => this.#env.window, report); + if (win === undefined) return undefined; + const width = hostRead(() => win.innerWidth, report); + const height = hostRead(() => win.innerHeight, report); + return positive(width) && positive(height) ? { width, height } : undefined; + } + case 'colorScheme': { + const dark = this.#matches(DARK); + return dark === undefined ? undefined : { dark }; + } + case 'reducedMotion': { + const reduce = this.#matches(REDUCED); + return reduce === undefined ? undefined : { reduce }; + } + case 'displayMode': + return this.#displayMode( + DISPLAY_MODES.map((mode) => this.#matches(`(display-mode: ${mode})`)), + ); + } + } + + #matches(query: string): boolean | undefined { + const report = this.#report; + const mm = hostRead(() => this.#env.matchMedia, report); + if (typeof mm !== 'function') return undefined; + const list = hostRead(() => mm(query), report); + if (list === undefined || list === null) return undefined; + const matches = hostRead(() => list.matches, report); + return typeof matches === 'boolean' ? matches : undefined; + } + + /** The first matching mode; 'browser' when all queries answered and none matched; undefined when any failed and none matched. */ + #displayMode(matches: ReadonlyArray): DisplayModeState | undefined { + const hit = DISPLAY_MODES[matches.indexOf(true)]; // undefined when none matched (index -1) + if (hit !== undefined) return { mode: hit }; + // 'browser' is a CLAIM that none of the modes apply: only made when every query answered. + return matches.includes(undefined) ? undefined : { mode: 'browser' }; + } + + // ---- emission ------------------------------------------------------------------------------------------------- + + #remember(stage: UiStage, value: unknown): void { + if (value === undefined) this.#last.delete(stage); + else this.#last.set(stage, JSON.stringify(value)); + } + + /** Emit `value` unless it equals the last emitted one. An undefined value (nothing valid to say) is never emitted. */ + #publish(stage: K, value: UiStages[K] | undefined): void { + if (value === undefined) return; + const serialized = JSON.stringify(value); + if (this.#last.get(stage) === serialized) return; + this.#last.set(stage, serialized); + this.emit(stage, value); + } + + /** Re-read and publish the stages that have listeners. */ + #refresh(stages: readonly UiStateStage[]): void { + for (const stage of stages) { + if (this.listenerCount(stage) > 0) this.#publish(stage, this.#read(stage) as never); + } + } + + /** A DOM listener: nothing it does may throw into the host's event dispatch. */ + #guarded(fn: (...args: A) => void): (...args: A) => void { + return (...args) => { + try { + fn(...args); + } catch (error) { + this.#report(error); + } + }; + } + + #listen( + offs: Array<() => void>, + target: Partial | undefined, + type: string, + listener: (event?: unknown) => void, + ): void { + if (typeof target?.addEventListener !== 'function') return; + offs.push(() => target.removeEventListener?.(type, listener)); + target.addEventListener(type, listener); + } + + #watchQuery( + offs: Array<() => void>, + query: string, + listener: (event: { readonly matches?: unknown }) => void, + ): void { + const mm = hostRead(() => this.#env.matchMedia, this.#report); + if (typeof mm !== 'function') return; + const list = hostRead(() => mm(query), this.#report); + if (list === undefined || list === null || typeof list.addEventListener !== 'function') return; + offs.push(() => list.removeEventListener?.('change', listener)); + list.addEventListener('change', listener); + } + + // ---- sources -------------------------------------------------------------------------------------------------- + + #makeBindings(): readonly Binding[] { + const env = (): UiEnv => this.#env; + const geometry: readonly UiStateStage[] = ['screenSize', 'viewport']; + return [ + { + id: 'resize', + kinds: geometry, + attach: (offs) => + this.#listen( + offs, + env().window, + 'resize', + this.#guarded(() => this.#refresh(geometry)), + ), + }, + { + id: 'orientation', + kinds: ['orientation', ...geometry], + attach: (offs) => { + // Engines differ in which of the two fires; the de-duplication collapses a double delivery. + const onChange = this.#guarded(() => this.#onOrientation()); + this.#listen( + offs, + hostRead(() => env().screen?.orientation, this.#report), + 'change', + onChange, + ); + this.#listen(offs, env().window, 'orientationchange', onChange); + }, + }, + { + id: 'screen', + kinds: ['screenSize'], + attach: (offs) => + this.#listen( + offs, + env().screen, + 'change', + this.#guarded(() => this.#refresh(['screenSize'])), + ), + }, + { + id: 'colorScheme', + kinds: ['colorScheme'], + attach: (offs) => + this.#watchQuery( + offs, + DARK, + this.#guarded((event) => { + if (typeof event.matches === 'boolean') + this.#publish('colorScheme', { dark: event.matches }); + }), + ), + }, + { + id: 'reducedMotion', + kinds: ['reducedMotion'], + attach: (offs) => + this.#watchQuery( + offs, + REDUCED, + this.#guarded((event) => { + if (typeof event.matches === 'boolean') + this.#publish('reducedMotion', { reduce: event.matches }); + }), + ), + }, + { + id: 'displayMode', + kinds: ['displayMode'], + attach: (offs) => { + const onChange = this.#guarded(() => this.#refresh(['displayMode'])); + for (const mode of DISPLAY_MODES) + this.#watchQuery(offs, `(display-mode: ${mode})`, onChange); + }, + }, + { id: 'frameRate', kinds: ['frameRate'], attach: (offs) => this.#attachFrameRate(offs) }, + ]; + } + + /** An orientation event: the orientation itself (an empty `{}` when the engine cannot read one) plus the geometry. */ + #onOrientation(): void { + if (this.listenerCount('orientation') > 0) { + const state = this.#read('orientation') as OrientationState | undefined; + // Without a readable orientation there is nothing to compare: announce the bare event, undeduplicated. + if (state === undefined) this.emit('orientation', {}); + else this.#publish('orientation', state); + } + this.#refresh(['screenSize', 'viewport']); + } + + // ---- frame rate (rAF counter; only while the page is visible) ------------------------------------------------- + // Hidden, unmeasurable, or without rAF/visibility events it emits NOTHING: omit, never zero. Once frames have + // flowed, the first window without any is reported as 0 (the main thread stopped painting) and a continuing stall + // then goes quiet; before the first frame nothing is reported (rAF can be paused while the page says `visible`). + + #attachFrameRate(offs: Array<() => void>): void { + const env = this.#env; + // No frames to count, or no visibility events to gate on (a hidden tab must never keep a frame loop): omit. + if (typeof env.requestAnimationFrame !== 'function') return; + const doc = env.document; + if (typeof doc?.addEventListener !== 'function') return; + offs.push(() => this.#stopLoop()); + const onVisibility = this.#guarded(() => { + if (this.#isVisible()) this.#startLoop(); + else this.#stopLoop(); + }); + this.#listen(offs, doc, 'visibilitychange', onVisibility); + if (this.#isVisible()) this.#startLoop(); + } + + #isVisible(): boolean { + return hostRead(() => this.#env.document?.visibilityState, this.#report) === 'visible'; + } + + #startLoop(): void { + if (this.#running) return; + this.#running = true; + this.#loop += 1; + this.#seenFrame = false; + this.#frames = 0; + try { + // The clock read is inside the guarded setup: a throwing clock must roll the run back like any other setup + // failure, or `#running` would stay true with no loop and block every later start. + this.#windowStart = (this.#env.now ?? defaultNow)(); + this.#arm(); + const scheduler = this.#env.scheduler ?? defaultScheduler; + const loop = this.#loop; + this.#timer = scheduler.setInterval( + // A tick from a loop that is no longer current (its clear failed) must never touch the live window. + this.#guarded(() => { + if (this.#running && loop === this.#loop) this.#tick(); + }), + this.#env.intervalMs ?? 1000, + ); + } catch (error) { + this.#report(error); + this.#stopLoop(); // never leave a half-started loop behind + } + } + + #stopLoop(): void { + this.#running = false; + if (this.#timer !== null) { + try { + (this.#env.scheduler ?? defaultScheduler).clearInterval(this.#timer); + } catch { + /* best-effort */ + } + } + this.#timer = null; + const raf = this.#raf; + this.#raf = undefined; + if (raf !== undefined) { + try { + this.#env.cancelAnimationFrame?.(raf); + } catch { + /* best-effort */ + } + } + } + + #arm(): void { + const loop = this.#loop; + this.#raf = this.#env.requestAnimationFrame?.(() => { + // A frame already in flight when its loop stopped (cancelAnimationFrame missing or failed) must not count + // or re-arm — not even after a restart, or two loops would run and fps would read double. + if (!this.#running || loop !== this.#loop) return; + this.#seenFrame = true; + this.#frames += 1; + try { + this.#arm(); + } catch (error) { + this.#report(error); + } + }); + } + + #tick(): void { + let now: number; + try { + now = (this.#env.now ?? defaultNow)(); + } catch (error) { + this.#report(error); // an unreadable clock skips this window + return; + } + const elapsed = now - this.#windowStart; + if (!(elapsed > 0)) return; // a zero-length (or non-finite) window has no rate + if (!this.#seenFrame) { + this.#windowStart = now; // the stalled stretch must not dilute the first measured window + return; + } + const fps = Math.round(((this.#frames * 1000) / elapsed) * 10) / 10; + if (this.#frames === 0) this.#seenFrame = false; + this.#frames = 0; + this.#windowStart = now; + this.emit('frameRate', fps); // the emitter isolates and reports a throwing consumer + } +} + +const registry = createTrackerRegistry(); + +// The key is the window the SDK is bound to; failing that the screen; failing that the env object itself (an +// ad-hoc env then gets a private tracker). Host reads are guarded AND reported. +function keyOf(env: UiEnv, onError?: (error: unknown) => void): object { + const win = hostRead(() => env.window, onError); + if (typeof win === 'object' && win !== null) return win; + const screen = hostRead(() => env.screen, onError); + if (typeof screen === 'object' && screen !== null) return screen; + return env; +} + +/** + * The singleton UiTracker for the env's window. Every call (a relaunch included) hands the shared tracker the latest + * launch's `onError` and the env fields it defines (see {@link UiTracker.rebind}: merge, never drop). + */ +export function uiTrackerFor(env: UiEnv, onError?: (error: unknown) => void): UiTracker { + return registry.for( + keyOf(env, onError), + () => new UiTracker(env, onError), + (tracker) => tracker.rebind(env, onError), + ); +} + +/** Test/teardown: drop the env's tracker (resetting it, so its listeners and timers are released). */ +export function resetUiTracker(env: UiEnv): void { + registry.reset(keyOf(env)); +} diff --git a/packages/trackers/src/emitter.test.ts b/packages/trackers/src/emitter.test.ts index 78dc8bbb..7bd31ff1 100644 --- a/packages/trackers/src/emitter.test.ts +++ b/packages/trackers/src/emitter.test.ts @@ -350,3 +350,52 @@ describe('createMultiKeyEmitter factory', () => { expect(fn).toHaveBeenCalledWith({ status: 204 }); }); }); + +class ListenerHookProbe extends MultiKeyEmitterBase<{ a: number; b: number }> { + calls = 0; + counts: Array<[number, number]> = []; + protected override onListenersChanged(): void { + this.calls += 1; + this.counts.push([this.listenerCount('a'), this.listenerCount('b')]); + } +} + +describe('MultiKeyEmitterBase — onListenersChanged / listenerCount', () => { + it('fires after every mutation with per-key counts (onAny counts for every key)', () => { + const p = new ListenerHookProbe(); + const offA = p.on('a', () => {}); + expect(p.counts.at(-1)).toEqual([1, 0]); + const offAny = p.onAny(() => {}); + expect(p.counts.at(-1)).toEqual([2, 1]); + p.once('b', () => {}); + expect(p.counts.at(-1)).toEqual([2, 2]); + offAny(); + expect(p.counts.at(-1)).toEqual([1, 1]); + offA(); + p.removeAllListeners('b'); + expect(p.counts.at(-1)).toEqual([0, 0]); + const before = p.calls; + p.removeAllListeners(); + expect(p.calls).toBe(before + 1); + }); +}); + +class OrderProbe extends MultiKeyEmitterBase<{ a: number }> { + order: string[] = []; + protected override onActiveChange(active: boolean): void { + this.order.push(`active:${active}`); + } + protected override onListenersChanged(): void { + this.order.push('changed'); + } +} + +describe('MultiKeyEmitterBase — onListenersChanged runs AFTER onActiveChange', () => { + it('orders the two hooks on activation and on deactivation', () => { + const p = new OrderProbe(); + const off = p.on('a', () => {}); + expect(p.order).toEqual(['active:true', 'changed']); + off(); + expect(p.order).toEqual(['active:true', 'changed', 'active:false', 'changed']); + }); +}); diff --git a/packages/trackers/src/emitter.ts b/packages/trackers/src/emitter.ts index e17a7a6a..02b2ffa2 100644 --- a/packages/trackers/src/emitter.ts +++ b/packages/trackers/src/emitter.ts @@ -82,9 +82,21 @@ export class MultiKeyEmitterBase implements MultiKeyEmitter { if (before !== this.#hasListeners()) { this.onActiveChange(!before); } + this.onListenersChanged(); return result; } + /** How many listeners would receive `name` right now (its own plus every onAny listener). */ + protected listenerCount(name: keyof M): number { + return (this.#channels.get(name)?.size ?? 0) + this.#anyListeners.size; + } + + /** + * Fired after EVERY listener-set mutation (even one that changed nothing), once any {@link onActiveChange} has run. + * For owners that bind a resource per stage and need to re-evaluate which stages have listeners; must be idempotent. + */ + protected onListenersChanged(): void {} + #dispatch(run: () => void): void { try { run(); diff --git a/packages/trackers/src/index.test.ts b/packages/trackers/src/index.test.ts index 4de6cc9e..60b3dedf 100644 --- a/packages/trackers/src/index.test.ts +++ b/packages/trackers/src/index.test.ts @@ -23,6 +23,7 @@ describe('@bugsee/trackers public surface', () => { 'ConnectivityTracker', 'PowerTracker', 'StorageTracker', + 'UiTracker', 'applicationTrackerFor', 'connectivityTrackerFor', 'hostRead', @@ -31,7 +32,9 @@ describe('@bugsee/trackers public surface', () => { 'resetConnectivityTracker', 'resetPowerTracker', 'resetStorageTracker', + 'resetUiTracker', 'storageTrackerFor', + 'uiTrackerFor', ]); }); }); diff --git a/packages/webview/src/launch.test.ts b/packages/webview/src/launch.test.ts index 27effc3f..f22bfb31 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -428,7 +428,8 @@ describe('launch (webview)', () => { 'tok', baseOptions({ global: fake.global, window: win.target as unknown as WindowEvents }), ); - expect(thisSeen).toEqual([win.target]); + expect(thisSeen).toHaveLength(2); // the baseline read + the change watch + expect(thisSeen.every((t) => t === win.target)).toBe(true); for (const f of [...listeners]) f({ matches: true }); const has = (msgs: ReturnType) => entriesOfType(msgs.msgs(), 'events.system').some((e) =>