/** * Internal dependencies */ import { extractCssSelectorMapFromDocument } from './helpers'; declare global { interface Window { nabCssSelectorDiscoveryLabels: { readonly ready: string; readonly error: string; }; } } type Settings = { readonly token: string; readonly endpoint: string; }; export function initCssSelectorDiscovery( settings: Settings ): void { const run = () => { const url = new URL( window.location.href ); url.searchParams.delete( 'nab-css-selector-discovery' ); url.hash = ''; void fetch( settings.endpoint, { method: 'POST', credentials: 'same-origin', cache: 'no-store', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', }, body: JSON.stringify( { token: settings.token, url: url.toString(), selectors: extractCssSelectorMapFromDocument( document ), } ), } ) .then( ( response ) => { if ( ! response.ok ) { throw new Error( 'Selector discovery failed.' ); } showMessage( window.nabCssSelectorDiscoveryLabels?.ready ?? 'Selectors are ready. Return to the AI agent and let it know.' ); } ) .catch( () => { showMessage( window.nabCssSelectorDiscoveryLabels?.error ?? 'Selector discovery could not be completed. Return to the AI agent and try again.' ); } ); }; if ( 'loading' === document.readyState ) { document.addEventListener( 'DOMContentLoaded', run, { once: true } ); } else { run(); } } function showMessage( message: string ): void { const notice = document.createElement( 'div' ); notice.textContent = message; notice.style.background = '#fff'; notice.style.border = '1px solid #1d2327'; notice.style.borderRadius = '4px'; notice.style.boxShadow = '0 2px 8px rgba(0, 0, 0, .2)'; notice.style.color = '#1d2327'; notice.style.fontFamily = 'sans-serif'; notice.style.left = '20px'; notice.style.padding = '12px 16px'; notice.style.position = 'fixed'; notice.style.top = '20px'; notice.style.zIndex = '2147483647'; document.body.appendChild( notice ); }