import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import http from 'node:http'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {test} from 'node:test'; import {chromium} from 'playwright-chromium'; import {evidenceDirectory} from './farm-docs-evidence.mjs'; const repository=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); const evidence=await evidenceDirectory(repository,'p06'); async function assertLanguageHead(page, expected) { const actual=await page.locator('head link[rel="alternate"][hreflang]').evaluateAll(links=>links.map(link=>({locale:link.hreflang,href:link.href})).sort((a,b)=>a.locale.localeCompare(b.locale))); await fs.writeFile(path.join(evidence,'runtime-language-head.json'),JSON.stringify({url:page.url(),actual,expected},null,2)); assert.deepEqual(actual,expected,'Head language links must follow genuine translations of the current version without stale links'); } test('runtime navigates actual locale/version pages in one document and updates context and head',async()=>{ const parent=path.join(repository,'examples/docs-minimal');const root=await fs.mkdtemp(path.join(parent,'runtime-fixture-'));let browser,server; try{ await fs.cp(path.join(repository,'examples/docs-features/content'),path.join(root,'content'),{recursive:true}); const site=JSON.parse(await fs.readFile(path.join(repository,'examples/docs-features/site.json'),'utf8')); await fs.writeFile(path.join(root,'content/en-current/unicode.md'),'---\ntitle: Unicode route\nslug: 介绍\n---\n# Unicode destination\n');site.theme.navbar.push({label:'Unicode route',to:'/guide/docs/介绍/'}); const component="import {useState} from 'react';import {useLocale,useVersion,usePage} from '@farmfe/docs/client';export default function RuntimeProbe(){const [n,setN]=useState(0);return

{useLocale()}/{useVersion()}/{usePage().title}

Scroll fixture
}"; for(const collection of site.docs.collections){const file=path.join(root,collection.dir,'index.md');const source=(await fs.readFile(file,'utf8')).replace(/(\r?\ntitle:[^\r\n]+)/,value=>value+'\ndescription: Runtime description '+collection.id).replace(/\r?\n---\r?\n/,match=>match+"\nimport RuntimeProbe from './_RuntimeProbe';\n");await fs.writeFile(path.join(root,collection.dir,'_RuntimeProbe.tsx'),component);await fs.rename(file,file+'x');await fs.writeFile(file+'x',source+'\n\n');} const {run}=await import('../packages/docs/dist/workflow.js');await run({command:'build',config:{root},options:{site,farm:{compilation:{output:{path:'build'},persistentCache:false,sourcemap:false}}}}); const output=path.join(root,'build');const requests=[],errors=[],failures=[]; server=http.createServer(async(request,response)=>{try{const url=new URL(request.url,'http://localhost');assert.ok(url.pathname.startsWith('/guide/'));let file=path.resolve(output,decodeURIComponent(url.pathname.slice(7)));assert.ok(file.startsWith(output+path.sep));if((await fs.stat(file)).isDirectory())file=path.join(file,'index.html');response.writeHead(200,{'Content-Type':file.endsWith('.html')?'text/html':file.endsWith('.css')?'text/css':'text/javascript'});response.end(await fs.readFile(file));}catch{response.writeHead(404).end();}}); await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const origin=`http://127.0.0.1:${server.address().port}`;browser=await chromium.launch({headless:true});const page=await browser.newPage();page.on('request',request=>{if(request.resourceType()==='document')requests.push(request.url());});page.on('response',response=>{if(response.status()>=400)failures.push(response.url());});page.on('pageerror',error=>errors.push(error.message));page.on('console',message=>{if(message.type()==='error')errors.push(message.text());}); await page.goto(origin+'/guide/docs/');await page.getByRole('button',{name:'Runtime 0',exact:true}).click();await page.getByRole('button',{name:'Runtime 1',exact:true}).waitFor();assert.equal(await page.getByTestId('context').textContent(),'en/current/English current'); await page.evaluate(()=>{window.__farmDocsDocumentSentinel='same-document';});await page.getByRole('link',{name:'中文 current',exact:true}).click();await page.waitForURL(origin+'/guide/zh/docs/');await page.getByTestId('context').waitFor(); const actual={url:page.url(),documentRequests:requests,context:await page.getByTestId('context').textContent(),title:await page.title(),canonical:await page.locator('link[rel=canonical]').getAttribute('href'),sentinel:await page.evaluate(()=>window.__farmDocsDocumentSentinel??null),errors,failures};await fs.writeFile(path.join(evidence,'runtime-first-navigation.json'),JSON.stringify(actual,null,2)); await assertLanguageHead(page,[{locale:'en',href:'https://example.com/guide/docs/'},{locale:'zh',href:'https://example.com/guide/zh/docs/'}]); assert.equal(requests.length,1,'internal locale navigation must not request a second document');assert.equal(actual.sentinel,'same-document');assert.equal(actual.context,'zh/current/中文 current');assert.equal(actual.title,'中文 current | Farm Docs Features');assert.equal(await page.locator('meta[name=description]').getAttribute('content'),'Runtime description zh-current');assert.equal(await page.evaluate(()=>document.documentElement.lang),'zh');assert.equal(actual.canonical,'https://example.com/guide/zh/docs/'); await page.getByRole('link',{name:'English previous',exact:true}).click();await page.waitForURL(origin+'/guide/v1/docs/');assert.equal(await page.getByTestId('context').textContent(),'en/previous/English previous');await assertLanguageHead(page,[{locale:'en',href:'https://example.com/guide/v1/docs/'},{locale:'zh',href:'https://example.com/guide/zh/v1/docs/'}]);await page.goBack();await page.waitForURL(origin+'/guide/zh/docs/');assert.equal(await page.getByTestId('context').textContent(),'zh/current/中文 current');await page.goForward();await page.waitForURL(origin+'/guide/v1/docs/');assert.equal(requests.length,1);await page.evaluate(()=>window.scrollTo(0,500));await page.waitForFunction(()=>window.scrollY===500);await page.evaluate(()=>{const anchor=document.createElement('a');anchor.id='runtime-query';anchor.href='/guide/docs/?from=runtime#farm-docs-content';anchor.textContent='Query route';anchor.style.cssText='position:fixed;bottom:0;right:0;z-index:100';document.body.append(anchor);});await page.locator('#runtime-query').click();await page.waitForURL(origin+'/guide/docs/?from=runtime#farm-docs-content');assert.equal(await page.getByTestId('context').textContent(),'en/current/English current');assert.equal(await page.evaluate(()=>document.activeElement?.id),'farm-docs-content');await page.getByRole('button',{name:'Runtime 0',exact:true}).click();await page.getByRole('button',{name:'Runtime 1',exact:true}).waitFor();await page.evaluate(()=>{const anchor=document.createElement('a');anchor.id='runtime-same-hash';anchor.href='#current-documentation';anchor.textContent='Same-page hash';anchor.style.cssText='position:fixed;bottom:35px;right:0;z-index:100';document.body.append(anchor);});await page.locator('#runtime-same-hash').click();await page.waitForURL(origin+'/guide/docs/?from=runtime#current-documentation');assert.equal(await page.evaluate(()=>document.activeElement?.id),'current-documentation');await page.getByRole('button',{name:'Runtime 1',exact:true}).waitFor();await page.goBack();await page.waitForURL(origin+'/guide/docs/?from=runtime#farm-docs-content');await page.goBack();await page.waitForURL(origin+'/guide/v1/docs/');assert.equal(await page.evaluate(()=>window.scrollY),500,'history restores captured scroll position');assert.equal(requests.length,1);for(const attributes of [{href:'/outside/'},{href:'/guide/docs/',download:''},{href:'/guide/docs/',target:'_blank'},{href:'https://other.example/docs/'},{href:'/guide/docs/',rel:'external'},{href:'/guide/docs/',ctrlKey:true}]){const prevented=await page.evaluate(attributes=>{const anchor=document.createElement('a');for(const [name,value] of Object.entries(attributes)){if(name!=='ctrlKey')anchor.setAttribute(name,value);}document.body.append(anchor);let result;window.addEventListener('click',event=>{result=event.defaultPrevented;event.preventDefault();},{once:true});anchor.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true,ctrlKey:attributes.ctrlKey??false}));anchor.remove();return result;},attributes);assert.equal(prevented,false,JSON.stringify(attributes));}await page.getByRole('navigation',{name:'Main navigation',exact:true}).getByRole('link',{name:'Unicode route',exact:true}).click();await page.waitForURL(origin+'/guide/docs/'+encodeURIComponent('介绍')+'/');await page.getByRole('heading',{name:'Unicode destination',exact:true}).waitFor();await assertLanguageHead(page,[{locale:'en',href:'https://example.com/guide/docs/'+encodeURIComponent('介绍')+'/'}]);assert.equal(requests.length,1,'Unicode public route must use same registered page without full navigation');await page.evaluate(()=>{const anchor=document.createElement('a');anchor.id='runtime-slash-alias';anchor.href='/guide/docs?from=alias#farm-docs-content';anchor.textContent='Slash alias';anchor.style.cssText='position:fixed;bottom:0;right:0;z-index:100';document.body.append(anchor);});await page.locator('#runtime-slash-alias').click();await page.waitForURL(origin+'/guide/docs?from=alias#farm-docs-content');await page.getByTestId('context').waitFor();await fs.writeFile(path.join(evidence,'runtime-alias-observation.json'),JSON.stringify({url:page.url(),requests,context:await page.getByTestId('context').textContent(),errors,failures},null,2));assert.equal(requests.length,1,'slash variant of a real page must remain in the same document');await page.getByRole('navigation',{name:'Main navigation',exact:true}).getByRole('link',{name:'Unicode route',exact:true}).click();await page.waitForURL(origin+'/guide/docs/'+encodeURIComponent('介绍')+'/');await page.getByRole('heading',{name:'Unicode destination',exact:true}).waitFor();await page.reload();await page.getByRole('heading',{name:'Unicode destination',exact:true}).waitFor();assert.equal(requests.length,2,'explicit deep reload remains a real document request');await page.getByRole('link',{name:'English previous',exact:true}).focus();await page.keyboard.press('Enter');await page.waitForURL(origin+'/guide/v1/docs/');assert.equal(await page.getByTestId('context').textContent(),'en/previous/English previous');await assertLanguageHead(page,[{locale:'en',href:'https://example.com/guide/v1/docs/'},{locale:'zh',href:'https://example.com/guide/zh/v1/docs/'}]);assert.equal(requests.length,2,'keyboard route navigation remains in the reloaded document');const staticContext=await browser.newContext({javaScriptEnabled:false});try{const staticPage=await staticContext.newPage();await staticPage.goto(origin+'/guide/docs/#farm-docs-content');assert.equal(await staticPage.getByTestId('context').textContent(),'en/current/English current');assert.equal(new URL(staticPage.url()).hash,'#farm-docs-content');assert.ok(await staticPage.evaluate(()=>window.scrollY)>0,'native first-load fragment scroll is preserved without JavaScript');}finally{await staticContext.close();}await fs.writeFile(path.join(evidence,'runtime-navigation-boundaries.json'),JSON.stringify({singleDocument:true,queryHash:true,samePageHashState:true,focus:true,scrollRestoration:true,history:true,browserSemanticsPreserved:true,unicodeRoute:true,descriptionUpdate:true,deepReload:true,keyboardNavigation:true,noJavaScriptFragment:true,errors,failures},null,2));assert.deepEqual(errors,[]);assert.deepEqual(failures,[]); }finally{await browser?.close();if(server){server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}assert.equal(path.dirname(root),parent);assert.ok(path.basename(root).startsWith('runtime-fixture-'));await fs.rm(root,{recursive:true,force:true});} });