import {createCompatibilityConsent as createConsent} from '@notabenda/core/consent/compat';
// @requirements REQ-PRODUCT-SERVICE-LOCALIZATION REQ-PRODUCT-LOCALIZATION REQ-PRODUCT-SERVICE-CATALOG REQ-PRODUCT-A11Y
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {JSDOM} from 'jsdom';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {validateSiteConfig,toPublicConfig} from '@notabenda/core';
import {createServiceDirectory,renderServiceDirectory,renderServiceDirectoryPage,mountServiceDirectory,normalizeServiceDirectoryLocalization} from '@notabenda/core/services';
import {ServiceDirectory} from '@notabenda/core/react/documents';
import {compileLegalDocuments,compileConsentRuntimeConfig,createConsentNotice} from '@notabenda/core/content';
import {recordLegalRelease,createDocumentHistory,validateLegalSourceArchive} from '@notabenda/cloudflare';
import {createSyntheticStorage} from '../../notabenda-cf/examples/synthetic.mjs';
import {fixture} from './helpers.mjs';
import {localizedServicesConfig} from '../../../examples/localization/services-build.mjs';
import {localizedExampleConfig} from '../../../examples/localization/config.mjs';
const messages=JSON.parse(await readFile(new URL('../../../examples/localization/service-messages.json',import.meta.url),'utf8'));
const settings={idPrefix:'services-pt'};
async function config(){const c=localizedServicesConfig(await fixture());c.localization.reviewStatus='reviewed';for(const d of Object.values(c.documents))d.review.status='reviewed';return c;}
const browser=html=>{const dom=new JSDOM(''+(html??'')+'
');return {dom,doc:dom.window.document,root:dom.window.document.getElementById('directory')};};
test('complete selected directory copy reaches script-free pages and React with explicit language, direction and translated facts',async()=>{
const c=await config(),html=renderServiceDirectory(c,settings),f=browser(html),d=f.doc;assert.equal(d.querySelector('section').lang,'pt-BR');assert.equal(d.querySelector('section').dir,'ltr');assert.equal(d.querySelector('h1').textContent,messages.title);assert.equal(d.querySelector('nav').getAttribute('aria-label'),messages.relatedPoliciesLabel);assert.equal(d.querySelector('summary').textContent,messages.detailsLabel);assert.ok(d.body.textContent.includes(messages.locationLabel));assert.ok(d.body.textContent.includes(messages.noStorage));assert.ok(d.body.textContent.includes(messages.unlistedPrivacy));assert.ok(d.body.textContent.includes(messages.storageLocalStorage));assert.ok(d.body.textContent.includes(messages.necessary));assert.ok(d.body.textContent.includes(messages.optional));assert.equal(d.querySelectorAll('script,input,select').length,0);assert.ok([...d.querySelectorAll('details')].every(n=>!n.open));assert.equal(renderToStaticMarkup(createElement(ServiceDirectory,{config:c,...settings})),`
${html}
`);
const page=new JSDOM(renderServiceDirectoryPage(c,settings));assert.equal(page.window.document.documentElement.lang,'pt-BR');assert.equal(page.window.document.documentElement.dir,'ltr');assert.equal(page.window.document.querySelector('.nb-service-skip').textContent,messages.skipToContent);assert.equal(page.window.document.querySelector('footer').textContent,messages.footer);assert.doesNotMatch(page.window.document.body.textContent,/Processing location|Purpose retention|Browser storage|Skip to content|Data & storage details|No browser storage is declared/);page.window.close();f.dom.window.close();
});
test('optional local search keeps focus and details, combines purpose filters and uses selected counts through destruction',async()=>{
const c=await config(),f=browser(renderServiceDirectory(c,settings)),details=f.root.querySelector('details');details.open=true;details.querySelector('summary').focus();const focused=f.doc.activeElement,ui=mountServiceDirectory(f.root,c,settings);assert.equal(f.doc.activeElement,focused);assert.equal(details.open,true);const search=f.root.querySelector('input'),purpose=f.root.querySelector('select'),count=f.root.querySelector('[role=status]');assert.equal(search.labels[0].textContent,messages.searchLabel);assert.equal(search.placeholder,messages.searchPlaceholder);assert.equal(purpose.labels[0].textContent,messages.purposeLabel+messages.allPurposes+c.purposes.map(p=>p.name).join(''));assert.equal(purpose.options[0].textContent,messages.allPurposes);assert.equal(count.textContent,'Exibindo 4 de 4 serviços declarados');assert.equal(count.querySelectorAll('bdi').length,2);
search.focus();search.value='Brookpost';search.dispatchEvent(new f.dom.window.Event('input'));assert.equal(f.doc.activeElement,search);assert.equal(count.textContent,'Exibindo 1 de 4 serviços declarados');assert.equal(f.root.querySelector('.nb-service-list > li:not([hidden])').dataset.serviceId,'mail');purpose.value='measurement';purpose.dispatchEvent(new f.dom.window.Event('change'));assert.equal(count.textContent,'Exibindo 0 de 4 serviços declarados');assert.equal(f.root.querySelector('[data-service-empty]').textContent,messages.noMatches);assert.equal(f.root.querySelector('[data-service-empty]').hidden,false);search.value='';search.dispatchEvent(new f.dom.window.Event('input'));assert.equal(f.root.querySelector('.nb-service-list > li:not([hidden])').dataset.serviceId,'measurement');ui.destroy();assert.equal(count.textContent,'4 serviços declarados');assert.equal(f.root.querySelectorAll('input,select').length,0);search.value='Brookpost';search.dispatchEvent(new f.dom.window.Event('input'));assert.equal(count.textContent,'4 serviços declarados');assert.equal(details.open,true);f.dom.window.close();
});
test('missing selected dictionaries reject presentation before replacing host content while headless facts stay usable',async()=>{
const c=await config();delete c.localization.serviceDirectory;assert.equal(validateSiteConfig(c).valid,true);assert.equal(createServiceDirectory(c).services.length,4);for(const render of [renderServiceDirectory,renderServiceDirectoryPage])assert.throws(()=>render(c,settings),/localization.serviceDirectory/);const f=browser('Keep host content
');assert.throws(()=>mountServiceDirectory(f.root,c,settings),/localization.serviceDirectory/);assert.equal(f.root.textContent,'Keep host content');f.dom.window.close();
});
test('dictionary validation is complete, bounded, descriptor-safe and rejects malformed placeholders and metadata',async()=>{
const c=await config();for(const mutate of [m=>delete m.noStorage,m=>m.unknown='extra',m=>m.title='',m=>m.description='copy',m=>m.searchLabel='x'.repeat(121),m=>m.description='💬'.repeat(600),m=>m.footer='x\n',m=>m.totalOne='one',m=>m.filteredCount='{shown}',m=>m.privacyLinkLabel='{provider}',m=>m.eyebrow='{siteName} {unknown}',m=>m.totalMany='{total} {',m=>m.noMatches='{total}']){const v=structuredClone(c);mutate(v.localization.serviceDirectory);assert.equal(validateSiteConfig(v).valid,false,mutate.toString());assert.throws(()=>renderServiceDirectory(v,settings));}
const selected=createServiceDirectory(c).localization;assert.deepEqual(normalizeServiceDirectoryLocalization(selected),selected);for(const patch of [{locale:'pt-br'},{locale:'en'},{direction:'auto'},{reviewStatus:'draft'},{revision:''},{schemaVersion:'1'}, {extra:'unused'}])assert.throws(()=>normalizeServiceDirectoryLocalization({...selected,...patch},{locale:'pt-BR'}));assert.ok(normalizeServiceDirectoryLocalization({...selected,reviewStatus:'draft'},{allowPreview:true}));let invoked=0;const malicious=structuredClone(c);Object.defineProperty(malicious.localization.serviceDirectory,'title',{enumerable:true,get(){invoked++;return 'unsafe';}});assert.throws(()=>toPublicConfig(malicious));assert.equal(invoked,0);
const large=structuredClone(c);for(const key of Object.keys(large.localization.serviceDirectory)){const m=large.localization.serviceDirectory[key];large.localization.serviceDirectory[key]='x'.repeat(key.endsWith('Label')?100:1000)+m;}assert.equal(validateSiteConfig(large).valid,false);
});
test('custom facts and substitutions remain literal, isolated and separate from message parsing',async()=>{
const c=await config();c.site.name='Juniper {total}';c.services[0].name='
{serviceName}';c.services[0].provider='Provider ';const f=browser(renderServiceDirectory(c,settings));assert.equal(f.root.querySelectorAll('script,img,[onerror]').length,0);assert.equal(f.root.querySelector('article h2').textContent,c.services[0].name);assert.equal(f.root.querySelector('.nb-service-privacy bdi').textContent,c.services[0].name);assert.ok(f.root.querySelector('.nb-service-eyebrow').textContent.includes(c.site.name));assert.equal(f.root.querySelector('.nb-service-privacy').textContent,'Privacidade: '+c.services[0].name+' ↗');assert.ok([...f.root.querySelectorAll('.nb-service-result-count bdi')].every(n=>n.dir==='auto'));f.dom.window.close();
});
test('copy is retained in exact legal releases and public display models, without entering cookie scopes or granting work',async()=>{
const base=localizedExampleConfig(await fixture());base.localization.reviewStatus='reviewed';for(const d of Object.values(base.documents))d.review.status='reviewed';base.localization.serviceDirectory=structuredClone(messages);base.private={token:'SERVICE_PRIVATE_SENTINEL'};base.services[0].resourceOrigins=['https://private-scope.example.test'];const before=structuredClone(base),one=compileLegalDocuments(base),changed=structuredClone(base);changed.localization.revision+='-new';changed.localization.serviceDirectory.title='Serviços e finalidades';const two=compileLegalDocuments(changed);assert.notEqual(one.manifest.artifactId,two.manifest.artifactId);assert.deepEqual(one.artifact.publicConfig.localization.serviceDirectory,messages);assert.notEqual(renderServiceDirectory(one.artifact.publicConfig,settings),renderServiceDirectory(two.artifact.publicConfig,settings));assert.deepEqual(compileConsentRuntimeConfig(base,{evidence:'local'}).inventory.localization.serviceDirectory,undefined);assert.equal(createConsentNotice(one.artifact,{scopeId:'choices'}).scopeDigest,createConsentNotice(two.artifact,{scopeId:'choices'}).scopeDigest);
const model=createServiceDirectory(base);assert.deepEqual(model.localization.serviceDirectory,messages);assert.equal(model.localization.consent,undefined);assert.equal(model.localization.documents,undefined);assert.doesNotMatch(JSON.stringify(model),/SERVICE_PRIVATE_SENTINEL|private-scope|resourceOrigins|scopeGuards/);model.localization.serviceDirectory.title='Detached';assert.equal(base.localization.serviceDirectory.title,messages.title);const store=createSyntheticStorage([]);await recordLegalRelease(store,one.artifact);assert.ok((await createDocumentHistory(store).get(one.manifest.artifactId)).data);const stored=await store.get('notabenda/releases/'+one.manifest.artifactId),checked=await validateLegalSourceArchive(stored.artifact);assert.deepEqual(JSON.parse(JSON.stringify(checked.artifact.publicConfig.localization.serviceDirectory)),messages);assert.equal(renderServiceDirectory(checked.artifact.publicConfig,settings),renderServiceDirectory(one.artifact.publicConfig,settings));
const consent=createConsent(base,{storage:{getItem:()=>null,setItem(){assert.fail('Directory must not write choices');},removeItem(){assert.fail();}},now:()=>Date.parse('2026-10-20T12:00:00Z'),schedule:()=>()=>{}});let starts=0;consent.registerService('reading',{purposes:['suggestions'],start(){starts++;return ()=>{};}});const f=browser();const ui=mountServiceDirectory(f.root,base,settings);f.root.querySelector('input').value='Juniper';f.root.querySelector('input').dispatchEvent(new f.dom.window.Event('input'));await new Promise(r=>setImmediate(r));assert.equal(starts,0);assert.equal(consent.isAllowed('suggestions'),false);assert.deepEqual(base,before);ui.destroy();consent.destroy();f.dom.window.close();
});
test('selected locale drives literal case matching and RTL count rendering, with all metadata explicit',async()=>{
const c=await config();c.site.locale=c.localization.locale='tr';c.localization.direction='ltr';c.services[0].provider='IŞIK';assert.equal(createServiceDirectory(c,{query:'ışık'}).services[0].id,'hosting');c.site.locale=c.localization.locale='ar-u-nu-arab';c.localization.direction='rtl';const f=browser(renderServiceDirectory(c,settings)),ui=mountServiceDirectory(f.root,c,settings);assert.equal(f.root.firstElementChild.dir,'rtl');assert.equal(f.root.querySelector('[role=status]').textContent,'Exibindo ٤ de ٤ serviços declarados');assert.ok([...f.root.querySelectorAll('[role=status] bdi')].every(n=>n.dir==='auto'));ui.destroy();assert.equal(f.root.querySelector('[data-service-results]').textContent,'٤ serviços declarados');f.dom.window.close();
});
test('empty and one-service inventories, static filtering and preview copy use the selected messages',async()=>{
const c=await config(),one=structuredClone(c);one.services=one.services.slice(0,1);one.storage=[];assert.ok(new JSDOM(renderServiceDirectory(one,settings)).window.document.body.textContent.includes('1 serviço declarado'));const filtered=new JSDOM(renderServiceDirectory(c,{...settings,purposeId:'measurement'}));assert.equal(filtered.window.document.querySelectorAll('article').length,1);assert.equal(filtered.window.document.querySelector('[data-service-results]').textContent,'Exibindo 1 de 4 serviços declarados');filtered.window.close();c.services=[];c.storage=[];assert.ok(new JSDOM(renderServiceDirectory(c,settings)).window.document.body.textContent.includes(messages.emptyInventory));c.localization.reviewStatus='draft';assert.throws(()=>renderServiceDirectory(c,settings));assert.ok(renderServiceDirectory(c,{...settings,mode:'preview'}).includes(messages.draft));
});
test('legacy English fragments and complete pages keep the exact prior rendering',async()=>{
// Compatibility fingerprints from commit 184f155, before directory localization.
const {createHash}=await import('node:crypto'),{serviceExampleConfig}=await import('../../../examples/services/build.mjs'),c=serviceExampleConfig(await fixture({reviewed:true})),options={idPrefix:'legacy-services'},digest=html=>createHash('sha256').update(html).digest('hex');assert.equal(digest(renderServiceDirectory(c,options)),'ff1a49e1ed9f769c07b7c830333bac79ebea904bd104e4a17e632253d90b3260');assert.equal(digest(renderServiceDirectoryPage(c,options)),'57a9c29f353a32b1bbe63a5558f8797dae44c6d46b157a1485334330130211ec');
});