import {createCompatibilityConsent as createConsent} from '@notabenda/core/consent/compat';
// @requirements REQ-PRODUCT-PROCESSING-LOCALIZATION REQ-PRODUCT-LOCALIZATION REQ-PRODUCT-PROCESSING-CHOICES REQ-PRODUCT-SAFE-CONTENT
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {JSDOM} from 'jsdom';
import {createProcessingChoices,mountProcessingChoices,normalizeProcessingNotice,toPublicConfig,validateSiteConfig} from '@notabenda/core';
import {compileLegalDocuments,compileConsentRuntimeConfig,createProcessingNotice,createConsentNotice,canonicalJson,sha256} from '@notabenda/core/content';
import {recordLegalRelease,registerProcessingNotice,recordProcessingRestriction,getProcessingHead,createProcessingRestrictionStore,renderRecordDetail} from '@notabenda/cloudflare';
import {createSyntheticStorage} from '../../notabenda-cf/examples/synthetic.mjs';
import {localizedProcessingConfig} from '../../../examples/localization/processing-build.mjs';
import {normalizeProcessingLocalization,processingMessageFields} from '../dist/processing-localization-policy.js';
import {fixture} from './helpers.mjs';
const settings={scopeId:'privacy-choices-pt',activities:['sale','sharing','targeted-advertising'],wording:{title:'Suas escolhas',description:'Oposição independente da permissão de cookies.',actionLabel:'Registrar oposição'}};
const rehash=n=>{const {noticeId:_,...value}=n;return {...n,noticeId:sha256(canonicalJson(value))};};
const memory=()=>{const values=new Map();return {values,storage:{getItem:k=>values.get(k)??null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};};
async function setup(change=()=>{}){
const c=localizedProcessingConfig(await fixture({reviewed:true}));c.localization.reviewStatus='reviewed';for(const d of Object.values(c.documents))d.review.status='reviewed';change(c);
const build=compileLegalDocuments(c),notice=createProcessingNotice(build.artifact,settings),storage=createSyntheticStorage([]),context={siteId:c.site.id,scopeId:settings.scopeId,streamId:'host-test-context',provenance:'explicit-opt-out'};
await recordLegalRelease(storage,build.artifact);await registerProcessingNotice(storage,notice,context);const initial=await getProcessingHead(storage,context);
return {c,build,notice,storage,context,options:{streamRef:initial.streamRef,read:()=>getProcessingHead(storage,context),submit:body=>recordProcessingRestriction(storage,body,context)}};
}
test('localized notices retain complete selected messages and the backend binds them to the actual privacy archive',async()=>{
const f=await setup();assert.equal(f.notice.schemaVersion,2);assert.equal(f.notice.localization.locale,'pt-BR');assert.deepEqual(normalizeProcessingNotice(f.notice).localization,f.notice.localization);assert.equal(f.notice.localization.consent,undefined);
for(const change of [n=>n.localization.processingChoices.error='Outra mensagem.',n=>n.localization.revision='other',n=>n.localization.locale='en',n=>n.localization.direction='rtl']){const n=structuredClone(f.notice);change(n);await assert.rejects(registerProcessingNotice(f.storage,rehash(n),f.context),e=>e.code==='invalid-notice');}
const downgrade=structuredClone(f.notice);downgrade.schemaVersion=1;delete downgrade.localization;await assert.rejects(registerProcessingNotice(f.storage,rehash(downgrade),f.context));
const missing=structuredClone(f.c);delete missing.localization.processingChoices;assert.equal(validateSiteConfig(missing).valid,true);assert.throws(()=>createProcessingNotice(compileLegalDocuments(missing).artifact,settings),/localization.processingChoices/);
const preview=compileLegalDocuments(f.c,{mode:'preview'}),draft=createProcessingNotice(preview.artifact,settings,{mode:'preview'});assert.throws(()=>normalizeProcessingNotice(draft));await recordLegalRelease(f.storage,preview.artifact);await assert.rejects(registerProcessingNotice(f.storage,draft,f.context));await registerProcessingNotice(f.storage,draft,{...f.context,allowPreview:true});
});
test('partial, mixed, malformed, oversized and executable-looking dictionaries fail without evaluating accessors',async()=>{
const f=await setup();for(const change of [m=>delete m.ready,m=>m.extra='extra',m=>m.ready='',m=>m.error='Erro',m=>m.recorded='{unknown}',m=>m.retired='x\n',m=>m.retryLabel='x'.repeat(121),m=>m.checking='😀'.repeat(600)]){const c=structuredClone(f.c);change(c.localization.processingChoices);assert.equal(validateSiteConfig(c).valid,false);assert.throws(()=>toPublicConfig(c));const n=structuredClone(f.notice);n.localization.processingChoices=c.localization.processingChoices;assert.throws(()=>normalizeProcessingNotice(n));await assert.rejects(registerProcessingNotice(f.storage,rehash(n),f.context));}
for(const [key,value] of [['direction',['rtl']],['locale','pt-br'],['schemaVersion','1'],['reviewStatus','draft']]){const n=structuredClone(f.notice);n.localization[key]=value;assert.throws(()=>normalizeProcessingNotice(n));await assert.rejects(registerProcessingNotice(f.storage,rehash(n),f.context));}
const huge=structuredClone(f.notice);for(const key of Object.keys(huge.localization.processingChoices))huge.localization.processingChoices[key]='x'.repeat(key.endsWith('Label')?120:1900);assert.throws(()=>normalizeProcessingNotice(huge));
let reads=0;for(const key of ['error','toJSON']){const n=structuredClone(f.notice);Object.defineProperty(n.localization.processingChoices,key,{enumerable:true,get(){reads++;throw Error('private');}});assert.throws(()=>normalizeProcessingNotice(n));await assert.rejects(registerProcessingNotice(f.storage,n,f.context));}assert.equal(reads,0);
const c=structuredClone(f.c);Object.defineProperty(c.localization.processingChoices,'ready',{enumerable:true,get(){reads++;return 'private';}});assert.throws(()=>toPublicConfig(c));assert.equal(reads,0);
});
test('copy revisions keep local restrictions, retry the old exact request and retain both notices without changing cookie scope',async()=>{
const f=await setup(),local=memory(),sent=[];let lose=true;const submit=async body=>{sent.push(structuredClone(body));const value=await f.options.submit(body);if(lose){lose=false;throw Error('Lost acknowledgment');}return value;};let p=createProcessingChoices(f.notice,{...f.options,submit},{storage:local.storage});await p.settled();await p.optOut();assert.equal(p.getSnapshot().pending,1);p.destroy();const before=new Map(local.values);
const next=structuredClone(f.c);next.localization.revision+='-copy-2';next.localization.processingChoices.recorded='Oposição confirmada nesta sessão.';const build=compileLegalDocuments(next),notice=createProcessingNotice(build.artifact,settings);assert.notEqual(notice.noticeId,f.notice.noticeId);await recordLegalRelease(f.storage,build.artifact);await registerProcessingNotice(f.storage,notice,f.context);
p=createProcessingChoices(notice,{...f.options,submit},{storage:local.storage});await p.settled();assert.deepEqual(sent[0],sent[1]);assert.equal(sent[1].noticeId,f.notice.noticeId);assert.equal(p.getSnapshot().status,'recorded');assert.equal(p.getSnapshot().revision,1);assert.deepEqual(p.getSnapshot().restrictedActivities,settings.activities);assert.equal(p.getSnapshot().pending,0);assert.ok([...before.keys()].filter(k=>k.includes(':sale')||k.includes(':sharing')).every(k=>local.values.get(k)===before.get(k)));
const dom=new JSDOM(''),ui=mountProcessingChoices(dom.window.document.querySelector('main'),p);assert.ok(dom.window.document.body.textContent.includes(next.localization.processingChoices.recorded));ui.destroy();p.destroy();dom.window.close();
const records=await createProcessingRestrictionStore(f.storage,{siteId:f.context.siteId}).list({query:'',kind:'',from:'',to:'',keyPrefix:'',limit:10});assert.equal(records.records.length,1);assert.equal(canonicalJson(records.records[0].data.notice.localization),canonicalJson(f.notice.localization));const html=renderRecordDetail(records.records[0],{basePath:'/admin',title:'Processing',scopeLabel:'Test',nonce:'a'.repeat(32)}),detail=new JSDOM(html).window.document;assert.ok(detail.body.textContent.includes(f.notice.localization.processingChoices.recorded));assert.ok(detail.body.textContent.includes('Declared interface wording'));assert.ok(detail.querySelector('dd[lang="pt-BR"][dir="ltr"]'));assert.ok(detail.body.textContent.includes('does not establish which interface states were displayed'));
assert.equal(createConsentNotice(f.build.artifact,{scopeId:'cookies'}).scopeDigest,createConsentNotice(build.artifact,{scopeId:'cookies'}).scopeDigest);assert.equal(compileConsentRuntimeConfig(next,{evidence:'local'}).inventory.localization.processingChoices,undefined);
});
test('translated controls use every supplied status and recovery message with RTL, and detached buttons cannot submit',async()=>{
const f=await setup(c=>{c.site.locale=c.localization.locale='ar';c.localization.direction='rtl';});const dom=new JSDOM(''),root=dom.window.document.querySelector('main'),notice=structuredClone(f.notice);notice.mode='preview';let listener,calls=0;
const stub={getNotice:()=>structuredClone(notice),subscribe(fn){listener=fn;return ()=>{listener=undefined;};},optOut:async()=>{calls++;},retry:async()=>{calls++;}};
const ui=mountProcessingChoices(root,stub),m=notice.localization.processingChoices,region=root.querySelector('section'),buttons=[...root.querySelectorAll('button')];assert.equal(region.lang,'ar');assert.equal(region.dir,'rtl');assert.ok(root.textContent.includes(m.draft));assert.equal(buttons[1].textContent,m.retryLabel);
const base={destroyed:false,restrictedActivities:[],persistence:'available',needsConfirmation:false};for(const status of ['checking','ready','saving','recorded','error','retired','destroyed']){listener({...base,status,destroyed:status==='destroyed'});assert.equal(root.querySelector('[role=status]').textContent,m[status]);}
for(const [persistence,key] of [['unavailable','recoveryUnavailable'],['invalid','recoveryInvalid']]){listener({...base,status:'error',persistence});assert.equal(root.querySelector('[role=status]').textContent,m.error+' '+m[key]);}
listener({...base,status:'error',needsConfirmation:true});assert.equal(root.querySelector('[role=status]').textContent,m.needsConfirmation);assert.equal(buttons[1].hidden,true);ui.destroy();for(const b of buttons)b.click();assert.equal(calls,0);dom.window.close();
});
test('real translated choices wait for acknowledgment and cookie acceptance never removes the opt-out',async()=>{
const f=await setup(),local=memory();let release;const wait=new Promise(resolve=>{release=resolve;});const p=createProcessingChoices(f.notice,{...f.options,submit:async body=>{await wait;return f.options.submit(body);}},{storage:local.storage}),dom=new JSDOM(''),ui=mountProcessingChoices(dom.window.document.querySelector('main'),p);await p.settled();const consent=createConsent(f.c,{storage:local.storage,now:()=>Date.now(),subscribe:()=>()=>{}},{processingChoices:p});for(const s of f.c.consent.services)consent.registerService(s.id,{purposes:f.c.services.find(x=>x.id===s.id).purposeIds,start:()=>()=>{}});
await consent.acceptAll();await consent.settled();assert.equal(consent.getSnapshot().servicePermissions.reading,true);const pending=p.optOut();assert.equal(consent.getSnapshot().servicePermissions.reading,false);assert.equal(consent.getSnapshot().servicePermissions['reading-counter'],true);assert.ok(dom.window.document.body.textContent.includes(f.notice.localization.processingChoices.saving));assert.equal(dom.window.document.body.textContent.includes(f.notice.localization.processingChoices.recorded),false);release();await pending;assert.ok(dom.window.document.body.textContent.includes(f.notice.localization.processingChoices.recorded));await consent.acceptAll();assert.equal(consent.getSnapshot().servicePermissions.reading,false);consent.destroy();ui.destroy();p.destroy();dom.window.close();
});
test('the standalone backend validator uses the same processing localization contract',async()=>{
const source=await readFile(new URL('../src/processing-localization-policy.ts',import.meta.url),'utf8'),copy=await readFile(new URL('../../notabenda-cf/src/processing-localization-policy.ts',import.meta.url),'utf8');assert.ok(copy.endsWith(source));const f=await setup();assert.deepEqual(Object.keys(f.notice.localization.processingChoices).sort(),Object.keys(processingMessageFields).sort());assert.deepEqual(normalizeProcessingLocalization(f.notice.localization),f.notice.localization);
});