From 4262862d215328d7e09dd9abffa659d5066ef7c7 Mon Sep 17 00:00:00 2001 From: Oleh H Date: Fri, 25 Sep 2026 23:58:54 +0000 Subject: [PATCH 1/2] Hear Pinia again after a stuck action, read tree levels faster, bound lookups - Pinia: an action whose promise never settles stops counting as running after ACTION_SETTLE_MS (10 s), so the store's direct changes are heard again. - Components tree and picking: the adapter names each function once, so a level of 500 rows of one component is placed with one call, not 500 (a 2,000-row Vue level: ~150-230 ms to ~30 ms); a path's first index reads the frameworks' tops only as far as it; a production Vue pick walks the vnode tree only down the elements that hold the element. The benchmark now follows the widest node, so React's 2,000-row level is measured too. - Leaving a workspace forgets the originals and hook names with the maps, and a lookup finishing after drops its answer. - Main: script records keep only live scripts, whether each names a map (not an inline map's whole data URL) and URLs of at most 2,048 characters; at most 1,000 functions are placed a read, one gone leaving the others; initiator calls keep bounded URLs and names. --- docs/SPEC.md | 18 ++--- src/main/inspector/adapter/adapterSource.ts | 8 +- src/main/inspector/adapter/reactTreeSource.ts | 51 ++++++++++++ src/main/inspector/adapter/treeSource.ts | 79 +++++++------------ src/main/inspector/adapter/vueSource.ts | 19 +++-- src/main/inspector/constants.ts | 4 + src/main/inspector/reading/ScriptUrls.ts | 14 +++- .../inspector/reading/functionLocations.ts | 13 +-- src/main/inspector/scriptCoverage.ts | 2 +- src/main/inspector/stores/constants.ts | 5 ++ src/main/inspector/stores/vueStoresSource.ts | 24 +++--- src/main/network/constants.ts | 3 + src/main/network/initiatorFrames.ts | 7 +- .../entities/inspector/model/store/types.ts | 2 + .../model/store/useInspectorStore.ts | 1 + .../model/sources/forgetSourceMaps.ts | 12 ++- .../model/sources/locateLocations.ts | 6 +- .../model/sources/nameHooksAt.ts | 5 +- .../model/sources/originLookups.ts | 6 +- test/fixtures/apps/piniaCart.ts | 12 ++- test/integration/inspect.chromium.test.ts | 7 ++ test/integration/stores.chromium.test.ts | 15 ++++ test/perf/inspector.perf.test.ts | 11 ++- test/renderer/mapFiles.test.ts | 17 +++- test/unit/inspectorLookups.test.ts | 76 ++++++++++++++++++ 25 files changed, 315 insertions(+), 102 deletions(-) create mode 100644 src/main/inspector/adapter/reactTreeSource.ts create mode 100644 test/unit/inspectorLookups.test.ts diff --git a/docs/SPEC.md b/docs/SPEC.md index 255cf35b..116fe34e 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -574,7 +574,7 @@ The Network panel lists what the page, its iframes and its workers send (`src/ma | Page loads | Each row carries the load of the top-level page it belongs to: a main-frame document request on the page's session (`requestId === loaderId`, after the main frame's first commit) starts the next one, and the panel drops the rows of earlier loads unless **Keep rows** is on | | Limits | The last 2,000 rows are kept (`MAX_NETWORK_REQUESTS`) here and in the panel. New and changed rows go out every 50 ms at most (`network-requests`); clearing sends `network-cleared`; `listNetworkRequests` gives a (re)starting renderer the rows | | Bodies | Read on demand, through the session that reported the request: the request's with `Network.getRequestPostData` when `requestWillBeSent` didn't carry it, the response's with `Network.getResponseBody` once it has finished, decoded with its charset (a binary one is only said to be binary). Never an event stream's, nor an `EventSource`'s before its response comes: reading one doesn't return while it is open, and the page then gets nothing (§6.3). A body Chromium no longer holds is reported gone | -| Who sent it | A request a script sent keeps the calls of `requestWillBeSent`'s initiator stack in files the page loaded (20 at most, through the async parents Chromium recorded; it records none unless DevTools asks, so the stack is the synchronous one). The panel's **Headers** tab lists them under **Sent by**, each traced to its original (a library's dimmed), and the Component page lists the requests sent from its file (§6.13) | +| Who sent it | A request a script sent keeps the calls of `requestWillBeSent`'s initiator stack in files the page loaded (20 at most, URLs of at most 2,048 characters, names cut at 200, through the async parents Chromium recorded; it records none unless DevTools asks, so the stack is the synchronous one). The panel's **Headers** tab lists them under **Sent by**, each traced to its original (a library's dimmed), and the Component page lists the requests sent from its file (§6.13) | | Overrides | `override-served` carries the request id, so the row of a request an override answered says so | | WebSockets | `Network.webSocketCreated` adds a row (type `WebSocket`, pending until `webSocketClosed`, failed on `webSocketFrameError`); the handshake events give its time, headers and status (101). Each frame sent or received is kept on it, the latest 1,000 (`MAX_SOCKET_MESSAGES`), text cut at 64 K characters, a binary one's bytes as base64; the row counts them and adds up their size. `getNetworkMessages(id, from)` reads those from number `from` on, so the panel asks only for what came since its last read. Read-only: Chromium reports frames but can't hold or change them | | HAR | `exportHar(ids)` asks where to save (a native dialog) and writes those rows as HAR 1.2: the wire headers when known, the query, the request and response bodies Chromium still holds (a binary response's is left out), `_resourceType`, and a socket's `_webSocketMessages` as Chrome writes them. `importHar()` asks for a HAR (100 MB at most) and makes each fetch() or XHR entry with a text body (by `_resourceType`, or by a text or JSON type when it has none) a response override answered without sending: its URL (exact, with its query when it had one), method, GraphQL operation, status and body, and a `Content-Type` change for a type other than JSON. The last response to the same request wins, at most 200 an import | @@ -625,17 +625,17 @@ Picking an element in the page, in any frame, shows the component that rendered | Picking | **Pick an element** (the page toolbar, the Inspect view, the palette, **View › Pick an Element**, Ctrl/Cmd+Shift+C) puts every session in Chromium's inspect mode at once (`DOM.enable`, `Overlay.enable`, `Overlay.setInspectMode` `searchForNode`), so the pointer can go into any frame, cross-site ones included; a frame that loads while picking joins in. Chromium draws the highlight, and the click doesn't reach the page. Esc in the page (`Overlay.inspectModeCanceled`) or in the editor, the button again or the menu item stop it in every session. Stopping also turns the Overlay domain off (`Overlay.disable`): left on, it taxes every layout of the page (a 2,000-row commit took twice as long after a pick). A highlight (a pick's element, a tree node) turns it on while it shows, and hiding the highlights turns it off again, unless picking | | Under the pointer | `Overlay.nodeHighlightRequested` names the node. At most every 100 ms (the latest node wins), the adapter's `summary` of it is read by value: the element and the names of the components that rendered it. The Inspect view shows it while picking | | The pick | `Overlay.inspectNodeRequested` ends picking and gives the node. It is resolved to a handle in an object group of its own (the last 20 picks are kept, older groups released), becomes the console's `$0` (`DOM.setInspectedNode`), and its frame is found by matching its document against each frame owner's content document (`DOM.getFrameOwner`, `DOM.describeNode`): CDP doesn't say which frame a node is in | -| Reading a component | `Runtime.callFunctionOn` of `ADAPTER_SOURCE` on the element, in the page's main world, `silent`. React: the fiber on the element or its nearest ancestor (`__reactFiber$…`; React keeps two copies of each fiber and doesn't update the element's key, so the copy on screen is found as React DevTools' `findCurrentFiberUsingSlowPath` does, at each step up), up through its `return`s to the function, class, `memo` and `forwardRef` components (the chain, at most 40); props from `memoizedProps`; hooks from the `memoizedState` list (state, a store, a ref, a memo; effects left out), a class's `state`; each context it reads (`dependencies.firstContext`) with its nearest provider's `value` and the component that renders it. Vue 3: `__vueParentComponent` in development builds; production builds don't set it, so the app's vnode tree is walked from the element it is mounted on (`_vnode`, at most 20,000 vnodes) to find the element's component; its props, `setupState` and `data`, what it provides, and the chain through `parent`. Vue 2: the instance on the nearest element carrying one (`__vue__`; components sharing a root element leave the outermost's, so the innermost is found down its root vnode), its props and `data`, what it provides, and the chain through `$parent`. Angular: a component is its host element; a development build's `window.ng.getComponent` gives a host's instance, and a production build's comes from Angular's private view registry, which the main process finds among every Map of the heap (`Runtime.queryObjects(Map.prototype)`, only for such a page, and not while hovering, when hosts are named by their tags): the host's `__ngContext__` is the id of the view that declares it, which holds the host's own component view (a `TView` of type 1), whose context slot is the instance (`ANGULAR_VIEW`, Angular 17 to 22, pinned by the tests); its inputs (`ɵcmp.inputs`), its signals (settable) and fields, and the chain of hosts up through shadow roots; the Component page labels a production one as read from Angular's internals. Custom elements: an element whose tag is defined (`customElements.get`), its class the element's constructor; Lit's reactive properties (`elementProperties`, internal state flagged `state`, settable) or the observed attributes, and the chain of hosts. The element's handlers: the `on…` props React keeps on it (`__reactProps$…`), or its vnode's. The adapter answers with previews and the functions it named; `Runtime.getProperties` gives each function's `[[FunctionLocation]]` (script id, line and column) | +| Reading a component | `Runtime.callFunctionOn` of `ADAPTER_SOURCE` on the element, in the page's main world, `silent`. React: the fiber on the element or its nearest ancestor (`__reactFiber$…`; React keeps two copies of each fiber and doesn't update the element's key, so the copy on screen is found as React DevTools' `findCurrentFiberUsingSlowPath` does, at each step up), up through its `return`s to the function, class, `memo` and `forwardRef` components (the chain, at most 40); props from `memoizedProps`; hooks from the `memoizedState` list (state, a store, a ref, a memo; effects left out), a class's `state`; each context it reads (`dependencies.firstContext`) with its nearest provider's `value` and the component that renders it. Vue 3: `__vueParentComponent` in development builds; production builds don't set it, so the app's vnode tree is walked from the element it is mounted on (`_vnode`, at most 20,000 vnodes) to find the element's component, only down the elements that hold it (an element's vnode holds its subtree), so a large app costs its depth, not its size; its props, `setupState` and `data`, what it provides, and the chain through `parent`. Vue 2: the instance on the nearest element carrying one (`__vue__`; components sharing a root element leave the outermost's, so the innermost is found down its root vnode), its props and `data`, what it provides, and the chain through `$parent`. Angular: a component is its host element; a development build's `window.ng.getComponent` gives a host's instance, and a production build's comes from Angular's private view registry, which the main process finds among every Map of the heap (`Runtime.queryObjects(Map.prototype)`, only for such a page, and not while hovering, when hosts are named by their tags): the host's `__ngContext__` is the id of the view that declares it, which holds the host's own component view (a `TView` of type 1), whose context slot is the instance (`ANGULAR_VIEW`, Angular 17 to 22, pinned by the tests); its inputs (`ɵcmp.inputs`), its signals (settable) and fields, and the chain of hosts up through shadow roots; the Component page labels a production one as read from Angular's internals. Custom elements: an element whose tag is defined (`customElements.get`), its class the element's constructor; Lit's reactive properties (`elementProperties`, internal state flagged `state`, settable) or the observed attributes, and the chain of hosts. The element's handlers: the `on…` props React keeps on it (`__reactProps$…`), or its vnode's. The adapter answers with previews and the functions it named, each once (a level of 500 rows of one component names one function); `Runtime.getProperties` gives each function's `[[FunctionLocation]]` (script id, line and column), for at most 1,000 functions a read, one that went away meanwhile leaving the others placed | | Listeners | Every listener on the picked element itself (`DOMDebugger.getEventListeners`, which gives the handlers only for a handle in a named object group): its event, options and the function it runs (Vue 3's invoker unwrapped through its `value`, an object's `handleEvent`), named and placed like the others. On a plain page they are all there is; a framework's own (React's no-op click, Angular's wrapper) show as they are | | Hook names | A production component's hooks are listed by place. Once its function's original is known, the source-map worker parses the original (`@babel/parser`: TypeScript and JSX), finds the function at that place and lays its hook calls out as React keeps them, each named by the variable it sets (`const [qty, setQty] = useState(1)` → `qty`): React 19 adds two entries for `useSyncExternalStore` and `useTransition`, three for `useActionState`, none for `useContext`, `use` and `useDebugValue`. A custom hook defined in the same file is read in place; one from elsewhere stops the naming, since how many entries it adds is unknown | | Setting state | A `useState` hook (its queue reduces with React's own `basicStateReducer`, told by its text, which a minifier may quote with backticks; a `useReducer`'s takes actions, so it can't be set), a class's state (`setState`), a Vue component's `data` key, or a writable ref in its `setupState` (read under the unwrapping proxy, which forwards descriptors; a computed ref is read-only) can be set: the new value is written as JSON (at most 64 KB), dispatched in the page by the adapter's `set`, and the component is read again 50 ms later, rendered with it | -| Components tree | A frame's components a level at a time, read in its main world (where the console's contexts say, so it needs **Record the console**) by the adapter's `tree`: React's roots from the hook stand-in (`getFiberRoots`, as the extension's hook has), else from the containers React marks (`__reactContainer$…`, in the first 5,000 elements), Vue apps (`[data-v-app]`; a production build sets no `app._instance`, so the container's root vnode leads to it), Vue 2's root instances (`$children` below), Angular's root hosts (`[ng-version]`) and the top custom elements (below them, the nearest hosts in their light DOM and shadow roots). A node's children are the nearest components under it; a node is addressed by its path of indexes from the top, at most 500 listed per level. A node opens as a pick of its first element, at its component's depth in that element's chain (`locate`), and highlights as that element; a pick tells its path, so the tree reveals it | -| Script URLs | Only `Debugger.scriptParsed` names a script id. When one isn't known yet, `Debugger.enable` replays it for every script already parsed, with `Debugger.setSkipAllPauses` so a `debugger` statement can't stop the page, and `Debugger.disable` right after | +| Components tree | A frame's components a level at a time, read in its main world (where the console's contexts say, so it needs **Record the console**) by the adapter's `tree`: React's roots from the hook stand-in (`getFiberRoots`, as the extension's hook has), else from the containers React marks (`__reactContainer$…`, in the first 5,000 elements), Vue apps (`[data-v-app]`; a production build sets no `app._instance`, so the container's root vnode leads to it), Vue 2's root instances (`$children` below), Angular's root hosts (`[ng-version]`) and the top custom elements (below them, the nearest hosts in their light DOM and shadow roots). A node's children are the nearest components under it; a node is addressed by its path of indexes from the top, at most 500 listed per level; the frameworks' tops are read only as far as the path's first index (a React node reads no other framework's top). A level of 2,000 rows reads in about 30 ms (§9, Performance). A node opens as a pick of its first element, at its component's depth in that element's chain (`locate`), and highlights as that element; a pick tells its path, so the tree reveals it | +| Script URLs | Only `Debugger.scriptParsed` names a script id. When one isn't known yet, `Debugger.enable` replays it for every script already parsed, with `Debugger.setSkipAllPauses` so a `debugger` statement can't stop the page, and `Debugger.disable` right after. Each replay replaces what was kept, so the scripts of documents gone go with them; a script keeps whether it names a map, not the map's URL (an inline map's is the whole map), and no URL past 2,048 characters (its functions go unplaced) | | Save as action | The adapter also gives selectors that find the picked element again: its id when unique, else its place under the nearest ancestor with one (or body), one selector per root, from the document in through each open shadow root. After a value is set, the Component page offers to keep setting it as an action of its frame: readable code (`src/shared/stateAction/`, per framework) that finds the element, goes up to the component as the adapter does (React's fibers, Vue 3's element tag or vnode tree, Vue 2's instances, Angular's `ng`, custom elements' hosts) and sets the value. None for an element in a closed shadow root, or Angular's production build (no `ng`). The Actions view opens on it, named after the value (`Set qty of CartItem to 5`) | | Requests | Once its function's original is known, the page lists the requests of its frame whose sending script passed through that file (the Network log's initiators, §6.10: a frame's are traced to the originals when one of its components is shown, and as rows arrive while it is), with the call in it | | The chain | Each component of the chain is read again from the kept element, by depth, when asked, so a page tab shows the component as it is now. A pick whose element or frame is gone says so | | What is kept | The page answers, so its answer is checked like any input (`toInspectedComponent`): known frameworks, builds and state kinds only, names and previews as labels (control characters removed, at most 160 characters), at most 60 items per list | -| The original | In the renderer, each function's place in the bundle as served goes through the bundle's source map (the source-map worker's `toOriginalRaw`; a map not loaded yet is loaded quietly): the original file and line, and the function's name, from the map's `names` or, when it has none (Vite's minifier writes none), read off the original's text where the definition starts (`function Name`, `class Name`, `const Name = (…) =>`, a method or a property). A React component is then named after its original; Vue components carry their own names. Each place is looked up once (one already looked up, or being looked up, is skipped; a map that was let go is loaded again once for all the places waiting on it), and what is found is written to the store in one go every 16 ms, so a batch of thousands of places re-renders once; each row reads its own place's original (`useOrigin`), so it re-renders for that one only | +| The original | In the renderer, each function's place in the bundle as served goes through the bundle's source map (the source-map worker's `toOriginalRaw`; a map not loaded yet is loaded quietly): the original file and line, and the function's name, from the map's `names` or, when it has none (Vite's minifier writes none), read off the original's text where the definition starts (`function Name`, `class Name`, `const Name = (…) =>`, a method or a property). A React component is then named after its original; Vue components carry their own names. Each place is looked up once (one already looked up, or being looked up, is skipped; a map that was let go is loaded again once for all the places waiting on it), and what is found is written to the store in one go every 16 ms, so a batch of thousands of places re-renders once; each row reads its own place's original (`useOrigin`), so it re-renders for that one only. Forgetting the maps (another workspace) forgets what they said, originals and hook names, and a lookup that finishes after drops its answer | **UI.** The **Inspect** view in the rail shows what is under the pointer while picking, then the component picked and its chain, the **Components** tree of a frame with React or Vue (a chip per such frame; hovering a row highlights it, pressing it opens it, a dot marks what rendered in the frame's last recorded commit), and the page stack in short. The **Component** page tab (one per workspace) is titled with the component's name and shows the element (hovering it highlights it in the page), its frame, the source card (**Open original**, read-only at the component's line; **Go to bundle code**, the pretty-printed bundle at its definition), props, state, context and who provides it, the element's handlers with where each is defined, and the chain, where clicking a component reads that one; React hooks are named after their variables when the original is known, a settable value has a pencil to set it (JSON, Enter), and a React component lists its recorded renders (§6.14). Picking again replaces it. @@ -658,7 +658,7 @@ While store actions are recorded, every action the page's stores handle in every | What | How | |---|---| -| The store stand-in | In the same script as the React stand-in (`HOOKS_SOURCE`), before the page's scripts: when the page has no Redux DevTools extension, a stand-in for its globals. `__REDUX_DEVTOOLS_EXTENSION_COMPOSE__` is what Redux Toolkit's `configureStore` composes in (production builds too), `__REDUX_DEVTOOLS_EXTENSION__()` the enhancer a plain Redux store adds: innermost, as the extension's, so it hears the plain actions that got through the middleware and measures the reducers. `connect()` is how NgRx's StoreDevtools (its app's action wrapped in `PERFORM_ACTION`) and Zustand's devtools middleware report each action with the state after it. Pinia's and Vuex's stores are found in the Vue app's global properties (`$pinia`, `$store`; a Vue 2 root's own) when recording starts and as a document loads (and a second later); a Pinia store created later is caught by a plugin. Pinia's actions are heard through `$onAction` (until its promise settles), its changes outside an action through a synchronous `$subscribe`, two levels deep and only while recording (it is a deep watcher: Vue walks the state on every change, which made an action on a 20,000-item store take 50 times as long; stopping takes it off), Vuex's mutations through `subscribe` | +| The store stand-in | In the same script as the React stand-in (`HOOKS_SOURCE`), before the page's scripts: when the page has no Redux DevTools extension, a stand-in for its globals. `__REDUX_DEVTOOLS_EXTENSION_COMPOSE__` is what Redux Toolkit's `configureStore` composes in (production builds too), `__REDUX_DEVTOOLS_EXTENSION__()` the enhancer a plain Redux store adds: innermost, as the extension's, so it hears the plain actions that got through the middleware and measures the reducers. `connect()` is how NgRx's StoreDevtools (its app's action wrapped in `PERFORM_ACTION`) and Zustand's devtools middleware report each action with the state after it. Pinia's and Vuex's stores are found in the Vue app's global properties (`$pinia`, `$store`; a Vue 2 root's own) when recording starts and as a document loads (and a second later); a Pinia store created later is caught by a plugin. Pinia's actions are heard through `$onAction` (until its promise settles; one still running after 10 s, `ACTION_SETTLE_MS`, stops counting as running, so the store's other changes are heard again), its changes outside an action through a synchronous `$subscribe`, two levels deep and only while recording (it is a deep watcher: Vue walks the state on every change, which made an action on a 20,000-item store take 50 times as long; stopping takes it off), Vuex's mutations through `subscribe` | | What changed | Two levels of the state at most. Redux's, NgRx's and Zustand's states are replaced, never changed in place, so the state before is kept by reference and compared by identity; Pinia's and Vuex's are changed in place, so they are written out before (bounded text: 400 characters a value, 300 paths) and compared as text. Only the deepest paths that changed are listed, at most 20, each with previews before and after (arrays with their length first, as DevTools shows them) | | The stack | A new Error's stack (`Error.stackTraceLimit` raised to 50 while it is read, the page's `prepareStackTrace` put aside), the calls in files the page loaded kept (NgRx's pipeline puts the app's call 40 deep). The renderer traces each to its original and links the first that isn't a library's (under node_modules) | | Handing over | As Renders': batched every 100 ms, at most 200 per batch, through the binding (`STORES_BINDING`); the payload (at most 4 MB) is checked (`toStoreActions`: known libraries only, text as labels, stacks in http(s) files, caps), numbered and given its frame (`stores-recorded`). The stand-in's timer, `JSON.stringify` and `addEventListener` are the ones the page started with | @@ -732,11 +732,11 @@ The site's `WebContentsView` can move to a window of its own (`PageWindow`), e.g | Layer | What | Command | |---|---|---| -| Unit | Matchers, header/SRI/source-map transforms, stores (persistence, atomic concurrent writes), engine logic and navigation rules with a fake CDP transport, iframe session coordination (timeouts, sessions that go away, cascading detach), worker sessions (setup order and resuming, `Fetch` kept on, settings per worker type, which session lists and credits a worker's files, missed-override reasons, outdated service workers and `prepareReload` (unregistering by scope, letting go, retrying), a service worker's state kept for its next session, shared-worker discovery and holding), minified heuristic, version comparison, CHANGELOG parsing (and that CHANGELOG.md covers `package.json`'s version), the update service with fakes (checks, quiet failures, progress, checksums, install failures, schedule), the Linux desktop entry (quoting paths, which copies install one, a package's entry winning, removing only its own, following a renamed AppImage, writing only what changed) and the `.rpm`'s install script kept in step with electron-builder's, workspaces in the stores (migration, per-workspace tabs, drafts, overrides and actions, deletion, frame names), the action store (each workspace's actions across instances, what it refuses and why, a failed write changing nothing, changes run in order), favicon loading (recognising images, size caps), the console service with a fake CDP transport (frames across sessions, contexts, rows and their previews, format directives, running code, properties, the cap, clearing, the setting), the session observer (handed every session before it runs, never holding interception up) and where the website's and the Actions panel's windows open (its saved place while it is on a screen, another screen than the editor's, fitted to a small one, at the size each opens at) and how that is saved (Keep on top too), rules (validation, the store's persistence, entries it can't read, broken and unreadable files, the engine's stages, header edits, CORS and preflights, request types, patterns), source maps (finding the reference, loading limits, header capture), response overrides that don't send (`unsentOverrides.test.ts`: patterns, the answer and its CORS, the preflight, what goes on to the server, the delay, the setting kept) and breakpoints (`breakpoints.test.ts`: validation and storage, patterns, holding at each stage and each action, what never stops, letting go), the JSON tree (`jsonTree.test.ts`: parsing without loss, offsets, what it refuses, diffing and applying edits, giving up on a document they don't fit), patch mode (`patchMode.test.ts`: the live response patched, edits worked out once per version, the saved text when upstream fails or the edits don't fit, never a stream, the setting kept), HAR files (`har.test.ts`: entries written, sockets' messages, overrides read back and what is left out), the network speed setting (kept, checked) and its commands on every kind of session, the page stack (the React hook stand-in in every session, with `Page` on first, taken out and put back with the setting; a frame looked at once it loads, silently in its main world, once for two loads in quick succession, not after it navigated, and not kept from the document it left; a cross-site iframe's own session, dropped with it; nothing while the console doesn't record, every frame once it does; the console unaffected when the stand-in can't go in; what the page answers checked: unknown ids and signals, builds, versions, at most 40); the component inspector with a fake CDP transport (`componentInspector.test.ts`: every session into inspect mode and out, one that attaches while picking too; what is under the pointer read at most every interval, the latest node winning; a click stopping picking, keeping the node as `$0` and sending its component with each function placed; a node's frame told by its frame owner; the chain's other components; Esc in the page; the last 20 picks kept and older handles freed; highlighting, with the Overlay domain off once picking and highlights are over; a node that can't be read; a production Angular page's view registry found and handed to the adapter; the element's own listeners, named and placed; what the page says checked: frameworks, builds, state kinds, labels, list caps); scripts' source maps counted per frame (inline, isolated-world, evaluated and other frames' scripts left out); renders, the tree and state (`componentRenders.test.ts`: the binding in every session while recording, one attaching too, removed and its function deleted when it stops; batches sent in order, checked, framed by their context, their functions located once per document; other bindings, bad payloads and anything after stopping ignored; the page's commits checked: kinds, reasons, labels, caps; a tree level read in the frame's main world, a node opened as a pick at its depth and highlighted, a gone frame or bad path refused; a state edit taken only as a known kind, a name and JSON); source maps loaded from files (`sourceMapFileStore.test.ts`: a copy kept per workspace and bundle and read back after a restart, replaced, forgotten, removed with its workspace, its copies deleted; index entries that don't hold up, a copy named outside the folder among them, left out; a file's map handed over as found against the bundle as served); store actions (`storeTimeline.test.ts`: the hooks' one script, which parses; the binding in every session while recording, each frame asked to find its Vue stores, taken out when it stops; batches checked, numbered and framed, others' and late ones ignored, a flood of them capped; known libraries, labels, stacks in loaded files and caps), the events sent to a window as JSON (`appEventWire.test.ts`), commits naming their store action and components their own render time, a request's initiator through its async parents in loaded files (`networkLog.test.ts`) | `npm test` | -| Renderer | Resource tree building and filtering (worker entries: kept across navigations for service and shared workers, dropped with their worker, filtered by worker URL), command-palette fuzzy matching, missed-override notices by reason (a nested worker's once per override version), update notifications, What's New and page tabs, session sync and workspace switching (pending drafts written, tabs closed without losing them, the other workspace's reopened), console frames (keys, labels, colours), rows, filters, Keep rows, prompt history and frame names, rules (quick rules and Undo, toggling with rollback, rule pages and their drafts, applying only what changed, results that arrive after a switch, hits and recent requests), original sources (parsing, positions through pretty-printing, tabs, jumps both ways, the tree, the palette), actions (finding an action's frame by key or by name, labels of frames not on the page, runs and why one couldn't run, the form's openings, saving and deleting, copies, the palette's group, the bridge loading and following them), the Actions window's bridge (what it loads, the events it follows and those it ignores) and the editor's copy of where the panel is and of settings another window changed, the Network panel (rows kept and replaced, earlier loads dropped unless kept, groups and the text filter, status, size and time cells, which actions a request offers) and response overrides (the inferred schema, which override answers a request, opening a response and saving it with its method, operation and answer, the response row's fields and Apply), the bottom pane's tab, held requests (`held.test.ts`: their tabs, what Send does at each stage and with an edited body, fields that can't go out, Send original, Fail, Save as override, closing the tab, the page giving up, never kept in the session), breakpoints (added, toggled, removed, refused, put back when saving fails, Pause like this) and Copy as fetch, quick edits (`quickEdits.test.ts`: lists emptied, texts lengthened but links, ids and dates, the value at the cursor nulled, the rest of the text as typed) and Patch live through the response row's form, the response tree (`responseTree.test.ts`: rows for what is open with unique ids, members removed with their comma, added as the last one is written, the selection after a rename or removal), the page stack (UI libraries named once, the top page's first; findings by kind; one Page stack tab; the bridge's snapshot and `stack-changed`), the component inspector (`componentInspector.test.ts`: a function's place in the bundle mapped to its original, named by the map or read off the original's text in each way code names a function; a React component named after its original, a Vue one by itself; picking toggled as main last said; another component of the chain read, or a toast when the page moved on; the bridge following picking and showing what was picked, in one Component tab renamed in place); hook names read off an original (`hookNames.test.ts`: hook calls laid out as React keeps them, same-file custom hooks followed, an imported one stopping the naming, arrows placed by their parameters); renders, the tree and state (`componentRenders.test.ts`: why a component took part, in words, hooks named; triggers; what a frame's last commit rendered; the log's cap; the bridge following recording and tracing functions once each; tree rows as far as open; a frame's top level, a node opened once and closed, a stale frame's level dropped, a pick revealed down its path; opening a node, and a toast when it can't; setting a value, and a toast when it can't); maps loaded from files (`mapFiles.test.ts`: location keys read back; a bundle's traced places forgotten and traced again once a map is loaded or forgotten, nothing when no file was picked, toasts on failures; the Explorer's menu items); store actions (`storeTimeline.test.ts`: recording followed, actions kept and capped, their calls traced once each, a failure to start said; the app's own call in a stack, past libraries); requests by component (`requestsByComponent.test.ts`: a frame's requests sent through a file, newest first, with the call); a commit's trigger with its action, a set value kept and the action written from it per framework (a hook's place, a class's key, selectors through shadow roots, none without a way in), renders by component (counts, own time summed, reasons, costliest first; kept as commits come and go the same as summed afresh; the log's rows) (`componentRenders.test.ts`) | `npm test` | +| Unit | Matchers, header/SRI/source-map transforms, stores (persistence, atomic concurrent writes), engine logic and navigation rules with a fake CDP transport, iframe session coordination (timeouts, sessions that go away, cascading detach), worker sessions (setup order and resuming, `Fetch` kept on, settings per worker type, which session lists and credits a worker's files, missed-override reasons, outdated service workers and `prepareReload` (unregistering by scope, letting go, retrying), a service worker's state kept for its next session, shared-worker discovery and holding), minified heuristic, version comparison, CHANGELOG parsing (and that CHANGELOG.md covers `package.json`'s version), the update service with fakes (checks, quiet failures, progress, checksums, install failures, schedule), the Linux desktop entry (quoting paths, which copies install one, a package's entry winning, removing only its own, following a renamed AppImage, writing only what changed) and the `.rpm`'s install script kept in step with electron-builder's, workspaces in the stores (migration, per-workspace tabs, drafts, overrides and actions, deletion, frame names), the action store (each workspace's actions across instances, what it refuses and why, a failed write changing nothing, changes run in order), favicon loading (recognising images, size caps), the console service with a fake CDP transport (frames across sessions, contexts, rows and their previews, format directives, running code, properties, the cap, clearing, the setting), the session observer (handed every session before it runs, never holding interception up) and where the website's and the Actions panel's windows open (its saved place while it is on a screen, another screen than the editor's, fitted to a small one, at the size each opens at) and how that is saved (Keep on top too), rules (validation, the store's persistence, entries it can't read, broken and unreadable files, the engine's stages, header edits, CORS and preflights, request types, patterns), source maps (finding the reference, loading limits, header capture), response overrides that don't send (`unsentOverrides.test.ts`: patterns, the answer and its CORS, the preflight, what goes on to the server, the delay, the setting kept) and breakpoints (`breakpoints.test.ts`: validation and storage, patterns, holding at each stage and each action, what never stops, letting go), the JSON tree (`jsonTree.test.ts`: parsing without loss, offsets, what it refuses, diffing and applying edits, giving up on a document they don't fit), patch mode (`patchMode.test.ts`: the live response patched, edits worked out once per version, the saved text when upstream fails or the edits don't fit, never a stream, the setting kept), HAR files (`har.test.ts`: entries written, sockets' messages, overrides read back and what is left out), the network speed setting (kept, checked) and its commands on every kind of session, the page stack (the React hook stand-in in every session, with `Page` on first, taken out and put back with the setting; a frame looked at once it loads, silently in its main world, once for two loads in quick succession, not after it navigated, and not kept from the document it left; a cross-site iframe's own session, dropped with it; nothing while the console doesn't record, every frame once it does; the console unaffected when the stand-in can't go in; what the page answers checked: unknown ids and signals, builds, versions, at most 40); the component inspector with a fake CDP transport (`componentInspector.test.ts`: every session into inspect mode and out, one that attaches while picking too; what is under the pointer read at most every interval, the latest node winning; a click stopping picking, keeping the node as `$0` and sending its component with each function placed; a node's frame told by its frame owner; the chain's other components; Esc in the page; the last 20 picks kept and older handles freed; highlighting, with the Overlay domain off once picking and highlights are over; a node that can't be read; a production Angular page's view registry found and handed to the adapter; the element's own listeners, named and placed; what the page says checked: frameworks, builds, state kinds, labels, list caps); scripts' source maps counted per frame (inline, isolated-world, evaluated and other frames' scripts left out); renders, the tree and state (`componentRenders.test.ts`: the binding in every session while recording, one attaching too, removed and its function deleted when it stops; batches sent in order, checked, framed by their context, their functions located once per document; other bindings, bad payloads and anything after stopping ignored; the page's commits checked: kinds, reasons, labels, caps; a tree level read in the frame's main world, a node opened as a pick at its depth and highlighted, a gone frame or bad path refused; a state edit taken only as a known kind, a name and JSON); source maps loaded from files (`sourceMapFileStore.test.ts`: a copy kept per workspace and bundle and read back after a restart, replaced, forgotten, removed with its workspace, its copies deleted; index entries that don't hold up, a copy named outside the folder among them, left out; a file's map handed over as found against the bundle as served); store actions (`storeTimeline.test.ts`: the hooks' one script, which parses; the binding in every session while recording, each frame asked to find its Vue stores, taken out when it stops; batches checked, numbered and framed, others' and late ones ignored, a flood of them capped; known libraries, labels, stacks in loaded files and caps), the events sent to a window as JSON (`appEventWire.test.ts`), the main process's lookups bounded (`inspectorLookups.test.ts`: only the scripts alive kept, whether each names a map, long URLs left out; at most 1,000 functions placed a read, one gone leaving the others; initiators' URLs and names), commits naming their store action and components their own render time, a request's initiator through its async parents in loaded files (`networkLog.test.ts`) | `npm test` | +| Renderer | Resource tree building and filtering (worker entries: kept across navigations for service and shared workers, dropped with their worker, filtered by worker URL), command-palette fuzzy matching, missed-override notices by reason (a nested worker's once per override version), update notifications, What's New and page tabs, session sync and workspace switching (pending drafts written, tabs closed without losing them, the other workspace's reopened), console frames (keys, labels, colours), rows, filters, Keep rows, prompt history and frame names, rules (quick rules and Undo, toggling with rollback, rule pages and their drafts, applying only what changed, results that arrive after a switch, hits and recent requests), original sources (parsing, positions through pretty-printing, tabs, jumps both ways, the tree, the palette), actions (finding an action's frame by key or by name, labels of frames not on the page, runs and why one couldn't run, the form's openings, saving and deleting, copies, the palette's group, the bridge loading and following them), the Actions window's bridge (what it loads, the events it follows and those it ignores) and the editor's copy of where the panel is and of settings another window changed, the Network panel (rows kept and replaced, earlier loads dropped unless kept, groups and the text filter, status, size and time cells, which actions a request offers) and response overrides (the inferred schema, which override answers a request, opening a response and saving it with its method, operation and answer, the response row's fields and Apply), the bottom pane's tab, held requests (`held.test.ts`: their tabs, what Send does at each stage and with an edited body, fields that can't go out, Send original, Fail, Save as override, closing the tab, the page giving up, never kept in the session), breakpoints (added, toggled, removed, refused, put back when saving fails, Pause like this) and Copy as fetch, quick edits (`quickEdits.test.ts`: lists emptied, texts lengthened but links, ids and dates, the value at the cursor nulled, the rest of the text as typed) and Patch live through the response row's form, the response tree (`responseTree.test.ts`: rows for what is open with unique ids, members removed with their comma, added as the last one is written, the selection after a rename or removal), the page stack (UI libraries named once, the top page's first; findings by kind; one Page stack tab; the bridge's snapshot and `stack-changed`), the component inspector (`componentInspector.test.ts`: a function's place in the bundle mapped to its original, named by the map or read off the original's text in each way code names a function; a React component named after its original, a Vue one by itself; picking toggled as main last said; another component of the chain read, or a toast when the page moved on; the bridge following picking and showing what was picked, in one Component tab renamed in place); hook names read off an original (`hookNames.test.ts`: hook calls laid out as React keeps them, same-file custom hooks followed, an imported one stopping the naming, arrows placed by their parameters); renders, the tree and state (`componentRenders.test.ts`: why a component took part, in words, hooks named; triggers; what a frame's last commit rendered; the log's cap; the bridge following recording and tracing functions once each; tree rows as far as open; a frame's top level, a node opened once and closed, a stale frame's level dropped, a pick revealed down its path; opening a node, and a toast when it can't; setting a value, and a toast when it can't); maps loaded from files (`mapFiles.test.ts`: location keys read back; a bundle's traced places forgotten and traced again once a map is loaded or forgotten, every original and hook name forgotten with the maps and a lookup finishing after dropped, nothing when no file was picked, toasts on failures; the Explorer's menu items); store actions (`storeTimeline.test.ts`: recording followed, actions kept and capped, their calls traced once each, a failure to start said; the app's own call in a stack, past libraries); requests by component (`requestsByComponent.test.ts`: a frame's requests sent through a file, newest first, with the call); a commit's trigger with its action, a set value kept and the action written from it per framework (a hook's place, a class's key, selectors through shadow roots, none without a way in), renders by component (counts, own time summed, reasons, costliest first; kept as commits come and go the same as summed afresh; the log's rows) (`componentRenders.test.ts`) | `npm test` | | Performance | The inspector on large apps in real Chromium (`test/perf/inspector.perf.test.ts`): a React and a Vue 3 app of some 14,000 components (a 2,000-row table, a chain 1,500 deep in React, 300 in Vue) and stores of 20,000 items (Redux Toolkit, Pinia), as production builds. It times a commit of every row with the hooks off, idle and recording renders, and after picking; hovering and picking deep in the table and at the end of the chain; the page stack; a level of the tree; a batch's size; Redux dispatches and Pinia actions idle, recording and after it stopped. And the built app's UI (`test/perf/ui.perf.test.ts`) fed what large apps record at the pace recording sends it (2,000 commits of 200 components, 1,000 store actions with 50-call stacks, 2,000 requests with 20-call initiators, their places traced through a real bundle's map): how long the window's main thread is blocked, its longest task, the memory the log takes, and how long **By component** takes to show. Each prints its medians and fails past a budget set well above what a laptop measures, so only work growing with the whole page on a hot path trips it; it isn't part of CI | `npm run test:perf` (on a display: `xvfb-run -a` on headless Linux) | | Architecture | Feature-Sliced Design layer rules; the code-structure rules (files of at most 150 lines, one function, component, class or store per file named after it, data-only constants/types/index files, no `switch`) | `npm run lint:fsd`, `npm run lint:structure` | -| Integration | Engine in real Chromium against the fixture site: gzip, static and runtime SRI, globs, CSS/HTML overrides, 404, redeploy detection, source maps, disable. Iframes through the session-aware WebSocket transport (`test/helpers/chromium.ts`): same-site, cross-site and nested iframes, SRI inside iframes, iframe HTML overrides, same-site navigation, removal, reload; each asserts the iframe really is a separate target. The console on a page of service iframes (same-site, and two on sites of their own): every frame's first log line on its own frame, code run in one frame and another frame's logs reacting, top-level `await` and expanding the result, uncaught errors and rejections, a frame keeping its id across a navigation, a cross-site frame's function refused from the top page but run in the frame itself (why actions run in their frame). Workers against the fixture's `/workers/` page (`workers.chromium.test.ts`, a fresh browser context per test): every kind runs while intercepted; edits reach a dedicated and a module worker's first script and imports, what a nested worker imports (its first script is served in Chromium 141, reported as missed in 152+), a shared worker, a service worker's script and imports, and an audio worklet's module; each file is listed with its worker and read through its session; a shared worker's races are forced by holding back its session's commands; workers under a cross-site iframe are served on its session and removed with it; workers are reported gone; an edit to an installed service worker applies on the next reload, and one whose page was left is reinstalled when its site loads again under other overrides (a workspace switch); the page's `registration.update()` is reported and the next reload undoes it; a service worker is listed again, and not reinstalled, when the page comes back to its site; the cache setting reaches what workers load. Rules (`rules.chromium.test.ts`): blocking before the server sees the request (a script, one inside a cross-site iframe, an iframe's document, a redirect's later hop), a URL both blocked and overridden, the page itself never blocked; a gzipped document's CSP removed and another's added, X-Frame-Options removed so a page can be framed, a document no rule changes never read, Cache-Control and Content-Type on streamed responses, headers back once a rule is off; CORS with credentials, a preflight the API refuses, redirects. Source maps named by headers, `X-SourceMap`, comments and `data:` URIs, a stylesheet's, and an override-served bundle's. The network log and response overrides (`network.chromium.test.ts`, the fixture's `/network/` page): what the log lists for fetch(), GraphQL, a failing call, an event stream and a worker's fetch, page loads counted, request and response bodies read, never a stream's (which keeps streaming); a response override answering fetch() and XHR with its body, status and header changes (the request still reaching the server) and marking the row, its delay, only its method and GraphQL operation, a dedicated worker's fetch, and an event stream left streaming or replaced as a whole. Held and unsent requests (`held.chromium.test.ts`): an override that doesn't send answering another origin's POST and its preflight with the server never hit (and, without it, the server turning the preflight away); breakpoints holding a response (its row marked) until answered edited or as it was, a request before it is sent (its row marked) sent elsewhere or answered, one failed, one the page gave up on let go, everything let go when interception stops, and nothing stopped once off. In `network.chromium.test.ts` too: patch mode keeping the live values it wasn't told to change and answering a failing upstream with the saved text; the page and its worker taken offline and slowed down; a WebSocket's handshake, text and binary messages read incrementally, and its close; the log written as HAR with its bodies and read back as overrides that answer without the server. The page stack (`stack.chromium.test.ts`): a React app the test bundles from the repo's react and react-dom, found through the hook stand-in with its version, as a production and a development build, and by its keys with **Framework hooks** off (and no hook left in the page); what Vue, Pinia, Angular, Next.js and webpack leave in a page; a cross-site iframe's React, which found the stand-in in place before it loaded; no console rows. The component inspector (`inspect.chromium.test.ts`), with real pointer input on carts in React and Vue the test bundles (`test/helpers/bundleApp.ts`), as minified production builds with source maps and as development builds: a production React component's chain, props, state, context and handler, each function traced through the map to its source line; a click the page never gets, and the element as `$0`; the chain's other components, and an element that is gone; a production Vue component through its app's vnode tree, with what the app provides, and a development build's from the element; picking inside a cross-site iframe on its own session; Esc in the page; a useState hook set and rendered, JSON and unsettable values refused; Vue's data and a setup ref set, a computed one refused; the Components tree of a React app through the hook stand-in and by its containers without it, and of a production Vue app, nodes opened as picks at their depth, picks' paths; renders recorded on a React app whose buttons each commit for another reason (own state and a store, a context with a memo child skipped, a parent's state with changed props, a class's state), with triggers, frames, durations and order, nothing after stopping, and a production build's mount recorded from a document loaded while recording, its functions placed through the map. The page stack (`stack.chromium.test.ts`) also counts a frame's scripts that name a source map by comment or header. The other frameworks (`frameworks.chromium.test.ts`), each bundled by the test from the repo's own packages: a production Angular component read through its view registry (inputs, a settable signal, a field that isn't, each class placed by the map; hosts named by their tags while hovering), a development build through `window.ng` and its tree, a production build's tree through the registry; a Vue 2 component's props, data (set), what the app provides, chain and tree; a Lit component in its shadow root, its properties and state (set), host chain and tree; a plain page's listeners with names, places and options; a Vue 3 listener's function, not Vue's invoker; store actions (`stores.chromium.test.ts`): Redux Toolkit's (the slice's type, payload, what changed, the handler's line through the map; the page stack names Redux), the React commit after one naming it and nothing once stopped, Zustand's through its devtools, Pinia's actions and direct changes and Vuex's mutations (found when recording starts and by a document loaded while recording), NgRx's through its StoreDevtools; a request keeping the stack of the handler that sent it; saved actions (`stateActions.chromium.test.ts`): a picked component's action written, the page loaded again, and the action setting the value in React (a hook), Vue 3 production and development (a ref and data), Vue 2 (data), Angular development (a signal; production gets none) and Lit (through two shadow roots) | `npm test` (skips if no Chromium; `npx playwright install chromium`) | +| Integration | Engine in real Chromium against the fixture site: gzip, static and runtime SRI, globs, CSS/HTML overrides, 404, redeploy detection, source maps, disable. Iframes through the session-aware WebSocket transport (`test/helpers/chromium.ts`): same-site, cross-site and nested iframes, SRI inside iframes, iframe HTML overrides, same-site navigation, removal, reload; each asserts the iframe really is a separate target. The console on a page of service iframes (same-site, and two on sites of their own): every frame's first log line on its own frame, code run in one frame and another frame's logs reacting, top-level `await` and expanding the result, uncaught errors and rejections, a frame keeping its id across a navigation, a cross-site frame's function refused from the top page but run in the frame itself (why actions run in their frame). Workers against the fixture's `/workers/` page (`workers.chromium.test.ts`, a fresh browser context per test): every kind runs while intercepted; edits reach a dedicated and a module worker's first script and imports, what a nested worker imports (its first script is served in Chromium 141, reported as missed in 152+), a shared worker, a service worker's script and imports, and an audio worklet's module; each file is listed with its worker and read through its session; a shared worker's races are forced by holding back its session's commands; workers under a cross-site iframe are served on its session and removed with it; workers are reported gone; an edit to an installed service worker applies on the next reload, and one whose page was left is reinstalled when its site loads again under other overrides (a workspace switch); the page's `registration.update()` is reported and the next reload undoes it; a service worker is listed again, and not reinstalled, when the page comes back to its site; the cache setting reaches what workers load. Rules (`rules.chromium.test.ts`): blocking before the server sees the request (a script, one inside a cross-site iframe, an iframe's document, a redirect's later hop), a URL both blocked and overridden, the page itself never blocked; a gzipped document's CSP removed and another's added, X-Frame-Options removed so a page can be framed, a document no rule changes never read, Cache-Control and Content-Type on streamed responses, headers back once a rule is off; CORS with credentials, a preflight the API refuses, redirects. Source maps named by headers, `X-SourceMap`, comments and `data:` URIs, a stylesheet's, and an override-served bundle's. The network log and response overrides (`network.chromium.test.ts`, the fixture's `/network/` page): what the log lists for fetch(), GraphQL, a failing call, an event stream and a worker's fetch, page loads counted, request and response bodies read, never a stream's (which keeps streaming); a response override answering fetch() and XHR with its body, status and header changes (the request still reaching the server) and marking the row, its delay, only its method and GraphQL operation, a dedicated worker's fetch, and an event stream left streaming or replaced as a whole. Held and unsent requests (`held.chromium.test.ts`): an override that doesn't send answering another origin's POST and its preflight with the server never hit (and, without it, the server turning the preflight away); breakpoints holding a response (its row marked) until answered edited or as it was, a request before it is sent (its row marked) sent elsewhere or answered, one failed, one the page gave up on let go, everything let go when interception stops, and nothing stopped once off. In `network.chromium.test.ts` too: patch mode keeping the live values it wasn't told to change and answering a failing upstream with the saved text; the page and its worker taken offline and slowed down; a WebSocket's handshake, text and binary messages read incrementally, and its close; the log written as HAR with its bodies and read back as overrides that answer without the server. The page stack (`stack.chromium.test.ts`): a React app the test bundles from the repo's react and react-dom, found through the hook stand-in with its version, as a production and a development build, and by its keys with **Framework hooks** off (and no hook left in the page); what Vue, Pinia, Angular, Next.js and webpack leave in a page; a cross-site iframe's React, which found the stand-in in place before it loaded; no console rows. The component inspector (`inspect.chromium.test.ts`), with real pointer input on carts in React and Vue the test bundles (`test/helpers/bundleApp.ts`), as minified production builds with source maps and as development builds: a production React component's chain, props, state, context and handler, each function traced through the map to its source line; a click the page never gets, and the element as `$0`; the chain's other components, and an element that is gone; a production Vue component through its app's vnode tree, with what the app provides, and a development build's from the element; picking inside a cross-site iframe on its own session; Esc in the page; a useState hook set and rendered, JSON and unsettable values refused; Vue's data and a setup ref set, a computed one refused; the Components tree of a React app through the hook stand-in and by its containers without it, and of a production Vue app (each function placed once however many of its components a level lists), nodes opened as picks at their depth, picks' paths; renders recorded on a React app whose buttons each commit for another reason (own state and a store, a context with a memo child skipped, a parent's state with changed props, a class's state), with triggers, frames, durations and order, nothing after stopping, and a production build's mount recorded from a document loaded while recording, its functions placed through the map. The page stack (`stack.chromium.test.ts`) also counts a frame's scripts that name a source map by comment or header. The other frameworks (`frameworks.chromium.test.ts`), each bundled by the test from the repo's own packages: a production Angular component read through its view registry (inputs, a settable signal, a field that isn't, each class placed by the map; hosts named by their tags while hovering), a development build through `window.ng` and its tree, a production build's tree through the registry; a Vue 2 component's props, data (set), what the app provides, chain and tree; a Lit component in its shadow root, its properties and state (set), host chain and tree; a plain page's listeners with names, places and options; a Vue 3 listener's function, not Vue's invoker; store actions (`stores.chromium.test.ts`): Redux Toolkit's (the slice's type, payload, what changed, the handler's line through the map; the page stack names Redux), the React commit after one naming it and nothing once stopped, Zustand's through its devtools, Pinia's actions and direct changes (heard again once an action that never settles stops counting) and Vuex's mutations (found when recording starts and by a document loaded while recording), NgRx's through its StoreDevtools; a request keeping the stack of the handler that sent it; saved actions (`stateActions.chromium.test.ts`): a picked component's action written, the page loaded again, and the action setting the value in React (a hook), Vue 3 production and development (a ref and data), Vue 2 (data), Angular development (a signal; production gets none) and Lit (through two shadow roots) | `npm test` (skips if no Chromium; `npx playwright install chromium`) | | End-to-end | Built Electron app driven by Playwright: open site, edit, save, page runs it, disable/enable, edit files inside a cross-site and a nested iframe, the fixture's `/workers/` page with its workers' files listed under their worker's badge and edited (imports of each kind of worker; a module worker's static import; the first script of a dedicated worker, a shared worker, a service worker and a worklet; a service worker's script edited again, turned off and on, and deleted; a worker under a cross-site iframe), the update check's toast with Bypass service workers off and its reload, what stays listed when the page leaves (its site's service worker) and when it leaves the site (nothing), each workspace running its own edit of the service worker's script (`workers.e2e.test.ts`), persistence across restart, a second launch handing over its URL, workspaces (a new one starts empty and doesn't serve another's overrides, takes its site's favicon, switching back restores the page, tabs and overrides with no history from the other, renaming, all of it across a restart), the console (each frame's rows, running code in a picked frame and seeing another react, filtering by frame, naming a frame and keeping the name across a restart, clearing), actions (`actions.e2e.test.ts`: code run in the console saved as an action for its frame, run with one click and another frame reacting, one for a frame picked from the page showing what it threw, run from the palette, changed and deleted, each workspace's own across a restart), the Actions panel in a window of its own (`actionsWindow.e2e.test.ts`: moved there, running and making actions from it, the workspace and the settings following it, Keep on top, reopened where it was after a restart, back by closing it, from the sidebar's notice and from the View menu), the website in a window of its own (`pageWindow.e2e.test.ts`: moved there from the preview's toolbar without reloading, the editor's saved edits served to it, navigating from its toolbar, back from its button, by closing it, from the title bar and from the View menu; the site's pop-ups moving with it; put back, or asked for its address bar, while its window still loads; where it was and that it was open kept across a restart). Rules: block a script from the file tree, turn it off and on, undo a quick rule, remove a page's CSP, allow CORS for an API with a preflight, keep an unapplied edit on its tab and apply it from File › Save, rules per workspace, delete, and blocking from the first load after a restart. Updates against a local feed: the automatic announcement, What's New with the release's notes, a download refused for its checksum and then accepted. The original sources behind a bundle: listed, opened read-only, jumping to the pretty-printed bundle line and back, found from the palette. The Network panel (`network.e2e.test.ts`): the page's fetch and GraphQL calls listed, Fetch/XHR first and the document under All; a response opened, edited, saved and served to the page, the row marked and the override in the Explorer with its method; another status applied from the response row; the override turned off; requests like the selected one paused and an edited response sent to the page, a paused response saved as an override that answers from then on, a breakpoint written in the menu holding a request before it is sent, and that request failed; the live response patched from the response row, a quick edit saved and served, the page taken offline and back from the network speed menu, a WebSocket's messages in its details, a response edited as a tree with the keyboard (a value retyped, a key renamed, a member removed) and saved, and the requests exported as HAR and imported back as overrides. The page stack (`stack.e2e.test.ts`): the status bar names the fixture's UI libraries and opens the Page stack, which lists each finding by kind with its version, build and evidence, and scans again. The component inspector (`inspect.e2e.test.ts`) on a production React cart framed from another site: the toolbar's button picks and the Inspect view shows what is under the pointer; a click opens the Component page, named `CartItem` and placed at its source line through the map, with props, state, context, the handler by its original name and the chain; **Open original** and **Go to bundle code** land on its definition; the View menu starts and stops picking, and Esc in the editor stops it; the Inspect view's tree lists the cart frame's components down to the one picked, selected; a state value named `qty` (from the original) is set from the Component page and the cart shows it; **Record renders** from the palette records a real click, the Renders tab says it was a click on `button#add-A1` and that `CartItem` rendered for `state qty 5 → 6`, and the Component page lists that render. A map from a file (`mapFile.e2e.test.ts`): a production React bundle that names no map, picked, given its map through **Load a source map…** (the system's dialog stubbed in the main process) and named `CartItem` at its line, then forgotten; a plain page's element shown with its listener and where it is defined; the inspected cart's renders by component, and its set value kept as an action that sets it again after a reload; a Redux Toolkit cart (`dataFlow.e2e.test.ts`): its actions recorded from the palette with what they changed and the line that dispatched them (and their stack), the commit after one naming it, and a request's **Sent by** stack traced to the handler | `npm run test:e2e` (on headless Linux: `xvfb-run npm run test:e2e`) | | Packaged | The installed app (asar, fuses, signature) fixes the demo store's checkout through the UI, driven over `--remote-debugging-port` since the fuses disable Node's inspector. The release workflow runs it on six runners, one per architecture: macOS (from the disk image), Windows (after a silent install; the x64 runner also checks that the ARM installer refuses it) and Linux (from the installed `.deb`, with Ubuntu's user-namespace restriction left on, also checking that the desktop entry and icons are the package's and the app added none of its own) | `npm run test:packaged -- ` | | Update | An installed app updates itself to a build one patch higher, served by a local stand-in for GitHub: the notification, What's New, the download, **Restart to update**, the restarted app running the new version (and What's New after it); an AppImage's desktop entry starts the old file before and the renamed one after. The release workflow runs it for the Windows installers (then uninstalls, checking the updater's cache goes too) and the AppImages on their four runners. The `.deb` path (as root, through `sudo`, and with the password refused) and the AppImage installing on quit were checked by hand | `npm run test:update -- ` | diff --git a/src/main/inspector/adapter/adapterSource.ts b/src/main/inspector/adapter/adapterSource.ts index 6750c12e..1a565037 100644 --- a/src/main/inspector/adapter/adapterSource.ts +++ b/src/main/inspector/adapter/adapterSource.ts @@ -40,8 +40,14 @@ export const ADAPTER_SOURCE = `function (mode, arg, edit, registry) { ${ANGULAR_JS} ${ELEMENT_JS} ${TREE_JS} + // Each function once (a level of 500 rows of one component names it 500 times): main places each with a call. const fns = []; - const fn = (value) => (typeof value === 'function' ? fns.push(value) - 1 : -1); + const fnIndex = new Map(); + const fn = (value) => { + if (typeof value !== 'function') return -1; + if (!fnIndex.has(value)) fnIndex.set(value, fns.push(value) - 1); + return fnIndex.get(value); + }; const attempt = (find, el) => { try { return find(el); diff --git a/src/main/inspector/adapter/reactTreeSource.ts b/src/main/inspector/adapter/reactTreeSource.ts new file mode 100644 index 00000000..8689e17c --- /dev/null +++ b/src/main/inspector/adapter/reactTreeSource.ts @@ -0,0 +1,51 @@ +import { MAX_ROOT_SCAN } from '../constants'; + +/** + * Page-side, in the Components tree (`TREE_JS`): React's part. Its top is the roots' components (the hook's + * roots, else the containers React marks, the first `MAX_ROOT_SCAN` elements looked through); a node's + * children are the nearest component fibers under it, and it leads to its first element. + */ +export const REACT_TREE_JS = ` + const reactRoots = () => { + const roots = new Set(); + const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook && hook.renderers && typeof hook.getFiberRoots === 'function') { + for (const id of hook.renderers.keys()) for (const root of hook.getFiberRoots(id)) roots.add(root); + } + const elements = roots.size ? [] : document.querySelectorAll('*'); + for (let i = 0; i < elements.length && i < ${MAX_ROOT_SCAN}; i++) { + const container = elements[i]; + const key = Object.keys(container).find((k) => k.startsWith('__reactContainer$')); + const legacy = container._reactRootContainer && container._reactRootContainer._internalRoot; + if (key && container[key] && container[key].stateNode) roots.add(container[key].stateNode); + else if (legacy) roots.add(legacy); + } + return [...roots].filter((root) => root.current); + }; + const reactKids = (fiber) => { + const out = []; + const walk = (parent) => { + for (let child = parent.child; child; child = child.sibling) { + if (isComponent(child)) out.push(child); + else walk(child); + } + }; + walk(fiber); + return out; + }; + const reactElement = (fiber) => { + if (fiber.stateNode instanceof Element) return fiber.stateNode; + for (let child = fiber.child; child; child = child.sibling) { + const found = reactElement(child); + if (found) return found; + } + return null; + }; + const REACT_TREE = { + top: () => reactRoots().flatMap((root) => reactKids(root.current)), + kids: reactKids, + element: reactElement, + node: (f, fn) => ({ name: componentName(f.type), key: f.key == null ? null : String(f.key), fn: fn(renderFunction(f.type)) }), + same: (a, b) => a === b || a === b.alternate, + }; +`; diff --git a/src/main/inspector/adapter/treeSource.ts b/src/main/inspector/adapter/treeSource.ts index 73569c7d..1194da4b 100644 --- a/src/main/inspector/adapter/treeSource.ts +++ b/src/main/inspector/adapter/treeSource.ts @@ -1,4 +1,5 @@ -import { MAX_ROOT_SCAN, MAX_TREE_NODES } from '../constants'; +import { MAX_TREE_NODES } from '../constants'; +import { REACT_TREE_JS } from './reactTreeSource'; /** * Page-side Components tree for the adapter (`ADAPTER_SOURCE`), from the top: @@ -11,41 +12,7 @@ import { MAX_ROOT_SCAN, MAX_TREE_NODES } from '../constants'; export const TREE_JS = ` // What an element belongs to, trying each framework in turn. const findAt = (el) => [reactFind, vueFind, vue2Find, angularFind, elementFind].reduce((hit, find) => hit || attempt(find, el), null); - const reactRoots = () => { - const roots = new Set(); - const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; - if (hook && hook.renderers && typeof hook.getFiberRoots === 'function') { - for (const id of hook.renderers.keys()) for (const root of hook.getFiberRoots(id)) roots.add(root); - } - const elements = roots.size ? [] : document.querySelectorAll('*'); - for (let i = 0; i < elements.length && i < ${MAX_ROOT_SCAN}; i++) { - const container = elements[i]; - const key = Object.keys(container).find((k) => k.startsWith('__reactContainer$')); - const legacy = container._reactRootContainer && container._reactRootContainer._internalRoot; - if (key && container[key] && container[key].stateNode) roots.add(container[key].stateNode); - else if (legacy) roots.add(legacy); - } - return [...roots].filter((root) => root.current); - }; - const reactKids = (fiber) => { - const out = []; - const walk = (parent) => { - for (let child = parent.child; child; child = child.sibling) { - if (isComponent(child)) out.push(child); - else walk(child); - } - }; - walk(fiber); - return out; - }; - const reactElement = (fiber) => { - if (fiber.stateNode instanceof Element) return fiber.stateNode; - for (let child = fiber.child; child; child = child.sibling) { - const found = reactElement(child); - if (found) return found; - } - return null; - }; + ${REACT_TREE_JS} const vueKids = (instance) => { const out = []; const visit = (vnode) => { @@ -68,13 +35,7 @@ export const TREE_JS = ` return null; }; const TREE = { - react: { - top: () => reactRoots().flatMap((root) => reactKids(root.current)), - kids: reactKids, - element: reactElement, - node: (f, fn) => ({ name: componentName(f.type), key: f.key == null ? null : String(f.key), fn: fn(renderFunction(f.type)) }), - same: (a, b) => a === b || a === b.alternate, - }, + react: REACT_TREE, vue: { top: () => Array.from(document.querySelectorAll('[data-v-app]')) @@ -98,16 +59,27 @@ export const TREE_JS = ` } }; const treeTop = () => Object.keys(TREE).flatMap((framework) => topOf(framework).map((ref) => ({ framework, ref }))); + // A top node by its index, reading each framework's top only as far as it: one found in React's reads no other's. + const topEntry = (index) => { + let offset = 0; + for (const framework of Object.keys(TREE)) { + const top = topOf(framework); + if (index < offset + top.length) return { framework, ref: top[index - offset] }; + offset += top.length; + } + return null; + }; const treeKids = (entry) => TREE[entry.framework].kids(entry.ref).map((ref) => ({ framework: entry.framework, ref })); const treeAt = (path) => { - let level = treeTop(); - let entry = null; - for (const index of path) { + if (!path.length) return { entry: null, level: treeTop() }; + let entry = topEntry(path[0]); + let level = entry ? treeKids(entry) : []; + for (const index of path.slice(1)) { entry = level[index]; if (!entry) return null; level = treeKids(entry); } - return { entry, level }; + return entry ? { entry, level } : null; }; const treeLevel = (path, fn) => { const at = treeAt(path); @@ -130,7 +102,16 @@ export const TREE_JS = ` if (index < 0) return null; path.unshift(index); } - const top = treeTop().findIndex((entry) => entry.framework === found.framework && same(entry.ref, found.refs[found.refs.length - 1])); - return top < 0 ? null : [top, ...path]; + // Its top's index: the frameworks before its own count, the ones after aren't read. + let offset = 0; + for (const framework of Object.keys(TREE)) { + const top = topOf(framework); + if (framework === found.framework) { + const index = top.findIndex((ref) => same(ref, found.refs[found.refs.length - 1])); + return index < 0 ? null : [offset + index, ...path]; + } + offset += top.length; + } + return null; }; `; diff --git a/src/main/inspector/adapter/vueSource.ts b/src/main/inspector/adapter/vueSource.ts index 922caaae..1deddbd8 100644 --- a/src/main/inspector/adapter/vueSource.ts +++ b/src/main/inspector/adapter/vueSource.ts @@ -2,7 +2,9 @@ * Page-side Vue 3 part of the adapter (`ADAPTER_SOURCE`). Development builds put * the component on each element (`__vueParentComponent`); production builds * don't, so the app's vnode tree is walked from the element it is mounted on - * (`_vnode`), as probed on Vue 3.5 (docs/INSPECTOR_RESEARCH.md §2). + * (`_vnode`), as probed on Vue 3.5 (docs/INSPECTOR_RESEARCH.md §2): only down + * the elements that hold the one looked for (an element's vnode holds its + * subtree), so a large app costs its depth, not its size. */ export const VUE_JS = ` const MAX_VNODES = 20000; @@ -21,21 +23,22 @@ export const VUE_JS = ` let container = el; while (container && !container._vnode) container = container.parentElement; if (!container) return null; - const byElement = new Map(); + // The deepest element holding it that a component rendered: the element itself, else its nearest such ancestor. + let hit = null; let visited = 0; const visit = (vnode, owner) => { if (!vnode || typeof vnode !== 'object' || visited++ > MAX_VNODES) return; if (vnode.component) return visit(vnode.component.subTree, vnode.component); - if (vnode.el && vnode.el.nodeType === 1 && !byElement.has(vnode.el)) byElement.set(vnode.el, { instance: owner, vnode }); + // An element's vnode (a string type) holds its subtree; a fragment's or a teleport's doesn't. + if (typeof vnode.type === 'string' && vnode.el && vnode.el.nodeType === 1) { + if (!vnode.el.contains(el)) return; + if (owner) hit = { instance: owner, vnode }; + } if (Array.isArray(vnode.children)) vnode.children.forEach((child) => visit(child, owner)); if (vnode.suspense) visit(vnode.suspense.activeBranch, owner); }; visit(container._vnode, null); - for (let node = el; node; node = node.parentElement) { - const hit = byElement.get(node); - if (hit && hit.instance) return { instance: hit.instance, vnode: hit.vnode, build: 'production' }; - } - return null; + return hit && { instance: hit.instance, vnode: hit.vnode, build: 'production' }; }; const vueFind = (el) => { const found = vueOwner(el); diff --git a/src/main/inspector/constants.ts b/src/main/inspector/constants.ts index 8f99664b..1e438248 100644 --- a/src/main/inspector/constants.ts +++ b/src/main/inspector/constants.ts @@ -33,6 +33,10 @@ export const INSPECT_MODE = { pick: 'searchForNode', off: 'none' } as const; export const ADAPTER_MODE = { summary: 'summary', describe: 'describe', set: 'set', tree: 'tree', locate: 'locate' } as const; /** The internal property V8 gives a function's place under. */ export const FUNCTION_LOCATION = '[[FunctionLocation]]'; +/** The most functions one read places (each is a call); the rest go unplaced. */ +export const MAX_PLACED_FUNCTIONS = 1000; +/** The longest script URL kept for placing functions (a longer one, a data: URL, leaves its functions unplaced). */ +export const MAX_SCRIPT_URL = 2048; /** What a read says when its element is gone. */ export const PICK_GONE = 'That element is gone: the page moved on since it was picked.'; /** The View menu's Pick an Element item. */ diff --git a/src/main/inspector/reading/ScriptUrls.ts b/src/main/inspector/reading/ScriptUrls.ts index 1c4cd52e..67400a1f 100644 --- a/src/main/inspector/reading/ScriptUrls.ts +++ b/src/main/inspector/reading/ScriptUrls.ts @@ -1,5 +1,6 @@ import type { CdpTransport } from '../../engine/cdp'; import { CDP } from '../../engine/constants'; +import { MAX_SCRIPT_URL } from '../constants'; /** What `Debugger.scriptParsed` says of a script that we keep. */ interface ParsedScript { @@ -9,10 +10,10 @@ interface ParsedScript { executionContextAuxData?: { frameId?: string; isDefault?: boolean }; } -/** A script of the session: its URL, the source map it names ('' for none), and the frame whose main world runs it (else null). */ +/** A script of the session: its URL ('' for none, or one past `MAX_SCRIPT_URL`), whether it names a source map, and the frame whose main world runs it (else null). */ export interface ScriptRecord { url: string; - sourceMap: string; + mapped: boolean; frameId: string | null; } @@ -23,9 +24,12 @@ export interface ScriptRecord { * replays it for every script already parsed: it is turned on just for that, * with pauses skipped (a page's `debugger` statement can't stop it), then off * again, whenever a script id isn't known yet or a frame's scripts are listed. + * Each replay replaces what was kept, so the scripts of documents gone go with + * them; a map named is kept as whether there is one (an inline map's URL holds + * the whole map). */ export class ScriptUrls { - private readonly scripts = new Map(); + private scripts = new Map(); private refreshing: Promise | null = null; constructor(private readonly cdp: CdpTransport) {} @@ -49,13 +53,15 @@ export class ScriptUrls { } private async replay(): Promise { + const scripts = new Map(); const off = this.cdp.on(CDP.Debugger.scriptParsed, (p: ParsedScript) => { const context = p.executionContextAuxData; - this.scripts.set(p.scriptId, { url: p.url, sourceMap: p.sourceMapURL ?? '', frameId: context?.isDefault && context.frameId ? context.frameId : null }); + scripts.set(p.scriptId, { url: p.url.length <= MAX_SCRIPT_URL ? p.url : '', mapped: !!p.sourceMapURL, frameId: context?.isDefault && context.frameId ? context.frameId : null }); }); try { await this.cdp.send(CDP.Debugger.enable); await this.cdp.send(CDP.Debugger.setSkipAllPauses, { skip: true }); + this.scripts = scripts; } finally { off(); await this.cdp.send(CDP.Debugger.disable).catch(() => undefined); diff --git a/src/main/inspector/reading/functionLocations.ts b/src/main/inspector/reading/functionLocations.ts index 61e351e8..d9973c85 100644 --- a/src/main/inspector/reading/functionLocations.ts +++ b/src/main/inspector/reading/functionLocations.ts @@ -2,7 +2,7 @@ import type { CodeLocation } from '../../../shared/types'; import type { GetPropertiesReply } from '../../console/types'; import type { CdpTransport } from '../../engine/cdp'; import { CDP } from '../../engine/constants'; -import { FUNCTION_LOCATION } from '../constants'; +import { FUNCTION_LOCATION, MAX_PLACED_FUNCTIONS } from '../constants'; import type { ScriptUrls } from './ScriptUrls'; /** V8's place of a function: its script, and 0-based line and column. */ @@ -14,18 +14,19 @@ interface FunctionPlace { /** * Where each function of an array in the page is defined, by index: null for one - * V8 doesn't place (native, bound), or whose script has no URL (evaluated code). + * V8 doesn't place (native, bound), whose script has no URL (evaluated code), that + * is past `MAX_PLACED_FUNCTIONS`, or that went away meanwhile (the others are kept). */ export async function functionLocations(transport: CdpTransport, arrayId: string, scripts: ScriptUrls): Promise> { const { result } = await transport.send(CDP.Runtime.getProperties, { objectId: arrayId, ownProperties: true }); const items = result.filter((p) => /^\d+$/.test(p.name)); const locations: Array = new Array(items.length).fill(null); await Promise.all( - items.map(async (item) => { + items.slice(0, MAX_PLACED_FUNCTIONS).map(async (item) => { if (!item.value?.objectId) return; - const reply = await transport.send(CDP.Runtime.getProperties, { objectId: item.value.objectId, ownProperties: true }); - const place = reply.internalProperties?.find((p) => p.name === FUNCTION_LOCATION)?.value?.value as FunctionPlace | undefined; - const url = place && (await scripts.url(place.scriptId)); + const reply = await transport.send(CDP.Runtime.getProperties, { objectId: item.value.objectId, ownProperties: true }).catch(() => null); + const place = reply?.internalProperties?.find((p) => p.name === FUNCTION_LOCATION)?.value?.value as FunctionPlace | undefined; + const url = place && (await scripts.url(place.scriptId).catch(() => null)); if (place && url) locations[Number(item.name)] = { url, line: place.lineNumber, column: place.columnNumber }; }), ); diff --git a/src/main/inspector/scriptCoverage.ts b/src/main/inspector/scriptCoverage.ts index 19b133df..45a401d8 100644 --- a/src/main/inspector/scriptCoverage.ts +++ b/src/main/inspector/scriptCoverage.ts @@ -7,7 +7,7 @@ export function scriptCoverage(scripts: readonly ScriptRecord[], documentUrl: st const byUrl = new Map(); for (const script of scripts) { if (!LOADED_SCRIPT.test(script.url) || script.url === documentUrl) continue; - byUrl.set(script.url, (byUrl.get(script.url) ?? false) || !!script.sourceMap); + byUrl.set(script.url, (byUrl.get(script.url) ?? false) || script.mapped); } const unmapped = [...byUrl].filter(([, mapped]) => !mapped).map(([url]) => url); return { scripts: byUrl.size, mapped: byUrl.size - unmapped.length, unmapped: unmapped.slice(0, MAX_UNMAPPED) }; diff --git a/src/main/inspector/stores/constants.ts b/src/main/inspector/stores/constants.ts index 5e996801..0828f024 100644 --- a/src/main/inspector/stores/constants.ts +++ b/src/main/inspector/stores/constants.ts @@ -35,6 +35,11 @@ export const PREVIEW_LENGTH = 80; export const TEXT_DEPTH = 3; /** A React commit this soon after a store action names that action as what led to it. */ export const ACTION_TRIGGER_MS = 250; +/** + * How long a Pinia action whose promise hasn't settled counts as running: while one runs, the store's other + * changes are taken as its own (its record shows them); one that never settles stops counting after this. + */ +export const ACTION_SETTLE_MS = 10_000; /** How long after a document loads its Vue apps are looked for again (one that mounts late). */ export const VUE_ATTACH_DELAY_MS = 1000; /** Elements looked through for a Vue 2 root instance. */ diff --git a/src/main/inspector/stores/vueStoresSource.ts b/src/main/inspector/stores/vueStoresSource.ts index fb135b09..55272a91 100644 --- a/src/main/inspector/stores/vueStoresSource.ts +++ b/src/main/inspector/stores/vueStoresSource.ts @@ -1,4 +1,4 @@ -import { MAX_VUE2_SCAN, STATE_DEPTH } from './constants'; +import { ACTION_SETTLE_MS, MAX_VUE2_SCAN, STATE_DEPTH } from './constants'; /** * Page-side, in the store stand-in (`STORE_HOOK_JS`): Pinia's and Vuex's stores, @@ -6,10 +6,11 @@ import { MAX_VUE2_SCAN, STATE_DEPTH } from './constants'; * properties hold `$pinia` and `$store` (production builds too), a Vue 2 root * instance its own. A Pinia store's actions are heard through `$onAction` (the * state written out before, and again once the action returns or its promise - * settles); changes outside an action through a synchronous `$subscribe`, which - * is a deep watcher (Vue walks the state on every change): it is on only while - * recording (`detach` takes it off), and only `STATE_DEPTH` levels deep, what the - * diff shows. A store created later is caught by a Pinia plugin. Vuex's + * settles; one that never does stops counting as running after + * `ACTION_SETTLE_MS`, so the store's other changes are heard again); changes + * outside an action through a synchronous `$subscribe`, which is a deep watcher + * (Vue walks the state on every change): it is on only while recording (`detach` + * takes it off), and only `STATE_DEPTH` levels deep, what the diff shows. A store created later is caught by a Pinia plugin. Vuex's * mutations are heard through `subscribe`, after they ran. The other listeners * do nothing while nothing records; the states kept are written out again when * recording starts. @@ -23,7 +24,9 @@ export const VUE_STORES_JS = String.raw` attached.add(store); const name = String(store.$id); let snapshot = snap(store.$state); - let running = 0; + // The actions running, by when each started: the store's changes meanwhile are theirs. + const running = new Map(); + let runs = 0; let unwatch = null; const stopWatching = () => { if (unwatch) unwatch(); @@ -31,7 +34,9 @@ export const VUE_STORES_JS = String.raw` }; const onDirect = (mutation) => { if (!recording()) return stopWatching(); - if (running) return; + const stale = performance.now() - ${ACTION_SETTLE_MS}; + running.forEach((started, run) => started < stale && running.delete(run)); + if (running.size) return; const next = snap(store.$state); const changes = diffSnaps(snapshot, next); snapshot = next; @@ -53,9 +58,10 @@ export const VUE_STORES_JS = String.raw` const before = snap(store.$state); const at = now(); const started = performance.now(); - running += 1; + const run = ++runs; + running.set(run, started); const done = () => { - running -= 1; + running.delete(run); snapshot = snap(store.$state); const payload = args.length ? preview(args.length === 1 ? args[0] : args) : null; record({ at, store: name, library: 'pinia', type: String(type), payload, changes: diffSnaps(before, snapshot), duration: performance.now() - started, stack }); diff --git a/src/main/network/constants.ts b/src/main/network/constants.ts index 923887f8..92f0cf82 100644 --- a/src/main/network/constants.ts +++ b/src/main/network/constants.ts @@ -42,6 +42,9 @@ export const TEXT_OPCODE = 1; /** The most calls of a script's stack a request keeps as what sent it (its initiator). */ export const MAX_INITIATOR_FRAMES = 20; +/** The longest URL a call of an initiator is kept with (longer ones are left out), and the most of its function's name kept. */ +export const MAX_INITIATOR_URL = 2048; +export const MAX_INITIATOR_NAME = 200; /** Calls in files the page loaded: the only ones a request's initiator keeps. */ export const LOADED_FILE = /^https?:/; diff --git a/src/main/network/initiatorFrames.ts b/src/main/network/initiatorFrames.ts index a7f53880..fa586262 100644 --- a/src/main/network/initiatorFrames.ts +++ b/src/main/network/initiatorFrames.ts @@ -1,18 +1,19 @@ import type { StackFrame } from '../../shared/types'; -import { LOADED_FILE, MAX_INITIATOR_FRAMES } from './constants'; +import { LOADED_FILE, MAX_INITIATOR_FRAMES, MAX_INITIATOR_NAME, MAX_INITIATOR_URL } from './constants'; import type { RequestInitiator } from './types'; /** * The stack of the script that sent a request, innermost first, as `Network.requestWillBeSent` tells it: * the calls in files the page loaded, through the async parents when Chromium recorded them. Empty when no - * script sent it (the parser, a preload, the user). + * script sent it (the parser, a preload, the user). Each request of the log keeps it, so URLs and names are + * bounded (`MAX_INITIATOR_URL`, `MAX_INITIATOR_NAME`). */ export function initiatorFrames(initiator: RequestInitiator | undefined): StackFrame[] { const frames: StackFrame[] = []; for (let stack = initiator?.stack; stack && frames.length < MAX_INITIATOR_FRAMES; stack = stack.parent) { for (const call of stack.callFrames) { if (frames.length >= MAX_INITIATOR_FRAMES) break; - if (LOADED_FILE.test(call.url)) frames.push({ name: call.functionName, url: call.url, line: call.lineNumber, column: call.columnNumber }); + if (LOADED_FILE.test(call.url) && call.url.length <= MAX_INITIATOR_URL) frames.push({ name: call.functionName.slice(0, MAX_INITIATOR_NAME), url: call.url, line: call.lineNumber, column: call.columnNumber }); } } return frames; diff --git a/src/renderer/src/entities/inspector/model/store/types.ts b/src/renderer/src/entities/inspector/model/store/types.ts index d3e509c1..93834d6f 100644 --- a/src/renderer/src/entities/inspector/model/store/types.ts +++ b/src/renderer/src/entities/inspector/model/store/types.ts @@ -46,4 +46,6 @@ export interface InspectorStore { setLastEdit(edit: LastStateEdit | null): void; /** Forgets the originals and hook names of every place in a bundle (its map changed). Returns the places forgotten. */ forgetBundle(bundleUrl: string): CodeLocation[]; + /** Forgets every original and hook name (the maps were forgotten: another workspace). */ + forgetOrigins(): void; } diff --git a/src/renderer/src/entities/inspector/model/store/useInspectorStore.ts b/src/renderer/src/entities/inspector/model/store/useInspectorStore.ts index 1bdb9184..9dd6d488 100644 --- a/src/renderer/src/entities/inspector/model/store/useInspectorStore.ts +++ b/src/renderer/src/entities/inspector/model/store/useInspectorStore.ts @@ -29,4 +29,5 @@ export const useInspectorStore = create()((set, get) => ({ set({ origins: keep(origins), hookNames: keep(hookNames) }); return [...gone].flatMap((key) => keyLocation(key) ?? []); }, + forgetOrigins: () => set({ origins: {}, hookNames: {} }), })); diff --git a/src/renderer/src/features/open-resource/model/sources/forgetSourceMaps.ts b/src/renderer/src/features/open-resource/model/sources/forgetSourceMaps.ts index 8b87d84a..8924746e 100644 --- a/src/renderer/src/features/open-resource/model/sources/forgetSourceMaps.ts +++ b/src/renderer/src/features/open-resource/model/sources/forgetSourceMaps.ts @@ -1,12 +1,22 @@ import { stopSourceMapWorker } from '@/shared/lib'; +import { useInspectorStore } from '@/entities/inspector'; import { useSourceMapStore } from '@/entities/source-map'; +import { originLookups } from './originLookups'; import { sourceMapLoads } from './sourceMapLoads'; import { useSourceTree } from './tree'; -/** Drops every loaded map (a workspace switch): the store, the tree's state, loads in flight and the worker. Synchronous. */ +/** + * Drops every loaded map (a workspace switch): the store, the tree's state, loads in flight and the worker, + * and what the maps said (the originals and hook names found, those being looked up). Synchronous. + */ export function forgetSourceMaps(): void { useSourceMapStore.getState().clear(); sourceMapLoads.loads.clear(); + sourceMapLoads.reloads.clear(); + originLookups.generation += 1; + originLookups.inFlight.clear(); + originLookups.found.clear(); + useInspectorStore.getState().forgetOrigins(); useSourceTree.getState().reset(); stopSourceMapWorker(); } diff --git a/src/renderer/src/features/open-resource/model/sources/locateLocations.ts b/src/renderer/src/features/open-resource/model/sources/locateLocations.ts index b14392bf..e53d121a 100644 --- a/src/renderer/src/features/open-resource/model/sources/locateLocations.ts +++ b/src/renderer/src/features/open-resource/model/sources/locateLocations.ts @@ -6,7 +6,8 @@ import { originLookups } from './originLookups'; /** * Looks up the original of each code location not known yet nor being looked up, and writes them together - * (`flushOrigins`). One that couldn't be told now isn't written, so it is looked up again next time. + * (`flushOrigins`). One that couldn't be told now isn't written, so it is looked up again next time; one + * that finishes after the maps were forgotten is dropped. */ export async function locateLocations(locations: readonly CodeLocation[]): Promise { const known = useInspectorStore.getState().origins; @@ -16,9 +17,12 @@ export async function locateLocations(locations: readonly CodeLocation[]): Promi if (!(key in known) && !originLookups.inFlight.has(key)) unknown.set(key, location); } for (const key of unknown.keys()) originLookups.inFlight.add(key); + const generation = originLookups.generation; await Promise.all( [...unknown].map(async ([key, location]) => { const place = await findOriginal(location).catch(() => undefined); + // The maps were forgotten meanwhile (another workspace): what this map said is gone with them. + if (generation !== originLookups.generation) return; if (place === undefined) originLookups.inFlight.delete(key); else originLookups.found.set(key, place); }), diff --git a/src/renderer/src/features/open-resource/model/sources/nameHooksAt.ts b/src/renderer/src/features/open-resource/model/sources/nameHooksAt.ts index 57db1449..b9c3bfb4 100644 --- a/src/renderer/src/features/open-resource/model/sources/nameHooksAt.ts +++ b/src/renderer/src/features/open-resource/model/sources/nameHooksAt.ts @@ -3,12 +3,15 @@ import { locationKey, useInspectorStore } from '@/entities/inspector'; import { askLoadedMap } from './askLoadedMap'; import { SCRIPT_KIND } from './constants'; import { isMiss } from './isMiss'; +import { originLookups } from './originLookups'; /** Reads the hook names of the React component defined at a place off its original, once that original is known (`locateLocations`). */ export async function nameHooksAt(location: CodeLocation): Promise { const { origins, hookNames, setHookNames } = useInspectorStore.getState(); const place = origins[locationKey(location)]; if (!place || locationKey(location) in hookNames) return; + const generation = originLookups.generation; const reply = await askLoadedMap({ type: 'hookNames', bundleUrl: place.bundleUrl, url: place.url, line: place.line, column: place.column }, { kind: SCRIPT_KIND }).catch(() => null); - if (reply && !isMiss(reply)) setHookNames(locationKey(location), reply.names); + // Not once the maps were forgotten meanwhile (another workspace). + if (reply && !isMiss(reply) && generation === originLookups.generation) setHookNames(locationKey(location), reply.names); } diff --git a/src/renderer/src/features/open-resource/model/sources/originLookups.ts b/src/renderer/src/features/open-resource/model/sources/originLookups.ts index b429283e..1986242a 100644 --- a/src/renderer/src/features/open-resource/model/sources/originLookups.ts +++ b/src/renderer/src/features/open-resource/model/sources/originLookups.ts @@ -2,10 +2,12 @@ import type { OriginalPlace } from '@/entities/inspector'; /** * Originals being looked up (by `locationKey`), and those found, waiting to be written together - * (`flushOrigins`), with the promise of that write. Mutated in place. + * (`flushOrigins`), with the promise of that write. `generation` goes up as the maps are forgotten + * (`forgetSourceMaps`): a lookup started before drops what it finds. Mutated in place. */ -export const originLookups: { inFlight: Set; found: Map; written: Promise | null } = { +export const originLookups: { inFlight: Set; found: Map; written: Promise | null; generation: number } = { inFlight: new Set(), found: new Map(), written: null, + generation: 0, }; diff --git a/test/fixtures/apps/piniaCart.ts b/test/fixtures/apps/piniaCart.ts index 5a993b59..1992efb6 100644 --- a/test/fixtures/apps/piniaCart.ts +++ b/test/fixtures/apps/piniaCart.ts @@ -1,8 +1,8 @@ /** * A cart in Vue with Pinia, and its settings in Vuex, for the store timeline's * tests, bundled by the test from the repo's own packages: an item calls the - * cart store's action, a reset button changes its state directly, and a currency - * button commits a Vuex mutation. + * cart store's action, a reset button changes its state directly, a hang button + * starts an action that never settles, and a currency button commits a Vuex mutation. */ import { createPinia, defineStore } from 'pinia'; import { createApp, h } from 'vue'; @@ -15,6 +15,10 @@ const useCart = defineStore('cart', { this.count += 1; this.skus.push(sku); }, + // An action waiting on something that never answers. + hang() { + return new Promise(() => undefined); + }, }, }); @@ -37,6 +41,9 @@ const CartItem = { function handleReset() { cart.count = 0; } + function handleHang() { + void cart.hang(); + } function handleCurrency() { settings.commit('setCurrency', 'USD'); } @@ -45,6 +52,7 @@ const CartItem = { `${props.sku} ${cart.count} `, h('button', { id: `add-${props.sku}`, onClick: handleAdd }, 'Add'), h('button', { id: 'reset', onClick: handleReset }, 'Reset'), + h('button', { id: 'hang', onClick: handleHang }, 'Hang'), h('button', { id: 'usd', onClick: handleCurrency }, 'USD'), ]); }, diff --git a/test/integration/inspect.chromium.test.ts b/test/integration/inspect.chromium.test.ts index 716d00b9..256f7cbc 100644 --- a/test/integration/inspect.chromium.test.ts +++ b/test/integration/inspect.chromium.test.ts @@ -243,6 +243,13 @@ describe.skipIf(!chromiumAvailable)('component inspector in Chromium', () => { expect(component.path).toEqual([0, 0, 1]); expect(shape(await treeAt([]))).toEqual([['App', null, 1]]); expect(shape(await treeAt([0, 0]))).toEqual([['CartItem', 'A1', 0], ['CartItem', 'B2', 0]]); + // Both items are one function, placed once (the array read, then the function), not once an item. + const sent: string[] = []; + const send = transport.send.bind(transport); + transport.send = ((method: string, params?: Record) => (sent.push(method), send(method, params))) as typeof transport.send; + await treeAt([0, 0]); + transport.send = send; + expect(sent.filter((method) => method === 'Runtime.getProperties')).toHaveLength(2); const item = await services.inspector.openTreeNode(component.frameId!, [0, 0, 0]); expect(item).toMatchObject({ framework: 'vue', element: { tag: 'li' }, chain: [{ name: 'CartItem', key: 'A1' }, { name: 'CartList' }, { name: 'App' }] }); }); diff --git a/test/integration/stores.chromium.test.ts b/test/integration/stores.chromium.test.ts index 3513e329..d0e6b270 100644 --- a/test/integration/stores.chromium.test.ts +++ b/test/integration/stores.chromium.test.ts @@ -16,6 +16,7 @@ import type { Page } from 'playwright-core'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { PageInterception } from '../../src/main/engine/PageInterception'; import { NetworkLog } from '../../src/main/network'; +import { ACTION_SETTLE_MS } from '../../src/main/inspector/stores/constants'; import { FrameServices } from '../../src/main/PageController/FrameServices'; import { DEFAULT_SETTINGS, type AppEvent, type RenderCommit, type StackFrame, type StoreAction } from '../../src/shared/types'; import { bundleApp } from '../helpers/bundleApp'; @@ -179,6 +180,20 @@ describe.skipIf(!chromiumAvailable)('store timelines in Chromium', () => { expect(currency).toMatchObject({ store: 'Vuex', library: 'vuex', type: 'setCurrency', payload: '"USD"', changes: [{ path: 'currency', from: '"EUR"', to: '"USD"' }] }); }); + it("hears Pinia's direct changes again once an action that never settles stops counting as running", async () => { + await open('pinia'); + await page.locator('#hang').click(); + await page.locator('#add-A1').click(); + await nextAction(1); + // Past ACTION_SETTLE_MS, as the stand-in tells time. + await page.evaluate((skew) => { + const now = performance.now.bind(performance); + performance.now = () => now() + skew; + }, ACTION_SETTLE_MS + 1000); + await page.locator('#reset').click(); + expect(await nextAction(2)).toMatchObject({ store: 'cart', type: 'direct', changes: [{ path: 'count', from: '1', to: '0' }] }); + }); + it("finds a Vue app's stores itself when the document loads while recording", async () => { await open('pinia', true); await page.locator('#add-A1').click(); diff --git a/test/perf/inspector.perf.test.ts b/test/perf/inspector.perf.test.ts index eda59329..ee60859e 100644 --- a/test/perf/inspector.perf.test.ts +++ b/test/perf/inspector.perf.test.ts @@ -179,17 +179,20 @@ describe.skipIf(!chromiumAvailable)('inspector performance on large apps', () => const frameId = services.inspector.list()[0]!.frameId; const levels: number[] = []; let path: number[] = []; - // Down the first child until a level lists the rows (the most a level lists). + let widest = 0; + // Down the node with the most children (names are minified) until a level lists the rows. for (let depth = 0; depth < 8; depth++) { const started = Date.now(); const level = await services.inspector.componentTree(frameId, path); levels.push(Date.now() - started); - if (!level || level.nodes.length + level.more >= 2000) break; - const next = level.nodes.findIndex((node) => node.children > 0 && node.name !== 'Nest'); + widest = Math.max(widest, level ? level.nodes.length + level.more : 0); + if (!level || widest >= 2000) break; + const next = level.nodes.reduce((best, node, index) => (node.children > (level.nodes[best]?.children ?? 0) ? index : best), -1); if (next < 0) break; path = [...path, next]; } - record(`${framework}: a level of the Components tree (slowest)`, [Math.max(...levels)], 2000); + expect(widest, 'the level of the rows reached').toBeGreaterThanOrEqual(2000); + record(`${framework}: a level of the Components tree (slowest)`, [Math.max(...levels)], 500); }); } diff --git a/test/renderer/mapFiles.test.ts b/test/renderer/mapFiles.test.ts index f5fcc0fc..8dfda975 100644 --- a/test/renderer/mapFiles.test.ts +++ b/test/renderer/mapFiles.test.ts @@ -7,7 +7,7 @@ vi.mock('@/shared/api', () => ({ api, onAppEvent: () => () => {}, errorMessage: vi.mock('@/shared/ui/toast', () => ({ toast: Object.assign(toast, { dismiss: vi.fn(), update: vi.fn() }) })); vi.mock('@/shared/monaco', () => ({ monaco: {}, languageFor: () => 'javascript', requestReveal: vi.fn() })); -const { forgetMapFile, loadMapFile } = await import('@/features/open-resource'); +const { forgetMapFile, forgetSourceMaps, loadMapFile, locateLocations } = await import('@/features/open-resource'); const { sourceMapMenu } = await import('@/widgets/explorer/ui/ResourceTree/sourceMapMenu'); const BUNDLE = 'https://site.test/assets/app.js'; @@ -36,6 +36,21 @@ describe('source maps loaded from files (renderer)', () => { expect(useInspectorStore.getState().hookNames).toEqual({}); }); + it('forgets every original and hook name with the maps (another workspace), and drops a lookup that finishes after', async () => { + let answer!: (state: unknown) => void; + api.getSourceMap.mockReturnValueOnce(new Promise((resolve) => (answer = resolve))); + const late = at('https://site.test/late.js', 9); + const lookup = locateLocations([late]); + forgetSourceMaps(); + expect(useInspectorStore.getState()).toMatchObject({ origins: {}, hookNames: {} }); + answer({ status: 'none', bundleHash: 'h' }); + await lookup; + expect(useInspectorStore.getState().origins).toEqual({}); + // Looked up again in the new workspace, it is told. + await locateLocations([late]); + expect(useInspectorStore.getState().origins).toEqual({ [locationKey(late)]: null }); + }); + it('loads a map from a file, reading the bundle again and tracing its places again; nothing when none was picked', async () => { api.loadSourceMapFile.mockResolvedValueOnce(null); expect(await loadMapFile(BUNDLE)).toBe(false); diff --git a/test/unit/inspectorLookups.test.ts b/test/unit/inspectorLookups.test.ts new file mode 100644 index 00000000..ddcfd2fc --- /dev/null +++ b/test/unit/inspectorLookups.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest'; +import type { CdpTransport } from '../../src/main/engine/cdp'; +import { MAX_PLACED_FUNCTIONS, MAX_SCRIPT_URL } from '../../src/main/inspector/constants'; +import { functionLocations } from '../../src/main/inspector/reading/functionLocations'; +import { ScriptUrls } from '../../src/main/inspector/reading/ScriptUrls'; +import { MAX_INITIATOR_FRAMES, MAX_INITIATOR_NAME, MAX_INITIATOR_URL } from '../../src/main/network/constants'; +import { initiatorFrames } from '../../src/main/network/initiatorFrames'; + +type Handler = (params: never) => void; + +/** A transport answering `send` from a function, with events emitted to its listeners. */ +function fakeTransport(answer: (method: string, params: Record | undefined, emit: (event: string, params: unknown) => void) => unknown) { + const handlers = new Map>(); + const emit = (event: string, params: unknown) => handlers.get(event)?.forEach((h) => h(params as never)); + const calls: string[] = []; + const transport = { + send: async (method: string, params?: Record) => { + calls.push(method); + return answer(method, params, emit); + }, + on: (event: string, handler: Handler) => { + if (!handlers.has(event)) handlers.set(event, new Set()); + handlers.get(event)!.add(handler); + return () => handlers.get(event)?.delete(handler); + }, + } as unknown as CdpTransport; + return { transport, calls }; +} + +describe("the main process's lookups stay bounded", () => { + it("keeps the scripts alive as each replay lists them, whether each names a map, and no URL past the most", async () => { + const script = (scriptId: string, url: string, sourceMapURL = '') => ({ scriptId, url, sourceMapURL, executionContextAuxData: { frameId: 'top', isDefault: true } }); + // An inline map's URL is the whole map. + let alive = [script('1', 'https://a.test/app.js', `data:application/json;base64,${'x'.repeat(100_000)}`), script('2', `https://a.test/${'y'.repeat(MAX_SCRIPT_URL)}.js`)]; + const { transport } = fakeTransport((method, _params, emit) => { + if (method === 'Debugger.enable') alive.forEach((parsed) => emit('Debugger.scriptParsed', parsed)); + return {}; + }); + const scripts = new ScriptUrls(transport); + expect(await scripts.url('1')).toBe('https://a.test/app.js'); + expect(await scripts.url('2')).toBeNull(); + expect(await scripts.ofFrame('top')).toEqual([ + { url: 'https://a.test/app.js', mapped: true, frameId: 'top' }, + { url: '', mapped: false, frameId: 'top' }, + ]); + // The page moved on: its scripts went with it. + alive = [script('3', 'https://a.test/next.js')]; + expect(await scripts.ofFrame('top')).toEqual([{ url: 'https://a.test/next.js', mapped: false, frameId: 'top' }]); + }); + + it(`places at most ${MAX_PLACED_FUNCTIONS} functions in one read, and one that went away doesn't lose the others`, async () => { + const count = MAX_PLACED_FUNCTIONS + 5; + const { transport, calls } = fakeTransport((_method, params) => { + if (params?.objectId === 'array') return { result: Array.from({ length: count }, (_, i) => ({ name: String(i), value: { objectId: `f${i}` } })).concat({ name: 'length', value: { objectId: '' } }) }; + if (params?.objectId === 'f1') throw new Error('Could not find object with given id'); + return { result: [], internalProperties: [{ name: '[[FunctionLocation]]', value: { value: { scriptId: '1', lineNumber: Number(String(params?.objectId).slice(1)), columnNumber: 2 } } }] }; + }); + const scripts = { url: async () => 'https://a.test/app.js' } as unknown as ScriptUrls; + const locations = await functionLocations(transport, 'array', scripts); + expect(locations).toHaveLength(count); + expect(locations[0]).toEqual({ url: 'https://a.test/app.js', line: 0, column: 2 }); + expect(locations[1]).toBeNull(); + expect(locations[MAX_PLACED_FUNCTIONS - 1]).toEqual({ url: 'https://a.test/app.js', line: MAX_PLACED_FUNCTIONS - 1, column: 2 }); + expect(locations[MAX_PLACED_FUNCTIONS]).toBeNull(); + expect(calls.filter((m) => m === 'Runtime.getProperties')).toHaveLength(1 + MAX_PLACED_FUNCTIONS); + }); + + it("keeps a request's initiator calls with bounded URLs and names", () => { + const call = (functionName: string, url: string) => ({ functionName, scriptId: '1', url, lineNumber: 1, columnNumber: 2 }); + const long = `https://a.test/${'q'.repeat(MAX_INITIATOR_URL)}.js`; + const frames = initiatorFrames({ type: 'script', stack: { callFrames: [call('x'.repeat(MAX_INITIATOR_NAME + 50), 'https://a.test/app.js'), call('fromLong', long), ...Array.from({ length: 30 }, () => call('f', 'https://a.test/app.js'))] } }); + expect(frames[0]!.name).toHaveLength(MAX_INITIATOR_NAME); + expect(frames.some((frame) => frame.url === long)).toBe(false); + expect(frames).toHaveLength(MAX_INITIATOR_FRAMES); + }); +}); From a8cae15c787f0bb01ce59b4d5d4c47e014288920 Mon Sep 17 00:00:00 2001 From: Oleh H Date: Sat, 26 Sep 2026 00:08:35 +0000 Subject: [PATCH 2/2] Keep Angular's view registry on the page once found A production Angular page's view registry was found by walking the heap (Runtime.queryObjects over every Map) on every Component page read and tree level. It is now found once per document and kept on the page's window as a non-enumerable global, where each later read takes it with one call: on a heap of 300,000 Maps, the first read takes about 1.1 s, the next ones 7 ms. A kept registry that no longer holds views is found again; it goes with the document. --- docs/SPEC.md | 8 ++++---- src/main/inspector/adapter/registrySource.ts | 18 ++++++++++++++---- src/main/inspector/constants.ts | 5 +++++ src/main/inspector/reading/angularRegistry.ts | 17 +++++++++++------ test/integration/frameworks.chromium.test.ts | 9 ++++++++- test/unit/componentInspector.test.ts | 17 +++++++++++++++-- test/unit/componentRenders.test.ts | 3 +++ 7 files changed, 60 insertions(+), 17 deletions(-) diff --git a/docs/SPEC.md b/docs/SPEC.md index 116fe34e..a94fbd05 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -625,7 +625,7 @@ Picking an element in the page, in any frame, shows the component that rendered | Picking | **Pick an element** (the page toolbar, the Inspect view, the palette, **View › Pick an Element**, Ctrl/Cmd+Shift+C) puts every session in Chromium's inspect mode at once (`DOM.enable`, `Overlay.enable`, `Overlay.setInspectMode` `searchForNode`), so the pointer can go into any frame, cross-site ones included; a frame that loads while picking joins in. Chromium draws the highlight, and the click doesn't reach the page. Esc in the page (`Overlay.inspectModeCanceled`) or in the editor, the button again or the menu item stop it in every session. Stopping also turns the Overlay domain off (`Overlay.disable`): left on, it taxes every layout of the page (a 2,000-row commit took twice as long after a pick). A highlight (a pick's element, a tree node) turns it on while it shows, and hiding the highlights turns it off again, unless picking | | Under the pointer | `Overlay.nodeHighlightRequested` names the node. At most every 100 ms (the latest node wins), the adapter's `summary` of it is read by value: the element and the names of the components that rendered it. The Inspect view shows it while picking | | The pick | `Overlay.inspectNodeRequested` ends picking and gives the node. It is resolved to a handle in an object group of its own (the last 20 picks are kept, older groups released), becomes the console's `$0` (`DOM.setInspectedNode`), and its frame is found by matching its document against each frame owner's content document (`DOM.getFrameOwner`, `DOM.describeNode`): CDP doesn't say which frame a node is in | -| Reading a component | `Runtime.callFunctionOn` of `ADAPTER_SOURCE` on the element, in the page's main world, `silent`. React: the fiber on the element or its nearest ancestor (`__reactFiber$…`; React keeps two copies of each fiber and doesn't update the element's key, so the copy on screen is found as React DevTools' `findCurrentFiberUsingSlowPath` does, at each step up), up through its `return`s to the function, class, `memo` and `forwardRef` components (the chain, at most 40); props from `memoizedProps`; hooks from the `memoizedState` list (state, a store, a ref, a memo; effects left out), a class's `state`; each context it reads (`dependencies.firstContext`) with its nearest provider's `value` and the component that renders it. Vue 3: `__vueParentComponent` in development builds; production builds don't set it, so the app's vnode tree is walked from the element it is mounted on (`_vnode`, at most 20,000 vnodes) to find the element's component, only down the elements that hold it (an element's vnode holds its subtree), so a large app costs its depth, not its size; its props, `setupState` and `data`, what it provides, and the chain through `parent`. Vue 2: the instance on the nearest element carrying one (`__vue__`; components sharing a root element leave the outermost's, so the innermost is found down its root vnode), its props and `data`, what it provides, and the chain through `$parent`. Angular: a component is its host element; a development build's `window.ng.getComponent` gives a host's instance, and a production build's comes from Angular's private view registry, which the main process finds among every Map of the heap (`Runtime.queryObjects(Map.prototype)`, only for such a page, and not while hovering, when hosts are named by their tags): the host's `__ngContext__` is the id of the view that declares it, which holds the host's own component view (a `TView` of type 1), whose context slot is the instance (`ANGULAR_VIEW`, Angular 17 to 22, pinned by the tests); its inputs (`ɵcmp.inputs`), its signals (settable) and fields, and the chain of hosts up through shadow roots; the Component page labels a production one as read from Angular's internals. Custom elements: an element whose tag is defined (`customElements.get`), its class the element's constructor; Lit's reactive properties (`elementProperties`, internal state flagged `state`, settable) or the observed attributes, and the chain of hosts. The element's handlers: the `on…` props React keeps on it (`__reactProps$…`), or its vnode's. The adapter answers with previews and the functions it named, each once (a level of 500 rows of one component names one function); `Runtime.getProperties` gives each function's `[[FunctionLocation]]` (script id, line and column), for at most 1,000 functions a read, one that went away meanwhile leaving the others placed | +| Reading a component | `Runtime.callFunctionOn` of `ADAPTER_SOURCE` on the element, in the page's main world, `silent`. React: the fiber on the element or its nearest ancestor (`__reactFiber$…`; React keeps two copies of each fiber and doesn't update the element's key, so the copy on screen is found as React DevTools' `findCurrentFiberUsingSlowPath` does, at each step up), up through its `return`s to the function, class, `memo` and `forwardRef` components (the chain, at most 40); props from `memoizedProps`; hooks from the `memoizedState` list (state, a store, a ref, a memo; effects left out), a class's `state`; each context it reads (`dependencies.firstContext`) with its nearest provider's `value` and the component that renders it. Vue 3: `__vueParentComponent` in development builds; production builds don't set it, so the app's vnode tree is walked from the element it is mounted on (`_vnode`, at most 20,000 vnodes) to find the element's component, only down the elements that hold it (an element's vnode holds its subtree), so a large app costs its depth, not its size; its props, `setupState` and `data`, what it provides, and the chain through `parent`. Vue 2: the instance on the nearest element carrying one (`__vue__`; components sharing a root element leave the outermost's, so the innermost is found down its root vnode), its props and `data`, what it provides, and the chain through `$parent`. Angular: a component is its host element; a development build's `window.ng.getComponent` gives a host's instance, and a production build's comes from Angular's private view registry, which the main process finds among every Map of the heap (`Runtime.queryObjects(Map.prototype)`, only for such a page, and not while hovering, when hosts are named by their tags) once per document, then keeps on the page's window (a non-enumerable global, `ANGULAR_REGISTRY_GLOBAL`, while it holds views), where each later read takes it with one call: on a heap of 300,000 Maps a first read takes about 1.1 s, the next ones 7 ms: the host's `__ngContext__` is the id of the view that declares it, which holds the host's own component view (a `TView` of type 1), whose context slot is the instance (`ANGULAR_VIEW`, Angular 17 to 22, pinned by the tests); its inputs (`ɵcmp.inputs`), its signals (settable) and fields, and the chain of hosts up through shadow roots; the Component page labels a production one as read from Angular's internals. Custom elements: an element whose tag is defined (`customElements.get`), its class the element's constructor; Lit's reactive properties (`elementProperties`, internal state flagged `state`, settable) or the observed attributes, and the chain of hosts. The element's handlers: the `on…` props React keeps on it (`__reactProps$…`), or its vnode's. The adapter answers with previews and the functions it named, each once (a level of 500 rows of one component names one function); `Runtime.getProperties` gives each function's `[[FunctionLocation]]` (script id, line and column), for at most 1,000 functions a read, one that went away meanwhile leaving the others placed | | Listeners | Every listener on the picked element itself (`DOMDebugger.getEventListeners`, which gives the handlers only for a handle in a named object group): its event, options and the function it runs (Vue 3's invoker unwrapped through its `value`, an object's `handleEvent`), named and placed like the others. On a plain page they are all there is; a framework's own (React's no-op click, Angular's wrapper) show as they are | | Hook names | A production component's hooks are listed by place. Once its function's original is known, the source-map worker parses the original (`@babel/parser`: TypeScript and JSX), finds the function at that place and lays its hook calls out as React keeps them, each named by the variable it sets (`const [qty, setQty] = useState(1)` → `qty`): React 19 adds two entries for `useSyncExternalStore` and `useTransition`, three for `useActionState`, none for `useContext`, `use` and `useDebugValue`. A custom hook defined in the same file is read in place; one from elsewhere stops the naming, since how many entries it adds is unknown | | Setting state | A `useState` hook (its queue reduces with React's own `basicStateReducer`, told by its text, which a minifier may quote with backticks; a `useReducer`'s takes actions, so it can't be set), a class's state (`setState`), a Vue component's `data` key, or a writable ref in its `setupState` (read under the unwrapping proxy, which forwards descriptors; a computed ref is read-only) can be set: the new value is written as JSON (at most 64 KB), dispatched in the page by the adapter's `set`, and the component is read again 50 ms later, rendered with it | @@ -720,7 +720,7 @@ The site's `WebContentsView` can move to a window of its own (`PageWindow`), e.g - The page stack's detector runs in each frame's main world, where the page can change what it answers: only known ids and signals are kept, versions only when they look like one, and everything shown besides a version is the app's own text (§6.12). The React hook stand-in is a global the page can see; **Framework hooks** turns it off. - The component inspector's adapter runs in the main world of the frame picked in, where the page could change what it answers: the answer is checked the same way (§6.13), and names, previews and keys are only ever shown as plain labels. Reading where a function is defined turns the page's Debugger domain on for a moment, with pauses skipped, and off again. Setting state runs in the page with a value the renderer wrote as JSON, parsed by main and passed as an argument, never as code. - A production Angular page's components are read by walking its heap for Maps (`Runtime.queryObjects`), only when one is picked or its tree is read; the registry found is used through its handle and released with the read. A source map loaded from a file is copied into the data folder as it is and parsed only by the renderer's worker, like a fetched one; the index naming the copies is checked when read, and a copy is only ever one the store named. -- While renders are recorded, each document has the binding's function as a global, which the page can see and call: what it hands over is checked like any other answer (§6.14), and it is taken out of loaded documents when recording stops. The same holds for the store actions' binding (§6.15). +- While renders are recorded, each document has the binding's function as a global, which the page can see and call: what it hands over is checked like any other answer (§6.14), and it is taken out of loaded documents when recording stops. The same holds for the store actions' binding (§6.15). A production Angular page also keeps its own view registry as a non-enumerable global once the inspector found it (§6.13): nothing the page didn't already hold. - The store stand-in puts the Redux DevTools extension's globals in pages that have none (only while **Framework hooks** is on): a page can tell, and a store made through them keeps working when nothing records (the stand-in's dispatch only notes the action). Its own global (`__consoleEditorStoreHook`) only finds a frame's Vue stores and says which libraries it heard of. Store names, action types, payload previews and stacks are checked like any answer; a stack's calls must be in http(s) files. - An action saved from the Component page is code the app wrote, shown in the action form before it is kept: the page's selectors are in it as JSON strings, and the value as the JSON you typed. - Rules change only what the app's own browser sees. A CORS rule makes an API readable by the page shown, credentials included, which is what it is for; it can't change what the server allows, and cookies still follow the browser's rules. @@ -732,11 +732,11 @@ The site's `WebContentsView` can move to a window of its own (`PageWindow`), e.g | Layer | What | Command | |---|---|---| -| Unit | Matchers, header/SRI/source-map transforms, stores (persistence, atomic concurrent writes), engine logic and navigation rules with a fake CDP transport, iframe session coordination (timeouts, sessions that go away, cascading detach), worker sessions (setup order and resuming, `Fetch` kept on, settings per worker type, which session lists and credits a worker's files, missed-override reasons, outdated service workers and `prepareReload` (unregistering by scope, letting go, retrying), a service worker's state kept for its next session, shared-worker discovery and holding), minified heuristic, version comparison, CHANGELOG parsing (and that CHANGELOG.md covers `package.json`'s version), the update service with fakes (checks, quiet failures, progress, checksums, install failures, schedule), the Linux desktop entry (quoting paths, which copies install one, a package's entry winning, removing only its own, following a renamed AppImage, writing only what changed) and the `.rpm`'s install script kept in step with electron-builder's, workspaces in the stores (migration, per-workspace tabs, drafts, overrides and actions, deletion, frame names), the action store (each workspace's actions across instances, what it refuses and why, a failed write changing nothing, changes run in order), favicon loading (recognising images, size caps), the console service with a fake CDP transport (frames across sessions, contexts, rows and their previews, format directives, running code, properties, the cap, clearing, the setting), the session observer (handed every session before it runs, never holding interception up) and where the website's and the Actions panel's windows open (its saved place while it is on a screen, another screen than the editor's, fitted to a small one, at the size each opens at) and how that is saved (Keep on top too), rules (validation, the store's persistence, entries it can't read, broken and unreadable files, the engine's stages, header edits, CORS and preflights, request types, patterns), source maps (finding the reference, loading limits, header capture), response overrides that don't send (`unsentOverrides.test.ts`: patterns, the answer and its CORS, the preflight, what goes on to the server, the delay, the setting kept) and breakpoints (`breakpoints.test.ts`: validation and storage, patterns, holding at each stage and each action, what never stops, letting go), the JSON tree (`jsonTree.test.ts`: parsing without loss, offsets, what it refuses, diffing and applying edits, giving up on a document they don't fit), patch mode (`patchMode.test.ts`: the live response patched, edits worked out once per version, the saved text when upstream fails or the edits don't fit, never a stream, the setting kept), HAR files (`har.test.ts`: entries written, sockets' messages, overrides read back and what is left out), the network speed setting (kept, checked) and its commands on every kind of session, the page stack (the React hook stand-in in every session, with `Page` on first, taken out and put back with the setting; a frame looked at once it loads, silently in its main world, once for two loads in quick succession, not after it navigated, and not kept from the document it left; a cross-site iframe's own session, dropped with it; nothing while the console doesn't record, every frame once it does; the console unaffected when the stand-in can't go in; what the page answers checked: unknown ids and signals, builds, versions, at most 40); the component inspector with a fake CDP transport (`componentInspector.test.ts`: every session into inspect mode and out, one that attaches while picking too; what is under the pointer read at most every interval, the latest node winning; a click stopping picking, keeping the node as `$0` and sending its component with each function placed; a node's frame told by its frame owner; the chain's other components; Esc in the page; the last 20 picks kept and older handles freed; highlighting, with the Overlay domain off once picking and highlights are over; a node that can't be read; a production Angular page's view registry found and handed to the adapter; the element's own listeners, named and placed; what the page says checked: frameworks, builds, state kinds, labels, list caps); scripts' source maps counted per frame (inline, isolated-world, evaluated and other frames' scripts left out); renders, the tree and state (`componentRenders.test.ts`: the binding in every session while recording, one attaching too, removed and its function deleted when it stops; batches sent in order, checked, framed by their context, their functions located once per document; other bindings, bad payloads and anything after stopping ignored; the page's commits checked: kinds, reasons, labels, caps; a tree level read in the frame's main world, a node opened as a pick at its depth and highlighted, a gone frame or bad path refused; a state edit taken only as a known kind, a name and JSON); source maps loaded from files (`sourceMapFileStore.test.ts`: a copy kept per workspace and bundle and read back after a restart, replaced, forgotten, removed with its workspace, its copies deleted; index entries that don't hold up, a copy named outside the folder among them, left out; a file's map handed over as found against the bundle as served); store actions (`storeTimeline.test.ts`: the hooks' one script, which parses; the binding in every session while recording, each frame asked to find its Vue stores, taken out when it stops; batches checked, numbered and framed, others' and late ones ignored, a flood of them capped; known libraries, labels, stacks in loaded files and caps), the events sent to a window as JSON (`appEventWire.test.ts`), the main process's lookups bounded (`inspectorLookups.test.ts`: only the scripts alive kept, whether each names a map, long URLs left out; at most 1,000 functions placed a read, one gone leaving the others; initiators' URLs and names), commits naming their store action and components their own render time, a request's initiator through its async parents in loaded files (`networkLog.test.ts`) | `npm test` | +| Unit | Matchers, header/SRI/source-map transforms, stores (persistence, atomic concurrent writes), engine logic and navigation rules with a fake CDP transport, iframe session coordination (timeouts, sessions that go away, cascading detach), worker sessions (setup order and resuming, `Fetch` kept on, settings per worker type, which session lists and credits a worker's files, missed-override reasons, outdated service workers and `prepareReload` (unregistering by scope, letting go, retrying), a service worker's state kept for its next session, shared-worker discovery and holding), minified heuristic, version comparison, CHANGELOG parsing (and that CHANGELOG.md covers `package.json`'s version), the update service with fakes (checks, quiet failures, progress, checksums, install failures, schedule), the Linux desktop entry (quoting paths, which copies install one, a package's entry winning, removing only its own, following a renamed AppImage, writing only what changed) and the `.rpm`'s install script kept in step with electron-builder's, workspaces in the stores (migration, per-workspace tabs, drafts, overrides and actions, deletion, frame names), the action store (each workspace's actions across instances, what it refuses and why, a failed write changing nothing, changes run in order), favicon loading (recognising images, size caps), the console service with a fake CDP transport (frames across sessions, contexts, rows and their previews, format directives, running code, properties, the cap, clearing, the setting), the session observer (handed every session before it runs, never holding interception up) and where the website's and the Actions panel's windows open (its saved place while it is on a screen, another screen than the editor's, fitted to a small one, at the size each opens at) and how that is saved (Keep on top too), rules (validation, the store's persistence, entries it can't read, broken and unreadable files, the engine's stages, header edits, CORS and preflights, request types, patterns), source maps (finding the reference, loading limits, header capture), response overrides that don't send (`unsentOverrides.test.ts`: patterns, the answer and its CORS, the preflight, what goes on to the server, the delay, the setting kept) and breakpoints (`breakpoints.test.ts`: validation and storage, patterns, holding at each stage and each action, what never stops, letting go), the JSON tree (`jsonTree.test.ts`: parsing without loss, offsets, what it refuses, diffing and applying edits, giving up on a document they don't fit), patch mode (`patchMode.test.ts`: the live response patched, edits worked out once per version, the saved text when upstream fails or the edits don't fit, never a stream, the setting kept), HAR files (`har.test.ts`: entries written, sockets' messages, overrides read back and what is left out), the network speed setting (kept, checked) and its commands on every kind of session, the page stack (the React hook stand-in in every session, with `Page` on first, taken out and put back with the setting; a frame looked at once it loads, silently in its main world, once for two loads in quick succession, not after it navigated, and not kept from the document it left; a cross-site iframe's own session, dropped with it; nothing while the console doesn't record, every frame once it does; the console unaffected when the stand-in can't go in; what the page answers checked: unknown ids and signals, builds, versions, at most 40); the component inspector with a fake CDP transport (`componentInspector.test.ts`: every session into inspect mode and out, one that attaches while picking too; what is under the pointer read at most every interval, the latest node winning; a click stopping picking, keeping the node as `$0` and sending its component with each function placed; a node's frame told by its frame owner; the chain's other components; Esc in the page; the last 20 picks kept and older handles freed; highlighting, with the Overlay domain off once picking and highlights are over; a node that can't be read; a production Angular page's view registry found and handed to the adapter, and taken from the page the next time; the element's own listeners, named and placed; what the page says checked: frameworks, builds, state kinds, labels, list caps); scripts' source maps counted per frame (inline, isolated-world, evaluated and other frames' scripts left out); renders, the tree and state (`componentRenders.test.ts`: the binding in every session while recording, one attaching too, removed and its function deleted when it stops; batches sent in order, checked, framed by their context, their functions located once per document; other bindings, bad payloads and anything after stopping ignored; the page's commits checked: kinds, reasons, labels, caps; a tree level read in the frame's main world, a node opened as a pick at its depth and highlighted, a gone frame or bad path refused; a state edit taken only as a known kind, a name and JSON); source maps loaded from files (`sourceMapFileStore.test.ts`: a copy kept per workspace and bundle and read back after a restart, replaced, forgotten, removed with its workspace, its copies deleted; index entries that don't hold up, a copy named outside the folder among them, left out; a file's map handed over as found against the bundle as served); store actions (`storeTimeline.test.ts`: the hooks' one script, which parses; the binding in every session while recording, each frame asked to find its Vue stores, taken out when it stops; batches checked, numbered and framed, others' and late ones ignored, a flood of them capped; known libraries, labels, stacks in loaded files and caps), the events sent to a window as JSON (`appEventWire.test.ts`), the main process's lookups bounded (`inspectorLookups.test.ts`: only the scripts alive kept, whether each names a map, long URLs left out; at most 1,000 functions placed a read, one gone leaving the others; initiators' URLs and names), commits naming their store action and components their own render time, a request's initiator through its async parents in loaded files (`networkLog.test.ts`) | `npm test` | | Renderer | Resource tree building and filtering (worker entries: kept across navigations for service and shared workers, dropped with their worker, filtered by worker URL), command-palette fuzzy matching, missed-override notices by reason (a nested worker's once per override version), update notifications, What's New and page tabs, session sync and workspace switching (pending drafts written, tabs closed without losing them, the other workspace's reopened), console frames (keys, labels, colours), rows, filters, Keep rows, prompt history and frame names, rules (quick rules and Undo, toggling with rollback, rule pages and their drafts, applying only what changed, results that arrive after a switch, hits and recent requests), original sources (parsing, positions through pretty-printing, tabs, jumps both ways, the tree, the palette), actions (finding an action's frame by key or by name, labels of frames not on the page, runs and why one couldn't run, the form's openings, saving and deleting, copies, the palette's group, the bridge loading and following them), the Actions window's bridge (what it loads, the events it follows and those it ignores) and the editor's copy of where the panel is and of settings another window changed, the Network panel (rows kept and replaced, earlier loads dropped unless kept, groups and the text filter, status, size and time cells, which actions a request offers) and response overrides (the inferred schema, which override answers a request, opening a response and saving it with its method, operation and answer, the response row's fields and Apply), the bottom pane's tab, held requests (`held.test.ts`: their tabs, what Send does at each stage and with an edited body, fields that can't go out, Send original, Fail, Save as override, closing the tab, the page giving up, never kept in the session), breakpoints (added, toggled, removed, refused, put back when saving fails, Pause like this) and Copy as fetch, quick edits (`quickEdits.test.ts`: lists emptied, texts lengthened but links, ids and dates, the value at the cursor nulled, the rest of the text as typed) and Patch live through the response row's form, the response tree (`responseTree.test.ts`: rows for what is open with unique ids, members removed with their comma, added as the last one is written, the selection after a rename or removal), the page stack (UI libraries named once, the top page's first; findings by kind; one Page stack tab; the bridge's snapshot and `stack-changed`), the component inspector (`componentInspector.test.ts`: a function's place in the bundle mapped to its original, named by the map or read off the original's text in each way code names a function; a React component named after its original, a Vue one by itself; picking toggled as main last said; another component of the chain read, or a toast when the page moved on; the bridge following picking and showing what was picked, in one Component tab renamed in place); hook names read off an original (`hookNames.test.ts`: hook calls laid out as React keeps them, same-file custom hooks followed, an imported one stopping the naming, arrows placed by their parameters); renders, the tree and state (`componentRenders.test.ts`: why a component took part, in words, hooks named; triggers; what a frame's last commit rendered; the log's cap; the bridge following recording and tracing functions once each; tree rows as far as open; a frame's top level, a node opened once and closed, a stale frame's level dropped, a pick revealed down its path; opening a node, and a toast when it can't; setting a value, and a toast when it can't); maps loaded from files (`mapFiles.test.ts`: location keys read back; a bundle's traced places forgotten and traced again once a map is loaded or forgotten, every original and hook name forgotten with the maps and a lookup finishing after dropped, nothing when no file was picked, toasts on failures; the Explorer's menu items); store actions (`storeTimeline.test.ts`: recording followed, actions kept and capped, their calls traced once each, a failure to start said; the app's own call in a stack, past libraries); requests by component (`requestsByComponent.test.ts`: a frame's requests sent through a file, newest first, with the call); a commit's trigger with its action, a set value kept and the action written from it per framework (a hook's place, a class's key, selectors through shadow roots, none without a way in), renders by component (counts, own time summed, reasons, costliest first; kept as commits come and go the same as summed afresh; the log's rows) (`componentRenders.test.ts`) | `npm test` | | Performance | The inspector on large apps in real Chromium (`test/perf/inspector.perf.test.ts`): a React and a Vue 3 app of some 14,000 components (a 2,000-row table, a chain 1,500 deep in React, 300 in Vue) and stores of 20,000 items (Redux Toolkit, Pinia), as production builds. It times a commit of every row with the hooks off, idle and recording renders, and after picking; hovering and picking deep in the table and at the end of the chain; the page stack; a level of the tree; a batch's size; Redux dispatches and Pinia actions idle, recording and after it stopped. And the built app's UI (`test/perf/ui.perf.test.ts`) fed what large apps record at the pace recording sends it (2,000 commits of 200 components, 1,000 store actions with 50-call stacks, 2,000 requests with 20-call initiators, their places traced through a real bundle's map): how long the window's main thread is blocked, its longest task, the memory the log takes, and how long **By component** takes to show. Each prints its medians and fails past a budget set well above what a laptop measures, so only work growing with the whole page on a hot path trips it; it isn't part of CI | `npm run test:perf` (on a display: `xvfb-run -a` on headless Linux) | | Architecture | Feature-Sliced Design layer rules; the code-structure rules (files of at most 150 lines, one function, component, class or store per file named after it, data-only constants/types/index files, no `switch`) | `npm run lint:fsd`, `npm run lint:structure` | -| Integration | Engine in real Chromium against the fixture site: gzip, static and runtime SRI, globs, CSS/HTML overrides, 404, redeploy detection, source maps, disable. Iframes through the session-aware WebSocket transport (`test/helpers/chromium.ts`): same-site, cross-site and nested iframes, SRI inside iframes, iframe HTML overrides, same-site navigation, removal, reload; each asserts the iframe really is a separate target. The console on a page of service iframes (same-site, and two on sites of their own): every frame's first log line on its own frame, code run in one frame and another frame's logs reacting, top-level `await` and expanding the result, uncaught errors and rejections, a frame keeping its id across a navigation, a cross-site frame's function refused from the top page but run in the frame itself (why actions run in their frame). Workers against the fixture's `/workers/` page (`workers.chromium.test.ts`, a fresh browser context per test): every kind runs while intercepted; edits reach a dedicated and a module worker's first script and imports, what a nested worker imports (its first script is served in Chromium 141, reported as missed in 152+), a shared worker, a service worker's script and imports, and an audio worklet's module; each file is listed with its worker and read through its session; a shared worker's races are forced by holding back its session's commands; workers under a cross-site iframe are served on its session and removed with it; workers are reported gone; an edit to an installed service worker applies on the next reload, and one whose page was left is reinstalled when its site loads again under other overrides (a workspace switch); the page's `registration.update()` is reported and the next reload undoes it; a service worker is listed again, and not reinstalled, when the page comes back to its site; the cache setting reaches what workers load. Rules (`rules.chromium.test.ts`): blocking before the server sees the request (a script, one inside a cross-site iframe, an iframe's document, a redirect's later hop), a URL both blocked and overridden, the page itself never blocked; a gzipped document's CSP removed and another's added, X-Frame-Options removed so a page can be framed, a document no rule changes never read, Cache-Control and Content-Type on streamed responses, headers back once a rule is off; CORS with credentials, a preflight the API refuses, redirects. Source maps named by headers, `X-SourceMap`, comments and `data:` URIs, a stylesheet's, and an override-served bundle's. The network log and response overrides (`network.chromium.test.ts`, the fixture's `/network/` page): what the log lists for fetch(), GraphQL, a failing call, an event stream and a worker's fetch, page loads counted, request and response bodies read, never a stream's (which keeps streaming); a response override answering fetch() and XHR with its body, status and header changes (the request still reaching the server) and marking the row, its delay, only its method and GraphQL operation, a dedicated worker's fetch, and an event stream left streaming or replaced as a whole. Held and unsent requests (`held.chromium.test.ts`): an override that doesn't send answering another origin's POST and its preflight with the server never hit (and, without it, the server turning the preflight away); breakpoints holding a response (its row marked) until answered edited or as it was, a request before it is sent (its row marked) sent elsewhere or answered, one failed, one the page gave up on let go, everything let go when interception stops, and nothing stopped once off. In `network.chromium.test.ts` too: patch mode keeping the live values it wasn't told to change and answering a failing upstream with the saved text; the page and its worker taken offline and slowed down; a WebSocket's handshake, text and binary messages read incrementally, and its close; the log written as HAR with its bodies and read back as overrides that answer without the server. The page stack (`stack.chromium.test.ts`): a React app the test bundles from the repo's react and react-dom, found through the hook stand-in with its version, as a production and a development build, and by its keys with **Framework hooks** off (and no hook left in the page); what Vue, Pinia, Angular, Next.js and webpack leave in a page; a cross-site iframe's React, which found the stand-in in place before it loaded; no console rows. The component inspector (`inspect.chromium.test.ts`), with real pointer input on carts in React and Vue the test bundles (`test/helpers/bundleApp.ts`), as minified production builds with source maps and as development builds: a production React component's chain, props, state, context and handler, each function traced through the map to its source line; a click the page never gets, and the element as `$0`; the chain's other components, and an element that is gone; a production Vue component through its app's vnode tree, with what the app provides, and a development build's from the element; picking inside a cross-site iframe on its own session; Esc in the page; a useState hook set and rendered, JSON and unsettable values refused; Vue's data and a setup ref set, a computed one refused; the Components tree of a React app through the hook stand-in and by its containers without it, and of a production Vue app (each function placed once however many of its components a level lists), nodes opened as picks at their depth, picks' paths; renders recorded on a React app whose buttons each commit for another reason (own state and a store, a context with a memo child skipped, a parent's state with changed props, a class's state), with triggers, frames, durations and order, nothing after stopping, and a production build's mount recorded from a document loaded while recording, its functions placed through the map. The page stack (`stack.chromium.test.ts`) also counts a frame's scripts that name a source map by comment or header. The other frameworks (`frameworks.chromium.test.ts`), each bundled by the test from the repo's own packages: a production Angular component read through its view registry (inputs, a settable signal, a field that isn't, each class placed by the map; hosts named by their tags while hovering), a development build through `window.ng` and its tree, a production build's tree through the registry; a Vue 2 component's props, data (set), what the app provides, chain and tree; a Lit component in its shadow root, its properties and state (set), host chain and tree; a plain page's listeners with names, places and options; a Vue 3 listener's function, not Vue's invoker; store actions (`stores.chromium.test.ts`): Redux Toolkit's (the slice's type, payload, what changed, the handler's line through the map; the page stack names Redux), the React commit after one naming it and nothing once stopped, Zustand's through its devtools, Pinia's actions and direct changes (heard again once an action that never settles stops counting) and Vuex's mutations (found when recording starts and by a document loaded while recording), NgRx's through its StoreDevtools; a request keeping the stack of the handler that sent it; saved actions (`stateActions.chromium.test.ts`): a picked component's action written, the page loaded again, and the action setting the value in React (a hook), Vue 3 production and development (a ref and data), Vue 2 (data), Angular development (a signal; production gets none) and Lit (through two shadow roots) | `npm test` (skips if no Chromium; `npx playwright install chromium`) | +| Integration | Engine in real Chromium against the fixture site: gzip, static and runtime SRI, globs, CSS/HTML overrides, 404, redeploy detection, source maps, disable. Iframes through the session-aware WebSocket transport (`test/helpers/chromium.ts`): same-site, cross-site and nested iframes, SRI inside iframes, iframe HTML overrides, same-site navigation, removal, reload; each asserts the iframe really is a separate target. The console on a page of service iframes (same-site, and two on sites of their own): every frame's first log line on its own frame, code run in one frame and another frame's logs reacting, top-level `await` and expanding the result, uncaught errors and rejections, a frame keeping its id across a navigation, a cross-site frame's function refused from the top page but run in the frame itself (why actions run in their frame). Workers against the fixture's `/workers/` page (`workers.chromium.test.ts`, a fresh browser context per test): every kind runs while intercepted; edits reach a dedicated and a module worker's first script and imports, what a nested worker imports (its first script is served in Chromium 141, reported as missed in 152+), a shared worker, a service worker's script and imports, and an audio worklet's module; each file is listed with its worker and read through its session; a shared worker's races are forced by holding back its session's commands; workers under a cross-site iframe are served on its session and removed with it; workers are reported gone; an edit to an installed service worker applies on the next reload, and one whose page was left is reinstalled when its site loads again under other overrides (a workspace switch); the page's `registration.update()` is reported and the next reload undoes it; a service worker is listed again, and not reinstalled, when the page comes back to its site; the cache setting reaches what workers load. Rules (`rules.chromium.test.ts`): blocking before the server sees the request (a script, one inside a cross-site iframe, an iframe's document, a redirect's later hop), a URL both blocked and overridden, the page itself never blocked; a gzipped document's CSP removed and another's added, X-Frame-Options removed so a page can be framed, a document no rule changes never read, Cache-Control and Content-Type on streamed responses, headers back once a rule is off; CORS with credentials, a preflight the API refuses, redirects. Source maps named by headers, `X-SourceMap`, comments and `data:` URIs, a stylesheet's, and an override-served bundle's. The network log and response overrides (`network.chromium.test.ts`, the fixture's `/network/` page): what the log lists for fetch(), GraphQL, a failing call, an event stream and a worker's fetch, page loads counted, request and response bodies read, never a stream's (which keeps streaming); a response override answering fetch() and XHR with its body, status and header changes (the request still reaching the server) and marking the row, its delay, only its method and GraphQL operation, a dedicated worker's fetch, and an event stream left streaming or replaced as a whole. Held and unsent requests (`held.chromium.test.ts`): an override that doesn't send answering another origin's POST and its preflight with the server never hit (and, without it, the server turning the preflight away); breakpoints holding a response (its row marked) until answered edited or as it was, a request before it is sent (its row marked) sent elsewhere or answered, one failed, one the page gave up on let go, everything let go when interception stops, and nothing stopped once off. In `network.chromium.test.ts` too: patch mode keeping the live values it wasn't told to change and answering a failing upstream with the saved text; the page and its worker taken offline and slowed down; a WebSocket's handshake, text and binary messages read incrementally, and its close; the log written as HAR with its bodies and read back as overrides that answer without the server. The page stack (`stack.chromium.test.ts`): a React app the test bundles from the repo's react and react-dom, found through the hook stand-in with its version, as a production and a development build, and by its keys with **Framework hooks** off (and no hook left in the page); what Vue, Pinia, Angular, Next.js and webpack leave in a page; a cross-site iframe's React, which found the stand-in in place before it loaded; no console rows. The component inspector (`inspect.chromium.test.ts`), with real pointer input on carts in React and Vue the test bundles (`test/helpers/bundleApp.ts`), as minified production builds with source maps and as development builds: a production React component's chain, props, state, context and handler, each function traced through the map to its source line; a click the page never gets, and the element as `$0`; the chain's other components, and an element that is gone; a production Vue component through its app's vnode tree, with what the app provides, and a development build's from the element; picking inside a cross-site iframe on its own session; Esc in the page; a useState hook set and rendered, JSON and unsettable values refused; Vue's data and a setup ref set, a computed one refused; the Components tree of a React app through the hook stand-in and by its containers without it, and of a production Vue app (each function placed once however many of its components a level lists), nodes opened as picks at their depth, picks' paths; renders recorded on a React app whose buttons each commit for another reason (own state and a store, a context with a memo child skipped, a parent's state with changed props, a class's state), with triggers, frames, durations and order, nothing after stopping, and a production build's mount recorded from a document loaded while recording, its functions placed through the map. The page stack (`stack.chromium.test.ts`) also counts a frame's scripts that name a source map by comment or header. The other frameworks (`frameworks.chromium.test.ts`), each bundled by the test from the repo's own packages: a production Angular component read through its view registry (found once, then taken from the page without walking the heap again; inputs, a settable signal, a field that isn't, each class placed by the map; hosts named by their tags while hovering), a development build through `window.ng` and its tree, a production build's tree through the registry; a Vue 2 component's props, data (set), what the app provides, chain and tree; a Lit component in its shadow root, its properties and state (set), host chain and tree; a plain page's listeners with names, places and options; a Vue 3 listener's function, not Vue's invoker; store actions (`stores.chromium.test.ts`): Redux Toolkit's (the slice's type, payload, what changed, the handler's line through the map; the page stack names Redux), the React commit after one naming it and nothing once stopped, Zustand's through its devtools, Pinia's actions and direct changes (heard again once an action that never settles stops counting) and Vuex's mutations (found when recording starts and by a document loaded while recording), NgRx's through its StoreDevtools; a request keeping the stack of the handler that sent it; saved actions (`stateActions.chromium.test.ts`): a picked component's action written, the page loaded again, and the action setting the value in React (a hook), Vue 3 production and development (a ref and data), Vue 2 (data), Angular development (a signal; production gets none) and Lit (through two shadow roots) | `npm test` (skips if no Chromium; `npx playwright install chromium`) | | End-to-end | Built Electron app driven by Playwright: open site, edit, save, page runs it, disable/enable, edit files inside a cross-site and a nested iframe, the fixture's `/workers/` page with its workers' files listed under their worker's badge and edited (imports of each kind of worker; a module worker's static import; the first script of a dedicated worker, a shared worker, a service worker and a worklet; a service worker's script edited again, turned off and on, and deleted; a worker under a cross-site iframe), the update check's toast with Bypass service workers off and its reload, what stays listed when the page leaves (its site's service worker) and when it leaves the site (nothing), each workspace running its own edit of the service worker's script (`workers.e2e.test.ts`), persistence across restart, a second launch handing over its URL, workspaces (a new one starts empty and doesn't serve another's overrides, takes its site's favicon, switching back restores the page, tabs and overrides with no history from the other, renaming, all of it across a restart), the console (each frame's rows, running code in a picked frame and seeing another react, filtering by frame, naming a frame and keeping the name across a restart, clearing), actions (`actions.e2e.test.ts`: code run in the console saved as an action for its frame, run with one click and another frame reacting, one for a frame picked from the page showing what it threw, run from the palette, changed and deleted, each workspace's own across a restart), the Actions panel in a window of its own (`actionsWindow.e2e.test.ts`: moved there, running and making actions from it, the workspace and the settings following it, Keep on top, reopened where it was after a restart, back by closing it, from the sidebar's notice and from the View menu), the website in a window of its own (`pageWindow.e2e.test.ts`: moved there from the preview's toolbar without reloading, the editor's saved edits served to it, navigating from its toolbar, back from its button, by closing it, from the title bar and from the View menu; the site's pop-ups moving with it; put back, or asked for its address bar, while its window still loads; where it was and that it was open kept across a restart). Rules: block a script from the file tree, turn it off and on, undo a quick rule, remove a page's CSP, allow CORS for an API with a preflight, keep an unapplied edit on its tab and apply it from File › Save, rules per workspace, delete, and blocking from the first load after a restart. Updates against a local feed: the automatic announcement, What's New with the release's notes, a download refused for its checksum and then accepted. The original sources behind a bundle: listed, opened read-only, jumping to the pretty-printed bundle line and back, found from the palette. The Network panel (`network.e2e.test.ts`): the page's fetch and GraphQL calls listed, Fetch/XHR first and the document under All; a response opened, edited, saved and served to the page, the row marked and the override in the Explorer with its method; another status applied from the response row; the override turned off; requests like the selected one paused and an edited response sent to the page, a paused response saved as an override that answers from then on, a breakpoint written in the menu holding a request before it is sent, and that request failed; the live response patched from the response row, a quick edit saved and served, the page taken offline and back from the network speed menu, a WebSocket's messages in its details, a response edited as a tree with the keyboard (a value retyped, a key renamed, a member removed) and saved, and the requests exported as HAR and imported back as overrides. The page stack (`stack.e2e.test.ts`): the status bar names the fixture's UI libraries and opens the Page stack, which lists each finding by kind with its version, build and evidence, and scans again. The component inspector (`inspect.e2e.test.ts`) on a production React cart framed from another site: the toolbar's button picks and the Inspect view shows what is under the pointer; a click opens the Component page, named `CartItem` and placed at its source line through the map, with props, state, context, the handler by its original name and the chain; **Open original** and **Go to bundle code** land on its definition; the View menu starts and stops picking, and Esc in the editor stops it; the Inspect view's tree lists the cart frame's components down to the one picked, selected; a state value named `qty` (from the original) is set from the Component page and the cart shows it; **Record renders** from the palette records a real click, the Renders tab says it was a click on `button#add-A1` and that `CartItem` rendered for `state qty 5 → 6`, and the Component page lists that render. A map from a file (`mapFile.e2e.test.ts`): a production React bundle that names no map, picked, given its map through **Load a source map…** (the system's dialog stubbed in the main process) and named `CartItem` at its line, then forgotten; a plain page's element shown with its listener and where it is defined; the inspected cart's renders by component, and its set value kept as an action that sets it again after a reload; a Redux Toolkit cart (`dataFlow.e2e.test.ts`): its actions recorded from the palette with what they changed and the line that dispatched them (and their stack), the commit after one naming it, and a request's **Sent by** stack traced to the handler | `npm run test:e2e` (on headless Linux: `xvfb-run npm run test:e2e`) | | Packaged | The installed app (asar, fuses, signature) fixes the demo store's checkout through the UI, driven over `--remote-debugging-port` since the fuses disable Node's inspector. The release workflow runs it on six runners, one per architecture: macOS (from the disk image), Windows (after a silent install; the x64 runner also checks that the ARM installer refuses it) and Linux (from the installed `.deb`, with Ubuntu's user-namespace restriction left on, also checking that the desktop entry and icons are the package's and the app added none of its own) | `npm run test:packaged -- ` | | Update | An installed app updates itself to a build one patch higher, served by a local stand-in for GitHub: the notification, What's New, the download, **Restart to update**, the restarted app running the new version (and What's New after it); an AppImage's desktop entry starts the old file before and the renamed one after. The release workflow runs it for the Windows installers (then uninstalls, checking the updater's cache goes too) and the AppImages on their four runners. The `.deb` path (as root, through `sudo`, and with the password refused) and the AppImage installing on quit were checked by hand | `npm run test:update -- ` | diff --git a/src/main/inspector/adapter/registrySource.ts b/src/main/inspector/adapter/registrySource.ts index 964b66f8..614b9dc2 100644 --- a/src/main/inspector/adapter/registrySource.ts +++ b/src/main/inspector/adapter/registrySource.ts @@ -1,9 +1,19 @@ -import { ANGULAR_VIEW } from '../constants'; +import { ANGULAR_REGISTRY_GLOBAL, ANGULAR_VIEW } from '../constants'; -/** On an element or document: whether its page runs a production Angular build, whose components only its view registry leads to. */ -export const NEEDS_REGISTRY_SOURCE = `function () { +/** + * On an element or document, for a page running a production Angular build (whose components only its view + * registry leads to): the registry, when it was found before and kept on the window (and still holds views); + * else null. Undefined for a page that needs none (no Angular, or a development build, with `window.ng`). + */ +export const KEPT_REGISTRY_SOURCE = `function () { const ng = window.ng; - return !!document.querySelector('[ng-version]') && !(ng && typeof ng.getComponent === 'function'); + if (!document.querySelector('[ng-version]') || (ng && typeof ng.getComponent === 'function')) return undefined; + const kept = Object.prototype.hasOwnProperty.call(window, '${ANGULAR_REGISTRY_GLOBAL}') ? window['${ANGULAR_REGISTRY_GLOBAL}'] : null; + return kept instanceof Map && kept.size ? kept : null; +}`; +/** On the registry found: kept on its page's window (`ANGULAR_REGISTRY_GLOBAL`), not enumerable. */ +export const KEEP_REGISTRY_SOURCE = `function () { + Object.defineProperty(window, '${ANGULAR_REGISTRY_GLOBAL}', { configurable: true, value: this }); }`; /** On an element or document: the Map prototype of its world, for `Runtime.queryObjects`. */ export const MAP_PROTOTYPE_SOURCE = 'function () { return Map.prototype; }'; diff --git a/src/main/inspector/constants.ts b/src/main/inspector/constants.ts index 1e438248..857f578d 100644 --- a/src/main/inspector/constants.ts +++ b/src/main/inspector/constants.ts @@ -89,6 +89,11 @@ export const LOADED_SCRIPT = /^https?:/; * component's own view), its context (the component instance) and its id (the registry's key). */ export const ANGULAR_VIEW = { tView: 1, context: 8, id: 19, componentType: 1 } as const; +/** + * Where a page keeps Angular's view registry once it was found (a non-enumerable global of its window): the + * next read takes it from there instead of walking the heap, and it goes with the document. + */ +export const ANGULAR_REGISTRY_GLOBAL = '__consoleEditorNgRegistry'; /** The most steps a selector for a picked element takes up from it (to an ancestor with an id, or body). */ export const MAX_SELECTOR_STEPS = 16; /** The most shadow roots a picked element's selectors go in through (the document's is one), and the longest selector taken. */ diff --git a/src/main/inspector/reading/angularRegistry.ts b/src/main/inspector/reading/angularRegistry.ts index 8651101b..ea218a1c 100644 --- a/src/main/inspector/reading/angularRegistry.ts +++ b/src/main/inspector/reading/angularRegistry.ts @@ -1,22 +1,27 @@ import type { EvaluateReply } from '../../console/types'; import type { CdpTransport } from '../../engine/cdp'; import { CDP } from '../../engine/constants'; -import { FIND_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE, NEEDS_REGISTRY_SOURCE } from '../adapter/registrySource'; +import { FIND_REGISTRY_SOURCE, KEEP_REGISTRY_SOURCE, KEPT_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE } from '../adapter/registrySource'; /** * Angular's view registry, when the page of an element (or document) runs a production Angular build: a handle - * in `objectGroup`, found among every Map of the heap (`Runtime.queryObjects`, a walk of the heap: only then). - * Null when the page doesn't need it, or it can't be found. + * in `objectGroup`. Found once per document among every Map of the heap (`Runtime.queryObjects`, a walk of the + * heap), then kept on its window, where each later read takes it with one call. Null when the page doesn't + * need it, or it can't be found. */ export async function angularRegistry(transport: CdpTransport, objectId: string, objectGroup: string): Promise { const call = (id: string, functionDeclaration: string, returnByValue = false) => transport.send(CDP.Runtime.callFunctionOn, { objectId: id, functionDeclaration, objectGroup, returnByValue, silent: true }); try { - const needs = await call(objectId, NEEDS_REGISTRY_SOURCE, true); - if (needs.result.value !== true) return null; + const kept = await call(objectId, KEPT_REGISTRY_SOURCE); + if (kept.result.objectId) return kept.result.objectId; + // Undefined: the page needs none; null: it needs one not found yet. + if (kept.result.subtype !== 'null') return null; const prototype = await call(objectId, MAP_PROTOTYPE_SOURCE); const { objects } = await transport.send<{ objects: { objectId?: string } }>(CDP.Runtime.queryObjects, { prototypeObjectId: prototype.result.objectId, objectGroup }); const registry = objects.objectId ? await call(objects.objectId, FIND_REGISTRY_SOURCE) : null; - return registry?.result.objectId ?? null; + const found = registry?.result.objectId ?? null; + if (found) await call(found, KEEP_REGISTRY_SOURCE, true); + return found; } catch { return null; } diff --git a/test/integration/frameworks.chromium.test.ts b/test/integration/frameworks.chromium.test.ts index dfff370a..d3157149 100644 --- a/test/integration/frameworks.chromium.test.ts +++ b/test/integration/frameworks.chromium.test.ts @@ -13,7 +13,7 @@ import { originalPositionFor, TraceMap } from '@jridgewell/trace-mapping'; import type { Locator, Page } from 'playwright-core'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { PageInterception } from '../../src/main/engine/PageInterception'; -import { NOT_SETTABLE } from '../../src/main/inspector/constants'; +import { ANGULAR_REGISTRY_GLOBAL, NOT_SETTABLE } from '../../src/main/inspector/constants'; import { FrameServices } from '../../src/main/PageController/FrameServices'; import { DEFAULT_SETTINGS, type AppEvent, type CodeLocation, type ComponentTreeLevel, type InspectedComponent, type InspectHover } from '../../src/shared/types'; import { bundleApp } from '../helpers/bundleApp'; @@ -164,7 +164,14 @@ describe.skipIf(!chromiumAvailable)('component inspector on Angular, Vue 2, web await page.locator('#add-A1').waitFor(); const top = await treeAt([]); expect(top.nodes.map((n) => lineIn(n.location))).toEqual([lineOf('angularCart.ts', 'class App')]); + // Found once, the registry is kept on the page's window: the next read doesn't walk the heap for it. + const sent: string[] = []; + const send = transport.send.bind(transport); + transport.send = ((method: string, params?: Record) => (sent.push(method), send(method, params))) as typeof transport.send; expect((await treeAt([0])).nodes).toHaveLength(2); + transport.send = send; + expect(sent).not.toContain('Runtime.queryObjects'); + expect(await page.evaluate((key) => [key in window, Object.keys(window).includes(key)], ANGULAR_REGISTRY_GLOBAL)).toEqual([true, false]); }); it('reads a Vue 2 component: props, data it can set, what the app provides, the chain and the tree', async () => { diff --git a/test/unit/componentInspector.test.ts b/test/unit/componentInspector.test.ts index 103bcc4e..6de77c07 100644 --- a/test/unit/componentInspector.test.ts +++ b/test/unit/componentInspector.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { CdpTransport } from '../../src/main/engine/cdp'; import { ADAPTER_SOURCE, DATA_OF_SOURCE, FNS_OF_SOURCE, OWNER_DOCUMENT_SOURCE } from '../../src/main/inspector/adapter/adapterSource'; import { LISTENERS_SOURCE } from '../../src/main/inspector/adapter/listenersSource'; -import { FIND_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE, NEEDS_REGISTRY_SOURCE } from '../../src/main/inspector/adapter/registrySource'; +import { FIND_REGISTRY_SOURCE, KEEP_REGISTRY_SOURCE, KEPT_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE } from '../../src/main/inspector/adapter/registrySource'; import { HOVER_INTERVAL_MS, MAX_PICKS, PICK_GONE } from '../../src/main/inspector/constants'; import { toInspectedComponent } from '../../src/main/inspector/reading/toInspectedComponent'; import { FrameServices } from '../../src/main/PageController/FrameServices'; @@ -84,6 +84,8 @@ describe('component inspector (picking and reading)', () => { ); cdp.replies.set('Runtime.callFunctionOn', (p: { functionDeclaration: string; arguments?: Array<{ value: unknown }>; objectId: string }) => { if (p.functionDeclaration === OWNER_DOCUMENT_SOURCE) return { result: { type: 'object', objectId: 'doc' } }; + // Not a production Angular page: no registry needed. + if (p.functionDeclaration === KEPT_REGISTRY_SOURCE) return { result: { type: 'undefined' } }; if (p.functionDeclaration === DATA_OF_SOURCE) return { result: { type: 'object', value: { ...DESCRIBED, depth: 0 } } }; if (p.functionDeclaration === FNS_OF_SOURCE) return { result: { type: 'object', objectId: 'fns' } }; if (p.arguments?.[0]?.value === 'summary') return { result: { type: 'object', value: { element: { tag: 'li', id: '', classes: [] }, framework: 'react', chain: [`at-${p.objectId}`] } } }; @@ -191,8 +193,14 @@ describe('component inspector (picking and reading)', () => { it("finds a production Angular page's view registry for the read, and reads the element's own listeners", async () => { const answer = cdp.replies.get('Runtime.callFunctionOn') as (p: { functionDeclaration: string; objectId: string }) => unknown; + // The page keeps the registry once it is handed back to it. + let kept = false; cdp.replies.set('Runtime.callFunctionOn', (p: { functionDeclaration: string; objectId: string }) => { - if (p.functionDeclaration === NEEDS_REGISTRY_SOURCE) return { result: { type: 'boolean', value: true } }; + if (p.functionDeclaration === KEPT_REGISTRY_SOURCE) return { result: kept ? { type: 'object', subtype: 'map', objectId: 'registry' } : { type: 'object', subtype: 'null', value: null } }; + if (p.functionDeclaration === KEEP_REGISTRY_SOURCE) { + kept = p.objectId === 'registry'; + return { result: { type: 'undefined' } }; + } if (p.functionDeclaration === MAP_PROTOTYPE_SOURCE) return { result: { type: 'object', objectId: 'map-prototype' } }; if (p.functionDeclaration === FIND_REGISTRY_SOURCE) return { result: { type: 'object', objectId: 'registry' } }; if (p.functionDeclaration === LISTENERS_SOURCE) return { result: { type: 'object', objectId: 'listeners' } }; @@ -209,6 +217,11 @@ describe('component inspector (picking and reading)', () => { expect(cdp.sent('Runtime.queryObjects', undefined)[0]!.params).toMatchObject({ prototypeObjectId: 'map-prototype' }); const adapter = cdp.sent('Runtime.callFunctionOn', undefined).find((c) => c.params?.functionDeclaration === ADAPTER_SOURCE)!; expect(adapter.params?.arguments[3]).toEqual({ objectId: 'registry' }); + // Kept on the page's window: the next read takes it from there, without walking the heap again. + await services.inspector.inspectComponent(picked()!.pickId, 0); + expect(cdp.sent('Runtime.queryObjects', undefined)).toHaveLength(1); + const again = cdp.sent('Runtime.callFunctionOn', undefined).filter((c) => c.params?.functionDeclaration === ADAPTER_SOURCE).at(-1)!; + expect(again.params?.arguments[3]).toEqual({ objectId: 'registry' }); // The DOM hands the handlers over, and the page says which function each runs. expect(cdp.sent('Runtime.callFunctionOn', undefined).find((c) => c.params?.functionDeclaration === LISTENERS_SOURCE)!.params).toMatchObject({ objectId: 'el-5', arguments: [{ objectId: 'h1' }] }); expect(picked()!.listeners).toEqual([{ type: 'click', name: 'onBuy', location: { url: APP_JS, line: 0, column: 120 }, capture: true, once: true, passive: false }]); diff --git a/test/unit/componentRenders.test.ts b/test/unit/componentRenders.test.ts index 033d15c6..93b5b8eb 100644 --- a/test/unit/componentRenders.test.ts +++ b/test/unit/componentRenders.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { CdpTransport } from '../../src/main/engine/cdp'; import { ADAPTER_SOURCE, DATA_OF_SOURCE, ELEMENT_OF_SOURCE, FNS_OF_SOURCE } from '../../src/main/inspector/adapter/adapterSource'; +import { KEPT_REGISTRY_SOURCE } from '../../src/main/inspector/adapter/registrySource'; import { FRAME_GONE, MAX_RENDERED, NO_ELEMENT, NOT_JSON, NOT_SETTABLE, RENDERED_TYPES, RENDERS_BINDING } from '../../src/main/inspector/constants'; import { toStateEdit } from '../../src/main/inspector/reading/toStateEdit'; import { toRenderCommits } from '../../src/main/inspector/renders/toRenderCommits'; @@ -180,6 +181,8 @@ describe('recording renders, the Components tree and setting state (main)', () = return { result: { type: 'object', value: { nodes: [{ framework: 'react', name: 'App', key: null, fn: 0, children: 2 }, { framework: 'svelte', name: 'X', fn: 1, children: 0 }], more: 3 } } }; if (p.functionDeclaration === FNS_OF_SOURCE) return { result: { type: 'object', objectId: 'fns' } }; if (p.functionDeclaration === ELEMENT_OF_SOURCE) return { result: { type: 'object', objectId: 'el-9' } }; + // Not a production Angular page: no registry needed. + if (p.functionDeclaration === KEPT_REGISTRY_SOURCE) return { result: { type: 'undefined' } }; if (p.functionDeclaration.includes('this.depth')) return { result: { type: 'number', value: 1 } }; return { result: { type: 'object', objectId: 'holder' } }; });