import type { BrowserLocator } from './browserLocator.js'; export type BrowserCondition = | { type: 'url'; pattern: string } | { type: 'text'; value: string; exact?: boolean } | { type: 'element-visible'; locator?: BrowserLocator; selector?: string } | { type: 'element-hidden'; locator?: BrowserLocator; selector?: string } | { type: 'load-state'; state: 'domcontentloaded' | 'load' | 'networkidle' } | { type: 'download'; filename?: string } | { type: 'new-tab'; url?: string } | { type: 'dialog'; dialogType?: 'alert' | 'confirm' | 'prompt' | 'beforeunload'; } | { type: 'page-change' }; export function conditionToScript( condition: BrowserCondition, targetExpression: (locator?: BrowserLocator, selector?: string) => string, ): string { switch (condition.type) { case 'url': return `(() => { const u = location.href; const p = ${JSON.stringify(condition.pattern)}; const parts = p.split('*'); if (parts.length === 1) return u === p; let at = 0; for (const [i, part] of parts.entries()) { if (!part) continue; const next = u.indexOf(part, at); if (next < 0 || (i === 0 && next !== 0) || (i === parts.length - 1 && next + part.length !== u.length)) return false; at = next + part.length; } return true; })()`; case 'text': return `(() => { const text = document.body?.innerText || ''; const expected = ${JSON.stringify(condition.value)}; return ${condition.exact === true ? 'text.trim()===expected' : 'text.includes(expected)'}; })()`; case 'element-visible': return `(() => { try { ${targetExpression(condition.locator, condition.selector)}; return true; } catch (error) { if (/^Locator matched (no elements|a hidden element)$/.test(error.message)) return false; throw error; } })()`; case 'element-hidden': return `(() => { try { const e = ${targetExpression(condition.locator, condition.selector)}; return !e; } catch (error) { if (/^Locator matched (no elements|a hidden element)$/.test(error.message)) return true; throw error; } })()`; case 'load-state': return condition.state === 'domcontentloaded' ? `document.readyState !== 'loading'` : condition.state === 'load' ? `document.readyState === 'complete'` : `(() => { throw new Error('networkidle is not a business completion condition; use explicit text/element conditions or verify probes'); })()`; case 'download': case 'new-tab': case 'dialog': throw new Error( `${condition.type} is an event condition and must be armed before the action`, ); case 'page-change': return `location.href + '|' + (document.body?.innerText || '').slice(0, 4000)`; } }