import {normalizeUrls,extractEvidence,resultsCsv} from './date-core.mjs'; import {toolResponseError} from './tool-access.mjs'; // A template's document fragment is inert: fetched scripts, images and frames // are never inserted into the live document or executed. export function htmlEvidence(html,url) { const template=document.createElement('template');template.innerHTML=html; const doc=template.content; return {url,title:doc.querySelector('title')?.textContent?.trim().slice(0,300)||'', canonical:doc.querySelector('link[rel~="canonical"]')?.getAttribute('href')||'', jsonld:[...doc.querySelectorAll('script[type="application/ld+json"]')].map(n=>n.textContent), meta:[...doc.querySelectorAll('meta[content]')].map(n=>({key:n.getAttribute('property')||n.getAttribute('name')||n.getAttribute('itemprop'),value:n.getAttribute('content')})), times:[...doc.querySelectorAll('time')].map(n=>({value:n.getAttribute('datetime')||n.textContent.trim(),context:[n.className,n.getAttribute('itemprop'),n.getAttribute('pubdate')!==null?'pubdate':'',n.parentElement?.className].join(' ')}))}; } for(const root of document.querySelectorAll('.aen-date-tool'))bind(root); function bind(root) { if(root.dataset.bound)return;root.dataset.bound='1'; const find=s=>root.querySelector(s),urls=find('[data-urls]'),run=find('[data-run]'),cancel=find('[data-cancel]'),share=find('[data-share]'),refreshButton=find('[data-refresh]'); const status=find('[data-status]'),remaining=find('[data-remaining]'),reset=find('[data-reset]'),results=find('[data-results]'),download=find('[data-download]'); const endpoint=new URL(root.dataset.toolEndpoint),requests=new Set(); let quota=null,busy=false,generation=0,rows=[],exportUrl='',refreshPromise=null; function message(text,error=false){status.textContent=text;status.dataset.error=error?'1':'0';} function controls(){run.disabled=busy||!!root.dataset.securityPending||!urls.value.trim()||!quota?.tools?.date||quota.tools.date.remaining<1;urls.disabled=busy;cancel.hidden=!busy;refreshButton.disabled=busy;share.disabled=busy||!!root.dataset.securityPending||!quota?.tools?.date||quota.share_claimed;root.setAttribute('aria-busy',busy?'true':'false');} function showQuota(data){ quota=data;const p=data.tools?.date; if(!p){remaining.textContent='This theme has no active date checker.';controls();return;} remaining.textContent=`${p.remaining} of ${p.limit} runs remaining today`; find('[data-batch]').textContent=`Up to${p.batch} pages per run.`; reset.textContent=`Resets ${new Date(data.reset_at).toLocaleString(undefined,{timeZone:data.timezone})} (${data.timezone}).`; share.textContent=data.share_claimed?'Daily bonus claimed':`Get ${p.share_bonus} extra uses`;controls(); } async function request(path,body){ if(endpoint.origin!==location.origin)throw new Error('Open the checker at its canonical website address.'); const controller=new AbortController();requests.add(controller);const timer=setTimeout(()=>controller.abort(),15000); try{ const options={cache:'no-store',credentials:'same-origin',signal:controller.signal}; if(body!==undefined){options.method='POST';options.headers={'Content-Type':'application/json','X-AEN-Tool-Token':quota?.token||''};options.body=JSON.stringify(body);} const response=await fetch(new URL(path,endpoint),options),data=await response.json(); if(data.tools)showQuota(data); toolResponseError(root,endpoint,response,data); return data; }finally{clearTimeout(timer);requests.delete(controller);} } function refresh(){if(!refreshPromise)refreshPromise=request('status').finally(()=>{refreshPromise=null;});return refreshPromise;} root.addEventListener('aen-security-change',controls); root.addEventListener('aen-security-verified',()=>refresh().then(()=>message('Security check passed. You can continue; your daily allowance is unchanged.')).catch(e=>message(e.message,true))); function clearExport(){if(exportUrl)URL.revokeObjectURL(exportUrl);exportUrl='';download.hidden=true;download.removeAttribute('href');} function exportResults(){clearExport();if(!rows.length)return;exportUrl=URL.createObjectURL(new Blob([resultsCsv(rows)],{type:'text/csv;charset=utf-8'}));download.href=exportUrl;download.download='sectorletter-date-evidence.csv';download.hidden=false;} const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;}; function renderRow(row){ const card=el('article');card.className='aen-date-result'; card.append(el('h3',row.title||'Page evidence')); const source=el('a',row.url);source.href=row.url;source.target='_blank';source.rel='noopener noreferrer';source.className='aen-date-source';card.append(source); const badge=el('p',row.status);badge.className='aen-date-result-state';card.append(badge); if(row.status==='Read'){ const dates=el('dl'); for(const [label,value]of[['Published',row.published],['Modified',row.modified]]){dates.append(el('dt',label),el('dd',value?`${value.date} · ${value.confidence} evidence`:'Not established'));} card.append(dates); if(row.evidence.length){const details=el('details'),list=el('ul');details.append(el('summary',`Evidence (${row.evidence.length})`));for(const e of row.evidence)list.append(el('li',`${e.source}: ${e.date} · ${e.kind}${e.future?' · future date, not selected':''}`));details.append(list);card.append(details);} } card.append(el('p',row.message)); const manual=el('a','Google Site — manual lookup');manual.href='https://www.google.com/search?q='+encodeURIComponent('site:'+row.url);manual.target='_blank';manual.rel='noopener noreferrer';card.append(manual);results.append(card); } async function inspect(url,ticket,grant){ try{ const source=await request('html',{url,grant});if(ticket!==generation)return null; const data=htmlEvidence(source.html,source.url||url),evidence=extractEvidence(data); const notes=[]; if(evidence.warnings.includes('conflicting-publication-dates'))notes.push('Publication signals disagree; inspect the source evidence.'); if(evidence.warnings.includes('future-date'))notes.push('Future-dated evidence was not selected.'); if(evidence.warnings.includes('invalid-jsonld'))notes.push('Some structured data could not be read.'); if(evidence.warnings.includes('structured-data-truncated'))notes.push('Complex structured data was only partly inspected.'); if(!evidence.published)notes.push('No reliable publication date was established.'); if(!evidence.evidence.length)notes.push('No supported date signals were found in the returned HTML.'); if(!notes.length)notes.push('A page-reported date is evidence, not a guarantee of first publication.'); return{url,title:data.title,status:'Read',...evidence,message:notes.join(' ')}; }catch(error){ if(ticket!==generation)return null; if(['aen_tool_verification_required','aen_tool_rate_limited','aen_tool_protection_unconfigured'].includes(error.code))throw error; return{url,status:'Unreadable',title:'',message:error.name==='AbortError'?'The page request timed out or was interrupted.':error.message||'The page could not be inspected.'}; } } run.addEventListener('click',async()=>{ if(busy)return;let targets; try{targets=normalizeUrls(urls.value,quota?.tools?.date?.batch||5);}catch(error){message(error.message,true);return;} const ticket=++generation;busy=true;controls();message('Checking today’s allowance…'); try{ await refresh();if(ticket!==generation)return; targets=normalizeUrls(urls.value,quota?.tools?.date?.batch||5); const accepted=await request('run',{tool:'date',count:targets.length});if(ticket!==generation)return; if(!accepted.accepted)throw new Error('The allowance could not be confirmed.'); rows=[];results.replaceChildren();clearExport(); for(let i=0;ir.status==='Read').length; message(`Finished: ${read} read, ${rows.length-read} unreadable. Review each result before relying on a date.`); }catch(error){if(ticket===generation)message(error.name==='AbortError'?'The allowance request was interrupted. Refresh before another run.':error.message||'The run could not start.',true);} finally{if(ticket===generation){busy=false;controls();}} }); cancel.addEventListener('click',()=>{generation++;for(const controller of requests)controller.abort();busy=false;controls();message('Cancelled. Completed results are retained; a started run still counts. Refresh the allowance before trying again.');}); urls.addEventListener('input',controls); refreshButton.addEventListener('click',()=>refresh().then(()=>message('Daily allowance refreshed.')).catch(e=>message(e.message||'Allowance temporarily unavailable.',true))); share.addEventListener('click',async()=>{ if(busy||quota?.share_claimed)return; if(navigator.share)navigator.share({title:document.title,url:root.dataset.home}).catch(()=>{}); else navigator.clipboard?.writeText(root.dataset.home).catch(()=>{}); const ticket=++generation;busy=true;controls();message('Checking the daily bonus…'); try{await refresh();if(ticket!==generation)return;const data=await request('share',{});if(ticket===generation)message(data.bonus_granted?'Daily bonus added. Use your share menu or copied website link to share.':'Today’s bonus was already claimed.');} catch(error){if(ticket===generation)message(error.message||'The bonus could not be confirmed.',true);} finally{if(ticket===generation){busy=false;controls();}} }); addEventListener('pagehide',event=>{if(event.persisted)return;generation++;for(const controller of requests)controller.abort();clearExport();}); addEventListener('pageshow',event=>{if(event.persisted)refresh().catch(e=>message(e.message||'Refresh the allowance.',true));}); message('Enter page URLs to inspect their date evidence.');refresh().catch(e=>{remaining.textContent='Daily allowance unavailable';message(e.message||'Refresh the allowance.',true);controls();}); }