PlotDirector/PlotLine.Tests/Browser/writing-solver-seo.cjs

17 lines
6.5 KiB
JavaScript

// Real Razor metadata/sitemap audit. Production mode is loopback-only: no Production deployment or database.
const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
const base=process.env.SOLVER_BASE_URL||'http://127.0.0.1:5238',production=process.env.SEO_MODE==='production';assert(!production||new URL(base).hostname==='127.0.0.1');
const graph=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json')),expected=graph.solutions.filter(s=>s.active&&s.index).map(s=>'/problem-solver/'+s.slug).sort();
(async()=>{const b=await chromium.launch(),c=await b.newContext({javaScriptEnabled:false});try{await c.addCookies([{name:'solver-anonymous',value:'true',url:base}]);const p=await c.newPage(),rows=[];
async function meta(path){const response=await p.goto(base+path);assert.equal(response.status(),200);const data=await p.evaluate(()=>({title:document.title,description:document.querySelector('meta[name=description]')?.content,canonical:document.querySelector('link[rel=canonical]')?.href,robots:document.querySelector('meta[name=robots]')?.content,og:Object.fromEntries([...document.querySelectorAll('meta[property^="og:"]')].map(e=>[e.getAttribute('property'),e.content])),json:[...document.querySelectorAll('script[type="application/ld+json"]')].map(e=>JSON.parse(e.textContent)),h1:document.querySelector('h1')?.textContent.trim(),links:[...document.querySelectorAll('main a[href]')].map(e=>e.getAttribute('href'))}));assert.equal(data.canonical,'https://plotdirector.com'+path);assert.equal(data.og['og:url'],data.canonical);assert(data.title&&data.description&&data.og['og:title']&&data.og['og:description']);assert(data.og['og:image']);const imagePath=new URL(data.og['og:image']).pathname;assert.equal((await c.request.get(base+imagePath)).status(),200);assert.equal(data.robots,production?'index, follow':'noindex, follow');assert(!production||!response.headers()['x-robots-tag']?.includes('noindex'));assert(data.json.length>0);for(const item of data.json){assert.equal(item['@type'],'WebPage');assert.equal(item.url,data.canonical);assert(item.name&&item.description);assert(!JSON.stringify(item).includes('state='));}return data;}
const entry=await meta('/problem-solver');assert(entry.links.includes('/problem-solver/browse'));for(const path of expected){const data=await meta(path);assert(data.links.includes('/problem-solver'));assert(data.links.some(u=>u.startsWith('/features/')));assert(data.links.some(u=>u.startsWith('/problem-solver/browse/')));rows.push({path,...data});}assert.equal(new Set(rows.map(r=>r.title)).size,expected.length);assert.equal(new Set(rows.map(r=>r.description)).size,expected.length);
// All permanent pages are discoverable through normal SSR browse anchors.
await p.goto(base+'/problem-solver/browse');const areas=await p.locator('main a[href^="/problem-solver/browse/"]').evaluateAll(es=>es.map(e=>e.getAttribute('href'))),linked=new Set();for(const area of areas){await p.goto(base+area);for(const href of await p.locator('.solver-problem-links a').evaluateAll(es=>es.map(e=>e.getAttribute('href'))))linked.add(href);}assert.deepEqual([...linked].sort(),expected);
const xml=await (await c.request.get(base+'/sitemap.xml')).text();const locs=await p.evaluate(xml=>{const d=new DOMParser().parseFromString(xml,'application/xml');if(d.querySelector('parsererror'))throw Error('Invalid sitemap XML');return [...d.getElementsByTagName('loc')].map(e=>e.textContent);},xml);assert.equal(locs.length,new Set(locs).size);assert(locs.every(u=>!u.includes("/writing-problems")));assert(locs.every(u=>!new URL(u).search&&!new URL(u).hash));const sitemapPaths=locs.map(u=>new URL(u).pathname),permanent=sitemapPaths.filter(u=>u.startsWith('/problem-solver/')&&!u.startsWith('/problem-solver/browse')).sort();assert.deepEqual(permanent,production?expected:[]);assert.equal(sitemapPaths.includes('/problem-solver'),production);
// Personal evidence changes the visible explanation, never the document's public identity.
await p.goto(base+'/problem-solver');let statePath;for(const choice of ['story-not-working','too-many','lost','unwanted']){await p.locator(`input[name=choices][value="${choice}"]`).check();await p.locator('.solver-form button[type=submit]').click();if(new URL(p.url()).searchParams.has('state')){statePath=new URL(p.url()).pathname+new URL(p.url()).search;assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/problem-solver');}}
assert(await p.locator('.solver-result-evidence li').count()>0);const path=new URL(p.url()).pathname,personal=await meta(path),direct=rows.find(r=>r.path===path);for(const key of ['title','description','canonical','og','json'])assert.deepEqual(personal[key],direct[key]);await p.goBack();await p.goForward();assert.equal(new URL(p.url()).pathname,path);const invalid=await p.goto(base+'/problem-solver?state=invalid');assert(invalid.headers()['x-robots-tag']?.includes('noindex'));assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/problem-solver');
await p.goto(base+'/problem-solver?choose=true');assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/problem-solver');
if(!production&&new URL(base).hostname==='dev.plotdirector.com')for(const route of ['/','/features','/help','/sitemap.xml','/robots.txt']){const response=await c.request.get(base+route);assert(response.headers()['x-robots-tag']?.includes('noindex'),`Missing environmental noindex: ${route}`);}
const report={mode:production?'Production configuration (isolated)':'Development',permanentFound:expected.length,permanentInSitemap:permanent.length,entryInSitemap:sitemapPaths.includes('/problem-solver'),statefulInSitemap:locs.filter(u=>new URL(u).search||new URL(u).hash).length,uniqueTitles:new Set(rows.map(r=>r.title)).size,uniqueDescriptions:new Set(rows.map(r=>r.description)).size,schemaTypes:[...new Set(rows.flatMap(r=>r.json.map(j=>j['@type'])))],personalIdentityStable:true,rows};fs.writeFileSync(process.env.SEO_REPORT||'/tmp/writing-solver-seo.json',JSON.stringify(report,null,2));console.log('PASS SEO audit',JSON.stringify({...report,rows:undefined}));}finally{await c.close();await b.close();}})().catch(e=>{console.error(e);process.exit(1)});