export type BrowserFrameInfo = { id: string; parentId?: string; url: string; name?: string; }; /** Fixed, read-only expression for observing nested same-origin frame trees. */ export const FRAME_INFO_EXPRESSION = `(() => { const walk = (doc, parentId = '', path = '') => Array.from(doc.querySelectorAll('iframe,frame')).flatMap((el, index) => { const id = 'dom-frame-' + (path ? path + '-' : '') + index; const item = { id, ...(parentId ? { parentId } : {}), url: el.src || '', name: el.name || undefined }; try { return [item, ...walk(el.contentDocument, id, id.replace('dom-frame-', ''))]; } catch { return [item]; } }); return walk(document); })()`; /** Normalize the recursive, browser-owned frame tree returned by CDP. */ export function normalizeFrameTree(value: unknown): BrowserFrameInfo[] { const frames: BrowserFrameInfo[] = []; const walk = (node: unknown, parentId?: string): void => { if (!node || typeof node !== 'object') return; const item = node as { frame?: { id?: unknown; url?: unknown; name?: unknown }; childFrames?: unknown[]; }; if (typeof item.frame?.id !== 'string' || !item.frame.id) return; const id = item.frame.id; frames.push({ id, ...(parentId ? { parentId } : {}), url: typeof item.frame.url === 'string' ? item.frame.url : '', ...(typeof item.frame.name === 'string' && item.frame.name ? { name: item.frame.name } : {}), }); for (const child of item.childFrames ?? []) walk(child, id); }; walk(value); return frames; } export function normalizeFrameInfo(value: unknown): BrowserFrameInfo[] { if (!Array.isArray(value)) return []; return value.flatMap((item) => { if (!item || typeof item !== 'object') return []; const frame = item as Record; if (typeof frame.id !== 'string' || typeof frame.url !== 'string') return []; return [ { id: frame.id, url: frame.url, ...(typeof frame.parentId === 'string' ? { parentId: frame.parentId } : {}), ...(typeof frame.name === 'string' ? { name: frame.name } : {}), }, ]; }); }