diff --git a/.changeset/application-tracker.md b/.changeset/application-tracker.md new file mode 100644 index 00000000..bd1433de --- /dev/null +++ b/.changeset/application-tracker.md @@ -0,0 +1,11 @@ +--- +'@bugsee/browser': minor +'@bugsee/webview': minor +'@bugsee/trackers': minor +--- + +`PageLifecycleTracker` becomes the domain `ApplicationTracker` (`applicationTrackerFor`, `ApplicationEnv`, `ApplicationEvents`, `ApplicationState` exported from `@bugsee/trackers/browser` and re-exported by `@bugsee/browser`). It is a singleton per document (else window), gains an aggregated, de-duplicated `state` stage (`foreground`/`background`) and `current()`, and retains the last known state while no one is subscribed (DOM listeners still attach on the first subscriber and detach on the last). `AppStateProducer` consumes `state`; the `app_state` trace and the `events.system` names and shapes are unchanged. `online`/`offline`/`orientationchange` remain on it until the Connectivity and UI trackers take them. + +Two behaviour changes on an UNREADABLE document (missing, non-string or throwing `visibilityState`): the `app_state` trace no longer reports `background`, and no `visibility` is emitted at all, so `process_background` is no longer recorded and the fps sampler is no longer paused on a fabricated hide. The tracker is shared per document, and the latest launch's `onError` is the reporter. An injected window without a document no longer borrows the host document in the events-source fallback. + +Behaviour change for standalone `createBrowserSystemEventsSource` callers that pass NO `lifecycle`: the host-global fallback is all-or-nothing. If either `window` or `document` is injected, the other is never taken from the host globals (an injected env must not borrow the host's), so e.g. `{ document }` alone no longer also receives the host window's `pagehide`/`online`/`offline`/`orientationchange` events. Pass both, or neither, to keep full coverage. Browser and webview launch always pass a tracker and are unaffected. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 3b13f666..c89b37b7 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -407,6 +407,7 @@ solid), in slices: - **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). - **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. - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.ts index caeae909..adfe9235 100644 --- a/packages/browser/src/index.ts +++ b/packages/browser/src/index.ts @@ -16,6 +16,13 @@ export { type LifecycleEventsListener, type LifecycleEventType, } from '@bugsee/core'; +export { + type ApplicationEnv, + type ApplicationEvents, + type ApplicationState, + ApplicationTracker, + applicationTrackerFor, +} from '@bugsee/trackers/browser'; export { COMPONENT_ATTRIBUTE, componentNameFromElement } from './component-name'; export { createUnhandledRejectionProvider, @@ -92,11 +99,6 @@ export { createBrowserSystemTraceProducers, defaultBrowserTraceEnv, } from './trace-producers'; -export { - type PageLifecycleEnv, - type PageLifecycleEvents, - PageLifecycleTracker, -} from './trackers/page-lifecycle-tracker'; export { createUiBreadcrumbProvider, createUiBreadcrumbSource, diff --git a/packages/browser/src/launch.test.ts b/packages/browser/src/launch.test.ts index 6401348c..7bbb0926 100644 --- a/packages/browser/src/launch.test.ts +++ b/packages/browser/src/launch.test.ts @@ -42,6 +42,7 @@ import { type RequestJson, Severity, } from '@bugsee/protocol'; +import { applicationTrackerFor } from '@bugsee/trackers/browser'; import { strFromU8, unzipSync } from '@bugsee/util'; import { IDBFactory } from 'fake-indexeddb'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -492,6 +493,80 @@ describe('launch', () => { expect(doc.count('visibilitychange')).toBe(0); }); + describe('launch goes through the ApplicationTracker registry', () => { + const blockedDoc = () => { + const doc = fakeWindow(); + const boom = new Error('visibilityState blocked'); + const state = { armed: false }; + Object.defineProperty(doc.win, 'visibilityState', { + get() { + if (state.armed) throw boom; + return 'visible'; + }, + }); + return { doc, boom, state, document: doc.win as unknown as Document }; + }; + + it('shares ONE tracker per document: a lookup for the launched document sees the launch listeners, not a second set', async () => { + const w = fakeWindow(); + const { document } = blockedDoc(); + await launchTracked( + 'tok', + baseOptions({ window: w.win, document, captureStore: memStore() }), + ); + expect(w.count('online')).toBe(1); + const shared = applicationTrackerFor({ window: w.win as never, document }); + const off = shared.on('online', () => {}); + expect(w.count('online')).toBe(1); // the SAME tracker: one listener serves launch and this subscriber + off(); + }); + + it("the latest launch's onError becomes the reporter; a relaunch without one keeps it", async () => { + const w = fakeWindow(); + const { doc, boom, state, document } = blockedDoc(); + const first = vi.fn(); + const second = vi.fn(); + // The tracker's own read fails only while the event is dispatched (launch itself reads the document too). + const fireBlocked = () => { + state.armed = true; + try { + doc.emit('visibilitychange', {}); + } catch { + /* a real DOM dispatch never propagates a listener's throw */ + } finally { + state.armed = false; + } + }; + const run = async (onError?: (e: unknown) => void) => { + const client = await launch( + 'tok', + baseOptions({ + window: w.win, + document, + captureStore: memStore(), + ...(onError !== undefined ? { onError } : {}), + }), + ); + return client; + }; + await (await run(first)).stop(); + await (await run(second)).stop(); + first.mockClear(); + second.mockClear(); + const live = await run(second); + clients.push(live); + fireBlocked(); + expect(second).toHaveBeenCalledWith(boom); + expect(first).not.toHaveBeenCalledWith(boom); + await live.stop(); + second.mockClear(); + const bare = await run(); // no onError: must NOT silence the earlier launch's sink + clients.push(bare); + fireBlocked(); + expect(second).toHaveBeenCalledWith(boom); + }); + }); + describe('dark mode, freeze and resume events (from the injected window + document)', () => { const mkMedia = () => { const l = new Set<(e: { matches: boolean }) => void>(); diff --git a/packages/browser/src/launch.ts b/packages/browser/src/launch.ts index e17843a5..f60d6b5f 100644 --- a/packages/browser/src/launch.ts +++ b/packages/browser/src/launch.ts @@ -75,6 +75,7 @@ import { type UploadResult, } from '@bugsee/core'; import { BugseeOption, type EnvironmentEnvelope } from '@bugsee/protocol'; +import { applicationTrackerFor } from '@bugsee/trackers/browser'; import { reportGuarded } from '@bugsee/util'; import { BROWSER_APP_VERSION_HINT, metaAppIdentity, warnToConsole } from './app-identity'; import type { WindowEvents } from './detection-providers'; @@ -97,7 +98,6 @@ import { import { parseStack } from './stack'; import { createBrowserSystemEventsSource } from './system-events'; import { browserTraceEnvFrom, createBrowserSystemTraceProducers } from './trace-producers'; -import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; import { createUiBreadcrumbProvider, createUiBreadcrumbSource } from './ui-breadcrumb-source'; import { createUserIdentifierStore } from './user-identifier-store'; import { createBrowserViewportSource } from './viewport-source'; @@ -878,7 +878,7 @@ async function buildLaunch( 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. - const lifecycle = new PageLifecycleTracker( + 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 0559b949..470dd9e3 100644 --- a/packages/browser/src/system-events.test.ts +++ b/packages/browser/src/system-events.test.ts @@ -1,7 +1,7 @@ import type { SystemEvent } from '@bugsee/capture'; +import { ApplicationTracker, resetApplicationTracker } from '@bugsee/trackers/browser'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { type BrowserSystemEventsEnv, createBrowserSystemEventsSource } from './system-events'; -import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; afterEach(() => { vi.unstubAllGlobals(); @@ -302,9 +302,45 @@ describe('createBrowserSystemEventsSource', () => { 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 }); + const b = activate({ ...env, window: win as never }); + expect(doc.count('visibilitychange')).toBe(1); + a.off(); + expect(doc.count('visibilitychange')).toBe(1); + b.off(); + expect(doc.count('visibilitychange')).toBe(0); + resetApplicationTracker({ document: env.document as never }); + }); + + it('an injected window without a document never borrows the host document (nor binds its singleton)', () => { + const hostWin = target(); + const hostDoc = target(); + vi.stubGlobal('window', hostWin); + vi.stubGlobal('document', { ...hostDoc, visibilityState: 'visible' }); + const injected = target(); + const off = createBrowserSystemEventsSource({ window: injected as never }).onAny(() => {}); + expect(injected.count('pagehide')).toBe(1); + expect(hostDoc.count('visibilitychange')).toBe(0); + expect(hostWin.count('pagehide')).toBe(0); + off(); + }); + + it('an injected document without a window never borrows the host window', () => { + const hostWin = target(); + vi.stubGlobal('window', hostWin); + const doc = target(); + const off = createBrowserSystemEventsSource({ + document: { ...doc, visibilityState: 'visible' } as never, + }).onAny(() => {}); + expect(hostWin.count('pagehide')).toBe(0); + off(); + }); + it('subscribes to an injected shared lifecycle tracker instead of attaching its own listeners', () => { const { env, win, doc } = fakeEnv(); - const lifecycle = new PageLifecycleTracker({ window: win, document: env.document as never }); + const lifecycle = new ApplicationTracker({ window: win, document: env.document as never }); const a = activate({ ...env, lifecycle }); const b = activate({ ...env, lifecycle }); // two sources over ONE tracker → one listener per type @@ -329,14 +365,14 @@ describe('createBrowserSystemEventsSource', () => { }); const { off } = activate({ ...env, onError }); expect(() => doc.emit('visibilitychange', {})).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledTimes(2); // the activation read + the event read, each reported once expect(win.count('pagehide')).toBe(1); off(); }); it('over a shared tracker, re-subscribing after a full release re-emits process_started and resubscribes', () => { const { env, win } = fakeEnv(); - const lifecycle = new PageLifecycleTracker({ window: win, document: env.document as never }); + const lifecycle = new ApplicationTracker({ window: win, document: env.document as never }); const source = createBrowserSystemEventsSource({ ...env, lifecycle }); const events: SystemEvent[] = []; const first = source.onAny((_s, e) => events.push(e)); diff --git a/packages/browser/src/system-events.ts b/packages/browser/src/system-events.ts index 3736c8b6..ea0842d5 100644 --- a/packages/browser/src/system-events.ts +++ b/packages/browser/src/system-events.ts @@ -1,8 +1,8 @@ import type { SystemEvent } from '@bugsee/capture'; import { type Interceptor, InterceptorBase } from '@bugsee/core'; +import { type ApplicationTracker, applicationTrackerFor } from '@bugsee/trackers/browser'; import type { WindowEvents } from './detection-providers'; import { hostGlobal } from './host-global'; -import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; // 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 @@ -44,20 +44,20 @@ export interface BrowserSystemEventsEnv { */ matchMedia?: (query: string) => MediaQueryLike; /** The shared lifecycle tracker; when absent one is created over `window` + `document`. */ - lifecycle?: Pick; + lifecycle?: Pick; onError?: (error: unknown) => void; } class BrowserSystemEventsSource extends InterceptorBase<{ event: SystemEvent }> { readonly name = 'browser-system-events'; - readonly #lifecycle: Pick; + readonly #lifecycle: Pick; readonly #screen: ScreenLike | undefined; readonly #matchMedia: ((query: string) => MediaQueryLike) | undefined; readonly #onError: (error: unknown) => void; #unsubscribe: Array<() => void> = []; constructor( - lifecycle: Pick, + lifecycle: Pick, screenLike: ScreenLike | undefined, matchMedia?: (query: string) => MediaQueryLike, onError?: (error: unknown) => void, @@ -144,10 +144,12 @@ export function createBrowserSystemEventsSource( // The host globals are read only when no lifecycle tracker was supplied: a supplied one already owns them. const lifecycle = env.lifecycle ?? - ((): PageLifecycleTracker => { - const win = env.window ?? hostGlobal('window', env.onError); - const doc = env.document ?? hostGlobal('document', env.onError); - return new PageLifecycleTracker( + ((): 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( { ...(win !== undefined ? { window: win } : {}), ...(doc !== undefined ? { document: doc } : {}), diff --git a/packages/browser/src/trace-producers.screen-lag.test.ts b/packages/browser/src/trace-producers.screen-lag.test.ts index 9f127490..03d3fdb8 100644 --- a/packages/browser/src/trace-producers.screen-lag.test.ts +++ b/packages/browser/src/trace-producers.screen-lag.test.ts @@ -1,4 +1,5 @@ import type { TraceProducer } from '@bugsee/capture'; +import { ApplicationTracker } from '@bugsee/trackers/browser'; import { describe, expect, it } from 'vitest'; import { browserTraceEnvFrom, @@ -7,7 +8,6 @@ import { ScreenSizeProducer, } from './trace-producers'; import { MainThreadLagTracker } from './trackers/main-thread-lag-tracker'; -import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; import { ScreenSizeTracker } from './trackers/screen-size-tracker'; function mkTarget() { @@ -87,7 +87,7 @@ describe('MainThreadLagProducer', () => { it('emits each tick drift as a POLLED value (hold:false), including a true 0, and releases on stop', () => { const win = mkTarget(); const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); - const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + const lifecycle = new ApplicationTracker({ window: win, document: doc }); let timer: (() => void) | undefined; let now = 0; const tracker = new MainThreadLagTracker({ @@ -126,7 +126,7 @@ describe('MainThreadLagProducer', () => { describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', () => { it('are added with a lifecycle (same gate as app_state/fps) and absent without one', () => { const win = mkTarget(); - const lifecycle = new PageLifecycleTracker({ window: win }); + const lifecycle = new ApplicationTracker({ window: win }); expect(names(createBrowserSystemTraceProducers({ lifecycle }))).toEqual( expect.arrayContaining(['screen-size', 'main-thread-lag']), ); @@ -139,7 +139,7 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', }); it('sensors:false builds the battery producer only', () => { - const lifecycle = new PageLifecycleTracker({ window: mkTarget() }); + const lifecycle = new ApplicationTracker({ window: mkTarget() }); expect(names(createBrowserSystemTraceProducers({ lifecycle, sensors: false }))).toEqual([ 'battery', ]); @@ -153,7 +153,7 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', performance: { now: () => t }, }); const doc = { visibilityState: 'visible' }; - const lifecycle = new PageLifecycleTracker({ + const lifecycle = new ApplicationTracker({ window: win, document: Object.assign(mkTarget(), doc), }); @@ -188,7 +188,7 @@ describe('createBrowserSystemTraceProducers: screen_size + main_thread_lag_ms', it('a window without a performance clock starts no timer and reports nothing (no error)', () => { const win = Object.assign(mkTarget(), { screen: { width: 1, height: 1 }, devicePixelRatio: 1 }); const doc = { visibilityState: 'visible' }; - const lifecycle = new PageLifecycleTracker({ + const lifecycle = new ApplicationTracker({ window: win, document: Object.assign(mkTarget(), doc), }); @@ -233,7 +233,7 @@ describe('performance.now wiring (lag and fps)', () => { }; const mkLifecycle = () => { const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); - return { doc, lifecycle: new PageLifecycleTracker({ window: mkTarget(), document: doc }) }; + return { doc, lifecycle: new ApplicationTracker({ window: mkTarget(), document: doc }) }; }; it('the lag and fps clocks are called as performance.now() (this === performance), with no error', () => { @@ -286,7 +286,7 @@ describe('main_thread_lag_ms clock wiring', () => { it('a performance.now that is not a function omits the trace quietly (no timer, no error)', () => { const win = mkTarget(); const doc = Object.assign(mkTarget(), { visibilityState: 'visible' }); - const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + const lifecycle = new ApplicationTracker({ window: win, document: doc }); let timers = 0; const errors: unknown[] = []; const lag = createBrowserSystemTraceProducers( diff --git a/packages/browser/src/trace-producers.ts b/packages/browser/src/trace-producers.ts index 60484fe1..c705ce44 100644 --- a/packages/browser/src/trace-producers.ts +++ b/packages/browser/src/trace-producers.ts @@ -1,6 +1,7 @@ import { type TraceProducer, TraceProducerBase } from '@bugsee/capture'; import type { Scheduler } from '@bugsee/core'; import { + type ApplicationTracker, type BatteryEnv, type BatteryManagerLike, type BatteryState, @@ -21,7 +22,6 @@ import { type OrientationState, OrientationTracker, } from './trackers/orientation-tracker'; -import type { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; import { type ScreenSizeEnv, type ScreenSizeState, @@ -213,30 +213,22 @@ export class OrientationProducer extends TraceProducerBase { */ export class AppStateProducer extends TraceProducerBase { readonly name = 'app-state'; - readonly #lifecycle: Pick; - readonly #document: { readonly visibilityState?: string } | undefined; + readonly #application: Pick; #off: (() => void) | undefined; - constructor( - lifecycle: Pick, - document: { readonly visibilityState?: string } | undefined, - ) { + constructor(application: Pick) { super(); - this.#lifecycle = lifecycle; - this.#document = document; + this.#application = application; } protected onStart(): void { - this.#off = this.#lifecycle.on('visibility', ({ visible }) => - this.emitIfChanged('app_state', visible ? 'foreground' : 'background'), + // Subscribe first (it activates the tracker and refreshes its retained state), then read the initial value. + this.#off = this.#application.on('state', ({ state }) => + this.emitIfChanged('app_state', state), ); - try { - const state = this.#document?.visibilityState; - if (state !== undefined) - this.emitIfChanged('app_state', state === 'visible' ? 'foreground' : 'background'); - } catch { - /* an unreadable document yields no initial value; the next visibility change still reports */ - } + // No known state (no/unreadable document) = no initial value; the next change still reports. + const initial = this.#application.current(); + if (initial !== undefined) this.emitIfChanged('app_state', initial); } protected override onStop(): void { @@ -356,8 +348,8 @@ export interface BrowserTraceEnv extends BatteryEnv { sensors?: boolean; /** Drives the heap poll; default the global timers. */ scheduler?: Scheduler; - /** Shared page-lifecycle tracker for connection/orientation; when absent each listens on `window`. */ - lifecycle?: Pick; + /** The shared ApplicationTracker feeding connection/orientation, app_state and fps; when absent connection/orientation listen on `window` and app_state/fps are omitted. */ + lifecycle?: Pick; } interface WindowSurfaces { @@ -509,7 +501,7 @@ export function createBrowserSystemTraceProducers( ), ...(env.lifecycle !== undefined ? [ - new AppStateProducer(env.lifecycle, env.document), + new AppStateProducer(env.lifecycle), new ScreenSizeProducer( new ScreenSizeTracker( { diff --git a/packages/browser/src/trace-producers.visibility.test.ts b/packages/browser/src/trace-producers.visibility.test.ts index 4298bd79..e31ac2f5 100644 --- a/packages/browser/src/trace-producers.visibility.test.ts +++ b/packages/browser/src/trace-producers.visibility.test.ts @@ -1,4 +1,5 @@ import type { TraceProducer } from '@bugsee/capture'; +import { ApplicationTracker } from '@bugsee/trackers/browser'; import { describe, expect, it } from 'vitest'; import { AppStateProducer, @@ -8,7 +9,6 @@ import { FpsProducer, } from './trace-producers'; import { FpsTracker } from './trackers/fps-tracker'; -import { PageLifecycleTracker } from './trackers/page-lifecycle-tracker'; function mkTarget() { const l = new Map void>>(); @@ -29,7 +29,7 @@ function mkTarget() { function mkPage(visible = true) { const win = mkTarget(); const doc = Object.assign(mkTarget(), { visibilityState: visible ? 'visible' : 'hidden' }); - const lifecycle = new PageLifecycleTracker({ window: win, document: doc }); + const lifecycle = new ApplicationTracker({ window: win, document: doc }); return { win, doc, @@ -56,7 +56,7 @@ describe('AppStateProducer', () => { const page = mkPage(); page.doc.visibilityState = vis; const out: Emit[] = []; - new AppStateProducer(page.lifecycle, page.doc).start(sinkOf(out)); + new AppStateProducer(page.lifecycle).start(sinkOf(out)); expect(out).toEqual([{ name: 'app_state', value: want, hold: true }]); } }); @@ -64,7 +64,7 @@ describe('AppStateProducer', () => { it('follows visibility changes, held and de-duplicated', () => { const page = mkPage(); const out: Emit[] = []; - new AppStateProducer(page.lifecycle, page.doc).start(sinkOf(out)); + new AppStateProducer(page.lifecycle).start(sinkOf(out)); page.setVisible(false); page.setVisible(false); page.setVisible(true); @@ -72,32 +72,48 @@ describe('AppStateProducer', () => { expect(out.every((o) => o.hold === true)).toBe(true); }); - it('with no document there is no initial value, but changes still report', () => { - const page = mkPage(); + it('with no readable state there is no initial value, but changes still report', () => { + const doc = mkTarget(); // no visibilityState at all + const lifecycle = new ApplicationTracker({ window: mkTarget(), document: doc }); const out: Emit[] = []; - new AppStateProducer(page.lifecycle, undefined).start(sinkOf(out)); + new AppStateProducer(lifecycle).start(sinkOf(out)); expect(out).toEqual([]); - page.setVisible(false); + Object.assign(doc, { visibilityState: 'hidden' }); + doc.fire('visibilitychange'); expect(out.map((o) => o.value)).toEqual(['background']); }); - it('a throwing visibilityState read yields no initial value', () => { - const page = mkPage(); - const doc = {}; + it('a throwing visibilityState read yields no initial value and never throws', () => { + const doc = mkTarget(); Object.defineProperty(doc, 'visibilityState', { get(): never { throw new Error('vis'); }, }); + const errors: unknown[] = []; + const lifecycle = new ApplicationTracker({ document: doc }, (e) => errors.push(e)); const out: Emit[] = []; - expect(() => new AppStateProducer(page.lifecycle, doc).start(sinkOf(out))).not.toThrow(); + expect(() => new AppStateProducer(lifecycle).start(sinkOf(out))).not.toThrow(); expect(out).toEqual([]); + expect(errors.length).toBeGreaterThan(0); + }); + + it('a producer started after a hidden gap reports the CURRENT state, not a stale one', () => { + const page = mkPage(); + const first = new AppStateProducer(page.lifecycle); + const out: Emit[] = []; + first.start(sinkOf(out)); + first.stop(); + page.doc.visibilityState = 'hidden'; // while nobody listened + const out2: Emit[] = []; + new AppStateProducer(page.lifecycle).start(sinkOf(out2)); + expect(out2.map((o) => o.value)).toEqual(['background']); }); it('stop() releases the lifecycle subscription', () => { const page = mkPage(); const out: Emit[] = []; - const p = new AppStateProducer(page.lifecycle, page.doc); + const p = new AppStateProducer(page.lifecycle); p.start(sinkOf(out)); expect(page.doc.count()).toBe(3); // visibilitychange + freeze + resume (the shared lifecycle's document listeners) p.stop(); diff --git a/packages/browser/src/trackers/connection-tracker.test.ts b/packages/browser/src/trackers/connection-tracker.test.ts index 06fcc5da..81ae166c 100644 --- a/packages/browser/src/trackers/connection-tracker.test.ts +++ b/packages/browser/src/trackers/connection-tracker.test.ts @@ -1,6 +1,6 @@ +import { ApplicationTracker } from '@bugsee/trackers/browser'; import { describe, expect, it, vi } from 'vitest'; import { ConnectionTracker } from './connection-tracker'; -import { PageLifecycleTracker } from './page-lifecycle-tracker'; function mkTarget() { const l = new Map void>>(); @@ -191,7 +191,7 @@ describe('ConnectionTracker', () => { it('with a shared lifecycle it takes online/offline from it and attaches NO window listener of its own', () => { const win = mkTarget(); const connection = mkTarget(); - const lifecycle = new PageLifecycleTracker({ window: win as never }); + const lifecycle = new ApplicationTracker({ window: win as never }); const t = new ConnectionTracker({ lifecycle, window: win, diff --git a/packages/browser/src/trackers/connection-tracker.ts b/packages/browser/src/trackers/connection-tracker.ts index 60a781bc..2ec8232f 100644 --- a/packages/browser/src/trackers/connection-tracker.ts +++ b/packages/browser/src/trackers/connection-tracker.ts @@ -1,5 +1,5 @@ import { InterceptorBase } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; +import type { ApplicationTracker } from '@bugsee/trackers/browser'; // Browser connectivity TRACKER (mirrors the mobile tracker/producer split): snapshots `navigator.onLine` // plus NetworkInformation whenever the browser says either changed — `online`/`offline` on the window and @@ -25,7 +25,7 @@ interface TargetLike { } export interface ConnectionEnv { /** Shared lifecycle tracker for `online`/`offline`; when absent they are listened for on `window`. */ - lifecycle?: Pick; + lifecycle?: Pick; window?: TargetLike; navigator?: { /** NetworkInformation; it is an EventTarget where it exists, but the fields are what matter. */ diff --git a/packages/browser/src/trackers/fps-tracker.ts b/packages/browser/src/trackers/fps-tracker.ts index abe74213..b303afee 100644 --- a/packages/browser/src/trackers/fps-tracker.ts +++ b/packages/browser/src/trackers/fps-tracker.ts @@ -1,5 +1,5 @@ import { InterceptorBase, type Scheduler } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; +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 @@ -12,7 +12,7 @@ import type { PageLifecycleTracker } from './page-lifecycle-tracker'; export interface FpsEnv { /** Shared lifecycle tracker for visibility changes. */ - lifecycle?: Pick; + lifecycle?: Pick; /** Visibility is read here at activation; unknown (absent) counts as not visible. */ document?: { readonly visibilityState?: string }; requestAnimationFrame?: (callback: (timestamp: number) => void) => number; diff --git a/packages/browser/src/trackers/main-thread-lag-tracker.ts b/packages/browser/src/trackers/main-thread-lag-tracker.ts index 3dfd4c8e..8265139a 100644 --- a/packages/browser/src/trackers/main-thread-lag-tracker.ts +++ b/packages/browser/src/trackers/main-thread-lag-tracker.ts @@ -1,5 +1,5 @@ import { InterceptorBase, type Scheduler } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; +import type { ApplicationTracker } from '@bugsee/trackers/browser'; // Browser main-thread responsiveness TRACKER (`main_thread_lag_ms`): TIMER DRIFT. The sampling timer runs on the // page's main thread, so on every tick `lag = max(0, now - (previousTickTime + intervalMs))` is how late it fired. @@ -30,7 +30,7 @@ import type { PageLifecycleTracker } from './page-lifecycle-tracker'; export interface MainThreadLagEnv { /** Shared lifecycle tracker for visibility changes. */ - lifecycle?: Pick; + lifecycle?: Pick; /** Visibility is read here at activation; unknown (absent) counts as not visible. */ document?: { readonly visibilityState?: string }; /** Monotonic ms (the injected `performance.now`); absent omits the trace — no wall-clock guess. */ diff --git a/packages/browser/src/trackers/orientation-tracker.test.ts b/packages/browser/src/trackers/orientation-tracker.test.ts index dbd3b099..0607b7fd 100644 --- a/packages/browser/src/trackers/orientation-tracker.test.ts +++ b/packages/browser/src/trackers/orientation-tracker.test.ts @@ -1,6 +1,6 @@ +import { ApplicationTracker } from '@bugsee/trackers/browser'; import { describe, expect, it, vi } from 'vitest'; import { OrientationTracker } from './orientation-tracker'; -import { PageLifecycleTracker } from './page-lifecycle-tracker'; function mkTarget() { const l = new Map void>>(); @@ -165,7 +165,7 @@ describe('OrientationTracker', () => { 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 PageLifecycleTracker({ window: win as never }); + 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)); diff --git a/packages/browser/src/trackers/orientation-tracker.ts b/packages/browser/src/trackers/orientation-tracker.ts index ab433384..ff145e4e 100644 --- a/packages/browser/src/trackers/orientation-tracker.ts +++ b/packages/browser/src/trackers/orientation-tracker.ts @@ -1,5 +1,5 @@ import { InterceptorBase } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; +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 @@ -16,7 +16,7 @@ interface TargetLike { } export interface OrientationEnv { /** Shared lifecycle tracker for `orientationchange`; when absent it is listened for on `window`. */ - lifecycle?: Pick; + lifecycle?: Pick; window?: TargetLike; screen?: { orientation?: { type: string; angle: number } & Partial; diff --git a/packages/browser/src/trackers/page-lifecycle-tracker.test.ts b/packages/browser/src/trackers/page-lifecycle-tracker.test.ts deleted file mode 100644 index 294bd524..00000000 --- a/packages/browser/src/trackers/page-lifecycle-tracker.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { PageLifecycleTracker } from './page-lifecycle-tracker'; - -function mkTarget() { - const l = new Map void>>(); - return { - addEventListener: (t: string, f: (e: unknown) => void) => { - const s = l.get(t) ?? new Set<(e: unknown) => void>(); - s.add(f); - l.set(t, s); - }, - removeEventListener: (t: string, f: (e: unknown) => void) => void l.get(t)?.delete(f), - fire: (t: string, e: unknown = {}) => - l.get(t)?.forEach((f) => { - f(e); - }), - count: (t?: string) => - t === undefined ? [...l.values()].reduce((n, s) => n + s.size, 0) : (l.get(t)?.size ?? 0), - }; -} - -function mkEnv() { - const win = mkTarget(); - const doc = Object.assign(mkTarget(), { visibilityState: 'visible' as string }); - return { win, doc }; -} - -describe('PageLifecycleTracker', () => { - it('attaches nothing until the first subscriber', () => { - const { win, doc } = mkEnv(); - new PageLifecycleTracker({ window: win, document: doc }); - expect(win.count() + doc.count()).toBe(0); - }); - - it('attaches pagehide/online/offline/orientationchange on window and visibilitychange on document', () => { - const { win, doc } = mkEnv(); - const t = new PageLifecycleTracker({ window: win, document: doc }); - t.on('online', () => {}); - for (const type of ['pagehide', 'online', 'offline', 'orientationchange']) { - expect(win.count(type)).toBe(1); - } - expect(doc.count('visibilitychange')).toBe(1); - }); - - it('freeze and resume are Page Lifecycle events on the DOCUMENT (they do not bubble to window)', () => { - const { win, doc } = mkEnv(); - const t = new PageLifecycleTracker({ window: win, document: doc }); - const seen: string[] = []; - t.on('freeze', () => seen.push('freeze')); - t.on('resume', () => seen.push('resume')); - expect(doc.count('freeze')).toBe(1); - expect(doc.count('resume')).toBe(1); - expect(win.count('freeze')).toBe(0); - expect(win.count('resume')).toBe(0); - win.fire('freeze'); // a window listener beside pagehide would never see these: nothing happens - doc.fire('freeze'); - doc.fire('resume'); - expect(seen).toEqual(['freeze', 'resume']); - }); - - it('freeze/resume without a document attach nothing (not on the window either) and do not throw', () => { - const { win } = mkEnv(); - const t = new PageLifecycleTracker({ window: win }); - let off: (() => void) | undefined; - expect(() => { - off = t.on('freeze', () => {}); - }).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 - off?.(); - }); - - it('a document that refuses only freeze/resume still delivers visibility', () => { - const { win, doc } = mkEnv(); - const realAdd = doc.addEventListener; - doc.addEventListener = (type, f) => { - if (type === 'freeze' || type === 'resume') throw new Error('newer types refused'); - realAdd(type, f); - }; - const errors: unknown[] = []; - const t = new PageLifecycleTracker({ window: win, document: doc }, (e) => errors.push(e)); - const seen: boolean[] = []; - t.on('visibility', (e) => seen.push(e.visible)); - doc.visibilityState = 'hidden'; - doc.fire('visibilitychange'); - expect(seen).toEqual([false]); - expect(errors).toHaveLength(1); - }); - - it('releases everything on the last unsubscribe and re-attaches on the next subscriber', () => { - const { win, doc } = mkEnv(); - const t = new PageLifecycleTracker({ window: win, document: doc }); - const offA = t.on('online', () => {}); - const offB = t.on('offline', () => {}); - offA(); - expect(win.count() + doc.count()).toBe(7); - offB(); - expect(win.count() + doc.count()).toBe(0); - t.on('online', () => {}); - expect(win.count() + doc.count()).toBe(7); - }); - - it('removes each listener exactly once per activation cycle (no stale entries replayed on a later stop)', () => { - const { win, doc } = mkEnv(); - const removes = vi.fn(); - const realRemove = win.removeEventListener; - win.removeEventListener = (t, f) => { - removes(t); - realRemove(t, f); - }; - const t = new PageLifecycleTracker({ window: win, document: doc }); - t.on('online', () => {})(); - t.on('online', () => {})(); - expect(removes).toHaveBeenCalledTimes(8); - }); - - it('emits typed events', () => { - const { win, doc } = mkEnv(); - const t = new PageLifecycleTracker({ window: win, document: doc }); - const seen: unknown[] = []; - t.on('pagehide', (e) => seen.push(['pagehide', e])); - 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'; - doc.fire('visibilitychange'); - doc.visibilityState = 'visible'; - doc.fire('visibilitychange'); - win.fire('online'); - win.fire('offline'); - win.fire('orientationchange'); - expect(seen).toEqual([ - ['pagehide', { persisted: true }], - ['pagehide', { persisted: false }], - ['visibility', { visible: false }], - ['visibility', { visible: true }], - ['online'], - ['offline'], - ['orientationchange'], - ]); - }); - - it('works with no document and with no window', () => { - const { win, doc } = mkEnv(); - const onlyWin = new PageLifecycleTracker({ window: win }); - onlyWin.on('online', () => {})(); - const onlyDoc = new PageLifecycleTracker({ document: doc }); - onlyDoc.on('visibility', () => {}); - expect(doc.count('visibilitychange')).toBe(1); - expect(() => new PageLifecycleTracker({}).on('online', () => {})()).not.toThrow(); - }); - - it('a missing visibilityState counts as not visible', () => { - const win = mkTarget(); - const doc = mkTarget(); - const t = new PageLifecycleTracker({ window: win, document: doc }); - const seen: unknown[] = []; - t.on('visibility', (e) => seen.push(e)); - doc.fire('visibilitychange'); - expect(seen).toEqual([{ visible: false }]); - }); - - it('a throwing getter in the event path is reported, never thrown into dispatch', () => { - const win = mkTarget(); - const onError = vi.fn(); - const doc = mkTarget(); - Object.defineProperty(doc, 'visibilityState', { - get(): never { - throw new Error('getter'); - }, - }); - const t = new PageLifecycleTracker({ window: win, document: doc }, onError); - t.on('visibility', () => {}); - expect(() => doc.fire('visibilitychange')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - }); - - it('a throwing addEventListener is reported and what attached is still released', () => { - const win = mkTarget(); - const onError = vi.fn(); - const doc = mkTarget(); - doc.addEventListener = () => { - throw new Error('detached'); - }; - const t = new PageLifecycleTracker({ window: win, document: doc }, onError); - const off = t.on('online', () => {}); - expect(onError).toHaveBeenCalledTimes(1); - off(); - expect(win.count()).toBe(0); - }); - - it('a throwing removeEventListener does not leak the others', () => { - const win = mkTarget(); - const doc = mkTarget(); - doc.removeEventListener = () => { - throw new Error('detached'); - }; - const t = new PageLifecycleTracker({ window: win, document: doc }); - const off = t.on('online', () => {}); - expect(() => off()).not.toThrow(); - expect(win.count()).toBe(0); - }); - - it('tolerates targets without addEventListener', () => { - const t = new PageLifecycleTracker({ - window: {} as never, - document: { visibilityState: 'visible' } as never, - }); - expect(() => t.on('online', () => {})()).not.toThrow(); - }); - - it('a throwing consumer is reported and the other consumers still receive the event', () => { - const { win, doc } = mkEnv(); - const onError = vi.fn(); - const t = new PageLifecycleTracker({ window: win, document: doc }, onError); - const seen: string[] = []; - t.on('online', () => { - throw new Error('consumer'); - }); - t.on('online', () => seen.push('second')); - expect(() => win.fire('online')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(1); - expect(seen).toEqual(['second']); - }); - - it('a throwing onError never escapes: not from a failed read, a throwing consumer, or a failed attach', () => { - const onError = vi.fn(() => { - throw new Error('reporter'); - }); - const win = mkTarget(); - const doc = mkTarget(); - Object.defineProperty(doc, 'visibilityState', { - get(): never { - throw new Error('getter'); - }, - }); - const t = new PageLifecycleTracker({ window: win, document: doc }, onError); - t.on('online', () => { - throw new Error('consumer'); - }); - t.on('visibility', () => {}); - expect(() => doc.fire('visibilitychange')).not.toThrow(); - expect(() => win.fire('online')).not.toThrow(); - expect(onError).toHaveBeenCalledTimes(2); - - const bad = mkTarget(); - bad.addEventListener = () => { - throw new Error('detached'); - }; - const t2 = new PageLifecycleTracker({ window: bad }, onError); - expect(() => t2.on('online', () => {})).not.toThrow(); - }); -}); diff --git a/packages/browser/src/trackers/page-lifecycle-tracker.ts b/packages/browser/src/trackers/page-lifecycle-tracker.ts deleted file mode 100644 index 45225243..00000000 --- a/packages/browser/src/trackers/page-lifecycle-tracker.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { InterceptorBase } from '@bugsee/core'; - -// Shared page-lifecycle TRACKER (the web analog of the mobile Application tracker that Android's TraceAppState -// and EventApplicationLifecycle both subscribe to): the ONE owner of the window/document lifecycle listeners. -// The system-events source and the connection/orientation trackers subscribe to it instead of each attaching -// their own, so the injected window+document are bound in exactly one place. Listeners attach on the first -// subscriber and are removed on the last. - -export interface PageLifecycleEvents { - /** `pagehide`; `persisted` is true when the page enters the bfcache rather than unloading. */ - pagehide: { persisted: boolean }; - /** `visibilitychange`, reduced to whether the document is now visible. */ - visibility: { visible: boolean }; - /** Page Lifecycle `freeze` / `resume`: fired on the DOCUMENT and they do not bubble, so never listened for on window. */ - freeze: undefined; - resume: undefined; - online: undefined; - offline: undefined; - orientationchange: undefined; -} -interface TargetLike { - addEventListener(type: string, listener: (event: unknown) => void): void; - removeEventListener(type: string, listener: (event: unknown) => void): void; -} -export interface PageLifecycleEnv { - window?: TargetLike; - document?: TargetLike & { readonly visibilityState?: string }; -} - -export class PageLifecycleTracker extends InterceptorBase { - readonly name = 'browser-page-lifecycle'; - readonly #env: PageLifecycleEnv; - readonly #onError: (error: unknown) => void; - #attached: Array<{ target: Partial; type: string; listener: (e: unknown) => void }> = - []; - - constructor(env: PageLifecycleEnv, onError?: (error: unknown) => void) { - // A throwing reporter must not escape into the host's event dispatch, so it is wrapped for the - // emitter and for the tracker's own catch paths alike. - const report = (error: unknown): void => { - try { - onError?.(error); - } catch { - /* the reporter itself failed; nothing left to tell */ - } - }; - super(report); - this.#env = env; - this.#onError = report; - } - - // Guarded: the tracker is already marked active before this runs, so a throwing target must be reported - // here, not leak out of `on()`. Whatever attached before the throw is still removed on deactivation. - protected onActivate(): void { - const { window: win, document: doc } = this.#env; - try { - this.#listen(win, 'pagehide', (e) => - this.#guard(() => - this.emit('pagehide', { persisted: (e as { persisted?: boolean }).persisted === true }), - ), - ); - for (const type of ['online', 'offline', 'orientationchange'] as const) { - this.#listen(win, type, () => this.#guard(() => this.emit(type, undefined))); - } - this.#listen(doc, 'visibilitychange', () => - this.#guard(() => this.emit('visibility', { visible: doc?.visibilityState === 'visible' })), - ); - // After visibilitychange: a document that refuses only the newer Page Lifecycle types must not cost - // foreground/background (and app_state / fps) for an optional signal. - for (const type of ['freeze', 'resume'] as const) { - this.#listen(doc, type, () => this.#guard(() => this.emit(type, undefined))); - } - } catch (error) { - this.#onError(error); - } - } - - protected override onDeactivate(): void { - const attached = this.#attached; - this.#attached = []; - for (const { target, type, listener } of attached) { - try { - target.removeEventListener?.(type, listener); - } catch { - /* best-effort: one detached target must not leak the others */ - } - } - } - - #listen( - target: Partial | undefined, - type: string, - listener: (event: unknown) => void, - ): void { - if (typeof target?.addEventListener !== 'function') return; - target.addEventListener(type, listener); - this.#attached.push({ target, type, listener }); - } - - /** Never throw into the browser's event dispatch. */ - #guard(fn: () => void): void { - try { - fn(); - } catch (error) { - this.#onError(error); - } - } -} diff --git a/packages/browser/src/trackers/screen-size-tracker.ts b/packages/browser/src/trackers/screen-size-tracker.ts index b29a3022..782e9099 100644 --- a/packages/browser/src/trackers/screen-size-tracker.ts +++ b/packages/browser/src/trackers/screen-size-tracker.ts @@ -1,11 +1,11 @@ import { InterceptorBase } from '@bugsee/core'; -import type { PageLifecycleTracker } from './page-lifecycle-tracker'; +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 PageLifecycleTracker (like the orientation tracker; without one, from the window), but `resize` +// 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). @@ -25,7 +25,7 @@ interface TargetLike { } export interface ScreenSizeEnv { /** Shared lifecycle tracker for `orientationchange`; when absent it is listened for on `window`. */ - lifecycle?: Pick; + 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 }; diff --git a/packages/trackers/README.md b/packages/trackers/README.md index d0494914..f09eba53 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 `PowerTracker` (`powerTrackerFor`, `resetPowerTracker`) 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`) 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 4b6c82ea..c3d311fa 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 (PowerTracker, 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, PowerTracker, 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 new file mode 100644 index 00000000..f1e67f55 --- /dev/null +++ b/packages/trackers/src/browser/application-tracker.test.ts @@ -0,0 +1,614 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + ApplicationTracker, + applicationTrackerFor, + resetApplicationTracker, +} from './application-tracker'; + +function mkTarget() { + const l = new Map void>>(); + return { + addEventListener: (t: string, f: (e: unknown) => void) => { + const s = l.get(t) ?? new Set<(e: unknown) => void>(); + s.add(f); + l.set(t, s); + }, + removeEventListener: (t: string, f: (e: unknown) => void) => void l.get(t)?.delete(f), + fire: (t: string, e: unknown = {}) => + l.get(t)?.forEach((f) => { + f(e); + }), + count: (t?: string) => + t === undefined ? [...l.values()].reduce((n, s) => n + s.size, 0) : (l.get(t)?.size ?? 0), + }; +} + +function mkEnv() { + const win = mkTarget(); + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' as string }); + return { win, doc }; +} + +describe('ApplicationTracker', () => { + it('attaches nothing until the first subscriber', () => { + const { win, doc } = mkEnv(); + new ApplicationTracker({ window: win, document: doc }); + expect(win.count() + doc.count()).toBe(0); + }); + + it('attaches pagehide/online/offline/orientationchange on window 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']) { + expect(win.count(type)).toBe(1); + } + expect(doc.count('visibilitychange')).toBe(1); + }); + + it('freeze and resume are Page Lifecycle events on the DOCUMENT (they do not bubble to window)', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen: string[] = []; + t.on('freeze', () => seen.push('freeze')); + t.on('resume', () => seen.push('resume')); + expect(doc.count('freeze')).toBe(1); + expect(doc.count('resume')).toBe(1); + expect(win.count('freeze')).toBe(0); + expect(win.count('resume')).toBe(0); + win.fire('freeze'); // a window listener beside pagehide would never see these: nothing happens + doc.fire('freeze'); + doc.fire('resume'); + expect(seen).toEqual(['freeze', 'resume']); + }); + + it('freeze/resume without a document attach nothing (not on the window either) and do not throw', () => { + const { win } = mkEnv(); + const t = new ApplicationTracker({ window: win }); + let off: (() => void) | undefined; + expect(() => { + off = t.on('freeze', () => {}); + }).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 + off?.(); + }); + + it('a document that refuses only freeze/resume still delivers visibility', () => { + const { win, doc } = mkEnv(); + const realAdd = doc.addEventListener; + doc.addEventListener = (type, f) => { + if (type === 'freeze' || type === 'resume') throw new Error('newer types refused'); + realAdd(type, f); + }; + const errors: unknown[] = []; + const t = new ApplicationTracker({ window: win, document: doc }, (e) => errors.push(e)); + const seen: boolean[] = []; + t.on('visibility', (e) => seen.push(e.visible)); + doc.visibilityState = 'hidden'; + doc.fire('visibilitychange'); + expect(seen).toEqual([false]); + expect(errors).toHaveLength(1); + }); + + it('releases everything on the last unsubscribe and re-attaches on the next subscriber', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const offA = t.on('online', () => {}); + const offB = t.on('offline', () => {}); + offA(); + expect(win.count() + doc.count()).toBe(7); + offB(); + expect(win.count() + doc.count()).toBe(0); + t.on('online', () => {}); + expect(win.count() + doc.count()).toBe(7); + }); + + it('removes each listener exactly once per activation cycle (no stale entries replayed on a later stop)', () => { + const { win, doc } = mkEnv(); + const removes = vi.fn(); + const realRemove = win.removeEventListener; + win.removeEventListener = (t, f) => { + removes(t); + realRemove(t, f); + }; + const t = new ApplicationTracker({ window: win, document: doc }); + t.on('online', () => {})(); + t.on('online', () => {})(); + expect(removes).toHaveBeenCalledTimes(8); + }); + + it('emits typed events', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen: unknown[] = []; + t.on('pagehide', (e) => seen.push(['pagehide', e])); + 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'; + doc.fire('visibilitychange'); + doc.visibilityState = 'visible'; + doc.fire('visibilitychange'); + win.fire('online'); + win.fire('offline'); + win.fire('orientationchange'); + expect(seen).toEqual([ + ['pagehide', { persisted: true }], + ['pagehide', { persisted: false }], + ['visibility', { visible: false }], + ['visibility', { visible: true }], + ['online'], + ['offline'], + ['orientationchange'], + ]); + }); + + it('works with no document and with no window', () => { + const { win, doc } = mkEnv(); + const onlyWin = new ApplicationTracker({ window: win }); + onlyWin.on('online', () => {})(); + const onlyDoc = new ApplicationTracker({ document: doc }); + onlyDoc.on('visibility', () => {}); + expect(doc.count('visibilitychange')).toBe(1); + expect(() => new ApplicationTracker({}).on('online', () => {})()).not.toThrow(); + }); + + it('a missing visibilityState emits NO visibility (it would fabricate a hide)', () => { + const win = mkTarget(); + const doc = mkTarget(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen: unknown[] = []; + t.on('visibility', (e) => seen.push(e)); + doc.fire('visibilitychange'); + expect(seen).toEqual([]); + }); + + it('a throwing getter in the event path is reported, never thrown into dispatch', () => { + const win = mkTarget(); + const onError = vi.fn(); + const doc = mkTarget(); + Object.defineProperty(doc, 'visibilityState', { + get(): never { + throw new Error('getter'); + }, + }); + const t = new ApplicationTracker({ window: win, document: doc }, onError); + t.on('visibility', () => {}); + expect(() => doc.fire('visibilitychange')).not.toThrow(); + expect(onError).toHaveBeenCalledTimes(2); // the activation read + the event read, each reported once + }); + + it('a throwing addEventListener is reported and what attached is still released', () => { + const win = mkTarget(); + const onError = vi.fn(); + const doc = mkTarget(); + doc.addEventListener = () => { + throw new Error('detached'); + }; + const t = new ApplicationTracker({ window: win, document: doc }, onError); + const off = t.on('online', () => {}); + expect(onError).toHaveBeenCalledTimes(1); + off(); + expect(win.count()).toBe(0); + }); + + it('a throwing removeEventListener does not leak the others', () => { + const win = mkTarget(); + const doc = mkTarget(); + doc.removeEventListener = () => { + throw new Error('detached'); + }; + const t = new ApplicationTracker({ window: win, document: doc }); + const off = t.on('online', () => {}); + expect(() => off()).not.toThrow(); + expect(win.count()).toBe(0); + }); + + it('tolerates targets without addEventListener', () => { + const t = new ApplicationTracker({ + window: {} as never, + document: { visibilityState: 'visible' } as never, + }); + expect(() => t.on('online', () => {})()).not.toThrow(); + }); + + it('a throwing consumer is reported and the other consumers still receive the event', () => { + const { win, doc } = mkEnv(); + const onError = vi.fn(); + const t = new ApplicationTracker({ window: win, document: doc }, onError); + const seen: string[] = []; + t.on('online', () => { + throw new Error('consumer'); + }); + t.on('online', () => seen.push('second')); + expect(() => win.fire('online')).not.toThrow(); + expect(onError).toHaveBeenCalledTimes(1); + expect(seen).toEqual(['second']); + }); + + it('a throwing onError never escapes: not from a failed read, a throwing consumer, or a failed attach', () => { + const onError = vi.fn(() => { + throw new Error('reporter'); + }); + const win = mkTarget(); + const doc = mkTarget(); + Object.defineProperty(doc, 'visibilityState', { + get(): never { + throw new Error('getter'); + }, + }); + const t = new ApplicationTracker({ window: win, document: doc }, onError); + t.on('online', () => { + throw new Error('consumer'); + }); + t.on('visibility', () => {}); + expect(() => doc.fire('visibilitychange')).not.toThrow(); + expect(() => win.fire('online')).not.toThrow(); + expect(onError).toHaveBeenCalledTimes(3); // activation read, event read, throwing consumer + + const bad = mkTarget(); + bad.addEventListener = () => { + throw new Error('detached'); + }; + const t2 = new ApplicationTracker({ window: bad }, onError); + expect(() => t2.on('online', () => {})).not.toThrow(); + }); +}); + +describe('ApplicationTracker: aggregated state', () => { + const states = (t: ApplicationTracker) => { + const seen: unknown[] = []; + t.on('state', (e) => seen.push(e.state)); + return seen; + }; + + it('current() answers before any event, from the document, without subscribing or attaching', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + expect(t.current()).toBe('foreground'); + doc.visibilityState = 'hidden'; + expect(t.current()).toBe('background'); + doc.visibilityState = 'prerender'; + expect(t.current()).toBe('background'); + expect(win.count() + doc.count()).toBe(0); + }); + + it('current() is undefined with no document, and keeps the last known value when the document becomes unreadable', () => { + expect(new ApplicationTracker({ window: mkTarget() }).current()).toBeUndefined(); + const doc = Object.assign(mkTarget(), { visibilityState: 'hidden' as string | undefined }); + const t = new ApplicationTracker({ document: doc }); + t.on('visibility', () => {}); // activation retains 'background' + doc.visibilityState = undefined; + expect(t.current()).toBe('background'); + }); + + it('emits `state` on a visibility change that changes it, and de-duplicates repeats', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen = states(t); + const visibility: boolean[] = []; + t.on('visibility', (e) => visibility.push(e.visible)); + for (const v of ['hidden', 'hidden', 'visible', 'visible', 'prerender']) { + doc.visibilityState = v; + doc.fire('visibilitychange'); + } + expect(seen).toEqual(['background', 'foreground', 'background']); + expect(visibility).toEqual([false, false, true, true, false]); // `visibility` itself is never de-duplicated + }); + + it('the first change after activation is compared against the document state at activation', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen = states(t); // activation retains 'foreground' + doc.fire('visibilitychange'); // still visible: no change + expect(seen).toEqual([]); + }); + + it('an unreadable document emits neither state nor visibility (never a fabricated background)', () => { + const doc = mkTarget(); // no visibilityState + const t = new ApplicationTracker({ document: doc }); + const seen = states(t); + const visibility: unknown[] = []; + t.on('visibility', (e) => visibility.push(e)); + doc.fire('visibilitychange'); + expect(seen).toEqual([]); + expect(visibility).toEqual([]); + }); + + it('a document that becomes unreadable after a known state emits no state and keeps the retained one', () => { + const doc = Object.assign(mkTarget(), { visibilityState: 'visible' as string | undefined }); + const t = new ApplicationTracker({ document: doc }); + const seen = states(t); + doc.visibilityState = undefined; + doc.fire('visibilitychange'); + expect(seen).toEqual([]); + expect(t.current()).toBe('foreground'); + }); + + it('a non-string visibilityState (null/number) is unreadable, not a background', () => { + const doc = Object.assign(mkTarget(), { + visibilityState: null as unknown as string | undefined, + }); + const t = new ApplicationTracker({ document: doc }); + expect(t.current()).toBeUndefined(); + doc.visibilityState = 0 as unknown as string; + expect(t.current()).toBeUndefined(); + }); + + it('retention: listeners detach on the last unsubscribe, the state survives, and the first subscriber after the gap is correct at once', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const offFirst = t.on('state', () => {}); + expect(doc.count('visibilitychange')).toBe(1); + offFirst(); + expect(win.count() + doc.count()).toBe(0); + doc.visibilityState = 'hidden'; // happens while NOBODY listens + expect(t.current()).toBe('background'); + const seen = states(t); // re-activation recomputes the baseline silently + expect(seen).toEqual([]); + doc.visibilityState = 'visible'; + doc.fire('visibilitychange'); + expect(seen).toEqual(['foreground']); // not swallowed by a stale baseline + }); + + it('retention: the state is kept across the gap even when the document cannot be read at re-activation', () => { + const doc = Object.assign(mkTarget(), { visibilityState: 'hidden' as string | undefined }); + const t = new ApplicationTracker({ document: doc }); + t.on('state', () => {})(); + doc.visibilityState = undefined; + const seen = states(t); + doc.visibilityState = 'hidden'; + doc.fire('visibilitychange'); // same as the retained background: no emission + expect(seen).toEqual([]); + }); + + it('a hostile pagehide event (throwing `persisted` getter) is reported, never thrown into dispatch', () => { + const { win, doc } = mkEnv(); + const onError = vi.fn(); + const t = new ApplicationTracker({ window: win, document: doc }, onError); + const seen: unknown[] = []; + t.on('pagehide', (e) => seen.push(e)); + const hostile = {}; + Object.defineProperty(hostile, 'persisted', { + get(): never { + throw new Error('persisted'); + }, + }); + expect(() => win.fire('pagehide', hostile)).not.toThrow(); + expect(onError).toHaveBeenCalledTimes(1); + expect(seen).toEqual([]); + }); + + it('a throwing visibilityState getter is reported on every read path and never thrown', () => { + const doc = mkTarget(); + Object.defineProperty(doc, 'visibilityState', { + get(): never { + throw new Error('getter'); + }, + }); + const onError = vi.fn(); + const t = new ApplicationTracker({ document: doc }, onError); + expect(t.current()).toBeUndefined(); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('reset() detaches, drops subscribers (a later event reaches nobody) and forgets the retained state', () => { + const { win, doc } = mkEnv(); + const t = new ApplicationTracker({ window: win, document: doc }); + const seen = states(t); + const online = vi.fn(); + t.on('online', online); + t.reset(); + expect(win.count() + doc.count()).toBe(0); + doc.visibilityState = 'hidden'; + doc.fire('visibilitychange'); + win.fire('online'); + expect(seen).toEqual([]); + expect(online).not.toHaveBeenCalled(); + // subscribing again re-attaches and works + const again = states(t); + doc.visibilityState = 'visible'; + doc.fire('visibilitychange'); + expect(again).toEqual(['foreground']); + const doc2 = Object.assign(mkTarget(), { visibilityState: 'hidden' as string | undefined }); + const t2 = new ApplicationTracker({ document: doc2 }); + t2.on('state', () => {}); + doc2.visibilityState = undefined; + expect(t2.current()).toBe('background'); + t2.reset(); + expect(t2.current()).toBeUndefined(); + }); +}); + +describe('applicationTrackerFor (singleton per key)', () => { + it('returns the SAME instance for the same document, whichever window is passed (latest request wins)', () => { + const { win, doc } = mkEnv(); + const a = applicationTrackerFor({ window: win, document: doc }); + expect(applicationTrackerFor({ window: win, document: doc })).toBe(a); + expect(applicationTrackerFor({ window: mkTarget(), document: doc })).toBe(a); + expect(applicationTrackerFor({ document: doc })).toBe(a); + resetApplicationTracker({ document: doc }); + }); + + it('keys by the window when there is no document, and distinct keys get distinct instances', () => { + const w1 = mkTarget(); + const w2 = mkTarget(); + const a = applicationTrackerFor({ window: w1 }); + expect(applicationTrackerFor({ window: w1 })).toBe(a); + expect(applicationTrackerFor({ window: w2 })).not.toBe(a); + const d = mkEnv().doc; + expect(applicationTrackerFor({ window: w1, document: d })).not.toBe(a); // the document is the key when given + resetApplicationTracker({ window: w1 }); + resetApplicationTracker({ window: w2 }); + resetApplicationTracker({ document: d }); + }); + + it('an env with neither shares one instance', () => { + const a = applicationTrackerFor({}); + expect(applicationTrackerFor({})).toBe(a); + resetApplicationTracker({}); + }); + + it("latest launch wins: a relaunch's onError replaces the reporter; one without onError keeps it", () => { + const { win, doc } = mkEnv(); + const a = vi.fn(); + const b = vi.fn(); + const t = applicationTrackerFor({ window: win, document: doc }, a); + const off = t.on('online', () => { + throw new Error('x'); + }); + win.fire('online'); + expect(a).toHaveBeenCalledTimes(1); + off(); + expect(applicationTrackerFor({ window: win, document: doc }, b)).toBe(t); + t.on('online', () => { + throw new Error('y'); + }); + win.fire('online'); + expect(b).toHaveBeenCalledTimes(1); + expect(a).toHaveBeenCalledTimes(1); + applicationTrackerFor({ window: win, document: doc }); // no onError: keeps b + win.fire('online'); + expect(b).toHaveBeenCalledTimes(2); + resetApplicationTracker({ document: doc }); + }); + + it('while IDLE a new request re-binds the window, so the tracker listens on the new one', () => { + const w1 = mkTarget(); + const w2 = mkTarget(); + const doc = mkEnv().doc; + const t = applicationTrackerFor({ window: w1, document: doc }); + t.on('online', () => {})(); + expect(applicationTrackerFor({ window: w2, document: doc })).toBe(t); + const seen: string[] = []; + t.on('online', () => seen.push('online')); + expect(w1.count()).toBe(0); + expect(w2.count('online')).toBe(1); + w2.fire('online'); + expect(seen).toEqual(['online']); + resetApplicationTracker({ document: doc }); + }); + + it('while ACTIVE the binding is kept and a different window is reported once', () => { + const w1 = mkTarget(); + const w2 = mkTarget(); + const doc = mkEnv().doc; + const t = applicationTrackerFor({ window: w1, document: doc }); + t.on('online', () => {}); + const onError = vi.fn(); + applicationTrackerFor({ window: w2, document: doc }, onError); + applicationTrackerFor({ window: w2, document: doc }, onError); + expect(w2.count()).toBe(0); + expect(w1.count('online')).toBe(1); + expect(onError).toHaveBeenCalledTimes(1); + expect(String((onError.mock.calls[0]?.[0] as Error).message)).toContain('already bound'); + applicationTrackerFor({ window: w1, document: doc }, onError); // the same binding is not a mismatch + expect(onError).toHaveBeenCalledTimes(1); + resetApplicationTracker({ document: doc }); + }); + + it('a differing document while active is also a mismatch', () => { + const w = mkTarget(); + const d1 = mkEnv().doc; + const onError = vi.fn(); + const t = new ApplicationTracker({ window: w, document: d1 }, onError); + t.on('online', () => {}); + t.rebind({ window: w, document: mkEnv().doc }); + expect(onError).toHaveBeenCalledTimes(1); + t.rebind({ window: w, document: d1 }); + expect(onError).toHaveBeenCalledTimes(1); + }); + + it('an idle rebind with a partial env keeps the targets it does not supply (merge, never drop)', () => { + const w1 = mkTarget(); + const w2 = mkTarget(); + const d1 = mkEnv().doc; + const d2 = mkEnv().doc; + const t = new ApplicationTracker({ window: w1, document: d1 }); + t.rebind({ window: w2 }); // no document supplied: d1 stays + let off = t.on('online', () => {}); + expect(w2.count('online')).toBe(1); + expect(w1.count('online')).toBe(0); + expect(d1.count('visibilitychange')).toBe(1); + off(); + t.rebind({ document: d2 }); // no window supplied: w2 stays + off = t.on('online', () => {}); + expect(w2.count('online')).toBe(1); + expect(d2.count('visibilitychange')).toBe(1); + expect(d1.count('visibilitychange')).toBe(0); + off(); + }); + + it('an ACTIVE rebind with a partial env is no mismatch: only the targets it supplies are compared', () => { + const w = mkTarget(); + const d = mkEnv().doc; + const onError = vi.fn(); + const t = new ApplicationTracker({ window: w, document: d }, onError); + t.on('online', () => {}); + t.rebind({ document: d }); // no window: nothing conflicts + t.rebind({ window: w }); // no document: nothing conflicts + t.rebind({}); + t.rebind({ window: w, document: d }); + expect(onError).not.toHaveBeenCalled(); + }); + + it('the active mismatch error names the target that actually differs', () => { + const w = mkTarget(); + const d = mkEnv().doc; + const msgs = (fn: ReturnType) => fn.mock.calls.map(([e]) => (e as Error).message); + const onWin = vi.fn(); + const a = new ApplicationTracker({ window: w, document: d }, onWin); + a.on('online', () => {}); + a.rebind({ window: mkTarget() }); + expect(msgs(onWin)).toEqual([ + 'ApplicationTracker already bound to another window while active', + ]); + const onDoc = vi.fn(); + const b = new ApplicationTracker({ window: w, document: d }, onDoc); + b.on('online', () => {}); + b.rebind({ document: mkEnv().doc }); + expect(msgs(onDoc)).toEqual([ + 'ApplicationTracker already bound to another document while active', + ]); + const onBoth = vi.fn(); + const c = new ApplicationTracker({ window: w, document: d }, onBoth); + c.on('online', () => {}); + c.rebind({ window: mkTarget(), document: mkEnv().doc }); + expect(msgs(onBoth)).toEqual([ + 'ApplicationTracker already bound to another window and document while active', + ]); + }); + + it('the mismatch is reported again after an idle gap (a fresh activation)', () => { + const w1 = mkTarget(); + const w2 = mkTarget(); + const doc = mkEnv().doc; + const onError = vi.fn(); + const t = applicationTrackerFor({ window: w1, document: doc }, onError); + let off = t.on('online', () => {}); + applicationTrackerFor({ window: w2, document: doc }); + expect(onError).toHaveBeenCalledTimes(1); + off(); + applicationTrackerFor({ window: w1, document: doc }); // idle: rebinds w1 + off = t.on('online', () => {}); + applicationTrackerFor({ window: w2, document: doc }); + expect(onError).toHaveBeenCalledTimes(2); + resetApplicationTracker({ document: doc }); + }); + + it('resetApplicationTracker detaches the old instance and the next request builds a fresh one', () => { + const { win, doc } = mkEnv(); + const a = applicationTrackerFor({ window: win, document: doc }); + a.on('online', () => {}); + expect(win.count()).toBe(4); + resetApplicationTracker({ window: win, document: doc }); + expect(win.count() + doc.count()).toBe(0); + expect(applicationTrackerFor({ window: win, document: doc })).not.toBe(a); + resetApplicationTracker({ document: doc }); + }); +}); diff --git a/packages/trackers/src/browser/application-tracker.ts b/packages/trackers/src/browser/application-tracker.ts new file mode 100644 index 00000000..50535967 --- /dev/null +++ b/packages/trackers/src/browser/application-tracker.ts @@ -0,0 +1,226 @@ +import { InterceptorBase } from '../interceptor-base'; +import { createTrackerRegistry } from '../tracker-registry'; +import { hostRead } from './host-read'; + +// The browser APPLICATION tracker (design §15; Android `BugseeTrackerApplication`): the domain owner of everything +// about the page being a running "application" — visible or hidden, frozen, leaving. It is the ONE owner of the +// window/document lifecycle listeners; the events source, the app_state trace and the fps/connection/orientation +// trackers subscribe to it instead of each attaching their own. +// +// RETENTION RULE. The DOM listeners attach on the FIRST subscriber and are removed on the LAST (a page with no +// capture pays nothing). What is retained across that gap is the last known `state`: on re-activation it is +// recomputed from the document (without emitting) so the `state` stage's de-duplication baseline is correct, and +// `current()` answers at once, with no wait for an event. Stopping therefore loses nothing a later subscriber needs. +// +// SINGLETON PER KEY. `applicationTrackerFor` returns one instance per KEY OBJECT: the document when one is given +// (it owns visibility/freeze/resume), else the window (pagehide), else a shared module key for an env with neither. +// 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. + +/** The Android app-state vocabulary (the viewer's table also has `started`, which the web never reports). */ +export type ApplicationState = 'foreground' | 'background'; + +export interface ApplicationEvents { + /** `pagehide`; `persisted` is true when the page enters the bfcache rather than unloading. */ + pagehide: { persisted: boolean }; + /** `visibilitychange`, reduced to whether the document is now visible. */ + visibility: { visible: boolean }; + /** The aggregated app state; emitted when a visibility change CHANGES it (de-duplicated). */ + state: { state: ApplicationState }; + /** Page Lifecycle `freeze` / `resume`: fired on the DOCUMENT and they do not bubble, so never listened for on window. */ + freeze: undefined; + resume: undefined; + online: undefined; + offline: undefined; + orientationchange: undefined; +} +interface TargetLike { + addEventListener(type: string, listener: (event: unknown) => void): void; + removeEventListener(type: string, listener: (event: unknown) => void): void; +} +export interface ApplicationEnv { + window?: TargetLike; + document?: TargetLike & { readonly visibilityState?: string }; +} + +export class ApplicationTracker extends InterceptorBase { + readonly name = 'browser-application'; + #env: ApplicationEnv; + readonly #onError: (error: unknown) => void; + readonly #sink: { current: ((error: unknown) => void) | undefined }; + #live = false; + #mismatchReported = false; + #state: ApplicationState | undefined; + #attached: Array<{ target: Partial; type: string; listener: (e: unknown) => void }> = + []; + + constructor(env: ApplicationEnv, onError?: (error: unknown) => void) { + // A throwing reporter must not escape into the host's event dispatch, so it is wrapped for the + // emitter and for the tracker's own catch paths alike. + const sink = { current: onError }; + const report = (error: unknown): void => { + try { + sink.current?.(error); + } catch { + /* the reporter itself failed; nothing left to tell */ + } + }; + super(report); + this.#env = env; + this.#sink = sink; + this.#onError = report; + } + + // Guarded: the tracker is already marked active before this runs, so a throwing target must be reported + // here, not leak out of `on()`. Whatever attached before the throw is still removed on deactivation. + protected onActivate(): void { + this.#live = true; + const { window: win, document: doc } = this.#env; + // Retention: catch up with whatever happened while nobody listened (no emit: nobody has been told anything yet). + this.#state = this.#readState() ?? this.#state; + try { + this.#listen(win, 'pagehide', (e) => + this.#guard(() => + this.emit('pagehide', { persisted: (e as { persisted?: boolean }).persisted === true }), + ), + ); + for (const type of ['online', 'offline', 'orientationchange'] as const) { + this.#listen(win, type, () => this.#guard(() => this.emit(type, undefined))); + } + this.#listen(doc, 'visibilitychange', () => this.#guard(() => this.#onVisibility())); + // After visibilitychange: a document that refuses only the newer Page Lifecycle types must not cost + // foreground/background (and app_state / fps) for an optional signal. + for (const type of ['freeze', 'resume'] as const) { + this.#listen(doc, type, () => this.#guard(() => this.emit(type, undefined))); + } + } catch (error) { + this.#onError(error); + } + } + + /** The last known app state: read live from the document, else the retained value; undefined when never known. */ + current(): ApplicationState | undefined { + return this.#readState() ?? this.#state; + } + + /** + * @internal Called by `applicationTrackerFor` on every request after the creating one: the LATEST launch wins. + * A defined `onError` replaces the reporter; undefined keeps the current one (a launch that supplies none must not + * silence an earlier launch's sink). LIMITATION (accepted): the sink is shared per key and never released on stop, so + * a relaunch on the same document that passes no `onError` still reports to the previous launch's callback (and keeps + * its closure alive) until a later launch supplies its own. While IDLE (no subscribers, so no DOM listeners) the window/document to attach + * to are re-bound; while ACTIVE live listeners cannot move, so the binding stays and a mismatch is reported once. + */ + rebind(env: ApplicationEnv, onError?: (error: unknown) => void): void { + if (onError !== undefined) this.#sink.current = onError; + if (!this.#live) { + // Merge: only a target the new env actually supplies replaces the old one (a partial env never drops one). + const window = env.window ?? this.#env.window; + const document = env.document ?? this.#env.document; + this.#env = { + ...(window !== undefined ? { window } : {}), + ...(document !== undefined ? { document } : {}), + }; + return; + } + // Only a target the new env SUPPLIES can conflict (undefined = keep, as in the idle merge). + const differs: string[] = []; + if (env.window !== undefined && env.window !== this.#env.window) differs.push('window'); + if (env.document !== undefined && env.document !== this.#env.document) differs.push('document'); + if (differs.length > 0 && !this.#mismatchReported) { + this.#mismatchReported = true; + this.#onError( + new Error( + `ApplicationTracker already bound to another ${differs.join(' and ')} while active`, + ), + ); + } + } + + /** @internal Called by the registry on `reset`: drops every subscriber (which detaches the DOM listeners) and forgets the retained state. Test/teardown use. */ + reset(): void { + this.removeAllListeners(); + this.#state = undefined; + } + + #readState(): ApplicationState | undefined { + const visibility = hostRead(() => this.#env.document?.visibilityState, this.#onError); + if (typeof visibility !== 'string') return undefined; + return visibility === 'visible' ? 'foreground' : 'background'; + } + + #onVisibility(): void { + const state = this.#readState(); + // An unreadable document says nothing about visibility OR state: emit neither (never fabricate a + // background, which would become process_background and pause fps). + if (state === undefined) return; + this.emit('visibility', { visible: state === 'foreground' }); + if (state === this.#state) return; + this.#state = state; + this.emit('state', { state }); + } + + protected override onDeactivate(): void { + this.#live = false; + this.#mismatchReported = false; + const attached = this.#attached; + this.#attached = []; + for (const { target, type, listener } of attached) { + try { + target.removeEventListener?.(type, listener); + } catch { + /* best-effort: one detached target must not leak the others */ + } + } + } + + #listen( + target: Partial | undefined, + type: string, + listener: (event: unknown) => void, + ): void { + if (typeof target?.addEventListener !== 'function') return; + target.addEventListener(type, listener); + this.#attached.push({ target, type, listener }); + } + + /** Never throw into the browser's event dispatch. */ + #guard(fn: () => void): void { + try { + fn(); + } catch (error) { + this.#onError(error); + } + } +} + +const registry = createTrackerRegistry(); +// An env with neither document nor window has nothing to bind: all such callers share this key. +const NO_TARGET_KEY: object = {}; + +function keyOf(env: ApplicationEnv): object { + return env.document ?? env.window ?? NO_TARGET_KEY; +} + +/** + * The singleton ApplicationTracker for `env`'s document (else window). The key is the document when present, so a + * window-only env and a window+document env are DISTINCT trackers. The LATEST request's onError/env are bound (see `rebind`). + */ +export function applicationTrackerFor( + env: ApplicationEnv, + onError?: (error: unknown) => void, +): ApplicationTracker { + return registry.for( + keyOf(env), + () => new ApplicationTracker(env, onError), + (existing) => existing.rebind(env, onError), + ); +} + +/** @internal Internal/test use: exported from `@bugsee/trackers/browser` but NOT re-exported by `@bugsee/browser`. Drop (and reset) the singleton for `env`'s key so the next request builds a fresh one. */ +export function resetApplicationTracker(env: ApplicationEnv): void { + registry.reset(keyOf(env)); +} diff --git a/packages/trackers/src/browser/index.ts b/packages/trackers/src/browser/index.ts index 31f01692..6dabbbc0 100644 --- a/packages/trackers/src/browser/index.ts +++ b/packages/trackers/src/browser/index.ts @@ -1,5 +1,13 @@ // `@bugsee/trackers/browser` entry. Platform tracker implementations that need DOM/Web-API APIs live under // src/browser/ and are exported from here. The portable root entry must never import from this directory. +export { + type ApplicationEnv, + type ApplicationEvents, + type ApplicationState, + ApplicationTracker, + applicationTrackerFor, + resetApplicationTracker, +} from './application-tracker'; export { hostRead } from './host-read'; export { type BatteryEnv, diff --git a/packages/trackers/src/index.test.ts b/packages/trackers/src/index.test.ts index 491e237b..c0a03f19 100644 --- a/packages/trackers/src/index.test.ts +++ b/packages/trackers/src/index.test.ts @@ -11,7 +11,7 @@ describe('@bugsee/trackers public surface', () => { ]); }); - it('reserves the node/electron entries as empty placeholders', async () => { + it('reserves the node and electron entries as empty placeholders', async () => { for (const entry of ['./node/index', './electron/index']) { expect(Object.keys(await import(entry))).toEqual([]); } @@ -19,9 +19,12 @@ describe('@bugsee/trackers public surface', () => { it('exports the browser tracker values from ./browser', async () => { expect(Object.keys(await import('./browser/index')).sort()).toEqual([ + 'ApplicationTracker', 'PowerTracker', + 'applicationTrackerFor', 'hostRead', 'powerTrackerFor', + 'resetApplicationTracker', 'resetPowerTracker', ]); }); diff --git a/packages/trackers/tsup.config.ts b/packages/trackers/tsup.config.ts index 95b4819b..64185e46 100644 --- a/packages/trackers/tsup.config.ts +++ b/packages/trackers/tsup.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; -// The root entry plus the reserved per-runtime subpath entries (dist/{index,browser,node,electron}.*). +// The root entry, the browser entry, and the reserved node/electron subpath entries (dist/{index,browser,node,electron}.*). export default defineConfig({ ...baseConfig, entry: { diff --git a/packages/webview/src/launch.test.ts b/packages/webview/src/launch.test.ts index 4eb0171d..b17331ed 100644 --- a/packages/webview/src/launch.test.ts +++ b/packages/webview/src/launch.test.ts @@ -1,4 +1,4 @@ -import type { WindowEvents } from '@bugsee/browser'; +import { applicationTrackerFor, type WindowEvents } from '@bugsee/browser'; import { BUGSEE_SDK_VERSION, BugseeStatus, @@ -115,6 +115,7 @@ function fakeEventTarget() { emit: (type: string, event: unknown) => { for (const l of [...(listeners.get(type) ?? [])]) l(event as Event); }, + count: (type: string) => listeners.get(type)?.size ?? 0, }; } @@ -151,6 +152,72 @@ const baseOptions = ( ...over, }); +describe('launch (webview) goes through the ApplicationTracker registry', () => { + const blockedDoc = () => { + const doc = fakeEventTarget(); + const boom = new Error('visibilityState blocked'); + const state = { armed: false }; + Object.defineProperty(doc.target, 'visibilityState', { + get() { + if (state.armed) throw boom; + return 'visible'; + }, + }); + return { doc, boom, state, document: doc.target as unknown as Document }; + }; + + it('shares ONE tracker per document: a lookup for the launched document sees the launch listeners', () => { + const win = fakeEventTarget(); + const { document } = blockedDoc(); + track('tok', baseOptions({ window: win.target as unknown as WindowEvents, document })); + expect(win.count('online')).toBe(1); + const shared = applicationTrackerFor({ window: win.target as never, document }); + const off = shared.on('online', () => {}); + expect(win.count('online')).toBe(1); // the SAME tracker: no second listener set + off(); + }); + + it("the latest launch's onError becomes the reporter; a relaunch without one keeps it", () => { + const win = fakeEventTarget(); + const { doc, boom, state, document } = blockedDoc(); + const first = vi.fn(); + const second = vi.fn(); + const fireBlocked = () => { + state.armed = true; + try { + doc.emit('visibilitychange', {}); + } catch { + /* a real DOM dispatch never propagates a listener's throw */ + } finally { + state.armed = false; + } + }; + const run = (onError?: (e: unknown) => void) => + launch( + 'tok', + baseOptions({ + window: win.target as unknown as WindowEvents, + document, + ...(onError !== undefined ? { onError } : {}), + }), + ); + run(first).stop(); + run(second).stop(); + first.mockClear(); + second.mockClear(); + const live = run(second); + clients.push(live); + fireBlocked(); + expect(second).toHaveBeenCalledWith(boom); + expect(first).not.toHaveBeenCalledWith(boom); + live.stop(); + second.mockClear(); + clients.push(run()); // no onError: must NOT silence the earlier launch's sink + fireBlocked(); + expect(second).toHaveBeenCalledWith(boom); + }); +}); + describe('launch (webview)', () => { it('returns a started client', () => { const client = track('tok', baseOptions()); diff --git a/packages/webview/src/launch.ts b/packages/webview/src/launch.ts index 755c2eec..dc88ba3f 100644 --- a/packages/webview/src/launch.ts +++ b/packages/webview/src/launch.ts @@ -1,4 +1,5 @@ import { + applicationTrackerFor, bindInputBlackout, boundMatchMedia, browserTraceEnvFrom, @@ -12,7 +13,6 @@ import { defaultBrowserTraceEnv, hostGlobal, hostRead, - PageLifecycleTracker, parseStack, type WindowEvents, } from '@bugsee/browser'; @@ -695,7 +695,7 @@ export function launchWithSeams( // HTTP server errors (5xx) → `error` reports (mechanism http-error). Off unless `detectHttpErrors`. client.addDetectionProvider(createHttpErrorDetectionProvider(network.interceptor)); // ONE lifecycle tracker over the host page's window+document, shared by the traces and the events source. - const lifecycle = new PageLifecycleTracker( + const lifecycle = applicationTrackerFor( { ...(win !== undefined ? { window: win } : {}), ...(domDocument !== undefined ? { document: domDocument } : {}),