import { randomUUID } from 'node:crypto'; import type { Frame, Locator } from 'playwright-core'; import { withPlaywrightPageCdpSession } from './connection.js'; const GUARD_MARKER = `function(attribute, ref, guard, timeout) { const element = this; const doc = element.ownerDocument; if (!element.isConnected || element.getAttribute(attribute) !== ref) return false; const root = doc.documentElement; const observer = new MutationObserver(check); const timer = setTimeout(release, timeout); function release() { observer.disconnect(); clearTimeout(timer); root.removeAttribute(guard); if (doc.documentElement !== root) doc.documentElement?.removeAttribute(guard); } function check() { if (!element.isConnected || element.ownerDocument !== doc || doc.documentElement !== root || element.getAttribute(attribute) !== ref) { release(); return; } observer.disconnect(); observer.observe(element, { attributes: true, attributeFilter: [attribute] }); let ancestor = element; while (ancestor !== doc) { if (ancestor instanceof ShadowRoot && ancestor.mode === 'closed') { release(); return; } ancestor = ancestor.parentNode || ancestor.host; observer.observe(ancestor, { childList: true }); } } root.setAttribute(guard, ''); check(); return root.hasAttribute(guard); }`; /** Keep Playwright retries in the captured document and retire the locator if the backend node disappears. */ export async function nativeRefLocator( frame: Frame, backendNodeId: number, attribute: string, id: string, remaining: () => number, ): Promise { const guard = `data-bc-action-${randomUUID()}`; const bound = await withPlaywrightPageCdpSession( frame.page(), async (session) => { await session.send('DOM.getDocument', { depth: 0 }); const { nodeIds } = await session.send('DOM.pushNodesByBackendIdsToFrontend', { backendNodeIds: [backendNodeId], }); if (!nodeIds[0]) return false; const { object } = await session.send('DOM.resolveNode', { nodeId: nodeIds[0] }); if (object.objectId === undefined || object.objectId === '') return false; try { const response = await session.send('Runtime.callFunctionOn', { objectId: object.objectId, functionDeclaration: GUARD_MARKER, arguments: [attribute, id, guard, remaining()].map((value) => ({ value })), returnByValue: true, }); if (response.exceptionDetails) throw new Error('Could not verify the native ref in its document.'); return response.result.value === true; } finally { await session.send('Runtime.releaseObject', { objectId: object.objectId }).catch((error: unknown) => { console.warn( `[browserclaw] could not release a ref's element (${error instanceof Error ? error.name : 'error'})`, ); }); } }, remaining(), frame, ); if (!bound) return undefined; const marker = `[${attribute}="${id}"]`; return frame.locator(`:root[${guard}]${marker}, :root[${guard}] ${marker}`); }